# Document extraction: text to the JSON its schema asks for

Source: https://docs.surogate.ai/engine/examples/kits/extract/

Qwen3.5-0.8B learns to read a document (an email, a receipt, a badge scan, a school
notice) and return exactly the JSON object its schema describes. 60 GRPO steps on one
GPU take the share of fields it gets right on 500 held-out documents from **67.6% to
87.8%**. Small enough to run on a laptop.

| Steps | Time on one L40S | Before | After | Held-out set | Adapter |
|---|---|---|---|---|---|
| 60 | 27 min | 67.6% | **87.8%** | 500 documents | [Hub ↗](https://huggingface.co/cetusian/qwen3.5-0.8b-doc-extract-grpo) |

## The task

[LiquidAI/structured-extraction](https://huggingface.co/datasets/LiquidAI/structured-extraction)
(Apache-2.0): 6,000 training and 500 test documents in 30 types and 16 languages, each
with its own JSON Schema of 6 to 13 top-level fields. The schema goes in the system
prompt and the document is the user message. The kit trains on the 5,888 training documents
that fit a 2,048-token context with room for the answer, and evaluates on all 500 test
documents. 14 of those do not fit, and they count as wrong both before and after.

**Reward:** the fraction of top-level fields whose normalised value equals the gold
one (dates as YYYY-MM-DD, times as HH:MM, amounts as numbers). Invalid JSON scores 0. A field the
reply leaves out scores 0 even where the gold is `null`, so echoing the schema back earns nothing. The
numbers below were scored before that rule was added. Rescoring the run's saved answers with it moves the base model
down about half a point and leaves the trained model unchanged.

## Can the base model do it?

Two times in three. It reads the document well, but it often answers with a filled-in
copy of the schema instead of the object: `{"title": ..., "type": "object",
"properties": {"full_name": "Nadja Wüthrich", ...}}`. It also copies dates and times as
they are written instead of converting them to the requested format.

## Run it

```bash
CUDA_VISIBLE_DEVICES=0 surogate grpo-colocate \
  --train examples/kits/extract/train.yaml \
  --infer examples/kits/extract/infer.yaml \
  --orch  examples/kits/extract/orch.yaml
```

16 documents × 8 rollouts a step, answers up to 512 tokens, thinking off, LoRA rank 16.
27 minutes for 60 steps on one L40S.

## Measure again

| | Fields right on 500 held-out documents |
|---|---|
| Base Qwen3.5-0.8B | 67.6% |
| After 20 steps | 84.5% |
| After 40 steps | 86.4% |
| **After 60 steps** | **87.8%** |

Greedy decoding, the same prompt and budget as training, one run. Checked outside the
engine with plain `transformers` + `peft` on the first 48 test documents: 77.6% before,
91.6% after; 2 of the 48 got worse.

## What changed

A German event badge scan (excerpt):

> **Before** (score 0: the answer is wrapped in the schema, and two fields are wrong)
> ```json
> {"title": "Contact card / email signature", "type": "object",
>  "properties": {"full_name": "Nadja Wüthrich", ..., "phone": "+41 44 512 78 00",
>                 "address": "Sihlblickstrasse 14", ...}, "required": [...]}
> ```
> **After** (score 1)
> ```json
> {"full_name": "Nadja Wüthrich", "job_title": "Senior Immobilienberaterin",
>  "company": "Limmatblick Immobilien AG", "email": "n.wuethrich@limmatblick-immo.example",
>  "phone": "+41 44 512 78 63", "mobile": "+41 79 358 21 47",
>  "address": "Sihlblickstrasse 14, 8004 Zürich", "website": "www.limmatblick-immo.example"}
> ```

A Korean school notice: before, the start time came back as `"2023.04.14T08:40"`;
after, `"08:40"`, as the schema asks.

## Use the adapter

```python
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel

tok = AutoTokenizer.from_pretrained("Qwen/Qwen3.5-0.8B")
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3.5-0.8B", torch_dtype="bfloat16")
model = PeftModel.from_pretrained(base, "cetusian/qwen3.5-0.8b-doc-extract-grpo")
```

Use the system prompt from
[`environments/doc-extract`](https://github.com/invergent-ai/surogate/blob/main/environments/doc-extract/doc_extract.py) with your
own schema, and `enable_thinking=False`.

## Limits

- Scored on top-level fields. Inside a list (attendees, line items) a small slip
  costs the whole field; the model still sometimes flattens a list of objects into a
  list of strings.
- Documents up to about 2,000 tokens, the context it was trained with.
- One run, one seed.

Next: compare the other [GRPO kits](/engine/examples/kits/), or read [RL Environments](/engine/guides/rl-environments/) to build a reward of your own.
