File size: 11,440 Bytes
0f27fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
"""Generate the results tables that the README embeds.

Every number in the model card comes from here, which reads only the JSON
written by scripts 02 and 03. Nothing is typed by hand.

    python scripts/04_report.py
"""

import json
import sys
from pathlib import Path

# RESULTS.md is written as UTF-8 regardless; this only stops a Windows console
# on a legacy codepage (cp1252/cp1254) from crashing on the arrows and dashes.
try:
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except (AttributeError, ValueError):  # pragma: no cover
    pass

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))

from cti_attack import config, data  # noqa: E402

ORDER = ["frequency", "keyword", "tfidf_lr", "modernbert", "deberta", "securebert"]
PRETTY = {
    "frequency": "Frequency prior",
    "keyword": "ATT&CK keyword match",
    "tfidf_lr": "TF-IDF + one-vs-rest LR",
    "modernbert": "ModernBERT-base (fine-tuned)",
    "deberta": "DeBERTa-v3-base (fine-tuned)",
    "securebert": "SecureBERT (fine-tuned)",
}
TRAINED = {"modernbert", "deberta", "securebert"}


def collect() -> dict:
    out: dict[str, dict] = {}
    for scheme in ("document", "random"):
        p = config.RESULTS_DIR / f"baselines__{scheme}.json"
        if p.exists():
            for name, payload in json.loads(p.read_text(encoding="utf-8")).items():
                out.setdefault(name, {})[scheme] = payload
        for name in TRAINED:
            q = config.RESULTS_DIR / f"{name}__{scheme}.json"
            if q.exists():
                out.setdefault(name, {})[scheme] = json.loads(q.read_text(encoding="utf-8"))
    return out


def _cell(res: dict, scheme: str, metric: str, mode: str) -> str:
    try:
        return f"{res[scheme][mode][metric]:.3f}"
    except (KeyError, TypeError):
        return "—"


def main_table(results: dict, mode: str = "per_class_threshold") -> str:
    lines = [
        "| Model | doc macro-F1 | doc micro-F1 | random macro-F1 | random micro-F1 | inflation |",
        "|---|---|---|---|---|---|",
    ]
    for name in ORDER:
        if name not in results:
            continue
        res = results[name]
        dm = _cell(res, "document", "macro_f1", mode)
        rm = _cell(res, "random", "macro_f1", mode)
        infl = "n/a"
        if dm != "—" and rm != "—" and float(dm) > 0:
            infl = f"{(float(rm) / float(dm) - 1) * 100:+.1f}%"
        label = PRETTY[name]
        if name == "modernbert":
            label = f"**{label}**"
        lines.append(
            f"| {label} | {dm} | {_cell(res, 'document', 'micro_f1', mode)} "
            f"| {rm} | {_cell(res, 'random', 'micro_f1', mode)} | {infl} |")
    return "\n".join(lines)


def per_class_table(results: dict, model: str = "modernbert", top: int = 12) -> str:
    try:
        pc = results[model]["document"]["per_class_threshold"]["per_class"]
    except KeyError:
        return "_(not available — train a model first)_"
    rows = sorted(pc.items(), key=lambda kv: -kv[1]["support"])[:top]

    try:
        from cti_attack import attack_meta
        names = attack_meta.build_technique_names()
        status = attack_meta.build_technique_status()
    except Exception:
        names, status = {}, {}

    lines = ["| Technique | Name | Support | P | R | F1 |", "|---|---|---|---|---|---|"]
    for tid, m in rows:
        nm = names.get(tid, "")
        if len(nm) > 46:
            nm = nm[:43] + "…"
        if status.get(tid) == "revoked":
            nm += " ⚠️*revoked*"
        lines.append(f"| `{tid}` | {nm} | {m['support']} | {m['precision']:.2f} "
                     f"| {m['recall']:.2f} | {m['f1']:.2f} |")
    return "\n".join(lines)


def tail_table(results: dict, model: str = "modernbert") -> str:
    """Head vs tail: the number that macro-F1 exists to expose."""
    try:
        pc = results[model]["document"]["per_class_threshold"]["per_class"]
    except KeyError:
        return "_(not available)_"
    head = [m for m in pc.values() if m["support"] >= 20]
    tail = [m for m in pc.values() if m["support"] < 20]
    lines = ["| Bucket | Techniques | Mean F1 |", "|---|---|---|"]
    for nm, bucket in (("head (>=20 test examples)", head), ("tail (<20 test examples)", tail)):
        if bucket:
            lines.append(f"| {nm} | {len(bucket)} | "
                         f"{sum(m['f1'] for m in bucket) / len(bucket):.3f} |")
    return "\n".join(lines)


def _paired(a: list[float], b: list[float]) -> dict:
    """Paired difference stats for a - b across folds, with a p-value if scipy is present."""
    import math
    d = [x - y for x, y in zip(a, b)]
    n = len(d)
    mean = sum(d) / n
    var = sum((x - mean) ** 2 for x in d) / (n - 1) if n > 1 else 0.0
    std = math.sqrt(var)
    se = std / math.sqrt(n) if std > 0 else 0.0
    t = mean / se if se > 0 else float("inf")
    pos = sum(1 for x in d if x > 0)
    p = None
    try:
        from scipy import stats  # optional
        p = float(stats.ttest_rel(a, b).pvalue)
    except Exception:
        pass
    return {"mean": mean, "std": std, "t": t, "pos": pos, "n": n, "p": p}


def _sig(p, t, n) -> str:
    if p is not None:
        return f"p = {p:.3f}"
    # df = n-1; two-sided 0.05 critical t for df=4 is 2.776, df=3 is 3.182
    crit = {2: 4.303, 3: 3.182, 4: 2.776, 5: 2.571, 6: 2.447}.get(n - 1, 2.776)
    return f"t = {t:.2f} ({'p<0.05' if abs(t) > crit else 'n.s.'})"


def cv_ensemble_section() -> str:
    """Cross-validated ensemble results, read from the CV and ensemble JSON.

    This is the section that turns 'higher on one split' into 'higher across
    independent leak-free folds, with a paired significance test'.
    """
    cvp = config.RESULTS_DIR / "cv_5fold__modernbert.json"
    enp = config.RESULTS_DIR / "ensemble_tfidf_modernbert__document.json"
    if not cvp.exists():
        return ""
    cv = json.loads(cvp.read_text(encoding="utf-8"))
    S, folds = cv["summary"], cv["per_fold"]

    def ms(k):
        return f"{S[k]['mean']:.4f} +/- {S[k]['std']:.4f}"

    lines = [
        f"One 70/15/15 split of a {cv['n_documents']}-document corpus is one "
        f"draw, so the gap between models can be noise. To check it, here is "
        f"{cv['folds']}-fold cross-validation grouped by document. Each report "
        f"lands in exactly one test fold. The blend weight and thresholds are "
        f"tuned on each fold's own dev set, never on its test set.\n",
        "| Model | doc macro-F1 (5-fold CV, mean +/- std) |",
        "|---|---|",
        f"| TF-IDF + LR (per-class) | {ms('tfidf_perclass')} |",
        f"| TF-IDF + LR (global) | {ms('tfidf_global')} |",
        f"| ModernBERT (per-class) | {ms('modernbert_perclass')} |",
        f"| **Ensemble TF-IDF+ModernBERT (per-class)** | **{ms('ensemble_perclass')}** |",
        "",
        "Paired per-fold test, per-class thresholds on both sides:",
    ]
    ep = [f["ensemble_perclass"] for f in folds]
    tests = [
        ("ensemble vs TF-IDF, same per-class regime", ep, [f["tfidf_perclass"] for f in folds]),
        ("ensemble vs ModernBERT, same per-class regime", ep, [f["modernbert_perclass"] for f in folds]),
        ("ensemble vs TF-IDF at its stronger global regime", ep, [f["tfidf_global"] for f in folds]),
    ]
    for label, a, b in tests:
        r = _paired(a, b)
        lines.append(
            f"- {label}: **{r['mean']:+.4f}**, {r['pos']}/{r['n']} folds positive, {_sig(r['p'], r['t'], r['n'])}")

    if enp.exists():
        en = json.loads(enp.read_text(encoding="utf-8"))
        a = en.get("alpha")
        pc = en["per_class_threshold"]["macro_f1"]
        comp = en["components_test_macro_f1"]
        lines.append(
            f"\nOn the original single 70/15/15 document split, the same ensemble "
            f"({a:.0%} TF-IDF, {1-a:.0%} ModernBERT) scores "
            f"**{pc:.4f}** macro-F1, against {comp['tfidf_lr']['per_class']:.4f} "
            f"for TF-IDF and {comp['modernbert']['per_class']:.4f} for ModernBERT.")

    lines.append(
        "\nHow to read this: the ensemble has the highest mean and the lowest "
        "variance of everything tested. Compared against each base model at the "
        "same threshold setting, it wins in all five folds. The one comparison it "
        "does not clearly win is against TF-IDF at its own best threshold setting, "
        "where the lead is small enough to be noise over five folds. That row is "
        "in the table on purpose.")
    return "\n".join(lines)


def main() -> None:
    results = collect()
    if not results:
        print("no results found — run scripts 02 and 03 first")
        return

    stats = json.loads((config.BUILD_DIR / "build_stats.json").read_text(encoding="utf-8"))
    labels = data.load_labels()
    cv_block = cv_ensemble_section()

    doc = [
        "<!-- generated by scripts/04_report.py - do not edit by hand -->",
        "### Test-set results\n",
        "Per-class thresholds tuned on dev. Macro-F1 is the headline metric. It "
        "weights all 49 techniques equally, so a handful of common ones cannot "
        "cover for a weak long tail.\n",
        main_table(results, "per_class_threshold"),
        "\n### Same table, single global threshold\n",
        main_table(results, "global_threshold"),
        *(["\n### Ensemble + cross-validated results\n", cv_block] if cv_block else []),
        "\n### ModernBERT per-technique, document split (12 most frequent)\n",
        per_class_table(results),
        "\n### Head vs tail, document split\n",
        tail_table(results),
        "\n### Corpus\n",
        f"- {stats['raw_sentences']:,} raw sentences, {stats['final_sentences']:,} after cleaning and dedup",
        f"- {stats['final_labelled']:,} carry at least one technique "
        f"({stats['final_labelled'] / stats['final_sentences']:.1%})",
        f"- {len(labels)} techniques across {stats['final_documents']} source documents",
        f"- {stats['duplicates_removed']:,} duplicate sentences removed "
        f"({stats['cross_document_duplicates']} of them appeared in more than one document)",
        f"- dropped for having too few documents to split: {', '.join(stats['dropped_techniques'])}",
    ]
    out = config.RESULTS_DIR / "RESULTS.md"
    out.write_text("\n".join(doc) + "\n", encoding="utf-8")
    print("\n".join(doc))
    print(f"\n-> {out.relative_to(config.REPO_ROOT)}")

    inject_into_readme("\n".join(doc[1:]))  # drop the "generated by" comment


BEGIN = "<!-- BEGIN GENERATED RESULTS - scripts/04_report.py -->"
END = "<!-- END GENERATED RESULTS -->"


def inject_into_readme(block: str) -> None:
    """Rewrite the results section of README.md in place.

    The tables in the model card are generated, not transcribed. Pasting them
    by hand is how a card drifts out of sync with the data it describes, which
    is the exact failure this repo argues against.
    """
    readme = config.REPO_ROOT / "README.md"
    if not readme.exists():
        return
    text = readme.read_text(encoding="utf-8")
    if BEGIN not in text or END not in text:
        print("! README.md is missing the generated-results markers; skipping injection")
        return
    head, rest = text.split(BEGIN, 1)
    _, tail = rest.split(END, 1)
    readme.write_text(f"{head}{BEGIN}\n{block}\n{END}{tail}", encoding="utf-8")
    print(f"-> README.md results section updated")


if __name__ == "__main__":
    main()