{"id": "http://arxiv.org/abs/2607.07026v1", "title": "Constrained Decoding for Diffusion Language Models via Efficient Inference over Finite Automata", "abstract": "Constrained decoding is essential for serving LLMs, ensuring that generated outputs follow specific structures such as JSON schema-formatted function calls. Existing systems are designed for autoregressive models and assume left-to-right generation, masking out invalid next tokens at each step. Diffusion language models, however, break this assumption: they sample multiple positions simultaneously from a fully-factorized mean-field distribution at each denoising step. In this paper, we present an exact and tractable algorithm for sampling from the constrained mean-field posterior under any constraint expressible as a finite automaton. Viewing finite automata as graphical models, we obtain tractable representations of the constrained distribution that enable efficient inference. The approach guarantees constraint satisfaction by construction, supports both greedy and sampling-based decoding, and is compatible with parallel and block-wise decoding under arbitrary remasking schedules. Applying depth-reduction techniques from arithmetic circuit theory, we further reduce sampling depth from linear to logarithmic in the sequence length. Empirical evaluations on Dream-7B and LLaDA-8B show substantial accuracy gains across various tasks including function calling (xLAM, BFCL), planning (Sudoku, Countdown), text-to-SQL (Spider), and math reasoning (GSM-Symbolic), with little inference overhead relative to unconstrained decoding. For example, on BFCL-Live, our approach improves Dream-7B's greedy decoding accuracy from 63.9% to 71.5%, and stochastic sampling accuracy from 22.3% to 69.0%, where the unconstrained baseline collapses, with under 5% wall-clock overhead.", "published_at": "2026-07-08T05:48:57+00:00", "source_updated_at": null, "source_url": "https://arxiv.org/abs/2607.07026v1", "source_hash": "9ca806c70c5bce15672b8f9d9d5336c339d27c59a17bab3d0bdec963acd6513c", "source_version": "v1", "full_text_available": true, "evidence_kind": "full_text_excerpt", "analysis_scope": "full_text_excerpt", "scope": "core", "topics": ["discrete-diffusion", "reasoning"], "code_url": null, "has_code": false, "indexable": true, "authors": [], "related_ids": ["http://arxiv.org/abs/2609.04531v1", "http://arxiv.org/abs/2609.04010v1", "http://arxiv.org/abs/2609.00495v1"], "related_work": {"version": "related-work-v1", "status": "not_assessed", "reason": "missing_context", "items": []}, "review": null, "explanations": {}, "full_article_summary": {"format": "research_guide_v14", "analysis_scope": "full_article_map_reduce", "source_hash": "9ca806c70c5bce15672b8f9d9d5336c339d27c59a17bab3d0bdec963acd6513c", "source_url": "https://arxiv.org/abs/2607.07026v1", "source_version": "v1", "revision_id": "39d768c9f4625b3634faf84ed65d5ba1a922aa08aa1f8e89dc5544b9da8ff0f5", "canonical_text_hash": "8bb250313ab84fb3cbc75c4a779581aa2f4b58d649d65e428edc703e73f12c14", "prompt_version": "full-article-research-guide-v14", "sections": {"verdict": {"ru": "Сильный метод для конечных автоматов: он обеспечивает точную глобально ограниченную выборку и 100% синтаксическую валидность, заметно улучшая структурированную генерацию при небольших накладных расходах. Область применимости ограничена регулярными ограничениями; семантически ошибочные, но валидные значения он не исправляет.", "en": "A strong method for finite-automaton constraints: it enables exact globally constrained sampling and 100% syntactic validity, substantially improving structured generation with small overhead. Its scope is limited to regular constraints, and it does not correct semantically wrong but schema-valid values."}, "main_idea": {"ru": "Представить конечный автомат как цепочную графическую модель и точно объединить его с факторизованным распределением диффузионной языковой модели на каждом шаге денойзинга. Forward–backward inference и tree-based sampling сохраняют целевое ограниченное распределение, включая при стохастической генерации и произвольных схемах remasking.", "en": "Represent a finite automaton as a chain graphical model and exactly combine it with the diffusion language model’s factorized distribution at every denoising step. Forward–backward inference and tree-based sampling preserve the target constrained distribution, including under stochastic generation and arbitrary remasking schedules."}, "claims": {"ru": "Авторы заявляют, что метод гарантирует валидные выходы, поддерживает DFA/NFA, снижает глубину последовательной выборки с линейной до O(log L), а state-space aggregation уменьшает вычислительную стоимость. На BFCL-Live с Dream-7B точность выросла с 63,9% до 71,5% при greedy decoding и с 22,3% до 69,0% при sampling; валидность составила 100%.", "en": "The authors claim that the method guarantees valid outputs, supports DFAs and NFAs, reduces sequential sampling depth from linear to O(log L), and lowers computation through state-space aggregation. On BFCL-Live with Dream-7B, accuracy increased from 63.9% to 71.5% with greedy decoding and from 22.3% to 69.0% with sampling; validity was 100%."}, "mechanism": {"ru": "Спецификация: состояние автомата — текущая позиция и automaton state; эмиссионные веса — токеновые вероятности факторизованного denoising posterior, ограниченные допустимыми переходами. Forward–backward сообщения учитывают принимающие состояния и взвешивают ребро через partition function допустимого суффикса; для NFA агрегируются все ребра между парами состояний. На каждом шаге вычисляются constrained marginals для выборки и remasking. Для параллельного режима bottom-up строятся skip-transition products, затем рекурсивно выбираются midpoint states; сегменты условно независимы, поэтому выборка точна и имеет O(log L) глубины при O(L(|S|³+|E||V|)) работе. Для воспроизведения: (1) построить DFA/NFA для ограничения; (2) получить факторизованные токеновые scores модели; (3) выполнить state-space forward–backward; (4) использовать marginals для remasking и constrained sampling; (5) при необходимости применить tree sampler и сравнить с edge-space или последовательным режимом. Точные детали обучения модели отсутствуют: метод описан как decoding/inference procedure.", "en": "Specification: the automaton state is the current position and automaton state; emission weights are token probabilities from the factorized denoising posterior, restricted to allowed transitions. Forward–backward messages incorporate accepting states and weight each edge by the valid-suffix partition function; for NFAs, all edges between state pairs are aggregated. At each denoising step, constrained marginals support sampling and remasking. For parallel inference, skip-transition products are built bottom-up, then midpoint states are sampled recursively; segments are conditionally independent, yielding exact sampling with O(log L) depth and O(L(|S|³+|E||V|)) work. Reproduction: (1) build a DFA/NFA constraint; (2) obtain factorized token scores; (3) run state-space forward–backward inference; (4) use marginals for remasking and constrained sampling; (5) optionally apply the tree sampler and compare it with edge-space or sequential sampling. Training details are absent: the method is presented as a decoding/inference procedure."}, "evidence": {"ru": "Наблюдаемые результаты включают BFCL, Sudoku, Countdown, GSM-Symbolic и Spider на Dream-7B и LLaDA-8B. На 200 BFCL-примерах tree sampling дал 79,2% accuracy при 25,35 мс и 4% overhead против 67,5% и 24,26 мс без ограничений. Constraint-aware remasking превосходил mean-field confidence, особенно при плохом согласовании свободной выборки с валидными выходами; при уменьшении denoising steps метод сохранял большую устойчивость. Сравнения проводились при согласованных длине и числе шагов, но превосходство над всеми альтернативами и общая эффективность вне указанных задач не установлены.", "en": "Observed results cover BFCL, Sudoku, Countdown, GSM-Symbolic, and Spider with Dream-7B and LLaDA-8B. On 200 BFCL examples, tree sampling achieved 79.2% accuracy at 25.35 ms with 4% overhead, versus 67.5% and 24.26 ms without constraints. Constraint-aware remasking outperformed mean-field confidence, especially when unconstrained sampling poorly matched valid outputs; robustness also improved when denoising steps were reduced. Comparisons matched sequence length and denoising steps, but superiority over all alternatives and general efficiency outside the reported tasks are not established."}, "applicability": {"ru": "Метод полезен для tool calling, JSON/schema decoding, фиксированных символов в Sudoku и других задач, задаваемых DFA/NFA, особенно когда требуется гарантированная синтаксическая валидность, стохастическая выборка или малое число шагов денойзинга. Tree sampling особенно подходит для GPU-параллелизма и снижения критического пути.", "en": "The method is useful for tool calling, JSON/schema decoding, fixed-cell Sudoku constraints, and other DFA/NFA-specifiable tasks, especially when guaranteed syntactic validity, stochastic sampling, or few denoising steps are required. Tree sampling is particularly suitable for GPU parallelism and reducing the critical path."}, "limitations": {"ru": "Метод напрямую покрывает только конечные автоматы и не распространяется на более богатые контекстно-свободные грамматики. Он не исправляет schema-valid semantic errors: неверные аргументы, чрезмерно конкретные locations или пропущенные выводимые optional fields. Для NFA до reweighting распределение зависит от числа accepting paths, поэтому требуется учитывать выбранную семантику автоматов. Дополнительные детали обучения, памяти и фактического масштабирования на более длинных последовательностях не указаны.", "en": "The method directly covers only finite automata and does not extend to richer context-free grammars. It cannot fix schema-valid semantic errors such as wrong arguments, over-specified locations, or omitted inferable optional fields. For NFAs, the pre-reweighting distribution depends on the number of accepting paths, so the intended automaton semantics must be specified. Further details on training, memory use, and actual scaling to longer sequences are not provided."}, "next_action": {"ru": "Провести контролируемый benchmark на одном DFA- и одном NFA-задании с одинаковыми моделью, длиной и числом denoising steps: сравнить unconstrained, sequential constrained и tree constrained decoding по accuracy, validity, latency, FLOPs и memory, отдельно проверив semantic errors.", "en": "Run a controlled benchmark on one DFA and one NFA task with the same model, sequence length, and denoising steps: compare unconstrained, sequential constrained, and tree constrained decoding on accuracy, validity, latency, FLOPs, and memory, while separately tracking semantic errors."}}, "source_coverage": {"canonical_text_hash": "8bb250313ab84fb3cbc75c4a779581aa2f4b58d649d65e428edc703e73f12c14", "covered_chunks": 6, "map_input_digest": "19bb1d8dd747d8722f1c67150b0247d9df8abb65ce595c21ed8fb0cd3959dd5c", "prompt_version": "full-article-research-guide-v14", "revision_id": "39d768c9f4625b3634faf84ed65d5ba1a922aa08aa1f8e89dc5544b9da8ff0f5", "total_chunks": 6}}, "resources": {"version": "paper-resources-v1", "source_hash": "9ca806c70c5bce15672b8f9d9d5336c339d27c59a17bab3d0bdec963acd6513c", "evidence_kind": "full_text_excerpt", "availability": "not_checked", "limited": false, "items": []}, "slug": "2607.07026-constrained-decoding-for-diffusion-language-models-via-efficient-inference-over-finite-automata"}