Download code/experiments/common.py from Nalarin/nalarin-multimodal-data: direct link, hf CLI and curl.
- Browser
- Download file 14 kB
-
https://huggingface.co/datasets/Nalarin/nalarin-multimodal-data/resolve/main/code/experiments/common.py
- Command line
-
hf download hf://datasets/Nalarin/nalarin-multimodal-data/code/experiments/common.py
-
curl -L -o common.py https://huggingface.co/datasets/Nalarin/nalarin-multimodal-data/resolve/main/code/experiments/common.py
14 kB
| """Utilitas bersama untuk semua eksperimen klasifikasi. | |
| Kontrak data, label, metrik, dan penyimpanan hasil ada di sini supaya lima | |
| konfigurasi (A1/A2/B0/M1/M2) memakai definisi yang sama. | |
| Jangan mengubah fungsi metrik tanpa memperbarui experiments/PROTOCOL.md. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import os | |
| import random | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| ROOT = Path(__file__).resolve().parents[1] | |
| EXP = ROOT / "experiments" | |
| DATASET = ROOT / "data" / "processed" / "model_dataset.parquet" | |
| TEXT_EMB = ROOT / "data" / "processed" / "transcript_embeddings_base.parquet" | |
| TEXT_TOKENS = EXP / "data" / "text_tokens" | |
| AUDIO_SOURCE = EXP / "data" / "audio" / "source.npz" | |
| AUDIO_CACHE = EXP / "data" / "audio" / "audio_seq.npy" | |
| AUDIO_IDS = EXP / "data" / "audio" / "audio_fid.npy" | |
| LEDGER = EXP / "ledger.csv" | |
| LABELS_FILE = EXP / "labels.json" | |
| LEDGER_COLUMNS = [ | |
| "run_id", "task", "owner", "model", "seed", | |
| "val_macro_f1", "test_macro_f1", "test_accuracy", "ci_low", "ci_high", | |
| "n_train", "n_val", "n_test", "hidden", "dropout", "lr", "batch_size", | |
| "class_weight", "epochs_run", "params", "dataset_sha256", "config_sha256", | |
| "notes", "date", | |
| ] | |
| def labels() -> list[str]: | |
| """Urutan kelas kanonik (indeks = id kelas di semua run).""" | |
| return json.loads(LABELS_FILE.read_text(encoding="utf-8")) | |
| def set_seed(seed: int) -> None: | |
| random.seed(seed) | |
| np.random.seed(seed) | |
| try: | |
| import torch | |
| torch.manual_seed(seed) | |
| torch.use_deterministic_algorithms(False) | |
| except ImportError: | |
| pass | |
| def sha256_file(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with Path(path).open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(16 * 1024 * 1024), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def load_dataset(path: Path = DATASET) -> pd.DataFrame: | |
| """Muat data beku dan validasi invariannya. | |
| Gagal keras bila split/label berubah, karena semua angka menjadi tidak | |
| sebanding. | |
| """ | |
| df = pd.read_parquet(path) | |
| required = {"segment_id", "fid", "text_row", "split", "group_id", "label", "language"} | |
| missing = required - set(df.columns) | |
| if missing: | |
| raise ValueError(f"kolom wajib tidak ada: {sorted(missing)}") | |
| if df["segment_id"].duplicated().any(): | |
| raise ValueError("segment_id duplikat") | |
| if not set(df["split"]).issubset({"train", "val", "test"}): | |
| raise ValueError(f"split tidak dikenal: {sorted(set(df['split']))}") | |
| unknown = set(df["label"]) - set(labels()) | |
| if unknown: | |
| raise ValueError(f"label di luar label.json: {sorted(unknown)}") | |
| crossing = df.groupby("group_id")["split"].nunique() | |
| if (crossing > 1).any(): | |
| raise ValueError(f"{int((crossing > 1).sum())} grup muncul di lebih dari satu split") | |
| counts = df["split"].value_counts().to_dict() | |
| expected = {"train": 24008, "val": 2901, "test": 2964} | |
| if counts != expected: | |
| print(f"[peringatan] split {counts} != beku {expected}; lanjutkan hanya untuk smoke test") | |
| order = {name: i for i, name in enumerate(labels())} | |
| df = df.copy() | |
| df["y"] = df["label"].map(order).astype("int64") | |
| return df | |
| def split_indices(df: pd.DataFrame) -> dict[str, np.ndarray]: | |
| return {s: df.index[df["split"] == s].to_numpy() for s in ("train", "val", "test")} | |
| def _l2(matrix: np.ndarray) -> np.ndarray: | |
| norm = np.linalg.norm(matrix, axis=1, keepdims=True) | |
| norm[norm == 0] = 1.0 | |
| return (matrix / norm).astype(np.float32) | |
| def load_text_pooled(df: pd.DataFrame) -> np.ndarray: | |
| """Vektor pooled IndoBERT 768 untuk setiap baris df (via text_row).""" | |
| emb = pd.read_parquet(TEXT_EMB, columns=["embedding"]) | |
| matrix = np.stack(emb["embedding"].to_numpy()).astype(np.float32) | |
| if matrix.shape[1] != 768: | |
| raise ValueError(f"dimensi teks {matrix.shape[1]} != 768") | |
| rows = df["text_row"].to_numpy() | |
| if rows.min() < 0 or rows.max() >= len(matrix): | |
| raise ValueError("text_row di luar jangkauan embedding teks") | |
| return _l2(matrix[rows]) | |
| def ensure_audio_cache(verbose: bool = True) -> tuple[np.ndarray, np.ndarray]: | |
| """Pastikan cache audio (n, 25, 1024) + fid tersedia; konversi sekali. | |
| Sumber: experiments/data/audio/source.npz dengan kunci `emb` (n,25,1024) | |
| dan `fid` (n,). Cache memakai .npy agar bisa di-memmap tanpa memuat 1,5 GB | |
| ke RAM. | |
| """ | |
| if AUDIO_CACHE.exists() and AUDIO_IDS.exists(): | |
| return np.load(AUDIO_CACHE, mmap_mode="r"), np.load(AUDIO_IDS) | |
| if not AUDIO_SOURCE.exists(): | |
| raise FileNotFoundError( | |
| f"vektor audio belum ada: {AUDIO_SOURCE}\n" | |
| "Minta Rambat menyediakan source.npz (kunci: emb (n,25,1024), fid (n,)).\n" | |
| "Kontrak lengkap: experiments/HANDOFF_MODEL.md bagian 2." | |
| ) | |
| data = np.load(AUDIO_SOURCE) | |
| emb = data["emb"] | |
| fids = data["fid"].astype(np.int64) | |
| if emb.ndim != 3 or emb.shape[1:] != (25, 1024): | |
| raise ValueError(f"bentuk audio {emb.shape} != (n, 25, 1024)") | |
| AUDIO_CACHE.parent.mkdir(parents=True, exist_ok=True) | |
| out = np.lib.format.open_memmap( | |
| AUDIO_CACHE, mode="w+", dtype=np.float16, shape=emb.shape | |
| ) | |
| out[:] = emb.astype(np.float16) | |
| out.flush() | |
| np.save(AUDIO_IDS, fids) | |
| if verbose: | |
| print(f"cache audio: {emb.shape} -> {AUDIO_CACHE}") | |
| return np.load(AUDIO_CACHE, mmap_mode="r"), fids | |
| def load_audio_pooled(df: pd.DataFrame) -> np.ndarray: | |
| seq, fids = ensure_audio_cache() | |
| position = {int(fid): i for i, fid in enumerate(fids)} | |
| missing = [int(f) for f in df["fid"] if int(f) not in position] | |
| if missing: | |
| raise ValueError(f"{len(missing)} fid tidak ada di cache audio (contoh {missing[:5]})") | |
| rows = np.array([position[int(f)] for f in df["fid"]], dtype=np.int64) | |
| pooled = seq[rows].astype(np.float32).mean(axis=1) | |
| return _l2(pooled) | |
| class TokenStore: | |
| """Akses token-level IndoBERT lewat .npy memmap (index.parquet).""" | |
| def __init__(self, root: Path = TEXT_TOKENS): | |
| index_path = root / "index.parquet" | |
| if not index_path.exists(): | |
| raise FileNotFoundError( | |
| f"{index_path} tidak ada. Jalankan experiments/scripts/extract_text_tokens.py" | |
| ) | |
| self.root = root | |
| self.index = pd.read_parquet(index_path) | |
| self.by_text_row = self.index.set_index("text_row") | |
| self._cache: dict[str, np.ndarray] = {} | |
| self._mask_cache: dict[str, np.ndarray] = {} | |
| def _array(self, shard: str, kind: str) -> np.ndarray: | |
| cache = self._cache if kind == "emb" else self._mask_cache | |
| name = shard if kind == "emb" else shard.replace(".emb.npy", ".mask.npy") | |
| if name not in cache: | |
| cache[name] = np.load(self.root / name, mmap_mode="r") | |
| return cache[name] | |
| def get_one(self, text_row: int) -> tuple[np.ndarray, np.ndarray]: | |
| row = self.by_text_row.loc[int(text_row)] | |
| emb = np.asarray(self._array(row["shard"], "emb")[int(row["row"])], dtype=np.float32) | |
| mask = np.asarray(self._array(row["shard"], "mask")[int(row["row"])], dtype=np.float32) | |
| return emb, mask | |
| def get(self, text_rows: np.ndarray) -> tuple[np.ndarray, np.ndarray]: | |
| missing = [int(r) for r in text_rows if int(r) not in self.by_text_row.index] | |
| if missing: | |
| raise IndexError(f"text_row tanpa token: {missing[:5]} ({len(missing)} baris)") | |
| meta = self.by_text_row.loc[[int(r) for r in text_rows]] | |
| emb = np.stack([ | |
| np.asarray(self._array(row.shard, "emb")[row.row], dtype=np.float32) | |
| for row in meta.itertuples() | |
| ]) | |
| mask = np.stack([ | |
| np.asarray(self._array(row.shard, "mask")[row.row], dtype=np.float32) | |
| for row in meta.itertuples() | |
| ]) | |
| return emb, mask | |
| class AudioStore: | |
| """Akses sekuens audio 25 x 1024 lewat cache memmap.""" | |
| def __init__(self): | |
| self.seq, fids = ensure_audio_cache() | |
| self.position = {int(fid): i for i, fid in enumerate(fids)} | |
| def get_one(self, fid: int) -> np.ndarray: | |
| if int(fid) not in self.position: | |
| raise IndexError(f"fid tanpa audio: {fid}") | |
| return np.asarray(self.seq[self.position[int(fid)]], dtype=np.float32) | |
| def get(self, fids: np.ndarray) -> np.ndarray: | |
| missing = [int(f) for f in fids if int(f) not in self.position] | |
| if missing: | |
| raise IndexError(f"fid tanpa audio: {missing[:5]} ({len(missing)} baris)") | |
| rows = np.array([self.position[int(f)] for f in fids], dtype=np.int64) | |
| return np.asarray(self.seq[rows], dtype=np.float32) | |
| def classification_metrics( | |
| y_true: np.ndarray, y_pred: np.ndarray, n_classes: int | None = None | |
| ) -> dict: | |
| from sklearn.metrics import ( | |
| accuracy_score, | |
| confusion_matrix, | |
| f1_score, | |
| precision_recall_fscore_support, | |
| ) | |
| names = labels() | |
| n_classes = n_classes or len(names) | |
| label_ids = list(range(n_classes)) | |
| precision, recall, f1, support = precision_recall_fscore_support( | |
| y_true, y_pred, labels=label_ids, zero_division=0 | |
| ) | |
| return { | |
| "macro_f1": float(f1_score(y_true, y_pred, average="macro", zero_division=0)), | |
| "accuracy": float(accuracy_score(y_true, y_pred)), | |
| "macro_precision": float(precision.mean()), | |
| "macro_recall": float(recall.mean()), | |
| "n": int(len(y_true)), | |
| "per_class": { | |
| names[i]: { | |
| "precision": float(precision[i]), | |
| "recall": float(recall[i]), | |
| "f1": float(f1[i]), | |
| "support": int(support[i]), | |
| } | |
| for i in label_ids | |
| }, | |
| "confusion_matrix": confusion_matrix(y_true, y_pred, labels=label_ids).tolist(), | |
| "labels": names, | |
| } | |
| def bootstrap_macro_f1( | |
| y_true: np.ndarray, | |
| y_pred: np.ndarray, | |
| groups: np.ndarray, | |
| n_boot: int = 1000, | |
| seed: int = 42, | |
| alpha: float = 0.05, | |
| ) -> tuple[float, float]: | |
| """CI bootstrap yang mengelompokkan per group_id (bukan per segmen).""" | |
| from sklearn.metrics import f1_score | |
| rng = np.random.default_rng(seed) | |
| unique = np.unique(groups) | |
| buckets = {g: np.flatnonzero(groups == g) for g in unique} | |
| # Kelas yang sama dengan titik estimasi: semua kelas yang ada di test penuh. | |
| label_ids = np.unique(y_true).tolist() | |
| scores = [] | |
| for _ in range(n_boot): | |
| pick = rng.choice(unique, size=len(unique)) | |
| rows = np.concatenate([buckets[g] for g in pick]) | |
| if len(np.unique(y_true[rows])) < 2: | |
| continue | |
| scores.append( | |
| f1_score(y_true[rows], y_pred[rows], labels=label_ids, | |
| average="macro", zero_division=0) | |
| ) | |
| if not scores: | |
| return (float("nan"), float("nan")) | |
| return (float(np.quantile(scores, alpha / 2)), float(np.quantile(scores, 1 - alpha / 2))) | |
| def mcnemar_test(y_true: np.ndarray, pred_a: np.ndarray, pred_b: np.ndarray) -> dict: | |
| """McNemar berpasangan per segment_id (benar/salah), koreksi kontinuitas.""" | |
| from scipy.stats import binomtest, chi2 | |
| correct_a = pred_a == y_true | |
| correct_b = pred_b == y_true | |
| b01 = int(np.sum(correct_a & ~correct_b)) | |
| b10 = int(np.sum(~correct_a & correct_b)) | |
| discordant = b01 + b10 | |
| if discordant == 0: | |
| return {"b01": 0, "b10": 0, "statistic": 0.0, "p_value": 1.0} | |
| if discordant < 25: | |
| p = binomtest(min(b01, b10), discordant, 0.5).pvalue | |
| return {"b01": b01, "b10": b10, "statistic": float(min(b01, b10)), "p_value": float(p)} | |
| statistic = (abs(b01 - b10) - 1) ** 2 / discordant | |
| return { | |
| "b01": b01, | |
| "b10": b10, | |
| "statistic": float(statistic), | |
| "p_value": float(chi2.sf(statistic, 1)), | |
| } | |
| def append_ledger(row: dict) -> None: | |
| """Tambah satu baris ledger secara atomik; tidak menimpa baris orang lain.""" | |
| lock = LEDGER.with_suffix(".lock") | |
| acquired = False | |
| for _ in range(60): | |
| try: | |
| handle = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY) | |
| os.write(handle, str(os.getpid()).encode()) | |
| os.close(handle) | |
| acquired = True | |
| break | |
| except FileExistsError: | |
| try: | |
| if time.time() - lock.stat().st_mtime > 600: | |
| print(f"[peringatan] lock ledger basi (>10 menit), diambil alih: {lock}") | |
| lock.unlink(missing_ok=True) | |
| continue | |
| except FileNotFoundError: | |
| continue | |
| time.sleep(0.5) | |
| if not acquired: | |
| raise RuntimeError(f"ledger sedang dipakai (lock {lock}); coba lagi") | |
| try: | |
| if not LEDGER.exists(): | |
| pd.DataFrame(columns=LEDGER_COLUMNS).to_csv(LEDGER, index=False) | |
| current = ( | |
| pd.read_csv(LEDGER, dtype=str) | |
| .reindex(columns=LEDGER_COLUMNS) | |
| .fillna("") | |
| ) | |
| if (current["run_id"].astype(str) == str(row["run_id"])).any(): | |
| raise ValueError(f"run_id {row['run_id']} sudah ada di ledger; pakai --run-id lain") | |
| line = pd.DataFrame( | |
| [{column: row.get(column, "") for column in LEDGER_COLUMNS}], | |
| columns=LEDGER_COLUMNS, | |
| ).fillna("") | |
| merged = pd.concat([current, line], ignore_index=True) | |
| temp = LEDGER.with_suffix(".tmp") | |
| merged.to_csv(temp, index=False) | |
| os.replace(temp, LEDGER) | |
| finally: | |
| lock.unlink(missing_ok=True) | |