CUDA error when using register_buffer instead of nn.Parameter

username: yYang
cooked: <p>I’m trying to implement a Linear layer with an extra constant weight <code>weight_fb</code> to compute <code>grad_input</code> in backward pass.</p>
<p>So I implemented a <code>MyLinearFunc</code> Function similar to the one <a href="https://pytorch.org/docs/master/notes/extending.html#extending-torch-autograd" rel="nofollow noopener">here</a>. In forward function of <code>MyLinear</code> Module, return</p>
<pre><code class="lang-auto">MyLinearFunc.apply(input, self.weight, self.weight_fb, self.bias)
</code></pre>
<p>and the return of backward function in <code>MyLinearFunc</code> is</p>
<pre><code class="lang-auto">grad_input, grad_weight, None, grad_bias
</code></pre>
<p>When I initiate <code>weight_fb</code> as</p>
<pre><code class="lang-auto">self.weight_fb = nn.Parameter(torch.Tensor(out_features, in_features), requires_grad=False)
</code></pre>
<p>everything works fine.</p>
<p>But as <code>weight_fb</code> is not a learnable parameter, I thought it would be better to use</p>
<pre><code class="lang-auto">self.weight_fb =torch.Tensor(out_features, in_features)
self.register_buffer('feedback_weight', self.weight_fb)
</code></pre>
<p>But this gives <code>CUDA error: an illegal memory access was encountered</code> when using GPU.</p>
<p>Just wondering if <code>nn.Parameter</code> and <code>Tensor</code> with <code>register_buffer()</code> give the same training results, and if I did something wrong when using <code>register_buffer()</code>.</p>
<p>Any help would be appreciated!</p>

username: ptrblck
cooked: <p>Could you post a minimal code snippet to reproduce this issue?<br>
Also, are you using a non-default device (i.e. not <code>cuda:0</code>)? If so, this error might be unrelated to your usage of parameters and buffers, but might be a bug in the extensions, which we are currently debugging.</p>

username: yYang
cooked: <p>I am using a default device. Here is a code snippet:</p>
<pre><code class="lang-auto">import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Function
from torch import Tensor
import math

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)

class MyLinearFunc(Function):

    @staticmethod
    def forward(ctx, input, weight, weight_fb, bias=None):
        ctx.save_for_backward(input, weight, weight_fb, bias)
        output = input.mm(weight.t())
        if bias is not None:
            output += bias.unsqueeze(0).expand_as(output)
        return output

    @staticmethod
    def backward(ctx, grad_output):
        input, weight, weight_fb, bias = ctx.saved_tensors
        grad_input = grad_weight = grad_weight_fb = grad_bias = None

        if ctx.needs_input_grad[0]:
            grad_input = grad_output.mm(weight_fb) # feedback weight
        if ctx.needs_input_grad[1]:
            grad_weight = grad_output.t().mm(input)
        if bias is not None and ctx.needs_input_grad[3]:
            grad_bias = grad_output.sum(0)

        return grad_input, grad_weight, grad_weight_fb, grad_bias


class MyLinear(nn.Module):
    
    __constants__ = ['in_features', 'out_features']
    in_features: int
    out_features: int
    weight: Tensor

    def __init__(self, in_features: int, out_features: int, bias: bool = True) -&gt; None:
        super(MyLinear, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.weight = nn.Parameter(torch.Tensor(out_features, in_features))
        #self.weight_fb = nn.Parameter(torch.Tensor(out_features, in_features), requires_grad=False)
        self.weight_fb =torch.Tensor(out_features, in_features) # feedback weight
        self.register_buffer('feedback_weight', self.weight_fb)
        if bias:
            self.bias = nn.Parameter(torch.Tensor(out_features))
        else:
            self.register_parameter('bias', None)
        self.reset_parameters()

    def reset_parameters(self) -&gt; None:
        nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
        nn.init.kaiming_uniform_(self.weight_fb, a=math.sqrt(5)) # feedback weight
        if self.bias is not None:
            fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight)
            bound = 1 / math.sqrt(fan_in)
            nn.init.uniform_(self.bias, -bound, bound)

    def forward(self, input: Tensor) -&gt; Tensor:
        return MyLinearFunc.apply(input, self.weight, self.weight_fb, self.bias)

    def extra_repr(self) -&gt; str:
        return 'in_features={}, out_features={}, bias={}'.format(
            self.in_features, self.out_features, self.bias is not None
        )
</code></pre>
<pre><code class="lang-auto">N, D_in, H, D_out = 64, 1000, 100, 10

model = nn.Sequential(
    MyLinear(D_in, H),
    MyLinear(H, D_out)
)

loss_fn = torch.nn.MSELoss(reduction='sum')

learning_rate = 0.1
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

for t in range(3):
    print(t)
    x = torch.randn(N, D_in).to(device=device)
    y = torch.randn(N, D_out).to(device=device)
    model.to(device=device)
    # Forward pass: compute predicted y by passing x to the model.
    y_pred = model(x)
    # Compute and print loss.
    loss = loss_fn(y_pred, y)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
</code></pre>
<p>Thanks a lot!</p>

username: ptrblck
cooked: <p>Thanks for the code.<br>
<code>weight_fb</code> needs to be on the device, as it’s not an <code>nn.Parameter</code>:</p>
<pre><code class="lang-python">self.weight_fb =torch.Tensor(out_features, in_features).to(device)
</code></pre>
<p>However, the error message shouldn’t be an illegal memory access, so thanks for reporting it.</p>

username: yYang
cooked: <p>Thanks a lot for your reply! That solves the problem.</p>
<p>I thought <code>register_buffer</code> makes <code>weight_fb</code> carried to the device when the network is carried to the device. So <code>register_buffer</code> only makes <code>weight_fb</code> appeared in <code>state_dict</code> and can be saved? Does that mean I don’t need to register it if I don’t care about its value?</p>

username: ptrblck
cooked: <p>The <code>feedback_weight</code> buffer will be registered and pushed to the device.<br>
However, you are not using it (via <code>self.feedback_weight</code>), but instead <code>self.weight_fb</code>, which is not the buffer.</p>

username: yYang
cooked: <p>I see. So instead of</p>
<pre><code class="lang-auto">self.weight_fb =torch.Tensor(out_features, in_features).to(device)
self.register_buffer('feedback_weight', self.weight_fb)
</code></pre>
<p>where <code>self.feedback_weight</code> is not actually used,</p>
<p>I can directly do</p>
<pre><code class="lang-auto">self.register_buffer('weight_fb', torch.Tensor(out_features, in_features))
</code></pre>
<p>Does that sound correct?</p>

username: ptrblck
cooked: <p>Yes, the second approach looks good. In the <code>forward</code>, you could still use <code>self.weight_fb</code> using this approach.</p>