Sub topic 8
Fine-tuned token classifiers and BIO tags
This chapter assumes you know basic Python, can read JSON, and understand precision, recall and F1 at an introductory level. It also assumes you know that a language model turns text into vectors. You do not need to have trained a transformer before.
Why tag tokens instead of generating text
A prompted extractor writes its answer as new text, and you then parse that text. A token classifier works differently. It reads the input and assigns one label to every token. The entities are read off those labels, so the output is always tied to positions in the original text.
This has three practical consequences:
- The model cannot invent a string that is not in the input. It can only mark spans that exist.
- Every extracted entity has character offsets, so you can highlight it, link it back to the source, or check it against the gold data.
- The output has a fixed shape, one label per token. There is no JSON to break.
The trade-off is that you must decide the label set before training, and you need labeled examples to train on. The earlier chapters on schemas and gold data cover that work.
The BIO scheme
A model that labels tokens needs a way to say where an entity starts and ends. The most common answer is the BIO scheme. Each token gets one of three kinds of tag:
B-Xmeans the token Begins an entity of type X.I-Xmeans the token is Inside an entity of type X, continuing the previous token.Omeans the token is Outside any entity.
Take the sentence "Angela Merkel visited Paris." Here is one tagging with the types PER (person) and LOC (location):
| Token | Tag |
|---|---|
| Angela | B-PER |
| Merkel | I-PER |
| visited | O |
| Paris | B-LOC |
| . | O |
The B- tag matters because it separates two adjacent entities of the same type. In "Alice Bob met", the tags B-PER B-PER O mean two people, while B-PER I-PER O means one person named "Alice Bob". With only I- and O tags, those two cases would look the same.
A tagging scheme with N entity types has 2N + 1 tags. With PER, LOC and ORG that is seven tags: O, plus a B- and an I- for each type.
Other schemes exist. BIOES adds E- (end) and S- (single-token entity). It gives the model slightly more explicit boundary information, and some systems train a little better with it. BIO is the most common default, and the Hugging Face NER datasets and models you will meet usually use it.
Decoding tags into spans
Training produces tags. Evaluation and downstream code need spans, meaning (start, end, label) triples. The function below converts a BIO sequence into spans. It uses a half-open interval, so end is the index after the last token of the entity. It appends a sentinel "O" so that an entity ending at the last token is still closed.
def bio_to_spans(tags):
spans = []
start = None
label = None
for i, tag in enumerate(tags + ["O"]):
if start is not None and not (tag.startswith("I-") and tag[2:] == label):
spans.append((start, i, label))
start = None
label = None
if tag != "O" and start is None:
start = i
label = tag[2:]
return spans
def precision_recall_f1(gold, pred):
gold, pred = set(gold), set(pred)
tp = len(gold & pred)
p = tp / len(pred) if pred else 0.0
r = tp / len(gold) if gold else 0.0
f1 = 2 * p * r / (p + r) if p + r else 0.0
return p, r, f1
gold = bio_to_spans(["B-PER", "I-PER", "O", "B-LOC"])
pred = bio_to_spans(["B-PER", "O", "O", "B-LOC"])
print(gold)
print(pred)
print(precision_recall_f1(gold, pred))The gold spans are [(0, 2, 'PER'), (3, 4, 'LOC')]. The prediction tagged only "Angela" as a person, so its spans are [(0, 1, 'PER'), (3, 4, 'LOC')]. Under exact-match scoring the PER span is wrong because its boundary differs, so one of two predictions is correct. Precision, recall and F1 are all 0.5.
This is the span-level scoring from the evaluation chapter. A token-level accuracy would be much higher here, because four of five tokens are right. That is why token accuracy is a poor metric for extraction: most tokens are O, so a model can score well while missing many entities.
Invalid sequences
A model predicts each tag from a probability distribution, so nothing guarantees a valid sequence. It may output O I-PER I-PER, where an I- tag follows O. It may also output B-PER I-LOC, where the type changes mid-entity.
The decoder above handles both in one particular way. It only starts an entity at a non-O tag when no entity is open, so a stray I-PER after O starts a new span. A type change closes the old span and starts a new one. Other decoders drop such tags instead. Whichever rule you pick, apply it identically to gold-versus-prediction comparisons, or your scores will not be comparable between runs.
How the model produces the tags
A fine-tuned token classifier has two parts:
- A pretrained encoder, such as BERT or RoBERTa. It reads the whole sentence and produces one vector per token. Because it uses context on both sides, the vector for "Paris" differs depending on whether the sentence is about a city or a person.
- A small classification layer on top. It is a linear layer that maps each token vector to one score per tag, followed by a softmax that turns the scores into probabilities.
Training uses labeled sentences. For each token, the loss compares the predicted tag distribution with the gold tag, using cross-entropy. Fine-tuning updates both the classification layer, which starts random, and the encoder weights, which start from pretraining. That is why a few thousand labeled sentences can be enough: the encoder already knows a lot about language.
At prediction time the model takes the highest-probability tag for each token. This is an independent choice per token. Some older systems added a conditional random field (CRF) layer on top to score whole tag sequences and rule out invalid transitions like O followed by I-PER. With modern encoders, a plain softmax is usually close in accuracy, and the simple decoding rules above clean up the rest.
Word pieces and label alignment
Transformer encoders do not read whole words. A tokenizer splits text into subword pieces. A rare word such as "Merkelstadt" might become Merkel, ##stadt. Your gold labels, however, are usually assigned per word. This creates an alignment problem that causes many silent bugs.
The common solution has two parts:
- During training, give the real label to the first piece of each word. Give the remaining pieces a special ignore value (
-100in PyTorch and Hugging Face), so the loss skips them. - During prediction, take the tag of the first piece as the tag for the whole word, or average the probabilities across pieces. Then merge pieces back into words.
If you skip the ignore step and copy B-PER to every piece, the model learns to predict B- in the middle of words. If you give the continuation pieces I- tags without a plan, you teach it a different label scheme than your gold data uses. Either way the tagging looks reasonable on a quick check while the scores fall.
Character offsets help here. Fast tokenizers can return, for each piece, its start and end character position in the original text. Working in character offsets lets you merge pieces and compare spans without depending on the tokenizer's choices.
Running a pretrained model
You do not always need to train from scratch. Public models fine-tuned on standard datasets can be used directly. The Hugging Face pipeline below loads one trained on the CoNLL-2003 data, which has the types PER, ORG, LOC and MISC.
from transformers import pipeline
ner = pipeline(
"token-classification",
model="dslim/bert-base-NER",
aggregation_strategy="simple",
)
for entity in ner("Angela Merkel visited Paris."):
print(entity["entity_group"], entity["word"], entity["start"], entity["end"])The aggregation_strategy="simple" option does the merging for you. It joins word pieces and consecutive B-/I- tags of one type into a single entity and reports character offsets. Without it, you get one record per token piece, with raw tags. The output for this sentence should be a PER entity "Angela Merkel" at characters 0 to 13 and a LOC entity "Paris" at characters 22 to 27. Exact scores and spans can vary slightly with the model version.
A public model only knows its own label set. dslim/bert-base-NER has no INVOICE_TOTAL or DRUG_DOSE tag. If your schema differs, you fine-tune your own model on your own gold data, starting from a pretrained encoder.
Fine-tuning in practice
The workflow follows the same steps for most projects:
- Split your gold data into train, validation and test sets, by document and not by sentence, so near-duplicate text does not leak between sets.
- Convert the annotations to BIO tags and align them to word pieces.
- Train for a few epochs with a small learning rate, often around 2e-5 to 5e-5, and pick the checkpoint with the best validation span-level F1.
- Score once on the test set with the same span-level metric you use for prompted systems.
Things that commonly go wrong:
- Class imbalance. Most tokens are
O. Models can drift toward predictingO, which raises recall errors. Check per-type recall, and consider more examples of rare types before trying loss weighting. - Long documents. Encoders have a maximum input length, often 512 pieces. Longer text must be split into windows, ideally with overlap, and the predicted spans merged afterward. Entities cut at a window boundary are a frequent source of boundary errors.
- Label drift. If annotators changed their rules midway, the model learns the mix. Re-check guidelines before adding more data.
- Domain shift. A model trained on news text loses accuracy on clinical notes or legal contracts. Test on data that looks like your production text.
Token classification also has limits. It handles flat spans well. It does not handle nested entities, such as a company name inside a longer organization name, unless you add layers or change the architecture. It also does not label relations between entities. A schema built around "extract the total, then link it to the invoice date" needs a second model or a different approach.
Where this fits against prompting
A token classifier is small, fast and deterministic, and its output always maps back to the text. Its price is the labeled data and a training pipeline. Prompting avoids that cost but gives you less control over boundaries and format. Later chapters compare the two on cost, latency and error types, and show how to combine them. For now, remember the central point: a token classifier chooses among a fixed set of tags for spans that already exist in the text, while a prompted model generates an answer.
Exercise
A model outputs the tags B-ORG I-ORG O B-PER I-PER for a five-token sentence. The gold tags are B-ORG I-ORG O B-PER O. Using bio_to_spans and exact-match scoring, give the predicted spans, the gold spans, and the precision, recall and F1. Then say what token-level accuracy would be and why it hides the problem.
Show answer
Predicted spans: (0, 2, 'ORG') and (3, 5, 'PER'). Gold spans: (0, 2, 'ORG') and (3, 4, 'PER'). Only the ORG span matches exactly, so true positives = 1, precision = 1/2 = 0.5, recall = 1/2 = 0.5, F1 = 0.5. Token-level accuracy is 4/5 = 0.8, because only the last token is wrong. It hides the problem because the boundary error makes the whole PER entity incorrect under span-level scoring, yet it costs only one token out of five.
Exercise
Why does the subword token "##stadt" in the word "Merkelstadt" get the label -100 during training, and what happens if you give it B-LOC instead?
Show answer
The label -100 tells the loss function to ignore that piece, so only the first piece of each word is trained on. If you copy B-LOC to every piece, the model learns to predict a "begin" tag inside words. At prediction time it then produces extra entity starts, which split one entity into several spans and lower span-level precision.