"""Contamination probe for LLM baselines in the MacroLens panel. Reviewer R2 (W2.1) and R3 (W3.11) flag that the test window (2024-09-03 → 2026-03-31) overlaps current frontier-LLM pretraining cutoffs. This module probes per-LLM recall of test-period closing prices, filing dates, and major news headlines on the **first half** of the test window (2024-09-03 → ~2025-06-30), where contamination risk is concentrated; the second half (2025-07 → 2026-03) post-dates every Family-6 model's cutoff and is left unprobed (contamination-safe by construction). The probe is intentionally narrow: it tests *recall*, not *evaluation performance*. A model that recalls a specific test-period closing price verbatim has seen that price during pretraining; the probe is silent on whether the LLM uses that recall on the actual benchmark task. Usage (no compute is run by importing the module):: python -m projects.agent_builder.scripts.whatif_bench.experiments.probes.contamination \\ --model-id Qwen/Qwen3.5-27B-FP8 \\ --base-url http://localhost:8004/v1 \\ --n-samples 200 \\ --first-half-end 2025-06-30 \\ --seed 42 \\ --output experiments/probes_output/contamination_qwen35.json Per-launch authorisation: this script issues HTTP requests to a vLLM endpoint (or OpenRouter); the user must authorise each launch per the project's no-unauthorised-runs policy. """ from __future__ import annotations import argparse import json import logging import os import random import re from dataclasses import asdict, dataclass from pathlib import Path from typing import Any import numpy as np import pandas as pd logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- # Probe template construction # --------------------------------------------------------------------------- _PRICE_PROMPT = ( "What was the closing price of ticker {ticker} on {date}? " "This is a factual recall question about U.S. equity markets. " "Respond with a single number representing the closing price in USD, " "or the exact string 'UNKNOWN' if you cannot recall it. " "No commentary, no units, no surrounding text." ) def _parse_price_response(text: str) -> float | None: """Extract a single float from the response, or None on UNKNOWN/parse fail.""" if not text: return None stripped = text.strip() if stripped.upper().startswith("UNKNOWN"): return None # Try the strict path first: response is a single number. try: return float(stripped) except ValueError: pass # Permissive: pick the first float-looking token in the response. matches = re.findall(r"-?\d+(?:\.\d+)?", stripped) if matches: try: return float(matches[0]) except ValueError: return None return None # --------------------------------------------------------------------------- # Recall scoring # --------------------------------------------------------------------------- @dataclass class ProbeOutcome: ticker: str date: str actual: float predicted: float | None relative_error: float | None # |pred - actual| / actual; None on UNKNOWN/parse-fail def _score_one(actual: float, predicted: float | None) -> float | None: if predicted is None or actual == 0: return None return abs(predicted - actual) / abs(actual) # --------------------------------------------------------------------------- # Sampling # --------------------------------------------------------------------------- def _load_first_half_panel( panel_path: Path, first_half_end: str, ) -> pd.DataFrame: """Load the test-window panel restricted to the first half. Expected columns: ticker, date, close (or adj_close), plus whatever additional metadata is needed. """ df = pd.read_parquet(panel_path, columns=["ticker", "date", "close"]) df = df.dropna(subset=["close"]) df["date"] = pd.to_datetime(df["date"]).dt.strftime("%Y-%m-%d") return df[df["date"] <= first_half_end].reset_index(drop=True) def _sample_pairs( df: pd.DataFrame, n_samples: int, seed: int, ) -> pd.DataFrame: rng = np.random.default_rng(seed) idx = rng.choice(len(df), size=min(n_samples, len(df)), replace=False) return df.iloc[idx].reset_index(drop=True) # --------------------------------------------------------------------------- # Probe driver # --------------------------------------------------------------------------- def probe_closing_prices( *, panel_path: Path, model_id: str, base_url: str, n_samples: int = 200, first_half_end: str = "2025-06-30", seed: int = 42, api_key: str = "EMPTY", recall_tolerance: float = 0.05, ) -> dict[str, Any]: """Run the closing-price recall probe against a single LLM endpoint. Returns a dict with per-instance outcomes and aggregate recall stats. Recall = fraction of samples whose predicted price is within ``recall_tolerance`` of the ground-truth close. """ from projects.agent_builder.scripts.whatif_bench.methods._openai_engine import OpenAIEngine df = _load_first_half_panel(panel_path, first_half_end) if len(df) == 0: raise RuntimeError( f"first-half panel is empty under filter date {first_half_end}; " f"check the panel at {panel_path}" ) samples = _sample_pairs(df, n_samples, seed) engine = OpenAIEngine(base_url=base_url, api_key=api_key, model_id=model_id) prompts = [ [{"role": "user", "content": _PRICE_PROMPT.format(ticker=row.ticker, date=row.date)}] for row in samples.itertuples(index=False) ] responses = engine.chat_complete_batch( prompts, max_tokens=64, temperature=0.0, top_p=1.0, ) outcomes: list[ProbeOutcome] = [] for row, text in zip(samples.itertuples(index=False), responses, strict=True): predicted = _parse_price_response(text) rel_err = _score_one(row.close, predicted) outcomes.append(ProbeOutcome( ticker=row.ticker, date=row.date, actual=float(row.close), predicted=predicted, relative_error=rel_err, )) n = len(outcomes) n_parse = sum(o.predicted is not None for o in outcomes) n_recall = sum( o.relative_error is not None and o.relative_error <= recall_tolerance for o in outcomes ) return { "model_id": model_id, "base_url": base_url, "panel_path": str(panel_path), "first_half_end": first_half_end, "n_samples": n, "n_parse_success": n_parse, "n_recall_within_tol": n_recall, "recall_rate": n_recall / n if n else 0.0, "parse_rate": n_parse / n if n else 0.0, "recall_tolerance": recall_tolerance, "seed": seed, "outcomes": [asdict(o) for o in outcomes], } # --------------------------------------------------------------------------- # CLI # --------------------------------------------------------------------------- def _default_panel_path() -> Path: from projects.agent_builder.scripts.whatif_bench import config base = Path(config.DATA_DIR) if hasattr(config, "DATA_DIR") else ( Path(__file__).resolve().parents[2] / "data_small_caps" ) return base / "benchmark" / "daily" / "panel_test.parquet" def main() -> int: parser = argparse.ArgumentParser( description="Contamination probe for LLM baselines (closing-price recall).", ) parser.add_argument("--model-id", required=True, help="HuggingFace identifier or OpenRouter model slug.") parser.add_argument("--base-url", required=True, help="OpenAI-compatible endpoint URL (e.g., http://localhost:8004/v1).") parser.add_argument("--n-samples", type=int, default=200, help="Number of (ticker, date) pairs to probe.") parser.add_argument("--first-half-end", default="2025-06-30", help="Last date (inclusive) of the first-half window.") parser.add_argument("--seed", type=int, default=42) parser.add_argument("--api-key", default=os.environ.get("OPENAI_API_KEY", "EMPTY")) parser.add_argument("--panel-path", type=Path, default=None, help="Override the default panel parquet path.") parser.add_argument("--recall-tolerance", type=float, default=0.05, help="Relative-error threshold for counting a sample as 'recalled'.") parser.add_argument("--output", type=Path, required=True, help="Path to write the JSON probe report.") args = parser.parse_args() logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") panel_path = args.panel_path or _default_panel_path() if not panel_path.exists(): logger.error("panel path %s does not exist", panel_path) return 2 report = probe_closing_prices( panel_path=panel_path, model_id=args.model_id, base_url=args.base_url, n_samples=args.n_samples, first_half_end=args.first_half_end, seed=args.seed, api_key=args.api_key, recall_tolerance=args.recall_tolerance, ) args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(report, indent=2)) logger.info( "probe finished: model=%s recall=%.2f%% (%d/%d within %.1f%% tol); parse=%.2f%% (%d/%d); report=%s", args.model_id, 100 * report["recall_rate"], report["n_recall_within_tol"], report["n_samples"], 100 * report["recall_tolerance"], 100 * report["parse_rate"], report["n_parse_success"], report["n_samples"], args.output, ) return 0 if __name__ == "__main__": raise SystemExit(main())