basal-engine 3.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. basal/__init__.py +7 -0
  2. basal/adapter.py +420 -0
  3. basal/adapters.py +8 -0
  4. basal/agree.py +393 -0
  5. basal/attach.py +160 -0
  6. basal/attn512.py +132 -0
  7. basal/auth.py +194 -0
  8. basal/bench.py +367 -0
  9. basal/blockquant.py +227 -0
  10. basal/calibrate.py +2198 -0
  11. basal/chat.py +175 -0
  12. basal/cli.py +70 -0
  13. basal/client.py +8 -0
  14. basal/decision_log.py +189 -0
  15. basal/decision_rules.py +569 -0
  16. basal/decisions.py +158 -0
  17. basal/derive.py +98 -0
  18. basal/disconnect.py +85 -0
  19. basal/engine.py +6023 -0
  20. basal/evidence.py +133 -0
  21. basal/examples/choice.jsonl +8 -0
  22. basal/examples/complex.jsonl +5 -0
  23. basal/examples/labelled_tickets.jsonl +500 -0
  24. basal/examples/local_backend.py +34 -0
  25. basal/examples/noul.jsonl +8 -0
  26. basal/examples/questions.jsonl +20 -0
  27. basal/examples/score.jsonl +8 -0
  28. basal/examples/selfcheck_basal-omni-pico-Q8_0.json +1 -0
  29. basal/examples/selfcheck_basal-omni-pico.json +1 -0
  30. basal/examples/types_demo.py +74 -0
  31. basal/facts.py +497 -0
  32. basal/feedback.py +234 -0
  33. basal/file_identity.py +39 -0
  34. basal/finetune.py +321 -0
  35. basal/fit_decisions.py +944 -0
  36. basal/fla_configs.json +1822 -0
  37. basal/fold.py +206 -0
  38. basal/fonts/OFL-DMSans.txt +93 -0
  39. basal/fonts/OFL-SpaceGrotesk.txt +93 -0
  40. basal/fonts/dm-sans-latin-ext.woff2 +0 -0
  41. basal/fonts/dm-sans-latin.woff2 +0 -0
  42. basal/fonts/space-grotesk-latin-ext.woff2 +0 -0
  43. basal/fonts/space-grotesk-latin.woff2 +0 -0
  44. basal/fp8block.py +100 -0
  45. basal/gdn_graph.py +1792 -0
  46. basal/gemma4.py +726 -0
  47. basal/gemma4_graph.py +931 -0
  48. basal/gguf_export.py +497 -0
  49. basal/identity.py +217 -0
  50. basal/int8block.py +50 -0
  51. basal/interpolate.py +330 -0
  52. basal/jsonl.py +172 -0
  53. basal/lean.py +204 -0
  54. basal/llama_attn.py +252 -0
  55. basal/llama_attn_kernels.py +266 -0
  56. basal/llama_graph.py +587 -0
  57. basal/llama_kernels.py +593 -0
  58. basal/loadtest.py +189 -0
  59. basal/mcp_server.py +432 -0
  60. basal/media.py +138 -0
  61. basal/metrics.py +16 -0
  62. basal/mlx_attn_kernels.py +1057 -0
  63. basal/mlx_forward.py +326 -0
  64. basal/mlx_kernels.py +543 -0
  65. basal/mlx_metal.py +510 -0
  66. basal/navcut.py +283 -0
  67. basal/navigate.py +646 -0
  68. basal/navtree.py +397 -0
  69. basal/nvfp4.py +245 -0
  70. basal/ordercheck.py +165 -0
  71. basal/pdf.py +183 -0
  72. basal/prepared.py +355 -0
  73. basal/presets.py +8 -0
  74. basal/prompt.py +462 -0
  75. basal/rank.py +373 -0
  76. basal/readout.py +121 -0
  77. basal/request.py +327 -0
  78. basal/response_cache.py +105 -0
  79. basal/router.py +1551 -0
  80. basal/router_ui.html +902 -0
  81. basal/router_ui.py +277 -0
  82. basal/run.py +376 -0
  83. basal/selfcheck.py +215 -0
  84. basal/server.py +5279 -0
  85. basal/sets.py +214 -0
  86. basal/signals.py +28 -0
  87. basal/state_disk.py +942 -0
  88. basal/strix.py +505 -0
  89. basal/synth.py +92 -0
  90. basal/tasks.py +848 -0
  91. basal/textio.py +21 -0
  92. basal/think.py +390 -0
  93. basal/tools.py +171 -0
  94. basal/tpu.py +336 -0
  95. basal/tpu_kernels.py +129 -0
  96. basal/trace.py +125 -0
  97. basal/ui.html +861 -0
  98. basal/ui.py +526 -0
  99. basal/varloop.py +813 -0
  100. basal/varloop_graph.py +1377 -0
  101. basal/varloop_kernels.py +907 -0
  102. basal/viz.html +660 -0
  103. basal/viz.py +375 -0
  104. basal/vllm_unified.py +100 -0
  105. basal_engine-3.0.3.dist-info/METADATA +416 -0
  106. basal_engine-3.0.3.dist-info/RECORD +111 -0
  107. basal_engine-3.0.3.dist-info/WHEEL +5 -0
  108. basal_engine-3.0.3.dist-info/entry_points.txt +21 -0
  109. basal_engine-3.0.3.dist-info/licenses/LICENSE +202 -0
  110. basal_engine-3.0.3.dist-info/licenses/NOTICE +34 -0
  111. basal_engine-3.0.3.dist-info/top_level.txt +1 -0
basal/varloop.py ADDED
@@ -0,0 +1,813 @@
1
+ """Variable-Depth Looped Transformer (VarLoop) core support (basal-engine 3.0.3).
2
+
3
+ Supports both target VarLoop architectures using the exact on-disk checkpoint format:
4
+ - Standard HF weights (config.json, model*.safetensors, tokenizer)
5
+ - varloop.json: {n_prelude, n_block2, n_block3, n_coda, gate_rank, default_passes, max_passes, rms_eps, arch}
6
+ - varloop_gates.safetensors: FP32 cross-loop gate weights ({0..n_core-1}.{q,k,v,mlp}.{reader,proj,keep,gain})
7
+
8
+ Supported architectures:
9
+ 1. Llama (arch="llama", 60L = 15 + (15 + 15) * T + 15, biased GQA-8)
10
+ 2. Gemma 4 MoE (arch="gemma4", 30L = 6 + (9 + 9) * T + 6, 128-expert MoE, 5:1 sliding/full, softcap=30.0)
11
+
12
+ Key semantics (exact parity with the reference VarLoopModel):
13
+ - Prelude anchor (v1) & block deltas: Pass t >= 2 re-enters Core at v1 (NOT h(B3)), feeding unit-RMS-normalized
14
+ v2_hat = _rms_unit(h(B2) - v1) and v3_hat = _rms_unit(h(B3) - h(B2)) into 4 channels (q, k, v, mlp) BEFORE
15
+ each sublayer's LayerNorm.
16
+ - Independent per-pass KV cache (SOAM-compatible): logical layer index L_pre + pass_idx * L_core + j
17
+ (60/90/120 KV slots with 60 layers; 30/48/66 with 30).
18
+ - Two-way bidirectional attention on full_attention layers (all layers on Llama; layers 5, 11, 17, 23, 29 on Gemma 4;
19
+ causal sliding_window=1024 on Gemma 4 sliding layers) + final_logit_softcapping=30.0 on Gemma 4.
20
+ - Coda-Lens adaptive early exit (exit_tau): optional Pass-1 Coda check (max(softmax(logits_codes)) >= tau exits at
21
+ T=1, skipping Passes 2..T with per-item batch compaction for remaining hard items).
22
+ """
23
+ from dataclasses import dataclass
24
+ import json
25
+ import math
26
+ import os
27
+ from pathlib import Path
28
+
29
+ import torch
30
+ import torch.nn.functional as F
31
+
32
+ from . import varloop_kernels as vk
33
+ from .readout import CodeReadout
34
+
35
+
36
+ VARLOOP_CONFIG_FILE = "varloop.json"
37
+ VARLOOP_GATES_FILE = "varloop_gates.safetensors"
38
+
39
+
40
+ @dataclass
41
+ class VarLoopConfig:
42
+ n_prelude: int
43
+ n_block2: int
44
+ n_block3: int
45
+ n_coda: int
46
+ gate_rank: int = 64
47
+ default_passes: int = 3
48
+ max_passes: int = 5
49
+ rms_eps: float = 1e-6
50
+ arch: str = "llama"
51
+ base: str = ""
52
+
53
+ @property
54
+ def n_core(self) -> int:
55
+ return self.n_block2 + self.n_block3
56
+
57
+ @property
58
+ def n_total(self) -> int:
59
+ return self.n_prelude + self.n_core + self.n_coda
60
+
61
+ def logical_layers(self, num_passes: int) -> int:
62
+ return self.n_prelude + int(num_passes) * self.n_core + self.n_coda
63
+
64
+ @classmethod
65
+ def from_dict(cls, d: dict) -> "VarLoopConfig":
66
+ fields = {
67
+ "n_prelude": int(d["n_prelude"]),
68
+ "n_block2": int(d["n_block2"]),
69
+ "n_block3": int(d["n_block3"]),
70
+ "n_coda": int(d["n_coda"]),
71
+ "gate_rank": int(d.get("gate_rank", 64)),
72
+ "default_passes": int(d.get("default_passes", 3)),
73
+ "max_passes": int(d.get("max_passes", 5)),
74
+ "rms_eps": float(d.get("rms_eps", 1e-6)),
75
+ "arch": str(d.get("arch", "llama")),
76
+ "base": str(d.get("base", "")),
77
+ }
78
+ return cls(**fields)
79
+
80
+
81
+ def is_varloop_dir(model_dir, strict=False) -> bool:
82
+ """True when model_dir contains varloop.json (a VarLoop looped checkpoint)."""
83
+ if model_dir is None:
84
+ return False
85
+ p = Path(model_dir) / VARLOOP_CONFIG_FILE
86
+ if not p.exists():
87
+ return False
88
+ if strict:
89
+ json.loads(p.read_text(encoding="utf-8"))
90
+ return True
91
+
92
+
93
+ def load_varloop_config(model_dir) -> VarLoopConfig:
94
+ p = Path(model_dir) / VARLOOP_CONFIG_FILE
95
+ if not p.exists():
96
+ raise FileNotFoundError(f"{model_dir}: missing {VARLOOP_CONFIG_FILE}")
97
+ return VarLoopConfig.from_dict(json.loads(p.read_text(encoding="utf-8")))
98
+
99
+
100
+ def text_model(model):
101
+ """Return the underlying text decoder (LlamaModel or Gemma4TextModel)."""
102
+ return getattr(model.model, "language_model", model.model)
103
+
104
+
105
+ def text_config(model):
106
+ cfg = model.config
107
+ return cfg.get_text_config() if hasattr(cfg, "get_text_config") else cfg
108
+
109
+
110
+ def is_gemma4_varloop(model) -> bool:
111
+ return str(getattr(model.config, "model_type", "")).startswith("gemma4")
112
+
113
+
114
+ class PackedCoreGates:
115
+ """Packed, GPU-optimized cross-loop gate weights for all `n_core` layers.
116
+
117
+ - `U_all` [n_core * 4, D] kept in FP32 so reader scoring across all 4*n_core channels runs in ONE single GEMM/pass
118
+ with exact fp32 softmax parity!
119
+ - Gate projections (`W_px_qkv`, `W_pm_qkv_t`, `W_kg_qkv_t`, `W_p_mlp`, `W_kg_mlp`) kept in model compute dtype
120
+ (BF16 on GPU, FP32 in fp32 tests) — never quantized to INT8/NVFP4 even when body weights are quantized.
121
+ """
122
+
123
+ def __init__(self, cfg: VarLoopConfig, hidden_size: int, state_dict: dict[str, torch.Tensor],
124
+ device, dtype: torch.dtype):
125
+ self.cfg = cfg
126
+ self.n_core = cfg.n_core
127
+ self.hidden_size = hidden_size
128
+ self.rank = cfg.gate_rank
129
+ self.eps = cfg.rms_eps
130
+ self.scale = 1.0 / math.sqrt(hidden_size)
131
+ self.dtype = dtype
132
+ self.device = torch.device(device)
133
+
134
+ readers = []
135
+ self.layers = []
136
+ for j in range(cfg.n_core):
137
+ w_px_qkv, w_pm_qkv_t, w_kg_qkv_t = [], [], []
138
+ for ch in ("q", "k", "v"):
139
+ pref = f"{j}.{ch}"
140
+ readers.append(state_dict[f"{pref}.reader"].to(device=self.device, dtype=torch.float32))
141
+ wp = state_dict[f"{pref}.proj.weight"].to(device=self.device, dtype=dtype) # [R, 2*D]
142
+ wk = state_dict[f"{pref}.keep.weight"].to(device=self.device, dtype=dtype) # [D, R]
143
+ wg = state_dict[f"{pref}.gain.weight"].to(device=self.device, dtype=dtype) # [D, R]
144
+ w_px_qkv.append(wp[:, :hidden_size])
145
+ w_pm_qkv_t.append(wp[:, hidden_size:].t().contiguous()) # [D, R]
146
+ w_kg_qkv_t.append(torch.cat([wk, wg], dim=0).t().contiguous()) # [R, 2*D]
147
+
148
+ pref = f"{j}.mlp"
149
+ readers.append(state_dict[f"{pref}.reader"].to(device=self.device, dtype=torch.float32))
150
+ wp_m = state_dict[f"{pref}.proj.weight"].to(device=self.device, dtype=dtype).contiguous()
151
+ wk_m = state_dict[f"{pref}.keep.weight"].to(device=self.device, dtype=dtype)
152
+ wg_m = state_dict[f"{pref}.gain.weight"].to(device=self.device, dtype=dtype)
153
+ w_kg_m = torch.cat([wk_m, wg_m], dim=0).contiguous() # [2*D, R]
154
+
155
+ self.layers.append({
156
+ "w_px_qkv": torch.cat(w_px_qkv, dim=0).contiguous(), # [3*R, D]
157
+ "w_pm_qkv_t": torch.stack(w_pm_qkv_t, dim=0).contiguous(), # [3, D, R]
158
+ "w_kg_qkv_t": torch.stack(w_kg_qkv_t, dim=0).contiguous(), # [3, R, 2*D]
159
+ "w_p_mlp": wp_m, # [R, 2*D]
160
+ "w_kg_mlp": w_kg_m, # [2*D, R]
161
+ })
162
+
163
+ # [n_core * 4, D] in fp32 for 1-GEMM-per-pass reader scoring
164
+ self.U_all = torch.stack(readers, dim=0).contiguous()
165
+
166
+ @classmethod
167
+ def from_dir(cls, model_dir, cfg: VarLoopConfig, hidden_size: int, device, dtype: torch.dtype) -> "PackedCoreGates":
168
+ from safetensors.torch import load_file
169
+ p = Path(model_dir) / VARLOOP_GATES_FILE
170
+ if not p.exists():
171
+ raise FileNotFoundError(f"{model_dir}: missing {VARLOOP_GATES_FILE}")
172
+ sd = load_file(str(p), device="cpu")
173
+ return cls(cfg, hidden_size, sd, device, dtype)
174
+
175
+ def compute_betas(self, v2_hat: torch.Tensor, v3_hat: torch.Tensor) -> torch.Tensor:
176
+ """Compute softmax reader weights for ALL n_core * 4 channels in ONE batched FP32 GEMM.
177
+ Returns beta_all: [M, n_core, 4, 2] in self.dtype."""
178
+ D = self.hidden_size
179
+ v2_f = v2_hat.reshape(-1, D).float()
180
+ v3_f = v3_hat.reshape(-1, D).float()
181
+ M = v2_f.shape[0]
182
+ Ut = self.U_all.t()
183
+ s2 = (v2_f @ Ut) * self.scale # [M, n_core * 4]
184
+ s3 = (v3_f @ Ut) * self.scale # [M, n_core * 4]
185
+ beta = torch.softmax(torch.stack([s2, s3], dim=-1), dim=-1).to(v2_hat.dtype)
186
+ return beta.view(M, self.n_core, 4, 2)
187
+
188
+ def apply_qkv_rmsnorm(self, x: torch.Tensor, v2_hat: torch.Tensor, v3_hat: torch.Tensor,
189
+ beta_qkv: torch.Tensor, core_j: int, ln_w: torch.Tensor, ln_eps: float,
190
+ gemma_norm: bool = False) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
191
+ """Fused 3-channel cross-loop gate + input_layernorm -> (h_q, h_k, h_v) in x.shape."""
192
+ shape = x.shape
193
+ D = shape[-1]
194
+ M = x.numel() // D
195
+ G = self.layers[core_j]
196
+ xh, mh = vk.varloop_prep_qkv(x, v2_hat, v3_hat, beta_qkv, self.eps) # [M, D], [3, M, D]
197
+ zx = F.linear(xh, G["w_px_qkv"]).view(M, 3, self.rank).transpose(0, 1) # [3, M, R]
198
+ z = zx + torch.bmm(mh, G["w_pm_qkv_t"]) # [3, M, R]
199
+ fg = torch.bmm(z, G["w_kg_qkv_t"]) # [3, M, 2*D]
200
+ h_qkv = vk.varloop_mix_rmsnorm_qkv(x, v2_hat, v3_hat, beta_qkv, fg, ln_w, ln_eps, gemma_norm=gemma_norm)
201
+ return h_qkv[0].reshape(shape), h_qkv[1].reshape(shape), h_qkv[2].reshape(shape)
202
+
203
+ def apply_mlp_rmsnorm(self, x: torch.Tensor, v2_hat: torch.Tensor, v3_hat: torch.Tensor,
204
+ beta_m: torch.Tensor, core_j: int, ln_w: torch.Tensor, ln_eps: float,
205
+ gemma_norm: bool = False) -> torch.Tensor:
206
+ """Fused MLP cross-loop gate + post_attention_layernorm -> h_mlp in x.shape."""
207
+ G = self.layers[core_j]
208
+ xm = vk.varloop_prep_mlp(x, v2_hat, v3_hat, beta_m, self.eps) # [M, 2*D]
209
+ z = F.linear(xm, G["w_p_mlp"]) # [M, R]
210
+ fg = F.linear(z, G["w_kg_mlp"]) # [M, 2*D]
211
+ return vk.varloop_mix_rmsnorm_mlp(x, v2_hat, v3_hat, beta_m, fg, ln_w, ln_eps, gemma_norm=gemma_norm)
212
+
213
+ def apply_gemma_ff(self, x: torch.Tensor, v2_hat: torch.Tensor, v3_hat: torch.Tensor,
214
+ beta_m: torch.Tensor, core_j: int, ln1_w: torch.Tensor, ln2_w: torch.Tensor | None,
215
+ ln_eps: float) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
216
+ """Fused Gemma 4 MLP cross-loop gate -> (x_ff, pre_ff_ln1(x_ff), pre_ff_ln2(x_ff) or None)."""
217
+ G = self.layers[core_j]
218
+ xm = vk.varloop_prep_mlp(x, v2_hat, v3_hat, beta_m, self.eps)
219
+ z = F.linear(xm, G["w_p_mlp"])
220
+ fg = F.linear(z, G["w_kg_mlp"])
221
+ if ln2_w is not None:
222
+ return vk.varloop_mix_gemma_ff(x, v2_hat, v3_hat, beta_m, fg, ln1_w, ln2_w, ln_eps)
223
+ # Dense Gemma 4 layer without MoE: only pre_ff_ln1 needed
224
+ y1 = vk.varloop_mix_rmsnorm_mlp(x, v2_hat, v3_hat, beta_m, fg, ln1_w, ln_eps, gemma_norm=True)
225
+ return None, y1, None
226
+
227
+
228
+ def _apply_rotary_llama(q, k, cos, sin):
229
+ """q: [B, H, L, D], k: [B, Hkv, L, D], cos/sin: [B, L, D] -> rotated (q, k)."""
230
+ c = cos.unsqueeze(1)
231
+ s = sin.unsqueeze(1)
232
+ half = q.shape[-1] // 2
233
+ q_rot = torch.cat((-q[..., half:], q[..., :half]), dim=-1)
234
+ k_rot = torch.cat((-k[..., half:], k[..., :half]), dim=-1)
235
+ return q * c + q_rot * s, k * c + k_rot * s
236
+
237
+
238
+ def _apply_rotary_gemma(x, cos, sin):
239
+ """x: [B, L, H, D], cos/sin: [B, L, D] -> [B, H, L, D]."""
240
+ c = cos.unsqueeze(2)
241
+ s = sin.unsqueeze(2)
242
+ half = x.shape[-1] // 2
243
+ x_rot = torch.cat((-x[..., half:], x[..., :half]), dim=-1)
244
+ return (x * c + x_rot * s).transpose(1, 2)
245
+
246
+
247
+ class VarLoopForward:
248
+ """Reference + SOAM + Two-Way + Coda-Lens VarLoop execution engine for EagerBackend (CPU / MPS / CUDA).
249
+
250
+ Handles both Llama and Gemma 4 MoE models with:
251
+ - Exact Prelude anchor (v1) & block deltas (v2_hat, v3_hat)
252
+ - Independent per-pass KV cache (logical index L_pre + pass_idx * L_core + j)
253
+ - SOAM shared-prefix execution (with lazy Passes 2..T prefix KV under Coda-Lens early exit!)
254
+ - Two-way bidirectional attention (full layers on Llama; full_attention layers 5,11,17,23,29 on Gemma 4)
255
+ - Last-layer Coda readout slicing (layer N-1 runs Q/Attn/O/MLP/MoE/norm at answer rows ONLY)
256
+ - Coda-Lens early exit (`exit_tau`) with batch compaction on hard items
257
+ """
258
+
259
+ CHUNK = 2048
260
+ MAX_BATCH_TOKENS = 16384
261
+
262
+ def __init__(self, model, model_dir, num_passes: int | None = None, exit_tau: float | None = None,
263
+ two_way: dict | None = None, prefix: dict | None = None, bidir_layers: list[int] | None = None):
264
+ self.model = model
265
+ self.cfg = load_varloop_config(model_dir)
266
+ self.lm = text_model(model)
267
+ self.tcfg = text_config(model)
268
+ self.is_gemma4 = is_gemma4_varloop(model)
269
+ self.layers = list(self.lm.layers[: self.tcfg.num_hidden_layers])
270
+ if self.cfg.n_total != len(self.layers):
271
+ raise ValueError(f"varloop.json sums to {self.cfg.n_total} layers, model has {len(self.layers)}")
272
+ if self.is_gemma4:
273
+ if getattr(self.tcfg, "num_kv_shared_layers", 0):
274
+ raise ValueError("VarLoop does not support Gemma 4 cross-layer KV sharing (num_kv_shared_layers > 0)")
275
+ if getattr(self.tcfg, "hidden_size_per_layer_input", 0):
276
+ raise ValueError("VarLoop does not support Gemma 4 per-layer embeddings")
277
+
278
+ self.num_passes = self.cfg.default_passes if num_passes is None else int(num_passes)
279
+ if not 1 <= self.num_passes <= self.cfg.max_passes:
280
+ raise ValueError(f"varloop_passes {self.num_passes} out of range 1..{self.cfg.max_passes}")
281
+ self.exit_tau = None if exit_tau is None else float(exit_tau)
282
+ if self.exit_tau is not None and not (0.0 <= self.exit_tau <= 1.0):
283
+ raise ValueError(f"varloop_exit_tau must be in [0, 1], got {self.exit_tau}")
284
+ self.two_way = dict(two_way) if two_way else None
285
+ self.prefix = dict(prefix) if prefix else None
286
+ self.types = (list(self.tcfg.layer_types[: len(self.layers)]) if self.is_gemma4
287
+ else ["full_attention"] * len(self.layers))
288
+ self.window = getattr(self.tcfg, "sliding_window", None) if self.is_gemma4 else None
289
+ if bidir_layers is not None:
290
+ bset = set(bidir_layers)
291
+ self.bidir_layer = [i in bset for i in range(len(self.layers))]
292
+ else:
293
+ self.bidir_layer = [t != "sliding_attention" for t in self.types]
294
+ self.softcap = getattr(self.tcfg, "final_logit_softcapping", None)
295
+ self.pad = getattr(self.tcfg, "pad_token_id", None)
296
+ if self.pad is None:
297
+ self.pad = getattr(self.tcfg, "eos_token_id", 0)
298
+ if isinstance(self.pad, list):
299
+ self.pad = self.pad[0]
300
+
301
+ emb = self.lm.embed_tokens.weight
302
+ self.dev, self.dtype = emb.device, emb.dtype
303
+ self.gates = PackedCoreGates.from_dir(model_dir, self.cfg, self.tcfg.hidden_size, self.dev, self.dtype)
304
+ self.head = model.get_output_embeddings()
305
+ self._wrows = {}
306
+ self.last_exit_stats = None # updated on each exit-enabled call: {"exited": int, "deep": int, "mean_passes": float}
307
+
308
+ def _code_readout(self):
309
+ return CodeReadout(self.head, self.softcap, self._wrows)
310
+
311
+ def _mask(self, layer_idx: int, qpos: torch.Tensor, kc: torch.Tensor | None, pos: torch.Tensor,
312
+ valid: torch.Tensor, two_way: bool = False) -> torch.Tensor:
313
+ """Boolean attention mask [B, 1, Sq, Lc + S]."""
314
+ sliding = self.types[layer_idx] == "sliding_attention"
315
+ d = qpos[:, :, None] - pos[:, None, :]
316
+ m = (d >= 0) & (valid[:, None, :] | (d == 0))
317
+ if sliding and self.window:
318
+ m = m & (d < self.window)
319
+ if two_way and self.bidir_layer[layer_idx] and not sliding:
320
+ m = valid[:, None, :] | (d == 0)
321
+ if kc is not None:
322
+ kq = kc[:, None, :]
323
+ mc = (kq >= 0) & (kq <= qpos[:, :, None])
324
+ if sliding and self.window:
325
+ mc = mc & (qpos[:, :, None] - kq < self.window)
326
+ m = torch.cat([mc, m], dim=-1)
327
+ return m[:, None]
328
+
329
+ def _sdpa(self, q, k, v, mask, scale):
330
+ """Exact GQA SDPA (avoids PyTorch <2.14.1 mem-efficient SDPA bug #191937 on Gemma 4 CUDA)."""
331
+ if q.is_cuda and self.is_gemma4:
332
+ from torch.nn.attention import SDPBackend, sdpa_kernel
333
+ g = q.shape[1] // k.shape[1]
334
+ if g > 1:
335
+ k = k.repeat_interleave(g, dim=1)
336
+ v = v.repeat_interleave(g, dim=1)
337
+ with sdpa_kernel([SDPBackend.MATH]):
338
+ return F.scaled_dot_product_attention(q, k, v, attn_mask=mask, scale=scale)
339
+ return F.scaled_dot_product_attention(q, k, v, attn_mask=mask, scale=scale, enable_gqa=True)
340
+
341
+ def _run_layer(self, phys_idx: int, logical_idx: int, h: torch.Tensor, rope_ctx, masks: dict,
342
+ kv_in: dict | None, grp: torch.Tensor | None, kv_out: dict | None,
343
+ core_j: int | None = None, v2_hat: torch.Tensor | None = None,
344
+ v3_hat: torch.Tensor | None = None, beta_layer: torch.Tensor | None = None,
345
+ read: torch.Tensor | None = None, kv_only: bool = False) -> torch.Tensor | None:
346
+ layer = self.layers[phys_idx]
347
+ attn = layer.self_attn
348
+ B, S, D = h.shape
349
+ gated = core_j is not None and v2_hat is not None and v3_hat is not None
350
+
351
+ if self.is_gemma4:
352
+ t = self.types[phys_idx]
353
+ cos, sin = rope_ctx[t]
354
+ m = masks[t] if not self.bidir_layer[phys_idx] else masks.get("full_bidir", masks[t])
355
+ ln_eps = layer.input_layernorm.eps
356
+ if gated:
357
+ h_q, h_k, h_v = self.gates.apply_qkv_rmsnorm(
358
+ h, v2_hat, v3_hat, beta_layer[:, :3, :], core_j,
359
+ layer.input_layernorm.weight, ln_eps, gemma_norm=True)
360
+ else:
361
+ h_q = h_k = h_v = layer.input_layernorm(h)
362
+
363
+ raw_k = attn.k_proj(h_k).view(B, S, -1, attn.head_dim)
364
+ raw_v = attn.v_proj(h_v).view(B, S, -1, attn.head_dim) if attn.v_proj is not None else raw_k
365
+ k = _apply_rotary_gemma(attn.k_norm(raw_k), cos, sin)
366
+ v = attn.v_norm(raw_v).transpose(1, 2)
367
+ if kv_out is not None:
368
+ kv_out[logical_idx] = (k, v)
369
+ if kv_only:
370
+ return None
371
+ if kv_in is not None and logical_idx in kv_in:
372
+ K, V = kv_in[logical_idx]
373
+ K = K.expand(B, -1, -1, -1) if K.shape[0] == 1 else K.index_select(0, grp)
374
+ V = V.expand(B, -1, -1, -1) if V.shape[0] == 1 else V.index_select(0, grp)
375
+ k, v = torch.cat([K, k], dim=2), torch.cat([V, v], dim=2)
376
+
377
+ if read is not None:
378
+ rows = (torch.arange(B, device=h.device), read)
379
+ h = h[rows][:, None]
380
+ h_q = h_q[rows][:, None]
381
+ cos = cos[rows][:, None]
382
+ sin = sin[rows][:, None]
383
+ m = m[rows[0], :, rows[1]][:, :, None]
384
+ Sq = 1
385
+ else:
386
+ Sq = S
387
+
388
+ q = _apply_rotary_gemma(attn.q_norm(attn.q_proj(h_q).view(B, Sq, -1, attn.head_dim)), cos, sin)
389
+ o = self._sdpa(q, k, v, m, attn.scaling)
390
+ o = attn.o_proj(o.transpose(1, 2).reshape(B, Sq, -1))
391
+ h = h + layer.post_attention_layernorm(o)
392
+
393
+ residual = h
394
+ has_moe = bool(getattr(layer, "enable_moe_block", False))
395
+ if gated:
396
+ x_ff, h_ff1, h_ff2 = self.gates.apply_gemma_ff(
397
+ h, v2_hat, v3_hat, beta_layer[:, 3, :], core_j,
398
+ layer.pre_feedforward_layernorm.weight,
399
+ layer.pre_feedforward_layernorm_2.weight if has_moe else None,
400
+ layer.pre_feedforward_layernorm.eps)
401
+ ff_out = layer.mlp(h_ff1)
402
+ if has_moe:
403
+ h1 = layer.post_feedforward_layernorm_1(ff_out)
404
+ _, top_k_weights, top_k_index = layer.router(x_ff.reshape(-1, D))
405
+ h2 = vk.grouped_moe_forward(
406
+ h_ff2.reshape(-1, D), top_k_index, top_k_weights,
407
+ layer.experts.gate_up_proj, layer.experts.down_proj)
408
+ ff_out = h1 + layer.post_feedforward_layernorm_2(h2.reshape_as(x_ff))
409
+ else:
410
+ ff_out = layer.mlp(layer.pre_feedforward_layernorm(h))
411
+ if has_moe:
412
+ h1 = layer.post_feedforward_layernorm_1(ff_out)
413
+ x_flat = h.reshape(-1, D)
414
+ _, top_k_weights, top_k_index = layer.router(x_flat)
415
+ h2 = vk.grouped_moe_forward(
416
+ layer.pre_feedforward_layernorm_2(x_flat), top_k_index, top_k_weights,
417
+ layer.experts.gate_up_proj, layer.experts.down_proj)
418
+ ff_out = h1 + layer.post_feedforward_layernorm_2(h2.reshape_as(h))
419
+
420
+ h = (residual + layer.post_feedforward_layernorm(ff_out)) * layer.layer_scalar
421
+ return h
422
+
423
+ # Llama layer
424
+ cos, sin = rope_ctx
425
+ m = masks["full_bidir"] if self.bidir_layer[phys_idx] else masks["full_causal"]
426
+ ln_eps = layer.input_layernorm.variance_epsilon
427
+ if gated:
428
+ h_q, h_k, h_v = self.gates.apply_qkv_rmsnorm(
429
+ h, v2_hat, v3_hat, beta_layer[:, :3, :], core_j,
430
+ layer.input_layernorm.weight, ln_eps, gemma_norm=False)
431
+ else:
432
+ h_q = h_k = h_v = layer.input_layernorm(h)
433
+
434
+ k = attn.k_proj(h_k).view(B, S, -1, attn.head_dim).transpose(1, 2)
435
+ v = attn.v_proj(h_v).view(B, S, -1, attn.head_dim).transpose(1, 2)
436
+ _, k = _apply_rotary_llama(k[:, :1], k, cos, sin) # rotate k only (exact match)
437
+ if kv_out is not None:
438
+ kv_out[logical_idx] = (k, v)
439
+ if kv_only:
440
+ return None
441
+ if kv_in is not None and logical_idx in kv_in:
442
+ K, V = kv_in[logical_idx]
443
+ K = K.expand(B, -1, -1, -1) if K.shape[0] == 1 else K.index_select(0, grp)
444
+ V = V.expand(B, -1, -1, -1) if V.shape[0] == 1 else V.index_select(0, grp)
445
+ k, v = torch.cat([K, k], dim=2), torch.cat([V, v], dim=2)
446
+
447
+ if read is not None:
448
+ rows = (torch.arange(B, device=h.device), read)
449
+ h = h[rows][:, None]
450
+ h_q = h_q[rows][:, None]
451
+ cos = cos[rows][:, None]
452
+ sin = sin[rows][:, None]
453
+ m = m[rows[0], :, rows[1]][:, :, None]
454
+ Sq = 1
455
+ else:
456
+ Sq = S
457
+
458
+ q = attn.q_proj(h_q).view(B, Sq, -1, attn.head_dim).transpose(1, 2)
459
+ q, _ = _apply_rotary_llama(q, q[:, :1], cos, sin)
460
+ o = self._sdpa(q, k, v, m, attn.scaling)
461
+ o = attn.o_proj(o.transpose(1, 2).reshape(B, Sq, -1))
462
+ h = h + o
463
+
464
+ residual = h
465
+ if gated:
466
+ h_mlp = self.gates.apply_mlp_rmsnorm(
467
+ h, v2_hat, v3_hat, beta_layer[:, 3, :], core_j,
468
+ layer.post_attention_layernorm.weight, layer.post_attention_layernorm.variance_epsilon,
469
+ gemma_norm=False)
470
+ else:
471
+ h_mlp = layer.post_attention_layernorm(h)
472
+ return residual + layer.mlp(h_mlp)
473
+
474
+ def _build_rope_masks(self, h, pos, valid, kpos=None, grp=None, two_way=False):
475
+ if self.is_gemma4:
476
+ types = set(self.types)
477
+ rope_ctx = {t: self.lm.rotary_emb(h, pos, t) for t in types}
478
+ masks = {}
479
+ for t in types:
480
+ idx0 = self.types.index(t)
481
+ kc = kpos[t][grp] if (kpos is not None and t in kpos) else None
482
+ masks[t] = self._mask(idx0, pos, kc, pos, valid, two_way=False)
483
+ if two_way:
484
+ kc_f = kpos["full_attention"][grp] if (kpos is not None and "full_attention" in kpos) else None
485
+ full_idx = next((i for i, t in enumerate(self.types) if t != "sliding_attention"), 0)
486
+ masks["full_bidir"] = self._mask(full_idx, pos, kc_f, pos, valid, two_way=True)
487
+ return rope_ctx, masks
488
+
489
+ rope_ctx = self.lm.rotary_emb(h, position_ids=pos)
490
+ kc = kpos["full_attention"][grp] if (kpos is not None and "full_attention" in kpos) else None
491
+ m_causal = self._mask(0, pos, kc, pos, valid, two_way=False)
492
+ masks = {"full_causal": m_causal}
493
+ if two_way:
494
+ masks["full_bidir"] = self._mask(0, pos, kc, pos, valid, two_way=True)
495
+ else:
496
+ masks["full_bidir"] = m_causal
497
+ return rope_ctx, masks
498
+
499
+ def _run_prelude(self, h, rope_ctx, masks, kv_in, grp, kv_out):
500
+ for i in range(self.cfg.n_prelude):
501
+ h = self._run_layer(i, i, h, rope_ctx, masks, kv_in, grp, kv_out)
502
+ return h
503
+
504
+ def _run_core_pass(self, v1, prev_v2_hat, prev_v3_hat, pass_idx, rope_ctx, masks, kv_in, grp, kv_out):
505
+ lc = self.cfg
506
+ h = v1
507
+ use_gates = prev_v2_hat is not None and prev_v3_hat is not None
508
+ betas = self.gates.compute_betas(prev_v2_hat, prev_v3_hat) if use_gates else None
509
+
510
+ for j in range(lc.n_block2):
511
+ phys_idx = lc.n_prelude + j
512
+ logical_idx = lc.n_prelude + pass_idx * lc.n_core + j
513
+ bl = betas[:, j] if use_gates else None
514
+ h = self._run_layer(phys_idx, logical_idx, h, rope_ctx, masks, kv_in, grp, kv_out,
515
+ core_j=j if use_gates else None,
516
+ v2_hat=prev_v2_hat, v3_hat=prev_v3_hat, beta_layer=bl)
517
+ h_b2 = h
518
+ for j in range(lc.n_block3):
519
+ core_j = lc.n_block2 + j
520
+ phys_idx = lc.n_prelude + core_j
521
+ logical_idx = lc.n_prelude + pass_idx * lc.n_core + core_j
522
+ bl = betas[:, core_j] if use_gates else None
523
+ h = self._run_layer(phys_idx, logical_idx, h, rope_ctx, masks, kv_in, grp, kv_out,
524
+ core_j=core_j if use_gates else None,
525
+ v2_hat=prev_v2_hat, v3_hat=prev_v3_hat, beta_layer=bl)
526
+ return h, h_b2
527
+
528
+ def _run_coda(self, h, num_passes, rope_ctx, masks, kv_in, grp, kv_out, read=None, kv_only=False):
529
+ lc = self.cfg
530
+ base_logical = lc.n_prelude + num_passes * lc.n_core
531
+ for i in range(lc.n_coda):
532
+ phys_idx = lc.n_prelude + lc.n_core + i
533
+ is_last = i == lc.n_coda - 1
534
+ h = self._run_layer(phys_idx, base_logical + i, h, rope_ctx, masks, kv_in, grp, kv_out,
535
+ read=read if is_last else None,
536
+ kv_only=kv_only and is_last)
537
+ if kv_only and is_last:
538
+ return None
539
+ if read is not None:
540
+ return self.lm.norm(h[:, 0])
541
+ return self.lm.norm(h)
542
+
543
+ def _slice_rope_masks(self, rope_ctx, masks, idx):
544
+ if self.is_gemma4:
545
+ r = {t: (c[idx], s[idx]) for t, (c, s) in rope_ctx.items()}
546
+ else:
547
+ r = (rope_ctx[0][idx], rope_ctx[1][idx])
548
+ m = {k: v[idx] for k, v in masks.items()}
549
+ return r, m
550
+
551
+ @torch.no_grad()
552
+ def forward_batch(self, seqs: list[list[int]], ids_list: list[list[int]] | None = None,
553
+ two_way: bool = False, num_passes: int | None = None,
554
+ exit_tau: float | None = None) -> tuple[torch.Tensor, list[list[float]] | None]:
555
+ """Run a batch of right-padded whole sequences -> (final_hidden [B, D], probs or None).
556
+ When exit_tau is set (and ids_list given, num_passes > 1), executes Coda-Lens Pass-1 check with batch
557
+ compaction for hard items only!"""
558
+ T = self.num_passes if num_passes is None else int(num_passes)
559
+ tau = self.exit_tau if exit_tau is None else exit_tau
560
+ B = len(seqs)
561
+ S = max(map(len, seqs))
562
+ ids = torch.tensor([list(s) + [self.pad] * (S - len(s)) for s in seqs], device=self.dev)
563
+ lens = torch.tensor([len(s) for s in seqs], device=self.dev)
564
+ ar = torch.arange(S, device=self.dev)
565
+ valid = ar[None] < lens[:, None]
566
+ pos = ar[None].expand(B, S)
567
+ read = lens - 1
568
+
569
+ h0 = self.lm.embed_tokens(ids)
570
+ rope_ctx, masks = self._build_rope_masks(h0, pos, valid, two_way=two_way)
571
+ v1 = self._run_prelude(h0, rope_ctx, masks, None, None, None)
572
+
573
+ # Pass 1 (always runs)
574
+ h_core, h_b2 = self._run_core_pass(v1, None, None, 0, rope_ctx, masks, None, None, None)
575
+
576
+ if tau is not None and T > 1 and ids_list is not None:
577
+ # Coda-Lens adaptive early exit after Pass 1
578
+ h1 = self._run_coda(h_core, 1, rope_ctx, masks, None, None, None, read=read)
579
+ probs1 = self._code_readout().probs_each(h1.float(), ids_list)
580
+ need_deep = [b for b, p in enumerate(probs1) if max(p) < tau]
581
+ n_deep = len(need_deep)
582
+ n_exit = B - n_deep
583
+ self.last_exit_stats = {
584
+ "exited": n_exit,
585
+ "deep": n_deep,
586
+ "mean_passes": (n_exit * 1 + n_deep * T) / max(1, B),
587
+ }
588
+ if not need_deep:
589
+ return h1, probs1
590
+ idx = torch.tensor(need_deep, dtype=torch.long, device=self.dev)
591
+ sub_v1 = v1[idx]
592
+ prev_v2_hat = vk.varloop_delta_rms_unit(h_b2[idx], sub_v1, self.cfg.rms_eps)
593
+ prev_v3_hat = vk.varloop_delta_rms_unit(h_core[idx], h_b2[idx], self.cfg.rms_eps)
594
+ sub_rope, sub_masks = self._slice_rope_masks(rope_ctx, masks, idx)
595
+ sub_read = read[idx]
596
+ sub_h = sub_v1
597
+ for pass_idx in range(1, T):
598
+ sub_h, sub_hb2 = self._run_core_pass(
599
+ sub_v1, prev_v2_hat, prev_v3_hat, pass_idx, sub_rope, sub_masks, None, None, None)
600
+ if pass_idx + 1 < T:
601
+ prev_v2_hat = vk.varloop_delta_rms_unit(sub_hb2, sub_v1, self.cfg.rms_eps)
602
+ prev_v3_hat = vk.varloop_delta_rms_unit(sub_h, sub_hb2, self.cfg.rms_eps)
603
+ h_deep = self._run_coda(sub_h, T, sub_rope, sub_masks, None, None, None, read=sub_read)
604
+ probs_deep = self._code_readout().probs_each(h_deep.float(), [ids_list[b] for b in need_deep])
605
+ out_h = h1.clone()
606
+ out_h[idx] = h_deep
607
+ out_p = list(probs1)
608
+ for b, p in zip(need_deep, probs_deep):
609
+ out_p[b] = p
610
+ return out_h, out_p
611
+
612
+ # Fixed-depth Pure Inkling: Prelude -> Core x T -> Coda (once)
613
+ prev_v2_hat = prev_v3_hat = None
614
+ for pass_idx in range(1, T):
615
+ prev_v2_hat = vk.varloop_delta_rms_unit(h_b2, v1, self.cfg.rms_eps)
616
+ prev_v3_hat = vk.varloop_delta_rms_unit(h_core, h_b2, self.cfg.rms_eps)
617
+ h_core, h_b2 = self._run_core_pass(v1, prev_v2_hat, prev_v3_hat, pass_idx, rope_ctx, masks, None, None, None)
618
+ final_h = self._run_coda(h_core, T, rope_ctx, masks, None, None, None, read=read)
619
+ probs = self._code_readout().probs_each(final_h.float(), ids_list) if ids_list is not None else None
620
+ return final_h, probs
621
+
622
+ def _trim_sliding(self, kv: dict, kpos: dict):
623
+ if not self.is_gemma4 or not self.window:
624
+ return kv, kpos
625
+ t, keep = "sliding_attention", self.window - 1
626
+ if t not in kpos or kpos[t].shape[1] <= keep:
627
+ return kv, kpos
628
+ lc = self.cfg
629
+ n = (kpos[t] >= 0).sum(1)
630
+ idx = (n - keep).clamp_min(0)[:, None] + torch.arange(keep, device=n.device)
631
+ ok = idx < n[:, None]
632
+ idx = idx.clamp_max(kpos[t].shape[1] - 1)
633
+ kpos = dict(kpos, **{t: torch.where(ok, kpos[t].gather(1, idx), -1)})
634
+
635
+ def phys_of(logical_idx: int) -> int:
636
+ if logical_idx < lc.n_prelude:
637
+ return logical_idx
638
+ rem = logical_idx - lc.n_prelude
639
+ # Coda logical indices start at n_prelude + pass_count * n_core; check if sliding
640
+ return lc.n_prelude + (rem % lc.n_core)
641
+
642
+ # Map each logical layer index explicitly via stored layer_type metadata
643
+ out = {}
644
+ for lid, (K, V) in kv.items():
645
+ if lid in self._logical_sliding:
646
+ g = idx[:, None, :, None].expand(-1, K.shape[1], -1, K.shape[3])
647
+ K, V = K.gather(2, g), V.gather(2, g)
648
+ out[lid] = (K, V)
649
+ return out, kpos
650
+
651
+ @torch.no_grad()
652
+ def _run_soam_group(self, toks: list[list[int]], ids_list: list[list[int]],
653
+ num_passes: int | None = None, exit_tau: float | None = None) -> list[list[float]]:
654
+ """Exact SOAM execution for a group of prompts sharing a prefix P > 0 with independent per-pass KV cache!
655
+ Under Coda-Lens early exit (`tau`), Passes 2..T of BOTH the shared prefix AND suffixes are computed lazily
656
+ ONLY when at least one prompt in the group has conf1 < tau!"""
657
+ T = self.num_passes if num_passes is None else int(num_passes)
658
+ tau = self.exit_tau if exit_tau is None else exit_tau
659
+ P = min(len(os.path.commonprefix(toks)), min(map(len, toks)) - 1)
660
+ if P <= 0:
661
+ _, probs = self.forward_batch(toks, ids_list, two_way=False, num_passes=T, exit_tau=tau)
662
+ return probs
663
+
664
+ lc = self.cfg
665
+ # Precompute which logical indices are sliding layers (for Gemma 4 window trim)
666
+ self._logical_sliding = set()
667
+ if self.is_gemma4:
668
+ for i in range(lc.n_prelude):
669
+ if self.types[i] == "sliding_attention":
670
+ self._logical_sliding.add(i)
671
+ for p in range(T):
672
+ for j in range(lc.n_core):
673
+ if self.types[lc.n_prelude + j] == "sliding_attention":
674
+ self._logical_sliding.add(lc.n_prelude + p * lc.n_core + j)
675
+ for p_count in (1, T):
676
+ base = lc.n_prelude + p_count * lc.n_core
677
+ for i in range(lc.n_coda):
678
+ if self.types[lc.n_prelude + lc.n_core + i] == "sliding_attention":
679
+ self._logical_sliding.add(base + i)
680
+
681
+ # 1. Prefix forward: Prelude + Core Pass 1 (+ Coda Pass 1 if exit_tau else Core Passes 2..T + Coda T)
682
+ p_ids = torch.tensor([list(toks[0][:P])], device=self.dev)
683
+ p_pos = torch.arange(P, device=self.dev)[None]
684
+ p_valid = torch.ones((1, P), dtype=torch.bool, device=self.dev)
685
+ p_h0 = self.lm.embed_tokens(p_ids)
686
+ p_rope, p_masks = self._build_rope_masks(p_h0, p_pos, p_valid, two_way=False)
687
+
688
+ kv_pre = {}
689
+ p_v1 = self._run_prelude(p_h0, p_rope, p_masks, None, None, kv_pre)
690
+ p_hcore, p_hb2 = self._run_core_pass(p_v1, None, None, 0, p_rope, p_masks, None, None, kv_pre)
691
+
692
+ kpos_full = {t: p_pos for t in (set(self.types) if self.is_gemma4 else {"full_attention"})}
693
+
694
+ # Prepare suffixes [B, S]
695
+ B = len(toks)
696
+ sfxs = [t[P:] for t in toks]
697
+ S = max(map(len, sfxs))
698
+ s_ids = torch.tensor([list(s) + [self.pad] * (S - len(s)) for s in sfxs], device=self.dev)
699
+ s_lens = torch.tensor([len(s) for s in sfxs], device=self.dev)
700
+ ar = torch.arange(S, device=self.dev)
701
+ s_valid = ar[None] < s_lens[:, None]
702
+ s_pos = P + ar[None].expand(B, S)
703
+ s_read = s_lens - 1
704
+ grp = torch.zeros(B, dtype=torch.long, device=self.dev)
705
+
706
+ s_h0 = self.lm.embed_tokens(s_ids)
707
+
708
+ if tau is not None and T > 1:
709
+ # Lazy Coda-Lens SOAM: finish Pass-1 Coda prefix KV first, test all suffixes at T=1!
710
+ self._run_coda(p_hcore, 1, p_rope, p_masks, None, None, kv_pre, kv_only=True)
711
+ kv_use, kpos_use = self._trim_sliding(kv_pre, kpos_full)
712
+ s_rope, s_masks = self._build_rope_masks(s_h0, s_pos, s_valid, kpos=kpos_use, grp=grp, two_way=False)
713
+ s_v1 = self._run_prelude(s_h0, s_rope, s_masks, kv_use, grp, None)
714
+ s_hcore, s_hb2 = self._run_core_pass(s_v1, None, None, 0, s_rope, s_masks, kv_use, grp, None)
715
+ h1 = self._run_coda(s_hcore, 1, s_rope, s_masks, kv_use, grp, None, read=s_read)
716
+ probs1 = self._code_readout().probs_each(h1.float(), ids_list)
717
+ need_deep = [b for b, p in enumerate(probs1) if max(p) < tau]
718
+ n_deep = len(need_deep)
719
+ n_exit = B - n_deep
720
+ self.last_exit_stats = {
721
+ "exited": n_exit,
722
+ "deep": n_deep,
723
+ "mean_passes": (n_exit * 1 + n_deep * T) / max(1, B),
724
+ }
725
+ if not need_deep:
726
+ return probs1
727
+ # Lazily compute Passes 2..T + Coda T prefix KV (starting directly from saved p_v1, p_hb2, p_hcore!)
728
+ p_v2h = vk.varloop_delta_rms_unit(p_hb2, p_v1, self.cfg.rms_eps)
729
+ p_v3h = vk.varloop_delta_rms_unit(p_hcore, p_hb2, self.cfg.rms_eps)
730
+ for pass_idx in range(1, T):
731
+ p_hcore, p_hb2 = self._run_core_pass(p_v1, p_v2h, p_v3h, pass_idx, p_rope, p_masks, None, None, kv_pre)
732
+ if pass_idx + 1 < T:
733
+ p_v2h = vk.varloop_delta_rms_unit(p_hb2, p_v1, self.cfg.rms_eps)
734
+ p_v3h = vk.varloop_delta_rms_unit(p_hcore, p_hb2, self.cfg.rms_eps)
735
+ self._run_coda(p_hcore, T, p_rope, p_masks, None, None, kv_pre, kv_only=True)
736
+ kv_use, kpos_use = self._trim_sliding(kv_pre, kpos_full)
737
+
738
+ # Compact suffixes to hard items only
739
+ idx = torch.tensor(need_deep, dtype=torch.long, device=self.dev)
740
+ sub_v1 = s_v1[idx]
741
+ sub_v2h = vk.varloop_delta_rms_unit(s_hb2[idx], sub_v1, self.cfg.rms_eps)
742
+ sub_v3h = vk.varloop_delta_rms_unit(s_hcore[idx], s_hb2[idx], self.cfg.rms_eps)
743
+ sub_rope, sub_masks = self._slice_rope_masks(s_rope, s_masks, idx)
744
+ sub_grp = grp[idx]
745
+ sub_read = s_read[idx]
746
+ sub_h = sub_v1
747
+ for pass_idx in range(1, T):
748
+ sub_h, sub_hb2 = self._run_core_pass(
749
+ sub_v1, sub_v2h, sub_v3h, pass_idx, sub_rope, sub_masks, kv_use, sub_grp, None)
750
+ if pass_idx + 1 < T:
751
+ sub_v2h = vk.varloop_delta_rms_unit(sub_hb2, sub_v1, self.cfg.rms_eps)
752
+ sub_v3h = vk.varloop_delta_rms_unit(sub_h, sub_hb2, self.cfg.rms_eps)
753
+ h_deep = self._run_coda(sub_h, T, sub_rope, sub_masks, kv_use, sub_grp, None, read=sub_read)
754
+ probs_deep = self._code_readout().probs_each(h_deep.float(), [ids_list[b] for b in need_deep])
755
+ out_p = list(probs1)
756
+ for b, p in zip(need_deep, probs_deep):
757
+ out_p[b] = p
758
+ return out_p
759
+
760
+ # Fixed-depth SOAM: complete prefix Passes 2..T + Coda T KV, then run all suffixes over kv_pre
761
+ for pass_idx in range(1, T):
762
+ p_v2h = vk.varloop_delta_rms_unit(p_hb2, p_v1, self.cfg.rms_eps)
763
+ p_v3h = vk.varloop_delta_rms_unit(p_hcore, p_hb2, self.cfg.rms_eps)
764
+ p_hcore, p_hb2 = self._run_core_pass(p_v1, p_v2h, p_v3h, pass_idx, p_rope, p_masks, None, None, kv_pre)
765
+ self._run_coda(p_hcore, T, p_rope, p_masks, None, None, kv_pre, kv_only=True)
766
+ kv_use, kpos_use = self._trim_sliding(kv_pre, kpos_full)
767
+
768
+ s_rope, s_masks = self._build_rope_masks(s_h0, s_pos, s_valid, kpos=kpos_use, grp=grp, two_way=False)
769
+ s_v1 = self._run_prelude(s_h0, s_rope, s_masks, kv_use, grp, None)
770
+ s_hcore, s_hb2 = self._run_core_pass(s_v1, None, None, 0, s_rope, s_masks, kv_use, grp, None)
771
+ for pass_idx in range(1, T):
772
+ s_v2h = vk.varloop_delta_rms_unit(s_hb2, s_v1, self.cfg.rms_eps)
773
+ s_v3h = vk.varloop_delta_rms_unit(s_hcore, s_hb2, self.cfg.rms_eps)
774
+ s_hcore, s_hb2 = self._run_core_pass(s_v1, s_v2h, s_v3h, pass_idx, s_rope, s_masks, kv_use, grp, None)
775
+ final_h = self._run_coda(s_hcore, T, s_rope, s_masks, kv_use, grp, None, read=s_read)
776
+ return self._code_readout().probs_each(final_h.float(), ids_list)
777
+
778
+ def two_way_rows(self, toks: list[list[int]]) -> list[bool]:
779
+ if not self.two_way:
780
+ return [False] * len(toks)
781
+ P = len(os.path.commonprefix(toks))
782
+ record = P + sum(len(t) - P for t in toks)
783
+ return [record <= self.two_way["max_record"] and len(t) <= self.two_way["max_prompt"] for t in toks]
784
+
785
+ @torch.no_grad()
786
+ def run_groups(self, groups: list[tuple[list[list[int]], list[list[int]]]]) -> list[list[list[float]]]:
787
+ """Run [(toks_list, ids_list), ...] -> [[probs per prompt], ...]."""
788
+ out = []
789
+ for toks, ids_list in groups:
790
+ if self.two_way:
791
+ ok = self.two_way_rows(toks)
792
+ if all(ok):
793
+ _, probs = self.forward_batch(toks, ids_list, two_way=True)
794
+ out.append(probs)
795
+ continue
796
+ if any(ok):
797
+ res = [None] * len(toks)
798
+ tw_idx = [i for i, f in enumerate(ok) if f]
799
+ cw_idx = [i for i, f in enumerate(ok) if not f]
800
+ _, tw_p = self.forward_batch([toks[i] for i in tw_idx], [ids_list[i] for i in tw_idx], two_way=True)
801
+ for i, p in zip(tw_idx, tw_p):
802
+ res[i] = p
803
+ cw_p = self._run_soam_group([toks[i] for i in cw_idx], [ids_list[i] for i in cw_idx])
804
+ for i, p in zip(cw_idx, cw_p):
805
+ res[i] = p
806
+ out.append(res)
807
+ continue
808
+ if len(toks) > 1:
809
+ out.append(self._run_soam_group(toks, ids_list))
810
+ else:
811
+ _, probs = self.forward_batch(toks, ids_list, two_way=False)
812
+ out.append(probs)
813
+ return out