Add recurrent-depth loop adapter (loop_r3), aligned MTP drafter v2, calibrated gate head, hardened serving plugin & stable recipe docs
3337c74 verified Download loop-adapter/training/loop_adapter.py from aidendle94/Inkling-2-Small-Looped-DGX-Spark: direct link, hf CLI and curl.
- Browser
- Download file 15.6 kB
-
https://huggingface.co/aidendle94/Inkling-2-Small-Looped-DGX-Spark/resolve/main/loop-adapter/training/loop_adapter.py
- Command line
-
hf download hf://aidendle94/Inkling-2-Small-Looped-DGX-Spark/loop-adapter/training/loop_adapter.py
-
curl -L -o loop_adapter.py https://huggingface.co/aidendle94/Inkling-2-Small-Looped-DGX-Spark/resolve/main/loop-adapter/training/loop_adapter.py
15.6 kB
| """Recurrent-depth loop adapter for Inkling-2-Small (48L, 8x6 AttnRes blocks). | |
| Architecture (stem layout — structurally bit-exact to stock at T=1): | |
| - Prelude (L0..core_start-1, default L0..29 = 5 AttnRes blocks): frozen, 0 adapters. | |
| Produces immutable prelude_blocks (b_0..b_4) and anchor = partial_{core_start-1} [S, D]. | |
| - Pass 0 (L30..41, 2 AttnRes blocks): frozen, 0 adapters -> s_0 = partial_{core_end-1}. | |
| - Pass p >= 1 (p = 1..T-1): | |
| 1. WorkspaceEntry(anchor, s_{p-1}; p_idx, rem_idx) -> new_partial [S, D] | |
| - FP32 internal math, rounded once to anchor.dtype | |
| - Learnable per-channel RMSNorm scales (w_s, w_a) | |
| - Low-rank mixer (cat([ns, na]) @ A) @ B (A: [2D, r_entry], B: [r_entry, D], B zero-init) | |
| - Conditioned on (p_idx, rem_idx = T - 1 - p) via per-slot zero-init gates gs, gm | |
| 2. Rewind AttnRes blocks to prelude_blocks (b_0..b_4) and run Core (L30..41) with: | |
| - CoreLoRA on attn.qkvr (rank 32), attn.wo_ud (rank 32), mlp.gate router (rank 16) | |
| each modulated by a learned (p_idx, rem_idx) scalar gate (init 1.0, LoRA B zero-init) | |
| - Optional CrossPassMixer at mid-core block boundary L36 (rank 128, zero-init gate) | |
| mixing pass (p-1)'s block-5 summary into pass p's block-5 summary | |
| - Optional LoopCD-Hidden (arXiv:2610.02185) on final state s_{T-1} vs s_{T-2} before Coda. | |
| - Coda (L42..47, 1 AttnRes block): | |
| - When T == 1: 0 adapters (100% bit-exact stock). | |
| - When T >= 2: CodaLoRA on attn.qkvr (rank 32) + attn.wo_ud (rank 32) -> frozen lm_head. | |
| MIT License, Copyright (c) 2026 Aiden Le. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import math | |
| from dataclasses import asdict, dataclass | |
| from pathlib import Path | |
| from typing import Any | |
| import torch | |
| import torch.nn as nn | |
| ENTRY_EPS: float = 1e-6 | |
| class InklingLoopConfig: | |
| hidden_size: int = 4608 | |
| num_layers: int = 48 | |
| n_layers_per_block: int = 6 | |
| core_start: int = 30 | |
| core_end: int = 42 # exclusive: Core = L30..41 (12L = 2 AttnRes blocks), Coda = L42..47 (6L = 1 block) | |
| max_train_passes: int = 3 # supports T in {1, 2, 3} with distinct (p_idx, rem_idx) slots | |
| entry_rank: int = 256 | |
| mixer_rank: int = 128 | |
| use_cross_pass_mixer: bool = True | |
| lora_rank_attn: int = 32 | |
| lora_alpha_attn: float = 32.0 | |
| lora_rank_router: int = 16 | |
| lora_alpha_router: float = 16.0 | |
| num_experts: int = 384 | |
| qkvr_out_dim_local: int = 8512 # will be set per-layer from actual qkvr weight shape | |
| qkvr_out_dim_global: int = 8512 | |
| wo_in_dim: int = 6144 # 48 heads * 128 head_dim | |
| def num_pass_slots(self) -> int: | |
| # Distinct (p_idx in 1..max_train_passes-1, rem_idx in 0..max_train_passes-2) | |
| # Compact mapping: slot(p, rem) -> clamped to [0, num_pass_slots - 1] | |
| # For max_train_passes=3: | |
| # (p=1, rem=0) -> 0 (final pass of T=2) | |
| # (p=1, rem=1) -> 1 (middle pass of T=3) | |
| # (p=2, rem=0) -> 2 (final pass of T=3) | |
| return max(1, (self.max_train_passes * (self.max_train_passes - 1)) // 2) | |
| def pass_slot(self, pass_idx: int, total_passes: int) -> int: | |
| """Map (pass_idx >= 1, total_passes >= 2) to a deterministic conditioning slot.""" | |
| assert pass_idx >= 1 and total_passes >= 2 | |
| rem = max(0, total_passes - 1 - pass_idx) | |
| if self.max_train_passes == 3: | |
| if pass_idx == 1 and rem == 0: | |
| return 0 | |
| if pass_idx == 1 and rem >= 1: | |
| return 1 | |
| return 2 # pass_idx >= 2 (final or deep pass) | |
| # General fallback | |
| p_clamped = min(pass_idx, self.max_train_passes - 1) | |
| r_clamped = min(rem, self.max_train_passes - 1 - p_clamped) | |
| # Triangular index | |
| idx = 0 | |
| for p in range(1, p_clamped): | |
| idx += (self.max_train_passes - p) | |
| return min(idx + r_clamped, self.num_pass_slots - 1) | |
| def _rms(x: torch.Tensor) -> torch.Tensor: | |
| return torch.sqrt(torch.mean(x * x, dim=-1, keepdim=True) + ENTRY_EPS) | |
| def loop_cd_hidden(final: torch.Tensor, ref: torch.Tensor, omega: float) -> torch.Tensor: | |
| """LoopCD-Hidden (arXiv:2610.02185): RMS-preserving hidden-state contrast in FP32.""" | |
| if omega == 0.0: | |
| return final | |
| mf = final.to(torch.float32) | |
| rf = ref.to(torch.float32) | |
| pushed = mf + float(omega) * (mf - rf) | |
| out = pushed * (_rms(mf) / _rms(pushed)) | |
| return out.to(final.dtype) | |
| class WorkspaceEntry(nn.Module): | |
| """Zero-initialized gated WorkspaceEntry conditioned on (p_idx, rem_idx). | |
| At initialization (gs = 0, gm = 0, B = 0), returns `anchor` bit-for-bit. | |
| """ | |
| def __init__(self, hidden_size: int, rank: int, num_slots: int) -> None: | |
| super().__init__() | |
| self.hidden_size = hidden_size | |
| self.rank = rank | |
| self.num_slots = num_slots | |
| self.w_s = nn.Parameter(torch.ones(hidden_size, dtype=torch.float32)) | |
| self.w_a = nn.Parameter(torch.ones(hidden_size, dtype=torch.float32)) | |
| self.gs = nn.Parameter(torch.zeros(num_slots, hidden_size, dtype=torch.float32)) | |
| self.gm = nn.Parameter(torch.zeros(num_slots, hidden_size, dtype=torch.float32)) | |
| # Shared low-rank projection A, B across slots (slots modulate via per-channel gs/gm). | |
| # B is small non-zero while gm=0 so Gate S1 is bit-exact at init WITHOUT a 0*0 saddle! | |
| a = torch.empty(2 * hidden_size, rank, dtype=torch.float32) | |
| nn.init.kaiming_uniform_(a, a=math.sqrt(5)) | |
| self.A = nn.Parameter(a) | |
| b = torch.empty(rank, hidden_size, dtype=torch.float32) | |
| nn.init.normal_(b, mean=0.0, std=1.0 / math.sqrt(rank)) | |
| self.B = nn.Parameter(b) | |
| def forward( | |
| self, | |
| anchor: torch.Tensor, | |
| s: torch.Tensor, | |
| slot: int, | |
| *, | |
| force_zero_gates: bool = False, | |
| ) -> torch.Tensor: | |
| if force_zero_gates: | |
| return anchor | |
| gs = self.gs[slot] | |
| gm = self.gm[slot] | |
| # Exact bit-identity short-circuit only when outside autograd (inference/eval) | |
| if not torch.is_grad_enabled() and not (anchor.is_cuda and torch.cuda.is_current_stream_capturing()): | |
| if torch.count_nonzero(gs) == 0 and torch.count_nonzero(gm) == 0: | |
| return anchor | |
| af = anchor.to(torch.float32) | |
| sf = s.to(torch.float32) | |
| rms_af = _rms(af) | |
| rms_sf = _rms(sf) | |
| ns = (sf / rms_sf) * self.w_s | |
| na = (af / rms_af) * self.w_a | |
| s_hat = ns * (rms_af / _rms(ns)) | |
| pair = torch.cat((ns, na), dim=-1) | |
| delta = torch.matmul(torch.matmul(pair, self.A), self.B) | |
| out = af + torch.tanh(gs) * (s_hat - af) + gm * delta | |
| return out.to(anchor.dtype) | |
| class CrossPassMixer(nn.Module): | |
| """Mid-core AttnRes block-boundary mixer (at L36) mixing pass (p-1)'s block-5 summary into pass p.""" | |
| def __init__(self, hidden_size: int, rank: int, num_slots: int) -> None: | |
| super().__init__() | |
| self.w_prev = nn.Parameter(torch.ones(hidden_size, dtype=torch.float32)) | |
| self.w_curr = nn.Parameter(torch.ones(hidden_size, dtype=torch.float32)) | |
| self.gate = nn.Parameter(torch.zeros(num_slots, hidden_size, dtype=torch.float32)) | |
| a = torch.empty(2 * hidden_size, rank, dtype=torch.float32) | |
| nn.init.kaiming_uniform_(a, a=math.sqrt(5)) | |
| self.A = nn.Parameter(a) | |
| b = torch.empty(rank, hidden_size, dtype=torch.float32) | |
| nn.init.normal_(b, mean=0.0, std=1.0 / math.sqrt(rank)) | |
| self.B = nn.Parameter(b) | |
| def forward( | |
| self, | |
| curr: torch.Tensor, | |
| prev: torch.Tensor, | |
| slot: int, | |
| *, | |
| force_zero_gates: bool = False, | |
| ) -> torch.Tensor: | |
| if force_zero_gates: | |
| return curr | |
| g = self.gate[slot] | |
| if not torch.is_grad_enabled() and not (curr.is_cuda and torch.cuda.is_current_stream_capturing()): | |
| if torch.count_nonzero(g) == 0: | |
| return curr | |
| cf = curr.to(torch.float32) | |
| pf = prev.to(torch.float32) | |
| nc = (cf / _rms(cf)) * self.w_curr | |
| np_ = (pf / _rms(pf)) * self.w_prev | |
| delta = torch.matmul(torch.matmul(torch.cat((nc, np_), dim=-1), self.A), self.B) | |
| return (cf + torch.tanh(g) * delta).to(curr.dtype) | |
| class ConditionedLoRA(nn.Module): | |
| """Low-rank adapter `(x @ A) @ B * (alpha/r) * slot_scale`, FP32 params, B zero-init. | |
| Supports both replicated and TP-sharded linear layers: | |
| - `shard_mode="none"`: A `[in, r]`, B `[r, out]` replicated across ranks. | |
| - `shard_mode="col"`: A `[in, r]` replicated, B `[r, out_local]` sharded along out dim. | |
| - `shard_mode="row"`: A `[in_local, r]` sharded along in dim, B `[r, out]` replicated | |
| (caller sums `x_local @ A_local` or all-reduces full output as part of RowParallelLinear). | |
| """ | |
| def __init__( | |
| self, | |
| in_features: int, | |
| out_features: int, | |
| rank: int, | |
| alpha: float, | |
| num_slots: int = 1, | |
| shard_mode: str = "none", | |
| ) -> None: | |
| super().__init__() | |
| self.in_features = in_features | |
| self.out_features = out_features | |
| self.rank = rank | |
| self.scale = float(alpha) / float(rank) | |
| self.shard_mode = shard_mode | |
| a = torch.empty(in_features, rank, dtype=torch.float32) | |
| nn.init.kaiming_uniform_(a, a=math.sqrt(5)) | |
| self.A = nn.Parameter(a) | |
| self.B = nn.Parameter(torch.zeros(rank, out_features, dtype=torch.float32)) | |
| # Per-slot scalar modulation (init 1.0; B=0 already guarantees bit-exact 0 delta at step 0) | |
| self.slot_scale = nn.Parameter(torch.ones(num_slots, dtype=torch.float32)) | |
| def forward(self, x: torch.Tensor, slot: int = 0) -> torch.Tensor: | |
| z = torch.matmul(torch.matmul(x.to(torch.float32), self.A), self.B) | |
| return (z * (self.scale * self.slot_scale[slot])).to(x.dtype) | |
| class InklingLoopAdapter(nn.Module): | |
| """Complete recurrent-depth adapter module for Inkling-2-Small (Core L30..41, Coda L42..47).""" | |
| def __init__( | |
| self, | |
| cfg: InklingLoopConfig, | |
| *, | |
| qkvr_out_dims_local: dict[int, int], | |
| wo_in_dims_local: dict[int, int], | |
| ) -> None: | |
| super().__init__() | |
| self.cfg = cfg | |
| n_slots = cfg.num_pass_slots | |
| self.entry = WorkspaceEntry(cfg.hidden_size, cfg.entry_rank, n_slots) | |
| self.mid_mixer = ( | |
| CrossPassMixer(cfg.hidden_size, cfg.mixer_rank, n_slots) | |
| if cfg.use_cross_pass_mixer | |
| else None | |
| ) | |
| # Core LoRAs (L30..41): qkvr (col-sharded), wo_ud (row-sharded), mlp.gate (replicated) | |
| self.core_qkvr = nn.ModuleDict() | |
| self.core_wo = nn.ModuleDict() | |
| self.core_router = nn.ModuleDict() | |
| for lid in range(cfg.core_start, cfg.core_end): | |
| k = str(lid) | |
| self.core_qkvr[k] = ConditionedLoRA( | |
| cfg.hidden_size, qkvr_out_dims_local[lid], cfg.lora_rank_attn, cfg.lora_alpha_attn, | |
| num_slots=n_slots, shard_mode="col", | |
| ) | |
| self.core_wo[k] = ConditionedLoRA( | |
| wo_in_dims_local[lid], cfg.hidden_size, cfg.lora_rank_attn, cfg.lora_alpha_attn, | |
| num_slots=n_slots, shard_mode="row", | |
| ) | |
| self.core_router[k] = ConditionedLoRA( | |
| cfg.hidden_size, cfg.num_experts, cfg.lora_rank_router, cfg.lora_alpha_router, | |
| num_slots=n_slots, shard_mode="none", | |
| ) | |
| # Coda LoRAs (L42..47): qkvr (col-sharded), wo_ud (row-sharded) — 1 slot (used whenever T >= 2) | |
| self.coda_qkvr = nn.ModuleDict() | |
| self.coda_wo = nn.ModuleDict() | |
| for lid in range(cfg.core_end, cfg.num_layers): | |
| k = str(lid) | |
| self.coda_qkvr[k] = ConditionedLoRA( | |
| cfg.hidden_size, qkvr_out_dims_local[lid], cfg.lora_rank_attn, cfg.lora_alpha_attn, | |
| num_slots=1, shard_mode="col", | |
| ) | |
| self.coda_wo[k] = ConditionedLoRA( | |
| wo_in_dims_local[lid], cfg.hidden_size, cfg.lora_rank_attn, cfg.lora_alpha_attn, | |
| num_slots=1, shard_mode="row", | |
| ) | |
| def parameter_groups(self, base_lr: float, gate_lr_mult: float = 20.0, weight_decay: float = 0.01) -> list[dict[str, Any]]: | |
| """Separate gate params (high LR, 0 weight decay) from LoRA/entry matrices (standard LR).""" | |
| gate_params, entry_params, lora_params = [], [], [] | |
| for name, p in self.named_parameters(): | |
| if not p.requires_grad: | |
| continue | |
| if name.endswith((".gs", ".gm", ".gate", ".slot_scale")): | |
| gate_params.append(p) | |
| elif name.startswith(("entry.", "mid_mixer.")): | |
| entry_params.append(p) | |
| else: | |
| lora_params.append(p) | |
| return [ | |
| {"name": "gates", "params": gate_params, "lr": base_lr * gate_lr_mult, "weight_decay": 0.0}, | |
| {"name": "entry", "params": entry_params, "lr": base_lr, "weight_decay": weight_decay}, | |
| {"name": "lora", "params": lora_params, "lr": base_lr, "weight_decay": weight_decay}, | |
| ] | |
| def gate_diagnostics(self) -> dict[str, float]: | |
| with torch.no_grad(): | |
| out: dict[str, float] = {} | |
| for s in range(self.cfg.num_pass_slots): | |
| out[f"gs_s{s}_absmax"] = float(self.entry.gs[s].abs().max().item()) | |
| out[f"gs_s{s}_rms"] = float(self.entry.gs[s].pow(2).mean().sqrt().item()) | |
| out[f"gm_s{s}_absmax"] = float(self.entry.gm[s].abs().max().item()) | |
| out[f"gm_s{s}_rms"] = float(self.entry.gm[s].pow(2).mean().sqrt().item()) | |
| if self.mid_mixer is not None: | |
| out[f"mix_s{s}_absmax"] = float(self.mid_mixer.gate[s].abs().max().item()) | |
| out[f"mix_s{s}_rms"] = float(self.mid_mixer.gate[s].pow(2).mean().sqrt().item()) | |
| return out | |
| def count_params(self) -> dict[str, int]: | |
| counts = {"entry": 0, "mid_mixer": 0, "core_lora": 0, "coda_lora": 0, "total": 0} | |
| for name, p in self.named_parameters(): | |
| n = p.numel() | |
| counts["total"] += n | |
| if name.startswith("entry."): | |
| counts["entry"] += n | |
| elif name.startswith("mid_mixer."): | |
| counts["mid_mixer"] += n | |
| elif name.startswith("core_"): | |
| counts["core_lora"] += n | |
| elif name.startswith("coda_"): | |
| counts["coda_lora"] += n | |
| return counts | |
| def save_adapter_checkpoint( | |
| path: Path, | |
| adapter: InklingLoopAdapter, | |
| *, | |
| step: int, | |
| tp_rank: int, | |
| tp_size: int, | |
| extra_meta: dict[str, Any] | None = None, | |
| ) -> Path: | |
| """Save rank-sharded adapter tensors + config + SHA-256 manifest.""" | |
| from safetensors.torch import save_file | |
| path.mkdir(parents=True, exist_ok=True) | |
| st_path = path / f"adapter_rank{tp_rank}.safetensors" | |
| tensors = {k: v.detach().cpu().contiguous() for k, v in adapter.state_dict().items()} | |
| save_file(tensors, str(st_path)) | |
| sha = hashlib.sha256(st_path.read_bytes()).hexdigest() | |
| meta = { | |
| "format": "inkling2-loop-v1", | |
| "step": step, | |
| "tp_rank": tp_rank, | |
| "tp_size": tp_size, | |
| "config": asdict(adapter.cfg), | |
| "file": st_path.name, | |
| "sha256": sha, | |
| **(extra_meta or {}), | |
| } | |
| (path / f"manifest_rank{tp_rank}.json").write_text(json.dumps(meta, indent=2)) | |
| return st_path | |