"""Score passages with the SynthID-Text and KGW detectors. python detect.py results/scores.jsonl results/generated.jsonl [results/rewritten-*.jsonl ...] Every passage is scored by both detectors, so the unmarked passages and the "wrong scheme" scores show what a passage with no matching watermark looks like. Scores are z-values: about 0 for text with no matching watermark, and above Z_THRESHOLD (2.326) only about 1 time in 100 by chance. Detection needs the tokenizer and the keys, not the model weights. Run it on the same kind of device (CPU, Apple GPU, CUDA) that generated the text. """ import json import math import sys import torch from transformers import AutoConfig, AutoTokenizer, SynthIDTextWatermarkingConfig, WatermarkDetector, WatermarkingConfig from wm_config import KGW_ARGS, MODEL_NAME, SYNTHID_ARGS, pick_device out_path, in_paths = sys.argv[1], sys.argv[2:] # The libraries build their random tables with a device-specific generator, so # detection has to run on the same kind of device that generated the text. device = pick_device() tok = AutoTokenizer.from_pretrained(MODEL_NAME) config = AutoConfig.from_pretrained(MODEL_NAME) synthid_cfg = SynthIDTextWatermarkingConfig(**SYNTHID_ARGS) synthid = synthid_cfg.construct_processor(config.vocab_size, device) depth = len(SYNTHID_ARGS["keys"]) kgw = WatermarkDetector(model_config=config, device=device, watermarking_config=WatermarkingConfig(**KGW_ARGS)) def synthid_z(ids: torch.Tensor): """Mean-score detector from the SynthID-Text paper, as a z-value. Each scored position has one 0/1 g-value per key. With no watermark these average 0.5; the watermark pushes the average up. Positions whose context already appeared earlier in the passage are skipped, as in the paper. """ if ids.shape[1] < SYNTHID_ARGS["ngram_len"] + 5: return None, 0 g = synthid.compute_g_values(ids).float() # (1, positions, depth) mask = synthid.compute_context_repetition_mask(ids).float() # (1, positions) n = int(mask.sum().item()) if n < 5: return None, n mean = float((g * mask.unsqueeze(-1)).sum().item() / (n * depth)) return (mean - 0.5) * math.sqrt(n * depth) / 0.5, n def kgw_z(ids: torch.Tensor): if ids.shape[1] < 10: return None res = kgw(ids, return_dict=True) return float(res.z_score[0]) with open(out_path, "w") as out: for path in in_paths: for line in open(path): if not line.strip(): continue row = json.loads(line) ids = tok(row["text"], return_tensors="pt", add_special_tokens=False)["input_ids"].to(device) sz, scored = synthid_z(ids) out.write( json.dumps( { "id": row["id"], "prompt": row.get("prompt"), "scheme": row["scheme"], "engine": row.get("engine", "none"), "tokens": int(ids.shape[1]), "synthid_z": None if sz is None else round(sz, 3), "synthid_positions": scored, "kgw_z": None if (kz := kgw_z(ids)) is None else round(kz, 3), } ) + "\n" ) print("scored", out_path)