Concepts / Pre-Trained Models

Pre-Trained Models

Fine-tuning adjusts a pre-trained model's weights to fit a specific task, and it can either update the whole model or only selected layers.

  • Programming

Start With the Encoded Text

This article works in the opposite order from most explanations. Instead of starting with fine-tuning in the abstract, we start with a short piece of code that prepares text for a pre-trained GPT model and checks what that preparation produces. Once you can read that output, the idea of changing only some layers of the model becomes much easier to follow.

The starting point is a model that was already built and loaded in an earlier step. A new output layer has been added to it, and certain layers have been marked as trainable or nontrainable. Even after those changes, the model can still be used the same way as before: you feed it a text example and it processes that text. So the first question is simply what the text looks like after it has been prepared for the model.

What do you think happens?

The sentence is 'Do you have time'. How many tokens does it become, and what is the shape of the tensor after an extra dimension is added at position zero?

  • 3 tokens, shape (1, 3)

  • 4 tokens, shape (1, 4)

  • 4 tokens, shape (4, 1)

  • 1 token, shape (1, 1, 4)

Reveal answer
Answer:

The sentence becomes 4 tokens, and after an extra dimension is inserted at the front, the tensor has shape (1, 4).

The first dimension is the batch size, which is 1 because there is one input sequence. The second dimension is num_tokens, which is 4 for this sentence.

How Text Becomes a Tensor

The conversion from text to model input happens in two steps. First, the tokenizer turns the text into a sequence of integer token IDs. Second, torch.tensor wraps that sequence in a tensor, and unsqueeze(0) inserts a new dimension at the front. The print statements in the snippet report both the values and the dimensions, so you can check each step separately.

Keeping these two steps apart matters when something goes wrong. The tokenizer decides how many tokens the text produces. The tensor conversion decides how those tokens are arranged in dimensions. A problem in either step will show up in the shape, so the shape is the first thing to inspect.

Batch index 0the only sequenceDotoken position 0youtoken position 1havetoken position 2timetoken position 3selects sequence
For a tensor of shape (batch_size, num_tokens) = (1, 4), each position along the token dimension holds one token ID, and the batch dimension selects which sequence is being read.

Reading the Shape Dimension by Dimension

The shape is written as (batch_size, num_tokens). The first dimension counts how many input sequences are processed together. The second dimension counts the tokens in each sequence. Reading the shape this way tells you immediately whether the text was encoded the way you intended.

Worked example

Reading the shape for 'Do you have time'

The tokenizer has encoded the sentence 'Do you have time' and torch.tensor with unsqueeze(0) has produced the input. What does the shape tell you?

  1. 1
    Identify the first dimension

    The first dimension is batch_size. It counts how many input sequences are processed together. Here there is one sentence, so batch_size is 1.

  2. 2
    Identify the second dimension

    The second dimension is num_tokens. It counts the tokens in each sequence. The sentence contributes four tokens, so num_tokens is 4.

  3. 3
    Combine the dimensions

    Written in the source's convention, the shape is (batch_size, num_tokens) = (1, 4).

  4. 4
    Check against intent

    If the shape had come out as (1, 3) or (4, 1), the encoding would not match what was intended, and the problem would be located at the encoding step, before any training happens.

Result

The shape (1, 4) confirms one sequence containing four tokens, which is the encoding that was intended.

What Fine-Tuning Changes

Fine-tuning adjusts a pre-trained model's weights to fit a specific task. The model arrives with weights that were learned earlier, and fine-tuning continues the training so that those weights move toward values that suit the new task. Fine-tuning does not have to touch every part of the model, and the choice of which parts to adjust is the core decision in the process.

Definition

A trainable layer is a layer whose weights are allowed to be adjusted during training. A nontrainable layer keeps the weights it was loaded with and does not change during training.

Why can this improve predictive performance? The source describes fine-tuning the entire model as an option that can improve predictive performance, after which you assess how much that change helps. Keeping the pre-trained layers nontrainable is a way of preserving what the model already learned, while letting the trainable layers adapt that knowledge toward the new task. The pre-trained structure is the general starting point, and the trainable part is where task-specific adaptation happens.

Full Versus Partial Fine-Tuning

There are two options the source describes. In full fine-tuning, the entire model is fine-tuned, so every layer's weights can be adjusted. In partial fine-tuning, only some layers are made trainable while the rest are kept nontrainable. The table below compares which parameters receive updates in each case.

AspectFull fine-tuningPartial (selected-layer) fine-tuning
Which layers are trainableThe entire modelOnly the layers chosen as trainable
Which weights can changeAll weights in the modelWeights of trainable layers only
Nontrainable layersNoneKeep the weights they were loaded with
Preserved pre-trained structureLess of it is preserved by designMost of it is preserved, since only selected parts adapt
AssessmentAssess how much the change helpsAssess how much the selected layers help

Full and partial fine-tuning differ in which parameters are allowed to receive updates.

Trainable Layers in the GPT Example

In the GPT example, the model contains 12 repeated transformer blocks. The new output layer is trainable, and so are the final LayerNorm and the last transformer block. The remaining 11 transformer blocks and the embedding layers are kept nontrainable. This means most of the pre-trained structure is preserved, and only the parts closest to the output are adapted to the new task.

GPT modelpre-trained, then modifiedEmbedding layersnontrainableTransformer blocks 1to 11nontrainableTransformer block 12trainableFinal LayerNormtrainableOutput layertrainable, newly added
The GPT model is split into a nontrainable embedding stage and 11 nontrainable transformer blocks, followed by the trainable last transformer block, the final LayerNorm, and the new output layer.

A useful way to read the diagram is to ask which parts of the model sit closest to the output. Those parts are the only ones the source marks as trainable, and that is where the task-specific adaptation takes place. Everything nearer the input keeps the weights it was loaded with.

Finding Where an Unexpected Result Starts

When a fine-tuning run does not behave as expected, the cause usually sits at one of three points: the encoded input, the trainable-layer selection, or the way the model is then used. Checking those points in order narrows the failure quickly. The flowchart below places those checkpoints inside the workflow.

Load pre-trainedmodelbuilt in an earlier stepAdd new output layerEncode input textcheck shape (batch_size,num_tokens)Select trainablelayerscheck which blocks aretrainableUse model on theinputcheck how the output isusedResultshape is as intendedselection is as intended
The workflow moves from loading the model to using it. The first checkpoint is the encoded input shape, then the trainable-layer selection, and then the way the model is used.

Work through the checkpoints in order. If the encoded input shape is wrong, the problem is already present before the trainable layers matter, so there is no point inspecting the layer selection first. Only after the input shape checks out should you move to the trainable-layer selection, and only then to how the model is used.

Mistakes When Reading Shapes and Layers

  • Common mistake

    Reading the first dimension as the number of tokens

    What it looks like

    Seeing (1, 4) and concluding that the sentence has one token.

    Why it fails

    The first dimension is batch_size, which counts the sequences processed together. The second dimension is num_tokens.

    Do this instead

    Read the shape as (batch_size, num_tokens), so (1, 4) means one sequence containing four tokens.

  • Common mistake

    Assuming a nontrainable layer is removed from the model

    Why it fails

    A nontrainable layer keeps its loaded weights but still processes the input.

    Do this instead

    Think of nontrainable as 'weights not updated during training', not 'layer not present'.

  • Common mistake

    Debugging the trainable-layer selection before checking the input

    Why it fails

    The source places the encoded input first in the checking order. An input problem will look like a training problem if you skip the shape check.

    Do this instead

    Check the encoded input shape first, then the trainable-layer selection, and then the way the model is used.

  • Common mistake

    Treating the output layer as frozen because it was added later

    Why it fails

    In the GPT example the new output layer is explicitly trainable.

    Do this instead

    Check each layer's trainable status individually rather than assuming by position or by when it was added.

Check Your Reading of a Model Setup

MEDIUM

A colleague encodes the sentence 'Do you have time' and reports that the tensor shape is (4, 1). Using the convention (batch_size, num_tokens), explain what this shape would mean, whether it matches the intended encoding, and at which checkpoint you would investigate first. Then state which GPT layers the source marks as trainable.

Hints
  • Identify which dimension is batch_size and which is num_tokens before comparing the shapes.
  • The source expects the intended encoding to be (1, 4) for this sentence.
  • Remember the order of the checkpoints: encoded input first, then trainable-layer selection, then model use.

Key Takeaways

  • Fine-tuning adjusts a pre-trained model's weights to fit a specific task, and it can update the whole model or only selected layers.
  • A tensor shape of (batch_size, num_tokens) tells you how many sequences are processed together and how many tokens each contains, so the shape is the first thing to check.
  • In the GPT example, the output layer, the final LayerNorm, and the last transformer block are trainable, while the remaining 11 transformer blocks and the embedding layers are nontrainable.
  • When results look wrong, check the encoded input shape first, then the trainable-layer selection, then how the model is used, to locate where the outcome diverged.

Related concepts

More concepts starting with P