
textGrain Watermark: Build and Break One in Python
Summary
Build a toy keyed text watermark like OpenAI's textGrain, then measure how edits break it.
On October 5, 2026 OpenAI announced that API customers can opt in to an invisible watermark on model text, and that ChatGPT and Codex text will carry one in the EU over the coming weeks. OpenAI calls the method textGrain. It changes no characters. It nudges which words the model picks, in a way only someone holding a secret key can measure.
The detector is not public. OpenAI is giving access to approved researchers and expert organizations case by case, and the API switch is a setting rather than a request parameter. So you cannot call textGrain from Python today. What you can do is understand the mechanism well enough to reason about it: why 400 tokens detect at about 95% but 200 tokens only about 80%, why 25% word replacement nearly erases it, and why math and non-English text are harder.
In this guide you build a small keyed watermark from scratch with numpy, using the Gumbel-max trick, then attack it and measure the damage. It is not OpenAI's algorithm. Per reporting, textGrain splits the vocabulary into blocks and uses an optimal-transport step; the toy here uses the simpler keyed Gumbel-max idea that the same reporting names as the family textGrain improves on. Treat every number below as a property of the toy, and use the comparison against OpenAI's published figures as a sanity check on the shape of the curves.
What you will be able to do
- Explain how a statistical text watermark hides a signal in word choice and how a key-holder detects it.
- Generate watermarked and plain text from a small language model and score both with a z-test.
- Calibrate a detection threshold to a 1% false positive rate empirically, instead of trusting the theory.
- Measure detection against text length, word-swap attacks, and token entropy.
- Read OpenAI's textGrain claims critically and decide what a detector result can and cannot prove.
Prerequisites
- Python 3.10+ and
numpy(pip install numpy). No GPU, no model downloads, no API key. - Comfort with probability distributions and sampling from them. You do not need cryptography.
- About 20 minutes. The experiments run in under a minute on a laptop.
How a statistical watermark works
A language model produces a probability distribution over the next token and then samples from it. Sampling uses randomness. A watermark replaces that randomness with pseudo-randomness derived from a secret key and the preceding words. To a reader the text looks like ordinary sampling. To a detector that knows the key, the chosen words are slightly too lucky: they land on high pseudo-random values more often than chance allows.
The classic recipe is Gumbel-max sampling. For each candidate token i with probability p_i, derive a keyed uniform value u_i from the key and the previous few tokens, then pick argmax u_i^(1/p_i). Averaged over keys this picks token i with exactly probability p_i, so output quality is unchanged on average. For one fixed key it is deterministic.
Detection reverses it. For every position, recompute u for the token that actually appeared and sum -ln(1-u). Without a watermark each term is Exponential(1), so the sum over n tokens is Gamma(n,1), roughly normal. A watermarked text has too many large u values, so the z-score jumps.
This also explains OpenAI's own caveat that a short passage can fail: with 30 tokens there is simply not enough evidence, and the z-score has a wide spread.
Step 1: A tiny language model and the keyed sampler
We need a model whose next-token distribution we control. Instead of downloading weights we generate a synthetic corpus from templates and fit a bigram table. It is crude, but it has real structure (subjects, verbs, adjectives) and every step of the watermark code is identical to what you would write around a real model's logits. Save this as wm.py.
"""Toy keyed text watermark (Gumbel-max / Aaronson style) on a bigram LM.
Educational stand-in for the *idea* behind OpenAI's textGrain; NOT its algorithm."""
import hashlib, numpy as np
KEY = b"demo-secret-key"
CTX = 2 # watermark depends on previous 2 tokens
rng0 = np.random.default_rng(7)
# ---- 1. a small synthetic corpus + bigram LM (no downloads) ----
topics = {
"subj": "the model|a researcher|our team|the agent|a student|the engineer|an analyst|the system|a developer|the lab".split("|"),
"verb": "trains|tests|ships|reviews|audits|improves|measures|compares|debugs|explains|builds|checks".split("|"),
"adj": "small|fast|robust|noisy|careful|large|simple|reliable|flaky|open|private|public".split("|"),
"obj": "dataset|pipeline|benchmark|prompt|detector|agent|policy|report|tokenizer|index|filter|result".split("|"),
"adv": "quickly|slowly|twice|again|carefully|today|early|often|rarely|openly".split("|"),
"conj": "and then|because|while|but|so|although".split("|"),
}
def sentence(r):
s = f"{r.choice(topics['subj'])} {r.choice(topics['verb'])} the {r.choice(topics['adj'])} {r.choice(topics['obj'])} {r.choice(topics['adv'])}"
if r.random() < .6:
s += f" {r.choice(topics['conj'])} {r.choice(topics['subj'])} {r.choice(topics['verb'])} the {r.choice(topics['obj'])}"
return s + " ."
r = np.random.default_rng(1)
corpus = " ".join(sentence(r) for _ in range(4000)).split()
vocab = sorted(set(corpus)); idx = {w: i for i, w in enumerate(vocab)}; V = len(vocab)
counts = np.ones((V, V)) * 0.01
for a, b in zip(corpus, corpus[1:]): counts[idx[a], idx[b]] += 1
P = counts / counts.sum(1, keepdims=True) # P[prev] -> next-token distribution
# ---- 2. keyed pseudo-random values u in (0,1) per (context, candidate token) ----
def u_vec(ctx_ids):
"""Return V uniform values derived from KEY + previous CTX token ids."""
seed = hashlib.sha256(KEY + bytes(str(tuple(ctx_ids)), "utf8")).digest()
g = np.random.default_rng(int.from_bytes(seed[:8], "big"))
return g.random(V) * (1 - 2e-9) + 1e-9
def generate(n, watermark, seed, start="the", warm=0):
"""warm = number of leading tokens sampled WITHOUT watermark, so outputs differ per seed."""
g = np.random.default_rng(seed)
out = [idx[start]]
for t in range(n - 1):
p = P[out[-1]]
if watermark and t >= warm:
u = u_vec(out[-CTX:])
nxt = int(np.argmax(u ** (1.0 / p))) # Gumbel-max trick: argmax u^(1/p) ~ p
else:
nxt = int(g.choice(V, p=p))
out.append(nxt)
return out
# ---- 3. detection: sum of -ln(1-u_chosen) ~ Gamma(n,1) under H0 ----
def score(ids):
s = 0.0; n = 0
for i in range(CTX, len(ids)):
u = u_vec(ids[i-CTX:i])[ids[i]]
s += -np.log(1 - u); n += 1
z = (s - n) / np.sqrt(n) # normal approx of Gamma(n,1)
return z, n
if __name__ == "__main__":
wm = generate(60, True, 0); pl = generate(60, False, 0)
print("WATERMARKED:", " ".join(vocab[i] for i in wm[:25]), "...")
print("PLAIN :", " ".join(vocab[i] for i in pl[:25]), "...")
print("z(watermarked) = %.2f z(plain) = %.2f" % (score(wm)[0], score(pl)[0]))
Two design choices matter. First, CTX = 2 means the key stream depends on the previous two tokens, so identical phrases in different places get different values. Second, warm lets the first few tokens be sampled normally. Without it, a fixed key and a fixed start give the same sentence every time, which is the identical-outputs problem that reporting says textGrain was designed to avoid.
Step 2: See it work
Run python wm.py. It generates 60 tokens each way and scores both. Output from my run:
WATERMARKED: the lab builds the large result quickly so the careful detector openly . a student trains the reliable detector . our team reviews the flaky ...
PLAIN : the policy . a developer ships the open report early while the agent tests the public dataset slowly and then our team builds the policy ...
z(watermarked) = 8.49 z(plain) = -1.19
A z-score of 8.5 against -1.2. Under the null hypothesis the z-score sits near zero with standard deviation about one, so 8.5 is not subtle. Read the two samples again, though. Nothing about the watermarked sentence looks odd. That is the point, and also the reason a human cannot be the detector.
Step 3: Calibrate the threshold empirically
A z-test with a normal approximation is fine for a first look, but the exact false positive rate depends on your tokenizer, your repeated phrases and your context window. OpenAI says the same about its detector: the theoretical rate assumes independent words, so a deployed key must be calibrated empirically. We do that directly: score 300 plain texts, take the 99th percentile as the threshold, and call anything above it watermarked. That fixes the false positive rate at 1% on texts like yours.
Save this as exp.py. It sweeps text length and the fraction of words swapped for another word of the same grammatical slot, a stand-in for synonym replacement.
import numpy as np
from wm import *
# category map for "synonym-like" swaps: replace a word with another word of the same slot
groups = [set(v) for k, v in topics.items() if k != "conj"]
groups = [set(w for w in g if " " not in w) for g in groups]
cat = {w: g for g in groups for w in g}
def attack(ids, frac, seed):
g = np.random.default_rng(seed); ids = list(ids)
for i in range(len(ids)):
w = vocab[ids[i]]
if w in cat and g.random() < frac:
ids[i] = idx[g.choice(sorted(cat[w]))]
return ids
N = 300
def zs(n, watermark, frac=0.0, base=0):
out = []
for s in range(N):
ids = generate(n, watermark, base + s, start=vocab[(base+s) % V], warm=3)
if frac: ids = attack(ids, frac, 10_000 + s)
out.append(score(ids)[0])
return np.array(out)
print("length | thr(1%FPR) | detect@0% | @10% | @25% | @50% swapped")
for n in (30, 60, 120, 240):
null = zs(n, False, base=50_000)
thr = np.quantile(null, 0.99)
row = [(zs(n, True, f, base=0) > thr).mean() for f in (0, .10, .25, .50)]
print(f"{n:6d} | {thr:9.2f} | " + " | ".join(f"{x*100:5.0f}%" for x in row))
Output:
length | thr(1%FPR) | detect@0% | @10% | @25% | @50% swapped
30 | 2.35 | 100% | 100% | 86% | 41%
60 | 2.56 | 100% | 100% | 98% | 59%
120 | 2.43 | 100% | 100% | 100% | 94%
240 | 2.04 | 100% | 100% | 100% | 100%
| Tokens | Threshold z (1% FPR) | No edits | 10% swapped | 25% swapped | 50% swapped |
|---|---|---|---|---|---|
| 30 | 2.35 | 100% | 100% | 86% | 41% |
| 60 | 2.56 | 100% | 100% | 98% | 59% |
| 120 | 2.43 | 100% | 100% | 100% | 94% |
| 240 | 2.04 | 100% | 100% | 100% | 100% |
Notice the shape. Longer text survives heavier editing, and detection falls off a cliff only when a large share of words change. OpenAI reports the same shape for textGrain, only harsher: at 400 tokens, 10% synonym replacement drops detection from about 92% to 66%, and 25% leaves 17%. Our toy is far more resilient. That gap is the first lesson, and the next step shows why.
Step 4: Why the toy is too optimistic, and what entropy does
Every sentence slot in our toy model offers a dozen roughly equal choices, so each token carries plenty of freedom for the watermark to bend. Real text is different. Code, math and boilerplate have one obviously correct next token. When the distribution is peaked, Gumbel-max picks the likely token whatever the key says, and no signal is written. OpenAI states that math detection is substantially lower for this reason, and that text under 200 tokens is exempt under the code of practice.
We can test that by sharpening the model's distribution (raising probabilities to a power and renormalizing, the same effect as lowering the sampling temperature). Save as exp2.py:
import numpy as np
import wm
from wm import *
def run(power, n=60):
Q = wm.P ** power; Q /= Q.sum(1, keepdims=True); wm.P[:] = Q
H = -(Q * np.log2(Q + 1e-12)).sum(1).mean()
def zs(w, base):
return np.array([score(generate(n, w, base+s, start=vocab[(base+s)%V], warm=3))[0] for s in range(300)])
thr = np.quantile(zs(False, 50_000), .99)
return H, (zs(True, 0) > thr).mean()
base = wm.P.copy()
for pw in (1.0, 8.0, 20.0, 50.0):
wm.P[:] = base
H, d = run(pw)
print(f"sharpen^{pw:<3} avg entropy {H:4.2f} bits/token -> detected {d*100:3.0f}% at 60 tokens")
sharpen^1.0 avg entropy 2.34 bits/token -> detected 100% at 60 tokens
sharpen^8.0 avg entropy 0.95 bits/token -> detected 100% at 60 tokens
sharpen^20.0 avg entropy 0.54 bits/token -> detected 0% at 60 tokens
sharpen^50.0 avg entropy 0.21 bits/token -> detected 0% at 60 tokens
Detection holds at 100% while average entropy is about one bit per token, then collapses to 0% below roughly half a bit. In this toy the cliff sits between 0.95 and 0.54 bits per token at 60 tokens. A real model on a coding task spends most of its tokens in that low-entropy regime, which is why a watermark detector tells you little about generated code and why text length matters so much: you can make up for low entropy per token only by observing more tokens.
A worked example: should this verdict hold up?
Suppose a university integrity office receives an essay and a researcher with detector access reports a watermark. Here is how to read that report using what you just measured.
- Length. A 120-token excerpt gives far weaker evidence than a 600-token essay. Ask for the token count and the score, not just a yes.
- Direction of error. A detected watermark is strong evidence the text, or a large part of it, came from a watermarked OpenAI model. OpenAI itself says a missing watermark proves nothing: short, edited, translated or other-vendor text may not show it.
- What it does not say. It does not identify the user, measure human contribution, or establish who is responsible. A student who wrote half the essay and pasted in half has a mixed document.
- Threshold honesty. Ask what false positive rate the threshold targets and whether it was calibrated on text like the essay. In our runs the 1% threshold moved between z=2.04 and z=2.56 across lengths.
Common pitfalls
- Trusting the normal approximation. For short texts the Gamma-to-normal step is rough. Calibrate empirically on your own plain text, as in Step 3.
- Reusing one key and one prompt. Gumbel-max with a fixed key is deterministic. Identical prompts yield identical completions, which is both a quality problem and a fingerprint. Vary the prefix or the context hash.
- Letting repeated n-grams inflate scores. If the same two-token context appears ten times, it contributes ten correlated terms. Production detectors deduplicate contexts. Ours does not, so repetitive text scores high even when it is unmarked.
- Forgetting the tokenizer. Watermark and detector must tokenize identically. Reformatting, adding spaces or changing normalization before detection silently breaks the context hash.
- Reading 'no watermark' as 'human'. OpenAI's own page rules this out. Short, edited, translated and other-vendor text all come back negative.
- Assuming synonym swaps are the only attack. Reporting notes that heavy paraphrasing or translation can erase the signal, and a swapped word can change a fact or figure. We only tested same-slot swaps.
- Expecting quality to be free. OpenAI reports no meaningful difference on its benchmarks, with DeepSWE v1.1 moving from 72.80% to 71.68%. Sampling-level watermarks are quality-neutral in expectation, not in every single run.
One more caveat about this very guide: details such as the Text provenance setting under Data controls come from press coverage of the announcement, and OpenAI's own page only says 'select models'. Check the official docs before you build a compliance workflow on it.
Quick reference
| Concept | What it means here | Number to remember |
|---|---|---|
| Gumbel-max sampling | Pick argmax of u^(1/p) with keyed u | Exact in expectation, deterministic per key |
| Score | Sum of -ln(1-u) over observed tokens | Gamma(n,1) under no watermark |
| Threshold | 99th percentile of plain-text scores | 1% false positive rate |
| OpenAI: 200 tokens | Detected at 1% FPR target | about 80% |
| OpenAI: 400 tokens | Detected at 1% FPR target | about 95% |
| OpenAI: 10% / 25% words swapped | 400-token passage | 92% to 66% / down to 17% |
| Toy entropy cliff | Detection at 60 tokens | 100% at 0.95 bits, 0% at 0.54 bits |
| API access | Opt-in, off by default, select models | Detector limited to approved researchers |
OpenAI's figures come from its provenance post and the reporting around it; the toy numbers come from the scripts above on a numpy 2.x install with the fixed seeds shown.
Next steps
- Swap the bigram table for a real model: take its next-token logits, convert to probabilities, and use the same
argmax u**(1/p)rule. Everything else inwm.pycarries over. - Add context deduplication to
score()and measure how much it lowers false positives on repetitive text. - Try attacks beyond same-slot swaps: random deletions, sentence reordering, and round-trip translation with a second model.
- Implement a green-list watermark (Kirchenbauer et al.) and compare its detection-versus-length curve with Gumbel-max on the same corpus.
- Watch for OpenAI's open-source release and technical report, which they say will arrive in the coming weeks, and compare the real algorithm with this toy.
Sources
- OpenAI, Our approach to EU text provenance: https://openai.com/index/eu-text-provenance/
- TechCrunch, OpenAI will start watermarking ChatGPT's text in the EU (Oct 5, 2026): https://techcrunch.com/2026/10/05/openai-will-start-watermarking-chatgpts-text-in-the-eu/
- ActuIA, ChatGPT watermarking in the EU: textGrain, API and the AI Act: https://www.actuia.com/en/news/openai-will-watermark-chatgpt-in-the-eu-but-leaves-the-api-opt-in/
- The Register, OpenAI rolls out weak sauce watermarking for AI text (Oct 6, 2026): https://www.theregister.com/ai-and-ml/2026/10/06/openai-rolls-out-weak-sauce-watermarking-for-ai-text/5301257
- Last Week in AI #346 (Oct 9, 2026): https://lastweekin.ai/p/last-week-in-ai-346-719-math-manuscripts
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,605 newsletter subscribers.