A watermark for generated code is a hidden statistical signature: during generation, some tokens are nudged toward a secret pseudo-random "green" subset of the vocabulary, and a detector later counts how many green tokens appear. The approach breaks down on short code. A ten-line function offers few tokens to count, and many of them cannot be nudged without changing what the program does. Current methods decide where to place the signature using the model's uncertainty, called entropy, at each position. Entropy, however, measures whether the model hesitates, not whether the program would still work. A comparison operator such as < versus <= can be high-entropy and behavior-critical. A freshly named local variable can be low-entropy and completely free. We propose to measure this freedom directly by running the code. For each token in a passing solution, we swap in plausible alternatives and rerun the unit tests. The fraction of swaps that still pass is the position's execution slack.
The proposal builds three things on top of slack. The first is a small classifier that predicts slack from code text alone. The second places watermark strength only at slack positions, scaled by how free each position is. The third embeds that watermark into the model's weights by distillation, with the gradient masked to zero everywhere except slack positions, so the logic tokens receive no watermark-driven update. Detection then uses a slack-weighted statistic instead of an unweighted count. The bet is that this holds functional correctness, measured by executing hidden tests, while making snippets of 16 to 32 tokens detectable. Entropy gating cannot do that, because it discards too many positions and keeps some dangerous ones.
Core Claim
In short code, the limit on watermark detectability is the number of positions where the token can change without changing behavior, and how much evidence each such position carries. Entropy is a noisy stand-in for that number. Execution can label it directly, and the labels can steer three components of a watermarking system: where the signature is placed, which tokens receive gradient when the signature is trained into weights, and how the detector weights each token.
Prior Work
Three lines of work motivate this proposal.
Who Wrote this Code? Watermarking for Code Generation introduced SWEET, which watermarks only positions whose entropy exceeds a threshold and scores only those positions. It reports an AUROC of 0.943 on HumanEval, with Pass@1 within 2–4% of the unwatermarked model. Because it scores only the gated positions, it shrinks the effective sample on short snippets. Its gate is also a proxy we intend to replace.
A Likelihood Based Approach for Watermark Detection shows that unweighted counting is statistically wasteful, since some tokens carry far more evidence than others. On C4 natural-language text, a weighted likelihood-ratio test reaches power near 0.8 at length 10, against about 0.55 for the baseline. It was never tested on code. It also needs the generating model's probabilities, and therefore the prompt, at detection time. Our slack classifier reads only the code, which removes that requirement.
Two RL systems learn a placement policy from execution rewards. Adaptive Code Watermarking Through Reinforcement Learning trains a 118M-parameter auxiliary policy and reports 62.65% Pass@1 and 77.71% AUROC on HumanEval. SWaRL trains LoRA weights jointly with a neural verifier and reports 58.22% Pass@1 against 55.23% for unwatermarked SFT, with AUROC 0.705–0.908. Both compress execution into one scalar reward per program. Both update every token uniformly. Neither bounds false positives analytically on short outputs.
The gradient-masking literature supplies our training method. Uncovering the Gradient Geometry of Long CoT zeroes backward gradients on low-value steps while keeping them in the forward pass for context. That gives a 5.5% average gain and raises AIME 2024 from 51.7% to 59.2% for Qwen3-4B-Instruct. Disentangling Reasoning Tokens and Boilerplate Tokens shows that uniform loss is dominated by boilerplate the model learns early. We reuse the forward-keep, backward-mask recipe. Our mask is derived from execution rather than from gradient geometry or shuffling statistics. CAPO masks curvature spikes in RL, and its authors note it is unverified on code. We do not depend on it, but we use it as a check that our gains are not just optimizer stabilization.
Execution-based evaluation constrains the whole design. Evaluating Large Language Models Trained on Code defines pass@k on HumanEval. Program Synthesis with Large Language Models supplies MBPP. APPS supplies training problems with many tests. Test-suite incompleteness is the main hazard for slack labels: a swap that passes weak tests may still be wrong. We therefore label slack against expanded test suites in the style of HumanEval+ and MBPP+.
Research Program
Slack labeling. We take passing solutions from the APPS training split, MBPP's training portion, and a subset of the OpenCoder-LLM data used by SWaRL. For each token position, we replace the token with the base model's top-k alternatives, keep the rest of the program fixed, and rerun the tests. Identifiers need special handling. A rename is applied consistently at all later references, so slack sits at the identifier's first occurrence. Later occurrences are marked deterministic.
The slack of position $t$, written $s_t \in [0,1]$, is the probability-weighted fraction of alternatives that still pass. This is the expensive step. It runs offline, once, with sandboxed execution. We report the execution budget it consumes.
Slack classifier. A small encoder reads only the code text and predicts $s_t$. This lets detection run without the prompt or the generator's logits.
Generation. The green-list bias at position $t$ becomes $\delta \cdot s_t$, using predicted slack in place of SWEET's entropy gate.
Weight embedding. A teacher produces slack-watermarked samples. The student is fine-tuned on them with the full sequence in the forward pass, but the loss, a KL divergence to the teacher, is applied only at positions with $s_t$ above a cutoff. Logic tokens therefore keep the student's original distribution. This is the setting of open-weight release that SWaRL targets.
Detection. Detection uses a weighted score over all $N$ tokens,
$$S = \frac{\sum_{t=1}^{N} w_t\,(g_t - \gamma)}{\sqrt{\gamma(1-\gamma)\sum_{t=1}^{N} w_t^2}},$$
where $g_t \in \{0,1\}$ indicates a green token, $\gamma$ is the green-list fraction, and $w_t$ is the weight on position $t$. Under the null hypothesis of unwatermarked code, each $g_t$ is green with probability $\gamma$ independently of the weights. The weights come from the slack classifier applied to the observed code and do not depend on the secret key. $S$ is therefore approximately standard normal, which gives an analytic false-positive bound. A plain z-score is the special case of uniform weights.
The weights follow the expected green shift at each position, which grows with $s_t$ and with the bias applied there. That is the green-list analogue of the likelihood-ratio weighting in Li et al. For very short inputs the normal approximation is loose, so we also calibrate thresholds empirically on human-written code.
Baselines
Unwatermarked model. The naive reference point fixes the Pass@1 ceiling on HumanEval, MBPP, HumanEval+, and MBPP+. Every watermark is judged by how far below it falls. Standard WLLM, a fixed bias on every token, is the other end of the trade-off. SWaRL reports that it drops Pass@1 to 30.82% from 55.23% unwatermarked.
SWEET. This is the strongest training-free competitor. It addresses exactly the correctness-versus-detectability trade-off with an inference-time gate. It reports 0.943 AUROC on HumanEval, pooled over all lengths rather than reported for short outputs. We rerun it on the same base model and the same prompts, sweeping its entropy threshold over the same budget we give our slack cutoff. Beating it means higher true-positive rate at 1% false-positive rate in the 16–32 token bucket at equal or better Pass@1.
CodeTracer and SWaRL. These are the strongest learned competitors. Both already use execution feedback and could in principle discover slack implicitly. CodeTracer reports 77.71% AUROC on HumanEval and 78.42% on MBPP. SWaRL reports 0.705–0.908 AUROC and 58.22% Pass@1. We retrain both on the same base model and the same OpenCoder subset. We match the total execution budget, counting our offline labeling runs against their RL rollouts. Beating them means a better short-length detection curve at matched Pass@1, with an analytic false-positive bound they lack.
Ablations. Two ablations isolate the key ingredient. The first keeps our whole pipeline but replaces execution slack with entropy, used everywhere: in the generation gate, in the gradient mask, and in the detector weights. Losing to this ablation would mean execution labels add nothing. The second keeps slack placement but trains with uniform loss instead of the masked loss. This tests whether masking matters for Pass@1 once watermarks are embedded in the weights. A CAPO-style curvature mask, run as a third variant, checks whether any mask would do.
Why not just…?
Why not just pair SWEET with a weighted detector and skip execution entirely? This is the most serious threat. If entropy and slack select nearly the same positions, the execution step is wasted compute. The entropy-for-slack ablation settles it directly. Before any watermarking, we also measure the overlap between high-entropy and high-slack positions on labeled data, and count behavior-critical high-entropy tokens such as operators and boundary constants. If the overlap is high and the ablation ties, we will report that entropy suffices and drop the claim.
Why not just let RL with execution rewards find the free tokens, as CodeTracer and SWaRL do? It may, but a single pass/fail reward per program gives weak credit for any individual token. Both systems also score detection with either an unweighted z-score or a neural verifier, so neither targets the short-length regime. The matched-budget comparison by length bucket shows whether their implicit placement matches explicit labels. If it does at long lengths but not short ones, the gap is the weighted detector rather than the labels. We report the two effects separately by swapping our detector onto their outputs.
Why not just apply the watermark at inference time and never touch the weights? If the model owner controls decoding, that may be enough, and our inference-time variant is exactly this. Weight embedding is only needed for released models. There the risk is that distilling watermarked samples with uniform loss shifts the logic tokens as well. The masked-versus-uniform ablation measures that risk in Pass@1. If uniform distillation loses nothing, masking is unnecessary and we will say so.
Proposed Experiments
Base model and evaluation sets. The base model is a 7B-class open code model, used for every method. Evaluation uses HumanEval, MBPP, HumanEval+, and MBPP+ for Pass@1. For detection, we construct a short-output regime: single-line and short-block infills cut from HumanEval and MBPP solutions, bucketed at at most 16, 16–32, 32–64, and more than 64 generated tokens. Human-written negatives in each bucket calibrate false positives.
Metrics. The primary metric is true-positive rate at 1% false-positive rate per length bucket. We also report AUROC for comparability with the cited numbers, and the minimum length needed to reach 0.8 true-positive rate. No reported result was found on Lacuna for likelihood-weighted watermark detection on code. Li et al.'s 0.8 power at length 10 is on natural language, and we treat it as an aspiration, not a target.
Robustness and slack quality. We test robustness by applying consistent variable renaming and refactoring to watermarked outputs. SWaRL reports a 3.45% detectability drop under refactoring against 12–17% for competing methods, and we use that as the reference. Slack concentrated on identifiers may be fragile under renaming, so this experiment could expose a real weakness. We also check slack label quality by re-testing a sample of "free" swaps against expanded tests and reporting how often slack was a false positive of weak tests.
Decisive checks. Three results decide the proposal. The first is whether slack weighting beats entropy weighting in the 16–32 token bucket at matched Pass@1. The second is whether masked distillation keeps Pass@1 within the unwatermarked model's confidence interval while uniform distillation does not. The third is whether the analytic bound on $S$ matches the empirical false-positive rate on human-written code at short lengths.
References
- Who Wrote this Code? Watermarking for Code Generation
- A Likelihood Based Approach for Watermark Detection
- Adaptive Code Watermarking Through Reinforcement Learning
- SWaRL: Safeguard Code Watermarking via Reinforcement Learning
- Uncovering the Gradient Geometry of Long CoT: A Spectral-guided Approach to Reasoning Distillation
- Disentangling Reasoning Tokens and Boilerplate Tokens For Language Model Fine-tuning
- Stabilizing Policy Gradients for Sample-Efficient Reinforcement Learning in LLM Reasoning
- Evaluating Large Language Models Trained on Code
- Program Synthesis with Large Language Models
- Measuring Coding Challenge Competence With APPS