Param-=alpha*param.grad

bhartpence: <p>Hello all,<br>
I have several models that quit working after an update (I think that was the catalyst) - all of the models are CNN and MLP based with code that is very similar to the examples on the site - just different sizes and shapes for layers and different optimizers… For some reason, all of them started failing with the same error:</p>
<p>unsupported operand type(s) for *: ‘float’ and ‘NoneType’</p>
<p>So, it looks like param.grad is None which previously worked fine but now I am getting the error. I recently did a system upgrade that included moving to Python 3.8.5. Before I go tarzaning around my models I thought I would ask you all about it.</p>
<p>Thanks</p>

ptrblck: <p>I haven’t seen this error popping up after a specific PyTorch update.<br>
The optimizer should also skip all gradients with a <code>None</code> value, so I assume the error is not raised by the optimizer.</p>

bhartpence: <p>Thanks for getting back. It is a little weird - I have dozens of models all running the same datasets and have never had a problem with it before. I even have ensembles of models with not prior problem. I am trying not to tunnel vision but the updates were substantial - system, applications, Python, etc.</p>
<p>So, if it is NOT the updates, any suggestions on where to look? Just for fun, here is a code snippet:</p>
<pre><code>for epoch in range(epochs):
    for i, data in enumerate(train_loader,1):
        inputs, targets = data
        
        if use_cuda:             #Use this for all other optimizers
            y_pred=net_model(inputs)
            loss=loss_fn(y_pred, targets)
            time=str(datetime.now())  
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()                   
        with torch.no_grad():
            counter=0
            for param in net_model.parameters():
                param-=alpha*param.grad

    loss_array[epoch]=loss.item()    #Un-comment these 6 lines if NOT using LBFGS
    if epoch%100==0:
        print(datetime.now(),"Loss for epoch:", epoch, loss.item())
    if loss.item() &lt; 1e-8:
        print(datetime.now(),"Loss for epoch:", epoch, loss.item())
        break</code></pre>

bhartpence: <p>Minor update - I ran models without specifying an optimizer and I get the same error.</p>

ptrblck: <p>I’m unsure why you are manipulating the parameters manually, if your are already using an optimizer, but this would at least explain why this operation could fail (as said before, the optimizer would just skip it).</p>
<p>Your code snippet works using this simple example:</p>
<pre><code class="lang-python">net_model = nn.Linear(1, 1)
loss_fn = nn.MSELoss()
inputs = torch.randn(1, 1)
targets = torch.randn(1, 1)

optimizer = torch.optim.SGD(net_model.parameters(), lr=1e-3)

y_pred=net_model(inputs)
loss=loss_fn(y_pred, targets)

optimizer.zero_grad()
loss.backward()
optimizer.step()
alpha = 0.1         
with torch.no_grad():
    counter=0
    for param in net_model.parameters():
        param-=alpha*param.grad
</code></pre>
<p>so could you post an executable code snippet to debug the issue?</p>

bhartpence: <p>Well, OK. First let me say that I appreciate your help with this. Second - I got it working. What the update did was kill my CUDA install. Looking at the code I realized that I had “if use_cuda” but not an else statement because I was lazy.</p>
<p>But, your comment about individual parameters has me wondering if I am doing this the best way. So here is the current working code.</p>
<p>use_cuda=torch.cuda.is_available()<br>
device=torch.device(“cuda:0” if use_cuda else “cpu”)<br>
x=X_train<br>
print(“Shape of x”,x.size())<br>
y=Y_labels<br>
print(“Shape of y”,y.size())<br>
print()<br>
loss_array=torch.zeros(epochs,1)<br>
tick=datetime.now()</p>
<p>loss_fn=torch.nn.MSELoss(reduction=‘sum’)<br>
optimizer=torch.optim.Adadelta(net_model.parameters(),lr=1.0,rho=0.9,eps=1e-06,weight_decay=0)</p>
<pre><code>for epoch in range(epochs):
    for i, data in enumerate(train_loader,1):
        inputs, targets = data
        #print(inputs.size(), targets.size())
        #print(epoch, i, data[1])
        
        if use_cuda:             #Use this for all other optimizers
            #print("CUDAing")
            y_pred=net_model(inputs)
            loss=loss_fn(y_pred, targets)
            time=str(datetime.now())  
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            #print('Here')
        else:
            #print("NOT CUDAing")
            y_pred=net_model(inputs)
            loss=loss_fn(y_pred, targets)
            time=str(datetime.now())  
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            #print('Here')                
            
        with torch.no_grad():
            #counter=0
            for param in net_model.parameters():
                param-=alpha*param.grad

    loss_array[epoch]=loss.item()    #Un-comment these 6 lines if NOT using LBFGS
    if epoch%100==0:
        print(datetime.now(),"Loss for epoch:", epoch, loss.item())
    if loss.item() &lt; 1e-8:
        print(datetime.now(),"Loss for epoch:", epoch, loss.item())
        break
</code></pre>
<p>Thanks again.</p>

ptrblck: <p>I’m not familiar with your use case, but the <code>optimizer</code> would already update all passed parameters in the <code>optimizer.step()</code> method. You are currently subtracting the <code>alpha*grad</code> again from each parameter even after the parameters were already updated.<br>
Could you explain your use case a bit more, as I might misunderstand it?</p>

bhartpence: <p>You are being very kind <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=9" title=":slight_smile:" class="emoji" alt=":slight_smile:"> I think we have an artifact of an earlier build. Before I discovered pytorch, I used to do things by manually coding everything and so this probably something I simply didn’t take out or simply forgot about. Been so focused on what we could get done I may have lost sight of some basic principles. Time to RTFM and I guess I know what I am doing with the other models…</p>
<p>I ran the current model without the lines you were wondering about and it seems to run fine.</p>
<p>BTW, the application deals with packet traffic on communication networks and seeing what we can do with machine learning to solve some problems.</p>
<p>And again, I appreciate the time and the clarity - if you are ever heading to Rochester I’d love to buy you a beer or coffee by way of thanks.</p>
<p>Bruce</p>

ptrblck: <aside class="quote no-group" data-username="bhartpence" data-post="8" data-topic="106373">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/b/e495f1/48.png" class="avatar"> bhartpence:</div>
<blockquote>
<p>And again, I appreciate the time and the clarity - if you are ever heading to Rochester I’d love to buy you a beer or coffee by way of thanks.</p>
</blockquote>
</aside>
<p>Ha, thanks! I’ll let you know once I’m in the area. <img src="https://discuss.pytorch.org/images/emoji/apple/wink.png?v=12" title=":wink:" class="emoji" alt=":wink:" loading="lazy" width="20" height="20"></p>