MedGemma 1.5 4B on vLLM with guided JSON: output pads with whitespace until max_new_tokens instead of finishing

Hi everyone,

We’re building a healthcare application that uses MedGemma to extract structured information from medical documents into JSON. We self-host the model and have run into two problems with long structured outputs that we haven’t been able to solve. If anyone has faced something similar or found a resolution, we’d be very grateful if you could share it.

Question 1: Runaway whitespace under guided JSON decoding
We serve google/medgemma-1.5-4b-it with vLLM 0.30.0 (bf16, --max-model-len 131072, temperature 0, fixed seed, max_new_tokens 8192) and use vLLM’s response_format: json_schema (guided decoding) so the model returns JSON matching our schema. When a value is not present in the input, our instructions tell the model to write a fixed placeholder string, and most of the time it does. But on a noticeable share of requests, the model stops producing content partway through the JSON and emits only whitespace (spaces and newlines) until it hits the token limit. The response ends with finish_reason="length", the JSON is incomplete and can’t be parsed, and in one batch eight responses together used about 83,000 output tokens, far more than a normal answer. Because we run at temperature 0 with a fixed seed, retrying gives exactly the same result. We tried disabling “any whitespace” in the structured-output backend, but the problem continued. Has anyone seen MedGemma do this under guided decoding? Is there a recommended vLLM structured-output backend or setting for MedGemma, or a schema or prompt pattern (for example, avoiding optional or deeply nested fields) that stops the model from padding instead of writing the placeholder or closing the JSON?

Question 2: Output length limit for large structured answers
Some of our schemas are fairly large, and a complete, correct answer needs an estimated 3,500–5,500 output tokens. Our server default is 8,192 new tokens, and we’re unsure whether MedGemma 1.5 4B handles long structured outputs reliably at that length. Was the model tuned mainly on shorter outputs? Is there a practical or recommended maximum output length, beyond which quality drops or runaway generation becomes more likely? We also see that very large JSON schemas, once compiled into a decoding grammar, seem to make the model less reliable than larger general-purpose models on the same schema. Would you recommend splitting one large schema into several smaller requests, or is there a known limit on schema size or complexity for MedGemma with guided decoding? Any guidance on output limits and schema design for long structured extractions would help a lot.

Happy to share more technical details (vLLM launch flags or a sample of the truncated output) if that would help. Thanks in advance for any pointers!

Hi @Aravind_S, Thanks for the detailed report!

Guided decoding behavior and long structured extractions can vary significantly depending on the backend and schema setup. To help troubleshoot this accurately, could you share a minimal reproduction or a few more technical details?

  • vLLM Launch Flags & Backend: Could you share your vLLM launch flags? Specifically, which guided decoding backend are you currently using?
  • Minimal Schema & Sample Output: Could you post a minimal snippet of your schema and an example of the truncated JSON output where the whitespace loop begins?
  • Output Length & Schema Size: Regarding your question on output limits, sustaining 3,500–5,500 tokens of strict JSON in a single shot is very demanding for any model and long constrained generations often see reliability drops. Splitting large schemas into smaller, logically grouped requests is generally recommended, have you had a chance to test breaking your schema down into smaller requests yet?

Hi Sonali, thank you for the reply. Here are the details, including a minimal reproduction.

1. Launch flags and backend

vLLM 0.30.0 (xgrammar 0.2.8, transformers 5.17.0, torch 2.13.0) on one NVIDIA L4 (23 GB), model google/medgemma-1.5-4b-it served from a local copy:

vllm serve /opt/models/medgemma \
  --served-model-name medgemma \
  --dtype bfloat16 \
  --max-model-len 131072 \
  --gpu-memory-utilization 0.92 \
  --override-generation-config '{"temperature": 0.0, "max_new_tokens": 8192}' \
  --host 0.0.0.0 --port 8000

We currently pass no --structured-outputs-config (we tried one and reverted it, see point 3), so the server log shows the default:

StructuredOutputsConfig(backend='auto', disable_any_whitespace=False, disable_additional_properties=False, reasoning_parser='', reasoning_parser_plugin='', enable_in_reasoning=False)

2. Minimal reproduction

Every field in the schema is required. The prompt asks for a fixed placeholder when a value is absent. The report states the tumour size but not the focality.

curl -s localhost:8000/v1/chat/completions -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d '{
 "model":"medgemma","temperature":0,"seed":7,"max_tokens":600,
 "messages":[{"role":"user","content":"Extract the fields from this pathology report. If a value is not in the report, write \"Not mentioned in the report\".\n\nReport: Left breast core biopsy. Invasive ductal carcinoma, grade 2. Tumour size 2.3 cm."}],
 "response_format":{"type":"json_schema","json_schema":{"name":"Path","schema":{"type":"object","required":["specimen_type_and_site","histological_type","tumour"],"properties":{"specimen_type_and_site":{"type":"string"},"histological_type":{"type":"string"},"tumour":{"type":"object","required":["grade","size","focality"],"properties":{"grade":{"type":"string"},"size":{"type":"string"},"focality":{"type":"string"}}}}}}}
}'

Result: finish_reason: "length", 974 characters, of which the last 807 are whitespace.

{
  "specimen_type_and_site": "Left breast core biopsy",
  "histological_type": "Invasive ductal carcinoma",
  "tumour": {
    "grade": "Grade 2",
    "size": "2.3 cm"
  
  
  
  ... (newline + two spaces, repeated until the token limit)

The content is correct up to "size". The model then emits only newline and indent, right where the next required field (focality) has no value in the input. It looks as if the model wants to close the object there, the grammar does not allow } yet, and whitespace is the only other token it permits. With our full schema and the default 8,192-token limit, the same thing costs 8,192 tokens and about 268 seconds per request. At temperature 0 with a fixed seed, a retry gives the same output.

3. What we tried

  • Per request, structured_outputs: {"disable_any_whitespace": true}: accepted, but no effect with backend: auto. The output is still pretty-printed and still runs away.
  • Server level, --structured-outputs-config '{"backend": "xgrammar", "disable_any_whitespace": true}' (with backend: auto vLLM 0.30 refuses to start with this option): the whitespace run stops, and our large pathology schema then completes in about 650 tokens with correct values and the placeholder where it belongs. But a small 4-field schema that worked before now fails differently. The model never closes a string value and fills it with invented text, for example "HER2 negative 2+ (negative) / HER2 negative 3+ … Final Final Final", up to the token limit. With a maxLength on the field it finishes, but the value is that invented text. A visible failure is safer for us than a wrong clinical value, so we reverted to the default.

4. Splitting the schema

We have not tested it, and we would prefer not to rely on it, for these reasons:

  • Schema size does not seem to be the trigger. The reproduction above has three nested fields and fails at the first required field whose value is absent. A split schema would fail the same way in whichever part contains such a field.
  • Each part must re-read the whole report. Our documents are long (multi-page pathology, radiology, clinical and genomics reports), so splitting one schema into N requests multiplies the input tokens by N while the output stays about the same.
  • Volume. One 12-page record is typically split into about 13 reports and already needs around 70 model calls end to end. We run six extraction agents, each with its own schema.
  • We run two models on every report. A second, independent commercial model (billed per token) fills the same schema, and the two answers are compared field by field. A split would either apply to both models, which multiplies the input tokens we pay for on the second one, or need a MedGemma-only path in all six agents.
  • Capacity. MedGemma runs on a single L4, so several times more requests per document is a real limit for us.
  • Related fields belong together. For example, staging depends on tumour size and nodal status, and we would rather the model fills them in one pass.

So two questions:

  • Is there a backend or setting you recommend for MedGemma 1.5 that avoids both behaviours (the whitespace run, and the unclosed string when whitespace is disabled)?
  • For absent values, would you recommend making those fields optional so the model may omit them, instead of requiring a placeholder string? Or a different pattern, such as null in a ["string","null"] type? That would keep a single request, which matters a lot for us.

Happy to run anything you would like to see on our side.

Hii Sonali, let me know is there any additional input you needed from my end..!!

You have diagnosed the exact failure mechanism in point 2: when greedy decoding (temperature 0) cannot reconcile an absent clinical finding with a required non-nullable string schema, the logits for arbitrary string tokens collapse. Because JSON grammar rules permit arbitrary formatting whitespace between tokens, xgrammar’s pushdown automaton leaves whitespace tokens as the only unmasked paths with non-zero probability. The model enters a deterministic whitespace sink until hitting max_new_tokens.

When you disabled whitespace, you removed that escape hatch, forcing the model to generate open string tokens under zero grounding, causing the repetition runaway you observed.

Here is the direct resolution for your two questions.


1. Schema Architecture for Absent Clinical Values (Question 2)

Use explicit nullable types (type: ["string", "null"]), never boilerplate placeholder strings, and avoid purely optional omitted keys.

Why placeholder strings fail:
Instructing a 4B parameter model to emit "Not mentioned in the report" requires autoregressive commitment across 6 to 8 tokens under conditions of negative evidence. If the model hesitates at token 1 of the placeholder, the grammar engine’s logit mask deadlocks against the vocabulary.

Why omitting keys (optional fields) is problematic:
In clinical pathology pipelines, an omitted key creates provenance ambiguity: did the extraction pipeline fail to parse the section, or was the finding truly absent from the biopsy? Beyond provenance, small instruction-tuned models given optional keys frequently hallucinate plausible clinical defaults (such as predicting unifocal disease) to satisfy common training distributions.

Why type: ["string", "null"] resolves the deadlock:
When a finding is absent, the literal null is a single, concise token (or two tokens depending on the vocabulary split). The probability mass on null when a concept is missing from the prompt context is orders of magnitude higher than arbitrary placeholder strings.

Update your schema to define absent attributes as nullable:

{
  "name": "Path",
  "schema": {
    "type": "object",
    "required": ["specimen_type_and_site", "histological_type", "tumour"],
    "properties": {
      "specimen_type_and_site": { "type": ["string", "null"] },
      "histological_type": { "type": ["string", "null"] },
      "tumour": {
        "type": "object",
        "required": ["grade", "size", "focality"],
        "properties": {
          "grade": { "type": ["string", "null"] },
          "size": { "type": ["string", "null"] },
          "focality": { "type": ["string", "null"] }
        }
      }
    }
  }
}

Prompt update:
Adjust your prompt instruction to match:
"Extract the fields from this pathology report. If a specific finding is not documented in the report, set its value to null."

This outputs:

{
  "specimen_type_and_site": "Left breast core biopsy",
  "histological_type": "Invasive ductal carcinoma",
  "tumour": {
    "grade": "Grade 2",
    "size": "2.3 cm",
    "focality": null
  }
}

Downstream ingestion can cleanly evaluate if record["tumour"]["focality"] is None: without brittle string matching.


2. Guided Decoding Engine & Tokenizer Stop Signals (Question 1)

If you retain standard JSON whitespace formatting, xgrammar it operates reliably once nullable types eliminate the dead-end state. However, on vLLM 0.30.0 with Gemma-derived architectures, check two specific runtime configurations:

A. Explicit Gemma Stop Token IDs

MedGemma uses the Gemma SentencePiece vocabulary, which features dual end-of-sequence boundaries: <eos> (Token ID 1) and <end_of_turn> (Token ID 107). If vLLM’s chat template or your completion call does not register ID 107 as an early-stopping token, guided decoders can stall after closing the root object bracket }.

In your inference payload or default sampling parameters, explicitly pass:

{
  "stop_token_ids": [1, 107],
  "stop": ["<end_of_turn>"]
}

B. Alternative Engine: Outlines Backend

If you encounter edge-case crashes with xgrammar 0.2.8 on nested schemas, switch vLLM to the Outlines backend:

--guided-decoding-backend outlines

Outlines constructs an indexed finite-state automaton (FSA) across the vocabulary. On byte-fallback SentencePiece tokenisers, Outlines handles transitions across punctuation boundaries more gracefully than xgrammar’s pushdown parser when handling nested object closures.

With nullable types in place, you can keep the default whitespace formatting enabled (disable_any_whitespace: false), avoiding both the whitespace spin and the invented text runaway in a single, un-split extraction request.