File size: 5,570 Bytes
6389ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Pemeriksaan cepat sebelum eksperimen: data, label, model, metrik.



Jalankan: python experiments/scripts/selfcheck.py

Tidak melatih model dan tidak menyentuh test.

"""

from __future__ import annotations

import sys
from pathlib import Path

import numpy as np
import pandas as pd

ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "experiments"))

import common  # noqa: E402
import train  # noqa: E402

ok = True


def check(name: str, condition: bool, detail: str = "") -> None:
    global ok
    print(f"[{'OK ' if condition else 'GAGAL'}] {name}" + (f" — {detail}" if detail else ""))
    ok = ok and condition


def main() -> int:
    names = common.labels()
    check("21 label unik", len(names) == 21 and len(set(names)) == 21)

    frame = common.load_dataset()
    counts = frame["split"].value_counts().to_dict()
    check("baris 29.873", len(frame) == 29873, str(len(frame)))
    check("split beku", counts == {"train": 24008, "val": 2901, "test": 2964}, str(counts))
    check("21 kelas di train", frame[frame.split == "train"]["label"].nunique() == 21)
    check("tidak ada grup lintas split",
          int((frame.groupby("group_id")["split"].nunique() > 1).sum()) == 0)

    text = common.load_text_pooled(frame.head(32))
    check("teks pooled (32,768)", text.shape == (32, 768), str(text.shape))
    check("teks ternormalisasi L2", np.allclose(np.linalg.norm(text, axis=1), 1.0, atol=1e-5))

    embedding = pd.read_parquet(common.TEXT_EMB, columns=["segment_id"])
    aligned = embedding.iloc[frame["text_row"].head(32).to_numpy()]["segment_id"].to_numpy()
    check("text_row menunjuk segmen yang sama",
          bool((aligned == frame["segment_id"].head(32).to_numpy()).all()))

    import torch

    batch_text = torch.randn(4, 128, 768)
    mask = torch.ones(4, 128)
    mask[0, 40:] = 0
    batch_audio = torch.randn(4, 25, 1024)

    mlp = train.build_model("mlp", {"hidden": 64, "dropout": 0.3}, 1792, 21)
    check("MLP keluaran (4,21)", tuple(mlp(torch.randn(4, 1792)).shape) == (4, 21))

    late = train.build_model("late_concat", {"hidden": 32, "dropout": 0.3}, 0, 21)
    out = late(batch_text, mask, batch_audio)
    check("M1 late concat keluaran (4,21)", tuple(out.shape) == (4, 21))

    dnn = train.build_model("dnn_fusion", {"hidden": 32, "dropout": 0.3}, 0, 21)
    out = dnn(batch_text, mask, batch_audio)
    check("M2 DNN fusion keluaran (4,21)", tuple(out.shape) == (4, 21))

    loss = torch.nn.CrossEntropyLoss()(late(batch_text, mask, batch_audio), torch.tensor([0, 1, 2, 3]))
    loss.backward()
    grads = [p.grad is not None for p in late.parameters()]
    check("M1 gradien mengalir", all(grads))

    y = np.array([0, 1, 2, 3, 4, 5])
    metrics = common.classification_metrics(y, y)
    check("macro-F1 prediksi sempurna = 1", abs(metrics["macro_f1"] - 1.0) < 1e-9)
    check("21 baris F1 per kelas", len(metrics["per_class"]) == 21)
    low, high = common.bootstrap_macro_f1(y, y, np.array(["a", "b", "a", "b", "a", "b"]), n_boot=50)
    check("bootstrap CI berisi 1", low <= 1.0 <= high, f"[{low:.3f}, {high:.3f}]")
    same = common.mcnemar_test(y, y, y)
    check("McNemar identik p=1", same["p_value"] == 1.0)

    toy = [
        {"hidden": 512, "dropout": 0.5, "lr": 0.001, "class_weight": None, "val_macro_f1": 0.5778},
        {"hidden": 128, "dropout": 0.5, "lr": 0.001, "class_weight": "balanced", "val_macro_f1": 0.5730},
        {"hidden": 256, "dropout": 0.5, "lr": 0.001, "class_weight": None, "val_macro_f1": 0.5500},
    ]
    pilihan, aturan = train.select_config(
        toy, ["hidden", "dropout", "lr", "class_weight"],
        {"hidden": 256, "class_weight": None}, tolerance=0.01,
    )
    check("tie-break pilih hidden 128", pilihan["hidden"] == 128, str(pilihan["hidden"]))
    check("tie-break menyimpan alasan", aturan["rule"] == "tie_break_simple")

    expected_hash = "17a67682afa3693fd8ca95bf97e6bd1b62228a181702774569a006522d0643a6"
    check("hash model_dataset sesuai", common.sha256_file(common.DATASET) == expected_hash)

    import yaml

    allowed = {"hidden", "dropout", "lr", "class_weight"}
    expected_grid = {"a1_text": 36, "a2_audio": 36, "b0_concat": 36, "m1_late": 8, "m2_dnn": 8}
    for name, expected in expected_grid.items():
        config = yaml.safe_load((common.EXP / "configs" / f"{name}.yaml").read_text(encoding="utf-8"))
        grid = config.get("grid") or {}
        total = 1
        for values in grid.values():
            total *= len(values)
        check(f"grid {name} = {expected}", total == expected, f"{total}")
        check(f"grid {name} hanya kunci yang dibaca trainer", set(grid).issubset(allowed), str(set(grid)))
        check(f"{name} memakai cosine warmup",
              config.get("training", {}).get("scheduler") == "cosine_warmup")

    ledger = pd.read_csv(common.LEDGER)
    check("header ledger 24 kolom", len(ledger.columns) == 24, str(len(ledger.columns)))

    audio = common.AUDIO_SOURCE.exists()
    cache = common.AUDIO_CACHE.exists() and common.AUDIO_IDS.exists()
    tokens = (common.TEXT_TOKENS / "index.parquet").exists()
    print(f"[info] audio: {'siap' if audio or cache else 'BELUM ADA (A2/B0/M1/M2 menunggu Rambat)'}")
    print(f"[info] text_tokens: {'siap' if tokens else 'belum (M1/M2 butuh extract_text_tokens.py)'}")

    print("\nSELESAI" if ok else "\nADA YANG GAGAL")
    return 0 if ok else 1


if __name__ == "__main__":
    raise SystemExit(main())