Sub topic 11
Fine-tuning a transformer for NER
Earlier chapters showed how to run a pretrained transformer NER model and how to align word labels to subword tokens. This chapter puts those pieces together. You will fine-tune a pretrained encoder on a labelled NER dataset with the Hugging Face Trainer, score it at the entity level, and use the result.
I assume you can run Python with transformers, datasets and seqeval installed, and that you know BIO tags and the -100 label convention from the alignment chapter. A GPU is strongly recommended. On CPU, one epoch of CoNLL-2003 takes hours.
What fine-tuning changes
A pretrained encoder such as bert-base-cased already produces a contextual vector for every subword token. For NER you add a small linear layer on top. It maps each token vector to one score per tag (O, B-PER, I-PER, and so on). AutoModelForTokenClassification builds this for you. The new layer starts with random weights, and training updates both it and the encoder weights.
The head size is fixed by the number of labels you pass. If your tag set differs from the one a checkpoint was trained with, the old head no longer fits. Start from the base encoder and let the library create a new head.
Load the data and the label list
CoNLL-2003 is the standard English benchmark. It has four entity types: PER, ORG, LOC and MISC. Each example has a tokens list and an ner_tags list of integer ids. The version below is stored as Parquet files, so it loads with current datasets releases.
The integer ids are meaningless without the label names, so read them from the dataset and pass them to the model. The saved model then reports B-PER instead of LABEL_3.
from datasets import load_dataset
raw = load_dataset("tomaarsen/conll2003")
label_list = raw["train"].features["ner_tags"].feature.names
id2label = {i: name for i, name in enumerate(label_list)}
label2id = {name: i for i, name in id2label.items()}
print(label_list)
print(raw["train"][0]["tokens"], raw["train"][0]["ner_tags"])If you use your own data, convert it to the same shape first: one list of words and one list of tag ids per example. Check that every sentence has the same number of tokens and tags. A single length mismatch causes errors later that are hard to trace.
Tokenize and align labels
This is the function from the alignment chapter, rewritten to work on batches. The word_ids(batch_index=i) call returns, for each subword, the index of the word it came from. Special tokens such as [CLS] and [SEP] get None.
from transformers import AutoTokenizer
checkpoint = "bert-base-cased"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
def tokenize_and_align_labels(batch):
tokenized = tokenizer(
batch["tokens"], is_split_into_words=True, truncation=True
)
all_labels = []
for i, word_tags in enumerate(batch["ner_tags"]):
previous_word_id = None
labels = []
for word_id in tokenized.word_ids(batch_index=i):
if word_id is None:
labels.append(-100)
elif word_id != previous_word_id:
labels.append(word_tags[word_id])
else:
labels.append(-100)
previous_word_id = word_id
all_labels.append(labels)
tokenized["labels"] = all_labels
return tokenized
tokenized = raw.map(
tokenize_and_align_labels,
batched=True,
remove_columns=raw["train"].column_names,
)Two choices here have consequences.
- First subword only. Only the first piece of each word carries a label. This makes evaluation simple, because there is exactly one prediction per word. An alternative is to copy the label to every subword, converting
B-toI-on continuation pieces. That gives the model more training signal, but you must then decide how to collapse the predictions back to words. - Truncation.
truncation=Truecuts inputs at the model's maximum length, 512 for BERT. CoNLL sentences are short, so nothing is lost. On long documents, truncation silently drops the entities at the end. Split long text into sentences or windows before training and inference.
Build the model
Pass the label maps when you create the model. They are stored in the model config and are used by the pipeline later.
from transformers import AutoModelForTokenClassification
model = AutoModelForTokenClassification.from_pretrained(
checkpoint,
num_labels=len(label_list),
id2label=id2label,
label2id=label2id,
)The library warns that some weights were newly initialized. This is expected. It refers to the classification head.
Define entity-level metrics
Accuracy per token is misleading for NER, because most tokens are O. A model that predicts O everywhere scores around 83% token accuracy on CoNLL and finds no entities at all. Use entity-level precision, recall and F1 from seqeval, which counts an entity as correct only when the whole span and the label match.
The metric function receives logits and the aligned label arrays. It must drop every position where the label is -100 before converting ids back to tag strings.
import numpy as np
from seqeval.metrics import f1_score, precision_score, recall_score
def compute_metrics(eval_pred):
logits, label_ids = eval_pred
predictions = np.argmax(logits, axis=-1)
true_tags, pred_tags = [], []
for pred_row, label_row in zip(predictions, label_ids):
true_tags.append(
[id2label[l] for l in label_row if l != -100]
)
pred_tags.append(
[id2label[p] for p, l in zip(pred_row, label_row) if l != -100]
)
return {
"precision": precision_score(true_tags, pred_tags),
"recall": recall_score(true_tags, pred_tags),
"f1": f1_score(true_tags, pred_tags),
}Train
DataCollatorForTokenClassification pads each batch to its longest sequence. It pads the labels with -100, so padding is ignored by the loss. The default collator would pad the inputs but not the labels, and batching would fail.
The settings below are a common starting point for BERT-sized encoders. The learning rate of 2e-5 is small on purpose. Larger rates risk overwriting what the encoder learned during pretraining.
from transformers import (
DataCollatorForTokenClassification,
Trainer,
TrainingArguments,
)
collator = DataCollatorForTokenClassification(tokenizer)
args = TrainingArguments(
output_dir="ner-bert-conll",
learning_rate=2e-5,
per_device_train_batch_size=16,
per_device_eval_batch_size=32,
num_train_epochs=3,
weight_decay=0.01,
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
metric_for_best_model="f1",
seed=42,
report_to="none",
)
trainer = Trainer(
model=model,
args=args,
train_dataset=tokenized["train"],
eval_dataset=tokenized["validation"],
data_collator=collator,
processing_class=tokenizer,
compute_metrics=compute_metrics,
)
trainer.train()
trainer.save_model("ner-bert-conll")With load_best_model_at_end=True, the Trainer reloads the epoch with the highest validation F1 once training finishes. The saved model is that checkpoint, not necessarily the last epoch.
Evaluate on the test split
Use the test split only once, after you have chosen your settings on the validation split. Tuning against the test set gives an optimistic score.
from seqeval.metrics import classification_report
output = trainer.predict(tokenized["test"])
predictions = np.argmax(output.predictions, axis=-1)
true_tags, pred_tags = [], []
for pred_row, label_row in zip(predictions, output.label_ids):
true_tags.append([id2label[l] for l in label_row if l != -100])
pred_tags.append(
[id2label[p] for p, l in zip(pred_row, label_row) if l != -100]
)
print(classification_report(true_tags, pred_tags))The report gives precision, recall and F1 for each entity type. For bert-base-cased on CoNLL-2003, an entity-level F1 around 0.90 to 0.92 is typical. A much lower value usually points to an alignment bug, not a weak model.
Use the fine-tuned model
The saved folder contains the weights, the config with your label names, and the tokenizer. Load it like any Hub model.
from transformers import pipeline
ner = pipeline(
"token-classification",
model="ner-bert-conll",
aggregation_strategy="simple",
)
for ent in ner("Ada Lovelace worked with Charles Babbage in London."):
print(ent["entity_group"], ent["word"], round(float(ent["score"]), 3))Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| F1 near zero, loss does not fall | Labels misaligned, or all labels are `-100` | Print one example's tokens next to its aligned labels |
| Error about tensors of different lengths | Default collator used instead of the token-classification one | Pass `DataCollatorForTokenClassification` |
| Outputs show `LABEL_0`, `LABEL_1` | `id2label` not passed to the model | Pass both maps in `from_pretrained` |
| Size mismatch error when loading | Starting from a checkpoint with a different label count | Start from the base encoder, or pass `ignore_mismatched_sizes=True` and expect a new head |
| Entities missing at the end of long texts | Truncation at the maximum length | Split the text into sentences or windows |
| Out-of-memory error | Batch size or sequence length too large | Lower the batch size, or add `fp16=True` on a supported GPU |
| Validation F1 drops in later epochs | Overfitting on a small dataset | Keep `load_best_model_at_end`, reduce epochs, or add data |
Practical notes
- Small datasets. With a few hundred examples, results vary a lot between seeds. Run several seeds and report the mean and spread, not one number.
- Class imbalance.
Odominates. Standard cross-entropy usually works well enough, but rare entity types may need more annotated examples more than they need loss tweaks. - Model choice. Cased models matter for NER, because capitalization is a strong cue.
bert-base-uncasedtypically scores lower thanbert-base-cased. Larger encoders like RoBERTa or DeBERTa often add a point or two of F1, at higher cost. - Reproducibility. Set
seed, record the library versions, and keep the label list with the model.
Exercise
After training, your validation F1 is 0.02 even though the loss decreased. You print one aligned example and see that every label is -100 except the first one. What is the most likely bug, and how do you confirm it?
Show answer
The alignment function is probably comparing word ids incorrectly, for example by calling tokenized.word_ids() without batch_index=i in a batched map. In that case it returns ids for the first example only, and the labels do not match the rest of the batch. Confirm it by printing tokenizer.convert_ids_to_tokens(example["input_ids"]) next to example["labels"] for a few examples. Each word's first subword should have a real label, and all other positions should have -100. Fix it by passing batch_index=i.
Exercise
Why must the metric function drop positions where the label is -100 before computing F1? What would go wrong if it kept them and treated -100 as a tag?
Show answer
Positions with -100 are special tokens, padding, and non-first subwords. They are not real words, and the loss ignores them. Keeping them would make id2label[-100] fail with a KeyError. If you mapped them to O, the model would be credited for easy O predictions that do not correspond to any word, and the scores would be inflated and not comparable to word-level results.
Exercise
You want to fine-tune on a dataset with 7 tags that is different from CoNLL's 9, starting from dslim/bert-base-NER, which already has a 9-label head. What happens if you call from_pretrained with num_labels=7 and no other arguments, and what are your two options?
Show answer
Loading fails with a size mismatch error, because the saved classifier weights have shape for 9 labels. Option one: start from a base encoder such as bert-base-cased, which has no NER head. Option two: pass ignore_mismatched_sizes=True so the old head is discarded and a new 7-label head is created. Both give you a new random head. The second option keeps the encoder weights that were already adapted to NER.