Download experiment_100m.py from Logn001/odpe-progressive-quantization: direct link, hf CLI and curl.
- Browser
- Download file 29.4 kB
-
https://huggingface.co/Logn001/odpe-progressive-quantization/resolve/main/experiment_100m.py
- Command line
-
hf download hf://Logn001/odpe-progressive-quantization/experiment_100m.py
-
curl -L -o experiment_100m.py https://huggingface.co/Logn001/odpe-progressive-quantization/resolve/main/experiment_100m.py
29.4 kB
| """100.5M-parameter Classical FP32 vs. Adaptive V5 scaling experiment on bilingual NLI. | |
| Supports both the initial 50,000-pair XNLI scaling baseline (`--dataset-mode xnli50k`) | |
| and the expanded multi-source 200,000-pair bilingual NLI retrain (`--dataset-mode expanded`) | |
| combining non-stress XNLI with external NLI sources (MoritzLaurer/multilingual-NLI-26lang-2mil7 | |
| ANLI/FEVER/LingNLI/WANLI and stanfordnlp/snli) while preserving strict separation from | |
| XNLI Validation (4,980), XNLI Test (10,020), and XNLI 20k Stress ([50k..60k)). | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import glob | |
| import json | |
| import os | |
| import random | |
| from pathlib import Path | |
| from typing import Any, Dict, List, Tuple | |
| 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 | |
| from datasets import load_dataset | |
| from torch.utils.data import DataLoader, Subset | |
| from adaptive_v5_series import run_adaptive_v5x | |
| from data_xnli import HF_CACHE_DIR, TOKENIZER_PATH, XNLIPairDataset, download_and_prepare_xnli | |
| from model import BilingualNLIConfig, BilingualNLITransformer, count_parameters | |
| from progressive_quant import BIT_LADDER_TERNARY, RouterConfig, effective_bits_for_code | |
| from validate_fp32_vs_v5 import make_eval_hook, prepare_disjoint_xnli_splits | |
| def stratified_sample_rows( | |
| rows: List[Dict[str, Any]], | |
| target_count: int, | |
| seed: int, | |
| ) -> List[Dict[str, Any]]: | |
| """Sample up to `target_count` rows cleanly with near-equal class balance over labels {0, 1, 2}.""" | |
| if target_count <= 0 or not rows: | |
| return [] | |
| rng = random.Random(seed) | |
| buckets: Dict[int, List[Dict[str, Any]]] = {0: [], 1: [], 2: []} | |
| for row in rows: | |
| lbl = int(row["label"]) | |
| if lbl in buckets: | |
| buckets[lbl].append(row) | |
| for lbl in buckets: | |
| rng.shuffle(buckets[lbl]) | |
| chosen: List[Dict[str, Any]] = [] | |
| idx_map = {0: 0, 1: 0, 2: 0} | |
| while len(chosen) < target_count: | |
| progressed = False | |
| for lbl in (0, 1, 2): | |
| if len(chosen) >= target_count: | |
| break | |
| pos = idx_map[lbl] | |
| if pos < len(buckets[lbl]): | |
| chosen.append(buckets[lbl][pos]) | |
| idx_map[lbl] = pos + 1 | |
| progressed = True | |
| if not progressed: | |
| break | |
| return chosen | |
| def prepare_expanded_bilingual_nli( | |
| xnli_per_lang: int = 60_000, | |
| ml_ru_count: int = 40_000, | |
| snli_en_count: int = 25_000, | |
| ml_en_count: int = 15_000, | |
| split_seed: int = 42, | |
| stress_offset: int = 50_000, | |
| stress_per_lang: int = 10_000, | |
| offline: bool = True, | |
| ) -> Dict[str, Any]: | |
| """Build a strictly stress-disjoint expanded bilingual NLI dataset from XNLI + ML-NLI + SNLI.""" | |
| from tokenizers import Tokenizer | |
| os.environ["HF_HOME"] = str(HF_CACHE_DIR) | |
| os.environ["HF_DATASETS_CACHE"] = str(HF_CACHE_DIR / "datasets") | |
| os.environ["HF_HUB_DISABLE_SYMLINKS_WARNING"] = "1" | |
| 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) | |
| stress_end = stress_offset + stress_per_lang | |
| avail_indices = list(range(0, stress_offset)) + list(range(stress_end, len(ru_shuffled))) | |
| if xnli_per_lang > len(avail_indices): | |
| raise ValueError(f"Requested {xnli_per_lang} non-stress XNLI rows, only {len(avail_indices)} available.") | |
| xnli_train_indices = avail_indices[:xnli_per_lang] | |
| def collect_xnli(ds, lang: str) -> List[Dict[str, Any]]: | |
| return [ | |
| {"premise": p, "hypothesis": h, "label": int(lbl), "lang": lang} | |
| for p, h, lbl in zip(ds["premise"], ds["hypothesis"], ds["label"]) | |
| ] | |
| val_rows = collect_xnli(ru_ds["validation"], "ru") + collect_xnli(en_ds["validation"], "en") | |
| test_rows = collect_xnli(ru_ds["test"], "ru") + collect_xnli(en_ds["test"], "en") | |
| stress_idx = range(stress_offset, stress_end) | |
| stress_rows = collect_xnli(ru_shuffled.select(stress_idx), "ru") + collect_xnli( | |
| en_shuffled.select(stress_idx), "en" | |
| ) | |
| eval_keys = {(r["premise"], r["hypothesis"], r["lang"]) for r in val_rows + test_rows + stress_rows} | |
| def pick_clean_xnli(ds_shuffled, lang: str) -> List[Dict[str, Any]]: | |
| selected: List[Dict[str, Any]] = [] | |
| sub = ds_shuffled.select(avail_indices[: xnli_per_lang + 512]) | |
| for p, h, lbl in zip(sub["premise"], sub["hypothesis"], sub["label"]): | |
| if (p, h, lang) in eval_keys: | |
| continue | |
| selected.append({"premise": p, "hypothesis": h, "label": int(lbl), "lang": lang}) | |
| if len(selected) >= xnli_per_lang: | |
| break | |
| if len(selected) < xnli_per_lang: | |
| raise ValueError(f"Only found {len(selected)} clean non-eval XNLI rows for {lang}") | |
| return selected | |
| xnli_ru_rows = pick_clean_xnli(ru_shuffled, "ru") | |
| xnli_en_rows = pick_clean_xnli(en_shuffled, "en") | |
| # External RU & EN from MoritzLaurer/multilingual-NLI-26lang-2mil7 (excluding MNLI to avoid XNLI overlap). | |
| ml_patterns = [ | |
| ("anli", "ru_anli-*.parquet"), | |
| ("fever", "ru_fever-*.parquet"), | |
| ("ling", "ru_ling-*.parquet"), | |
| ("wanli", "ru_wanli-*.parquet"), | |
| ] | |
| ml_all_rows: List[Tuple[int, Dict[str, Any], Dict[str, Any]]] = [] | |
| global_idx = 0 | |
| for _, pat in ml_patterns: | |
| files = sorted( | |
| glob.glob(str(HF_CACHE_DIR / "hub" / "datasets--MoritzLaurer--multilingual-NLI-26lang-2mil7" / "snapshots" / "*" / "data" / pat)) | |
| ) | |
| if not files: | |
| raise FileNotFoundError(f"Missing cached ML-NLI parquet for pattern {pat}") | |
| ds_part = load_dataset("parquet", data_files=files, split="train") | |
| for p_ru, h_ru, p_en, h_en, lbl in zip( | |
| ds_part["premise"], | |
| ds_part["hypothesis"], | |
| ds_part["premise_original"], | |
| ds_part["hypothesis_original"], | |
| ds_part["label"], | |
| ): | |
| lbl_i = int(lbl) | |
| ru_item = {"premise": p_ru, "hypothesis": h_ru, "label": lbl_i, "lang": "ru", "_ml_id": global_idx} | |
| en_item = {"premise": p_en, "hypothesis": h_en, "label": lbl_i, "lang": "en", "_ml_id": global_idx} | |
| ml_all_rows.append((global_idx, ru_item, en_item)) | |
| global_idx += 1 | |
| ml_ru_candidates = [pair[1] for pair in ml_all_rows if (pair[1]["premise"], pair[1]["hypothesis"], "ru") not in eval_keys] | |
| ml_ru_selected = stratified_sample_rows(ml_ru_candidates, ml_ru_count, seed=split_seed + 11) | |
| used_ml_ids = {item["_ml_id"] for item in ml_ru_selected} | |
| for item in ml_ru_selected: | |
| item.pop("_ml_id", None) | |
| # Disjoint English originals (strictly different source rows from the selected RU pairs). | |
| ml_en_candidates = [ | |
| pair[2] | |
| for pair in ml_all_rows | |
| if pair[0] not in used_ml_ids and (pair[2]["premise"], pair[2]["hypothesis"], "en") not in eval_keys | |
| ] | |
| ml_en_selected = stratified_sample_rows(ml_en_candidates, ml_en_count, seed=split_seed + 17) | |
| for item in ml_en_selected: | |
| item.pop("_ml_id", None) | |
| # External English SNLI (non-overlapping image-caption entailment domain). | |
| snli_files = sorted( | |
| glob.glob(str(HF_CACHE_DIR / "hub" / "datasets--stanfordnlp--snli" / "snapshots" / "*" / "plain_text" / "train-*.parquet")) | |
| ) | |
| if not snli_files: | |
| raise FileNotFoundError("Missing cached SNLI parquet files") | |
| snli_ds = load_dataset("parquet", data_files=snli_files, split="train") | |
| snli_candidates = [ | |
| {"premise": p, "hypothesis": h, "label": int(lbl), "lang": "en"} | |
| for p, h, lbl in zip(snli_ds["premise"], snli_ds["hypothesis"], snli_ds["label"]) | |
| if int(lbl) in (0, 1, 2) and (p, h, "en") not in eval_keys | |
| ] | |
| snli_en_selected = stratified_sample_rows(snli_candidates, snli_en_count, seed=split_seed + 23) | |
| ru_rows = xnli_ru_rows + ml_ru_selected | |
| en_rows = xnli_en_rows + snli_en_selected + ml_en_selected | |
| train_rows = ru_rows + en_rows | |
| tokenizer = Tokenizer.from_file(str(TOKENIZER_PATH)) | |
| return { | |
| "train": train_rows, | |
| "validation": val_rows, | |
| "test": test_rows, | |
| "stress": stress_rows, | |
| "tokenizer": tokenizer, | |
| "summary": { | |
| "dataset_mode": "expanded", | |
| "train_total": len(train_rows), | |
| "train_ru": len(ru_rows), | |
| "train_en": len(en_rows), | |
| "val_total": len(val_rows), | |
| "test_total": len(test_rows), | |
| "stress_total": len(stress_rows), | |
| "vocab_size": tokenizer.get_vocab_size(), | |
| "tokenizer_path": str(TOKENIZER_PATH), | |
| "stress_range": [stress_offset, stress_end], | |
| "source_breakdown": { | |
| "xnli_ru": len(xnli_ru_rows), | |
| "ml_nli_ru_anli_fever_ling_wanli": len(ml_ru_selected), | |
| "xnli_en": len(xnli_en_rows), | |
| "snli_en": len(snli_en_selected), | |
| "ml_nli_en_orig_disjoint": len(ml_en_selected), | |
| }, | |
| }, | |
| } | |
| def make_100m_v6_spec( | |
| vocab_size: int, | |
| args: argparse.Namespace, | |
| ) -> Tuple[BilingualNLIConfig, RouterConfig, Dict[str, Any]]: | |
| """Build 100M Adaptive V6 spec transferring V5.8 technologies cleanly to 99.17M / 200k scale.""" | |
| cfg = BilingualNLIConfig( | |
| vocab_size=vocab_size, | |
| max_len=128, | |
| d_model=768, | |
| n_heads=12, | |
| n_layers=12, | |
| d_ff=2240, | |
| initial_bits=10, | |
| protect_attention_and_head=True, | |
| attn_init_bits=16, | |
| head_init_bits=40, | |
| attn_bit_cost_scale=0.75, | |
| head_bit_cost_scale=0.35, | |
| ffn_bit_cost_scale=1.15, | |
| ste_clip=True, | |
| use_tier_scales=True, | |
| group_size=64, | |
| precision_tenths=True, | |
| backbone_max_bits=80, | |
| head_max_bits=160, | |
| use_rms_norm=True, | |
| use_rope=True, | |
| use_qk_norm=True, | |
| use_swiglu=True, | |
| ) | |
| router_cfg = RouterConfig( | |
| bit_ladder=BIT_LADDER_TERNARY, | |
| precision_tenths=True, | |
| oscillation_band=0.1, | |
| min_delta=1e-5, | |
| oscillation_patience=1.95, | |
| osc_decay=0.70, | |
| warmup_steps=args.warmup_steps, | |
| 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=0.015, | |
| rollback_cooldown_steps=28, | |
| rollback_patience_penalty=0.5, | |
| enforce_rollback_in_verify=True, | |
| strict_loss_gain_rollback=True, | |
| use_weighted_bit_cost=True, | |
| unit_fraction_penalty=True, | |
| track_salience=True, | |
| use_salience_gating=True, | |
| salience_ema_decay=0.92, | |
| salience_min_ratio=0.65, | |
| ) | |
| run_kw: Dict[str, Any] = dict( | |
| epochs=args.epochs, | |
| min_stage1_epochs=args.min_stage1_epochs, | |
| max_stage1_epochs=args.max_stage1_epochs, | |
| batch_size=args.batch_size, | |
| lr=args.v6_lr, | |
| select_best_in_stage2=True, | |
| val_loss_weight=0.12, | |
| tier_scale_lr_mult=2.5, | |
| do_consolidate_down=True, | |
| consolidate_fractions=(0.15, 0.30, 0.45), | |
| consolidate_max_loss_inc=0.004, | |
| bit_cost_curriculum=(0.65, 1.40), | |
| verify_eval_batches=2, | |
| stage1_label_smoothing=0.03, | |
| stage1_emb_lr_mult=0.80, | |
| stage1_emb_weight_decay=0.025, | |
| stage2_ema_distill_weight=0.12, | |
| stage2_distill_temp=2.0, | |
| sam_rho=args.v6_sam_rho, | |
| sam_interval=args.v6_sam_interval, | |
| emb_lr_mult=0.50, | |
| emb_weight_decay=0.06, | |
| cal_lr=9.0e-5, | |
| cal_dropout=0.14, | |
| cal_weight_decay=0.04, | |
| cal_label_smoothing=0.07, | |
| ema_decay=0.9988, | |
| log_every_steps=625, | |
| ) | |
| return cfg, router_cfg, run_kw | |
| def generate_100m_plots( | |
| results: Dict[str, Any], | |
| curves_path: Path | None = None, | |
| comparison_path: Path | None = None, | |
| title_tag: str = "100.5M", | |
| ) -> None: | |
| """Plot 100M Classical FP32 vs Adaptive V5 / Adaptive V6 validation curves, bits, and splits.""" | |
| RESULTS_DIR.mkdir(parents=True, exist_ok=True) | |
| curves_out = curves_path or (RESULTS_DIR / "experiment_100m_curves.png") | |
| comparison_out = comparison_path or (RESULTS_DIR / "experiment_100m_comparison.png") | |
| fp_res = results["classical_fp32"] | |
| series = [("classical_fp32", "Classical FP32", "o", "tab:blue", "--")] | |
| if "adaptive_v5" in results: | |
| series.append(("adaptive_v5", "Adaptive V5", "P", "tab:cyan", "-")) | |
| if "adaptive_v6" in results: | |
| series.append(("adaptive_v6", "Adaptive V6 (V5.8)", "^", "tab:green", "-")) | |
| fig, axes = plt.subplots(1, 3, figsize=(16.0, 4.8)) | |
| for key, label, marker, color, ls in series: | |
| hist = results[key]["history"] | |
| eps = [h["epoch"] for h in hist] | |
| axes[0].plot(eps, [h["val_acc"] * 100 for h in hist], f"{marker}-", color=color, linewidth=2.1, label=label) | |
| axes[1].plot(eps, [h["val_loss"] for h in hist], f"{marker}-", color=color, linewidth=2.0, label=f"{label} Val") | |
| axes[1].plot(eps, [h["train_loss"] for h in hist], f"{marker}--", color=color, alpha=0.45, label=f"{label} Train") | |
| if key != "classical_fp32": | |
| bits = results[key]["final_avg_bits"] | |
| axes[2].plot(eps, [h["avg_bits"] for h in hist], f"{marker}-", color=color, linewidth=2.1, label=f"{label} ({bits:.2f}b)") | |
| axes[0].set_title(f"{title_tag} Validation Accuracy (%)") | |
| axes[0].set_xlabel("Epoch") | |
| axes[0].set_ylabel("Accuracy (%)") | |
| axes[0].grid(True, alpha=0.3) | |
| axes[0].legend(fontsize=8) | |
| axes[1].set_title(f"{title_tag} Cross-Entropy Loss") | |
| axes[1].set_xlabel("Epoch") | |
| axes[1].set_ylabel("Loss") | |
| axes[1].grid(True, alpha=0.3) | |
| axes[1].legend(fontsize=7) | |
| axes[2].axhline(32.0, linestyle="--", color="gray", label="Classical FP32 (32b)") | |
| axes[2].set_title(f"{title_tag} Mean Linear Bit-Width") | |
| axes[2].set_xlabel("Epoch") | |
| axes[2].set_ylabel("Bits per Parameter") | |
| axes[2].set_ylim(0, 34) | |
| axes[2].grid(True, alpha=0.3) | |
| axes[2].legend(fontsize=8) | |
| plt.tight_layout() | |
| plt.savefig(curves_out, dpi=150) | |
| plt.close(fig) | |
| fig, axes = plt.subplots(1, 2, figsize=(14.5, 4.8)) | |
| quant_key = "adaptive_v6" if "adaptive_v6" in results else "adaptive_v5" | |
| q_res = results[quant_key] | |
| q_title = "V6" if quant_key == "adaptive_v6" else "V5" | |
| is_tenths = quant_key == "adaptive_v6" | |
| ladder = list(BIT_LADDER_TERNARY) if is_tenths else [1, 2, 4, 8, 16, 32] | |
| raw_counts = q_res["final_bit_counts"] | |
| tot_p = max(1, sum(int(v) for v in raw_counts.values())) | |
| pcts = [100.0 * int(raw_counts.get(str(b), raw_counts.get(b, 0))) / tot_p for b in ladder] | |
| b_labels = [] | |
| for b in ladder: | |
| eff_b = effective_bits_for_code(b, precision_tenths=is_tenths) | |
| if eff_b >= 32.0: | |
| b_labels.append("FP32") | |
| elif abs(eff_b - 1.5849625) < 0.05: | |
| b_labels.append("1.58b") | |
| else: | |
| b_labels.append(f"{int(round(eff_b))}b") | |
| axes[0].bar(np.arange(len(b_labels)), pcts, color="tab:green" if is_tenths else "tab:cyan") | |
| axes[0].set_xticks(np.arange(len(b_labels))) | |
| axes[0].set_xticklabels(b_labels) | |
| axes[0].set_ylabel("Linear Params (%)") | |
| axes[0].set_title(f"{title_tag} {q_title} Bit Allocation ({q_res['final_avg_bits']:.2f}b / {q_res['memory_summary']['compression_ratio']:.2f}x)") | |
| axes[0].grid(True, axis="y", alpha=0.3) | |
| cats = ["Seen\nProbe", "Test\nFinal", "Test\nBestVal", "Stress 20k\nFinal", "Stress 20k\nBestVal"] | |
| x = np.arange(len(cats)) | |
| n_series = len(series) | |
| w = 0.78 / n_series | |
| for idx, (key, label, _, color, _) in enumerate(series): | |
| m_res = results[key] | |
| m_det = m_res["detailed"] | |
| vals = [ | |
| m_res["seen_train_probe"]["acc"] * 100, | |
| m_det["ep8_test"]["acc"] * 100, | |
| m_det["best_val_test"]["acc"] * 100, | |
| m_det["ep8_stress"]["acc"] * 100, | |
| m_det["best_val_stress"]["acc"] * 100, | |
| ] | |
| offset = (idx - (n_series - 1) / 2.0) * w | |
| axes[1].bar(x + offset, vals, width=w, color=color, label=label) | |
| axes[1].set_xticks(x) | |
| axes[1].set_xticklabels(cats) | |
| axes[1].set_ylim(0, 102) | |
| axes[1].set_ylabel("Accuracy (%)") | |
| axes[1].set_title(f"{title_tag} Generalization & Overfitting Comparison") | |
| axes[1].grid(True, axis="y", alpha=0.3) | |
| axes[1].legend(fontsize=8) | |
| plt.tight_layout() | |
| plt.savefig(comparison_out, dpi=150) | |
| plt.close(fig) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--seed", type=int, default=42) | |
| parser.add_argument("--dataset-mode", type=str, default="xnli50k", choices=["xnli50k", "expanded"]) | |
| parser.add_argument("--epochs", type=int, default=6) | |
| parser.add_argument("--batch-size", type=int, default=64) | |
| parser.add_argument("--max-train-per-lang", type=int, default=25_000) | |
| parser.add_argument("--xnli-per-lang", type=int, default=60_000) | |
| parser.add_argument("--ml-ru-count", type=int, default=40_000) | |
| parser.add_argument("--snli-en-count", type=int, default=25_000) | |
| parser.add_argument("--ml-en-count", type=int, default=15_000) | |
| parser.add_argument("--lr", type=float, default=3e-4) | |
| parser.add_argument("--min-stage1-epochs", type=int, default=2) | |
| parser.add_argument("--max-stage1-epochs", type=int, default=4) | |
| parser.add_argument("--cal-lr", type=float, default=8e-5) | |
| parser.add_argument("--cal-dropout", type=float, default=0.15) | |
| parser.add_argument("--cal-weight-decay", type=float, default=0.03) | |
| parser.add_argument("--cal-label-smoothing", type=float, default=0.08) | |
| parser.add_argument("--ema-decay", type=float, default=0.997) | |
| parser.add_argument("--bit-cost-weight", type=float, default=0.015) | |
| parser.add_argument("--warmup-steps", type=int, default=120) | |
| parser.add_argument("--cooldown-steps", type=int, default=24) | |
| parser.add_argument("--matmul-precision", type=str, default="high", choices=["highest", "high", "medium"]) | |
| parser.add_argument("--mode", type=str, default="v5", choices=["v5", "v6", "both"]) | |
| parser.add_argument("--v6-lr", type=float, default=3.2e-4) | |
| parser.add_argument("--v6-sam-rho", type=float, default=0.025) | |
| parser.add_argument("--v6-sam-interval", type=int, default=3) | |
| parser.add_argument("--out-path", type=str, default="") | |
| parser.add_argument("--curves-out", type=str, default="") | |
| parser.add_argument("--comparison-out", type=str, default="") | |
| parser.add_argument("--resume-dir", type=str, default="") | |
| args = parser.parse_args() | |
| if not args.out_path: | |
| default_name = ( | |
| "experiment_100m_expanded_results.json" | |
| if args.dataset_mode == "expanded" | |
| else "experiment_100m_results.json" | |
| ) | |
| args.out_path = str(RESULTS_DIR / default_name) | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| if device.type == "cuda": | |
| torch.set_float32_matmul_precision(args.matmul_precision) | |
| print( | |
| f"100M Experiment Device: {device}" | |
| + (f" ({torch.cuda.get_device_name(0)}, matmul={args.matmul_precision})" if device.type == "cuda" else ""), | |
| flush=True, | |
| ) | |
| if args.dataset_mode == "expanded": | |
| data = prepare_expanded_bilingual_nli( | |
| xnli_per_lang=args.xnli_per_lang, | |
| ml_ru_count=args.ml_ru_count, | |
| snli_en_count=args.snli_en_count, | |
| ml_en_count=args.ml_en_count, | |
| split_seed=args.seed, | |
| offline=True, | |
| ) | |
| stress_rows = data["stress"] | |
| else: | |
| data = download_and_prepare_xnli( | |
| max_train_per_lang=args.max_train_per_lang, | |
| seed=args.seed, | |
| offline=True, | |
| ) | |
| stress_data = prepare_disjoint_xnli_splits( | |
| train_offset=25_000, | |
| train_per_lang=0, | |
| stress_offset=50_000, | |
| stress_per_lang=10_000, | |
| split_seed=args.seed, | |
| offline=True, | |
| ) | |
| stress_rows = stress_data["stress"] | |
| tokenizer = data["tokenizer"] | |
| print(f"Dataset Summary: {data['summary']}", flush=True) | |
| 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(stress_rows, tokenizer, max_len=128) | |
| n_ru = int(data["summary"]["train_ru"]) | |
| n_tot = len(train_ds) | |
| rng_probe = random.Random(args.seed + 99) | |
| ru_probe = sorted(rng_probe.sample(range(n_ru), min(1000, n_ru))) | |
| en_probe = sorted(rng_probe.sample(range(n_ru, n_tot), min(1000, n_tot - n_ru))) | |
| seen_probe_ds = Subset(train_ds, ru_probe + en_probe) | |
| val_loader = DataLoader(val_ds, batch_size=128, shuffle=False) | |
| seen_loader = DataLoader(seen_probe_ds, batch_size=128, shuffle=False) | |
| test_loader = DataLoader(test_ds, batch_size=128, shuffle=False) | |
| stress_loader = DataLoader(stress_ds, batch_size=128, shuffle=False) | |
| cls_cfg = BilingualNLIConfig( | |
| vocab_size=tokenizer.get_vocab_size(), | |
| max_len=128, | |
| d_model=768, | |
| n_heads=12, | |
| n_layers=12, | |
| d_ff=3424, | |
| ) | |
| v5_cfg = BilingualNLIConfig( | |
| vocab_size=tokenizer.get_vocab_size(), | |
| max_len=128, | |
| d_model=768, | |
| n_heads=12, | |
| n_layers=12, | |
| d_ff=3424, | |
| 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=args.warmup_steps, | |
| 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.bit_cost_weight, | |
| rollback_cooldown_steps=args.cooldown_steps, | |
| 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) | |
| pinfo = count_parameters(ref_model) | |
| print(f"100M Architecture params: {pinfo}", flush=True) | |
| init_state = {k: v.detach().clone() for k, v in ref_model.state_dict().items()} | |
| out_path = Path(args.out_path) | |
| out_path.parent.mkdir(parents=True, exist_ok=True) | |
| resume_dir = Path(args.resume_dir) if args.resume_dir else None | |
| cls_ckpt = (resume_dir / "classical_fp32_resume.pt") if resume_dir is not None else None | |
| v5_ckpt = (resume_dir / "adaptive_v5_resume.pt") if resume_dir is not None else None | |
| base_results: Dict[str, Any] = { | |
| "config": { | |
| "scale": "100M", | |
| "params": pinfo, | |
| "training": vars(args), | |
| "dataset_summary": {**data["summary"], "stress_total": len(stress_ds)}, | |
| "device": torch.cuda.get_device_name(0) if device.type == "cuda" else "cpu", | |
| } | |
| } | |
| if out_path.exists(): | |
| try: | |
| existing = json.loads(out_path.read_text(encoding="utf-8")) | |
| except Exception: | |
| existing = {} | |
| else: | |
| existing = {} | |
| if "classical_fp32" in existing and "detailed" in existing["classical_fp32"]: | |
| fp32_res = existing["classical_fp32"] | |
| fp32_det = fp32_res["detailed"] | |
| base_results["classical_fp32"] = fp32_res | |
| print(f"Loaded completed Classical FP32 results from {out_path}", flush=True) | |
| else: | |
| fp32_det = {} | |
| fp32_res = run_classical( | |
| cfg=cls_cfg, | |
| init_state=init_state, | |
| train_ds=train_ds, | |
| val_loader=val_loader, | |
| seen_loader=seen_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), | |
| resume_file=cls_ckpt, | |
| ) | |
| base_results["classical_fp32"] = {**fp32_res, "detailed": fp32_det} | |
| with open(out_path, "w", encoding="utf-8") as f: | |
| json.dump(base_results, f, indent=2, ensure_ascii=False) | |
| print(f"Saved intermediate Classical FP32 results to {out_path}", flush=True) | |
| if device.type == "cuda": | |
| torch.cuda.empty_cache() | |
| results = dict(base_results) | |
| if "adaptive_v5" in existing: | |
| results["adaptive_v5"] = existing["adaptive_v5"] | |
| if args.mode in ("v5", "both"): | |
| 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=seen_loader, | |
| test_loader=test_loader, | |
| device=device, | |
| epochs=args.epochs, | |
| max_stage1_epochs=args.max_stage1_epochs, | |
| min_stage1_epochs=args.min_stage1_epochs, | |
| batch_size=args.batch_size, | |
| lr=args.lr, | |
| cal_lr=args.cal_lr, | |
| cal_dropout=args.cal_dropout, | |
| cal_weight_decay=args.cal_weight_decay, | |
| cal_label_smoothing=args.cal_label_smoothing, | |
| ema_decay=args.ema_decay, | |
| seed=args.seed, | |
| eval_hook=make_eval_hook(v5_det, test_loader, stress_loader, device), | |
| resume_file=v5_ckpt, | |
| ) | |
| results["adaptive_v5"] = {**v5_res, "detailed": v5_det} | |
| with open(out_path, "w", encoding="utf-8") as f: | |
| json.dump(results, f, indent=2, ensure_ascii=False) | |
| if args.mode in ("v6", "both"): | |
| if device.type == "cuda": | |
| torch.cuda.empty_cache() | |
| v6_cfg, v6_router_cfg, v6_run_kw = make_100m_v6_spec(tokenizer.get_vocab_size(), args) | |
| v6_ckpt = (resume_dir / "adaptive_v6_resume.pt") if resume_dir is not None else None | |
| print( | |
| f"\n=== Running Adaptive V6 (100M / d_ff={v6_cfg.d_ff}) transferring V5.8 technologies ===", | |
| flush=True, | |
| ) | |
| v6_res = run_adaptive_v5x( | |
| variant_name="adaptive_v6_100m", | |
| cfg=v6_cfg, | |
| router_cfg=v6_router_cfg, | |
| init_state=init_state, | |
| train_ds=train_ds, | |
| val_loader=val_loader, | |
| seen_loader=seen_loader, | |
| test_loader=test_loader, | |
| stress_loader=stress_loader, | |
| device=device, | |
| seed=args.seed, | |
| resume_file=v6_ckpt, | |
| **v6_run_kw, | |
| ) | |
| results["adaptive_v6"] = v6_res | |
| with open(out_path, "w", encoding="utf-8") as f: | |
| json.dump(results, f, indent=2, ensure_ascii=False) | |
| tag = "100M (200k Multi-Source)" if args.dataset_mode == "expanded" else "100M" | |
| curves_out = Path(args.curves_out) if args.curves_out else ( | |
| RESULTS_DIR / ("experiment_100m_expanded_curves.png" if args.dataset_mode == "expanded" else "experiment_100m_curves.png") | |
| ) | |
| comparison_out = Path(args.comparison_out) if args.comparison_out else ( | |
| RESULTS_DIR / ("experiment_100m_expanded_comparison.png" if args.dataset_mode == "expanded" else "experiment_100m_comparison.png") | |
| ) | |
| generate_100m_plots(results, curves_path=curves_out, comparison_path=comparison_out, title_tag=tag) | |
| print("\n=== 100M COMPARISON SUMMARY ===", flush=True) | |
| print( | |
| f"Classical FP32 (100.5M) | Final Test: {fp32_det['ep8_test']['acc']:.4f} (ECE={fp32_det['ep8_test']['ece_10bin']:.4f}) | " | |
| f"BestVal@{fp32_res['best_val_epoch']} Test: {fp32_det['best_val_test']['acc']:.4f} | " | |
| f"Stress20k: {fp32_det['ep8_stress']['acc']:.4f} / {fp32_det['best_val_stress']['acc']:.4f} | " | |
| f"Seen: {fp32_res['seen_train_probe']['acc']:.4f} | Wall: {fp32_res['wall_sec']:.1f}s", | |
| flush=True, | |
| ) | |
| for k, title in (("adaptive_v5", "Adaptive V5 (100.5M)"), ("adaptive_v6", "Adaptive V6 (99.2M)")): | |
| if k not in results: | |
| continue | |
| r_m = results[k] | |
| d_m = r_m["detailed"] | |
| print( | |
| f"{title} | Final Test: {d_m['ep8_test']['acc']:.4f} (ECE={d_m['ep8_test']['ece_10bin']:.4f}) | " | |
| f"BestVal@{r_m['best_val_epoch']} Test: {d_m['best_val_test']['acc']:.4f} | " | |
| f"Stress20k: {d_m['ep8_stress']['acc']:.4f} / {d_m['best_val_stress']['acc']:.4f} | " | |
| f"Seen: {r_m['seen_train_probe']['acc']:.4f} | Bits: {r_m['final_avg_bits']:.2f} " | |
| f"({r_m['memory_summary']['compression_ratio']:.2f}x) | Wall: {r_m['wall_sec']:.1f}s", | |
| flush=True, | |
| ) | |
| if __name__ == "__main__": | |
| main() | |