NeurIPS 2026Coming to NeurIPS?Explore papers, orals & directions

Constrained Code Generation with Diffusion Language Models

Lize Shao, Michael Cardei, Zichen Xie, Ferdinando Fioretto, Wenxi WangNeurIPS 2026

TL;DR

Standard code generation models write programs one token at a time from left to right, meaning you usually can't catch deep logical bugs or security flaws until the entire program is already written. Constrained Diffusion for Code (CDC) flips this script by hijacking discrete diffusion language models mid-generation—spotting bugs and vulnerabilities in the rough drafts of a program and performing surgical, localized fixes before the final code is ever committed. Best of all, it boosts correctness and security without retraining the underlying model.

Figure 1: CDC vs. other diffusion code baselines on HumanEval-X (HE-X), MBPP, CWEval and LLMSecEval+.

What Problem Does This Paper Address?

Writing code isn't like writing prose; a program can look completely plausible to a language model while harboring a silent runtime bug or an exploitable security vulnerability. Because functional correctness and security depend on global dataflow and program-wide semantics, you cannot easily enforce them while generating code strictly left-to-right (autoregressively).

Historically, if an AI-generated program failed a test or security check, our main recourse was post-hoc repair: throw the output back at the model with an error message and ask it to regenerate large chunks—or the entire program—from scratch. In a massive combinatorial search space where valid, secure programs are rare, waiting until generation is finished to intervene is wasteful and unreliable.

Diffusion language models (DLMs) offer a fascinating alternative. Instead of writing left-to-right, they start with a sequence of [MASK] tokens and iteratively refine the entire program at once. Because DLMs expose a global "rough draft" of the whole program at every denoising step, the authors ask: can we evaluate and steer the code while it is still materializing?

Methods

The authors introduce Constrained Diffusion for Code (CDC), an inference-time neurosymbolic framework that leaves the base diffusion weights frozen and treats sampling as an editable trajectory.

Figure 2: Overview of CDC.

At selected denoising steps, the base model predicts a clean-token distribution across the whole sequence. CDC decodes this intermediate draft, evaluates it against specifications, pinpoints the exact tokens causing trouble, and applies a localized correction—anchored via Kullback–Leibler (KL) divergence so it doesn't drift too far from the base model's distribution.

CDC instantiates this loop in two ways, depending on the type of constraint:

  • GradGuide (Soft Surrogate Guidance for Functionality): Since you can't take gradients through a compiler or unit test during denoising, GradGuide uses a lightweight, pre-trained neural surrogate that predicts test-pass probabilities from token embeddings. A single backward pass highlights high-saliency "buggy" spans via gradients, shifting token probabilities toward working logic and re-masking flawed regions so future steps can rewrite them.
  • MDFI (Mid-Diffusion Feedback Injection for Security): Security is a hard constraint. At specific checkpoints, CDC runs a symbolic static program analyzer on the partial code's syntax and dataflow graphs. If it flags a vulnerability, MDFI surgically re-masks offending tokens (for substitutions) or splices in fresh [MASK] tokens near structural anchors (for missing checks), injecting remediation hints into the context for the remaining denoising steps.

Datasets

  • Evaluation: Functional correctness and syntax compilation are tested on HumanEval-X C++ (164 tasks) and MBPP-C++ (397 tasks). Security and joint functionality-security are evaluated on CWEval (spanning Python, JS, C++, and Go) and LLMSecEval+.
  • Training: Base diffusion models are never retrained. The GradGuide surrogate is trained once ahead of time (taking 1.8 GPU-hours) using execution-driven labels from CodeContests problems, kept strictly disjoint from the evaluation benchmarks. No new benchmarks are introduced.

Key Insights and Ideas

  • Syntax rules alone don't fix logic: Enforcing context-free grammar rules during diffusion (like the baseline CFG-CD) helps code compile, but sometimes hurts functional pass rates. Steering with execution-trained signals (CDC) improves both logic and compilation simultaneously.
  • Surgical edits beat full rewrites: Post-hoc autoregressive re-prompting rewrites a median of 98–123 tokens per fix. Because diffusion states remain globally editable, CDC fixes bugs and vulnerabilities by editing a median of just 12 to 35 tokens—leaving working code intact.
  • Symbolic static analysis is practically free: Calling a CPU-based static analyzer seven times mid-diffusion in MDFI adds just 46 milliseconds total (a 2.3–6.1% latency bump), nearly tripling the throughput of secure, working programs.

Key Results

  • Functionality & Syntax: Using Dream-Coder 7B, CDC jumps pass@1 from 34.1% to 65.2% on HumanEval-X C++ (even beating autoregressive DeepSeek-Coder 6.7B with re-prompting at 64.0%) and from 27.7% to 59.2% on MBPP-C++. As a side effect, C++ compilation rates climb from 67.1% to 79.3% on HumanEval-X and from 41.1% to 72.0% on MBPP-C++.
  • Security: On CWEval, CDC nearly triples joint functionality-security (fs@1) over vanilla diffusion from 12.0% to 34.3%. On LLMSecEval+, it pushes sec@1 from 54.7% to 80.7%, outperforming all baselines including autoregressive re-prompting (64.7%).
  • Overhead: While MDFI adds negligible latency (1.02–1.06×), GradGuide's neural surrogate passes increase mean latency to 1.72–2.01× (median 1.41–1.47×) and peak GPU memory by 53–61%.
Table 2: Security-aware code generation on CWEval and LLMSecEval+. Parenthesized values give the absolute change relative to the vanilla model: green marks gains of ≥10%, yellow gains of <10%, and red regressions. Within each model, the best performance is bolded.

Limitations and Future Work

CDC is only as smart as its evaluators: GradGuide can be misled by noisy surrogate predictions (swapping in an uncalibrated surrogate actually drops pass@1 below vanilla decoding), while MDFI is bounded by static analyzers that can miss bugs or raise false alarms. Furthermore, GradGuide introduces noticeable GPU memory and latency overhead, and the experiments are confined to 7B-scale models and standalone benchmark tasks rather than massive, multi-file software repositories. Future extensions were not explicitly discussed in the paper, though scaling to repository-level contexts and richer verifiers naturally looms on the horizon.

Summary updated

BibTeX
@inproceedings{shao2026constrained,
  author = {Lize Shao and Michael Cardei and Zichen Xie and Ferdinando Fioretto and Wenxi Wang},
  title = {{Constrained Code Generation with Diffusion Language Models}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2026},
  url = {https://openreview.net/forum?id=zoVQ8aHNUH},
}
Figure