File size: 5,730 Bytes
2044e6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Small HF Jobs probe for the TimeRCD reproduction.

Runs on a GPU flavor to satisfy the challenge's cloud-execution expectation,
but keeps the experiment scoped to public-code generator and RCD mechanism
checks rather than expensive checkpoint pretraining.
"""

from __future__ import annotations

import json
import os
import random
import subprocess
import sys
import time
from pathlib import Path

import numpy as np


def sh(cmd: list[str], cwd: Path | None = None) -> str:
    proc = subprocess.run(cmd, cwd=cwd, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=True)
    return proc.stdout


def best_f1(scores: np.ndarray, labels: np.ndarray) -> dict:
    thresholds = np.unique(np.quantile(scores, np.linspace(0, 1, 151)))
    best = {"f1": -1.0, "threshold": 0.0, "precision": 0.0, "recall": 0.0}
    for th in thresholds:
        pred = scores >= th
        tp = int(np.sum(pred & (labels == 1)))
        fp = int(np.sum(pred & (labels == 0)))
        fn = int(np.sum((~pred) & (labels == 1)))
        precision = tp / (tp + fp) if tp + fp else 0.0
        recall = tp / (tp + fn) if tp + fn else 0.0
        f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
        if f1 > best["f1"]:
            best = {"f1": float(f1), "threshold": float(th), "precision": float(precision), "recall": float(recall)}
    return best


def make_contextual(n: int = 80, length: int = 512) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    rng = np.random.default_rng(20260720)
    xs, labels, groups = [], [], []
    for i in range(n):
        t = np.arange(length)
        period = rng.uniform(40, 80)
        phase = rng.uniform(0, 2 * np.pi)
        y = np.sin(2 * np.pi * t / period + phase) + 0.2 * np.sin(2 * np.pi * t / (period / 3))
        y += rng.normal(0, 0.08, length)
        lab = np.zeros(length, dtype=int)
        if i >= n // 2:
            start = int(rng.integers(160, 330))
            width = int(rng.integers(40, 75))
            end = min(length, start + width)
            y[start:end] = 0.25 * np.sin(2 * np.pi * np.arange(end - start) / (period * 0.45) + phase)
            y[start:end] += rng.normal(0, 0.06, end - start)
            lab[start:end] = 1
        xs.append(y)
        labels.append(lab)
        groups.append(np.full(length, i))
    return np.concatenate(xs), np.concatenate(labels), np.concatenate(groups)


def rcd_score(x: np.ndarray, group: np.ndarray) -> np.ndarray:
    out = np.zeros_like(x, dtype=float)
    for g in np.unique(group):
        idx = np.flatnonzero(group == g)
        y = x[idx]
        s = np.zeros_like(y)
        for i in range(len(y)):
            q = y[max(0, i - 15): min(len(y), i + 16)]
            left = y[max(0, i - 96): max(0, i - 15)]
            right = y[min(len(y), i + 16): min(len(y), i + 97)]
            ctx = np.concatenate([left, right]) if left.size + right.size else q
            s[i] = abs(q.mean() - ctx.mean()) + abs(q.std() - ctx.std())
        out[idx] = s
    return out


def reconstruction_like(x: np.ndarray, group: np.ndarray) -> np.ndarray:
    out = np.zeros_like(x, dtype=float)
    for g in np.unique(group):
        idx = np.flatnonzero(group == g)
        y = x[idx]
        pred = np.r_[y[0], y[:-1]]
        out[idx] = np.abs(y - pred)
    return out


def main() -> None:
    root = Path.cwd()
    print("nvidia-smi:")
    try:
        print(sh(["nvidia-smi"]))
    except Exception as exc:
        print(f"nvidia-smi unavailable: {exc}")

    print(sh(["git", "clone", "--depth", "1", "https://github.com/thu-sail-lab/TSAD_dataset_gen_public", "gen"]))
    print(sh(["git", "clone", "--depth", "1", "https://github.com/thu-sail-lab/Time-RCD", "time_rcd"]))

    sys.path.insert(0, str(root / "gen/src"))
    cwd = Path.cwd()
    os.chdir(root / "gen")
    try:
        from generate_dataset import generate_dataset

        random.seed(11)
        np.random.seed(11)
        t0 = time.perf_counter()
        uni = generate_dataset(num_samples=24, seq_len=768, anomaly_sample_ratio=1.0, is_multivariate=False, use_attribute_set=True, num_workers=1)
        multi = generate_dataset(num_samples=8, seq_len=512, anomaly_sample_ratio=1.0, is_multivariate=True, num_features=4, use_attribute_set=True, num_workers=1)
        elapsed = time.perf_counter() - t0
    finally:
        os.chdir(cwd)

    points = int(sum(np.asarray(d["time_series"]).size for d in uni + multi))
    x, y, g = make_contextual()
    rcd = best_f1(rcd_score(x, g), y)
    rec = best_f1(reconstruction_like(x, g), y)
    wrapper = (root / "time_rcd/model_wrapper.py").read_text(encoding="utf-8")
    pretrain = (root / "time_rcd/models/time_rcd/TimeRCD_pretrain_multi.py").read_text(encoding="utf-8")
    summary = {
        "job_kind": "HF t4-small reduced public-code probe",
        "official_generator_samples": len(uni) + len(multi),
        "official_generator_points": points,
        "official_generator_sec": elapsed,
        "official_generator_points_per_sec": points / elapsed,
        "rcd_proxy_best_f1": rcd,
        "reconstruction_like_best_f1": rec,
        "released_code_has_dual_heads": "self.reconstruction_head" in pretrain and "self.anomaly_head" in pretrain,
        "released_code_uses_zero_shot_logits": "score_list, logit_list = cls.zero_shot(data)" in wrapper,
        "links": [
            "https://github.com/thu-sail-lab/TSAD_dataset_gen_public",
            "https://github.com/thu-sail-lab/Time-RCD",
            "https://huggingface.co/thu-sail-lab/Time-RCD",
        ],
    }
    print("HF_TIMRCD_PROBE_SUMMARY_START")
    print(json.dumps(summary, indent=2))
    print("HF_TIMRCD_PROBE_SUMMARY_END")


if __name__ == "__main__":
    main()