RSIChallenge / auto-impl /analysis /decon_tool_audit.py
Jerry999's picture
Add files using upload-large-folder tool
158258b verified
Raw History Blame Contribute Delete
6.71 kB
#!/usr/bin/env python3
"""Why upstream's contamination checker reported 0 on a genuinely contaminated file.
The leakage audit found one verbatim test item -- HumanEval/121's docstring
and a working solution -- inside the training data of
`codex / humaneval_Qwen_Qwen3-4B-Base`, in a record sourced from
`magicoder_evol_decontaminated`. Upstream's own
`src/judges/judge_tools/contamination_check.py` had reported
"Contaminated documents 0 / Total matches 0" on that file.
That left two candidate explanations, and the audit could not separate them
because the checker needs the `cl100k_base` BPE vocabulary, which is not
reachable from the aws login node: either the detection algorithm under-detects a
test item wrapped inside a larger instruction, or the substitute tokenizer
the agent shimmed in was to blame.
With the real vocabulary in `scripts/tiktoken_cache` (fetched from a compute
node, which -- unlike the login node and the eval sandbox -- does reach
openaipublic.blob.core.windows.net), the question is settled, and it is
neither of those. The algorithm has a structural blind spot:
* A reference item carrying both a question and an answer is scored
`0.75 * question + 0.25 * answer` (COMPONENT_WEIGHTS), against a 0.8
threshold (CONTAMINATION_THRESHOLD). A document that reproduces the
question perfectly and contains nothing of the answer therefore scores
exactly 0.75 -- and 0.75 < 0.8. **Question-only contamination cannot be
flagged, by construction.**
* `read_input_documents` scans one field per record: the first of
`text`, `content`, `input`, `prompt`, `question`. The ordinary SFT
schema `{"prompt": ..., "answer": ...}` therefore gets its prompt
scanned and its answer ignored.
Those two compose into the real case. The offending record holds the test
question in its `prompt`, so the checker scans the prompt, scores the
question field at a perfect 1.0, applies the 0.75 weight, and reports clean.
This script reproduces all of it:
TIKTOKEN_CACHE_DIR=$PWD/scripts/tiktoken_cache \
~/.venv-vllm-serve/bin/python analysis/decon_tool_audit.py
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import os
import pathlib
import sys
REPO = pathlib.Path(__file__).resolve().parent.parent
CHECKER = REPO / "third_party/PostTrainBench/src/judges/judge_tools/contamination_check.py"
REFERENCE = REPO / "third_party/PostTrainBench/src/eval/tasks/humaneval/test_data.json"
CONTAMINATED = pathlib.Path(
"/lustre-storage/fsx_2/user/jiaruiliu/ptb-data/results_codex_sdk_gpt-5.6-sol_20261006"
"/codex_sdk_gpt-5.6-sol_10h_run1/humaneval_Qwen_Qwen3-4B-Base_20261006-084333"
"/task/data/train_main.jsonl"
)
NEEDLE = "sum of all of the odd elements that are in even positions" # HumanEval/121
def load_checker():
"""Import upstream's checker unmodified, as a module."""
os.environ.setdefault("TIKTOKEN_CACHE_DIR", str(REPO / "scripts/tiktoken_cache"))
spec = importlib.util.spec_from_file_location("contamination_check", CHECKER)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
def best_score(index, text: str, ref_index: int) -> float | None:
"""The checker's own combined score, read at threshold 0 so near-misses show."""
hits = [m for m in index.query(text, 0.0) if m["ref_index"] == ref_index]
return max((m["combined_score"] for m in hits), default=None)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--json", default=None)
args = ap.parse_args()
cc = load_checker()
ref = cc.read_reference(REFERENCE)
index = cc.ReferenceIndex(ref)
thr = cc.CONTAMINATION_THRESHOLD
weights = cc.COMPONENT_WEIGHTS[frozenset(["question", "answer"])]
report: dict = {
"tokenizer": cc.TOKENIZER_NAME,
"threshold": thr,
"weights_question_answer": weights,
"reference_items": len(ref),
}
print(f"tokenizer={cc.TOKENIZER_NAME} threshold={thr} weights={weights}")
print(f"reference: {len(ref)} HumanEval items\n")
# --- 1. does the tool work at all? -----------------------------------
full = [i for i, it in enumerate(ref)
if (best_score(index, it["question"] + "\n" + it["answer"], i) or 0) >= thr]
print(f"[control] whole items (question + answer) fed back verbatim : "
f"{len(full)}/{len(ref)} flagged")
# --- 2. the blind spot ------------------------------------------------
q_scores = [best_score(index, it["question"], i) for i, it in enumerate(ref)]
seen = [s for s in q_scores if s is not None]
q_flagged = [s for s in seen if s >= thr]
print(f"[blind spot] questions ONLY fed back verbatim : "
f"{len(q_flagged)}/{len(ref)} flagged")
if seen:
print(f" every one of them scores in "
f"[{min(seen):.4f}, {max(seen):.4f}] -- the 0.75 question weight is a ceiling")
report["control_whole_item_flagged"] = len(full)
report["question_only_flagged"] = len(q_flagged)
report["question_only_score_range"] = [min(seen), max(seen)] if seen else None
# --- 3. the real record ----------------------------------------------
if not CONTAMINATED.is_file():
print(f"\n(skipping the real record: {CONTAMINATED} not readable here)")
else:
rec = next((json.loads(l) for l in open(CONTAMINATED) if NEEDLE in l), None)
if rec is None:
sys.exit("the offending record is no longer in that file")
print(f"\nthe real record (source={rec.get('source')}, fields={sorted(rec)})")
cases = {
"prompt only -- what the tool actually scans": rec["prompt"],
"answer only": rec["answer"],
"prompt + answer": rec["prompt"] + "\n" + rec["answer"],
}
report["real_record"] = {"source": rec.get("source"), "fields": sorted(rec), "cases": {}}
for label, text in cases.items():
s = best_score(index, text, 121)
verdict = "no candidate" if s is None else ("FLAGGED" if s >= thr else "missed")
print(f" {label:44s} {('%.4f' % s) if s is not None else ' - '} {verdict}")
report["real_record"]["cases"][label] = s
print("\nconclusion: the 0 was not the substitute tokenizer. A document that copies a test"
f"\nquestion verbatim and nothing of its answer tops out at {weights['question']:.2f},"
f"\nbelow the {thr} threshold, so it is undetectable by construction.")
if args.json:
pathlib.Path(args.json).write_text(json.dumps(report, indent=1))
print(f"\nwrote {args.json}")
if __name__ == "__main__":
main()