From Token IDs to a Predicted Label

A tokenizer turns text into token IDs, but token IDs are only numbers in a list. To sort a text into one of a few classes, a model has to read those numbers, give each class a score, and let you turn the scores into a choice you can trust or doubt. This page follows that path from token IDs to a predicted label, and explains why a model that has just been given a classification head can only guess until it is trained.

An encoder reads the whole text at once

The transformer models used to sort text into classes are encoder models. An encoder receives the token IDs of a whole text in one go and returns one vector per token: a list of numbers (768 of them in a small model such as DistilBERT) that describes what that token means in this particular text.

Each of those vectors is computed with attention. Seen from the outside, attention lets the model look at every other token of the text while it works out the vector of one token. In "the river bank" and "the bank account", the token bank gets a different vector, because the words around it are different. An encoder stacks several such layers (DistilBERT has six), and each layer refines the vectors of the one before.

  • [CLS]
  • the
  • rain
  • Encoder 6 layers, each token attends to all others
  • vector 768 numbers
  • vector 768 numbers
  • vector 768 numbers
  • [CLS] to Encoder
  • the to Encoder
  • rain to Encoder
  • Encoder to vector
  • Encoder to vector
  • Encoder to vector

This is different from the models behind chat assistants, which are decoder models. A decoder writes text one token at a time, and while it works on a token it may look only at the tokens before it, since the later ones do not exist yet. An encoder has the whole text from the start and looks in both directions, which is why it suits tasks that need an understanding of the full text: sorting it into a class, labelling its words, finding an answer inside it. It does not write replies.

ModelEach token seesReturnsSuited to
Encoder (BERT, DistilBERT)every token of the textone vector per tokenclassifying and understanding text
Decoder (GPT-2)only the tokens before itthe next token, again and againgenerating text

True or false?

An encoder computes the vector of the last token of a text without looking at the first token.

False. An encoder looks in both directions: the vector of every token is computed with attention to every other token, earlier and later ones alike.

The same word can get a different vector in two different texts.

True. Each vector depends on the whole text around the token, so the word bank in a text about rivers and in a text about money ends up with different vectors.

The body makes vectors, the head makes scores

Vectors are not yet an answer. A classifier needs one score per class, so a model for classification has two parts. The body is the encoder described above: the pretrained layers that turn token IDs into vectors. The head is a small set of layers on top that turns one vector into a score for each class of the task.

The head does not read every token's vector. It reads the vector of the first token, the special [CLS] token the tokenizer puts at the start of every text. Because that vector was computed with attention to all the other tokens, it already carries information about the whole text, and it serves as a summary of it.

  • Token IDs and attention mask
  • Body 6 encoder layers
  • [CLS] vector 768 numbers
  • pre_classifier 768 to 768
  • classifier 768 to 3
  • 3 scores one per class
  • Token IDs to Body
  • Body to [CLS] vector
  • [CLS] vector to pre_classifier
  • pre_classifier to classifier
  • classifier to 3 scores

In DistilBERT the classification head is two linear layers. The first, pre_classifier, maps the 768 numbers of the [CLS] vector to another 768, and a ReLU and a dropout follow it. The second, classifier, maps those 768 numbers to one score per class. With three classes, that last layer has 768 times 3 weights plus 3 biases. Some other models use a single linear layer as their head; the idea is the same.

The split matters because the two parts come from different places. The body holds what the model learned in pretraining, roughly 66 million weights that took a large amount of text and computing time to train. The head is under a million weights and depends on the task: a head for three news topics and a head for ten kinds of support request need a different number of outputs, so each task gets its own head on top of the same body.

True or false?

The classification head of DistilBERT reads the vector of the first token only.

True. It takes the vector of the [CLS] token. That vector was computed with attention to every other token, so it reflects the whole text.

The head is the largest part of a classification model.

False. It is small: in DistilBERT, under a million weights against roughly 66 million in the pretrained body.

One checkpoint, a class for each task

A checkpoint on the Hub stores the weights a model was saved with. The checkpoint distilbert/distilbert-base-uncased (Apache 2.0 licence) was saved with the head it used in pretraining, a head that predicts hidden words. To use the same body for another task, the Transformers library offers one model class per task. Each class builds the same body and puts a different head on it.

One body, a class per task (each class name starts with DistilBert)
  • DistilBERT body pretrained encoder
  • No head Model
  • Hidden words ForMaskedLM
  • One label per text ForSequenceClassification
  • One label per token ForTokenClassification
  • An answer span ForQuestionAnswering
  • DistilBERT body to No head
  • DistilBERT body to Hidden words
  • DistilBERT body to One label per text
  • DistilBERT body to One label per token
  • DistilBERT body to An answer span

You rarely name these classes yourself. AutoModelForSequenceClassification reads the checkpoint's configuration, sees that it is a DistilBERT model, and builds DistilBertForSequenceClassification. What it cannot read from the checkpoint is your task, so you tell it how many classes there are and what they are called:

from transformers import AutoModelForSequenceClassification

id2label = {0: "sport", 1: "politics", 2: "science"}
label2id = {name: i for i, name in id2label.items()}

model = AutoModelForSequenceClassification.from_pretrained(
    "distilbert/distilbert-base-uncased",
    num_labels=3,
    id2label=id2label,
    label2id=label2id,
)

print(model.config.num_labels)   # 3
print(model.config.id2label)     # {0: 'sport', 1: 'politics', 2: 'science'}

These values go into the model's configuration, the object at model.config that is saved with the model as config.json. num_labels sets the size of the last layer of the head. id2label maps each output position to a class name, and label2id is the same map in the other direction. The library does not build label2id from your id2label, so pass both.

If you pass only num_labels, the names default to LABEL_0, LABEL_1 and so on. If you pass nothing, the head gets two classes. Neither is an error, which is why a model with the wrong number of classes or meaningless names can load without complaint. The names change nothing in the computation; they are there so that a prediction can be read as science instead of as position 2.

True or false?

Loading with num_labels=3 and nothing else gives the classes readable names.

False. The names become LABEL_0, LABEL_1 and LABEL_2. Real names come only from id2label, passed together with label2id.

The same checkpoint can be loaded with different task classes, each adding its own head.

True. The body is shared. The class decides which head is built on top of it.

From logits to probabilities to a label

Running the model is a forward pass, as with any PyTorch network: tokenize the text, give the result to the model, and read its output. When you only use the model and do not train it, wrap the call in torch.no_grad(): it turns off gradient tracking, which saves memory and time. The model comes back from from_pretrained in evaluation mode, so dropout is already off.

import torch
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
inputs = tokenizer(["The match went to extra time."], return_tensors="pt")

with torch.no_grad():
    logits = model(**inputs).logits        # shape (1, 3): one row per text

probs = torch.nn.functional.softmax(logits, dim=-1)   # each row sums to 1
predicted = probs.argmax(dim=-1).item()               # position of the highest
print(model.config.id2label[predicted], probs[0, predicted].item())

The output holds logits: one raw score per class, one row per text. A logit can be any number, positive or negative, and the scores of a row do not add up to anything in particular. A higher logit means the model leans more towards that class, but a logit of 2.0 is not a chance of anything.

To read the scores as probabilities, you apply the softmax function along the class dimension. It raises \( e \) to the power of each logit, which makes every value positive, and divides each result by their total, which makes them sum to one:

$$p_i = \frac{e^{z_i}}{\sum_{j} e^{z_j}}$$

Softmax z are the logits of one text, p the probabilities

With three logits of 2.0, 0.5 and -1.0, softmax gives about 0.79, 0.18 and 0.04. The highest logit becomes the highest probability, and the gaps between the scores decide how far apart the probabilities end up.

  • Logits
  • 0
  • sport
  • politics
  • science
  • 2.0
  • 0.5
  • -1.0
After softmax

probability

  • sport 0.79
  • politics 0.18
  • science 0.04

The prediction is the class with the highest probability: argmax returns its position, and id2label turns the position into a name. Since softmax never changes which score is the largest, argmax on the logits gives the same class. Softmax is needed to read how sure the model is, not to pick the winner.

Models return logits instead of probabilities for a training reason. The cross-entropy loss used for classification takes the raw logits and applies the softmax inside, in a way that is more stable numerically. When you pass labels to the model, it computes that loss for you and returns it next to the logits.

True or false?

Taking argmax of the logits and argmax of the probabilities always picks the same class.

True. Softmax keeps the order of the scores: the largest logit always becomes the largest probability.

The logits of one text add up to one.

False. Logits are raw, unnormalized scores. Only after softmax do the values of a row lie between 0 and 1 and sum to one.

You should add a softmax at the end of the model before training it with cross-entropy loss.

False. The cross-entropy loss expects raw logits and applies the softmax itself. Adding another one would squash the scores twice.

A new head only guesses

The checkpoint holds weights for the body and for the old head that predicted hidden words. It holds no weights for a three-class head, because nobody has trained one yet. So when the model is built, the library copies the body's weights from the checkpoint and starts the new head from random weights: small numbers drawn from a normal distribution with mean 0 (a standard deviation of 0.02 for DistilBERT), and biases set to zero.

The library tells you this when the model loads. In current versions of Transformers it logs a load report headed DistilBertForSequenceClassification LOAD REPORT from: distilbert/distilbert-base-uncased, then a table of weight names with a status for each, then notes that explain the statuses.

What the load report says
StatusWhich weightsThe note it prints
UNEXPECTEDthe old head that predicted hidden words, such as vocab_transform and vocab_layer_norm: in the checkpoint, not in the new modelcan be ignored when loading from different task/architecture; not ok if you expect identical arch.
MISSINGthe new head, pre_classifier and classifier: in the new model, not in the checkpointthose params were newly initialized because missing from the checkpoint. Consider training on your downstream task.

Neither status is an error. UNEXPECTED weights belong to a head this model does not use, so they are left out. MISSING weights are the ones that were just drawn at random. The report is the library saying, correctly, that this model has a part that has never been trained. Older versions printed a sentence instead, saying that some weights "are newly initialized" and that you "should probably TRAIN this model". Many tutorials still show that sentence; it means the same thing.

A model in this state runs without trouble and produces logits, probabilities and a label. They mean nothing. Because the head's weights start so small, its logits all sit close to zero, and softmax spreads the probability almost evenly: about one in three for each of three classes. The body still produces a good vector for the text, but the random head maps that vector to scores that have no connection to your classes, because nothing ever showed it which texts belong to sport and which to science. Its label is a guess, and its probabilities are not confidence. The weights of the head come only from training on labelled examples.

True or false?

The load report means the checkpoint failed to load and the model cannot be used.

False. It is a logged warning. The body loaded from the checkpoint; the report only lists the old head that was left out and the new head that was initialized at random.

A freshly initialized DistilBERT head gives probabilities close to one in three for each of three classes.

True. Its small random weights give logits near zero, and softmax turns nearly equal logits into nearly equal probabilities. Even the highest of them is a guess, not confidence.

Without a fixed seed, loading the same checkpoint twice can give two different predictions for the same text.

True. Each load draws new random weights for the head. Dropout plays no part here, since the model loads in evaluation mode.