File size: 4,308 Bytes
f138992
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""E14: predicting criticality without fault injection (runs on CPU, e.g. M4).

Using only static features of a fault site (which field, which bit, its class,
and the stored value), we train a classifier to predict whether the upset is
catastrophic, without rendering.  A high area under the ROC curve means the
critical bits can be identified from parameter statistics alone, which turns the
expensive injection campaign into a cheap static screen for future models.
"""
import argparse
import glob
import os

import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.metrics import roc_auc_score, roc_curve
from sklearn.preprocessing import StandardScaler

FIELDS = ["means", "scales", "quats", "opacities", "sh0", "shN"]


def load(root):
    X, y = [], []
    for s in sorted(glob.glob(os.path.join(root, "campaign", "shard_*_fp32.npz"))):
        if s.endswith("_guard.npz"):
            continue
        d = np.load(s, allow_pickle=True); a = d["data"]; cols = list(d["cols"]); ci = {c: i for i, c in enumerate(cols)}
        field = a[:, ci["field_id"]]; bit = a[:, ci["bit"]]; bc = a[:, ci["bitclass"]]
        cv = a[:, ci["clean_val"]]; fr = a[:, ci["fracchg"]]; cat = a[:, ci["cat"]]
        fonehot = np.eye(6)[field.astype(int)]
        bconehot = np.eye(3)[bc.astype(int)]
        absv = np.abs(cv); logabs = np.log10(absv + 1e-12); sgn = np.sign(cv)
        feat = np.column_stack([fonehot, bconehot, bit, absv, logabs, sgn])
        lab = ((cat > 0.5) | (fr > 0.01)).astype(int)
        X.append(feat); y.append(lab)
    return np.concatenate(X), np.concatenate(y)


FEATNAMES = (["field=" + f for f in FIELDS] + ["sign", "exp", "mantissa", "bit", "absval", "log|val|", "signval"])


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--root", default="data_local")
    ap.add_argument("--out", default="../generated")
    args = ap.parse_args()
    os.makedirs(args.out, exist_ok=True)
    X, y = load(args.root)
    print(f"samples={len(y)} positives={y.sum()} ({100*y.mean():.2f}%)")
    macros = {}

    Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
    rf = RandomForestClassifier(n_estimators=200, max_depth=10, n_jobs=-1, random_state=0)
    rf.fit(Xtr, ytr)
    p = rf.predict_proba(Xte)[:, 1]
    auc_rf = roc_auc_score(yte, p)

    sc = StandardScaler().fit(Xtr)
    lr = LogisticRegression(max_iter=2000)
    lr.fit(sc.transform(Xtr), ytr)
    auc_lr = roc_auc_score(yte, lr.predict_proba(sc.transform(Xte))[:, 1])

    # field+bit-only model (no value information at all)
    fb_cols = list(range(0, 9)) + [9]  # field one-hot + bitclass + bit
    rf2 = RandomForestClassifier(n_estimators=200, max_depth=8, n_jobs=-1, random_state=0)
    rf2.fit(Xtr[:, fb_cols], ytr)
    auc_fb = roc_auc_score(yte, rf2.predict_proba(Xte[:, fb_cols])[:, 1])

    imp = rf.feature_importances_
    top = FEATNAMES[int(np.argmax(imp))]
    macros["predAUC"] = f"{auc_rf:.3f}"
    macros["predAUClr"] = f"{auc_lr:.3f}"
    macros["predAUCfieldbit"] = f"{auc_fb:.3f}"
    macros["predTopFeat"] = top.replace("=", " ").replace("_", " ")

    fpr, tpr, _ = roc_curve(yte, p)
    plt.figure(figsize=(5.4, 4.2))
    plt.plot(fpr, tpr, label=f"random forest (AUC {auc_rf:.3f})")
    fpr2, tpr2, _ = roc_curve(yte, rf2.predict_proba(Xte[:, fb_cols])[:, 1])
    plt.plot(fpr2, tpr2, "--", label=f"field+bit only (AUC {auc_fb:.3f})")
    plt.plot([0, 1], [0, 1], ":", color="gray")
    plt.xlabel("false positive rate"); plt.ylabel("true positive rate")
    plt.legend(loc="lower right"); plt.grid(alpha=0.3)
    plt.savefig(os.path.join(args.out, "fig_predictor.pdf"), bbox_inches="tight"); plt.close()

    with open(os.path.join(args.out, "predictor_numbers.tex"), "w") as f:
        defaults = {"predAUC": "0.0", "predAUClr": "0.0", "predAUCfieldbit": "0.0", "predTopFeat": "n/a"}
        for k, v in defaults.items():
            macros.setdefault(k, v)
        for k, v in macros.items():
            f.write(f"\\newcommand{{\\{k}}}{{{v}}}\n")
    print("PREDICTOR macros:", macros)


if __name__ == "__main__":
    main()