├── .gitignore ├── LICENSE ├── README.md ├── bilinear.h ├── bilinear_upsampling.py ├── nv_upsampling.cpp ├── nv_upsampling_cuda_kernel.cu ├── setup.py ├── starry_small.jpg ├── test.py └── test2.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.i 2 | *.ii 3 | *.gpu 4 | *.ptx 5 | *.cubin 6 | *.fatbin 7 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Fast Bilinear Upsampling for PyTorch 2 | 3 | ### What is this? 4 | 5 | This implementation of bilinear upsampling is considerably faster than the native PyTorch one in half precision (fp16). It is also slightly faster for single precision (fp32). See the "Performance" section below. 6 | 7 | ### Requirements 8 | * PyTorch 1.0.0+ 9 | * CUDA 10.0+ 10 | * GPU with compute capability 7.0+ (Tesla V100, Titan V, GeForce RTX 2070/2080/2080Ti, etc.) 11 | 12 | ### Caveats 13 | 14 | Currently this implementation is equivalent to PyTorch's bilinear upsampling with `align_corners=True`. The case of `align_corners=False` hasn't been implemented yet. 15 | 16 | ### Installation 17 | 18 | `$python setup.py install` 19 | 20 | ### Sample execution 21 | 22 | The script `test.py` demonstrates use. The TL;DR is that the following calls are equivalent: 23 | * PyTorch: 24 | ```result = torch.nn.functional.interpolate(data, scale_factor=2, mode='bilinear', align_corners=True)``` 25 | * This library: 26 | ``` 27 | from bilinear_upsampling import Interpolation 28 | interp = Interpolation() 29 | result = interp(data, scale_factor=2) 30 | ``` 31 | 32 | ### Performance 33 | 34 | Tensor dimensions: (128, 3, 224, 224) 35 | 36 | Test env: Titan V GPU, Intel Core i7-7800X CPU @ 3.50GHz 37 | 38 | 39 | **fp16** 40 | 41 | | Direction | PyTorch | This Implementation | 42 | |-----------|----------|---------------------| 43 | | forward | 685 us | 482 us | 44 | | backward | 15.11 ms | 4.17 ms | 45 | 46 | **fp32** 47 | 48 | | Direction | PyTorch | This Implementation | 49 | |-----------|----------|---------------------| 50 | | forward | 788 us | 629 us | 51 | | backward | 1.92 ms | 1.49 ms | 52 | 53 | 54 | -------------------------------------------------------------------------------- /bilinear.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | at::Tensor bilinear_cuda_forward(at::Tensor& in, const int new_h, const int new_w); 6 | 7 | at::Tensor bilinear_cuda_backward(at::Tensor& in, const int orig_h, const int orig_w); 8 | -------------------------------------------------------------------------------- /bilinear_upsampling.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import nv_bilinear_upsampling_cuda as ups_cuda 3 | 4 | class InterpolationFunction(torch.autograd.Function): 5 | @staticmethod 6 | def forward(ctx, input, new_h=None, new_w=None, scale_factor=None): 7 | dims = new_h is not None and new_w is not None 8 | assert dims or scale_factor, "either new dims (new_h, new_w) or scale factor need to be given" 9 | if scale_factor is not None: 10 | new_h, new_w = int(input.shape[-2] * scale_factor), int(input.shape[-1] * scale_factor) 11 | outputs = ups_cuda.bilinear_forward(input.contiguous(), new_h, new_w) 12 | variables = [torch.as_tensor(input.size(-2)), torch.as_tensor(input.size(-1))] 13 | ctx.save_for_backward(*variables) 14 | return outputs 15 | 16 | @staticmethod 17 | def backward(ctx, grad_o): 18 | outputs = ups_cuda.bilinear_backward(grad_o.contiguous(), *ctx.saved_variables) 19 | return outputs, None, None, None 20 | 21 | class Interpolation(torch.nn.Module): 22 | def __init__(self): 23 | super(Interpolation, self).__init__() 24 | 25 | def forward(self, input, new_h=None, new_w=None, scale_factor=None): 26 | return InterpolationFunction.apply(input, new_h, new_w, scale_factor) 27 | -------------------------------------------------------------------------------- /nv_upsampling.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "bilinear.h" 4 | 5 | #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") 6 | #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") 7 | #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) 8 | 9 | at::Tensor bilinear_forward(at::Tensor& z, const int new_h, const int new_w) { 10 | CHECK_INPUT(z); 11 | return bilinear_cuda_forward(z, new_h, new_w); 12 | } 13 | 14 | at::Tensor bilinear_backward(at::Tensor& z, const int orig_h, const int orig_w) { 15 | CHECK_INPUT(z); 16 | return bilinear_cuda_backward(z, orig_h, orig_w); 17 | } 18 | 19 | 20 | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { 21 | m.def("bilinear_forward", &bilinear_forward, "bilinear forward"); 22 | m.def("bilinear_backward", &bilinear_backward, "bilinear backward"); 23 | } 24 | -------------------------------------------------------------------------------- /nv_upsampling_cuda_kernel.cu: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | 5 | #include "bilinear.h" 6 | 7 | #include 8 | #include 9 | 10 | #include 11 | 12 | #if __CUDA_ARCH__ >= 350 13 | // Device has __ldg 14 | template 15 | __device__ __forceinline__ T __ldg(const T *ptr) { 16 | typedef typename detail::working_array::type aliased; 17 | aliased storage = detail::load_storage::impl(ptr); 18 | return detail::fuse(storage); 19 | } 20 | 21 | #else 22 | template 23 | __device__ __forceinline__ T __ldg(const T *ptr) { 24 | return *ptr; 25 | } 26 | 27 | #endif 28 | 29 | template ::value>::type * = nullptr> 31 | __device__ __forceinline__ void fastSpecializedAtomicAdd(scalar_t *tensor, 32 | int index, int numel, 33 | scalar_t value) { 34 | #if ((CUDA_VERSION < 10000) || \ 35 | (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 700))) 36 | atomicAdd(reinterpret_cast(tensor) + index, 37 | static_cast(value)); 38 | #else 39 | if (index % 2 == 0 && index < (numel - 1)) { 40 | __half2 value2; 41 | value2.x = value; 42 | value2.y = __int2half_rz(0); 43 | atomicAdd(reinterpret_cast<__half2 *>(tensor) + index / 2, value2); 44 | 45 | } else if (index % 2 == 1) { 46 | __half2 value2; 47 | value2.x = __int2half_rz(0); 48 | value2.y = value; 49 | atomicAdd(reinterpret_cast<__half2 *>(tensor) + index / 2, value2); 50 | 51 | } else { 52 | atomicAdd(reinterpret_cast<__half *>(tensor) + index, 53 | static_cast<__half>(value)); 54 | } 55 | #endif 56 | } 57 | 58 | template ::value>::type * = nullptr> 60 | __device__ __forceinline__ void fastSpecializedAtomicAdd(scalar_t *tensor, 61 | int index, int numel, 62 | scalar_t value) { 63 | atomicAdd(tensor + index, value); 64 | } 65 | 66 | template 67 | __device__ __forceinline__ void fastAtomicAdd(scalar_t *__restrict__ tensor, 68 | int index, int numel, 69 | scalar_t value) { 70 | fastSpecializedAtomicAdd(tensor, index, numel, value); 71 | } 72 | 73 | __device__ __forceinline__ int idx(const int n, const int num_channels, 74 | const int c, const int height, 75 | const int width, const int y, const int x) { 76 | return ((n * num_channels + c) * height + y) * width + x; 77 | } 78 | 79 | // input is X, output is Y 80 | template 81 | __global__ void bilinearForwardKernel( 82 | const int output_size, const int num_channels, const int input_height, 83 | const int input_width, const int output_height, const int output_width, 84 | const scalar_t *const __restrict__ X, scalar_t *const __restrict__ Y) { 85 | const float height_scale = 1.0f * output_height / input_height; 86 | const float width_scale = 1.0f * output_width / input_width; 87 | 88 | const int batch_size = 89 | output_size / num_channels / output_height / output_width; 90 | 91 | const int index = blockDim.x * blockIdx.x + threadIdx.x; 92 | 93 | int indexTemp = index; 94 | const int out_x = indexTemp % output_width; 95 | indexTemp /= output_width; 96 | const int out_y = indexTemp % output_height; 97 | 98 | const int in_y = fminf(out_y / height_scale, input_height - 1); 99 | const int in_x = fminf(out_x / width_scale, input_width - 1); 100 | 101 | const float rheight = 102 | output_height > 1 ? (input_height - 1.f) / (output_height - 1.f) : 0.f; 103 | const float rwidth = 104 | output_width > 1 ? (input_width - 1.f) / (output_width - 1.f) : 0.f; 105 | 106 | const float h1r = rheight * out_y; 107 | const int h1 = static_cast(h1r); 108 | const int h1p = (h1 < input_height - 1) ? 1 : 0; 109 | const float h1lambda = h1r - h1; 110 | const float h0lambda = 1.f - h1lambda; 111 | 112 | const float w1r = rwidth * out_x; 113 | const int w1 = static_cast(w1r); 114 | const int w1p = (w1 < input_width - 1) ? 1 : 0; 115 | const float w1lambda = w1r - w1; 116 | const float w0lambda = 1.f - w1lambda; 117 | 118 | for (int n = 0; n < batch_size; n++) { 119 | for (int c = 0; c < num_channels; c++) { 120 | Y[idx(n, num_channels, c, output_height, output_width, out_y, out_x)] = 121 | static_cast( 122 | h0lambda * 123 | (w0lambda * __ldg(&X[idx(n, num_channels, c, input_height, 124 | input_width, h1, w1)]) + 125 | w1lambda * __ldg(&X[idx(n, num_channels, c, input_height, 126 | input_width, h1, w1 + w1p)])) + 127 | h1lambda * 128 | (w0lambda * __ldg(&X[idx(n, num_channels, c, input_height, 129 | input_width, h1 + h1p, w1)]) + 130 | w1lambda * __ldg(&X[idx(n, num_channels, c, input_height, 131 | input_width, h1 + h1p, w1 + w1p)]))); 132 | } 133 | } 134 | } 135 | 136 | // TODO: Launch this with thread per gradInput instead of gradOutput 137 | // input is dY, output is dX 138 | template 139 | __global__ void bilinearBackwardKernel2( 140 | const int input_size, const int num_channels, const int input_height, 141 | const int input_width, const int output_height, const int output_width, 142 | const scalar_t *const __restrict__ dY, scalar_t *const __restrict__ dX) { 143 | const float height_scale = 1.0f * output_height / input_height; 144 | const float width_scale = 1.0f * output_width / input_width; 145 | 146 | const int index = blockDim.x * blockIdx.x + threadIdx.x; 147 | 148 | int indexTemp = index; 149 | const int in_x = indexTemp % input_width; 150 | indexTemp /= input_width; 151 | const int in_y = indexTemp % input_height; 152 | indexTemp /= input_height; 153 | const int c = indexTemp % num_channels; 154 | indexTemp /= num_channels; 155 | 156 | // const int n = indexTemp; 157 | const int n = 0; 158 | 159 | if (index > input_size - 1) { 160 | return; 161 | } 162 | 163 | const int dst_idx = 164 | idx(n, num_channels, c, input_height, input_width, in_y, in_x); 165 | 166 | // accumulator 167 | float acc = 0.0f; 168 | 169 | // TODO: figure out which Ys to loop over 170 | // TODO: figure out what lambdas to use for which Y 171 | 172 | const int y_window = ceilf(height_scale); 173 | const int x_window = ceilf(width_scale); 174 | 175 | // Not expecting overflow here, static_cast(roundf(x)) is ugly 176 | const int y_base_idx = lroundf(in_y * height_scale); 177 | const int x_base_idx = lroundf(in_x * width_scale); 178 | 179 | int ctr = 0; 180 | 181 | for (int out_y = y_base_idx; 182 | out_y <= min(y_base_idx + y_window, output_height - 1); out_y++) { 183 | for (int out_x = x_base_idx; 184 | out_x <= min(x_base_idx + x_window, output_width - 1); out_x++) { 185 | ctr += 1; 186 | 187 | const int src_idx = 188 | idx(n, num_channels, c, output_height, output_width, out_y, out_x); 189 | 190 | // TODO: calculate lambdas for y and x !! 191 | 192 | acc += dY[src_idx]; 193 | } 194 | } 195 | 196 | dX[dst_idx] = static_cast(acc); 197 | } 198 | 199 | // input is dY, output is dX 200 | template 201 | __global__ void bilinearBackwardKernel( 202 | const int input_size, const int num_channels, const int input_height, 203 | const int input_width, const int output_height, const int output_width, 204 | const scalar_t *const __restrict__ dY, scalar_t *const __restrict__ dX) { 205 | const float height_scale = 1.0f * output_height / input_height; 206 | const float width_scale = 1.0f * output_width / input_width; 207 | 208 | for (size_t index = blockDim.x * blockIdx.x + threadIdx.x; index < input_size; 209 | index += blockDim.x * gridDim.x) { 210 | int indexTemp = index; 211 | const int in_x = indexTemp % input_width; 212 | indexTemp /= input_width; 213 | const int in_y = indexTemp % input_height; 214 | indexTemp /= input_height; 215 | const int c = indexTemp % num_channels; 216 | indexTemp /= num_channels; 217 | const int n = indexTemp; 218 | 219 | const int out_y = fminf(in_y / height_scale, output_height - 1); 220 | const int out_x = fminf(in_x / width_scale, output_width - 1); 221 | 222 | const float rheight = 223 | output_height > 1 ? (output_height - 1.f) / (input_height - 1.f) : 0.f; 224 | const float rwidth = 225 | output_width > 1 ? (output_width - 1.f) / (input_width - 1.f) : 0.f; 226 | 227 | // Compute Y axis lambdas 228 | const float h1r = rheight * in_y; 229 | const int h1 = static_cast(h1r); 230 | const int h1p = (h1 < output_height - 1) ? 1 : 0; 231 | const float h1lambda = h1r - h1; 232 | const float h0lambda = 1.f - h1lambda; 233 | 234 | // Compute X axis lambdas 235 | const float w1r = rwidth * in_x; 236 | const int w1 = static_cast(w1r); 237 | const int w1p = (w1 < output_width - 1) ? 1 : 0; 238 | const float w1lambda = w1r - w1; 239 | const float w0lambda = 1.f - w1lambda; 240 | 241 | const scalar_t dYi = __ldg(&dY[index]); 242 | 243 | const int out_numel = input_size / (input_height * input_width) * 244 | output_height * output_width; 245 | 246 | if (n == 2 && c == 1 && h1 == 12 && w1 == 14) { 247 | int idx0 = idx(n, num_channels, c, output_height, output_width, h1, w1); 248 | 249 | printf("n = %d, c = %d, h1 = %d, w1 = %d, dX idx = %d, dY idx = %d\n", n, 250 | c, h1, w1, idx0, (int)index); 251 | } 252 | 253 | fastAtomicAdd( 254 | dX, idx(n, num_channels, c, output_height, output_width, h1, w1), 255 | out_numel, static_cast(h0lambda * w0lambda * dYi)); 256 | 257 | fastAtomicAdd( 258 | dX, idx(n, num_channels, c, output_height, output_width, h1, w1 + w1p), 259 | out_numel, static_cast(h0lambda * w1lambda * dYi)); 260 | 261 | fastAtomicAdd( 262 | dX, idx(n, num_channels, c, output_height, output_width, h1 + h1p, w1), 263 | out_numel, static_cast(h1lambda * w0lambda * dYi)); 264 | 265 | fastAtomicAdd(dX, idx(n, num_channels, c, output_height, 266 | output_width, h1 + h1p, w1 + w1p), 267 | out_numel, 268 | static_cast(h1lambda * w1lambda * dYi)); 269 | } 270 | } 271 | 272 | at::Tensor bilinear_cuda_forward(at::Tensor &in, const int new_h, 273 | const int new_w) { 274 | const int nIn = in.size(0); 275 | const int cIn = in.size(1); 276 | const int hIn = in.size(2); 277 | const int wIn = in.size(3); 278 | 279 | at::Tensor out = at::empty({nIn, cIn, new_h, new_w}, in.options()); 280 | 281 | const int outSize = nIn * cIn * new_h * new_w; 282 | const dim3 block(256); 283 | const dim3 grid(((outSize / cIn / nIn) + block.x - 1) / block.x); 284 | 285 | AT_DISPATCH_FLOATING_TYPES_AND_HALF( 286 | in.type(), "bilinearForwardKernel", ([&] { 287 | 288 | bilinearForwardKernel<<>>( 289 | out.numel(), cIn, hIn, wIn, new_h, new_w, in.data(), 290 | out.data()); 291 | 292 | })); 293 | 294 | AT_CHECK(cudaGetLastError() == cudaSuccess, 295 | "issue with bilinearForwardKernel, CUDA code ", cudaGetLastError()); 296 | 297 | return out; 298 | } 299 | 300 | at::Tensor bilinear_cuda_backward(at::Tensor &in, const int out_h, 301 | const int out_w) { 302 | const int nIn = in.size(0); 303 | const int cIn = in.size(1); 304 | const int hIn = in.size(2); 305 | const int wIn = in.size(3); 306 | 307 | at::Tensor out = at::empty({nIn, cIn, out_h, out_w}, in.options()); 308 | 309 | /* 310 | const int outSize = nIn * cIn * out_h * out_w; 311 | const dim3 block(256); 312 | const dim3 grid((outSize + block.x - 1) / block.x); 313 | */ 314 | 315 | const int inSize = nIn * cIn * hIn * wIn; 316 | const dim3 block(256); 317 | const dim3 grid((inSize + block.x - 1) / block.x); 318 | 319 | AT_DISPATCH_FLOATING_TYPES_AND_HALF( 320 | in.type(), "bilinearBackwardKernel", ([&] { 321 | 322 | // bilinearBackwardKernel2 323 | bilinearBackwardKernel<<>>( 324 | in.numel(), cIn, hIn, wIn, out_h, out_w, in.data(), 325 | out.data()); 326 | 327 | })); 328 | 329 | AT_CHECK(cudaGetLastError() == cudaSuccess, 330 | "issue with bilinearForwardKernel, CUDA code ", cudaGetLastError()); 331 | 332 | return out; 333 | } 334 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | from torch.utils.cpp_extension import BuildExtension, CUDAExtension 3 | 4 | setup(name='nv_bilinear_upsampling', 5 | 6 | ext_modules=[ 7 | CUDAExtension('nv_bilinear_upsampling_cuda', ['nv_upsampling.cpp', 'nv_upsampling_cuda_kernel.cu'], 8 | 9 | extra_compile_args={ 10 | 'cxx': ['-std=c++14', '-O3', '-Wall'], 11 | 'nvcc': [ 12 | '-gencode', 'arch=compute_35,code=sm_35', 13 | '-gencode', 'arch=compute_50,code=sm_50', 14 | '-gencode', 'arch=compute_52,code=sm_52', 15 | '-gencode', 'arch=compute_60,code=sm_60', 16 | '-gencode', 'arch=compute_61,code=sm_61', 17 | '-gencode', 'arch=compute_70,code=sm_70', 18 | '-gencode', 'arch=compute_75,code=sm_75', 19 | '-gencode', 'arch=compute_70,code=compute_70', 20 | '-Xcompiler', '-Wall', 21 | '-std=c++14', 22 | '-O3', 23 | '--use_fast_math' 24 | ] 25 | })], 26 | version='0.1.0', 27 | py_modules=['bilinear_upsampling'], 28 | cmdclass={'build_ext': BuildExtension}) 29 | -------------------------------------------------------------------------------- /starry_small.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mkolod/fast_upsampling/1aedc8c4308ae7f57f6fcadb529828766983c37c/starry_small.jpg -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn.functional as F 3 | 4 | import numpy as np 5 | 6 | from matplotlib.image import imread, imsave 7 | 8 | from bilinear_upsampling import Interpolation 9 | 10 | fp16 = True 11 | 12 | num_runs = 20 13 | 14 | log = False 15 | 16 | # foo = torch.randn(1, 1, 5, 5, requires_grad=True).cuda() 17 | 18 | x = imread("starry_small.jpg") 19 | #foo = x.swapaxes(1, 2).swapaxes(0, 1) 20 | foo = np.expand_dims(x, axis=0) 21 | 22 | # NWHC to NCHW 23 | foo = torch.from_numpy(foo).cuda().float().permute(0, 3, 1, 2) 24 | 25 | foo.requires_grad = True 26 | 27 | if fp16: 28 | foo = foo.half() 29 | 30 | for i in range(num_runs): 31 | bar = F.interpolate(foo, scale_factor=2, mode='bilinear', align_corners=True) # False 32 | 33 | if log: 34 | print("Original data") 35 | print(foo) 36 | print("Reference implementation") 37 | print(bar) 38 | 39 | interp = Interpolation() 40 | 41 | for i in range(num_runs): 42 | baz = interp(foo, scale_factor=2) 43 | 44 | if log: 45 | print("My implementation") 46 | 47 | print(baz) 48 | 49 | print("Max fprop difference:") 50 | 51 | print(torch.max(torch.abs(bar - baz))) 52 | 53 | def set_grad(var): 54 | def hook(grad): 55 | var.grad = grad 56 | return hook 57 | 58 | bar2 = bar.sum() 59 | baz2 = baz.sum() 60 | 61 | #bar.register_hook(set_grad(bar)) 62 | #baz.register_hook(set_grad(baz)) 63 | # 64 | #bar2.register_hook(set_grad(bar2)) 65 | #baz2.register_hook(set_grad(baz2)) 66 | 67 | for i in range(num_runs): 68 | bar2.backward(retain_graph=True) 69 | baz2.backward(retain_graph=True) 70 | 71 | 72 | #print("bar2: {}".format(bar2)) 73 | #print("baz2: {}".format(baz2)) 74 | 75 | 76 | #spam = bar.detach().squeeze().permute(1, 2, 0).float().cpu().numpy().astype(np.uint8) 77 | 78 | #ham = baz.detach().squeeze().permute(1, 2, 0).float().cpu().numpy().astype(np.uint8) 79 | 80 | #print(spam.shape) 81 | #print(ham.shape) 82 | 83 | #print(spam) 84 | #print(ham) 85 | #print(spam - ham) 86 | 87 | #pic = np.squeeze(spam).swapaxes(0, 1).swapaxes(1, 2).astype(np.uint8) 88 | #pic = ham 89 | #print(pic.shape) 90 | #print(pic.dtype) 91 | 92 | #print(x) 93 | #print("\n\n") 94 | #print(pic) 95 | 96 | #imsave('resized.jpg', pic) 97 | 98 | #print(bar.grad, baz.grad) 99 | #print(bar2.grad, baz2.grad) 100 | 101 | 102 | #print("Maximum backprop difference for [bar, baz]:") 103 | #print(torch.max(torch.abs(bar.grad - baz.grad))) 104 | # 105 | #print("Maximum backprop difference for [bar2, baz2]:") 106 | #print(torch.max(torch.abs(bar2.grad - baz2.grad))) 107 | 108 | # print(bar - baz) 109 | -------------------------------------------------------------------------------- /test2.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn.functional as F 3 | 4 | import numpy as np 5 | 6 | from matplotlib.image import imread, imsave 7 | 8 | from bilinear_upsampling import Interpolation 9 | 10 | fp16 = True 11 | 12 | num_runs = 100 13 | 14 | log = False 15 | 16 | # foo = torch.randn(1, 1, 5, 5, requires_grad=True).cuda() 17 | 18 | #x = imread("starry_small.jpg") 19 | #foo = x.swapaxes(1, 2).swapaxes(0, 1) 20 | #foo = np.expand_dims(x, axis=0) 21 | 22 | # NWHC to NCHW 23 | #foo = torch.from_numpy(foo).cuda().float().permute(0, 3, 1, 2) 24 | 25 | foo = torch.randn(128, 3, 224, 224).cuda() 26 | 27 | foo.requires_grad = True 28 | 29 | if fp16: 30 | foo = foo.half() 31 | 32 | for i in range(num_runs): 33 | bar = F.interpolate(foo, scale_factor=2, mode='bilinear', align_corners=True) # False 34 | 35 | if log: 36 | print("Original data") 37 | print(foo) 38 | print("Reference implementation") 39 | print(bar) 40 | 41 | interp = Interpolation() 42 | 43 | for i in range(num_runs): 44 | baz = interp(foo, scale_factor=2) 45 | 46 | if log: 47 | print("My implementation") 48 | 49 | print(baz) 50 | 51 | print("Max fprop difference:") 52 | 53 | print(torch.max(torch.abs(bar - baz))) 54 | 55 | def set_grad(var): 56 | def hook(grad): 57 | var.grad = grad 58 | return hook 59 | 60 | bar2 = bar.sum() 61 | baz2 = baz.sum() 62 | 63 | #bar.register_hook(set_grad(bar)) 64 | #baz.register_hook(set_grad(baz)) 65 | # 66 | #bar2.register_hook(set_grad(bar2)) 67 | #baz2.register_hook(set_grad(baz2)) 68 | 69 | for i in range(num_runs): 70 | bar2.backward(retain_graph=True) 71 | baz2.backward(retain_graph=True) 72 | 73 | #print("bar2: {}".format(bar2)) 74 | #print("baz2: {}".format(baz2)) 75 | 76 | #spam = bar.detach().squeeze().permute(1, 2, 0).float().cpu().numpy().astype(np.uint8) 77 | 78 | #ham = baz.detach().squeeze().permute(1, 2, 0).float().cpu().numpy().astype(np.uint8) 79 | 80 | #print(spam.shape) 81 | #print(ham.shape) 82 | 83 | #print(spam) 84 | #print(ham) 85 | #print(spam - ham) 86 | 87 | #pic = np.squeeze(spam).swapaxes(0, 1).swapaxes(1, 2).astype(np.uint8) 88 | #pic = ham 89 | #print(pic.shape) 90 | #print(pic.dtype) 91 | 92 | #print(x) 93 | #print("\n\n") 94 | #print(pic) 95 | 96 | #imsave('resized.jpg', pic) 97 | 98 | #print(bar.grad, baz.grad) 99 | #print(bar2.grad, baz2.grad) 100 | 101 | 102 | #print("Maximum backprop difference for [bar, baz]:") 103 | #print(torch.max(torch.abs(bar.grad - baz.grad))) 104 | # 105 | #print("Maximum backprop difference for [bar2, baz2]:") 106 | #print(torch.max(torch.abs(bar2.grad - baz2.grad))) 107 | 108 | # print(bar - baz) 109 | --------------------------------------------------------------------------------