Sub topic 6
How transformer encoders label tokens
This chapter explains the working model behind transformer-based NER. It assumes you know basic Python, what a token is, and what a neural network classifier does. You do not need to have trained a transformer. Later chapters cover subword tokenization, running Hugging Face models, and fine-tuning. Here the goal is to understand what the model computes and where it commonly goes wrong.
From classifying a text to classifying every token
A sentence classifier reads a text and outputs one label for the whole input. NER needs a different output: one label for each token. This is called token classification, or sequence labelling.
A transformer encoder fits this task well. It takes a sequence of N input tokens and returns N vectors, one per token. Each vector is a contextual embedding. It describes the token in light of the whole sentence, not in isolation. A small classifier then maps each vector to a tag.
The word "Washington" shows why context matters. In "Washington signed the bill" it is probably a person or a government. In "She flew to Washington" it is a place. A static word vector gives the same representation in both sentences. An encoder gives different ones, because each token's vector is computed after looking at every other token.
What the encoder does internally
An encoder is a stack of identical layers. Each layer has two main parts.
- Self-attention. Every token computes a weighted mix of the other tokens' representations. The weights are learned, so a token such as "Inc." can attend strongly to the capitalized words before it.
- A feed-forward network. This transforms each token's vector independently after attention.
Residual connections and layer normalization surround both parts. They keep training stable. After the last layer you have the final hidden states, one vector per token. A BERT-base model, for example, produces a 768-dimensional vector for each token.
Self-attention is bidirectional in encoder models such as BERT, RoBERTa and DeBERTa. Each token sees both its left and right context. This matters for NER. In "Jordan was named MVP", the right-hand context tells you that "Jordan" is a person. Decoder-only models read left to right by default, which is why encoders are the usual choice for tagging tasks.
The classification head
The classification head is small. It is usually dropout followed by one linear layer that maps the hidden size to the number of tags. With 9 tags and a hidden size of 768, the layer has a 768 by 9 weight matrix and 9 biases.
For each token the layer produces 9 raw scores called logits. A softmax turns them into probabilities. The predicted tag is the one with the highest probability. Most of the model's capacity sits in the encoder. The head only reads off a decision from what the encoder has already built.
The training loss is cross-entropy, computed per token and averaged over the tokens that count. Some positions are excluded from the loss. The label alignment chapter covers how this exclusion works.
The tag set
The tags come from the BIO scheme covered in the earlier chapter. A common four-type setup, as in CoNLL-2003, uses nine tags:
| Tag | Meaning |
|---|---|
| O | Outside any entity |
| B-PER, I-PER | Begins or continues a person |
| B-ORG, I-ORG | Begins or continues an organization |
| B-LOC, I-LOC | Begins or continues a location |
| B-MISC, I-MISC | Begins or continues another entity |
The model learns a mapping between tag names and integer ids. This mapping is stored in the model config as id2label and label2id. You can inspect it:
from transformers import AutoConfig
config = AutoConfig.from_pretrained("dslim/bert-base-NER")
print(config.num_labels)
print(config.id2label)The final layer's output size must equal num_labels. If you change the tag set, you must replace the head. The pretrained encoder weights can stay.
Special tokens and padding
The tokenizer adds special tokens around your text. BERT uses [CLS] at the start and [SEP] at the end. RoBERTa uses <s> and </s>. The encoder produces a vector for these tokens too, so the model emits a prediction at those positions. These predictions are not meaningful entities. Training masks them out, and inference code ignores them.
Batching adds padding tokens so that all sequences have the same length. An attention mask tells the encoder to ignore padding. The classification head still produces outputs at padded positions, so you must drop them when you read predictions.
You can see all of this with a short script:
import torch
from transformers import AutoModelForTokenClassification, AutoTokenizer
name = "dslim/bert-base-NER"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForTokenClassification.from_pretrained(name)
model.eval()
inputs = tokenizer("Hugging Face is based in New York City.", return_tensors="pt")
with torch.no_grad():
logits = model(**inputs).logits
pred_ids = logits.argmax(dim=-1)[0]
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
print(logits.shape)
for token, pred in zip(tokens, pred_ids):
print(f"{token:12} {model.config.id2label[pred.item()]}")The logits tensor has shape (batch, sequence_length, num_labels). The printed rows include [CLS] and [SEP], and you will see the model assigns them some tag, usually O. The Hugging Face pipeline that a later chapter introduces hides this step and returns clean entity spans.
Predictions are made per token, independently
The head classifies each token on its own. It does not enforce that the output is a valid BIO sequence. The encoder's context usually makes sequences consistent, but the model can still output an invalid sequence such as O I-PER I-PER, where an entity continues without a beginning.
The softmax at one position does not depend on the tag chosen at the next. Older models, such as BiLSTM-CRF taggers, added a conditional random field layer to score whole tag sequences and forbid illegal transitions. Transformer taggers typically skip this and rely on the encoder, then repair invalid sequences in post-processing.
Common repair rules include:
- Treat a stray
I-XafterOas the start of a new entity. - Treat an
I-Xafter a different type, such asB-ORG I-PER, as the start of a new entity. - Drop the entity entirely if you prefer precision over recall.
Hugging Face's aggregation strategies apply rules like these when they merge tokens into entity groups.
Where subwords enter
Transformer tokenizers split rare words into pieces. "Anthropic" might become Anthrop and ##ic. The encoder then labels pieces, not words. This creates two practical questions. Which piece's prediction represents the word? How do you map predictions back to character offsets? The next chapter covers subword tokenization, and the alignment chapter covers training labels. For now, keep in mind that the sequence length N is the number of subword tokens, and it is almost always larger than the number of words.
Sequence length limits
An encoder has a maximum input length, often 512 tokens for BERT-style models. Longer documents must be handled explicitly. Truncation silently drops the end of the text, and with it any entities there.
Two common approaches work around the limit.
- Split the document into sentences or fixed windows, tag each, and merge the results.
- Use overlapping windows with a stride, so entities near a boundary appear whole in at least one window. Then keep the prediction from the window where the entity is furthest from the edge.
Context also matters. A window that is too short loses the information the encoder needs to resolve ambiguous names. Sentences are a reasonable default, and a few neighbouring sentences often help.
Common errors and how they arise
| Symptom | Likely cause |
|---|---|
| Entities split in the middle, such as "New" and "York" tagged separately | Subword or word predictions not merged, or an invalid BIO sequence |
| Tags shifted by one position | Special tokens at the start were not accounted for when mapping back to words |
| Entity at the end of a long text is missing | Input truncated at the maximum length |
| Wrong labels after changing the tag set | Head still has the old `num_labels` or an old `id2label` mapping |
| Good scores on the dev set, poor on your own text | Domain difference, such as lowercase text or unusual names, versus the training data |
| Different results between cased and uncased models | An uncased model lowercases the input and loses capitalization, a strong NER signal |
The last row deserves emphasis. Capitalization is one of the strongest cues for English NER. For that reason, cased models such as bert-base-cased are the usual starting point.
Pretraining and why it helps
The encoder is pretrained on large amounts of unlabelled text. BERT, for instance, learns by predicting masked tokens. To do this well it must learn syntax, word meaning and some world knowledge, such as which names refer to places. NER fine-tuning then needs far fewer labelled examples than training from scratch. A few thousand annotated sentences can produce a useful model, where a model without pretraining would need many more.
The cost is size and speed. A BERT-base model has about 110 million parameters. It runs slowly on a CPU compared with spaCy's small statistical models, which is a trade-off the final chapter returns to.
Exercise
A tokenizer turns "Sundar Pichai visited Zurich." into 9 tokens, including [CLS] and [SEP], and the model uses 9 tags. What is the shape of the logits tensor for this single sentence, and why might the model output a tag for [CLS]?
Show answer
The shape is (1, 9, 9): batch size 1, sequence length 9, and 9 tag scores per token. The head is applied to every position, including special tokens, so it outputs a tag at [CLS] and [SEP] as well. Training masks those positions out and inference code ignores them.
Exercise
A model returns the tag sequence "O I-PER I-PER O" for a four-token sentence. Why is this a problem, and name one way to handle it?
Show answer
I-PER should only follow B-PER or another I-PER, so the sequence has an entity continuing without a beginning. The per-token head does not enforce valid transitions. You can treat the first I-PER as the start of a new entity, or drop the span if you prefer precision.