"""train_l2_gddr7_wikipedia.py Unified L2-Pinned Configurable-Depth Reasoning Core + Dual-Tier GDDR7 Sparse Memory Architecture on an NVIDIA RTX PRO 6000 Blackwell (96 GB GDDR7, 128 MiB L2). Unified Architecture: Input IDs ──(async CUDA stream: Engram N-gram gather)──────────────────┐ │ ▼ [tok_emb] ─► [Prelude Loops 1–2] ─► [+ Layer-2 Engram Gate] ─► Save h_anchor │ ┌──────────────────────────────────────────────────────────────────┘ ▼ ┌─► [Shared L2-Pinned Core × r loops (PLN Stochastic Depth + TBPTT b=6)] ─┐ │ • Gated Input Injection from h_anchor (prevents prompt washout) │ │ • F_seq: Fused 6-way QKV + FLA GDN-2 + SWA FlexAttention + MoLA │ │ • G_ffn: SwiGLU (100% tok, L2) + MoD-Gated UltraMemV2 (top 12.5%) │ └─────────────────────────────────────────────────────────────────────────┘ │ ▼ [Coda Loops 1–2] ─► [Liger Fused Linear CE (16k L2-pinned sub-batch)] Test-Time Thinking Effort Presets (total loops = Prelude 2 + Shared r + Coda 2): low=8, medium=16, high=24, xhigh=32, max=40 """ from __future__ import annotations import math import os import sys from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") _cache_root = os.environ.get("A100_CACHE_DIR", os.path.expanduser("~/.cache/a100_train")) os.makedirs(_cache_root, exist_ok=True) os.environ.setdefault("TORCHINDUCTOR_CACHE_DIR", os.path.join(_cache_root, "torchinductor_cache")) os.environ.setdefault("TRITON_CACHE_DIR", os.path.join(_cache_root, "triton_cache")) os.environ.setdefault("TORCHINDUCTOR_FX_GRAPH_CACHE", "1") os.environ.setdefault("TORCHINDUCTOR_AUTOGRAD_CACHE", "1") import queue import threading import time import unicodedata import numpy as np import pyarrow.parquet as pq import json import torch import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F from torch.utils.checkpoint import checkpoint from tokenizers import Tokenizer # Optional high-performance kernels (auto-detected with graceful fallbacks) try: from liger_kernel.transformers import LigerFusedLinearCrossEntropyLoss _HAS_LIGER_CE = True except Exception: LigerFusedLinearCrossEntropyLoss = None _HAS_LIGER_CE = False _CCE_IMPORT_ERR = None try: from cut_cross_entropy import linear_cross_entropy as _cce_linear_cross_entropy _HAS_CUT_CE = True except Exception as _exc: _cce_linear_cross_entropy = None _HAS_CUT_CE = False _CCE_IMPORT_ERR = str(_exc) _FLA_IMPORT_ERR = None # Prevent broken tilelang (missing tvm_ffi/z3) from crashing fla.ops import try: import tvm_ffi # noqa: F401 except Exception: sys.modules.setdefault("tilelang", None) try: from fla.ops.gated_delta_rule import chunk_gated_delta_rule as _fla_chunk_gdn _HAS_FLA = True except Exception as _exc: _fla_chunk_gdn = None _HAS_FLA = False _FLA_IMPORT_ERR = str(_exc) try: from fla.modules import ShortConvolution as _FLAShortConv _HAS_FLA_CONV = True except Exception: _FLAShortConv = None _HAS_FLA_CONV = False try: from torch.nn.attention.flex_attention import create_block_mask, flex_attention _HAS_FLEX_ATTN = True except Exception: create_block_mask = None flex_attention = None _HAS_FLEX_ATTN = False try: import triton import triton.language as tl _HAS_TRITON = True except Exception: triton = None tl = None _HAS_TRITON = False try: from quack.rmsnorm import rmsnorm as _quack_rmsnorm _HAS_QUACK_RMS = True except Exception: _quack_rmsnorm = None _HAS_QUACK_RMS = False try: _HAS_FLASH_QLA = False # sm_120-only; A100 (sm_80) uses FLA Triton chunk_gated_delta_rule except Exception: _HAS_FLASH_QLA = False # ===================================================================== CONFIG # Locked-in Final 200B-Token Architecture: 1.50B Engram + 10.00B UltraMemV2 (topK=32 total) = 11.50B sparse (~32.5 GiB GDDR7) SEQ_LEN = 1024 # sequence length per sample BATCH_SIZE = 32 # 32 * 1024 = 32,768 micro-tokens (~59-62 GiB peak w/ 11.50B sparse + expandable_segments) GRAD_ACCUM_STEPS = 4 # effective batch = 131,072 tokens/step (4 sampled loop depths/step) PREFETCH_BATCHES = 8 # fallback thread-prefetch queue depth MAX_STEPS = 500 # number of optimizer steps to run LOG_EVERY = 10 # print telemetry every N optimizer steps EVAL_EVERY = 40 # validation / health check cadence # Flat binary memmap cache (eliminates 100% CPU tokenization bottleneck) USE_MEMMAP_CACHE = True DATA_CACHE_DIR = os.environ.get("A100_DATA_DIR", os.path.expanduser("~/a100_data")) MEMMAP_BIN_PATH = os.path.join(DATA_CACHE_DIR, "wiki_tokens.bin") VAL_PROMPTS_JSON = os.path.join(DATA_CACHE_DIR, "wiki_val_prompts.json") MEMMAP_MAX_TOKENS = int(os.environ.get("MEMMAP_MAX_TOKENS", "100000000")) TOKENIZER_HF_REPO = os.environ.get("TOKENIZER_HF_REPO", "gpt2") TOKENIZER_PATH = os.environ.get("TOKENIZER_PATH", "") HF_DATASET_NAME = os.environ.get("HF_DATASET_NAME", "wikimedia/wikipedia") HF_DATASET_CONFIG = os.environ.get("HF_DATASET_CONFIG", "20231101.en") DATA_PARQUET_DIR = os.environ.get("DATA_PARQUET_DIR", "") # ~600 MB uint16 across all 29 shards (strict <1.0 epoch, kills memorization!) VAL_RESERVE_TOKENS = 262_144 # held-out tail tokens for objective effort-scaling PPL eval # Configurable Thinking Effort & Stochastic Depth (Huginn + Parcae + OrthoInj) N_PRELUDE = 1 # slim 1-block Prelude (eliminates perimeter bypass & saves ~12.6M/L2!) N_SHARED_CELL_BLOCKS = 2 # 2-block recurrent cell (~25 MiB FP8, fits comfortably in 128 MiB L2!) N_CODA = 1 # slim 1-block Coda (forces shared_core to carry multi-step reasoning) EFFORT_TOTAL_LOOPS = { "low": 8, # 1 + 3*2 + 1 (3 cell iters) "medium": 16, # 1 + 7*2 + 1 (7 cell iters) "high": 24, # 1 + 11*2 + 1 (11 cell iters) "xhigh": 32, # 1 + 15*2 + 1 (15 cell iters) "max": 40, # 1 + 19*2 + 1 (19 cell iters) } # Deep-weighted bucket sampling over (8, 12, 16, 24, 32, 40) loops: 60% main / 68% anneal at >=24L! PLN_ITER_BUCKETS = (3, 5, 7, 11, 15, 19) # total blocks: 8, 12, 16, 24, 32, 40 DEPTH_BUCKET_PROBS_MAIN = (0.10, 0.12, 0.18, 0.22, 0.20, 0.18) # mean 11.0 iters (24L), 18% at 40L DEPTH_BUCKET_PROBS_ANNEAL = (0.06, 0.10, 0.16, 0.22, 0.24, 0.22) # mean 12.0 iters (26L), 22% at 40L PLN_MAIN_MEAN_ITERS = 11.0 PLN_ANNEAL_MEAN_ITERS = 12.0 PLN_SIGMA = 0.65 TBPTT_BACKPROP_ITERS = 4 # max TBPTT window (= 8 shared blks, 0.999 BPTT cos) # 4-stage progressive depth curriculum (0-60%: 10L/TBPTT=2 -> 60-65%: 16L/TBPTT=3 -> 65-90%: 24L/TBPTT=4 -> 90-100%: 26L/TBPTT=4) ENABLE_PROGRESSIVE_DEPTH = True PROGRESSIVE_DEPTH_STAGES = ( (0.60, 2, (3, 4, 5), (0.30, 0.40, 0.30), "S1-10L"), (0.65, 3, (3, 5, 7, 9, 11), (0.12, 0.22, 0.32, 0.22, 0.12), "S2-16L"), (0.90, 4, PLN_ITER_BUCKETS, DEPTH_BUCKET_PROBS_MAIN, "S3-24L"), (1.01, 4, PLN_ITER_BUCKETS, DEPTH_BUCKET_PROBS_ANNEAL, "S4-26L"), ) # Continuous sinusoidal/Fourier loop conditioning (zero-init identity; extrapolates cleanly to 2x+ post-train loops) ENABLE_CONTINUOUS_LOOP_COND = True LOOP_FOURIER_FREQS = 16 LOOP_COND_HIDDEN = 64 LOOP_COND_R_REF = 19 # 40L reference iteration count (smoothly extrapolates to 80L+ post-train) # Option 1: Hoisted TALA-Base (arXiv:2611.39694) — token-anchored shared Base K/V added to Block 1 SWA ENABLE_TALA_BASE = True TALA_BASE_DIM = 512 # shared base latent width (computed once per sequence, reused across all loops) # FP8 E4M3 + per-row FP32 w_scale sparse tables (-10.5 GiB VRAM, -50% sparse GDDR7 bandwidth, Philox SR) # On 4x A100-80GB (4-way sharded), pure BF16 sparse tables use only ~8.4 GiB/GPU with zero quant noise. # Set SPARSE_TABLE_USE_FP8=1 in env to enable software Triton FP8 sparse tables if desired. SPARSE_TABLE_USE_FP8 = os.environ.get("SPARSE_TABLE_USE_FP8", "0") == "1" FP8_E4M3_MAX = 448.0 # Async secondary CUDA stream overlapping sparse_adam_step behind opt_dense.step() (NorMuon) ENABLE_ASYNC_SPARSE_ADAM = True CONTRACTION_REG_COEFF = 0.005 # feather-light Banach contraction: ||dx_r|| <= 0.97 ||dx_{r-1}|| MONO_LOSS_COEFF = 0.25 # hinge forcing L(r_final) <= L(r_mid).detach() - 0.01 RMID_LOSS_COEFF = 0.15 # Ouro intermediate-depth NTP supervision weight RMID_BATCH_FRAC = 0.125 # 12.5% batch fused into single CCE call with Main + ECHO # Token-Sparse Gated Multi-Hop UltraMemV2 (MoD-style per-loop gate) MEM_CAPACITY_FRAC = 0.25 # top 25.0% of tokens on Block 1 per cell iter (8,192 of 32,768 tok) MEM_EVAL_THRESHOLD = 0.50 # test-time threshold: easy tokens never touch GDDR7 # Optimization hyperparameters LR_CORE_MUON = 1.0e-2 # NorMuon exact-RMS calibrated LR for Prelude/Coda LR_SHARED_MUON = 6.0e-3 # 0.6x depth-scaled Muon LR for weight-tied shared_core LR_CORE_ADAMW = 1.5e-3 # FP32 AdamW learning rate on 1D/norm/router/skinny-gate/vocab LR_ENGRAM_MULT = 2.5 # moderated Engram LR (prevents Layer-2 n-gram shortcut) LR_ULTRAMEM_MULT = 5.0 # full 5x LR for UltraMemV2 factual slots ENGRAM_DROPOUT = 0.10 # light dropout on Layer-2 Engram during training WEIGHT_DECAY_CORE = 0.01 # weight decay for core & router (0.0 for sparse tables!) ULTRAMEM_BIAS_GAMMA = 1.5e-2 # Asymmetric overload bias rate + key centering (MemEnt > 0.99, MaxLoad < 2x) ULTRAMEM_ROUTER_SCALE = 16.0 # router softmax temperature scale to prevent load collapse ECHO_LOSS_COEFF = 0.25 # ECHO multi-horizon auxiliary loss weight (paired with r_mid NTP) ECHO_FIXED_DEPTH = 1 # fixed 1-horizon ECHO for static torch.compile graphs (None = DDS) ECHO_BATCH_FRAC = 0.125 # 12.5% batch (16,384 tok/step): fused with Main + r_mid in 1 CCE call MAX_GRAD_NORM = 1.0 # Acceleration & Precision flags USE_TORCH_COMPILE = True # torch.compile on core, routers, & sparse Adam CORE_COMPILE_MODE = "max-autotune-no-cudagraphs" # Blackwell-tuned Triton & cuBLAS GEMM schedules USE_FP8_LINEAR = False # A100 (sm_80) has no hardware FP8 Tensor Cores; use native BF16 Tensor Cores USE_NVFP4_CORE = False # set True to test NVFP4 (RHT+SR) on the 4 Shared Core linears only USE_FLEX_ATTENTION = True # PyTorch FlexAttention for SWA-only (score_mod=None) + online-softmax MoLA USE_FLA_GDN = True # uses installed flash-linear-attention Triton kernel (auto-fallbacks if absent) CE_CHUNK_TOKENS = 1024 # chunk size for fallback linear cross-entropy PREFER_CUT_CE = True # prefer Cut Cross-Entropy (apple/ml-cross-entropy) over Liger when installed LIGER_SUB_BATCH_TOKENS = 16384 # keeps logits <= 96 MiB in L2 while halving 192 MiB tok_emb reads SPARSE_OPT_CHUNK = 131_072 # chunk size for sparse_adam_step to keep L2 hot # Architecture constants D_TOTAL = 2048 D_STREAM = D_TOTAL // 2 # 1024 per reversible stream D_VOCAB = 1024 # factorized tied vocab/LM-head dim (cuts LM-head FLOPs by 50%!) SWIGLU_TILE_TOKENS = 512 N_HEADS = 8 HEAD_DIM = 64 ATTN_DIM = N_HEADS * HEAD_DIM # 512 per branch GDN_CONV_KERNEL = 4 GDN_CHUNK_SIZE = 64 # power-of-2; 64 halves inter-chunk scan when using fallback WY SWA_WINDOW = 256 # 256x16..32 loops = 4k-8k receptive field; halves FlexAttention BF16 IO HISA_PHI = math.pi / 2.0 HISA_BLOCK_TOKENS = 128 HISA_CHUNK_PAIRS = 8 MOLA_MEM_SLOTS = 16 FFN_HIDDEN = 2688 ROPE_BASE = 10000.0 EPS = 1e-6 EPS_DEFAULT = EPS DEFAULT_EPS = EPS INIT_SCALE = 0.25 MUON_BLOCK_PAPER = 2048 # Exact published 5-step Polar Express coefficients (arXiv:2505.16932v2, Algorithm 1) _POLAR_EXPRESS_RAW = ( (8.28721201814563, -23.595886519098837, 17.300387312530933), (4.107059111542203, -2.9478499167379106, 0.5448431082926601), (3.9486908534822946, -2.908902115962949, 0.5518191394370137), (3.3184196573706015, -2.488488024314874, 0.51004894012372), (2.300652019954817, -1.6689039845747493, 0.4188073119525673), ) POLAR_EXPRESS_SAFE = tuple( (a / 1.01, b / (1.01 ** 3), c / (1.01 ** 5)) for (a, b, c) in _POLAR_EXPRESS_RAW[:-1] ) + (_POLAR_EXPRESS_RAW[-1],) MUON_NS_STEPS = 5 ECHO_DDS_PROBS = (0.6, 0.3, 0.1) FP8_E4M3_MAX = 448.0 FP8_E5M2_MAX = 57344.0 FP4_E2M1_MAX = 6.0 # Locked-in Final Tier 1 (1.50B Engram) & Tier 2 (10.00B UltraMemV2 TDQKR, topK=32 total) config SPARSE_MEMORY_CFG = { "engram_heads": 8, "engram_rows_per_head": 1_464_844, # 1,464,844 * 8 * 128 = 1.500B params (~4.33 GiB GDDR7) "engram_dim": 128, "ultramem_heads": 2, "ultramem_k": 3125, # 3125^2 = 9.766M slots/head * 2 * 512 = 10.000B params (~28.18 GiB GDDR7) "ultramem_dv": 512, "ultramem_tucker_rank": 4, "ultramem_cand_k0": 32, "ultramem_topk": 16, # 16/head = 32 total retrieved slots/token } USE_TRITON_MOLA_IN_COMPILE = True # Registered via torch.library.custom_op -> 0 graph breaks in torch.compile! USE_CACHED_FP8_CORE = False # Disabled on A100 (sm_80); native BF16 Tensor Cores + torch.compile MiB = 2**20 GiB = 2**30 NON_MUON_2D_NAMES = { "swa.mola_beta", "mola_beta", "tok_emb.weight", "w_q_row.weight", "w_q_col.weight", } NVFP4_SHARED_CORE_TARGETS = { f"shared_core.{i}.{layer}" for i in range(N_SHARED_CELL_BLOCKS) for layer in ("qkv_fg_fused", "out_proj", "w_gate_up", "w_down") } # ============================================================ HELPER FUNCTIONS def banner(title): print("\n" + "=" * 84) print(f" {title}") print("=" * 84) def rms_norm(x, weight=None, eps=EPS, out_dtype=None): x32 = x.float() normed = x32 * torch.rsqrt(x32.pow(2).mean(-1, keepdim=True) + eps) if weight is not None: normed = normed * weight.float() return normed.to(out_dtype or x.dtype) def l2_norm(x, eps=EPS): x32 = x.float() return (x32 * torch.rsqrt(x32.pow(2).sum(-1, keepdim=True) + eps)).to(x.dtype) def get_progressive_depth_stage(step, max_steps): """Return (tbptt_iters, iter_buckets, probs, stage_label) for the current training fraction.""" if not ENABLE_PROGRESSIVE_DEPTH: in_anneal = step > int(0.80 * max_steps) probs = DEPTH_BUCKET_PROBS_ANNEAL if in_anneal else DEPTH_BUCKET_PROBS_MAIN return TBPTT_BACKPROP_ITERS, PLN_ITER_BUCKETS, probs, ("FIX-26L" if in_anneal else "FIX-24L") frac = float(step) / float(max(1, max_steps)) for end_frac, tbptt, buckets, probs, label in PROGRESSIVE_DEPTH_STAGES: if frac <= end_frac: return tbptt, buckets, probs, label _, tbptt, buckets, probs, label = PROGRESSIVE_DEPTH_STAGES[-1] return tbptt, buckets, probs, label def sample_pln_shared_iters(step, max_steps, rng): """Deep-weighted or 4-stage progressive stochastic depth sampler over 2-block cell iterations.""" _, buckets, probs, _ = get_progressive_depth_stage(step, max_steps) idx = int(rng.choice(len(buckets), p=probs)) return int(buckets[idx]) def invert_unit_lower_tri(A): """Exact functional inverse of unit lower-triangular [..., C, C] (power-of-2 C).""" n = A.size(-1) if n == 1: return torch.ones_like(A) if n == 2: ones = torch.ones_like(A[..., 0, 0]) zeros = torch.zeros_like(ones) row0 = torch.stack([ones, zeros], dim=-1) row1 = torch.stack([-A[..., 1, 0], ones], dim=-1) return torch.stack([row0, row1], dim=-2) assert (n & (n - 1)) == 0, f"invert_unit_lower_tri requires power-of-2 size, got {n}" h = n // 2 diag_pair = torch.stack([A[..., :h, :h], A[..., h:, h:]], dim=0) inv_pair = invert_unit_lower_tri(diag_pair) inv_tl, inv_br = inv_pair[0], inv_pair[1] off = -torch.matmul(torch.matmul(inv_br, A[..., h:, :h]), inv_tl) top = torch.cat([inv_tl, torch.zeros_like(off)], dim=-1) bot = torch.cat([off, inv_br], dim=-1) return torch.cat([top, bot], dim=-2) def is_muon_matrix_param(name, p): if p.ndim != 2 or min(p.shape) < 64: return False if name in NON_MUON_2D_NAMES or name.endswith(tuple(NON_MUON_2D_NAMES)): return False return True def partition_muon_adamw_params(named_params): muon_params, adamw_params = [], [] for name, p in named_params: if not p.requires_grad: continue if is_muon_matrix_param(name, p): muon_params.append(p) else: adamw_params.append(p) return muon_params, adamw_params def stochastic_round_bf16(x): """Unbiased FP32 -> BF16: E[result] == x, so sub-ULP updates accumulate.""" bits = x.float().contiguous().view(torch.int32) noise = torch.randint(0, 1 << 16, bits.shape, device=bits.device, dtype=torch.int32) return ((bits + noise) & -65536).view(torch.float32).to(torch.bfloat16) def write_back_(param, new_fp32): if param.dtype == torch.bfloat16: param.copy_(stochastic_round_bf16(new_fp32)) else: param.copy_(new_fp32) def cast_model_preserve_fp32_1d(model, device): """Large 2D matrices & tok_emb -> BF16; AdamW norms/gains/keys/skinny gates stay FP32.""" model.to(device) _, adamw_params = partition_muon_adamw_params(model.named_parameters()) keep_fp32 = {id(p) for p in adamw_params} - {id(model.tok_emb.weight)} for p in model.parameters(): p.data = p.data.float() if id(p) in keep_fp32 else p.data.bfloat16() return model # ============================================== NVFP4 (SM120) & TORCHAO FP8 def _make_hadamard_16(device): """Normalized 16x16 Sylvester Hadamard matrix H (H @ H.T == I).""" h = torch.tensor([[1.0]], device=device, dtype=torch.float32) for _ in range(4): h = torch.cat([torch.cat([h, h], dim=1), torch.cat([h, -h], dim=1)], dim=0) return h / 4.0 _E2M1_LEVELS = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0) def _quantize_e2m1_1d_blocks(x, stochastic=False): """NVFP4 1x16 block quantization with FP8 E4M3 block scales + FP32 global scale.""" orig_shape = x.shape x32 = x.float().reshape(-1, 16) g_scale = x32.abs().amax().clamp_min(1e-12) / (FP8_E4M3_MAX * FP4_E2M1_MAX) blk_max = x32.abs().amax(dim=-1, keepdim=True) blk_scale = (blk_max / (FP4_E2M1_MAX * g_scale)).clamp(min=1e-6, max=FP8_E4M3_MAX) if hasattr(torch, "float8_e4m3fn"): blk_scale = blk_scale.to(torch.float8_e4m3fn).float() eff_scale = (blk_scale * g_scale).clamp_min(1e-12) scaled = (x32 / eff_scale).clamp(-FP4_E2M1_MAX, FP4_E2M1_MAX) signs = scaled.sign() a = scaled.abs() levels = torch.tensor(_E2M1_LEVELS, device=x.device, dtype=torch.float32) idx_hi = torch.bucketize(a, levels).clamp(1, len(_E2M1_LEVELS) - 1) lo = levels[idx_hi - 1] hi = levels[idx_hi] if stochastic: prob_hi = ((a - lo) / (hi - lo).clamp_min(1e-12)).clamp(0.0, 1.0) q_abs = torch.where(torch.rand_like(prob_hi) < prob_hi, hi, lo) else: q_abs = torch.where((a - lo) < (hi - a), lo, hi) return (signs * q_abs * eff_scale).view(orig_shape).to(x.dtype) def _quantize_e2m1_2d_blocks(w): """NVFP4 2D 16x16 weight block quantization (identical Q(W) in fwd and bwd).""" out_f, in_f = w.shape w32 = w.float().view(out_f // 16, 16, in_f // 16, 16).permute(0, 2, 1, 3) g_scale = w32.abs().amax().clamp_min(1e-12) / (FP8_E4M3_MAX * FP4_E2M1_MAX) blk_max = w32.abs().amax(dim=(-2, -1), keepdim=True) blk_scale = (blk_max / (FP4_E2M1_MAX * g_scale)).clamp(min=1e-6, max=FP8_E4M3_MAX) if hasattr(torch, "float8_e4m3fn"): blk_scale = blk_scale.to(torch.float8_e4m3fn).float() eff_scale = (blk_scale * g_scale).clamp_min(1e-12) scaled = (w32 / eff_scale).clamp(-FP4_E2M1_MAX, FP4_E2M1_MAX) signs = scaled.sign() a = scaled.abs() levels = torch.tensor(_E2M1_LEVELS, device=w.device, dtype=torch.float32) idx_hi = torch.bucketize(a, levels).clamp(1, len(_E2M1_LEVELS) - 1) lo = levels[idx_hi - 1] hi = levels[idx_hi] q_abs = torch.where((a - lo) < (hi - a), lo, hi) q = (signs * q_abs * eff_scale).permute(0, 2, 1, 3).contiguous().view(out_f, in_f) return q.to(w.dtype) class _NVFP4SoftwareLinearFn(torch.autograd.Function): """Reference NVFP4 training recipe (arXiv:2509.25149): - 2D 16x16 weight RTN scaling (identical Q(W) in fwd/bwd) - 1D 1x16 activation RTN scaling - 1D 1x16 Stochastic Rounding on dY - 16x16 Random Hadamard Transform (RHT) on Wgrad only """ @staticmethod def forward(ctx, x, weight, h16): x2d = x.reshape(-1, x.size(-1)) xq = _quantize_e2m1_1d_blocks(x2d, stochastic=False) wq = _quantize_e2m1_2d_blocks(weight) out = F.linear(xq, wq) ctx.save_for_backward(x2d, wq, h16) ctx.x_shape = x.shape return out.view(*x.shape[:-1], weight.size(0)) @staticmethod def backward(ctx, grad_out): x2d, wq, h16 = ctx.saved_tensors dy2d = grad_out.reshape(-1, wq.size(0)) dy_sr = _quantize_e2m1_1d_blocks(dy2d, stochastic=True) dx = torch.matmul(dy_sr, wq) # 16x16 Random Hadamard Transform on Wgrad reduction dim (M) m_rows = x2d.size(0) pad = (-m_rows) % 16 x_m = F.pad(x2d, (0, 0, 0, pad)) if pad else x2d dy_m = F.pad(dy2d, (0, 0, 0, pad)) if pad else dy2d signs = (torch.randint(0, 2, (16,), device=x2d.device, dtype=torch.float32) * 2.0 - 1.0) rh = (h16 * signs.unsqueeze(0)).to(x2d.dtype) # Apply H along M-blocks of 16: dW = (dY^T H)(H^T X) x_rot = torch.matmul(rh.t(), x_m.view(-1, 16, x2d.size(1))).reshape(-1, x2d.size(1)) dy_rot = torch.matmul(rh.t(), dy_m.view(-1, 16, dy2d.size(1))).reshape(-1, dy2d.size(1)) x_rot_q = _quantize_e2m1_1d_blocks(x_rot.t().contiguous(), stochastic=False) dy_rot_q = _quantize_e2m1_1d_blocks(dy_rot.t().contiguous(), stochastic=True) dw = torch.matmul(dy_rot_q, x_rot_q.t()) return dx.view(ctx.x_shape), dw.to(wq.dtype), None class NVFP4Linear(nn.Module): """NVFP4 wrapper keeping the original nn.Linear weight parameter.""" def __init__(self, linear, h16): super().__init__() assert linear.bias is None self.weight = linear.weight self.in_features = linear.in_features self.out_features = linear.out_features self.register_buffer("h16", h16, persistent=False) def forward(self, x): return _NVFP4SoftwareLinearFn.apply(x, self.weight, self.h16) def enable_precision_recipes(model, device): """Apply NVFP4 (optional, 4 Shared Core GEMMs only) and torchao FP8 (remaining large linears). High-precision perimeter (tok_emb/LM head, RMSNorm, GDN-2 gates, Flex+MoLA, Engram/UltraMemV2 routers, Prelude 1-2, Coda 1-2) never uses NVFP4. """ n_nvfp4 = 0 nvfp4_backend = "disabled" nvfp4_fqns = set() if USE_NVFP4_CORE and device.type == "cuda": # Prefer hardware sm120-nvfp4-training kernel if installed; else software RHT+SR recipe try: import sm120_nvfp4 # type: ignore if hasattr(sm120_nvfp4, "convert_linear"): for name, mod in list(model.named_modules()): if name in NVFP4_SHARED_CORE_TARGETS and isinstance(mod, nn.Linear): parent_name, attr = name.rsplit(".", 1) parent = model.get_submodule(parent_name) setattr(parent, attr, sm120_nvfp4.convert_linear(mod)) nvfp4_fqns.add(name) n_nvfp4 += 1 nvfp4_backend = "sm120_nvfp4_hardware" except Exception: h16 = _make_hadamard_16(device) for name, mod in list(model.named_modules()): if name in NVFP4_SHARED_CORE_TARGETS and isinstance(mod, nn.Linear): parent_name, attr = name.rsplit(".", 1) parent = model.get_submodule(parent_name) setattr(parent, attr, NVFP4Linear(mod, h16)) nvfp4_fqns.add(name) n_nvfp4 += 1 nvfp4_backend = "software_rht_sr_reference" n_fp8 = 0 if USE_CACHED_FP8_CORE and USE_FP8_LINEAR and (not USE_NVFP4_CORE) and device.type == "cuda": try: wrapped = wrap_shared_core_with_cached_fp8(model, use_rowwise=True) n_fp8 += len(wrapped) except Exception as exc: print(f" CachedFP8Linear wrap skipped ({exc}); falling back to torchao FP8.") if USE_FP8_LINEAR and device.type == "cuda": try: from torchao.float8 import Float8LinearConfig, convert_to_float8_training converted_count = [0] def module_filter_fn(mod, fqn): if fqn in nvfp4_fqns or not isinstance(mod, nn.Linear) or mod.bias is not None: return False # Lower threshold to >=512 so emb_up, lm_down, UltraMemV2 & Engram projections also run FP8! ok = ( min(mod.in_features, mod.out_features) >= 512 and mod.in_features % 16 == 0 and mod.out_features % 16 == 0 ) if ok: converted_count[0] += 1 return ok convert_to_float8_training( model, config=Float8LinearConfig(), module_filter_fn=module_filter_fn ) n_fp8 += converted_count[0] except Exception as exc: print(f" torchao FP8 unavailable ({exc}); using BF16 linear layers.") return n_fp8, n_nvfp4, nvfp4_backend # ===================================== INTERNET HF TOKENIZER & DATA STREAMING def init_distributed(): """Initialize torch.distributed when launched via torchrun; no-op for single-GPU runs.""" world_size = int(os.environ.get("WORLD_SIZE", "1")) if world_size > 1 and not dist.is_initialized(): local_rank = int(os.environ.get("LOCAL_RANK", "0")) if torch.cuda.is_available(): torch.cuda.set_device(local_rank) dist.init_process_group(backend="nccl" if torch.cuda.is_available() else "gloo") rank = dist.get_rank() device = torch.device(f"cuda:{local_rank}" if torch.cuda.is_available() else "cpu") return rank, local_rank, world_size, device device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") return 0, 0, 1, device def dist_is_active(): return dist.is_available() and dist.is_initialized() and dist.get_world_size() > 1 class _DistAllToAllFn(torch.autograd.Function): """Differentiable equal-split all_to_all_single for 4-way head-sharded Engram.""" @staticmethod def forward(ctx, x): out = torch.empty_like(x) dist.all_to_all_single(out, x.contiguous()) return out @staticmethod def backward(ctx, grad_out): grad_in = torch.empty_like(grad_out) dist.all_to_all_single(grad_in, grad_out.contiguous()) return grad_in class _DistAllGatherFn(torch.autograd.Function): """Differentiable all_gather (backward = reduce_scatter sum) for sharded UltraMemV2 weights.""" @staticmethod def forward(ctx, x): w = dist.get_world_size() out = torch.empty((w, *x.shape), device=x.device, dtype=x.dtype) dist.all_gather_into_tensor(out, x.contiguous()) return out @staticmethod def backward(ctx, grad_out): grad_in = torch.empty(grad_out.shape[1:], device=grad_out.device, dtype=grad_out.dtype) dist.reduce_scatter_tensor(grad_in, grad_out.contiguous(), op=dist.ReduceOp.SUM) return grad_in class _DistReduceScatterSumFn(torch.autograd.Function): """Differentiable reduce_scatter sum (backward = all_gather) for sharded UltraMemV2 outputs.""" @staticmethod def forward(ctx, x): out = torch.empty(x.shape[1:], device=x.device, dtype=x.dtype) dist.reduce_scatter_tensor(out, x.contiguous(), op=dist.ReduceOp.SUM) return out @staticmethod def backward(ctx, grad_out): w = dist.get_world_size() grad_in = torch.empty((w, *grad_out.shape), device=grad_out.device, dtype=grad_out.dtype) dist.all_gather_into_tensor(grad_in, grad_out.contiguous()) return grad_in def load_internet_tokenizer(): """Load tokenizer from TOKENIZER_PATH if provided, else download from Hugging Face Hub.""" if TOKENIZER_PATH and os.path.exists(TOKENIZER_PATH): return Tokenizer.from_file(TOKENIZER_PATH) return Tokenizer.from_pretrained(TOKENIZER_HF_REPO) def prepare_internet_wiki_memmap( tokenizer, vocab_size, out_path=MEMMAP_BIN_PATH, prompts_path=VAL_PROMPTS_JSON, max_tokens=MEMMAP_MAX_TOKENS, ): """Build or reuse a local uint16/uint32 token memmap from local parquets or HF streaming Wikipedia.""" os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True) np_dtype = np.uint16 if vocab_size < 65536 else np.uint32 item_bytes = np.dtype(np_dtype).itemsize if os.path.exists(out_path) and os.path.getsize(out_path) >= 1_000_000 * item_bytes: n_tok = os.path.getsize(out_path) // item_bytes val_prompts = [] if os.path.exists(prompts_path): try: val_prompts = json.loads(Path(prompts_path).read_text(encoding="utf-8")) except Exception: val_prompts = [] return n_tok, np_dtype, val_prompts # Optional local parquet folder override if DATA_PARQUET_DIR and os.path.isdir(DATA_PARQUET_DIR): pfiles = sorted( os.path.join(dp, fn) for dp, _, fns in os.walk(DATA_PARQUET_DIR) for fn in fns if fn.endswith(".parquet") ) if pfiles: n_tok, dt, val_prompts = pretokenize_parquet_to_bin( pfiles, tokenizer, vocab_size, out_path=out_path, max_tokens=max_tokens ) Path(prompts_path).write_text(json.dumps(val_prompts), encoding="utf-8") return n_tok, dt, val_prompts # Default: stream directly from Hugging Face Hub over A100 VM internet from datasets import load_dataset eos_id = _resolve_eos_id(tokenizer) ds = load_dataset(HF_DATASET_NAME, HF_DATASET_CONFIG, split="train", streaming=True) tmp_path = out_path + ".tmp" t0 = time.perf_counter() written = 0 val_prompts = [] text_buf = [] BATCH_DOCS = 256 print( f" Streaming {HF_DATASET_NAME} ({HF_DATASET_CONFIG}) -> {out_path} " f"(target {max_tokens / 1e6:.0f}M tokens, {np_dtype.__name__})..." ) with open(tmp_path, "wb") as f: for row in ds: txt = row.get("text") or row.get("content") or "" if not isinstance(txt, str) or len(txt) < 40: continue if len(val_prompts) < 8 and len(txt) > 80: snip = " ".join(txt.strip().split()[:24]) if len(snip) > 30: val_prompts.append(snip) text_buf.append(txt) if len(text_buf) >= BATCH_DOCS: encs = tokenizer.encode_batch(text_buf) text_buf.clear() ids_chunk = [] for e in encs: if e.ids: ids_chunk.extend(e.ids) ids_chunk.append(eos_id) if ids_chunk: arr = np.asarray(ids_chunk, dtype=np_dtype) rem = max_tokens - written if arr.size > rem: arr = arr[:rem] f.write(arr.tobytes()) written += int(arr.size) if written >= max_tokens: break if text_buf and written < max_tokens: encs = tokenizer.encode_batch(text_buf) ids_chunk = [] for e in encs: if e.ids: ids_chunk.extend(e.ids) ids_chunk.append(eos_id) if ids_chunk: arr = np.asarray(ids_chunk, dtype=np_dtype)[: max_tokens - written] f.write(arr.tobytes()) written += int(arr.size) os.replace(tmp_path, out_path) Path(prompts_path).write_text(json.dumps(val_prompts), encoding="utf-8") dt_s = max(time.perf_counter() - t0, 1e-6) print(f" Pretokenized {written:,d} tokens in {dt_s:.1f}s ({written / dt_s / 1e6:.2f}M tok/s).") return written, np_dtype, val_prompts def build_engram_canonical_map(tokenizer, vocab_size, device): vocab = tokenizer.get_vocab() id_to_token = {idx: tok for tok, idx in vocab.items() if idx < vocab_size} canonical_to_id = {} proj = torch.arange(vocab_size, dtype=torch.long) for idx in range(vocab_size): tok = id_to_token.get(idx, "") clean = tok.replace("Ġ", " ").replace("▁", " ") norm = unicodedata.normalize("NFKC", clean).lower().strip() if not norm: norm = tok if norm not in canonical_to_id: canonical_to_id[norm] = idx proj[idx] = canonical_to_id[norm] compression_ratio = 1.0 - (len(canonical_to_id) / max(vocab_size, 1)) return proj.to(device), len(canonical_to_id), compression_ratio def _resolve_eos_id(tokenizer): for cand in ("", "<|endoftext|>", "[SEP]"): tid = tokenizer.token_to_id(cand) if tid is not None: return tid return 0 def collect_val_prompts(parquet_files, limit=8): prompts = [] for path in parquet_files: pf = pq.ParquetFile(path) col = "text" if "text" in pf.schema.names else pf.schema.names[-1] for rb in pf.iter_batches(batch_size=64, columns=[col]): for t in rb.column(0).to_pylist(): if isinstance(t, str) and len(t) > 80: snippet = " ".join(t.strip().split()[:24]) if len(snippet) > 30: prompts.append(snippet) if len(prompts) >= limit: return prompts return prompts def pretokenize_parquet_to_bin( parquet_files, tokenizer, vocab_size, out_path=MEMMAP_BIN_PATH, max_tokens=MEMMAP_MAX_TOKENS, ): np_dtype = np.uint16 if vocab_size < 65536 else np.uint32 item_bytes = np.dtype(np_dtype).itemsize if os.path.exists(out_path) and os.path.getsize(out_path) >= 1_000_000 * item_bytes: n_tok = os.path.getsize(out_path) // item_bytes return n_tok, np_dtype, collect_val_prompts(parquet_files) os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True) eos_id = _resolve_eos_id(tokenizer) written = 0 val_prompts = [] t0 = time.perf_counter() with open(out_path, "wb") as f: for path in parquet_files: pf = pq.ParquetFile(path) col = "text" if "text" in pf.schema.names else pf.schema.names[-1] for rb in pf.iter_batches(batch_size=1024, columns=[col]): texts = [ t for t in rb.column(0).to_pylist() if isinstance(t, str) and len(t) > 80 ] if not texts: continue if len(val_prompts) < 8: for t in texts[:4]: snippet = " ".join(t.strip().split()[:24]) if len(snippet) > 30 and len(val_prompts) < 8: val_prompts.append(snippet) ids = [] for enc in tokenizer.encode_batch(texts): if len(enc.ids) > 16: ids.extend(enc.ids) ids.append(eos_id) if not ids: continue arr = np.asarray(ids, dtype=np_dtype) arr.tofile(f) written += arr.size if written >= max_tokens: dt = time.perf_counter() - t0 print( f" Pre-tokenized {written:,d} tokens ({np_dtype.__name__}) to {out_path} in {dt:.1f}s" ) return written, np_dtype, val_prompts dt = time.perf_counter() - t0 print(f" Pre-tokenized {written:,d} tokens ({np_dtype.__name__}) to {out_path} in {dt:.1f}s") return written, np_dtype, val_prompts class FastMemmapLoader: """Async background-threaded shuffled memmap loader with pinned H2D transfer.""" def __init__( self, bin_path, np_dtype, seq_len, batch_size, device, extra_horizon=2, val_prompts=None, seed=42, prefetch=4, ): self.data = np.memmap(bin_path, dtype=np_dtype, mode="r") self.seq_len = seq_len self.batch_size = batch_size self.device = device self.extra_horizon = extra_horizon self.span = seq_len + extra_horizon self.pin_memory = device.type == "cuda" self.val_prompts = val_prompts or [] self.val_reserve = min(VAL_RESERVE_TOKENS, len(self.data) // 10) self.train_len = max(self.span + 1, len(self.data) - self.val_reserve) self._rng = np.random.default_rng(seed) self._queue = queue.Queue(maxsize=max(2, prefetch)) self._stop_event = threading.Event() self._worker_error = None self._thread = threading.Thread( target=self._prefetch_loop, name="memmap-prefetch", daemon=True ) self._thread.start() def _prefetch_loop(self): try: n_seqs = max(1, (self.train_len - self.span) // self.span) order = self._rng.permutation(n_seqs) cursor = 0 while not self._stop_event.is_set(): if cursor + self.batch_size > n_seqs: order = self._rng.permutation(n_seqs) cursor = 0 seq_ids = order[cursor : cursor + self.batch_size] cursor += self.batch_size offsets = seq_ids * self.span rows = np.stack( [self.data[o : o + self.span] for o in offsets], axis=0 ).astype(np.int64) chunk = torch.from_numpy(rows) if self.pin_memory: chunk = chunk.pin_memory() while not self._stop_event.is_set(): try: self._queue.put(chunk, timeout=0.2) break except queue.Full: continue except Exception as exc: self._worker_error = exc def next_batch(self): while True: if self._worker_error is not None: raise RuntimeError("Memmap prefetch worker failed") from self._worker_error try: chunk = self._queue.get(timeout=0.2) break except queue.Empty: continue arr = chunk.to(self.device, non_blocking=self.pin_memory) return arr[:, : self.seq_len], [ arr[:, k : k + self.seq_len] for k in range(1, self.extra_horizon + 1) ] def close(self): self._stop_event.set() while not self._queue.empty(): try: self._queue.get_nowait() except queue.Empty: break if self._thread.is_alive(): self._thread.join(timeout=2.0) class WikipediaParquetStreamLoader: """Fallback background-threaded streaming token packer when memmap cache is disabled.""" def __init__( self, parquet_files, tokenizer, seq_len, batch_size, device, extra_horizon=2, prefetch_batches=PREFETCH_BATCHES, ): self.parquet_files = parquet_files self.tokenizer = tokenizer self.seq_len = seq_len self.batch_size = batch_size self.device = device self.extra_horizon = extra_horizon self.pin_memory = device.type == "cuda" self.eos_id = _resolve_eos_id(tokenizer) self.token_buffer = [] self.val_prompts = [] self._file_idx = 0 self._batch_iter = None self._text_col = None span = self.seq_len + self.extra_horizon self._fill_buffer(self.batch_size * span + 1024) self._queue = queue.Queue(maxsize=max(2, prefetch_batches)) self._stop_event = threading.Event() self._worker_error = None self._thread = threading.Thread( target=self._prefetch_loop, name="parquet-prefetch", daemon=True ) self._thread.start() def _open_next_file(self): if not self.parquet_files: return False path = self.parquet_files[self._file_idx % len(self.parquet_files)] self._file_idx += 1 pf = pq.ParquetFile(path) cols = pf.schema.names self._text_col = "text" if "text" in cols else cols[-1] self._batch_iter = pf.iter_batches(batch_size=256, columns=[self._text_col]) return True def _fill_buffer(self, min_tokens): while len(self.token_buffer) < min_tokens: if self._batch_iter is None: if not self._open_next_file(): synth = torch.randint(10, 5000, (min_tokens,)).tolist() self.token_buffer.extend(synth) return try: record_batch = next(self._batch_iter) except StopIteration: self._batch_iter = None continue texts = [ t for t in record_batch.column(0).to_pylist() if isinstance(t, str) and len(t) > 80 ] if not texts: continue if len(self.val_prompts) < 8: for t in texts[:4]: snippet = " ".join(t.strip().split()[:24]) if len(snippet) > 30 and len(self.val_prompts) < 8: self.val_prompts.append(snippet) encodings = self.tokenizer.encode_batch(texts) for enc in encodings: if len(enc.ids) > 16: self.token_buffer.extend(enc.ids) self.token_buffer.append(self.eos_id) def _make_cpu_batch(self): span = self.seq_len + self.extra_horizon needed = self.batch_size * span self._fill_buffer(needed + 1024) chunk = self.token_buffer[:needed] del self.token_buffer[:needed] arr = torch.tensor(chunk, dtype=torch.long).view(self.batch_size, span) if self.pin_memory: arr = arr.pin_memory() return arr def _prefetch_loop(self): try: while not self._stop_event.is_set(): arr = self._make_cpu_batch() while not self._stop_event.is_set(): try: self._queue.put(arr, timeout=0.2) break except queue.Full: continue except Exception as exc: self._worker_error = exc def next_batch(self): while True: if self._worker_error is not None: raise RuntimeError("Prefetch worker failed") from self._worker_error try: arr_cpu = self._queue.get(timeout=0.2) break except queue.Empty: continue arr = arr_cpu.to(self.device, non_blocking=self.pin_memory) x = arr[:, : self.seq_len] targets = [ arr[:, k : k + self.seq_len] for k in range(1, self.extra_horizon + 1) ] return x, targets def close(self): self._stop_event.set() while not self._queue.empty(): try: self._queue.get_nowait() except queue.Empty: break if self._thread.is_alive(): self._thread.join(timeout=2.0) # ===================== COALESCED GDDR7 SPARSE GATHER & LAZY 8-BIT SPARSE ADAM if _HAS_TRITON: @triton.jit def _triton_fp8_plain_lookup_kernel( w_ptr, wscale_ptr, idx_ptr, out_ptr, N, n_rows, D, BLOCK_D: tl.constexpr, USE_FP8: tl.constexpr, ): """1-pass coalesced FP8/BF16 plain embedding lookup with per-row FP32 w_scale.""" pid_n = tl.program_id(0) if pid_n >= N: return tok_i64 = pid_n.to(tl.int64) slot = tl.load(idx_ptr + tok_i64).to(tl.int64) offs_d = tl.arange(0, BLOCK_D).to(tl.int64) mask_d = offs_d < D slot_ok = (slot >= 0) & (slot < n_rows) val = tl.load(w_ptr + slot * D + offs_d, mask=mask_d & slot_ok, other=0.0).to(tl.float32) if USE_FP8: sc = tl.load(wscale_ptr + slot, mask=slot_ok, other=1.0).to(tl.float32) val = val * sc tl.store(out_ptr + tok_i64 * D + offs_d, val.to(tl.bfloat16), mask=mask_d) def _sparse_plain_lookup_impl(weight, w_scale, flat_indices, use_fp8): """Fast FP8-aware or BF16 plain lookup returning [N, D] BF16.""" N = flat_indices.numel() n_rows, D = weight.shape if N == 0: return torch.empty((0, D), device=weight.device, dtype=torch.bfloat16) if use_fp8: if _HAS_TRITON and weight.is_cuda and D <= 1024: out = torch.empty((N, D), device=weight.device, dtype=torch.bfloat16) block_d = 1 << (max(1, D) - 1).bit_length() _triton_fp8_plain_lookup_kernel[(N,)]( weight.contiguous(), w_scale.contiguous(), flat_indices.contiguous(), out, N, n_rows, D, BLOCK_D=block_d, USE_FP8=True, num_warps=4 if block_d <= 256 else 8, ) return out idx_l = flat_indices.to(torch.long) return (weight[idx_l].float() * w_scale[idx_l].unsqueeze(-1)).to(torch.bfloat16) return F.embedding(flat_indices, weight) class CoalescedSparseGatherFunction(torch.autograd.Function): @staticmethod def forward(ctx, weight, w_scale, flat_indices, grad_buffer_list, grad_hook, use_fp8): out = _sparse_plain_lookup_impl(weight, w_scale, flat_indices, use_fp8) ctx.save_for_backward(flat_indices) ctx.grad_buffer_list = grad_buffer_list ctx.row_dim = weight.size(1) return out @staticmethod def backward(ctx, grad_out): (flat_indices,) = ctx.saved_tensors ctx.grad_buffer_list.append( (flat_indices.detach(), grad_out.reshape(-1, ctx.row_dim).detach()) ) return None, None, None, None, None, None if _HAS_TRITON: @triton.jit def _triton_sparse_adam_rowv_kernel( w_ptr, wscale_ptr, qm_ptr, msc_ptr, vrow_ptr, step_ptr, uidx_ptr, g_ptr, lr, b1, b2, log_b1, log_b2, eps, seed, n_unique, D: tl.constexpr, STORE_FP8: tl.constexpr, ): """1-pass fused Triton Sparse Adam (FP8 E4M3 per-row w_scale OR BF16 SR + INT8 m + FP32 v_row).""" pid = tl.program_id(0) if pid >= n_unique: return row_id = tl.load(uidx_ptr + pid).to(tl.int64) offs = tl.arange(0, D).to(tl.int64) row_base = row_id * D + offs g_base = pid.to(tl.int64) * D + offs w_raw = tl.load(w_ptr + row_base).to(tl.float32) if STORE_FP8: w_sc = tl.load(wscale_ptr + row_id).to(tl.float32) w = w_raw * w_sc else: w = w_raw g = tl.load(g_ptr + g_base).to(tl.float32) qm = tl.load(qm_ptr + row_base).to(tl.float32) msc = tl.load(msc_ptr + row_id).to(tl.float32) v_prev = tl.load(vrow_ptr + row_id).to(tl.float32) cnt = tl.load(step_ptr + row_id) + 1 tl.store(step_ptr + row_id, cnt) m_prev = qm * msc m_new = b1 * m_prev + (1.0 - b1) * g g2_mean = tl.sum(g * g, axis=0) / D v_new = b2 * v_prev + (1.0 - b2) * g2_mean cnt_f = cnt.to(tl.float32) bc1 = 1.0 - tl.exp(cnt_f * log_b1) bc2 = 1.0 - tl.exp(cnt_f * log_b2) denom = tl.sqrt(v_new / bc2) + eps w_new = w - lr * (m_new / bc1) / denom # Unbiased Philox-4x32-7 stochastic rounding for FP8 E4M3 (per-row scaled) or BF16 r_bits = tl.randint(seed, row_base.to(tl.int32)) if STORE_FP8: w_amax = tl.max(tl.abs(w_new), axis=0) new_wsc = tl.maximum(w_amax / 448.0, 1e-12) w_scaled = tl.minimum(tl.maximum(w_new / new_wsc, -448.0), 448.0) u_rand = ((r_bits & 0xFFFF).to(tl.float32) / 65536.0) - 0.5 w_dither = tl.minimum( tl.maximum(w_scaled + u_rand * tl.maximum(tl.abs(w_scaled) * 0.0625, 1e-4), -448.0), 448.0, ) tl.store(w_ptr + row_base, w_dither.to(w_ptr.dtype.element_ty)) tl.store(wscale_ptr + row_id, new_wsc) else: noise = (r_bits & 0xFFFF).to(tl.int32) w_bits = w_new.to(tl.int32, bitcast=True) w_bf16 = ((w_bits + noise) & (-65536)).to(tl.float32, bitcast=True).to(tl.bfloat16) tl.store(w_ptr + row_base, w_bf16) m_absmax = tl.max(tl.abs(m_new), axis=0) new_msc = tl.maximum(m_absmax / 127.0, 1e-12) qm_f = tl.minimum(tl.maximum(tl.floor(m_new / new_msc + 0.5), -127.0), 127.0) tl.store(qm_ptr + row_base, qm_f.to(tl.int8)) tl.store(msc_ptr + row_id, new_msc) tl.store(vrow_ptr + row_id, v_new) def _sparse_adam_math_rowwise_v( w_active, g_sum, m_prev, v_row_prev, row_counts, lr_t, b1, b2, eps ): """Row-wise FP32 v_row sparse Adam fallback (-25% VRAM & GDDR7 IO, 0.00% v quant error).""" m_new = b1 * m_prev + (1.0 - b1) * g_sum v_row_new = b2 * v_row_prev + (1.0 - b2) * (g_sum * g_sum).mean(dim=-1) bc1 = 1.0 - (b1 ** row_counts) bc2 = 1.0 - (b2 ** row_counts.squeeze(-1)) denom = (v_row_new / bc2).sqrt().unsqueeze(-1) + eps w_new = w_active - lr_t * (m_new / bc1) / denom w_bf16 = stochastic_round_bf16(w_new) m_sc = (m_new.abs().amax(dim=-1) / 127.0).clamp_min(1e-12) qm_new = torch.clamp(torch.round(m_new / m_sc.unsqueeze(-1)), -127, 127).to(torch.int8) return w_bf16, qm_new, m_sc, v_row_new # ===================================================== CUSTOM TRITON KERNELS _HAS_TORCH = True HAS_TRITON = _HAS_TRITON WINDOW_SIZE = GDN_CONV_KERNEL DEFAULT_BLOCK_T = 64 NEG_INF_SCORE = -1e9 FP8_DTYPE = getattr(torch, 'float8_e4m3fn', None) FP8_SCALE_EPS = 1e-12 def _is_power_of_two(x: int) -> bool: return x > 0 and (x & (x - 1)) == 0 # --- Kernel Suite 1: UltraMemV2 Gather-Reduce + Compact Sparse Grad Coalescing --- if _HAS_TRITON: @triton.jit def _triton_ultramem_gather_reduce_fwd( weight_ptr, wscale_ptr, slots_ptr, weights_ptr, out_ptr, N, n_rows, D, M_TOTAL: tl.constexpr, BLOCK_D: tl.constexpr, OUT_BF16: tl.constexpr, USE_FP8: tl.constexpr, ): """Fused gather + weighted reduction (FP8 per-row scaled or BF16): v_agg[tok, d] = sum_{k=0..M-1} weights[tok, k] * (weight[slots[tok, k], d] * w_scale[slots[tok, k]]). """ pid_n = tl.program_id(0) if pid_n >= N: return pid_d = tl.program_id(1) tok_i64 = pid_n.to(tl.int64) offs_d = pid_d.to(tl.int64) * BLOCK_D + tl.arange(0, BLOCK_D).to(tl.int64) mask_d = offs_d < D tok_m_base = tok_i64 * M_TOTAL acc = tl.zeros((BLOCK_D,), dtype=tl.float32) for k in range(M_TOTAL): slot = tl.load(slots_ptr + tok_m_base + k).to(tl.int64) w_scalar = tl.load(weights_ptr + tok_m_base + k).to(tl.float32) slot_ok = (slot >= 0) & (slot < n_rows) valid = mask_d & slot_ok # CRITICAL int64 addressing: slot (int64) * D + offs_d (int64) avoids int32 overflow (>2.14B) row_offs = slot * D + offs_d val = tl.load(weight_ptr + row_offs, mask=valid, other=0.0).to(tl.float32) if USE_FP8: sc = tl.load(wscale_ptr + slot, mask=slot_ok, other=1.0).to(tl.float32) w_scalar = w_scalar * sc acc += val * w_scalar out_offs = tok_i64 * D + offs_d if OUT_BF16: tl.store(out_ptr + out_offs, acc.to(tl.bfloat16), mask=mask_d) else: tl.store(out_ptr + out_offs, acc, mask=mask_d) @triton.jit def _triton_ultramem_dweights_bwd( weight_ptr, wscale_ptr, slots_ptr, dv_agg_ptr, dweights_ptr, N, n_rows, D, M_TOTAL: tl.constexpr, BLOCK_D: tl.constexpr, SINGLE_TILE: tl.constexpr, OUT_BF16: tl.constexpr, USE_FP8: tl.constexpr, ): """Fused routing-weight gradient (FP8 per-row scaled or BF16): d_weights[tok, k] = sum_d(d_v_agg[tok, d] * weight[slots[tok, k], d] * w_scale[slots[tok, k]]). """ pid_n = tl.program_id(0) if pid_n >= N: return tok_i64 = pid_n.to(tl.int64) tok_d_base = tok_i64 * D tok_m_base = tok_i64 * M_TOTAL if SINGLE_TILE: offs_d = tl.arange(0, BLOCK_D).to(tl.int64) mask_d = offs_d < D dv = tl.load(dv_agg_ptr + tok_d_base + offs_d, mask=mask_d, other=0.0).to(tl.float32) for k in range(M_TOTAL): slot = tl.load(slots_ptr + tok_m_base + k).to(tl.int64) slot_ok = (slot >= 0) & (slot < n_rows) valid = mask_d & slot_ok row_offs = slot * D + offs_d val = tl.load(weight_ptr + row_offs, mask=valid, other=0.0).to(tl.float32) dot = tl.sum(dv * val, axis=0) if USE_FP8: sc = tl.load(wscale_ptr + slot, mask=slot_ok, other=1.0).to(tl.float32) dot = dot * sc if OUT_BF16: tl.store(dweights_ptr + tok_m_base + k, dot.to(tl.bfloat16)) else: tl.store(dweights_ptr + tok_m_base + k, dot) else: # General multi-tile path when D > BLOCK_D for k in range(M_TOTAL): slot = tl.load(slots_ptr + tok_m_base + k).to(tl.int64) slot_ok = (slot >= 0) & (slot < n_rows) dot = tl.zeros((), dtype=tl.float32) d_start = 0 while d_start < D: offs_d = tl.arange(0, BLOCK_D).to(tl.int64) + d_start mask_d = offs_d < D dv = tl.load(dv_agg_ptr + tok_d_base + offs_d, mask=mask_d, other=0.0).to(tl.float32) val = tl.load( weight_ptr + slot * D + offs_d, mask=mask_d & slot_ok, other=0.0, ).to(tl.float32) dot += tl.sum(dv * val, axis=0) d_start += BLOCK_D if USE_FP8: sc = tl.load(wscale_ptr + slot, mask=slot_ok, other=1.0).to(tl.float32) dot = dot * sc if OUT_BF16: tl.store(dweights_ptr + tok_m_base + k, dot.to(tl.bfloat16)) else: tl.store(dweights_ptr + tok_m_base + k, dot) @triton.jit def _triton_ultramem_scatter_grad( inv_ptr, weights_ptr, dv_agg_ptr, g_sum_ptr, N, n_unique, D, M_TOTAL: tl.constexpr, BLOCK_D: tl.constexpr, ): """Fused compact sparse-grad coalescing: g_sum[inv[tok, k], d] += weights[tok, k] * d_v_agg[tok, d] (in FP32). Grid: (N, cdiv(D, BLOCK_D)) Loads d_v_agg[tok, :] ONCE into FP32 registers and scatters weighted contributions directly into the coalesced FP32 unique-slot gradient buffer g_sum [n_unique, D], completely avoiding materialization of [N, H, topK, D]. """ pid_n = tl.program_id(0) if pid_n >= N: return pid_d = tl.program_id(1) tok_i64 = pid_n.to(tl.int64) offs_d = pid_d.to(tl.int64) * BLOCK_D + tl.arange(0, BLOCK_D).to(tl.int64) mask_d = offs_d < D tok_d_base = tok_i64 * D tok_m_base = tok_i64 * M_TOTAL dv = tl.load(dv_agg_ptr + tok_d_base + offs_d, mask=mask_d, other=0.0).to(tl.float32) for k in range(M_TOTAL): u_row = tl.load(inv_ptr + tok_m_base + k).to(tl.int64) w_scalar = tl.load(weights_ptr + tok_m_base + k).to(tl.float32) valid = mask_d & (u_row >= 0) & (u_row < n_unique) g_offs = u_row * D + offs_d tl.atomic_add(g_sum_ptr + g_offs, dv * w_scalar, mask=valid) # ============================================================================= # 2. LAUNCHERS & MEMORY-LEAN PYTORCH FALLBACKS # ============================================================================= def _next_pow2(n: int) -> int: return 1 << (max(1, n) - 1).bit_length() def _select_block_d(D: int) -> int: return min(1024, _next_pow2(D)) def _ultramem_gather_reduce_fwd_impl( weight: "torch.Tensor", slots_2d: "torch.Tensor", weights_2d: "torch.Tensor", out_dtype: "torch.dtype", chunk_tokens: int = 256, w_scale: Optional["torch.Tensor"] = None, ) -> "torch.Tensor": """Forward dispatcher: Triton kernel on CUDA (FP8 per-row scaled or BF16), chunked fallback otherwise.""" N, M = slots_2d.shape n_rows, D = weight.shape use_fp8 = w_scale is not None if N == 0: return torch.empty((0, D), device=weight.device, dtype=out_dtype) use_triton = ( _HAS_TRITON and weight.is_cuda and slots_2d.is_cuda and weights_2d.is_cuda and out_dtype in (torch.bfloat16, torch.float32) ) if use_triton: w_c = weight.contiguous() wsc_c = w_scale.contiguous() if use_fp8 else weights_2d s_c = slots_2d.contiguous() wt_c = weights_2d.contiguous() out = torch.empty((N, D), device=weight.device, dtype=out_dtype) block_d = _select_block_d(D) grid = (N, triton.cdiv(D, block_d)) _triton_ultramem_gather_reduce_fwd[grid]( w_c, wsc_c, s_c, wt_c, out, N, n_rows, D, M_TOTAL=M, BLOCK_D=block_d, OUT_BF16=(out_dtype == torch.bfloat16), USE_FP8=use_fp8, num_warps=8 if block_d >= 512 else 4, ) return out # Memory-lean chunked PyTorch fallback (avoids full [N, M, D] allocation when N is large) out = torch.empty((N, D), device=weight.device, dtype=out_dtype) for n0 in range(0, N, chunk_tokens): n1 = min(N, n0 + chunk_tokens) s_c = slots_2d[n0:n1].to(torch.long) wt_c = weights_2d[n0:n1].float().unsqueeze(-1) # [C, M, 1] if use_fp8: vals_c = weight[s_c.reshape(-1)].float().view(n1 - n0, M, D) sc_c = w_scale[s_c.reshape(-1)].view(n1 - n0, M, 1) vals_c = vals_c * sc_c else: vals_c = F.embedding(s_c.reshape(-1), weight).view(n1 - n0, M, D).float() out[n0:n1] = (vals_c * wt_c).sum(dim=1).to(out_dtype) return out def _ultramem_dweights_bwd_impl( weight: "torch.Tensor", slots_2d: "torch.Tensor", dv_agg: "torch.Tensor", out_dtype: "torch.dtype", chunk_tokens: int = 256, w_scale: Optional["torch.Tensor"] = None, ) -> "torch.Tensor": """Backward d_weights dispatcher: Triton kernel on CUDA (FP8 per-row scaled or BF16), chunked fallback otherwise.""" N, M = slots_2d.shape n_rows, D = weight.shape use_fp8 = w_scale is not None if N == 0: return torch.empty((0, M), device=weight.device, dtype=out_dtype) use_triton = ( _HAS_TRITON and weight.is_cuda and slots_2d.is_cuda and dv_agg.is_cuda and out_dtype in (torch.bfloat16, torch.float32) ) if use_triton: w_c = weight.contiguous() wsc_c = w_scale.contiguous() if use_fp8 else dv_agg s_c = slots_2d.contiguous() dv_c = dv_agg.contiguous() d_weights = torch.empty((N, M), device=weight.device, dtype=out_dtype) block_d = _select_block_d(D) single_tile = D <= block_d _triton_ultramem_dweights_bwd[(N,)]( w_c, wsc_c, s_c, dv_c, d_weights, N, n_rows, D, M_TOTAL=M, BLOCK_D=block_d, SINGLE_TILE=single_tile, OUT_BF16=(out_dtype == torch.bfloat16), USE_FP8=use_fp8, num_warps=8 if block_d >= 512 else 4, ) return d_weights # Memory-lean chunked PyTorch fallback d_weights = torch.empty((N, M), device=weight.device, dtype=out_dtype) for n0 in range(0, N, chunk_tokens): n1 = min(N, n0 + chunk_tokens) s_c = slots_2d[n0:n1].to(torch.long) dv_c = dv_agg[n0:n1].float().unsqueeze(1) # [C, 1, D] if use_fp8: vals_c = weight[s_c.reshape(-1)].float().view(n1 - n0, M, D) sc_c = w_scale[s_c.reshape(-1)].view(n1 - n0, M, 1) vals_c = vals_c * sc_c else: vals_c = F.embedding(s_c.reshape(-1), weight).view(n1 - n0, M, D).float() d_weights[n0:n1] = (vals_c * dv_c).sum(dim=-1).to(out_dtype) return d_weights def coalesce_compact_sparse_grads( grad_buffer: Sequence[Tuple["torch.Tensor", ...]], dim: int, device: Optional["torch.device"] = None, chunk_tokens: int = 256, ) -> Tuple["torch.Tensor", "torch.Tensor"]: """Materialize coalesced `(u_idx, g_sum)` FP32 gradients from compact 3-tuples `(slots [N, M], weights [N, M], d_v_agg [N, D])` AND/OR legacy 2-tuples `(flat_idx, grad_out)`. Never allocates `[N_total, M, D]`. Uses `_triton_ultramem_scatter_grad` on CUDA+Triton and a chunked `index_add_` fallback on CPU or without Triton. """ if not grad_buffer: dev = device if device is not None else torch.device("cpu") return ( torch.empty((0,), device=dev, dtype=torch.long), torch.empty((0, dim), device=dev, dtype=torch.float32), ) compact_entries: List[Tuple["torch.Tensor", "torch.Tensor", "torch.Tensor"]] = [] legacy_entries: List[Tuple["torch.Tensor", "torch.Tensor"]] = [] for item in grad_buffer: if len(item) == 3: compact_entries.append((item[0], item[1], item[2])) elif len(item) == 2: legacy_entries.append((item[0], item[1])) else: raise ValueError(f"Unsupported grad_buffer entry tuple length: {len(item)}") # Gather all flat slot IDs once to compute a single global unique index map flat_idx_parts: List["torch.Tensor"] = [] compact_counts: List[int] = [] for slots_2d, _, _ in compact_entries: flat_s = slots_2d.reshape(-1).to(torch.long) flat_idx_parts.append(flat_s) compact_counts.append(flat_s.numel()) legacy_counts: List[int] = [] for flat_idx, _ in legacy_entries: flat_s = flat_idx.reshape(-1).to(torch.long) flat_idx_parts.append(flat_s) legacy_counts.append(flat_s.numel()) all_idx = flat_idx_parts[0] if len(flat_idx_parts) == 1 else torch.cat(flat_idx_parts, dim=0) dev = device if device is not None else all_idx.device u_idx, inv = torch.unique(all_idx, return_inverse=True) n_unique = u_idx.numel() g_sum = torch.zeros((n_unique, dim), device=dev, dtype=torch.float32) offset = 0 for (slots_2d, weights_2d, dv_agg), count in zip(compact_entries, compact_counts): N, M = slots_2d.shape inv_2d = inv[offset : offset + count].view(N, M) offset += count if N == 0: continue if _HAS_TRITON and g_sum.is_cuda and dv_agg.is_cuda and weights_2d.is_cuda: block_d = _select_block_d(dim) grid = (N, triton.cdiv(dim, block_d)) _triton_ultramem_scatter_grad[grid]( inv_2d.contiguous(), weights_2d.contiguous(), dv_agg.contiguous(), g_sum, N, n_unique, dim, M_TOTAL=M, BLOCK_D=block_d, num_warps=8 if block_d >= 512 else 4, ) else: for n0 in range(0, N, chunk_tokens): n1 = min(N, n0 + chunk_tokens) inv_c = inv_2d[n0:n1].reshape(-1) wt_c = weights_2d[n0:n1].float().unsqueeze(-1) # [C, M, 1] dv_c = dv_agg[n0:n1].float().unsqueeze(1) # [C, 1, D] contrib = (wt_c * dv_c).reshape(-1, dim) g_sum.index_add_(0, inv_c, contrib) for (_, grad_out), count in zip(legacy_entries, legacy_counts): inv_seg = inv[offset : offset + count] offset += count if count > 0: g_sum.index_add_(0, inv_seg, grad_out.reshape(-1, dim).float()) return u_idx, g_sum # ============================================================================= # 3. PYTORCH AUTOGRAD WRAPPER & DROP-IN INTEGRATION HELPERS # ============================================================================= if True: class FusedUltraMemGatherReduceFunction(torch.autograd.Function): """Autograd wrapper fusing GDDR7 sparse gather + weighted reduction. Forward inputs: weight: [V, D] BF16/FP32 sparse table (e.g. [29_337_800, 512]) global_slots: [N, H, topK] (or [N, M]) int64/int32 slot indices weights: [N, H, topK] (or [N, M]) BF16/FP32 routing weights grad_buffer_list: GDDR7SparseTable.grad_buffer (or compact_grad_buffer), or None grad_hook: optional 0-elem requires_grad tensor (used only if weights.requires_grad is False) Forward output: v_agg: [N, D] (same dtype as `weights`, typically BF16) Backward: - Computes `d_weights` via `_triton_ultramem_dweights_bwd` (zero [N, H, topK, D] materialization). - Appends compact 3-tuple `(slots_i32_or_i64, weights_2d, d_v_agg)` (~4.75 MiB/block for N=4096) to `grad_buffer_list` for coalesced update in `GDDR7SparseTable.sparse_adam_step`. """ @staticmethod def forward(ctx, weight, global_slots, weights, grad_buffer_list, grad_hook, w_scale): orig_weight_shape = weights.shape N = orig_weight_shape[0] M = weights.numel() // max(1, N) slots_2d = global_slots.reshape(N, M) weights_2d = weights.reshape(N, M) out_dtype = weights.dtype v_agg = _ultramem_gather_reduce_fwd_impl( weight, slots_2d, weights_2d, out_dtype=out_dtype, w_scale=w_scale ) # Store int32 slots when safe (29,337,800 < 2^31-1) to halve TBPTT buffer size for slots! slots_saved = ( slots_2d.to(torch.int32) if weight.size(0) <= 2_147_483_647 else slots_2d.to(torch.int64) ) ctx.has_w_scale = w_scale is not None if w_scale is not None: ctx.save_for_backward(weight, slots_saved, weights_2d, w_scale) else: ctx.save_for_backward(weight, slots_saved, weights_2d) ctx.orig_weight_shape = orig_weight_shape ctx.weights_dtype = weights.dtype ctx.grad_buffer_list = grad_buffer_list return v_agg @staticmethod def backward(ctx, d_v_agg): if ctx.has_w_scale: weight, slots_saved, weights_2d, w_scale = ctx.saved_tensors else: weight, slots_saved, weights_2d = ctx.saved_tensors w_scale = None dv_c = d_v_agg.contiguous() # 1. Compact sparse gradient buffering for GDDR7SparseTable (no [N, H, topK, D]!) d_weight = None if ctx.grad_buffer_list is not None: ctx.grad_buffer_list.append( (slots_saved.detach(), weights_2d.detach(), dv_c.detach()) ) elif ctx.needs_input_grad[0]: # Standalone autograd fallback (e.g. unit testing / gradcheck without GDDR7SparseTable) u_idx, g_sum = coalesce_compact_sparse_grads( [(slots_saved, weights_2d, dv_c)], dim=weight.size(1), device=weight.device ) d_weight = torch.zeros_like(weight, dtype=torch.float32) d_weight.index_add_(0, u_idx, g_sum) d_weight = d_weight.to(weight.dtype) # 2. Fused routing-weight gradient d_weights [N, H, topK] d_weights = None if ctx.needs_input_grad[2]: d_weights_2d = _ultramem_dweights_bwd_impl( weight, slots_saved, dv_c, out_dtype=ctx.weights_dtype, w_scale=w_scale ) d_weights = d_weights_2d.view(ctx.orig_weight_shape) return d_weight, None, d_weights, None, None, None def fused_ultramem_gather_reduce( weight: "torch.Tensor", global_slots: "torch.Tensor", weights: "torch.Tensor", grad_buffer_list: Optional[list] = None, w_scale: Optional["torch.Tensor"] = None, ) -> "torch.Tensor": """Public entry point matching `GDDR7SparseTable` + `UltraMemV2TDQKRBridge`. Drop-in replacement in `UltraMemV2TDQKRBridge.forward_flat`: # Before (materialized 134 MB [N, 2, 16, 512] intermediate!): # vals = self.sparse_table.lookup(global_slots) # v_agg = (vals * weights.unsqueeze(-1)).sum(dim=(1, 2)) # # After (fused in registers, 4 MB output + ~4.75 MB compact grad buffer): # v_agg = fused_ultramem_gather_reduce( # self.sparse_table.weight, global_slots, weights, self.sparse_table.grad_buffer # ) """ if not _HAS_TORCH: raise RuntimeError("PyTorch is required to call fused_ultramem_gather_reduce.") if not torch.is_grad_enabled(): N = weights.shape[0] M = weights.numel() // max(1, N) return _ultramem_gather_reduce_fwd_impl( weight, global_slots.reshape(N, M), weights.reshape(N, M), out_dtype=weights.dtype, w_scale=w_scale, ) grad_hook = None if grad_buffer_list is not None and not weights.requires_grad: grad_hook = torch.empty(0, device=weight.device, requires_grad=True) return FusedUltraMemGatherReduceFunction.apply( weight, global_slots, weights, grad_buffer_list, grad_hook, w_scale ) def patch_gddr7_sparse_table(table) -> None: """Optional runtime helper to attach `lookup_and_reduce` and compact-grad `sparse_adam_step` support to an existing `GDDR7SparseTable` instance without modifying its `__init__`. Inside `GDDR7SparseTable.sparse_adam_step`, replace lines 1056-1067 with: u_idx, g_sum = coalesce_compact_sparse_grads(self.grad_buffer, self.dim, device=self.device) self.grad_buffer.clear() Everything downstream (visited_mask, grad norm clip, `_triton_sparse_adam_rowv_kernel`) stays identical! """ import types def lookup_and_reduce(self, global_slots, weights): return fused_ultramem_gather_reduce( self.weight, global_slots, weights, self.grad_buffer ) table.lookup_and_reduce = types.MethodType(lookup_and_reduce, table) # --- Kernel Suite 2: TDQKR Tucker-TopK + OrthoInj-ZOH --- if _HAS_TRITON: @triton.jit def _tdqkr_tucker_topk_fwd_kernel( sr_ptr, sc_ptr, g_ptr, inv_temp_ptr, top_scores_ptr, sub_r_ptr, sub_c_ptr, weights_ptr, # Input strides stride_sr_n, stride_sr_h, stride_sr_r, stride_sr_k, stride_sc_n, stride_sc_h, stride_sc_r, stride_sc_k, stride_g_h, stride_g_r, stride_g_s, stride_it_h, # Output strides stride_out_n, stride_out_h, stride_out_k, # Runtime dimensions H, # Compile-time power-of-2 constants R: tl.constexpr, K0: tl.constexpr, K0_SQ: tl.constexpr, TOPK: tl.constexpr, ): """One program per (n, h) pair. Computes S[i, j] = sum_{r, s} sr[n, h, r, i] * G[h, r, s] * sc[n, h, s, j] strictly in registers without writing [N, H, K0, K0] to GDDR7, selects the exact top-TOPK entries via iterative argmax, computes FP32 softmax(top * inv_temp), and writes only [N, H, TOPK] outputs. """ pid = tl.program_id(0) n = pid // H h = pid % H n_i64 = n.to(tl.int64) h_i64 = h.to(tl.int64) offs_k0 = tl.arange(0, K0) offs_k0_i64 = offs_k0.to(tl.int64) sr_base = n_i64 * stride_sr_n + h_i64 * stride_sr_h sc_base = n_i64 * stride_sc_n + h_i64 * stride_sc_h g_base = h_i64 * stride_g_h # Compute S = (sr^T @ G) @ sc in FP32 registers via static rank unrolling. # Avoids tl.dot minimum-tile (>=16) restrictions for R=4 and avoids # materializing any [R, K0, K0] intermediate tensor. s_grid = tl.zeros([K0, K0], dtype=tl.float32) for s in tl.static_range(R): sc_s = tl.load( sc_ptr + sc_base + s * stride_sc_r + offs_k0_i64 * stride_sc_k ).to(tl.float32) m_s = tl.zeros([K0], dtype=tl.float32) for r in tl.static_range(R): sr_r = tl.load( sr_ptr + sr_base + r * stride_sr_r + offs_k0_i64 * stride_sr_k ).to(tl.float32) g_rs = tl.load(g_ptr + g_base + r * stride_g_r + s * stride_g_s).to( tl.float32 ) m_s += sr_r * g_rs s_grid += m_s[:, None] * sc_s[None, :] # Flatten [K0, K0] -> [K0_SQ] (1024) in registers and run exact top-K selection. s_work = tl.reshape(s_grid, [K0_SQ]) offs_flat = tl.arange(0, K0_SQ) offs_top = tl.arange(0, TOPK) neg_inf = tl.full([K0_SQ], float("-inf"), dtype=tl.float32) top_vals = tl.zeros([TOPK], dtype=tl.float32) top_idxs = tl.zeros([TOPK], dtype=tl.int32) for k in tl.static_range(TOPK): val = tl.max(s_work, axis=0) idx = tl.argmax(s_work, axis=0).to(tl.int32) top_vals = tl.where(offs_top == k, val, top_vals) top_idxs = tl.where(offs_top == k, idx, top_idxs) s_work = tl.where(offs_flat == idx, neg_inf, s_work) # Decode 2D coordinates inside the K0 x K0 candidate grid. sub_r = (top_idxs // K0).to(tl.int64) sub_c = (top_idxs % K0).to(tl.int64) # Numerically stable FP32 softmax over top-K scores. inv_temp_val = tl.load(inv_temp_ptr + h_i64 * stride_it_h).to(tl.float32) scaled = top_vals * inv_temp_val max_scaled = tl.max(scaled, axis=0) exps = tl.exp(scaled - max_scaled) denom = tl.sum(exps, axis=0) weights = exps / denom # Coalesced 16-element vector stores to GDDR7. out_base = n_i64 * stride_out_n + h_i64 * stride_out_h out_offs = out_base + offs_top.to(tl.int64) * stride_out_k tl.store(top_scores_ptr + out_offs, top_vals) tl.store(sub_r_ptr + out_offs, sub_r) tl.store(sub_c_ptr + out_offs, sub_c) tl.store(weights_ptr + out_offs, weights) @triton.jit def _orthoinj_zoh_fwd_kernel( x_ptr, a_ptr, lam_ptr, g_ptr, x_out_ptr, p_out_ptr, q_norm2_out_ptr, stride_x_n, stride_a_n, stride_out_n, D, eps, BLOCK_D: tl.constexpr, ): """Single-pass OrthoInj + ZOH forward kernel (one program per token row). Loads x, a, lam, g once into registers, computes FP32 reductions for p = sum(lx * q) / (sum(q^2) + eps), writes x_out = (lx - p * q) + q, and saves scalar (p, q_norm2) for single-pass backward. """ row = tl.program_id(0) row_i64 = row.to(tl.int64) offs = tl.arange(0, BLOCK_D) offs_i64 = offs.to(tl.int64) mask = offs < D x = tl.load(x_ptr + row_i64 * stride_x_n + offs_i64, mask=mask, other=0.0).to( tl.float32 ) a = tl.load(a_ptr + row_i64 * stride_a_n + offs_i64, mask=mask, other=0.0).to( tl.float32 ) lam = tl.load(lam_ptr + offs_i64, mask=mask, other=0.0).to(tl.float32) g = tl.load(g_ptr + offs_i64, mask=mask, other=0.0).to(tl.float32) q = g * a lx = lam * x num = tl.sum(lx * q, axis=0) q_norm2 = tl.sum(q * q, axis=0) p = num / (q_norm2 + eps) x_out = (lx - p * q) + q tl.store(x_out_ptr + row_i64 * stride_out_n + offs_i64, x_out.to(x_out_ptr.dtype.element_ty), mask=mask) tl.store(p_out_ptr + row_i64, p) tl.store(q_norm2_out_ptr + row_i64, q_norm2) @triton.jit def _orthoinj_zoh_bwd_kernel( dy_ptr, x_ptr, a_ptr, lam_ptr, g_ptr, p_ptr, q_norm2_ptr, dx_ptr, da_ptr, dlam_ptr, dg_ptr, stride_dy_n, stride_x_n, stride_a_n, stride_dx_n, stride_da_n, N, D, eps, BLOCK_D: tl.constexpr, ): """Single-pass persistent-grid OrthoInj + ZOH backward kernel. Each program loads lam and g once into registers, strides across rows computing exact dx, da in one pass per row, accumulates partial dlam and dg in FP32 registers, and performs a single atomic_add per program at exit. """ pid = tl.program_id(0) num_pids = tl.num_programs(0) offs = tl.arange(0, BLOCK_D) offs_i64 = offs.to(tl.int64) mask = offs < D lam = tl.load(lam_ptr + offs_i64, mask=mask, other=0.0).to(tl.float32) g = tl.load(g_ptr + offs_i64, mask=mask, other=0.0).to(tl.float32) acc_dlam = tl.zeros([BLOCK_D], dtype=tl.float32) acc_dg = tl.zeros([BLOCK_D], dtype=tl.float32) for row in range(pid, N, num_pids): row_i64 = row.to(tl.int64) dy = tl.load( dy_ptr + row_i64 * stride_dy_n + offs_i64, mask=mask, other=0.0 ).to(tl.float32) x = tl.load( x_ptr + row_i64 * stride_x_n + offs_i64, mask=mask, other=0.0 ).to(tl.float32) a = tl.load( a_ptr + row_i64 * stride_a_n + offs_i64, mask=mask, other=0.0 ).to(tl.float32) p = tl.load(p_ptr + row_i64).to(tl.float32) q_norm2 = tl.load(q_norm2_ptr + row_i64).to(tl.float32) q = g * a lx = lam * x denom = q_norm2 + eps dy_dot_q = tl.sum(dy * q, axis=0) alpha = -dy_dot_q / denom dlx = dy + alpha * q dq = (1.0 - p) * dy + alpha * (lx - 2.0 * p * q) dx = dlx * lam da = dq * g tl.store(dx_ptr + row_i64 * stride_dx_n + offs_i64, dx.to(dx_ptr.dtype.element_ty), mask=mask) tl.store(da_ptr + row_i64 * stride_da_n + offs_i64, da.to(da_ptr.dtype.element_ty), mask=mask) acc_dlam += dlx * x acc_dg += dq * a tl.atomic_add(dlam_ptr + offs_i64, acc_dlam, mask=mask) tl.atomic_add(dg_ptr + offs_i64, acc_dg, mask=mask) # ============================================================================= # 2. PYTORCH FALLBACKS & AUTOGRAD FUNCTIONS # ============================================================================= if True: def _tdqkr_tucker_topk_fwd_pytorch( sr_sub: torch.Tensor, sc_sub: torch.Tensor, tucker_core: torch.Tensor, inv_temp: torch.Tensor, topk: int = 16, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: """Reference PyTorch forward for `fused_tdqkr_tucker_topk`.""" sr_f = sr_sub.float() sc_f = sc_sub.float() g_f = tucker_core.float() it_f = inv_temp.float() N, H, _R, K0 = sr_f.shape # M[n, h, i, s] = sum_r sr[n, h, r, i] * G[h, r, s] # S[n, h, i, j] = sum_s M[n, h, i, s] * sc[n, h, s, j] s_grid = torch.einsum("nhri,hrs,nhsj->nhij", sr_f, g_f, sc_f) top_scores, flat_idx = torch.topk( s_grid.reshape(N, H, K0 * K0), k=topk, dim=-1 ) sub_r = (flat_idx // K0).to(torch.int64) sub_c = (flat_idx % K0).to(torch.int64) weights = F.softmax(top_scores * it_f, dim=-1) return top_scores, sub_r, sub_c, weights def _tdqkr_tucker_topk_bwd_sparse_pytorch( sr_sub: torch.Tensor, sc_sub: torch.Tensor, tucker_core: torch.Tensor, inv_temp: torch.Tensor, top_scores: torch.Tensor, sub_r: torch.Tensor, sub_c: torch.Tensor, weights: torch.Tensor, grad_top_scores: Optional[torch.Tensor], grad_weights: Optional[torch.Tensor], ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: """Exact sparse backward strictly over the topK selected (sub_r, sub_c) pairs. Performs 64x less compute than dense [N, H, 32, 32] backward for K0=32, topK=16. """ sr_f = sr_sub.float() sc_f = sc_sub.float() g_f = tucker_core.float() it_f = inv_temp.float() N, H, R, K0 = sr_f.shape K = top_scores.shape[-1] g_top = torch.zeros_like(top_scores, dtype=torch.float32) if grad_top_scores is not None: g_top = g_top + grad_top_scores.float() d_inv_temp = torch.zeros_like(it_f, dtype=torch.float32) if grad_weights is not None: gw = grad_weights.float() w = weights.float() dot = (gw * w).sum(dim=-1, keepdim=True) dz = w * (gw - dot) g_top = g_top + dz * it_f d_inv_temp = (dz * top_scores.float()).sum(dim=(0, 2)).view(1, H, 1) # Gather selected row & col rank vectors: [N, H, R, K] -> [N, H, K, R] idx_r_exp = sub_r.unsqueeze(2).expand(N, H, R, K) idx_c_exp = sub_c.unsqueeze(2).expand(N, H, R, K) u = torch.gather(sr_f, dim=-1, index=idx_r_exp).transpose(-1, -2) # [N, H, K, R] v = torch.gather(sc_f, dim=-1, index=idx_c_exp).transpose(-1, -2) # [N, H, K, R] # Sparse gradients over only K=16 active pairs: # du[n, h, k, r] = g_top[n, h, k] * sum_s G[h, r, s] * v[n, h, k, s] # dv[n, h, k, s] = g_top[n, h, k] * sum_r u[n, h, k, r] * G[h, r, s] # dG[h, r, s] = sum_{n, k} g_top[n, h, k] * u[n, h, k, r] * v[n, h, k, s] gv = torch.einsum("hrs,nhks->nhkr", g_f, v) ug = torch.einsum("nhkr,hrs->nhks", u, g_f) du = (g_top.unsqueeze(-1) * gv).transpose(-1, -2) # [N, H, R, K] dv = (g_top.unsqueeze(-1) * ug).transpose(-1, -2) # [N, H, R, K] d_sr_sub = torch.zeros_like(sr_f) d_sc_sub = torch.zeros_like(sc_f) d_sr_sub.scatter_add_(dim=-1, index=idx_r_exp, src=du) d_sc_sub.scatter_add_(dim=-1, index=idx_c_exp, src=dv) d_tucker_core = torch.einsum("nhk,nhkr,nhks->hrs", g_top, u, v) return ( d_sr_sub.to(sr_sub.dtype), d_sc_sub.to(sc_sub.dtype), d_tucker_core.to(tucker_core.dtype), d_inv_temp.to(inv_temp.dtype), ) class _FusedTDQKRTuckerTopKFn(torch.autograd.Function): @staticmethod def forward( ctx, sr_sub: torch.Tensor, sc_sub: torch.Tensor, tucker_core: torch.Tensor, inv_temp: torch.Tensor, topk: int, ): N, H, R, K0 = sr_sub.shape use_triton = ( _HAS_TRITON and sr_sub.is_cuda and sc_sub.is_cuda and tucker_core.is_cuda and inv_temp.is_cuda and _is_power_of_two(R) and _is_power_of_two(K0) and _is_power_of_two(topk) and topk <= K0 * K0 ) if use_triton: sr_c = sr_sub.contiguous().float() sc_c = sc_sub.contiguous().float() g_c = tucker_core.contiguous().float() it_c = inv_temp.contiguous().float() top_scores = torch.empty( (N, H, topk), device=sr_c.device, dtype=torch.float32 ) sub_r = torch.empty((N, H, topk), device=sr_c.device, dtype=torch.int64) sub_c = torch.empty((N, H, topk), device=sr_c.device, dtype=torch.int64) weights = torch.empty( (N, H, topk), device=sr_c.device, dtype=torch.float32 ) grid = (N * H,) _tdqkr_tucker_topk_fwd_kernel[grid]( sr_c, sc_c, g_c, it_c, top_scores, sub_r, sub_c, weights, sr_c.stride(0), sr_c.stride(1), sr_c.stride(2), sr_c.stride(3), sc_c.stride(0), sc_c.stride(1), sc_c.stride(2), sc_c.stride(3), g_c.stride(0), g_c.stride(1), g_c.stride(2), it_c.stride(1), top_scores.stride(0), top_scores.stride(1), top_scores.stride(2), H, R=R, K0=K0, K0_SQ=K0 * K0, TOPK=topk, num_warps=4, ) else: top_scores, sub_r, sub_c, weights = _tdqkr_tucker_topk_fwd_pytorch( sr_sub, sc_sub, tucker_core, inv_temp, topk=topk ) ctx.save_for_backward( sr_sub, sc_sub, tucker_core, inv_temp, top_scores, sub_r, sub_c, weights ) ctx.mark_non_differentiable(sub_r, sub_c) return top_scores, sub_r, sub_c, weights @staticmethod def backward(ctx, grad_top_scores, grad_sub_r, grad_sub_c, grad_weights): ( sr_sub, sc_sub, tucker_core, inv_temp, top_scores, sub_r, sub_c, weights, ) = ctx.saved_tensors d_sr, d_sc, d_g, d_it = _tdqkr_tucker_topk_bwd_sparse_pytorch( sr_sub, sc_sub, tucker_core, inv_temp, top_scores, sub_r, sub_c, weights, grad_top_scores, grad_weights, ) return d_sr, d_sc, d_g, d_it, None def fused_tdqkr_tucker_topk( sr_sub: torch.Tensor, sc_sub: torch.Tensor, tucker_core: torch.Tensor, inv_temp: torch.Tensor, topk: int = 16, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: """Fused Tucker score grid + exact top-K + softmax with sparse 64x-faster backward. Args: sr_sub: [N, H, R, cand_k0] FP32 (locked-in: [N, 2, 4, 32]) sc_sub: [N, H, R, cand_k0] FP32 (locked-in: [N, 2, 4, 32]) tucker_core: [H, R, R] FP32 (locked-in: [2, 4, 4]) inv_temp: [1, H, 1] FP32 (locked-in: [1, 2, 1]) topk: number of top slots to select (locked-in: 16) Returns: (top_scores [N, H, topk], sub_r [N, H, topk], sub_c [N, H, topk], weights [N, H, topk]) """ return _FusedTDQKRTuckerTopKFn.apply( sr_sub, sc_sub, tucker_core, inv_temp, topk ) def _orthoinj_zoh_fwd_pytorch( x: torch.Tensor, a: torch.Tensor, lam: torch.Tensor, g: torch.Tensor, eps: float = EPS_DEFAULT, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Reference PyTorch forward for `fused_orthoinj_zoh`.""" x_f = x.float() a_f = a.float() lam_f = lam.float() g_f = g.float() q = g_f * a_f lx = lam_f * x_f num = (lx * q).sum(dim=-1, keepdim=True) q_norm2 = (q * q).sum(dim=-1, keepdim=True) p = num / (q_norm2 + eps) x_out = (lx - p * q) + q return x_out.to(x.dtype), p.squeeze(-1), q_norm2.squeeze(-1) def _orthoinj_zoh_bwd_pytorch( dy: torch.Tensor, x: torch.Tensor, a: torch.Tensor, lam: torch.Tensor, g: torch.Tensor, p: torch.Tensor, q_norm2: torch.Tensor, eps: float = EPS_DEFAULT, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: """Reference PyTorch backward for `fused_orthoinj_zoh`.""" dy_f = dy.float() x_f = x.float() a_f = a.float() lam_f = lam.float() g_f = g.float() p_f = p.float().unsqueeze(-1) denom = q_norm2.float().unsqueeze(-1) + eps q = g_f * a_f lx = lam_f * x_f dy_dot_q = (dy_f * q).sum(dim=-1, keepdim=True) alpha = -dy_dot_q / denom dlx = dy_f + alpha * q dq = (1.0 - p_f) * dy_f + alpha * (lx - 2.0 * p_f * q) dx = (dlx * lam_f).to(x.dtype) da = (dq * g_f).to(a.dtype) dlam = (dlx * x_f).sum(dim=0).to(lam.dtype) dg = (dq * a_f).sum(dim=0).to(g.dtype) return dx, da, dlam, dg class _FusedOrthoInjZOHFn(torch.autograd.Function): @staticmethod def forward( ctx, x: torch.Tensor, a: torch.Tensor, lam: torch.Tensor, g: torch.Tensor, eps: float, ): orig_shape = x.shape D = orig_shape[-1] x_2d = x.reshape(-1, D).contiguous() a_2d = a.reshape(-1, D).contiguous() lam_c = lam.contiguous().float() g_c = g.contiguous().float() N = x_2d.shape[0] use_triton = ( _HAS_TRITON and x_2d.is_cuda and a_2d.is_cuda and lam_c.is_cuda and g_c.is_cuda and D <= 4096 ) if use_triton: block_d = triton.next_power_of_2(D) x_out_2d = torch.empty_like(x_2d) p_out = torch.empty((N,), device=x_2d.device, dtype=torch.float32) q_norm2_out = torch.empty((N,), device=x_2d.device, dtype=torch.float32) _orthoinj_zoh_fwd_kernel[(N,)]( x_2d, a_2d, lam_c, g_c, x_out_2d, p_out, q_norm2_out, x_2d.stride(0), a_2d.stride(0), x_out_2d.stride(0), D, float(eps), BLOCK_D=block_d, num_warps=4, ) else: x_out_2d, p_out, q_norm2_out = _orthoinj_zoh_fwd_pytorch( x_2d, a_2d, lam_c, g_c, eps=eps ) ctx.save_for_backward(x_2d, a_2d, lam_c, g_c, p_out, q_norm2_out) ctx.orig_shape = orig_shape ctx.eps = float(eps) ctx.use_triton = use_triton ctx.lam_dtype = lam.dtype ctx.g_dtype = g.dtype return x_out_2d.view(orig_shape) @staticmethod def backward(ctx, grad_output): x_2d, a_2d, lam_c, g_c, p_out, q_norm2_out = ctx.saved_tensors orig_shape = ctx.orig_shape D = orig_shape[-1] N = x_2d.shape[0] dy_2d = grad_output.reshape(-1, D).contiguous() if ctx.use_triton and _HAS_TRITON and dy_2d.is_cuda: block_d = triton.next_power_of_2(D) dx_2d = torch.empty_like(x_2d) da_2d = torch.empty_like(a_2d) dlam = torch.zeros((D,), device=x_2d.device, dtype=torch.float32) dg = torch.zeros((D,), device=x_2d.device, dtype=torch.float32) num_progs = min(N, 128) if N > 0 else 1 _orthoinj_zoh_bwd_kernel[(num_progs,)]( dy_2d, x_2d, a_2d, lam_c, g_c, p_out, q_norm2_out, dx_2d, da_2d, dlam, dg, dy_2d.stride(0), x_2d.stride(0), a_2d.stride(0), dx_2d.stride(0), da_2d.stride(0), N, D, ctx.eps, BLOCK_D=block_d, num_warps=4, ) dlam = dlam.to(ctx.lam_dtype) dg = dg.to(ctx.g_dtype) else: dx_2d, da_2d, dlam, dg = _orthoinj_zoh_bwd_pytorch( dy_2d, x_2d, a_2d, lam_c, g_c, p_out, q_norm2_out, eps=ctx.eps ) dlam = dlam.to(ctx.lam_dtype) dg = dg.to(ctx.g_dtype) return dx_2d.view(orig_shape), da_2d.view(orig_shape), dlam, dg, None def fused_orthoinj_zoh( x: torch.Tensor, a: torch.Tensor, lam: torch.Tensor, g: torch.Tensor, eps: float = EPS_DEFAULT, ) -> torch.Tensor: """Fused single-pass OrthoInj + Parcae ZOH forward and backward. Computes: q = g * a lx = lam * x p = sum(lx * q) / (sum(q^2) + eps) x_out = (lx - p * q) + q Args: x: [..., D] stream activations (D=1024 for Block 0) a: [..., D] anchor activations lam: [D] FP32 precomputed exp(-softplus(zoh_log_decay)) g: [D] FP32 precomputed sigmoid(anchor_gate) eps: numerical stability epsilon (default 1e-6) Returns: x_out with same shape and dtype as `x`. """ return _FusedOrthoInjZOHFn.apply(x, a, lam, g, eps) # ============================================================================= # --- Kernel Suite 3: Pre-RoPE MoLA Online-Softmax Merge --- if _HAS_TRITON: @triton.jit def _triton_mola_online_merge_fwd( o_tok_ptr, lse_tok_ptr, q_ptr, k_mem_ptr, v_mem_ptr, beta_ptr, out_ptr, lse_mem_ptr, # Strides for o_tok [B, H, T, D] s_ot_b, s_ot_h, s_ot_t, s_ot_d, # Strides for lse_tok [B, H, T] s_lt_b, s_lt_h, s_lt_t, # Strides for q_normed [B, H, T, D] s_q_b, s_q_h, s_q_t, s_q_d, # Strides for k_mem_n [H, M, D] s_km_h, s_km_m, s_km_d, # Strides for v_mem [H, M, D] s_vm_h, s_vm_m, s_vm_d, # Strides for out [B, H, T, D] s_out_b, s_out_h, s_out_t, s_out_d, # Strides for lse_mem [B, H, T] s_lm_b, s_lm_h, s_lm_t, # Dimensions H, T, # Compile-time constants (strict power-of-2 + scalar constexpr) SCALE: tl.constexpr, BLOCK_T: tl.constexpr, HEAD_DIM: tl.constexpr, M_MOLA: tl.constexpr, INPUT_PRECISION: tl.constexpr, ): """Fused MoLA forward + online-softmax merge for one (b, h, t_tile).""" pid_t = tl.program_id(0) pid_bh = tl.program_id(1) b = pid_bh // H h = pid_bh % H offs_t = pid_t * BLOCK_T + tl.arange(0, BLOCK_T) offs_d = tl.arange(0, HEAD_DIM) offs_m = tl.arange(0, M_MOLA) t_mask = offs_t < T # Load per-head MoLA memory keys/values/bias once into registers km_ptrs = k_mem_ptr + h * s_km_h + offs_m[:, None] * s_km_m + offs_d[None, :] * s_km_d vm_ptrs = v_mem_ptr + h * s_vm_h + offs_m[:, None] * s_vm_m + offs_d[None, :] * s_vm_d k_mem = tl.load(km_ptrs) # [M_MOLA, HEAD_DIM] v_mem = tl.load(vm_ptrs) # [M_MOLA, HEAD_DIM] beta_h = tl.load(beta_ptr + h).to(tl.float32) # scalar FP32 # Load token tile: q_normed [BLOCK_T, HEAD_DIM], o_tok [BLOCK_T, HEAD_DIM], lse_tok [BLOCK_T] q_ptrs = q_ptr + b * s_q_b + h * s_q_h + offs_t[:, None] * s_q_t + offs_d[None, :] * s_q_d ot_ptrs = o_tok_ptr + b * s_ot_b + h * s_ot_h + offs_t[:, None] * s_ot_t + offs_d[None, :] * s_ot_d lt_ptrs = lse_tok_ptr + b * s_lt_b + h * s_lt_h + offs_t * s_lt_t q_tile = tl.load(q_ptrs, mask=t_mask[:, None], other=0.0) o_tok = tl.load(ot_ptrs, mask=t_mask[:, None], other=0.0) lse_tok = tl.load(lt_ptrs, mask=t_mask, other=0.0).to(tl.float32) # scores = (q_normed @ k_mem_n^T) * (1 / sqrt(HEAD_DIM)) + beta_h [BLOCK_T, M_MOLA] scores = tl.dot( q_tile, tl.trans(k_mem), out_dtype=tl.float32, input_precision=INPUT_PRECISION, ) * SCALE + beta_h # Numerically stable logsumexp & softmax over M_MOLA m_max = tl.max(scores, axis=1) # [BLOCK_T] exp_s = tl.exp(scores - m_max[:, None]) # [BLOCK_T, M_MOLA] sum_exp = tl.sum(exp_s, axis=1) # [BLOCK_T] lse_mem = m_max + tl.log(sum_exp) # [BLOCK_T] p_mem = exp_s / sum_exp[:, None] # [BLOCK_T, M_MOLA], FP32 # o_mem = p_mem @ v_mem in registers [BLOCK_T, HEAD_DIM], FP32 accum o_mem = tl.dot( p_mem.to(v_mem.dtype), v_mem, out_dtype=tl.float32, input_precision=INPUT_PRECISION, ) # Overflow-safe sigmoid: alpha = sigmoid(lse_mem - lse_tok) diff = lse_mem - lse_tok pos_sig = 1.0 / (1.0 + tl.exp(-tl.where(diff >= 0.0, diff, 0.0))) exp_neg = tl.exp(tl.where(diff < 0.0, diff, 0.0)) neg_sig = exp_neg / (1.0 + exp_neg) alpha = tl.where(diff >= 0.0, pos_sig, neg_sig) # [BLOCK_T], FP32 # Online-softmax merge: out = (1 - alpha) * o_tok + alpha * o_mem out_f32 = (1.0 - alpha[:, None]) * o_tok.to(tl.float32) + alpha[:, None] * o_mem # Store only out [B, H, T, D] and lse_mem [B, H, T] out_ptrs = out_ptr + b * s_out_b + h * s_out_h + offs_t[:, None] * s_out_t + offs_d[None, :] * s_out_d lm_ptrs = lse_mem_ptr + b * s_lm_b + h * s_lm_h + offs_t * s_lm_t tl.store(out_ptrs, out_f32.to(o_tok.dtype), mask=t_mask[:, None]) tl.store(lm_ptrs, lse_mem, mask=t_mask) @triton.jit def _triton_mola_online_merge_bwd( d_out_ptr, out_ptr, lse_tok_ptr, lse_mem_ptr, q_ptr, k_mem_ptr, v_mem_ptr, beta_ptr, # Output gradients d_ot_ptr, d_q_ptr, d_km_ptr, # FP32 zero-initialized [H, M, D], accumulated via atomic_add d_vm_ptr, # FP32 zero-initialized [H, M, D], accumulated via atomic_add d_beta_ptr, # FP32 zero-initialized [H], accumulated via atomic_add # Strides for d_out [B, H, T, D] s_do_b, s_do_h, s_do_t, s_do_d, # Strides for out [B, H, T, D] s_out_b, s_out_h, s_out_t, s_out_d, # Strides for lse_tok [B, H, T] s_lt_b, s_lt_h, s_lt_t, # Strides for lse_mem [B, H, T] s_lm_b, s_lm_h, s_lm_t, # Strides for q_normed [B, H, T, D] s_q_b, s_q_h, s_q_t, s_q_d, # Strides for k_mem_n [H, M, D] s_km_h, s_km_m, s_km_d, # Strides for v_mem [H, M, D] s_vm_h, s_vm_m, s_vm_d, # Strides for d_o_tok [B, H, T, D] s_dot_b, s_dot_h, s_dot_t, s_dot_d, # Strides for d_q_normed [B, H, T, D] s_dq_b, s_dq_h, s_dq_t, s_dq_d, # Strides for d_k_mem_n [H, M, D] (FP32) s_dkm_h, s_dkm_m, s_dkm_d, # Strides for d_v_mem [H, M, D] (FP32) s_dvm_h, s_dvm_m, s_dvm_d, # Dimensions H, T, # Compile-time constants SCALE: tl.constexpr, BLOCK_T: tl.constexpr, HEAD_DIM: tl.constexpr, M_MOLA: tl.constexpr, INPUT_PRECISION: tl.constexpr, ): """Fused MoLA backward for one (b, h, t_tile). Computes exact analytical gradients: d_o_tok = (1 - alpha) * d_out D_out = sum_d(d_out * out) ds = (alpha * p_mem) * (d_out @ v_mem^T - D_out) d_q_normed = (ds @ k_mem_n) * SCALE d_k_mem_n += (ds^T @ q_normed) * SCALE d_v_mem += (alpha * p_mem)^T @ d_out d_beta += sum_{t,m}(ds) """ pid_t = tl.program_id(0) pid_bh = tl.program_id(1) b = pid_bh // H h = pid_bh % H offs_t = pid_t * BLOCK_T + tl.arange(0, BLOCK_T) offs_d = tl.arange(0, HEAD_DIM) offs_m = tl.arange(0, M_MOLA) t_mask = offs_t < T # Load per-head MoLA parameters once into registers km_ptrs = k_mem_ptr + h * s_km_h + offs_m[:, None] * s_km_m + offs_d[None, :] * s_km_d vm_ptrs = v_mem_ptr + h * s_vm_h + offs_m[:, None] * s_vm_m + offs_d[None, :] * s_vm_d k_mem = tl.load(km_ptrs) # [M_MOLA, HEAD_DIM] v_mem = tl.load(vm_ptrs) # [M_MOLA, HEAD_DIM] beta_h = tl.load(beta_ptr + h).to(tl.float32) # Load token tiles do_ptrs = d_out_ptr + b * s_do_b + h * s_do_h + offs_t[:, None] * s_do_t + offs_d[None, :] * s_do_d out_ptrs = out_ptr + b * s_out_b + h * s_out_h + offs_t[:, None] * s_out_t + offs_d[None, :] * s_out_d q_ptrs = q_ptr + b * s_q_b + h * s_q_h + offs_t[:, None] * s_q_t + offs_d[None, :] * s_q_d lt_ptrs = lse_tok_ptr + b * s_lt_b + h * s_lt_h + offs_t * s_lt_t lm_ptrs = lse_mem_ptr + b * s_lm_b + h * s_lm_h + offs_t * s_lm_t g_tile = tl.load(do_ptrs, mask=t_mask[:, None], other=0.0) out_tile = tl.load(out_ptrs, mask=t_mask[:, None], other=0.0) q_tile = tl.load(q_ptrs, mask=t_mask[:, None], other=0.0) lse_tok = tl.load(lt_ptrs, mask=t_mask, other=0.0).to(tl.float32) lse_mem = tl.load(lm_ptrs, mask=t_mask, other=0.0).to(tl.float32) g_f32 = g_tile.to(tl.float32) out_f32 = out_tile.to(tl.float32) # Recompute alpha = sigmoid(lse_mem - lse_tok) diff = lse_mem - lse_tok pos_sig = 1.0 / (1.0 + tl.exp(-tl.where(diff >= 0.0, diff, 0.0))) exp_neg = tl.exp(tl.where(diff < 0.0, diff, 0.0)) neg_sig = exp_neg / (1.0 + exp_neg) alpha = tl.where(diff >= 0.0, pos_sig, neg_sig) # [BLOCK_T], FP32 # 1) d_o_tok = (1 - alpha) * g d_ot_f32 = (1.0 - alpha[:, None]) * g_f32 dot_ptrs = d_ot_ptr + b * s_dot_b + h * s_dot_h + offs_t[:, None] * s_dot_t + offs_d[None, :] * s_dot_d tl.store(dot_ptrs, d_ot_f32.to(g_tile.dtype), mask=t_mask[:, None]) # Recompute p_mem = exp(scores - lse_mem) in registers scores = tl.dot( q_tile, tl.trans(k_mem), out_dtype=tl.float32, input_precision=INPUT_PRECISION, ) * SCALE + beta_h p_mem = tl.exp(scores - lse_mem[:, None]) # [BLOCK_T, M_MOLA] p_masked = tl.where(t_mask[:, None], p_mem, 0.0) # Effective joint probability on memory slots: ap = alpha * p_mem ap_masked = alpha[:, None] * p_masked # [BLOCK_T, M_MOLA] # FlashAttention-2 joint-softmax identity: # D_out = sum_d(g * out) = (1 - alpha) * + alpha * # ds = (alpha * p_mem) * (g @ v_mem^T - D_out) d_out_dot = tl.sum(g_f32 * out_f32, axis=1) # [BLOCK_T] gv = tl.dot( g_tile, tl.trans(v_mem), out_dtype=tl.float32, input_precision=INPUT_PRECISION, ) # [BLOCK_T, M_MOLA] ds = ap_masked * (gv - d_out_dot[:, None]) # [BLOCK_T, M_MOLA], already zeroed where ~t_mask # 2) d_q_normed = (ds @ k_mem_n) * SCALE dq_f32 = tl.dot( ds.to(k_mem.dtype), k_mem, out_dtype=tl.float32, input_precision=INPUT_PRECISION, ) * SCALE dq_ptrs = d_q_ptr + b * s_dq_b + h * s_dq_h + offs_t[:, None] * s_dq_t + offs_d[None, :] * s_dq_d tl.store(dq_ptrs, dq_f32.to(q_tile.dtype), mask=t_mask[:, None]) # 3) d_k_mem_n += (ds^T @ q_normed) * SCALE dk_tile = tl.dot( tl.trans(ds.to(q_tile.dtype)), q_tile, out_dtype=tl.float32, input_precision=INPUT_PRECISION, ) * SCALE dkm_ptrs = d_km_ptr + h * s_dkm_h + offs_m[:, None] * s_dkm_m + offs_d[None, :] * s_dkm_d tl.atomic_add(dkm_ptrs, dk_tile) # 4) d_v_mem += (alpha * p_mem)^T @ g dv_tile = tl.dot( tl.trans(ap_masked.to(g_tile.dtype)), g_tile, out_dtype=tl.float32, input_precision=INPUT_PRECISION, ) dvm_ptrs = d_vm_ptr + h * s_dvm_h + offs_m[:, None] * s_dvm_m + offs_d[None, :] * s_dvm_d tl.atomic_add(dvm_ptrs, dv_tile) # 5) d_beta += sum_{t,m}(ds) dbeta_val = tl.sum(tl.sum(ds, axis=1), axis=0) tl.atomic_add(d_beta_ptr + h, dbeta_val) if True: def fused_mola_online_merge_ref( o_tok: "torch.Tensor", lse_tok: "torch.Tensor", q_normed: "torch.Tensor", k_mem_n: "torch.Tensor", v_mem: "torch.Tensor", beta: "torch.Tensor", ) -> "torch.Tensor": """Exact PyTorch reference matching HiSASlidingWindowAttention (lines 1940-1950).""" dt = o_tok.dtype _, H, _, D = q_normed.shape scores_mem = ( torch.matmul(q_normed, k_mem_n.to(dt).transpose(-1, -2)).float() / math.sqrt(D) + beta.float().view(1, H, 1, 1) ) lse_mem = torch.logsumexp(scores_mem, dim=-1) p_mem = torch.softmax(scores_mem, dim=-1).to(dt) o_mem = torch.matmul(p_mem, v_mem.to(dt)) alpha = torch.sigmoid(lse_mem - lse_tok.detach().float()).unsqueeze(-1).to(dt) return (1.0 - alpha) * o_tok + alpha * o_mem class _FusedMoLAOnlineMergeFn(torch.autograd.Function): """Autograd wrapper around `_triton_mola_online_merge_{fwd,bwd}`.""" @staticmethod def forward( ctx, o_tok: "torch.Tensor", lse_tok: "torch.Tensor", q_normed: "torch.Tensor", k_mem_n: "torch.Tensor", v_mem: "torch.Tensor", beta: "torch.Tensor", ) -> "torch.Tensor": B, H, T, D = q_normed.shape M = k_mem_n.shape[1] dt = o_tok.dtype orig_ot_dtype = o_tok.dtype orig_q_dtype = q_normed.dtype orig_km_dtype = k_mem_n.dtype orig_vm_dtype = v_mem.dtype orig_beta_dtype = beta.dtype # Ensure matching dtype and contiguous innermost dim (zero-copy for .transpose(1, 2)) if o_tok.stride(-1) != 1: o_tok = o_tok.contiguous() if q_normed.dtype != dt: q_normed = q_normed.to(dt) if q_normed.stride(-1) != 1: q_normed = q_normed.contiguous() if k_mem_n.dtype != dt or not k_mem_n.is_contiguous(): k_mem_n = k_mem_n.to(dt).contiguous() if v_mem.dtype != dt or not v_mem.is_contiguous(): v_mem = v_mem.to(dt).contiguous() lse_tok_f32 = lse_tok.detach().float() if lse_tok_f32.stride(-1) != 1: lse_tok_f32 = lse_tok_f32.contiguous() beta_f32 = beta.float().contiguous() out = torch.empty((B, H, T, D), device=o_tok.device, dtype=dt) lse_mem = torch.empty((B, H, T), device=o_tok.device, dtype=torch.float32) BLOCK_T = 64 scale = 1.0 / math.sqrt(D) input_precision = "ieee" if dt == torch.float32 else "tf32" grid = (triton.cdiv(T, BLOCK_T), B * H) _triton_mola_online_merge_fwd[grid]( o_tok, lse_tok_f32, q_normed, k_mem_n, v_mem, beta_f32, out, lse_mem, o_tok.stride(0), o_tok.stride(1), o_tok.stride(2), o_tok.stride(3), lse_tok_f32.stride(0), lse_tok_f32.stride(1), lse_tok_f32.stride(2), q_normed.stride(0), q_normed.stride(1), q_normed.stride(2), q_normed.stride(3), k_mem_n.stride(0), k_mem_n.stride(1), k_mem_n.stride(2), v_mem.stride(0), v_mem.stride(1), v_mem.stride(2), out.stride(0), out.stride(1), out.stride(2), out.stride(3), lse_mem.stride(0), lse_mem.stride(1), lse_mem.stride(2), H, T, SCALE=scale, BLOCK_T=BLOCK_T, HEAD_DIM=D, M_MOLA=M, INPUT_PRECISION=input_precision, num_warps=4, num_stages=2, ) ctx.save_for_backward(out, lse_tok_f32, lse_mem, q_normed, k_mem_n, v_mem, beta_f32) ctx.meta = ( scale, BLOCK_T, D, M, input_precision, orig_ot_dtype, orig_q_dtype, orig_km_dtype, orig_vm_dtype, orig_beta_dtype, ) return out @staticmethod def backward(ctx, d_out: "torch.Tensor"): out, lse_tok_f32, lse_mem, q_normed, k_mem_n, v_mem, beta_f32 = ctx.saved_tensors ( scale, BLOCK_T, D, M, input_precision, ot_dtype, q_dtype, km_dtype, vm_dtype, beta_dtype, ) = ctx.meta B, H, T, _ = q_normed.shape if d_out.dtype != out.dtype: d_out = d_out.to(out.dtype) if d_out.stride(-1) != 1: d_out = d_out.contiguous() d_o_tok = torch.empty((B, H, T, D), device=d_out.device, dtype=out.dtype) d_q_normed = torch.empty((B, H, T, D), device=d_out.device, dtype=out.dtype) d_k_mem_n = torch.zeros((H, M, D), device=d_out.device, dtype=torch.float32) d_v_mem = torch.zeros((H, M, D), device=d_out.device, dtype=torch.float32) d_beta = torch.zeros((H,), device=d_out.device, dtype=torch.float32) grid = (triton.cdiv(T, BLOCK_T), B * H) _triton_mola_online_merge_bwd[grid]( d_out, out, lse_tok_f32, lse_mem, q_normed, k_mem_n, v_mem, beta_f32, d_o_tok, d_q_normed, d_k_mem_n, d_v_mem, d_beta, d_out.stride(0), d_out.stride(1), d_out.stride(2), d_out.stride(3), out.stride(0), out.stride(1), out.stride(2), out.stride(3), lse_tok_f32.stride(0), lse_tok_f32.stride(1), lse_tok_f32.stride(2), lse_mem.stride(0), lse_mem.stride(1), lse_mem.stride(2), q_normed.stride(0), q_normed.stride(1), q_normed.stride(2), q_normed.stride(3), k_mem_n.stride(0), k_mem_n.stride(1), k_mem_n.stride(2), v_mem.stride(0), v_mem.stride(1), v_mem.stride(2), d_o_tok.stride(0), d_o_tok.stride(1), d_o_tok.stride(2), d_o_tok.stride(3), d_q_normed.stride(0), d_q_normed.stride(1), d_q_normed.stride(2), d_q_normed.stride(3), d_k_mem_n.stride(0), d_k_mem_n.stride(1), d_k_mem_n.stride(2), d_v_mem.stride(0), d_v_mem.stride(1), d_v_mem.stride(2), H, T, SCALE=scale, BLOCK_T=BLOCK_T, HEAD_DIM=D, M_MOLA=M, INPUT_PRECISION=input_precision, num_warps=4, num_stages=2, ) # d_lse_tok is strictly None (lse_tok.detach() in forward) return ( d_o_tok.to(ot_dtype), None, d_q_normed.to(q_dtype), d_k_mem_n.to(km_dtype), d_v_mem.to(vm_dtype), d_beta.to(beta_dtype), ) def fused_mola_online_merge( o_tok: "torch.Tensor", lse_tok: "torch.Tensor", q_normed: "torch.Tensor", k_mem_n: "torch.Tensor", v_mem: "torch.Tensor", beta: "torch.Tensor", ) -> "torch.Tensor": """Drop-in replacement for lines 1940-1950 of `HiSASlidingWindowAttention.forward`. Dispatches to the fused Triton kernel on CUDA when `HEAD_DIM >= 16` and `M_MOLA >= 16` are powers of 2; otherwise falls back cleanly to PyTorch. """ D = q_normed.shape[-1] M = k_mem_n.shape[1] if ( _HAS_TRITON and o_tok.is_cuda and D >= 16 and M >= 16 and _is_power_of_two(D) and _is_power_of_two(M) ): return _FusedMoLAOnlineMergeFn.apply( o_tok, lse_tok, q_normed, k_mem_n, v_mem, beta ) return fused_mola_online_merge_ref( o_tok, lse_tok, q_normed, k_mem_n, v_mem, beta ) # ===================================================================== # --- Kernel Suite 4: 1-Pass Triton SWGDN2-G1 Local SWA (custom_op, 0 graph breaks) --- if _HAS_TRITON: @triton.jit def _triton_swgdn2_local_swa_fwd( # Input tensors: [B, T, H, D] q_ptr, k_ptr, v_ptr, kn_ptr, # Pre-rotated pseudo-queries: [3, 4, H, D] prot_ptr, # Output tensors: [B, T, H, D] and [B, 3, 4, T, H] FP32 q_out_ptr, k_out_ptr, v_out_ptr, attn_ptr, # Strides for q, k, v, k_n sq_b, sq_t, sq_h, sq_d, sk_b, sk_t, sk_h, sk_d, sv_b, sv_t, sv_h, sv_d, skn_b, skn_t, skn_h, skn_d, # Strides for p_rot: [3, 4, H, D] sp_x, sp_w, sp_h, sp_d, # Strides for outputs q_mix, k_mix, v_mix: [B, T, H, D] soq_b, soq_t, soq_h, soq_d, sok_b, sok_t, sok_h, sok_d, sov_b, sov_t, sov_h, sov_d, # Strides for attn: [B, 3, 4, T, H] sa_b, sa_x, sa_w, sa_t, sa_h, # Dimensions & scale T, scale, BLOCK_T: tl.constexpr, HEAD_DIM: tl.constexpr, ): pid_b = tl.program_id(0).to(tl.int64) pid_h = tl.program_id(1).to(tl.int64) pid_tile = tl.program_id(2).to(tl.int64) t_start = pid_tile * BLOCK_T t_offs = t_start + tl.arange(0, BLOCK_T).to(tl.int64) # [BLOCK_T] d_offs = tl.arange(0, HEAD_DIM).to(tl.int64) # [HEAD_DIM] m_t = t_offs < T # [BLOCK_T] # Valid masks and clamped causal indices for w in {0, 1, 2, 3} t0 = t_offs t1 = t_offs - 1 t2 = t_offs - 2 t3 = t_offs - 3 m0 = m_t & (t0 >= 0) m1 = m_t & (t1 >= 0) m2 = m_t & (t2 >= 0) m3 = m_t & (t3 >= 0) t0_c = tl.where(m0, t0, 0) t1_c = tl.where(m1, t1, 0) t2_c = tl.where(m2, t2, 0) t3_c = tl.where(m3, t3, 0) # Cast strides to int64 skn_b64 = tl.cast(skn_b, tl.int64) skn_t64 = tl.cast(skn_t, tl.int64) skn_h64 = tl.cast(skn_h, tl.int64) skn_d64 = tl.cast(skn_d, tl.int64) # Load k_n[b, t - w, h, :] ONCE for all 3 branches (FP32) kn_base = pid_b * skn_b64 + pid_h * skn_h64 kn0 = tl.load( kn_ptr + kn_base + t0_c[:, None] * skn_t64 + d_offs[None, :] * skn_d64, mask=m0[:, None], other=0.0, ).to(tl.float32) kn1 = tl.load( kn_ptr + kn_base + t1_c[:, None] * skn_t64 + d_offs[None, :] * skn_d64, mask=m1[:, None], other=0.0, ).to(tl.float32) kn2 = tl.load( kn_ptr + kn_base + t2_c[:, None] * skn_t64 + d_offs[None, :] * skn_d64, mask=m2[:, None], other=0.0, ).to(tl.float32) kn3 = tl.load( kn_ptr + kn_base + t3_c[:, None] * skn_t64 + d_offs[None, :] * skn_d64, mask=m3[:, None], other=0.0, ).to(tl.float32) # Load p_rot[0..2, 0..3, h, :] ONCE into registers (12 x HEAD_DIM FP32) sp_x64 = tl.cast(sp_x, tl.int64) sp_w64 = tl.cast(sp_w, tl.int64) sp_h64 = tl.cast(sp_h, tl.int64) sp_d64 = tl.cast(sp_d, tl.int64) p_h_base = pid_h * sp_h64 + d_offs * sp_d64 p00 = tl.load(prot_ptr + 0 * sp_x64 + 0 * sp_w64 + p_h_base).to(tl.float32) p01 = tl.load(prot_ptr + 0 * sp_x64 + 1 * sp_w64 + p_h_base).to(tl.float32) p02 = tl.load(prot_ptr + 0 * sp_x64 + 2 * sp_w64 + p_h_base).to(tl.float32) p03 = tl.load(prot_ptr + 0 * sp_x64 + 3 * sp_w64 + p_h_base).to(tl.float32) p10 = tl.load(prot_ptr + 1 * sp_x64 + 0 * sp_w64 + p_h_base).to(tl.float32) p11 = tl.load(prot_ptr + 1 * sp_x64 + 1 * sp_w64 + p_h_base).to(tl.float32) p12 = tl.load(prot_ptr + 1 * sp_x64 + 2 * sp_w64 + p_h_base).to(tl.float32) p13 = tl.load(prot_ptr + 1 * sp_x64 + 3 * sp_w64 + p_h_base).to(tl.float32) p20 = tl.load(prot_ptr + 2 * sp_x64 + 0 * sp_w64 + p_h_base).to(tl.float32) p21 = tl.load(prot_ptr + 2 * sp_x64 + 1 * sp_w64 + p_h_base).to(tl.float32) p22 = tl.load(prot_ptr + 2 * sp_x64 + 2 * sp_w64 + p_h_base).to(tl.float32) p23 = tl.load(prot_ptr + 2 * sp_x64 + 3 * sp_w64 + p_h_base).to(tl.float32) sa_b64 = tl.cast(sa_b, tl.int64) sa_x64 = tl.cast(sa_x, tl.int64) sa_w64 = tl.cast(sa_w, tl.int64) sa_t64 = tl.cast(sa_t, tl.int64) sa_h64 = tl.cast(sa_h, tl.int64) a_base = pid_b * sa_b64 + pid_h * sa_h64 + t_offs * sa_t64 neg_inf = -1e9 # ---------------- Branch 0: Q ---------------- s0 = tl.where(m0, tl.sum(kn0 * p00[None, :], axis=1) * scale, neg_inf) s1 = tl.where(m1, tl.sum(kn1 * p01[None, :], axis=1) * scale, neg_inf) s2 = tl.where(m2, tl.sum(kn2 * p02[None, :], axis=1) * scale, neg_inf) s3 = tl.where(m3, tl.sum(kn3 * p03[None, :], axis=1) * scale, neg_inf) m_max = tl.maximum(tl.maximum(s0, s1), tl.maximum(s2, s3)) e0 = tl.exp(s0 - m_max) e1 = tl.exp(s1 - m_max) e2 = tl.exp(s2 - m_max) e3 = tl.exp(s3 - m_max) inv_s = 1.0 / (e0 + e1 + e2 + e3) a0 = e0 * inv_s a1 = e1 * inv_s a2 = e2 * inv_s a3 = e3 * inv_s tl.store(attn_ptr + a_base + 0 * sa_x64 + 0 * sa_w64, a0, mask=m_t) tl.store(attn_ptr + a_base + 0 * sa_x64 + 1 * sa_w64, a1, mask=m_t) tl.store(attn_ptr + a_base + 0 * sa_x64 + 2 * sa_w64, a2, mask=m_t) tl.store(attn_ptr + a_base + 0 * sa_x64 + 3 * sa_w64, a3, mask=m_t) sq_b64 = tl.cast(sq_b, tl.int64) sq_t64 = tl.cast(sq_t, tl.int64) sq_h64 = tl.cast(sq_h, tl.int64) sq_d64 = tl.cast(sq_d, tl.int64) q_base = pid_b * sq_b64 + pid_h * sq_h64 x0 = tl.load(q_ptr + q_base + t0_c[:, None] * sq_t64 + d_offs[None, :] * sq_d64, mask=m0[:, None], other=0.0).to(tl.float32) x1 = tl.load(q_ptr + q_base + t1_c[:, None] * sq_t64 + d_offs[None, :] * sq_d64, mask=m1[:, None], other=0.0).to(tl.float32) x2 = tl.load(q_ptr + q_base + t2_c[:, None] * sq_t64 + d_offs[None, :] * sq_d64, mask=m2[:, None], other=0.0).to(tl.float32) x3 = tl.load(q_ptr + q_base + t3_c[:, None] * sq_t64 + d_offs[None, :] * sq_d64, mask=m3[:, None], other=0.0).to(tl.float32) u = a0[:, None] * x0 + a1[:, None] * x1 + a2[:, None] * x2 + a3[:, None] * x3 y = u * tl.sigmoid(u) soq_b64 = tl.cast(soq_b, tl.int64) soq_t64 = tl.cast(soq_t, tl.int64) soq_h64 = tl.cast(soq_h, tl.int64) soq_d64 = tl.cast(soq_d, tl.int64) tl.store( q_out_ptr + pid_b * soq_b64 + t_offs[:, None] * soq_t64 + pid_h * soq_h64 + d_offs[None, :] * soq_d64, y.to(q_out_ptr.dtype.element_ty), mask=m_t[:, None], ) # ---------------- Branch 1: K ---------------- s0 = tl.where(m0, tl.sum(kn0 * p10[None, :], axis=1) * scale, neg_inf) s1 = tl.where(m1, tl.sum(kn1 * p11[None, :], axis=1) * scale, neg_inf) s2 = tl.where(m2, tl.sum(kn2 * p12[None, :], axis=1) * scale, neg_inf) s3 = tl.where(m3, tl.sum(kn3 * p13[None, :], axis=1) * scale, neg_inf) m_max = tl.maximum(tl.maximum(s0, s1), tl.maximum(s2, s3)) e0 = tl.exp(s0 - m_max) e1 = tl.exp(s1 - m_max) e2 = tl.exp(s2 - m_max) e3 = tl.exp(s3 - m_max) inv_s = 1.0 / (e0 + e1 + e2 + e3) a0 = e0 * inv_s a1 = e1 * inv_s a2 = e2 * inv_s a3 = e3 * inv_s tl.store(attn_ptr + a_base + 1 * sa_x64 + 0 * sa_w64, a0, mask=m_t) tl.store(attn_ptr + a_base + 1 * sa_x64 + 1 * sa_w64, a1, mask=m_t) tl.store(attn_ptr + a_base + 1 * sa_x64 + 2 * sa_w64, a2, mask=m_t) tl.store(attn_ptr + a_base + 1 * sa_x64 + 3 * sa_w64, a3, mask=m_t) sk_b64 = tl.cast(sk_b, tl.int64) sk_t64 = tl.cast(sk_t, tl.int64) sk_h64 = tl.cast(sk_h, tl.int64) sk_d64 = tl.cast(sk_d, tl.int64) k_base = pid_b * sk_b64 + pid_h * sk_h64 x0 = tl.load(k_ptr + k_base + t0_c[:, None] * sk_t64 + d_offs[None, :] * sk_d64, mask=m0[:, None], other=0.0).to(tl.float32) x1 = tl.load(k_ptr + k_base + t1_c[:, None] * sk_t64 + d_offs[None, :] * sk_d64, mask=m1[:, None], other=0.0).to(tl.float32) x2 = tl.load(k_ptr + k_base + t2_c[:, None] * sk_t64 + d_offs[None, :] * sk_d64, mask=m2[:, None], other=0.0).to(tl.float32) x3 = tl.load(k_ptr + k_base + t3_c[:, None] * sk_t64 + d_offs[None, :] * sk_d64, mask=m3[:, None], other=0.0).to(tl.float32) u = a0[:, None] * x0 + a1[:, None] * x1 + a2[:, None] * x2 + a3[:, None] * x3 y = u * tl.sigmoid(u) sok_b64 = tl.cast(sok_b, tl.int64) sok_t64 = tl.cast(sok_t, tl.int64) sok_h64 = tl.cast(sok_h, tl.int64) sok_d64 = tl.cast(sok_d, tl.int64) tl.store( k_out_ptr + pid_b * sok_b64 + t_offs[:, None] * sok_t64 + pid_h * sok_h64 + d_offs[None, :] * sok_d64, y.to(k_out_ptr.dtype.element_ty), mask=m_t[:, None], ) # ---------------- Branch 2: V ---------------- s0 = tl.where(m0, tl.sum(kn0 * p20[None, :], axis=1) * scale, neg_inf) s1 = tl.where(m1, tl.sum(kn1 * p21[None, :], axis=1) * scale, neg_inf) s2 = tl.where(m2, tl.sum(kn2 * p22[None, :], axis=1) * scale, neg_inf) s3 = tl.where(m3, tl.sum(kn3 * p23[None, :], axis=1) * scale, neg_inf) m_max = tl.maximum(tl.maximum(s0, s1), tl.maximum(s2, s3)) e0 = tl.exp(s0 - m_max) e1 = tl.exp(s1 - m_max) e2 = tl.exp(s2 - m_max) e3 = tl.exp(s3 - m_max) inv_s = 1.0 / (e0 + e1 + e2 + e3) a0 = e0 * inv_s a1 = e1 * inv_s a2 = e2 * inv_s a3 = e3 * inv_s tl.store(attn_ptr + a_base + 2 * sa_x64 + 0 * sa_w64, a0, mask=m_t) tl.store(attn_ptr + a_base + 2 * sa_x64 + 1 * sa_w64, a1, mask=m_t) tl.store(attn_ptr + a_base + 2 * sa_x64 + 2 * sa_w64, a2, mask=m_t) tl.store(attn_ptr + a_base + 2 * sa_x64 + 3 * sa_w64, a3, mask=m_t) sv_b64 = tl.cast(sv_b, tl.int64) sv_t64 = tl.cast(sv_t, tl.int64) sv_h64 = tl.cast(sv_h, tl.int64) sv_d64 = tl.cast(sv_d, tl.int64) v_base = pid_b * sv_b64 + pid_h * sv_h64 x0 = tl.load(v_ptr + v_base + t0_c[:, None] * sv_t64 + d_offs[None, :] * sv_d64, mask=m0[:, None], other=0.0).to(tl.float32) x1 = tl.load(v_ptr + v_base + t1_c[:, None] * sv_t64 + d_offs[None, :] * sv_d64, mask=m1[:, None], other=0.0).to(tl.float32) x2 = tl.load(v_ptr + v_base + t2_c[:, None] * sv_t64 + d_offs[None, :] * sv_d64, mask=m2[:, None], other=0.0).to(tl.float32) x3 = tl.load(v_ptr + v_base + t3_c[:, None] * sv_t64 + d_offs[None, :] * sv_d64, mask=m3[:, None], other=0.0).to(tl.float32) u = a0[:, None] * x0 + a1[:, None] * x1 + a2[:, None] * x2 + a3[:, None] * x3 y = u * tl.sigmoid(u) sov_b64 = tl.cast(sov_b, tl.int64) sov_t64 = tl.cast(sov_t, tl.int64) sov_h64 = tl.cast(sov_h, tl.int64) sov_d64 = tl.cast(sov_d, tl.int64) tl.store( v_out_ptr + pid_b * sov_b64 + t_offs[:, None] * sov_t64 + pid_h * sov_h64 + d_offs[None, :] * sov_d64, y.to(v_out_ptr.dtype.element_ty), mask=m_t[:, None], ) @triton.jit def _bwd_branch_step( # Computes one branch's contribution to dX[i], dk_n[i], and atomic_add(d_p_rot[x, w, h, :]) x_ptr, g_ptr, attn_ptr, prot_ptr, dprot_ptr, kn_i, dk_n_acc, sx_b, sx_t, sx_h, sx_d, sg_b, sg_t, sg_h, sg_d, sa_b, sa_x, sa_w, sa_t, sa_h, sp_x, sp_w, sp_h, sp_d, sdp_x, sdp_w, sdp_h, sdp_d, pid_b, pid_h, i_offs, d_offs, T, scale, branch_x: tl.constexpr, BLOCK_T: tl.constexpr, HEAD_DIM: tl.constexpr, ): dx_acc = tl.zeros((BLOCK_T, HEAD_DIM), dtype=tl.float32) x_base = pid_b * sx_b + pid_h * sx_h g_base = pid_b * sg_b + pid_h * sg_h a_xh_base = pid_b * sa_b + branch_x * sa_x + pid_h * sa_h p_xh_base = branch_x * sp_x + pid_h * sp_h + d_offs * sp_d dp_xh_base = branch_x * sdp_x + pid_h * sdp_h + d_offs * sdp_d for w_shift in tl.static_range(4): t_offs = i_offs + w_shift m_t = t_offs < T t_c = tl.where(m_t, t_offs, 0) # Load softmax weights a[b, x, 0..3, t, h] (FP32) a_t_base = a_xh_base + t_c * sa_t a0 = tl.load(attn_ptr + a_t_base + 0 * sa_w, mask=m_t, other=0.0).to(tl.float32) a1 = tl.load(attn_ptr + a_t_base + 1 * sa_w, mask=m_t, other=0.0).to(tl.float32) a2 = tl.load(attn_ptr + a_t_base + 2 * sa_w, mask=m_t, other=0.0).to(tl.float32) a3 = tl.load(attn_ptr + a_t_base + 3 * sa_w, mask=m_t, other=0.0).to(tl.float32) # Window indices t - w' for w' in {0, 1, 2, 3} t0 = t_offs t1 = t_offs - 1 t2 = t_offs - 2 t3 = t_offs - 3 m0 = m_t & (t0 >= 0) m1 = m_t & (t1 >= 0) m2 = m_t & (t2 >= 0) m3 = m_t & (t3 >= 0) t0_c = tl.where(m0, t0, 0) t1_c = tl.where(m1, t1, 0) t2_c = tl.where(m2, t2, 0) t3_c = tl.where(m3, t3, 0) # Load X[b, t - w', h, :] (L1-resident across w_shift) x0 = tl.load(x_ptr + x_base + t0_c[:, None] * sx_t + d_offs[None, :] * sx_d, mask=m0[:, None], other=0.0).to(tl.float32) x1 = tl.load(x_ptr + x_base + t1_c[:, None] * sx_t + d_offs[None, :] * sx_d, mask=m1[:, None], other=0.0).to(tl.float32) x2 = tl.load(x_ptr + x_base + t2_c[:, None] * sx_t + d_offs[None, :] * sx_d, mask=m2[:, None], other=0.0).to(tl.float32) x3 = tl.load(x_ptr + x_base + t3_c[:, None] * sx_t + d_offs[None, :] * sx_d, mask=m3[:, None], other=0.0).to(tl.float32) # Recompute pre-SiLU mix u[t] = sum_{w'=0..3} a[w', t] * X[t - w'] u = a0[:, None] * x0 + a1[:, None] * x1 + a2[:, None] * x2 + a3[:, None] * x3 # Upstream gradient g[t] and SiLU backward: du = g * sig(u) * (1 + u * (1 - sig(u))) g = tl.load(g_ptr + g_base + t_c[:, None] * sg_t + d_offs[None, :] * sg_d, mask=m_t[:, None], other=0.0).to(tl.float32) sig = tl.sigmoid(u) du = g * sig * (1.0 + u * (1.0 - sig)) # Select a_wshift and da_wshift for current w_shift da0 = tl.sum(du * x0, axis=1) da1 = tl.sum(du * x1, axis=1) da2 = tl.sum(du * x2, axis=1) da3 = tl.sum(du * x3, axis=1) d_dot = a0 * da0 + a1 * da1 + a2 * da2 + a3 * da3 if w_shift == 0: a_w = a0 da_w = da0 elif w_shift == 1: a_w = a1 da_w = da1 elif w_shift == 2: a_w = a2 da_w = da2 else: a_w = a3 da_w = da3 # Accumulate dX[b, i, h, :] += a[x, w_shift, i + w_shift] * du[i + w_shift] dx_acc += a_w[:, None] * du # Softmax backward: ds[x, w_shift, t] = a_w * (da_w - sum_{w'} a_{w'} da_{w'}) ds_w = tl.where(m_t, a_w * (da_w - d_dot), 0.0) ds_scaled = ds_w * scale # Accumulate dk_n[b, i, h, :] += (scale * ds[x, w_shift, i + w_shift]) * p_rot[x, w_shift, h, :] p_w = tl.load(prot_ptr + p_xh_base + w_shift * sp_w).to(tl.float32) dk_n_acc += ds_scaled[:, None] * p_w[None, :] # Accumulate d_p_rot[x, w_shift, h, :] += sum_{i} (scale * ds[x, w_shift, i + w_shift]) * k_n[b, i, h, :] dp_w = tl.sum(ds_scaled[:, None] * kn_i, axis=0) tl.atomic_add(dprot_ptr + dp_xh_base + w_shift * sdp_w, dp_w) return dx_acc, dk_n_acc @triton.jit def _triton_swgdn2_local_swa_bwd( # Upstream gradients: [B, T, H, D] gq_ptr, gk_ptr, gv_ptr, # Saved forward inputs: [B, T, H, D], [3, 4, H, D], [B, 3, 4, T, H] q_ptr, k_ptr, v_ptr, kn_ptr, prot_ptr, attn_ptr, # Output gradients: [B, T, H, D] and FP32 [3, 4, H, D] dq_ptr, dk_ptr, dv_ptr, dkn_ptr, dprot_ptr, # Strides for upstream gradients sgq_b, sgq_t, sgq_h, sgq_d, sgk_b, sgk_t, sgk_h, sgk_d, sgv_b, sgv_t, sgv_h, sgv_d, # Strides for q, k, v, k_n sq_b, sq_t, sq_h, sq_d, sk_b, sk_t, sk_h, sk_d, sv_b, sv_t, sv_h, sv_d, skn_b, skn_t, skn_h, skn_d, # Strides for p_rot & d_p_rot: [3, 4, H, D] sp_x, sp_w, sp_h, sp_d, sdp_x, sdp_w, sdp_h, sdp_d, # Strides for attn: [B, 3, 4, T, H] sa_b, sa_x, sa_w, sa_t, sa_h, # Strides for output gradients dq, dk, dv, dkn: [B, T, H, D] sdq_b, sdq_t, sdq_h, sdq_d, sdk_b, sdk_t, sdk_h, sdk_d, sdv_b, sdv_t, sdv_h, sdv_d, sdkn_b, sdkn_t, sdkn_h, sdkn_d, # Dimensions & scale T, scale, BLOCK_T: tl.constexpr, HEAD_DIM: tl.constexpr, ): pid_b = tl.program_id(0).to(tl.int64) pid_h = tl.program_id(1).to(tl.int64) pid_tile = tl.program_id(2).to(tl.int64) i_start = pid_tile * BLOCK_T i_offs = i_start + tl.arange(0, BLOCK_T).to(tl.int64) # [BLOCK_T] d_offs = tl.arange(0, HEAD_DIM).to(tl.int64) # [HEAD_DIM] m_i = i_offs < T i_c = tl.where(m_i, i_offs, 0) # Load k_n[b, i, h, :] ONCE for d_p_rot accumulation across all 3 branches skn_b64 = tl.cast(skn_b, tl.int64) skn_t64 = tl.cast(skn_t, tl.int64) skn_h64 = tl.cast(skn_h, tl.int64) skn_d64 = tl.cast(skn_d, tl.int64) kn_i = tl.load( kn_ptr + pid_b * skn_b64 + i_c[:, None] * skn_t64 + pid_h * skn_h64 + d_offs[None, :] * skn_d64, mask=m_i[:, None], other=0.0, ).to(tl.float32) sa_b64 = tl.cast(sa_b, tl.int64) sa_x64 = tl.cast(sa_x, tl.int64) sa_w64 = tl.cast(sa_w, tl.int64) sa_t64 = tl.cast(sa_t, tl.int64) sa_h64 = tl.cast(sa_h, tl.int64) sp_x64 = tl.cast(sp_x, tl.int64) sp_w64 = tl.cast(sp_w, tl.int64) sp_h64 = tl.cast(sp_h, tl.int64) sp_d64 = tl.cast(sp_d, tl.int64) sdp_x64 = tl.cast(sdp_x, tl.int64) sdp_w64 = tl.cast(sdp_w, tl.int64) sdp_h64 = tl.cast(sdp_h, tl.int64) sdp_d64 = tl.cast(sdp_d, tl.int64) dk_n_acc = tl.zeros((BLOCK_T, HEAD_DIM), dtype=tl.float32) # Branch 0: Q dq_acc, dk_n_acc = _bwd_branch_step( q_ptr, gq_ptr, attn_ptr, prot_ptr, dprot_ptr, kn_i, dk_n_acc, tl.cast(sq_b, tl.int64), tl.cast(sq_t, tl.int64), tl.cast(sq_h, tl.int64), tl.cast(sq_d, tl.int64), tl.cast(sgq_b, tl.int64), tl.cast(sgq_t, tl.int64), tl.cast(sgq_h, tl.int64), tl.cast(sgq_d, tl.int64), sa_b64, sa_x64, sa_w64, sa_t64, sa_h64, sp_x64, sp_w64, sp_h64, sp_d64, sdp_x64, sdp_w64, sdp_h64, sdp_d64, pid_b, pid_h, i_offs, d_offs, T, scale, 0, BLOCK_T, HEAD_DIM, ) tl.store( dq_ptr + pid_b * tl.cast(sdq_b, tl.int64) + i_offs[:, None] * tl.cast(sdq_t, tl.int64) + pid_h * tl.cast(sdq_h, tl.int64) + d_offs[None, :] * tl.cast(sdq_d, tl.int64), dq_acc.to(dq_ptr.dtype.element_ty), mask=m_i[:, None], ) # Branch 1: K dk_acc, dk_n_acc = _bwd_branch_step( k_ptr, gk_ptr, attn_ptr, prot_ptr, dprot_ptr, kn_i, dk_n_acc, tl.cast(sk_b, tl.int64), tl.cast(sk_t, tl.int64), tl.cast(sk_h, tl.int64), tl.cast(sk_d, tl.int64), tl.cast(sgk_b, tl.int64), tl.cast(sgk_t, tl.int64), tl.cast(sgk_h, tl.int64), tl.cast(sgk_d, tl.int64), sa_b64, sa_x64, sa_w64, sa_t64, sa_h64, sp_x64, sp_w64, sp_h64, sp_d64, sdp_x64, sdp_w64, sdp_h64, sdp_d64, pid_b, pid_h, i_offs, d_offs, T, scale, 1, BLOCK_T, HEAD_DIM, ) tl.store( dk_ptr + pid_b * tl.cast(sdk_b, tl.int64) + i_offs[:, None] * tl.cast(sdk_t, tl.int64) + pid_h * tl.cast(sdk_h, tl.int64) + d_offs[None, :] * tl.cast(sdk_d, tl.int64), dk_acc.to(dk_ptr.dtype.element_ty), mask=m_i[:, None], ) # Branch 2: V dv_acc, dk_n_acc = _bwd_branch_step( v_ptr, gv_ptr, attn_ptr, prot_ptr, dprot_ptr, kn_i, dk_n_acc, tl.cast(sv_b, tl.int64), tl.cast(sv_t, tl.int64), tl.cast(sv_h, tl.int64), tl.cast(sv_d, tl.int64), tl.cast(sgv_b, tl.int64), tl.cast(sgv_t, tl.int64), tl.cast(sgv_h, tl.int64), tl.cast(sgv_d, tl.int64), sa_b64, sa_x64, sa_w64, sa_t64, sa_h64, sp_x64, sp_w64, sp_h64, sp_d64, sdp_x64, sdp_w64, sdp_h64, sdp_d64, pid_b, pid_h, i_offs, d_offs, T, scale, 2, BLOCK_T, HEAD_DIM, ) tl.store( dv_ptr + pid_b * tl.cast(sdv_b, tl.int64) + i_offs[:, None] * tl.cast(sdv_t, tl.int64) + pid_h * tl.cast(sdv_h, tl.int64) + d_offs[None, :] * tl.cast(sdv_d, tl.int64), dv_acc.to(dv_ptr.dtype.element_ty), mask=m_i[:, None], ) # Store accumulated dk_n[b, i, h, :] tl.store( dkn_ptr + pid_b * tl.cast(sdkn_b, tl.int64) + i_offs[:, None] * tl.cast(sdkn_t, tl.int64) + pid_h * tl.cast(sdkn_h, tl.int64) + d_offs[None, :] * tl.cast(sdkn_d, tl.int64), dk_n_acc.to(dkn_ptr.dtype.element_ty), mask=m_i[:, None], ) # ============================================================================= # 2. Pure-PyTorch Fallback & Triton Launch Helpers # ============================================================================= if True: def _validate_inputs( q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, k_n: torch.Tensor, p_rot: torch.Tensor, ) -> Tuple[int, int, int, int]: if q.ndim != 4 or k.ndim != 4 or v.ndim != 4 or k_n.ndim != 4: raise ValueError( f"q, k, v, k_n must be 4D [B, T, H, D]; got {q.shape}, {k.shape}, {v.shape}, {k_n.shape}" ) if q.shape != k.shape or q.shape != v.shape or q.shape != k_n.shape: raise ValueError( f"q, k, v, k_n must have identical shapes; got {q.shape}, {k.shape}, {v.shape}, {k_n.shape}" ) B, T, H, D = q.shape if p_rot.shape != (3, WINDOW_SIZE, H, D): raise ValueError( f"p_rot must have shape (3, {WINDOW_SIZE}, {H}, {D}); got {tuple(p_rot.shape)}" ) return B, T, H, D def _swgdn2_can_use_triton( q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, k_n: torch.Tensor, p_rot: torch.Tensor, ) -> bool: if not (_HAS_TRITON and q.is_cuda and k.is_cuda and v.is_cuda and k_n.is_cuda and p_rot.is_cuda): return False D = q.shape[-1] return _is_power_of_two(D) and D <= 256 def _launch_triton_fwd( q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, k_n: torch.Tensor, p_rot: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: B, T, H, D = _validate_inputs(q, k, v, k_n, p_rot) out_dtype = q.dtype q_mix = torch.empty((B, T, H, D), device=q.device, dtype=out_dtype) k_mix = torch.empty((B, T, H, D), device=q.device, dtype=out_dtype) v_mix = torch.empty((B, T, H, D), device=q.device, dtype=out_dtype) attn = torch.empty((B, 3, WINDOW_SIZE, T, H), device=q.device, dtype=torch.float32) if B == 0 or T == 0 or H == 0: return q_mix, k_mix, v_mix, attn scale = 1.0 / math.sqrt(float(D)) block_t = DEFAULT_BLOCK_T grid = (B, H, triton.cdiv(T, block_t)) _triton_swgdn2_local_swa_fwd[grid]( q, k, v, k_n, p_rot, q_mix, k_mix, v_mix, attn, q.stride(0), q.stride(1), q.stride(2), q.stride(3), k.stride(0), k.stride(1), k.stride(2), k.stride(3), v.stride(0), v.stride(1), v.stride(2), v.stride(3), k_n.stride(0), k_n.stride(1), k_n.stride(2), k_n.stride(3), p_rot.stride(0), p_rot.stride(1), p_rot.stride(2), p_rot.stride(3), q_mix.stride(0), q_mix.stride(1), q_mix.stride(2), q_mix.stride(3), k_mix.stride(0), k_mix.stride(1), k_mix.stride(2), k_mix.stride(3), v_mix.stride(0), v_mix.stride(1), v_mix.stride(2), v_mix.stride(3), attn.stride(0), attn.stride(1), attn.stride(2), attn.stride(3), attn.stride(4), T, scale, BLOCK_T=block_t, HEAD_DIM=D, num_warps=4, ) return q_mix, k_mix, v_mix, attn def _launch_triton_bwd( d_q_mix: torch.Tensor, d_k_mix: torch.Tensor, d_v_mix: torch.Tensor, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, k_n: torch.Tensor, p_rot: torch.Tensor, attn: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: B, T, H, D = _validate_inputs(q, k, v, k_n, p_rot) d_q = torch.empty((B, T, H, D), device=q.device, dtype=q.dtype) d_k = torch.empty((B, T, H, D), device=k.device, dtype=k.dtype) d_v = torch.empty((B, T, H, D), device=v.device, dtype=v.dtype) d_k_n = torch.empty((B, T, H, D), device=k_n.device, dtype=k_n.dtype) d_p_rot_fp32 = torch.zeros((3, WINDOW_SIZE, H, D), device=p_rot.device, dtype=torch.float32) if B == 0 or T == 0 or H == 0: return d_q, d_k, d_v, d_k_n, d_p_rot_fp32.to(p_rot.dtype) scale = 1.0 / math.sqrt(float(D)) block_t = DEFAULT_BLOCK_T grid = (B, H, triton.cdiv(T, block_t)) _triton_swgdn2_local_swa_bwd[grid]( d_q_mix, d_k_mix, d_v_mix, q, k, v, k_n, p_rot, attn, d_q, d_k, d_v, d_k_n, d_p_rot_fp32, d_q_mix.stride(0), d_q_mix.stride(1), d_q_mix.stride(2), d_q_mix.stride(3), d_k_mix.stride(0), d_k_mix.stride(1), d_k_mix.stride(2), d_k_mix.stride(3), d_v_mix.stride(0), d_v_mix.stride(1), d_v_mix.stride(2), d_v_mix.stride(3), q.stride(0), q.stride(1), q.stride(2), q.stride(3), k.stride(0), k.stride(1), k.stride(2), k.stride(3), v.stride(0), v.stride(1), v.stride(2), v.stride(3), k_n.stride(0), k_n.stride(1), k_n.stride(2), k_n.stride(3), p_rot.stride(0), p_rot.stride(1), p_rot.stride(2), p_rot.stride(3), d_p_rot_fp32.stride(0), d_p_rot_fp32.stride(1), d_p_rot_fp32.stride(2), d_p_rot_fp32.stride(3), attn.stride(0), attn.stride(1), attn.stride(2), attn.stride(3), attn.stride(4), d_q.stride(0), d_q.stride(1), d_q.stride(2), d_q.stride(3), d_k.stride(0), d_k.stride(1), d_k.stride(2), d_k.stride(3), d_v.stride(0), d_v.stride(1), d_v.stride(2), d_v.stride(3), d_k_n.stride(0), d_k_n.stride(1), d_k_n.stride(2), d_k_n.stride(3), T, scale, BLOCK_T=block_t, HEAD_DIM=D, num_warps=4, ) return d_q, d_k, d_v, d_k_n, d_p_rot_fp32.to(p_rot.dtype) def _pytorch_swgdn2_local_swa_fwd( q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, k_n: torch.Tensor, p_rot: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: """Exact PyTorch FP32-accumulated fallback matching SWGDN2LocalSWA Eq. 7-8.""" B, T, H, D = _validate_inputs(q, k, v, k_n, p_rot) out_dtype = q.dtype scale = 1.0 / math.sqrt(float(D)) raw_scores = torch.einsum("bthd,xwhd->bxwth", k_n.float(), p_rot.float()) * scale logits_w = [raw_scores[:, :, 0]] for w in range(1, WINDOW_SIZE): if T > w: pad = torch.full( (B, 3, w, H), NEG_INF_SCORE, device=q.device, dtype=torch.float32 ) logits_w.append(torch.cat([pad, raw_scores[:, :, w, : T - w]], dim=2)) else: logits_w.append( torch.full((B, 3, T, H), NEG_INF_SCORE, device=q.device, dtype=torch.float32) ) attn = F.softmax(torch.stack(logits_w, dim=2), dim=2) # [B, 3, 4, T, H] FP32 def _mix(x_b: torch.Tensor, a_b: torch.Tensor) -> torch.Tensor: xf = x_b.float() u = a_b[:, 0].unsqueeze(-1) * xf for w in range(1, WINDOW_SIZE): if T > w: x_shift = F.pad(xf[:, : T - w], (0, 0, 0, 0, w, 0)) u = u + a_b[:, w].unsqueeze(-1) * x_shift return F.silu(u).to(out_dtype) q_mix = _mix(q, attn[:, 0]) k_mix = _mix(k, attn[:, 1]) v_mix = _mix(v, attn[:, 2]) return q_mix, k_mix, v_mix, attn def _pytorch_swgdn2_local_swa_bwd( d_q_mix: torch.Tensor, d_k_mix: torch.Tensor, d_v_mix: torch.Tensor, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, k_n: torch.Tensor, p_rot: torch.Tensor, attn: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: """Exact analytical PyTorch backward fallback (matches Triton backward 1-to-1).""" B, T, H, D = _validate_inputs(q, k, v, k_n, p_rot) scale = 1.0 / math.sqrt(float(D)) kn_f = k_n.float() prot_f = p_rot.float() attn_f = attn.float() xs = (q.float(), k.float(), v.float()) gs = (d_q_mix.float(), d_k_mix.float(), d_v_mix.float()) dxs = [] d_k_n_f = torch.zeros((B, T, H, D), device=q.device, dtype=torch.float32) d_p_rot_f = torch.zeros((3, WINDOW_SIZE, H, D), device=p_rot.device, dtype=torch.float32) for x_idx in range(3): xf = xs[x_idx] gf = gs[x_idx] a_b = attn_f[:, x_idx] # [B, 4, T, H] # Shifted views x_shift[w][b, t] = xf[b, t - w] (0 for t < w) x_shifts = [xf] for w in range(1, WINDOW_SIZE): if T > w: x_shifts.append(F.pad(xf[:, : T - w], (0, 0, 0, 0, w, 0))) else: x_shifts.append(torch.zeros_like(xf)) u = sum(a_b[:, w].unsqueeze(-1) * x_shifts[w] for w in range(WINDOW_SIZE)) sig = torch.sigmoid(u) du = gf * sig * (1.0 + u * (1.0 - sig)) # [B, T, H, D] # da[w] = sum_d du[t] * x[t - w] da = torch.stack([(du * x_shifts[w]).sum(dim=-1) for w in range(WINDOW_SIZE)], dim=1) d_dot = (a_b * da).sum(dim=1, keepdim=True) ds = a_b * (da - d_dot) # [B, 4, T, H] # dX[i] = sum_{w: i + w < T} a[w, i + w] * du[i + w] dx_f = a_b[:, 0].unsqueeze(-1) * du for w in range(1, WINDOW_SIZE): if T > w: dx_f[:, : T - w] = dx_f[:, : T - w] + a_b[:, w, w:].unsqueeze(-1) * du[:, w:] dxs.append(dx_f) # dk_n[i] += scale * sum_{w: i + w < T} ds[w, i + w] * p_rot[x, w] # dp_rot[x, w] += scale * sum_{b, i: i + w < T} ds[w, i + w] * k_n[i] for w in range(WINDOW_SIZE): if T > w: ds_w = ds[:, w, w:] * scale # [B, T - w, H] d_k_n_f[:, : T - w] = d_k_n_f[:, : T - w] + ( ds_w.unsqueeze(-1) * prot_f[x_idx, w].view(1, 1, H, D) ) d_p_rot_f[x_idx, w] = torch.einsum("bth,bthd->hd", ds_w, kn_f[:, : T - w]) return ( dxs[0].to(q.dtype), dxs[1].to(k.dtype), dxs[2].to(v.dtype), d_k_n_f.to(k_n.dtype), d_p_rot_f.to(p_rot.dtype), ) # ========================================================================= # 3. torch.library.custom_op (PyTorch 2.4+ zero graph breaks) + Fallback # ========================================================================= _HAS_CUSTOM_OP = hasattr(torch, "library") and hasattr(torch.library, "custom_op") if _HAS_CUSTOM_OP: @torch.library.custom_op("swgdn2::local_swa_fwd", mutates_args=()) def _swgdn2_local_swa_fwd_op( q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, k_n: torch.Tensor, p_rot: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: if _swgdn2_can_use_triton(q, k, v, k_n, p_rot): return _launch_triton_fwd(q, k, v, k_n, p_rot) return _pytorch_swgdn2_local_swa_fwd(q, k, v, k_n, p_rot) @_swgdn2_local_swa_fwd_op.register_fake def _swgdn2_local_swa_fwd_fake( q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, k_n: torch.Tensor, p_rot: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: B, T, H, D = _validate_inputs(q, k, v, k_n, p_rot) q_mix = q.new_empty((B, T, H, D), dtype=q.dtype) k_mix = k.new_empty((B, T, H, D), dtype=q.dtype) v_mix = v.new_empty((B, T, H, D), dtype=q.dtype) attn = q.new_empty((B, 3, WINDOW_SIZE, T, H), dtype=torch.float32) return q_mix, k_mix, v_mix, attn @torch.library.custom_op("swgdn2::local_swa_bwd", mutates_args=()) def _swgdn2_local_swa_bwd_op( d_q_mix: torch.Tensor, d_k_mix: torch.Tensor, d_v_mix: torch.Tensor, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, k_n: torch.Tensor, p_rot: torch.Tensor, attn: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: if _swgdn2_can_use_triton(q, k, v, k_n, p_rot): return _launch_triton_bwd( d_q_mix, d_k_mix, d_v_mix, q, k, v, k_n, p_rot, attn ) return _pytorch_swgdn2_local_swa_bwd( d_q_mix, d_k_mix, d_v_mix, q, k, v, k_n, p_rot, attn ) @_swgdn2_local_swa_bwd_op.register_fake def _swgdn2_local_swa_bwd_fake( d_q_mix: torch.Tensor, d_k_mix: torch.Tensor, d_v_mix: torch.Tensor, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, k_n: torch.Tensor, p_rot: torch.Tensor, attn: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: B, T, H, D = _validate_inputs(q, k, v, k_n, p_rot) return ( q.new_empty((B, T, H, D), dtype=q.dtype), k.new_empty((B, T, H, D), dtype=k.dtype), v.new_empty((B, T, H, D), dtype=v.dtype), k_n.new_empty((B, T, H, D), dtype=k_n.dtype), p_rot.new_empty((3, WINDOW_SIZE, H, D), dtype=p_rot.dtype), ) def _setup_context(ctx, inputs, output): q, k, v, k_n, p_rot = inputs _q_mix, _k_mix, _v_mix, attn = output ctx.save_for_backward(q, k, v, k_n, p_rot, attn) def _backward_custom_op(ctx, d_q_mix, d_k_mix, d_v_mix, _d_attn): q, k, v, k_n, p_rot, attn = ctx.saved_tensors if d_q_mix is None: d_q_mix = torch.zeros_like(q) if d_k_mix is None: d_k_mix = torch.zeros_like(k) if d_v_mix is None: d_v_mix = torch.zeros_like(v) return _swgdn2_local_swa_bwd_op( d_q_mix, d_k_mix, d_v_mix, q, k, v, k_n, p_rot, attn ) _swgdn2_local_swa_fwd_op.register_autograd( _backward_custom_op, setup_context=_setup_context ) class _FusedSWGDN2LocalSWAFunction(torch.autograd.Function): """Standard autograd.Function fallback when torch.library.custom_op is unavailable.""" @staticmethod def forward(ctx, q, k, v, k_n, p_rot): if _swgdn2_can_use_triton(q, k, v, k_n, p_rot): q_mix, k_mix, v_mix, attn = _launch_triton_fwd(q, k, v, k_n, p_rot) else: q_mix, k_mix, v_mix, attn = _pytorch_swgdn2_local_swa_fwd(q, k, v, k_n, p_rot) ctx.save_for_backward(q, k, v, k_n, p_rot, attn) return q_mix, k_mix, v_mix @staticmethod def backward(ctx, d_q_mix, d_k_mix, d_v_mix): q, k, v, k_n, p_rot, attn = ctx.saved_tensors if d_q_mix is None: d_q_mix = torch.zeros_like(q) if d_k_mix is None: d_k_mix = torch.zeros_like(k) if d_v_mix is None: d_v_mix = torch.zeros_like(v) if _swgdn2_can_use_triton(q, k, v, k_n, p_rot): return _launch_triton_bwd( d_q_mix, d_k_mix, d_v_mix, q, k, v, k_n, p_rot, attn ) return _pytorch_swgdn2_local_swa_bwd( d_q_mix, d_k_mix, d_v_mix, q, k, v, k_n, p_rot, attn ) def fused_swgdn2_local_swa( q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, k_n: torch.Tensor, p_rot: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """1-pass fused SWGDN2LocalSWA (arXiv:2611.33257 Eq. 7-8). Args: q: `[B, T, H, D]` projected queries (may be non-contiguous view of `g_qkv`) k: `[B, T, H, D]` projected keys v: `[B, T, H, D]` projected values k_n: `[B, T, H, D]` RMSNorm-normalized keys `rms_norm(k, k_norm)` p_rot: `[3, 4, H, D]` pre-rotated RMSNorm pseudo-queries Returns: `(q_mix, k_mix, v_mix)` each `[B, T, H, D]` in `q.dtype`. """ if _HAS_CUSTOM_OP: q_mix, k_mix, v_mix, _ = _swgdn2_local_swa_fwd_op(q, k, v, k_n, p_rot) return q_mix, k_mix, v_mix return _FusedSWGDN2LocalSWAFunction.apply(q, k, v, k_n, p_rot) # ============================================================================= # --- Kernel Suite 5: Fused MoD Gate Score & Scaled Scatter-Add --- if _HAS_TRITON: @triton.jit def _triton_mod_gate_score_fwd( h_ptr, w_ptr, b_ptr, c_gate_ptr, out_ptr, sig_ptr, N, D, stride_hn, stride_hd, HAS_BIAS: tl.constexpr, HAS_CGATE: tl.constexpr, SAVE_SIG: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_D: tl.constexpr, ): """Fused linear(D -> 1) + sigmoid + optional c_gate multiply in 1 pass. Grid: (cdiv(N, BLOCK_N),) For locked-in D=1024, BLOCK_D=1024 -> inner D-loop runs exactly 1 iteration. """ pid_n = tl.program_id(0).to(tl.int64) offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N).to(tl.int64) mask_n = offs_n < N acc = tl.zeros((BLOCK_N,), dtype=tl.float32) for d_start in range(0, D, BLOCK_D): offs_d = tl.arange(0, BLOCK_D).to(tl.int64) + d_start mask_d = offs_d < D w_val = tl.load(w_ptr + offs_d, mask=mask_d, other=0.0).to(tl.float32) h_ptrs = h_ptr + offs_n[:, None] * stride_hn + offs_d[None, :] * stride_hd h_val = tl.load( h_ptrs, mask=mask_n[:, None] & mask_d[None, :], other=0.0 ).to(tl.float32) acc += tl.sum(h_val * w_val[None, :], axis=1) if HAS_BIAS: b_val = tl.load(b_ptr).to(tl.float32) acc = acc + b_val sig = tl.sigmoid(acc) if SAVE_SIG: tl.store(sig_ptr + offs_n, sig, mask=mask_n) if HAS_CGATE: cg = tl.load(c_gate_ptr + offs_n, mask=mask_n, other=1.0).to(tl.float32) eff = sig * cg else: eff = sig tl.store(out_ptr + offs_n, eff.to(out_ptr.dtype.element_ty), mask=mask_n) @triton.jit def _triton_mod_gate_score_bwd_persistent( d_eff_ptr, h_ptr, w_ptr, sig_ptr, c_gate_ptr, d_h_ptr, d_w_fp32_ptr, d_b_fp32_ptr, N, D, num_tiles, stride_hn, stride_hd, stride_dhn, stride_dhd, HAS_CGATE: tl.constexpr, NEED_DH: tl.constexpr, NEED_DW: tl.constexpr, NEED_DB: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_D: tl.constexpr, ): """Persistent-grid backward pass for `fused_mod_gate_score`. Computes `d_h_ffn [N, D]`, `d_w [1, D]` (accumulated in FP32), and `d_b [1]` (accumulated in FP32) in ONE Triton kernel launch. Treats `c_gate` as a detached constant (matching `forward_backbone`). Grid: (num_progs, cdiv(D, BLOCK_D)) For locked-in D=1024, BLOCK_D=1024 -> Grid is (num_progs, 1). """ pid_p = tl.program_id(0).to(tl.int64) num_progs = tl.num_programs(0).to(tl.int64) pid_d = tl.program_id(1).to(tl.int64) offs_d = pid_d * BLOCK_D + tl.arange(0, BLOCK_D).to(tl.int64) mask_d = offs_d < D # Load w once into registers for the entire persistent tile loop if NEED_DH: w_reg = tl.load(w_ptr + offs_d, mask=mask_d, other=0.0).to(tl.float32) else: w_reg = tl.zeros((BLOCK_D,), dtype=tl.float32) dw_acc = tl.zeros((BLOCK_D,), dtype=tl.float32) db_acc = tl.zeros((1,), dtype=tl.float32) tile_idx = pid_p while tile_idx < num_tiles: offs_n = tile_idx * BLOCK_N + tl.arange(0, BLOCK_N).to(tl.int64) mask_n = offs_n < N d_eff = tl.load(d_eff_ptr + offs_n, mask=mask_n, other=0.0).to(tl.float32) sig = tl.load(sig_ptr + offs_n, mask=mask_n, other=0.0).to(tl.float32) if HAS_CGATE: cg = tl.load(c_gate_ptr + offs_n, mask=mask_n, other=0.0).to(tl.float32) delta = d_eff * cg * sig * (1.0 - sig) else: delta = d_eff * sig * (1.0 - sig) delta = tl.where(mask_n, delta, 0.0) if NEED_DB: db_acc += tl.sum(delta, axis=0) if NEED_DH: dh_tile = delta[:, None] * w_reg[None, :] dh_ptrs = ( d_h_ptr + offs_n[:, None] * stride_dhn + offs_d[None, :] * stride_dhd ) tl.store( dh_ptrs, dh_tile.to(d_h_ptr.dtype.element_ty), mask=mask_n[:, None] & mask_d[None, :], ) if NEED_DW: h_ptrs = ( h_ptr + offs_n[:, None] * stride_hn + offs_d[None, :] * stride_hd ) h_tile = tl.load( h_ptrs, mask=mask_n[:, None] & mask_d[None, :], other=0.0 ).to(tl.float32) dw_acc += tl.sum(delta[:, None] * h_tile, axis=0) tile_idx += num_progs if NEED_DW: tl.atomic_add(d_w_fp32_ptr + offs_d, dw_acc, mask=mask_d) if NEED_DB: if pid_d == 0: tl.atomic_add(d_b_fp32_ptr + tl.arange(0, 1), db_acc) @triton.jit def _triton_mod_scaled_scatter_add_fwd( out_ptr, top_idx_ptr, top_g_ptr, bridge_scale_ptr, m_sel_ptr, N, K, D, stride_on, stride_od, stride_mk, stride_md, BLOCK_D: tl.constexpr, ): """Fused scaled scatter-add without materializing `mem_delta [K, D]`. For each k in 0..K-1: out[top_idx[k], d] += top_g[k] * bridge_scale * m_sel[k, d] Safe without atomics because `top_idx` from `torch.topk` / `nonzero` contains strictly unique token indices. Grid: (K, cdiv(D, BLOCK_D)) For locked-in K=8192, D=1024, BLOCK_D=1024 -> Grid is (8192, 1). """ pid_k = tl.program_id(0).to(tl.int64) if pid_k >= K: return pid_d = tl.program_id(1).to(tl.int64) tok_idx = tl.load(top_idx_ptr + pid_k).to(tl.int64) if (tok_idx < 0) | (tok_idx >= N): return g_k = tl.load(top_g_ptr + pid_k).to(tl.float32) bs = tl.load(bridge_scale_ptr).to(tl.float32) scale = g_k * bs offs_d = pid_d * BLOCK_D + tl.arange(0, BLOCK_D).to(tl.int64) mask_d = offs_d < D m_ptrs = m_sel_ptr + pid_k * stride_mk + offs_d * stride_md m_val = tl.load(m_ptrs, mask=mask_d, other=0.0).to(tl.float32) o_ptrs = out_ptr + tok_idx * stride_on + offs_d * stride_od cur = tl.load(o_ptrs, mask=mask_d, other=0.0).to(tl.float32) updated = cur + scale * m_val tl.store(o_ptrs, updated.to(out_ptr.dtype.element_ty), mask=mask_d) @triton.jit def _triton_mod_scaled_scatter_add_bwd_persistent( d_out_ptr, top_idx_ptr, top_g_ptr, bridge_scale_ptr, m_sel_ptr, d_m_sel_ptr, d_top_g_ptr, d_bs_fp32_ptr, N, K, D, stride_gon, stride_god, stride_mk, stride_md, stride_dmk, stride_dmd, NEED_DM: tl.constexpr, NEED_DG: tl.constexpr, NEED_DBS: tl.constexpr, BLOCK_D: tl.constexpr, ): """Persistent-grid fused backward pass for `fused_mod_scaled_scatter_add`. Given `d_out [N, D]`: - d_m_sel[k, d] = (top_g[k] * bridge_scale) * d_out[top_idx[k], d] - d_top_g[k] = bridge_scale * sum_d(d_out[top_idx[k], d] * m_sel[k, d]) - d_bridge_scale = sum_k(top_g[k] * sum_d(d_out[top_idx[k], d] * m_sel[k, d])) (d_ffn_out = d_out is returned directly by the autograd wrapper.) Grid: (num_progs,) For locked-in D=1024, BLOCK_D=1024 -> inner D-loop runs exactly 1 iteration, and `d_bridge_scale` requires only `num_progs` (~128) FP32 atomic adds total. """ pid_p = tl.program_id(0).to(tl.int64) num_progs = tl.num_programs(0).to(tl.int64) bs = tl.load(bridge_scale_ptr).to(tl.float32) dbs_acc = tl.zeros((1,), dtype=tl.float32) k_idx = pid_p while k_idx < K: tok_idx = tl.load(top_idx_ptr + k_idx).to(tl.int64) valid_tok = (tok_idx >= 0) & (tok_idx < N) g_k = tl.load(top_g_ptr + k_idx).to(tl.float32) scale = g_k * bs dot_k = tl.zeros((1,), dtype=tl.float32) for d_start in range(0, D, BLOCK_D): offs_d = tl.arange(0, BLOCK_D).to(tl.int64) + d_start mask_d = (offs_d < D) & valid_tok go_ptrs = d_out_ptr + tok_idx * stride_gon + offs_d * stride_god go_val = tl.load(go_ptrs, mask=mask_d, other=0.0).to(tl.float32) if NEED_DM: dm_ptrs = d_m_sel_ptr + k_idx * stride_dmk + offs_d * stride_dmd dm_val = scale * go_val tl.store( dm_ptrs, dm_val.to(d_m_sel_ptr.dtype.element_ty), mask=offs_d < D, ) if NEED_DG | NEED_DBS: m_ptrs = m_sel_ptr + k_idx * stride_mk + offs_d * stride_md m_val = tl.load(m_ptrs, mask=mask_d, other=0.0).to(tl.float32) dot_k += tl.sum(go_val * m_val, axis=0) if NEED_DG: dg_val = bs * dot_k tl.store( d_top_g_ptr + k_idx + tl.arange(0, 1), dg_val.to(d_top_g_ptr.dtype.element_ty), ) if NEED_DBS: dbs_acc += g_k * dot_k k_idx += num_progs if NEED_DBS: tl.atomic_add(d_bs_fp32_ptr + tl.arange(0, 1), dbs_acc) # ============================================================================= # 2. LAUNCH HELPERS & PYTORCH FALLBACKS # ============================================================================= def _next_pow2_capped(val: int, cap: int = 1024) -> int: if val <= 1: return 1 p = 1 << (val - 1).bit_length() return min(p, cap) def _get_num_sms(device: "torch.device") -> int: try: return int(torch.cuda.get_device_properties(device).multi_processor_count) except Exception: return 128 def _mod_can_use_triton(tensor: "torch.Tensor") -> bool: return bool(_HAS_TRITON and _HAS_TORCH and tensor.is_cuda) # --- Kernel 1: fused_mod_gate_score impls --- def _pytorch_mod_gate_score_fwd( h_2d: "torch.Tensor", w_1d: "torch.Tensor", bias: Optional["torch.Tensor"], c_gate_1d: Optional["torch.Tensor"], out_dtype: "torch.dtype", ) -> Tuple["torch.Tensor", "torch.Tensor"]: logits = torch.mv(h_2d.float(), w_1d.float()) if bias is not None: logits = logits + bias.reshape(-1)[0].float() sig = torch.sigmoid(logits) eff = sig * c_gate_1d.float() if c_gate_1d is not None else sig return eff.to(out_dtype), sig def _pytorch_mod_gate_score_bwd( d_eff_1d: "torch.Tensor", h_2d: "torch.Tensor", w_1d: "torch.Tensor", sig_1d: "torch.Tensor", c_gate_1d: Optional["torch.Tensor"], need_dh: bool, need_dw: bool, need_db: bool, h_dtype: "torch.dtype", w_shape: Tuple[int, ...], w_dtype: "torch.dtype", b_shape: Optional[Tuple[int, ...]], b_dtype: Optional["torch.dtype"], ) -> Tuple[Optional["torch.Tensor"], Optional["torch.Tensor"], Optional["torch.Tensor"]]: delta = d_eff_1d.float() * sig_1d.float() * (1.0 - sig_1d.float()) if c_gate_1d is not None: delta = delta * c_gate_1d.float() d_h = None if need_dh: d_h = (delta.unsqueeze(1) * w_1d.float().unsqueeze(0)).to(h_dtype) d_w = None if need_dw: # Explicitly reshape to w_shape (guaranteed [1, D] for nn.Linear(D, 1)!) d_w = torch.matmul(delta, h_2d.float()).reshape(w_shape).to(w_dtype) d_b = None if need_db and b_shape is not None and b_dtype is not None: d_b = delta.sum().reshape(b_shape).to(b_dtype) return d_h, d_w, d_b def _mod_gate_score_fwd_impl( h_2d: "torch.Tensor", w_1d: "torch.Tensor", bias: Optional["torch.Tensor"], c_gate_1d: Optional["torch.Tensor"], out_dtype: "torch.dtype", save_sig: bool, ) -> Tuple["torch.Tensor", Optional["torch.Tensor"]]: N, D = h_2d.shape if N == 0: empty_out = torch.empty((0,), device=h_2d.device, dtype=out_dtype) empty_sig = torch.empty((0,), device=h_2d.device, dtype=torch.float32) if save_sig else None return empty_out, empty_sig if not _mod_can_use_triton(h_2d): eff, sig = _pytorch_mod_gate_score_fwd(h_2d, w_1d, bias, c_gate_1d, out_dtype) return eff, (sig if save_sig else None) w_c = w_1d.contiguous() b_c = bias.reshape(-1).contiguous() if bias is not None else w_c cg_c = c_gate_1d.contiguous() if c_gate_1d is not None else w_c out = torch.empty((N,), device=h_2d.device, dtype=out_dtype) sig = torch.empty((N,), device=h_2d.device, dtype=torch.float32) if save_sig else out BLOCK_D = _next_pow2_capped(D, 1024) BLOCK_N = 4 grid = (triton.cdiv(N, BLOCK_N),) _triton_mod_gate_score_fwd[grid]( h_2d, w_c, b_c, cg_c, out, sig, N, D, h_2d.stride(0), h_2d.stride(1), HAS_BIAS=(bias is not None), HAS_CGATE=(c_gate_1d is not None), SAVE_SIG=save_sig, BLOCK_N=BLOCK_N, BLOCK_D=BLOCK_D, num_warps=4, ) return out, (sig if save_sig else None) def _mod_gate_score_bwd_impl( d_eff_1d: "torch.Tensor", h_2d: "torch.Tensor", w_1d: "torch.Tensor", sig_1d: "torch.Tensor", c_gate_1d: Optional["torch.Tensor"], need_dh: bool, need_dw: bool, need_db: bool, h_dtype: "torch.dtype", w_shape: Tuple[int, ...], w_dtype: "torch.dtype", b_shape: Optional[Tuple[int, ...]], b_dtype: Optional["torch.dtype"], ) -> Tuple[Optional["torch.Tensor"], Optional["torch.Tensor"], Optional["torch.Tensor"]]: N, D = h_2d.shape if N == 0: d_h = torch.empty((0, D), device=h_2d.device, dtype=h_dtype) if need_dh else None d_w = torch.zeros(w_shape, device=h_2d.device, dtype=w_dtype) if need_dw else None d_b = ( torch.zeros(b_shape, device=h_2d.device, dtype=b_dtype) if (need_db and b_shape is not None and b_dtype is not None) else None ) return d_h, d_w, d_b if not _mod_can_use_triton(h_2d): return _pytorch_mod_gate_score_bwd( d_eff_1d, h_2d, w_1d, sig_1d, c_gate_1d, need_dh, need_dw, need_db, h_dtype, w_shape, w_dtype, b_shape, b_dtype, ) d_eff_c = d_eff_1d.contiguous() w_c = w_1d.contiguous() sig_c = sig_1d.contiguous() cg_c = c_gate_1d.contiguous() if c_gate_1d is not None else sig_c d_h = torch.empty((N, D), device=h_2d.device, dtype=h_dtype) if need_dh else h_2d d_w_fp32 = torch.zeros((D,), device=h_2d.device, dtype=torch.float32) if need_dw else sig_c d_b_fp32 = torch.zeros((1,), device=h_2d.device, dtype=torch.float32) if need_db else sig_c BLOCK_D = _next_pow2_capped(D, 1024) BLOCK_N = 4 num_tiles = triton.cdiv(N, BLOCK_N) num_progs = min(max(1, _get_num_sms(h_2d.device)), num_tiles) grid = (num_progs, triton.cdiv(D, BLOCK_D)) _triton_mod_gate_score_bwd_persistent[grid]( d_eff_c, h_2d, w_c, sig_c, cg_c, d_h, d_w_fp32, d_b_fp32, N, D, num_tiles, h_2d.stride(0), h_2d.stride(1), d_h.stride(0), d_h.stride(1), HAS_CGATE=(c_gate_1d is not None), NEED_DH=need_dh, NEED_DW=need_dw, NEED_DB=need_db, BLOCK_N=BLOCK_N, BLOCK_D=BLOCK_D, num_warps=4, ) out_dh = d_h if need_dh else None out_dw = d_w_fp32.reshape(w_shape).to(w_dtype) if need_dw else None out_db = ( d_b_fp32.reshape(b_shape).to(b_dtype) if (need_db and b_shape is not None and b_dtype is not None) else None ) return out_dh, out_dw, out_db # --- Kernel 2: fused_mod_scaled_scatter_add impls --- def _pytorch_mod_scaled_scatter_add_fwd( out_2d: "torch.Tensor", top_idx_1d: "torch.Tensor", top_g_1d: "torch.Tensor", bridge_scale_1d: "torch.Tensor", m_sel_2d: "torch.Tensor", ) -> "torch.Tensor": scale = (top_g_1d.float() * bridge_scale_1d.reshape(-1)[0].float()).unsqueeze(-1) delta = (scale * m_sel_2d.float()).to(out_2d.dtype) out_2d.index_add_(0, top_idx_1d.long(), delta) return out_2d def _pytorch_mod_scaled_scatter_add_bwd( d_out_2d: "torch.Tensor", top_idx_1d: "torch.Tensor", top_g_1d: "torch.Tensor", bridge_scale_1d: "torch.Tensor", m_sel_2d: "torch.Tensor", need_dm: bool, need_dg: bool, need_dbs: bool, m_dtype: "torch.dtype", g_dtype: "torch.dtype", bs_shape: Tuple[int, ...], bs_dtype: "torch.dtype", ) -> Tuple[Optional["torch.Tensor"], Optional["torch.Tensor"], Optional["torch.Tensor"]]: go_sel = d_out_2d.index_select(0, top_idx_1d.long()).float() g_f = top_g_1d.float() bs_f = bridge_scale_1d.reshape(-1)[0].float() d_m_sel = None if need_dm: d_m_sel = ((g_f * bs_f).unsqueeze(-1) * go_sel).to(m_dtype) d_top_g = None d_bs = None if need_dg or need_dbs: dot_k = (go_sel * m_sel_2d.float()).sum(dim=-1) if need_dg: d_top_g = (bs_f * dot_k).to(g_dtype) if need_dbs: d_bs = (g_f * dot_k).sum().reshape(bs_shape).to(bs_dtype) return d_m_sel, d_top_g, d_bs def _mod_scaled_scatter_add_fwd_impl( out_2d: "torch.Tensor", top_idx_1d: "torch.Tensor", top_g_1d: "torch.Tensor", bridge_scale_1d: "torch.Tensor", m_sel_2d: "torch.Tensor", ) -> "torch.Tensor": N, D = out_2d.shape K = top_idx_1d.numel() if K == 0 or N == 0: return out_2d if not _mod_can_use_triton(out_2d): return _pytorch_mod_scaled_scatter_add_fwd( out_2d, top_idx_1d, top_g_1d, bridge_scale_1d, m_sel_2d ) idx_c = top_idx_1d.contiguous() g_c = top_g_1d.contiguous() bs_c = bridge_scale_1d.reshape(-1).contiguous() m_c = m_sel_2d.contiguous() BLOCK_D = _next_pow2_capped(D, 1024) grid = (K, triton.cdiv(D, BLOCK_D)) _triton_mod_scaled_scatter_add_fwd[grid]( out_2d, idx_c, g_c, bs_c, m_c, N, K, D, out_2d.stride(0), out_2d.stride(1), m_c.stride(0), m_c.stride(1), BLOCK_D=BLOCK_D, num_warps=4, ) return out_2d def _mod_scaled_scatter_add_bwd_impl( d_out_2d: "torch.Tensor", top_idx_1d: "torch.Tensor", top_g_1d: "torch.Tensor", bridge_scale_1d: "torch.Tensor", m_sel_2d: "torch.Tensor", need_dm: bool, need_dg: bool, need_dbs: bool, m_dtype: "torch.dtype", g_dtype: "torch.dtype", bs_shape: Tuple[int, ...], bs_dtype: "torch.dtype", ) -> Tuple[Optional["torch.Tensor"], Optional["torch.Tensor"], Optional["torch.Tensor"]]: N, D = d_out_2d.shape K = top_idx_1d.numel() if K == 0 or N == 0: d_m = torch.empty((0, D), device=d_out_2d.device, dtype=m_dtype) if need_dm else None d_g = torch.empty((0,), device=d_out_2d.device, dtype=g_dtype) if need_dg else None d_bs = ( torch.zeros(bs_shape, device=d_out_2d.device, dtype=bs_dtype) if need_dbs else None ) return d_m, d_g, d_bs if not _mod_can_use_triton(d_out_2d): return _pytorch_mod_scaled_scatter_add_bwd( d_out_2d, top_idx_1d, top_g_1d, bridge_scale_1d, m_sel_2d, need_dm, need_dg, need_dbs, m_dtype, g_dtype, bs_shape, bs_dtype, ) idx_c = top_idx_1d.contiguous() g_c = top_g_1d.contiguous() bs_c = bridge_scale_1d.reshape(-1).contiguous() m_c = m_sel_2d.contiguous() d_m_sel = torch.empty((K, D), device=d_out_2d.device, dtype=m_dtype) if need_dm else m_c d_top_g = torch.empty((K,), device=d_out_2d.device, dtype=g_dtype) if need_dg else g_c d_bs_fp32 = ( torch.zeros((1,), device=d_out_2d.device, dtype=torch.float32) if need_dbs else bs_c ) BLOCK_D = _next_pow2_capped(D, 1024) num_progs = min(max(1, _get_num_sms(d_out_2d.device)), K) grid = (num_progs,) _triton_mod_scaled_scatter_add_bwd_persistent[grid]( d_out_2d, idx_c, g_c, bs_c, m_c, d_m_sel, d_top_g, d_bs_fp32, N, K, D, d_out_2d.stride(0), d_out_2d.stride(1), m_c.stride(0), m_c.stride(1), d_m_sel.stride(0), d_m_sel.stride(1), NEED_DM=need_dm, NEED_DG=need_dg, NEED_DBS=need_dbs, BLOCK_D=BLOCK_D, num_warps=4, ) out_dm = d_m_sel if need_dm else None out_dg = d_top_g if need_dg else None out_dbs = d_bs_fp32.reshape(bs_shape).to(bs_dtype) if need_dbs else None return out_dm, out_dg, out_dbs # ============================================================================= # 3. PYTORCH AUTOGRAD WRAPPERS & PUBLIC ENTRY POINTS # ============================================================================= if True: class FusedModGateScoreFunction(torch.autograd.Function): @staticmethod def forward( ctx, h_ffn: "torch.Tensor", weight: "torch.Tensor", bias: Optional["torch.Tensor"], c_gate: Optional["torch.Tensor"], out_dtype: "torch.dtype", ) -> "torch.Tensor": orig_h_shape = tuple(h_ffn.shape) D = orig_h_shape[-1] h_2d = h_ffn.reshape(-1, D) w_1d = weight.reshape(D) cg_1d = c_gate.reshape(-1) if c_gate is not None else None need_bwd = ( ctx.needs_input_grad[0] or ctx.needs_input_grad[1] or (bias is not None and ctx.needs_input_grad[2]) ) eff_score, sig = _mod_gate_score_fwd_impl( h_2d, w_1d, bias, cg_1d, out_dtype=out_dtype, save_sig=need_bwd ) ctx.orig_h_shape = orig_h_shape ctx.h_dtype = h_ffn.dtype ctx.w_shape = tuple(weight.shape) ctx.w_dtype = weight.dtype ctx.b_shape = tuple(bias.shape) if bias is not None else None ctx.b_dtype = bias.dtype if bias is not None else None ctx.has_cgate = cg_1d is not None if need_bwd: if cg_1d is not None: ctx.save_for_backward(h_2d, w_1d, sig, cg_1d) else: ctx.save_for_backward(h_2d, w_1d, sig) return eff_score @staticmethod def backward(ctx, d_eff_score: "torch.Tensor"): saved = ctx.saved_tensors if ctx.has_cgate: h_2d, w_1d, sig, cg_1d = saved else: h_2d, w_1d, sig = saved cg_1d = None need_dh = ctx.needs_input_grad[0] need_dw = ctx.needs_input_grad[1] need_db = (ctx.b_shape is not None) and ctx.needs_input_grad[2] d_h_2d, d_w, d_b = _mod_gate_score_bwd_impl( d_eff_score.reshape(-1), h_2d, w_1d, sig, cg_1d, need_dh=need_dh, need_dw=need_dw, need_db=need_db, h_dtype=ctx.h_dtype, w_shape=ctx.w_shape, w_dtype=ctx.w_dtype, b_shape=ctx.b_shape, b_dtype=ctx.b_dtype, ) d_h = d_h_2d.view(ctx.orig_h_shape) if d_h_2d is not None else None # c_gate is treated as a detached constant (matching forward_backbone) return d_h, d_w, d_b, None, None class FusedModScaledScatterAddFunction(torch.autograd.Function): @staticmethod def forward( ctx, ffn_out: "torch.Tensor", top_idx: "torch.Tensor", top_g: "torch.Tensor", bridge_scale: "torch.Tensor", m_sel: "torch.Tensor", inplace: bool, ) -> "torch.Tensor": orig_shape = tuple(ffn_out.shape) D = orig_shape[-1] can_inplace = ( inplace and ffn_out.is_contiguous() and not (ffn_out.is_leaf and ffn_out.requires_grad) ) if can_inplace: out = ffn_out ctx.mark_dirty(ffn_out) else: out = ffn_out.clone().contiguous() out_2d = out.view(-1, D) idx_1d = top_idx.reshape(-1) g_1d = top_g.reshape(-1) bs_1d = bridge_scale.reshape(-1) m_2d = m_sel.reshape(-1, D) _mod_scaled_scatter_add_fwd_impl(out_2d, idx_1d, g_1d, bs_1d, m_2d) ctx.ffn_dtype = ffn_out.dtype ctx.m_dtype = m_sel.dtype ctx.g_shape = tuple(top_g.shape) ctx.g_dtype = top_g.dtype ctx.bs_shape = tuple(bridge_scale.shape) ctx.bs_dtype = bridge_scale.dtype ctx.D = D ctx.save_for_backward(idx_1d, g_1d, bs_1d, m_2d) return out @staticmethod def backward(ctx, d_out: "torch.Tensor"): idx_1d, g_1d, bs_1d, m_2d = ctx.saved_tensors need_dffn = ctx.needs_input_grad[0] need_dg = ctx.needs_input_grad[2] need_dbs = ctx.needs_input_grad[3] need_dm = ctx.needs_input_grad[4] d_ffn_out = None if need_dffn: d_ffn_out = d_out if d_out.dtype == ctx.ffn_dtype else d_out.to(ctx.ffn_dtype) d_m_sel = None d_top_g = None d_bs = None if need_dm or need_dg or need_dbs: d_out_2d = d_out.reshape(-1, ctx.D) d_m_sel, d_g_1d, d_bs = _mod_scaled_scatter_add_bwd_impl( d_out_2d, idx_1d, g_1d, bs_1d, m_2d, need_dm=need_dm, need_dg=need_dg, need_dbs=need_dbs, m_dtype=ctx.m_dtype, g_dtype=ctx.g_dtype, bs_shape=ctx.bs_shape, bs_dtype=ctx.bs_dtype, ) if d_g_1d is not None: d_top_g = d_g_1d.view(ctx.g_shape) return d_ffn_out, None, d_top_g, d_bs, d_m_sel, None def fused_mod_gate_score( h_ffn: "torch.Tensor", weight: "torch.Tensor", bias: Optional["torch.Tensor"] = None, c_gate: Optional["torch.Tensor"] = None, out_dtype: Optional["torch.dtype"] = None, ) -> "torch.Tensor": """Fused MoD gate scoring: `eff_score[n] = sigmoid(dot(h_ffn[n], w) + b) * c_gate[n]`. Drop-in replacement in `train_l2_gddr7_wikipedia.py` (lines 3858-3865): eff_score = fused_mod_gate_score( h_ffn_mg, self.mem_need_gate.weight, self.mem_need_gate.bias, contraction_gate, ) Args: h_ffn: Input hidden states `[..., D]` (e.g. `[B, T, 1024]` or `[N, 1024]`). weight: Gate projection weight `[1, D]` (guaranteed `[1, D]` gradient shape). bias: Optional gate bias `[1]`. c_gate: Optional detached contraction gate `[...]` (flattened to `[N]`) or `None`. out_dtype: Output dtype (defaults to `weight.dtype`, matching eager `nn.Linear`). Returns: 1D `eff_score` tensor of shape `[N]`. """ if not _HAS_TORCH: raise RuntimeError("PyTorch is required to call fused_mod_gate_score.") target_dtype = out_dtype if out_dtype is not None else weight.dtype if not torch.is_grad_enabled(): D = h_ffn.shape[-1] eff, _ = _mod_gate_score_fwd_impl( h_ffn.reshape(-1, D), weight.reshape(D), bias, c_gate.reshape(-1) if c_gate is not None else None, out_dtype=target_dtype, save_sig=False, ) return eff return FusedModGateScoreFunction.apply(h_ffn, weight, bias, c_gate, target_dtype) def fused_mod_scaled_scatter_add( ffn_out: "torch.Tensor", top_idx: "torch.Tensor", top_g: "torch.Tensor", bridge_scale: "torch.Tensor", m_sel: "torch.Tensor", inplace: bool = True, ) -> "torch.Tensor": """Fused scaled scatter-add: `ffn_out[top_idx[k]] += top_g[k] * bridge_scale * m_sel[k]`. Drop-in replacement in `train_l2_gddr7_wikipedia.py` (lines 3884-3892): ffn_out = fused_mod_scaled_scatter_add( ffn_out, top_idx, top_g, bridge.bridge_scale, m_sel, inplace=True ) Note on telemetry (`collect_telemetry=True`, line 3896): `b_rms` can be computed without materializing `mem_delta` via: b_rms = ( (top_g.float() * bridge.bridge_scale.float()).pow(2) * m_sel.float().pow(2).mean(dim=-1) ).mean().sqrt().item() Args: ffn_out: Target tensor `[..., D]` (e.g. `[B, T, 1024]` or `[N, 1024]`). top_idx: Strictly unique selected token indices `[K]` (int32 or int64). top_g: Selected token gate scores `[K]`. bridge_scale: Scalar `()` or `[1]` bridge scale tensor. m_sel: Selected memory outputs `[K, D]`. inplace: If `True` (default), updates `ffn_out` in-place when contiguous and non-leaf, avoiding the 64 MiB `ffn_out.clone()` allocation. Returns: Updated tensor with the same shape and dtype as `ffn_out`. """ if not _HAS_TORCH: raise RuntimeError("PyTorch is required to call fused_mod_scaled_scatter_add.") if not torch.is_grad_enabled(): D = ffn_out.shape[-1] out = ffn_out if (inplace and ffn_out.is_contiguous()) else ffn_out.clone().contiguous() _mod_scaled_scatter_add_fwd_impl( out.view(-1, D), top_idx.reshape(-1), top_g.reshape(-1), bridge_scale.reshape(-1), m_sel.reshape(-1, D), ) return out return FusedModScaledScatterAddFunction.apply( ffn_out, top_idx, top_g, bridge_scale, m_sel, inplace ) # ============================================================================= # --- Kernel Suite 6: Fused SwiGLU-FP8, RMSNorm-FP8 & CachedFP8Linear --- def _is_triton_cuda_tensor(t: torch.Tensor) -> bool: return HAS_TRITON and t.is_cuda def _can_use_fp8(t: torch.Tensor) -> bool: return FP8_DTYPE is not None and t.is_cuda # ============================================================================== # TRITON KERNELS # ============================================================================== if HAS_TRITON: @triton.jit def _quantize_rowwise_fp8_kernel( x_ptr, y_fp8_ptr, y_scale_ptr, stride_x_row, stride_y_row, N: tl.constexpr, BLOCK_N: tl.constexpr, ): """Rowwise dynamic FP8 E4M3FN quantization (handles arbitrary N via masking).""" row = tl.program_id(0).to(tl.int64) x_row_ptr = x_ptr + row * stride_x_row y_row_ptr = y_fp8_ptr + row * stride_y_row # Vector max across tiles avoids repeated cross-lane warp reductions inside the loop row_amax_vec = tl.zeros((BLOCK_N,), dtype=tl.float32) for col_start in range(0, N, BLOCK_N): offs = col_start + tl.arange(0, BLOCK_N) mask = offs < N x = tl.load(x_row_ptr + offs, mask=mask, other=0.0).to(tl.float32) row_amax_vec = tl.maximum(row_amax_vec, tl.abs(x)) row_amax = tl.max(row_amax_vec, axis=0) scale = tl.maximum(row_amax * (1.0 / 448.0), 1e-12) inv_scale = 1.0 / scale tl.store(y_scale_ptr + row, scale) for col_start in range(0, N, BLOCK_N): offs = col_start + tl.arange(0, BLOCK_N) mask = offs < N x = tl.load(x_row_ptr + offs, mask=mask, other=0.0).to(tl.float32) q = tl.minimum(tl.maximum(x * inv_scale, -448.0), 448.0) tl.store(y_row_ptr + offs, q.to(y_fp8_ptr.dtype.element_ty), mask=mask) @triton.jit def _silu_mul_fp8_fwd_kernel( gate_ptr, up_ptr, y_fp8_ptr, y_scale_ptr, y_bf16_ptr, stride_gate_row, stride_up_row, stride_y_fp8_row, stride_y_bf16_row, N: tl.constexpr, BLOCK_N: tl.constexpr, WRITE_BF16: tl.constexpr, ): """Fused SwiGLU + per-row FP8 E4M3FN quantization. Computes y = silu(gate) * up in FP32, per-row scale = max(amax(|y|) / 448.0, 1e-12), and writes y_fp8 [M, N] (float8_e4m3fn) + y_scale [M] (fp32), plus optional BF16 y. Handles N = 2688 (21 * 128) cleanly with power-of-2 BLOCK_N and mask = offs < N. """ row = tl.program_id(0).to(tl.int64) gate_row_ptr = gate_ptr + row * stride_gate_row up_row_ptr = up_ptr + row * stride_up_row y_fp8_row_ptr = y_fp8_ptr + row * stride_y_fp8_row y_bf16_row_ptr = y_bf16_ptr + row * stride_y_bf16_row # Pass 1: compute row amax in FP32 (and optionally write BF16 output). # 5376 * 2B = 10.75 KiB per row stays resident in L1 cache for Pass 2. row_amax_vec = tl.zeros((BLOCK_N,), dtype=tl.float32) for col_start in range(0, N, BLOCK_N): offs = col_start + tl.arange(0, BLOCK_N) mask = offs < N g = tl.load(gate_row_ptr + offs, mask=mask, other=0.0).to(tl.float32) u = tl.load(up_row_ptr + offs, mask=mask, other=0.0).to(tl.float32) sig = tl.sigmoid(g) y = (g * sig) * u if WRITE_BF16: tl.store( y_bf16_row_ptr + offs, y.to(y_bf16_ptr.dtype.element_ty), mask=mask, ) row_amax_vec = tl.maximum(row_amax_vec, tl.abs(y)) row_amax = tl.max(row_amax_vec, axis=0) scale = tl.maximum(row_amax * (1.0 / 448.0), 1e-12) inv_scale = 1.0 / scale tl.store(y_scale_ptr + row, scale) # Pass 2: quantize exact FP32 y to FP8 E4M3FN using per-row scale for col_start in range(0, N, BLOCK_N): offs = col_start + tl.arange(0, BLOCK_N) mask = offs < N g = tl.load(gate_row_ptr + offs, mask=mask, other=0.0).to(tl.float32) u = tl.load(up_row_ptr + offs, mask=mask, other=0.0).to(tl.float32) sig = tl.sigmoid(g) y = (g * sig) * u q = tl.minimum(tl.maximum(y * inv_scale, -448.0), 448.0) tl.store( y_fp8_row_ptr + offs, q.to(y_fp8_ptr.dtype.element_ty), mask=mask, ) @triton.jit def _silu_mul_bwd_kernel( dy_ptr, gate_ptr, up_ptr, d_gate_ptr, d_up_ptr, stride_dy_row, stride_gate_row, stride_up_row, stride_dgate_row, stride_dup_row, N: tl.constexpr, BLOCK_N: tl.constexpr, ): """Single-pass fused SwiGLU backward kernel. d_up = dy * silu(gate) d_gate = dy * up * sig * (1 + gate * (1 - sig)) """ row = tl.program_id(0).to(tl.int64) col_block = tl.program_id(1) offs = col_block * BLOCK_N + tl.arange(0, BLOCK_N) mask = offs < N dy = tl.load(dy_ptr + row * stride_dy_row + offs, mask=mask, other=0.0).to(tl.float32) g = tl.load(gate_ptr + row * stride_gate_row + offs, mask=mask, other=0.0).to(tl.float32) u = tl.load(up_ptr + row * stride_up_row + offs, mask=mask, other=0.0).to(tl.float32) sig = tl.sigmoid(g) silu_g = g * sig d_up = dy * silu_g d_gate = dy * u * sig * (1.0 + g * (1.0 - sig)) tl.store( d_gate_ptr + row * stride_dgate_row + offs, d_gate.to(d_gate_ptr.dtype.element_ty), mask=mask, ) tl.store( d_up_ptr + row * stride_dup_row + offs, d_up.to(d_up_ptr.dtype.element_ty), mask=mask, ) @triton.jit def _rmsnorm_fp8_fwd_kernel( x_ptr, gamma_ptr, y_fp8_ptr, y_scale_ptr, rstd_ptr, y_bf16_ptr, stride_x_row, stride_y_fp8_row, stride_y_bf16_row, eps, D: tl.constexpr, BLOCK_D: tl.constexpr, HAS_GAMMA: tl.constexpr, WRITE_BF16: tl.constexpr, ): """Single-pass RMSNorm + per-row FP8 E4M3FN quantization for D = 1024 (power of 2).""" row = tl.program_id(0).to(tl.int64) offs = tl.arange(0, BLOCK_D) mask = offs < D x = tl.load(x_ptr + row * stride_x_row + offs, mask=mask, other=0.0).to(tl.float32) mean_sq = tl.sum(x * x, axis=0) * (1.0 / D) rstd = tl.rsqrt(mean_sq + eps) tl.store(rstd_ptr + row, rstd) y = x * rstd if HAS_GAMMA: gamma = tl.load(gamma_ptr + offs, mask=mask, other=0.0).to(tl.float32) y = y * gamma if WRITE_BF16: tl.store( y_bf16_ptr + row * stride_y_bf16_row + offs, y.to(y_bf16_ptr.dtype.element_ty), mask=mask, ) amax = tl.max(tl.abs(y), axis=0) scale = tl.maximum(amax * (1.0 / 448.0), 1e-12) inv_scale = 1.0 / scale q = tl.minimum(tl.maximum(y * inv_scale, -448.0), 448.0) tl.store( y_fp8_ptr + row * stride_y_fp8_row + offs, q.to(y_fp8_ptr.dtype.element_ty), mask=mask, ) tl.store(y_scale_ptr + row, scale) @triton.jit def _rmsnorm_bwd_dx_partial_dgamma_kernel( dy_ptr, x_ptr, rstd_ptr, gamma_ptr, dx_ptr, partial_dgamma_ptr, stride_dy_row, stride_x_row, stride_dx_row, stride_pg_row, M, rows_per_group, D: tl.constexpr, BLOCK_D: tl.constexpr, HAS_GAMMA: tl.constexpr, ): """Single-pass RMSNorm backward computing exact dx and FP32 partial dgamma. Each program handles a contiguous stripe of rows, keeping `gamma` and `dgamma_acc` in FP32 registers (zero atomic_add contention). """ pid = tl.program_id(0).to(tl.int64) offs = tl.arange(0, BLOCK_D) mask = offs < D if HAS_GAMMA: gamma = tl.load(gamma_ptr + offs, mask=mask, other=0.0).to(tl.float32) dgamma_acc = tl.zeros((BLOCK_D,), dtype=tl.float32) row_start = pid * rows_per_group row_end = tl.minimum(row_start + rows_per_group, M) for row in range(row_start, row_end): x = tl.load(x_ptr + row * stride_x_row + offs, mask=mask, other=0.0).to(tl.float32) dy = tl.load(dy_ptr + row * stride_dy_row + offs, mask=mask, other=0.0).to(tl.float32) rstd = tl.load(rstd_ptr + row).to(tl.float32) x_hat = x * rstd if HAS_GAMMA: g = dy * gamma dgamma_acc += dy * x_hat else: g = dy c = tl.sum(g * x_hat, axis=0) * (1.0 / D) dx = rstd * (g - c * x_hat) tl.store( dx_ptr + row * stride_dx_row + offs, dx.to(dx_ptr.dtype.element_ty), mask=mask, ) if HAS_GAMMA: tl.store( partial_dgamma_ptr + pid * stride_pg_row + offs, dgamma_acc, mask=mask, ) @triton.jit def _rmsnorm_dgamma_reduce_kernel( partial_dgamma_ptr, dgamma_ptr, stride_pg_row, num_groups, D: tl.constexpr, BLOCK_D: tl.constexpr, ): """Final FP32 reduction of partial_dgamma [num_groups, D] -> dgamma [D].""" offs = tl.arange(0, BLOCK_D) mask = offs < D acc = tl.zeros((BLOCK_D,), dtype=tl.float32) for g in range(0, num_groups): acc += tl.load(partial_dgamma_ptr + g * stride_pg_row + offs, mask=mask, other=0.0) tl.store(dgamma_ptr + offs, acc.to(dgamma_ptr.dtype.element_ty), mask=mask) # ============================================================================== # QUANTIZATION HELPERS # ============================================================================== def quantize_rowwise_fp8( x: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor]: """Rowwise dynamic FP8 E4M3FN quantization of a 2D tensor [M, N]. Returns: (x_fp8 [M, N] float8_e4m3fn, x_scale [M, 1] float32) """ assert x.ndim == 2, f"Expected 2D tensor, got shape {tuple(x.shape)}" M, N = x.shape x_contig = x.contiguous() if _is_triton_cuda_tensor(x_contig) and FP8_DTYPE is not None: y_fp8 = torch.empty((M, N), device=x.device, dtype=FP8_DTYPE) y_scale = torch.empty((M, 1), device=x.device, dtype=torch.float32) if M > 0 and N > 0: block_n = 256 if N >= 256 else max(16, 1 << (N - 1).bit_length()) _quantize_rowwise_fp8_kernel[(M,)]( x_contig, y_fp8, y_scale, x_contig.stride(0), y_fp8.stride(0), N=N, BLOCK_N=block_n, num_warps=4, ) return y_fp8, y_scale # PyTorch fallback (CPU or no Triton) x32 = x_contig.float() amax = x32.abs().amax(dim=-1, keepdim=True) scale = torch.clamp(amax / FP8_E4M3_MAX, min=FP8_SCALE_EPS) q = torch.clamp(x32 / scale, -FP8_E4M3_MAX, FP8_E4M3_MAX) out_dtype = FP8_DTYPE if FP8_DTYPE is not None else torch.float32 return q.to(out_dtype), scale def quantize_tensorwise_fp8( x: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor]: """Tensorwise dynamic FP8 E4M3FN quantization. Returns: (x_fp8 float8_e4m3fn, x_scale [1] float32) """ x32 = x.float() amax = x32.abs().amax() scale = torch.clamp(amax / FP8_E4M3_MAX, min=FP8_SCALE_EPS).reshape(1).to(torch.float32) q = torch.clamp(x32 / scale, -FP8_E4M3_MAX, FP8_E4M3_MAX) out_dtype = FP8_DTYPE if FP8_DTYPE is not None else torch.float32 return q.to(out_dtype), scale # ============================================================================== # COMPONENT 1: FUSED SWIGLU + FP8 QUANTIZATION (FWD & BWD) # ============================================================================== def fused_silu_mul_fp8_quant( gate_up: torch.Tensor, up: Optional[torch.Tensor] = None, return_bf16: bool = False, block_n: int = 256, ) -> Union[ Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor, torch.Tensor, torch.Tensor], ]: """Fused SwiGLU (`silu(gate) * up`) + per-row FP8 E4M3FN quantization. Args: gate_up: Either fused `[..., 2 * N]` tensor (e.g. `[M, 5376]`) when `up is None`, or `gate [..., N]` tensor (e.g. `[M, 2688]`) when `up` is provided. up: Optional separate `up [..., N]` tensor. return_bf16: If True, also return BF16 `y` (useful for non-FP8 fallback). block_n: Power-of-2 tile width (default 256; 128 also supported). Returns: `(y_fp8 [..., N], y_scale [..., 1])` or `(y_fp8, y_scale, y_bf16)`. """ if up is None: assert gate_up.shape[-1] % 2 == 0, ( f"gate_up last dim must be even, got {gate_up.shape[-1]}" ) orig_shape = gate_up.shape[:-1] N = gate_up.shape[-1] // 2 gu_2d = gate_up.reshape(-1, 2 * N).contiguous() M = gu_2d.shape[0] gate_2d = gu_2d[:, :N] up_2d = gu_2d[:, N:] else: assert gate_up.shape == up.shape, ( f"gate {tuple(gate_up.shape)} and up {tuple(up.shape)} must match" ) orig_shape = gate_up.shape[:-1] N = gate_up.shape[-1] gate_2d = gate_up.reshape(-1, N).contiguous() up_2d = up.reshape(-1, N).contiguous() M = gate_2d.shape[0] assert block_n > 0 and (block_n & (block_n - 1)) == 0, "block_n must be power of 2" if _is_triton_cuda_tensor(gate_2d) and FP8_DTYPE is not None: y_fp8 = torch.empty((M, N), device=gate_2d.device, dtype=FP8_DTYPE) y_scale = torch.empty((M, 1), device=gate_2d.device, dtype=torch.float32) y_bf16 = ( torch.empty((M, N), device=gate_2d.device, dtype=torch.bfloat16) if return_bf16 else torch.empty((1,), device=gate_2d.device, dtype=torch.bfloat16) ) if M > 0 and N > 0: _silu_mul_fp8_fwd_kernel[(M,)]( gate_2d, up_2d, y_fp8, y_scale, y_bf16, gate_2d.stride(0), up_2d.stride(0), y_fp8.stride(0), y_bf16.stride(0) if return_bf16 else 0, N=N, BLOCK_N=block_n, WRITE_BF16=return_bf16, num_warps=4, ) y_fp8 = y_fp8.reshape(*orig_shape, N) y_scale = y_scale.reshape(*orig_shape, 1) if return_bf16: return y_fp8, y_scale, y_bf16.reshape(*orig_shape, N) return y_fp8, y_scale # Reference PyTorch fallback g32 = gate_2d.float() u32 = up_2d.float() y32 = F.silu(g32) * u32 amax = y32.abs().amax(dim=-1, keepdim=True) scale = torch.clamp(amax / FP8_E4M3_MAX, min=FP8_SCALE_EPS) q = torch.clamp(y32 / scale, -FP8_E4M3_MAX, FP8_E4M3_MAX) out_dtype = FP8_DTYPE if FP8_DTYPE is not None else torch.float32 y_fp8 = q.to(out_dtype).reshape(*orig_shape, N) y_scale = scale.reshape(*orig_shape, 1) if return_bf16: return y_fp8, y_scale, y32.to(torch.bfloat16).reshape(*orig_shape, N) return y_fp8, y_scale def fused_silu_mul_bwd( dy: torch.Tensor, gate_up: torch.Tensor, up: Optional[torch.Tensor] = None, block_n: int = 256, ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: """Single-pass fused SwiGLU backward kernel. Args: dy: Upstream gradient `[..., N]`. gate_up: Either fused `[..., 2 * N]` when `up is None`, or `gate [..., N]`. up: Optional separate `up [..., N]`. block_n: Power-of-2 tile width (default 256). Returns: `d_gate_up [..., 2 * N]` if `up is None`, else `(d_gate [..., N], d_up [..., N])`. """ assert block_n > 0 and (block_n & (block_n - 1)) == 0, "block_n must be power of 2" if up is None: orig_shape = dy.shape[:-1] N = dy.shape[-1] assert gate_up.shape[-1] == 2 * N, ( f"Expected gate_up last dim {2 * N}, got {gate_up.shape[-1]}" ) dy_2d = dy.reshape(-1, N).contiguous() gu_2d = gate_up.reshape(-1, 2 * N).contiguous() M = dy_2d.shape[0] gate_2d = gu_2d[:, :N] up_2d = gu_2d[:, N:] d_gate_up = torch.empty((M, 2 * N), device=gate_up.device, dtype=gate_up.dtype) d_gate_2d = d_gate_up[:, :N] d_up_2d = d_gate_up[:, N:] fused_out = True else: orig_shape = dy.shape[:-1] N = dy.shape[-1] dy_2d = dy.reshape(-1, N).contiguous() gate_2d = gate_up.reshape(-1, N).contiguous() up_2d = up.reshape(-1, N).contiguous() M = dy_2d.shape[0] d_gate_2d = torch.empty((M, N), device=gate_up.device, dtype=gate_up.dtype) d_up_2d = torch.empty((M, N), device=up.device, dtype=up.dtype) fused_out = False if _is_triton_cuda_tensor(dy_2d): if M > 0 and N > 0: grid = (M, triton.cdiv(N, block_n)) _silu_mul_bwd_kernel[grid]( dy_2d, gate_2d, up_2d, d_gate_2d, d_up_2d, dy_2d.stride(0), gate_2d.stride(0), up_2d.stride(0), d_gate_2d.stride(0), d_up_2d.stride(0), N=N, BLOCK_N=block_n, num_warps=4, ) else: dy32 = dy_2d.float() g32 = gate_2d.float() u32 = up_2d.float() sig = torch.sigmoid(g32) d_up_2d.copy_((dy32 * (g32 * sig)).to(d_up_2d.dtype)) d_gate_2d.copy_((dy32 * u32 * sig * (1.0 + g32 * (1.0 - sig))).to(d_gate_2d.dtype)) if fused_out: return d_gate_up.reshape(*orig_shape, 2 * N) return d_gate_2d.reshape(*orig_shape, N), d_up_2d.reshape(*orig_shape, N) # ============================================================================== # COMPONENT 2: FUSED RMSNORM + FP8 QUANTIZATION (FWD & BWD) FOR D = 1024 # ============================================================================== def fused_rmsnorm_fp8_quant( x: torch.Tensor, gamma: Optional[torch.Tensor] = None, eps: float = DEFAULT_EPS, return_bf16: bool = False, ) -> Union[ Tuple[torch.Tensor, torch.Tensor, torch.Tensor], Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor], ]: """Single-pass fused RMSNorm + per-row FP8 E4M3FN quantization. Optimized for D = 1024 (power of 2); works for any D <= 8192 via power-of-2 BLOCK_D. Args: x: Input tensor `[..., D]` (BF16/FP16/FP32). gamma: Optional affine weight `[D]` (FP32/BF16). eps: Epsilon for numerical stability (default 1e-6). return_bf16: If True, also return BF16 normalized output `y_bf16`. Returns: `(y_fp8 [..., D], y_scale [..., 1], rstd [..., 1])`, or with `y_bf16` appended. """ orig_shape = x.shape[:-1] D = x.shape[-1] x_2d = x.reshape(-1, D).contiguous() M = x_2d.shape[0] has_gamma = gamma is not None gamma_contig = ( gamma.contiguous() if has_gamma else torch.empty((1,), device=x.device, dtype=torch.float32) ) if _is_triton_cuda_tensor(x_2d) and FP8_DTYPE is not None: block_d = triton.next_power_of_2(D) y_fp8 = torch.empty((M, D), device=x.device, dtype=FP8_DTYPE) y_scale = torch.empty((M, 1), device=x.device, dtype=torch.float32) rstd = torch.empty((M, 1), device=x.device, dtype=torch.float32) y_bf16 = ( torch.empty((M, D), device=x.device, dtype=torch.bfloat16) if return_bf16 else torch.empty((1,), device=x.device, dtype=torch.bfloat16) ) if M > 0 and D > 0: num_warps = 4 if block_d <= 1024 else 8 _rmsnorm_fp8_fwd_kernel[(M,)]( x_2d, gamma_contig, y_fp8, y_scale, rstd, y_bf16, x_2d.stride(0), y_fp8.stride(0), y_bf16.stride(0) if return_bf16 else 0, eps, D=D, BLOCK_D=block_d, HAS_GAMMA=has_gamma, WRITE_BF16=return_bf16, num_warps=num_warps, ) y_fp8 = y_fp8.reshape(*orig_shape, D) y_scale = y_scale.reshape(*orig_shape, 1) rstd = rstd.reshape(*orig_shape, 1) if return_bf16: return y_fp8, y_scale, rstd, y_bf16.reshape(*orig_shape, D) return y_fp8, y_scale, rstd # Reference PyTorch fallback x32 = x_2d.float() rstd = torch.rsqrt(x32.pow(2).mean(dim=-1, keepdim=True) + eps) y32 = x32 * rstd if has_gamma: y32 = y32 * gamma_contig.float() amax = y32.abs().amax(dim=-1, keepdim=True) scale = torch.clamp(amax / FP8_E4M3_MAX, min=FP8_SCALE_EPS) q = torch.clamp(y32 / scale, -FP8_E4M3_MAX, FP8_E4M3_MAX) out_dtype = FP8_DTYPE if FP8_DTYPE is not None else torch.float32 y_fp8 = q.to(out_dtype).reshape(*orig_shape, D) y_scale = scale.reshape(*orig_shape, 1) rstd = rstd.reshape(*orig_shape, 1) if return_bf16: return y_fp8, y_scale, rstd, y32.to(torch.bfloat16).reshape(*orig_shape, D) return y_fp8, y_scale, rstd def fused_rmsnorm_bwd( dy: torch.Tensor, x: torch.Tensor, rstd: torch.Tensor, gamma: Optional[torch.Tensor] = None, max_groups: int = 128, ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: """Exact single-pass Triton RMSNorm backward with FP32 partial reductions for dgamma. Args: dy: Upstream gradient `[..., D]`. x: Forward input `[..., D]`. rstd: Saved reciprocal RMS `[..., 1]` (or `[M]`) in FP32. gamma: Optional forward weight `[D]`. max_groups: Number of SM row groups for partial FP32 dgamma reduction. Returns: `(dx [..., D], dgamma [D] or None)`. """ orig_shape = x.shape[:-1] D = x.shape[-1] x_2d = x.reshape(-1, D).contiguous() dy_2d = dy.reshape(-1, D).contiguous() rstd_1d = rstd.reshape(-1).contiguous().float() M = x_2d.shape[0] has_gamma = gamma is not None if _is_triton_cuda_tensor(x_2d): dx_2d = torch.empty_like(x_2d) if M == 0 or D == 0: dgamma = torch.zeros_like(gamma) if has_gamma else None return dx_2d.reshape(*orig_shape, D), dgamma block_d = triton.next_power_of_2(D) num_warps = 4 if block_d <= 1024 else 8 num_groups = min(M, max_groups) rows_per_group = (M + num_groups - 1) // num_groups num_groups = (M + rows_per_group - 1) // rows_per_group gamma_contig = ( gamma.contiguous() if has_gamma else torch.empty((1,), device=x.device, dtype=torch.float32) ) partial_dgamma = ( torch.empty((num_groups, D), device=x.device, dtype=torch.float32) if has_gamma else torch.empty((1, 1), device=x.device, dtype=torch.float32) ) _rmsnorm_bwd_dx_partial_dgamma_kernel[(num_groups,)]( dy_2d, x_2d, rstd_1d, gamma_contig, dx_2d, partial_dgamma, dy_2d.stride(0), x_2d.stride(0), dx_2d.stride(0), partial_dgamma.stride(0), M, rows_per_group, D=D, BLOCK_D=block_d, HAS_GAMMA=has_gamma, num_warps=num_warps, ) dgamma: Optional[torch.Tensor] = None if has_gamma: dgamma = torch.empty((D,), device=x.device, dtype=gamma.dtype) _rmsnorm_dgamma_reduce_kernel[(1,)]( partial_dgamma, dgamma, partial_dgamma.stride(0), num_groups, D=D, BLOCK_D=block_d, num_warps=num_warps, ) return dx_2d.reshape(*orig_shape, D), dgamma # Reference PyTorch fallback x32 = x_2d.float() dy32 = dy_2d.float() rstd32 = rstd_1d.unsqueeze(-1) x_hat = x32 * rstd32 if has_gamma: g = dy32 * gamma.float() dgamma = (dy32 * x_hat).sum(dim=0).to(gamma.dtype) else: g = dy32 dgamma = None c = (g * x_hat).mean(dim=-1, keepdim=True) dx_2d = (rstd32 * (g - c * x_hat)).to(x.dtype) return dx_2d.reshape(*orig_shape, D), dgamma # ============================================================================== # COMPONENT 3: CachedFP8Linear (nn.Module + torch.autograd.Function) # ============================================================================== def _scaled_mm_rowwise_or_tensorwise( a_fp8: torch.Tensor, b_fp8_colmajor: torch.Tensor, scale_a: torch.Tensor, scale_b: torch.Tensor, out_dtype: torch.dtype, bias: Optional[torch.Tensor] = None, use_fast_accum: bool = False, ) -> torch.Tensor: """Invoke `torch._scaled_mm` with rowwise/tensorwise scales. `a_fp8`: [M, K] row-major float8_e4m3fn `b_fp8_colmajor`: [K, N] column-major float8_e4m3fn (`stride(0) == 1`) `scale_a`: [M, 1] (rowwise) or [1] (tensorwise) float32 `scale_b`: [1, N] (columnwise of B) or [1] (tensorwise) float32 """ kwargs = { "scale_a": scale_a, "scale_b": scale_b, "out_dtype": out_dtype, "use_fast_accum": use_fast_accum, } if bias is not None: kwargs["bias"] = bias.to(out_dtype) res = torch._scaled_mm(a_fp8, b_fp8_colmajor, **kwargs) # PyTorch < 2.5 returned (out, amax); >= 2.5 returns out directly. if isinstance(res, tuple): return res[0] return res def _shapes_ok_for_scaled_mm(M: int, K: int, N: int) -> bool: return M > 0 and K > 0 and N > 0 and (M % 16 == 0) and (K % 16 == 0) and (N % 16 == 0) class _CachedFP8LinearFunction(torch.autograd.Function): """Autograd function using cached FP8 weights `(w_fp8, w_scale, w_t_fp8, w_t_scale)`. Forward: Y = scaled_mm(X_fp8, W_fp8^T, x_scale, w_scale^T) + bias Backward: dX = scaled_mm(dY_fp8, W_t_fp8^T, dy_scale, w_t_scale^T) dW = dY^T @ X (computed in BF16/input dtype using saved X) db = dY.sum(dim=0) Automatically falls back to BF16 `F.linear` if shapes are not 16-aligned or if `torch._scaled_mm` raises a RuntimeError on `sm_120` scaling constraints. """ @staticmethod def forward( ctx, x: torch.Tensor, weight: torch.Tensor, bias: Optional[torch.Tensor], w_fp8: Optional[torch.Tensor], w_scale: Optional[torch.Tensor], w_t_fp8: Optional[torch.Tensor], w_t_scale: Optional[torch.Tensor], scaling_mode: str, use_fast_accum: bool, ) -> torch.Tensor: orig_shape = x.shape[:-1] K = x.shape[-1] N = weight.shape[0] x_2d = x.reshape(-1, K) M = x_2d.shape[0] out_dtype = x.dtype if x.dtype in (torch.bfloat16, torch.float16) else torch.bfloat16 used_fp8 = False if ( w_fp8 is not None and w_scale is not None and _can_use_fp8(x_2d) and _shapes_ok_for_scaled_mm(M, K, N) and hasattr(torch, "_scaled_mm") ): try: if scaling_mode == "rowwise": x_fp8, x_scale = quantize_rowwise_fp8(x_2d) w_scale_b = w_scale.t() # [1, N] fast_acc = False # rowwise scaled_mm requires use_fast_accum=False else: x_fp8, x_scale = quantize_tensorwise_fp8(x_2d) w_scale_b = w_scale # [1] fast_acc = use_fast_accum # w_fp8 is [N, K] contiguous -> w_fp8.t() is [K, N] column-major y_2d = _scaled_mm_rowwise_or_tensorwise( x_fp8, w_fp8.t(), x_scale, w_scale_b, out_dtype=out_dtype, bias=bias, use_fast_accum=fast_acc, ) used_fp8 = True except (RuntimeError, NotImplementedError): used_fp8 = False if not used_fp8: x_bf16 = x_2d.to(out_dtype) w_bf16 = weight.to(out_dtype) b_bf16 = bias.to(out_dtype) if bias is not None else None y_2d = F.linear(x_bf16, w_bf16, b_bf16) ctx.save_for_backward(x_2d, weight, w_t_fp8, w_t_scale) ctx.has_bias = bias is not None ctx.orig_dtype = x.dtype ctx.scaling_mode = scaling_mode ctx.use_fast_accum = use_fast_accum ctx.used_fp8 = used_fp8 return y_2d.to(x.dtype).reshape(*orig_shape, N) @staticmethod def backward(ctx, grad_output: torch.Tensor): x_2d, weight, w_t_fp8, w_t_scale = ctx.saved_tensors orig_shape = grad_output.shape[:-1] N = grad_output.shape[-1] K = weight.shape[1] dy_2d = grad_output.reshape(-1, N) M = dy_2d.shape[0] comp_dtype = dy_2d.dtype if dy_2d.dtype in (torch.bfloat16, torch.float16) else torch.bfloat16 dx = None if ctx.needs_input_grad[0]: dx_done = False if ( ctx.used_fp8 and w_t_fp8 is not None and w_t_scale is not None and _can_use_fp8(dy_2d) and _shapes_ok_for_scaled_mm(M, N, K) and hasattr(torch, "_scaled_mm") ): try: if ctx.scaling_mode == "rowwise": dy_fp8, dy_scale = quantize_rowwise_fp8(dy_2d) wt_scale_b = w_t_scale.t() # [1, K] fast_acc = False else: dy_fp8, dy_scale = quantize_tensorwise_fp8(dy_2d) wt_scale_b = w_t_scale # [1] fast_acc = ctx.use_fast_accum # w_t_fp8 is [K, N] contiguous -> w_t_fp8.t() is [N, K] column-major dx_2d = _scaled_mm_rowwise_or_tensorwise( dy_fp8, w_t_fp8.t(), dy_scale, wt_scale_b, out_dtype=comp_dtype, bias=None, use_fast_accum=fast_acc, ) dx_done = True except (RuntimeError, NotImplementedError): dx_done = False if not dx_done: dx_2d = torch.matmul(dy_2d.to(comp_dtype), weight.to(comp_dtype)) dx = dx_2d.to(ctx.orig_dtype).reshape(*orig_shape, K) dw = None if ctx.needs_input_grad[1]: dw = torch.matmul(dy_2d.to(comp_dtype).t(), x_2d.to(comp_dtype)).to(weight.dtype) db = None if ctx.has_bias and ctx.needs_input_grad[2]: db = dy_2d.sum(dim=0, dtype=torch.float32).to(weight.dtype) return dx, dw, db, None, None, None, None, None, None class _FusedRMSNormCachedFP8LinearFn(torch.autograd.Function): """End-to-end autograd fusion: `fused_rmsnorm_fp8_quant` -> `CachedFP8Linear`. Avoids materializing a BF16 activation between RMSNorm and `qkv_fg_fused` / `w_gate_up` in the forward pass while preserving exact Triton RMSNorm backward + cached FP8 dX. """ @staticmethod def forward( ctx, x: torch.Tensor, gamma: Optional[torch.Tensor], eps: float, weight: torch.Tensor, bias: Optional[torch.Tensor], w_fp8: Optional[torch.Tensor], w_scale: Optional[torch.Tensor], w_t_fp8: Optional[torch.Tensor], w_t_scale: Optional[torch.Tensor], scaling_mode: str, ) -> torch.Tensor: orig_shape = x.shape[:-1] K = x.shape[-1] N = weight.shape[0] M = x.numel() // K out_dtype = x.dtype if x.dtype in (torch.bfloat16, torch.float16) else torch.bfloat16 need_bf16 = not ( w_fp8 is not None and w_scale is not None and _can_use_fp8(x) and _shapes_ok_for_scaled_mm(M, K, N) and scaling_mode == "rowwise" and hasattr(torch, "_scaled_mm") ) res = fused_rmsnorm_fp8_quant(x, gamma, eps=eps, return_bf16=need_bf16) if need_bf16: y_fp8, y_scale, rstd, y_bf16 = res else: y_fp8, y_scale, rstd = res y_bf16 = None used_fp8 = False if not need_bf16: try: out_2d = _scaled_mm_rowwise_or_tensorwise( y_fp8.reshape(M, K), w_fp8.t(), y_scale.reshape(M, 1), w_scale.t(), out_dtype=out_dtype, bias=bias, use_fast_accum=False, ) used_fp8 = True except (RuntimeError, NotImplementedError): used_fp8 = False if not used_fp8: if y_bf16 is None: y_bf16 = y_fp8.to(out_dtype) * y_scale.to(out_dtype) out_2d = F.linear( y_bf16.reshape(M, K).to(out_dtype), weight.to(out_dtype), bias.to(out_dtype) if bias is not None else None, ) ctx.save_for_backward(x, gamma, rstd, weight, w_t_fp8, w_t_scale) ctx.has_bias = bias is not None ctx.orig_dtype = x.dtype ctx.used_fp8 = used_fp8 return out_2d.to(x.dtype).reshape(*orig_shape, N) @staticmethod def backward(ctx, grad_output: torch.Tensor): x, gamma, rstd, weight, w_t_fp8, w_t_scale = ctx.saved_tensors orig_shape = grad_output.shape[:-1] N = grad_output.shape[-1] K = weight.shape[1] dy_2d = grad_output.reshape(-1, N) M = dy_2d.shape[0] comp_dtype = dy_2d.dtype if dy_2d.dtype in (torch.bfloat16, torch.float16) else torch.bfloat16 # 1. d_norm = dy @ W d_norm_done = False if ( ctx.used_fp8 and w_t_fp8 is not None and w_t_scale is not None and _can_use_fp8(dy_2d) and _shapes_ok_for_scaled_mm(M, N, K) and hasattr(torch, "_scaled_mm") ): try: dy_fp8, dy_scale = quantize_rowwise_fp8(dy_2d) d_norm_2d = _scaled_mm_rowwise_or_tensorwise( dy_fp8, w_t_fp8.t(), dy_scale, w_t_scale.t(), out_dtype=comp_dtype, bias=None, use_fast_accum=False, ) d_norm_done = True except (RuntimeError, NotImplementedError): d_norm_done = False if not d_norm_done: d_norm_2d = torch.matmul(dy_2d.to(comp_dtype), weight.to(comp_dtype)) # 2. Exact single-pass Triton RMSNorm backward dx, dgamma = fused_rmsnorm_bwd(d_norm_2d.reshape(*orig_shape, K), x, rstd, gamma) # 3. dW = dy^T @ y_norm (recompute lightweight y_norm from x, rstd, gamma) dw = None if ctx.needs_input_grad[3]: y_norm = x.reshape(M, K).float() * rstd.reshape(M, 1).float() if gamma is not None: y_norm = y_norm * gamma.float() dw = torch.matmul(dy_2d.to(comp_dtype).t(), y_norm.to(comp_dtype)).to(weight.dtype) db = None if ctx.has_bias and ctx.needs_input_grad[4]: db = dy_2d.sum(dim=0, dtype=torch.float32).to(weight.dtype) return dx, dgamma, None, dw, db, None, None, None, None, None class _FusedSiLUMulCachedFP8DownFn(torch.autograd.Function): """End-to-end autograd fusion: `fused_silu_mul_fp8_quant` -> `CachedFP8Linear` (`w_down`). Eliminates materializing BF16 `silu(gate) * up` [M, 2688] before `w_down` and runs 1-pass `fused_silu_mul_bwd` in backward. """ @staticmethod def forward( ctx, gate_up: torch.Tensor, weight: torch.Tensor, bias: Optional[torch.Tensor], w_fp8: Optional[torch.Tensor], w_scale: Optional[torch.Tensor], w_t_fp8: Optional[torch.Tensor], w_t_scale: Optional[torch.Tensor], scaling_mode: str, ) -> torch.Tensor: orig_shape = gate_up.shape[:-1] K = gate_up.shape[-1] // 2 # 2688 N = weight.shape[0] # 1024 M = gate_up.numel() // (2 * K) out_dtype = gate_up.dtype if gate_up.dtype in (torch.bfloat16, torch.float16) else torch.bfloat16 need_bf16 = not ( w_fp8 is not None and w_scale is not None and _can_use_fp8(gate_up) and _shapes_ok_for_scaled_mm(M, K, N) and scaling_mode == "rowwise" and hasattr(torch, "_scaled_mm") ) res = fused_silu_mul_fp8_quant(gate_up, return_bf16=need_bf16) if need_bf16: mid_fp8, mid_scale, mid_bf16 = res else: mid_fp8, mid_scale = res mid_bf16 = None used_fp8 = False if not need_bf16: try: out_2d = _scaled_mm_rowwise_or_tensorwise( mid_fp8.reshape(M, K), w_fp8.t(), mid_scale.reshape(M, 1), w_scale.t(), out_dtype=out_dtype, bias=bias, use_fast_accum=False, ) used_fp8 = True except (RuntimeError, NotImplementedError): used_fp8 = False if not used_fp8: if mid_bf16 is None: mid_bf16 = mid_fp8.to(out_dtype) * mid_scale.to(out_dtype) out_2d = F.linear( mid_bf16.reshape(M, K).to(out_dtype), weight.to(out_dtype), bias.to(out_dtype) if bias is not None else None, ) ctx.save_for_backward(gate_up, mid_fp8, mid_scale, weight, w_t_fp8, w_t_scale) ctx.has_bias = bias is not None ctx.orig_dtype = gate_up.dtype ctx.used_fp8 = used_fp8 return out_2d.to(gate_up.dtype).reshape(*orig_shape, N) @staticmethod def backward(ctx, grad_output: torch.Tensor): gate_up, mid_fp8, mid_scale, weight, w_t_fp8, w_t_scale = ctx.saved_tensors orig_shape = grad_output.shape[:-1] N = grad_output.shape[-1] K = weight.shape[1] dy_2d = grad_output.reshape(-1, N) M = dy_2d.shape[0] comp_dtype = dy_2d.dtype if dy_2d.dtype in (torch.bfloat16, torch.float16) else torch.bfloat16 # 1. d_mid = dy @ W_down d_mid_done = False if ( ctx.used_fp8 and w_t_fp8 is not None and w_t_scale is not None and _can_use_fp8(dy_2d) and _shapes_ok_for_scaled_mm(M, N, K) and hasattr(torch, "_scaled_mm") ): try: dy_fp8, dy_scale = quantize_rowwise_fp8(dy_2d) d_mid_2d = _scaled_mm_rowwise_or_tensorwise( dy_fp8, w_t_fp8.t(), dy_scale, w_t_scale.t(), out_dtype=comp_dtype, bias=None, use_fast_accum=False, ) d_mid_done = True except (RuntimeError, NotImplementedError): d_mid_done = False if not d_mid_done: d_mid_2d = torch.matmul(dy_2d.to(comp_dtype), weight.to(comp_dtype)) # 2. Single-pass Triton SwiGLU backward d_gate_up = fused_silu_mul_bwd(d_mid_2d.reshape(*orig_shape, K), gate_up) # 3. dW_down = dy^T @ mid (dequantize compact FP8 mid instead of storing BF16 mid) dw = None if ctx.needs_input_grad[1]: mid_deq = mid_fp8.reshape(M, K).to(comp_dtype) * mid_scale.reshape(M, 1).to(comp_dtype) dw = torch.matmul(dy_2d.to(comp_dtype).t(), mid_deq).to(weight.dtype) db = None if ctx.has_bias and ctx.needs_input_grad[2]: db = dy_2d.sum(dim=0, dtype=torch.float32).to(weight.dtype) return d_gate_up, dw, db, None, None, None, None, None class CachedFP8Linear(nn.Module): """Drop-in `nn.Linear` wrapper that caches quantized FP8 weights across recurrent loops. Designed for `shared_core` layers (`qkv_fg_fused`, `out_proj`, `w_gate_up`, `w_down`) that are reused 24-40 loops x 4 grad-accum (~100x) per optimizer step. Caches `(w_fp8, w_scale, w_t_fp8, w_t_scale)` once per optimizer step and invalidates via `invalidate_fp8_cache()` after `optimizer.step()` (with an automatic `_version` guard to prevent stale weights if mutated in-place). """ def __init__( self, in_features: int, out_features: int, bias: bool = False, scaling_mode: str = "rowwise", use_fast_accum: bool = False, enable_fp8: bool = True, device=None, dtype=None, ): super().__init__() if scaling_mode not in ("rowwise", "tensorwise"): raise ValueError(f"scaling_mode must be 'rowwise' or 'tensorwise', got {scaling_mode!r}") self.in_features = in_features self.out_features = out_features self.scaling_mode = scaling_mode self.use_fast_accum = use_fast_accum self.enable_fp8 = enable_fp8 factory_kwargs = {"device": device, "dtype": dtype} self.weight = nn.Parameter(torch.empty((out_features, in_features), **factory_kwargs)) if bias: self.bias = nn.Parameter(torch.empty((out_features,), **factory_kwargs)) else: self.register_parameter("bias", None) # Cached FP8 buffers (non-persistent; rebuilt lazily once per optimizer step) self._w_fp8: Optional[torch.Tensor] = None self._w_scale: Optional[torch.Tensor] = None self._w_t_fp8: Optional[torch.Tensor] = None self._w_t_scale: Optional[torch.Tensor] = None self._cached_weight_version: int = -1 self._cache_hits: int = 0 self._cache_misses: int = 0 self.reset_parameters() def reset_parameters(self) -> None: nn.init.kaiming_uniform_(self.weight, a=5**0.5) if self.bias is not None: fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight) bound = 1.0 / (fan_in**0.5) if fan_in > 0 else 0.0 nn.init.uniform_(self.bias, -bound, bound) self.invalidate_fp8_cache() @classmethod def from_linear( cls, linear: nn.Linear, scaling_mode: str = "rowwise", use_fast_accum: bool = False, enable_fp8: bool = True, ) -> "CachedFP8Linear": """Wrap an existing `nn.Linear` sharing its exact `weight` and `bias` parameters.""" mod = cls.__new__(cls) nn.Module.__init__(mod) mod.in_features = linear.in_features mod.out_features = linear.out_features mod.scaling_mode = scaling_mode mod.use_fast_accum = use_fast_accum mod.enable_fp8 = enable_fp8 mod.weight = linear.weight mod.bias = linear.bias mod._w_fp8 = None mod._w_scale = None mod._w_t_fp8 = None mod._w_t_scale = None mod._cached_weight_version = -1 mod._cache_hits = 0 mod._cache_misses = 0 return mod def invalidate_fp8_cache(self) -> None: """Invalidate cached FP8 weights. Call once after `optimizer.step()`.""" self._w_fp8 = None self._w_scale = None self._w_t_fp8 = None self._w_t_scale = None self._cached_weight_version = -1 def _get_cached_fp8_weights( self, ) -> Tuple[ Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor], ]: if not self.enable_fp8 or not _can_use_fp8(self.weight): return None, None, None, None cur_ver = self.weight._version if self._w_fp8 is not None and self._cached_weight_version == cur_ver: self._cache_hits += 1 return self._w_fp8, self._w_scale, self._w_t_fp8, self._w_t_scale with torch.no_grad(): w = self.weight.detach() w_t = w.t().contiguous() if self.scaling_mode == "rowwise": w_fp8, w_scale = quantize_rowwise_fp8(w) w_t_fp8, w_t_scale = quantize_rowwise_fp8(w_t) else: w_fp8, w_scale = quantize_tensorwise_fp8(w) w_t_fp8, w_t_scale = quantize_tensorwise_fp8(w_t) self._w_fp8 = w_fp8 self._w_scale = w_scale self._w_t_fp8 = w_t_fp8 self._w_t_scale = w_t_scale self._cached_weight_version = cur_ver self._cache_misses += 1 return w_fp8, w_scale, w_t_fp8, w_t_scale def forward(self, x: torch.Tensor) -> torch.Tensor: w_fp8, w_scale, w_t_fp8, w_t_scale = self._get_cached_fp8_weights() return _CachedFP8LinearFunction.apply( x, self.weight, self.bias, w_fp8, w_scale, w_t_fp8, w_t_scale, self.scaling_mode, self.use_fast_accum, ) def forward_from_rmsnorm( self, x: torch.Tensor, gamma: Optional[torch.Tensor] = None, eps: float = DEFAULT_EPS, ) -> torch.Tensor: """Fused `fused_rmsnorm_fp8_quant(x, gamma, eps)` -> `CachedFP8Linear`.""" w_fp8, w_scale, w_t_fp8, w_t_scale = self._get_cached_fp8_weights() return _FusedRMSNormCachedFP8LinearFn.apply( x, gamma, eps, self.weight, self.bias, w_fp8, w_scale, w_t_fp8, w_t_scale, self.scaling_mode, ) def forward_from_swiglu(self, gate_up: torch.Tensor) -> torch.Tensor: """Fused `fused_silu_mul_fp8_quant(gate_up)` -> `CachedFP8Linear` (`w_down`).""" w_fp8, w_scale, w_t_fp8, w_t_scale = self._get_cached_fp8_weights() return _FusedSiLUMulCachedFP8DownFn.apply( gate_up, self.weight, self.bias, w_fp8, w_scale, w_t_fp8, w_t_scale, self.scaling_mode, ) def extra_repr(self) -> str: return ( f"in_features={self.in_features}, out_features={self.out_features}, " f"bias={self.bias is not None}, scaling_mode={self.scaling_mode!r}, " f"enable_fp8={self.enable_fp8}" ) def invalidate_all_fp8_caches(model: nn.Module) -> int: """Invalidate FP8 weight caches on all `CachedFP8Linear` modules in `model`. Call once immediately after `optimizer.step()`. Returns the number of modules invalidated. """ count = 0 for mod in model.modules(): if isinstance(mod, CachedFP8Linear): mod.invalidate_fp8_cache() count += 1 return count def wrap_shared_core_with_cached_fp8( model: nn.Module, target_names: Optional[Iterable[str]] = None, scaling_mode: str = "rowwise", use_fast_accum: bool = False, ) -> int: """Replace targeted `nn.Linear` modules (e.g. `NVFP4_SHARED_CORE_TARGETS`) with `CachedFP8Linear`. Returns the number of wrapped layers. """ target_set = set(target_names) if target_names is not None else None replaced = 0 for full_name, mod in list(model.named_modules()): if not isinstance(mod, nn.Linear): continue if target_set is not None and full_name not in target_set: continue parts = full_name.split(".") parent = model for p in parts[:-1]: parent = getattr(parent, p) setattr( parent, parts[-1], CachedFP8Linear.from_linear( mod, scaling_mode=scaling_mode, use_fast_accum=use_fast_accum, ), ) replaced += 1 return replaced __all__ = [ "D_STREAM", "FFN_HIDDEN", "D_TOTAL", "DEFAULT_EPS", "FP8_E4M3_MAX", "FP8_SCALE_EPS", "quantize_rowwise_fp8", "quantize_tensorwise_fp8", "fused_silu_mul_fp8_quant", "fused_silu_mul_bwd", "fused_rmsnorm_fp8_quant", "fused_rmsnorm_bwd", "CachedFP8Linear", "invalidate_all_fp8_caches", "wrap_shared_core_with_cached_fp8", ] # Register fused_mola_online_merge as torch.library.custom_op for 0-graph-break torch.compile def _mola_online_merge_fwd_dispatch(o_tok, lse_tok, q_normed, k_mem_n, v_mem, beta): B, H, T, D = q_normed.shape M = k_mem_n.shape[1] dt = o_tok.dtype if o_tok.stride(-1) != 1: o_tok = o_tok.contiguous() if q_normed.dtype != dt or q_normed.stride(-1) != 1: q_normed = q_normed.to(dt).contiguous() if k_mem_n.dtype != dt or not k_mem_n.is_contiguous(): k_mem_n = k_mem_n.to(dt).contiguous() if v_mem.dtype != dt or not v_mem.is_contiguous(): v_mem = v_mem.to(dt).contiguous() lse_tok_f32 = lse_tok.detach().float() if lse_tok_f32.stride(-1) != 1: lse_tok_f32 = lse_tok_f32.contiguous() beta_f32 = beta.float().contiguous() out = torch.empty((B, H, T, D), device=o_tok.device, dtype=dt) lse_mem = torch.empty((B, H, T), device=o_tok.device, dtype=torch.float32) BLOCK_T = 64 scale = 1.0 / math.sqrt(D) input_precision = "ieee" if dt == torch.float32 else "tf32" grid = (triton.cdiv(T, BLOCK_T), B * H) _triton_mola_online_merge_fwd[grid]( o_tok, lse_tok_f32, q_normed, k_mem_n, v_mem, beta_f32, out, lse_mem, o_tok.stride(0), o_tok.stride(1), o_tok.stride(2), o_tok.stride(3), lse_tok_f32.stride(0), lse_tok_f32.stride(1), lse_tok_f32.stride(2), q_normed.stride(0), q_normed.stride(1), q_normed.stride(2), q_normed.stride(3), k_mem_n.stride(0), k_mem_n.stride(1), k_mem_n.stride(2), v_mem.stride(0), v_mem.stride(1), v_mem.stride(2), out.stride(0), out.stride(1), out.stride(2), out.stride(3), lse_mem.stride(0), lse_mem.stride(1), lse_mem.stride(2), H, T, SCALE=scale, BLOCK_T=BLOCK_T, HEAD_DIM=D, M_MOLA=M, INPUT_PRECISION=input_precision, num_warps=4, num_stages=2, ) return out, lse_mem def _mola_online_merge_bwd_dispatch(d_out, out, lse_tok, lse_mem, q_normed, k_mem_n, v_mem, beta): B, H, T, D = q_normed.shape M = k_mem_n.shape[1] dt = out.dtype ot_dt, q_dt, km_dt, vm_dt, beta_dt = out.dtype, q_normed.dtype, k_mem_n.dtype, v_mem.dtype, beta.dtype if d_out.dtype != dt or d_out.stride(-1) != 1: d_out = d_out.to(dt).contiguous() if q_normed.dtype != dt or q_normed.stride(-1) != 1: q_normed = q_normed.to(dt).contiguous() if k_mem_n.dtype != dt or not k_mem_n.is_contiguous(): k_mem_n = k_mem_n.to(dt).contiguous() if v_mem.dtype != dt or not v_mem.is_contiguous(): v_mem = v_mem.to(dt).contiguous() lse_tok_f32 = lse_tok.detach().float() if lse_tok_f32.stride(-1) != 1: lse_tok_f32 = lse_tok_f32.contiguous() beta_f32 = beta.float().contiguous() d_o_tok = torch.empty((B, H, T, D), device=d_out.device, dtype=dt) d_q_normed = torch.empty((B, H, T, D), device=d_out.device, dtype=dt) d_k_mem_n = torch.zeros((H, M, D), device=d_out.device, dtype=torch.float32) d_v_mem = torch.zeros((H, M, D), device=d_out.device, dtype=torch.float32) d_beta = torch.zeros((H,), device=d_out.device, dtype=torch.float32) BLOCK_T = 64 scale = 1.0 / math.sqrt(D) input_precision = "ieee" if dt == torch.float32 else "tf32" grid = (triton.cdiv(T, BLOCK_T), B * H) _triton_mola_online_merge_bwd[grid]( d_out, out, lse_tok_f32, lse_mem, q_normed, k_mem_n, v_mem, beta_f32, d_o_tok, d_q_normed, d_k_mem_n, d_v_mem, d_beta, d_out.stride(0), d_out.stride(1), d_out.stride(2), d_out.stride(3), out.stride(0), out.stride(1), out.stride(2), out.stride(3), lse_tok_f32.stride(0), lse_tok_f32.stride(1), lse_tok_f32.stride(2), lse_mem.stride(0), lse_mem.stride(1), lse_mem.stride(2), q_normed.stride(0), q_normed.stride(1), q_normed.stride(2), q_normed.stride(3), k_mem_n.stride(0), k_mem_n.stride(1), k_mem_n.stride(2), v_mem.stride(0), v_mem.stride(1), v_mem.stride(2), d_o_tok.stride(0), d_o_tok.stride(1), d_o_tok.stride(2), d_o_tok.stride(3), d_q_normed.stride(0), d_q_normed.stride(1), d_q_normed.stride(2), d_q_normed.stride(3), d_k_mem_n.stride(0), d_k_mem_n.stride(1), d_k_mem_n.stride(2), d_v_mem.stride(0), d_v_mem.stride(1), d_v_mem.stride(2), H, T, SCALE=scale, BLOCK_T=BLOCK_T, HEAD_DIM=D, M_MOLA=M, INPUT_PRECISION=input_precision, num_warps=4, num_stages=2, ) return d_o_tok.to(ot_dt), d_q_normed.to(q_dt), d_k_mem_n.to(km_dt), d_v_mem.to(vm_dt), d_beta.to(beta_dt) _HAS_MOLA_CUSTOM_OP = False if hasattr(torch, "library") and hasattr(torch.library, "custom_op"): try: @torch.library.custom_op("l2gddr7::mola_online_merge_fwd", mutates_args=()) def _mola_op_fwd( o_tok: torch.Tensor, lse_tok: torch.Tensor, q_normed: torch.Tensor, k_mem_n: torch.Tensor, v_mem: torch.Tensor, beta: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor]: return _mola_online_merge_fwd_dispatch(o_tok, lse_tok, q_normed, k_mem_n, v_mem, beta) @_mola_op_fwd.register_fake def _mola_op_fwd_fake(o_tok, lse_tok, q_normed, k_mem_n, v_mem, beta): B, H, T, D = o_tok.shape return ( o_tok.new_empty((B, H, T, D)), torch.empty((B, H, T), device=o_tok.device, dtype=torch.float32), ) @torch.library.custom_op("l2gddr7::mola_online_merge_bwd", mutates_args=()) def _mola_op_bwd( d_out: torch.Tensor, out: torch.Tensor, lse_tok: torch.Tensor, lse_mem: torch.Tensor, q_normed: torch.Tensor, k_mem_n: torch.Tensor, v_mem: torch.Tensor, beta: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: return _mola_online_merge_bwd_dispatch( d_out, out, lse_tok, lse_mem, q_normed, k_mem_n, v_mem, beta ) @_mola_op_bwd.register_fake def _mola_op_bwd_fake(d_out, out, lse_tok, lse_mem, q_normed, k_mem_n, v_mem, beta): return ( out.new_empty(out.shape), q_normed.new_empty(q_normed.shape), k_mem_n.new_empty(k_mem_n.shape), v_mem.new_empty(v_mem.shape), beta.new_empty(beta.shape), ) def _mola_setup_ctx(ctx, inputs, output): o_tok, lse_tok, q_normed, k_mem_n, v_mem, beta = inputs out, lse_mem = output ctx.save_for_backward(out, lse_tok, lse_mem, q_normed, k_mem_n, v_mem, beta) def _mola_backward(ctx, d_out, _d_lse_mem): out, lse_tok, lse_mem, q_normed, k_mem_n, v_mem, beta = ctx.saved_tensors d_o_tok, d_q, d_km, d_vm, d_beta = _mola_op_bwd( d_out, out, lse_tok, lse_mem, q_normed, k_mem_n, v_mem, beta ) return d_o_tok, None, d_q, d_km, d_vm, d_beta _mola_op_fwd.register_autograd(_mola_backward, setup_context=_mola_setup_ctx) _HAS_MOLA_CUSTOM_OP = True except Exception: _HAS_MOLA_CUSTOM_OP = False class GDDR7SparseTable: """Direct-on-CUDA FP8 E4M3 (per-row FP32 w_scale + Philox SR) or BF16 sparse table + INT8 m + Row-Wise FP32 v_row (~2.05 B/param in FP8, ~3.0 B/param in BF16).""" _compiled_rowv_fn = None def __init__(self, name, n_rows, dim, device, init_std=0.02): self.name = name self.n_rows = n_rows self.dim = dim self.device = device fp8_dt = getattr(torch, "float8_e4m3fn", None) self.use_fp8 = bool(SPARSE_TABLE_USE_FP8 and fp8_dt is not None and device.type == "cuda") self._fp8_dtype = fp8_dt if self.use_fp8: self.weight = torch.empty((n_rows, dim), device=device, dtype=fp8_dt) self.w_scale = torch.empty((n_rows,), device=device, dtype=torch.float32) chunk = 524_288 for r0 in range(0, n_rows, chunk): r1 = min(n_rows, r0 + chunk) tmp = torch.empty((r1 - r0, dim), device=device, dtype=torch.float32).normal_(0.0, init_std) sc = (tmp.abs().amax(dim=-1) / FP8_E4M3_MAX).clamp_min(1e-12) self.weight[r0:r1].copy_((tmp / sc.unsqueeze(-1)).clamp(-FP8_E4M3_MAX, FP8_E4M3_MAX).to(fp8_dt)) self.w_scale[r0:r1].copy_(sc) else: self.weight = torch.empty((n_rows, dim), device=device, dtype=torch.bfloat16) self.w_scale = torch.ones((n_rows,), device=device, dtype=torch.float32) chunk = 1_048_576 for r0 in range(0, n_rows, chunk): r1 = min(n_rows, r0 + chunk) self.weight[r0:r1].normal_(0.0, init_std) self.q_m = torch.zeros((n_rows, dim), device=device, dtype=torch.int8) self.m_scale = torch.zeros((n_rows,), device=device, dtype=torch.float32) self.v_row = torch.zeros((n_rows,), device=device, dtype=torch.float32) self.step_count = torch.zeros((n_rows,), device=device, dtype=torch.int32) self.grad_buffer = [] self.visited_mask = torch.zeros((n_rows,), device=device, dtype=torch.bool) self.last_unique_count = 0 self.last_grad_norm = 0.0 self.last_dead_slot_frac = 0.0 self._pending_grad_norm_t = None self._pending_dead_slot_t = None use_comp = USE_TORCH_COMPILE and device.type == "cuda" and hasattr(torch, "compile") if GDDR7SparseTable._compiled_rowv_fn is None: GDDR7SparseTable._compiled_rowv_fn = ( torch.compile(_sparse_adam_math_rowwise_v, mode="default", dynamic=True) if use_comp else _sparse_adam_math_rowwise_v ) self._update_fn = GDDR7SparseTable._compiled_rowv_fn def memory_bytes(self): w_b = 1 if self.use_fp8 else 2 return ( self.weight.numel() * w_b + self.q_m.numel() * 1 + (self.w_scale.numel() * 4 if self.use_fp8 else 0) + self.m_scale.numel() * 4 + self.v_row.numel() * 4 + self.step_count.numel() * 4 ) def lookup(self, indices): orig_shape = indices.shape flat_idx = indices.reshape(-1) if not torch.is_grad_enabled(): return _sparse_plain_lookup_impl( self.weight, self.w_scale, flat_idx, self.use_fp8 ).view(*orig_shape, self.dim) grad_hook = torch.empty(0, device=self.weight.device, requires_grad=True) out = CoalescedSparseGatherFunction.apply( self.weight, self.w_scale, flat_idx, self.grad_buffer, grad_hook, self.use_fp8 ) return out.view(*orig_shape, self.dim) def finalize_telemetry(self): """Read deferred 0-D GPU telemetry tensors to Python floats after stream sync.""" if self._pending_grad_norm_t is not None: self.last_grad_norm = float(self._pending_grad_norm_t.item()) self._pending_grad_norm_t = None if self._pending_dead_slot_t is not None: self.last_dead_slot_frac = float(self._pending_dead_slot_t.item()) self._pending_dead_slot_t = None @torch.no_grad() def sparse_adam_step( self, lr, betas=(0.9, 0.98), eps=1e-6, collect_telemetry=False, defer_telemetry=False ): if not self.grad_buffer: if collect_telemetry: self.last_unique_count = 0 self.last_grad_norm = 0.0 self.last_dead_slot_frac = 0.0 self._pending_grad_norm_t = None self._pending_dead_slot_t = None return u_idx, g_sum = coalesce_compact_sparse_grads( self.grad_buffer, self.dim, device=self.device ) self.grad_buffer.clear() self.visited_mask[u_idx] = True grad_norm_t = g_sum.norm() max_sparse_norm = MAX_GRAD_NORM * 10.0 g_sum.mul_((max_sparse_norm / (grad_norm_t + 1e-6)).clamp(max=1.0)) b1, b2 = betas n_unique = u_idx.numel() if _HAS_TRITON and self.device.type == "cuda" and (self.dim & (self.dim - 1)) == 0: self._triton_seed = getattr(self, "_triton_seed", 0) + 1 _triton_sparse_adam_rowv_kernel[(n_unique,)]( self.weight, self.w_scale, self.q_m, self.m_scale, self.v_row, self.step_count, u_idx, g_sum.contiguous(), float(lr), float(b1), float(b2), math.log(b1), math.log(b2), float(eps), int(self._triton_seed), n_unique, D=self.dim, STORE_FP8=self.use_fp8, num_warps=4 if self.dim <= 128 else 8, ) else: self.step_count.index_add_(0, u_idx, torch.ones_like(u_idx, dtype=torch.int32)) lr_t = torch.tensor(lr, device=self.device, dtype=torch.float32) for c0 in range(0, n_unique, SPARSE_OPT_CHUNK): c1 = min(n_unique, c0 + SPARSE_OPT_CHUNK) idx_c = u_idx[c0:c1] g_c = g_sum[c0:c1] m_prev = ( self.q_m.index_select(0, idx_c).float() * self.m_scale.index_select(0, idx_c).unsqueeze(-1) ) v_row_prev = self.v_row.index_select(0, idx_c) row_counts = self.step_count.index_select(0, idx_c).float().unsqueeze(-1) w_active = self.weight.index_select(0, idx_c).float() if self.use_fp8: w_active = w_active * self.w_scale.index_select(0, idx_c).unsqueeze(-1) w_bf16, qm_new, m_sc, v_row_new = self._update_fn( w_active, g_c, m_prev, v_row_prev, row_counts, lr_t, b1, b2, eps ) if self.use_fp8: w_f = w_bf16.float() w_sc = (w_f.abs().amax(dim=-1) / FP8_E4M3_MAX).clamp_min(1e-12) self.weight.index_copy_( 0, idx_c, (w_f / w_sc.unsqueeze(-1)).clamp(-FP8_E4M3_MAX, FP8_E4M3_MAX).to(self._fp8_dtype) ) self.w_scale.index_copy_(0, idx_c, w_sc) else: self.weight.index_copy_(0, idx_c, w_bf16) self.q_m.index_copy_(0, idx_c, qm_new) self.m_scale.index_copy_(0, idx_c, m_sc) self.v_row.index_copy_(0, idx_c, v_row_new) if collect_telemetry: self.last_unique_count = int(n_unique) dead_t = (self.w_scale[u_idx] < 1e-4).float().mean() if self.use_fp8 else None if defer_telemetry: self._pending_grad_norm_t = grad_norm_t self._pending_dead_slot_t = dead_t else: self.last_grad_norm = float(grad_norm_t.item()) self.last_dead_slot_frac = float(dead_t.item()) if dead_t is not None else 0.0 # ============================ TIER 1 GDDR7: LAYER-2 DEEPSEEK ENGRAM (ASYNC) class EngramConditionalMemory(nn.Module): """DeepSeek Engram (arXiv:2601.07372) placed strictly after Prelude Loop 2, with async CUDA stream prefetch to hide GDDR7 lookup latency behind Prelude. """ def __init__(self, canonical_map, cfg, device, rank=0, world_size=1): super().__init__() self.register_buffer("canonical_map", canonical_map, persistent=False) self.rank = int(rank) self.world_size = int(world_size) self.n_heads = cfg["engram_heads"] assert self.n_heads % self.world_size == 0, ( f"engram_heads ({self.n_heads}) must be divisible by world_size ({self.world_size})" ) self.local_heads = self.n_heads // self.world_size self.head_start = self.rank * self.local_heads self.head_end = self.head_start + self.local_heads self.rows_per_head = cfg["engram_rows_per_head"] self.head_dim = cfg["engram_dim"] self.local_row_offset = self.head_start * self.rows_per_head total_rows = self.local_heads * self.rows_per_head primes = torch.tensor( [ [1000003, 1000033, 1], [1000037, 1000039, 1], [1000081, 1000099, 1], [1000117, 1000121, 1], [1000133, 1000151, 1000159], [1000171, 1000183, 1000187], [1000193, 1000199, 1000211], [1000213, 1000231, 1000249], ], device=device, dtype=torch.long, )[: self.n_heads] self.register_buffer("primes", primes, persistent=False) trigram_mask = ( torch.arange(self.n_heads, device=device, dtype=torch.long) >= (self.n_heads // 2) ).to(torch.long) self.register_buffer("trigram_mask", trigram_mask, persistent=False) head_offsets = ( torch.arange(self.n_heads, device=device, dtype=torch.long) * self.rows_per_head ) self.register_buffer("head_offsets", head_offsets, persistent=False) self.sparse_table = GDDR7SparseTable( "Engram_Ngram_Table", total_rows, self.head_dim, device=device, init_std=1.0 / math.sqrt(D_STREAM), ) self.norm_q = nn.Parameter(torch.ones(D_STREAM)) self.norm_k = nn.Parameter(torch.ones(D_STREAM)) self.norm_v = nn.Parameter(torch.ones(D_STREAM)) self.w_eng = nn.Linear(D_STREAM, D_STREAM, bias=False) nn.init.zeros_(self.w_eng.weight) self._gate_and_project_compiled = None self.collect_telemetry = False self.last_gate_mean = 0.0 self.last_gate_std = 0.0 def compute_ngram_indices(self, token_ids): c0 = self.canonical_map[token_ids.clamp(0, self.canonical_map.numel() - 1)] c_prev1 = F.pad(c0[:, :-1], (1, 0), value=0) c_prev2 = F.pad(c0[:, :-2], (2, 0), value=0) p0 = self.primes[:, 0].view(1, 1, -1) p1 = self.primes[:, 1].view(1, 1, -1) p2 = self.primes[:, 2].view(1, 1, -1) tri = self.trigram_mask.view(1, 1, -1) raw = (c0.unsqueeze(-1) * p0) ^ (c_prev1.unsqueeze(-1) * p1) raw = raw ^ ((c_prev2.unsqueeze(-1) * p2) * tri) return (raw.abs() % self.rows_per_head) + self.head_offsets.view(1, 1, -1) def prefetch_embeddings(self, token_ids): """Launchable on a separate CUDA stream before Prelude Loop 1. When world_size > 1, shards Engram's 8 heads evenly across ranks via differentiable all_to_all. """ indices = self.compute_ngram_indices(token_ids) if self.world_size == 1 or not dist_is_active(): retrieved = self.sparse_table.lookup(indices) return retrieved.reshape(token_ids.size(0), token_ids.size(1), D_STREAM) B, T = token_ids.shape all_idx = torch.empty((self.world_size, B, T, self.n_heads), device=indices.device, dtype=indices.dtype) dist.all_gather_into_tensor(all_idx, indices.contiguous()) local_idx = all_idx[..., self.head_start : self.head_end] - self.local_row_offset local_emb = self.sparse_table.lookup(local_idx) # [W, B, T, local_heads, head_dim] gathered_emb = _DistAllToAllFn.apply(local_emb) # [W, B, T, local_heads, head_dim] -> rank r's batch across all W head shards return gathered_emb.permute(1, 2, 0, 3, 4).reshape(B, T, D_STREAM) def _gate_and_project(self, x1_ctx, e_t): dt = self.w_eng.weight.dtype q_normed = rms_norm(x1_ctx, self.norm_q) k_normed = rms_norm(e_t, self.norm_k) gate_logits = (q_normed.float() * k_normed.float()).sum( dim=-1, keepdim=True ) / math.sqrt(D_STREAM) gate = torch.sigmoid(gate_logits).to(dt) gated_val = gate * rms_norm(e_t, self.norm_v, out_dtype=dt) if self.training and ENGRAM_DROPOUT > 0.0: gated_val = F.dropout(gated_val, p=ENGRAM_DROPOUT, training=True) return x1_ctx + self.w_eng(gated_val).to(x1_ctx.dtype), gate def apply_prefetched(self, x1_ctx, e_t): fn = ( self._gate_and_project_compiled if (self.training and self._gate_and_project_compiled is not None) else self._gate_and_project ) out, gate = fn(x1_ctx, e_t) if self.collect_telemetry: with torch.no_grad(): self.last_gate_mean = float(gate.mean().item()) self.last_gate_std = float(gate.std().item()) return out def forward(self, x1_ctx, token_ids): e_t = self.prefetch_embeddings(token_ids) return self.apply_prefetched(x1_ctx, e_t) # =================== TIER 2 GDDR7: TOKEN-SPARSE MULTI-HOP ULTRAMEMV2 TDQKR class UltraMemV2TDQKRBridge(nn.Module): """Shared UltraMemV2 (arXiv:2508.18756) + Memory+ router/table supporting flat token-sparse multi-hop lookups `[N_sel, D_STREAM]` from the Shared Core FFN. """ def __init__(self, cfg, device, rank=0, world_size=1): super().__init__() self.rank = int(rank) self.world_size = int(world_size) self.n_heads = cfg["ultramem_heads"] self.grid_k = cfg["ultramem_k"] self.slots_per_head = self.grid_k * self.grid_k self.total_slots = self.n_heads * self.slots_per_head shard_size = (self.total_slots + self.world_size - 1) // self.world_size self.shard_start = self.rank * shard_size self.shard_end = min(self.total_slots, self.shard_start + shard_size) self.local_slots = max(1, self.shard_end - self.shard_start) self.dv = cfg["ultramem_dv"] self.rank = cfg["ultramem_tucker_rank"] self.cand_k0 = cfg["ultramem_cand_k0"] self.topk = cfg["ultramem_topk"] self.dk = HEAD_DIM q_out_dim = self.n_heads * self.rank * self.dk self.w_q_row = nn.Linear(D_STREAM, q_out_dim, bias=False) self.w_q_col = nn.Linear(D_STREAM, q_out_dim, bias=False) self.k_row = nn.Parameter( torch.randn(self.n_heads, self.grid_k, self.dk) * (self.dk ** -0.5) ) self.k_col = nn.Parameter( torch.randn(self.n_heads, self.grid_k, self.dk) * (self.dk ** -0.5) ) eye_r = torch.eye(self.rank).unsqueeze(0).repeat(self.n_heads, 1, 1) self.tucker_core = nn.Parameter(eye_r + 0.05 * torch.randn_like(eye_r)) self.log_temp = nn.Parameter(torch.zeros(self.n_heads)) self.sparse_table = GDDR7SparseTable( "UltraMemV2_TDQKR_Table", self.local_slots, self.dv, device=device, init_std=1.0 / math.sqrt(self.dv), ) head_offsets = ( torch.arange(self.n_heads, device=device, dtype=torch.long) * self.slots_per_head ) self.register_buffer("head_offsets", head_offsets, persistent=False) key_head_offsets = ( torch.arange(self.n_heads, device=device, dtype=torch.long) * self.grid_k ) self.register_buffer("key_head_offsets", key_head_offsets, persistent=False) self.pre_norm = nn.Parameter(torch.ones(D_STREAM)) self.post_norm = nn.Parameter(torch.ones(D_STREAM)) self.w_gate = nn.Linear(D_STREAM, self.dv, bias=False) self.w_ive = nn.Linear(self.dv, D_STREAM, bias=False) nn.init.zeros_(self.w_ive.weight) # zero Step-1 noise (matches Engram.w_eng!) # Floored positive scale in [0.08, 0.50] (starts ~0.15, zero WD, cannot collapse to 0.009!) self.bridge_scale_logit = nn.Parameter(torch.tensor(-1.60, dtype=torch.float32)) # DeepSeek-V3 Auxiliary-Loss-Free Top-k0 Bias + EMA Query Mean-Centering self.register_buffer("b_row", torch.zeros(self.n_heads, self.grid_k, device=device, dtype=torch.float32)) self.register_buffer("b_col", torch.zeros(self.n_heads, self.grid_k, device=device, dtype=torch.float32)) self.register_buffer("ema_qr_mean", torch.zeros(self.n_heads, self.dk, device=device, dtype=torch.float32)) self.register_buffer("ema_qc_mean", torch.zeros(self.n_heads, self.dk, device=device, dtype=torch.float32)) self.register_buffer("step_c_row", torch.zeros(self.n_heads, self.grid_k, device=device, dtype=torch.float32), persistent=False) self.register_buffer("step_c_col", torch.zeros(self.n_heads, self.grid_k, device=device, dtype=torch.float32), persistent=False) self.register_buffer("step_q_sum_r", torch.zeros(self.n_heads, self.dk, device=device, dtype=torch.float32), persistent=False) self.register_buffer("step_q_sum_c", torch.zeros(self.n_heads, self.dk, device=device, dtype=torch.float32), persistent=False) self.step_tok_count = 0 self._route_flat_compiled = None self._proj_flat_compiled = None self.collect_telemetry = False self.last_entropy_norm = 0.0 self.last_max_load_ratio = 1.0 self.last_bridge_rms_ratio = 0.0 @property def bridge_scale(self): return 0.08 + 0.42 * torch.sigmoid(self.bridge_scale_logit) def _route_and_score_flat(self, x_flat): """Auxiliary-loss-free TDQKR routing with EMA query centering & re-normed mean-rank.""" N, _ = x_flat.shape H, R, K, Dk = self.n_heads, self.rank, self.grid_k, self.dk dt = self.w_gate.weight.dtype h = rms_norm(x_flat, self.pre_norm, out_dtype=dt) qr_raw = self.w_q_row(h.to(self.w_q_row.weight.dtype)).view(N, H, R, Dk) qc_raw = self.w_q_col(h.to(self.w_q_col.weight.dtype)).view(N, H, R, Dk) qr = l2_norm(qr_raw).to(dt) qc = l2_norm(qc_raw).to(dt) kr = l2_norm(self.k_row - self.k_row.mean(dim=1, keepdim=True)).to(dt) # centered keys defeat cone collapse kc = l2_norm(self.k_col - self.k_col.mean(dim=1, keepdim=True)).to(dt) # Re-normalized, EMA-centered mean-rank query defeats MoD top-12.5% cone collapse! qr_mean_raw = qr.mean(dim=-2).transpose(0, 1).float() # [H, N, Dk] qc_mean_raw = qc.mean(dim=-2).transpose(0, 1).float() qr_m = l2_norm(qr_mean_raw - self.ema_qr_mean.unsqueeze(1)).to(dt) qc_m = l2_norm(qc_mean_raw - self.ema_qc_mean.unsqueeze(1)).to(dt) s_row_mean = torch.bmm(qr_m, kr.transpose(-1, -2)).transpose(0, 1) # [N, H, K] s_col_mean = torch.bmm(qc_m, kc.transpose(-1, -2)).transpose(0, 1) k0 = min(self.cand_k0, K) # Biased candidate selection (loss-free load balance), unbiased Tucker scoring! _, idx_r = torch.topk(s_row_mean.float() + self.b_row.unsqueeze(0), k=k0, dim=-1) _, idx_c = torch.topk(s_col_mean.float() + self.b_col.unsqueeze(0), k=k0, dim=-1) h_key_off = self.key_head_offsets.view(1, H, 1) kr_sub = F.embedding( (idx_r + h_key_off).reshape(-1), kr.reshape(H * K, Dk) ).view(N, H, k0, Dk) kc_sub = F.embedding( (idx_c + h_key_off).reshape(-1), kc.reshape(H * K, Dk) ).view(N, H, k0, Dk) sr_sub = torch.matmul(qr, kr_sub.transpose(-1, -2)).float() # [N, H, R, k0] sc_sub = torch.matmul(qc, kc_sub.transpose(-1, -2)).float() return h, sr_sub, sc_sub, idx_r, idx_c, qr_mean_raw, qc_mean_raw def _gate_and_project_flat(self, h, v_agg): gated_v = v_agg * F.silu(self.w_gate(h)) return rms_norm(self.w_ive(gated_v), self.post_norm) def forward_flat(self, x_flat): route_fn = ( self._route_flat_compiled if (self.training and self._route_flat_compiled is not None) else self._route_and_score_flat ) h, sr_sub, sc_sub, idx_r, idx_c, qr_mean_raw, qc_mean_raw = route_fn(x_flat) # Custom Triton Kernel 2: in-register 32x32 Tucker scoring + top-16 + softmax (zero 33.5 MiB grid!) inv_temp = (1.0 / torch.exp(self.log_temp).clamp(0.05, 10.0)).view(1, self.n_heads, 1).float() _, sub_r, sub_c, weights_f32 = fused_tdqkr_tucker_topk( sr_sub, sc_sub, self.tucker_core.float(), inv_temp, topk=self.topk ) real_r = torch.gather(idx_r, dim=-1, index=sub_r) real_c = torch.gather(idx_c, dim=-1, index=sub_c) global_slots = real_r * self.grid_k + real_c + self.head_offsets.view(1, self.n_heads, 1) weights = weights_f32.to(h.dtype) # Accumulate top-k0 counts only on grad-enabled loops (skip no_grad TBPTT iters!) if self.training and torch.is_grad_enabled(): with torch.no_grad(): H = self.n_heads ir = idx_r.permute(1, 0, 2).reshape(H, -1) ic = idx_c.permute(1, 0, 2).reshape(H, -1) ones = torch.ones_like(ir, dtype=torch.float32) self.step_c_row.scatter_add_(1, ir, ones) self.step_c_col.scatter_add_(1, ic, ones) self.step_q_sum_r.add_(qr_mean_raw.sum(dim=1)) self.step_q_sum_c.add_(qc_mean_raw.sum(dim=1)) self.step_tok_count += x_flat.size(0) # Custom Triton Kernel 1: 1-pass int64-safe gather + weighted sum (1-GPU local or W-GPU row-sharded exact!) if self.world_size == 1 or not dist_is_active(): v_agg = fused_ultramem_gather_reduce( self.sparse_table.weight, global_slots, weights, self.sparse_table.grad_buffer if torch.is_grad_enabled() else None, w_scale=(self.sparse_table.w_scale if self.sparse_table.use_fp8 else None), ) else: N_loc = global_slots.size(0) all_slots = torch.empty( (self.world_size, *global_slots.shape), device=global_slots.device, dtype=global_slots.dtype, ) dist.all_gather_into_tensor(all_slots, global_slots.contiguous()) all_weights = _DistAllGatherFn.apply(weights) in_shard = (all_slots >= self.shard_start) & (all_slots < self.shard_end) local_slots = (all_slots - self.shard_start).clamp(0, self.local_slots - 1) local_weights = all_weights * in_shard.to(all_weights.dtype) v_partial_flat = fused_ultramem_gather_reduce( self.sparse_table.weight, local_slots.reshape(self.world_size * N_loc, self.n_heads, self.topk), local_weights.reshape(self.world_size * N_loc, self.n_heads, self.topk), self.sparse_table.grad_buffer if torch.is_grad_enabled() else None, w_scale=(self.sparse_table.w_scale if self.sparse_table.use_fp8 else None), ) v_agg = _DistReduceScatterSumFn.apply(v_partial_flat.view(self.world_size, N_loc, self.dv)) proj_fn = ( self._proj_flat_compiled if (self.training and self._proj_flat_compiled is not None) else self._gate_and_project_flat ) return proj_fn(h, v_agg), None @torch.no_grad() def update_routing_bias_and_ema(self, gamma=ULTRAMEM_BIAS_GAMMA, collect_telemetry=False): """Step-end DeepSeek-V3 loss-free top-k0 bias + EMA query centering update.""" if self.step_tok_count == 0: return tok_count_eff = float(self.step_tok_count) if self.world_size > 1 and dist_is_active(): dist.all_reduce(self.step_c_row, op=dist.ReduceOp.SUM) dist.all_reduce(self.step_c_col, op=dist.ReduceOp.SUM) dist.all_reduce(self.step_q_sum_r, op=dist.ReduceOp.SUM) dist.all_reduce(self.step_q_sum_c, op=dist.ReduceOp.SUM) tok_count_eff *= float(self.world_size) if gamma > 0.0: avg_r = self.step_c_row.mean(dim=-1, keepdim=True) avg_c = self.step_c_col.mean(dim=-1, keepdim=True) # Asymmetric overload pushback (-5x max on hot keys, gentle +1x on cold keys, [-1.5, 1.5] range) ratio_r = self.step_c_row / (avg_r + 1e-6) ratio_c = self.step_c_col / (avg_c + 1e-6) delta_r = torch.where(ratio_r > 1.0, -(ratio_r - 1.0).clamp(max=5.0), 1.0 - ratio_r) delta_c = torch.where(ratio_c > 1.0, -(ratio_c - 1.0).clamp(max=5.0), 1.0 - ratio_c) self.b_row.add_(gamma * delta_r) self.b_col.add_(gamma * delta_c) self.b_row.sub_(self.b_row.mean(dim=-1, keepdim=True)) self.b_col.sub_(self.b_col.mean(dim=-1, keepdim=True)) self.b_row.clamp_(-1.5, 1.5) self.b_col.clamp_(-1.5, 1.5) if gamma > 0.0: q_mean_r = self.step_q_sum_r / tok_count_eff q_mean_c = self.step_q_sum_c / tok_count_eff self.ema_qr_mean.lerp_(q_mean_r, 0.05) self.ema_qc_mean.lerp_(q_mean_c, 0.05) if collect_telemetry: p_r = self.step_c_row / self.step_c_row.sum(dim=-1, keepdim=True).clamp_min(1.0) p_c = self.step_c_col / self.step_c_col.sum(dim=-1, keepdim=True).clamp_min(1.0) p_avg = 0.5 * (p_r + p_c).clamp_min(1e-12) ent = -(p_avg * p_avg.log()).sum(dim=-1).mean().item() self.last_entropy_norm = float(ent / math.log(self.grid_k)) self.last_max_load_ratio = float( max(p_r.max().item(), p_c.max().item()) * self.grid_k ) self.step_c_row.zero_() self.step_c_col.zero_() self.step_q_sum_r.zero_() self.step_q_sum_c.zero_() self.step_tok_count = 0 # =========================== ON-CHIP L2 BLOCK: GDN-2 + SWA FLEX + MOLA + FFN class CausalConv1dSiLU(nn.Module): """Uses fla.modules.ShortConvolution (zero-transpose Triton conv+SiLU) when available.""" def __init__(self, dim, kernel_size=GDN_CONV_KERNEL): super().__init__() self.dim = dim self.kernel_size = kernel_size if _HAS_FLA_CONV: self.short_conv = _FLAShortConv( hidden_size=dim, kernel_size=kernel_size, bias=False, activation="silu" ) self.weight = None else: self.short_conv = None self.weight = nn.Parameter(torch.empty(dim, 1, kernel_size)) nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) def forward(self, x): if self.short_conv is not None and x.is_cuda: res = self.short_conv(x.to(self.short_conv.weight.dtype)) out = res[0] if isinstance(res, tuple) else res return out.to(x.dtype) w = self.short_conv.weight if self.short_conv is not None else self.weight xt = F.pad(x.transpose(1, 2), (self.kernel_size - 1, 0)) out = F.conv1d(xt, w.to(xt.dtype), bias=None, groups=self.dim) return F.silu(out.transpose(1, 2)) class SWGDN2LocalSWA(nn.Module): """Exact SWGDN2-G1 Pseudo-Query-Driven Sliding-Window Attention (Song & Chen, arXiv:2611.33257 Eq. 7-8). Replaces fixed-coefficient ShortConv1d(W=4)+SiLU before GDN-2 recurrence with content- & relative-offset-adaptive W=4 SWA using learned per-branch pseudo-queries (Q, K, V), RMSNorm, and exact relative-offset RoPE: (RoPE(p^X, t))^T RoPE(k_i, i) == (RoPE(p^X, t - i))^T k_i for delta = t - i in {0..W-1}. """ def __init__(self, n_heads, head_dim=HEAD_DIM, window_size=GDN_CONV_KERNEL): super().__init__() self.n_heads = int(n_heads) self.head_dim = int(head_dim) self.window_size = int(window_size) # 3 branches (Q, K, V), G=1 group per head -> [3, H, D] self.pseudo_q = nn.Parameter( torch.randn(3, self.n_heads, self.head_dim) * (self.head_dim ** -0.5) ) self.p_norm = nn.Parameter(torch.ones(self.head_dim)) self.k_norm = nn.Parameter(torch.ones(self.head_dim)) half = self.head_dim // 2 inv_freq = ROPE_BASE ** (-torch.arange(half, dtype=torch.float32) / half) deltas = torch.arange(self.window_size, dtype=torch.float32) # [W] = {0, 1, 2, 3} angles = torch.outer(deltas, inv_freq) # [W, D/2] self.register_buffer("rel_cos", torch.cos(angles), persistent=False) self.register_buffer("rel_sin", torch.sin(angles), persistent=False) def _rotate_pseudo_q(self, p_n): # p_n: [3, H, D] -> p_rot: [3, W, H, D] for relative offsets delta in {0..W-1} half = self.head_dim // 2 p0 = p_n[..., :half].unsqueeze(1) # [3, 1, H, D/2] p1 = p_n[..., half:].unsqueeze(1) c = self.rel_cos.to(p_n.dtype).view(1, self.window_size, 1, half) s = self.rel_sin.to(p_n.dtype).view(1, self.window_size, 1, half) return torch.cat([p0 * c - p1 * s, p0 * s + p1 * c], dim=-1) def forward(self, g_qkv): B, T, _ = g_qkv.shape H, D, W = self.n_heads, self.head_dim, self.window_size dt = g_qkv.dtype q, k, v = g_qkv.view(B, T, 3, H, D).unbind(dim=2) # each [B, T, H, D] # Eq. (7): RMSNorm + relative-RoPE scoring on projected keys k for all 3 branches p_n = rms_norm(self.pseudo_q, self.p_norm, out_dtype=dt) # [3, H, D] k_n = rms_norm(k, self.k_norm, out_dtype=dt) # [B, T, H, D] p_rot = self._rotate_pseudo_q(p_n) # [3, W, H, D] # 1-pass Triton SWGDN2-G1 (registered as custom_op -> 0 graph breaks, eliminates ~600 MiB F.pad traffic!) return fused_swgdn2_local_swa(q, k, v, k_n, p_rot) class GatedDeltaNet2(nn.Module): """Per-head scalar-decay GDN-2 with fused 3x depthwise conv, in-kernel FLA (L2Norm + gate + beta-sigmoid, scale=1.0, no double-gating), and Chunk-64 block-Schur WY fallback. """ def __init__(self, stable_symmetric=True, use_fla=USE_FLA_GDN, n_heads=N_HEADS): super().__init__() self.use_fla = bool(use_fla and _HAS_FLA and (not stable_symmetric)) self.stable_symmetric = stable_symmetric self.n_heads = int(n_heads) self.attn_dim = self.n_heads * HEAD_DIM # SWGDN2-G1 (arXiv:2611.33257 Eq. 7-8): intra-SWA (W=4) replacing fixed ShortConv1d self.local_swa = SWGDN2LocalSWA(self.n_heads, head_dim=HEAD_DIM, window_size=GDN_CONV_KERNEL) self.f_proj_out = nn.Linear(HEAD_DIM, self.n_heads, bias=False) a_init = torch.empty(self.n_heads, dtype=torch.float32).uniform_(1.0, 16.0) self.A_log = nn.Parameter(torch.log(a_init)) dt = torch.exp( torch.empty(self.n_heads, dtype=torch.float32).uniform_( math.log(1e-3), math.log(0.1) ) ) self.dt_bias = nn.Parameter(dt + torch.log(-torch.expm1(-dt))) self.b_proj = nn.Linear( D_STREAM, self.n_heads if self.use_fla else self.attn_dim, bias=False ) self.w_proj = None if self.use_fla else nn.Linear(D_STREAM, self.attn_dim, bias=False) self.g_proj_out = nn.Linear(HEAD_DIM, self.attn_dim, bias=True) self.o_norm_weight = nn.Parameter(torch.ones(HEAD_DIM)) def _compute_features_and_gates(self, h, g_qkv, f_in): B, T, _ = h.shape H = self.n_heads q, k, v = self.local_swa(g_qkv) f_lin = self.f_proj_out(f_in.to(self.f_proj_out.weight.dtype)).float() b_lin = self.b_proj(h.to(self.b_proj.weight.dtype)).float() if self.use_fla: return q, k, v, f_lin, b_lin, None q = l2_norm(q).float() k = l2_norm(k).float() v = v.float() f_sp = F.softplus(f_lin + self.dt_bias.float()) g_log = (-torch.exp(self.A_log.float()).view(1, 1, H) * f_sp).unsqueeze(-1) b_gate = torch.sigmoid(b_lin).view(B, T, H, HEAD_DIM) w_gate = torch.sigmoid(self.w_proj(h).float()).view(B, T, H, HEAD_DIM) return q, k, v, g_log, b_gate, w_gate @staticmethod def recurrent_scan(q, k, v, g_log, b_gate, w_gate, stable_symmetric=True): B, T, H, K = q.shape V = v.shape[-1] S = q.new_zeros(B, H, K, V, dtype=torch.float32) outs = [] for t in range(T): qt, kt, vt = q[:, t], k[:, t], v[:, t] alpha_t = torch.exp(g_log[:, t]) bt, wt = b_gate[:, t], w_gate[:, t] S_dec = S * alpha_t.unsqueeze(-1) w_vt = wt * vt if not stable_symmetric: ek = bt * kt erased = torch.einsum("bhkv,bhk->bhv", S_dec, ek) S = S_dec + torch.einsum("bhk,bhv->bhkv", kt, w_vt - erased) else: ut = torch.sqrt(bt.clamp_min(1e-12)) * kt erased = torch.einsum("bhkv,bhk->bhv", S_dec, ut) res = torch.sqrt((-torch.expm1(2.0 * g_log[:, t])).clamp_min(1e-12)) k_eff = ut + res * (kt - ut) S = ( S_dec - torch.einsum("bhk,bhv->bhkv", ut, erased) + torch.einsum("bhk,bhv->bhkv", k_eff, w_vt) ) outs.append(torch.einsum("bhkv,bhk->bhv", S, qt)) return torch.stack(outs, dim=1), S @staticmethod def chunkwise_wy( q, k, v, g_log, b_gate, w_gate, chunk_size=GDN_CHUNK_SIZE, stable_symmetric=True, use_bf16_gram=True, ): B, T, H, K = q.shape V = v.shape[-1] C = chunk_size pad_t = (C - (T % C)) % C if pad_t > 0: q = F.pad(q, (0, 0, 0, 0, 0, pad_t)) k = F.pad(k, (0, 0, 0, 0, 0, pad_t)) v = F.pad(v, (0, 0, 0, 0, 0, pad_t)) g_log = F.pad(g_log, (0, 0, 0, 0, 0, pad_t)) b_gate = F.pad(b_gate, (0, 0, 0, 0, 0, pad_t)) w_gate = F.pad(w_gate, (0, 0, 0, 0, 0, pad_t)) T_pad = q.shape[1] n_chunks = T_pad // C def reshape_chunks(x): return x.transpose(1, 2).reshape(B, H, n_chunks, C, -1) qc, kc, vc, gc, bc, wc = map( reshape_chunks, (q, k, v, g_log, b_gate, w_gate) ) wvc = wc * vc gamma = gc.cumsum(dim=-2) dev = q.device tril_strict = torch.tril( torch.ones(C, C, device=dev, dtype=torch.bool), diagonal=-1 ) tril_incl = torch.tril( torch.ones(C, C, device=dev, dtype=torch.bool), diagonal=0 ) eye_c = torch.eye(C, device=dev, dtype=torch.float32) diff = (gamma - gamma.transpose(-1, -2)).masked_fill(~tril_incl, 0.0) decay_tril = torch.exp(diff) * tril_incl decay_strict = decay_tril * tril_strict exp_gm = torch.exp(gamma) gm_last = gamma[..., -1:, :] exp_gm_last = torch.exp(gm_last) end_decay = torch.exp(gm_last - gamma) gram_dt = torch.bfloat16 if (use_bf16_gram and q.is_cuda) else torch.float32 exp_gm_last_g = exp_gm_last.to(gram_dt) wvc_g = wvc.to(gram_dt) S = q.new_zeros(B, H, K, V, dtype=gram_dt) outs = [] if not stable_symmetric: ec = bc * kc L = torch.matmul( ec.to(gram_dt), kc.to(gram_dt).transpose(-1, -2) ).float() * decay_strict A = eye_c + L A_inv = invert_unit_lower_tri(A).to(gram_dt) W_wy = torch.matmul(A_inv, (exp_gm * ec).to(gram_dt)) U_wy = torch.matmul(A_inv, wvc_g) M_g = ( torch.matmul(qc.to(gram_dt), kc.to(gram_dt).transpose(-1, -2)).float() * decay_tril ).to(gram_dt) o_local = torch.matmul(M_g, U_wy) q_eff = (exp_gm * qc).to(gram_dt) - torch.matmul(M_g, W_wy) k_end_t = (end_decay * kc).to(gram_dt).transpose(-1, -2) dS_local = torch.matmul(k_end_t, U_wy) for c_idx in range(n_chunks): outs.append( o_local[:, :, c_idx] + torch.matmul(q_eff[:, :, c_idx], S) ) ws = torch.matmul(W_wy[:, :, c_idx], S) S = ( S * exp_gm_last_g[:, :, c_idx] + dS_local[:, :, c_idx] - torch.matmul(k_end_t[:, :, c_idx], ws) ) else: uc = torch.sqrt(bc.clamp_min(1e-12)) * kc resc = torch.sqrt((-torch.expm1(2.0 * gc)).clamp_min(1e-12)) keffc = uc + resc * (kc - uc) u_g = uc.to(gram_dt) ke_g = keffc.to(gram_dt) q_g = qc.to(gram_dt) L_uu = torch.matmul(u_g, u_g.transpose(-1, -2)).float() * decay_strict A_sym = eye_c + L_uu R_uke_g = ( torch.matmul(u_g, ke_g.transpose(-1, -2)).float() * decay_strict ).to(gram_dt) M_qke_g = ( torch.matmul(q_g, ke_g.transpose(-1, -2)).float() * decay_tril ).to(gram_dt) M_qu_g = ( torch.matmul(q_g, u_g.transpose(-1, -2)).float() * decay_tril ).to(gram_dt) A_inv = invert_unit_lower_tri(A_sym).to(gram_dt) W_wy = torch.matmul(A_inv, (exp_gm * uc).to(gram_dt)) Z_local = torch.matmul(A_inv, torch.matmul(R_uke_g, wvc_g)) o_local = torch.matmul(M_qke_g, wvc_g) - torch.matmul(M_qu_g, Z_local) q_eff = (exp_gm * qc).to(gram_dt) - torch.matmul(M_qu_g, W_wy) ke_end_t = (end_decay * keffc).to(gram_dt).transpose(-1, -2) u_end_t = (end_decay * uc).to(gram_dt).transpose(-1, -2) dS_local = torch.matmul(ke_end_t, wvc_g) - torch.matmul(u_end_t, Z_local) for c_idx in range(n_chunks): outs.append( o_local[:, :, c_idx] + torch.matmul(q_eff[:, :, c_idx], S) ) ws = torch.matmul(W_wy[:, :, c_idx], S) S = ( S * exp_gm_last_g[:, :, c_idx] + dS_local[:, :, c_idx] - torch.matmul(u_end_t[:, :, c_idx], ws) ) out = torch.cat(outs, dim=2).transpose(1, 2)[:, :T].float() return out, S.float() def forward(self, h, g_qkv, f_in, g_in, use_chunkwise=True): B, T, _ = h.shape dt = h.dtype q, k, v, g_or_raw, b_or_raw, w_gate = self._compute_features_and_gates(h, g_qkv, f_in) if self.use_fla and h.is_cuda: out, _ = _fla_chunk_gdn( q.to(dt), k.to(dt), v.to(dt), g=g_or_raw.to(dt), beta=b_or_raw.to(dt), scale=1.0, use_qk_l2norm_in_kernel=True, use_gate_in_kernel=True, A_log=self.A_log, dt_bias=self.dt_bias, use_beta_sigmoid_in_kernel=True, ) out = out.float() else: if self.use_fla: q = l2_norm(q).float() k = l2_norm(k).float() v = v.float() f_sp = F.softplus(g_or_raw + self.dt_bias.float()) g_log = (-torch.exp(self.A_log.float()).view(1, 1, self.n_heads) * f_sp).unsqueeze(-1) b_4d = torch.sigmoid(b_or_raw).unsqueeze(-1) w_gate = b_4d else: g_log = g_or_raw b_4d = b_or_raw.unsqueeze(-1) if b_or_raw.ndim == 3 else b_or_raw if use_chunkwise: out, _ = self.chunkwise_wy( q, k, v, g_log, b_4d, w_gate, stable_symmetric=self.stable_symmetric, use_bf16_gram=True, ) else: out, _ = self.recurrent_scan( q, k, v, g_log, b_4d, w_gate, stable_symmetric=self.stable_symmetric, ) out_normed = rms_norm(out, self.o_norm_weight) g_out = F.silu( F.linear(g_in, self.g_proj_out.weight).float() + self.g_proj_out.bias.float() ).view(B, T, self.n_heads, HEAD_DIM) return (out_normed * g_out).reshape(B, T, self.attn_dim).to(dt) class HiSASlidingWindowAttention(nn.Module): """BF16 SWA-only FlexAttention (score_mod=None) + exact online-softmax pre-RoPE MoLA with cached RoPE (cos, sin) buffers. """ def __init__(self, use_reversible_mola=True, use_flex_attention=USE_FLEX_ATTENTION, n_heads=N_HEADS): super().__init__() self.use_reversible_mola = use_reversible_mola self.use_flex_attention = use_flex_attention and _HAS_FLEX_ATTN self.n_heads = int(n_heads) self.attn_dim = self.n_heads * HEAD_DIM self.q_norm_weight = nn.Parameter(torch.ones(HEAD_DIM)) self.k_norm_weight = nn.Parameter(torch.ones(HEAD_DIM)) if use_reversible_mola: self.mola_k_mem = nn.Parameter( torch.randn(self.n_heads, MOLA_MEM_SLOTS, HEAD_DIM) * (HEAD_DIM ** -0.5) ) self.mola_v_mem = nn.Parameter( torch.randn(self.n_heads, MOLA_MEM_SLOTS, HEAD_DIM) * (HEAD_DIM ** -0.5) ) self.mola_beta = nn.Parameter(torch.zeros(self.n_heads)) half = HEAD_DIM // 2 inv_freq = ROPE_BASE ** (-torch.arange(half, dtype=torch.float32) / half) dmax = torch.floor(HISA_PHI / inv_freq).to(torch.long) max_pos = max(SEQ_LEN, 2048) ang = torch.arange(max_pos, dtype=torch.float32)[:, None] * inv_freq[None, :] self.register_buffer("inv_freq", inv_freq, persistent=False) self.register_buffer("pair_dmax", dmax, persistent=False) self.register_buffer("rope_cos", ang.cos()[None, None, :, :], persistent=False) self.register_buffer("rope_sin", ang.sin()[None, None, :, :], persistent=False) self._block_mask_cache = {} self._sdpa_mask_cache = {} self._compiled_flex = ( torch.compile(flex_attention, mode="default") if (self.use_flex_attention and USE_TORCH_COMPILE and hasattr(torch, "compile")) else flex_attention ) def _apply_interleaved_rope(self, q, k): T = q.shape[2] dt = q.dtype if T <= self.rope_cos.size(2): cos = self.rope_cos[:, :, :T, :].to(dt) sin = self.rope_sin[:, :, :T, :].to(dt) else: pos = torch.arange(T, device=q.device, dtype=torch.float32) ang = pos[:, None] * self.inv_freq[None, :] cos = ang.cos().to(dt)[None, None, :, :] sin = ang.sin().to(dt)[None, None, :, :] def rotate(x): x_even, x_odd = x[..., 0::2], x[..., 1::2] return torch.stack( [x_even * cos - x_odd * sin, x_even * sin + x_odd * cos], dim=-1 ).flatten(-2) return rotate(q), rotate(k) def _scores_block_reference(self, qr, kr): B, H, T, _ = qr.shape S = HISA_BLOCK_TOKENS C_feat = 2 * HISA_CHUNK_PAIRS n_chunks = HEAD_DIM // C_feat n_blocks = math.ceil(T / S) scores = qr.new_zeros(B, H, T, T) for bq in range(n_blocks): q0, q1 = bq * S, min(T, (bq + 1) * S) bk_min = max(0, (q0 - SWA_WINDOW + 1) // S) for bk in range(bk_min, bq + 1): k0, k1 = bk * S, min(T, (bk + 1) * S) min_d = 0 if bq == bk else (bq - bk - 1) * S + 1 keep_pairs = min_d <= self.pair_dmax if not keep_pairs.any(): continue tile_score = qr.new_zeros(B, H, q1 - q0, k1 - k0) for c in range(n_chunks): p_slice = keep_pairs[ c * HISA_CHUNK_PAIRS : (c + 1) * HISA_CHUNK_PAIRS ] if not p_slice.any(): continue f0, f1 = c * C_feat, (c + 1) * C_feat q_chunk = qr[:, :, q0:q1, f0:f1] k_chunk = kr[:, :, k0:k1, f0:f1] if not p_slice.all(): q_chunk = q_chunk * p_slice.repeat_interleave(2).to(qr.dtype) tile_score = tile_score + torch.matmul( q_chunk, k_chunk.transpose(-1, -2) ) scores[:, :, q0:q1, k0:k1] = tile_score / math.sqrt(HEAD_DIM) return scores def _scores_block_fast(self, qr, kr): B, H, T, D = qr.shape S = HISA_BLOCK_TOKENS if T % S != 0: return self._scores_block_reference(qr, kr) n_blocks = T // S C_feat = 2 * HISA_CHUNK_PAIRS max_db = min(n_blocks - 1, SWA_WINDOW // S) qb = qr.view(B, H, n_blocks, S, D) kb = kr.view(B, H, n_blocks, S, D) scores = qr.new_zeros(B, H, n_blocks, S, n_blocks, S) for db in range(max_db + 1): min_d = 0 if db == 0 else (db - 1) * S + 1 keep_pairs = min_d <= self.pair_dmax if not keep_pairs.any(): continue active_chunks = [ c for c in range(D // C_feat) if keep_pairs[ c * HISA_CHUNK_PAIRS : (c + 1) * HISA_CHUNK_PAIRS ].any() ] f_start = active_chunks[0] * C_feat f_end = (active_chunks[-1] + 1) * C_feat feat_mask = ( keep_pairs[f_start // 2 : f_end // 2] .repeat_interleave(2) .to(qr.dtype) ) q_diag = qb[:, :, db:, :, f_start:f_end] * feat_mask k_diag = kb[:, :, : n_blocks - db, :, f_start:f_end] diag_scores = torch.matmul(q_diag, k_diag.transpose(-1, -2)) / math.sqrt( HEAD_DIM ) b_idx = torch.arange(n_blocks - db, device=qr.device) scores[:, :, b_idx + db, :, b_idx, :] = diag_scores.permute(2, 0, 1, 3, 4) return scores.view(B, H, T, T) def _get_flex_block_mask(self, T, device): key = (T, str(device)) bm = self._block_mask_cache.get(key) if bm is None: def swa_only_mask(b, h, q_idx, kv_idx): return (q_idx >= kv_idx) & ((q_idx - kv_idx) < SWA_WINDOW) bm = create_block_mask( swa_only_mask, B=None, H=None, Q_LEN=T, KV_LEN=T, device=device, ) self._block_mask_cache[key] = bm return bm def _get_sdpa_token_mask(self, T, device, dtype): key = (T, str(device), dtype) mask = self._sdpa_mask_cache.get(key) if mask is None: idx = torch.arange(T, device=device) dist = idx[:, None] - idx[None, :] in_window = (dist >= 0) & (dist < SWA_WINDOW) mask = torch.zeros((1, 1, T, T), device=device, dtype=dtype) mask.masked_fill_(~in_window.view(1, 1, T, T), float("-inf")) if len(self._sdpa_mask_cache) > 64: self._sdpa_mask_cache.clear() self._sdpa_mask_cache[key] = mask return mask def prepare_mask(self, T, device, dtype): use_flex = ( self.use_flex_attention and device.type == "cuda" and (self.training or T == SEQ_LEN) and (T > SWA_WINDOW) ) if use_flex: return self._get_flex_block_mask(T, device), None if T <= SWA_WINDOW: return None, None return None, self._get_sdpa_token_mask(T, device, dtype) def _run_flex_lse(self, q, k, v, block_mask): is_compiling = ( hasattr(torch, "compiler") and hasattr(torch.compiler, "is_compiling") and torch.compiler.is_compiling() ) fn = flex_attention if is_compiling else self._compiled_flex return fn(q, k, v, block_mask=block_mask, return_lse=True) def forward(self, sq, sk, sv, block_mask=None, tok_mask=None): B, T, _ = sq.shape dt = sq.dtype q = sq.view(B, T, self.n_heads, HEAD_DIM) k = sk.view(B, T, self.n_heads, HEAD_DIM) v = sv.view(B, T, self.n_heads, HEAD_DIM) q_normed = rms_norm(q, self.q_norm_weight, out_dtype=dt).transpose(1, 2) k_normed = rms_norm(k, self.k_norm_weight, out_dtype=dt).transpose(1, 2) v_t = v.to(dt).transpose(1, 2) qr, kr = self._apply_interleaved_rope(q_normed, k_normed) if self.use_reversible_mola and block_mask is not None: o_tok, lse_tok = self._run_flex_lse(qr, kr, v_t, block_mask) k_mem_n = rms_norm(self.mola_k_mem, self.k_norm_weight, out_dtype=dt) is_comp = ( hasattr(torch, "compiler") and hasattr(torch.compiler, "is_compiling") and torch.compiler.is_compiling() ) if (not is_comp) or (USE_TRITON_MOLA_IN_COMPILE and _HAS_MOLA_CUSTOM_OP): # Custom Triton Kernel 3: 1-pass Pre-RoPE MoLA online-softmax merge (custom_op -> 0 graph breaks!) if _HAS_MOLA_CUSTOM_OP and o_tok.is_cuda: out, _ = _mola_op_fwd( o_tok, lse_tok, q_normed, k_mem_n, self.mola_v_mem.to(dt), self.mola_beta ) else: out = fused_mola_online_merge( o_tok, lse_tok, q_normed, k_mem_n, self.mola_v_mem.to(dt), self.mola_beta ) else: scores_mem = ( torch.matmul(q_normed, k_mem_n.transpose(-1, -2)).float() / math.sqrt(HEAD_DIM) + self.mola_beta.float().view(1, self.n_heads, 1, 1) ) lse_mem = torch.logsumexp(scores_mem, dim=-1) o_mem = torch.matmul( torch.softmax(scores_mem, dim=-1).to(dt), self.mola_v_mem.to(dt) ) alpha = torch.sigmoid(lse_mem - lse_tok.detach()).unsqueeze(-1).to(dt) out = (1.0 - alpha) * o_tok + alpha * o_mem elif self.use_reversible_mola: k_mem_n = rms_norm(self.mola_k_mem, self.k_norm_weight, out_dtype=dt) scores_tok = torch.matmul(qr, kr.transpose(-1, -2)).float() / math.sqrt(HEAD_DIM) tm = ( tok_mask if tok_mask is not None else self._get_sdpa_token_mask(T, sq.device, torch.float32) ) scores_tok = scores_tok + tm.float() scores_mem = ( torch.matmul(q_normed, k_mem_n.transpose(-1, -2)).float() / math.sqrt(HEAD_DIM) + self.mola_beta.float().view(1, self.n_heads, 1, 1) ) attn_joint = torch.softmax(torch.cat([scores_tok, scores_mem], dim=-1), dim=-1).to(dt) out = torch.matmul(attn_joint[..., :T], v_t) + torch.matmul( attn_joint[..., T:], self.mola_v_mem.to(dt) ) else: if T <= SWA_WINDOW: out = F.scaled_dot_product_attention(qr, kr, v_t, is_causal=True) elif block_mask is not None: out, _ = self._run_flex_lse(qr, kr, v_t, block_mask) else: tm = ( tok_mask if tok_mask is not None else self._get_sdpa_token_mask(T, sq.device, dt) ) out = F.scaled_dot_product_attention(qr, kr, v_t, attn_mask=tm) return out.transpose(1, 2).reshape(B, T, self.attn_dim).to(dt) class ReversibleReasoningBlock(nn.Module): """Single reversible block used for Prelude (2x), Shared Core (r loops), and Coda (2x). - Optional gated Input Injection from post-Prelude anchor (a1, a2) - Optional MoD-style token-sparse UltraMemV2 gate inside the FFN (top 12.5% tokens) """ def __init__( self, gdn_stable_symmetric=True, use_reversible_mola=True, use_anchor_inject=False, use_gated_mem=False, use_givens=True, use_sandwich_norm=False, anchor_init=-1.5, seq_mixer="parallel", ): super().__init__() assert seq_mixer in ("parallel", "gdn", "swa"), f"Unknown seq_mixer={seq_mixer}" self.seq_mixer = seq_mixer self.use_anchor_inject = use_anchor_inject self.use_gated_mem = use_gated_mem self.use_givens = use_givens self.use_sandwich_norm = use_sandwich_norm self.theta = nn.Parameter(torch.tensor(math.pi / 64.0)) if use_givens else None self.gamma_seq = nn.Parameter(torch.ones(D_STREAM)) self.gamma_seq_post = nn.Parameter(torch.ones(D_STREAM)) self.gamma_ffn = nn.Parameter(torch.ones(D_STREAM)) self.gamma_ffn_post = nn.Parameter(torch.ones(D_STREAM)) self.scale_1 = nn.Parameter(torch.tensor(INIT_SCALE)) self.scale_2 = nn.Parameter(torch.tensor(INIT_SCALE)) if use_sandwich_norm: # Huginn sandwich-norm hard-clamps ||y1||, ||y2|| to unit RMS at 8..40 loops self.stream_norm_1 = nn.Parameter(torch.ones(D_STREAM)) self.stream_norm_2 = nn.Parameter(torch.ones(D_STREAM)) if use_anchor_inject: # Parcae ZOH decay (lam = exp(-softplus(-3.0)) ~= 0.953/iter -> no premature 16L freeze!) self.zoh_log_decay_1 = nn.Parameter(torch.full((D_STREAM,), -3.0)) self.zoh_log_decay_2 = nn.Parameter(torch.full((D_STREAM,), -3.0)) self.anchor_gate_1 = nn.Parameter(torch.full((D_STREAM,), float(anchor_init))) self.anchor_gate_2 = nn.Parameter(torch.full((D_STREAM,), float(anchor_init))) full_heads = D_STREAM // HEAD_DIM # 16 heads x 64 = 1024 full-width sequential mixer if seq_mixer == "gdn": self.qkv_fg_fused = nn.Linear(D_STREAM, 3 * D_STREAM + 2 * HEAD_DIM, bias=False) self.gdn = GatedDeltaNet2(stable_symmetric=gdn_stable_symmetric, n_heads=full_heads) self.swa = None elif seq_mixer == "swa": self.qkv_fg_fused = nn.Linear(D_STREAM, 3 * D_STREAM, bias=False) self.gdn = None self.swa = HiSASlidingWindowAttention(use_reversible_mola=use_reversible_mola, n_heads=full_heads) else: # Parallel Prelude/Coda: single fused 1024 -> 3200 FP8 GEMM for GDN(512) + SWA(512) self.qkv_fg_fused = nn.Linear(D_STREAM, 6 * ATTN_DIM + 2 * HEAD_DIM, bias=False) self.gdn = GatedDeltaNet2(stable_symmetric=gdn_stable_symmetric, n_heads=N_HEADS) self.swa = HiSASlidingWindowAttention(use_reversible_mola=use_reversible_mola, n_heads=N_HEADS) self.out_proj = nn.Linear(D_STREAM, D_STREAM, bias=False) self.w_gate_up = nn.Linear(D_STREAM, 2 * FFN_HIDDEN, bias=False) self.w_down = nn.Linear(FFN_HIDDEN, D_STREAM, bias=False) if use_gated_mem: self.mem_need_gate = nn.Linear(D_STREAM, 1, bias=True) nn.init.zeros_(self.mem_need_gate.bias) self.register_buffer( "eval_thr", torch.tensor(MEM_EVAL_THRESHOLD, dtype=torch.float32) ) self._dense_step_compiled = None self.last_mem_gate_mean = 0.0 self.last_mem_active_frac = 0.0 def _dense_step_impl(self, x1, x2, block_mask, tok_mask, k_base=None, v_base=None): dt = x1.dtype if self.use_givens and self.theta is not None: th = self.theta.float() c = torch.cos(th).to(dt) s = torch.sin(th).to(dt) xp1 = c * x1 - s * x2 xp2 = s * x1 + c * x2 else: # Orientation-invariant reversible coupling (no >90 deg rotation drift at 24..40 loops!) xp1, xp2 = x1, x2 if self.seq_mixer == "swa" and isinstance(self.qkv_fg_fused, CachedFP8Linear): # 1-pass Triton RMSNorm->FP8 + cached FP8 weight GEMM (skips intermediate BF16 h_seq!) sq, sk, sv = self.qkv_fg_fused.forward_from_rmsnorm(xp2, self.gamma_seq, eps=EPS).chunk(3, dim=-1) mixed = self.swa(sq, sk, sv, block_mask=block_mask, tok_mask=tok_mask) else: h_seq = rms_norm(xp2, self.gamma_seq, out_dtype=self.qkv_fg_fused.weight.dtype) if self.seq_mixer == "gdn": g_qkv, f_in, g_in = self.qkv_fg_fused(h_seq).split( [3 * D_STREAM, HEAD_DIM, HEAD_DIM], dim=-1 ) mixed = self.gdn(h_seq, g_qkv, f_in, g_in) elif self.seq_mixer == "swa": sq, sk, sv = self.qkv_fg_fused(h_seq).chunk(3, dim=-1) if k_base is not None: sk = sk + k_base.to(sk.dtype) sv = sv + v_base.to(sv.dtype) mixed = self.swa(sq, sk, sv, block_mask=block_mask, tok_mask=tok_mask) else: g_qkv, sq, sk, sv, f_in, g_in = self.qkv_fg_fused(h_seq).split( [3 * ATTN_DIM, ATTN_DIM, ATTN_DIM, ATTN_DIM, HEAD_DIM, HEAD_DIM], dim=-1 ) mixed = torch.cat( [ self.gdn(h_seq, g_qkv, f_in, g_in), self.swa(sq, sk, sv, block_mask=block_mask, tok_mask=tok_mask), ], dim=-1, ) f_out = rms_norm(self.out_proj(mixed), self.gamma_seq_post) y1 = xp1 + self.scale_1.to(dt) * f_out.to(dt) if self.use_sandwich_norm: y1 = rms_norm(y1, self.stream_norm_1, out_dtype=dt) if (not self.use_gated_mem) and isinstance(self.w_gate_up, CachedFP8Linear): h_ffn = None gate_up = self.w_gate_up.forward_from_rmsnorm(y1, self.gamma_ffn, eps=EPS) else: h_ffn = rms_norm(y1, self.gamma_ffn, out_dtype=self.w_gate_up.weight.dtype) gate_up = self.w_gate_up(h_ffn) if isinstance(self.w_down, CachedFP8Linear): # 1-pass Triton SwiGLU->FP8 + cached FP8 w_down GEMM (cuts ~500 MiB/block BF16<->FP8 traffic!) ffn_out = rms_norm(self.w_down.forward_from_swiglu(gate_up), self.gamma_ffn_post).to(dt) else: gate, up = gate_up.chunk(2, dim=-1) ffn_out = rms_norm(self.w_down(F.silu(gate) * up), self.gamma_ffn_post).to(dt) # Return h_ffn and run N=1 mem_need_gate outside max-autotune (avoids Inductor [1,1024]->[1024] bwd squeeze bug!) return y1, xp2, ffn_out, (h_ffn if self.use_gated_mem else None) def compile_step(self, mode=CORE_COMPILE_MODE): if hasattr(torch, "compile"): self._dense_step_compiled = torch.compile(self._dense_step_impl, mode=mode) def forward( self, x1, x2, a1=None, a2=None, bridge=None, collect_telemetry=False, cached_masks=None, contraction_gate=None, ): if self.swa is None: bm, tm = None, None elif cached_masks is not None: bm, tm = cached_masks else: bm, tm = self.swa.prepare_mask(x1.shape[1], x1.device, self.qkv_fg_fused.weight.dtype) if self.use_anchor_inject and a1 is not None: # Custom Triton Kernel 2B: 1-pass OrthoInj + ZOH outside compile (zero graph breaks!) lam1 = torch.exp(-F.softplus(self.zoh_log_decay_1.float())) lam2 = torch.exp(-F.softplus(self.zoh_log_decay_2.float())) g1 = torch.sigmoid(self.anchor_gate_1.float()) g2 = torch.sigmoid(self.anchor_gate_2.float()) x1 = fused_orthoinj_zoh(x1, a1, lam1, g1, eps=EPS) x2 = fused_orthoinj_zoh(x2, a2, lam2, g2, eps=EPS) fn = ( self._dense_step_compiled if (self.training and self._dense_step_compiled is not None) else self._dense_step_impl ) tala_kv = getattr(self, "_active_tala_kv", None) if tala_kv is not None: y1, xp2, ffn_out, h_ffn_mg = fn(x1, x2, bm, tm, tala_kv[0], tala_kv[1]) else: y1, xp2, ffn_out, h_ffn_mg = fn(x1, x2, bm, tm) dt = x1.dtype aux_loss = None if self.use_gated_mem and bridge is not None and h_ffn_mg is not None: # Custom Triton Kernel 5A: fused mem_need_gate + sigmoid + c_gate (guaranteed [1,1024] bwd!) c_flat = contraction_gate.reshape(-1) if contraction_gate is not None else None eff_score = fused_mod_gate_score( h_ffn_mg.reshape(-1, D_STREAM), self.mem_need_gate.weight, self.mem_need_gate.bias, c_flat, ) n_tok = eff_score.numel() if self.training or n_tok >= 8: k_tok = max(1, int(n_tok * MEM_CAPACITY_FRAC)) top_g, top_idx = torch.topk(eff_score, k=k_tok, sorted=False) h_sel = y1.reshape(-1, D_STREAM).index_select(0, top_idx) m_sel, aux_loss = bridge.forward_flat(h_sel) # MoD-style BCE calibration + EMA eval threshold on exact eff_score if self.training and torch.is_grad_enabled(): is_sel = torch.zeros_like(eff_score, dtype=torch.float32) is_sel.scatter_(0, top_idx, 1.0) gate_bce = F.binary_cross_entropy( eff_score.float().clamp(1e-6, 1.0 - 1e-6), is_sel ) aux_loss = 0.05 * gate_bce with torch.no_grad(): self.eval_thr.lerp_(top_g.min().detach().float(), 0.05) # Custom Triton Kernel 5B: fused scaled scatter-add (no 16 MiB mem_delta / 64 MiB clone!) ffn_out = fused_mod_scaled_scatter_add( ffn_out.reshape(-1, D_STREAM), top_idx, top_g, bridge.bridge_scale, m_sel, inplace=False, ).view_as(ffn_out) if collect_telemetry: with torch.no_grad(): self.last_mem_gate_mean = float(eff_score.mean().item()) self.last_mem_active_frac = float(k_tok / max(1, n_tok)) b_scale_f = float(bridge.bridge_scale.float().item()) b_rms = ( (top_g.float().pow(2) * m_sel.float().pow(2).mean(dim=-1)).mean().sqrt().item() * abs(b_scale_f) ) f_rms = ffn_out.float().pow(2).mean().sqrt().clamp_min(1e-6).item() bridge.last_bridge_rms_ratio = float(b_rms / f_rms) else: sel_mask = eff_score > self.eval_thr if sel_mask.any(): top_idx = sel_mask.nonzero(as_tuple=False).squeeze(-1) top_g = eff_score.index_select(0, top_idx) h_sel = y1.reshape(-1, D_STREAM).index_select(0, top_idx) m_sel, _ = bridge.forward_flat(h_sel) ffn_out = fused_mod_scaled_scatter_add( ffn_out.reshape(-1, D_STREAM), top_idx, top_g, bridge.bridge_scale, m_sel, inplace=False, ).view_as(ffn_out) y2 = xp2 + self.scale_2.to(dt) * ffn_out if self.use_sandwich_norm: y2 = rms_norm(y2, self.stream_norm_2, out_dtype=dt) return y1, y2, aux_loss class ECHOCausalSelfRecursion(nn.Module): """ECHO Causal Self-Recursion (Zhou et al., 2026, arXiv:2610.24766).""" def __init__(self): super().__init__() self.norm_h1 = nn.Parameter(torch.ones(D_STREAM)) self.norm_h2 = nn.Parameter(torch.ones(D_STREAM)) self.norm_e1 = nn.Parameter(torch.ones(D_STREAM)) self.norm_e2 = nn.Parameter(torch.ones(D_STREAM)) self.w_fuse = nn.Linear(2 * D_STREAM, D_STREAM, bias=False) self._fuse_step_compiled = None @staticmethod def sample_dds_depth(probs=ECHO_DDS_PROBS): p = torch.tensor(probs, dtype=torch.float32) return int(torch.multinomial(p, num_samples=1).item()) + 1 def _fuse_step_impl(self, x1, x2, emb): e1, e2 = emb.chunk(2, dim=-1) dt = self.w_fuse.weight.dtype def fuse(x, nx, e, ne): parts = [rms_norm(x, nx, out_dtype=dt), rms_norm(e, ne, out_dtype=dt)] return self.w_fuse(torch.cat(parts, dim=-1)).to(x.dtype) return ( fuse(x1, self.norm_h1, e1, self.norm_e1), fuse(x2, self.norm_h2, e2, self.norm_e2), ) def fuse_step(self, x1, x2, emb): fn = ( self._fuse_step_compiled if (self.training and self._fuse_step_compiled is not None) else self._fuse_step_impl ) return fn(x1, x2, emb) def forward(self, coda_block, h_backbone, future_token_embs): x1, x2 = h_backbone.chunk(2, dim=-1) horizon_states = [] for emb_k in future_token_embs: x1, x2 = self.fuse_step(x1, x2, emb_k) x1, x2, _ = coda_block(x1, x2) horizon_states.append(torch.cat([x1, x2], dim=-1)) return horizon_states # ================= UNIFIED PRELUDE + SHARED CORE + CODA + DUAL-TIER GDDR7 LM class ContinuousLoopCond(nn.Module): """Continuous Fourier/sinusoidal depth conditioning for arbitrary post-training loop extrapolation. Never uses a discrete nn.Embedding(max_loops, D) table: encodes both linear (r / r_ref) and log-compressed (log(1+r) / log(1+r_ref)) depth ratios with zero-initialized FiLM outputs so step-0 is an exact identity and post-training 2x+ loop doubling (e.g. 40L -> 80L+) is smooth. """ def __init__( self, d_stream: int = D_STREAM, n_freqs: int = LOOP_FOURIER_FREQS, hidden: int = LOOP_COND_HIDDEN, ): super().__init__() freqs = torch.exp(torch.linspace(0.0, math.log(16.0), n_freqs)) * math.pi self.register_buffer("freqs", freqs, persistent=False) self.fc1 = nn.Linear(4 * n_freqs, hidden) self.fc_out = nn.Linear(hidden, 4 * d_stream) nn.init.zeros_(self.fc_out.weight) nn.init.zeros_(self.fc_out.bias) def forward(self, loop_idx: int, r_ref: int = LOOP_COND_R_REF): t_lin = float(loop_idx) / float(max(1, r_ref)) t_log = math.log1p(float(loop_idx)) / math.log1p(float(max(1, r_ref))) ang_lin = self.freqs * t_lin ang_log = self.freqs * t_log feat = torch.cat( [torch.sin(ang_lin), torch.cos(ang_lin), torch.sin(ang_log), torch.cos(ang_log)], dim=-1, ).float() h = F.silu(F.linear(feat, self.fc1.weight.float(), self.fc1.bias.float())) out = F.linear(h, self.fc_out.weight.float(), self.fc_out.bias.float()) s1, b1, s2, b2 = out.chunk(4, dim=-1) return s1, b1, s2, b2 class HoistedTALABase(nn.Module): """Option 1 Hoisted TALA-Base (arXiv:2611.39694, Eq. 13-14): Derives a single shared token-anchored Base latent b = W_B(x0) from the initial token embedding x0 (before any contextual attention) and pre-decodes (k_base, v_base) ONCE per sequence outside the SharedCell loop, adding it as a zero-initialized residual to Block 1 SWA keys and values across all 10L..40L (and 80L post-train) iterations. """ def __init__(self, d_in: int = D_TOTAL, d_base: int = TALA_BASE_DIM, d_kv: int = D_STREAM): super().__init__() self.norm = nn.Parameter(torch.ones(d_in)) self.w_down = nn.Linear(d_in, d_base, bias=False) self.w_up_kv = nn.Linear(d_base, 2 * d_kv, bias=False) nn.init.zeros_(self.w_up_kv.weight) # exact identity at step 0 (k_base=0, v_base=0) def forward(self, x0: torch.Tensor): h = rms_norm(x0, self.norm, out_dtype=self.w_down.weight.dtype) b = self.w_down(h) k_base, v_base = self.w_up_kv(b).chunk(2, dim=-1) return k_base, v_base class L2GDDR7HybridLanguageModel(nn.Module): """Unified Language Model: - Outer Tied Vocabulary Embeddings & LM Head (L2-pinned Liger CE) - Async CUDA Stream Prefetch for Layer-2 DeepSeek Engram (after Prelude 2) - Prelude (2 blocks, FP8/BF16) -> Engram Gate -> Save h_anchor - Shared L2-Pinned Core x r loops (PLN Stochastic Depth + TBPTT b=6 + Gated h_anchor Injection + Top-12.5% MoD-Gated UltraMemV2 Multi-Hop) - Coda (2 blocks, FP8/BF16) + ECHO Causal Self-Recursion """ def __init__(self, vocab_size, canonical_map, device, rank=0, world_size=1): super().__init__() self.vocab_size = vocab_size self.tok_emb = nn.Embedding(vocab_size, D_VOCAB) nn.init.normal_(self.tok_emb.weight, mean=0.0, std=0.02) self.emb_up = nn.Linear(D_VOCAB, D_TOTAL, bias=False) self.lm_down = nn.Linear(D_TOTAL, D_VOCAB, bias=False) use_sym = not (USE_FLA_GDN and _HAS_FLA) self.prelude = nn.ModuleList( [ ReversibleReasoningBlock( gdn_stable_symmetric=use_sym, use_reversible_mola=True, use_anchor_inject=False, use_gated_mem=False, ) for _ in range(N_PRELUDE) ] ) self.engram = EngramConditionalMemory(canonical_map, SPARSE_MEMORY_CFG, device, rank=rank, world_size=world_size) # Sequential 2-block recurrent cell: # Block 0: OrthoInj+ZOH + Full-Width GDN-2 (16 heads x 64 = 1024) + FFN # Block 1: Full-Width SWA+MoLA (16 heads x 64 = 1024) + FFN + topK=32 UltraMemV2 + Post-Cell RMSNorm self.shared_core = nn.ModuleList( [ ReversibleReasoningBlock( gdn_stable_symmetric=use_sym, use_reversible_mola=True, use_anchor_inject=(i == 0), use_gated_mem=(i == N_SHARED_CELL_BLOCKS - 1), use_givens=False, use_sandwich_norm=(i == N_SHARED_CELL_BLOCKS - 1), anchor_init=-1.5, seq_mixer=("gdn" if i == 0 else "swa"), ) for i in range(N_SHARED_CELL_BLOCKS) ] ) self.last_eval_step_rms = 0.0 self.loop_cond = ( ContinuousLoopCond(D_STREAM, LOOP_FOURIER_FREQS, LOOP_COND_HIDDEN) if ENABLE_CONTINUOUS_LOOP_COND else None ) self.tala_base = ( HoistedTALABase(D_TOTAL, TALA_BASE_DIM, D_STREAM) if ENABLE_TALA_BASE else None ) self.bridge = UltraMemV2TDQKRBridge(SPARSE_MEMORY_CFG, device, rank=rank, world_size=world_size) self.coda = nn.ModuleList( [ ReversibleReasoningBlock( gdn_stable_symmetric=use_sym, use_reversible_mola=True, use_anchor_inject=False, use_gated_mem=False, ) for _ in range(N_CODA) ] ) self.echo = ECHOCausalSelfRecursion() self.final_norm = nn.Parameter(torch.ones(D_TOTAL)) self._final_norm_compiled = None self._engram_stream = ( torch.cuda.Stream(device=device) if (device.type == "cuda" and world_size == 1) else None ) if PREFER_CUT_CE and _HAS_CUT_CE and device.type == "cuda": self._liger_ce = None self.ce_backend = "cut_cross_entropy" elif _HAS_LIGER_CE and device.type == "cuda": self._liger_ce = LigerFusedLinearCrossEntropyLoss() self.ce_backend = "liger_fused_linear_ce" else: self._liger_ce = None self.ce_backend = "chunked_checkpointed_ce" def set_telemetry(self, enabled: bool): self.engram.collect_telemetry = enabled self.bridge.collect_telemetry = enabled def compile_hot_paths(self, enabled: bool): if not enabled or not hasattr(torch, "compile"): return False for blk in self.prelude: blk.compile_step(mode="default") for blk in self.shared_core: blk.compile_step(mode=CORE_COMPILE_MODE) for blk in self.coda: blk.compile_step(mode="default") self.engram._gate_and_project_compiled = torch.compile( self.engram._gate_and_project, mode="default" ) self.bridge._route_flat_compiled = torch.compile( self.bridge._route_and_score_flat, mode="default", dynamic=False ) self.bridge._proj_flat_compiled = torch.compile( self.bridge._gate_and_project_flat, mode="default", dynamic=False ) self.echo._fuse_step_compiled = torch.compile( self.echo._fuse_step_impl, mode="default" ) self._final_norm_compiled = torch.compile(self._apply_final_norm, mode="default", dynamic=True) return True def embed_tokens(self, input_ids): return self.emb_up(self.tok_emb(input_ids)) def _apply_final_norm(self, hidden): h_n = rms_norm(hidden, self.final_norm, out_dtype=self.lm_down.weight.dtype) return self.lm_down(h_n).to(self.tok_emb.weight.dtype) def forward_backbone(self, input_ids, n_shared_iters=6, tbptt_iters=None): """Run Prelude(2) + Async Layer-2 Engram + SharedCore(2-block cell x n_shared_iters) + Coda(2).""" if self._engram_stream is not None: cur_stream = torch.cuda.current_stream(input_ids.device) self._engram_stream.wait_stream(cur_stream) with torch.cuda.stream(self._engram_stream): e_t_prefetched = self.engram.prefetch_embeddings(input_ids) else: e_t_prefetched = self.engram.prefetch_embeddings(input_ids) x0 = self.embed_tokens(input_ids) x1, x2 = x0.chunk(2, dim=-1) for blk in self.prelude: x1, x2, _ = blk(x1, x2) if self._engram_stream is not None: cur_stream = torch.cuda.current_stream(input_ids.device) cur_stream.wait_stream(self._engram_stream) e_t_prefetched.record_stream(cur_stream) x1 = self.engram.apply_prefetched(x1, e_t_prefetched) # Hoist SWA BlockMask once per micro-batch from SWA block (Block 1 in sequential shared_core!) swa_blk = self.shared_core[-1] if self.shared_core[-1].swa is not None else self.coda[-1] cached_masks = swa_blk.swa.prepare_mask( x1.shape[1], x1.device, swa_blk.qkv_fg_fused.weight.dtype ) # Unit-RMS anchor + Path-Independent Init (prevents shallow-loop cheating!) a1, a2 = rms_norm(x1), rms_norm(x2) if self.training: x1 = torch.randn_like(a1) * 0.02 x2 = torch.randn_like(a2) * 0.02 else: x1 = torch.zeros_like(a1) x2 = torch.zeros_like(a2) if tbptt_iters is not None and self.training and torch.is_grad_enabled(): n_nograd = max(0, n_shared_iters - tbptt_iters) else: n_nograd = 0 # Option 1 Hoisted TALA-Base: compute (k_base, v_base) ONCE per sequence outside the loop! tala_blk = self.shared_core[-1] if (self.tala_base is not None and self.shared_core[-1].seq_mixer == "swa") else None x1_prev = None if n_nograd > 0: with torch.no_grad(): if tala_blk is not None: tala_blk._active_tala_kv = self.tala_base(x0) try: for iter_ng in range(n_nograd): if x1_prev is not None: step_rms = (x1 - x1_prev).pow(2).mean(dim=-1, dtype=torch.float32).sqrt() c_gate = 0.65 + 0.35 * torch.tanh(step_rms / 0.05) else: c_gate = None x1_prev = x1 if self.loop_cond is not None: s1, b1, s2, b2 = self.loop_cond(iter_ng) x1 = x1 * (1.0 + s1.to(x1.dtype)) + b1.to(x1.dtype) x2 = x2 * (1.0 + s2.to(x2.dtype)) + b2.to(x2.dtype) for blk in self.shared_core: x1, x2, _ = blk( x1, x2, a1=a1, a2=a2, bridge=self.bridge, collect_telemetry=False, cached_masks=cached_masks, contraction_gate=c_gate, ) finally: if tala_blk is not None: tala_blk._active_tala_kv = None x1, x2 = x1.detach(), x2.detach() x1_prev = x1_prev.detach() if x1_prev is not None else None n_grad_iters = n_shared_iters - n_nograd aux_total = x1.new_zeros((), dtype=torch.float32) aux_count = 0 mid_idx = 0 # widest contrast inside TBPTT window (r_final - 3 vs r_final) mid_pair = None last_step_rms = None prev_step_rms = None if tala_blk is not None: tala_blk._active_tala_kv = self.tala_base(x0) try: for idx_g in range(n_grad_iters): is_last_iter = (idx_g == n_grad_iters - 1) if last_step_rms is not None: c_gate = 0.65 + 0.35 * torch.tanh(last_step_rms.detach() / 0.05) elif x1_prev is not None: sr = (x1 - x1_prev).pow(2).mean(dim=-1, dtype=torch.float32).sqrt() c_gate = 0.65 + 0.35 * torch.tanh(sr.detach() / 0.05) else: c_gate = None x1_before = x1 if self.loop_cond is not None: s1, b1, s2, b2 = self.loop_cond(n_nograd + idx_g) x1 = x1 * (1.0 + s1.to(x1.dtype)) + b1.to(x1.dtype) x2 = x2 * (1.0 + s2.to(x2.dtype)) + b2.to(x2.dtype) for b_idx, blk in enumerate(self.shared_core): is_last_blk = is_last_iter and (b_idx == len(self.shared_core) - 1) x1, x2, aux_l = blk( x1, x2, a1=a1, a2=a2, bridge=self.bridge, collect_telemetry=(self.bridge.collect_telemetry and is_last_blk), cached_masks=cached_masks, contraction_gate=c_gate, ) if aux_l is not None: aux_total = aux_total + aux_l aux_count += 1 prev_step_rms = last_step_rms last_step_rms = (x1 - x1_before).pow(2).mean(dim=-1, dtype=torch.float32).sqrt() if self.training and n_grad_iters >= 2 and idx_g == mid_idx and RMID_LOSS_COEFF > 0.0: b_mid = max(1, int(round(input_ids.size(0) * RMID_BATCH_FRAC))) mid_pair = (x1[:b_mid], x2[:b_mid]) finally: if tala_blk is not None: tala_blk._active_tala_kv = None aux_loss = aux_total / max(1, aux_count) if self.training and CONTRACTION_REG_COEFF > 0.0 and prev_step_rms is not None and last_step_rms is not None: aux_loss = aux_loss + CONTRACTION_REG_COEFF * F.relu( last_step_rms - 0.97 * prev_step_rms.detach() ).mean() if not self.training and last_step_rms is not None: self.last_eval_step_rms = float(last_step_rms.mean().item()) # Coda readout refinement (plus Ouro r_mid sub-batch readout when active) for blk in self.coda: x1, x2, _ = blk(x1, x2, cached_masks=cached_masks) h_out = torch.cat([x1, x2], dim=-1) h_mid_out = None if mid_pair is not None: mx1, mx2 = mid_pair for blk in self.coda: mx1, mx2, _ = blk(mx1, mx2, cached_masks=cached_masks) h_mid_out = torch.cat([mx1, mx2], dim=-1) return h_out, aux_loss, h_mid_out @staticmethod def _chunk_ce_sum(h_chunk, w, t_chunk): logits = F.linear(h_chunk, w).float() return F.cross_entropy(logits, t_chunk, reduction="sum") def compute_lm_loss(self, hidden, targets): h_norm = self._apply_final_norm(hidden) h_flat = h_norm.reshape(-1, D_VOCAB) t_flat = targets.reshape(-1) if self._liger_ce is not None: n_tok = h_flat.size(0) sub = LIGER_SUB_BATCH_TOKENS if n_tok <= sub: return self._liger_ce(self.tok_emb.weight, h_flat, t_flat) total_loss = h_flat.new_zeros((), dtype=torch.float32) for s in range(0, n_tok, sub): e = min(n_tok, s + sub) total_loss = total_loss + self._liger_ce( self.tok_emb.weight, h_flat[s:e], t_flat[s:e] ) * ((e - s) / n_tok) return total_loss if self.ce_backend == "cut_cross_entropy": return _cce_linear_cross_entropy(h_flat, self.tok_emb.weight, t_flat) n_tok = h_flat.size(0) total_loss = h_flat.new_zeros((), dtype=torch.float32) use_ckpt = self.training and torch.is_grad_enabled() for start in range(0, n_tok, CE_CHUNK_TOKENS): end = min(n_tok, start + CE_CHUNK_TOKENS) hc = h_flat[start:end] tc = t_flat[start:end] if use_ckpt: total_loss = total_loss + checkpoint( self._chunk_ce_sum, hc, self.tok_emb.weight, tc, use_reentrant=False ) else: total_loss = total_loss + self._chunk_ce_sum(hc, self.tok_emb.weight, tc) return total_loss / n_tok def forward_train( self, input_ids, target_horizons, n_shared_iters, dds_depth=ECHO_FIXED_DEPTH, echo_batch_frac=ECHO_BATCH_FRAC, tbptt_iters=TBPTT_BACKPROP_ITERS, ): h_backbone, aux_loss, h_mid_out = self.forward_backbone( input_ids, n_shared_iters=n_shared_iters, tbptt_iters=tbptt_iters, ) if echo_batch_frac > 0.0: if dds_depth is None: dds_depth = ECHOCausalSelfRecursion.sample_dds_depth() dds_depth = min(dds_depth, len(target_horizons) - 1) b_echo = max(1, int(round(input_ids.size(0) * echo_batch_frac))) h_echo_in = h_backbone[:b_echo] future_embs = [ self.embed_tokens(target_horizons[k - 1][:b_echo]) for k in range(1, dds_depth + 1) ] horizon_states = self.echo(self.coda[-1], h_echo_in, future_embs) norm_fn = ( self._final_norm_compiled if (self.training and self._final_norm_compiled is not None) else self._apply_final_norm ) rmid_loss = None if self.ce_backend == "cut_cross_entropy" and dds_depth == 1: parts_h = [h_backbone, horizon_states[0]] parts_t = [target_horizons[0], target_horizons[1][:b_echo]] if h_mid_out is not None: parts_h.append(h_mid_out) parts_t.append(target_horizons[0][: h_mid_out.size(0)]) h_norm = norm_fn(torch.cat(parts_h, dim=0)) t_cat = torch.cat(parts_t, dim=0) losses = _cce_linear_cross_entropy( h_norm.reshape(-1, D_VOCAB), self.tok_emb.weight, t_cat.reshape(-1), reduction="none", ) T_seq = h_backbone.size(1) n_main = h_backbone.size(0) * T_seq n_echo = horizon_states[0].size(0) * T_seq lm_loss = losses[:n_main].mean() echo_loss = losses[n_main : n_main + n_echo].mean() if h_mid_out is not None: rmid_loss = losses[n_main + n_echo :].mean() else: lm_loss = self.compute_lm_loss(h_backbone, target_horizons[0]) if dds_depth == 1: echo_loss = self.compute_lm_loss( horizon_states[0], target_horizons[1][:b_echo] ) else: echo_losses = [ self.compute_lm_loss( horizon_states[k - 1], target_horizons[k][:b_echo] ) for k in range(1, dds_depth + 1) ] echo_loss = torch.stack(echo_losses).mean() if h_mid_out is not None: rmid_loss = self.compute_lm_loss( h_mid_out, target_horizons[0][: h_mid_out.size(0)] ) total_loss = lm_loss + ECHO_LOSS_COEFF * echo_loss + aux_loss if rmid_loss is not None: mono_hinge = F.relu(lm_loss - rmid_loss.detach() + 0.01) total_loss = total_loss + RMID_LOSS_COEFF * rmid_loss + MONO_LOSS_COEFF * mono_hinge echo_det = echo_loss.detach() else: lm_loss = self.compute_lm_loss(h_backbone, target_horizons[0]) total_loss = lm_loss + aux_loss echo_det = None return total_loss, { "lm_loss": lm_loss.detach(), "echo_loss": echo_det, "aux_loss": aux_loss.detach(), "total_loss": total_loss.detach(), } @torch.no_grad() def generate( self, prompt_ids, max_new_tokens=32, effort="medium", temperature=0.8, top_p=0.9 ): """Eager autoregressive generation with configurable thinking effort ('low'=8, 'medium'=16, 'high'=24, 'xhigh'=32, 'max'=40 total loops). """ self.eval() self.set_telemetry(False) total_loops = ( EFFORT_TOTAL_LOOPS[effort] if isinstance(effort, str) else int(effort) ) n_iters = max(1, (total_loops - N_PRELUDE - N_CODA) // N_SHARED_CELL_BLOCKS) seq = prompt_ids.clone() for _ in range(max_new_tokens): ctx = seq[:, -SEQ_LEN:] h_out, _, _ = self.forward_backbone(ctx, n_shared_iters=n_iters, tbptt_iters=None) h_last = self._apply_final_norm(h_out[:, -1, :]) logits = F.linear(h_last, self.tok_emb.weight).float() if temperature <= 0.0: next_tok = logits.argmax(dim=-1, keepdim=True) else: probs = F.softmax(logits / temperature, dim=-1) sorted_probs, sorted_idx = torch.sort(probs, descending=True) cum_probs = torch.cumsum(sorted_probs, dim=-1) mask = (cum_probs - sorted_probs) > top_p sorted_probs[mask] = 0.0 sorted_probs.div_(sorted_probs.sum(dim=-1, keepdim=True)) sampled = torch.multinomial(sorted_probs, num_samples=1) next_tok = torch.gather(sorted_idx, -1, sampled) seq = torch.cat([seq, next_tok], dim=1) return seq @torch.no_grad() def echo_speculative_draft_test(self, input_ids, draft_depth=2, effort="medium"): self.eval() self.set_telemetry(False) total_loops = ( EFFORT_TOTAL_LOOPS[effort] if isinstance(effort, str) else int(effort) ) n_iters = max(1, (total_loops - N_PRELUDE - N_CODA) // N_SHARED_CELL_BLOCKS) h_backbone, _, _ = self.forward_backbone( input_ids, n_shared_iters=n_iters, tbptt_iters=None ) h_norm = self._apply_final_norm(h_backbone[:, -1:, :]) tok_k0 = F.linear(h_norm, self.tok_emb.weight).argmax(dim=-1) drafted = [tok_k0] x1, x2 = h_backbone.chunk(2, dim=-1) cur_tok = tok_k0 shifted_ids = input_ids for _ in range(draft_depth): shifted_ids = torch.cat([shifted_ids[:, 1:], cur_tok], dim=1) emb_step = self.embed_tokens(shifted_ids) x1, x2 = self.echo.fuse_step(x1, x2, emb_step) x1, x2, _ = self.coda[-1](x1, x2) h_k = self._apply_final_norm(torch.cat([x1[:, -1:, :], x2[:, -1:, :]], dim=-1)) cur_tok = F.linear(h_k, self.tok_emb.weight).argmax(dim=-1) drafted.append(cur_tok) return torch.cat(drafted, dim=1) # ======================== 8-BIT BLOCKWISE MUON + FUSED FP32 ADAMW OPTIMIZER def _zeropower_polar_express_bf16(G, steps=MUON_NS_STEPS): """5-step Polar Express orthogonalization (arXiv:2505.16932v2): -57% BF16 spectral error.""" X = G.bfloat16() transposed = G.size(0) > G.size(1) if transposed: X = X.T X = X / (X.float().norm().mul(1.01).to(X.dtype) + 1e-7) for a, b, c in POLAR_EXPRESS_SAFE[:steps]: A = X @ X.T B = b * A + c * (A @ A) X = a * X + B @ X return (X.T if transposed else X).float() def _adamw_update_bf16_compiled(p, g, m, v, lr_t, wd, b1, b2, bc1_t, bc2_t): """Compiled zero-recompile BF16 AdamW (0-D tensor scalars -> 1 single Triton kernel!).""" m.mul_(b1).add_(g, alpha=1.0 - b1) v.mul_(b2).addcmul_(g, g, value=1.0 - b2) p_fp32 = p.float() * (1.0 - lr_t * wd) - lr_t * (m / bc1_t) / ((v / bc2_t).sqrt() + 1e-8) return stochastic_round_bf16(p_fp32) class Muon8BitWithAdamW: """8-Bit Blockwise Muon (BF16 NS5) + Fused CUDA FP32 AdamW + Eager BF16 tok_emb AdamW.""" def __init__( self, model, lr_muon=LR_CORE_MUON, lr_adamw=LR_CORE_ADAMW, momentum=0.95, nesterov=True, ns_steps=MUON_NS_STEPS, block_size=MUON_BLOCK_PAPER, betas=(0.9, 0.95), weight_decay=WEIGHT_DECAY_CORE, compile_kernels=USE_TORCH_COMPILE, ): self.lr_muon = lr_muon self.lr_adamw = lr_adamw self.momentum = momentum self.nesterov = nesterov self.ns_steps = ns_steps self.block_size = block_size self.betas = betas self.weight_decay = weight_decay self.step_count = 0 self._ns5_fn = ( torch.compile(_zeropower_polar_express_bf16, mode="default", dynamic=True) if (compile_kernels and hasattr(torch, "compile")) else _zeropower_polar_express_bf16 ) self._adamw_bf16_fn = ( torch.compile(_adamw_update_bf16_compiled, mode="default") if (compile_kernels and hasattr(torch, "compile")) else _adamw_update_bf16_compiled ) self.params_2d, self.params_1d = partition_muon_adamw_params( model.named_parameters() ) shared_ids = {id(p) for p in model.shared_core.parameters()} echo_ids = {id(p) for p in model.echo.parameters()} self.muon_state = {} for p in self.params_2d: n_el = p.numel() n_blk = math.ceil(n_el / block_size) self.muon_state[id(p)] = { "q_mom": torch.zeros(n_el, device=p.device, dtype=torch.int8), "scales": torch.zeros(n_blk, device=p.device, dtype=torch.float32), "v_row": torch.zeros(p.size(0), device=p.device, dtype=torch.float32), "lr_base": LR_SHARED_MUON if id(p) in shared_ids else lr_muon, } # Split FP32 AdamW: decayed 2D/3D, zero-WD 1D/gates/ZOH, and 2x-LR echo params fp32_decay, fp32_nodecay, fp32_echo = [], [], [] self.params_1d_bf16 = [] for p in self.params_1d: if p.dtype != torch.float32: self.params_1d_bf16.append(p) elif id(p) in echo_ids: fp32_echo.append(p) elif p.ndim >= 2: fp32_decay.append(p) else: fp32_nodecay.append(p) adamw_groups = [] if fp32_decay: adamw_groups.append({"params": fp32_decay, "weight_decay": weight_decay, "lr_mult": 1.0}) if fp32_nodecay: adamw_groups.append({"params": fp32_nodecay, "weight_decay": 0.0, "lr_mult": 1.0}) if fp32_echo: adamw_groups.append({"params": fp32_echo, "weight_decay": 0.0, "lr_mult": 2.0}) self.adamw_fp32_opt = ( torch.optim.AdamW( adamw_groups, lr=lr_adamw, betas=betas, fused=torch.cuda.is_available(), ) if adamw_groups else None ) self.adamw_bf16_state = { id(p): { "m": torch.zeros_like(p, dtype=torch.float32), "v": torch.zeros_like(p, dtype=torch.float32), } for p in self.params_1d_bf16 } @staticmethod def quantize_int8_blockwise(x_flat, block_size): n_el = x_flat.numel() n_blk = math.ceil(n_el / block_size) pad = n_blk * block_size - n_el x_pad = F.pad(x_flat.float(), (0, pad)) if pad > 0 else x_flat.float() blocks = x_pad.view(n_blk, block_size) scales = blocks.abs().amax(dim=-1) / 127.0 q = torch.clamp( torch.round(blocks / scales.clamp_min(1e-12).unsqueeze(-1)), -127, 127 ).to(torch.int8) return q.view(-1)[:n_el], scales @staticmethod def dequantize_int8_blockwise(q_flat, scales, block_size, shape): n_el = q_flat.numel() n_blk = scales.numel() pad = n_blk * block_size - n_el q_pad = F.pad(q_flat, (0, pad)) if pad > 0 else q_flat x = q_pad.float().view(n_blk, block_size) * scales.unsqueeze(-1) return x.view(-1)[:n_el].view(shape) @torch.no_grad() def step(self, lr_scale=1.0): self.step_count += 1 lr_m = self.lr_muon * lr_scale lr_a = self.lr_adamw * lr_scale for p in self.params_2d: if p.grad is None: continue g = p.grad.float() st = self.muon_state[id(p)] m = self.dequantize_int8_blockwise( st["q_mom"], st["scales"], self.block_size, p.shape ) m = self.momentum * m + g st["q_mom"], st["scales"] = self.quantize_int8_blockwise( m.reshape(-1), self.block_size ) u_in = (g + self.momentum * m) if self.nesterov else m lr_p = st["lr_base"] * lr_scale ortho = self._ns5_fn(u_in, self.ns_steps) v_row = st["v_row"] v_row.mul_(0.95).add_(ortho.pow(2).mean(dim=-1), alpha=0.05) v_hat = v_row / (1.0 - 0.95 ** self.step_count) ortho = ortho / (v_hat.sqrt().unsqueeze(-1) + 1e-8) rms_scale = (0.2 * math.sqrt(p.numel())) / ortho.norm().clamp_min(1e-8) p_fp32 = p.float() if self.weight_decay > 0.0: p_fp32.sub_(p_fp32 * (ortho * p_fp32 >= 0.0).float(), alpha=lr_p * self.weight_decay) p_fp32.add_(ortho * (-lr_p * rms_scale)) write_back_(p, p_fp32) if self.adamw_fp32_opt is not None: for pg in self.adamw_fp32_opt.param_groups: pg["lr"] = lr_a * pg.get("lr_mult", 1.0) self.adamw_fp32_opt.step() b1, b2 = self.betas bc1 = 1.0 - b1 ** self.step_count bc2 = 1.0 - b2 ** self.step_count for p in self.params_1d_bf16: if p.grad is None: continue st = self.adamw_bf16_state[id(p)] lr_t = torch.tensor(lr_a, device=p.device, dtype=torch.float32) bc1_t = torch.tensor(bc1, device=p.device, dtype=torch.float32) bc2_t = torch.tensor(bc2, device=p.device, dtype=torch.float32) p.copy_( self._adamw_bf16_fn( p, p.grad.float(), st["m"], st["v"], lr_t, self.weight_decay, b1, b2, bc1_t, bc2_t ) ) # =========================================== PRE-FLIGHT MATHEMATICAL CHECKS def run_preflight_checks(device): prev_tf32 = torch.backends.cuda.matmul.allow_tf32 torch.backends.cuda.matmul.allow_tf32 = False try: _preflight_checks(device) finally: torch.backends.cuda.matmul.allow_tf32 = prev_tf32 def _preflight_checks(device): banner("STEP 1 - Pre-Flight Paper-Exact Mathematical & Kernel Verification") # 1. Stable Symmetric GDN-2 (Block-Schur Inverse) Chunkwise WY vs. Recurrence torch.manual_seed(42) q = l2_norm(torch.randn(1, 64, N_HEADS, HEAD_DIM, device=device)) k = l2_norm(torch.randn(1, 64, N_HEADS, HEAD_DIM, device=device)) v = torch.randn(1, 64, N_HEADS, HEAD_DIM, device=device) g = -F.softplus(torch.randn(1, 64, N_HEADS, 1, device=device) - 1.5) b = torch.sigmoid(torch.randn(1, 64, N_HEADS, HEAD_DIM, device=device)) w = torch.sigmoid(torch.randn(1, 64, N_HEADS, HEAD_DIM, device=device)) o_rec, s_rec = GatedDeltaNet2.recurrent_scan( q, k, v, g, b, w, stable_symmetric=True ) o_wy, s_wy = GatedDeltaNet2.chunkwise_wy( q, k, v, g, b, w, chunk_size=16, stable_symmetric=True, use_bf16_gram=False ) err_sym_wy = max( (o_rec - o_wy).abs().max().item(), (s_rec - s_wy).abs().max().item() ) print( f" [{'PASS' if err_sym_wy < 1e-5 else 'FAIL'}] Stable Symmetric GDN-2 (Block-Schur WY) == Recurrence " f"(max|err| = {err_sym_wy:.3e} < 1e-5)" ) assert err_sym_wy < 1e-5 # 2. Vectorized Banded-Diagonal Flash-HiSA vs. Reference Tile-by-Tile Flash-HiSA swa = HiSASlidingWindowAttention( use_reversible_mola=True, use_flex_attention=False ).to(device) qr = torch.randn(1, N_HEADS, 256, HEAD_DIM, device=device) kr = torch.randn(1, N_HEADS, 256, HEAD_DIM, device=device) s_ref = swa._scores_block_reference(qr, kr) s_fast = swa._scores_block_fast(qr, kr) err_hisa = (s_ref - s_fast).abs().max().item() print( f" [{'PASS' if err_hisa < 1e-5 else 'FAIL'}] Banded-Diagonal Flash-HiSA (arXiv:2611.26363) == Reference Block Rule " f"(max|err| = {err_hisa:.3e} < 1e-5)" ) assert err_hisa < 1e-5 # 3. FLA Blackwell Determinism & Finiteness Check if USE_FLA_GDN and _HAS_FLA and device.type == "cuda": import fla qf = F.normalize(torch.randn(4, 256, N_HEADS, HEAD_DIM, device=device, dtype=torch.bfloat16), dim=-1) kf = F.normalize(torch.randn(4, 256, N_HEADS, HEAD_DIM, device=device, dtype=torch.bfloat16), dim=-1) vf = torch.randn(4, 256, N_HEADS, HEAD_DIM, device=device, dtype=torch.bfloat16) gf = -F.softplus(torch.randn(4, 256, N_HEADS, device=device, dtype=torch.float32) - 1.5) bf = torch.sigmoid(torch.randn(4, 256, N_HEADS, device=device, dtype=torch.float32)) o1, _ = _fla_chunk_gdn(qf, kf, vf, g=gf, beta=bf, scale=1.0) o2, _ = _fla_chunk_gdn(qf, kf, vf, g=gf, beta=bf, scale=1.0) diff_det = ((o1 - o2).float().norm() / o1.float().norm().clamp_min(1e-12)).item() is_fin = bool(torch.isfinite(o1).all().item()) fla_ver = getattr(fla, "__version__", "unknown") print( f" [{'PASS' if (diff_det < 1e-4 and is_fin) else 'FAIL'}] FLA ({fla_ver}) Blackwell Determinism " f"(rel L2 diff = {diff_det:.3e}, finite = {is_fin})" ) assert diff_det < 1e-4 and is_fin, "FLA Blackwell forward corruption detected! Upgrade flash-linear-attention>=0.6.0" # =========================================================== MAIN TRAINING def main(): rank, local_rank, world_size, device = init_distributed() is_main = (rank == 0) if is_main: run_preflight_checks(device) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True if hasattr(torch, "_dynamo"): torch._dynamo.config.cache_size_limit = 64 if is_main: banner( f"STEP 2 - Loading Hugging Face Tokenizer ({TOKENIZER_HF_REPO}) & Streaming Wikipedia " f"(world_size={world_size}, A100 BF16 + {world_size}-Way Sharded Sparse)" ) tokenizer = load_internet_tokenizer() vocab_size = tokenizer.get_vocab_size() n_tok, np_dtype, val_prompts = prepare_internet_wiki_memmap( tokenizer, vocab_size, out_path=MEMMAP_BIN_PATH, prompts_path=VAL_PROMPTS_JSON, max_tokens=MEMMAP_MAX_TOKENS, ) if dist_is_active(): dist.barrier() if not is_main: tokenizer = load_internet_tokenizer() vocab_size = tokenizer.get_vocab_size() n_tok, np_dtype, val_prompts = prepare_internet_wiki_memmap( tokenizer, vocab_size, out_path=MEMMAP_BIN_PATH, prompts_path=VAL_PROMPTS_JSON, max_tokens=MEMMAP_MAX_TOKENS, ) canonical_map, n_canonical, comp_ratio = build_engram_canonical_map( tokenizer, vocab_size, device ) if is_main: print( f" Raw Vocabulary Size : {vocab_size:,d} tokens -> " f"Engram Canonical Vocab: {n_canonical:,d} tokens (-{100 * comp_ratio:.1f}% surface redundancy)" ) extra_horizon = 4 if ECHO_FIXED_DEPTH is None else max(2, ECHO_FIXED_DEPTH + 1) loader = FastMemmapLoader( MEMMAP_BIN_PATH, np_dtype, seq_len=SEQ_LEN, batch_size=BATCH_SIZE, device=device, extra_horizon=extra_horizon, val_prompts=val_prompts, seed=1234 + rank * 997, ) if is_main: print( f" FastMemmapLoader active ({n_tok:,d} tokens, zero CPU tokenization, {world_size} rank(s)). " f"Collected {len(loader.val_prompts)} Wikipedia test prompts." ) try: banner( "STEP 3 - Instantiating Final Locked Architecture: Prelude(1)+SharedCore(2)+Coda(1) + Factorized LM(1024) + 11.50B GDDR7 (1.5B Engram + 10B UltraMemV2 topK=32)" ) if torch.cuda.is_available(): free_b, total_b = torch.cuda.mem_get_info() print( f" GPU VRAM Before Init : {(total_b - free_b) / GiB:.2f} GiB used / {total_b / GiB:.2f} GiB total" ) t_init0 = time.perf_counter() torch.manual_seed(42) # identical dense init across all ranks model = L2GDDR7HybridLanguageModel(vocab_size, canonical_map, device, rank=rank, world_size=world_size) model = cast_model_preserve_fp32_1d(model, device) if dist_is_active(): for p in model.parameters(): dist.broadcast(p.data, src=0) for b in model.buffers(): dist.broadcast(b.data, src=0) n_fp8_layers, n_nvfp4_layers, nvfp4_backend = enable_precision_recipes(model, device) compiled_ok = model.compile_hot_paths(USE_TORCH_COMPILE and device.type == "cuda") opt_dense = Muon8BitWithAdamW( model, compile_kernels=USE_TORCH_COMPILE and device.type == "cuda" ) if torch.cuda.is_available(): torch.cuda.synchronize() t_init = time.perf_counter() - t_init0 prelude_params = sum(p.numel() for p in model.prelude.parameters()) shared_params = sum(p.numel() for p in model.shared_core.parameters()) coda_params = sum(p.numel() for p in model.coda.parameters()) core_params = prelude_params + shared_params + coda_params router_echo_params = ( sum(p.numel() for p in model.engram.parameters()) + sum(p.numel() for p in model.bridge.parameters()) + sum(p.numel() for p in model.echo.parameters()) + model.final_norm.numel() ) vocab_params = model.tok_emb.weight.numel() + model.emb_up.weight.numel() + model.lm_down.weight.numel() engram_sparse_params = model.engram.sparse_table.weight.numel() ultramem_sparse_params = model.bridge.sparse_table.weight.numel() total_sparse_params = engram_sparse_params + ultramem_sparse_params total_params = ( core_params + router_echo_params + vocab_params + total_sparse_params ) sparse_gddr7_bytes = ( model.engram.sparse_table.memory_bytes() + model.bridge.sparse_table.memory_bytes() ) gdn_desc = ( "FLA Triton chunk_gated_delta_rule (in-kernel L2Norm/Gate/Beta)" if (model.shared_core[0].gdn.use_fla and device.type == "cuda") else f"Chunk-{GDN_CHUNK_SIZE} Block-Schur WY ({'Symmetric' if model.shared_core[0].gdn.stable_symmetric else 'Asymmetric'})" ) print(f" Initialization time : {t_init:.2f} s") print(f" Precision recipes : torchao FP8 = {n_fp8_layers} layers | NVFP4 = {n_nvfp4_layers} ({nvfp4_backend})") print(f" torch.compile hot paths enabled : {compiled_ok} (core mode={CORE_COMPILE_MODE})") l2_active_fp8_mib = (shared_params + router_echo_params) / MiB l2_total_fp8_mib = (core_params + router_echo_params) / MiB print(f" Depth schedule / TBPTT : Prelude({N_PRELUDE}) + {N_SHARED_CELL_BLOCKS}-Block Sequential SharedCell(Blk0=GDN2-16h+OrthoInj -> Blk1=SWA+MoLA-16h+UltraMemV2+PostCellNorm, DeepBucket mean={PLN_MAIN_MEAN_ITERS:.1f}->{PLN_ANNEAL_MEAN_ITERS:.1f} iters, TBPTT={TBPTT_BACKPROP_ITERS}) + Coda({N_CODA})") print(f" L2 Cache Residency Estimate (128 MiB L2): Active Shared+Routers ~{l2_active_fp8_mib:.1f} MiB FP8 | All Dense ~{l2_total_fp8_mib:.1f} MiB FP8") print(f" Layer-2 Engram async CUDA stream : {model._engram_stream is not None}") print(f" Multi-hop UltraMemV2 MoD gate : top {100 * MEM_CAPACITY_FRAC:.1f}% tokens/block (EMA eval_thr)") print(f" Cross-Entropy backend : {model.ce_backend} (sub={LIGER_SUB_BATCH_TOKENS}, ECHO {int(ECHO_BATCH_FRAC*100)}% batch/micro)") if PREFER_CUT_CE and not _HAS_CUT_CE: print(f" (Cut Cross-Entropy import note: {_CCE_IMPORT_ERR})") print(f" GDN-2 kernel backend : {gdn_desc} | LocalMix=SWGDN2-G1 Intra-SWA(W={GDN_CONV_KERNEL}) | FlashQLA={_HAS_FLASH_QLA}") print(f" Sparse Adam / QuACK kernels : {'1-Pass Triton Row-v' if (_HAS_TRITON and device.type == 'cuda') else 'PyTorch Row-v'} | QuACK-RMS={_HAS_QUACK_RMS}") print(f" Custom Triton Kernels : UltraMemGatherReduce={'ON' if (_HAS_TRITON and device.type == 'cuda') else 'Fallback'} | TDQKR-TopK={'ON' if (_HAS_TRITON and device.type == 'cuda') else 'Fallback'} | OrthoInj-ZOH={'ON' if (_HAS_TRITON and device.type == 'cuda') else 'Fallback'} | SWGDN2-SWA={'ON' if (_HAS_TRITON and device.type == 'cuda') else 'Fallback'} | MoD-GateScatter={'ON' if (_HAS_TRITON and device.type == 'cuda') else 'Fallback'} | MoLA-CustomOp={'ON' if (_HAS_MOLA_CUSTOM_OP and _HAS_TRITON and device.type == 'cuda') else 'Fallback'} | CachedFP8Core={USE_CACHED_FP8_CORE}") if USE_FLA_GDN and not _HAS_FLA: print(f" (FLA import note: {_FLA_IMPORT_ERR})") print(f" On-Chip L2 Prelude+Shared+Coda params : {core_params:,d} ({core_params / 1e6:.2f} M; shared block = {shared_params / 1e6:.2f} M)") print(f" On-Chip L2 Routers + IVE + ECHO params : {router_echo_params:,d} ({router_echo_params / 1e6:.2f} M)") print(f" Outer Tied Vocab Embeddings / LM Head : {vocab_params:,d} ({vocab_params / 1e6:.2f} M)") print(f" Tier 1 GDDR7 Engram N-Gram Table : {engram_sparse_params:,d} ({engram_sparse_params / 1e9:.3f} B)") print(f" Tier 2 GDDR7 UltraMemV2 TDQKR Table : {ultramem_sparse_params:,d} ({ultramem_sparse_params / 1e9:.3f} B)") print(f" TOTAL MODEL PARAMETERS : {total_params:,d} ({total_params / 1e9:.3f} Billion)") print(f" GDDR7 Sparse Tables + 8-Bit Lazy State : {sparse_gddr7_bytes / GiB:.2f} GiB") if torch.cuda.is_available(): alloc_b = torch.cuda.memory_allocated() print(f" Total GPU VRAM Allocated : {alloc_b / GiB:.2f} GiB") # ======================================================= TRAINING LOOP banner( f"STEP 4 - End-to-End Pretraining on Wikipedia ({MAX_STEPS} Steps, " f"{BATCH_SIZE * SEQ_LEN * GRAD_ACCUM_STEPS:,d} tok/step)" ) header = ( f"{'Step':>4} | {'Lp':>2} | {'tok/s':>7} | {'TotLoss':>7} | {'LMLoss':>6} | {'PPL':>7} | " f"{'ECHOLoss':>8} | {'AuxBal':>7} | {'gCore':>5} | {'gRtr':>5} | {'gSprs':>5} | " f"{'EngGate':>7} | {'MemGt':>5} | {'MemEnt':>6} | {'ActSlots':>8} | {'BrgRMS':>6}" ) print(header) print("-" * len(header)) grad_accum_local = max(1, GRAD_ACCUM_STEPS // world_size) model.train() tokens_per_step = BATCH_SIZE * SEQ_LEN * grad_accum_local * world_size history = [] depth_rng = np.random.default_rng(1337) shared_core_params = list(model.shared_core.parameters()) other_dense_params = ( list(model.prelude.parameters()) + list(model.coda.parameters()) + list(model.engram.parameters()) + list(model.bridge.parameters()) + list(model.echo.parameters()) + (list(model.loop_cond.parameters()) if model.loop_cond is not None else []) + (list(model.tala_base.parameters()) if model.tala_base is not None else []) + [model.tok_emb.weight, model.emb_up.weight, model.lm_down.weight, model.final_norm] ) sparse_opt_stream = ( torch.cuda.Stream(device=device) if (ENABLE_ASYNC_SPARSE_ADAM and torch.cuda.is_available() and device.type == "cuda") else None ) bwd_done_event = torch.cuda.Event() if sparse_opt_stream is not None else None sparse_done_event = torch.cuda.Event() if sparse_opt_stream is not None else None if torch.cuda.is_available(): torch.cuda.synchronize() t_window = time.perf_counter() steps_in_window = 0 warmup_steps = max(10, int(0.05 * MAX_STEPS)) cooldown_start = int(0.80 * MAX_STEPS) for step in range(1, MAX_STEPS + 1): log_this_step = (step == 1) or (step % LOG_EVERY == 0) or (step == MAX_STEPS) model.zero_grad(set_to_none=True) # WSD (1-sqrt) LR schedule synchronized with PLN depth annealing at 80% in_cooldown = step > cooldown_start if step <= warmup_steps: lr_scale = step / float(warmup_steps) elif not in_cooldown: lr_scale = 1.0 else: t_cd = (step - cooldown_start) / max(1, MAX_STEPS - cooldown_start) lr_scale = 0.05 + 0.95 * (1.0 - math.sqrt(min(1.0, max(0.0, t_cd)))) accum_lm = torch.zeros((), device=device, dtype=torch.float32) accum_echo = torch.zeros((), device=device, dtype=torch.float32) accum_aux = torch.zeros((), device=device, dtype=torch.float32) accum_tot = torch.zeros((), device=device, dtype=torch.float32) echo_micro_count = 0 step_loops_sum = 0 step_tbptt, _, _, _ = get_progressive_depth_stage(step, MAX_STEPS) for micro_idx in range(grad_accum_local): # Synchronized per-microbatch depth sampling across all ranks (zero straggler skew!) n_iters = sample_pln_shared_iters(step, MAX_STEPS, depth_rng) step_loops_sum += N_PRELUDE + n_iters * N_SHARED_CELL_BLOCKS + N_CODA model.set_telemetry( log_this_step and (micro_idx == grad_accum_local - 1) ) x_ids, target_horizons = loader.next_batch() loss, m_dict = model.forward_train( x_ids, target_horizons, n_shared_iters=n_iters, dds_depth=ECHO_FIXED_DEPTH, echo_batch_frac=ECHO_BATCH_FRAC, tbptt_iters=step_tbptt, ) (loss / grad_accum_local).backward() if log_this_step: accum_lm += m_dict["lm_loss"] accum_aux += m_dict["aux_loss"] accum_tot += m_dict["total_loss"] if m_dict["echo_loss"] is not None: accum_echo += m_dict["echo_loss"] echo_micro_count += 1 total_loops_step = int(round(step_loops_sum / grad_accum_local)) # Overlap sparse_adam_step on secondary CUDA stream behind clip + opt_dense.step() (NorMuon)! # Dense params and GDDR7 sparse tables are 100% disjoint; bwd_done/sparse_done events ensure order. if sparse_opt_stream is not None: bwd_done_event.record() with torch.cuda.stream(sparse_opt_stream): sparse_opt_stream.wait_event(bwd_done_event) model.engram.sparse_table.sparse_adam_step( lr=LR_CORE_ADAMW * LR_ENGRAM_MULT * lr_scale, collect_telemetry=log_this_step, defer_telemetry=True, ) model.bridge.sparse_table.sparse_adam_step( lr=LR_CORE_ADAMW * LR_ULTRAMEM_MULT * lr_scale, collect_telemetry=log_this_step, defer_telemetry=True, ) sparse_done_event.record(sparse_opt_stream) # Hybrid DDP AllReduce over ~170M dense params (overlapped with sharded sparse_opt_stream!) if dist_is_active(): for p in model.parameters(): if p.grad is not None: dist.all_reduce(p.grad, op=dist.ReduceOp.AVG) # Decoupled grad clipping: shared_core (TBPTT multi-visit) vs prelude/coda/routers gnorm_core_t = torch.nn.utils.clip_grad_norm_( shared_core_params, MAX_GRAD_NORM ) gnorm_router_t = torch.nn.utils.clip_grad_norm_( other_dense_params, MAX_GRAD_NORM ) opt_dense.step(lr_scale=lr_scale) if USE_CACHED_FP8_CORE: invalidate_all_fp8_caches(model) # LR-coupled DeepSeek-V3 bias update (only freeze final 2% so MemEnt stays >0.98 in cooldown!) bias_gamma = ( 0.0 if step > int(0.98 * MAX_STEPS) else ULTRAMEM_BIAS_GAMMA * max(0.50, lr_scale) ) model.bridge.update_routing_bias_and_ema( gamma=bias_gamma, collect_telemetry=log_this_step, ) if sparse_opt_stream is not None: torch.cuda.current_stream().wait_event(sparse_done_event) else: model.engram.sparse_table.sparse_adam_step( lr=LR_CORE_ADAMW * LR_ENGRAM_MULT * lr_scale, collect_telemetry=log_this_step, ) model.bridge.sparse_table.sparse_adam_step( lr=LR_CORE_ADAMW * LR_ULTRAMEM_MULT * lr_scale, collect_telemetry=log_this_step, ) steps_in_window += 1 if log_this_step: if torch.cuda.is_available(): torch.cuda.synchronize() model.engram.sparse_table.finalize_telemetry() model.bridge.sparse_table.finalize_telemetry() dt_window = max(time.perf_counter() - t_window, 1e-6) tok_per_sec = (tokens_per_step * steps_in_window) / dt_window t_window = time.perf_counter() steps_in_window = 0 inv_accum = 1.0 / grad_accum_local lm_l = float((accum_lm * inv_accum).item()) echo_l = float((accum_echo / max(1, echo_micro_count)).item()) aux_l = float((accum_aux * inv_accum).item()) tot_l = float((accum_tot * inv_accum).item()) ppl = math.exp(min(lm_l, 15.0)) gnorm_core = float(gnorm_core_t.item()) gnorm_router = float(gnorm_router_t.item()) gnorm_sparse = math.hypot( model.engram.sparse_table.last_grad_norm, model.bridge.sparse_table.last_grad_norm, ) eng_gate = model.engram.last_gate_mean mem_gt = model.shared_core[-1].last_mem_gate_mean mem_ent = model.bridge.last_entropy_norm act_slots = ( model.engram.sparse_table.last_unique_count + model.bridge.sparse_table.last_unique_count ) brg_rms = model.bridge.last_bridge_rms_ratio rec = { "step": step, "loops": total_loops_step, "tok_s": tok_per_sec, "tot_loss": tot_l, "lm_loss": lm_l, "ppl": ppl, "echo_loss": echo_l, "aux_loss": aux_l, "gnorm_core": gnorm_core, "gnorm_router": gnorm_router, "gnorm_sparse": gnorm_sparse, "eng_gate": eng_gate, "mem_gt": mem_gt, "mem_ent": mem_ent, "act_slots": act_slots, "brg_rms": brg_rms, } history.append(rec) if is_main: print( f"{step:4d} | {total_loops_step:2d} | {tok_per_sec:7.0f} | {tot_l:7.3f} | " f"{lm_l:6.3f} | {ppl:7.1f} | {echo_l:8.3f} | {aux_l:7.4f} | " f"{gnorm_core:5.2f} | {gnorm_router:5.2f} | {gnorm_sparse:5.2f} | " f"{eng_gate:7.3f} | {mem_gt:5.3f} | {mem_ent:6.3f} | {act_slots * world_size:8,d} | {brg_rms:6.3f}" ) # ============================================= TELEMETRY HEALTH SUMMARY banner("STEP 5 - Training & Sparse Memory Block Health Summary") steady_records = history[1:] if len(history) > 1 else history steady_tok_s = sum(r["tok_s"] for r in steady_records) / max(1, len(steady_records)) eng_visited = int(model.engram.sparse_table.visited_mask.sum().item()) ult_visited = int(model.bridge.sparse_table.visited_mask.sum().item()) print(f" Sustained Training Throughput : {steady_tok_s:,.0f} tok/s") print(f" Initial -> Final Main LM Loss (PPL) : {history[0]['lm_loss']:.3f} ({history[0]['ppl']:.1f}) -> {history[-1]['lm_loss']:.3f} ({history[-1]['ppl']:.1f})") print(f" Initial -> Final ECHO Horizon Loss : {history[0]['echo_loss']:.3f} -> {history[-1]['echo_loss']:.3f}") print(f" Layer-2 Engram Collision Gate : mean = {model.engram.last_gate_mean:.3f} +/- {model.engram.last_gate_std:.3f}") print(f" Shared Core Multi-Hop MemGate Mean : {model.shared_core[-1].last_mem_gate_mean:.3f} (Block-1 only, train cap = {100 * MEM_CAPACITY_FRAC:.1f}%, eval_thr = {[round(b.eval_thr.item(), 3) for b in model.shared_core if b.use_gated_mem]})") print(f" UltraMemV2 TDQKR Routing Entropy : {model.bridge.last_entropy_norm:.4f} (1.000 = ideal uniform slot usage)") print(f" UltraMemV2 Max Marginal Key Load Ratio : {model.bridge.last_max_load_ratio:.2f}x uniform") print(f" Unique GDDR7 Slots Written During Run : Engram = {eng_visited:,d} | UltraMemV2 = {ult_visited:,d} | Total = {eng_visited + ult_visited:,d}") if model.bridge.sparse_table.use_fp8: print( f" FP8 Sparse Tables (per-row w_scale+SR) : ACTIVE | Dead% (w_scale<1e-4): " f"Engram={100.0 * model.engram.sparse_table.last_dead_slot_frac:.2f}% | " f"UltraMemV2={100.0 * model.bridge.sparse_table.last_dead_slot_frac:.2f}%" ) print( f" Speedup Stack & Loop Conditioning : ProgDepth={ENABLE_PROGRESSIVE_DEPTH} | " f"AsyncSparseAdam={ENABLE_ASYNC_SPARSE_ADAM} | ContinuousLoopCond={ENABLE_CONTINUOUS_LOOP_COND}" ) lam_mean = float(torch.exp(-F.softplus(model.shared_core[0].zoh_log_decay_1.float())).mean().item()) print(f" Knowledge Bridge RMS Modulation Ratio : {model.bridge.last_bridge_rms_ratio:.4f} (bridge scale = {model.bridge.bridge_scale.item():.4f})") print(f" Shared Core ZOH Carryover Lambda Mean : {lam_mean:.4f} (healthy range ~0.88 - 0.97)") # ============================================ POST-TRAINING INFERENCE banner("STEP 6 - Configurable Thinking Effort (8 / 16 / 24 / 32 / 40 Loops) & ECHO Tests") if hasattr(loader, "data") and len(loader.data) >= 32 * (SEQ_LEN + 1): model.eval() model.set_telemetry(False) val_arr = ( torch.from_numpy(loader.data[-32 * (SEQ_LEN + 1) :].astype(np.int64)) .view(32, SEQ_LEN + 1) .to(device) ) val_x, val_y = val_arr[:, :SEQ_LEN], val_arr[:, 1:] print(f" Fixed Held-Out Validation PPL by Thinking Effort (eval_thr = {[round(b.eval_thr.item(), 3) for b in model.shared_core if b.use_gated_mem]}):") with torch.no_grad(): for eff_name, tot_l in EFFORT_TOTAL_LOOPS.items(): n_it = max(1, (tot_l - N_PRELUDE - N_CODA) // N_SHARED_CELL_BLOCKS) h_v, _, _ = model.forward_backbone(val_x, n_shared_iters=n_it, tbptt_iters=None) v_loss = model.compute_lm_loss(h_v, val_y).item() if is_main: print( f" {eff_name:>6} ({tot_l:2d} loops) -> Val Loss = {v_loss:.4f} | Val PPL = {math.exp(min(v_loss, 15.0)):7.2f} | StepRMS = {model.last_eval_step_rms:.4f}" ) test_prompts = ( loader.val_prompts[:3] if loader.val_prompts else [ "The history of artificial intelligence began in", "In physics and mathematics, the theory of", "Wikipedia is a free online encyclopedia created and edited by", ] ) for idx, prompt_str in enumerate(test_prompts, 1): enc = tokenizer.encode(prompt_str) p_ids = torch.tensor([enc.ids[:32]], dtype=torch.long, device=device) t_g0 = time.perf_counter() out_low = model.generate(p_ids, max_new_tokens=24, effort="low", temperature=0.7, top_p=0.9) dt_low = time.perf_counter() - t_g0 out_med = model.generate(p_ids, max_new_tokens=24, effort="medium", temperature=0.7, top_p=0.9) out_high = model.generate(p_ids, max_new_tokens=24, effort="high", temperature=0.7, top_p=0.9) draft_tokens = model.echo_speculative_draft_test(p_ids, draft_depth=2, effort="medium") draft_str = tokenizer.decode(draft_tokens[0].tolist()) if is_main: print(f"\n [Prompt {idx}] {prompt_str!r}") print(f" -> Low Effort (8 loops, {24 / dt_low:.1f} tok/s) : {tokenizer.decode(out_low[0].tolist())!r}") print(f" -> Med Effort (16 loops) : {tokenizer.decode(out_med[0].tolist())!r}") print(f" -> High Effort (24 loops) : {tokenizer.decode(out_high[0].tolist())!r}") print(f" -> ECHO 3-Token Speculative Step : tokenIds={draft_tokens[0].tolist()} decoded={draft_str!r}") finally: loader.close() if dist_is_active(): dist.destroy_process_group() if __name__ == "__main__": main()