"""Reproduce and export ready-to-use Classical FP32 and Adaptive V5 checkpoints (.safetensors).""" from __future__ import annotations import json from pathlib import Path from typing import Dict import torch from safetensors.torch import save_file from torch.utils.data import DataLoader, Subset from data_xnli import XNLIPairDataset, download_and_prepare_xnli from model import BilingualNLIConfig, BilingualNLITransformer, count_parameters from progressive_quant import PrecisionRouter, RouterConfig, pack_quantized_state_dict from train_experiment import _reallocate_all_blocks, run_adaptive_v5, run_classical, set_seed PROJECT_DIR = Path(__file__).resolve().parent CKPT_DIR = PROJECT_DIR / "checkpoints" def export_checkpoints(seed: int = 42, epochs: int = 8, batch_size: int = 256, lr: float = 6e-4) -> Dict[str, str]: CKPT_DIR.mkdir(parents=True, exist_ok=True) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(f"Exporting ready models on {device} (seed={seed})...", flush=True) data = download_and_prepare_xnli(max_train_per_lang=25_000, seed=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) n_ru = data["summary"]["train_ru"] probe_idx = list(range(min(1000, n_ru))) + list(range(n_ru, min(n_ru + 1000, len(train_ds)))) seen_probe_ds = Subset(train_ds, probe_idx) val_loader = DataLoader(val_ds, batch_size=256, shuffle=False) seen_loader = DataLoader(seen_probe_ds, batch_size=256, shuffle=False) test_loader = DataLoader(test_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=0.008, rollback_cooldown_steps=12, rollback_patience_penalty=0.5, enforce_rollback_in_verify=True, strict_loss_gain_rollback=True, ) set_seed(seed) ref_model = BilingualNLITransformer(cls_cfg, use_quantization=False) init_state = {k: v.detach().clone() for k, v in ref_model.state_dict().items()} saved: Dict[str, str] = {} def save_hook(prefix: str): def _hook(tag: str, model: BilingualNLITransformer) -> None: out_path = CKPT_DIR / f"{prefix}_{tag}.safetensors" tensors = {k: v.detach().cpu().contiguous() for k, v in model.state_dict().items()} save_file(tensors, str(out_path)) saved[f"{prefix}_{tag}"] = str(out_path) print(f"Saved checkpoint: {out_path}", flush=True) return _hook cls_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=epochs, batch_size=batch_size, lr=lr, seed=seed, eval_hook=save_hook("classical_fp32"), ) 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=epochs, max_stage1_epochs=5, min_stage1_epochs=3, batch_size=batch_size, lr=lr, cal_lr=1.2e-4, cal_dropout=0.15, cal_weight_decay=0.03, cal_label_smoothing=0.08, ema_decay=0.99, seed=seed, eval_hook=save_hook("adaptive_v5"), ) cfg_out = CKPT_DIR / "config.json" with open(cfg_out, "w", encoding="utf-8") as f: json.dump( { "architecture": "BilingualNLITransformer", "author": "Levon Ginosyan (Logn001)", "license": "apache-2.0", "seed": seed, "model_config": v5_cfg.__dict__, "id2label": {"0": "entailment", "1": "neutral", "2": "contradiction"}, "checkpoints": { "classical_fp32_ep8": "classical_fp32_ep8.safetensors", "classical_fp32_best_val": "classical_fp32_best_val.safetensors", "adaptive_v5_ep8_ema": "adaptive_v5_ep8.safetensors", "adaptive_v5_best_val_ema": "adaptive_v5_best_val.safetensors", }, "metrics": { "classical_fp32_ep8_test_acc": cls_res["test"]["acc"], "adaptive_v5_ep8_test_acc": v5_res["test"]["acc"], "adaptive_v5_best_val_test_acc": v5_res["best_val_ckpt_test"]["acc"], "adaptive_v5_avg_bits": v5_res["final_avg_bits"], "adaptive_v5_compression": v5_res["memory_summary"]["compression_ratio"], }, }, f, indent=2, ensure_ascii=False, ) saved["config"] = str(cfg_out) print(f"Saved config: {cfg_out}", flush=True) return saved def export_v6_100m_from_resume( resume_pt: Path = PROJECT_DIR / ".ckpt_100m_v6" / "adaptive_v6_resume.pt", results_json: Path = PROJECT_DIR / "results" / "experiment_100m_expanded_results.json", ) -> Dict[str, str]: """Export bit-packed Adaptive V6 100M checkpoints (.safetensors) and config_v6_100m.json.""" import argparse from experiment_100m import make_100m_v6_spec CKPT_DIR.mkdir(parents=True, exist_ok=True) ckpt = torch.load(resume_pt, map_location="cpu", weights_only=False) ns = argparse.Namespace( warmup_steps=250, epochs=4, min_stage1_epochs=2, max_stage1_epochs=2, batch_size=64, v6_lr=3.2e-4, v6_sam_rho=0.025, v6_sam_interval=3, ) v6_cfg, v6_rcfg, _ = make_100m_v6_spec(10_000, ns) model = BilingualNLITransformer(v6_cfg, use_quantization=True) router = PrecisionRouter(v6_rcfg) saved: Dict[str, str] = {} # 1. Export Best-Val@Ep.3 checkpoint model.load_state_dict(ckpt["best_val_state"]) _reallocate_all_blocks(model) best_packed = pack_quantized_state_dict(model) best_path = CKPT_DIR / "adaptive_v6_100m_best_val.safetensors" save_file(best_packed, str(best_path)) saved["best_val"] = str(best_path) # 2. Export Final Ep.4 checkpoint (EMA weights + frozen model buffers) model.load_state_dict(ckpt["model"]) for name, param in model.named_parameters(): if name in ckpt["ema_state"]: param.data.copy_(ckpt["ema_state"][name]) _reallocate_all_blocks(model) final_packed = pack_quantized_state_dict(model) final_path = CKPT_DIR / "adaptive_v6_100m_final.safetensors" save_file(final_packed, str(final_path)) saved["final"] = str(final_path) snap = router.snapshot_stats(model) pinfo = count_parameters(model) metrics: Dict[str, object] = {} if results_json.exists(): rj = json.loads(results_json.read_text(encoding="utf-8")) if "adaptive_v6" in rj: v6 = rj["adaptive_v6"] d = v6["detailed"] metrics = { "best_val_epoch": v6["best_val_epoch"], "final_avg_bits": v6["final_avg_bits"], "compression_ratio_weights": v6["memory_summary"]["compression_ratio"], "effective_bits_with_group64_scales": v6["memory_summary"]["effective_avg_bits_with_scales"], "compression_ratio_with_scales": v6["memory_summary"]["compression_with_scales"], "test_final_acc": d["ep8_test"]["acc"], "test_best_val_acc": d["best_val_test"]["acc"], "stress_20k_final_acc": d["ep8_stress"]["acc"], "stress_20k_best_val_acc": d["best_val_stress"]["acc"], "ece_test_best_val": d["best_val_test"]["ece_10bin"], "ece_test_final": d["ep8_test"]["ece_10bin"], "macro_f1_stress_final": d["ep8_stress"]["macro_f1"], } cfg_v6_out = CKPT_DIR / "config_v6_100m.json" with open(cfg_v6_out, "w", encoding="utf-8") as f: json.dump( { "architecture": "BilingualNLITransformer", "variant": "Adaptive V6 100M (V5.8 stack)", "author": "Levon Ginosyan (Logn001)", "license": "apache-2.0", "seed": 42, "params": pinfo, "packed_format": { "version": 1, "packing": "1b->uint8(8/byte), 1.585b->uint8(base3,5/byte), 2b->uint8(4/byte), 4b->uint8(2/byte), 8b->int8, group64_scales->fp16, tok_emb->fp16", "best_val_file_mb": round(best_path.stat().st_size / (1024 * 1024), 2), "final_file_mb": round(final_path.stat().st_size / (1024 * 1024), 2), }, "model_config": v6_cfg.__dict__, "id2label": {"0": "entailment", "1": "neutral", "2": "contradiction"}, "checkpoints": { "adaptive_v6_100m_best_val": "adaptive_v6_100m_best_val.safetensors", "adaptive_v6_100m_final": "adaptive_v6_100m_final.safetensors", }, "avg_bits": snap.avg_bits, "metrics": metrics, }, f, indent=2, ensure_ascii=False, ) saved["config"] = str(cfg_v6_out) print( f"Exported V6 100M packed checkpoints: best={best_path.stat().st_size / 1048576:.2f} MB, " f"final={final_path.stat().st_size / 1048576:.2f} MB", flush=True, ) return saved if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("--v6-100m", action="store_true") args = parser.parse_args() if args.v6_100m: export_v6_100m_from_resume() else: export_checkpoints()