Download validate_fp32_vs_v5.py from Logn001/odpe-progressive-quantization: direct link, hf CLI and curl.
- Browser
- Download file 18 kB
-
https://huggingface.co/Logn001/odpe-progressive-quantization/resolve/main/validate_fp32_vs_v5.py
- Command line
-
hf download hf://Logn001/odpe-progressive-quantization/validate_fp32_vs_v5.py
-
curl -L -o validate_fp32_vs_v5.py https://huggingface.co/Logn001/odpe-progressive-quantization/resolve/main/validate_fp32_vs_v5.py
18 kB
| """Independent disjoint-fold and calibration validation comparing Classical FP32 vs. Adaptive V5. | |
| Runs a fresh, non-overlapping training fold of `facebook/xnli` (ru + en) from a new random seed | |
| (`seed=123`, 50,000 unseen training pairs disjoint from the main `seed=42` experiment), tracks | |
| both Epoch-8 and Best-Validation checkpoints for BOTH Classical FP32 and Adaptive V5 via shared | |
| `run_classical` and `run_adaptive_v5` runners, and evaluates: | |
| 1. Standard held-out XNLI Test (`10,020` pairs) | |
| 2. Large Out-of-Sample Unseen Stress Split (`20,000` unused XNLI pairs) | |
| 3. Expected Calibration Error (10-bin ECE), Brier score, Macro-F1, wrong-answer overconfidence, | |
| and long-sequence (`>= 48` tokens) robustness. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| from pathlib import Path | |
| from typing import Any, Dict, List | |
| from train_experiment import ( | |
| RESULTS_DIR, | |
| _ensure_writable_cache_env, | |
| run_adaptive_v5, | |
| run_classical, | |
| set_seed, | |
| ) | |
| PROJECT_DIR = Path(__file__).resolve().parent | |
| _ensure_writable_cache_env("TORCHINDUCTOR_CACHE_DIR", PROJECT_DIR / ".torch_cache") | |
| _ensure_writable_cache_env("MPLCONFIGDIR", PROJECT_DIR / ".mpl_cache") | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| from datasets import load_dataset | |
| from tokenizers import Tokenizer | |
| from torch.utils.data import DataLoader | |
| from data_xnli import HF_CACHE_DIR, TOKENIZER_PATH, XNLIPairDataset | |
| from model import BilingualNLIConfig, BilingualNLITransformer | |
| from progressive_quant import RouterConfig | |
| def prepare_disjoint_xnli_splits( | |
| train_offset: int = 25_000, | |
| train_per_lang: int = 25_000, | |
| stress_offset: int = 50_000, | |
| stress_per_lang: int = 10_000, | |
| split_seed: int = 42, | |
| offline: bool = True, | |
| ) -> Dict[str, Any]: | |
| """Load strictly disjoint training and stress-evaluation slices from cached XNLI (ru + en).""" | |
| if train_offset + train_per_lang > stress_offset: | |
| raise ValueError("train slice and stress slice must remain strictly disjoint") | |
| os.environ["HF_HOME"] = str(HF_CACHE_DIR) | |
| os.environ["HF_DATASETS_CACHE"] = str(HF_CACHE_DIR / "datasets") | |
| if offline: | |
| os.environ["HF_HUB_OFFLINE"] = "1" | |
| os.environ["HF_DATASETS_OFFLINE"] = "1" | |
| ru_ds = load_dataset("facebook/xnli", "ru", cache_dir=str(HF_CACHE_DIR / "datasets")) | |
| en_ds = load_dataset("facebook/xnli", "en", cache_dir=str(HF_CACHE_DIR / "datasets")) | |
| ru_shuffled = ru_ds["train"].shuffle(seed=split_seed) | |
| en_shuffled = en_ds["train"].shuffle(seed=split_seed) | |
| train_idx = range(train_offset, train_offset + train_per_lang) | |
| stress_idx = range(stress_offset, stress_offset + stress_per_lang) | |
| def collect(ds, lang: str) -> List[Dict[str, Any]]: | |
| return [ | |
| { | |
| "premise": ex["premise"], | |
| "hypothesis": ex["hypothesis"], | |
| "label": int(ex["label"]), | |
| "lang": lang, | |
| } | |
| for ex in ds | |
| ] | |
| train_rows = collect(ru_shuffled.select(train_idx), "ru") + collect( | |
| en_shuffled.select(train_idx), "en" | |
| ) | |
| val_rows = collect(ru_ds["validation"], "ru") + collect(en_ds["validation"], "en") | |
| test_rows = collect(ru_ds["test"], "ru") + collect(en_ds["test"], "en") | |
| stress_rows = collect(ru_shuffled.select(stress_idx), "ru") + collect( | |
| en_shuffled.select(stress_idx), "en" | |
| ) | |
| tokenizer = Tokenizer.from_file(str(TOKENIZER_PATH)) | |
| return { | |
| "train": train_rows, | |
| "validation": val_rows, | |
| "test": test_rows, | |
| "stress": stress_rows, | |
| "tokenizer": tokenizer, | |
| "summary": { | |
| "split_seed": split_seed, | |
| "train_range": [train_offset, train_offset + train_per_lang], | |
| "stress_range": [stress_offset, stress_offset + stress_per_lang], | |
| "train_total": len(train_rows), | |
| "val_total": len(val_rows), | |
| "test_total": len(test_rows), | |
| "stress_total": len(stress_rows), | |
| }, | |
| } | |
| def evaluate_detailed( | |
| model: torch.nn.Module, | |
| loader: DataLoader, | |
| device: torch.device, | |
| num_classes: int = 3, | |
| long_seq_threshold: int = 48, | |
| n_bins: int = 10, | |
| ) -> Dict[str, Any]: | |
| """Compute accuracy, Macro-F1, 10-bin ECE, Brier score, wrong confidence, and length slices.""" | |
| model.eval() | |
| all_probs: List[torch.Tensor] = [] | |
| all_labels: List[torch.Tensor] = [] | |
| all_langs: List[torch.Tensor] = [] | |
| all_lens: List[torch.Tensor] = [] | |
| total_loss = 0.0 | |
| total_count = 0 | |
| for input_ids, token_type_ids, attention_mask, labels, lang_ids in loader: | |
| input_ids = input_ids.to(device, non_blocking=True) | |
| token_type_ids = token_type_ids.to(device, non_blocking=True) | |
| attention_mask = attention_mask.to(device, non_blocking=True) | |
| labels = labels.to(device, non_blocking=True) | |
| logits = model(input_ids, token_type_ids, attention_mask) | |
| total_loss += float(F.cross_entropy(logits, labels, reduction="sum").item()) | |
| total_count += labels.size(0) | |
| all_probs.append(torch.softmax(logits, dim=-1).cpu()) | |
| all_labels.append(labels.cpu()) | |
| all_langs.append(lang_ids.cpu()) | |
| all_lens.append(attention_mask.sum(dim=-1).cpu()) | |
| probs = torch.cat(all_probs, dim=0) | |
| labels_t = torch.cat(all_labels, dim=0) | |
| langs_t = torch.cat(all_langs, dim=0) | |
| lens_t = torch.cat(all_lens, dim=0) | |
| confs, preds = probs.max(dim=-1) | |
| correct = preds == labels_t | |
| ru_mask = langs_t == 0 | |
| en_mask = langs_t == 1 | |
| long_mask = lens_t >= long_seq_threshold | |
| short_mask = ~long_mask | |
| one_hot = F.one_hot(labels_t, num_classes=num_classes).float() | |
| brier = float(((probs - one_hot) ** 2).sum(dim=-1).mean().item()) | |
| f1s: List[float] = [] | |
| for c in range(num_classes): | |
| tp = int(((preds == c) & (labels_t == c)).sum().item()) | |
| fp = int(((preds == c) & (labels_t != c)).sum().item()) | |
| fn = int(((preds != c) & (labels_t == c)).sum().item()) | |
| denom = 2 * tp + fp + fn | |
| f1s.append((2.0 * tp / denom) if denom > 0 else 0.0) | |
| bin_edges = torch.linspace(0.0, 1.0, n_bins + 1) | |
| ece = 0.0 | |
| reliability_bins: List[Dict[str, float | int]] = [] | |
| n_total = max(1, len(labels_t)) | |
| for i in range(n_bins): | |
| lo, hi = float(bin_edges[i]), float(bin_edges[i + 1]) | |
| in_bin = (confs >= lo) & (confs <= hi) if i == 0 else (confs > lo) & (confs <= hi) | |
| cnt = int(in_bin.sum().item()) | |
| if cnt > 0: | |
| bin_acc = float(correct[in_bin].float().mean().item()) | |
| bin_conf = float(confs[in_bin].mean().item()) | |
| ece += (cnt / n_total) * abs(bin_acc - bin_conf) | |
| reliability_bins.append( | |
| {"bin_center": (lo + hi) * 0.5, "acc": bin_acc, "conf": bin_conf, "count": cnt} | |
| ) | |
| wrong_mask = ~correct | |
| wrong_conf = float(confs[wrong_mask].mean().item()) if wrong_mask.any() else 0.0 | |
| return { | |
| "count": int(total_count), | |
| "loss": total_loss / max(1, total_count), | |
| "acc": float(correct.float().mean().item()), | |
| "acc_ru": float(correct[ru_mask].float().mean().item()) if ru_mask.any() else 0.0, | |
| "acc_en": float(correct[en_mask].float().mean().item()) if en_mask.any() else 0.0, | |
| "macro_f1": float(sum(f1s) / num_classes), | |
| "per_class_f1": f1s, | |
| "ece_10bin": float(ece), | |
| "brier_score": brier, | |
| "mean_confidence": float(confs.mean().item()), | |
| "mean_wrong_confidence": wrong_conf, | |
| "long_seq_acc": float(correct[long_mask].float().mean().item()) if long_mask.any() else 0.0, | |
| "short_seq_acc": float(correct[short_mask].float().mean().item()) if short_mask.any() else 0.0, | |
| "long_seq_count": int(long_mask.sum().item()), | |
| "reliability_bins": reliability_bins, | |
| } | |
| def make_eval_hook( | |
| bag: Dict[str, Any], | |
| test_loader: DataLoader, | |
| stress_loader: DataLoader, | |
| device: torch.device, | |
| ): | |
| """Build an eval_hook capturing detailed Test and Stress-20k metrics at Ep.8 and Best-Val.""" | |
| def _hook(tag: str, model: BilingualNLITransformer) -> None: | |
| bag[f"{tag}_test"] = evaluate_detailed(model, test_loader, device) | |
| bag[f"{tag}_stress"] = evaluate_detailed(model, stress_loader, device) | |
| return _hook | |
| def generate_validation_plot(fp32_det: Dict[str, Any], v5_det: Dict[str, Any], v5_bits: float) -> None: | |
| """Create 3-panel plot comparing FP32 vs V5 across held-out splits and calibration reliability.""" | |
| RESULTS_DIR.mkdir(parents=True, exist_ok=True) | |
| fig, axes = plt.subplots(1, 3, figsize=(15.5, 4.7)) | |
| labels = [ | |
| "Test\n(Ep. 8)", | |
| "Test\n(Best Val)", | |
| "Stress 20k\n(Ep. 8)", | |
| "Stress 20k\n(Best Val)", | |
| "Long Seq\n(Ep. 8)", | |
| "Macro-F1\n(Best Val)", | |
| ] | |
| fp_vals = [ | |
| fp32_det["ep8_test"]["acc"] * 100, | |
| fp32_det["best_val_test"]["acc"] * 100, | |
| fp32_det["ep8_stress"]["acc"] * 100, | |
| fp32_det["best_val_stress"]["acc"] * 100, | |
| fp32_det["ep8_test"]["long_seq_acc"] * 100, | |
| fp32_det["best_val_test"]["macro_f1"] * 100, | |
| ] | |
| v5_vals = [ | |
| v5_det["ep8_test"]["acc"] * 100, | |
| v5_det["best_val_test"]["acc"] * 100, | |
| v5_det["ep8_stress"]["acc"] * 100, | |
| v5_det["best_val_stress"]["acc"] * 100, | |
| v5_det["ep8_test"]["long_seq_acc"] * 100, | |
| v5_det["best_val_test"]["macro_f1"] * 100, | |
| ] | |
| x = np.arange(len(labels)) | |
| w = 0.36 | |
| axes[0].bar(x - w / 2, fp_vals, width=w, label="Classical FP32 (32b)", color="tab:blue") | |
| axes[0].bar(x + w / 2, v5_vals, width=w, label=f"Adaptive V5 ({v5_bits:.2f}b)", color="tab:cyan") | |
| axes[0].set_xticks(x) | |
| axes[0].set_xticklabels(labels, fontsize=8.5) | |
| axes[0].set_ylim(38, 56) | |
| axes[0].set_ylabel("Score (%)") | |
| axes[0].set_title("Disjoint-Fold Accuracy & Robustness (seed=123)") | |
| axes[0].grid(True, axis="y", alpha=0.3) | |
| axes[0].legend(fontsize=8) | |
| fp_bins = fp32_det["ep8_stress"]["reliability_bins"] | |
| v5_bins = v5_det["ep8_stress"]["reliability_bins"] | |
| axes[1].plot([0.3, 1.0], [0.3, 1.0], "--", color="gray", label="Perfect Calibration") | |
| axes[1].plot( | |
| [b["conf"] for b in fp_bins], | |
| [b["acc"] for b in fp_bins], | |
| "o-", | |
| color="tab:blue", | |
| label=f"FP32 (ECE={fp32_det['ep8_stress']['ece_10bin']:.3f})", | |
| ) | |
| axes[1].plot( | |
| [b["conf"] for b in v5_bins], | |
| [b["acc"] for b in v5_bins], | |
| "P-", | |
| color="tab:cyan", | |
| linewidth=2.2, | |
| label=f"V5 (ECE={v5_det['ep8_stress']['ece_10bin']:.3f})", | |
| ) | |
| axes[1].set_title("Calibration Reliability (20k Stress, Ep. 8)") | |
| axes[1].set_xlabel("Mean Confidence") | |
| axes[1].set_ylabel("Empirical Accuracy") | |
| axes[1].set_xlim(0.3, 1.0) | |
| axes[1].set_ylim(0.25, 1.0) | |
| axes[1].grid(True, alpha=0.3) | |
| axes[1].legend(fontsize=8) | |
| c_labels = ["Cross-Entropy\nLoss", "ECE\n(10-bin)", "Brier\nScore", "Wrong-Pred\nConfidence"] | |
| c_fp = [ | |
| fp32_det["ep8_stress"]["loss"], | |
| fp32_det["ep8_stress"]["ece_10bin"], | |
| fp32_det["ep8_stress"]["brier_score"], | |
| fp32_det["ep8_stress"]["mean_wrong_confidence"], | |
| ] | |
| c_v5 = [ | |
| v5_det["ep8_stress"]["loss"], | |
| v5_det["ep8_stress"]["ece_10bin"], | |
| v5_det["ep8_stress"]["brier_score"], | |
| v5_det["ep8_stress"]["mean_wrong_confidence"], | |
| ] | |
| xc = np.arange(len(c_labels)) | |
| axes[2].bar(xc - w / 2, c_fp, width=w, label="Classical FP32 (Lower is Better)", color="tab:blue") | |
| axes[2].bar(xc + w / 2, c_v5, width=w, label="Adaptive V5 (Lower is Better)", color="tab:cyan") | |
| axes[2].set_xticks(xc) | |
| axes[2].set_xticklabels(c_labels, fontsize=8.5) | |
| axes[2].set_title("Overconfidence & Error Metrics (20k Stress, Ep. 8)") | |
| axes[2].grid(True, axis="y", alpha=0.3) | |
| axes[2].legend(fontsize=8) | |
| plt.tight_layout() | |
| plt.savefig(RESULTS_DIR / "v5_vs_fp32_validation.png", dpi=150) | |
| plt.close(fig) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--seed", type=int, default=123) | |
| parser.add_argument("--split-seed", type=int, default=42) | |
| parser.add_argument("--train-offset", type=int, default=25_000) | |
| parser.add_argument("--train-per-lang", type=int, default=25_000) | |
| parser.add_argument("--stress-offset", type=int, default=50_000) | |
| parser.add_argument("--stress-per-lang", type=int, default=10_000) | |
| parser.add_argument("--epochs", type=int, default=8) | |
| parser.add_argument("--batch-size", type=int, default=256) | |
| parser.add_argument("--lr", type=float, default=6e-4) | |
| parser.add_argument("--v5-min-stage1-epochs", type=int, default=3) | |
| parser.add_argument("--v5-max-stage1-epochs", type=int, default=5) | |
| parser.add_argument("--v5-cal-lr", type=float, default=1.2e-4) | |
| parser.add_argument("--v5-cal-dropout", type=float, default=0.15) | |
| parser.add_argument("--v5-cal-weight-decay", type=float, default=0.03) | |
| parser.add_argument("--v5-cal-label-smoothing", type=float, default=0.08) | |
| parser.add_argument("--v5-ema-decay", type=float, default=0.99) | |
| parser.add_argument("--v5-bit-cost-weight", type=float, default=0.008) | |
| parser.add_argument("--out-path", type=str, default=str(RESULTS_DIR / "v5_vs_fp32_validation.json")) | |
| args = parser.parse_args() | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| print(f"Independent Validation Device: {device}", flush=True) | |
| data = prepare_disjoint_xnli_splits( | |
| train_offset=args.train_offset, | |
| train_per_lang=args.train_per_lang, | |
| stress_offset=args.stress_offset, | |
| stress_per_lang=args.stress_per_lang, | |
| split_seed=args.split_seed, | |
| offline=True, | |
| ) | |
| tokenizer = data["tokenizer"] | |
| train_ds = XNLIPairDataset(data["train"], tokenizer, max_len=128) | |
| val_ds = XNLIPairDataset(data["validation"], tokenizer, max_len=128) | |
| test_ds = XNLIPairDataset(data["test"], tokenizer, max_len=128) | |
| stress_ds = XNLIPairDataset(data["stress"], tokenizer, max_len=128) | |
| val_loader = DataLoader(val_ds, batch_size=256, shuffle=False) | |
| test_loader = DataLoader(test_ds, batch_size=256, shuffle=False) | |
| stress_loader = DataLoader(stress_ds, batch_size=256, shuffle=False) | |
| cls_cfg = BilingualNLIConfig(vocab_size=tokenizer.get_vocab_size(), max_len=128) | |
| v5_cfg = BilingualNLIConfig( | |
| vocab_size=tokenizer.get_vocab_size(), | |
| max_len=128, | |
| protect_attention_and_head=True, | |
| attn_init_bits=2, | |
| head_init_bits=4, | |
| ) | |
| v5_router_cfg = RouterConfig( | |
| oscillation_band=0.1, | |
| min_delta=1e-5, | |
| oscillation_patience=1.95, | |
| osc_decay=0.70, | |
| warmup_steps=30, | |
| neuron_osc_threshold=0.11, | |
| max_verify_iters=2, | |
| loss_improvement_tol=1e-3, | |
| enable_rollback_penalty=True, | |
| rollback_min_loss_gain=1e-4, | |
| rollback_bit_cost_weight=args.v5_bit_cost_weight, | |
| rollback_cooldown_steps=12, | |
| rollback_patience_penalty=0.5, | |
| enforce_rollback_in_verify=True, | |
| strict_loss_gain_rollback=True, | |
| ) | |
| set_seed(args.seed) | |
| ref_model = BilingualNLITransformer(cls_cfg, use_quantization=False) | |
| init_state = {k: v.detach().clone() for k, v in ref_model.state_dict().items()} | |
| fp32_det: Dict[str, Any] = {} | |
| fp32_res = run_classical( | |
| cfg=cls_cfg, | |
| init_state=init_state, | |
| train_ds=train_ds, | |
| val_loader=val_loader, | |
| seen_loader=val_loader, | |
| test_loader=test_loader, | |
| device=device, | |
| epochs=args.epochs, | |
| batch_size=args.batch_size, | |
| lr=args.lr, | |
| seed=args.seed, | |
| eval_hook=make_eval_hook(fp32_det, test_loader, stress_loader, device), | |
| ) | |
| v5_det: Dict[str, Any] = {} | |
| v5_res = run_adaptive_v5( | |
| cfg=v5_cfg, | |
| router_cfg=v5_router_cfg, | |
| init_state=init_state, | |
| train_ds=train_ds, | |
| val_loader=val_loader, | |
| seen_loader=val_loader, | |
| test_loader=test_loader, | |
| device=device, | |
| epochs=args.epochs, | |
| max_stage1_epochs=args.v5_max_stage1_epochs, | |
| min_stage1_epochs=args.v5_min_stage1_epochs, | |
| batch_size=args.batch_size, | |
| lr=args.lr, | |
| cal_lr=args.v5_cal_lr, | |
| cal_dropout=args.v5_cal_dropout, | |
| cal_weight_decay=args.v5_cal_weight_decay, | |
| cal_label_smoothing=args.v5_cal_label_smoothing, | |
| ema_decay=args.v5_ema_decay, | |
| seed=args.seed, | |
| eval_hook=make_eval_hook(v5_det, test_loader, stress_loader, device), | |
| ) | |
| out = { | |
| "config": { | |
| "seed": args.seed, | |
| "data_summary": data["summary"], | |
| "device": torch.cuda.get_device_name(0) if device.type == "cuda" else "cpu", | |
| }, | |
| "classical_fp32": {**fp32_res, "detailed": fp32_det}, | |
| "adaptive_v5": {**v5_res, "detailed": v5_det}, | |
| } | |
| out_path = Path(args.out_path) | |
| out_path.parent.mkdir(parents=True, exist_ok=True) | |
| with open(out_path, "w", encoding="utf-8") as f: | |
| json.dump(out, f, indent=2, ensure_ascii=False) | |
| generate_validation_plot(fp32_det, v5_det, v5_res["final_avg_bits"]) | |
| print("\n=== INDEPENDENT DISJOINT-FOLD VALIDATION (seed=123, 20k Unseen Stress) ===", flush=True) | |
| for name, res, det in [ | |
| ("Classical FP32", fp32_res, fp32_det), | |
| ("Adaptive V5 ", v5_res, v5_det), | |
| ]: | |
| print( | |
| f"{name} | Ep.8 Test: {det['ep8_test']['acc']:.4f} (ECE={det['ep8_test']['ece_10bin']:.4f}) | " | |
| f"BestVal@{res['best_val_epoch']} Test: {det['best_val_test']['acc']:.4f} | " | |
| f"Stress20k Ep.8: {det['ep8_stress']['acc']:.4f} / Best: {det['best_val_stress']['acc']:.4f} | " | |
| f"Macro-F1: {det['best_val_test']['macro_f1']:.4f} | MeanBits: {res['final_avg_bits']:.2f}", | |
| flush=True, | |
| ) | |
| if __name__ == "__main__": | |
| main() | |