Algorithmresearch
Green list watermark for language models
Also called Kirchenbauer watermark, LLM output watermarking.
Biases generation toward a pseudorandom green list of tokens seeded by the previous token, and detects the watermark by a z-test on green counts.
- Time
- O(T V) detectO(T (c + V)) generate
- Space
- O(V + T) extra
- Where
- T = the number of tokens; V = the vocabulary size; c = the cost of one call of the language model
- Model
- Real RAM
- Properties
- randomizednot exactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- John Kirchenbauer, Jonas Geiping, Yuxin Wen, Jonathan Katz, Ian Miers, Tom Goldstein, 2023
The green list watermark of Kirchenbauer et al. (2023) marks the text that a language model generates, so that a detector with a secret key can later tell, with a known false-positive rate, whether a text came from the marked model. Before each token is drawn, a hash of the key and the previous token splits the vocabulary into a green list of tokens and a red list of the others, and the logits of the green tokens get a bonus . Plain text has about a fraction of green tokens, and marked text has more. The detector counts the green tokens among scored tokens and computes the z-score . It needs the key, but not the model and not the prompt.
Threat model. The watermark is a defense for provenance. The adversary wants to remove the mark from a marked text (so it is not detected) or to put the mark on a text that the model did not write (so it is wrongly detected). The adversary does not know the key but can read marked texts. The capability is to edit tokens of a text, by insertion, deletion or substitution. The guarantee against false accusation is a theorem; the robustness against edits is a bound for a given number of edits, and a heuristic for paraphrase.
In plain words
Think of the vocabulary as a deck of cards. Before each word, a secret key and the previous word shuffle the deck, and a quarter of the cards are painted green. The model is gently pushed to pick a green word, but it can still pick any word.
A person who writes text without the key picks green words about a quarter of the time, by chance. Text from the marked model has many more green words. A checker with the key repaints the cards for each position, counts the green words and asks how surprising the count is. A count far above a quarter is strong evidence of the mark.
The mark is weak when the model has almost no choice, for example in a fixed phrase, because then the push changes nothing.
The problem
Given a language model over a vocabulary , generate text whose distribution is close to , such that a detector with a key flags generated texts of enough length and enough entropy, and flags a text that does not depend on with probability at most a chosen small number. The detector sees only the tokens , where is the last token of the prompt.
The algorithm
GENERATE(p, s_0, T, gamma, delta, k)- 1
for t ← 1 to T do - 2
z ← the logits of p for the next token after s_0, ..., s_{t-1} - 3
G ← GREEN-LIST(k, s_{t-1}, gamma) - 4
for each v ∈ G do z[v] ← z[v] + delta - 5
s_t ← a draw from softmax(z) - 6
return s_1, ..., s_T GREEN-LIST(k, u, gamma)- 7
r ← a generator seeded with H(k, u) ▷ H is a keyed hash - 8
return ⌊gamma |V|⌋ tokens of V drawn by r without replacement DETECT(s_0, ..., s_T, gamma, k, z*)- 9
count ← 0, scored ← 0, seen ← ∅ - 10
for t ← 1 to T do - 11
if (s_{t-1}, s_t) ∈ seen then continue ▷ score each pair once - 12
seen ← seen ∪ {(s_{t-1}, s_t)}, scored ← scored + 1 - 13
if s_t ∈ GREEN-LIST(k, s_{t-1}, gamma) then count ← count + 1 - 14
z ← (count - gamma' · scored) / sqrt(scored · gamma' (1 - gamma')) ▷ gamma' = ⌊gamma |V|⌋ / |V| - 15
return (z, z > z*)
GENERATE is Algorithm 2 of the paper, the soft red list. Line L2 asks the model for its logits. Lines L3 and L4 raise the logits of the green tokens by , which multiplies their probabilities by before the softmax normalizes them again. Line L5 draws the token as usual, so the model can still pick a red token when it is very sure of it. Lines L7 and L8 make the green list a function of the key and the previous token only, so the detector can rebuild it from the text.
DETECT does not call the model. Lines L11 and L12 skip a pair (previous token, token) that was already scored: a repeated pair has the same green status every time, so counting it again would add no evidence and would break the independence that the z-test needs. Line L14 is the one-proportion z-test against the green fraction of plain text.
Example
Take a toy bigram model over integer tokens, with logits drawn from by a fixed seed, (16 green tokens per context) and . After the token 0, the green mass of the model is . Line L4 raises it to .
A marked text of 12 tokens after has 11 green tokens. Plain text would have about 3, and line L14 gives , above the threshold .
The table is a measurement on this toy model: 20 texts of tokens for each , all with the same key.
| mean green fraction | mean | smallest | |
|---|---|---|---|
| 0 (no mark) | 0.246 | -0.13 | -1.44 |
| 1 | 0.466 | 6.78 | 5.00 |
| 2 | 0.671 | 13.05 | 11.35 |
| 4 | 0.938 | 20.68 | 19.92 |
The z-score grows like for a fixed green fraction: with half of the tokens green, at , at , at and at . So short texts cannot be flagged with confidence.
Correctness
Theorem (false positives). Model as a random function, so the green lists of different previous tokens are independent, uniformly random sets of size . Let the text not depend on the key. Then DETECT returns true with probability at most for every threshold .
Lemma (the bonus helps). If the green mass of the model at a step is , the green mass after line L4 is , with equality only for .
Lemma (edits). Changing tokens of a text lowers the count of line L13 by at most .
The theorem is proved by grouping the scored pairs by the previous token. Within a group the scored tokens are distinct, so their green indicators are a sample without replacement from the vocabulary; across groups they are independent. Hoeffding showed that a sum of draws without replacement satisfies the same tail bound as independent draws, so for scored pairs; the choice gives the bound. For and the bound is , a theorem. The paper gives , the one-sided normal tail at 4, which is the right value for large by the central limit theorem but not a finite-sample guarantee. The edit lemma holds because a token at position enters only the pairs at positions and . The full proof is in proofs/correctness.md.
The power of the test is a separate theorem of the paper (Theorem 4.2): if the average spike entropy of the steps is at least , with , then the expected number of green tokens is at least . Low entropy gives a weak mark.
Proof: The green list detector has a bounded false-positive rate, the bonus never lowers the green mass, and edits lower the count by at most two eachfull
Let be the vocabulary, with , and . For a previous token , let be the green list of lines L7 and L8. We model the keyed hash as a random function: the sets for different are independent, and each is uniformly random among the subsets of of size . A text does not depend on the key if it is fixed before the key is drawn, or drawn independently of it.
For a text , let be the set of distinct pairs with . Lines L9 to L13 set and , because line L11 skips a pair exactly when it is already in the set , and line L12 adds each new pair once.
Lemma 1 (Hoeffding). Let be a sample without replacement from a finite list of numbers in with mean , and let be independent draws with replacement from the same list. Then for every real .
Hoeffding (1963) proved this comparison for every continuous convex function in place of . We use it without proof.
Lemma 2 (Hoeffding's lemma). If takes values in with mean , then for every real .
This is the standard lemma behind Hoeffding's inequality. We use it without proof.
Theorem 1 (false positives). Let not depend on the key, let , and let . Then , where is the value of line L14. If , then and DETECT returns false.
Proof. The set is fixed, because does not depend on the key. Group its pairs by the first token: for each , let be the distinct tokens with , so . Let , so .
Fix . Since is a uniform subset of size , the green status of the distinct tokens has the same distribution as draws without replacement from a list of numbers, of them equal to 1 and the rest equal to 0: label the tokens of by ; by symmetry this labeling is a uniform random arrangement of the list, and reading it at fixed distinct places is a sample without replacement. The list has mean . By Lemma 1 and then Lemma 2, for every ,
,
where the are independent Bernoulli variables with mean .
The variables for different are functions of different, independent sets , so they are independent, and
.
By Markov's inequality, for , , and the choice gives .
Line L14 gives exactly when . Take . Then . If , the code returns , and is false.
Lemma 3 (the bonus helps). Let a step have the distribution and let . After line L4 the green mass is . If , then , and if the equality holds only for .
Proof. Adding to the logit of a token multiplies its unnormalized weight by . With , the green weight becomes and the red weight stays , so . Let . Then , since the denominator is at least . For the numerator is zero exactly when or .
Theorem 2 (edits). Let be the text with the tokens at positions changed, with the same key. Then .
Proof. The pair at position is , so it changes only if or is an edited position. Let , a set of at most positions. For , the pair of at position is the same as the pair of at position . So every pair of that occurs in at some position outside is also in , and holds only pairs that occur in only at positions in ; there are at most such pairs. The green status of a pair depends only on , which is the same for both texts, so the green pairs of that are lost number at most , and new pairs can only add to the count. Hence .
Complexity
- Generation. One call of the model per token, as without the mark, plus for the hash, the green list and the bonus: . The green list of tokens costs with a partial shuffle.
- Detection. time, or hash calls if the test of line L13 asks the generator only whether is green. It needs no model and no GPU.
- Space. , for the logits, one green list and the set of seen pairs.
Properties
- Keyed detection. Without the key, the green lists look random, so a reader cannot see the mark by counting. With the key, the test is a plain z-test.
- Bounded false positives. For a text that does not depend on the key, the false-positive rate is at most (the theorem). This covers human text, under the model of as a random function.
- Quality cost. The mark changes the output distribution. A larger gives a stronger mark and a larger change, which can lower quality. It is not distortion-free.
- Entropy dependence. The mark is strong only where the model has a real choice. Code, lists and fixed phrases carry a weak mark (the lemma and Theorem 4.2).
- Local robustness. Each edit lowers the count by at most 2, so many edits are needed to remove the mark from a long text. Paraphrase by another model can still remove it, a heuristic limit found in later work.
- Context width. A green list seeded by only one previous token can be learned by an adversary who sees many marked texts and counts which pairs are frequent; a wider context makes this harder but makes edits hurt more.
Variants and improvements
- Hard red list. Algorithm 1 of the paper forbids red tokens completely. The mark is stronger, but low-entropy text suffers, because the best token may be red.
- Wider or private context. The paper also seeds the green list with more than one previous token, and with a pseudorandom function of the key, to make the lists harder to learn.
- Undetectable watermarks. Christ, Gunn and Zamir (2024) use a pseudorandom function to embed the mark so that, without the key, no efficient test can tell marked text from unmarked text; the output distribution is unchanged in that computational sense.
- Distortion-free sampling. Other schemes replace the bonus by a keyed choice of the random numbers of line L5, so each token has the model's own distribution, and detect by the correlation of the tokens with those numbers.
- Unique scoring. Lines L11 and L12 follow the later advice of the paper to not count repeated n-grams. Without them, a text that repeats a green pair many times gets a z-score far too high.
When to use it
Use it when the provider of a model wants to detect its own output later, for example to label generated text or to filter it from future training data, and can keep a key secret. It needs control of the sampling step, so it does not apply to models that others run. Do not use it as proof of authorship of short or low-entropy texts, and do not treat a missing mark as proof that a human wrote a text, because edits and paraphrase can remove it.
Pitfalls
- Too short a text. At line L14 the z-score grows like , so a text of 25 tokens with half of them green gives only . Set a minimum length before flagging.
- Counting repeated pairs. If lines L11 and L12 are removed, a repeated phrase is counted many times and can give a large for human text. Score each pair once.
- Using when is not a whole number. Line L8 takes tokens, so line L14 must use ; otherwise the z-score is biased.
- The normal tail as a guarantee. The value at is the normal approximation. For a guaranteed rate, use the Hoeffding bound or an exact binomial tail.
- A weak hash at line L7. If the green list depends on a public or guessable seed, anyone can detect or forge the mark. The key must be secret, and should be a keyed function such as a message authentication code.
- Testing many keys or many windows. Each extra test raises the chance of a false alarm; the threshold must account for every test that is run.
Implementations
The code of this page is an abstract model on synthetic data. The language model is a seeded table of bigram logits over 64 integer tokens, built with mlkit.softmax, and there is no real text and no real model. The tests check that the green lists have the right size and depend on the key, the z-score values, that marked texts of 200 tokens are flagged, that plain texts and a wrong key are not flagged, that the false-positive rate over 600 random keys stays under the Hoeffding bound, that repeated pairs are scored once, that the bonus never lowers the green mass, that peaked models carry a weaker mark, that the mean green mass meets the spike entropy bound of Theorem 4.2, and that 20 edits lower the count by at most 40.
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/language-model-watermarking/. The authors are listed in prov/635TD2.jsonl.
"""The green list watermark of Kirchenbauer et al. (2023) on a toy language model.
Before each token is drawn, a key and the previous token seed a pseudorandom split of
the vocabulary, and the logits of the green part get a bonus delta. The detector,
which knows the key, counts green tokens and computes the one-proportion z-score
z = (count - gamma T) / sqrt(T gamma (1 - gamma)).
The detector here scores each pair (previous token, token) only once, as the later
versions of the paper advise. Repeated pairs have the same green status, so counting
them again would break the independence that the false-positive bound needs.
The language model is a seeded table of bigram logits over a vocabulary of integers.
There is no real text and no real model here.
"""
import hashlib
import math
import random
from typing import Sequence
import mlkit
Model = list[list[float]]
def toy_bigram_model(rng: random.Random, vocab_size: int, spread: float) -> Model:
"""A seeded table of next-token logits: row u holds the logits after token u.
The logits are drawn from N(0, spread^2). A large spread gives peaked, low-entropy
rows; spread 0 gives the uniform distribution.
"""
return [[rng.gauss(0.0, spread) for _ in range(vocab_size)] for _ in range(vocab_size)]
def green_size(vocab_size: int, gamma: float) -> int:
"""The number of green tokens, floor(gamma |V|), at least 1 and at most |V| - 1."""
return min(max(int(gamma * vocab_size), 1), vocab_size - 1)
def green_list(key: bytes, prev: int, gamma: float, vocab_size: int) -> frozenset[int]:
"""The green tokens after the token prev, a pseudorandom set seeded by the key and prev."""
digest = hashlib.sha256(key + b"|" + str(prev).encode()).digest() # @line L7
r = random.Random(int.from_bytes(digest[:16], "big")) # @line L7
return frozenset(r.sample(range(vocab_size), green_size(vocab_size, gamma))) # @line L8
def draw(probs: Sequence[float], rng: random.Random) -> int:
"""A draw from a finite distribution by the inverse of its distribution function."""
u = rng.random()
acc = 0.0
for v, p in enumerate(probs):
acc += p
if u < acc:
return v
return len(probs) - 1
def generate(model: Model, start: int, length: int, gamma: float, delta: float, key: bytes,
rng: random.Random) -> list[int]:
"""length tokens after start, drawn with the green list bonus delta (delta = 0: no watermark)."""
vocab_size = len(model)
text = [start]
for _ in range(length): # @line L1
z = list(model[text[-1]]) # @line L2
green = green_list(key, text[-1], gamma, vocab_size) # @line L3
for v in green: # @line L4
z[v] += delta # @line L4
text.append(draw(mlkit.softmax(z), rng)) # @line L5
return text[1:] # @line L6
def z_score(count: int, scored: int, gamma_eff: float) -> float:
"""The one-proportion z-score of count green tokens among scored tokens."""
if scored == 0:
return 0.0
return (count - gamma_eff * scored) / math.sqrt(scored * gamma_eff * (1.0 - gamma_eff))
def green_count(tokens: Sequence[int], gamma: float, key: bytes, vocab_size: int) -> tuple[int, int]:
"""(green, scored) over the distinct pairs (tokens[t-1], tokens[t]) for t >= 1."""
count, scored, seen = 0, 0, set() # @line L9
for t in range(1, len(tokens)): # @line L10
pair = (tokens[t - 1], tokens[t])
if pair in seen: # @line L11
continue # @line L11
seen.add(pair) # @line L12
scored += 1 # @line L12
if tokens[t] in green_list(key, tokens[t - 1], gamma, vocab_size): # @line L13
count += 1 # @line L13
return count, scored
def detect(tokens: Sequence[int], gamma: float, key: bytes, vocab_size: int,
threshold: float) -> tuple[float, bool]:
"""(z, z > threshold) for the token list tokens[0], ..., tokens[T], where tokens[0] is the start.
Under the null hypothesis (the text does not depend on the key, and the green lists
behave like independent random sets), the false-positive rate is at most
exp(-2 threshold^2 gamma' (1 - gamma')), by Hoeffding's inequality.
"""
count, scored = green_count(tokens, gamma, key, vocab_size)
gamma_eff = green_size(vocab_size, gamma) / vocab_size
z = z_score(count, scored, gamma_eff) # @line L14
return z, z > threshold # @line L15
def false_positive_bound(threshold: float, gamma_eff: float) -> float:
"""Hoeffding's bound exp(-2 threshold^2 gamma' (1 - gamma')) on P(z > threshold) under the null."""
return math.exp(-2.0 * threshold * threshold * gamma_eff * (1.0 - gamma_eff))
def green_probability(probs: Sequence[float], green: frozenset[int], delta: float) -> tuple[float, float]:
"""(q, q') for one step: the green mass before and after the bonus delta.
q' = e^delta q / (e^delta q + 1 - q), which is at least q.
"""
q = math.fsum(probs[v] for v in green)
a = math.exp(delta)
return q, a * q / (a * q + 1.0 - q)
def spike_entropy(probs: Sequence[float], gamma: float, delta: float) -> float:
"""The spike entropy of Kirchenbauer et al.: the sum of p / (1 + z p) with z = (1 - gamma)(e^delta - 1) / (1 + (e^delta - 1) gamma)."""
a = math.exp(delta)
zc = (1.0 - gamma) * (a - 1.0) / (1.0 + (a - 1.0) * gamma)
return math.fsum(p / (1.0 + zc * p) for p in probs)
mlkit.py 252 lines
# SPDX-License-Identifier: MIT
# Shared helper of the security and privacy pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small vector tools, synthetic data and two tiny models for the adversarial machine learning pages.
Vectors are lists of floats. Every model here is synthetic: it is built from a seeded
random.Random and never from real data. The helper holds no attack loop, no
certification and no defense; those live in the slug files of the pages.
"""
import math
import random
from typing import Callable, Sequence
Vector = list[float]
Matrix = list[list[float]]
Net = dict[str, list]
Data = list[tuple[Vector, int]]
def dot(u: Sequence[float], v: Sequence[float]) -> float:
"""Inner product of two vectors of the same length. Cost O(d)."""
return math.fsum(a * b for a, b in zip(u, v, strict=True))
def add(u: Sequence[float], v: Sequence[float]) -> Vector:
"""Coordinatewise sum u + v. Cost O(d)."""
return [a + b for a, b in zip(u, v, strict=True)]
def sub(u: Sequence[float], v: Sequence[float]) -> Vector:
"""Coordinatewise difference u - v. Cost O(d)."""
return [a - b for a, b in zip(u, v, strict=True)]
def scale(c: float, v: Sequence[float]) -> Vector:
"""The vector c v. Cost O(d)."""
return [c * a for a in v]
def norm1(v: Sequence[float]) -> float:
"""The l1 norm, the sum of |v_i|. Cost O(d)."""
return math.fsum(abs(a) for a in v)
def norm2(v: Sequence[float]) -> float:
"""The Euclidean norm. Cost O(d)."""
return math.sqrt(math.fsum(a * a for a in v))
def norminf(v: Sequence[float]) -> float:
"""The l_infinity norm, max |v_i|, and 0 for the empty vector. Cost O(d)."""
return max((abs(a) for a in v), default=0.0)
def project_l2(v: Sequence[float], center: Sequence[float], radius: float) -> Vector:
"""Euclidean projection of v onto the l2 ball of the given center and radius >= 0.
A point inside the ball is returned unchanged; a point outside is moved along the
segment to the center until it is on the sphere. Cost O(d).
"""
diff = sub(v, center)
r = norm2(diff)
if r <= radius:
return list(v)
return add(center, scale(radius / r, diff))
def project_linf(v: Sequence[float], center: Sequence[float], radius: float) -> Vector:
"""Euclidean projection of v onto the l_infinity ball: clip each coordinate to [c_i - r, c_i + r]. Cost O(d)."""
return [min(max(a, c - radius), c + radius) for a, c in zip(v, center, strict=True)]
def clip01(v: Sequence[float]) -> Vector:
"""Euclidean projection onto the box [0, 1]^d. Cost O(d)."""
return [min(max(a, 0.0), 1.0) for a in v]
def make_blobs(rng: random.Random, n: int, d: int, centers: Sequence[Sequence[float]], sigma: float) -> Data:
"""n synthetic points in R^d from Gaussian blobs N(center, sigma^2 I).
Point i gets the label i mod len(centers) and is drawn around that center, so the
classes are balanced. The points are not clipped. Cost O(n d) and n d draws of rng.
"""
for c in centers:
if len(c) != d:
raise ValueError("each center must have d coordinates")
data: Data = []
for i in range(n):
label = i % len(centers)
x = [c + rng.gauss(0.0, sigma) for c in centers[label]]
data.append((x, label))
return data
def sigmoid(t: float) -> float:
"""The logistic function 1 / (1 + e^(-t)), computed without overflow. Cost O(1)."""
if t >= 0:
return 1.0 / (1.0 + math.exp(-t))
e = math.exp(t)
return e / (1.0 + e)
def _softplus(t: float) -> float:
"""ln(1 + e^t) without overflow."""
return max(t, 0.0) + math.log1p(math.exp(-abs(t)))
def logistic_loss(w: Sequence[float], b: float, x: Sequence[float], y: int) -> float:
"""Logistic loss of the linear model z = w.x + b on a label y in {0, 1}.
The loss is ln(1 + e^(-s z)) with s = 2 y - 1. Cost O(d).
"""
s = 2 * y - 1
return _softplus(-s * (dot(w, x) + b))
def grad_x_logistic(w: Sequence[float], b: float, x: Sequence[float], y: int) -> Vector:
"""Gradient of logistic_loss in the input x: (sigmoid(z) - y) w. Cost O(d)."""
g = sigmoid(dot(w, x) + b) - y
return scale(g, w)
def grad_w_logistic(w: Sequence[float], b: float, x: Sequence[float], y: int) -> tuple[Vector, float]:
"""Gradient of logistic_loss in the parameters: ((sigmoid(z) - y) x, sigmoid(z) - y). Cost O(d)."""
g = sigmoid(dot(w, x) + b) - y
return scale(g, x), g
def train_logistic(data: Data, steps: int, lr: float, l2: float) -> tuple[Vector, float]:
"""Full-batch gradient descent on the mean logistic loss plus (l2 / 2) ||w||^2.
Labels are in {0, 1}. The weights start at zero, so the result is deterministic.
The bias has no penalty. Returns (w, b). Cost O(steps n d).
"""
d = len(data[0][0])
n = len(data)
w = [0.0] * d
b = 0.0
for _ in range(steps):
gw = [0.0] * d
gb = 0.0
for x, y in data:
g = sigmoid(dot(w, x) + b) - y
for j in range(d):
gw[j] += g * x[j]
gb += g
w = [w[j] - lr * (gw[j] / n + l2 * w[j]) for j in range(d)]
b -= lr * gb / n
return w, b
def tiny_relu_net(rng: random.Random, d: int, h: int, k: int) -> Net:
"""A fixed-seed two-layer ReLU network with d inputs, h hidden units and k logits.
The weights are drawn from N(0, 1/d) in the first layer and N(0, 1/h) in the second,
and the biases from N(0, 0.01). The dict has the keys W1 (h rows of d), b1 (h),
W2 (k rows of h) and b2 (k). Cost O(h d + k h).
"""
s1, s2 = 1.0 / math.sqrt(d), 1.0 / math.sqrt(h)
return {
"W1": [[rng.gauss(0.0, s1) for _ in range(d)] for _ in range(h)],
"b1": [rng.gauss(0.0, 0.1) for _ in range(h)],
"W2": [[rng.gauss(0.0, s2) for _ in range(h)] for _ in range(k)],
"b2": [rng.gauss(0.0, 0.1) for _ in range(k)],
}
def _hidden(net: Net, x: Sequence[float]) -> tuple[Vector, Vector]:
"""Pre-activations and activations of the hidden layer."""
pre = [dot(row, x) + bi for row, bi in zip(net["W1"], net["b1"], strict=True)]
return pre, [max(a, 0.0) for a in pre]
def forward(net: Net, x: Sequence[float]) -> Vector:
"""Logits z(x) = W2 relu(W1 x + b1) + b2 of a tiny_relu_net. Cost O(h d + k h)."""
_, act = _hidden(net, x)
return [dot(row, act) + bi for row, bi in zip(net["W2"], net["b2"], strict=True)]
def argmax(z: Sequence[float]) -> int:
"""The first index of a largest entry. Cost O(k)."""
best = 0
for i in range(1, len(z)):
if z[i] > z[best]:
best = i
return best
def softmax(z: Sequence[float]) -> Vector:
"""The softmax of a logit vector, shifted by the maximum to avoid overflow. Cost O(k)."""
m = max(z)
e = [math.exp(a - m) for a in z]
s = math.fsum(e)
return [a / s for a in e]
def cross_entropy(z: Sequence[float], label: int) -> float:
"""Cross-entropy loss -ln softmax(z)[label], computed as logsumexp(z) - z[label]. Cost O(k)."""
m = max(z)
return m + math.log(math.fsum(math.exp(a - m) for a in z)) - z[label]
def logits_jacobian(net: Net, x: Sequence[float]) -> Matrix:
"""The k by d Jacobian of the logits in the input, W2 diag(relu'(pre)) W1.
The derivative of the ReLU is taken as 0 at a pre-activation of exactly 0.
Cost O(k h d).
"""
pre, _ = _hidden(net, x)
d = len(x)
rows = []
for w2 in net["W2"]:
row = [0.0] * d
for i, a in enumerate(pre):
if a > 0 and w2[i] != 0.0:
c = w2[i]
w1 = net["W1"][i]
for j in range(d):
row[j] += c * w1[j]
rows.append(row)
return rows
def input_gradient(net: Net, x: Sequence[float], label: int) -> Vector:
"""Gradient in x of cross_entropy(forward(net, x), label), by backpropagation.
The derivative of the ReLU is taken as 0 at a pre-activation of exactly 0.
Cost O(h d + k h).
"""
pre, act = _hidden(net, x)
z = [dot(row, act) + bi for row, bi in zip(net["W2"], net["b2"], strict=True)]
p = softmax(z)
p[label] -= 1.0
back = [0.0] * len(pre)
for c, row in zip(p, net["W2"], strict=True):
for i in range(len(pre)):
back[i] += c * row[i]
g = [0.0] * len(x)
for i, a in enumerate(pre):
if a > 0:
w1 = net["W1"][i]
for j in range(len(x)):
g[j] += back[i] * w1[j]
return g
def accuracy(predict: Callable[[Vector], int], data: Data) -> float:
"""Fraction of the pairs (x, y) of data with predict(x) == y. Cost: n calls of predict."""
if not data:
return 0.0
return sum(1 for x, y in data if predict(x) == y) / len(data)
test_language_model_watermarking.py 154 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/language-model-watermarking/. The authors are listed in prov/635TD2.jsonl.
"""Tests of the green list watermark on a seeded toy bigram model over integer tokens."""
import math
import random
import mlkit
from language_model_watermarking import (
detect,
draw,
false_positive_bound,
generate,
green_count,
green_list,
green_probability,
green_size,
spike_entropy,
toy_bigram_model,
z_score,
)
V = 64
GAMMA = 0.25
KEY = b"test-key-1"
def test_green_list_is_deterministic_and_has_the_right_size():
for prev in range(V):
g = green_list(KEY, prev, GAMMA, V)
assert len(g) == 16
assert g == green_list(KEY, prev, GAMMA, V)
assert all(0 <= v < V for v in g)
assert green_list(KEY, 3, GAMMA, V) != green_list(b"other-key", 3, GAMMA, V)
assert green_size(10, 0.25) == 2 and green_size(4, 0.0) == 1 and green_size(4, 1.0) == 3
def test_each_token_is_green_for_about_gamma_of_the_contexts():
hits = [0] * V
for prev in range(V):
for v in green_list(KEY, prev, GAMMA, V):
hits[v] += 1
assert sum(hits) == 16 * V
keys = [bytes([i]) for i in range(200)]
frac = sum(1 for k in keys if 5 in green_list(k, 7, GAMMA, V)) / len(keys)
assert abs(frac - 0.25) < 0.1
def test_z_score_values():
assert z_score(25, 100, 0.25) == 0.0
assert abs(z_score(50, 100, 0.25) - 25 / math.sqrt(18.75)) < 1e-12
assert abs(z_score(50, 100, 0.25) - 5.773502691896258) < 1e-12
assert z_score(0, 0, 0.25) == 0.0
def test_watermarked_text_is_detected():
rng = random.Random(2023)
model = toy_bigram_model(rng, V, 1.0)
for _ in range(8):
text = generate(model, 0, 200, GAMMA, 2.0, KEY, rng)
z, flagged = detect([0] + text, GAMMA, KEY, V, 4.0)
assert flagged and z > 6.0
def test_plain_text_and_a_wrong_key_are_not_flagged():
rng = random.Random(7)
model = toy_bigram_model(rng, V, 1.0)
flagged = 0
for _ in range(40):
plain = generate(model, 0, 150, GAMMA, 0.0, KEY, rng)
flagged += detect([0] + plain, GAMMA, KEY, V, 4.0)[1]
marked = generate(model, 0, 150, GAMMA, 2.0, KEY, rng)
flagged += detect([0] + marked, GAMMA, b"wrong-key", V, 4.0)[1]
assert flagged == 0
def test_false_positive_rate_over_random_keys_is_below_the_bound():
# The theorem: for a text that does not depend on the key, P(z > z*) <= exp(-2 z*^2 gamma (1 - gamma)).
rng = random.Random(99)
model = toy_bigram_model(rng, V, 1.0)
text = [0] + generate(model, 0, 60, GAMMA, 0.0, b"unused", rng)
for threshold in (1.0, 2.0):
bound = false_positive_bound(threshold, 0.25)
hits = sum(1 for i in range(600) if detect(text, GAMMA, b"k%d" % i, V, threshold)[1])
assert hits / 600 <= bound
assert abs(false_positive_bound(4.0, 0.25) - math.exp(-6.0)) < 1e-15
def test_repeated_pairs_are_scored_once():
text = [1, 2, 1, 2, 1, 2, 1, 2, 1]
count, scored = green_count(text, GAMMA, KEY, V)
assert scored == 2
assert count == (2 in green_list(KEY, 1, GAMMA, V)) + (1 in green_list(KEY, 2, GAMMA, V))
def test_the_bonus_never_lowers_the_green_mass():
rng = random.Random(3)
for _ in range(200):
probs = mlkit.softmax([rng.gauss(0, 2) for _ in range(V)])
green = green_list(KEY, rng.randrange(V), GAMMA, V)
delta = rng.uniform(0.0, 5.0)
q, q2 = green_probability(probs, green, delta)
assert q2 >= q - 1e-15
z = [math.log(p) + (delta if v in green else 0.0) for v, p in enumerate(probs)]
assert abs(math.fsum(mlkit.softmax(z)[v] for v in green) - q2) < 1e-12
def test_low_entropy_text_carries_a_weak_watermark():
rng = random.Random(5)
peaked = toy_bigram_model(rng, V, 12.0)
flat = toy_bigram_model(rng, V, 1.0)
zs = {}
for name, model in (("peaked", peaked), ("flat", flat)):
text = generate(model, 0, 200, GAMMA, 2.0, KEY, rng)
zs[name] = detect([0] + text, GAMMA, KEY, V, 4.0)[0]
assert zs["peaked"] < zs["flat"]
assert spike_entropy(mlkit.softmax(peaked[0]), GAMMA, 2.0) < spike_entropy(mlkit.softmax(flat[0]), GAMMA, 2.0)
def test_expected_green_count_meets_the_spike_entropy_bound():
# Theorem 4.2 of Kirchenbauer et al. for one step, averaged exactly over 300 random green lists.
rng = random.Random(11)
delta = 2.0
a = math.exp(delta)
for _ in range(5):
probs = mlkit.softmax([rng.gauss(0, 1.5) for _ in range(V)])
mean = sum(green_probability(probs, green_list(b"s%d" % i, 0, GAMMA, V), delta)[1] for i in range(300)) / 300
bound = GAMMA * a / (1 + (a - 1) * GAMMA) * spike_entropy(probs, GAMMA, delta)
assert mean >= bound - 0.03
def test_one_edit_changes_at_most_two_scores():
rng = random.Random(13)
model = toy_bigram_model(rng, V, 1.0)
text = [0] + generate(model, 0, 200, GAMMA, 2.0, KEY, rng)
count, _ = green_count(text, GAMMA, KEY, V)
edited = list(text)
positions = rng.sample(range(1, len(text)), 20)
for p in positions:
edited[p] = rng.randrange(V)
count2, _ = green_count(edited, GAMMA, KEY, V)
# An edit at position p changes only the pairs at p and p + 1, so the set of distinct green pairs loses at most 2.
assert count - count2 <= 2 * len(positions)
assert detect(edited, GAMMA, KEY, V, 4.0)[1]
def test_draw_follows_the_distribution():
rng = random.Random(1)
probs = [0.1, 0.6, 0.3]
counts = [0, 0, 0]
for _ in range(3000):
counts[draw(probs, rng)] += 1
assert all(abs(c / 3000 - p) < 0.04 for c, p in zip(counts, probs))
History
Watermarks for text existed before language models, for example by the choice of synonyms, but they changed the text after it was written. Kirchenbauer, Geiping, Wen, Katz, Miers and Goldstein posted the green list watermark in January 2023 (ICML 2023). Its main ideas were to change the sampling step, not the text, and to detect with a z-test that needs only the key. They proved the bound on the expected green count through the spike entropy, and measured the effect on quality and the robustness to edits on an open model. Christ, Gunn and Zamir (COLT 2024) gave a cryptographic definition of an undetectable watermark and a construction. Later work studied distortion-free schemes, robustness to paraphrase, and attacks that learn the green lists from many marked texts.
References
- John Kirchenbauer, Jonas Geiping, Yuxin Wen, Jonathan Katz, Ian Miers and Tom Goldstein, A watermark for large language models, ICML 2023, PMLR 202, pages 17061 to 17084, Algorithm 1 (hard red list) and Algorithm 2 (soft red list), the z-test with the threshold z = 4, the spike entropy and Theorem 4.2 on the expected green count, and the advice not to count repeated n-grams (arXiv:2301.10226)
- Miranda Christ, Sam Gunn and Or Zamir, Undetectable watermarks for language models, COLT 2024, PMLR 247, pages 1125 to 1139, the definition of an undetectable watermark and the construction from a pseudorandom function
- Wassily Hoeffding, Probability inequalities for sums of bounded random variables, Journal of the American Statistical Association 58, 1963, the tail bound for sums of independent bounded variables, and its extension to sampling without replacement
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 635TD2 Edit this page History Report an error Markdown