├── LICENSE ├── Non-Local_pytorch_0.3.1 ├── demo_MNIST.py └── lib │ ├── backup │ ├── non_local.py │ └── non_local_simple_version.py │ ├── network.py │ ├── non_local_concatenation.py │ ├── non_local_dot_product.py │ ├── non_local_embedded_gaussian.py │ └── non_local_gaussian.py ├── Non-Local_pytorch_0.4.1_to_1.1.0 ├── demo_MNIST.py └── lib │ ├── network.py │ ├── non_local_concatenation.py │ ├── non_local_dot_product.py │ ├── non_local_embedded_gaussian.py │ └── non_local_gaussian.py ├── README.md ├── demo_MNIST_AMP_train_with_single_gpu.py ├── demo_MNIST_train.py ├── lib ├── network.py ├── non_local_concatenation.py ├── non_local_dot_product.py ├── non_local_embedded_gaussian.py └── non_local_gaussian.py ├── nl_map_save.py ├── nl_map_vis ├── nl_map_1.npy ├── nl_map_1 │ ├── 110.png │ ├── 147.png │ ├── 161.png │ ├── 174.png │ ├── 177.png │ ├── 188.png │ ├── 37.png │ ├── 44.png │ ├── 46.png │ ├── 49.png │ ├── 51.png │ ├── 61.png │ ├── 63.png │ └── 66.png ├── nl_map_2.npy ├── nl_map_2 │ ├── 1.png │ ├── 10.png │ ├── 18.png │ ├── 19.png │ ├── 22.png │ ├── 38.png │ └── 8.png ├── nl_map_vis.py └── sample.png └── weights └── net.pth /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Non-Local_pytorch_0.3.1/demo_MNIST.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.utils.data as Data 3 | import torchvision 4 | from lib.network import Network 5 | from torch.autograd import Variable 6 | from torch import nn 7 | import time 8 | 9 | 10 | def calc_acc(x, y): 11 | x = torch.max(x, dim=-1)[1] 12 | accuracy = sum(x == y) / x.size(0) 13 | return accuracy 14 | 15 | 16 | train_data = torchvision.datasets.MNIST(root='./mnist', train=True, 17 | transform=torchvision.transforms.ToTensor(), 18 | download=True) 19 | test_data = torchvision.datasets.MNIST(root='./mnist/', 20 | transform=torchvision.transforms.ToTensor(), 21 | train=False) 22 | 23 | train_loader = Data.DataLoader(dataset=train_data, batch_size=128, shuffle=True) 24 | test_loader = Data.DataLoader(dataset=test_data, batch_size=128, shuffle=False) 25 | 26 | train_batch_num = len(train_loader) 27 | test_batch_num = len(test_loader) 28 | 29 | net = Network() 30 | if torch.cuda.is_available(): 31 | net = nn.DataParallel(net) 32 | net.cuda() 33 | 34 | opt = torch.optim.Adam(net.parameters(), lr=0.001) 35 | loss_func = nn.CrossEntropyLoss() 36 | 37 | 38 | for epoch_index in range(20): 39 | st = time.time() 40 | for train_batch_index, (img_batch, label_batch) in enumerate(train_loader): 41 | img_batch = Variable(img_batch) 42 | label_batch = Variable(label_batch) 43 | 44 | if torch.cuda.is_available(): 45 | img_batch = img_batch.cuda() 46 | label_batch = label_batch.cuda() 47 | 48 | predict = net(img_batch) 49 | acc = calc_acc(predict.cpu().data, label_batch.cpu().data) 50 | loss = loss_func(predict, label_batch) 51 | 52 | net.zero_grad() 53 | loss.backward() 54 | opt.step() 55 | 56 | print('(LR:%f) Time of a epoch:%.4fs' % (opt.param_groups[0]['lr'], time.time()-st)) 57 | 58 | net.eval() 59 | total_loss = 0 60 | total_acc = 0 61 | 62 | for test_batch_index, (img_batch, label_batch) in enumerate(test_loader): 63 | img_batch = Variable(img_batch, volatile=True) 64 | label_batch = Variable(label_batch, volatile=True) 65 | 66 | if torch.cuda.is_available(): 67 | img_batch = img_batch.cuda() 68 | label_batch = label_batch.cuda() 69 | 70 | predict = net(img_batch) 71 | acc = calc_acc(predict.cpu().data, label_batch.cpu().data) 72 | loss = loss_func(predict, label_batch) 73 | 74 | total_loss += loss 75 | total_acc += acc 76 | 77 | net.train() 78 | 79 | mean_acc = total_acc / test_batch_num 80 | mean_loss = total_loss / test_batch_num 81 | 82 | print('[Test] epoch[%d/%d] acc:%.4f loss:%.4f\n' 83 | % (epoch_index, 100, mean_acc, mean_loss.data[0])) 84 | -------------------------------------------------------------------------------- /Non-Local_pytorch_0.3.1/lib/backup/non_local.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.nn import functional as F 4 | 5 | 6 | class _NonLocalBlockND(nn.Module): 7 | def __init__(self, in_channels, inter_channels=None, dimension=3, mode='embedded_gaussian', 8 | sub_sample=True, bn_layer=True): 9 | super(_NonLocalBlockND, self).__init__() 10 | 11 | assert dimension in [1, 2, 3] 12 | assert mode in ['embedded_gaussian', 'gaussian', 'dot_product', 'concatenation'] 13 | 14 | # print('Dimension: %d, mode: %s' % (dimension, mode)) 15 | 16 | self.mode = mode 17 | self.dimension = dimension 18 | self.sub_sample = sub_sample 19 | 20 | self.in_channels = in_channels 21 | self.inter_channels = inter_channels 22 | 23 | if self.inter_channels is None: 24 | self.inter_channels = in_channels // 2 25 | if self.inter_channels == 0: 26 | self.inter_channels = 1 27 | 28 | if dimension == 3: 29 | conv_nd = nn.Conv3d 30 | max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2)) 31 | bn = nn.BatchNorm3d 32 | elif dimension == 2: 33 | conv_nd = nn.Conv2d 34 | max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2)) 35 | bn = nn.BatchNorm2d 36 | else: 37 | conv_nd = nn.Conv1d 38 | max_pool_layer = nn.MaxPool1d(kernel_size=(2)) 39 | bn = nn.BatchNorm1d 40 | 41 | self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 42 | kernel_size=1, stride=1, padding=0) 43 | 44 | if bn_layer: 45 | self.W = nn.Sequential( 46 | conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 47 | kernel_size=1, stride=1, padding=0), 48 | bn(self.in_channels) 49 | ) 50 | nn.init.constant(self.W[1].weight, 0) 51 | nn.init.constant(self.W[1].bias, 0) 52 | else: 53 | self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 54 | kernel_size=1, stride=1, padding=0) 55 | nn.init.constant(self.W.weight, 0) 56 | nn.init.constant(self.W.bias, 0) 57 | 58 | self.theta = None 59 | self.phi = None 60 | self.concat_project = None 61 | 62 | # if mode in ['embedded_gaussian', 'dot_product', 'concatenation']: 63 | self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 64 | kernel_size=1, stride=1, padding=0) 65 | 66 | self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 67 | kernel_size=1, stride=1, padding=0) 68 | # elif mode == 'concatenation': 69 | self.concat_project = nn.Sequential( 70 | nn.Conv2d(self.inter_channels * 2, 1, 1, 1, 0, bias=False), 71 | nn.ReLU() 72 | ) 73 | 74 | # if mode in ['embedded_gaussian', 'dot_product', 'concatenation']: 75 | # self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 76 | # kernel_size=1, stride=1, padding=0) 77 | # self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 78 | # kernel_size=1, stride=1, padding=0) 79 | # 80 | # if mode == 'embedded_gaussian': 81 | # self.operation_function = self._embedded_gaussian 82 | # elif mode == 'dot_product': 83 | # self.operation_function = self._dot_product 84 | # elif mode == 'concatenation': 85 | # self.operation_function = self._concatenation 86 | # self.concat_project = nn.Sequential( 87 | # nn.Conv2d(self.inter_channels * 2, 1, 1, 1, 0, bias=False), 88 | # nn.ReLU() 89 | # ) 90 | # elif mode == 'gaussian': 91 | # self.operation_function = self._gaussian 92 | 93 | if sub_sample: 94 | self.g = nn.Sequential(self.g, max_pool_layer) 95 | if self.phi is None: 96 | self.phi = max_pool_layer 97 | else: 98 | self.phi = nn.Sequential(self.phi, max_pool_layer) 99 | 100 | print(self.phi) 101 | 102 | def forward(self, x): 103 | ''' 104 | :param x: (b, c, t, h, w) 105 | :return: 106 | ''' 107 | 108 | if self.mode == 'embedded_gaussian': 109 | output = self._embedded_gaussian(x) 110 | elif mode == 'dot_product': 111 | output = self._dot_product(x) 112 | elif mode == 'concatenation': 113 | output = self._concatenation(x) 114 | elif mode == 'gaussian': 115 | output = self._gaussian(x) 116 | 117 | return output 118 | 119 | def _embedded_gaussian(self, x): 120 | batch_size = x.size(0) 121 | 122 | # g=>(b, c, t, h, w)->(b, 0.5c, t, h, w)->(b, thw, 0.5c) 123 | g_x = self.g(x).view(batch_size, self.inter_channels, -1) 124 | g_x = g_x.permute(0, 2, 1) 125 | 126 | # theta=>(b, c, t, h, w)[->(b, 0.5c, t, h, w)]->(b, thw, 0.5c) 127 | # phi =>(b, c, t, h, w)[->(b, 0.5c, t, h, w)]->(b, 0.5c, thw) 128 | # f=>(b, thw, 0.5c)dot(b, 0.5c, twh) = (b, thw, thw) 129 | theta_x = self.theta(x).view(batch_size, self.inter_channels, -1) 130 | theta_x = theta_x.permute(0, 2, 1) 131 | phi_x = self.phi(x).view(batch_size, self.inter_channels, -1) 132 | f = torch.matmul(theta_x, phi_x) 133 | f_div_C = F.softmax(f, dim=-1) 134 | 135 | # (b, thw, thw)dot(b, thw, 0.5c) = (b, thw, 0.5c)->(b, 0.5c, t, h, w)->(b, c, t, h, w) 136 | y = torch.matmul(f_div_C, g_x) 137 | y = y.permute(0, 2, 1).contiguous() 138 | y = y.view(batch_size, self.inter_channels, *x.size()[2:]) 139 | W_y = self.W(y) 140 | z = W_y + x 141 | 142 | return z 143 | 144 | def _gaussian(self, x): 145 | batch_size = x.size(0) 146 | 147 | g_x = self.g(x).view(batch_size, self.inter_channels, -1) 148 | 149 | g_x = g_x.permute(0, 2, 1) 150 | 151 | theta_x = x.view(batch_size, self.in_channels, -1) 152 | theta_x = theta_x.permute(0, 2, 1) 153 | 154 | if self.sub_sample: 155 | print(self.phi(x).size()) 156 | phi_x = self.phi(x).view(batch_size, self.in_channels, -1) 157 | else: 158 | phi_x = x.view(batch_size, self.in_channels, -1) 159 | print(phi_x.size()) 160 | f = torch.matmul(theta_x, phi_x) 161 | f_div_C = F.softmax(f, dim=-1) 162 | 163 | print(f_div_C.size(), g_x.size()) 164 | 165 | y = torch.matmul(f_div_C, g_x) 166 | y = y.permute(0, 2, 1).contiguous() 167 | y = y.view(batch_size, self.inter_channels, *x.size()[2:]) 168 | W_y = self.W(y) 169 | z = W_y + x 170 | 171 | return z 172 | 173 | def _dot_product(self, x): 174 | batch_size = x.size(0) 175 | 176 | g_x = self.g(x).view(batch_size, self.inter_channels, -1) 177 | g_x = g_x.permute(0, 2, 1) 178 | 179 | theta_x = self.theta(x).view(batch_size, self.inter_channels, -1) 180 | theta_x = theta_x.permute(0, 2, 1) 181 | phi_x = self.phi(x).view(batch_size, self.inter_channels, -1) 182 | f = torch.matmul(theta_x, phi_x) 183 | N = f.size(-1) 184 | f_div_C = f / N 185 | 186 | y = torch.matmul(f_div_C, g_x) 187 | y = y.permute(0, 2, 1).contiguous() 188 | y = y.view(batch_size, self.inter_channels, *x.size()[2:]) 189 | W_y = self.W(y) 190 | z = W_y + x 191 | 192 | return z 193 | 194 | def _concatenation(self, x): 195 | batch_size = x.size(0) 196 | 197 | g_x = self.g(x).view(batch_size, self.inter_channels, -1) 198 | g_x = g_x.permute(0, 2, 1) 199 | 200 | # (b, c, N, 1) 201 | theta_x = self.theta(x).view(batch_size, self.inter_channels, -1, 1) 202 | # (b, c, 1, N) 203 | phi_x = self.phi(x).view(batch_size, self.inter_channels, 1, -1) 204 | 205 | h = theta_x.size(2) 206 | w = phi_x.size(3) 207 | theta_x = theta_x.repeat(1, 1, 1, w) 208 | phi_x = phi_x.repeat(1, 1, h, 1) 209 | 210 | concat_feature = torch.cat([theta_x, phi_x], dim=1) 211 | f = self.concat_project(concat_feature) 212 | b, _, h, w = f.size() 213 | f = f.view(b, h, w) 214 | 215 | N = f.size(-1) 216 | f_div_C = f / N 217 | 218 | y = torch.matmul(f_div_C, g_x) 219 | y = y.permute(0, 2, 1).contiguous() 220 | y = y.view(batch_size, self.inter_channels, *x.size()[2:]) 221 | W_y = self.W(y) 222 | z = W_y + x 223 | 224 | return z 225 | 226 | 227 | class NONLocalBlock1D(_NonLocalBlockND): 228 | def __init__(self, in_channels, inter_channels=None, mode='embedded_gaussian', sub_sample=True, bn_layer=True): 229 | super(NONLocalBlock1D, self).__init__(in_channels, 230 | inter_channels=inter_channels, 231 | dimension=1, mode=mode, 232 | sub_sample=sub_sample, 233 | bn_layer=bn_layer) 234 | 235 | 236 | class NONLocalBlock2D(_NonLocalBlockND): 237 | def __init__(self, in_channels, inter_channels=None, mode='embedded_gaussian', sub_sample=True, bn_layer=True): 238 | super(NONLocalBlock2D, self).__init__(in_channels, 239 | inter_channels=inter_channels, 240 | dimension=2, mode=mode, 241 | sub_sample=sub_sample, 242 | bn_layer=bn_layer) 243 | 244 | 245 | class NONLocalBlock3D(_NonLocalBlockND): 246 | def __init__(self, in_channels, inter_channels=None, mode='embedded_gaussian', sub_sample=True, bn_layer=True): 247 | super(NONLocalBlock3D, self).__init__(in_channels, 248 | inter_channels=inter_channels, 249 | dimension=3, mode=mode, 250 | sub_sample=sub_sample, 251 | bn_layer=bn_layer) 252 | 253 | 254 | if __name__ == '__main__': 255 | from torch.autograd import Variable 256 | 257 | # mode_list = ['concatenation', 'embedded_gaussian', 'gaussian', 'dot_product', ] 258 | mode_list = ['gaussian'] 259 | 260 | for mode in mode_list: 261 | print(mode) 262 | img = Variable(torch.zeros(2, 6, 20)) 263 | net = NONLocalBlock1D(6, mode=mode, sub_sample=True) 264 | out = net(img) 265 | print(out.size()) 266 | 267 | # img = Variable(torch.zeros(2, 4, 20, 20)) 268 | # net = NONLocalBlock2D(4, mode=mode, sub_sample=False, bn_layer=False) 269 | # out = net(img) 270 | # print(out.size()) 271 | # 272 | # img = Variable(torch.zeros(2, 4, 10, 20, 20)) 273 | # net = NONLocalBlock3D(4, mode=mode) 274 | # out = net(img) 275 | # print(out.size()) 276 | 277 | -------------------------------------------------------------------------------- /Non-Local_pytorch_0.3.1/lib/backup/non_local_simple_version.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.nn import functional as F 4 | 5 | 6 | class _NonLocalBlockND(nn.Module): 7 | def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True): 8 | super(_NonLocalBlockND, self).__init__() 9 | 10 | assert dimension in [1, 2, 3] 11 | 12 | self.dimension = dimension 13 | self.sub_sample = sub_sample 14 | 15 | self.in_channels = in_channels 16 | self.inter_channels = inter_channels 17 | 18 | if self.inter_channels is None: 19 | self.inter_channels = in_channels // 2 20 | if self.inter_channels == 0: 21 | self.inter_channels = 1 22 | 23 | if dimension == 3: 24 | conv_nd = nn.Conv3d 25 | max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2)) 26 | bn = nn.BatchNorm3d 27 | elif dimension == 2: 28 | conv_nd = nn.Conv2d 29 | max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2)) 30 | bn = nn.BatchNorm2d 31 | else: 32 | conv_nd = nn.Conv1d 33 | max_pool_layer = nn.MaxPool1d(kernel_size=(2)) 34 | bn = nn.BatchNorm1d 35 | 36 | self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 37 | kernel_size=1, stride=1, padding=0) 38 | 39 | if bn_layer: 40 | self.W = nn.Sequential( 41 | conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 42 | kernel_size=1, stride=1, padding=0), 43 | bn(self.in_channels) 44 | ) 45 | nn.init.constant(self.W[1].weight, 0) 46 | nn.init.constant(self.W[1].bias, 0) 47 | else: 48 | self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 49 | kernel_size=1, stride=1, padding=0) 50 | nn.init.constant(self.W.weight, 0) 51 | nn.init.constant(self.W.bias, 0) 52 | 53 | self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 54 | kernel_size=1, stride=1, padding=0) 55 | self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 56 | kernel_size=1, stride=1, padding=0) 57 | 58 | if sub_sample: 59 | self.g = nn.Sequential(self.g, max_pool_layer) 60 | self.phi = nn.Sequential(self.phi, max_pool_layer) 61 | 62 | def forward(self, x): 63 | ''' 64 | :param x: (b, c, t, h, w) 65 | :return: 66 | ''' 67 | 68 | batch_size = x.size(0) 69 | 70 | g_x = self.g(x).view(batch_size, self.inter_channels, -1) 71 | g_x = g_x.permute(0, 2, 1) 72 | 73 | theta_x = self.theta(x).view(batch_size, self.inter_channels, -1) 74 | theta_x = theta_x.permute(0, 2, 1) 75 | phi_x = self.phi(x).view(batch_size, self.inter_channels, -1) 76 | f = torch.matmul(theta_x, phi_x) 77 | f_div_C = F.softmax(f, dim=-1) 78 | 79 | y = torch.matmul(f_div_C, g_x) 80 | y = y.permute(0, 2, 1).contiguous() 81 | y = y.view(batch_size, self.inter_channels, *x.size()[2:]) 82 | W_y = self.W(y) 83 | z = W_y + x 84 | 85 | return z 86 | 87 | 88 | class NONLocalBlock1D(_NonLocalBlockND): 89 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 90 | super(NONLocalBlock1D, self).__init__(in_channels, 91 | inter_channels=inter_channels, 92 | dimension=1, sub_sample=sub_sample, 93 | bn_layer=bn_layer) 94 | 95 | 96 | class NONLocalBlock2D(_NonLocalBlockND): 97 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 98 | super(NONLocalBlock2D, self).__init__(in_channels, 99 | inter_channels=inter_channels, 100 | dimension=2, sub_sample=sub_sample, 101 | bn_layer=bn_layer) 102 | 103 | 104 | class NONLocalBlock3D(_NonLocalBlockND): 105 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 106 | super(NONLocalBlock3D, self).__init__(in_channels, 107 | inter_channels=inter_channels, 108 | dimension=3, sub_sample=sub_sample, 109 | bn_layer=bn_layer) 110 | 111 | 112 | if __name__ == '__main__': 113 | from torch.autograd import Variable 114 | import torch 115 | 116 | sub_sample = True 117 | bn_layer = True 118 | 119 | img = Variable(torch.zeros(2, 3, 20)) 120 | net = NONLocalBlock1D(3, sub_sample=sub_sample, bn_layer=bn_layer) 121 | out = net(img) 122 | print(out.size()) 123 | 124 | img = Variable(torch.zeros(2, 3, 20, 20)) 125 | net = NONLocalBlock2D(3, sub_sample=sub_sample, bn_layer=bn_layer) 126 | out = net(img) 127 | print(out.size()) 128 | 129 | img = Variable(torch.randn(2, 3, 10, 20, 20)) 130 | net = NONLocalBlock3D(3, sub_sample=sub_sample, bn_layer=bn_layer) 131 | out = net(img) 132 | print(out.size()) 133 | 134 | -------------------------------------------------------------------------------- /Non-Local_pytorch_0.3.1/lib/network.py: -------------------------------------------------------------------------------- 1 | from torch import nn 2 | # from lib.non_local_concatenation import NONLocalBlock2D 3 | # from lib.non_local_gaussian import NONLocalBlock2D 4 | from lib.non_local_embedded_gaussian import NONLocalBlock2D 5 | # from lib.non_local_dot_product import NONLocalBlock2D 6 | 7 | 8 | class Network(nn.Module): 9 | def __init__(self): 10 | super(Network, self).__init__() 11 | 12 | self.convs = nn.Sequential( 13 | nn.Conv2d(in_channels=1, out_channels=32, kernel_size=3, stride=1, padding=1), 14 | nn.BatchNorm2d(32), 15 | nn.ReLU(), 16 | nn.MaxPool2d(2), 17 | 18 | NONLocalBlock2D(in_channels=32), 19 | nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1), 20 | nn.BatchNorm2d(64), 21 | nn.ReLU(), 22 | nn.MaxPool2d(2), 23 | 24 | NONLocalBlock2D(in_channels=64), 25 | nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1), 26 | nn.BatchNorm2d(128), 27 | nn.ReLU(), 28 | nn.MaxPool2d(2), 29 | ) 30 | 31 | self.fc = nn.Sequential( 32 | nn.Linear(in_features=128*3*3, out_features=256), 33 | nn.ReLU(), 34 | nn.Dropout(0.5), 35 | 36 | nn.Linear(in_features=256, out_features=10) 37 | ) 38 | 39 | def forward(self, x): 40 | batch_size = x.size(0) 41 | output = self.convs(x).view(batch_size, -1) 42 | output = self.fc(output) 43 | return output 44 | 45 | if __name__ == '__main__': 46 | import torch 47 | from torch.autograd import Variable 48 | 49 | img = Variable(torch.randn(3, 1, 28, 28)) 50 | net = Network() 51 | out = net(img) 52 | print(out.size()) 53 | 54 | -------------------------------------------------------------------------------- /Non-Local_pytorch_0.3.1/lib/non_local_concatenation.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.nn import functional as F 4 | 5 | 6 | class _NonLocalBlockND(nn.Module): 7 | def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True): 8 | super(_NonLocalBlockND, self).__init__() 9 | 10 | assert dimension in [1, 2, 3] 11 | 12 | self.dimension = dimension 13 | self.sub_sample = sub_sample 14 | 15 | self.in_channels = in_channels 16 | self.inter_channels = inter_channels 17 | 18 | if self.inter_channels is None: 19 | self.inter_channels = in_channels // 2 20 | if self.inter_channels == 0: 21 | self.inter_channels = 1 22 | 23 | if dimension == 3: 24 | conv_nd = nn.Conv3d 25 | max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2)) 26 | bn = nn.BatchNorm3d 27 | elif dimension == 2: 28 | conv_nd = nn.Conv2d 29 | max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2)) 30 | bn = nn.BatchNorm2d 31 | else: 32 | conv_nd = nn.Conv1d 33 | max_pool_layer = nn.MaxPool1d(kernel_size=(2)) 34 | bn = nn.BatchNorm1d 35 | 36 | self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 37 | kernel_size=1, stride=1, padding=0) 38 | 39 | if bn_layer: 40 | self.W = nn.Sequential( 41 | conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 42 | kernel_size=1, stride=1, padding=0), 43 | bn(self.in_channels) 44 | ) 45 | nn.init.constant(self.W[1].weight, 0) 46 | nn.init.constant(self.W[1].bias, 0) 47 | else: 48 | self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 49 | kernel_size=1, stride=1, padding=0) 50 | nn.init.constant(self.W.weight, 0) 51 | nn.init.constant(self.W.bias, 0) 52 | 53 | self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 54 | kernel_size=1, stride=1, padding=0) 55 | 56 | self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 57 | kernel_size=1, stride=1, padding=0) 58 | 59 | self.concat_project = nn.Sequential( 60 | nn.Conv2d(self.inter_channels * 2, 1, 1, 1, 0, bias=False), 61 | nn.ReLU() 62 | ) 63 | 64 | if sub_sample: 65 | self.g = nn.Sequential(self.g, max_pool_layer) 66 | self.phi = nn.Sequential(self.phi, max_pool_layer) 67 | 68 | def forward(self, x): 69 | ''' 70 | :param x: (b, c, t, h, w) 71 | :return: 72 | ''' 73 | 74 | batch_size = x.size(0) 75 | 76 | g_x = self.g(x).view(batch_size, self.inter_channels, -1) 77 | g_x = g_x.permute(0, 2, 1) 78 | 79 | # (b, c, N, 1) 80 | theta_x = self.theta(x).view(batch_size, self.inter_channels, -1, 1) 81 | # (b, c, 1, N) 82 | phi_x = self.phi(x).view(batch_size, self.inter_channels, 1, -1) 83 | 84 | h = theta_x.size(2) 85 | w = phi_x.size(3) 86 | theta_x = theta_x.repeat(1, 1, 1, w) 87 | phi_x = phi_x.repeat(1, 1, h, 1) 88 | 89 | concat_feature = torch.cat([theta_x, phi_x], dim=1) 90 | f = self.concat_project(concat_feature) 91 | b, _, h, w = f.size() 92 | f = f.view(b, h, w) 93 | 94 | N = f.size(-1) 95 | f_div_C = f / N 96 | 97 | y = torch.matmul(f_div_C, g_x) 98 | y = y.permute(0, 2, 1).contiguous() 99 | y = y.view(batch_size, self.inter_channels, *x.size()[2:]) 100 | W_y = self.W(y) 101 | z = W_y + x 102 | 103 | return z 104 | 105 | 106 | class NONLocalBlock1D(_NonLocalBlockND): 107 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 108 | super(NONLocalBlock1D, self).__init__(in_channels, 109 | inter_channels=inter_channels, 110 | dimension=1, sub_sample=sub_sample, 111 | bn_layer=bn_layer) 112 | 113 | 114 | class NONLocalBlock2D(_NonLocalBlockND): 115 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 116 | super(NONLocalBlock2D, self).__init__(in_channels, 117 | inter_channels=inter_channels, 118 | dimension=2, sub_sample=sub_sample, 119 | bn_layer=bn_layer) 120 | 121 | 122 | class NONLocalBlock3D(_NonLocalBlockND): 123 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 124 | super(NONLocalBlock3D, self).__init__(in_channels, 125 | inter_channels=inter_channels, 126 | dimension=3, sub_sample=sub_sample, 127 | bn_layer=bn_layer) 128 | 129 | 130 | if __name__ == '__main__': 131 | from torch.autograd import Variable 132 | import torch 133 | 134 | for (sub_sample, bn_layer) in [(True, True), (False, False), (True, False), (False, True)]: 135 | img = Variable(torch.zeros(2, 3, 20)) 136 | net = NONLocalBlock1D(3, sub_sample=sub_sample, bn_layer=bn_layer) 137 | out = net(img) 138 | print(out.size()) 139 | 140 | img = Variable(torch.zeros(2, 3, 20, 20)) 141 | net = NONLocalBlock2D(3, sub_sample=sub_sample, bn_layer=bn_layer) 142 | out = net(img) 143 | print(out.size()) 144 | 145 | img = Variable(torch.randn(2, 3, 8, 20, 20)) 146 | net = NONLocalBlock3D(3, sub_sample=sub_sample, bn_layer=bn_layer) 147 | out = net(img) 148 | print(out.size()) 149 | -------------------------------------------------------------------------------- /Non-Local_pytorch_0.3.1/lib/non_local_dot_product.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.nn import functional as F 4 | 5 | 6 | class _NonLocalBlockND(nn.Module): 7 | def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True): 8 | super(_NonLocalBlockND, self).__init__() 9 | 10 | assert dimension in [1, 2, 3] 11 | 12 | self.dimension = dimension 13 | self.sub_sample = sub_sample 14 | 15 | self.in_channels = in_channels 16 | self.inter_channels = inter_channels 17 | 18 | if self.inter_channels is None: 19 | self.inter_channels = in_channels // 2 20 | if self.inter_channels == 0: 21 | self.inter_channels = 1 22 | 23 | if dimension == 3: 24 | conv_nd = nn.Conv3d 25 | max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2)) 26 | bn = nn.BatchNorm3d 27 | elif dimension == 2: 28 | conv_nd = nn.Conv2d 29 | max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2)) 30 | bn = nn.BatchNorm2d 31 | else: 32 | conv_nd = nn.Conv1d 33 | max_pool_layer = nn.MaxPool1d(kernel_size=(2)) 34 | bn = nn.BatchNorm1d 35 | 36 | self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 37 | kernel_size=1, stride=1, padding=0) 38 | 39 | if bn_layer: 40 | self.W = nn.Sequential( 41 | conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 42 | kernel_size=1, stride=1, padding=0), 43 | bn(self.in_channels) 44 | ) 45 | nn.init.constant(self.W[1].weight, 0) 46 | nn.init.constant(self.W[1].bias, 0) 47 | else: 48 | self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 49 | kernel_size=1, stride=1, padding=0) 50 | nn.init.constant(self.W.weight, 0) 51 | nn.init.constant(self.W.bias, 0) 52 | 53 | self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 54 | kernel_size=1, stride=1, padding=0) 55 | 56 | self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 57 | kernel_size=1, stride=1, padding=0) 58 | 59 | if sub_sample: 60 | self.g = nn.Sequential(self.g, max_pool_layer) 61 | self.phi = nn.Sequential(self.phi, max_pool_layer) 62 | 63 | def forward(self, x): 64 | ''' 65 | :param x: (b, c, t, h, w) 66 | :return: 67 | ''' 68 | 69 | batch_size = x.size(0) 70 | 71 | g_x = self.g(x).view(batch_size, self.inter_channels, -1) 72 | g_x = g_x.permute(0, 2, 1) 73 | 74 | theta_x = self.theta(x).view(batch_size, self.inter_channels, -1) 75 | theta_x = theta_x.permute(0, 2, 1) 76 | phi_x = self.phi(x).view(batch_size, self.inter_channels, -1) 77 | f = torch.matmul(theta_x, phi_x) 78 | N = f.size(-1) 79 | f_div_C = f / N 80 | 81 | y = torch.matmul(f_div_C, g_x) 82 | y = y.permute(0, 2, 1).contiguous() 83 | y = y.view(batch_size, self.inter_channels, *x.size()[2:]) 84 | W_y = self.W(y) 85 | z = W_y + x 86 | 87 | return z 88 | 89 | 90 | class NONLocalBlock1D(_NonLocalBlockND): 91 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 92 | super(NONLocalBlock1D, self).__init__(in_channels, 93 | inter_channels=inter_channels, 94 | dimension=1, sub_sample=sub_sample, 95 | bn_layer=bn_layer) 96 | 97 | 98 | class NONLocalBlock2D(_NonLocalBlockND): 99 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 100 | super(NONLocalBlock2D, self).__init__(in_channels, 101 | inter_channels=inter_channels, 102 | dimension=2, sub_sample=sub_sample, 103 | bn_layer=bn_layer) 104 | 105 | 106 | class NONLocalBlock3D(_NonLocalBlockND): 107 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 108 | super(NONLocalBlock3D, self).__init__(in_channels, 109 | inter_channels=inter_channels, 110 | dimension=3, sub_sample=sub_sample, 111 | bn_layer=bn_layer) 112 | 113 | 114 | if __name__ == '__main__': 115 | from torch.autograd import Variable 116 | import torch 117 | 118 | for (sub_sample, bn_layer) in [(True, True), (False, False), (True, False), (False, True)]: 119 | img = Variable(torch.zeros(2, 3, 20)) 120 | net = NONLocalBlock1D(3, sub_sample=sub_sample, bn_layer=bn_layer) 121 | out = net(img) 122 | print(out.size()) 123 | 124 | img = Variable(torch.zeros(2, 3, 20, 20)) 125 | net = NONLocalBlock2D(3, sub_sample=sub_sample, bn_layer=bn_layer) 126 | out = net(img) 127 | print(out.size()) 128 | 129 | img = Variable(torch.randn(2, 3, 8, 20, 20)) 130 | net = NONLocalBlock3D(3, sub_sample=sub_sample, bn_layer=bn_layer) 131 | out = net(img) 132 | print(out.size()) 133 | 134 | 135 | 136 | -------------------------------------------------------------------------------- /Non-Local_pytorch_0.3.1/lib/non_local_embedded_gaussian.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.nn import functional as F 4 | 5 | 6 | class _NonLocalBlockND(nn.Module): 7 | def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True): 8 | super(_NonLocalBlockND, self).__init__() 9 | 10 | assert dimension in [1, 2, 3] 11 | 12 | self.dimension = dimension 13 | self.sub_sample = sub_sample 14 | 15 | self.in_channels = in_channels 16 | self.inter_channels = inter_channels 17 | 18 | if self.inter_channels is None: 19 | self.inter_channels = in_channels // 2 20 | if self.inter_channels == 0: 21 | self.inter_channels = 1 22 | 23 | if dimension == 3: 24 | conv_nd = nn.Conv3d 25 | max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2)) 26 | bn = nn.BatchNorm3d 27 | elif dimension == 2: 28 | conv_nd = nn.Conv2d 29 | max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2)) 30 | bn = nn.BatchNorm2d 31 | else: 32 | conv_nd = nn.Conv1d 33 | max_pool_layer = nn.MaxPool1d(kernel_size=(2)) 34 | bn = nn.BatchNorm1d 35 | 36 | self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 37 | kernel_size=1, stride=1, padding=0) 38 | 39 | if bn_layer: 40 | self.W = nn.Sequential( 41 | conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 42 | kernel_size=1, stride=1, padding=0), 43 | bn(self.in_channels) 44 | ) 45 | nn.init.constant(self.W[1].weight, 0) 46 | nn.init.constant(self.W[1].bias, 0) 47 | else: 48 | self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 49 | kernel_size=1, stride=1, padding=0) 50 | nn.init.constant(self.W.weight, 0) 51 | nn.init.constant(self.W.bias, 0) 52 | 53 | self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 54 | kernel_size=1, stride=1, padding=0) 55 | self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 56 | kernel_size=1, stride=1, padding=0) 57 | 58 | if sub_sample: 59 | self.g = nn.Sequential(self.g, max_pool_layer) 60 | self.phi = nn.Sequential(self.phi, max_pool_layer) 61 | 62 | def forward(self, x): 63 | ''' 64 | :param x: (b, c, t, h, w) 65 | :return: 66 | ''' 67 | 68 | batch_size = x.size(0) 69 | 70 | g_x = self.g(x).view(batch_size, self.inter_channels, -1) 71 | g_x = g_x.permute(0, 2, 1) 72 | 73 | theta_x = self.theta(x).view(batch_size, self.inter_channels, -1) 74 | theta_x = theta_x.permute(0, 2, 1) 75 | phi_x = self.phi(x).view(batch_size, self.inter_channels, -1) 76 | f = torch.matmul(theta_x, phi_x) 77 | f_div_C = F.softmax(f, dim=-1) 78 | 79 | y = torch.matmul(f_div_C, g_x) 80 | y = y.permute(0, 2, 1).contiguous() 81 | y = y.view(batch_size, self.inter_channels, *x.size()[2:]) 82 | W_y = self.W(y) 83 | z = W_y + x 84 | 85 | return z 86 | 87 | 88 | class NONLocalBlock1D(_NonLocalBlockND): 89 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 90 | super(NONLocalBlock1D, self).__init__(in_channels, 91 | inter_channels=inter_channels, 92 | dimension=1, sub_sample=sub_sample, 93 | bn_layer=bn_layer) 94 | 95 | 96 | class NONLocalBlock2D(_NonLocalBlockND): 97 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 98 | super(NONLocalBlock2D, self).__init__(in_channels, 99 | inter_channels=inter_channels, 100 | dimension=2, sub_sample=sub_sample, 101 | bn_layer=bn_layer) 102 | 103 | 104 | class NONLocalBlock3D(_NonLocalBlockND): 105 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 106 | super(NONLocalBlock3D, self).__init__(in_channels, 107 | inter_channels=inter_channels, 108 | dimension=3, sub_sample=sub_sample, 109 | bn_layer=bn_layer) 110 | 111 | 112 | if __name__ == '__main__': 113 | from torch.autograd import Variable 114 | import torch 115 | 116 | sub_sample = True 117 | bn_layer = True 118 | 119 | img = Variable(torch.zeros(2, 3, 20)) 120 | net = NONLocalBlock1D(3, sub_sample=sub_sample, bn_layer=bn_layer) 121 | out = net(img) 122 | print(out.size()) 123 | 124 | img = Variable(torch.zeros(2, 3, 20, 20)) 125 | net = NONLocalBlock2D(3, sub_sample=sub_sample, bn_layer=bn_layer) 126 | out = net(img) 127 | print(out.size()) 128 | 129 | img = Variable(torch.randn(2, 3, 10, 20, 20)) 130 | net = NONLocalBlock3D(3, sub_sample=sub_sample, bn_layer=bn_layer) 131 | out = net(img) 132 | print(out.size()) 133 | 134 | -------------------------------------------------------------------------------- /Non-Local_pytorch_0.3.1/lib/non_local_gaussian.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.nn import functional as F 4 | 5 | 6 | class _NonLocalBlockND(nn.Module): 7 | def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True): 8 | super(_NonLocalBlockND, self).__init__() 9 | 10 | assert dimension in [1, 2, 3] 11 | 12 | self.dimension = dimension 13 | self.sub_sample = sub_sample 14 | 15 | self.in_channels = in_channels 16 | self.inter_channels = inter_channels 17 | 18 | if self.inter_channels is None: 19 | self.inter_channels = in_channels // 2 20 | if self.inter_channels == 0: 21 | self.inter_channels = 1 22 | 23 | if dimension == 3: 24 | conv_nd = nn.Conv3d 25 | max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2)) 26 | bn = nn.BatchNorm3d 27 | elif dimension == 2: 28 | conv_nd = nn.Conv2d 29 | max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2)) 30 | bn = nn.BatchNorm2d 31 | else: 32 | conv_nd = nn.Conv1d 33 | max_pool_layer = nn.MaxPool1d(kernel_size=(2)) 34 | bn = nn.BatchNorm1d 35 | 36 | self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 37 | kernel_size=1, stride=1, padding=0) 38 | 39 | if bn_layer: 40 | self.W = nn.Sequential( 41 | conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 42 | kernel_size=1, stride=1, padding=0), 43 | bn(self.in_channels) 44 | ) 45 | nn.init.constant(self.W[1].weight, 0) 46 | nn.init.constant(self.W[1].bias, 0) 47 | else: 48 | self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 49 | kernel_size=1, stride=1, padding=0) 50 | nn.init.constant(self.W.weight, 0) 51 | nn.init.constant(self.W.bias, 0) 52 | 53 | if sub_sample: 54 | self.g = nn.Sequential(self.g, max_pool_layer) 55 | self.phi = max_pool_layer 56 | 57 | def forward(self, x): 58 | ''' 59 | :param x: (b, c, t, h, w) 60 | :return: 61 | ''' 62 | 63 | batch_size = x.size(0) 64 | 65 | g_x = self.g(x).view(batch_size, self.inter_channels, -1) 66 | 67 | g_x = g_x.permute(0, 2, 1) 68 | 69 | theta_x = x.view(batch_size, self.in_channels, -1) 70 | theta_x = theta_x.permute(0, 2, 1) 71 | 72 | if self.sub_sample: 73 | phi_x = self.phi(x).view(batch_size, self.in_channels, -1) 74 | else: 75 | phi_x = x.view(batch_size, self.in_channels, -1) 76 | 77 | f = torch.matmul(theta_x, phi_x) 78 | f_div_C = F.softmax(f, dim=-1) 79 | 80 | y = torch.matmul(f_div_C, g_x) 81 | y = y.permute(0, 2, 1).contiguous() 82 | y = y.view(batch_size, self.inter_channels, *x.size()[2:]) 83 | W_y = self.W(y) 84 | z = W_y + x 85 | 86 | return z 87 | 88 | 89 | class NONLocalBlock1D(_NonLocalBlockND): 90 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 91 | super(NONLocalBlock1D, self).__init__(in_channels, 92 | inter_channels=inter_channels, 93 | dimension=1, sub_sample=sub_sample, 94 | bn_layer=bn_layer) 95 | 96 | 97 | class NONLocalBlock2D(_NonLocalBlockND): 98 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 99 | super(NONLocalBlock2D, self).__init__(in_channels, 100 | inter_channels=inter_channels, 101 | dimension=2, sub_sample=sub_sample, 102 | bn_layer=bn_layer) 103 | 104 | 105 | class NONLocalBlock3D(_NonLocalBlockND): 106 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 107 | super(NONLocalBlock3D, self).__init__(in_channels, 108 | inter_channels=inter_channels, 109 | dimension=3, sub_sample=sub_sample, 110 | bn_layer=bn_layer) 111 | 112 | 113 | if __name__ == '__main__': 114 | from torch.autograd import Variable 115 | import torch 116 | 117 | for (sub_sample, bn_layer) in [(True, True), (False, False), (True, False), (False, True)]: 118 | img = Variable(torch.zeros(2, 3, 20)) 119 | net = NONLocalBlock1D(3, sub_sample=sub_sample, bn_layer=bn_layer) 120 | out = net(img) 121 | print(out.size()) 122 | 123 | img = Variable(torch.zeros(2, 3, 20, 20)) 124 | net = NONLocalBlock2D(3, sub_sample=sub_sample, bn_layer=bn_layer) 125 | out = net(img) 126 | print(out.size()) 127 | 128 | img = Variable(torch.randn(2, 3, 8, 20, 20)) 129 | net = NONLocalBlock3D(3, sub_sample=sub_sample, bn_layer=bn_layer) 130 | out = net(img) 131 | print(out.size()) 132 | 133 | 134 | 135 | 136 | 137 | -------------------------------------------------------------------------------- /Non-Local_pytorch_0.4.1_to_1.1.0/demo_MNIST.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.utils.data as Data 3 | import torchvision 4 | from lib.network import Network 5 | from torch import nn 6 | import time 7 | 8 | 9 | # def calc_acc(x, y): 10 | # x = torch.max(x, dim=-1)[1] 11 | # accuracy = sum(x == y) / x.size(0) 12 | # return accuracy 13 | 14 | 15 | train_data = torchvision.datasets.MNIST(root='./mnist', train=True, 16 | transform=torchvision.transforms.ToTensor(), 17 | download=True) 18 | test_data = torchvision.datasets.MNIST(root='./mnist/', 19 | transform=torchvision.transforms.ToTensor(), 20 | train=False) 21 | 22 | train_loader = Data.DataLoader(dataset=train_data, batch_size=128, shuffle=True) 23 | test_loader = Data.DataLoader(dataset=test_data, batch_size=128, shuffle=False) 24 | 25 | train_batch_num = len(train_loader) 26 | test_batch_num = len(test_loader) 27 | 28 | net = Network() 29 | if torch.cuda.is_available(): 30 | net = nn.DataParallel(net) 31 | net.cuda() 32 | 33 | opt = torch.optim.Adam(net.parameters(), lr=0.001) 34 | loss_func = nn.CrossEntropyLoss() 35 | 36 | for epoch_index in range(20): 37 | st = time.time() 38 | 39 | torch.set_grad_enabled(True) 40 | net.train() 41 | for train_batch_index, (img_batch, label_batch) in enumerate(train_loader): 42 | if torch.cuda.is_available(): 43 | img_batch = img_batch.cuda() 44 | label_batch = label_batch.cuda() 45 | 46 | predict = net(img_batch) 47 | # acc = calc_acc(predict.cpu().data, label_batch.cpu().data) 48 | loss = loss_func(predict, label_batch) 49 | 50 | net.zero_grad() 51 | loss.backward() 52 | opt.step() 53 | 54 | print('(LR:%f) Time of a epoch:%.4fs' % (opt.param_groups[0]['lr'], time.time()-st)) 55 | 56 | torch.set_grad_enabled(False) 57 | net.eval() 58 | total_loss = [] 59 | total_acc = 0 60 | total_sample = 0 61 | 62 | for test_batch_index, (img_batch, label_batch) in enumerate(test_loader): 63 | if torch.cuda.is_available(): 64 | img_batch = img_batch.cuda() 65 | label_batch = label_batch.cuda() 66 | 67 | predict = net(img_batch) 68 | loss = loss_func(predict, label_batch) 69 | 70 | predict = predict.argmax(dim=1) 71 | acc = (predict == label_batch).sum() 72 | 73 | total_loss.append(loss) 74 | total_acc += acc 75 | total_sample += img_batch.size(0) 76 | 77 | net.train() 78 | 79 | mean_acc = total_acc.item() * 1.0 / total_sample 80 | mean_loss = sum(total_loss) / total_loss.__len__() 81 | 82 | print('[Test] epoch[%d/%d] acc:%.4f%% loss:%.4f\n' 83 | % (epoch_index, 100, mean_acc * 100, mean_loss.item())) 84 | -------------------------------------------------------------------------------- /Non-Local_pytorch_0.4.1_to_1.1.0/lib/network.py: -------------------------------------------------------------------------------- 1 | from torch import nn 2 | # from lib.non_local_concatenation import NONLocalBlock2D 3 | # from lib.non_local_gaussian import NONLocalBlock2D 4 | from lib.non_local_embedded_gaussian import NONLocalBlock2D 5 | # from lib.non_local_dot_product import NONLocalBlock2D 6 | 7 | 8 | class Network(nn.Module): 9 | def __init__(self): 10 | super(Network, self).__init__() 11 | 12 | self.convs = nn.Sequential( 13 | nn.Conv2d(in_channels=1, out_channels=32, kernel_size=3, stride=1, padding=1), 14 | nn.BatchNorm2d(32), 15 | nn.ReLU(), 16 | nn.MaxPool2d(2), 17 | 18 | NONLocalBlock2D(in_channels=32), 19 | nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1), 20 | nn.BatchNorm2d(64), 21 | nn.ReLU(), 22 | nn.MaxPool2d(2), 23 | 24 | NONLocalBlock2D(in_channels=64), 25 | nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1), 26 | nn.BatchNorm2d(128), 27 | nn.ReLU(), 28 | nn.MaxPool2d(2), 29 | ) 30 | 31 | self.fc = nn.Sequential( 32 | nn.Linear(in_features=128*3*3, out_features=256), 33 | nn.ReLU(), 34 | nn.Dropout(0.5), 35 | 36 | nn.Linear(in_features=256, out_features=10) 37 | ) 38 | 39 | def forward(self, x): 40 | batch_size = x.size(0) 41 | output = self.convs(x).view(batch_size, -1) 42 | output = self.fc(output) 43 | return output 44 | 45 | if __name__ == '__main__': 46 | import torch 47 | 48 | img = torch.randn(3, 1, 28, 28) 49 | net = Network() 50 | out = net(img) 51 | print(out.size()) 52 | 53 | -------------------------------------------------------------------------------- /Non-Local_pytorch_0.4.1_to_1.1.0/lib/non_local_concatenation.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.nn import functional as F 4 | 5 | 6 | class _NonLocalBlockND(nn.Module): 7 | def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True): 8 | super(_NonLocalBlockND, self).__init__() 9 | 10 | assert dimension in [1, 2, 3] 11 | 12 | self.dimension = dimension 13 | self.sub_sample = sub_sample 14 | 15 | self.in_channels = in_channels 16 | self.inter_channels = inter_channels 17 | 18 | if self.inter_channels is None: 19 | self.inter_channels = in_channels // 2 20 | if self.inter_channels == 0: 21 | self.inter_channels = 1 22 | 23 | if dimension == 3: 24 | conv_nd = nn.Conv3d 25 | max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2)) 26 | bn = nn.BatchNorm3d 27 | elif dimension == 2: 28 | conv_nd = nn.Conv2d 29 | max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2)) 30 | bn = nn.BatchNorm2d 31 | else: 32 | conv_nd = nn.Conv1d 33 | max_pool_layer = nn.MaxPool1d(kernel_size=(2)) 34 | bn = nn.BatchNorm1d 35 | 36 | self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 37 | kernel_size=1, stride=1, padding=0) 38 | 39 | if bn_layer: 40 | self.W = nn.Sequential( 41 | conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 42 | kernel_size=1, stride=1, padding=0), 43 | bn(self.in_channels) 44 | ) 45 | nn.init.constant_(self.W[1].weight, 0) 46 | nn.init.constant_(self.W[1].bias, 0) 47 | else: 48 | self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 49 | kernel_size=1, stride=1, padding=0) 50 | nn.init.constant_(self.W.weight, 0) 51 | nn.init.constant_(self.W.bias, 0) 52 | 53 | self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 54 | kernel_size=1, stride=1, padding=0) 55 | 56 | self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 57 | kernel_size=1, stride=1, padding=0) 58 | 59 | self.concat_project = nn.Sequential( 60 | nn.Conv2d(self.inter_channels * 2, 1, 1, 1, 0, bias=False), 61 | nn.ReLU() 62 | ) 63 | 64 | if sub_sample: 65 | self.g = nn.Sequential(self.g, max_pool_layer) 66 | self.phi = nn.Sequential(self.phi, max_pool_layer) 67 | 68 | def forward(self, x): 69 | ''' 70 | :param x: (b, c, t, h, w) 71 | :return: 72 | ''' 73 | 74 | batch_size = x.size(0) 75 | 76 | g_x = self.g(x).view(batch_size, self.inter_channels, -1) 77 | g_x = g_x.permute(0, 2, 1) 78 | 79 | # (b, c, N, 1) 80 | theta_x = self.theta(x).view(batch_size, self.inter_channels, -1, 1) 81 | # (b, c, 1, N) 82 | phi_x = self.phi(x).view(batch_size, self.inter_channels, 1, -1) 83 | 84 | h = theta_x.size(2) 85 | w = phi_x.size(3) 86 | theta_x = theta_x.repeat(1, 1, 1, w) 87 | phi_x = phi_x.repeat(1, 1, h, 1) 88 | 89 | concat_feature = torch.cat([theta_x, phi_x], dim=1) 90 | f = self.concat_project(concat_feature) 91 | b, _, h, w = f.size() 92 | f = f.view(b, h, w) 93 | 94 | N = f.size(-1) 95 | f_div_C = f / N 96 | 97 | y = torch.matmul(f_div_C, g_x) 98 | y = y.permute(0, 2, 1).contiguous() 99 | y = y.view(batch_size, self.inter_channels, *x.size()[2:]) 100 | W_y = self.W(y) 101 | z = W_y + x 102 | 103 | return z 104 | 105 | 106 | class NONLocalBlock1D(_NonLocalBlockND): 107 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 108 | super(NONLocalBlock1D, self).__init__(in_channels, 109 | inter_channels=inter_channels, 110 | dimension=1, sub_sample=sub_sample, 111 | bn_layer=bn_layer) 112 | 113 | 114 | class NONLocalBlock2D(_NonLocalBlockND): 115 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 116 | super(NONLocalBlock2D, self).__init__(in_channels, 117 | inter_channels=inter_channels, 118 | dimension=2, sub_sample=sub_sample, 119 | bn_layer=bn_layer) 120 | 121 | 122 | class NONLocalBlock3D(_NonLocalBlockND): 123 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 124 | super(NONLocalBlock3D, self).__init__(in_channels, 125 | inter_channels=inter_channels, 126 | dimension=3, sub_sample=sub_sample, 127 | bn_layer=bn_layer) 128 | 129 | 130 | if __name__ == '__main__': 131 | import torch 132 | 133 | for (sub_sample, bn_layer) in [(True, True), (False, False), (True, False), (False, True)]: 134 | img = torch.zeros(2, 3, 20) 135 | net = NONLocalBlock1D(3, sub_sample=sub_sample, bn_layer=bn_layer) 136 | out = net(img) 137 | print(out.size()) 138 | 139 | img = torch.zeros(2, 3, 20, 20) 140 | net = NONLocalBlock2D(3, sub_sample=sub_sample, bn_layer=bn_layer) 141 | out = net(img) 142 | print(out.size()) 143 | 144 | img = torch.randn(2, 3, 8, 20, 20) 145 | net = NONLocalBlock3D(3, sub_sample=sub_sample, bn_layer=bn_layer) 146 | out = net(img) 147 | print(out.size()) 148 | -------------------------------------------------------------------------------- /Non-Local_pytorch_0.4.1_to_1.1.0/lib/non_local_dot_product.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.nn import functional as F 4 | 5 | 6 | class _NonLocalBlockND(nn.Module): 7 | def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True): 8 | super(_NonLocalBlockND, self).__init__() 9 | 10 | assert dimension in [1, 2, 3] 11 | 12 | self.dimension = dimension 13 | self.sub_sample = sub_sample 14 | 15 | self.in_channels = in_channels 16 | self.inter_channels = inter_channels 17 | 18 | if self.inter_channels is None: 19 | self.inter_channels = in_channels // 2 20 | if self.inter_channels == 0: 21 | self.inter_channels = 1 22 | 23 | if dimension == 3: 24 | conv_nd = nn.Conv3d 25 | max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2)) 26 | bn = nn.BatchNorm3d 27 | elif dimension == 2: 28 | conv_nd = nn.Conv2d 29 | max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2)) 30 | bn = nn.BatchNorm2d 31 | else: 32 | conv_nd = nn.Conv1d 33 | max_pool_layer = nn.MaxPool1d(kernel_size=(2)) 34 | bn = nn.BatchNorm1d 35 | 36 | self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 37 | kernel_size=1, stride=1, padding=0) 38 | 39 | if bn_layer: 40 | self.W = nn.Sequential( 41 | conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 42 | kernel_size=1, stride=1, padding=0), 43 | bn(self.in_channels) 44 | ) 45 | nn.init.constant_(self.W[1].weight, 0) 46 | nn.init.constant_(self.W[1].bias, 0) 47 | else: 48 | self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 49 | kernel_size=1, stride=1, padding=0) 50 | nn.init.constant_(self.W.weight, 0) 51 | nn.init.constant_(self.W.bias, 0) 52 | 53 | self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 54 | kernel_size=1, stride=1, padding=0) 55 | 56 | self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 57 | kernel_size=1, stride=1, padding=0) 58 | 59 | if sub_sample: 60 | self.g = nn.Sequential(self.g, max_pool_layer) 61 | self.phi = nn.Sequential(self.phi, max_pool_layer) 62 | 63 | def forward(self, x): 64 | ''' 65 | :param x: (b, c, t, h, w) 66 | :return: 67 | ''' 68 | 69 | batch_size = x.size(0) 70 | 71 | g_x = self.g(x).view(batch_size, self.inter_channels, -1) 72 | g_x = g_x.permute(0, 2, 1) 73 | 74 | theta_x = self.theta(x).view(batch_size, self.inter_channels, -1) 75 | theta_x = theta_x.permute(0, 2, 1) 76 | phi_x = self.phi(x).view(batch_size, self.inter_channels, -1) 77 | f = torch.matmul(theta_x, phi_x) 78 | N = f.size(-1) 79 | f_div_C = f / N 80 | 81 | y = torch.matmul(f_div_C, g_x) 82 | y = y.permute(0, 2, 1).contiguous() 83 | y = y.view(batch_size, self.inter_channels, *x.size()[2:]) 84 | W_y = self.W(y) 85 | z = W_y + x 86 | 87 | return z 88 | 89 | 90 | class NONLocalBlock1D(_NonLocalBlockND): 91 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 92 | super(NONLocalBlock1D, self).__init__(in_channels, 93 | inter_channels=inter_channels, 94 | dimension=1, sub_sample=sub_sample, 95 | bn_layer=bn_layer) 96 | 97 | 98 | class NONLocalBlock2D(_NonLocalBlockND): 99 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 100 | super(NONLocalBlock2D, self).__init__(in_channels, 101 | inter_channels=inter_channels, 102 | dimension=2, sub_sample=sub_sample, 103 | bn_layer=bn_layer) 104 | 105 | 106 | class NONLocalBlock3D(_NonLocalBlockND): 107 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 108 | super(NONLocalBlock3D, self).__init__(in_channels, 109 | inter_channels=inter_channels, 110 | dimension=3, sub_sample=sub_sample, 111 | bn_layer=bn_layer) 112 | 113 | 114 | if __name__ == '__main__': 115 | import torch 116 | 117 | for (sub_sample, bn_layer) in [(True, True), (False, False), (True, False), (False, True)]: 118 | img = torch.zeros(2, 3, 20) 119 | net = NONLocalBlock1D(3, sub_sample=sub_sample, bn_layer=bn_layer) 120 | out = net(img) 121 | print(out.size()) 122 | 123 | img = torch.zeros(2, 3, 20, 20) 124 | net = NONLocalBlock2D(3, sub_sample=sub_sample, bn_layer=bn_layer) 125 | out = net(img) 126 | print(out.size()) 127 | 128 | img = torch.randn(2, 3, 8, 20, 20) 129 | net = NONLocalBlock3D(3, sub_sample=sub_sample, bn_layer=bn_layer) 130 | out = net(img) 131 | print(out.size()) 132 | 133 | 134 | 135 | -------------------------------------------------------------------------------- /Non-Local_pytorch_0.4.1_to_1.1.0/lib/non_local_embedded_gaussian.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.nn import functional as F 4 | 5 | 6 | class _NonLocalBlockND(nn.Module): 7 | def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True): 8 | super(_NonLocalBlockND, self).__init__() 9 | 10 | assert dimension in [1, 2, 3] 11 | 12 | self.dimension = dimension 13 | self.sub_sample = sub_sample 14 | 15 | self.in_channels = in_channels 16 | self.inter_channels = inter_channels 17 | 18 | if self.inter_channels is None: 19 | self.inter_channels = in_channels // 2 20 | if self.inter_channels == 0: 21 | self.inter_channels = 1 22 | 23 | if dimension == 3: 24 | conv_nd = nn.Conv3d 25 | max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2)) 26 | bn = nn.BatchNorm3d 27 | elif dimension == 2: 28 | conv_nd = nn.Conv2d 29 | max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2)) 30 | bn = nn.BatchNorm2d 31 | else: 32 | conv_nd = nn.Conv1d 33 | max_pool_layer = nn.MaxPool1d(kernel_size=(2)) 34 | bn = nn.BatchNorm1d 35 | 36 | self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 37 | kernel_size=1, stride=1, padding=0) 38 | 39 | if bn_layer: 40 | self.W = nn.Sequential( 41 | conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 42 | kernel_size=1, stride=1, padding=0), 43 | bn(self.in_channels) 44 | ) 45 | nn.init.constant_(self.W[1].weight, 0) 46 | nn.init.constant_(self.W[1].bias, 0) 47 | else: 48 | self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 49 | kernel_size=1, stride=1, padding=0) 50 | nn.init.constant_(self.W.weight, 0) 51 | nn.init.constant_(self.W.bias, 0) 52 | 53 | self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 54 | kernel_size=1, stride=1, padding=0) 55 | self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 56 | kernel_size=1, stride=1, padding=0) 57 | 58 | if sub_sample: 59 | self.g = nn.Sequential(self.g, max_pool_layer) 60 | self.phi = nn.Sequential(self.phi, max_pool_layer) 61 | 62 | def forward(self, x): 63 | ''' 64 | :param x: (b, c, t, h, w) 65 | :return: 66 | ''' 67 | 68 | batch_size = x.size(0) 69 | 70 | g_x = self.g(x).view(batch_size, self.inter_channels, -1) 71 | g_x = g_x.permute(0, 2, 1) 72 | 73 | theta_x = self.theta(x).view(batch_size, self.inter_channels, -1) 74 | theta_x = theta_x.permute(0, 2, 1) 75 | phi_x = self.phi(x).view(batch_size, self.inter_channels, -1) 76 | f = torch.matmul(theta_x, phi_x) 77 | f_div_C = F.softmax(f, dim=-1) 78 | 79 | y = torch.matmul(f_div_C, g_x) 80 | y = y.permute(0, 2, 1).contiguous() 81 | y = y.view(batch_size, self.inter_channels, *x.size()[2:]) 82 | W_y = self.W(y) 83 | z = W_y + x 84 | 85 | return z 86 | 87 | 88 | class NONLocalBlock1D(_NonLocalBlockND): 89 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 90 | super(NONLocalBlock1D, self).__init__(in_channels, 91 | inter_channels=inter_channels, 92 | dimension=1, sub_sample=sub_sample, 93 | bn_layer=bn_layer) 94 | 95 | 96 | class NONLocalBlock2D(_NonLocalBlockND): 97 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 98 | super(NONLocalBlock2D, self).__init__(in_channels, 99 | inter_channels=inter_channels, 100 | dimension=2, sub_sample=sub_sample, 101 | bn_layer=bn_layer) 102 | 103 | 104 | class NONLocalBlock3D(_NonLocalBlockND): 105 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 106 | super(NONLocalBlock3D, self).__init__(in_channels, 107 | inter_channels=inter_channels, 108 | dimension=3, sub_sample=sub_sample, 109 | bn_layer=bn_layer) 110 | 111 | 112 | if __name__ == '__main__': 113 | import torch 114 | 115 | for (sub_sample, bn_layer) in [(True, True), (False, False), (True, False), (False, True)]: 116 | img = torch.zeros(2, 3, 20) 117 | net = NONLocalBlock1D(3, sub_sample=sub_sample, bn_layer=bn_layer) 118 | out = net(img) 119 | print(out.size()) 120 | 121 | img = torch.zeros(2, 3, 20, 20) 122 | net = NONLocalBlock2D(3, sub_sample=sub_sample, bn_layer=bn_layer) 123 | out = net(img) 124 | print(out.size()) 125 | 126 | img = torch.randn(2, 3, 8, 20, 20) 127 | net = NONLocalBlock3D(3, sub_sample=sub_sample, bn_layer=bn_layer) 128 | out = net(img) 129 | print(out.size()) 130 | 131 | 132 | -------------------------------------------------------------------------------- /Non-Local_pytorch_0.4.1_to_1.1.0/lib/non_local_gaussian.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.nn import functional as F 4 | 5 | 6 | class _NonLocalBlockND(nn.Module): 7 | def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True): 8 | super(_NonLocalBlockND, self).__init__() 9 | 10 | assert dimension in [1, 2, 3] 11 | 12 | self.dimension = dimension 13 | self.sub_sample = sub_sample 14 | 15 | self.in_channels = in_channels 16 | self.inter_channels = inter_channels 17 | 18 | if self.inter_channels is None: 19 | self.inter_channels = in_channels // 2 20 | if self.inter_channels == 0: 21 | self.inter_channels = 1 22 | 23 | if dimension == 3: 24 | conv_nd = nn.Conv3d 25 | max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2)) 26 | bn = nn.BatchNorm3d 27 | elif dimension == 2: 28 | conv_nd = nn.Conv2d 29 | max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2)) 30 | bn = nn.BatchNorm2d 31 | else: 32 | conv_nd = nn.Conv1d 33 | max_pool_layer = nn.MaxPool1d(kernel_size=(2)) 34 | bn = nn.BatchNorm1d 35 | 36 | self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 37 | kernel_size=1, stride=1, padding=0) 38 | 39 | if bn_layer: 40 | self.W = nn.Sequential( 41 | conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 42 | kernel_size=1, stride=1, padding=0), 43 | bn(self.in_channels) 44 | ) 45 | nn.init.constant_(self.W[1].weight, 0) 46 | nn.init.constant_(self.W[1].bias, 0) 47 | else: 48 | self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 49 | kernel_size=1, stride=1, padding=0) 50 | nn.init.constant_(self.W.weight, 0) 51 | nn.init.constant_(self.W.bias, 0) 52 | 53 | if sub_sample: 54 | self.g = nn.Sequential(self.g, max_pool_layer) 55 | self.phi = max_pool_layer 56 | 57 | def forward(self, x): 58 | ''' 59 | :param x: (b, c, t, h, w) 60 | :return: 61 | ''' 62 | 63 | batch_size = x.size(0) 64 | 65 | g_x = self.g(x).view(batch_size, self.inter_channels, -1) 66 | 67 | g_x = g_x.permute(0, 2, 1) 68 | 69 | theta_x = x.view(batch_size, self.in_channels, -1) 70 | theta_x = theta_x.permute(0, 2, 1) 71 | 72 | if self.sub_sample: 73 | phi_x = self.phi(x).view(batch_size, self.in_channels, -1) 74 | else: 75 | phi_x = x.view(batch_size, self.in_channels, -1) 76 | 77 | f = torch.matmul(theta_x, phi_x) 78 | f_div_C = F.softmax(f, dim=-1) 79 | 80 | y = torch.matmul(f_div_C, g_x) 81 | y = y.permute(0, 2, 1).contiguous() 82 | y = y.view(batch_size, self.inter_channels, *x.size()[2:]) 83 | W_y = self.W(y) 84 | z = W_y + x 85 | 86 | return z 87 | 88 | 89 | class NONLocalBlock1D(_NonLocalBlockND): 90 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 91 | super(NONLocalBlock1D, self).__init__(in_channels, 92 | inter_channels=inter_channels, 93 | dimension=1, sub_sample=sub_sample, 94 | bn_layer=bn_layer) 95 | 96 | 97 | class NONLocalBlock2D(_NonLocalBlockND): 98 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 99 | super(NONLocalBlock2D, self).__init__(in_channels, 100 | inter_channels=inter_channels, 101 | dimension=2, sub_sample=sub_sample, 102 | bn_layer=bn_layer) 103 | 104 | 105 | class NONLocalBlock3D(_NonLocalBlockND): 106 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 107 | super(NONLocalBlock3D, self).__init__(in_channels, 108 | inter_channels=inter_channels, 109 | dimension=3, sub_sample=sub_sample, 110 | bn_layer=bn_layer) 111 | 112 | 113 | if __name__ == '__main__': 114 | import torch 115 | 116 | for (sub_sample, bn_layer) in [(True, True), (False, False), (True, False), (False, True)]: 117 | img = torch.zeros(2, 3, 20) 118 | net = NONLocalBlock1D(3, sub_sample=sub_sample, bn_layer=bn_layer) 119 | out = net(img) 120 | print(out.size()) 121 | 122 | img = torch.zeros(2, 3, 20, 20) 123 | net = NONLocalBlock2D(3, sub_sample=sub_sample, bn_layer=bn_layer) 124 | out = net(img) 125 | print(out.size()) 126 | 127 | img = torch.randn(2, 3, 8, 20, 20) 128 | net = NONLocalBlock3D(3, sub_sample=sub_sample, bn_layer=bn_layer) 129 | out = net(img) 130 | print(out.size()) 131 | 132 | 133 | 134 | 135 | 136 | 137 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Non-local_pytorch 2 | - Implementation of [**Non-local Neural Block**](https://arxiv.org/abs/1711.07971). 3 | 4 | ## Statement 5 | - You can find different kinds of non-local block in **lib/**. 6 | 7 | - You can **visualize** the Non_local Attention Map by following the **Running Steps** shown below. 8 | 9 | - The code is tested on MNIST dataset. You can select the type of non-local block in **lib/network.py**. 10 | 11 | - If there is something wrong in my code, please contact me, thanks! 12 | 13 | ## Environment 14 | - python 3.7.7 (>=3.8) 15 | - pytorch 1.4.0 (>=1.2.0; 2.0.0 works too) 16 | - opencv 4.2.0.34 (others work too) 17 | 18 | ## Visualization 19 | 1. In the **first** Non-local Layer. 20 | 21 | ![](nl_map_vis/nl_map_1/37.png) ![](nl_map_vis/nl_map_1/44.png) ![](nl_map_vis/nl_map_1/46.png) ![](nl_map_vis/nl_map_1/110.png) ![](nl_map_vis/nl_map_1/161.png) 22 | 23 | 2. In the **second** Non-local Layer. 24 | 25 | ![](nl_map_vis/nl_map_2/1.png) ![](nl_map_vis/nl_map_2/8.png) ![](nl_map_vis/nl_map_2/10.png) ![](nl_map_vis/nl_map_2/18.png) ![](nl_map_vis/nl_map_2/38.png) 26 | 27 | 28 | ## Running Steps 29 | 1. Select the type of non-local block in **lib/network.py**. 30 | ``` 31 | from lib.non_local_concatenation import NONLocalBlock2D 32 | from lib.non_local_gaussian import NONLocalBlock2D 33 | from lib.non_local_embedded_gaussian import NONLocalBlock2D 34 | from lib.non_local_dot_product import NONLocalBlock2D 35 | ``` 36 | 37 | 2. Run **demo_MNIST_train.py** with one GPU or multi GPU to train the Network. Then the weights will be save in **weights/**. 38 | ``` 39 | CUDA_VISIBLE_DEVICES=0,1 python demo_MNIST_train.py 40 | 41 | # Or train with Automatic Mixed Precision based on pytorch 1.6.0 42 | CUDA_VISIBLE_DEVICES=0 python demo_MNIST_AMP_train_with_single_gpu.py 43 | ``` 44 | 45 | 3. Run **nl_map_save.py** to save NL_MAP of one test sample in **nl_map_vis**. 46 | ``` 47 | CUDA_VISIBLE_DEVICES=0,1 python nl_map_save.py 48 | ``` 49 | 50 | 4. Come into **nl_map_vis/** and run **nl_map_vis.py** to visualize the NL_MAP. (tips: if the Non-local type you select is **non_local_concatenation** or **non_local_dot_product** (without Softmax operation), you may need to normalize NL_MAP in the visualize code) 51 | ``` 52 | python nl_map_save.py 53 | ``` 54 | 55 | ## Update Records 56 | 1. Figure out how to implement the **concatenation** type, and add the code to **lib/**. 57 | 58 | 2. Fix the bug in **lib/non_local.py** (old version) when using multi-gpu. Someone shares the 59 | reason with me, and you can find it in [here](https://github.com/pytorch/pytorch/issues/8637). 60 | 61 | 3. Fix the error of 3D pooling in **lib/non_local.py** (old version). Appreciate 62 | [**protein27**](https://github.com/AlexHex7/Non-local_pytorch/issues/17) for pointing it out. 63 | 64 | 4. For convenience, I split the **lib/non_local.py** into four python files, and move the 65 | old versions (**lib/non_loca.py** and **lib/non_local_simple_version.py**) into 66 | **lib/backup/**. 67 | 68 | 5. Modify the code to support pytorch 0.4.1, and move the code supporting pytorch 0.3.1 \ 69 | to **Non-Local_pytorch_0.3.1/**. 70 | 71 | 6. Test the code with pytorch 1.1.0 and it works. 72 | 73 | 7. Move the code supporting pytorch 0.4.1 and 1.1.0 to **Non-Local_pytorch_0.4.1_to_1.1.0/** (In fact, I think it can also support pytorch 1.2.0). 74 | 75 | 8. In order to visualize NL_MAP, some code have been slightly modified. The code **nl_map_save.py** is added to save NL_MAP (two Non-local Layer) of one test sample. The code **Non-local_pytorch/nl_map_vis.py** is added to visualize NL_MAP. Besieds, the code is support pytorch 1.2.0. 76 | 77 | 9. The code also works well in **pytorch 1.4.0**. 78 | 79 | 10. The code also works well in **pytorch 1.6.0**. Add **demo_MNIST_AMP_train_with_single_gpu.py** with Automatic Mixed Precision Training (FP16), supported by **pytorch 1.6.0**. It can reduce GPU memory during training. What's more, if you use GPU 2080Ti (tensor cores), training speed can be increased. More details (such as how to train with multiple GPUs) can be found in [here](https://pytorch.org/docs/stable/notes/amp_examples.html#typical-mixed-precision-training) 80 | 81 | 11. Verify that the code works well in **pytorch 1.7.0**. 82 | 83 | 12. Verify that the code works well in **pytorch 1.8.1**. 84 | 85 | 13. Verify that the code works well in **pytorch 1.9.0**. 86 | 87 | 14. Verify that the code works well in **pytorch 1.10.1**. 88 | 89 | 15. Verify that the code works well in **pytorch 1.11.0**. 90 | 91 | 16. Verify that the code works well in **pytorch 1.12.0**. 92 | 93 | 17. Remove redundant the code `net.train()` in training code files. 94 | 95 | 18. Verify that the code works well in **pytorch 1.13.0 and 2.0.0**. 96 | 97 | ## Todo 98 | - Experiments on Charades dataset. 99 | - Experiments on COCO dataset. 100 | 101 | 102 | ## Related Repositories 103 | 1. [**Non-local ResNet-50 TSM**](https://github.com/MIT-HAN-LAB/temporal-shift-module) 104 | ([**Paper**](https://arxiv.org/abs/1811.08383)) on Kinetics dataset. They report that their model achieves a good performance 105 | of **75.6% on Kinetics**, which is even higher than Non-local ResNet-50 I3D 106 | ([**Here**](https://github.com/AlexHex7/Non-local_pytorch/issues/23)). 107 | -------------------------------------------------------------------------------- /demo_MNIST_AMP_train_with_single_gpu.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.utils.data as Data 3 | import torchvision 4 | from lib.network import Network 5 | from torch import nn 6 | from torch.cuda import amp 7 | import time 8 | 9 | 10 | train_data = torchvision.datasets.MNIST(root='./mnist', train=True, 11 | transform=torchvision.transforms.ToTensor(), 12 | download=True) 13 | test_data = torchvision.datasets.MNIST(root='./mnist/', 14 | transform=torchvision.transforms.ToTensor(), 15 | train=False) 16 | 17 | train_loader = Data.DataLoader(dataset=train_data, batch_size=128 * 50, shuffle=True) 18 | test_loader = Data.DataLoader(dataset=test_data, batch_size=128 * 50, shuffle=False) 19 | 20 | train_batch_num = len(train_loader) 21 | test_batch_num = len(test_loader) 22 | 23 | net = Network() 24 | if torch.cuda.is_available(): 25 | # net = nn.DataParallel(net) 26 | net.cuda() 27 | 28 | # +++++++++++++++++++++++++++++++ 29 | scaler = amp.GradScaler() 30 | # +++++++++++++++++++++++++++++++ 31 | 32 | opt = torch.optim.Adam(net.parameters(), lr=0.001) 33 | loss_func = nn.CrossEntropyLoss() 34 | 35 | for epoch_index in range(10): 36 | st = time.time() 37 | 38 | torch.set_grad_enabled(True) 39 | net.train() 40 | for train_batch_index, (img_batch, label_batch) in enumerate(train_loader): 41 | if torch.cuda.is_available(): 42 | img_batch = img_batch.cuda() 43 | label_batch = label_batch.cuda() 44 | 45 | # ++++++++++++++++++++++++++++++++++++++++++++++ 46 | # predict = net(img_batch) 47 | # loss = loss_func(predict, label_batch) 48 | with amp.autocast(): 49 | predict = net(img_batch) 50 | loss = loss_func(predict, label_batch) 51 | # ++++++++++++++++++++++++++++++++++++++++++++++ 52 | 53 | net.zero_grad() 54 | # ++++++++++++++++++++++++++++++++++++++++++++++ 55 | # loss.backward() 56 | # opt.step() 57 | scaler.scale(loss).backward() 58 | scaler.step(opt) 59 | scaler.update() 60 | # ++++++++++++++++++++++++++++++++++++++++++++++ 61 | 62 | print('(LR:%f) Time of a epoch:%.4fs' % (opt.param_groups[0]['lr'], time.time()-st)) 63 | 64 | torch.set_grad_enabled(False) 65 | net.eval() 66 | total_loss = [] 67 | total_acc = 0 68 | total_sample = 0 69 | 70 | for test_batch_index, (img_batch, label_batch) in enumerate(test_loader): 71 | if torch.cuda.is_available(): 72 | img_batch = img_batch.cuda() 73 | label_batch = label_batch.cuda() 74 | 75 | predict = net(img_batch) 76 | loss = loss_func(predict, label_batch) 77 | 78 | predict = predict.argmax(dim=1) 79 | acc = (predict == label_batch).sum() 80 | 81 | total_loss.append(loss) 82 | total_acc += acc 83 | total_sample += img_batch.size(0) 84 | 85 | mean_acc = total_acc.item() * 1.0 / total_sample 86 | mean_loss = sum(total_loss) / total_loss.__len__() 87 | 88 | print('[Test] epoch[%d/%d] acc:%.4f%% loss:%.4f\n' 89 | % (epoch_index, 10, mean_acc * 100, mean_loss.item())) 90 | 91 | # weight_path = 'weights/net.pth' 92 | # print('Save Net weights to', weight_path) 93 | # net.cpu() 94 | # torch.save(net.state_dict(), weight_path) 95 | -------------------------------------------------------------------------------- /demo_MNIST_train.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.utils.data as Data 3 | import torchvision 4 | from lib.network import Network 5 | from torch import nn 6 | import time 7 | 8 | 9 | train_data = torchvision.datasets.MNIST(root='./mnist', train=True, 10 | transform=torchvision.transforms.ToTensor(), 11 | download=True) 12 | test_data = torchvision.datasets.MNIST(root='./mnist/', 13 | transform=torchvision.transforms.ToTensor(), 14 | train=False) 15 | 16 | train_loader = Data.DataLoader(dataset=train_data, batch_size=128, shuffle=True) 17 | test_loader = Data.DataLoader(dataset=test_data, batch_size=128, shuffle=False) 18 | 19 | train_batch_num = len(train_loader) 20 | test_batch_num = len(test_loader) 21 | 22 | net = Network() 23 | if torch.cuda.is_available(): 24 | net = nn.DataParallel(net) 25 | net.cuda() 26 | 27 | opt = torch.optim.Adam(net.parameters(), lr=0.001) 28 | loss_func = nn.CrossEntropyLoss() 29 | 30 | for epoch_index in range(10): 31 | st = time.time() 32 | 33 | torch.set_grad_enabled(True) 34 | net.train() 35 | for train_batch_index, (img_batch, label_batch) in enumerate(train_loader): 36 | if torch.cuda.is_available(): 37 | img_batch = img_batch.cuda() 38 | label_batch = label_batch.cuda() 39 | 40 | predict = net(img_batch) 41 | loss = loss_func(predict, label_batch) 42 | 43 | net.zero_grad() 44 | loss.backward() 45 | opt.step() 46 | 47 | print('(LR:%f) Time of a epoch:%.4fs' % (opt.param_groups[0]['lr'], time.time()-st)) 48 | 49 | torch.set_grad_enabled(False) 50 | net.eval() 51 | total_loss = [] 52 | total_acc = 0 53 | total_sample = 0 54 | 55 | for test_batch_index, (img_batch, label_batch) in enumerate(test_loader): 56 | if torch.cuda.is_available(): 57 | img_batch = img_batch.cuda() 58 | label_batch = label_batch.cuda() 59 | 60 | predict = net(img_batch) 61 | loss = loss_func(predict, label_batch) 62 | 63 | predict = predict.argmax(dim=1) 64 | acc = (predict == label_batch).sum() 65 | 66 | total_loss.append(loss) 67 | total_acc += acc 68 | total_sample += img_batch.size(0) 69 | 70 | mean_acc = total_acc.item() * 1.0 / total_sample 71 | mean_loss = sum(total_loss) / total_loss.__len__() 72 | 73 | print('[Test] epoch[%d/%d] acc:%.4f%% loss:%.4f\n' 74 | % (epoch_index, 10, mean_acc * 100, mean_loss.item())) 75 | 76 | # weight_path = 'weights/net.pth' 77 | # print('Save Net weights to', weight_path) 78 | # net.cpu() 79 | # torch.save(net.state_dict(), weight_path) 80 | -------------------------------------------------------------------------------- /lib/network.py: -------------------------------------------------------------------------------- 1 | from torch import nn 2 | # from lib.non_local_concatenation import NONLocalBlock2D 3 | # from lib.non_local_gaussian import NONLocalBlock2D 4 | from lib.non_local_embedded_gaussian import NONLocalBlock2D 5 | # from lib.non_local_dot_product import NONLocalBlock2D 6 | 7 | 8 | class Network(nn.Module): 9 | def __init__(self): 10 | super(Network, self).__init__() 11 | 12 | self.conv_1 = nn.Sequential( 13 | nn.Conv2d(in_channels=1, out_channels=32, kernel_size=3, stride=1, padding=1), 14 | nn.BatchNorm2d(32), 15 | nn.ReLU(), 16 | nn.MaxPool2d(2), 17 | ) 18 | 19 | self.nl_1 = NONLocalBlock2D(in_channels=32) 20 | self.conv_2 = nn.Sequential( 21 | nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1), 22 | nn.BatchNorm2d(64), 23 | nn.ReLU(), 24 | nn.MaxPool2d(2), 25 | ) 26 | 27 | self.nl_2 = NONLocalBlock2D(in_channels=64) 28 | self.conv_3 = nn.Sequential( 29 | nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1), 30 | nn.BatchNorm2d(128), 31 | nn.ReLU(), 32 | nn.MaxPool2d(2), 33 | ) 34 | 35 | self.fc = nn.Sequential( 36 | nn.Linear(in_features=128*3*3, out_features=256), 37 | nn.ReLU(), 38 | nn.Dropout(0.5), 39 | 40 | nn.Linear(in_features=256, out_features=10) 41 | ) 42 | 43 | def forward(self, x): 44 | batch_size = x.size(0) 45 | 46 | feature_1 = self.conv_1(x) 47 | nl_feature_1 = self.nl_1(feature_1) 48 | 49 | feature_2 = self.conv_2(nl_feature_1) 50 | nl_feature_2 = self.nl_2(feature_2) 51 | 52 | output = self.conv_3(nl_feature_2).view(batch_size, -1) 53 | output = self.fc(output) 54 | 55 | return output 56 | 57 | def forward_with_nl_map(self, x): 58 | batch_size = x.size(0) 59 | 60 | feature_1 = self.conv_1(x) 61 | nl_feature_1, nl_map_1 = self.nl_1(feature_1, return_nl_map=True) 62 | 63 | feature_2 = self.conv_2(nl_feature_1) 64 | nl_feature_2, nl_map_2 = self.nl_2(feature_2, return_nl_map=True) 65 | 66 | output = self.conv_3(nl_feature_2).view(batch_size, -1) 67 | output = self.fc(output) 68 | 69 | return output, [nl_map_1, nl_map_2] 70 | 71 | 72 | if __name__ == '__main__': 73 | import torch 74 | 75 | img = torch.randn(3, 1, 28, 28) 76 | net = Network() 77 | out = net(img) 78 | print(out.size()) 79 | 80 | -------------------------------------------------------------------------------- /lib/non_local_concatenation.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.nn import functional as F 4 | 5 | 6 | class _NonLocalBlockND(nn.Module): 7 | def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True): 8 | super(_NonLocalBlockND, self).__init__() 9 | 10 | assert dimension in [1, 2, 3] 11 | 12 | self.dimension = dimension 13 | self.sub_sample = sub_sample 14 | 15 | self.in_channels = in_channels 16 | self.inter_channels = inter_channels 17 | 18 | if self.inter_channels is None: 19 | self.inter_channels = in_channels // 2 20 | if self.inter_channels == 0: 21 | self.inter_channels = 1 22 | 23 | if dimension == 3: 24 | conv_nd = nn.Conv3d 25 | max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2)) 26 | bn = nn.BatchNorm3d 27 | elif dimension == 2: 28 | conv_nd = nn.Conv2d 29 | max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2)) 30 | bn = nn.BatchNorm2d 31 | else: 32 | conv_nd = nn.Conv1d 33 | max_pool_layer = nn.MaxPool1d(kernel_size=(2)) 34 | bn = nn.BatchNorm1d 35 | 36 | self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 37 | kernel_size=1, stride=1, padding=0) 38 | 39 | if bn_layer: 40 | self.W = nn.Sequential( 41 | conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 42 | kernel_size=1, stride=1, padding=0), 43 | bn(self.in_channels) 44 | ) 45 | nn.init.constant_(self.W[1].weight, 0) 46 | nn.init.constant_(self.W[1].bias, 0) 47 | else: 48 | self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 49 | kernel_size=1, stride=1, padding=0) 50 | nn.init.constant_(self.W.weight, 0) 51 | nn.init.constant_(self.W.bias, 0) 52 | 53 | self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 54 | kernel_size=1, stride=1, padding=0) 55 | 56 | self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 57 | kernel_size=1, stride=1, padding=0) 58 | 59 | self.concat_project = nn.Sequential( 60 | nn.Conv2d(self.inter_channels * 2, 1, 1, 1, 0, bias=False), 61 | nn.ReLU() 62 | ) 63 | 64 | if sub_sample: 65 | self.g = nn.Sequential(self.g, max_pool_layer) 66 | self.phi = nn.Sequential(self.phi, max_pool_layer) 67 | 68 | def forward(self, x, return_nl_map=False): 69 | ''' 70 | :param x: (b, c, t, h, w) 71 | :param return_nl_map: if True return z, nl_map, else only return z. 72 | :return: 73 | ''' 74 | 75 | batch_size = x.size(0) 76 | 77 | g_x = self.g(x).view(batch_size, self.inter_channels, -1) 78 | g_x = g_x.permute(0, 2, 1) 79 | 80 | # (b, c, N, 1) 81 | theta_x = self.theta(x).view(batch_size, self.inter_channels, -1, 1) 82 | # (b, c, 1, N) 83 | phi_x = self.phi(x).view(batch_size, self.inter_channels, 1, -1) 84 | 85 | h = theta_x.size(2) 86 | w = phi_x.size(3) 87 | theta_x = theta_x.repeat(1, 1, 1, w) 88 | phi_x = phi_x.repeat(1, 1, h, 1) 89 | 90 | concat_feature = torch.cat([theta_x, phi_x], dim=1) 91 | f = self.concat_project(concat_feature) 92 | b, _, h, w = f.size() 93 | f = f.view(b, h, w) 94 | 95 | N = f.size(-1) 96 | f_div_C = f / N 97 | 98 | y = torch.matmul(f_div_C, g_x) 99 | y = y.permute(0, 2, 1).contiguous() 100 | y = y.view(batch_size, self.inter_channels, *x.size()[2:]) 101 | W_y = self.W(y) 102 | z = W_y + x 103 | 104 | if return_nl_map: 105 | return z, f_div_C 106 | return z 107 | 108 | 109 | class NONLocalBlock1D(_NonLocalBlockND): 110 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 111 | super(NONLocalBlock1D, self).__init__(in_channels, 112 | inter_channels=inter_channels, 113 | dimension=1, sub_sample=sub_sample, 114 | bn_layer=bn_layer) 115 | 116 | 117 | class NONLocalBlock2D(_NonLocalBlockND): 118 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 119 | super(NONLocalBlock2D, self).__init__(in_channels, 120 | inter_channels=inter_channels, 121 | dimension=2, sub_sample=sub_sample, 122 | bn_layer=bn_layer) 123 | 124 | 125 | class NONLocalBlock3D(_NonLocalBlockND): 126 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True,): 127 | super(NONLocalBlock3D, self).__init__(in_channels, 128 | inter_channels=inter_channels, 129 | dimension=3, sub_sample=sub_sample, 130 | bn_layer=bn_layer) 131 | 132 | 133 | if __name__ == '__main__': 134 | import torch 135 | 136 | for (sub_sample_, bn_layer_) in [(True, True), (False, False), (True, False), (False, True)]: 137 | img = torch.zeros(2, 3, 20) 138 | net = NONLocalBlock1D(3, sub_sample=sub_sample_, bn_layer=bn_layer_) 139 | out = net(img) 140 | print(out.size()) 141 | 142 | img = torch.zeros(2, 3, 20, 20) 143 | net = NONLocalBlock2D(3, sub_sample=sub_sample_, bn_layer=bn_layer_) 144 | out = net(img) 145 | print(out.size()) 146 | 147 | img = torch.randn(2, 3, 8, 20, 20) 148 | net = NONLocalBlock3D(3, sub_sample=sub_sample_, bn_layer=bn_layer_) 149 | out = net(img) 150 | print(out.size()) 151 | -------------------------------------------------------------------------------- /lib/non_local_dot_product.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.nn import functional as F 4 | 5 | 6 | class _NonLocalBlockND(nn.Module): 7 | def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True): 8 | super(_NonLocalBlockND, self).__init__() 9 | 10 | assert dimension in [1, 2, 3] 11 | 12 | self.dimension = dimension 13 | self.sub_sample = sub_sample 14 | 15 | self.in_channels = in_channels 16 | self.inter_channels = inter_channels 17 | 18 | if self.inter_channels is None: 19 | self.inter_channels = in_channels // 2 20 | if self.inter_channels == 0: 21 | self.inter_channels = 1 22 | 23 | if dimension == 3: 24 | conv_nd = nn.Conv3d 25 | max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2)) 26 | bn = nn.BatchNorm3d 27 | elif dimension == 2: 28 | conv_nd = nn.Conv2d 29 | max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2)) 30 | bn = nn.BatchNorm2d 31 | else: 32 | conv_nd = nn.Conv1d 33 | max_pool_layer = nn.MaxPool1d(kernel_size=(2)) 34 | bn = nn.BatchNorm1d 35 | 36 | self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 37 | kernel_size=1, stride=1, padding=0) 38 | 39 | if bn_layer: 40 | self.W = nn.Sequential( 41 | conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 42 | kernel_size=1, stride=1, padding=0), 43 | bn(self.in_channels) 44 | ) 45 | nn.init.constant_(self.W[1].weight, 0) 46 | nn.init.constant_(self.W[1].bias, 0) 47 | else: 48 | self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 49 | kernel_size=1, stride=1, padding=0) 50 | nn.init.constant_(self.W.weight, 0) 51 | nn.init.constant_(self.W.bias, 0) 52 | 53 | self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 54 | kernel_size=1, stride=1, padding=0) 55 | 56 | self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 57 | kernel_size=1, stride=1, padding=0) 58 | 59 | if sub_sample: 60 | self.g = nn.Sequential(self.g, max_pool_layer) 61 | self.phi = nn.Sequential(self.phi, max_pool_layer) 62 | 63 | def forward(self, x, return_nl_map=False): 64 | """ 65 | :param x: (b, c, t, h, w) 66 | :param return_nl_map: if True return z, nl_map, else only return z. 67 | :return: 68 | """ 69 | 70 | batch_size = x.size(0) 71 | 72 | g_x = self.g(x).view(batch_size, self.inter_channels, -1) 73 | g_x = g_x.permute(0, 2, 1) 74 | 75 | theta_x = self.theta(x).view(batch_size, self.inter_channels, -1) 76 | theta_x = theta_x.permute(0, 2, 1) 77 | phi_x = self.phi(x).view(batch_size, self.inter_channels, -1) 78 | f = torch.matmul(theta_x, phi_x) 79 | N = f.size(-1) 80 | f_div_C = f / N 81 | 82 | y = torch.matmul(f_div_C, g_x) 83 | y = y.permute(0, 2, 1).contiguous() 84 | y = y.view(batch_size, self.inter_channels, *x.size()[2:]) 85 | W_y = self.W(y) 86 | z = W_y + x 87 | 88 | if return_nl_map: 89 | return z, f_div_C 90 | return z 91 | 92 | 93 | class NONLocalBlock1D(_NonLocalBlockND): 94 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 95 | super(NONLocalBlock1D, self).__init__(in_channels, 96 | inter_channels=inter_channels, 97 | dimension=1, sub_sample=sub_sample, 98 | bn_layer=bn_layer) 99 | 100 | 101 | class NONLocalBlock2D(_NonLocalBlockND): 102 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 103 | super(NONLocalBlock2D, self).__init__(in_channels, 104 | inter_channels=inter_channels, 105 | dimension=2, sub_sample=sub_sample, 106 | bn_layer=bn_layer) 107 | 108 | 109 | class NONLocalBlock3D(_NonLocalBlockND): 110 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 111 | super(NONLocalBlock3D, self).__init__(in_channels, 112 | inter_channels=inter_channels, 113 | dimension=3, sub_sample=sub_sample, 114 | bn_layer=bn_layer) 115 | 116 | 117 | if __name__ == '__main__': 118 | import torch 119 | 120 | for (sub_sample_, bn_layer_) in [(True, True), (False, False), (True, False), (False, True)]: 121 | img = torch.zeros(2, 3, 20) 122 | net = NONLocalBlock1D(3, sub_sample=sub_sample_, bn_layer=bn_layer_) 123 | out = net(img) 124 | print(out.size()) 125 | 126 | img = torch.zeros(2, 3, 20, 20) 127 | net = NONLocalBlock2D(3, sub_sample=sub_sample_, bn_layer=bn_layer_) 128 | out = net(img) 129 | print(out.size()) 130 | 131 | img = torch.randn(2, 3, 8, 20, 20) 132 | net = NONLocalBlock3D(3, sub_sample=sub_sample_, bn_layer=bn_layer_) 133 | out = net(img) 134 | print(out.size()) 135 | 136 | 137 | 138 | -------------------------------------------------------------------------------- /lib/non_local_embedded_gaussian.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.nn import functional as F 4 | 5 | 6 | class _NonLocalBlockND(nn.Module): 7 | def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True): 8 | """ 9 | :param in_channels: 10 | :param inter_channels: 11 | :param dimension: 12 | :param sub_sample: 13 | :param bn_layer: 14 | """ 15 | 16 | super(_NonLocalBlockND, self).__init__() 17 | 18 | assert dimension in [1, 2, 3] 19 | 20 | self.dimension = dimension 21 | self.sub_sample = sub_sample 22 | 23 | self.in_channels = in_channels 24 | self.inter_channels = inter_channels 25 | 26 | if self.inter_channels is None: 27 | self.inter_channels = in_channels // 2 28 | if self.inter_channels == 0: 29 | self.inter_channels = 1 30 | 31 | if dimension == 3: 32 | conv_nd = nn.Conv3d 33 | max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2)) 34 | bn = nn.BatchNorm3d 35 | elif dimension == 2: 36 | conv_nd = nn.Conv2d 37 | max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2)) 38 | bn = nn.BatchNorm2d 39 | else: 40 | conv_nd = nn.Conv1d 41 | max_pool_layer = nn.MaxPool1d(kernel_size=(2)) 42 | bn = nn.BatchNorm1d 43 | 44 | self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 45 | kernel_size=1, stride=1, padding=0) 46 | 47 | if bn_layer: 48 | self.W = nn.Sequential( 49 | conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 50 | kernel_size=1, stride=1, padding=0), 51 | bn(self.in_channels) 52 | ) 53 | nn.init.constant_(self.W[1].weight, 0) 54 | nn.init.constant_(self.W[1].bias, 0) 55 | else: 56 | self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 57 | kernel_size=1, stride=1, padding=0) 58 | nn.init.constant_(self.W.weight, 0) 59 | nn.init.constant_(self.W.bias, 0) 60 | 61 | self.theta = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 62 | kernel_size=1, stride=1, padding=0) 63 | self.phi = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 64 | kernel_size=1, stride=1, padding=0) 65 | 66 | if sub_sample: 67 | self.g = nn.Sequential(self.g, max_pool_layer) 68 | self.phi = nn.Sequential(self.phi, max_pool_layer) 69 | 70 | def forward(self, x, return_nl_map=False): 71 | """ 72 | :param x: (b, c, t, h, w) 73 | :param return_nl_map: if True return z, nl_map, else only return z. 74 | :return: 75 | """ 76 | 77 | batch_size = x.size(0) 78 | 79 | g_x = self.g(x).view(batch_size, self.inter_channels, -1) 80 | g_x = g_x.permute(0, 2, 1) 81 | 82 | theta_x = self.theta(x).view(batch_size, self.inter_channels, -1) 83 | theta_x = theta_x.permute(0, 2, 1) 84 | phi_x = self.phi(x).view(batch_size, self.inter_channels, -1) 85 | f = torch.matmul(theta_x, phi_x) 86 | f_div_C = F.softmax(f, dim=-1) 87 | 88 | y = torch.matmul(f_div_C, g_x) 89 | y = y.permute(0, 2, 1).contiguous() 90 | y = y.view(batch_size, self.inter_channels, *x.size()[2:]) 91 | W_y = self.W(y) 92 | z = W_y + x 93 | 94 | if return_nl_map: 95 | return z, f_div_C 96 | return z 97 | 98 | 99 | class NONLocalBlock1D(_NonLocalBlockND): 100 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 101 | super(NONLocalBlock1D, self).__init__(in_channels, 102 | inter_channels=inter_channels, 103 | dimension=1, sub_sample=sub_sample, 104 | bn_layer=bn_layer) 105 | 106 | 107 | class NONLocalBlock2D(_NonLocalBlockND): 108 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 109 | super(NONLocalBlock2D, self).__init__(in_channels, 110 | inter_channels=inter_channels, 111 | dimension=2, sub_sample=sub_sample, 112 | bn_layer=bn_layer,) 113 | 114 | 115 | class NONLocalBlock3D(_NonLocalBlockND): 116 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 117 | super(NONLocalBlock3D, self).__init__(in_channels, 118 | inter_channels=inter_channels, 119 | dimension=3, sub_sample=sub_sample, 120 | bn_layer=bn_layer,) 121 | 122 | 123 | if __name__ == '__main__': 124 | import torch 125 | 126 | for (sub_sample_, bn_layer_) in [(True, True), (False, False), (True, False), (False, True)]: 127 | img = torch.zeros(2, 3, 20) 128 | net = NONLocalBlock1D(3, sub_sample=sub_sample_, bn_layer=bn_layer_) 129 | out = net(img) 130 | print(out.size()) 131 | 132 | img = torch.zeros(2, 3, 20, 20) 133 | net = NONLocalBlock2D(3, sub_sample=sub_sample_, bn_layer=bn_layer_) 134 | out = net(img) 135 | print(out.size()) 136 | 137 | img = torch.randn(2, 3, 8, 20, 20) 138 | net = NONLocalBlock3D(3, sub_sample=sub_sample_, bn_layer=bn_layer_) 139 | out = net(img) 140 | print(out.size()) 141 | 142 | 143 | -------------------------------------------------------------------------------- /lib/non_local_gaussian.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.nn import functional as F 4 | 5 | 6 | class _NonLocalBlockND(nn.Module): 7 | def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True): 8 | super(_NonLocalBlockND, self).__init__() 9 | 10 | assert dimension in [1, 2, 3] 11 | 12 | self.dimension = dimension 13 | self.sub_sample = sub_sample 14 | 15 | self.in_channels = in_channels 16 | self.inter_channels = inter_channels 17 | 18 | if self.inter_channels is None: 19 | self.inter_channels = in_channels // 2 20 | if self.inter_channels == 0: 21 | self.inter_channels = 1 22 | 23 | if dimension == 3: 24 | conv_nd = nn.Conv3d 25 | max_pool_layer = nn.MaxPool3d(kernel_size=(1, 2, 2)) 26 | bn = nn.BatchNorm3d 27 | elif dimension == 2: 28 | conv_nd = nn.Conv2d 29 | max_pool_layer = nn.MaxPool2d(kernel_size=(2, 2)) 30 | bn = nn.BatchNorm2d 31 | else: 32 | conv_nd = nn.Conv1d 33 | max_pool_layer = nn.MaxPool1d(kernel_size=(2)) 34 | bn = nn.BatchNorm1d 35 | 36 | self.g = conv_nd(in_channels=self.in_channels, out_channels=self.inter_channels, 37 | kernel_size=1, stride=1, padding=0) 38 | 39 | if bn_layer: 40 | self.W = nn.Sequential( 41 | conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 42 | kernel_size=1, stride=1, padding=0), 43 | bn(self.in_channels) 44 | ) 45 | nn.init.constant_(self.W[1].weight, 0) 46 | nn.init.constant_(self.W[1].bias, 0) 47 | else: 48 | self.W = conv_nd(in_channels=self.inter_channels, out_channels=self.in_channels, 49 | kernel_size=1, stride=1, padding=0) 50 | nn.init.constant_(self.W.weight, 0) 51 | nn.init.constant_(self.W.bias, 0) 52 | 53 | if sub_sample: 54 | self.g = nn.Sequential(self.g, max_pool_layer) 55 | self.phi = max_pool_layer 56 | 57 | def forward(self, x, return_nl_map=False): 58 | """ 59 | :param x: (b, c, t, h, w) 60 | :param return_nl_map: if True return z, nl_map, else only return z. 61 | :return: 62 | """ 63 | 64 | batch_size = x.size(0) 65 | 66 | g_x = self.g(x).view(batch_size, self.inter_channels, -1) 67 | 68 | g_x = g_x.permute(0, 2, 1) 69 | 70 | theta_x = x.view(batch_size, self.in_channels, -1) 71 | theta_x = theta_x.permute(0, 2, 1) 72 | 73 | if self.sub_sample: 74 | phi_x = self.phi(x).view(batch_size, self.in_channels, -1) 75 | else: 76 | phi_x = x.view(batch_size, self.in_channels, -1) 77 | 78 | f = torch.matmul(theta_x, phi_x) 79 | f_div_C = F.softmax(f, dim=-1) 80 | 81 | # if self.store_last_batch_nl_map: 82 | # self.nl_map = f_div_C 83 | 84 | y = torch.matmul(f_div_C, g_x) 85 | y = y.permute(0, 2, 1).contiguous() 86 | y = y.view(batch_size, self.inter_channels, *x.size()[2:]) 87 | W_y = self.W(y) 88 | z = W_y + x 89 | 90 | if return_nl_map: 91 | return z, f_div_C 92 | return z 93 | 94 | 95 | class NONLocalBlock1D(_NonLocalBlockND): 96 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 97 | super(NONLocalBlock1D, self).__init__(in_channels, 98 | inter_channels=inter_channels, 99 | dimension=1, sub_sample=sub_sample, 100 | bn_layer=bn_layer) 101 | 102 | 103 | class NONLocalBlock2D(_NonLocalBlockND): 104 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 105 | super(NONLocalBlock2D, self).__init__(in_channels, 106 | inter_channels=inter_channels, 107 | dimension=2, sub_sample=sub_sample, 108 | bn_layer=bn_layer) 109 | 110 | 111 | class NONLocalBlock3D(_NonLocalBlockND): 112 | def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True): 113 | super(NONLocalBlock3D, self).__init__(in_channels, 114 | inter_channels=inter_channels, 115 | dimension=3, sub_sample=sub_sample, 116 | bn_layer=bn_layer) 117 | 118 | 119 | if __name__ == '__main__': 120 | import torch 121 | 122 | for (sub_sample_, bn_layer_) in [(True, True), (False, False), (True, False), (False, True)]: 123 | img = torch.zeros(2, 3, 20) 124 | net = NONLocalBlock1D(3, sub_sample=sub_sample_, bn_layer=bn_layer_) 125 | out = net(img) 126 | print(out.size()) 127 | 128 | img = torch.zeros(2, 3, 20, 20) 129 | net = NONLocalBlock2D(3, sub_sample=sub_sample_, bn_layer=bn_layer_) 130 | out = net(img) 131 | print(out.size()) 132 | 133 | img = torch.randn(2, 3, 8, 20, 20) 134 | net = NONLocalBlock3D(3, sub_sample=sub_sample_, bn_layer=bn_layer_) 135 | out = net(img) 136 | print(out.size()) 137 | 138 | 139 | 140 | 141 | 142 | 143 | -------------------------------------------------------------------------------- /nl_map_save.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.utils.data as Data 3 | import torchvision 4 | from lib.network import Network 5 | from torch import nn 6 | import numpy as np 7 | 8 | 9 | test_data = torchvision.datasets.MNIST(root='./mnist/', 10 | transform=torchvision.transforms.ToTensor(), 11 | train=False) 12 | 13 | test_loader = iter(Data.DataLoader(dataset=test_data, batch_size=1, shuffle=False)) 14 | 15 | net = Network() 16 | if torch.cuda.is_available(): 17 | net = nn.DataParallel(net) 18 | net.cuda() 19 | 20 | net.load_state_dict(torch.load('weights/net.pth')) 21 | 22 | 23 | img_batch, label_batch = test_loader.__next__() 24 | img_batch = img_batch.cuda() 25 | label_batch = label_batch.cuda() 26 | 27 | torch.set_grad_enabled(False) 28 | net.eval() 29 | 30 | _, nl_mep_list = net.module.forward_with_nl_map(img_batch) 31 | 32 | # (b, h1*w1, h2*w2) 33 | nl_map_1 = nl_mep_list[0].cpu().numpy() 34 | nl_map_2 = nl_mep_list[1].cpu().numpy() 35 | 36 | img = torchvision.transforms.ToPILImage()(img_batch.cpu()[0]) 37 | img.save('nl_map_vis/sample.png') 38 | np.save('nl_map_vis/nl_map_1', nl_map_1) 39 | np.save('nl_map_vis/nl_map_2', nl_map_2) 40 | -------------------------------------------------------------------------------- /nl_map_vis/nl_map_1.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_1.npy -------------------------------------------------------------------------------- /nl_map_vis/nl_map_1/110.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_1/110.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_1/147.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_1/147.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_1/161.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_1/161.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_1/174.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_1/174.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_1/177.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_1/177.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_1/188.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_1/188.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_1/37.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_1/37.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_1/44.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_1/44.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_1/46.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_1/46.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_1/49.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_1/49.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_1/51.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_1/51.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_1/61.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_1/61.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_1/63.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_1/63.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_1/66.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_1/66.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_2.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_2.npy -------------------------------------------------------------------------------- /nl_map_vis/nl_map_2/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_2/1.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_2/10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_2/10.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_2/18.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_2/18.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_2/19.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_2/19.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_2/22.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_2/22.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_2/38.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_2/38.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_2/8.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/nl_map_2/8.png -------------------------------------------------------------------------------- /nl_map_vis/nl_map_vis.py: -------------------------------------------------------------------------------- 1 | """ 2 | (tips: if the Non-local type you select is **non_local_concatenation** 3 | or **non_local_dot_product** (without Softmax operation), 4 | you may need to normalize NL_MAP in the visualize code) 5 | """ 6 | import numpy as np 7 | import cv2 8 | import math 9 | import os 10 | 11 | 12 | def vis_nl_map(img_path, nl_map_path, vis_size=(56, 56)): 13 | dst_dir = nl_map_path.split('.')[0] 14 | if not os.path.exists(dst_dir): 15 | os.mkdir(dst_dir) 16 | 17 | img = cv2.imread(img_path, 1) 18 | img = cv2.resize(img, dsize=vis_size) 19 | h, w, c = img.shape 20 | 21 | nl_map_1 = np.load(nl_map_path)[0] 22 | 23 | total_region, nl_map_length = nl_map_1.shape 24 | region_per_row = round(math.sqrt(total_region)) 25 | size_of_region = round(w / region_per_row) 26 | 27 | nl_map_size = round(math.sqrt(nl_map_length)) 28 | 29 | for index in range(total_region): 30 | img_draw = img.copy() 31 | nl_map = nl_map_1[index] 32 | nl_map = nl_map.reshape(nl_map_size, nl_map_size) 33 | nl_map = cv2.resize(nl_map, dsize=(h, w)) 34 | 35 | nl_map = np.uint8(nl_map * 255) 36 | 37 | heat_img = cv2.applyColorMap(nl_map, cv2.COLORMAP_JET) 38 | heat_img = cv2.cvtColor(heat_img, cv2.COLOR_BGR2RGB) 39 | img_add = cv2.addWeighted(img_draw, 0.3, heat_img, 0.7, 0) 40 | 41 | x0 = index // region_per_row * size_of_region 42 | x1 = x0 + size_of_region 43 | 44 | y0 = index % region_per_row * size_of_region 45 | y1 = y0 + size_of_region 46 | 47 | cv2.rectangle(img_add, (y0, x0), (y1, x1), (255, 0, 0), 1) 48 | cv2.imwrite('%s/%d.png' % (dst_dir, index), cv2.cvtColor(img_add, cv2.COLOR_BGR2RGB)) 49 | 50 | 51 | if __name__ == '__main__': 52 | vis_nl_map(img_path='sample.png', nl_map_path='nl_map_1.npy', vis_size=(56, 56)) 53 | vis_nl_map(img_path='sample.png', nl_map_path='nl_map_2.npy', vis_size=(56, 56)) 54 | -------------------------------------------------------------------------------- /nl_map_vis/sample.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/nl_map_vis/sample.png -------------------------------------------------------------------------------- /weights/net.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlexHex7/Non-local_pytorch/ec15789af4533448169f3dc36abe542badd34221/weights/net.pth --------------------------------------------------------------------------------