Enforcing Grammar in Code Synthesis with Transformers

Dmytro Vitel, Stephen Steinle, John LicatoProceedings of the ... International Florida Artificial Intelligence Research Society Conference 2023

Abstract

Even more so than natural language, code is extremely sensitive to syntax; a small error could make an entire snippet invalid. It is therefore important to explore methods for ensuring syntactic correctness in generated code. Existing methods to resolve this issue often rely on the complex architecture of syntax-guided decoders. In this work, we present the grammar enforcement method, which introduces a separate layer that constrains the decisions of the transformer during fine-tuning according to syntactic constructs present both in the target language grammar and the given training set. We experiment with the Hearthstone dataset to study its effects on result programs and compare it with the existing state-of-art syntax-guided decoders. We demonstrate a statistically significant positive effect of grammar enforcement on the quality of generated programs in terms of exact match accuracy and grammatically correct percent of samples. At the same time, we observe lower values for text-based metrics, chrF, and BLEU, potentially indicating their inability to represent the quality of generated abstract syntax sequences.

Introduction

Large Language Models (LLMs) have demonstrated remarkable proficiency in code generation. However, unlike natural language, programming languages are governed by strict formal grammars where a single misplaced character can invalidate an entire program. Standard Transformer architectures lack an inherent mechanism to enforce these rules, often leading to syntactically incorrect outputs.

Current solutions typically involve "syntax-guided decoders"—specialized neural architectures designed to follow grammar rules during generation. While effective, these models are often complex, difficult to train, and hard to adapt to different base models. This research proposes a "black-box" alternative: a Grammar Enforcement (GE) layer that constrains standard Transformers to obey syntactic rules without requiring architectural redesign.

Methodology: The Grammar Enforcement Layer

The Grammar Enforcement (GE) method operates as a separate layer atop a standard Transformer. It consists of two primary components:

  1. Grammar Statistics Collector: This component analyzes the training dataset to map valid syntactic transitions based on the language's Abstract Syntax Tree (AST). It identifies which nodes can follow others, effectively learning the "shape" of valid programs.
  2. Grammar Enforcement Layer: Implemented as a finite state transducer (FST), this layer acts as a dynamic mask during inference. By identifying valid tokens at each step, it adjusts the model's output logits—preserving or boosting valid tokens while penalizing invalid ones.
Finite State Transducer (FST) used to manage transitions between symbol, literal, and list generation states.

To facilitate this, code is represented as a linearized AST. The model predicts a sequence of tree nodes (e.g., Module, Expr, BinOp), which the GE layer ensures form a valid tree structure before they are converted back into source code.

Experimental Results

The researchers evaluated the GE method using the Hearthstone dataset, a benchmark for mapping natural language descriptions to Python code, using distilgpt2 as the base model.

Syntactic Correctness and Accuracy

The most striking result was the improvement in syntactic reliability. A standard Transformer achieved only 33.6% grammatical correctness. With the GE layer enabled, this figure rose to a perfect 100%. Furthermore, the GE method significantly improved Exact Match (EM) accuracy.

Comparison of the Grammar Enforcement (GE) method against various state-of-the-art syntax-guided decoders on the Hearthstone benchmark.

As shown in the results, the GE method achieved an exact match accuracy of 30.3% (at down = 0.7), making it highly competitive with complex, specialized architectures like TreeGen-B (31.8%), despite the GE approach requiring no additional trainable weights.

The "Fuzzy" Sweet Spot

An interesting finding was that the best performance did not come from the strictest enforcement during fine-tuning. A hyperparameter called "down-level" controls the penalty applied to invalid tokens. Setting this to a "fuzzy" value (between 0.3 and 0.7) allowed the model to explore slightly beyond the strict grammar during training, which ultimately led to better generalization and higher EM accuracy than a hard mask (0.0).

The BLEU Paradox

The study highlighted a discrepancy between functional correctness and traditional text-based metrics like BLEU and chrF. While GE-enabled models produced more correct and concise code, their BLEU scores were often lower than unconstrained models. Unconstrained models tend to produce long, repetitive sequences that mimic the "noise" in training data, artificially inflating n-gram overlap metrics while failing to produce valid code.

Conclusion and Future Work

The Grammar Enforcement method demonstrates that syntactic correctness can be achieved in code synthesis without complex architectural changes. By using a simple, portable masking layer, researchers can ensure 100% valid syntax while maintaining competitive accuracy.

Future work aims to address current limitations, such as handling multi-token identifiers more robustly and incorporating static analysis to ensure semantic correctness (e.g., variable definition checks). This approach paves the way for more reliable code generation in smaller, efficient models.

Summary updated

BibTeX
@inproceedings{vitel2023enforcing,
  author = {Dmytro Vitel and Stephen Steinle and John Licato},
  title = {{Enforcing Grammar in Code Synthesis with Transformers}},
  booktitle = {Proceedings of the ... International Florida Artificial Intelligence Research Society Conference},
  year = {2023},
  doi = {10.32473/flairs.36.133363},
}
Figure