← 开源

Codebase for generation-time and post-hoc text watermarking, as well as watermark radioactivity detection.

AI EngineeringTest & guardPython
增长势头
+024 小时新增 Star0.0%
78
Star
8
Fork
+0
本周
3
贡献者
创建于 2025-12-16 · 更新于 2026-11-28 · 今日第 28266 名
主要开发者
g-milispierrefdzsandertom
README

Text Seal

Meta Text Seal is a toolkit for LLM generation-time watermarking, post-hoc text watermarking through LLM rephrasing, and contamination detection through watermark radioactivity.

[post-hoc paper] [textseal paper] [textseal2 paper] [contamination paper] [meta seal] [colab]

Features

  • 🆕 TextSeal2: Distortion-free two-key copula watermark that stays exact and detectable under speculative decoding, with the scripts reproducing its paper. See docs/README_textseal2.md and the paper.
  • TextSeal: Dual-key generation-time watermarking with speculative decoding and localized detection. See docs/README_textseal.md.
  • 🔏 Post-hoc Watermarking: Rephrase text with an LLM while inserting a watermark using generation-time scheme (Green-list/Red-list, Gumbel-max, DipMark, SynthID, MorphMark, WaterMax, etc.).
  • 🔑 Public Detection: One key for public detection, both keys for full detection that flags tampering. See docs/README_attack.md.
  • 🧪 Contamination Detection: Detect watermarked dataset membership inference through radioactivity.
  • 🚀 Training Infrastructure: Distributed pretraining and SFT with contamination injection support for research purposes.

TextSeal2 Quick Start

from transformers import AutoModelForCausalLM, AutoTokenizer
from textseal.watermarking.config import WatermarkConfig
from textseal.watermarking.detector import build_detector
from textseal.watermarking.generator import build_generator

model_name = "meta-llama/Llama-3.2-3B-Instruct"
model = AutoModelForCausalLM.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)

# Generate watermarked text (rho trades diversity for detection)
wm_config = WatermarkConfig(watermark_type="textseal2", secret_key=42, ngram=3, rho=0.9, prf="hires")
generator = build_generator(model, tokenizer, wm_config)
texts = generator.generate([prompt], max_gen_len=200, temperature=1.0, top_p=0.95)

# Detect watermark (Gamma test on the virtual key, each (window, token) scored once)
detector = build_detector(tokenizer, wm_config)
scores = detector.get_scores_by_t(texts, scoring_method="v2", seen_windows=set())[0]
print(f"p-value: {detector.get_pvalue(sum(scores), len(scores)):.2e}")

See the TextSeal2 README for speculative decoding and the paper's experiments, and the TextSeal README for TextSeal (localized detection, python demo.py).

Quick Start for Post-hoc Watermarking

Installation

Option 1: pip install (fastest)

pip install textseal

Option 2: Install from source

git clone https://github.com/facebookresearch/textseal.git
cd textseal
pip install -e .

If your Hugging Face assets live in a non-default cache, set:

export HF_HOME=/path/to/cache

or pass model_config=ModelConfig(cache_dir="/path/to/cache") in Python / --model.cache_dir /path/to/cache in the CLI.

Python API

Watermark text using the Python API:

from textseal import PostHocWatermarker, WatermarkConfig, ModelConfig, ProcessingConfig

# Basic usage with defaults
watermarker = PostHocWatermarker()
result = watermarker.process_text("Your text here")
print(result["wm_text"])  # Watermarked text
print(result["wm_eval"]["p_value"])  # Detection p-value

# Custom configuration
watermarker = PostHocWatermarker(
    watermark_config=WatermarkConfig(watermark_type="gumbelmax"),
    model_config=ModelConfig(model_name="meta-llama/Llama-3.2-3B-Instruct"),
    processing_config=ProcessingConfig(temperature=0.8, top_p=0.95),
)
result = watermarker.process_text("Text to watermark")

💡 Tip: Increasing watermark strength. For Gumbel-max watermarking, increase temperature for stronger watermarks (e.g., temperature=1.2 in ProcessingConfig). For Greenlist watermarking, increase delta (e.g., delta=3.0 in WatermarkConfig). See Watermark Configuration Guide for details.

See docs/README_posthoc.md for detailed documentation on the configurations and usage.

Common Use Cases:

  • Watermarking + Detection: Use process_text() to watermark text and get detection metrics (p-value, score) in one call.
  • Watermarking Only: Use rephrase_with_watermark() to get just the watermarked text without evaluation.
  • Detection Only: Set enable_detection_only=True and use evaluate_watermark() to check existing text for watermarks without loading the LLM.

See docs/README_posthoc_api.md for complete API usage examples

Command Line Interface

After installing textseal, you get the textseal-watermark CLI command:

# Get help
textseal-watermark --help

# Watermark a file
textseal-watermark --input_path document.txt --dump_dir output/

# Detection-only mode
textseal-watermark --input_path text_to_check.txt --evaluation.enable_detection_only true

Using the Repository

Installation

Option 3: Development setup

# Clone the repository
git clone https://github.com/facebookresearch/textseal.git
cd textseal

# Create environment and install dependencies
conda create -n text_seal python=3.11.13
conda activate text_seal
pip install -r requirements.txt

💡 For contamination detection experiments (training with contamination injection), you need additional setup. First follow the Meta Lingua installation instructions, then install the requirements above. See Environment Setup for details.

Post-hoc Watermarking

Watermark existing text by rephrasing it with a paraphrasing LLM:

python -m textseal.watermarking.main \
  --input_path assets/sample_document.txt \
  --dump_dir output/ \
  --watermark.watermark_type textseal2 --watermark.ngram 3 --watermark.prf hires \
  --model.model_name meta-llama/Llama-3.2-3B-Instruct \
  --processing.temperature 1.0 \
  --processing.top_p 0.95

See the full Post-hoc Watermarking README for details on watermark methods, strength tuning, and evaluation.

Generation-time Watermarking

Generate watermarked text directly from prompts:

python -m textseal.watermarking.main \
  --input_path prompts.jsonl --text_key question \
  --processing.generation_mode true \
  --processing.max_gen_len 512 \
  --model.model_name Qwen/Qwen3.5-2B \
  --watermark.watermark_type textseal2 --watermark.ngram 3 --watermark.prf hires

Supports reasoning mode for thinking models (e.g., Qwen3.5):

python -m textseal.watermarking.main \
  --input_path prompts.jsonl --text_key question \
  --processing.generation_mode true \
  --processing.reasoning.enabled true \
  --processing.reasoning.max_tokens 200 \
  --processing.max_gen_len 1024 \
  --model.model_name Qwen/Qwen3.5-2B \
  --watermark.watermark_type textseal2 --watermark.ngram 3 --watermark.prf hires

See the full Generation-time Watermarking README for reasoning options, configuration, and output format.

Results are saved in output/ directory as a JSONL file containing original, watermarked text and statistics.

Contamination Detection

Inject watermarked benchmarks during training and detect memorization through watermark radioactivity.

Download DCLM training data and benchmark datasets (ARC-Easy, ARC-Challenge, MMLU). See Data Preparation in the contamination docs.

The contamination detection workflow consists of three steps, each with its own experiment configuration file:

# Step 1: Watermark benchmarks with different secret keys
python -m textseal.watermarking.main --config configs/watermark_benchmarks.yaml

# Step 2: Train model with contaminated watermarked data
python -m textseal.common.stool script=textseal.wmtraining.train \
  config=configs/train_with_contamination.yaml \
  nodes=4 ngpu=8 partition=learn qos=high time=4320

# Step 3: Detect contamination via watermark evaluation
python -m textseal.wmtraining.eval_wm --config configs/eval_contamination.yaml

Configuration files:

See docs/README_contamination.md for detailed documentation.

Documentation

Repository Structure

textseal/
├── textseal/
│   ├── watermarking/     # Watermarking: post-hoc, generation-time, detection
│   ├── attacks/          # Removal/forgery attacks
│   ├── wmtraining/       # Training and evaluation
│   ├── analysis/         # Analysis tools
│   └── common/           # Shared utilities (LLM, watermark, config)
├── docs/                 # Detailed documentation
├── configs/              # Example configurations for watermarking and training
├── assets/               # Sample texts
├── setup/                # Setup scripts and data processing

Use Cases

1. Content Authentication

Watermark text to enable verification and provenance tracking.

2. Dataset Contamination Detection

Detect if evaluation benchmarks were included in training data by injecting watermarked versions and checking for "radioactivity."

3. Research on Watermarking

Experiment with different watermarking algorithms and detection methods on your own models and datasets.

License

This project is licensed under the Apache License 2.0.

See the NOTICE file for required attributions.

The contamination detection app builds on Meta Lingua for training, which has a BSD 3-Clause License. The models used for post-hoc watermarking are loaded from Hugging Face and are subject to their respective licenses.

Papers

This codebase implements methods from:

Citation

If you use Text Seal in your research, please cite:

@article{sander2025detecting,
  title={Detecting benchmark contamination through watermarking},
  author={Sander, Tom and Fernandez, Pierre and Mahloujifar, Saeed and Durmus, Alain and Guo, Chuan},
  journal={arXiv preprint arXiv:2502.17259},
  year={2025}
}

@article{fernandez2025how,
  title={How Good is Post-Hoc Watermarking With Language Model Rephrasing?},
  author = {Fernandez, Pierre and Sander, Tom and Elsahar, Hady and Chang, Hongyan and Sou\v{c}ek, Tom\'{a}\v{s} and Lacatusu, Valeriu and Tran, Tuan and Rebuffi, Sylvestre-Alvise and Mourachko, Alexandre},
  year={2025}
}

@article{sander2026textseal,
  title={TextSeal: A Localized LLM Watermark for Provenance \& Distillation Protection},
  author={Sander, Tom and Chang, Hongyan and Sou\v{c}ek, Tom\'{a}\v{s} and Tran, Tuan and Lacatusu, Valeriu and Rebuffi, Sylvestre-Alvise and Mourachko, Alexandre and Parimi, Surya and Ropers, Christophe and Moritz, Rashel and Stark, Vanessa and Elsahar, Hady and Fernandez, Pierre},
  journal={arXiv preprint arXiv:2605.12456},
  year={2026}
}

@article{sander2026textseal2,
  title={TextSeal2: Distortion-Free LLM Watermarking with Copula Mixing and Memoryless Races},
  author={Sander, Tom and Fernandez, Pierre and Gat, Itai and Bao, Haiming and Shi, Jiaxin and Park, Jason and Lacatusu, Valeriu and Rebuffi, Sylvestre-Alvise and Chang, Hongyan and Elsahar, Hady and Sou\v{c}ek, Tom\'{a}\v{s} and Tran, Tuan and Parimi, Surya and Mourachko, Alexandre},
  journal={arXiv preprint arXiv:2610.40613},
  year={2026}
}
排名相邻
同类项目

AI Rank iPhone 版

随时追踪 AI 模型榜单

在 App Store 下载