Sub topic 9
Fine-tuning generative models for extraction
This chapter assumes you can read basic Python and JSON. It also assumes you know what a gold dataset and span-level F1 are, and how a BIO token classifier works. Earlier chapters covered all of these.
Where this approach fits
A token classifier labels each token of the input and can only return spans copied from the text. Prompting asks a general model for JSON and hopes it follows the schema. Fine-tuning a generative model sits between the two. You keep a text-to-text model that writes JSON, but you train it on your own pairs of input text and target JSON, so the schema and labeling rules end up in the model weights instead of in a long prompt.
This option is worth considering in these cases:
- The output is not a flat list of spans. Nested objects, lists of line items, and relations between entities are natural to generate and awkward to encode as BIO tags.
- The values need normalizing. A date written as "3rd of March, '24" should come out as
2024-03-03, which is not a span of the input. - Prompting is close to good enough but fails on a consistent set of cases that more instructions do not fix.
- You need a small, fast model to do a job that a large prompted model does well.
The cost is the same as for token classification. You need labeled data, a training run, and a retraining step whenever the schema changes.
What the training data looks like
Each training example is an input paired with the exact output you want. Hosted fine-tuning services and open-source libraries both accept a chat-style JSONL file, with one example per line. The example below turns gold annotations into that format. It also removes duplicate texts before splitting, so the same document cannot land in both training and development data.
import json
import random
SYSTEM = (
"Extract the invoice fields from the text. "
"Return only a JSON object with keys vendor, total, currency. "
"Use null when a field is not stated."
)
KEYS = ("vendor", "total", "currency")
def canonical_target(fields):
if set(fields) != set(KEYS):
raise ValueError(f"unexpected keys: {sorted(fields)}")
return json.dumps({k: fields[k] for k in KEYS}, ensure_ascii=False)
def to_record(text, fields):
return {
"messages": [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": text},
{"role": "assistant", "content": canonical_target(fields)},
]
}
def split(examples, seed=13, dev_fraction=0.2):
unique = {}
for text, fields in examples:
unique.setdefault(text, fields)
items = sorted(unique.items())
random.Random(seed).shuffle(items)
n_dev = max(1, round(len(items) * dev_fraction))
return items[n_dev:], items[:n_dev]
def write_jsonl(path, items):
with open(path, "w", encoding="utf-8") as f:
for text, fields in items:
f.write(json.dumps(to_record(text, fields), ensure_ascii=False) + "\n")
examples = [
("Invoice from Acme GmbH. Total due: 120.50 EUR.",
{"vendor": "Acme GmbH", "total": 120.5, "currency": "EUR"}),
("Globex Ltd billed us 80 USD for March.",
{"vendor": "Globex Ltd", "total": 80, "currency": "USD"}),
("Payment reminder, no amount listed.",
{"vendor": None, "total": None, "currency": None}),
("Initech charged a flat fee.",
{"vendor": "Initech", "total": None, "currency": None}),
("Umbrella Corp invoice: 1999 GBP.",
{"vendor": "Umbrella Corp", "total": 1999, "currency": "GBP"}),
("Invoice from Acme GmbH. Total due: 120.50 EUR.",
{"vendor": "Acme GmbH", "total": 120.5, "currency": "EUR"}),
]
train, dev = split(examples)
write_jsonl("train.jsonl", train)
write_jsonl("dev.jsonl", dev)
print(len(train), "train,", len(dev), "dev")
print(canonical_target(train[0][1]))Four details in this code matter for training quality.
- The target is serialized the same way every time. Fixed key order and fixed formatting mean the model learns one output shape. If annotators' files vary in key order or spacing, the model spends capacity on noise.
- Null cases are included. The third and fourth examples teach the model that "not stated" is a valid answer. Without them, a fine-tuned model tends to fill every field, which is the same guessing behavior you tried to prevent in the prompting chapters.
- The system prompt is short but present. Keep a stable instruction in training and use the identical text at inference. A mismatch between the two lowers accuracy.
- The split happens at the document level. If one invoice is cut into several examples, split by invoice, not by example.
Training choices
Three setups cover most projects.
| Setup | What changes | Typical use | Main risk |
|---|---|---|---|
| Hosted fine-tuning API | Provider trains and serves a private copy | Fastest start, little infrastructure | Provider-controlled model versions and pricing |
| Full fine-tuning of a small open model | All weights | Enough GPU memory and a few thousand examples | Overfitting, large checkpoints to store |
| Parameter-efficient tuning (LoRA) | Small adapter matrices, base weights frozen | Medium or large open models on limited hardware | Adapter must be matched to the exact base model version |
Whichever you choose, some settings behave the same way:
- Loss on the answer only. Most libraries let you mask the prompt tokens so the model is graded on the JSON it writes, not on reproducing the invoice text. If you skip this, the model also learns to predict input text, which wastes training signal.
- Few epochs. Two or three passes over a few hundred to a few thousand examples is a common range. More passes often make training loss fall while development F1 stalls or drops, because the model memorizes training documents.
- Low learning rate. You are adjusting a pretrained model. A high rate can erase useful language knowledge.
- Use the development set for stopping. Pick the checkpoint with the best development F1. Keep a separate test set that you read only once at the end, as in the evaluation chapter.
Decoding and validation still apply
A fine-tuned model writes valid JSON far more often than a prompted one, but not always. A long input can be truncated, generation can stop at the maximum token limit in the middle of an object, and rare inputs can produce odd output. Run the same checks you used for prompted extraction: parse the JSON, confirm the keys, and confirm the types.
Use greedy decoding (temperature 0) for extraction. You want the same input to give the same output, and sampling adds variation that only hurts here.
Some serving stacks support constrained decoding, which restricts the tokens the model may produce so the output always matches a JSON schema or grammar. This guarantees the syntax and the key names. It does not guarantee the values are right. A constrained model can still write a well-formed object with the wrong vendor.
Scoring generated output
Span-level F1 needs spans, and a generative model returns values. There are two common ways to score it:
- Field-level exact match. Compare each predicted field with the gold value after normalization. This works well for flat records like the invoice.
- Span recovery. When the task is entity extraction, require each generated string to appear in the source, then locate it by searching the text. This yields spans you can score with the BIO-to-span metrics from the evaluation chapter. A string that appears twice is ambiguous, so decide in advance whether you take the first match, or ask the model for context, or accept the ambiguity and score by string instead of by position.
The function below parses raw model outputs, counts invalid ones, scores each field, and flags string values that are not grounded in the source text.
import json
KEYS = ("vendor", "total", "currency")
def evaluate(rows):
"""rows: list of (source_text, gold_dict, raw_model_output)."""
invalid = 0
ungrounded = 0
correct = {k: 0 for k in KEYS}
for text, gold, raw in rows:
try:
pred = json.loads(raw)
except json.JSONDecodeError:
invalid += 1
continue
if not isinstance(pred, dict) or set(pred) != set(KEYS):
invalid += 1
continue
for k in KEYS:
if pred[k] == gold[k]:
correct[k] += 1
vendor = pred["vendor"]
if isinstance(vendor, str) and vendor not in text:
ungrounded += 1
n = len(rows)
return {
"invalid_rate": invalid / n,
"ungrounded_vendors": ungrounded,
"field_accuracy": {k: correct[k] / n for k in KEYS},
}
rows = [
("Invoice from Acme GmbH. Total due: 120.50 EUR.",
{"vendor": "Acme GmbH", "total": 120.5, "currency": "EUR"},
'{"vendor": "Acme GmbH", "total": 120.5, "currency": "EUR"}'),
("Globex Ltd billed us 80 USD for March.",
{"vendor": "Globex Ltd", "total": 80, "currency": "USD"},
'{"vendor": "Globex Limited", "total": 80, "currency": "USD"}'),
("Payment reminder, no amount listed.",
{"vendor": None, "total": None, "currency": None},
'{"vendor": null, "total": null'),
]
print(evaluate(rows))In the second row, the model expanded "Ltd" to "Limited". The field-accuracy metric marks it wrong, and the grounding check flags it, which tells you the model is rewriting text instead of copying it. In the third row, the output was cut off, so it counts as invalid. Reporting the invalid rate separately matters, because a model with 95% accuracy on the outputs it parses and a 10% invalid rate is a different system from one with 95% accuracy and no invalid output.
Edge cases and failure modes
- Too little data. With a few dozen examples, fine-tuning often does not beat a good few-shot prompt. Plot development F1 against training set size (500, 1,000, and so on) to see whether more labels would help. A curve that is still rising says to annotate more. A flat curve says the problem is elsewhere.
- Label noise is copied. If two annotators disagreed on whether "Acme GmbH" or "Acme" is the vendor, the model learns the inconsistency. Fix the labeling guideline and relabel before you retrain.
- Skewed null rates. If 95% of training examples have every field filled, the model will rarely output null. Make the null rate in training match the real data, and include enough null examples that the model sees them.
- Length mismatch. Training on short texts and running on long ones can fail quietly. Check the length distribution of both, and set the maximum input and output token limits to cover the longest realistic document.
- Hallucinated values. A generative model can write a plausible vendor name that is not in the text. The grounding check above catches this for strings. Numbers need normalization first, because "120.50" in the text and
120.5in the output are the same value but not the same substring. - Schema drift. Adding a field means new gold labels and a new training run. The prompt-only approach changes by editing text. Plan for this before committing to a schema that is likely to change.
- Version coupling. A fine-tuned adapter or hosted model is tied to one base model version. When the provider retires that base model, you retrain. Keep the training data, the script, and the evaluation set under version control so a retrain is routine.
How it compares
| Property | Few-shot prompting | Token classifier | Fine-tuned generative model |
|---|---|---|---|
| Output form | Any JSON | Spans from the input | Any JSON |
| Normalized values | Yes, with instructions | No | Yes, learned from examples |
| Labeled data needed | A handful | Hundreds to thousands | Hundreds to thousands |
| Risk of invented text | Higher | None, spans are copied | Lower than prompting, not zero |
| Change the schema | Edit the prompt | Relabel and retrain | Relabel and retrain |
| Per-call cost | Long prompt, large model | Small encoder, cheap | Short prompt, small or mid model |
Exercise
A fine-tuned invoice extractor scores 0.94 field accuracy on parsed outputs, but 8% of its outputs fail to parse as JSON, and most of those end in the middle of an object. Name two likely causes and one fix for each.
Show answer
Likely cause 1: the maximum output token limit is too low, so generation stops mid-object on documents with many fields or long values. Fix: raise the limit and check the length distribution of the targets. Likely cause 2: the training targets were longer or formatted differently from what the model now produces, or the input was truncated so the model lost context. Fix: serialize targets canonically, check input truncation, and retrain on a set whose length distribution matches production. Constrained decoding to the JSON schema can also remove the syntax failures.
Exercise
Your training file contains 600 examples, and 590 of them have all three invoice fields filled. After fine-tuning, the model never outputs null, even for letters that contain no invoice data. What is wrong, and what do you change?
Show answer
The null rate in the training data is much lower than in real traffic, so the model learned that every field is always present. Add gold examples where fields are missing or the document is unrelated, so that nulls form a realistic share of the training set. Retrain, then check the null-field precision and recall on a dev set that has real-world null rates.