File size: 9,563 Bytes
5cc5437 | 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 | #!/usr/bin/env python3
"""Inspect TimeRCD released code, checkpoints, and synthetic generator.
This is designed as a lightweight, reproducible evidence pass: no full benchmark
sweep, but enough to verify architecture, released-weight scale, generator stages,
and plausible synthetic-corpus throughput.
"""
from __future__ import annotations
import ast
import json
import os
import random
import re
import sys
import time
from pathlib import Path
import numpy as np
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "outputs" / "deep_repro"
TIME_RCD = ROOT / "official_Time-RCD"
GEN = ROOT / "official_TSAD_dataset_gen_public"
def read(path: Path) -> str:
return path.read_text(encoding="utf-8", errors="ignore")
def config_defaults() -> dict[str, object]:
source = read(TIME_RCD / "models" / "time_rcd" / "time_rcd_config.py")
tree = ast.parse(source)
defaults: dict[str, dict[str, object]] = {}
for node in ast.walk(tree):
if isinstance(node, ast.ClassDef) and node.name in {"TimeSeriesConfig", "TimeRCDConfig"}:
defaults[node.name] = {}
for stmt in node.body:
if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name):
try:
defaults[node.name][stmt.target.id] = ast.literal_eval(stmt.value)
except Exception:
defaults[node.name][stmt.target.id] = ast.unparse(stmt.value)
return defaults
def checkpoint_summary() -> dict[str, object]:
ckpt_paths = sorted((TIME_RCD / "best_model").glob("*.pth"))
summary: dict[str, object] = {"checkpoint_files": [str(p.relative_to(ROOT)) for p in ckpt_paths]}
if not ckpt_paths:
summary["status"] = "no checkpoint files present"
return summary
try:
import torch
except Exception as exc: # pragma: no cover - environment fallback
summary["status"] = f"torch import failed: {exc}"
return summary
rows: list[dict[str, object]] = []
for path in ckpt_paths:
raw = torch.load(path, map_location="cpu")
state = raw.get("model_state_dict", raw) if isinstance(raw, dict) else raw
tensors = {k.removeprefix("module."): v for k, v in state.items() if hasattr(v, "numel")}
total = int(sum(v.numel() for v in tensors.values()))
head_keys = [k for k in tensors if "head" in k]
rows.append(
{
"file": str(path.relative_to(ROOT)),
"tensors": len(tensors),
"parameters": total,
"parameters_millions": round(total / 1_000_000, 3),
"has_reconstruction_head_weights": any("reconstruction_head" in k for k in tensors),
"has_anomaly_head_weights": any("anomaly_head" in k for k in tensors),
"head_key_sample": head_keys[:12],
}
)
summary["status"] = "loaded"
summary["checkpoints"] = rows
return summary
def architecture_audit() -> dict[str, object]:
pretrain = read(TIME_RCD / "models" / "time_rcd" / "TimeRCD_pretrain_multi.py")
encoder = read(TIME_RCD / "models" / "time_rcd" / "ts_encoder_bi_bias.py")
wrapper = read(TIME_RCD / "model_wrapper.py")
config = config_defaults()
ts_config = config.get("TimeSeriesConfig", {})
return {
"repo": "https://github.com/thu-sail-lab/Time-RCD",
"hf_model": "https://huggingface.co/thu-sail-lab/Time-RCD",
"config_defaults": config,
"is_standard_transformer_encoder_family": "nn.TransformerEncoder" in encoder
or "TransformerEncoderLayerWithRoPE" in encoder,
"encoder_layers": ts_config.get("num_layers"),
"hidden_size": ts_config.get("d_model"),
"num_attention_heads": ts_config.get("num_heads"),
"has_reconstruction_head": "self.reconstruction_head" in pretrain,
"has_anomaly_head": "self.anomaly_head" in pretrain,
"reconstruction_loss_in_training": "F.mse_loss" in pretrain and "reconstruction" in pretrain,
"anomaly_loss_in_training": "F.cross_entropy" in pretrain and "anomaly" in pretrain,
"zero_shot_inference_uses_anomaly_logits": "score_list, logit_list = cls.zero_shot(data)" in wrapper
and "logit" in wrapper,
"source_snippets": {
"heads": [line.strip() for line in pretrain.splitlines() if "self.reconstruction_head" in line or "self.anomaly_head" in line][:8],
"loss_terms": [line.strip() for line in pretrain.splitlines() if "F.mse_loss" in line or "F.cross_entropy" in line][:8],
},
}
def generator_audit() -> dict[str, object]:
gen = read(GEN / "src" / "generate_dataset.py")
uni = read(GEN / "src" / "ts_generator.py")
multi = read(GEN / "src" / "ts_multi_generator.py")
trend = read(GEN / "src" / "trend_utils.py")
config_src = read(GEN / "src" / "config.py")
cfg = json.loads(read(GEN / "config" / "synthetic.json"))
anomaly_types = sorted(set(re.findall(r"anomaly_type\s*==\s*['\"]([^'\"]+)['\"]", uni + multi)))
explicit_types = sorted(set(re.findall(r"['\"]([a-zA-Z_]+_anomaly|[a-zA-Z_]+_change|[a-zA-Z_]+_shift)['\"]", uni + multi)))
return {
"repo": "https://github.com/thu-sail-lab/TSAD_dataset_gen_public",
"config": cfg,
"stage_1_context_templates": all(token in uni + trend + config_src for token in ("generate_trend", "generate_seasonal", "generate_noise")),
"stage_2_joint_context_fusion": "generate_random_dag" in multi
and "nx.is_directed_acyclic_graph" in multi
and "y_0[t] = a * y_0[t - 1]" in multi,
"stage_3_causal_contextual_injection": "is_endogenous = random.choice([True, False])" in multi
and all(token in uni for token in ("generate_local_chars", "seasonal_anomalies", "y_abnormal")),
"stage_4_token_level_labels": "'labels': labels" in gen and "labels = labels | labels_i" in multi,
"arx_clamp_present": "COEFF_A_MIN = -0.8" in multi and "COEFF_A_MAX = 0.8" in multi,
"observed_anomaly_type_names": sorted(set(anomaly_types + explicit_types))[:80],
"label_decay_rule_found": "half" in gen.lower() or "decay" in gen.lower() or "halflife" in gen.lower(),
}
def throughput_probe(samples: int = 120) -> dict[str, object]:
sys.path.insert(0, str(GEN / "src"))
old_cwd = Path.cwd()
os.chdir(GEN)
from generate_dataset import generate_dataset
random.seed(2026)
np.random.seed(2026)
lengths = np.random.default_rng(2026).integers(100, 10001, size=samples).tolist()
total_points = 0
generated = 0
started = time.perf_counter()
try:
for length in lengths:
batch = generate_dataset(
num_samples=1,
seq_len=int(length),
anomaly_sample_ratio=1.0,
is_multivariate=False,
use_attribute_set=True,
num_workers=1,
)
item = batch[0]
series = item.get("time_series", item.get("timeseries"))
total_points += int(np.asarray(series).size)
generated += 1
finally:
os.chdir(old_cwd)
elapsed = time.perf_counter() - started
points_per_second = total_points / elapsed if elapsed else 0.0
return {
"samples": generated,
"min_length": int(min(lengths)),
"max_length": int(max(lengths)),
"total_points": total_points,
"elapsed_seconds": round(elapsed, 3),
"points_per_second": round(points_per_second, 1),
"estimated_hours_for_2_5b_at_this_rate": round(2_500_000_000 / points_per_second / 3600, 2)
if points_per_second
else None,
}
def main() -> None:
OUT.mkdir(parents=True, exist_ok=True)
result = {
"architecture": architecture_audit(),
"checkpoints": checkpoint_summary(),
"generator": generator_audit(),
"throughput_probe": throughput_probe(),
}
path = OUT / "timercd_deep_audit.json"
path.write_text(json.dumps(result, indent=2), encoding="utf-8")
arch = result["architecture"]
ckpt = result["checkpoints"]
gen = result["generator"]
thr = result["throughput_probe"]
print(
f"architecture: layers={arch['encoder_layers']} hidden={arch['hidden_size']} "
f"heads={arch['num_attention_heads']} dual_heads="
f"{arch['has_reconstruction_head'] and arch['has_anomaly_head']} "
f"inference_logits={arch['zero_shot_inference_uses_anomaly_logits']}"
)
if ckpt.get("status") == "loaded":
for row in ckpt["checkpoints"]:
print(
f"checkpoint: {row['file']} params={row['parameters_millions']}M "
f"recon_head={row['has_reconstruction_head_weights']} "
f"anomaly_head={row['has_anomaly_head_weights']}"
)
else:
print(f"checkpoint: {ckpt.get('status')}")
print(
"generator stages: "
f"template={gen['stage_1_context_templates']} "
f"dag_arx={gen['stage_2_joint_context_fusion']} "
f"injection={gen['stage_3_causal_contextual_injection']} "
f"labels={gen['stage_4_token_level_labels']} "
f"label_decay_found={gen['label_decay_rule_found']}"
)
print(
f"throughput: {thr['total_points']} points in {thr['elapsed_seconds']}s "
f"({thr['points_per_second']} pts/s), 2.5B estimate "
f"{thr['estimated_hours_for_2_5b_at_this_rate']} h"
)
print(f"wrote {path}")
if __name__ == "__main__":
main()
|