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
@@ -0,0 +1,907 @@
1
+ """Pure-Triton fused kernels for VarLoop looped transformers (basal-engine 3.0.3):
2
+
3
+ - varloop_rms_unit(x, eps) unit RMS normalization in fp32: x / sqrt(mean(x^2) + eps)
4
+ - varloop_delta_rms_unit(h, anchor, eps) fused block delta + unit RMS: _rms_unit(h - anchor, eps)
5
+ - varloop_prep_qkv(x, v2, v3, beta_qkv, eps) fused x_hat (shared across q/k/v) + 3-channel m_hat [3, M, D]
6
+ - varloop_mix_rmsnorm_qkv(x, v2, v3, beta, fg, w, eps, gemma_norm)
7
+ fuses m, (1 - tanh(f))*x + tanh(g)*m, and input_layernorm for q/k/v
8
+ - varloop_prep_mlp(x, v2, v3, beta_m, eps) fused [x_hat, m_hat] [M, 2*D] for the mlp cross-loop channel
9
+ - varloop_mix_rmsnorm_mlp(x, v2, v3, beta_m, fg_m, w, eps, gemma_norm)
10
+ fuses m, (1 - tanh(f))*x + tanh(g)*m, and post_attention_layernorm
11
+ - varloop_mix_gemma_ff(x, v2, v3, beta_m, fg_m, w1, w2, eps)
12
+ fuses Gemma 4 mlp gate -> (x_ff, pre_ff_ln1(x_ff), pre_ff_ln2(x_ff))
13
+ - gemma_gelu_mul(gu) fused gelu_pytorch_tanh(gate) * up
14
+ - grouped_moe_forward(x, top_k_index, top_k_weights, gate_up_proj, down_proj)
15
+ zero-sync 128-expert MoE via torch._grouped_mm (CUDA) / exact fallback
16
+
17
+ Every Triton op is registered via torch.library.triton_op on CUDA (zero torch.compile graph breaks, CUDA-graph
18
+ capturable, deterministic fixed tiles) and has an exact PyTorch fallback on CPU / MPS.
19
+ """
20
+ import torch
21
+ import torch.nn.functional as F
22
+
23
+ _OPS = []
24
+
25
+
26
+ def _rms_unit_ref(x, eps):
27
+ xf = x.float()
28
+ return (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps)).to(x.dtype)
29
+
30
+
31
+ def _rmsnorm_ref(x, w, eps, gemma_norm=False):
32
+ xf = x.float()
33
+ y = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps)
34
+ if w is None:
35
+ return y.to(x.dtype)
36
+ if gemma_norm:
37
+ return (y * w.float()).to(x.dtype)
38
+ return w * y.to(x.dtype)
39
+
40
+
41
+ def _build():
42
+ import triton
43
+ import triton.language as tl
44
+ from torch.library import triton_op, wrap_triton
45
+
46
+ # Note: tanh is inlined as (2.0 * tl.sigmoid(2.0 * x) - 1.0) inside each kernel because
47
+ # TorchInductor's compile-worker subprocess serializes kernel ASTs without closure helpers.
48
+
49
+ @triton.jit
50
+ def _rms_unit_k(X_ptr, A_ptr, Y_ptr, M, D, eps, HAS_ANCHOR: tl.constexpr, BLOCK_D: tl.constexpr):
51
+ row = tl.program_id(0).to(tl.int64)
52
+ offs = tl.arange(0, BLOCK_D)
53
+ mask = offs < D
54
+ x = tl.load(X_ptr + row * D + offs, mask=mask, other=0.0).to(tl.float32)
55
+ if HAS_ANCHOR:
56
+ a = tl.load(A_ptr + row * D + offs, mask=mask, other=0.0).to(tl.float32)
57
+ # Match reference (h - anchor) in x's dtype before fp32 unit-RMS
58
+ x = (x - a).to(Y_ptr.dtype.element_ty).to(tl.float32)
59
+ var = tl.sum(x * x, axis=0) / D
60
+ inv = tl.math.rsqrt(var + eps)
61
+ y = (x * inv).to(Y_ptr.dtype.element_ty)
62
+ tl.store(Y_ptr + row * D + offs, y, mask=mask)
63
+
64
+ @triton.jit
65
+ def _prep_qkv_k(X_ptr, V2_ptr, V3_ptr, B_ptr, XH_ptr, MH_ptr, M, D, eps, BLOCK_D: tl.constexpr):
66
+ """One program per token row: computes x_hat once and m_hat for all 3 channels (q, k, v)."""
67
+ row = tl.program_id(0).to(tl.int64)
68
+ offs = tl.arange(0, BLOCK_D)
69
+ mask = offs < D
70
+ base = row * D + offs
71
+ dt = XH_ptr.dtype.element_ty
72
+
73
+ x = tl.load(X_ptr + base, mask=mask, other=0.0).to(tl.float32)
74
+ x_var = tl.sum(x * x, axis=0) / D
75
+ xh = (x * tl.math.rsqrt(x_var + eps)).to(dt)
76
+ tl.store(XH_ptr + base, xh, mask=mask)
77
+
78
+ v2 = tl.load(V2_ptr + base, mask=mask, other=0.0).to(tl.float32)
79
+ v3 = tl.load(V3_ptr + base, mask=mask, other=0.0).to(tl.float32)
80
+
81
+ # B_ptr layout: [M, 3, 2]
82
+ for c in tl.static_range(3):
83
+ b0 = tl.load(B_ptr + row * 6 + c * 2).to(tl.float32)
84
+ b1 = tl.load(B_ptr + row * 6 + c * 2 + 1).to(tl.float32)
85
+ m = (b0 * v2 + b1 * v3).to(dt).to(tl.float32)
86
+ m_var = tl.sum(m * m, axis=0) / D
87
+ mh = (m * tl.math.rsqrt(m_var + eps)).to(dt)
88
+ tl.store(MH_ptr + (c * M + row) * D + offs, mh, mask=mask)
89
+
90
+ @triton.jit
91
+ def _mix_rmsnorm_qkv_k(X_ptr, V2_ptr, V3_ptr, B_ptr, FG_ptr, W_ptr, OUT_ptr, M, D, eps,
92
+ GEMMA_NORM: tl.constexpr, BLOCK_D: tl.constexpr):
93
+ """One program per (token row, channel c in {0,1,2}): computes m, gated mix, and input_layernorm."""
94
+ row = tl.program_id(0).to(tl.int64)
95
+ c = tl.program_id(1).to(tl.int64)
96
+ offs = tl.arange(0, BLOCK_D)
97
+ mask = offs < D
98
+ base = row * D + offs
99
+ dt = OUT_ptr.dtype.element_ty
100
+
101
+ x = tl.load(X_ptr + base, mask=mask, other=0.0).to(tl.float32)
102
+ v2 = tl.load(V2_ptr + base, mask=mask, other=0.0).to(tl.float32)
103
+ v3 = tl.load(V3_ptr + base, mask=mask, other=0.0).to(tl.float32)
104
+ b0 = tl.load(B_ptr + row * 6 + c * 2).to(tl.float32)
105
+ b1 = tl.load(B_ptr + row * 6 + c * 2 + 1).to(tl.float32)
106
+ m = (b0 * v2 + b1 * v3).to(dt).to(tl.float32)
107
+
108
+ # FG_ptr layout: [3, M, 2*D]
109
+ fg_base = (c * M + row) * (2 * D) + offs
110
+ f = tl.load(FG_ptr + fg_base, mask=mask, other=0.0).to(tl.float32)
111
+ g = tl.load(FG_ptr + fg_base + D, mask=mask, other=0.0).to(tl.float32)
112
+ fz = (2.0 * tl.sigmoid(2.0 * f) - 1.0).to(dt).to(tl.float32)
113
+ gz = (2.0 * tl.sigmoid(2.0 * g) - 1.0).to(dt).to(tl.float32)
114
+ mixed = ((1.0 - fz) * x + gz * m).to(dt).to(tl.float32)
115
+
116
+ var = tl.sum(mixed * mixed, axis=0) / D
117
+ inv = tl.math.rsqrt(var + eps)
118
+ w = tl.load(W_ptr + offs, mask=mask, other=0.0)
119
+ if GEMMA_NORM:
120
+ y = (mixed * inv * w.to(tl.float32)).to(dt)
121
+ else:
122
+ y = ((mixed * inv).to(dt) * w).to(dt)
123
+ tl.store(OUT_ptr + (c * M + row) * D + offs, y, mask=mask)
124
+
125
+ @triton.jit
126
+ def _prep_mlp_k(X_ptr, V2_ptr, V3_ptr, B_ptr, XM_ptr, M, D, eps, BLOCK_D: tl.constexpr):
127
+ """One program per token row: writes [x_hat, m_hat] into XM_ptr [M, 2*D]."""
128
+ row = tl.program_id(0).to(tl.int64)
129
+ offs = tl.arange(0, BLOCK_D)
130
+ mask = offs < D
131
+ base = row * D + offs
132
+ dt = XM_ptr.dtype.element_ty
133
+
134
+ x = tl.load(X_ptr + base, mask=mask, other=0.0).to(tl.float32)
135
+ x_var = tl.sum(x * x, axis=0) / D
136
+ xh = (x * tl.math.rsqrt(x_var + eps)).to(dt)
137
+
138
+ v2 = tl.load(V2_ptr + base, mask=mask, other=0.0).to(tl.float32)
139
+ v3 = tl.load(V3_ptr + base, mask=mask, other=0.0).to(tl.float32)
140
+ b0 = tl.load(B_ptr + row * 2).to(tl.float32)
141
+ b1 = tl.load(B_ptr + row * 2 + 1).to(tl.float32)
142
+ m = (b0 * v2 + b1 * v3).to(dt).to(tl.float32)
143
+ m_var = tl.sum(m * m, axis=0) / D
144
+ mh = (m * tl.math.rsqrt(m_var + eps)).to(dt)
145
+
146
+ out_base = row * (2 * D) + offs
147
+ tl.store(XM_ptr + out_base, xh, mask=mask)
148
+ tl.store(XM_ptr + out_base + D, mh, mask=mask)
149
+
150
+ @triton.jit
151
+ def _mix_rmsnorm_mlp_k(X_ptr, V2_ptr, V3_ptr, B_ptr, FG_ptr, W1_ptr, W2_ptr,
152
+ RAW_ptr, Y1_ptr, Y2_ptr, M, D, eps,
153
+ GEMMA_NORM: tl.constexpr, WRITE_RAW: tl.constexpr, HAS_W2: tl.constexpr,
154
+ BLOCK_D: tl.constexpr):
155
+ """Fused MLP cross-loop mix + RMSNorm (+ optional raw x_ff and 2nd RMSNorm for Gemma 4 MoE)."""
156
+ row = tl.program_id(0).to(tl.int64)
157
+ offs = tl.arange(0, BLOCK_D)
158
+ mask = offs < D
159
+ base = row * D + offs
160
+ dt = Y1_ptr.dtype.element_ty
161
+
162
+ x = tl.load(X_ptr + base, mask=mask, other=0.0).to(tl.float32)
163
+ v2 = tl.load(V2_ptr + base, mask=mask, other=0.0).to(tl.float32)
164
+ v3 = tl.load(V3_ptr + base, mask=mask, other=0.0).to(tl.float32)
165
+ b0 = tl.load(B_ptr + row * 2).to(tl.float32)
166
+ b1 = tl.load(B_ptr + row * 2 + 1).to(tl.float32)
167
+ m = (b0 * v2 + b1 * v3).to(dt).to(tl.float32)
168
+
169
+ fg_base = row * (2 * D) + offs
170
+ f = tl.load(FG_ptr + fg_base, mask=mask, other=0.0).to(tl.float32)
171
+ g = tl.load(FG_ptr + fg_base + D, mask=mask, other=0.0).to(tl.float32)
172
+ fz = (2.0 * tl.sigmoid(2.0 * f) - 1.0).to(dt).to(tl.float32)
173
+ gz = (2.0 * tl.sigmoid(2.0 * g) - 1.0).to(dt).to(tl.float32)
174
+ mixed_dt = ((1.0 - fz) * x + gz * m).to(dt)
175
+ if WRITE_RAW:
176
+ tl.store(RAW_ptr + base, mixed_dt, mask=mask)
177
+ mixed = mixed_dt.to(tl.float32)
178
+
179
+ var = tl.sum(mixed * mixed, axis=0) / D
180
+ inv = tl.math.rsqrt(var + eps)
181
+ w1 = tl.load(W1_ptr + offs, mask=mask, other=0.0)
182
+ if GEMMA_NORM:
183
+ y1 = (mixed * inv * w1.to(tl.float32)).to(dt)
184
+ else:
185
+ y1 = ((mixed * inv).to(dt) * w1).to(dt)
186
+ tl.store(Y1_ptr + base, y1, mask=mask)
187
+ if HAS_W2:
188
+ w2 = tl.load(W2_ptr + offs, mask=mask, other=0.0)
189
+ y2 = (mixed * inv * w2.to(tl.float32)).to(dt)
190
+ tl.store(Y2_ptr + base, y2, mask=mask)
191
+
192
+ @triton.jit
193
+ def _gemma_gelu_mul_k(GU_ptr, Y_ptr, M, I, BLOCK: tl.constexpr):
194
+ """Fused gelu_pytorch_tanh(gate) * up from merged [M, 2*I] tensor."""
195
+ row = tl.program_id(0).to(tl.int64)
196
+ blk = tl.program_id(1)
197
+ offs = blk * BLOCK + tl.arange(0, BLOCK)
198
+ mask = offs < I
199
+ g = tl.load(GU_ptr + row * (2 * I) + offs, mask=mask, other=0.0).to(tl.float32)
200
+ u = tl.load(GU_ptr + row * (2 * I) + I + offs, mask=mask, other=0.0).to(tl.float32)
201
+ # gelu_pytorch_tanh: 0.5 * g * (1 + tanh(sqrt(2/pi) * (g + 0.044715 * g^3)))
202
+ c = 0.7978845608028654 * (g + 0.044715 * g * g * g)
203
+ act = (0.5 * g * (1.0 + (2.0 * tl.sigmoid(2.0 * c) - 1.0))).to(Y_ptr.dtype.element_ty).to(tl.float32)
204
+ y = (act * u).to(Y_ptr.dtype.element_ty)
205
+ tl.store(Y_ptr + row * I + offs, y, mask=mask)
206
+
207
+ @triton.jit
208
+ def _quant_rowfp8_k(X_ptr, Q_ptr, S_ptr, M, D, BLOCK_D: tl.constexpr):
209
+ """Single-pass per-row FP8 E4M3 quantization with zero-padding to M_pad (multiple of 16)."""
210
+ row = tl.program_id(0).to(tl.int64)
211
+ offs = tl.arange(0, BLOCK_D)
212
+ mask = offs < D
213
+ if row >= M:
214
+ tl.store(Q_ptr + row * D + offs, tl.zeros([BLOCK_D], dtype=tl.float8e4nv), mask=mask)
215
+ tl.store(S_ptr + row, 1.0)
216
+ return
217
+ x = tl.load(X_ptr + row * D + offs, mask=mask, other=0.0).to(tl.float32)
218
+ amax = tl.maximum(tl.max(tl.abs(x), axis=0), 1e-12)
219
+ s = amax / 448.0
220
+ q = tl.minimum(tl.maximum(tl.math.div_rn(x, s), -448.0), 448.0).to(tl.float8e4nv)
221
+ tl.store(Q_ptr + row * D + offs, q, mask=mask)
222
+ tl.store(S_ptr + row, s)
223
+
224
+ @triton.jit
225
+ def _add_rms_rowfp8_k(H_ptr, R_ptr, W_ptr, HO_ptr, QO_ptr, SO_ptr, M, D, eps,
226
+ HAS_RES: tl.constexpr, BLOCK_D: tl.constexpr):
227
+ """Fused residual add + RMSNorm + per-row FP8 E4M3 quant + M_pad padding in ONE kernel!"""
228
+ row = tl.program_id(0).to(tl.int64)
229
+ offs = tl.arange(0, BLOCK_D)
230
+ mask = offs < D
231
+ if row >= M:
232
+ tl.store(QO_ptr + row * D + offs, tl.zeros([BLOCK_D], dtype=tl.float8e4nv), mask=mask)
233
+ tl.store(SO_ptr + row, 1.0)
234
+ return
235
+ h = tl.load(H_ptr + row * D + offs, mask=mask, other=0.0)
236
+ if HAS_RES:
237
+ r = tl.load(R_ptr + row * D + offs, mask=mask, other=0.0)
238
+ h = (h.to(tl.float32) + r.to(tl.float32)).to(HO_ptr.dtype.element_ty)
239
+ tl.store(HO_ptr + row * D + offs, h, mask=mask)
240
+ hf = h.to(tl.float32)
241
+ var = tl.sum(hf * hf, axis=0) / D
242
+ inv = tl.math.rsqrt(var + eps)
243
+ w = tl.load(W_ptr + offs, mask=mask, other=0.0)
244
+ y = ((hf * inv).to(H_ptr.dtype.element_ty) * w).to(tl.float32)
245
+ amax = tl.maximum(tl.max(tl.abs(y), axis=0), 1e-12)
246
+ s = amax / 448.0
247
+ q = tl.minimum(tl.maximum(tl.math.div_rn(y, s), -448.0), 448.0).to(tl.float8e4nv)
248
+ tl.store(QO_ptr + row * D + offs, q, mask=mask)
249
+ tl.store(SO_ptr + row, s)
250
+
251
+ @triton.jit
252
+ def _swiglu_rowfp8_k(GU_ptr, QO_ptr, SO_ptr, M, I, BLOCK: tl.constexpr):
253
+ """Fused SiLU(gate)*up + per-row FP8 E4M3 quant + M_pad padding (loops over I in chunks of BLOCK)."""
254
+ row = tl.program_id(0).to(tl.int64)
255
+ if row >= M:
256
+ tl.store(SO_ptr + row, 1.0)
257
+ for start in tl.range(0, I, BLOCK):
258
+ offs = start + tl.arange(0, BLOCK)
259
+ tl.store(QO_ptr + row * I + offs, tl.zeros([BLOCK], dtype=tl.float8e4nv), mask=offs < I)
260
+ return
261
+ amax = 1e-12
262
+ for start in tl.range(0, I, BLOCK):
263
+ offs = start + tl.arange(0, BLOCK)
264
+ mask = offs < I
265
+ g = tl.load(GU_ptr + row * (2 * I) + offs, mask=mask, other=0.0).to(tl.float32)
266
+ u = tl.load(GU_ptr + row * (2 * I) + I + offs, mask=mask, other=0.0).to(tl.float32)
267
+ y = g * tl.sigmoid(g) * u
268
+ amax = tl.maximum(amax, tl.max(tl.abs(y), axis=0))
269
+ s = amax / 448.0
270
+ tl.store(SO_ptr + row, s)
271
+ for start in tl.range(0, I, BLOCK):
272
+ offs = start + tl.arange(0, BLOCK)
273
+ mask = offs < I
274
+ g = tl.load(GU_ptr + row * (2 * I) + offs, mask=mask, other=0.0).to(tl.float32)
275
+ u = tl.load(GU_ptr + row * (2 * I) + I + offs, mask=mask, other=0.0).to(tl.float32)
276
+ y = g * tl.sigmoid(g) * u
277
+ q = tl.minimum(tl.maximum(tl.math.div_rn(y, s), -448.0), 448.0).to(tl.float8e4nv)
278
+ tl.store(QO_ptr + row * I + offs, q, mask=mask)
279
+
280
+ @triton.jit
281
+ def _mix_rmsnorm_qkv_rowfp8_k(X_ptr, V2_ptr, V3_ptr, B_ptr, FG_ptr, W_ptr, QO_ptr, SO_ptr,
282
+ M, M_pad, D, eps, GEMMA_NORM: tl.constexpr, BLOCK_D: tl.constexpr):
283
+ """Fused cross-loop mix + RMSNorm + per-row FP8 E4M3 quant for Q/K/V in ONE kernel!"""
284
+ row = tl.program_id(0).to(tl.int64)
285
+ c = tl.program_id(1).to(tl.int64)
286
+ offs = tl.arange(0, BLOCK_D)
287
+ mask = offs < D
288
+ q_base = (c * M_pad + row) * D + offs
289
+ s_idx = c * M_pad + row
290
+ if row >= M:
291
+ tl.store(QO_ptr + q_base, tl.zeros([BLOCK_D], dtype=tl.float8e4nv), mask=mask)
292
+ tl.store(SO_ptr + s_idx, 1.0)
293
+ return
294
+ base = row * D + offs
295
+ dt = X_ptr.dtype.element_ty
296
+ x = tl.load(X_ptr + base, mask=mask, other=0.0).to(tl.float32)
297
+ v2 = tl.load(V2_ptr + base, mask=mask, other=0.0).to(tl.float32)
298
+ v3 = tl.load(V3_ptr + base, mask=mask, other=0.0).to(tl.float32)
299
+ b0 = tl.load(B_ptr + row * 6 + c * 2).to(tl.float32)
300
+ b1 = tl.load(B_ptr + row * 6 + c * 2 + 1).to(tl.float32)
301
+ m = (b0 * v2 + b1 * v3).to(dt).to(tl.float32)
302
+
303
+ fg_base = (c * M + row) * (2 * D) + offs
304
+ f = tl.load(FG_ptr + fg_base, mask=mask, other=0.0).to(tl.float32)
305
+ g = tl.load(FG_ptr + fg_base + D, mask=mask, other=0.0).to(tl.float32)
306
+ fz = (2.0 * tl.sigmoid(2.0 * f) - 1.0).to(dt).to(tl.float32)
307
+ gz = (2.0 * tl.sigmoid(2.0 * g) - 1.0).to(dt).to(tl.float32)
308
+ mixed = ((1.0 - fz) * x + gz * m).to(dt).to(tl.float32)
309
+
310
+ var = tl.sum(mixed * mixed, axis=0) / D
311
+ inv = tl.math.rsqrt(var + eps)
312
+ w = tl.load(W_ptr + offs, mask=mask, other=0.0)
313
+ if GEMMA_NORM:
314
+ y = (mixed * inv * w.to(tl.float32)).to(dt).to(tl.float32)
315
+ else:
316
+ y = ((mixed * inv).to(dt) * w).to(tl.float32)
317
+ amax = tl.maximum(tl.max(tl.abs(y), axis=0), 1e-12)
318
+ s = amax / 448.0
319
+ q = tl.minimum(tl.maximum(tl.math.div_rn(y, s), -448.0), 448.0).to(tl.float8e4nv)
320
+ tl.store(QO_ptr + q_base, q, mask=mask)
321
+ tl.store(SO_ptr + s_idx, s)
322
+
323
+ @triton.jit
324
+ def _mix_rmsnorm_mlp_rowfp8_k(X_ptr, V2_ptr, V3_ptr, B_ptr, FG_ptr, W_ptr, QO_ptr, SO_ptr,
325
+ M, D, eps, GEMMA_NORM: tl.constexpr, BLOCK_D: tl.constexpr):
326
+ """Fused cross-loop MLP mix + RMSNorm + per-row FP8 E4M3 quant in ONE kernel!"""
327
+ row = tl.program_id(0).to(tl.int64)
328
+ offs = tl.arange(0, BLOCK_D)
329
+ mask = offs < D
330
+ if row >= M:
331
+ tl.store(QO_ptr + row * D + offs, tl.zeros([BLOCK_D], dtype=tl.float8e4nv), mask=mask)
332
+ tl.store(SO_ptr + row, 1.0)
333
+ return
334
+ base = row * D + offs
335
+ dt = X_ptr.dtype.element_ty
336
+ x = tl.load(X_ptr + base, mask=mask, other=0.0).to(tl.float32)
337
+ v2 = tl.load(V2_ptr + base, mask=mask, other=0.0).to(tl.float32)
338
+ v3 = tl.load(V3_ptr + base, mask=mask, other=0.0).to(tl.float32)
339
+ b0 = tl.load(B_ptr + row * 2).to(tl.float32)
340
+ b1 = tl.load(B_ptr + row * 2 + 1).to(tl.float32)
341
+ m = (b0 * v2 + b1 * v3).to(dt).to(tl.float32)
342
+
343
+ fg_base = row * (2 * D) + offs
344
+ f = tl.load(FG_ptr + fg_base, mask=mask, other=0.0).to(tl.float32)
345
+ g = tl.load(FG_ptr + fg_base + D, mask=mask, other=0.0).to(tl.float32)
346
+ fz = (2.0 * tl.sigmoid(2.0 * f) - 1.0).to(dt).to(tl.float32)
347
+ gz = (2.0 * tl.sigmoid(2.0 * g) - 1.0).to(dt).to(tl.float32)
348
+ mixed = ((1.0 - fz) * x + gz * m).to(dt).to(tl.float32)
349
+
350
+ var = tl.sum(mixed * mixed, axis=0) / D
351
+ inv = tl.math.rsqrt(var + eps)
352
+ w = tl.load(W_ptr + offs, mask=mask, other=0.0)
353
+ if GEMMA_NORM:
354
+ y = (mixed * inv * w.to(tl.float32)).to(dt).to(tl.float32)
355
+ else:
356
+ y = ((mixed * inv).to(dt) * w).to(tl.float32)
357
+ amax = tl.maximum(tl.max(tl.abs(y), axis=0), 1e-12)
358
+ s = amax / 448.0
359
+ q = tl.minimum(tl.maximum(tl.math.div_rn(y, s), -448.0), 448.0).to(tl.float8e4nv)
360
+ tl.store(QO_ptr + base, q, mask=mask)
361
+ tl.store(SO_ptr + row, s)
362
+
363
+ @triton_op("basal::varloop_rms_unit", mutates_args=())
364
+ def op_rms_unit(x: torch.Tensor, eps: float) -> torch.Tensor:
365
+ shape = x.shape
366
+ D = shape[-1]
367
+ x2 = x.reshape(-1, D).contiguous()
368
+ M = x2.shape[0]
369
+ y = torch.empty_like(x2)
370
+ if M:
371
+ bd = triton.next_power_of_2(D)
372
+ wrap_triton(_rms_unit_k)[(M,)](x2, x2, y, M, D, eps, HAS_ANCHOR=False, BLOCK_D=bd,
373
+ num_warps=4 if bd <= 2048 else 8)
374
+ return y.reshape(shape)
375
+
376
+ @triton_op("basal::varloop_delta_rms_unit", mutates_args=())
377
+ def op_delta_rms_unit(h: torch.Tensor, anchor: torch.Tensor, eps: float) -> torch.Tensor:
378
+ shape = h.shape
379
+ D = shape[-1]
380
+ h2 = h.reshape(-1, D).contiguous()
381
+ a2 = anchor.reshape(-1, D).contiguous()
382
+ M = h2.shape[0]
383
+ y = torch.empty_like(h2)
384
+ if M:
385
+ bd = triton.next_power_of_2(D)
386
+ wrap_triton(_rms_unit_k)[(M,)](h2, a2, y, M, D, eps, HAS_ANCHOR=True, BLOCK_D=bd,
387
+ num_warps=4 if bd <= 2048 else 8)
388
+ return y.reshape(shape)
389
+
390
+ @triton_op("basal::varloop_prep_qkv", mutates_args=())
391
+ def op_prep_qkv(x: torch.Tensor, v2: torch.Tensor, v3: torch.Tensor, beta_qkv: torch.Tensor,
392
+ eps: float) -> tuple[torch.Tensor, torch.Tensor]:
393
+ D = x.shape[-1]
394
+ x2 = x.reshape(-1, D).contiguous()
395
+ v2_2 = v2.reshape(-1, D).contiguous()
396
+ v3_2 = v3.reshape(-1, D).contiguous()
397
+ M = x2.shape[0]
398
+ b2 = beta_qkv.reshape(M, 3, 2).contiguous()
399
+ xh = torch.empty_like(x2)
400
+ mh = torch.empty((3, M, D), dtype=x2.dtype, device=x2.device)
401
+ if M:
402
+ bd = triton.next_power_of_2(D)
403
+ wrap_triton(_prep_qkv_k)[(M,)](x2, v2_2, v3_2, b2, xh, mh, M, D, eps,
404
+ BLOCK_D=bd, num_warps=4 if bd <= 2048 else 8)
405
+ return xh, mh
406
+
407
+ @triton_op("basal::varloop_mix_rmsnorm_qkv", mutates_args=())
408
+ def op_mix_rmsnorm_qkv(x: torch.Tensor, v2: torch.Tensor, v3: torch.Tensor, beta_qkv: torch.Tensor,
409
+ fg_qkv: torch.Tensor, ln_w: torch.Tensor, eps: float, gemma_norm: bool) -> torch.Tensor:
410
+ D = x.shape[-1]
411
+ x2 = x.reshape(-1, D).contiguous()
412
+ v2_2 = v2.reshape(-1, D).contiguous()
413
+ v3_2 = v3.reshape(-1, D).contiguous()
414
+ M = x2.shape[0]
415
+ b2 = beta_qkv.reshape(M, 3, 2).contiguous()
416
+ fg2 = fg_qkv.reshape(3, M, 2 * D).contiguous()
417
+ out = torch.empty((3, M, D), dtype=x2.dtype, device=x2.device)
418
+ if M:
419
+ bd = triton.next_power_of_2(D)
420
+ wrap_triton(_mix_rmsnorm_qkv_k)[(M, 3)](
421
+ x2, v2_2, v3_2, b2, fg2, ln_w.contiguous(), out, M, D, eps,
422
+ GEMMA_NORM=gemma_norm, BLOCK_D=bd, num_warps=4 if bd <= 2048 else 8)
423
+ return out
424
+
425
+ @triton_op("basal::varloop_prep_mlp", mutates_args=())
426
+ def op_prep_mlp(x: torch.Tensor, v2: torch.Tensor, v3: torch.Tensor, beta_m: torch.Tensor,
427
+ eps: float) -> torch.Tensor:
428
+ D = x.shape[-1]
429
+ x2 = x.reshape(-1, D).contiguous()
430
+ v2_2 = v2.reshape(-1, D).contiguous()
431
+ v3_2 = v3.reshape(-1, D).contiguous()
432
+ M = x2.shape[0]
433
+ b2 = beta_m.reshape(M, 2).contiguous()
434
+ xm = torch.empty((M, 2 * D), dtype=x2.dtype, device=x2.device)
435
+ if M:
436
+ bd = triton.next_power_of_2(D)
437
+ wrap_triton(_prep_mlp_k)[(M,)](x2, v2_2, v3_2, b2, xm, M, D, eps,
438
+ BLOCK_D=bd, num_warps=4 if bd <= 2048 else 8)
439
+ return xm
440
+
441
+ @triton_op("basal::varloop_mix_rmsnorm_mlp", mutates_args=())
442
+ def op_mix_rmsnorm_mlp(x: torch.Tensor, v2: torch.Tensor, v3: torch.Tensor, beta_m: torch.Tensor,
443
+ fg_m: torch.Tensor, ln_w: torch.Tensor, eps: float, gemma_norm: bool) -> torch.Tensor:
444
+ shape = x.shape
445
+ D = shape[-1]
446
+ x2 = x.reshape(-1, D).contiguous()
447
+ v2_2 = v2.reshape(-1, D).contiguous()
448
+ v3_2 = v3.reshape(-1, D).contiguous()
449
+ M = x2.shape[0]
450
+ b2 = beta_m.reshape(M, 2).contiguous()
451
+ fg2 = fg_m.reshape(M, 2 * D).contiguous()
452
+ y1 = torch.empty_like(x2)
453
+ if M:
454
+ bd = triton.next_power_of_2(D)
455
+ w = ln_w.contiguous()
456
+ wrap_triton(_mix_rmsnorm_mlp_k)[(M,)](
457
+ x2, v2_2, v3_2, b2, fg2, w, w, y1, y1, y1, M, D, eps,
458
+ GEMMA_NORM=gemma_norm, WRITE_RAW=False, HAS_W2=False,
459
+ BLOCK_D=bd, num_warps=4 if bd <= 2048 else 8)
460
+ return y1.reshape(shape)
461
+
462
+ @triton_op("basal::varloop_mix_gemma_ff", mutates_args=())
463
+ def op_mix_gemma_ff(x: torch.Tensor, v2: torch.Tensor, v3: torch.Tensor, beta_m: torch.Tensor,
464
+ fg_m: torch.Tensor, ln1_w: torch.Tensor, ln2_w: torch.Tensor,
465
+ eps: float) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
466
+ shape = x.shape
467
+ D = shape[-1]
468
+ x2 = x.reshape(-1, D).contiguous()
469
+ v2_2 = v2.reshape(-1, D).contiguous()
470
+ v3_2 = v3.reshape(-1, D).contiguous()
471
+ M = x2.shape[0]
472
+ b2 = beta_m.reshape(M, 2).contiguous()
473
+ fg2 = fg_m.reshape(M, 2 * D).contiguous()
474
+ raw = torch.empty_like(x2)
475
+ y1 = torch.empty_like(x2)
476
+ y2 = torch.empty_like(x2)
477
+ if M:
478
+ bd = triton.next_power_of_2(D)
479
+ wrap_triton(_mix_rmsnorm_mlp_k)[(M,)](
480
+ x2, v2_2, v3_2, b2, fg2, ln1_w.contiguous(), ln2_w.contiguous(), raw, y1, y2, M, D, eps,
481
+ GEMMA_NORM=True, WRITE_RAW=True, HAS_W2=True,
482
+ BLOCK_D=bd, num_warps=4 if bd <= 2048 else 8)
483
+ return raw.reshape(shape), y1.reshape(shape), y2.reshape(shape)
484
+
485
+ @triton_op("basal::gemma_gelu_mul", mutates_args=())
486
+ def op_gemma_gelu_mul(gu: torch.Tensor) -> torch.Tensor:
487
+ shape = gu.shape
488
+ I = shape[-1] // 2
489
+ g2 = gu.reshape(-1, 2 * I).contiguous()
490
+ M = g2.shape[0]
491
+ y = torch.empty((M, I), dtype=gu.dtype, device=gu.device)
492
+ if M:
493
+ blk = 256
494
+ wrap_triton(_gemma_gelu_mul_k)[(M, triton.cdiv(I, blk))](g2, y, M, I, BLOCK=blk, num_warps=4)
495
+ return y.reshape(*shape[:-1], I)
496
+
497
+ @triton_op("basal::varloop_quant_rowfp8", mutates_args=())
498
+ def op_quant_rowfp8(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
499
+ D = x.shape[-1]
500
+ x2 = x.reshape(-1, D).contiguous()
501
+ M = x2.shape[0]
502
+ Mp = ((M + 15) // 16) * 16
503
+ qo = torch.empty((Mp, D), dtype=torch.float8_e4m3fn, device=x.device)
504
+ so = torch.empty((Mp, 1), dtype=torch.float32, device=x.device)
505
+ if Mp:
506
+ bd = triton.next_power_of_2(D)
507
+ wrap_triton(_quant_rowfp8_k)[(Mp,)](x2, qo, so, M, D, BLOCK_D=bd, num_warps=4 if bd <= 2048 else 8)
508
+ return qo, so
509
+
510
+ @triton_op("basal::varloop_rms_rowfp8", mutates_args=())
511
+ def op_rms_rowfp8(h: torch.Tensor, w: torch.Tensor, eps: float) -> tuple[torch.Tensor, torch.Tensor]:
512
+ D = h.shape[-1]
513
+ h2 = h.reshape(-1, D).contiguous()
514
+ M = h2.shape[0]
515
+ Mp = ((M + 15) // 16) * 16
516
+ qo = torch.empty((Mp, D), dtype=torch.float8_e4m3fn, device=h.device)
517
+ so = torch.empty((Mp, 1), dtype=torch.float32, device=h.device)
518
+ if Mp:
519
+ bd = triton.next_power_of_2(D)
520
+ wrap_triton(_add_rms_rowfp8_k)[(Mp,)](
521
+ h2, h2, w.contiguous(), h2, qo, so, M, D, eps, HAS_RES=False, BLOCK_D=bd,
522
+ num_warps=4 if bd <= 2048 else 8)
523
+ return qo, so
524
+
525
+ @triton_op("basal::varloop_add_rms_rowfp8", mutates_args=())
526
+ def op_add_rms_rowfp8(h: torch.Tensor, res: torch.Tensor, w: torch.Tensor,
527
+ eps: float) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
528
+ shape = h.shape
529
+ D = shape[-1]
530
+ h2 = h.reshape(-1, D).contiguous()
531
+ r2 = res.reshape(-1, D).contiguous()
532
+ M = h2.shape[0]
533
+ Mp = ((M + 15) // 16) * 16
534
+ ho = torch.empty_like(h2)
535
+ qo = torch.empty((Mp, D), dtype=torch.float8_e4m3fn, device=h.device)
536
+ so = torch.empty((Mp, 1), dtype=torch.float32, device=h.device)
537
+ if Mp:
538
+ bd = triton.next_power_of_2(D)
539
+ wrap_triton(_add_rms_rowfp8_k)[(Mp,)](
540
+ h2, r2, w.contiguous(), ho, qo, so, M, D, eps, HAS_RES=True, BLOCK_D=bd,
541
+ num_warps=4 if bd <= 2048 else 8)
542
+ return ho.reshape(shape), qo, so
543
+
544
+ @triton_op("basal::varloop_swiglu_rowfp8", mutates_args=())
545
+ def op_swiglu_rowfp8(gu: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
546
+ I = gu.shape[-1] // 2
547
+ g2 = gu.reshape(-1, 2 * I).contiguous()
548
+ M = g2.shape[0]
549
+ Mp = ((M + 15) // 16) * 16
550
+ qo = torch.empty((Mp, I), dtype=torch.float8_e4m3fn, device=gu.device)
551
+ so = torch.empty((Mp, 1), dtype=torch.float32, device=gu.device)
552
+ if Mp:
553
+ wrap_triton(_swiglu_rowfp8_k)[(Mp,)](g2, qo, so, M, I, BLOCK=1024, num_warps=8)
554
+ return qo, so
555
+
556
+ @triton_op("basal::varloop_mix_rmsnorm_qkv_rowfp8", mutates_args=())
557
+ def op_mix_rmsnorm_qkv_rowfp8(x: torch.Tensor, v2: torch.Tensor, v3: torch.Tensor, beta_qkv: torch.Tensor,
558
+ fg_qkv: torch.Tensor, ln_w: torch.Tensor, eps: float,
559
+ gemma_norm: bool) -> tuple[torch.Tensor, torch.Tensor]:
560
+ D = x.shape[-1]
561
+ x2 = x.reshape(-1, D).contiguous()
562
+ v2_2 = v2.reshape(-1, D).contiguous()
563
+ v3_2 = v3.reshape(-1, D).contiguous()
564
+ M = x2.shape[0]
565
+ Mp = ((M + 15) // 16) * 16
566
+ b2 = beta_qkv.reshape(M, 3, 2).contiguous()
567
+ fg2 = fg_qkv.reshape(3, M, 2 * D).contiguous()
568
+ qo = torch.empty((3, Mp, D), dtype=torch.float8_e4m3fn, device=x.device)
569
+ so = torch.empty((3, Mp, 1), dtype=torch.float32, device=x.device)
570
+ if Mp:
571
+ bd = triton.next_power_of_2(D)
572
+ wrap_triton(_mix_rmsnorm_qkv_rowfp8_k)[(Mp, 3)](
573
+ x2, v2_2, v3_2, b2, fg2, ln_w.contiguous(), qo, so, M, Mp, D, eps,
574
+ GEMMA_NORM=gemma_norm, BLOCK_D=bd, num_warps=4 if bd <= 2048 else 8)
575
+ return qo, so
576
+
577
+ @triton_op("basal::varloop_mix_rmsnorm_mlp_rowfp8", mutates_args=())
578
+ def op_mix_rmsnorm_mlp_rowfp8(x: torch.Tensor, v2: torch.Tensor, v3: torch.Tensor, beta_m: torch.Tensor,
579
+ fg_m: torch.Tensor, ln_w: torch.Tensor, eps: float,
580
+ gemma_norm: bool) -> tuple[torch.Tensor, torch.Tensor]:
581
+ D = x.shape[-1]
582
+ x2 = x.reshape(-1, D).contiguous()
583
+ v2_2 = v2.reshape(-1, D).contiguous()
584
+ v3_2 = v3.reshape(-1, D).contiguous()
585
+ M = x2.shape[0]
586
+ Mp = ((M + 15) // 16) * 16
587
+ b2 = beta_m.reshape(M, 2).contiguous()
588
+ fg2 = fg_m.reshape(M, 2 * D).contiguous()
589
+ qo = torch.empty((Mp, D), dtype=torch.float8_e4m3fn, device=x.device)
590
+ so = torch.empty((Mp, 1), dtype=torch.float32, device=x.device)
591
+ if Mp:
592
+ bd = triton.next_power_of_2(D)
593
+ wrap_triton(_mix_rmsnorm_mlp_rowfp8_k)[(Mp,)](
594
+ x2, v2_2, v3_2, b2, fg2, ln_w.contiguous(), qo, so, M, D, eps,
595
+ GEMMA_NORM=gemma_norm, BLOCK_D=bd, num_warps=4 if bd <= 2048 else 8)
596
+ return qo, so
597
+
598
+ return (op_rms_unit, op_delta_rms_unit, op_prep_qkv, op_mix_rmsnorm_qkv,
599
+ op_prep_mlp, op_mix_rmsnorm_mlp, op_mix_gemma_ff, op_gemma_gelu_mul,
600
+ op_quant_rowfp8, op_rms_rowfp8, op_add_rms_rowfp8, op_swiglu_rowfp8,
601
+ op_mix_rmsnorm_qkv_rowfp8, op_mix_rmsnorm_mlp_rowfp8)
602
+
603
+
604
+ def prepare():
605
+ if torch.cuda.is_available() and not _OPS:
606
+ _OPS.extend(_build())
607
+
608
+
609
+ def varloop_rms_unit(x, eps=1e-6):
610
+ if x.is_cuda:
611
+ prepare()
612
+ return torch.ops.basal.varloop_rms_unit(x, float(eps))
613
+ return _rms_unit_ref(x, eps)
614
+
615
+
616
+ def varloop_delta_rms_unit(h, anchor, eps=1e-6):
617
+ if h.is_cuda:
618
+ prepare()
619
+ return torch.ops.basal.varloop_delta_rms_unit(h, anchor, float(eps))
620
+ return _rms_unit_ref(h - anchor, eps)
621
+
622
+
623
+ def varloop_prep_qkv(x, v2_hat, v3_hat, beta_qkv, eps=1e-6):
624
+ """Returns (x_hat [M, D], m_hat_qkv [3, M, D])."""
625
+ if x.is_cuda:
626
+ prepare()
627
+ return torch.ops.basal.varloop_prep_qkv(x, v2_hat, v3_hat, beta_qkv, float(eps))
628
+ D = x.shape[-1]
629
+ x2 = x.reshape(-1, D)
630
+ v2 = v2_hat.reshape(-1, D)
631
+ v3 = v3_hat.reshape(-1, D)
632
+ b = beta_qkv.reshape(-1, 3, 2)
633
+ xh = _rms_unit_ref(x2, eps)
634
+ mhs = []
635
+ for c in range(3):
636
+ mc = b[:, c, 0:1] * v2 + b[:, c, 1:2] * v3
637
+ mhs.append(_rms_unit_ref(mc, eps))
638
+ return xh, torch.stack(mhs, dim=0)
639
+
640
+
641
+ def varloop_mix_rmsnorm_qkv(x, v2_hat, v3_hat, beta_qkv, fg_qkv, ln_w, eps=1e-6, gemma_norm=False):
642
+ """Returns stacked [3, M, D] = (h_q, h_k, h_v) after cross-loop gate + input_layernorm."""
643
+ if x.is_cuda:
644
+ prepare()
645
+ return torch.ops.basal.varloop_mix_rmsnorm_qkv(x, v2_hat, v3_hat, beta_qkv, fg_qkv, ln_w, float(eps),
646
+ bool(gemma_norm))
647
+ D = x.shape[-1]
648
+ x2 = x.reshape(-1, D)
649
+ v2 = v2_hat.reshape(-1, D)
650
+ v3 = v3_hat.reshape(-1, D)
651
+ b = beta_qkv.reshape(-1, 3, 2)
652
+ fg = fg_qkv.reshape(3, -1, 2 * D)
653
+ outs = []
654
+ for c in range(3):
655
+ mc = b[:, c, 0:1] * v2 + b[:, c, 1:2] * v3
656
+ fz = torch.tanh(fg[c, :, :D]).to(x.dtype)
657
+ gz = torch.tanh(fg[c, :, D:]).to(x.dtype)
658
+ mixed = (1.0 - fz) * x2 + gz * mc
659
+ outs.append(_rmsnorm_ref(mixed, ln_w, eps, gemma_norm=gemma_norm))
660
+ return torch.stack(outs, dim=0)
661
+
662
+
663
+ def varloop_prep_mlp(x, v2_hat, v3_hat, beta_m, eps=1e-6):
664
+ """Returns cat([x_hat, m_hat], -1) [M, 2*D]."""
665
+ if x.is_cuda:
666
+ prepare()
667
+ return torch.ops.basal.varloop_prep_mlp(x, v2_hat, v3_hat, beta_m, float(eps))
668
+ D = x.shape[-1]
669
+ x2 = x.reshape(-1, D)
670
+ v2 = v2_hat.reshape(-1, D)
671
+ v3 = v3_hat.reshape(-1, D)
672
+ b = beta_m.reshape(-1, 2)
673
+ m = b[:, 0:1] * v2 + b[:, 1:2] * v3
674
+ return torch.cat([_rms_unit_ref(x2, eps), _rms_unit_ref(m, eps)], dim=-1)
675
+
676
+
677
+ def varloop_mix_rmsnorm_mlp(x, v2_hat, v3_hat, beta_m, fg_m, ln_w, eps=1e-6, gemma_norm=False):
678
+ if x.is_cuda:
679
+ prepare()
680
+ return torch.ops.basal.varloop_mix_rmsnorm_mlp(x, v2_hat, v3_hat, beta_m, fg_m, ln_w, float(eps),
681
+ bool(gemma_norm))
682
+ shape, D = x.shape, x.shape[-1]
683
+ x2 = x.reshape(-1, D)
684
+ v2 = v2_hat.reshape(-1, D)
685
+ v3 = v3_hat.reshape(-1, D)
686
+ b = beta_m.reshape(-1, 2)
687
+ fg = fg_m.reshape(-1, 2 * D)
688
+ m = b[:, 0:1] * v2 + b[:, 1:2] * v3
689
+ fz = torch.tanh(fg[:, :D]).to(x.dtype)
690
+ gz = torch.tanh(fg[:, D:]).to(x.dtype)
691
+ mixed = (1.0 - fz) * x2 + gz * m
692
+ return _rmsnorm_ref(mixed, ln_w, eps, gemma_norm=gemma_norm).reshape(shape)
693
+
694
+
695
+ def varloop_mix_gemma_ff(x, v2_hat, v3_hat, beta_m, fg_m, ln1_w, ln2_w, eps=1e-6):
696
+ """Gemma 4 MoE MLP gate -> (x_ff, pre_ff_ln1(x_ff), pre_ff_ln2(x_ff)) in one fused pass."""
697
+ if x.is_cuda:
698
+ prepare()
699
+ return torch.ops.basal.varloop_mix_gemma_ff(x, v2_hat, v3_hat, beta_m, fg_m, ln1_w, ln2_w, float(eps))
700
+ shape, D = x.shape, x.shape[-1]
701
+ x2 = x.reshape(-1, D)
702
+ v2 = v2_hat.reshape(-1, D)
703
+ v3 = v3_hat.reshape(-1, D)
704
+ b = beta_m.reshape(-1, 2)
705
+ fg = fg_m.reshape(-1, 2 * D)
706
+ m = b[:, 0:1] * v2 + b[:, 1:2] * v3
707
+ fz = torch.tanh(fg[:, :D]).to(x.dtype)
708
+ gz = torch.tanh(fg[:, D:]).to(x.dtype)
709
+ raw = ((1.0 - fz) * x2 + gz * m).reshape(shape)
710
+ return raw, _rmsnorm_ref(raw, ln1_w, eps, gemma_norm=True), _rmsnorm_ref(raw, ln2_w, eps, gemma_norm=True)
711
+
712
+
713
+ def gemma_gelu_mul(gu):
714
+ if gu.is_cuda:
715
+ prepare()
716
+ return torch.ops.basal.gemma_gelu_mul(gu)
717
+ g, u = gu.chunk(2, dim=-1)
718
+ return F.gelu(g, approximate="tanh") * u
719
+
720
+
721
+ # ---------------------------------------------------------------------------
722
+ # Fast cuBLAS Rowwise-FP8 (per-row activation scale x per-channel weight scale)
723
+ # ~1.85x faster than BF16 on Blackwell/Hopper with zero external dependencies!
724
+ # ---------------------------------------------------------------------------
725
+ class RowFP8Linear(torch.nn.Module):
726
+ """Per-channel weight FP8 E4M3 linear with cuBLAS torch._scaled_mm rowwise activation scaling.
727
+ Supports zero-copy `.part(offset, size)` views so Pass 1 uses merged qkv while Pass t>=2 uses q/k/v slices."""
728
+
729
+ def __init__(self, weight_q: torch.Tensor, weight_scale: torch.Tensor, bias: torch.Tensor | None = None):
730
+ super().__init__()
731
+ # weight_q: [N, K] float8_e4m3fn row-major -> weight_q.t() is [K, N] col-major (native _scaled_mm layout!)
732
+ # weight_scale: [1, N] float32 contiguous
733
+ self.register_buffer("weight", weight_q)
734
+ self.register_buffer("weight_scale", weight_scale)
735
+ if bias is not None:
736
+ self.register_buffer("bias", bias)
737
+ else:
738
+ self.bias = None
739
+ self.out_features, self.in_features = int(weight_q.shape[0]), int(weight_q.shape[1])
740
+
741
+ @classmethod
742
+ def fits(cls, mod: torch.nn.Module) -> bool:
743
+ return (isinstance(mod, torch.nn.Linear)
744
+ and mod.in_features % 16 == 0 and mod.out_features % 16 == 0)
745
+
746
+ @classmethod
747
+ @torch.no_grad()
748
+ def of(cls, mod: torch.nn.Linear) -> "RowFP8Linear":
749
+ w = mod.weight.detach()
750
+ ws = (w.float().abs().amax(dim=1, keepdim=True).clamp(min=1e-12) / 448.0) # [N, 1]
751
+ wq = (w.float() / ws).clamp(-448.0, 448.0).to(torch.float8_e4m3fn).contiguous()
752
+ ws_col = ws.t().contiguous() # [1, N]
753
+ b = None if mod.bias is None else mod.bias.detach().clone()
754
+ return cls(wq, ws_col, b)
755
+
756
+ def part(self, offset: int, size: int) -> "RowFP8Linear":
757
+ """Zero-copy output-channel slice view preserving col-major _scaled_mm layout."""
758
+ b = None if self.bias is None else self.bias[offset: offset + size]
759
+ return RowFP8Linear(self.weight[offset: offset + size], self.weight_scale[:, offset: offset + size].contiguous(), b)
760
+
761
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
762
+ q, s = quant_rowfp8(x)
763
+ return rowfp8_mm(q, s, self.weight, self.weight_scale, self.bias, x.dtype, x.numel() // self.in_features,
764
+ (*x.shape[:-1], self.out_features))
765
+
766
+
767
+ def quant_rowfp8(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
768
+ if x.is_cuda:
769
+ prepare()
770
+ return torch.ops.basal.varloop_quant_rowfp8(x)
771
+ D = x.shape[-1]
772
+ x2 = x.reshape(-1, D).float()
773
+ M = x2.shape[0]
774
+ Mp = ((M + 15) // 16) * 16
775
+ if Mp > M:
776
+ x2 = F.pad(x2, (0, 0, 0, Mp - M))
777
+ s = x2.abs().amax(dim=1, keepdim=True).clamp(min=1e-12) / 448.0
778
+ q = (x2 / s).clamp(-448.0, 448.0).to(torch.float8_e4m3fn)
779
+ return q, s
780
+
781
+
782
+ def add_rmsnorm_rowfp8(h: torch.Tensor, res: torch.Tensor | None, w: torch.Tensor, eps: float):
783
+ """Fused residual add + RMSNorm + per-row FP8 quant -> (h_out, q [Mp, D], s [Mp, 1])."""
784
+ if h.is_cuda:
785
+ prepare()
786
+ if res is None:
787
+ q, s = torch.ops.basal.varloop_rms_rowfp8(h, w, float(eps))
788
+ return h, q, s
789
+ return torch.ops.basal.varloop_add_rms_rowfp8(h, res, w, float(eps))
790
+ ho = h if res is None else (h + res)
791
+ y = _rmsnorm_ref(ho, w, eps, gemma_norm=False)
792
+ q, s = quant_rowfp8(y)
793
+ return ho, q, s
794
+
795
+
796
+ def swiglu_rowfp8(gu: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
797
+ if gu.is_cuda:
798
+ prepare()
799
+ return torch.ops.basal.varloop_swiglu_rowfp8(gu)
800
+ g, u = gu.chunk(2, dim=-1)
801
+ y = F.silu(g) * u
802
+ return quant_rowfp8(y)
803
+
804
+
805
+ def varloop_mix_rmsnorm_qkv_rowfp8(x, v2_hat, v3_hat, beta_qkv, fg_qkv, ln_w, eps=1e-6, gemma_norm=False):
806
+ if x.is_cuda:
807
+ prepare()
808
+ return torch.ops.basal.varloop_mix_rmsnorm_qkv_rowfp8(
809
+ x, v2_hat, v3_hat, beta_qkv, fg_qkv, ln_w, float(eps), bool(gemma_norm))
810
+ h_qkv = varloop_mix_rmsnorm_qkv(x, v2_hat, v3_hat, beta_qkv, fg_qkv, ln_w, eps, gemma_norm=gemma_norm)
811
+ qs, ss = [], []
812
+ for c in range(3):
813
+ qc, sc = quant_rowfp8(h_qkv[c])
814
+ qs.append(qc)
815
+ ss.append(sc)
816
+ return torch.stack(qs, dim=0), torch.stack(ss, dim=0)
817
+
818
+
819
+ def varloop_mix_rmsnorm_mlp_rowfp8(x, v2_hat, v3_hat, beta_m, fg_m, ln_w, eps=1e-6, gemma_norm=False):
820
+ if x.is_cuda:
821
+ prepare()
822
+ return torch.ops.basal.varloop_mix_rmsnorm_mlp_rowfp8(
823
+ x, v2_hat, v3_hat, beta_m, fg_m, ln_w, float(eps), bool(gemma_norm))
824
+ y = varloop_mix_rmsnorm_mlp(x, v2_hat, v3_hat, beta_m, fg_m, ln_w, eps, gemma_norm=gemma_norm)
825
+ return quant_rowfp8(y)
826
+
827
+
828
+ def rowfp8_mm(q: torch.Tensor, s: torch.Tensor, w_q: torch.Tensor, w_s: torch.Tensor,
829
+ bias: torch.Tensor | None, out_dtype: torch.dtype, m_orig: int, out_shape) -> torch.Tensor:
830
+ """Fast cuBLAS FP8 GEMM: q [Mp, K] e4m3, s [Mp, 1] fp32, w_q [N, K] e4m3, w_s [1, N] fp32 -> out_shape."""
831
+ if q.is_cuda:
832
+ y = torch._scaled_mm(
833
+ q, w_q.t(), scale_a=s, scale_b=w_s,
834
+ bias=None if bias is None else bias.to(out_dtype),
835
+ out_dtype=out_dtype, use_fast_accum=True)[:m_orig]
836
+ return y.reshape(out_shape)
837
+ y = (q[:m_orig].float() * s[:m_orig]) @ (w_q.float() * w_s.t()).t()
838
+ if bias is not None:
839
+ y = y + bias.float()
840
+ return y.to(out_dtype).reshape(out_shape)
841
+
842
+
843
+ def _can_grouped_mm(x, gate_up_proj):
844
+ return (x.is_cuda
845
+ and hasattr(torch, "_grouped_mm")
846
+ and x.dtype in (torch.bfloat16, torch.float16)
847
+ and gate_up_proj.dtype == x.dtype
848
+ and x.shape[-1] % 8 == 0
849
+ and gate_up_proj.shape[1] % 16 == 0
850
+ and torch.cuda.get_device_capability(x.device) >= (9, 0))
851
+
852
+
853
+ def grouped_moe_forward(x, top_k_index, top_k_weights, gate_up_proj, down_proj):
854
+ """Zero-sync grouped GEMM forward for Gemma 4 128-expert MoE (replaces transformers' 128-iter Python loop!).
855
+
856
+ Args:
857
+ x: [M, D] normalized hidden states (output of pre_feedforward_layernorm_2)
858
+ top_k_index: [M, K] selected expert indices in 0..E-1
859
+ top_k_weights: [M, K] per-expert routing weights (already normalized & scaled by per_expert_scale)
860
+ gate_up_proj: [E, 2*I, D] stacked expert gate+up weights
861
+ down_proj: [E, D, I] stacked expert down weights
862
+ Returns:
863
+ out: [M, D] in x.dtype (exact match to Gemma4TextExperts.forward up to bf16 rounding)
864
+ """
865
+ M, D = x.shape
866
+ E = gate_up_proj.shape[0]
867
+ if M == 0:
868
+ return torch.zeros_like(x)
869
+ if _can_grouped_mm(x, gate_up_proj):
870
+ K = top_k_index.shape[1]
871
+ flat_e = top_k_index.reshape(-1)
872
+ flat_w = top_k_weights.reshape(-1)
873
+ # Sort token-expert pairs by expert id (zero CPU sync!)
874
+ order = torch.argsort(flat_e, stable=True)
875
+ sorted_e = flat_e.index_select(0, order)
876
+ tok_idx = torch.div(order, K, rounding_mode="floor")
877
+ sorted_x = x.index_select(0, tok_idx)
878
+ sorted_w = flat_w.index_select(0, order).to(x.dtype)
879
+ # Cumulative token counts per expert: [E] int32 strictly on GPU (zero CPU sync, CUDA-graph capturable!)
880
+ counts = torch.zeros(E, dtype=torch.int32, device=x.device)
881
+ counts.scatter_add_(0, sorted_e, torch.ones(sorted_e.shape, dtype=torch.int32, device=x.device))
882
+ offs = counts.cumsum(0, dtype=torch.int32)
883
+ gu = torch._grouped_mm(sorted_x, gate_up_proj.transpose(1, 2), offs=offs)
884
+ mid = gemma_gelu_mul(gu)
885
+ y = torch._grouped_mm(mid, down_proj.transpose(1, 2), offs=offs)
886
+ y = (y * sorted_w[:, None]).to(x.dtype)
887
+ out = torch.zeros_like(x)
888
+ out.index_add_(0, tok_idx, y)
889
+ return out
890
+
891
+ # Exact fallback (CPU / fp32 / pre-Hopper CUDA)
892
+ out = torch.zeros_like(x)
893
+ K = top_k_index.shape[1]
894
+ flat_e = top_k_index.reshape(-1)
895
+ flat_w = top_k_weights.reshape(-1)
896
+ tok_ids = torch.arange(M, device=x.device).repeat_interleave(K)
897
+ for e in torch.unique(flat_e):
898
+ ei = int(e.item())
899
+ sel = flat_e == e
900
+ t_idx = tok_ids[sel]
901
+ w_sel = flat_w[sel]
902
+ gu = F.linear(x.index_select(0, t_idx), gate_up_proj[ei])
903
+ g, u = gu.chunk(2, dim=-1)
904
+ mid = F.gelu(g, approximate="tanh") * u
905
+ ye = F.linear(mid, down_proj[ei]) * w_sel[:, None]
906
+ out.index_add_(0, t_idx, ye.to(out.dtype))
907
+ return out