Every research article starts with the same things: title, authors, affiliations, abstract, keywords, funding, DOI. Getting them out of a PDF into clean, structured data is boring work, and it is exactly the kind of job a small language model can do if you force its output into a schema.
In this guide you will serve Gemma 4 E2B on a free Colab TPU v5e-1, ask it for JSON that follows a schema, and score the answers against ground truth on 40 open-access articles from SciELO Brazil. You will also see where it fails: reading page images, for example, is far worse than reading text.
What you will learn
- how to serve Gemma 4 with vLLM-TorchTPU and constrain its output with a JSON schema
- how to build ground truth for free from the publisher's own XML
- how to score extraction field by field
- text layer vs page image: how big the gap is
- when prefix caching helps, and why you must check the answers, not only the speed, when you turn it on; what a profile looks like
What you need: a Google account for Colab and basic Python. No cloud credits.
The big picture
1. The task, with an example
A real case (article S1983-51752025000100216, Rev Bras Cir Pl√°st 2025). The model receives the first-page text, which starts like this:
Repercussão da abdominoplastia nos relacionamentos interpessoais e na vida social de pacientes dos Serviços Integrados de Cirurgia Plástica de São Paulo Repercussion of Abdominoplasty on Interpersonal ... Flávia Mesquita Soares1 Luiz Eduardo Felipe Abla1 José Octávio Gonçalves de Freitas1 1Serviços Integrados de Cirurgia Plástica, Hospital Ipiranga, São Paulo, SP, Brasil. and returns this (shortened):
{"title": "Repercussão da abdominoplastia nos relacionamentos interpessoais e na vida social de pacientes dos Serviços Integrados de Cirurgia Plástica de São Paulo", "language": "pt", "authors": [{"surname": "Soares", "given_names": "Flávia Mesquita"}, {"surname": "Abla", "given_names": "Luiz Eduardo Felipe"}, {"surname": "Freitas", "given_names": "José Octávio Gonçalves de"}], "affiliations": [{"institution": "Serviços Integrados de Cirurgia Plástica, Hospital Ipiranga, São Paulo, SP, Brasil", "country": "Brasil"}], "abstract": "Introduction The significant increase in overweight and obesity ...", ...} Title, language, authors and affiliation match the ground truth. Where it went wrong: the abstract is the English one, although the instruction asks for the abstract in the article's main language (Portuguese). My abstract score takes the best match over the languages the XML has, so this error costs nothing in the numbers; a stricter score would count it (see Limits).
The model reads the first page (text or image) and fills this schema:
{ "title": "...", "language": "pt", "authors": [{"surname": "...", "given_names": "..."}], "affiliations": [{"institution": "...", "country": "..."}], "abstract": "...", "keywords": ["..."], "funding": ["..."], "doi": "..." } Structured output means the server only lets the model produce tokens that keep the text valid against your schema, so the result always parses. Prefix caching reuses the work done on the start of a prompt when many requests begin the same way. TTFT is the time to the first token.
2. Step 1: get ground truth for free
SciELO publishes each article as JATS XML through its ArticleMeta API. I sampled 40 articles that are CC-BY, written mainly in Portuguese and published in 2025 or later, and turned the XML into gold labels with src/collect_gold.py. Title, authors and affiliations exist for all 40; abstract and keywords for 35.
Two traps worth knowing:
- The API's
fromparameter filters by update date, not publication date. The collector therefore filters by year itself. - The XML has no funding data for any of the 40, so funding has no automatic ground truth (see Limits).
The model never sees the XML; it sees the PDF's first page. SciELO's PDF endpoint refused Colab's addresses (HTTP 403), so I download the PDFs on my laptop, extract the first page's text (first 6,000 characters of the text layer) and a 130 dpi PNG with PyMuPDF, and upload a zip. The PDFs are not redistributed.
3. Step 2: serve the model
Open notebooks/01_extraction_colab_v5e1.ipynb, set the runtime to TPU v5e-1 and run it in order. It installs vllm-torchtpu in a Python 3.12 virtualenv (the Colab kernel is 3.13, and only one process can own the TPU, so the notebook never imports torch itself) and prints the installed versions.
vllm serve google/gemma-4-E2B-it --tensor-parallel-size 1 --port 8000 \ --structured-outputs-config '{"backend": "xgrammar"}' \ --max-model-len 8192 --limit-mm-per-prompt '{"image": 1}' Checkpoint: the first start takes about 10 minutes (570 s in my run, including the model download), later ones about 6. The server log should report:
- a 9.54 GiB checkpoint, and about 9.96 GiB of the 15.75 GiB of HBM in use after loading (E2B fits with room to spare; I did not try E4B)
- a KV cache of 234,382 tokens
Using token paddings: [16, 32, 64, 128, 256, 512, 1024, 2048]
4. Step 3: ask for JSON, then score it
The system prompt carries the instruction; the article comes last, so every request starts with the same text. The request uses response_format with json_schema. The harness in src/bench.py scores each field against the gold:
- authors: F1 over normalized surnames
- affiliations, funding: F1 with fuzzy string matching
- keywords: F1 over normalized terms; abstract: text similarity; DOI: exact match
- a field the XML lacks (abstract and keywords in 5 articles) is not scored, rather than counted as zero
5. Results: reading the page text
| valid JSON | authors F1 | affiliations F1 | keywords F1 | abstract similarity | DOI exact | |
|---|---|---|---|---|---|---|
| schema-constrained | 100% | 0.72 | 0.96 to 0.97 | 0.78 | 0.82 | 0.58 |
| schema in the prompt only (one run) | 100% | 0.78 | 0.97 | 0.80 | 0.81 | 0.55 |
Affiliations and abstracts come out well; authors and keywords are weaker; DOI is hit or miss (0.58). With 40 articles the two rows cannot be told apart: constrained decoding did not cost accuracy and guaranteed the output parses, but I cannot say it improved accuracy.
6. Which JSON-schema features work on TPU
I sent one tiny request per feature and checked that the reply obeyed the schema:
| feature | obeyed |
|---|---|
| flat object, nested object | yes |
| array of strings, array of objects | yes |
| enum, integer range, string pattern | yes |
nullable anyOf, additionalProperties: false | yes |
All nine passed. Read this carefully: my prompts could lead the model to a valid answer without the constraint, so it shows the replies obeyed the schema, not that the grammar forced each one. For anyOf with null the model returned the string "N/A", which the schema allows but which does not prove null works. A harder probe that forces violations is a good next step.
7. Text layer vs page image
Giving the model the page as an image is clearly worse here: authors 0.43 against 0.72, keywords 0.43 against 0.78, DOI 0.06 against 0.57, and valid JSON in 88 to 95% of cases (two full runs) against 100%. The image prompt averages only about 419 tokens, so I suspect the page is shrunk a lot, but I did not test that.
Practical rule: if the PDF has a text layer, send the text. Use images for scans.
8. Speed
After a server start and a discarded warm-up, I ran the same 40 articles three times, 8 at a time:
- text: about 25 s for 40 articles, about 1.6 articles per second, median latency a little over 4 s
- image: about 34 s (1.1 to 1.3 articles per second), but one run per setting stalled for up to 103 s. It was the second repetition in both of two full runs, so it is reproducible, not random. I did not investigate; my guess is new image shapes triggering XLA compilation even after warm-up
Cost per 1,000 articles = seconds per article √ó 1,000 / 3,600 √ó chip price. At US$1.20 per chip-hour for v5e on demand in us-central1 (Cloud TPU pricing page; check the live page): about US$0.21 for text, about US$0.29 for a typical image run and US$0.86 for the stalled one. Colab itself was free; this is a reference price, and it ignores the 6 to 10 minutes of each server start.
9. Does prefix caching help? Yes, but check your answers
Prefix caching reuses the computation of a prompt's shared beginning. Every request here starts with the same instruction, so it seems a good fit.
Test 1: the short instruction. Three warm runs with and without --no-enable-prefix-caching: no difference (median 25.1 s with caching, 24.0 s without). The log explains why: Using KV cache block size: 256. Caching works in full blocks of 256 tokens, and my instruction is roughly 150 tokens, less than one block, so there was nothing to cache. (This follows from the block size; I did not measure cache hits.)
Test 2: a long shared prefix. I added about 680 tokens of extraction rules to the instruction (the prompt grows from 1,064 to 1,745 tokens), enough for two full blocks.
| prefix caching | wall time for 40 articles (s) | articles/s | TTFT p50 (s) |
|---|---|---|---|
| on | 19.8 / 30.0 / 19.0 | 2.02 / 1.33 / 2.10 | 0.07 / 0.04 / 0.04 |
| off | 28.1 / 27.3 / 27.3 | 1.43 / 1.47 / 1.47 | 0.08 / 0.08 / 0.08 |
With caching the median run takes 19.8 s against 27.3 s, 27% less (one run at 30.0 s was an outlier I did not investigate).
But the answers got worse. With caching on, title exact match fell from 0.82 to 0.25, authors F1 from 0.75 to 0.34, affiliations from 0.97 to 0.58 and DOI from 0.95 to 0.25; one run also returned invalid JSON for one article. Decoding is deterministic (temperature 0), so the same prompt should give nearly the same answer with the cache on or off. A drop this large suggests the cache returned wrong data for the shared prefix.
What I do not know is the cause. My hypothesis, untested: Gemma 4 mixes sliding-window and full-attention layers (the log shows Applied TPU patch: hybrid KV cache), and prefix caching with that hybrid layout may reuse the wrong data. Repeating the test with a model that has no sliding-window layers would tell. The repo has a notebook that checks it directly (the same request twice, cache on against off).
One more thing the rules taught me: with the cache off, the long prefix lifted DOI exact match from 0.58 to 0.95. I suspect the rule that says to return the DOI without the https://doi.org/ prefix (untested).
Takeaway: whenever you turn on prefix caching with a new model, compare the answers with it on and off, not only the speed.
10. What the TPU was doing: an XProf profile
I profiled a 16-article run (PyTorch profiler flags in vLLM, /start_profile and /stop_profile) and opened the xplane.pb in XProf 2.24 (device: TPU v5 Lite):
- TPU duty cycle 53.7%: busy a little over half the window. I did not investigate the idle share.
- 98.5% of operation time on the device, 1.5% on the host.
- By category: convolution fusion 72.7%, custom calls 13.7%, the rest small. I believe convolution fusion is the XLA category for fused matrix multiplications, but I did not check a specific operation.
- FLOPS and HBM-bandwidth utilization read "unknown" because XProf saw no step marker, so this profile does not tell whether the run is compute- or memory-bound.
The profiled run is not a performance number; profiling slows the server.
11. Limits
- Funding is not measured. The XML has no funding data, so there is no automatic ground truth. Scoring it needs hand annotation of 30 to 50 articles, which I have not done.
- 40 articles, one sample, one model (E2B), one chip (v5e-1). Treat the numbers as a worked example, not a benchmark.
- DOI exact match is 0.58 with the short instruction; the long rules lifted it to 0.95, probably because they say how to write the DOI (untested).
- The abstract and title scores take the best match over the languages the XML has, so a Portuguese article whose model returned the English abstract still scores well. A stricter score would count it.
- With a long shared prefix, prefix caching degraded the answers on Gemma 4 (section 9). I do not know the cause.
- Versions on 30 November 2026:
vllm-torchtpu0.33.0 (withvllm-torchtpu-core0.33.0),torch-tpu0.2.0,libtpu0.0.50,xgrammar0.2.8. The notebooks now installvllm-torchtpu==0.33.0so you get the same version; newer releases may behave differently. - The probe shows replies obeyed the schema, not that the grammar forced them.
12. Reproduce it
Code, notebooks, gold labels and raw results: https://github.com/ahirtonlopes/gemma4-article-metadata-torchtpu.
- Build the inputs on your machine:
python3 src/build_colab_inputs.py --pids data/pids.txt --out data/colab_inputs(downloads the PDFs, writescolab_inputs.zip). - Open
notebooks/01_extraction_colab_v5e1.ipynb(full pipeline) ornotebooks/02_fair_round_colab_v5e1.ipynb(warm, repeated timing) in Colab with a TPU v5e-1 runtime, and upload the zip when asked. - Compare with
results/and rebuild the charts withtools/make_figures.py.
Data: SciELO article metadata under CC-BY. Please credit the journals and authors.
Glossary
- Structured output / constrained decoding: the server only allows tokens that keep the output valid for your schema.
- Prefix caching: reusing work on the shared start of many prompts.
- TTFT: time to first token.
- F1: the balance of precision and recall; 1.0 is perfect.
- HBM: the TPU's on-chip memory (16 GB on a v5e).
- XProf: Google's profiler for TPU programs.
#TorchTPUSprint











