Sub topic 9
Fine-tuning Generative Models for Extraction
Assume you know Python, JSON, and the basic meaning of precision, recall, and F1. This chapter focuses on causal language models: models that generate text one token at a time. Fine-tuning teaches such a model to produce a particular extraction format for a particular domain.
The working model
A generative extractor receives an instruction and a document, then generates a serialized answer, usually JSON.
For example:
Extract the invoice fields.
Text: Invoice from Acme. Total: €120.50.
JSON:
{"vendor":"Acme","total":120.50,"currency":"EUR"}During fine-tuning, the model sees many input-output pairs like this. Training adjusts its weights to increase the probability of the correct output tokens. This process is usually called supervised fine-tuning.
The target must be consistent. If one example uses "total": 120.5 and another uses "amount": "€120.50", the model receives conflicting signals. Define the schema before creating training examples.
Preparing training examples
Each example should contain:
- The source text.
- The same instruction or prompt template used at inference time.
- A valid target object.
nullfor fields that are absent, when that is your agreed rule.
Split examples into training, validation, and test sets. Keep the test set untouched until you compare systems. If documents from the same customer appear in multiple sets, the score may be overly optimistic because the model can memorize customer-specific patterns.
A common training objective masks the prompt tokens and calculates loss only on the answer. This tells the model that the important behavior is generating the target structure, not copying the instruction.
import json
from datasets import Dataset
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
Trainer,
TrainingArguments,
default_data_collator,
)
MODEL = "sshleifer/tiny-gpt2"
MAX_LENGTH = 128
examples = [
{
"text": "Invoice from Acme. Total: EUR 120.50.",
"answer": {"vendor": "Acme", "total": 120.50, "currency": "EUR"},
},
{
"text": "Globex invoice, amount $80.",
"answer": {"vendor": "Globex", "total": 80.0, "currency": "USD"},
},
]
tokenizer = AutoTokenizer.from_pretrained(MODEL)
tokenizer.pad_token = tokenizer.eos_token
model = AutoModelForCausalLM.from_pretrained(MODEL)
def encode(example):
prompt = (
"Extract vendor, total, and currency. "
"Return only JSON. Use null when absent.\n"
f"Text: {example['text']}\nJSON:\n"
)
target = json.dumps(example["answer"], separators=(",", ":"))
full = tokenizer(
prompt + target + tokenizer.eos_token,
max_length=MAX_LENGTH,
padding="max_length",
truncation=True,
)
prompt_ids = tokenizer(prompt, add_special_tokens=False)["input_ids"]
labels = full["input_ids"].copy()
labels[:len(prompt_ids)] = [-100] * len(prompt_ids)
labels = [
token if mask else -100
for token, mask in zip(labels, full["attention_mask"])
]
full["labels"] = labels
return full
dataset = Dataset.from_list(examples).map(
encode, remove_columns=["text", "answer"]
)
split = dataset.train_test_split(test_size=0.5, seed=7)
args = TrainingArguments(
output_dir="invoice-extractor",
num_train_epochs=1,
per_device_train_batch_size=2,
logging_steps=1,
save_strategy="no",
report_to=[],
)
trainer = Trainer(
model=model,
args=args,
train_dataset=split["train"],
eval_dataset=split["test"],
data_collator=default_data_collator,
)
trainer.train()This example uses a tiny model so the mechanics are easy to inspect. A useful extractor needs a suitable pretrained model, substantially more examples, and repeated evaluation. Generation settings also matter. Sampling can produce varied but invalid answers, so extraction usually uses deterministic decoding, such as greedy decoding or a low-temperature setting.
Fine-tuning pipeline
Trade-offs and failure modes
Fine-tuning can improve consistency when the domain has stable language, a fixed schema, and enough labeled examples. It can also reduce per-request cost when a smaller local model replaces repeated calls to a large general-purpose model.
The model does not automatically become a database parser. It can still hallucinate values, omit fields, produce malformed JSON, or copy a nearby number. Fine-tuning may also teach annotation mistakes. If the training set labels a guessed currency as USD, the model may learn to guess rather than return null.
| Concern | Fine-tuning generative model |
|---|---|
| Output shape | Learned from examples; still validate every response |
| Data need | Moderate to large labeled set |
| Schema changes | Often requires new examples and another training run |
| Inference cost | Can be low with a small deployed model |
| Explainability | Generated text is harder to inspect than explicit tags |
Generative fine-tuning is different from token classification. A token classifier assigns labels such as B-VENDOR to input tokens, while a generative model writes an output sequence. Generation handles normalized fields and relations naturally, but it introduces decoding errors and makes exact span offsets harder to guarantee.
>callout note > Treat fine-tuning as behavior shaping, not as a replacement for validation. Parse the generated text, check its keys and types, and reject values that violate domain rules.
Choosing this approach
Use generative fine-tuning when the output combines several field types, requires normalization, or may change between related tasks. Prefer token classification when exact spans, predictable latency, and compact outputs matter most. A hybrid system can use a fine-tuned model for common documents and a prompted model as a fallback for unfamiliar formats.
Exercise
Why should the prompt tokens often be masked from the training loss?
Show answer
Masking focuses the loss on the target answer, so training teaches the model to generate the required extraction rather than merely reproduce the instruction.