TLDR
- What: Grammar-Driven Watermarking (GDW) preserves syntactic correctness in LLM-generated code using context-free grammars (CFGs) and adjusts watermark strength based on the structural roles of tokens (syntax-critical vs. content-bearing).
- Who's at risk: Enterprise code-generation pipelines, AI coding assistants (e.g., Copilot, Cursor, Claude Code), and open-source compliance frameworks trying to track intellectual property or detect machine-generated code without breaking compilability.
- Key number: GDW achieves an Area Under the Trade-off Curve (AUTC) of up to 0.951 (Qwen2.5-Coder-3B on HumanEvalPack-Go), outperforming standard KGW by up to 0.116 points on low-entropy code generation benchmarks.
In recent years, large language models (LLMs) have become indispensable tools for code generation, powering popular coding assistants like GitHub Copilot, Cursor, and Claude Code. However, as AI-generated code increasingly integrates into open-source projects and proprietary codebases, concerns over licensing, copyright infringement, and provenance have surged.
Traditional text watermarking methods, which subtly bias token selection to leave statistical footprints, struggle when applied to code. Because programming languages are inherently low-entropy (governed by rigid syntax and predictable structures), naively modifying output logits often breaks compilability, degrades code quality, or fails to embed a detectable signature. GDW attempts to solve this by making the watermarking process explicitly aware of code grammar and token functionality.
Threat Model
| Attacker | A user or third-party entity trying to bypass the watermark (e.g., through variable-renaming attacks or local edits) while preserving code execution functionality. |
| Victim | LLM providers or IP owners seeking to reliably verify if a code snippet was generated by their model. |
| Goal | Embed a highly detectable, statistically significant watermark (high z-score/F1-score) without degrading code quality or syntactic validity. |
| Budget | Zero retraining or fine-tuning cost. The watermarking mechanism runs entirely at inference time, albeit with a slight computational overhead from incremental parsing. |
Background & Problem Setup
The primary challenge in code watermarking is the low-entropy nature of programming languages. As shown in Figure 2 of the paper, syntax-critical tokens (like keywords and operators) consistently exhibit significantly lower mean token entropy (e.g., 0.419 on MBPP+ with Qwen2.5-Coder-3B) compared to content-bearing tokens (like variable identifiers, which average 0.649 on the same dataset).
When standard logits-based watermarks apply uniform biases across all tokens, they risk corrupting these highly deterministic, syntax-critical positions, causing syntax errors. Conversely, entropy-based baselines that simply skip low-entropy tokens lose valuable opportunities to embed watermark signals, degrading detectability.
The following table compares the GDW approach with existing methods cited in the paper:
| Method | Entropy-Aware? | Syntax-Preserving? | Detection Strategy | Primary Bottleneck / Limitation |
|---|---|---|---|---|
| KGW (Kirchenbauer et al., 2023a) | No | No | Standard z-test on uniform greenlist count | Distorts rigid code syntax, causing compilation and logic errors. |
| SWEET (Lee et al., 2024) | Yes (Threshold-based) | No | Standard z-test on high-entropy tokens | Completely excludes low-entropy tokens, severely limiting watermark detectability. |
| EWD (Lu et al., 2024) | Yes | No | Entropy-weighted z-test | Lacks formal syntactic awareness, risking logic errors on boundary tokens. |
| CodeIP (Guan et al., 2024) | No | Yes (Type predictor) | Model-based classification | Demands substantial computational resources to train and run a specialized type predictor. |
| GDW (Ours) | Yes (Via structural role) | Yes (CFG-constrained) | Role-aware weighted z-test | Introduces inference latency overhead due to incremental CFG parsing. |
Methodology
GDW mitigates the trade-off between code quality and watermark strength through a three-step generation framework and an aligned, weighted detection mechanism.
+--------------------------+
| Input Prefix Code |
+-------------+------------+
|
v
+----------------+---------------+
| Incremental CFG Parsing |
+----------------+---------------+
|
v
+----------------------+----------------------+
| |
v v
+--------+--------+ +--------+--------+
| Syntax Validity | | Greenlist Split |
| Mask (Msyn) | | Mask (Mwm) |
+--------+--------+ +--------+--------+
| |
+----------------------+----------------------+
|
v
+-------------+------------+
| Eligibility Mask (Melig)|
+-------------+------------+
|
v
+------------------+------------------+
| Structural Role Modulation (Mrole) |
| - Weak bias (\delta) for Syntax |
| - Strong bias (\lambda*\delta) |
| for Content Tokens |
+------------------+------------------+
|
v
+-------------+------------+
| Watermarked Logits |
+--------------------------+
Step 1: Three-Level Masking Mechanism
At each decoding step , GDW constructs three binary masks over the vocabulary to determine where a watermark can be safely applied:
-
Watermark Greenlist Mask (): Partitions the vocabulary based on a hash of the preceding token (following standard KGW).
-
Syntactic Validity Mask (): An incremental parser evaluates the current prefix against Context-Free Grammar (CFG) rules in EBNF format, identifying the set of syntactically admissible next tokens .
-
Eligibility Mask (): Merges both constraints via element-wise multiplication:
Melig,t = Mwm,t \odot Msyn,t
#### Step 2: Structural Role-Aware Modulation Tokens are categorized into **syntax-critical** ($V_{syntax}$) and **content-bearing** ($V_{content}$) sets. To avoid disrupting program structures, GDW scales the watermark strength using a role function $r(v)$:r(v) = \begin{cases} 1, & \text{if } v \in V_{syntax} \ \lambda, & \text{if } v \in V_{content} \end{cases}
Here, $\lambda > 1$ represents a scaling factor that amplifies watermark signals in high-entropy, content-bearing regions (e.g., variable names and literals) while maintaining a conservative bias ($\delta$) on syntax-critical keywords (e.g., `def`, `if`, `while`). #### Step 3: Hierarchical Logit Modulation The final watermarked logits $l'_t$ are calculated as:l'_t = l_t + Melig,t \odot (Mrole + \lambda \cdot (1 - Mrole)) \cdot \delta
Where $M_{role}$ is the structural role mask ($1$ for syntax-critical, $0$ for content-bearing tokens). This formula restricts logit perturbation strictly to syntactically valid greenlist tokens, while dynamically scaling strength based on the token's structural role. #### Step 4: Role-Aware Weighted Detection To verify the watermark, GDW computes a weighted z-score that aligns with the generation step. Instead of treating all tokens equally, it scales the contribution of each token by its role-aware weight $w_t = r(x_t)$:z = \frac{\sum_{t=2}^T w_t I_t - \gamma \sum_{t=2}^T w_t}{\sqrt{\gamma(1 - \gamma) \sum_{t=2}^T w_t^2}}
Where $I_t$ is an indicator variable indicating whether token $x_t$ belongs to the greenlist $G_t$, and $\gamma$ is the greenlist ratio. --- ### Key Results The authors evaluated GDW against six baselines across three models (StarCoder2-3B, Qwen2.5-Coder-3B, and Qwen3-4B) using HumanEval (Python) and HumanEvalPack (Java, Go). The primary metric, **Area Under the Trade-off Curve (AUTC)**, measures the normalized area under the Pass@1 vs. F1-score curve. A higher AUTC represents a superior trade-off frontier. #### Table 1: Quality-Detectability Trade-off (AUTC) on Python Benchmarks *The highest AUTC in each category is highlighted in bold.* | Methods | Qwen2.5-Coder-3B (HumanEval - Sample) | Qwen2.5-Coder-3B (HumanEval - Beam) | Qwen3-4B (HumanEval - Sample) | StarCoder2-3B (HumanEval - Sample) | |---|---|---|---|---| | **KGW** | 0.745 | 0.832 | 0.714 | 0.691 | | **SWEET** | 0.784 | 0.742 | 0.766 | 0.722 | | **EWD** | 0.771 | 0.774 | 0.796 | 0.712 | | **STONE** | 0.666 | 0.677 | 0.666 | 0.681 | | **CodeIP** | 0.805 | 0.730 | 0.722 | 0.725 | | **SynthID-Text** | 0.702 | 0.692 | 0.705 | 0.700 | | **GDW (Ours)** | **0.811** | **0.847** | **0.830** | **0.743** | *Skeptical Analysis of Table 1:* GDW consistently leads across all models. While the improvements over older methods like KGW are substantial (e.g., GDW's 0.830 vs. KGW's 0.714 on Qwen3-4B), the margin over specialized code watermarks like CodeIP under sample decoding can be relatively narrow (0.811 vs. 0.805). However, under deterministic decoding configurations like beam search, GDW's advantage becomes highly pronounced (0.847 vs. CodeIP's 0.730). #### Table 2: Robustness Under Variable Renaming Attack (AUTC) Variable renaming is the most common bypass technique used by adversaries. By systematically replacing variable names with arbitrary identifiers, adversaries target content-bearing tokens where GDW embeds its strongest signal. | Method | Before Attack | After Attack | Performance Drop | |---|---|---|---| | **KGW** | 0.832 | 0.811 | 0.021 | | **SWEET** | 0.742 | 0.685 | 0.057 | | **CodeIP** | 0.730 | 0.696 | 0.034 | | **GDW (Ours)** | **0.847** | **0.819** | **0.028** | *Skeptical Analysis of Table 2:* As expected, the attack successfully degrades GDW's performance, dropping its AUTC from 0.847 to 0.819 (a loss of 0.028). Despite this drop, GDW still retains the highest absolute post-attack AUTC among all compared methods, demonstrating that its weighted detection framework preserves robustness even when identifier tokens are completely scrambled. --- ### Limitations & Open Questions 1. **Inference Latency Overhead**: GDW relies on an incremental parser to evaluate the CFG rules at *every single token generation step*. The authors note this "introduces a slight computational overhead during the inference stage due to the necessity of incremental grammar parsing." In production environments where tokens-per-second (TPS) is a primary KPI, this parsing overhead could bottleneck high-throughput applications. 2. **Grammar Spec Sensitivity**: The method depends on strict adherence to predefined EBNF grammars. If an application requires generating multi-language code blocks, pseudo-code, or non-standard syntax extensions, a rigid CFG parser may overly constrain the LLM's vocabulary, causing artificial generation failures. 3. **Vulnerability to Code Refactoring**: While the paper evaluates variable renaming (Table 5), it does not test GDW's resilience against semantic-preserving structural modifications (e.g., converting a `for` loop to a `while` loop, or flattening helper functions). Since GDW places its conservative, weaker watermark on syntax-critical structures, structural refactoring could disproportionately degrade its detectability compared to identifier renaming. --- ### What Practitioners Should Do If you are an ML engineer or security researcher tasked with implementing code watermarking, follow these integration steps: 1. **Adopt Structural Token Segmentation**: Do not apply uniform logit biases. Separate your tokenizer's vocabulary into $V_{syntax}$ (control flow keywords, braces, mathematical operators) and $V_{content}$ (user-defined strings, variable names, literals). 2. **Calibrate the Scaling Factor ($\lambda$)**: Set the scaling parameter to $\lambda = 2.0$. As demonstrated in the paper's parameter sweep (Table 3), setting $\lambda = 2.0$ yields the optimal trade-off of 0.942 AUTC on Java benchmarks. Pushing $\lambda$ to 5.0 results in overly aggressive perturbation of content tokens, dropping the AUTC to 0.897. 3. **Optimize Incremental Parsing**: Implement the incremental grammar parsing step using specialized incremental parsers or parallelization techniques to minimize the computational overhead during the inference stage. 4. **Enforce Role-Aware Weighted z-scores on the Detection Client**: Ensure your detection API does not treat all greenlist matches equally. Scale the statistical importance of each matched token by its structural role weight ($w_t = 1.0$ for keywords, $w_t = \lambda$ for identifiers) to maximize statistical power. --- ### The Takeaway GDW demonstrates that effective watermarking of highly structured text like code cannot be syntax-agnostic. By combining context-free grammar constraints with role-aware logit scaling, it achieves a superior quality-detectability frontier without requiring model fine-tuning. However, practitioners must carefully weigh GDW's superior detection metrics against the real-world latency cost of running continuous grammar parsing during LLM inference. --- ## Den's Take I am highly encouraged by this work because it finally treats code watermarking as a grammar-constrained compiler problem rather than a generic natural language token-biasing exercise. Standard methods like KGW fail miserably in low-entropy code generation because they blindly bias syntax-critical tokens. This paper’s observation that syntax-critical tokens have a mean entropy of just 0.419 compared to 0.649 for content-bearing tokens on MBPP+ perfectly highlights why uniform logit-biasing breaks compilability. By using context-free grammars (CFGs) to dynamically adjust watermark strength based on syntactic roles, GDW achieves an impressive Area Under the Trade-off Curve (AUTC) of up to 0.951 on Qwen2.5-Coder-3B. Outperforming standard KGW by up to 0.116 points on HumanEval demonstrates that structural awareness is the only viable path forward for protecting intellectual property in developer tooling. This closely mirrors the core argument that watermark design must respect the underlying information entropy limits of the target domain to remain both detectable and non-disruptive. My only practical reservation is how GDW handles simple post-generation edits. While CFGs guarantee syntactic validity during generation, an adversary can easily strip the watermark using automated semantic-preserving refactoring tools. Until we address robustness against AST-level modifications, even the most grammatically elegant inference-time watermarks will struggle in adversarial environments.