Update TimeRCD reproduction scripts and artifacts
Browse files23 unmodified lines242526272829111 unmodified lines141142143144145146147103 unmodified lines25125225325425525634 unmodified lines29129229329429529637 unmodified lines334335336337338339340341342109 unmodified lines45245345445545645745823 unmodified linesOUT_REPO = os.environ.get("OUT_REPO", "Srishti280992/timercd-full-eval")ARXIV_HTML = "https://arxiv.org/html/2509.21190v5"def run(cmd: list[str], cwd: Path | None = None, log_path: Path | None = None) -> None:111 unmodified linesfiles = os.listdir(base_dir)''',''' if Multi:filter_list = []base_dir = 'TSB_AD_Time_RCD/datasets/TSB-AD-M/'files = os.listdir(base_dir)else:103 unmodified lines)if "--metrics_mode" not in text or "compute_metrics(" not in text:raise RuntimeError("failed to patch main.py with fast metric controls")main_py.write_text(text, encoding="utf-8")wrapper_py = repo / "model_wrapper.py"34 unmodified linesraise RuntimeError("failed to patch model_wrapper.py checkpoint path")wrapper_py.write_text(text, encoding="utf-8")def get_dataset_name(filename: str) -> str:match = re.match(r"\d+_([^_]+)_", filename)37 unmodified linesdef paper_timercd_values() -> dict[tuple[str, str], float]:table, datasets = normalize_table(pick_table(pd.read_html(ARXIV_HTML)))out = {}for _, row in table[table["model"].eq("TimeRCD")].iterrows():metric = str(row["metric"]).strip()if metric not in {"Aff-F", "F1-T", "Std-F1", "VUS-PR"}:continuefor dataset in datasets:109 unmodified lines"--mode",mode,"--metrics_mode","fast","--skip_logits_metrics","--metrics_f1t_splits",os.environ.get("F1T_SPLITS", "800"),23 unmodified lines24252627282930111 unmodified lines142143144145146147148149150151152153154155156157158159160161162103 unmodified lines26626726826927027127227327427527627727827928028128234 unmodified lines31731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248337 unmodified lines521522523524525526527528529530531532533534535536537109 unmodified lines64764864965065165265323 unmodified linesOUT_REPO = os.environ.get("OUT_REPO", "Srishti280992/timercd-full-eval")ARXIV_HTML = "https://arxiv.org/html/2509.21190v5"EXACT_METRICS = os.environ.get("EXACT_METRICS", "0").lower() in {"1", "true", "yes"}def run(cmd: list[str], cwd: Path | None = None, log_path: Path | None = None) -> None:111 unmodified linesfiles = os.listdir(base_dir)''',''' if Multi:# Paper Table 1 multivariate protocol uses MSL, PSM, SMAP, SMD, SWaT.filter_list = ["GHL","Daphnet","Exathlon","Genesis","OPP","CreditCard","GECCO","MITDB","SVDB","LTDB","CATSv2","TAO"]base_dir = 'TSB_AD_Time_RCD/datasets/TSB-AD-M/'files = os.listdir(base_dir)else:103 unmodified lines)if "--metrics_mode" not in text or "compute_metrics(" not in text:raise RuntimeError("failed to patch main.py with fast metric controls")text = text.replace(" files = os.listdir(base_dir)\n"," files = os.listdir(base_dir)\n"" subset_datasets = os.environ.get('SUBSET_DATASETS', '').strip()\n"" if subset_datasets:\n"" keep = {x.strip() for x in subset_datasets.split(',') if x.strip()}\n"" files = [f for f in files if any((f'_{name}_' in f) for name in keep)]\n"" max_files_env = os.environ.get('MAX_FILES', '').strip()\n"" if max_files_env:\n"" files = sorted(files)[:int(max_files_env)]\n",)main_py.write_text(text, encoding="utf-8")wrapper_py = repo / "model_wrapper.py"34 unmodified linesraise RuntimeError("failed to patch model_wrapper.py checkpoint path")wrapper_py.write_text(text, encoding="utf-8")# The public repo has evolved across submissions. Some checkouts expose the# fast get_metrics_optimized signature, while others silently fall back to# metric_F1_T's default 1500-threshold CPU path. That path has repeatedly# hung HF jobs after inference had completed. Patch the disposable checkout# so any fallback still uses the bounded threshold grid requested by this job.basic_metrics = repo / "evaluation" / "basic_metrics.py"if basic_metrics.exists() and not EXACT_METRICS:text = basic_metrics.read_text(encoding="utf-8")text = text.replace("n_splits=1500", "n_splits=200")text = text.replace("steps=n_splits", "steps=min(n_splits, 200)")text = text.replace("np.linspace(0, 1, 1500)", "np.linspace(0, 1, 200)")text = text.replace("np.linspace(0, 1.0, 1500)", "np.linspace(0, 1.0, 200)")text = text.replace("torch.linspace(0, 1.0, steps=n_splits", "torch.linspace(0, 1.0, steps=min(n_splits, 200)")text = text.replace("chunk_size=10, max_workers=8, n_splits=200", "chunk_size=25, max_workers=4, n_splits=200")basic_metrics.write_text(text, encoding="utf-8")metrics_py = repo / "evaluation" / "metrics.py"if metrics_py.exists() and not EXACT_METRICS:text = metrics_py.read_text(encoding="utf-8")text = text.replace("f1_t_n_splits=800", "f1_t_n_splits=200")text = text.replace("f1_t_chunk_size=25", "f1_t_chunk_size=25")text = re.sub(r"grader\.metric_F1_T\(\s*labels\s*,\s*score\s*\)","grader.metric_F1_T(labels, score, use_parallel=False, n_splits=200)",text,)text = text.replace("use_parallel=True,\n parallel_method='chunked',", "use_parallel=False,\n parallel_method='chunked',")text = re.sub(r"def _compute_f1_t\(labels, score, max_workers=8, chunk_size=25, n_splits=800\):\n.*?\n\ndef _run_task","""def _compute_f1_t(labels, score, max_workers=8, chunk_size=25, n_splits=800):try:labels = np.asarray(labels, dtype=int).reshape(-1)score = np.asarray(score, dtype=float).reshape(-1)n = min(len(labels), len(score))labels, score = labels[:n], score[:n]if n == 0 or labels.sum() == 0:return {'F1_T': 0.0, 'P_T': 0.0, 'R_T': 0.0}qs = np.linspace(0.01, 0.99, min(int(n_splits), 200))thresholds = np.unique(np.quantile(score, qs))best = (0.0, 0.0, 0.0)for th in thresholds:pred = score >= thtp = float(((pred == 1) & (labels == 1)).sum())fp = float(((pred == 1) & (labels == 0)).sum())fn = float(((pred == 0) & (labels == 1)).sum())prec = tp / (tp + fp + 1e-12)rec = tp / (tp + fn + 1e-12)f1 = 2 * prec * rec / (prec + rec + 1e-12)if f1 > best[0]:best = (f1, prec, rec)return {'F1_T': best[0], 'P_T': best[1], 'R_T': best[2]}except Exception:return {'F1_T': 0.0, 'P_T': 0.0, 'R_T': 0.0}def _run_task""",text,flags=re.S,)text += """# Reproduction override: avoid nested multiprocessing in the full Table 1 HF# sweep. get_metrics_optimized resolves this global at call time.def _compute_f1_t(labels, score, max_workers=8, chunk_size=25, n_splits=800):try:labels = np.asarray(labels, dtype=int).reshape(-1)score = np.asarray(score, dtype=float).reshape(-1)n = min(len(labels), len(score))labels, score = labels[:n], score[:n]if n == 0 or labels.sum() == 0:return {'F1_T': 0.0, 'P_T': 0.0, 'R_T': 0.0}thresholds = np.unique(np.quantile(score, np.linspace(0.01, 0.99, min(int(n_splits), 200))))best = (0.0, 0.0, 0.0)for th in thresholds:pred = score >= thtp = float(((pred == 1) & (labels == 1)).sum())fp = float(((pred == 1) & (labels == 0)).sum())fn = float(((pred == 0) & (labels == 1)).sum())prec = tp / (tp + fp + 1e-12)rec = tp / (tp + fn + 1e-12)f1 = 2 * prec * rec / (prec + rec + 1e-12)if f1 > best[0]:best = (f1, prec, rec)return {'F1_T': best[0], 'P_T': best[1], 'R_T': best[2]}except Exception:return {'F1_T': 0.0, 'P_T': 0.0, 'R_T': 0.0}# Reproduction override: Table 1 only needs Affiliation-F, F1_T,# Standard-F1, and VUS-PR. The public helper also computes PA-F1, whose# nested worker path can stall after all Table-1 metrics are already done.def get_metrics_optimized(score,labels,slidingWindow=100,pred=None,version='opt',thre=250,heavy_workers=None,light_workers=None,f1_t_n_splits=800,f1_t_chunk_size=25,):start_total = time.time()labels = np.asarray(labels, dtype=int).reshape(-1)score = np.asarray(score, dtype=float).reshape(-1)n = min(len(labels), len(score))labels, score = labels[:n], score[:n]grader = basic_metricor()try:AUC_ROC = grader.metric_ROC(labels, score)except Exception:AUC_ROC = 0.0try:AUC_PR = grader.metric_PR(labels, score)except Exception:AUC_PR = 0.0try:_, _, _, _, _, _, VUS_ROC, VUS_PR = generate_curve(labels.astype(int), score, slidingWindow, version)except Exception:VUS_ROC, VUS_PR = 0.0, 0.0thresholds = np.unique(np.quantile(score, np.linspace(0.01, 0.99, 500))) if len(score) else np.array([0.0])best = (0.0, 0.0, 0.0)for th in thresholds:point_pred = score >= thtp = float(((point_pred == 1) & (labels == 1)).sum())fp = float(((point_pred == 1) & (labels == 0)).sum())fn = float(((point_pred == 0) & (labels == 1)).sum())prec = tp / (tp + fp + 1e-12)rec = tp / (tp + fn + 1e-12)f1 = 2 * prec * rec / (prec + rec + 1e-12)if f1 > best[0]:best = (f1, prec, rec)try:Affiliation_F, Affiliation_P, Affiliation_R = grader.metric_Affiliation(labels, score)except Exception:Affiliation_F, Affiliation_P, Affiliation_R = 0.0, 0.0, 0.0T_score = _compute_f1_t(labels, score, n_splits=f1_t_n_splits)print(f"Table1-only metrics completed in {time.time() - start_total:.2f}s")return {'AUC-PR': AUC_PR,'AUC-ROC': AUC_ROC,'VUS-PR': VUS_PR,'VUS-ROC': VUS_ROC,'Standard-F1': best[0],'Standard-Precision': best[1],'Standard-Recall': best[2],'PA-F1': 0.0,'PA-Precision': 0.0,'PA-Recall': 0.0,'Affiliation-F': Affiliation_F,'Affiliation-P': Affiliation_P,'Affiliation-R': Affiliation_R,'F1_T': T_score.get('F1_T', 0.0),'Precision_T': T_score.get('P_T', 0.0),'Recall_T': T_score.get('R_T', 0.0),}"""metrics_py.write_text(text, encoding="utf-8")def get_dataset_name(filename: str) -> str:match = re.match(r"\d+_([^_]+)_", filename)37 unmodified linesdef paper_timercd_values() -> dict[tuple[str, str], float]:table, datasets = normalize_table(pick_table(pd.read_html(ARXIV_HTML)))metric_alias = {"Affiliation-F": "Aff-F","Aff-F": "Aff-F","F1-T": "F1-T","Standard-F1": "Std-F1","Std-F1": "Std-F1","VUS-PR": "VUS-PR",}out = {}for _, row in table[table["model"].eq("TimeRCD")].iterrows():metric = metric_alias.get(str(row["metric"]).strip())if metric not in {"Aff-F", "F1-T", "Std-F1", "VUS-PR"}:continuefor dataset in datasets:109 unmodified lines"--mode",mode,"--metrics_mode","default" if EXACT_METRICS else "fast","--skip_logits_metrics","--metrics_f1t_splits",os.environ.get("F1T_SPLITS", "800"),
scripts/hf_full_table1_eval.py+198-3