Constrained Code Generation with Discrete Diffusion

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

TL;DR

Autoregressive language models struggle to enforce global constraints like security and functional correctness during code generation, often requiring expensive post-hoc regeneration. This paper introduces Constrained Diffusion for Code (CDC), a training-free framework that leverages the global, editable intermediate states of discrete diffusion models to surgically inject constraint feedback during the denoising process. CDC drastically improves code functionality and security while editing only a small fraction of the tokens required by traditional re-prompting methods.

What Problem Does This Paper Address?

When large language models (LLMs) generate code, they typically do so autoregressively—predicting code token-by-token from left to right. However, critical program properties like functional correctness (passing unit tests) and security (avoiding vulnerabilities) depend on global structure and semantic dataflows that aren't visible at the individual token level.

If an autoregressive model introduces a bug or a vulnerability early in the generation process, traditional correction methods (like re-prompting or post-hoc repair) have to intervene after the code is fully generated. This usually requires discarding large chunks of code and regenerating the entire suffix or program from scratch, which is computationally wasteful and highly inefficient.

Discrete diffusion models offer a unique alternative: they generate code by iteratively refining an entire sequence of tokens simultaneously. This means a global program state is exposed at every single denoising step, presenting a natural intervention point to guide and correct the code before it is finalized.

Methods

The authors introduce Constrained Diffusion for Code (CDC), a training-free neurosymbolic framework that integrates constraint satisfaction directly into the reverse denoising process of discrete diffusion models.

Figure 2: Overview of CDC.

At each denoising step, CDC executes a four-stage loop:

  1. Clean-state proposal: The base diffusion model proposes a token distribution for the entire program.
  2. Constraint-aware localization: A constraint evaluator assesses the intermediate code candidate and maps feedback to specific, problematic token regions.
  3. Constraint-aware correction: A correction operator adjusts the proposal to minimize constraint violations using a trust-region optimization that keeps the new proposal close to the base model's original distribution.
  4. Constrained reverse update: The model samples the next state based on this corrected proposal.

The authors instantiate CDC using two distinct operators to handle different types of constraints:

  • GradGuide (for functionality): Uses a differentiable surrogate model trained on execution outcomes (like test-pass labels). It computes gradients through the surrogate to pinpoint exactly which tokens are causing functional failures, then applies soft optimization updates and local remasking to let the model try again.
  • MDFI (Mid-Diffusion Feedback Injection, for security): Uses a non-differentiable symbolic static analyzer to build a partial program graph and detect vulnerabilities. It then performs discrete interventions like remasking vulnerable tokens, inserting new mask tokens for missing guards, and injecting natural language remediation hints into a pre-allocated prompt buffer.

Datasets

The authors evaluated CDC across several standard code generation and security benchmarks:

  • HumanEval-X (C++) & MBPP (C++): Used to evaluate syntax (compile success) and functional correctness (unit tests).
  • CWEval: A multi-language benchmark (C, C++, Go, JavaScript, Python) designed to evaluate both functionality and security.
  • LLMSecEval+: An enhanced version of LLMSecEval containing natural language prompts paired with executable functional and security oracles.

Key Insights and Ideas

  • Diffusion as an Editable Trajectory: The core "aha" moment is treating the intermediate steps of a diffusion model not just as a path to a sample, but as a dynamic, editable workspace where code can be evaluated and repaired mid-generation.
  • Surgical vs. Wholesale Edits: Instead of the "burn it down and start over" approach of autoregressive re-prompting, CDC acts like a precise surgeon, changing only the specific tokens responsible for a bug or vulnerability.
  • Neurosymbolic Synergy: CDC seamlessly blends continuous gradient-based guidance (GradGuide) with discrete, rule-based symbolic feedback from static analyzers (MDFI), showing that diffusion models are uniquely suited for hybrid neurosymbolic AI.

Key Results

CDC achieves massive performance boosts across the board compared to vanilla diffusion and autoregressive baselines:

  • Functional Correctness: On HumanEval-X C++, CDC boosted the pass@1 rate of Dream-Coder 7B from 34.1% to 65.2%. On MBPP-C++, it went from 27.7% to 59.2%.
  • Security: On CWEval, the joint functionality-security success rate (fs@1) nearly tripled, jumping from 12.04% to 34.26%.
  • Token Efficiency: CDC is incredibly efficient. For security fixes on CWEval, autoregressive re-prompting rewrote a median of 113 tokens, while CDC achieved better security fixes by editing a median of just 12 tokens.
Figure 3: Edited tokens per correction attempt (fewer means higher efficiency): (a) functionality corrections on HumanEval-X and MBPP, and (b) security corrections on CWEval and LLMSecEval+.

Limitations and Future Work

  • Dependency on Evaluator Quality: CDC is only as good as its feedback loops. If the surrogate model provides noisy gradients or the static analyzer yields false positives/negatives, the correction quality drops.
  • Inference Overhead: Running a static analyzer or a surrogate model forward/backward pass at multiple denoising checkpoints adds computational latency during inference.
  • Scale and Complexity: The framework was tested on standard benchmarks with relatively short contexts. Scaling CDC to massive, multi-file codebases or highly complex software engineering workflows remains an open challenge.

Summary updated

BibTeX
@misc{shao2026constrained,
  author = {Lize Shao and Michael Cardei and Zichen Xie and Ferdinando Fioretto and Wenxi Wang},
  title = {{Constrained Code Generation with Discrete Diffusion}},
  year = {2026},
  eprint = {2605.16829},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2605.16829},
}
Figure