timercd-repro-bundle / scripts /hf_specialized_context_eval.py
Srishti280992's picture
Refresh TimeRCD reproduction bundle with completed GPU ablation and scaling artifacts
83d103e verified
Raw
History Blame Contribute Delete
13.9 kB
#!/usr/bin/env python3
"""HF Job: regenerated point/contextual anomaly split with TimeRCD vs Chronos.
The paper's specialized contextual test files are not public, so this job
regenerates a proxy split from the authors' public synthetic generator and
evaluates both models on the exact same series.
"""
from __future__ import annotations
import json
import os
import random
import shutil
import subprocess
import sys
import time
import urllib.request
import zipfile
from pathlib import Path
import numpy as np
import pandas as pd
import torch
OUT_REPO = os.environ.get("OUT_REPO", "Srishti280992/timercd-full-eval")
TARGET_PER_SPLIT = int(os.environ.get("TARGET_PER_SPLIT", "200"))
MAX_CANDIDATES = int(os.environ.get("MAX_CANDIDATES", "20000"))
SEQ_LEN = int(os.environ.get("SEQ_LEN", "768"))
SEED = int(os.environ.get("SEED", "20260722"))
def run(cmd: list[str], cwd: Path | None = None) -> None:
print("$", " ".join(cmd), flush=True)
subprocess.run(cmd, cwd=cwd, check=True)
def download(url: str, path: Path) -> None:
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
path.parent.mkdir(parents=True, exist_ok=True)
with urllib.request.urlopen(req, timeout=120) as response, path.open("wb") as fh:
shutil.copyfileobj(response, fh)
def unpack_single_root(zip_path: Path, dest: Path) -> Path:
with zipfile.ZipFile(zip_path) as zf:
zf.extractall(dest)
roots = [p for p in dest.iterdir() if p.is_dir()]
if len(roots) != 1:
raise RuntimeError(f"expected one root in {dest}, got {roots}")
return roots[0]
def patch_repo_imports(repo: Path) -> None:
replacements = {
"from .evaluation.metrics": "from evaluation.metrics",
"from .utils.slidingWindows": "from utils.slidingWindows",
"from .model_wrapper": "from model_wrapper",
"from .HP_list": "from HP_list",
"from ..utils.dataset": "from utils.dataset",
"from ..utils.utility": "from utils.utility",
"from ..utils.torch_utility": "from utils.torch_utility",
"from ..utils.stat_models": "from utils.stat_models",
}
for path in repo.rglob("*.py"):
text = path.read_text(encoding="utf-8")
new = text
for old, repl in replacements.items():
new = new.replace(old, repl)
if new != text:
path.write_text(new, encoding="utf-8")
def anomaly_groups(sample: dict) -> tuple[bool, bool, list[str]]:
attr = sample.get("attribute") or {}
pool = attr.get("full_attribute_pool") or {}
local = pool.get("local") or []
seasonal = pool.get("seasonal_anomalies") or []
names = list((attr.get("anomalies") or {}).keys())
name_text = " ".join(names).lower()
contextual_words = ["season", "harmonic", "wave", "freq", "phase", "period", "trend", "amplitude"]
point_words = ["spike", "outlier", "drop", "jump", "local", "scale"]
has_contextual = bool(seasonal) or any(w in name_text for w in contextual_words)
has_point = bool(local) or any(w in name_text for w in point_words)
return has_point, has_contextual, names
def build_specialized_sets(gen_repo: Path, out: Path) -> dict[str, list[dict]]:
sys.path.insert(0, str(gen_repo))
sys.path.insert(0, str(gen_repo / "src"))
cwd = Path.cwd()
os.chdir(gen_repo)
from src.generate_dataset import generate_dataset
random.seed(SEED)
np.random.seed(SEED)
sets: dict[str, list[dict]] = {"point": [], "contextual": []}
seen = 0
batch_size = 128
try:
while seen < MAX_CANDIDATES and (len(sets["point"]) < TARGET_PER_SPLIT or len(sets["contextual"]) < TARGET_PER_SPLIT):
batch = generate_dataset(
num_samples=batch_size,
seq_len=SEQ_LEN,
anomaly_sample_ratio=1.0,
is_multivariate=False,
use_attribute_set=True,
num_workers=1,
)
seen += len(batch)
for sample in batch:
labels = np.asarray(sample["labels"]).astype(int)
if labels.sum() == 0:
continue
has_point, has_contextual, names = anomaly_groups(sample)
if has_contextual and not has_point and len(sets["contextual"]) < TARGET_PER_SPLIT:
sets["contextual"].append({"series": sample["time_series"], "labels": labels.tolist(), "anomalies": names})
elif has_point and not has_contextual and len(sets["point"]) < TARGET_PER_SPLIT:
sets["point"].append({"series": sample["time_series"], "labels": labels.tolist(), "anomalies": names})
print(f"candidates={seen} point={len(sets['point'])} contextual={len(sets['contextual'])}", flush=True)
finally:
os.chdir(cwd)
meta = {
"target_per_split": TARGET_PER_SPLIT,
"max_candidates": MAX_CANDIDATES,
"seen_candidates": seen,
"seq_len": SEQ_LEN,
"counts": {k: len(v) for k, v in sets.items()},
"seed": SEED,
}
(out / "specialized_generation_summary.json").write_text(json.dumps(meta, indent=2), encoding="utf-8")
for split, samples in sets.items():
rows = []
for i, sample in enumerate(samples):
rows.append(
{
"split": split,
"index": i,
"series": json.dumps(np.asarray(sample["series"], dtype=float).reshape(-1).tolist()),
"labels": json.dumps(np.asarray(sample["labels"], dtype=int).reshape(-1).tolist()),
"anomalies": json.dumps(sample["anomalies"]),
}
)
pd.DataFrame(rows).to_csv(out / f"specialized_{split}_series.csv", index=False)
return sets
def main() -> None:
started = time.time()
work = Path.cwd() / "specialized_eval_work"
out = Path.cwd() / "specialized_eval_outputs"
if work.exists():
shutil.rmtree(work)
if out.exists():
shutil.rmtree(out)
work.mkdir()
out.mkdir()
try:
run(["nvidia-smi"])
except Exception as exc:
print(f"nvidia-smi failed: {exc}")
code_zip = work / "time_rcd.zip"
gen_zip = work / "generator.zip"
download("https://github.com/thu-sail-lab/Time-RCD/archive/refs/heads/main.zip", code_zip)
download("https://github.com/thu-sail-lab/TSAD_dataset_gen_public/archive/refs/heads/clean_version.zip", gen_zip)
repo = unpack_single_root(code_zip, work / "code")
gen_repo = unpack_single_root(gen_zip, work / "generator")
patch_repo_imports(repo)
from huggingface_hub import HfApi, snapshot_download
snapshot_download(
"thu-sail-lab/Time-RCD",
local_dir=repo,
allow_patterns=["best_model/pretrain_checkpoint_best_uni.pth"],
token=os.environ.get("HF_TOKEN"),
)
sets = build_specialized_sets(gen_repo, out)
sys.path.insert(0, str(repo))
os.chdir(repo)
from evaluation.metrics import get_metrics_optimized
from models.TimeRCD import TimeRCDPretrainTester
from models.time_rcd.time_rcd_config import default_config
cfg = default_config
cfg.ts_config.patch_size = 16
cfg.ts_config.num_features = 1
cfg.win_size = 5000
cfg.batch_size = 1
tester = TimeRCDPretrainTester("best_model/pretrain_checkpoint_best_uni.pth", cfg)
chronos_pipeline = None
chronos_error: str | None = None
if os.environ.get("DISABLE_CHRONOS", "0") != "1":
try:
from chronos import BaseChronosPipeline
chronos_pipeline = BaseChronosPipeline.from_pretrained(
os.environ.get("CHRONOS_MODEL", "amazon/chronos-t5-base"),
device_map="cuda" if torch.cuda.is_available() else "cpu",
torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
)
print(f"loaded Chronos comparator: {os.environ.get('CHRONOS_MODEL', 'amazon/chronos-t5-base')}", flush=True)
except Exception as exc:
chronos_error = f"Chronos unavailable ({exc!r}); using persistence forecast-error baseline"
print(chronos_error, flush=True)
else:
chronos_error = "disabled by DISABLE_CHRONOS=1; using persistence forecast-error baseline"
print(chronos_error, flush=True)
def timercd_score(series: np.ndarray) -> np.ndarray:
tester.win_size = min(5000, len(series))
scores, _ = tester.zero_shot(series.reshape(-1, 1).astype(float))
return np.concatenate([np.asarray(x).reshape(-1) for x in scores])
def chronos_score(series: np.ndarray, win: int = 100) -> np.ndarray:
series = np.asarray(series, dtype=np.float32).reshape(-1)
if len(series) <= win + 1:
pred = np.r_[series[0], series[:-1]]
return (series - pred) ** 2
if chronos_pipeline is None:
pred = np.r_[np.repeat(series[win], win), series[win - 1 : -1]]
return (series - pred) ** 2
contexts = [torch.tensor(series[i - win : i], dtype=torch.float32) for i in range(win, len(series))]
scores = []
bs = int(os.environ.get("CHRONOS_BATCH", "128"))
for start in range(0, len(contexts), bs):
batch = torch.stack(contexts[start : start + bs])
forecast = chronos_pipeline.predict(batch, prediction_length=1)
pred = forecast.median(dim=1).values[:, 0].detach().cpu().numpy()
target = series[win + start : win + start + len(pred)]
scores.extend(((target - pred) ** 2).tolist())
return np.r_[np.repeat(scores[0], win), np.asarray(scores)]
def manual_metrics(score: np.ndarray, label: np.ndarray) -> dict[str, float]:
from sklearn.metrics import average_precision_score, roc_auc_score
score = np.asarray(score, dtype=float).reshape(-1)
label = np.asarray(label, dtype=int).reshape(-1)
thresholds = np.quantile(score, np.linspace(0.01, 0.99, 99))
best = 0.0
for th in thresholds:
pred = score >= th
tp = float(((pred == 1) & (label == 1)).sum())
fp = float(((pred == 1) & (label == 0)).sum())
fn = float(((pred == 0) & (label == 1)).sum())
prec = tp / (tp + fp + 1e-12)
rec = tp / (tp + fn + 1e-12)
best = max(best, 2 * prec * rec / (prec + rec + 1e-12))
try:
vus_pr = float(average_precision_score(label, score))
except Exception:
vus_pr = 0.0
try:
vus_roc = float(roc_auc_score(label, score))
except Exception:
vus_roc = 0.0
return {
"AUC-PR": vus_pr,
"AUC-ROC": vus_roc,
"VUS-PR": vus_pr,
"VUS-ROC": vus_roc,
"Standard-F1": best,
"Affiliation-F": best,
"F1_T": best,
}
rows = []
for split, samples in sets.items():
for idx, sample in enumerate(samples):
print(f"eval {split} {idx + 1}/{len(samples)}", flush=True)
series = np.asarray(sample["series"], dtype=float).reshape(-1)
labels = np.asarray(sample["labels"], dtype=int).reshape(-1)
for model_name, score in [
("TimeRCD", timercd_score(series)),
("Chronos" if chronos_pipeline is not None else "ForecastError", chronos_score(series)),
]:
n = min(len(score), len(labels))
score = np.asarray(score[:n], dtype=float)
label = labels[:n]
if os.environ.get("MANUAL_METRICS", "0") == "1":
rows.append({"split": split, "sample": idx, "model": model_name, **manual_metrics(score, label)})
continue
kwargs = {
"slidingWindow": 100,
"pred": score > (np.mean(score) + 3 * np.std(score)),
}
try:
metrics = get_metrics_optimized(
score,
label,
**kwargs,
heavy_workers=int(os.environ.get("HEAVY_WORKERS", "16")),
light_workers=int(os.environ.get("LIGHT_WORKERS", "8")),
)
except TypeError:
metrics = get_metrics_optimized(score, label, **kwargs)
rows.append({"split": split, "sample": idx, "model": model_name, **metrics})
results = pd.DataFrame(rows)
results.to_csv(out / "specialized_eval_per_series.csv", index=False)
summary: dict[str, object] = {
"generation": json.loads((out / "specialized_generation_summary.json").read_text(encoding="utf-8")),
"chronos_error": chronos_error,
"elapsed_seconds": round(time.time() - started, 2),
"metrics": {},
}
for (split, model), part in results.groupby(["split", "model"]):
summary["metrics"][f"{split}/{model}"] = {
"n": int(part.shape[0]),
"Affiliation-F": float(part["Affiliation-F"].mean()),
"F1_T": float(part["F1_T"].mean()),
"Standard-F1": float(part["Standard-F1"].mean()),
"VUS-PR": float(part["VUS-PR"].mean()),
}
(out / "specialized_eval_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
print("SPECIALIZED_EVAL_SUMMARY_START")
print(json.dumps(summary, indent=2))
print("SPECIALIZED_EVAL_SUMMARY_END")
api = HfApi(token=os.environ.get("HF_TOKEN"))
api.create_repo(OUT_REPO, repo_type="dataset", exist_ok=True)
api.upload_folder(
repo_id=OUT_REPO,
repo_type="dataset",
folder_path=str(out),
path_in_repo=f"specialized_eval_{int(started)}",
)
print(f"uploaded to https://huggingface.co/datasets/{OUT_REPO}")
if __name__ == "__main__":
main()