Is it possible to modify the low level convolution operation?

NagisaKaworuAdam: <p>I’m new to PyTorch low level stuff.</p>
<ol>
<li>When using nn.Conv2d, I guess, there should be some low level CUDA code for doing the real convolution operations, right? Where to find them in the PyTorch or somewhere else?</li>
<li>I have implemented some optimized convolution operations in CUDA (C++) and I am trying to replace my code into the original PyTorch and recompile the PyTorch, if this is possible, what is the correct step by step workflow for this?</li>
</ol>
<p>Thank you for your time and your help would be greatly appreciated!</p>

ptrblck: <ol>
<li>
<p>It depends on the device and thus backend you are using. E.g. if you are using a GPU you could find the native convolution in <a href="https://github.com/pytorch/pytorch/blob/35d4a805ebc3b6eca1bafb2d332dffa8d0c1fc54/aten/src/ATen/native/cuda/ConvolutionMM2d.cu"><code>aten/stc/ATen/native/cuda/ConvolutionMM2d.cu</code></a> and could adapt it. cuDNN is used by default for better performance, but since it’s closed source you won’t be able to take a look at their code and manipulate it.</p>
</li>
<li>
<p>Either change the definition in the linked file or create a custom extension, which might be easier.</p>
</li>
</ol>

NagisaKaworuAdam: <p>Thank you for your reply!<br>
Yes, I am using a GPU, so I looked through that linked file (ConvolutionMM2d.cu).</p>
<ol>
<li>In it, I found <strong>slow_conv2d_forward</strong> function which contains <strong>at::cuda::blas::gemm</strong> at the end. I think this is the place where convolution is done by CUDNN, right?</li>
<li>I implemented my fast convolution code by following the standard Visual Studio CUDA template (Prepare input data, prepare device memory, copy to device, invoke convolution operation kernel, then copy data back, etc.).<br>
And I think my kernel functions (__ global __ void fasterConv) are correct and they are controlling the GPU hardware at a low level.<br>
So, could you please elaborate the way to merge my kernel code into PyTorch to achieve faster convolution? In my case, is this the correct tutorial for creating a <a href="https://pytorch.org/tutorials/advanced/cpp_extension.html" rel="noopener nofollow ugc">custom extension</a>? Or maybe I can just copy my kernel code to somewhere and fix the type errors and other minor errors.</li>
</ol>
<p>My questions are pretty long, thank you for your patience and your time!</p>

ptrblck: <ol>
<li>
<p>No, the <code>matmul</code> approach via <code>cublas</code> is the native implementation in PyTorch and cuDNN is closed source as described before. The cuDNN calls are performed <a href="https://github.com/pytorch/pytorch/blob/fdc419786df8a6d86edf8c82b07bf4e9b8b551d0/aten/src/ATen/native/cudnn/Conv_v7.cpp">here</a> for the v7 API and <a href="https://github.com/pytorch/pytorch/blob/fdc419786df8a6d86edf8c82b07bf4e9b8b551d0/aten/src/ATen/native/cudnn/Conv_v8.cpp">here</a> for the newer v8 API.</p>
</li>
<li>
<p>Yes, a custom extension should work.</p>
</li>
</ol>

NagisaKaworuAdam: <p>Great! Thank you for your reply!<br>
More accurately, my project is optimizing depthwise and pointwise convolution operations for mobilenets. So, my question should be: how are these operations implemented in the original pytorch in the backend? Where are the code for them? Can I replace my depthwise and pointwise convolution kernels to those places?<br>
I had a look at the link for custom extension. It’s kind of creating a new module, which needs forward pass and backward pass. But for now, I only implemented the optimized forward pass code. Is there any existed code for the backward pass for depthwise and pointwise convolution that I can use directly? or maybe other easy ways to implement the backward pass for the custom extension module?<br>
Thank you so much!</p>

ptrblck: <aside class="quote no-group" data-username="NagisaKaworuAdam" data-post="5" data-topic="164775">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/nagisakaworuadam/48/49232_2.png" class="avatar"> NagisaKaworuAdam:</div>
<blockquote>
<p>So, my question should be: how are these operations implemented in the original pytorch in the backend?</p>
</blockquote>
</aside>
<p>As explained before, PyTorch uses native (slow) kernels as well as optimized kernels from e.g. cuDNN (and other libs for other backends). You can use the first posted link to check for different conv implementations, e.g. <a href="https://github.com/pytorch/pytorch/blob/35d4a805ebc3b6eca1bafb2d332dffa8d0c1fc54/aten/src/ATen/native/cuda/DepthwiseConv2d.cu"><code>DepthwiseConv2d.cu</code></a> should contain the native (slow) code for depthwise convs.</p>
<aside class="quote no-group" data-username="NagisaKaworuAdam" data-post="5" data-topic="164775">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/nagisakaworuadam/48/49232_2.png" class="avatar"> NagisaKaworuAdam:</div>
<blockquote>
<p>Is there any existed code for the backward pass for depthwise and pointwise convolution that I can use directly?</p>
</blockquote>
</aside>
<p>Yes, you should be able to find the <code>backward</code> in the linked code and could reuse it.</p>

NagisaKaworuAdam: <p>Hello! My project got some progress. I created my optimized depthwise convolution extension. The forward pass is working well, my forward pass time is faster than nn.conv2d() forward time.<br>
But I am still stuck at the backward pass part.<br>
I initially used pytorch native backward implementation in DepthwiseConv2d.cu, and it worked, but slow, compared to the backward pass time of nn.conv2d. Then I tried:</p>
<ol>
<li>
<a href="https://github.com/jordan-g/PyTorch-cuDNN-Convolution" rel="noopener nofollow ugc">cudnn convolution</a>, but got error that <code>cudnn_convolution_backward_weight</code> and <code>cudnn_convolution_backward_input</code> are not members of ‘at’, because my pytorch is 1.12.</li>
<li>then I found <a href="https://discuss.pytorch.org/t/at-has-no-member-cudnn-convolution-xxx/163716" class="inline-onebox">"at" has no member "cudnn_convolution_xxx"</a>, and tried at::convolution_backward(), but it seems that it is still slow compared to nn.conv2d().</li>
<li>then I tried to use <code>at::cudnn_convolution_backward</code> at <a href="https://github.com/pytorch/pytorch/blob/main/aten/src/ATen/native/cudnn/ConvShared.cpp" class="inline-onebox" rel="noopener nofollow ugc">pytorch/ConvShared.cpp at main · pytorch/pytorch · GitHub</a>, but got “not a member of ‘at’” error.</li>
</ol>
<p>I am not sure how to set up the backward pass code with cudnn. Could you please tell me a little bit more about how to use cudnn convolution backward? Thank you!</p>
<p>And here is the code:</p>
<pre><code class="lang-auto">#include &lt;torch/extension.h&gt;
#include &lt;vector&gt;
#include &lt;ATen/NativeFunctions.h&gt;
#include &lt;ATen/Functions.h&gt;
#include &lt;ATen/Config.h&gt;

// CUDA backward declarations

std::tuple&lt;at::Tensor, at::Tensor&gt; optimizedDepthwise_backward(
    const at::Tensor&amp; grad_output, 
    const at::Tensor&amp; input, 
    const at::Tensor&amp; weight,
    int64_t padding, 
    int64_t stride, 
    int64_t dilation, 
    int64_t groups,
    bool benchmark, 
    bool deterministic, 
    bool allow_tf32, 
    std::array&lt;bool,2&gt; output_mask);

std::tuple&lt;at::Tensor, at::Tensor&gt; optimizedDepthwise_backward(
  const at::Tensor&amp; grad_output, 
  const at::Tensor&amp; input, 
  const at::Tensor&amp; weight,
  int64_t padding, 
  int64_t stride, 
  int64_t dilation, 
  int64_t groups,
  bool benchmark, 
  bool deterministic, 
  bool allow_tf32, 
  std::array&lt;bool,2&gt; output_mask){

    return at::cudnn_convolution_backward(
        input,
        grad_output, 
        weight,
        padding,
        stride,
        dilation,
        groups,
        benchmark,
        deterministic,
        output_mask);
}</code></pre>

ptrblck: <p><code>at::convolution_backward</code> should be the right approach.</p>

NagisaKaworuAdam: <p>Thank you! I see… Then, I guess, my convolution backward pass should have comparable performance to nn.conv2d, right? But that’s not the case for me. Do you have any hint on this? My forward kernels have no effect on the backward pass. And I do have CUDA compatible GPU on the backend, is it possible that for some reason, at::convolution_backward didn’t use cuDNN? How can I check this?</p>

ptrblck: <p>It might be possible that native kernels are used and you could check it by profiling your actual workload to see if cuDNN is used or not. To do so you could use the built-in profiler or e.g. Nsight Systems.</p>

NagisaKaworuAdam: <p>Thank you for your help! I used PyTorch profiler to profile both of my convolution module and the nn.conv2d.</p>
<p>It shows that, during the <code>.backward()</code>:</p>
<ul>
<li>
<p>nn.conv2d called <code>at::native::(anonymous namespace)::conv_depthwi...</code> <strong>once</strong></p>
</li>
<li>
<p>my module called above function <strong>twice</strong>.</p>
</li>
</ul>
<p>I think the reason is that my module is calcualting “input_grad” and “weight_grad” as shown here:</p>
<pre><code class="lang-auto">def backward(ctx, grad_output):
        input, filter = ctx.saved_tensors
        conf = ctx.conf
        output = optimizedDepthwise_cuda.backward(grad_output, input, filter, conf["stride"],
conf["padding"], conf["dilation"], False, 0, conf["groups"], [True, True, False])
        input_grad, weight_grad, _ = output
        return input_grad, weight_grad, None, None, None, None, None
</code></pre>
<p>So my new questions are:</p>
<ul>
<li>Does nn.conv2d calculate input_grad or weight_grad? or both?</li>
<li>Should I calculate both of them for the correct backward pass?</li>
</ul>
<p>I just followed some tutorials to finish the backward call, and they calculated both input_grad and weight_grad, but I’m not sure if they are correct.</p>
<p>Thank you so much! Your help is highly appreciated!!!</p>

NagisaKaworuAdam: <p>Seems that this should be the correct solution:</p>
<p>To implement my optimized module in python:</p>
<pre><code class="lang-auto">class optimizedDepthwiseFunction(torch.autograd.Function):
    @staticmethod
    def forward(ctx, input, filter, filterHeight, stride, padding, dilation, groups):
        ctx.save_for_backward(input, filter)
        ctx.conf = {
            "filterHeight": filterHeight,
            "stride": stride,
            "padding": padding,
            "dilation": dilation,
            "groups": groups
        }

        output = optimizedDepthwise_cuda.forward(input, filter, filterHeight, stride)
        return output

    @staticmethod
    def backward(ctx, grad_output):
        input, filter = ctx.saved_tensors

        conf = ctx.conf
        grad_input = grad_weight = None

        if ctx.needs_input_grad[0]:
            input_ = grad_output.new_empty(1).expand(input.shape)
            grad_input = torch.ops.aten.convolution_backward(grad_output, input_, filter, None,
                                               (conf["stride"], conf["stride"]), (conf["padding"], conf["padding"]), (conf["dilation"], conf["dilation"]),
                                               False, [0], conf["groups"], (True, False, False))[0]
        
        if ctx.needs_input_grad[1]:
            filter_ = grad_output.new_empty(1).expand(filter.shape)
            grad_weight = torch.ops.aten.convolution_backward(grad_output, input, filter_, None,
                                               (conf["stride"], conf["stride"]), (conf["padding"], conf["padding"]), (conf["dilation"], conf["dilation"]),
                                               False, [0], conf["groups"], (False, True, False))[1]
        
        return grad_input, grad_weight, None, None, None, None, None
</code></pre>
<pre><code class="lang-auto">class optimizedDepthwiseLayer(torch.nn.Module):
    def __init__(self, inputChannel, outputChannel, filterHeight, stride):
        super(optimizedDepthwiseLayer, self).__init__()
        self.inputChannel = inputChannel
        self.outputChannel = outputChannel
        self.filterHeight = filterHeight
        self.stride = stride
        if(self.filterHeight == 3):
            self.padding = 1
        elif(self.filterHeight == 5):
            self.padding = 2
        self.dilation = 1
        self.groups = inputChannel
        
        self.filter = torch.nn.Parameter(torch.empty((self.inputChannel, 1, self.filterHeight, self.filterHeight), dtype=torch.float))
        self.reset_parameters()

    def reset_parameters(self):
        stdv = 1.0 / math.sqrt(self.inputChannel * self.filterHeight * self.filterHeight)
        for weight in self.parameters():
            weight.data.uniform_(-stdv, +stdv)

    def forward(self, input):
        return optimizedDepthwiseFunction.apply(
            input, 
            self.filter, 
            self.filterHeight,
            self.stride,
            self.padding,
            self.dilation,
            self.groups)
</code></pre>
<p>And I acutually do not need at::convolution_backward in the cpp file, because I can directly use <code>torch.ops.aten.convolution_backward</code> in my python module.</p>
<pre><code class="lang-auto">#include &lt;torch/extension.h&gt;
#include &lt;vector&gt;
#include &lt;array&gt;

#define CHECK_CUDA(x) TORCH_CHECK(x.device().is_cuda(), #x " must be a CUDA tensor")
#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)

torch::Tensor optimizedDepthwise_cuda_forward(
  torch::Tensor input, 
  torch::Tensor filter,
  int filterHeight,
  int stride);

torch::Tensor optimizedDepthwise_forward(
    torch::Tensor input,
    torch::Tensor filter,
    int filterHeight,
    int stride) {
    
    CHECK_INPUT(input);
    CHECK_INPUT(filter);

    return optimizedDepthwise_cuda_forward(
      input,
      filter,
      filterHeight,
      stride);
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
  m.def("forward", &amp;optimizedDepthwise_forward, "Optimized Depthwise forward (CUDA)");
}
</code></pre>
<p>Could you please help me to double check if my implementation logic contains any mistake? Thank you!</p>

ptrblck: <p>Your code looks good. One minor suggestion: don’t use the deprecated <code>.data</code> attribute but initialize the parameter in a <code>with torch.no_grad()</code> guard using methods from the <code>torch.nn.init</code> namespace.</p>

NagisaKaworuAdam: <p>Thank you! It worked! The layers can be placed into the model and it is running correctly!<br>
But now, I got another problem. I am trying to run my code on a ROCm device, and it seems that my backward part of the custom extension is wrong. It’s not calculating correctly…<br>
Could you please tell me which one of the following options is the right one? for <strong>PyTorch 1.10+rocm</strong></p>
<ol>
<li>in the python backward static function: call <code>torch.ops.aten.miopen_depthwise_convolution_backward</code> (I thought this is for depthwise convolution backward)</li>
<li>in the python backward static function: call <code>torch.ops.aten.miopen_convolution_backward</code>
</li>
<li>in the extension cpp file, use <code>aten::miopen_depthwise_convolution_backward_weight</code> and <code>aten::miopen_depthwise_convolution_backward_input</code>.</li>
</ol>
<p>Is there a correct method for doing backward on a rocm device?</p>

ptrblck: <p>Sorry, I’m not familiar with ROCm and MIOpen, but the function names look correct (1 and 3).</p>