Concepts / Saving and Loading Model Weights in PyTorch

Saving and Loading Model Weights in PyTorch

The second is how the weights of a model are saved to storage and loaded back later so that training can continue instead of starting over.

  • Programming

A Model That Does Not Answer the Same Way Twice

Ask a trained language model the same question several times and you may get several different replies. That can look like a bug, but it is often a direct result of how the model chooses its words. This article covers two related ideas from the same chapter. The first is how generation settings, temperature and top-k, control how much variety appears in the text. The second is how the weights of a model are saved to storage and loaded back later so that training can continue instead of starting over. Both ideas come down to controlling what survives between runs and how the next step is chosen.

Text Generation Is a Choice Among Candidates

A trained language model does not simply hand back one fixed reply. At each step it weighs many possible next tokens, and how it picks among them determines what text comes out. If the choice is always the single most likely token, the output is predictable. If the choice is drawn at random from the candidates, the same prompt can produce a different result each time.

Two settings give you a practical handle on this behavior: temperature and top-k. Both are used to control the randomness of text generation. It helps to treat them as dials you can turn and observe, rather than as fixed rules. Both act on the choice of the next token, but they limit or reshape that choice in different ways.

Temperature and Top-k as Two Dials

The two dials are easiest to understand side by side. Each one changes the candidate pool or the weighting of candidates for the next token, and each one tends to change the variety of the output in its own way. The comparison below summarizes the difference, and it is worth keeping in mind as you read the rest of the article.

How the Two Dials Act on One Choice

The diagram below places the steps of a single token choice in order. Read it left to right. Top-k first narrows the set of candidate tokens. Temperature then reshapes how the remaining candidates are weighted. Finally one token is chosen, either as the most likely candidate or by drawing at random. This is a conceptual picture of how the two dials relate to one choice, so focus on how each step passes its result forward.

Candidate nexttokensmany possible continuationsTop-k limitnarrows the candidate poolTemperature reshapingchanges how spread out thechoice isChosen tokenmost likely, or drawn atrandomlimit to top-kreshape remainingpick one
Which dial acts first on the candidates, and how does each step pass its result on until one token is chosen?

Because the two dials act on the same choice in different ways, setting both low and setting both high can produce noticeably different styles of text. A low setting on both narrows the candidates and makes the output steadier. A high setting on both widens the candidates and makes the output more varied. Mixed settings produce styles between these extremes.

Lower Versus Higher Settings in Practice

SettingLower value tends toHigher value tends to
TemperatureProduce more consistent outputAllow more variety in the output
Top-kKeep the candidate pool narrow and the output close to the strongest optionsWiden the candidate pool and allow more varied tokens

How lower and higher values of each setting tend to affect generated text

The right choice depends on what you want the text to do. A steady answer, where you want the same kind of reply each time, is usually better served by lower settings. A varied brainstorm, where you want many different ideas from the same prompt, is usually better served by higher settings. Notice that these are guidelines to test, not fixed rules.

EASY

Pick one prompt and two goals: a steady answer and a varied brainstorm. For each goal, decide whether a lower or higher temperature and a smaller or larger top-k would serve it better. Write these choices down before you run anything.

Hints
  • Think about whether the goal values repeatability or variety.
  • Lower settings narrow the choice, while higher settings widen it.

Forcing Deterministic Output from generate

Sometimes you want the opposite of variety. The same input should always produce the same output. This is called deterministic behavior: the output is always the same given the same input. Lower temperature and top-k settings make output more consistent, but consistency is not the same as determinism. Determinism is achieved by changing how the generate function selects tokens.

The key idea is disabling random sampling. When random sampling is turned off, the generate function always selects the same tokens for the same input and produces the same outputs. The source describes this as similar to the generate_simple function used earlier in the chapter, which also selects tokens without drawing them at random.

Key point

Deterministic output comes from disabling random sampling in the generate function. Temperature and top-k control how random the sampling is, so they do not guarantee repeatable text on their own.

Why Saving Weights Matters

Saving model weights means storing the learned values of a model so that they can be used later. Training a large language model is a long process, and a training run does not always finish in one sitting. The weights hold the progress made so far, so writing them to storage lets that progress survive after the session ends.

The reason the chapter pauses to save weights comes down to cost. Pretraining an LLM is computationally expensive, and even with a relatively small model and dataset, the chapter's exercise made this clear. Saving the model means you do not have to rerun training every time you want to use it in a new session, and the same saved weights can be used to continue training later.

The chapter also looks ahead. It will later load a more capable pretrained GPT model from OpenAI into the GPTModel instance. The save and load functions built here are the bridge between the model trained in this chapter and that later model.

Tracing Weights Across a Save and a Load

Follow one set of weights through a full cycle. Start with a model whose weights have been trained for some time. Saving writes the current weights to storage, so a copy of that learned state now exists in a file. The model in memory and the file are two separate places holding the same learned values at the moment of the save.

Later, in a new session, the saved weights are read back in. Loading is the reverse of saving: the stored weights are restored into the model, so it starts from that saved state rather than from scratch. Training can now carry on from where it left off. The diagram traces this movement, with the changed states marking what the save and load produce.

Trained weights inmemoryprogress from earliertrainingSaved weights instoragestored learned valuesLoaded weights inmodelrestored saved stateTraining continuespicks up from the savedstatesave writesload readsresume
What is the state of the weights before saving, in the saved file, and after loading, and when does training pick up from there?

Loading Only Means Something With a Save

Saving and loading are used together to continue training an LLM rather than starting over. Because they are a pair, each one depends on the other to be useful. A save without a later load stores the progress but does not put it back to work. A load is only meaningful when there is a saved set of weights to restore.

Mistakes That Make a Resumed Run Start Over

  • Common mistake

    Saving the weights but never loading them in the next session

    What it looks like

    Training runs, the weights are written to storage, and then the next session builds a fresh model and trains as if nothing had been saved.

    Why it fails

    A save stores progress but does not put it back to work. Without a load, the new session does not use the saved state.

    Do this instead

    Load the saved weights into the model before continuing, so training picks up from the stored state.

  • Common mistake

    Attempting to load when no saved weights exist

    What it looks like

    A new session tries to restore weights from a location where no save was ever made.

    Why it fails

    A load only has meaning when there is a saved set of weights to restore.

    Do this instead

    Confirm that a save happened and that the stored weights are available before loading.

  • Common mistake

    Expecting lower temperature alone to make output repeatable

    What it looks like

    A steady setting is used, and the author assumes two runs will match word for word.

    Why it fails

    Lower settings tend to produce more consistent output, but deterministic output comes from disabling random sampling in the generate function.

    Do this instead

    Disable random sampling in the generate function if the same input must always give the same output.

Predict Before You Run

MEDIUM

Before running any generation experiment, write a guess. Choose one prompt and one goal, such as a steady answer or a varied brainstorm. Predict whether a lower or higher temperature will serve that goal better, and whether a smaller or larger top-k will change the variety you see. Then run generation several times at each setting and compare what you observe with your prediction.

Hints
  • Compare the spread of replies across several runs, not just one.
  • Then test deterministic output by disabling random sampling and checking whether repeated runs match.

Key Takeaways

  • Temperature and top-k are dials that control the randomness of text generation. Lower settings tend to produce more consistent output, while higher settings allow more variety.
  • The right setting depends on the application: steady answers favor lower values, and varied brainstorms favor higher values.
  • Deterministic output, where the same input always gives the same result, comes from disabling random sampling in the generate function.
  • Saving model weights stores learned values so they can be used later, avoiding rerunning expensive pretraining in every session.
  • Loading restores saved weights so the model starts from that state, and saving and loading are used together to continue training rather than starting over.

Related concepts

More concepts starting with S