File size: 9,969 Bytes
ff4becd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 | """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())
|