---
title: Directed-Token Approach in Code Watermarking
url: https://www.emergentmind.com/topics/directed-token-approach
type: topic
---

# Directed-Token Approach in Code Watermarking

The Directed-Token Approach, as introduced in CodeTracer, is a policy-driven code watermarking method in which a small watermarking policy $\pi_\phi$ is interposed alongside a frozen base code LLM $\pi_\theta$ and used to bias next-token prediction only at selected decoding positions. The method is designed for the highly structured and syntactically constrained environment of code generation: it aims to embed a statistically detectable watermark while preserving code functionality, and it is trained by reinforcement learning with execution feedback, watermark embedding signals, and a differentiable relaxation for discrete token-selection decisions [2508.11925].

## 1. Policy-driven token biasing

At decoding step $t$, the frozen model $\pi_\theta$ produces unmodified logits
\[
l_j=\bigl[\logit(\pi_\theta(y_t=v_j\mid x,\,y_{<t}))\bigr]_{j=1}^{|V|},
\]
where $V$ is the full vocabulary. The watermarking policy $\pi_\phi$ observes the same context
\[
c_t=(x,y_{(t-c)\dots(t-1)})
\]
and outputs two objects: a binary switch $w_t\in\{0,1\}$ indicating whether watermarking should be applied at that position, and a subset $G_t\subset V$ of size $|G_t|=\lfloor \gamma\cdot |V|\rfloor$, called the green list [2508.11925].

The composite policy $\pi_{\theta\oplus\phi}$ biases the logits by adding a fixed positive bias $\delta$ only to vocabulary items that belong to the selected green list and only when the switch is active:
\[
\tilde l_j=l_j+w_t\,\delta\,\mathbf{1}_{v_j\in G_t}.
\]
Sampling then proceeds from $\mathrm{softmax}(\tilde l)$. In this formulation, watermarking is not a uniform perturbation over all decoding steps. Because $\pi_\phi$ can set $w_t=0$, no bias is added at positions judged unsafe for watermarking. When $w_t=1$, the green list is chosen by a learned subpolicy so that the biased tokens remain syntactically valid in context [2508.11925].

Semantic preservation is enforced operationally rather than by a static constraint. During training, outputs that fail compilation or test cases are punished through the reward system. A common misconception is that the method simply forces “green” tokens whenever possible; the actual mechanism is selective and context-conditioned, with the policy learning when to abstain and how to choose a green list that is compatible with valid code generation.

## 2. Reinforcement-learning formulation

Learning the watermark policy parameters $\phi$ is cast as a policy-gradient problem under Group Relative Policy Optimization (GRPO). In each rollout, the system generates $K$ completions under $\pi_{\theta\oplus\phi}$, collects execution and watermarking feedback, forms advantages, and updates only $\phi$; the base model parameters $\theta$ remain frozen [2508.11925].

The reward decomposes into three terms. The execution reward $R_1$ evaluates functional correctness:
\[
R_1(s)=
\begin{cases}
1, & \text{if all test cases pass},\\
0, & \text{otherwise}.
\end{cases}
\]
The outcome-based watermark reward $R_2$ measures statistical detectability through the watermark z-score:
\[
R_2(s)=
\begin{cases}
1, & z(s)\ge 3,\\
z(s)/3, & 0<z(s)<3,\\
0, & z(s)\le 0,
\end{cases}
\qquad
z(s)=\frac{N_G-T\gamma}{\sqrt{T\gamma(1-\gamma)}}.
\]
Here $T$ is the number of positions where $w_t=1$, and $N_G$ counts how many sampled tokens at those positions fall in the corresponding green lists. The process-based watermark reward $R_3$ supplies token-level credit:
\[
R_3(s_t,a_t)=
\begin{cases}
+1, & w_t=1\wedge y_t\in G_t,\\
-1, & w_t=1\wedge y_t\notin G_t,\\
0, & w_t=0.
\end{cases}
\]
These are combined through a weighted sum
\[
R(s_t,a_t)=\alpha R_1(s)+\beta R_2(s)+\gamma_{\rm p}R_3(s_t,a_t),
\]
with $\alpha,\beta,\gamma_{\rm p}\ge 0$ chosen by hyperparameter sweep [2508.11925].

The full objective maximizes discounted reward under a KL regularizer against a lagged reference policy $\pi_{\mathrm{ref}}$, which is a lagged copy of $\pi_{\theta\oplus\phi}$. The regularization term is explicitly described as a small penalty to prevent drifting too far from $\pi_\theta$ [2508.11925]. This coupling of execution reward and watermark reward is central: correctness is treated as a first-class optimization target rather than as a post hoc filter.

## 3. Discrete green-list selection and Gumbel Top-k

Choosing $G_t$ is a discrete top-$k$ decision over a vocabulary-sized score vector $\ell_\phi$, which is non-differentiable. To address this, the method adopts Gumbel Top-$k$ reparameterization. The perturbed logits are
\[
g_j=\ell_{\phi,j}+[-\log(-\log(u_j))],\qquad u_j\sim\mathrm{Uniform}(0,1),
\]
and the green list is defined by
\[
G_t=\mathrm{arg\,top\text{-}k}(g),\qquad k=\lfloor\gamma |V|\rfloor.
\]
This provides a hard set in the forward pass [2508.11925].

For backpropagation, CodeTracer uses a differentiable relaxation via a Gumbel-Softmax soft indicator vector $\ell_G\in[0,1]^{|V|}$:
\[
\ell_{G,j}
= \mathbf{1}_{j\in G_t} + S(g)_j - \mathrm{sg}(S(g)_j),
\]
where $\mathrm{sg}(\cdot)$ denotes stop-gradient. A temperature $\tau$ may be applied inside $S(g)$ to control sharpness. The result is a straight-through construction: the forward pass uses the hard top-$k$ set, while the backward pass propagates through the continuous relaxation [2508.11925].

This component is technically consequential because the watermark policy does not merely choose whether to watermark. It also learns which subset of the vocabulary should receive the bias at each step. The Gumbel Top-$k$ mechanism therefore turns green-list construction into an optimized, context-sensitive control problem rather than a fixed heuristic.

## 4. Architecture and generation procedure

The watermark policy is implemented as a small transformer encoder with 6 layers, 8 heads, $d_{\text{model}}=512$, and $d_{\text{ff}}=2048$. Its input is the last $c=2$ tokens of context plus embeddings. It outputs a scalar logit $w_\phi$ for the binary watermark switch, using a straight-through sigmoid, and a $|V|$-dimensional vector $\ell_\phi$ for green-list selection [2508.11925].

The generation loop follows a fixed pattern. At each step, the policy reads the recent context, predicts the watermark switch and green-list scores, thresholds the switch by $w=\mathbf{1}[w_\phi>0.5]$, and either leaves the base logits untouched or adds $\delta\cdot \mathbf{1}[v\in G]$ to produce biased logits. The next token is then sampled from the resulting softmax. The RL loop further reconstructs $(w_t,G_t)$ for each generated token, computes $R_1$, $R_2$, and $R_3$, aggregates advantages, normalizes group rewards, subtracts reference-policy log-probabilities, and adds the KL penalty before updating $\phi$ [2508.11925].

Two implementation details matter for interpretation. First, the policy has access only to a short local context window, not the full sequence history. Second, the base model remains frozen. This suggests that the Directed-Token Approach is intended as an adaptive watermarking layer over an existing code generator rather than as a retraining strategy for the generator itself.

## 5. Empirical performance and attack resilience

The reported evaluation compares CodeTracer with a no-watermark base model and practical watermark baselines WLLM and EXP-edit. The reproduced summary reports the following values [2508.11925]:

| Method | Pass@1/10 | AUROC / TPR@5%FPR |
|---|---:|---:|
| Base | 65.42 / 79.17 | — |
| WLLM | 58.05 / 70.35 | 70.17% / 20.73% |
| EXP-edit | 59.29 / 72.41 | 66.50% / 25.61% |
| CodeTracer | 60.82 / 79.72 | 82.95% / 46.34% |

These results are described as demonstrating significant superiority over state-of-the-art baselines in both watermark detectability and preservation of generated code functionality [2508.11925]. The functional metrics show that CodeTracer narrows the gap to the unwatermarked base model relative to the other practical watermark baselines, while the detection metrics show materially stronger separability.

Under adversarial code-transformation attacks, CodeTracer is reported to retain the highest AUROC and TPR. The supplied example is renaming, where CodeTracer achieves 73.36% AUROC versus 62.02% for EXP-edit [2508.11925]. Scaling to the larger 8B model yields 78.69% AUROC with only an approximately 0.4% drop in Pass@1, indicating that the approach is not limited to the specific smaller model configuration used in the main experiments.

A common misunderstanding is that stronger detectability necessarily requires aggressive distortion of generated programs. The reported results suggest a different operating point: token-level, policy-conditioned biasing can improve detectability while remaining competitive in Pass@1 and Pass@10 relative to practical watermark baselines.

## 6. Position within the broader “directed-token” vocabulary

The phrase “Directed-Token Approach” is not standardized across arXiv, and its meaning depends strongly on context. In CodeTracer, it denotes policy-driven token biasing for code watermarking [2508.11925]. In TGDPO, a related phrase refers to token-level reward guidance for Direct Preference Optimization, where different tokens are assigned varying degrees of deviation from a reference policy through token-wise weights [2506.14574]. In large language-vision models, “directed tokens” denotes learnable embeddings appended to the sequence and used to reconstruct the order of shuffled visual inputs [2508.14264]. In efficient LLM inference, OrthoRank uses a directed-token interpretation based on tokens moving toward a sink token in hidden-state space and ranks them by orthogonality to that sink [2507.03865].

This suggests that the shared label identifies a broader design pattern rather than a single technique: token-level control is made explicit, and token behavior is directed by an auxiliary mechanism rather than left entirely to the base model dynamics. Within that broader family, CodeTracer is specifically an adaptive watermarking framework in which the directed-token mechanism operates at next-token logit level, is trained by GRPO, and is grounded in execution-aware reward shaping [2508.11925].

The main conceptual significance of the CodeTracer variant is therefore not merely that it biases token choice, but that it turns watermark placement into a learned control problem over discrete generation decisions. The method’s operational safeguards—selective application through $w_t$, context-dependent green-list construction, execution reward, and KL regularization—define the distinctive content of the Directed-Token Approach in code watermarking.

Source: https://www.emergentmind.com/topics/directed-token-approach