Training Through the Grammar: Constraint-Masked Fine-Tuning for Visually Grounded Choices Across a Sequence of Domains

When a vision-language model has to output something a program will parse, the possible answers usually come from a fixed list. It might be an entity ID from a catalog, a product attribute value, a relation label, or a field in a JSON object. Grammar-constrained decoding guarantees that the output is one of those legal options by masking illegal tokens at every generation step. It does not help the model choose the right legal option. That choice is where the image matters: a terse caption mentions "Jordan" and only the picture says whether it means the country or the basketball player. Today, models are fine-tuned with ordinary next-token loss and the grammar is added only at test time. During fine-tuning, much of the gradient is spent teaching the model which tokens are legal, which the grammar already guarantees. When the model is later fine-tuned on a second and third domain, that redundant learning is also what gets overwritten.

We propose to put the grammar inside the training loss. The model's probabilities are renormalized over only the legal next tokens before computing cross-entropy. Each update then teaches nothing except how to discriminate among legal candidates, which is largely the visual tie-breaking skill. The domain-specific part (which entities, which values, which schema) lives in a grammar that can be swapped without retraining. We test whether this one change makes a single model adapt across a sequence of multimodal structured-prediction domains with less forgetting, more reliance on the image, and better handling of entities never seen in training.

Core Claim

Let $x$ be the input (image plus text) and $G(x)$ an input-dependent grammar, for example a trie over the tokenized names in the current domain's catalog or a JSON schema whose value slots are catalog-restricted. Let $\mathcal{A}_t \subseteq \mathcal{V}$ be the tokens of the vocabulary $\mathcal{V}$ that $G(x)$ permits after the gold prefix $y_{<t}$. With model logits $z_\theta$, we train on

$$\mathcal{L}_{\text{CM}}(\theta) = -\sum_t \log \frac{\exp z_\theta(y_t \mid x, y_{<t})}{\sum_{v \in \mathcal{A}_t} \exp z_\theta(v \mid x, y_{<t})}.$$

On deterministic positions such as brackets, keys, and forced continuations of a trie, $|\mathcal{A}_t|=1$ and the loss is exactly zero. On branching positions, the gradient touches only the logits of legal competitors. Standard cross-entropy, by contrast, pushes down all $|\mathcal{V}|$ logits at every position. This produces three predictions.

The first is less drift per domain and therefore less forgetting of earlier domains. The reason is that the gradient mass is concentrated on far fewer positions and logits.

The second is that the image is used more. Once format and catalog membership are given, the remaining errors are exactly the cases text cannot resolve.

The third concerns entities absent from training. If a NIL ("not in catalog") branch is included in $G(x)$, the model learns when to abstain, and new catalog entries can be added at test time without retraining.

Relation to Prior Work

The closest work is Generative Multimodal Entity Linking (GEMEL). It maps frozen CLIP features into soft prompts for a frozen LLM and decodes entity names under a knowledge-base prefix trie, reaching 86.3% accuracy on WikiDiverse and 82.6% on WikiMEL. GEMEL supplies our trie machinery and our strongest single-domain reference. It differs from this proposal in three ways. Its trie is applied only at decoding, not in the training loss. It works within one fixed domain. And it explicitly assumes every answer is in the knowledge base. We change all three.

Two papers supply the decoding method and motivate the gap. Grammar-Constrained Decoding for Structured NLP Tasks without Finetuning introduces input-dependent grammars and shows that a frozen text LLM under such constraints rises from 54.1% to 80.3% on entity disambiguation and beats a fine-tuned GenIE baseline on closed information extraction. SynCode provides the token-level masking that handles subword tokens straddling grammar terminals, and eliminates JSON syntax errors on JSON-Mode-Eval. We reuse both techniques to compute $\mathcal{A}_t$. Neither paper trains with the mask, uses images, or studies adaptation across domains. The first paper's frozen-model result also constrains our design: it is the "no training at all" alternative we must beat.

Work on sequential adaptation motivates the forgetting question. Don't Stop Pretraining shows staged adaptation beats one-shot training and that training on unrelated domains hurts. The C-to-Rust curriculum gains on its target (87.3% vs 72.3%) while losing general ability (SWE-bench Verified 72.4% to 70.6%). PathologyVLM applies a multi-stage curriculum to a vision-language model but produces free text with no output guarantees. All three treat format as something to be learned by the weights. We treat format and catalog as external, which is what could make sequential adaptation cheaper.

Adaptive Minds takes the opposite route to the same tension: it isolates format into per-task LoRA adapters chosen by a router. It sidesteps forgetting by never sharing parameters, and it is unimodal. It is our main parameter-isolation competitor.

Agent-X motivates the whole line. In its error analysis of vision-centric tool use, invalid JSON and misread visual content are the two dominant failures, and no model exceeds a 50% full-chain success rate. Its agent setting is a later target rather than our main testbed.

Research Program

The model. We build a single LoRA-adapted vision-language model on Qwen2.5-VL-7B (an open model evaluated in Agent-X). It is trained sequentially on four multimodal structured-prediction domains, each with its own grammar.

The domain sequence. It runs from WikiMEL to WikiDiverse to MEPAVE to MNRE.

  • WikiMEL and WikiDiverse are entity linking. The grammar is a catalog trie plus a NIL branch.
  • MEPAVE is e-commerce attribute–value extraction. Output is a JSON object whose keys are the category's attributes and whose values are restricted to spans of the product text or NIL.
  • MNRE is relation extraction. Output is a JSON triple with the relation drawn from its 23 labels.

These domains differ in image type (news photos, product shots, tweets), schema, and catalog. That makes forgetting measurable and tests whether the "discriminate among legal options using the image" skill carries over between them.

Unseen entities. For each linking domain we hold out 15% of catalog entities from training. At test time we evaluate them both as in-catalog (their names are added to the trie) and as NIL (their names are removed). This directly probes GEMEL's closed-world limitation.

Analyses. Beyond accuracy, we run three analyses tied to the mechanism.

  • Image reliance. We measure the accuracy drop when the image is replaced by a different image from the same domain. Prediction 2 says this drop should be larger under constraint-masked training.
  • Gradient concentration and drift. We measure the fraction of loss mass on branching positions and the parameter drift per domain, including the norm of each LoRA update and the change in outputs on earlier domains' held-out inputs.
  • Unconstrained side effects. We evaluate unconstrained generation on a general-capability probe to see whether training through a mask harms behavior outside the grammar. Agent-X serves as the probe, scored by goal accuracy and format-error rate.

Baselines

Reference points with no fine-tuning. The "do nothing" reference is the base model prompted with few-shot examples and decoded without constraints. It shows how often outputs are unparseable or off-catalog. The stronger no-training reference is the same base model with input-dependent grammar-constrained decoding, following Grammar-Constrained Decoding for Structured NLP Tasks without Finetuning. This tests that paper's claim that constraints make fine-tuning unnecessary. To beat it, our method must improve on every domain, not just on parse validity, where both should be perfect.

The strongest competitor and key ablation. This is standard sequential LoRA fine-tuning with ordinary cross-entropy, decoded at test time under the identical grammar. It is the obvious recipe and differs from ours only in where the mask sits, so it isolates the proposal's key ingredient. Both runs use the same domain order, data, LoRA rank, steps, learning-rate sweep (the same number of trials, selected on the same validation split of the current domain), and test-time grammar. We count it as beaten only if constraint-masked training shows lower average forgetting (backward transfer across the sequence) and equal or higher final average accuracy, across three seeds and two domain orders.

Published single-domain reference points. For the published numbers on these benchmarks, GEMEL reports 86.3% accuracy on WikiDiverse and 82.6% on WikiMEL (Generative Multimodal Entity Linking). M-JAVE reports 87.17% value-extraction F1 on MEPAVE (Multimodal Joint Attribute Prediction and Value Extraction for E-commerce Product). The retrieval-augmented model reports 84.64% F1 on MNRE (Multimodal Relation Extraction with Cross-Modal Retrieval and Synthesis). Each is a specialist trained on one domain only. Our sequential model is not expected to beat them. Matching them on the final domain while retaining earlier ones within a few points would be the practically meaningful result.

Parameter-isolation baseline. Separate per-domain LoRA adapters with oracle domain selection, in the spirit of Adaptive Minds, give an upper bound with zero forgetting by construction.

Replay baseline. Sequential standard fine-tuning with 5% replay of earlier domains tests whether a classic remedy for forgetting already closes the gap.

Joint baseline. A model trained on all four domains pooled at once marks the non-sequential ceiling.

Why not just…?

Why not just fine-tune normally and add the grammar at decoding time? This is the real threat, because it already gives perfect validity. It differs from our method only if the redundant format-learning gradient actually causes forgetting or crowds out visual learning. That is an empirical question we have not settled. The core ablation in the Baselines section answers it directly. If backward transfer and image reliance are indistinguishable between the two, the proposal's claim is false, and we will report it as such: "masking at test time is enough."

Why not just use a frozen model with input-dependent constraints and skip training? Grammar-Constrained Decoding for Structured NLP Tasks without Finetuning shows this is strong for text. GEMEL's gains also came from training a visual mapper, with tail-entity accuracy on WikiDiverse rising from 37.5% text-only to 57.5% with images. That suggests a frozen model does not use visual evidence well enough unaided. The frozen-plus-grammar baseline measures this on all four domains.

Why not just keep one adapter per domain? It avoids forgetting at the cost of parameters that grow with every domain and a router that must pick the right adapter, which Adaptive Minds shows can itself fail. It also gives no transfer to a new domain. Our model must come close to the oracle-routed version while using one adapter. We also test zero-shot transfer to a fifth domain, N24News headline classification with a 24-label grammar, where separate adapters have nothing to offer.

Why not just use replay? Replay is cheap and may remove most forgetting on its own. We therefore also run constraint-masked training with replay. If the masked loss adds nothing once replay is present, its value reduces to the no-replay setting, and we will say so.

Proposed Experiments and Decisive Checks

Every method is run over the four-domain sequence in two orders and three seeds. We report three things for each domain after each stage: accuracy or F1, the parse-validity rate, and the off-catalog rate.

The first decisive check is the core ablation. We compare backward transfer and final average score between constraint-masked and standard sequential fine-tuning under the same test-time grammar. The predicted signature is that the advantage grows with the share of deterministic tokens in the gold outputs, which is high for the JSON-schema domains (MEPAVE, MNRE) and lower for entity names. A per-domain correlation between that share and the reduction in forgetting would support the mechanism rather than an incidental effect.

The second check is image reliance. If masked training does not increase the accuracy drop under image swapping, prediction 2 fails, even if forgetting improves.

The third check concerns held-out entities. We measure in-catalog accuracy after adding their names to the trie, and NIL precision and recall after removing them. Both are compared against standard fine-tuning with the same NIL branch.

The fourth check tests unconstrained side effects. We compare Agent-X goal accuracy and format-error rate before and after the sequence. Published references there are 37% for GPT-4o and 40% for Gemini 2.5 Pro; the file gives no reported Qwen2.5-VL-7B goal accuracy.

The method succeeds if it shows lower forgetting than the standard-loss ablation, a larger reliance on the image, and accuracy within a few points of oracle per-domain adapters while using a single adapter. It fails cleanly if the core ablation shows no difference.