pytorch / tutorials

PyTorch tutorials.
https://pytorch.org/tutorials/
BSD 3-Clause "New" or "Revised" License
8.22k stars 4.07k forks source link

Neural style transfer tutorial requires_grad_ error #1736

Closed chacorp closed 1 year ago

chacorp commented 3 years ago

Hi, thanks for the all those easy tutorials!

recently i've run the tutorial codes for Neural style transfer and got an error like this

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-32-e24e09205fd4> in <module>()
      1 output = run_style_transfer(cnn, cnn_normalization_mean, cnn_normalization_std,
----> 2                             content_img, style_img, input_img)
      3 
      4 plt.figure()
      5 imshow(output, title='Output Image')

<ipython-input-31-3ee3a2602483> in run_style_transfer(cnn, normalization_mean, normalization_std, content_img, style_img, input_img, num_steps, style_weight, content_weight)
     10     # update all the requires_grad fields accordingly
     11     input_img.requires_grad_(True)
---> 12     model.requires_grad_(False)
     13    

~/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py in __getattr__(self, name)
    533                 return modules[name]
    534         raise AttributeError("'{}' object has no attribute '{}'".format(
--> 535             type(self).__name__, name))
    536 
    537     def __setattr__(self, name, value):

AttributeError: 'Sequential' object has no attribute 'requires_grad_'

Since it was optimizing the input not the model, I changed the code "model.requiresgrad(False)" in run_style_transfer function to "model.eval()". And then it worked out fine!

i'm not sure if I changed it right, But I think this part should be modified in the code!

svekars commented 1 year ago

Link to tutorial: https://pytorch.org/tutorials/advanced/neural_style_tutorial.html

Suhas-G commented 1 year ago

/assigntome

Suhas-G commented 1 year ago

Hello, This example actually works fine. https://github.com/pytorch/pytorch/pull/22576 added the requires_grad_ function for nn.Module as well. Does it still make sense to change to model.eval() ?

Thanks