Structured Code Generation via AST-Aware Discrete Flow Matching with State Space Conditioning and Energy-Based Constraint Guidance
A Research Proposal for Constraint-Driven Program Synthesis
This document proposes ASTRAL (AST-aware Refinement And Learning), a novel architecture for code generation that treats program synthesis as constrained search through valid program space rather than probabilistic text completion. ASTRAL combines three complementary innovations: (1) AST-aware discrete flow matching that respects syntactic structure during generation, (2) state space model conditioning for efficient long-context reasoning over specifications and surrounding code, and (3) energy-based constraint guidance that shapes generation toward programs satisfying formal properties. This hybrid architecture addresses fundamental limitations of autoregressive code models – their left-to-right commitment problem, inability to globally plan, and lack of formal guarantees – while maintaining practical efficiency through SSM's linear-time context processing and flow matching's parallel generation capabilities.
Primary target application: Repository-scale code editing, infilling, and repair with verifiable constraints – tasks where bidirectional context and constraint integration provide principled advantages over autoregressive generation.
Current state-of-the-art code generation relies overwhelmingly on autoregressive (AR) transformers. While effective, this paradigm introduces fundamental misalignments with how code actually works:
Left-to-Right Commitment: AR models must commit to function signatures before knowing what the body requires, choose variable names before seeing their usage patterns, and declare types before understanding downstream constraints. Code has bidirectional dependencies that AR models handle through implicit lookahead at best.
No Global Planning: When generating a complex function, AR models cannot "sketch" the overall structure and refine details. They must immediately produce final tokens, leading to local optima and incoherent long-range structure.
No Formal Guarantees: AR models provide no mechanism for enforcing that generated code satisfies specifications, type constraints, or other formal properties beyond hoping the training distribution induces such behavior.
Inefficient Editing: Modifying code in the middle of a file requires regenerating everything downstream, even when changes are semantically local.
We propose combining three emerging technologies that address complementary weaknesses:
| Component | Addresses | Mechanism |
|---|---|---|
| Discrete Flow Matching | Global planning, bidirectional context | Iterative refinement from noise to code |
| AST-Aware Structure | Syntactic validity, hierarchical reasoning | Corruption/generation respects syntax tree |
| SSM Conditioning | Long context efficiency, cross-file dependencies | O(n) context processing with selective state |
| Energy-Based Guidance | Constraint satisfaction, formal properties | Constraints as energy functions shaping generation |
The key insight is that these components are not merely additive – they create emergent capabilities impossible with any single approach.
Flow matching provides a theoretically elegant framework for generative modeling by learning to transport samples from a source distribution (noise) to a target distribution (data) along probability paths.
For discrete data like code tokens, Discrete Flow Matching (DFM) [4] operates over continuous-time Markov chains (CTMCs). Given a coupling
The core training objective learns a denoiser
where
Advantages over Diffusion: Flow matching offers cleaner theoretical foundations, more flexible probability paths (not restricted to diffusion processes), and often faster sampling through straighter trajectories.
Advantages over AR: Parallel generation, bidirectional context at each step, and natural support for infilling and editing operations.
State Space Models (SSMs) provide an alternative to attention with fundamentally different computational characteristics. The core SSM equations:
Mamba [6] introduces selective SSMs where parameters
Mamba-2 and State Space Duality (SSD) [3]: Recent work reveals deep connections between SSMs and attention through structured matrices. SSD restricts the diagonal
- Matrix multiplication primitives (tensor core acceleration)
- Attention-like formulation for theoretical analysis
- Efficient algorithms combining recurrent and parallel computation
Relevance to Code: SSMs excel at modeling discrete, tokenized data with long-range dependencies. Their linear complexity enables processing entire files or even repositories as context, crucial for understanding cross-file dependencies, import relationships, and project-wide conventions.
Energy-Based Models (EBMs) define distributions through unnormalized energy functions:
For constrained generation, we can decompose energy into base model likelihood and constraint terms:
where
COLD Decoding [9] demonstrated that Langevin dynamics can sample from such distributions at inference time, enabling constraint satisfaction without retraining.
Energy-Based Diffusion Language Models (EDLM) [12] showed that incorporating sequence-level energy functions into discrete diffusion addresses the independence assumption that causes accumulated errors in parallel decoding.
Abstract Syntax Trees capture the hierarchical, compositional structure of programs:
- Internal nodes represent syntactic constructs (functions, loops, conditionals)
- Leaves correspond to terminal tokens
- Tree structure encodes scoping, binding, and typed relationships
TreeDiff [14] recently demonstrated that AST-guided masking in diffusion models improves code generation by respecting syntactic boundaries rather than corrupting at arbitrary token positions.
AST-T5 [7] showed that AST-aware pretraining objectives (segmentation and span corruption aligned with syntax) significantly improve code understanding and generation, especially for code-to-code tasks.
Diffusion on Syntax Trees [15] (Russell et al., ICLR 2025) directly operates on tree structures for program synthesis, demonstrating that tree-native generation preserves structural validity more naturally than token-level approaches.
┌─────────────────────────────────────────────────────────────────────┐
│ ASTRAL Architecture │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ ┌───────────────┐ ┌──────────────────┐ ┌─────────────────┐ │
│ │ Context │ │ Constraint │ │ Generation │ │
│ │ Encoder │───▶│ Compiler │───▶│ Orchestrator │ │
│ │ (SSM) │ │ (Energy Fn) │ │ (DFM + EBM) │ │
│ └───────────────┘ └──────────────────┘ └─────────────────┘ │
│ │ │ │ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌──────────────────────────────────────────────────────────────┐ │
│ │ AST Structure Layer │ │
│ │ • Syntax-aware tokenization and masking │ │
│ │ • Hierarchical position encodings │ │
│ │ • Syntax-guided filtering with error-driven repair │ │
│ └──────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────┘
The context encoder processes all conditioning information – surrounding code, specifications, type signatures, documentation, and cross-file dependencies – into a compressed representation that guides generation.
Architecture: We employ a Mamba-2 backbone with the following modifications:
class ContextEncoder(nn.Module):
def __init__(self, d_model=1024, n_layers=24, d_state=128):
self.embedding = CodeEmbedding(d_model)
self.mamba_layers = nn.ModuleList([
Mamba2Block(d_model, d_state, d_conv=4, expand=2)
for _ in range(n_layers)
])
self.context_projector = nn.Linear(d_model, d_context)
def forward(self, context_tokens, context_mask):
# Embed with AST-aware positional encoding
x = self.embedding(context_tokens)
# Process through Mamba layers
for layer in self.mamba_layers:
x = layer(x) # O(n) complexity
# Project to conditioning space
return self.context_projector(x)AST-Aware Positional Encoding: Rather than standard positional encodings, we incorporate:
- Depth encoding: Distance from AST root
- Sibling encoding: Position among siblings in AST
- Scope encoding: Learned embeddings for scope nesting level
- Node type encoding: Syntactic category of containing AST node
Cross-File Attention via Symbol Graph: For repository-level context, we use sparse attention patterns that connect semantically related spans across files. We construct an edge-indexed cross-attention mask from tree-sitter's symbol resolution:
- Import edges: Import statements → their definitions in other files
- Call edges: Function/method calls → their declarations
- Type edges: Type annotations → type definitions
For languages where tree-sitter queries don't provide sufficient symbol resolution, we fall back to LSP symbol graphs (via language servers) or retrieval of top-k spans per unresolved symbol based on embedding similarity.
Context Compression for Long Sequences: When
class ContextBottleneck(nn.Module):
def __init__(self, n_latents=256, d_model=1024):
self.latent_queries = nn.Parameter(torch.randn(n_latents, d_model))
self.cross_attn = nn.MultiheadAttention(d_model, n_heads=8)
def forward(self, context_seq):
# Compress variable-length context to fixed latents
latents, _ = self.cross_attn(
self.latent_queries.unsqueeze(0),
context_seq, context_seq
)
return latents # Shape: (batch, n_latents, d_model)This enables O(
The core generative model uses discrete flow matching with syntax-aware design choices at every level.
Rather than uniform random masking, we corrupt code respecting its hierarchical structure:
class ASTCorruption:
def __init__(self, syntax_parser):
self.parser = syntax_parser
def corrupt(self, code_tokens, t, ast):
"""
Corrupt tokens with probability based on:
1. Time t (more corruption at t=0, less at t=1)
2. AST structure (corrupt entire subtrees coherently)
"""
# Compute corruption probability per AST node
node_probs = self.compute_node_corruption_probs(ast, t)
# For each AST node, either keep or mask entire subtree
mask = torch.zeros_like(code_tokens)
for node in ast.traverse():
if torch.rand(1) < node_probs[node.id]:
# Mask all tokens in this subtree
mask[node.start:node.end] = 1
# Apply mask token
corrupted = torch.where(mask, self.mask_token, code_tokens)
return corrupted, maskHierarchical Corruption Schedule: We design the noise schedule to respect AST depth:
- High-level constructs (function definitions, class declarations) are corrupted/revealed first
- Low-level details (variable names, literals) are corrupted/revealed last
This mirrors how humans write code: sketch structure, then fill details.
The denoiser learns to predict clean tokens given corrupted intermediate states:
class ASTFlowMatcher(nn.Module):
def __init__(self, d_model, n_heads, n_layers):
self.token_embedding = nn.Embedding(vocab_size, d_model)
self.time_embedding = SinusoidalEmbedding(d_model)
self.ast_embedding = ASTNodeEmbedding(d_model)
# Bidirectional transformer for denoising
self.transformer = nn.TransformerEncoder(
nn.TransformerEncoderLayer(d_model, n_heads),
num_layers=n_layers
)
self.output_head = nn.Linear(d_model, vocab_size)
def forward(self, x_t, t, context, ast_info):
# Embed corrupted tokens
tok_emb = self.token_embedding(x_t)
time_emb = self.time_embedding(t)
ast_emb = self.ast_embedding(ast_info)
# Combine embeddings
x = tok_emb + time_emb + ast_emb
# Cross-attend to context from SSM encoder
x = self.cross_attention(x, context)
# Self-attention for denoising
x = self.transformer(x)
# Predict clean token logits
return self.output_head(x)Training Objective: We use the standard DFM objective with an additional AST validity regularizer:
where
This formulation is compatible with the bidirectional denoiser: we decode the model's full prediction
The constraint system transforms formal specifications into energy functions that guide generation.
We support multiple constraint types, each with corresponding energy formulations:
Type Constraints:
where
Syntactic Constraints (grammar validity):
computed via incremental parsing.
Semantic Constraints (specifications):
For formal specifications in a logic (e.g., refinement types, contracts):
Style Constraints (soft preferences):
A naive implementation that evaluates expensive constraints (type checking, test execution, SMT solving) at every denoising step would be computationally prohibitive. We adopt a two-tier guidance architecture:
Tier 1 – Learned Surrogate Energies (per-step): Lightweight neural networks trained to predict constraint violations from partial programs. These run at every denoising step with negligible overhead:
class SurrogateTypeEnergy(nn.Module):
"""Learned predictor of type errors from partial code."""
def __init__(self, d_model):
self.encoder = TransformerEncoder(d_model, n_layers=2)
self.head = nn.Linear(d_model, 1)
def forward(self, partial_code, mask):
# Predict expected type error count
h = self.encoder(partial_code)
return self.head(h.mean(dim=1))Critical: Surrogate Fidelity ("The Alignment Gap")
The system's efficacy depends on Tier 1 surrogates accurately predicting Tier 2 verifier outcomes. If surrogates produce gradients uncorrelated with actual compiler acceptance, the flow matcher optimizes toward "hallucinated valid states" that exact verification rejects.
To ensure surrogate fidelity:
- On-policy training: Train surrogates on noisy code generated by the model itself (trajectory data), not just static datasets. This ensures surrogates learn the generator's specific failure modes.
- Correlation benchmarking: Phase 1 must include a milestone measuring surrogate-to-verifier correlation (target: Spearman ρ > 0.7 for type errors, parse errors).
- Iterative refinement: Retrain surrogates periodically as the generator improves, maintaining distribution alignment.
Tier 2 – Exact Verification (end-stage): Expensive ground-truth checkers (type checkers, test execution, SMT solvers) run only:
- At final step as post-generation verification
- Sparsely during generation (every 10-20 steps) for trajectory correction
- In rejection sampling loops for verification-critical applications
This design follows the blueprint established by DiffuCoder's [5] use of GRPO-style training to move expensive verification into training, enabling lighter inference-time guidance.
The connection between energy functions and discrete sampling requires explicit specification. In the CTMC view of discrete flow matching, generation proceeds via transition rates between token states. We modify these rates based on energy gradients:
Per-Step Guidance Computation:
def compute_guidance(self, x_t, t, logits, surrogate_energy, context):
"""
Compute energy-based guidance for discrete token sampling.
Args:
x_t: Current token sequence (partially masked)
t: Diffusion timestep
logits: Denoiser output logits, shape (batch, seq_len, vocab_size)
surrogate_energy: Tier 1 energy model
context: Encoded context from SSM (for context-aware surrogates)
Returns:
adjusted_logits: Energy-modified logits for sampling
"""
# 1. Compute per-position energy penalties
# For each position, evaluate surrogate on candidate tokens
with torch.no_grad():
# Get top-k candidates per position for efficiency
top_k_tokens = logits.topk(k=32, dim=-1).indices
# Evaluate surrogate energy for each candidate
# Surrogate sees partial code + context for cross-file awareness
energy_penalties = torch.zeros_like(logits)
for pos in masked_positions(x_t):
for tok in top_k_tokens[pos]:
x_candidate = x_t.clone()
x_candidate[pos] = tok
# Surrogate attends to context_projector output
energy = surrogate_energy(x_candidate, context)
energy_penalties[pos, tok] = energy
# 2. Convert energies to logit adjustments
# Lower energy = higher probability (energy minimization)
guidance_strength = self.tau * (1 - t) # Stronger guidance at later steps
adjusted_logits = logits - guidance_strength * energy_penalties
# 3. Sample from adjusted distribution
return adjusted_logitsGuidance Modes:
| Mode | Mechanism | Use Case |
|---|---|---|
| Logit shaping | Direct logit subtraction | Default, differentiable surrogates |
| Rate modification | Scale CTMC transition rates by exp(-E) | Theoretical purity, matches CTMC formulation |
| Rejection sampling | Sample, evaluate, accept/reject | Exact energies at sparse steps |
For Tier 1 surrogates, we use logit shaping (computationally cheapest). For Tier 2 exact checks, we use rejection with localized remasking on failure.
Context-Aware Surrogates: Type errors often depend on definitions in context (e.g., an imported class's interface). The surrogate energy model receives the context_projector output from the SSM encoder, enabling it to reason about cross-file dependencies:
class ContextAwareSurrogate(nn.Module):
def __init__(self, d_model):
self.code_encoder = TransformerEncoder(d_model, n_layers=2)
self.context_cross_attn = nn.MultiheadAttention(d_model, n_heads=4)
self.head = nn.Linear(d_model, 1)
def forward(self, partial_code, context_from_ssm):
h = self.code_encoder(partial_code)
# Attend to context for cross-file type information
h, _ = self.context_cross_attn(h, context_from_ssm, context_from_ssm)
return self.head(h.mean(dim=1))A local-only surrogate (without context attention) would fail to predict type errors from imported symbols, limiting effectiveness on repository-level tasks.
Constraints from various sources are compiled into unified energy functions:
class ConstraintCompiler:
def compile(self, spec: Specification) -> Tuple[SurrogateEnergy, ExactEnergy]:
surrogate_energies = []
exact_energies = []
# Parse type annotations
if spec.type_hints:
surrogate_energies.append(SurrogateTypeEnergy.load_pretrained())
exact_energies.append(TypeCheckerEnergy(spec.type_hints))
# Parse docstring examples
if spec.examples:
surrogate_energies.append(SurrogateIOEnergy.load_pretrained())
exact_energies.append(ExecutionEnergy(spec.examples))
# Grammar constraints (always present, cheap enough for exact)
exact_energies.append(GrammarEnergy(spec.language))
return (
CompositeEnergy(surrogate_energies, self.learned_weights),
CompositeEnergy(exact_energies, self.constraint_weights)
)Constraint Compiler I/O Summary:
┌─────────────────────────────────────────────────────────────────┐
│ Constraint Compiler │
├─────────────────────────────────────────────────────────────────┤
│ INPUTS OUTPUTS │
│ ─────── ──────── │
│ • Type hints (mypy stubs) → Surrogate: SurrogateTypeEnergy │
│ • I/O examples → Surrogate: SurrogateIOEnergy │
│ • Contracts (pre/post) → Surrogate: SurrogateSpecEnergy │
│ • Style rules (linter) → Surrogate: SurrogateStyleEnergy│
│ │
│ • Grammar (tree-sitter) → Exact: GrammarEnergy │
│ • Type checker (mypy) → Exact: TypeCheckerEnergy │
│ • Test suite (pytest) → Exact: ExecutionEnergy │
│ • SMT solver (Z3/Dafny) → Exact: FormalEnergy │
├─────────────────────────────────────────────────────────────────┤
│ GUIDANCE HOOKS │
│ ───────────── │
│ • Per-step: Surrogate energies → logit adjustment │
│ • Sparse (every 10-20 steps): Exact verification → remask │
│ • Final: Exact verification → reject/repair loop │
└─────────────────────────────────────────────────────────────────┘
def guided_sample(self, context, constraints, n_steps=50):
"""Two-tier guided sampling with amortized constraint evaluation."""
x = torch.full((seq_len,), MASK_TOKEN)
# Compile constraints into surrogate and exact energies
surrogate_energy, exact_energy = self.constraint_compiler(constraints)
for step, t in enumerate(torch.linspace(0, 1, n_steps)):
logits = self.denoiser(x, t, context)
# Tier 1: Cheap surrogate guidance at every step
adjusted_logits = self.compute_guidance(
x, t, logits, surrogate_energy, context
)
# Tier 2: Expensive exact check sparsely (every 10 steps)
if step % 10 == 0 and step > 0:
exact_score = exact_energy(self.decode(x))
if exact_score > self.threshold:
# Localize errors and increase mask in those regions
error_spans = exact_energy.localize_errors(x)
x = self.remask_spans(x, error_spans)
x = self.sample_transition(x, adjusted_logits, t)
# Final verification with rejection/repair
return self.verify_and_repair(x, exact_energy)The AST structure layer provides shared infrastructure used by all other components.
We use tree-sitter's error-tolerant parsing, which produces partial ASTs even for syntactically incomplete or malformed code. Crucially, tree-sitter does not fail on invalid input – it marks unparseable regions with ERROR nodes while successfully parsing surrounding valid structure. This is why tree-sitter powers syntax highlighting in editors like Neovim, Zed, and Helix: it handles incomplete code gracefully. (Note: VS Code uses TextMate grammars by default; tree-sitter is available via extensions.)
This error tolerance is fundamental to our approach. We do not attempt to parse raw masked token sequences; we:
- Decode the current token sequence to text
- Parse the text with tree-sitter (which always succeeds, producing ERROR nodes for invalid regions)
- Use ERROR node locations to identify problematic spans
- Re-mask those spans for continued generation
class IncrementalAST:
def __init__(self, language):
self.parser = tree_sitter.Parser()
self.parser.set_language(tree_sitter.Language(language))
self.tree = None
def update(self, code_bytes: bytes):
"""Parse or incrementally update the AST.
Tree-sitter ALWAYS produces a tree, even for invalid input.
Invalid regions are marked with ERROR or MISSING nodes.
"""
if self.tree is None:
self.tree = self.parser.parse(code_bytes)
else:
# Compute minimal edit and reparse incrementally
self.tree = self.parser.parse(code_bytes, self.tree)
return self.tree
def get_error_spans(self) -> List[Tuple[int, int]]:
"""
Return byte ranges containing parse errors.
Tree-sitter marks unparseable regions with ERROR nodes,
allowing us to localize syntax issues precisely.
"""
errors = []
def collect_errors(node):
if node.type == 'ERROR' or node.is_missing:
errors.append((node.start_byte, node.end_byte))
for child in node.children:
collect_errors(child)
collect_errors(self.tree.root_node)
return errors
def get_subtree_spans(self, node_types: List[str]) -> List[Tuple[int, int]]:
"""Return spans for nodes of specified types (for AST-aware masking)."""
spans = []
def collect(node):
if node.type in node_types:
spans.append((node.start_byte, node.end_byte))
for child in node.children:
collect(child)
collect(self.tree.root_node)
return spansAlternative: Two-Stage Generation
An alternative architecture explicitly separates structure and content:
- Stage 1: Generate AST skeleton (node types, control flow) via a small flow model
- Stage 2: Condition the main flow matcher on the valid skeleton to fill in identifiers and literals
This guarantees the parser always sees valid structure but requires training two models and defining a skeleton representation. We favor the repair-loop approach for simplicity, but two-stage generation remains a viable alternative worth exploring.
Rather than claiming hard grammar guarantees via token masking (which would require a grammar-compatible tokenization scheme), we employ a soft filter + repair approach that achieves high syntactic validity empirically:
class SyntaxGuidedGenerator:
def __init__(self, parser, tokenizer):
self.parser = parser
self.tokenizer = tokenizer
def generate_with_repair(self, context, max_repairs=3):
"""Generate with parse-error-driven repair loop."""
for attempt in range(max_repairs + 1):
# Generate candidate
x = self.base_generate(context)
code = self.tokenizer.decode(x)
# Check for parse errors
ast = self.parser.update(code.encode())
error_spans = self.parser.get_error_spans()
if not error_spans:
return x # Clean parse
if attempt < max_repairs:
# Convert byte spans to token spans
token_spans = self.bytes_to_tokens(error_spans, code)
# Re-mask error regions and regenerate
x = self.remask_and_continue(x, token_spans, context)
return x # Return best effort after max repairsWhy this approach: Direct mapping from grammar symbols to BPE tokens requires either (a) a lexer-aligned tokenization scheme, or (b) a two-level decoder that emits grammar terminals then renders to bytes. Both are viable but add significant complexity. The repair-loop approach achieves high parse success rates empirically while using standard BPE tokenization, and naturally integrates with flow matching's iterative refinement.
Implementation Note: Hot Path Performance
The decode-parse-encode loop (Tokens → Text → AST → Error Spans → Token Mask) runs inside the generation process. If implemented naively in Python, this serialization overhead could negate flow matching's parallelism benefits. Critical path components must be implemented in a systems language:
- IncrementalAST: Tree-sitter is written in C; use direct bindings from Zig (zero FFI overhead), Rust (via tree-sitter crate), or C++
- Span-to-token mapping: Implement in Zig/Rust/C++ with zero-copy access to tokenizer state. Zig's explicit memory model is particularly well-suited for the pointer arithmetic and slice operations needed here.
- Batch processing: Parse multiple candidates in parallel when evaluating top-k
Performance Targets and Microbenchmark Plan:
We target <1ms per parse-and-localize cycle with native implementations. To validate this target, we will publish microbenchmarks covering:
| Metric | Variables | Target |
|---|---|---|
| Parse latency | File size (100, 1k, 10k, 100k bytes) | <0.5ms for 10k bytes |
| Error localization | % tokens edited (1%, 10%, 50%) | <0.1ms overhead |
| Span-to-token mapping | Tokenizer (BPE, SentencePiece) | <0.05ms |
| Full cycle (decode-parse-localize-remask) | Combined | <1ms for typical functions |
| Language variation | Python, TypeScript, Rust, Go | Within 2x of Python baseline |
| Batch efficiency | Batch size (1, 8, 32) | Near-linear scaling |
These benchmarks will be published alongside Phase 1 results. If targets prove unachievable, we will document actual performance and adjust the parsing schedule accordingly.
Parsing Schedule: Tree-sitter's "incremental" parsing requires localized edits to be efficient. Early in diffusion (many tokens changing), incremental updates provide little benefit – we effectively do full reparses. Practical mitigation:
- Sparse parsing: Parse only at late steps (t > 0.7) and after repair iterations, not every step
- Region-limited parsing: For infill/edit tasks, parse only the edited region plus local context
- Projection-at-finalization: Treat parsing as a projection operator invoked when the sampler is about to commit, not continuously
Future work: For applications requiring guaranteed syntactic validity, we plan to explore grammar-aligned tokenization (following Synchromesh [10]) or integration with constrained decoding frameworks like llguidance.
Stage 1: SSM Context Encoder
- Train on next-token prediction over large code corpus
- Use AST-aware positional encodings from the start
- Objective: Standard language modeling loss
Stage 2: Flow Matcher (Frozen SSM)
- Train denoiser with AST-aware corruption
- Condition on frozen SSM representations
- Objective: DFM loss + AST consistency loss
Stage 3: Joint Fine-tuning
- Unfreeze SSM, train end-to-end
- Add constraint guidance during training (randomly sample constraints)
- Objective: DFM loss + constraint satisfaction reward
We propose a tiered scaling strategy reflecting resource availability:
| Data Type | Purpose | Scale |
|---|---|---|
| Raw code | Base pretraining | 50-100B tokens |
| Parsed ASTs | Structure-aware training | All code with ASTs |
| Type-annotated code | Type constraint learning | 1B+ tokens (Python typed subset) |
| Tested code | I/O constraint learning | 100M+ tokens |
This scale is comparable to DiffuCoder [5], which trained a competitive 7B model on 130B code tokens.
| Data Type | Purpose | Scale |
|---|---|---|
| Raw code | Base pretraining | 500B+ tokens |
| Parsed ASTs | Structure-aware training | All code with ASTs |
| Type-annotated code | Type constraint learning | 10B+ tokens |
| Tested code (with tests) | I/O constraint learning | 1B+ tokens |
| Formally verified code | Formal constraint learning | 100M+ tokens (synthetic) |
Frontier scale requires significant GPU allocation (thousands of H100-hours) and is marked as optional stretch goals.
Naturally-occurring formally verified code (Dafny, Liquid Haskell, Coq) exists at perhaps 1-10M tokens in public datasets – far below our frontier target. We propose a synthesis pipeline:
- Spec Inference: Use frontier AR models (Claude, GPT-4, DeepSeek) to generate formal specifications (pre/post conditions, invariants) for existing well-tested code
- Verification Filtering: Run actual verifiers to filter to specs that (a) are syntactically valid and (b) the code actually satisfies
- Difficulty Curriculum: Rank by verification complexity for curriculum learning
This follows the "synthetic data flywheel" pattern: use capable models to generate training signal that bootstraps more capable models. Similar approaches have succeeded for math (Llemma) and reasoning (STaR).
Training Tier 1 surrogate energy models requires a massive dataset of broken code annotated with compiler/verifier errors. Random token corruption is insufficient – it produces unrealistic errors that don't match the generator's actual failure modes. We propose:
- High-temperature generation: Use a standard AR model (e.g., CodeLlama-7B) at T=1.5 to generate "synthetic broken code" with realistic logic and syntax errors (hallucinatory imports, type mismatches, undefined variables)
- On-policy corruption: Sample from the flow matcher's own intermediate states during training
- Error annotation: Run exact verifiers (mypy, pytest, tree-sitter) to label error types and locations
- Curriculum: Progress from obvious errors (syntax) to subtle errors (logic, edge cases)
We employ curriculum learning over constraint difficulty:
- Syntactic only: Grammar validity constraints
- Add type constraints: Well-typed programs
- Add simple I/O: Single input-output examples
- Add complex I/O: Multiple examples, edge cases
- Add formal specs: Contracts, invariants, refinement types (frontier only)
def generate(prompt, spec, n_steps=50):
# Encode context
context = ssm_encoder(prompt)
# Compile constraints
surrogate_fn, exact_fn = constraint_compiler(spec)
# Initialize generation
x = initialize_with_structure(prompt) # May have partial AST
# Flow matching with amortized guidance
for t in schedule(n_steps):
x = guided_denoise_step(x, t, context, surrogate_fn)
# Final verification and repair
return verify_and_repair(x, exact_fn)The bidirectional nature of flow matching enables natural infilling:
def infill(code, hole_start, hole_end, spec):
# Parse existing code
ast = parse(code)
# Mark hole region as masked
x = tokenize(code)
x[hole_start:hole_end] = MASK_TOKEN
# Generate only the masked region
# (unchanged tokens have energy 0, no gradient)
return guided_sample(x, spec, mask=create_mask(hole_start, hole_end))For editing multiple non-contiguous regions:
def multi_edit(code, regions: List[Tuple[int, int]], specs):
x = tokenize(code)
# Mask all regions
mask = torch.zeros_like(x)
for start, end in regions:
x[start:end] = MASK_TOKEN
mask[start:end] = 1
# Parallel generation of all regions
# Flow matching naturally handles dependencies between regions
return guided_sample(x, specs, mask=mask)For latency-critical applications, distill the multi-step flow into a consistency model [11]:
def train_consistency_model(flow_model, n_distill_steps=1000):
consistency_model = ConsistencyWrapper(flow_model)
for step in range(n_distill_steps):
# Sample adjacent points on flow trajectory
t = torch.rand(1)
x_t = flow_model.sample_at_time(t)
x_t_plus = flow_model.sample_at_time(t + delta)
# Train consistency model to map both to same clean output
loss = consistency_loss(
consistency_model(x_t, t),
consistency_model(x_t_plus, t + delta)
)
loss.backward()This enables 1-4 step generation with minimal quality loss.
Claim 1: ASTRAL can represent any program distribution expressible by AR models.
Sketch: Flow matching with sufficient denoising steps converges to the target distribution. AST-aware corruption is a strict generalization of random corruption.
Claim 2: ASTRAL can enforce constraints that AR models cannot express tractably.
Sketch: Energy-based guidance allows arbitrary constraint functions, including those requiring full-program analysis (e.g., type checking, specification satisfaction).
| Operation | AR Transformer | ASTRAL |
|---|---|---|
| Context encoding | O(n²) attention | O(n) via SSM |
| Single denoising step | – | O(n²) attention in denoiser |
| Full sequence generation | O(n²) total | O(n² · k) for k steps |
| Editing m tokens | O(n · m) minimum | O(n² · k) regardless of m |
Complexity breakdown:
- SSM context encoder: O(n_ctx) – linear in context length
- Denoiser self-attention: O(n_out²) per step – standard quadratic attention over output sequence
- Cross-attention to context: O(n_out · n_ctx) per step – if using full cross-attention; can be reduced via sparse/retrieval patterns
- Energy guidance: O(1) per step with surrogate energies; expensive exact checks amortized to O(k/10) calls
Cross-attention can dominate for long contexts: When n_ctx >> n_out (e.g., 100k context, 1k output), the O(n_out · n_ctx) term exceeds denoiser self-attention. Default mitigations:
- Primary: Context bottleneck (Perceiver-style compression to fixed latents, §3.2)
- Alternative: Edge-sparse attention via symbol graph (attend only to retrieved/relevant spans)
- Fallback: SSM final state as summary vector (loses fine-grained conditioning)
The key efficiency wins are: (1) linear context encoding enables repository-scale conditioning, (2) k denoising steps (typically 10-50) vs. n sequential AR steps, (3) editing requires only k steps regardless of edit location.
Note on compute parity: Prior work [8] suggests masked diffusion models may require more compute than AR to match likelihood. We accept this tradeoff for the architectural benefits (bidirectionality, constraint integration, editing), and note that DiffuCoder [5] achieves competitive results with reasonable compute.
Grammar validity: Achieved empirically through repair loops. We target >99% parse success rate; actual rates will be measured and reported. Not formally guaranteed without grammar-aligned tokenization.
Type/semantic constraints: Probabilistic satisfaction via energy guidance. With temperature
This bound is meaningful only when the learned energy landscape achieves and maintains separation – an empirical property we must measure, not assume.
Verification-critical applications: For applications requiring formal guarantees:
- Run exact verifiers post-generation
- Reject or repair programs that fail verification
- Report empirical constraint satisfaction rates
We explicitly avoid claiming "formal guarantees" for constraints enforced via learned surrogates or soft energy guidance. Hard guarantees require hard verification.
Code Generation:
- HumanEval, HumanEval+ (MVP)
- MBPP, MBPP+ (MVP)
- LiveCodeBench (extended)
- StudentEval (extended)
Constrained Generation:
- Type-constrained generation (measure type error rate)
- Specification-guided synthesis (SyGuS benchmarks, extended)
- Contract satisfaction (Dafny, Liquid Haskell programs, frontier only)
Editing and Infilling (Primary evaluation surface):
- CodeXGLUE code refinement (MVP)
- Bug fixing benchmarks (MVP)
- Multi-hole completion (extended)
- ASTRAL Editing Benchmark (new, see §7.5)
Efficiency:
- Tokens per second
- Time to first token
- GPU memory usage
- AR baselines: CodeLlama, DeepSeek-Coder, Qwen-Coder, StarCoder
- Diffusion baselines: DiffuCoder [5], LLaDA [8]
- Constrained baselines: Synchromesh [10], PICARD, grammar-constrained decoding
- SSM vs. Transformer context encoder
- AST-aware vs. random corruption
- Surrogate energy guidance vs. no guidance
- Flow matching vs. masked diffusion
- Number of denoising steps vs. quality
- Repair loop iterations vs. parse success rate
- Context bottleneck (Perceiver) vs. full cross-attention
- Surrogate correlation ablation (new, see §7.6)
| Metric | Measures |
|---|---|
| pass@k | Functional correctness |
| Type error rate | Type constraint satisfaction |
| Parse success rate | Syntactic validity |
| Spec satisfaction rate | Formal property satisfaction |
| Edit distance | Naturalness of generated code |
| Inference latency | Practical efficiency |
| Time to first valid | Efficiency advantage for constrained tasks |
| Surrogate-verifier ρ | Surrogate fidelity |
To directly test our "editing-first" positioning, we introduce a benchmark where AR models are structurally disadvantaged:
Task: Multi-hole infill with verification constraints
- Input: Repository context (10-50 files), file with 2-5 masked regions (functions, expressions, type annotations), type hints, test suite
- Output: Completed code that parses, type-checks, and passes tests
Construction:
- Sample well-tested, typed Python repositories from GitHub
- Randomly mask 2-5 syntactically coherent regions per file
- Include full repository context (imports, dependencies, related files)
- Require: (a) parse success, (b) mypy clean, (c) test pass
Metrics:
- pass@k: Standard functional correctness
- parse@1: First-attempt parse success rate
- type@1: First-attempt type-check success rate
- time-to-valid: Wall-clock time to first candidate passing all constraints
Hypothesis: ASTRAL's bidirectional generation and integrated constraint guidance will show larger advantages on time-to-valid than on raw pass@k, demonstrating the value of constraint-aware generation even when final accuracy is similar.
The surrogate fidelity milestone (ρ > 0.7) is a necessary gate, but demonstrating causal impact requires ablation:
Experiment Design:
- Train surrogate energy models to varying correlation levels with exact verifiers
- Intentionally degrade surrogates via: (a) training on out-of-distribution data, (b) early stopping, (c) reduced capacity
- Measure generation quality (pass@k, type error rate) as function of surrogate-verifier correlation
Expected Result: Quality degrades sharply below ρ ≈ 0.5-0.6, validating that surrogate fidelity is causally necessary, not merely correlated with success.
Scientific Claim: This ablation transforms the ρ > 0.7 milestone from a project management heuristic into an empirically grounded design principle for two-tier guidance systems.
DiffuCoder [5] demonstrated that masked diffusion models can approach AR performance on coding benchmarks, with unique properties like controllable generation order and temperature effects on parallelism. Their use of coupled-GRPO for RL-style improvement informs our amortized guidance strategy.
CodeFusion (2023) explored continuous diffusion in code embedding space but struggled with long sequences.
TreeDiff [14] introduced AST-guided masking for code diffusion, showing improved structure preservation.
Diffusion on Syntax Trees [15] (Russell et al., ICLR 2025) directly generates programs as syntax trees rather than token sequences, demonstrating that tree-native diffusion naturally preserves syntactic structure.
Synchromesh [10] uses completion engines to constrain AR generation but is limited to CFG constraints and requires careful tokenizer alignment.
COLD Decoding [9] demonstrated energy-based constrained generation via Langevin dynamics for natural language.
Grammar-constrained decoding (various) masks invalid tokens but doesn't handle semantic constraints and faces tokenizer-grammar alignment challenges.
Codestral Mamba (Mistral AI, 2024) is a production Mamba-2 model specialized for code generation, demonstrating that SSM architectures achieve competitive code generation quality with linear-time inference and 256k+ context handling.
Jamba (AI21, 2024) demonstrated hybrid attention-SSM architectures for long-context language modeling, showing that combining SSM efficiency with sparse attention preserves quality.
Neural-guided synthesis combines neural networks with symbolic search (e.g., miniKanren, SMT solvers).
Neurosymbolic approaches like DreamCoder learn program libraries and use neural guidance for search.
Given significant overlap with recent work, we explicitly delineate ASTRAL's contributions:
| Aspect | TreeDiff [14] | Diffusion on Syntax Trees [15] | ASTRAL |
|---|---|---|---|
| Representation | Token-level with AST masking | Native syntax trees | Token-level with tool-driven projection |
| Structure enforcement | AST-guided corruption | Tree diffusion | Parse-repair loop (tree-sitter) |
| Context model | Standard transformer | Standard transformer | SSM encoder (O(n) for repo-scale) |
| Constraint integration | None | Search-based | Unified energy compilation (surrogate + exact) |
| Target tasks | Generation | Synthesis | Generation + editing + infilling |
ASTRAL's specific contributions:
-
Tool-driven structural projection: Rather than encoding AST structure into the model architecture (TreeDiff) or operating natively on trees (Russell), we use tree-sitter as a runtime projection operator. This decouples structure enforcement from model design.
-
SSM-conditioned flow matching: We are not aware of published work that combines SSM context encoding with discrete flow matching. (Based on literature search through December 2025; concurrent work may exist.) This enables repository-scale context (100k+ tokens) without quadratic attention cost in the context encoder.
-
Two-tier energy compilation: Unified framework compiling heterogeneous constraints (types, tests, specs) into surrogate energies (cheap, per-step) and exact energies (expensive, end-stage). Neither TreeDiff nor syntax-tree diffusion addresses semantic constraints.
-
Editing-first evaluation: We prioritize editing/infilling benchmarks (SWE-bench style) where flow matching has principled advantages, rather than competing purely on generation metrics where AR models excel.
What we do NOT claim: We do not claim novelty in AST-aware corruption (TreeDiff), tree-structured diffusion (Russell), or energy-based guidance (EDLM). Our contribution is the specific combination optimized for practical code editing with formal constraint integration.
AST Availability During Generation: Partially generated code may not parse cleanly. We address this via:
- Error-tolerant parsing: Tree-sitter produces valid trees even for malformed input, marking unparseable regions with ERROR nodes rather than failing. This is not a workaround – it's tree-sitter's core design for editor integration.
- Parse-after-decode: We parse decoded text, not raw masked token sequences. The model outputs tokens, we decode to text, then parse.
- Soft AST features: Learned embeddings predict likely AST structure before parsing, providing guidance even when ERROR nodes dominate.
- Graceful degradation: When AST guidance is low-quality (many ERROR nodes), we fall back to token-level operation and rely on the base flow model.
Energy Function Differentiability: Some constraints (execution, type checking) are non-differentiable. We use:
- Learned surrogate energy functions (primary approach for per-step guidance)
- Straight-through estimators (for training surrogates)
- REINFORCE-style gradient estimation (for fine-tuning)
- Offline RL: Train on pre-computed verification labels rather than online evaluation (following DiffuCoder's GRPO)
Grammar-Tokenizer Alignment: Standard BPE tokenizers don't align with grammar terminals – tokens often straddle syntactic boundaries (e.g., ): merged into one token), making precise span-to-token mapping difficult. We address this via:
- Repair-loop approach (primary): Parse, localize errors, remask, regenerate – tolerates imprecise boundaries
- Byte-level fallback: For precise masking, operate at byte level then re-tokenize
- Grammar-aligned tokenizer (contingency): If repair loops prove inefficient due to token misalignment, train a custom tokenizer where syntax atoms (keywords, operators, delimiters) are distinct tokens. This is a significant undertaking but may be necessary for production quality.
The repair-loop approach is our default because it works with off-the-shelf tokenizers, but we maintain grammar-aligned tokenization as a fallback if empirical results demand it.
Scaling: Training flow matching models is computationally intensive. Mitigation:
- Adapt from pretrained AR models (as in DiffuGPT)
- Progressive training curriculum
- Start with MVP scale, validate approach before frontier investment
-
Optimal corruption schedule: What AST-aware corruption schedule maximizes learning efficiency?
-
Energy function learning: Can we learn constraint energy functions from data rather than hand-specifying?
-
SSM-Diffusion interaction: What's the optimal interface between SSM context and flow matching denoiser?
-
Consistency distillation for code: How much quality is lost when distilling to 1-step generation?
-
Compositional constraints: How do multiple constraints interact? Can we guarantee satisfaction of all constraints simultaneously?
-
Grammar-native generation: Would a lexer-aligned tokenization scheme provide meaningful gains over repair loops?
- Implement AST-aware tokenization and positional encoding
- Build incremental parsing infrastructure with error localization (Zig/Rust/C++ hot path)
- Publish parse latency microbenchmarks (per §3.5.2 targets)
- Train baseline Mamba encoder on code (MVP scale: 50B tokens, Python)
- Implement discrete flow matching training loop
- Milestone: Surrogate Correlation Benchmark – Train initial surrogate energy models on trajectory data; validate Spearman ρ > 0.7 correlation with exact verifiers before proceeding
- Integrate SSM encoder with flow matching denoiser
- Implement AST-aware corruption schedules
- Build syntax-guided repair loop
- Initial end-to-end training runs
- Evaluate on HumanEval, MBPP (establish baselines)
- Train surrogate energy functions (type, parse, simple I/O)
- Implement exact energy wrappers (mypy, pytest)
- Build two-tier guidance infrastructure
- Guided sampling implementation and tuning
- Surrogate correlation ablation study (§7.6)
- Comprehensive benchmark evaluation (pass@k, constraint satisfaction rates)
- ASTRAL Editing Benchmark evaluation (§7.5)
- Ablation studies
- Efficiency optimization
- Consistency model distillation experiments
- Paper writing and release
- Scale to frontier data (500B+ tokens)
- Multi-language support
- Formal verification integration (SMT, Dafny)
- Repository-scale context experiments
ASTRAL represents a principled approach to code generation that respects the fundamental nature of programs: they are structured, constrained, and bidirectionally dependent. By combining AST-aware discrete flow matching for global planning, SSM conditioning for efficient long-context reasoning, and energy-based guidance for constraint satisfaction, we address limitations that are inherent to the autoregressive paradigm rather than merely incidental to current implementations.
The key innovations – syntax-aware corruption, hierarchical generation schedules, and amortized two-tier constraint handling – emerge from treating code generation as what it fundamentally is: constrained search through the space of valid programs, not probabilistic text completion.
We are explicit about what ASTRAL provides and what it does not: empirically high constraint satisfaction rates through learned guidance and repair loops, not formal guarantees from soft constraints; practical syntactic validity through error-driven repair, not hard grammar enforcement without tokenizer alignment. For verification-critical applications, we advocate exact post-generation verification with rejection or repair.
We believe this architecture points toward a future where AI code generation provides measurable, improving constraint satisfaction alongside practical utility, where editing is as natural as generation, and where specifications meaningfully shape the generation process.
[1] Austin, J., Johnson, D. D., Ho, J., Tarlow, D., & van den Berg, R. (2021). Structured Denoising Diffusion Models in Discrete State-Spaces. NeurIPS 2021. https://arxiv.org/abs/2107.03006
[2] Campbell, A., Benton, J., De Bortoli, V., Rainforth, T., Deligiannidis, G., & Doucet, A. (2024). A Continuous Time Framework for Discrete Denoising Models. NeurIPS 2024. https://arxiv.org/abs/2205.14987
[3] Dao, T., & Gu, A. (2024). Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality. ICML 2024. https://arxiv.org/abs/2405.21060
[4] Gat, I., Remez, T., Shaul, N., Kreuk, F., Chen, R. T. Q., Synnaeve, G., Adi, Y., & Lipman, Y. (2024). Discrete Flow Matching. NeurIPS 2024. https://arxiv.org/abs/2407.15595
[5] Gong, S., Zhang, R., Zheng, H., Gu, J., Jaitly, N., Kong, L., & Zhang, Y. (2025). DiffuCoder: Understanding and Improving Masked Diffusion Models for Code Generation. arXiv preprint. https://arxiv.org/abs/2506.20639
[6] Gu, A., & Dao, T. (2023). Mamba: Linear-Time Sequence Modeling with Selective State Spaces. arXiv preprint. https://arxiv.org/abs/2312.00752
[7] Gong, L., Elhoushi, M., & Cheung, A. (2024). AST-T5: Structure-Aware Pretraining for Code Generation and Understanding. arXiv preprint. https://arxiv.org/abs/2401.03003
[8] Nie, S., Zhu, F., You, Z., Zhang, X., Ou, J., Hu, J., Zhou, J., Lin, Y., Wen, J.-R., & Li, C. (2025). Large Language Diffusion Models. arXiv preprint. https://arxiv.org/abs/2502.09992
[9] Qin, L., Welleck, S., Khashabi, D., & Choi, Y. (2022). COLD Decoding: Energy-based Constrained Text Generation with Langevin Dynamics. NeurIPS 2022. https://arxiv.org/abs/2202.11705
[10] Poesia, G., Polozov, A., Le, V., Tiwari, A., Soares, G., Meek, C., & Gulwani, S. (2022). Synchromesh: Reliable Code Generation from Pre-trained Language Models. ICLR 2022. https://arxiv.org/abs/2201.11227
[11] Song, Y., Dhariwal, P., Chen, M., & Sutskever, I. (2023). Consistency Models. ICML 2023. https://arxiv.org/abs/2303.01469
[12] Xu, M., Geffner, T., Kreis, K., Nie, W., Xu, Y., Leskovec, J., Ermon, S., & Vahdat, A. (2024). Energy-Based Diffusion Language Models for Text Generation. ICLR 2025. https://arxiv.org/abs/2410.21357
[13] Ye, J., Liu, M., Shi, J., & Yeung, D.-Y. (2024). DREAM: Diffusion Rectification and Estimation-Adaptive Models. CVPR 2024. https://arxiv.org/abs/2312.00210
[14] Zeng, Y., Cao, J., Li, Z., Chen, Y., Ren, T., Xiang, D., Wu, X., Gao, S., & Yu, T. (2025). TreeDiff: AST-Guided Code Generation with Diffusion LLMs. arXiv preprint. https://arxiv.org/abs/2508.01473
[15] Russell, S. et al. (2025). Diffusion on Syntax Trees for Program Synthesis. ICLR 2025. https://people.eecs.berkeley.edu/~russell/papers/russell-iclr25-diffusion.pdf
[16] Jaegle, A., Gimeno, F., Brock, A., Zisserman, A., Vinyals, O., & Carreira, J. (2021). Perceiver: General Perception with Iterative Attention. ICML 2021. https://arxiv.org/abs/2103.03206
[17] Mistral AI. (2024). Codestral Mamba. Technical Report. https://mistral.ai/news/codestral-mamba
Proposal drafted December 2025.
Revision 6: Added Guidance Operator subsection (§3.4.3) specifying discrete sampling mechanics. Added symbol graph construction for cross-file attention (§3.2). Added context bottleneck for long sequences (§3.2). Reformulated L_AST as bidirectional parser-based regularizer (§3.3.2). Added microbenchmark plan table (§3.5.2). Added ASTRAL Editing Benchmark (§7.5). Added surrogate correlation ablation (§7.6). Added synthetic broken code generation for surrogate training (§4.2). Added Perceiver reference. Softened absolute novelty claims (§8.5). Added time-to-valid metric. Moved product surface statement to abstract.