NameError: name 'args' is not defined when I load mode follow the saving and loading model tutorial

I followed the saving and loading models tutorial using Jupiter notebook.
https://pytorch.org/tutorials/beginner/saving_loading_models.html

But there is error

35 print(var_name, “\t”, optimizer.state_dict()[var_name])
36 torch.save(model.state_dict(), PATH)
—> 37 model = TheModelClass(*args, **kwargs)
38 model.load_state_dict(torch.load(PATH))
39 model.eval()

NameError: name ‘args’ is not defined

First, Please properly indent your code with ```. Eg

>>> import code from code
>>> code.magic()
magggggiicccc

Coming to your question,
Since there are no args or kwargs to pass, just do it like

model = TheModelClass()

It will work fine.


@ptrblck I don’t think we need to the *args and *kwargs as there are none. Right? Or I am missing something? I can make a PR to fix it if that’s the case.

I think the code snippets use *args and **kwargs just to demonstrate that you should pass all necessary arguments to the model and optimizer.
If that’s confusing, maybe a short note in the text saying that you should adapt the arguments to your use case would be nice. What do you think?

2 Likes

True. I agree with you.
But it might be confusing for beginners (in python) / someone who is just following along the tutorial.

May be

# Pass all parameters required while initializing the model here.
model = TheModelClass()

or we can just

# Modify the arguments passed to the model as needed.
model = TheModelClass(*args, **kwargs)

Let me know.


Also, I just went to the Colab notebook to make sure that everything works in Colab.
But I saw, there are no code cells at all!!!

Here: Colab Notebook
Here is the Github notebook: Github Notebook
??!

This tutorial looks as if it’s not supposed to be executable without modifications (e.g. PATH seems also to be undefined).

CC @MatthewInkawhich who wrote this tutorial.

@ptrblck is correct. This “tutorial” is meant to be a centralized reference document. It was NOT intended to be executed as-is. Variables in the text such as args and PATH are simply placeholders.

If that’s the case, I think it should be updated to be executed with appropriate comments. As beginners in PyTorch can hugely benefit from these. What do you think? @ptrblck @MatthewInkawhich

2 Likes