Concepts / Replacing the Output Layer for Classification

Replacing the Output Layer for Classification

There are two separate changes to understand: the replacement output layer changes how many values are produced per token, and slice indexing selects which token's output row to use.

  • Programming

From Model Output to Class Decision

After text is converted into token IDs and passed to the model, the model returns numbers rather than a direct answer such as spam or not spam. To prepare the model for classification, replace its final output layer so it produces a number of outputs that matches the task. Then select the output row used for the input's classification decision.

Key point

There are two separate changes to understand: the replacement output layer changes how many values are produced per token, and slice indexing selects which token's output row to use.

Read the Three Output Dimensions

Suppose the model output has shape 1 x 4 x 2. Read the dimensions in order: the first dimension is the batch, which contains one input here; the second dimension has one row for each of the four input tokens; and the third dimension gives the number of values produced for each token. In this example, each token row contains two values. These rows are numeric representations, not word labels or class names.

1batch item4token rows2values per tokencontainseach row has
What does each dimension of the shape 1 x 4 x 2 index?

The last dimension reveals which output layer is in use. With the original output layer, the example shape would instead be 1 x 4 x 50257. That layer produces one value for each vocabulary entry for every token position. After replacing it for a two-class task, the final dimension is 2 rather than 50257.

Select the Final Token Row

python

Read the slice from left to right, matching each part to an output dimension. The first colon keeps the batch dimension. The -1 selects the final position on the token axis. The last colon keeps all values in that token's output row. Starting from a tensor shaped 1 x 4 x 2, this selection gives a result shaped 1 x 2: one batch item with two values.

Token row 0two valuesToken row 1two valuesToken row 2two valuesToken row 3last rowIndex -1selects final row1 x 2one row, two valuesselected bykeeps batch and values
Which token row does the slice keep, and which rows does it leave out?

The classification setup uses one decision per input, so it selects one token row rather than asking for a separate classification decision at every token position. The final row is the chosen readout point in this lesson. This selection sets up classification fine-tuning; it does not itself convert the two numbers into the words spam or not spam.

Four input tokensFour output rowsone per tokenLast-row sliceOne selected rowclassification readoutmodel producesindexed with -1selects
How does the full set of token rows become the single row selected for classification?

Size the Replacement Layer

The original output layer maps each token's internal vector to 50,257 values, one for every entry in the model's vocabulary. Classification between two categories does not need a score for every vocabulary entry. Set the replacement layer's output width to the task's number of classes instead.

Internal vectorInternal vectorOriginal output layerReplacement outputlayer50,257 vocabularyvalues2 class valuesprojectsproducesprojectsproduces
How does the final output width change when the language-model head is replaced for a two-class task?
python

The assignment replaces model.out_head and leaves the rest of the network unchanged. The Linear layer's in_features argument sets the width it expects from the preceding model layers, so it uses the model's embedding dimension. The out_features argument sets how many values the new layer produces, so it uses num_classes. With num_classes set to 2, each token's output row has two values.

torch.nn.Linearcreates the new layerin_featuresincoming vector widthBASE_CONFIG["emb_dim"]model embedding dimensionout_featuresnumber of outputsnum_classesset to 2 heretakesset fromtakesset from
Which parts of the constructor specify the incoming vector width and the number of outputs?
Worked example

Predict the Weight Shape

For gpt2-small, BASE_CONFIG["emb_dim"] is 768. If num_classes is 2, what shape does the replacement layer's weight have?

  1. 1
    Find the input width

    The layer receives vectors whose width is the embedding dimension, 768.

  2. 2
    Find the output width

    The replacement layer produces 2 outputs, one for each class.

  3. 3
    Apply the weight layout

    The weight has one row per output feature and one column per input feature.

Result

The weight shape is 2 x 768.

Using BASE_CONFIG["emb_dim"] instead of writing 768 directly connects the replacement layer to the selected model's configuration. The source gives 768 as the embedding dimension for gpt2-small and explains that reading the value from configuration lets the same replacement code work with larger GPT-2 variants whose embedding dimensions are stored in their configurations.

Check Shapes at the First Use

Model inputLayers before headReplacement outputheadLast-row sliceShape inspectionpasses throughvector reachesproduces outputinspect shape
Where may a shape mismatch first become visible after the output layer is replaced?

A replacement line may be accepted before a size problem becomes apparent. The problem usually shows up later, when data first passes through the new layer or when a shape is inspected. Trace from the replacement to its first use, then check the output shape. If the full output has the expected dimensions but the selected result does not, investigate the indexing; if the full output is already unexpected, investigate the model output or replacement layer first.

  • Common mistake

    Reading the token dimension as the number of classes.

    What it looks like

    In 1 x 4 x 2, treating 4 as the number of classes.

    Why it fails

    The second dimension counts token rows. The third dimension counts values per token.

    Do this instead

    Read the dimensions in order: batch, token rows, values per token.

  • Common mistake

    Selecting the wrong axis when extracting the final token.

    What it looks like

    Changing the slice so it no longer selects -1 on the token dimension.

    Why it fails

    The final-token index belongs in the middle position of outputs[:, -1, :].

    Do this instead

    Keep the batch and value dimensions with colons, and use -1 for the token dimension.

  • Common mistake

    Using a hardcoded input width in place of the model configuration.

    What it looks like
    Writing 768 directly as in_features.
    Why it fails

    The stated embedding dimension for gpt2-small is 768, but other GPT-2 variants can have a different configured dimension.

    Do this instead

    Read the input width from BASE_CONFIG["emb_dim"].

  • Common mistake

    Expecting the replacement layer to produce a trained class label immediately.

    Why it fails

    The new layer has new weights that must be trained for the task, and the selected row is still numeric output rather than a label word.

    Do this instead

    Treat replacement and training as separate steps; the replacement sets the output size, while fine-tuning trains the new layer for classification.

Predict Before Running the Shape Checks

MEDIUM

A model output has shape 1 x 4 x 2. First, write down what each dimension represents. Then determine the shape returned by outputs[:, -1, :]. Finally, for gpt2-small with num_classes set to 2, predict the replacement layer's weight shape before checking it.

Hints
  • Match the three dimensions to batch, token rows, and values per token.
  • The -1 selects the final position on the token axis, while the two colons keep the other dimensions.
  • The weight has one row per output feature and one column per input feature.

Key Takeaways

  • A model output shaped 1 x 4 x 2 has one batch item, four token rows, and two values per token.
  • The slice outputs[:, -1, :] selects the final token row and yields a 1 x 2 result in this example.
  • The original output head produces 50,257 vocabulary values per token; a two-class replacement produces two.
  • For the replacement Linear layer, in_features comes from BASE_CONFIG["emb_dim"] and out_features comes from num_classes.
  • A shape problem may first appear when data passes through the replacement layer or when the resulting shape is inspected.

More concepts starting with R