Sub topic 6
How Transformer Encoders Label Tokens
Assume you know basic Python, tokens, and the idea of a neural network classifier. You should also know that named entity recognition (NER) assigns labels such as PERSON, ORG, and LOC to parts of a sentence. This chapter explains how a transformer encoder produces those labels.
From tokens to contextual representations
A transformer encoder reads the whole input sequence and creates a numeric representation for every token. This representation is called a hidden state. It contains information about the token and its surrounding context.
For example, the word “bank” has different meanings in these sentences:
- “I deposited money at the bank.”
- “We sat beside the river bank.”
Self-attention lets the encoder compare “bank” with other words in the sentence. The resulting hidden state can therefore reflect the correct meaning.
A model such as BERT first converts text into token IDs. It then processes those IDs through several encoder layers. Each layer updates the representation of every token by combining information from other positions.
The token classification head
NER uses a token classification head on top of the encoder. A classification head is a small neural network that converts each hidden state into one score for every possible label.
Suppose the label set is:
O, B-PER, I-PER, B-ORG, I-ORG
For a sentence with 10 tokens, the model produces a matrix with 10 rows and 5 columns. Each row belongs to one token. Each column contains that token's score for one label.
These raw scores are called logits. A larger logit means that the model favors that label. During prediction, the model normally selects the label with the largest logit. A softmax function can convert the logits into probabilities.
| Stage | Example shape | Meaning |
|---|---|---|
| Input IDs | `(10,)` | Ten token IDs |
| Hidden states | `(10, 768)` | One 768-number representation per token |
| Logits | `(10, 5)` | Five label scores per token |
The classification head usually applies the same linear transformation to every token's hidden state. It does not classify the entire sentence as one item. This is why the task is called token classification.
import torch
from transformers import AutoModelForTokenClassification, AutoTokenizer
checkpoint = "dslim/bert-base-NER"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModelForTokenClassification.from_pretrained(checkpoint)
text = "Hugging Face is based in New York City."
inputs = tokenizer(text, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
for token_id, scores in zip(inputs["input_ids"][0], outputs.logits[0]):
label_id = int(scores.argmax())
probability = float(scores.softmax(dim=-1)[label_id])
token = tokenizer.convert_ids_to_tokens(int(token_id))
label = model.config.id2label[label_id]
print(token, label, round(probability, 3))Turning labels into entities
The model's direct output is one label per token. An NER system turns consecutive BIO labels into entity spans.
For example:
B-PERstarts a person entity.I-PERcontinues that person entity.Omeans the token is outside an entity.
The sequence B-PER I-PER O B-LOC I-LOC represents two entities. The first covers a person's name, and the second covers a location.
Transformers may tokenize one written word into several subword tokens. For example, an uncommon word might become ["un", "## familiar"]. Each subword receives a prediction, so an application must later combine compatible subword predictions into a word-level entity.
Training the head
During fine-tuning, the encoder and classification head produce logits for labelled training sentences. A cross-entropy loss compares each predicted distribution with the correct label. The model updates its parameters to increase the score of correct labels.
Special tokens such as [CLS] and [SEP] do not represent ordinary words. Training datasets usually assign them an ignored label so they do not affect the loss. Subword alignment requires similar care.
Exercise
If a sentence has 12 tokens and the model supports 9 NER labels, what is the shape of its token-classification logits before batching?
Show answer
The shape is (12, 9): one row for each token and one score for each label.