Concepts / Loading a Saved PyTorch Model

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.

  • Programming

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.

python
Notes on the code
  • model.state_dict() produces the state dictionary taken from the model
  • file_name is 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.

modelholds the learned valuesstate dictionaryfrom model.state_dict()torch.savewrites the data outgpt2-medium355M-sft.pththe .pth file on disktorch.loadreads the file backsaved statedictionaryreturned by torch.loadload_state_dictcopies values into a modelmodelreceives the saved valuesstate_dict()first argumentnamed by file_namesame file namereturnsargumentapplies values
Where do the values go when torch.save runs, and how do they travel back into a model when torch.load and load_state_dict run?

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.

first namea key in the dictionarysecond nameanother key in thedictionarystored valuesthe value that key pointstostored valuesthe value that key pointstopoints topoints to
What does model.state_dict() contain, and how does each saved name point to a specific stored tensor?

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.

python
Output (expected)
gpt2-medium355M-sft.pth
Notes on the code
  • re.sub removes 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
Worked example

Tracing the file name for a new model name

Predict the file name produced when CHOOSE_MODEL is set to 'My Model (v2)'.

  1. 1
    Start with the model name

    The string is My Model (v2). It contains two spaces, one opening parenthesis, and one closing parenthesis.

  2. 2
    Apply the pattern [ ()]

    Every space and both parentheses match the pattern, so they are removed. The letters, digits, and any other characters remain, giving MyModelv2.

  3. 3
    Append the suffix

    Adding -sft.pth gives MyModelv2-sft.pth.

  4. 4
    Check the result

    The file name has no spaces or parentheses, and it ends with the .pth extension that torch.save writes.

Result

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.

python
Notes on the code
  • 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 like

    Saving to gpt2-medium355M-sft.pth but loading from gpt2-medium-355M-sft.pth

    Why it fails

    The 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 instead

    Keep 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 like

    Calling torch.save with an empty or missing file_name

    Why it fails

    The 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 instead

    Always 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 like
    Calling model.load_state_dict("gpt2-medium355M-sft.pth")
    Why it fails

    load_state_dict expects a state dictionary as its argument, not a file name. The file must first be read by torch.load.

    Do this instead
    Pass 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.

Build file_namere.sub, then -sft.pthtorch.savewrites the .pth fileSame name in load?compare the two stringstorch.loadreads the file backload_state_dictapplies values to modelInspect the mismatchthe name differs from thesaved onefile_namefile on diskyesnostate dictionary
In the sequence of save and load steps, which step is the failing one, and how does a learner trace an error back to that line?

Practice Tracing the Round Trip

MEDIUM

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.sub and 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.

Related concepts

More concepts starting with L