Loading a Saved PyTorch Model
torch.save(model.state_dict(), file_name) writes a model's state dictionary to a .pth file, so the fine-tuned model can be reused later.
Why Learned Values Need a File
After a model has been fine-tuned, the values it has learned exist only while the program is running. When the program ends, those values are gone unless they were written to a file. Saving is therefore the final step of the fine-tuning workflow: the fine-tuned model is stored on disk so it can be reused in future projects, and later loaded back into a program.
This article follows the saving and loading path one line at a time. As you read, pay attention to which value each line produces before the next line uses it. Most save and load problems come from a value produced on one line that does not match what a later line expects.
Saving the State Dictionary
The saving work happens in one call: torch.save(model.state_dict(), file_name). The first argument is model.state_dict(), which gives the model's state dictionary. The second argument is file_name, a string that names the file on disk. The model is saved as a .pth file.
model.state_dict()produces the state dictionary taken from the modelfile_nameis a string that names the file on disk- torch.save writes the state dictionary to that file as a .pth file
The file name is computed on the line before the save, so the name is fixed before torch.save runs. The save call does not decide where the output goes on its own; the file name alone determines the destination. This is why a wrong file name produces a file with the wrong name rather than a missing save.
What a State Dictionary Contains
The saved object is the state dictionary, not the whole program. Calling model.state_dict() gives a dictionary-style collection of the model's stored values. Each entry in this collection is associated with a name, and that name points to one stored value. Loading later depends on those names, which is why the saved structure must be recovered in the same form.
Building the File Name from a Model Name
The file name is not typed by hand. It is generated from the chosen model name. The code takes CHOOSE_MODEL, removes every space, opening parenthesis, and closing parenthesis using re.sub with the pattern [ ()], and then appends the suffix -sft.pth. The result is a name such as gpt2-medium355M-sft.pth.
gpt2-medium355M-sft.pthre.subremoves every character that matches the class [ ()], which is a space, an opening parenthesis, or a closing parenthesis- Hyphens and digits are not in the class, so they are kept
- The suffix -sft.pth is appended after the cleaning step
Tracing the file name for a new model name
Predict the file name produced when CHOOSE_MODEL is set to 'My Model (v2)'.
- 1Start with the model name
The string is My Model (v2). It contains two spaces, one opening parenthesis, and one closing parenthesis.
- 2Apply the pattern [ ()]
Every space and both parentheses match the pattern, so they are removed. The letters, digits, and any other characters remain, giving MyModelv2.
- 3Append the suffix
Adding -sft.pth gives MyModelv2-sft.pth.
- 4Check the result
The file name has no spaces or parentheses, and it ends with the .pth extension that torch.save writes.
The file is named MyModelv2-sft.pth.
Reading Values Back with torch.load
Loading runs in the opposite direction to saving. The file is read by torch.load, the resulting state dictionary is passed to load_state_dict, and the model receives the saved values. The order matters: load_state_dict is called on a model object, and the argument it receives comes from torch.load.
- torch.load reads the file and returns the saved state dictionary
- model.load_state_dict copies that saved data into the model object
- The file name string must match the one produced by the save step
Read the load line from the inside out. torch.load(...) is evaluated first and produces a state dictionary. That dictionary is then passed as the argument to model.load_state_dict, which applies it to the model. The model object is the one that changes; the file itself is only read.
Mistakes That Break a Save or Load
Common mistake Retyping the file name in the load step
What it looks likeSaving to gpt2-medium355M-sft.pth but loading from gpt2-medium-355M-sft.pth
Why it failsThe two steps must use the same generated string. Any difference means the load step looks for a file name that the save step never produced.
Do this insteadKeep the name in one variable, or copy the exact generated string into the load call.
Common mistake Assuming the file name can be left out of the save
What it looks likeCalling torch.save with an empty or missing file_name
Why it failsThe second argument of torch.save is the string that names the file on disk. Without it, there is no destination for the saved state dictionary.
Do this insteadAlways compute file_name on the line before the save and pass it as the second argument.
Common mistake Expecting load_state_dict to read the file directly
What it looks likeCalling model.load_state_dict("gpt2-medium355M-sft.pth")Why it failsload_state_dictexpects a state dictionary as its argument, not a file name. The file must first be read by torch.load.Do this insteadPass the result of torch.load to load_state_dict, as in model.load_state_dict(torch.load(file_name)).Common mistake Treating the model name as the file name without the cleaning step, so spaces and parentheses end up in the file name
Locating a Failing Save or Load Step
When a save or load fails, trace the file name first, since both steps must use the same generated string. Then walk the sequence in order: the name is built, the state dictionary is passed to torch.save, the file is read by torch.load, and the result is applied by load_state_dict. The first step where the values or names stop matching is the one to inspect.
Practice Tracing the Round Trip
Set CHOOSE_MODEL to 'gpt2-small (124M)'. Work out the exact file name produced by the cleaning step and the suffix, then write the save line and the matching load line. Check that the two file name strings are identical.
Hints
- Remove every space, opening parenthesis, and closing parenthesis, but keep the hyphen and digits.
- The suffix -sft.pth is added after the cleaning step.
- The load call must use the same string as the save call.
Key Takeaways
torch.save(model.state_dict(), file_name)writes a model's state dictionary to a .pth file so the fine-tuned model can be reused later.- The file name is generated from CHOOSE_MODEL by removing spaces and parentheses with
re.suband the pattern [ ()], then appending -sft.pth, which produces names such as gpt2-medium355M-sft.pth. - Loading reverses the flow: torch.load reads the file and returns the state dictionary, and model.load_state_dict applies those saved values to a model.
- When a save or load fails, trace the file name first, because both steps must use the same generated string, and then walk the steps in order to find the first mismatch.