Algorithm Search⌘K

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
Properties
randomizednot exactonlineiterative
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 γ∣V∣\gamma |V| tokens and a red list of the others, and the logits of the green tokens get a bonus δ\delta. Plain text has about a fraction γ\gamma of green tokens, and marked text has more. The detector counts the green tokens among TT scored tokens and computes the z-score z=(∣s∣G−γT)/Tγ(1−γ)z = (|s|_G - \gamma T) / \sqrt{T \gamma (1 - \gamma)}. 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 p(⋅∣s<t)p(\cdot \mid s_{<t}) over a vocabulary VV, generate text whose distribution is close to pp, such that a detector with a key kk flags generated texts of enough length and enough entropy, and flags a text that does not depend on kk with probability at most a chosen small number. The detector sees only the tokens s0,s1,…,sTs_0, s_1, \dots, s_T, where s0s_0 is the last token of the prompt.

The algorithm

  1. GENERATE(p, s_0, T, gamma, delta, k)
  2. 1for t ← 1 to T do
  3. 2z ← the logits of p for the next token after s_0, ..., s_{t-1}
  4. 3G ← GREEN-LIST(k, s_{t-1}, gamma)
  5. 4for each v ∈ G do z[v] ← z[v] + delta
  6. 5s_t ← a draw from softmax(z)
  7. 6return s_1, ..., s_T
  8. GREEN-LIST(k, u, gamma)
  9. 7r ← a generator seeded with H(k, u) ▷ H is a keyed hash
  10. 8return ⌊gamma |V|⌋ tokens of V drawn by r without replacement
  11. DETECT(s_0, ..., s_T, gamma, k, z*)
  12. 9count ← 0, scored ← 0, seen ← ∅
  13. 10for t ← 1 to T do
  14. 11if (s_{t-1}, s_t) ∈ seen then continue ▷ score each pair once
  15. 12seen ← seen ∪ {(s_{t-1}, s_t)}, scored ← scored + 1
  16. 13if s_t ∈ GREEN-LIST(k, s_{t-1}, gamma) then count ← count + 1
  17. 14z ← (count - gamma' · scored) / sqrt(scored · gamma' (1 - gamma')) ▷ gamma' = ⌊gamma |V|⌋ / |V|
  18. 15return (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 δ\delta, which multiplies their probabilities by eδe^\delta 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 γ′\gamma' of plain text.

Example

Take a toy bigram model over ∣V∣=64|V| = 64 integer tokens, with logits drawn from N(0,1)N(0, 1) by a fixed seed, γ=0.25\gamma = 0.25 (16 green tokens per context) and δ=2\delta = 2. After the token 0, the green mass of the model is q=0.179q = 0.179. Line L4 raises it to e2q/(e2q+1−q)=0.617e^2 q / (e^2 q + 1 - q) = 0.617.

A marked text of 12 tokens after s0=0s_0 = 0 has 11 green tokens. Plain text would have about 3, and line L14 gives z=(11−3)/12⋅0.25⋅0.75=8/1.5=5.33z = (11 - 3) / \sqrt{12 \cdot 0.25 \cdot 0.75} = 8 / 1.5 = 5.33, above the threshold z∗=4z^* = 4.

The table is a measurement on this toy model: 20 texts of T=200T = 200 tokens for each δ\delta, all with the same key.

δ\delta mean green fraction mean zz smallest zz
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 T\sqrt T for a fixed green fraction: with half of the tokens green, z=2.66z = 2.66 at T=25T = 25, 4.084.08 at T=50T = 50, 5.775.77 at T=100T = 100 and 8.168.16 at T=200T = 200. So short texts cannot be flagged with confidence.

Correctness

Theorem (false positives). Model HH as a random function, so the green lists of different previous tokens are independent, uniformly random sets of size ⌊γ∣V∣⌋\lfloor \gamma |V| \rfloor. Let the text s0,…,sTs_0, \dots, s_T not depend on the key. Then DETECT returns true with probability at most e−2z∗2γ′(1−γ′)e^{-2 z^{*2} \gamma' (1 - \gamma')} for every threshold z∗>0z^* > 0.

Lemma (the bonus helps). If the green mass of the model at a step is qq, the green mass after line L4 is eδq/(eδq+1−q)≥qe^\delta q / (e^\delta q + 1 - q) \ge q, with equality only for q∈{0,1}q \in \{0, 1\}.

Lemma (edits). Changing mm tokens of a text lowers the count of line L13 by at most 2m2m.

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 P(count−γ′N≥a)≤e−2a2/NP(\mathrm{count} - \gamma' N \ge a) \le e^{-2a^2/N} for NN scored pairs; the choice a=z∗Nγ′(1−γ′)a = z^* \sqrt{N \gamma'(1 - \gamma')} gives the bound. For γ=0.25\gamma = 0.25 and z∗=4z^* = 4 the bound is e−6=0.0025e^{-6} = 0.0025, a theorem. The paper gives 3×10−53 \times 10^{-5}, the one-sided normal tail at 4, which is the right value for large TT by the central limit theorem but not a finite-sample guarantee. The edit lemma holds because a token at position pp enters only the pairs at positions pp and p+1p + 1. 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 S(p,ζ)=∑vpv/(1+ζpv)S(p, \zeta) = \sum_v p_v / (1 + \zeta p_v) of the steps is at least S∗S^*, with ζ=(1−γ)(eδ−1)/(1+(eδ−1)γ)\zeta = (1 - \gamma)(e^\delta - 1) / (1 + (e^\delta - 1)\gamma), then the expected number of green tokens is at least γeδTS∗/(1+(eδ−1)γ)\gamma e^\delta T S^* / (1 + (e^\delta - 1)\gamma). 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 VV be the vocabulary, g=⌊γ∣V∣⌋g = \lfloor \gamma |V| \rfloor with 1≤g≤∣V∣−11 \le g \le |V| - 1, and γ′=g/∣V∣\gamma' = g / |V|. For a previous token uu, let G(u)G(u) be the green list of lines L7 and L8. We model the keyed hash HH as a random function: the sets G(u)G(u) for different uu are independent, and each is uniformly random among the subsets of VV of size gg. A text s=(s0,…,sT)s = (s_0, \dots, s_T) does not depend on the key if it is fixed before the key is drawn, or drawn independently of it.

For a text ss, let P(s)P(s) be the set of distinct pairs (st−1,st)(s_{t-1}, s_t) with 1≤t≤T1 \le t \le T. Lines L9 to L13 set scored=∣P(s)∣\mathrm{scored} = |P(s)| and count=∣{(u,v)∈P(s):v∈G(u)}∣\mathrm{count} = |\{(u, v) \in P(s) : v \in G(u)\}|, because line L11 skips a pair exactly when it is already in the set seen\mathrm{seen}, and line L12 adds each new pair once.

Lemma 1 (Hoeffding). Let X1,…,XmX_1, \dots, X_m be a sample without replacement from a finite list of numbers in [0,1][0, 1] with mean μ\mu, and let Y1,…,YmY_1, \dots, Y_m be independent draws with replacement from the same list. Then E[eλ∑Xi]≤E[eλ∑Yi]E[e^{\lambda \sum X_i}] \le E[e^{\lambda \sum Y_i}] for every real λ\lambda.

Hoeffding (1963) proved this comparison for every continuous convex function in place of eλxe^{\lambda x}. We use it without proof.

Lemma 2 (Hoeffding's lemma). If YY takes values in [0,1][0, 1] with mean μ\mu, then E[eλ(Y−μ)]≤eλ2/8E[e^{\lambda (Y - \mu)}] \le e^{\lambda^2 / 8} for every real λ\lambda.

This is the standard lemma behind Hoeffding's inequality. We use it without proof.

Theorem 1 (false positives). Let ss not depend on the key, let N=∣P(s)∣≥1N = |P(s)| \ge 1, and let z∗>0z^* > 0. Then P(z>z∗)≤e−2z∗2γ′(1−γ′)P(z > z^*) \le e^{-2 z^{*2} \gamma'(1 - \gamma')}, where zz is the value of line L14. If N=0N = 0, then z=0z = 0 and DETECT returns false.

Proof. The set P(s)P(s) is fixed, because ss does not depend on the key. Group its pairs by the first token: for each uu, let v1,…,vmuv_1, \dots, v_{m_u} be the distinct tokens with (u,vi)∈P(s)(u, v_i) \in P(s), so ∑umu=N\sum_u m_u = N. Let Cu=∑i1{vi∈G(u)}C_u = \sum_i 1\{v_i \in G(u)\}, so count=∑uCu\mathrm{count} = \sum_u C_u.

Fix uu. Since G(u)G(u) is a uniform subset of size gg, the green status of the distinct tokens v1,…,vmuv_1, \dots, v_{m_u} has the same distribution as mum_u draws without replacement from a list of ∣V∣|V| numbers, gg of them equal to 1 and the rest equal to 0: label the tokens of VV by 1{v∈G(u)}1\{v \in G(u)\}; by symmetry this labeling is a uniform random arrangement of the list, and reading it at mum_u fixed distinct places is a sample without replacement. The list has mean γ′\gamma'. By Lemma 1 and then Lemma 2, for every λ>0\lambda > 0,

E[eλ(Cu−γ′mu)]≤∏i=1muE[eλ(Yi−γ′)]≤emuλ2/8E[e^{\lambda (C_u - \gamma' m_u)}] \le \prod_{i=1}^{m_u} E[e^{\lambda (Y_i - \gamma')}] \le e^{m_u \lambda^2 / 8},

where the YiY_i are independent Bernoulli variables with mean γ′\gamma'.

The variables CuC_u for different uu are functions of different, independent sets G(u)G(u), so they are independent, and

E[eλ(count−γ′N)]=∏uE[eλ(Cu−γ′mu)]≤eNλ2/8E[e^{\lambda (\mathrm{count} - \gamma' N)}] = \prod_u E[e^{\lambda (C_u - \gamma' m_u)}] \le e^{N \lambda^2 / 8}.

By Markov's inequality, for a>0a > 0, P(count−γ′N≥a)≤e−λa+Nλ2/8P(\mathrm{count} - \gamma' N \ge a) \le e^{-\lambda a + N \lambda^2 / 8}, and the choice λ=4a/N\lambda = 4a / N gives P(count−γ′N≥a)≤e−2a2/NP(\mathrm{count} - \gamma' N \ge a) \le e^{-2a^2 / N}.

Line L14 gives z>z∗z > z^* exactly when count−γ′N>z∗Nγ′(1−γ′)\mathrm{count} - \gamma' N > z^* \sqrt{N \gamma'(1 - \gamma')}. Take a=z∗Nγ′(1−γ′)>0a = z^* \sqrt{N \gamma'(1 - \gamma')} > 0. Then P(z>z∗)≤P(count−γ′N≥a)≤e−2z∗2Nγ′(1−γ′)/N=e−2z∗2γ′(1−γ′)P(z > z^*) \le P(\mathrm{count} - \gamma' N \ge a) \le e^{-2 z^{*2} N \gamma'(1 - \gamma') / N} = e^{-2 z^{*2}\gamma'(1 - \gamma')}. If N=0N = 0, the code returns z=0z = 0, and 0>z∗0 > z^* is false. □\square

Lemma 3 (the bonus helps). Let a step have the distribution p=softmax(z)p = \mathrm{softmax}(z) and let q=∑v∈Gpvq = \sum_{v \in G} p_v. After line L4 the green mass is q′=eδq/(eδq+1−q)q' = e^\delta q / (e^\delta q + 1 - q). If δ≥0\delta \ge 0, then q′≥qq' \ge q, and if δ>0\delta > 0 the equality holds only for q∈{0,1}q \in \{0, 1\}.

Proof. Adding δ\delta to the logit of a token multiplies its unnormalized weight ezve^{z_v} by eδe^\delta. With Z=∑vezvZ = \sum_v e^{z_v}, the green weight becomes eδqZe^\delta q Z and the red weight stays (1−q)Z(1 - q) Z, so q′=eδq/(eδq+1−q)q' = e^\delta q / (e^\delta q + 1 - q). Let a=eδ≥1a = e^\delta \ge 1. Then q′−q=q(a−(aq+1−q))/(aq+1−q)=q(1−q)(a−1)/(aq+1−q)≥0q' - q = q (a - (a q + 1 - q)) / (a q + 1 - q) = q (1 - q)(a - 1) / (a q + 1 - q) \ge 0, since the denominator is at least 1−q+q=1>01 - q + q = 1 > 0. For a>1a > 1 the numerator is zero exactly when q=0q = 0 or q=1q = 1. □\square

Theorem 2 (edits). Let s′s' be the text ss with the tokens at mm positions p1,…,pm∈{1,…,T}p_1, \dots, p_m \in \{1, \dots, T\} changed, with the same key. Then count(s′)≥count(s)−2m\mathrm{count}(s') \ge \mathrm{count}(s) - 2m.

Proof. The pair at position tt is (st−1,st)(s_{t-1}, s_t), so it changes only if tt or t−1t - 1 is an edited position. Let A={pi}∪{pi+1}A = \{p_i\} \cup \{p_i + 1\}, a set of at most 2m2m positions. For t∉At \notin A, the pair of s′s' at position tt is the same as the pair of ss at position tt. So every pair of P(s)P(s) that occurs in ss at some position outside AA is also in P(s′)P(s'), and P(s)∖P(s′)P(s) \setminus P(s') holds only pairs that occur in ss only at positions in AA; there are at most ∣A∣≤2m|A| \le 2m such pairs. The green status of a pair (u,v)(u, v) depends only on G(u)G(u), which is the same for both texts, so the green pairs of P(s)P(s) that are lost number at most 2m2m, and new pairs can only add to the count. Hence count(s′)≥count(s)−2m\mathrm{count}(s') \ge \mathrm{count}(s) - 2m. ■\blacksquare

Complexity

  • Generation. One call of the model per token, as without the mark, plus O(∣V∣)O(|V|) for the hash, the green list and the bonus: O(T(c+∣V∣))O(T(c + |V|)). The green list of ⌊γ∣V∣⌋\lfloor \gamma |V| \rfloor tokens costs O(γ∣V∣)O(\gamma |V|) with a partial shuffle.
  • Detection. O(T∣V∣)O(T |V|) time, or O(T)O(T) hash calls if the test of line L13 asks the generator only whether sts_t is green. It needs no model and no GPU.
  • Space. O(∣V∣+T)O(|V| + T), 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 e−2z∗2γ′(1−γ′)e^{-2 z^{*2}\gamma'(1-\gamma')} (the theorem). This covers human text, under the model of HH as a random function.
  • Quality cost. The mark changes the output distribution. A larger δ\delta 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 T\sqrt T, so a text of 25 tokens with half of them green gives only z=2.66z = 2.66. 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 zz for human text. Score each pair once.
  • Using γ\gamma when γ∣V∣\gamma |V| is not a whole number. Line L8 takes ⌊γ∣V∣⌋\lfloor \gamma |V| \rfloor tokens, so line L14 must use γ′=⌊γ∣V∣⌋/∣V∣\gamma' = \lfloor \gamma |V| \rfloor / |V|; otherwise the z-score is biased.
  • The normal tail as a guarantee. The value 3×10−53 \times 10^{-5} at z∗=4z^* = 4 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 HH 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.

language_model_watermarking.pyI0RawGitHub
# 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

  1. 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)
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.detect
  • a full proof of time.generate
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example