Python MIT License Open Source Project

AI Text Watermarking in Python: Green-List Watermark, z-Score Detection and C2PA-Style Provenance Experiments (Free Code)

Build an AI text watermarking lab in Python: green-list and Gumbel watermarks, z-score detection, paraphrase tests and signed C2PA-style provenance.

Project Specifications & Technical Summary

Difficulty Beginner
License MIT License
Advertisement

AI Text Watermarking moved from research papers into everyday products this autumn. Anthropic and Google now hide a statistical signal in the words their models choose, OpenAI does the same for ChatGPT in the EU and for API customers who opt in, and the EU AI Act’s grace period for older systems ends on 2 December 2026. Yet almost nobody outside these labs can test how well the marks work.

This tutorial gives MTech and PhD students a complete experiment lab for AI text watermarking in Python. You will implement the green-list watermark of Kirchenbauer et al. and a distortion-free Gumbel watermark, detect both with a z-test, and attack them with edits, paraphrases and Unicode tricks. You will also measure false positives on human writing and build C2PA-style signed provenance manifests for text and images with Ed25519.

Everything runs on a laptop CPU in about a minute, using a small language model trained on public-domain novels. An optional backend repeats the main experiment on a real transformer, and we did that on Qwen2.5-0.5B-Instruct. The code, results, plots and 229 tests are free on GitHub under the MIT License.

Why AI Text Watermarking Matters in November 2026

Here is the dated news behind this project. Every item links to the original source:

  • 5 Oct 2026: OpenAI described textGrain, its text watermark. It is opt-in for API customers worldwide and is being added to eligible ChatGPT and Codex output in the EU. Detector access is limited to approved researchers. OpenAI’s own numbers: at a 1% false-positive target, about 80% of 200-token passages and 95% of 400-token passages were detected. Replacing 10% of words with synonyms cut detection from about 92% to 66%, and 25% cut it to 17%.
  • 21 Oct 2026: ETH Zurich’s SRI Lab probed SynthID-Text on the Gemini API. They report that the Gemini models they tested are watermarked, that most share one key (Gemini 4 Argon and Gemini Carbon differ because their tokenizer differs), that the watermark context is 4 tokens, and that hidden thinking traces are watermarked too.
  • 31 Oct and 4 Nov 2026: The Decoder reported that Anthropic is adding its text watermark to older Claude models in waves, with Opus 4.6, Opus 4.5, Sonnet 4.5 and Haiku 4.5 from 16 November. On these models the mark applies only when temperature, top_p and top_k stay at their defaults, which Anthropic’s documentation confirms. The Decoder says Anthropic uses a variant of SynthID-Text.
  • 5 Nov 2026: IEEE Spectrum pointed out that the EU Code of Practice does not require watermarks on outputs shorter than 200 tokens, and that textGrain’s results have not been independently verified.
  • 10 Nov 2026: Writer announced customer-specific watermarks with adjustable strength and a multi-bit mode that can carry a campaign ID. It is available from 2 December and on by default in the EU.
  • 12 Nov 2026: trifero’s “Washed out” report applied SynthID-Text with its own key to Gemma 4 models. One paraphrase by a small open model brought verification down to about 2%, no higher than unmarked text.
  • 24 Nov 2026: UC Irvine’s student paper New University summed up the student angle: both Anthropic and OpenAI say a detected mark does not prove AI authorship, and detectors are designed to wrongly flag about one passage in 100.

So the industry has chosen statistical watermarks, regulators require them, and the open question is how reliable they are. That is exactly the kind of question a thesis can answer with careful experiments. Our AI PhD thesis topics 2026 list includes provenance and watermarking as topic 25. This post turns that one topic into a working lab you can extend.

What the Law Says: EU AI Act Article 50 and India's IT Rules

European Union

Article 50 of the EU AI Act applies from 2 August 2026. Providers of generative AI systems must mark outputs in a machine-readable format and make them detectable as AI-generated. The Commission’s Article 50 guidelines say both parts are required: marking without a way to detect it does not comply. Recital 133 lists watermarks, metadata, cryptographic provenance methods, logging and fingerprints as possible techniques, alone or combined.

The voluntary Code of Practice on Transparency of AI-generated Content is the recognised route to show compliance. Its signatories meet in task forces; minutes list meetings on 5 and 17 November 2026. The grace period for systems placed on the market before 2 August ends on 2 December 2026, which is why the Claude retrofits happened this month.

India

India amended the IT Rules on 10 February 2026, in force from 20 February. MeitY’s FAQ on the amendment defines “synthetically generated information” as audio, visual or audio-visual content that appears real. Platforms must label lawful synthetic media, embed provenance metadata where technically feasible and must not let users remove those labels. Pure text is outside this definition.

On 8 October 2026 MeitY sent an advisory to social media platforms, reported by MediaNama, asking them to “identify and appropriately label/contextualise manipulated, synthetically generated or misleading content”. Unlike the February rules, that advisory does not limit itself to audio-visual content. A PIB statement of 6 August 2026 summarises the wider legal framework against deepfakes.

For Indian researchers this creates a clear gap: image and video provenance is regulated, text provenance is not, and nobody has published how text watermarks behave on Hindi, Hinglish or Indian English. That gap is a thesis.

How AI Text Watermarking Works: The Green-List Watermark

The classic scheme is from Kirchenbauer et al., “A Watermark for Large Language Models” (ICML 2023). It is often called KGW after the authors. At every step, before the model picks the next token:

  1. Hash the secret key together with the previous token (or the previous h tokens). This gives a seed.
  2. Use the seed to mark a fraction γ (gamma, for example 25%) of the vocabulary as green. The rest is red.
  3. Add a bias δ (delta, for example 2.0) to the logits of green tokens, then sample as usual.

The model still writes fluent text, because it only prefers green words when several words are reasonable. But over 200 tokens the share of green words climbs far above 25%. Anyone with the key can count them. If T tokens were scored and G were green, the detector computes

z = (G - γ·T) / sqrt(T · γ · (1 - γ))

Without a watermark, each token is green with probability γ, so z is roughly standard normal. A threshold of z ≥ 4 means a one-sided false-positive rate of about 3 in 100,000 per test. The detector never needs the language model, only the key and the tokenizer. That is what makes watermarking cheap to deploy.

Distortion-Free Watermarks: Gumbel Sampling and SynthID-Text

KGW changes the output distribution: a strong δ makes text less natural. A second family avoids that. For each candidate token i with probability pi, a keyed hash gives a random number ri, and the sampler picks the token with the largest ri1/pi. Averaged over keys, this picks each token with exactly probability pi, yet the chosen tokens have unusually high r values that a detector can sum.

This exponential-minimum or Gumbel trick is the idea behind Aaronson’s proposal and Kuditipudi et al.’s distortion-free watermarks. Google DeepMind’s SynthID-Text, published in Nature in October 2024 with an open-source reference implementation, builds on the same family with a tournament sampling scheme. A March 2026 arXiv analysis studies its theoretical robustness.

Our Gumbel detector sums S = Σ −ln(1 − rt). Without a watermark this follows a Gamma(T, 1) distribution, so we can compute an exact p-value and convert it to a z-equivalent. Both schemes then share one threshold. Like SynthID-Text, our Gumbel generator samples normally when a context repeats; otherwise the deterministic choice would loop forever.

Watermarks vs Provenance vs AI Detectors

Students often confuse AI text watermarking with two other tools. This table shows how they differ:

Statistical watermarkSigned provenance (C2PA-style)“AI detector” classifier
What it checksA hidden pattern in word choicesA signed claim plus a content hashStyle features learned from data
Who can checkHolder of the detection keyAnyone with the manifestAnyone with the model
Survives copy-paste?Yes (it is in the words)No, unless the manifest travelsNot applicable
Survives editing?Partly; paraphrase removes itAny edit breaks the hard bindingUnreliable
False positivesControlled by the z thresholdEssentially noneHard to bound, biased against some writers
Tells you who wrote it?Only that one key’s model was involvedWho signed, and their claimNo

This project covers the first two. It deliberately does not build a style-based “AI detector”, because those cannot bound their false-positive rate. That makes them a poor basis for decisions about students.

Project Overview: The AI Text Watermarking Lab

The repository is a Python package called wmlab. It has a CLI, a local Flask UI and an experiment runner. Here is what it includes:

  • Two watermark schemes: KGW green list (γ, δ, context width h) and Gumbel sampling.
  • A detector with z-score, p-value, minimum length, per-token green/red flags, de-duplication of repeated (context, token) pairs, and Unicode normalisation (NFKC, zero-width removal, Cyrillic look-alikes) before scoring.
  • A CPU language model: an interpolated trigram model trained on Pride and Prejudice and The Adventures of Sherlock Holmes. Frankenstein, A Tale of Two Cities and Alice in Wonderland serve as held-out human text.
  • Attacks: word substitution, deletion, insertion, swaps, a rule-based paraphrase, truncation, mixing into human text, zero-width characters and homoglyphs.
  • Six experiments that write CSV files, plots and a summary.md.
  • Provenance: Ed25519 key generation, signed manifests with IPTC digitalSourceType, SHA-256 hard binding, dHash soft binding for images, PNG embedding, a trust list and edit history.
  • An optional Hugging Face backend with a LogitsProcessor for both schemes and an LLM paraphrase attack.
AI text watermarking web UI showing watermarked text with green-list words highlighted and a z-score of 9.26
The Generate tab. Green words fell in the keyed green list, red words did not. 70 of 111 scored words are green (63%, against 25% expected by chance), so z = 9.26.

Architecture and Project Structure

AI-Text-Watermark-Provenance-Lab-Python/
├── wmlab/
│   ├── tokenize.py      # word tokenizer, Unicode normalisation, 64-bit token ids
│   ├── hashing.py       # keyed BLAKE2b seed + SplitMix64 uniforms (numpy)
│   ├── watermark.py     # KGW bias, Gumbel choice, z-score / p-value detection
│   ├── lm.py            # CPU trigram LM: generate, perplexity
│   ├── attacks.py       # substitution, deletion, paraphrase, mixing, zero-width ...
│   ├── experiments.py   # E1-E6 -> CSV + summary.md
│   ├── plots.py         # matplotlib figures
│   ├── provenance.py    # C2PA-style manifests, Ed25519, hard/soft bindings
│   ├── web.py           # Flask UI (templates/, static/)
│   ├── cli.py           # python -m wmlab ...
│   ├── backends/hf.py   # optional transformers backend
│   └── data/            # public-domain corpora (gzip)
├── examples/hf_experiment.py
├── docs/results/        # CSVs, plots and summary from our run
└── tests/               # 229 pytest tests

The design rule is simple: the detector depends only on tokenize.py, hashing.py and watermark.py. It never imports the language model. That mirrors real deployments, where the verifier holds a key but not the model weights.

Installation and Quick Start

You need Python 3.10 or newer. The dependencies are numpy, cryptography, Pillow, matplotlib and Flask. The AI text watermarking lab needs no GPU and no API key.

git clone https://github.com/GetProjectsIdea/AI-Text-Watermark-Provenance-Lab-Python.git
cd AI-Text-Watermark-Provenance-Lab-Python
python -m venv .venv && source .venv/bin/activate      # Windows: .venv\Scripts\activate
pip install -r requirements-dev.txt

python -m wmlab demo                          # 10-second tour
python -m wmlab web                           # http://127.0.0.1:5088
python -m wmlab experiment all --out results  # CSV + plots + summary.md
python -m pytest -q                           # 229 passed

The built-in demo key is public, so set your own secret key before running real experiments:

export WMLAB_KEY="$(python -c 'import secrets; print(secrets.token_hex(16))')"
wmlab CLI demo detecting a text watermark and measuring z-scores after substitution, paraphrase and zero-width attacks
python -m wmlab demo: the watermark is detected (z = 12.00), the same model without a watermark is not (z = 1.03), and 70% word substitution finally removes it.

Step 1: Keyed Hashing, the Heart of the Green List

Every scheme needs a function that turns (key, previous tokens, candidate token) into a number between 0 and 1 that looks random to anyone without the key. We hash the key and context with BLAKE2b, then mix in each candidate’s id with SplitMix64, vectorised in numpy so one call scores the whole candidate list:

def context_seed(key: str | bytes, context: Sequence[int]) -> int:
    k = key_bytes(key)
    if not k:
        raise ValueError("watermark key must not be empty")
    if len(k) > 64:  # BLAKE2b keys are limited to 64 bytes
        k = hashlib.sha256(k).digest()
    h = hashlib.blake2b(digest_size=8, key=k)
    for c in context:
        h.update(int(c).to_bytes(8, "little", signed=False))
    return int.from_bytes(h.digest(), "little")


def splitmix64(x: np.ndarray) -> np.ndarray:
    with np.errstate(over="ignore"):
        z = x + GOLDEN
        z = (z ^ (z >> np.uint64(30))) * M1
        z = (z ^ (z >> np.uint64(27))) * M2
        return z ^ (z >> np.uint64(31))


def uniforms(seed: int, ids: Sequence[int] | np.ndarray) -> np.ndarray:
    """Pseudo-random numbers in [0, 1) for each candidate id under one context seed."""
    arr = np.asarray(ids, dtype=np.uint64)
    with np.errstate(over="ignore"):
        mixed = splitmix64(arr * GOLDEN ^ np.uint64(seed))
    # top 53 bits -> float in [0,1)
    return (mixed >> np.uint64(11)).astype(np.float64) / float(2**53)

Token ids are stable 64-bit BLAKE2b hashes of each word, so the watermark works for any word, including words the language model has never seen. With the HF backend the same functions run on the model’s tokenizer ids instead.

Step 2: Embedding the AI Text Watermarking Signal During Generation

KGW adds δ to the logits of green candidates. Gumbel picks the candidate that maximises log(r)/p, which is the same as maximising r1/p:

def kgw_bias(cfg: WatermarkConfig, context: Sequence[int], cand_ids, logits: np.ndarray) -> np.ndarray:
    """Return logits with ``delta`` added to green candidates."""
    u = uniforms(context_seed(cfg.key, context), cand_ids)
    return logits + cfg.delta * (u < cfg.gamma)


def gumbel_choice(cfg: WatermarkConfig, context: Sequence[int], cand_ids, probs: np.ndarray) -> int:
    """Index of the candidate chosen by exponential-minimum sampling: argmax log(r)/p."""
    r = uniforms(context_seed(cfg.key, context), cand_ids)
    r = np.clip(r, 1e-12, 1 - 1e-12)
    with np.errstate(divide="ignore"):
        score = np.where(probs > 0, np.log(r) / probs, -np.inf)
    return int(np.argmax(score))

Inside the generator, the bias is applied before top-k filtering and sampling, exactly where a LogitsProcessor sits in Hugging Face transformers:

if watermark is not None and watermark.scheme == "kgw":
    logits = kgw_bias(watermark, ctx, cand_ids, logits)
if top_k and top_k < len(cand):
    keep = np.argpartition(-logits, top_k)[:top_k]
    cand, logits, cand_ids = cand[keep], logits[keep], cand_ids[keep]
probs = np.exp(logits - logits.max())
probs /= probs.sum()
# Gumbel sampling is deterministic per context, so a repeated context would repeat the
# same token forever. Like SynthID-Text we sample normally when a context repeats.
if watermark is not None and watermark.scheme == "gumbel" and tuple(ctx) not in used_ctx:
    used_ctx.add(tuple(ctx))
    j = gumbel_choice(watermark, ctx, cand_ids, probs)
else:
    j = int(rng.choice(len(cand), p=probs))

Step 3: Detecting the Watermark with a z-Test

The detector walks through the tokens, rebuilds each context, and checks whether the token was green. Repeated (context, token) pairs are scored only once. Without this de-duplication, repeated phrases, lists and code inflate z, as experiment E3 shows.

for t, tok in enumerate(display):
    if t < h:
        if keep_flags:
            flags.append(TokenFlag(tok, "context"))
        continue
    ctx = tuple(ids[t - h:t])
    pair = ctx + (ids[t],)
    if cfg.dedupe and pair in seen:
        if keep_flags:
            flags.append(TokenFlag(tok, "repeat"))
        continue
    seen.add(pair)
    u = float(uniforms(context_seed(cfg.key, ctx), [ids[t]])[0])
    scored += 1
    if cfg.scheme == "kgw":
        is_green = u < cfg.gamma
        green += is_green
        if keep_flags:
            flags.append(TokenFlag(tok, "green" if is_green else "red", round(u, 4)))
    else:
        s = -math.log(max(1e-12, 1.0 - u))
        s_total += s
        is_green = u > 0.5  # for display only: high r values are "watermark-like"
        green += is_green
        if keep_flags:
            flags.append(TokenFlag(tok, "green" if is_green else "red", round(s, 4)))
if cfg.scheme == "kgw":
    if scored:
        z = (green - cfg.gamma * scored) / math.sqrt(scored * cfg.gamma * (1 - cfg.gamma))
    else:
        z = 0.0
    p = normal_sf(z)
    score = float(green)
else:
    p = gamma_sf_int(scored, s_total) if scored else 1.0
    z = normal_isf(p) if scored else 0.0
    z = max(min(z, 40.0), -40.0)
    score = s_total

Before scoring, tokenize() normalises the text: NFKC, removal of zero-width characters, and mapping of common Cyrillic and Greek look-alike letters to Latin. Without this step, sprinkling zero-width spaces inside words drops z from 12.4 to 1.0 in our tests. With it, the attack has no effect.

python -m wmlab detect wm.txt --tokens          # coloured green/red tokens, z and p-value
python -m wmlab detect wm.txt --json
python -m wmlab detect - --raw < attacked.txt   # skip normalisation (to study the attack)

Step 4: Attacks: Editing, Paraphrasing and Evasion

AI text watermarking is only useful if the mark survives what people normally do to text. The attack module never sees the key or the detector, just like a real user. Word substitution uses an offline synonym table and falls back to a random common word:

def substitute(tokens: list[str], rate: float, *, seed: int = 0, filler: list[str] | None = None) -> list[str]:
    """Replace ``rate`` of the words: a synonym when we know one, otherwise a random filler word."""
    if not 0 <= rate <= 1:
        raise ValueError("rate must be in [0, 1]")
    rng = random.Random(seed)
    out = tokens[:]
    pos = _word_positions(out)
    k = round(rate * len(pos))
    pool = filler or ["thing", "matter", "place", "way", "time", "day", "word", "hand", "eye", "door"]
    for i in rng.sample(pos, k):
        alts = synonyms(out[i])
        out[i] = rng.choice(alts) if alts else rng.choice(pool)
        if " " in out[i]:
            out[i] = out[i].split()[0]
    return out

Other attacks delete or insert words, swap neighbours, rotate clauses, truncate, embed a watermarked passage inside a long human document, and insert zero-width characters or homoglyphs. Every attack is seeded, so results are reproducible.

Watermark robustness test: 30% word substitution lowers the z-score from 9.26 to 4.43
The Attack tab. Replacing 30% of the words drops z from 9.26 to 4.43: still detected, but only just.

Step 5: C2PA-Style Provenance with Ed25519 Signatures

AI text watermarking answers “did this key’s model take part?”. Provenance answers “who claims to have made this, and has it changed since?”. The C2PA specification behind Content Credentials signs a manifest of assertions and binds it to the content with a hash.

Our teaching format keeps the same ideas in about 300 readable lines:

Advertisement
  • a c2pa.actions assertion with an IPTC digitalSourceType such as trainedAlgorithmicMedia,
  • an optional assertion that records which watermark scheme the text carries,
  • a hard binding: SHA-256 of normalised text, or of decoded image pixels (so stripping metadata does not break it, but any pixel change does),
  • a soft binding for images: a 64-bit difference hash (dHash) that survives re-encoding,
  • ingredients that link an edited file to its parent manifest,
  • an Ed25519 signature over canonical JSON, checked against a local trust list.
actual = _content_hash_for(manifest, content)
if actual == expected:
    v.checks.append("hard binding: OK (content hash matches)")
else:
    v.checks.append("hard binding: MISMATCH - the content was modified after signing")
    v.status, v.ok = "content_mismatch", False
    soft = manifest.get("soft_binding")
    if soft and manifest.get("format") == "image":
        try:
            v.soft_distance = hamming(soft["value"], dhash(content))
            same = v.soft_distance <= SOFT_MATCH_BITS
            v.checks.append(f"soft binding: dHash distance {v.soft_distance}/64 - "
                            + ("looks like a re-encoded/resized copy of the signed image" if same
                               else "looks like a different image"))
        except Exception:  # noqa: BLE001
            v.checks.append("soft binding: could not compute")
if parent is not None:
    want = hashlib.sha256(canonical(parent)).hexdigest()
    got = [i.get("manifest_sha256") for i in manifest.get("ingredients", [])]
    if want in got:
        v.checks.append("ingredient: OK (parent manifest is referenced)")
    else:
        v.checks.append("ingredient: parent manifest NOT referenced")
        v.ok = False
        if v.status == "valid":
            v.status = "content_mismatch"

It is not a conformant C2PA implementation: there are no JUMBF boxes, no COSE signatures and no X.509 certificate chain. For production, use the official C2PA SDKs. Keep them updated, too: Adobe’s security bulletin APSB26-184 (10 Nov 2026) fixed signature-verification and path-traversal bugs in the Content Credentials Rust SDK and c2patool.

python -m wmlab keygen --trust trusted/
python -m wmlab sign essay.txt --generator "my model" --watermark-scheme kgw
python -m wmlab verify essay.txt --trust trusted/
python -m wmlab sign poster.png                  # sidecar + manifest embedded in the PNG
python -m wmlab verify copy.jpg --manifest poster.png.manifest.json
wmlab CLI signing text and images with Ed25519 manifests and verifying hard and soft bindings
Signing and verifying text and images from the terminal. The JPEG copy fails the hard binding but matches the soft binding (dHash distance 0/64).

Provenance adoption is moving fast. The Content Authenticity Initiative launched an Ecosystem Explorer on 9 November 2026 and published a C2PA conformance guide on 3 November. Sitecore added C2PA validation to Content Hub on 13 November. On 20 November, Euronews reported a public TikTok tool that checks uploads for both Content Credentials metadata and an invisible watermark. That is the layered approach this lab lets you study.

Running the Experiments

One command runs all six experiments with fixed seeds and 100 samples per setting. It writes CSV files, PNG plots and a Markdown summary. Use --quick for a smoke run in seconds.

python -m wmlab experiment all --out results          # ~1 minute on a laptop CPU
python -m wmlab experiment robustness fpr --out results --quick
ExperimentQuestionOutput
E1 lengthHow many tokens does detection need?e1_length.csv / .png
E2 robustnessWhich edits remove the mark?e2_robustness.csv / .png
E3 false positivesDoes human text ever get flagged?e3_fpr.csv, e3_human_z.csv / .png
E4 qualityWhat does detectability cost in fluency?e4_quality.csv / .png
E5 parametersHow do γ and context width trade off?e5_gamma_context.csv
E6 image provenanceWhich image edits break hard vs soft bindings?e6_image_provenance.csv / .png
wmlab experiment runner writing CSV files and plots, with 229 passing pytest tests
The full experiment run takes about a minute on a laptop CPU. All 229 tests pass offline.

Results: Detection vs Text Length

All results below come from our bundled run. The full tables are in docs/results/summary.md. AI text watermarking detection needs enough tokens. With δ = 2 and γ = 0.25, 89% of 32-token texts and 100% of 64-token texts were detected. With a weak δ = 1, detection reached 96% only at 200 tokens. The Gumbel scheme detected 95% at just 16 tokens.

Plot of AI text watermark detection rate against number of tokens for different delta values
E1: share of watermarked texts detected at z ≥ 4 as the text gets longer. The dashed line is the false-positive rate on human text (zero).

Do not compare these numbers directly with OpenAI’s 80% at 200 tokens. A trigram model has far more freedom per word than an instruction-tuned LLM answering a maths question, and more freedom means a stronger signal. The toy numbers are useful for relative comparisons between schemes and settings. That is also why the EU Code of Practice does not demand watermarks on outputs under 200 tokens.

Results: Robustness of AI Text Watermarking to Edits

Edit (KGW δ = 2, 200 tokens)Mean zDetected
None12.43100%
10% words substituted10.37100%
30% substituted6.95100%
50% substituted3.9246%
70% substituted1.843%
30% deleted7.37100%
Watermarked span = 25% of a human document5.7194%
Watermarked span = 10% of a human document3.2118%
Zero-width characters, no normalisation1.010%
Zero-width characters, with normalisation12.43100%
Plot of mean watermark z-score after substitution, deletion, insertion, swap and paraphrase attacks for KGW and Gumbel
E2: mean z-score after each kind of edit. Points below the dashed line (z = 4) are, on average, no longer detected.

Three lessons stand out. First, KGW with a context width of one word is surprisingly tolerant of local edits: each substitution only spoils about two scored positions. Second, mixing matters. When the watermarked passage is only 10% of a document, whole-document KGW detection collapses to 18%, while Gumbel still caught 100% thanks to its heavy-tailed score. Third, cheap Unicode tricks are fully defeated by normalisation, so always normalise before you detect.

Our rule-based paraphrase barely hurt either scheme. Do not read that as robustness: it only drops filler words and swaps clauses. The realistic attack is an LLM paraphrase, tested on a real transformer below. There it removed most of the signal, which matches OpenAI’s synonym numbers and trifero’s SynthID results.

Results: False Positives on Human Text

An AI text watermarking detector is only fair if it almost never flags human writing. We scored 1,235 human paragraphs from Frankenstein, A Tale of Two Cities and Alice in Wonderland under five different keys. None reached z ≥ 4, and the z-scores follow the standard normal curve closely.

Histogram of watermark z-scores on human-written text following a standard normal curve
E3: 1,235 z-scores from human paragraphs (two corpora, five keys) follow the N(0,1) curve. None reached the threshold.

Now the trap. We repeated the same human paragraph ten times and scored it without de-duplication. Then 9% of the documents were flagged at z ≥ 4, against a theoretical 0.003%. Repetition multiplies the same random deviation, so z grows with the square root of the number of copies. With de-duplication the rate went back to 0%. Templates, form letters, code and lists are full of repetition, so this check is essential before anyone uses a detector on student work.

Results: Quality Cost and Parameter Choices

SettingMedian perplexityMean z (150 tokens)Detected
No watermark16.94-0.520%
KGW δ = 0.517.622.212%
KGW δ = 118.925.1889%
KGW δ = 223.6810.84100%
KGW δ = 440.2117.84100%
KGW δ = 853.7419.89100%
Gumbel17.5717.62100%

Every AI text watermarking scheme trades some fluency for detectability. Perplexity is measured by the same trigram model without the watermark, so lower means closer to the model’s natural choices. KGW buys detectability with quality: δ = 4 more than doubles perplexity. Gumbel gets a strong signal at almost no perplexity cost, which is why production systems lean towards that family.

Experiment E5 varies γ and the context width h on 100-token texts. Wider contexts look the same on clean text but are more fragile. After 20% substitution, detection fell from 99% at h = 1 to 42% at h = 4 (γ = 0.25), because one edited word now spoils four scored positions. Larger contexts are harder to reverse-engineer, as the ETH study of Gemini’s 4-token context shows. That trade-off is a good thesis question.

Results: Image Provenance with Hard and Soft Bindings

Bar chart comparing SHA-256 hard binding and dHash soft binding after JPEG, resize, crop and brightness changes
E6: the pixel hash breaks on any change; the perceptual hash survives JPEG, resizing and brightness changes, but not a 10% crop.

The pixel hash survives metadata stripping and lossless re-saving, and breaks on every real change. The perceptual dHash matched after JPEG quality 70, a 50% resize and a brightness change. It failed on a 10% crop in most trials and never matched a different image. This is why Content Credentials pair hard bindings with soft bindings or invisible watermarks: metadata gets stripped on upload, and a soft signal helps find the original manifest again.

Testing on a Real Transformer (Qwen2.5-0.5B)

The optional backend applies the same schemes through a transformers LogitsProcessor. We ran examples/hf_experiment.py with Qwen2.5-0.5B-Instruct on CPU: 12 student-style prompts, 160 new tokens, KGW δ = 2, γ = 0.25. The whole run took 225 seconds.

TextMean zDetected (z ≥ 4)
Watermarked answer8.7212/12
Same prompt, no watermark0.460/12
Watermarked → paraphrased by the same model without the watermark1.752/12
Watermarked → first 60 tokens only4.356/12

This is the most important AI text watermarking result in the project: one paraphrase by a small open model removed the watermark in 10 of 12 cases. We also checked SmolLM2-135M-Instruct with both schemes (KGW z = 9.35, Gumbel z = 15.53, unwatermarked under 2). Larger models were not tested.

pip install torch transformers
python examples/hf_experiment.py --model Qwen/Qwen2.5-0.5B-Instruct --n 12 --out results

The Local Web UI

Run python -m wmlab web and open http://127.0.0.1:5088. It has four tabs. Generate shows coloured green and red tokens. Detect accepts pasted text, and Attack compares z before and after an edit. Provenance signs text and lets you tamper with one word to watch verification fail.

The UI listens on 127.0.0.1 only and rejects other Host headers, which blocks DNS rebinding. POST requests need a custom header as a CSRF guard. A strict Content Security Policy forbids inline scripts and styles, and the watermark key never leaves the server.

C2PA-style provenance manifest verification failing with content mismatch after one word was edited
The Provenance tab. The signature is still valid, but one changed word breaks the SHA-256 hard binding, so verification reports CONTENT_MISMATCH.

Research Questions for MTech and PhD Theses on AI Text Watermarking

Each AI text watermarking question below can be started with this repository and grown into a dissertation. For broader directions see our AI PhD thesis topics 2026, the MTech thesis ideas list and research domains for MTech in computer science.

  • Indian languages. How do green-list and Gumbel watermarks behave on Hindi, Hinglish and transliterated text? Tokenizers split Devanagari differently, and transliteration changes every token. No public study covers this yet.
  • Translation attacks. Generate in English, translate to Hindi and back. How much signal survives, and can a semantic watermark do better?
  • Windowed detection. Our E2 shows whole-document KGW fails when the watermarked part is small. Design a sliding-window or change-point test, and prove a correct false-positive rate under multiple testing.
  • Paragraph-level paraphrase robustness. Compare token-level schemes with semantic ones such as SAMark (arXiv 2605.25796, v4 revised 14 Nov 2026), which reports up to 90.2% TP@FP1% under paragraph-level paraphrasing.
  • Privacy-preserving watermarks. Han and Hashimoto (arXiv 2611.06100, 4 Nov 2026) propose locally differentially private watermarks that estimate how much of a population’s text is AI-written without tracking individuals. Can that work for exam boards?
  • Corpus-level estimation. Ye (arXiv 2611.17035, 12 Nov 2026) derives bounds on the share of an edited corpus that came from a watermarked model. Replicate the bounds on student essays.
  • Multi-bit payloads for short text. Janas et al. (arXiv 2611.16890, 12 Nov 2026) embed 16-24-bit payloads with codebooks. What can be carried in a 50-token WhatsApp message?
  • Entropy-aware thresholds. Code and mathematics leave little choice per token. Calibrate thresholds by measured entropy so short technical answers are neither missed nor over-flagged.
  • Combining layers. Pair a signed manifest with a text watermark so the claim survives copy-paste, and measure the end-to-end detection rate after real platform uploads.
  • Video and images. Extend E6 with robust image watermarks, building on our video copyright content detection system design.

A good methodology section reports TPR at a fixed FPR (for example 1%), uses several keys, separates development and test corpora, publishes seeds, and includes a human evaluation of quality. The repository’s experiment runner already follows the first four rules.

Ethics: Why a Detector Score Is Not Proof

AI text watermarking gives evidence about one key only. A positive result says a specific model probably produced or processed some of the text. It says nothing about how much a student wrote, whether they used AI for translation or grammar, or whether the use was allowed. A negative result proves nothing either: the text may come from another model, an older model, a short answer or a paraphrase.

If you build a tool on this code, report the p-value and the number of tokens scored. Use a conservative threshold, keep the key secret, and never base a disciplinary decision on a score alone. Both Anthropic and OpenAI say the same about their own detectors.

Limitations of This Project

  • The trigram model has much higher per-token entropy than a modern LLM, which makes detection easier than in production. Use the HF backend for absolute numbers.
  • The rule-based paraphrase is weak. Only the LLM paraphrase in the HF experiment is realistic.
  • The real-model check covers two small models (Qwen2.5-0.5B-Instruct, SmolLM2-135M-Instruct) on CPU. Larger models, Hindi text and Gumbel on Qwen were not tested.
  • The provenance format is a teaching simplification and is not interoperable with real Content Credentials.
  • Watermarks from this lab say nothing about text from Gemini, Claude or ChatGPT, whose keys are private.

Download the Source Code

The complete AI text watermarking project (package, tests, experiment results, screenshots and the real-model script) is on GitHub: GetProjectsIdea/AI-Text-Watermark-Provenance-Lab-Python. It is MIT licensed, so you can use it in coursework, theses and papers. Please cite the original watermarking papers alongside it.

Viva Questions You Should Prepare

  • Derive the z-score for the green-list test. What assumption makes it approximately normal?
  • Why does repeating text inflate the false-positive rate, and how does de-duplication fix it?
  • Why is Gumbel sampling called distortion-free? What does it lose compared with ordinary sampling?
  • Why does a larger context width make the watermark more secure but less robust?
  • What is the difference between a hard binding and a soft binding in content provenance?
  • Why can’t a signed manifest alone prove that an image was not AI-generated?
  • What does the EU AI Act require for text, and what do India’s IT Rules require?
  • How would you design a fair experiment to measure paraphrase robustness?

This is day 7, the last post in our daily project series. Earlier posts: AI coding agent security scanner, third-party script monitor, sandboxed coding agent, hardened LLM gateway, local AI coding assistant with Ollama and Gemini student assistant. Also see the prompt injection firewall, AI agent detection rules, top 20 AI project ideas and 50 major project ideas for BTech and MCA.

FAQs: AI Text Watermarking

What is AI text watermarking?

AI Text Watermarking hides a statistical pattern in the words a language model chooses, using a secret key. A detector with the same key counts how often the pattern appears and computes a z-score. Readers cannot see the mark, and it adds no extra characters.

Can a watermark prove that a student used ChatGPT or Claude?

No. A detection is evidence that one provider’s model was involved with part of the text. It does not show how much the student wrote. A missing mark does not prove human authorship either. Only the provider and approved organisations hold the detection keys for commercial models.

How many words are needed for reliable detection?

It depends on the scheme and on how much freedom the model had. For flexible content such as psychology answers, OpenAI reports about 80% detection at 200 tokens and 95% at 400 tokens at a 1% false-positive rate, and much less for mathematics. Our toy model needs about 64 tokens with δ = 2, because it has more freedom per word than a modern LLM.

Does paraphrasing remove the watermark?

Mostly, yes. In our test on Qwen2.5-0.5B-Instruct, a single paraphrase by the same model without the watermark left only 2 of 12 texts detectable. Light edits and synonym swaps of up to about 30% of words usually leave the mark detectable.

Is this project’s provenance format real C2PA?

No. It uses the same ideas (signed assertions, hard and soft bindings, ingredients, IPTC source types) in a simple JSON format with Ed25519. For real Content Credentials, use the official C2PA SDKs and a certificate from the C2PA trust list.

Do India’s rules require labelling AI-generated text?

The February 2026 IT Rules amendment covers synthetic audio, images and video that appear real; pure text is excluded. MeitY’s 8 October 2026 advisory asks platforms to label or contextualise manipulated, synthetic or misleading content more broadly. Check the latest MeitY notifications before relying on this.

Was it tested on a real language model?

Yes, on CPU with Qwen2.5-0.5B-Instruct (12 prompts) and SmolLM2-135M-Instruct, using the optional transformers backend. Larger models and Indian-language text were not tested. All 229 unit tests run offline with the built-in trigram model.

Is the source code free for my thesis?

Yes. The full code is on GitHub under the MIT License. Cite the original papers (Kirchenbauer et al. 2023, Dathathri et al. 2024) when you use the methods.

References

Conclusion

AI Text Watermarking is now a legal requirement in Europe and a default in major AI products, but it remains a statistical signal that weakens with short text, heavy editing and especially paraphrasing. This lab lets you measure all of that yourself: two schemes, a fair detector, realistic attacks, false-positive checks and signed provenance, all on a laptop.

Start with python -m wmlab demo, run the experiments, then pick one research question and swap in a real model. Careful, honest measurement is what this field needs most, and it makes an excellent MTech or PhD project.

Advertisement

Team Get Projects

Contributor & Author
View All Projects →

Contributor at GetProjects.org, sharing open-source codebases, tutorials, and practical software architectures.

0 Discussion Comments

Markdown Supported

Join the Discussion & Code Review

Share architectural feedback, benchmark results, or troubleshooting notes.