Skip to content
Detect AI Text: Build a SynthID Watermark Scorer — ContentBuffer guide

Detect AI Text: Build a SynthID Watermark Scorer

K
Kodetra Technologies··12 min read Advanced

Summary

Score any text for Claude-style SynthID watermarks in Python, with real measured g-values.

On August 14, Anthropic published the details of how Claude’s new text watermark works. Every new Claude model launched on or after August 2, 2026 embeds a machine-readable mark in the text it writes — not hidden characters, not extra tokens, nothing you can see. It is a statistical fingerprint left in the model’s word choices, and it is there to satisfy the EU AI Act Code of Practice on Transparency of AI-Generated Content.

The method is a variant of SynthID-Text, published by Google DeepMind in Nature in 2024. Anthropic says a detection API is coming but has not shipped it. That leaves a gap: people are arguing loudly about what this watermark can and cannot catch, and almost nobody arguing has actually measured one.

You can. SynthID-Text has been in Hugging Face Transformers since v4.46, and the detector that matters most for understanding the mechanism — the mean g-value scorer — needs no training at all. In this guide you will watermark your own model, build a scorer from scratch, and produce hard numbers for the three questions everyone is asking: how short is too short, how much editing kills it, and why code and factual text barely carry a mark.

Every number in this guide came out of a real run on GPT-2 on CPU. You can reproduce all of it in about ten minutes.


Prerequisites

  • Python 3.10+ and roughly 2 GB of free disk for model weights
  • torch and transformers>=4.46 (this guide was verified on torch 2.13.0+cpu and transformers 5.15.1)
  • Comfort with model.generate() and basic tensor indexing
  • No GPU required — everything here runs on CPU with gpt2
pip install 'torch' 'transformers>=4.46' numpy

Step 1 — What the watermark actually does

Start with the intuition Anthropic uses. When a model writes “The weather today was cold and ___”, both overcast and grey are fine. Sampling picks one using a random number. Watermarking does not change which words are candidates and it does not push the model toward weird words. It changes where the randomness comes from.

Concretely, SynthID-Text runs tournament sampling. At each step it takes the n-gram of recent tokens plus a secret key and feeds them through a pseudorandom function called the g-function, which assigns every candidate token a g-value of 0 or 1. Candidates are then paired off in a tournament; in each match the token with the higher g-value wins. The winner is emitted.

The consequence is subtle and important. Over a long passage, tokens that survived the tournament will carry a higher-than-chance average g-value. Text that was never watermarked has no reason to favour high-g tokens, so its average sits at 0.5. That gap is the entire signal.

Two parameters define a watermark. keys is a list of integers — the secret. Its length is the number of tournament layers (depth). Twenty to thirty keys is the documented recommendation. ngram_len is how many recent tokens seed the g-function; larger means more detectable but more brittle to edits, with 5 as the sane default.

The critical property: the g-function only needs the tokens, not the model. That is why you can score arbitrary text after the fact, and why the key must stay secret — whoever holds it can both detect and forge.


Step 2 — Configure a watermark

Transformers exposes the watermark twice. SynthIDTextWatermarkingConfig is the generation-side dataclass you hand to generate(). SynthIDTextWatermarkLogitsProcessor is the same machinery exposed directly, and it is what you use for detection. Both must be built with identical parameters or the scores are meaningless.

import torch, numpy as np
from transformers import (
    AutoTokenizer, AutoModelForCausalLM,
    SynthIDTextWatermarkingConfig,
    SynthIDTextWatermarkLogitsProcessor,
)

torch.manual_seed(0)
MODEL = "openai-community/gpt2"
DEVICE = torch.device("cpu")

# The secret. 20 keys => 20 tournament layers.
KEYS = [654, 400, 836, 123, 340, 443, 597, 160, 57, 29,
        590, 639, 13, 715, 468, 990, 966, 226, 324, 585]
NGRAM_LEN = 5

tok = AutoTokenizer.from_pretrained(MODEL)
tok.pad_token = tok.eos_token
tok.padding_side = "left"          # required for batched generation
model = AutoModelForCausalLM.from_pretrained(MODEL).eval()

# Detection-side processor. Parameters MUST match the generation config.
lp = SynthIDTextWatermarkLogitsProcessor(
    ngram_len=NGRAM_LEN,
    keys=KEYS,
    sampling_table_size=2**16,
    sampling_table_seed=0,
    context_history_size=1024,
    device=DEVICE,
)

print(lp.expected_mean_g_value(vocab_size=model.config.vocab_size))

Output:

0.7499950255685774

Note that number and then set it aside. It is the theoretical mean g-value for single-layer watermarking over a uniform next-token distribution. Real language models are nothing like uniform, so your measured scores will land well below it. Treating 0.75 as a target is the first mistake people make.


Step 3 — Generate a watermarked and an unwatermarked corpus

Adding the watermark is one keyword argument. Everything else about generation stays the same. Note that watermarking requires sampling — do_sample=True — because a greedy decode has no randomness to redirect.

PROMPTS = [
    "The best way to learn a new language is",
    "Scientists have long wondered why the ocean",
    "In the early days of the internet, people",
    "My favourite thing about living in a small town is",
    "The most surprising part of running a marathon is",
    "When you first start playing chess, the hardest thing",
    "A good cup of coffee depends on",
    "The history of the bicycle begins with",
]

def generate(watermark: bool):
    enc = tok(PROMPTS, return_tensors="pt", padding=True)
    kwargs = dict(
        do_sample=True, top_k=40, temperature=0.7,
        max_new_tokens=160, pad_token_id=tok.eos_token_id,
    )
    if watermark:
        kwargs["watermarking_config"] = SynthIDTextWatermarkingConfig(
            keys=KEYS, ngram_len=NGRAM_LEN,
        )
    with torch.no_grad():
        out = model.generate(**enc, **kwargs)
    # Score only what the model wrote, never the prompt.
    return out[:, enc["input_ids"].shape[1]:]

watermarked = generate(True)
clean = generate(False)

Slicing off the prompt matters. Prompt tokens were not chosen by the tournament, so leaving them in dilutes the score with pure noise — and on a short generation with a long prompt it can bury the signal entirely.


Step 4 — Build the scorer

The detector is about eight lines. Three calls do the work, and two of them are masks that exist for reasons worth understanding.

  1. compute_g_values(input_ids) returns g-values shaped (batch, tokens - (ngram_len - 1), depth). Each token gets one g-value per tournament layer.
  2. compute_context_repetition_mask(input_ids) zeroes out positions whose preceding context n-gram already appeared. A repeated context produces the same g-values, so counting it twice double-counts one observation — and looping models would otherwise inflate their own score.
  3. compute_eos_token_mask(input_ids, eos_token_id) zeroes out padding after end-of-sequence. Slice it by [:, ngram_len - 1:] to line it up with the g-value tensor.
def watermark_score(ids: torch.LongTensor):
    """Mean g-value over valid n-grams. ~0.5 = clean, higher = watermarked."""
    g = lp.compute_g_values(input_ids=ids)                    # (B, T-(n-1), depth)
    repetition = lp.compute_context_repetition_mask(input_ids=ids)
    eos = lp.compute_eos_token_mask(
        input_ids=ids, eos_token_id=tok.eos_token_id,
    )[:, NGRAM_LEN - 1:]

    mask = (repetition * eos).unsqueeze(-1)                   # (B, T-(n-1), 1)
    numer = (g * mask).sum(dim=(1, 2))
    denom = mask.expand_as(g).sum(dim=(1, 2)).clamp(min=1)
    scores = (numer / denom)
    n_ngrams = mask.squeeze(-1).sum(dim=1)                    # evidence available
    return scores.tolist(), n_ngrams.tolist()

Always return n_ngrams alongside the score. A score of 0.58 from 140 n-grams and a score of 0.58 from 9 n-grams are not the same claim, and conflating them is how you end up accusing a human of using AI.


Step 5 — Real numbers

Running the scorer over both corpora, eight samples each, 160 new tokens per sample:

s_wm, n_wm = watermark_score(watermarked)
s_cl, n_cl = watermark_score(clean)

print("watermarked  :", [round(x, 4) for x in s_wm])
print("clean        :", [round(x, 4) for x in s_cl])

Actual output:

watermarked  : [0.5715, 0.5762, 0.5818, 0.6155, 0.5726, 0.5928, 0.5623, 0.5935]
clean        : [0.4982, 0.4907, 0.4965, 0.5037, 0.4895, 0.5123, 0.4997, 0.4987]

mean watermarked = 0.5833   (min 0.5623)
mean clean       = 0.4987   (max 0.5123)
separation       = 0.0499

The clean distribution sits on 0.4987, within noise of the theoretical 0.5, which is a good sanity check that the scorer is correct. The watermarked distribution sits on 0.5833. Every watermarked sample scores above every clean sample, with a 0.05 gap between the two closest — on 160 tokens, from a 124M-parameter model, on a laptop CPU.

Note again that 0.5833 is nowhere near the theoretical 0.75. Nothing is broken. Real next-token distributions are sharply peaked, so most positions have almost no free choice for the tournament to exploit.


Step 6 — Worked example: the three failure modes, measured

This is the part worth your attention, because it is where the public debate is currently running on vibes.

Length

Truncate the same generations to shorter prefixes and rescore:

for L in (20, 40, 80, 160):
    s, _ = watermark_score(watermarked[:, :L])
    print(f"watermarked len={L:3d} -> mean {np.mean(s):.4f}  min {min(s):.4f}")
for L in (20, 40, 80, 160):
    s, _ = watermark_score(clean[:, :L])
    print(f"clean       len={L:3d} -> mean {np.mean(s):.4f}  max {max(s):.4f}")
watermarked len= 20 -> mean 0.6027  min 0.5813
watermarked len= 40 -> mean 0.5925  min 0.5750
watermarked len= 80 -> mean 0.5821  min 0.5693
watermarked len=160 -> mean 0.5833  min 0.5623

clean       len= 20 -> mean 0.5043  max 0.5312
clean       len= 40 -> mean 0.4961  max 0.5194
clean       len= 80 -> mean 0.4956  max 0.5037
clean       len=160 -> mean 0.4987  max 0.5123

Read the spread, not the mean. At 160 tokens the worst watermarked sample beats the best clean sample by 0.050. At 20 tokens that margin has closed to 0.050 as well — but only because the clean maximum jumped to 0.5312. With eight samples you can still separate them; with thousands of clean samples the tail keeps climbing and a fixed threshold starts producing false positives. Short text does not weaken the mark per token; it weakens your confidence, because the variance of a mean over 16 observations is enormous.

Entropy

Anthropic’s claim is that factual passages and code carry less watermark, because there is only one correct next token and the nudge is not applied. Temperature is a clean proxy: lower temperature means a peakier distribution means less room for the tournament.

for t in (0.3, 0.7, 1.0):
    ids = generate_at_temperature(t, watermark=True)
    print(f"temperature {t}  mean g = {np.mean(watermark_score(ids)[0]):.4f}")
temperature 0.3  watermarked mean g = 0.5260
temperature 0.7  watermarked mean g = 0.5990
temperature 1.0  watermarked mean g = 0.6244

At temperature 0.3 the signal has collapsed from 0.60 to 0.53 — roughly half the margin, on identical prompts with an identical key. That is the mechanism behind the code caveat. A model writing for i in range( has essentially no free choice, so there is nothing for the watermark to ride on. Anthropic’s note that watermarking survives mostly in code comments is exactly this effect.

Editing

Replace a fraction of tokens at random and rescore. Random replacement is harsher than real editing, so treat these as a lower bound on survival:

for frac in (0.05, 0.10, 0.25, 0.50):
    edited = watermarked.clone()
    B, T = edited.shape
    k = int(T * frac)
    for b in range(B):
        idx = torch.randperm(T)[:k]
        edited[b, idx] = torch.randint(0, model.config.vocab_size, (k,))
    print(f"{int(frac*100):2d}% replaced -> mean g {np.mean(watermark_score(edited)[0]):.4f}")
 5% replaced -> mean g 0.5605
10% replaced -> mean g 0.5414
25% replaced -> mean g 0.5152
50% replaced -> mean g 0.5039

The decay is steeper than a linear read would suggest, and the reason is ngram_len=5. Changing one token invalidates the g-value at that position and at the four positions that used it as context. A 10% edit therefore damages closer to 40% of the observations. At 50% replacement the score is 0.5039 — statistically indistinguishable from never-watermarked text.

This is the honest answer to “can you just paraphrase it away?” Yes, if you rewrite enough of it. Anthropic says the same thing in plainer words: a complete rewrite removes the watermark, at which point it is fair to ask whether the text is still AI-generated.


Step 7 — Turning a score into a decision

A raw mean g-value is not a verdict. Two things convert it into one.

Calibrate empirically, per length bucket. Generate a few thousand unwatermarked samples from the same model at each length you care about, take the empirical quantile at your target false positive rate, and use that as your threshold. DeepMind’s reference implementation recommends exactly this for the mean detector rather than any closed-form threshold.

# Threshold at a 1% false positive rate, for one length bucket.
clean_scores = np.array([...])            # >= 2000 unwatermarked samples, same length
threshold = np.quantile(clean_scores, 0.99)

def verdict(score, n_ngrams, threshold, min_ngrams=80):
    if n_ngrams < min_ngrams:
        return "inconclusive"             # not enough evidence, do not guess
    return "watermarked" if score > threshold else "not detected"

Use three outcomes, never two. Watermarked, not detected, inconclusive. “Not detected” is not “human-written” — it also covers a different model, a different key, a heavy edit, or a passage too factual to mark. Anthropic is explicit that its key answers exactly one question: how likely is it that Claude was involved. It cannot tell you the text is human, and it cannot tell you which human.

For production you would swap the mean detector for the Bayesian one. Transformers ships BayesianDetectorModel and SynthIDTextWatermarkDetector for this, with a training example under examples/research_projects/synthid_text/. It needs roughly 10k labelled examples per watermark configuration and is materially more sensitive on short text. The mean detector is what you use to understand and audit the mechanism; the Bayesian detector is what you deploy.


Pitfalls

  • Scoring the prompt. Prompt tokens were never tournament-selected. Include them and you are averaging signal with pure noise. Always slice from input_ids.shape[1].
  • Mismatched parameters. The detection processor and the generation config must agree on keys, ngram_len, sampling_table_size and sampling_table_seed. One wrong key and every score collapses to 0.5, which looks exactly like “no watermark”.
  • Chasing 0.75. expected_mean_g_value() assumes a uniform distribution and a single layer. Measured values of 0.55–0.65 on real text are normal. Calibrate against your own clean baseline, not against theory.
  • Skipping the repetition mask. A model that loops repeats contexts, which repeats g-values. Without the mask a degenerate repetitive generation scores higher than a good one.
  • Right-padding a batch. padding_side must be "left" for decoder-only generation. Right padding silently corrupts both the generations and the n-gram alignment.
  • Greedy decoding. do_sample=False means no randomness to redirect, so no watermark. Beam search has the same problem.
  • Publishing your keys. The key is symmetric. Anyone holding it can forge a watermark as easily as detect one, which makes a leaked key worse than no watermark — you now have false positives you cannot distinguish from real ones.
  • Treating a hit as proof. A detected watermark means the key-holder’s model likely touched the text. It does not establish authorship, ownership, or intent.

Quick reference

ItemValue / behaviour
Generation configSynthIDTextWatermarkingConfig(keys, ngram_len) → generate(watermarking_config=...)
DetectionSynthIDTextWatermarkLogitsProcessor + compute_g_values
keys20–30 random ints; length = tournament depth; secret
ngram_lenDefault 5, minimum 2; higher = more detectable, more edit-fragile
Clean baseline~0.500 mean g (measured 0.4987)
Watermarked, temp 0.7~0.58–0.60 mean g (measured 0.5833)
Theoretical max0.750 — uniform dist, single layer; not a real target
Temp 0.3 vs 1.00.5260 vs 0.6244 — low entropy halves the margin
10% tokens edited0.5414 (from 0.5833)
50% tokens edited0.5039 — effectively erased
Requires samplingYes — do_sample=True; greedy and beam produce no mark
Extra tokens / costNone
Trained detectorBayesianDetectorModel, ~10k labelled examples per config

Next steps

  • Swap gpt2 for gemma-2-2b-it or any instruct model and rerun Step 5 — instruction-tuned models produce lower-entropy text, and the margin narrows in a way that is worth seeing yourself.
  • Build the calibration set properly: 2,000 clean samples per length bucket, then plot the ROC curve. That is the difference between a demo and a detector.
  • Train the Bayesian detector from examples/research_projects/synthid_text/detector_training.py and compare its sensitivity on 20-token samples against the mean scorer.
  • Replace random token replacement with real paraphrasing — run the watermarked text back through a second model and rescore. Real paraphrase is the attack that matters, and the numbers are different.
  • Read the Nature paper (Dathathri et al., 2024, doi:10.1038/s41586-024-08025-4) for the weighted-mean and Bayesian scoring functions and the threshold analysis in Appendix A.3.1.
  • Watch for Anthropic’s detection API. When it ships, the interesting test is whether its answers agree with what this kind of scorer predicts on short, factual, and lightly-edited text.

Watermarking is now a compliance requirement rather than a research curiosity, and roughly 190 signatories to the EU Code of Practice means the rest of the industry is shipping their own. Knowing what the signal is made of — and precisely where it evaporates — is going to be a more useful skill than having an opinion about it.

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,605 newsletter subscribers.

Also get