"""Cut Cross-Entropy (CCE) — opt-in fused linear-CE for the large-vocab LM head. Qwen3.5/3.6 have a ~152k-token vocab, so the LM head's logit tensor ([tokens, 152k]) is the single largest activation in an SFT step. Liger's fused-linear-CE (the current default) chunks it; Cut Cross-Entropy (apple/ml-cross-entropy, arXiv 2411.09009) goes further — it never materializes the logits at all (correct-token logit + a streamed log-sum-exp in SRAM) and skips gradient contributions below bf16 precision. Published head-to-head at 256k vocab: ~2.1x faster and ~21% lower memory than Liger; the win grows as vocab >> hidden, exactly our regime. Safety (via engine.kernel_safety.run_gpu_self_test): - Gated by AUTOSLM_CCE=1; default OFF. - Runs a numeric self-test (CCE loss+grad vs eager CE) on the live GPU and only patches if it matches within tolerance; any import/patch/self-test failure leaves the model untouched (correctness over speed — the run falls back to Liger/eager). This is a production-scale capability: like every fused kernel it pays a one-time JIT cost, so on a short micro-benchmark it can look neutral/negative — the win shows on real (long) runs. """ from __future__ import annotations import os from autoslm.engine.kernel_safety import run_gpu_self_test def _cce_enabled() -> bool: # strip()+lower() so a blank/whitespace value (e.g. AUTOSLM_CCE=" " from env forwarding) is # treated as OFF. The falsey set mirrors autoslm.spec._FALSE_STRINGS so "no"/"off"/"none" (and # "false"/"0") all read as OFF too, not accidentally enabling the self-test + patching. return os.environ.get("AUTOSLM_CCE", "0").strip().lower() not in ( "0", "false", "no", "off", "none", "", ) def cce_will_install() -> bool: """True only when CCE is enabled AND its package is importable — i.e. ``install_cce`` will really patch the loss path. Used by the trainer to decide whether to SUPPRESS Liger: suppress only when CCE will actually take over the loss, else an enabled-but-uninstallable CCE (e.g. RunPod, where the worker deps don't ship cut_cross_entropy) silently drops the run to slow eager cross-entropy instead of keeping the Liger fused-CE win.""" if not _cce_enabled(): return False try: import importlib.util return importlib.util.find_spec("cut_cross_entropy") is not None except Exception: return False def _self_test() -> bool: """Numeric parity of CCE's linear_cross_entropy vs eager F.cross_entropy (loss + dhidden).""" return run_gpu_self_test(_self_test_body) def _self_test_body() -> bool: import torch import torch.nn.functional as F try: from cut_cross_entropy import linear_cross_entropy except Exception as e: print("[cce] package not importable; skipping:", e) return False V, H, T = 152064, 2048, 64 # Qwen-scale vocab/hidden, a small token block h = torch.randn(T, H, device="cuda", dtype=torch.bfloat16, requires_grad=True) W = torch.randn(V, H, device="cuda", dtype=torch.bfloat16) / (H**0.5) labels = torch.randint(0, V, (T,), device="cuda") # CCE loss_cce = linear_cross_entropy(h, W, labels) loss_cce.backward() dh_cce = h.grad.clone() h.grad = None # Eager reference (fp32 logits) ref = F.cross_entropy((h.float() @ W.float().t()), labels) ref.backward() dh_ref = h.grad.clone() if not torch.allclose(loss_cce.float(), ref, atol=2e-2, rtol=2e-2): print(f"[cce] self-test FAILED loss ({loss_cce.item():.4f} vs {ref.item():.4f}); fallback") return False # CCE filters tiny grads, so allow a looser tolerance on dhidden. if not torch.allclose(dh_cce.float(), dh_ref.float(), atol=5e-2, rtol=5e-2): print("[cce] self-test FAILED dhidden parity; fallback") return False print("[cce] self-test passed (loss+dhidden parity vs eager)") return True def install_cce(model) -> bool: """Patch the model's LM-head loss to Cut Cross-Entropy, IFF enabled + self-test passes. Returns True if installed. `model` may be a PEFT-wrapped trainer model — we patch the underlying HF model. Never raises (correctness-preserving: on any failure the caller keeps its existing Liger/eager loss path).""" if not _cce_enabled(): return False try: if not _self_test(): return False from cut_cross_entropy.transformers import cce_patch # Unwrap PEFT to reach the HF base model the patch keys off (model_type). base = model for attr in ("get_base_model", "base_model"): inner = getattr(base, attr, None) base = inner() if callable(inner) else (inner or base) cce_patch(base) print(f"[cce] Cut Cross-Entropy installed on {type(base).__name__}") return True except Exception as e: print("[cce] install skipped:", e) return False