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/llama_kernels.py ADDED
@@ -0,0 +1,593 @@
1
+ """Pure-Triton fused layer kernels for Llama / Bielik 3.0 (basal/llama_graph.py):
2
+ - add_rmsnorm(h, res, w, eps) fused residual add + RMSNorm (exact LlamaRMSNorm fp32 variance)
3
+ - add_rmsnorm_fp8(h, res, w, eps, xs) fused residual add + RMSNorm + static per-tensor FP8 quant
4
+ - add_rmsnorm_fp8_block(h, res, w, eps) fused residual add + RMSNorm + 1x128 block FP8 quant
5
+ - qkv_rope(qkv, cos, sin, H, Hkv, D) fused split-QKV + in-place fp32 RoPE in native NHD layout
6
+ - kv_rope(kv, cos, sin, Hkv, D) fused split-KV + RoPE for last-layer readout slicing / Pass-1 early stop
7
+ - q_rope(q, cos, sin, H, D) fused Q-only RoPE on readout rows
8
+ - swiglu(gu) fused SiLU(gate) * up from merged gate_up output
9
+ - swiglu_fp8(gu, xs) fused SiLU(gate) * up + static per-tensor FP8 quant
10
+ - swiglu_fp8_block(gu) fused SiLU(gate) * up + 1x128 block FP8 quant
11
+ - LosslessMergedFP8Linear merged ModelOpt FP8 weights with per-column weight_scale (zero re-quant!)
12
+
13
+ Every op is registered via torch.library.triton_op on CUDA (zero torch.compile graph breaks, CUDA-graph capturable,
14
+ deterministic fixed tiles) and has an exact PyTorch fallback on CPU / non-CUDA devices.
15
+ """
16
+ import torch
17
+ import torch.nn.functional as F
18
+
19
+ E4M3 = torch.float8_e4m3fn
20
+ FP8_MAX = 448.0
21
+ _OPS = []
22
+
23
+
24
+ def _rms_ref(x, w, eps):
25
+ xf = x.float()
26
+ return w * (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps)).to(x.dtype)
27
+
28
+
29
+ def _rot_ref(x, cos, sin):
30
+ """x [..., H, D], cos / sin [..., 1, D] -> rotated x in x.dtype."""
31
+ half = x.shape[-1] // 2
32
+ x1, x2 = x[..., :half], x[..., half:]
33
+ c1, c2 = cos[..., :half], cos[..., half:]
34
+ s1, s2 = sin[..., :half], sin[..., half:]
35
+ return torch.cat((x1 * c1 - x2 * s1, x2 * c2 + x1 * s2), -1)
36
+
37
+
38
+ def _build():
39
+ import triton
40
+ import triton.language as tl
41
+ from torch.library import triton_op, wrap_triton
42
+
43
+ @triton.jit
44
+ def _add_rms_k(H_ptr, R_ptr, W_ptr, HO_ptr, XO_ptr, M, D, eps,
45
+ HAS_RES: tl.constexpr, BLOCK_D: tl.constexpr):
46
+ row = tl.program_id(0).to(tl.int64)
47
+ offs = tl.arange(0, BLOCK_D)
48
+ mask = offs < D
49
+ h = tl.load(H_ptr + row * D + offs, mask=mask, other=0.0)
50
+ if HAS_RES:
51
+ r = tl.load(R_ptr + row * D + offs, mask=mask, other=0.0)
52
+ h = (h.to(tl.float32) + r.to(tl.float32)).to(HO_ptr.dtype.element_ty)
53
+ tl.store(HO_ptr + row * D + offs, h, mask=mask)
54
+ hf = h.to(tl.float32)
55
+ var = tl.sum(hf * hf, axis=0) / D
56
+ inv = tl.math.rsqrt(var + eps)
57
+ w = tl.load(W_ptr + offs, mask=mask, other=0.0)
58
+ y = (hf * inv).to(XO_ptr.dtype.element_ty) * w
59
+ tl.store(XO_ptr + row * D + offs, y, mask=mask)
60
+
61
+ @triton.jit
62
+ def _add_rms_fp8_k(H_ptr, R_ptr, W_ptr, HO_ptr, QO_ptr, XS_ptr, M, D, eps,
63
+ HAS_RES: tl.constexpr, BLOCK_D: tl.constexpr):
64
+ row = tl.program_id(0).to(tl.int64)
65
+ offs = tl.arange(0, BLOCK_D)
66
+ mask = offs < D
67
+ h = tl.load(H_ptr + row * D + offs, mask=mask, other=0.0)
68
+ if HAS_RES:
69
+ r = tl.load(R_ptr + row * D + offs, mask=mask, other=0.0)
70
+ h = (h.to(tl.float32) + r.to(tl.float32)).to(HO_ptr.dtype.element_ty)
71
+ tl.store(HO_ptr + row * D + offs, h, mask=mask)
72
+ hf = h.to(tl.float32)
73
+ var = tl.sum(hf * hf, axis=0) / D
74
+ inv = tl.math.rsqrt(var + eps)
75
+ w = tl.load(W_ptr + offs, mask=mask, other=0.0)
76
+ y = ((hf * inv).to(H_ptr.dtype.element_ty) * w).to(tl.float32)
77
+ xs = tl.load(XS_ptr).to(tl.float32)
78
+ q = tl.minimum(tl.maximum(tl.math.div_rn(y, xs), -448.0), 448.0).to(tl.float8e4nv)
79
+ tl.store(QO_ptr + row * D + offs, q, mask=mask)
80
+
81
+ @triton.jit
82
+ def _qkv_rope_k(QKV_ptr, COS_ptr, SIN_ptr, Q_ptr, K_ptr, V_ptr,
83
+ M, H: tl.constexpr, HKV: tl.constexpr, D: tl.constexpr, HALF: tl.constexpr,
84
+ HAS_Q: tl.constexpr):
85
+ """One program per (token row, head_index in [0, H + 2*HKV) or [0, 2*HKV))."""
86
+ row = tl.program_id(0).to(tl.int64)
87
+ hi = tl.program_id(1)
88
+ offs = tl.arange(0, HALF)
89
+ tot_h = (H + 2 * HKV) if HAS_Q else (2 * HKV)
90
+ base = row * tot_h * D + hi.to(tl.int64) * D
91
+ if HAS_Q and hi < H:
92
+ c = tl.load(COS_ptr + row * D + offs).to(tl.float32)
93
+ s = tl.load(SIN_ptr + row * D + offs).to(tl.float32)
94
+ x1 = tl.load(QKV_ptr + base + offs).to(tl.float32)
95
+ x2 = tl.load(QKV_ptr + base + HALF + offs).to(tl.float32)
96
+ y1 = (x1 * c - x2 * s).to(Q_ptr.dtype.element_ty)
97
+ y2 = (x2 * c + x1 * s).to(Q_ptr.dtype.element_ty)
98
+ qbase = row * H * D + hi.to(tl.int64) * D
99
+ tl.store(Q_ptr + qbase + offs, y1)
100
+ tl.store(Q_ptr + qbase + HALF + offs, y2)
101
+ else:
102
+ kh = (hi - H) if HAS_Q else hi
103
+ if kh < HKV:
104
+ c = tl.load(COS_ptr + row * D + offs).to(tl.float32)
105
+ s = tl.load(SIN_ptr + row * D + offs).to(tl.float32)
106
+ x1 = tl.load(QKV_ptr + base + offs).to(tl.float32)
107
+ x2 = tl.load(QKV_ptr + base + HALF + offs).to(tl.float32)
108
+ y1 = (x1 * c - x2 * s).to(K_ptr.dtype.element_ty)
109
+ y2 = (x2 * c + x1 * s).to(K_ptr.dtype.element_ty)
110
+ kbase = row * HKV * D + kh.to(tl.int64) * D
111
+ tl.store(K_ptr + kbase + offs, y1)
112
+ tl.store(K_ptr + kbase + HALF + offs, y2)
113
+ else:
114
+ vh = kh - HKV
115
+ v1 = tl.load(QKV_ptr + base + offs)
116
+ v2 = tl.load(QKV_ptr + base + HALF + offs)
117
+ vbase = row * HKV * D + vh.to(tl.int64) * D
118
+ tl.store(V_ptr + vbase + offs, v1)
119
+ tl.store(V_ptr + vbase + HALF + offs, v2)
120
+
121
+ @triton.jit
122
+ def _q_rope_k(Q_ptr, COS_ptr, SIN_ptr, QO_ptr, M, H: tl.constexpr, D: tl.constexpr, HALF: tl.constexpr):
123
+ row = tl.program_id(0).to(tl.int64)
124
+ hi = tl.program_id(1)
125
+ offs = tl.arange(0, HALF)
126
+ base = row * H * D + hi.to(tl.int64) * D
127
+ c = tl.load(COS_ptr + row * D + offs).to(tl.float32)
128
+ s = tl.load(SIN_ptr + row * D + offs).to(tl.float32)
129
+ x1 = tl.load(Q_ptr + base + offs).to(tl.float32)
130
+ x2 = tl.load(Q_ptr + base + HALF + offs).to(tl.float32)
131
+ tl.store(QO_ptr + base + offs, (x1 * c - x2 * s).to(QO_ptr.dtype.element_ty))
132
+ tl.store(QO_ptr + base + HALF + offs, (x2 * c + x1 * s).to(QO_ptr.dtype.element_ty))
133
+
134
+ @triton.jit
135
+ def _swiglu_k(GU_ptr, Y_ptr, M, I, BLOCK: tl.constexpr):
136
+ row = tl.program_id(0).to(tl.int64)
137
+ blk = tl.program_id(1)
138
+ offs = blk * BLOCK + tl.arange(0, BLOCK)
139
+ mask = offs < I
140
+ g = tl.load(GU_ptr + row * (2 * I) + offs, mask=mask, other=0.0).to(tl.float32)
141
+ u = tl.load(GU_ptr + row * (2 * I) + I + offs, mask=mask, other=0.0).to(tl.float32)
142
+ sg = (g * tl.sigmoid(g)).to(Y_ptr.dtype.element_ty).to(tl.float32)
143
+ y = (sg * u).to(Y_ptr.dtype.element_ty)
144
+ tl.store(Y_ptr + row * I + offs, y, mask=mask)
145
+
146
+ @triton.jit
147
+ def _swiglu_fp8_k(GU_ptr, QO_ptr, XS_ptr, M, I, BLOCK: tl.constexpr):
148
+ row = tl.program_id(0).to(tl.int64)
149
+ blk = tl.program_id(1)
150
+ offs = blk * BLOCK + tl.arange(0, BLOCK)
151
+ mask = offs < I
152
+ g = tl.load(GU_ptr + row * (2 * I) + offs, mask=mask, other=0.0).to(tl.float32)
153
+ u = tl.load(GU_ptr + row * (2 * I) + I + offs, mask=mask, other=0.0).to(tl.float32)
154
+ y = g * tl.sigmoid(g) * u
155
+ xs = tl.load(XS_ptr).to(tl.float32)
156
+ q = tl.minimum(tl.maximum(tl.math.div_rn(y, xs), -448.0), 448.0).to(tl.float8e4nv)
157
+ tl.store(QO_ptr + row * I + offs, q, mask=mask)
158
+
159
+ @triton.jit
160
+ def _swiglu_fp8_blk_k(GU_ptr, QO_ptr, SO_ptr, M, I, NB):
161
+ row = tl.program_id(0).to(tl.int64)
162
+ blk = tl.program_id(1)
163
+ offs = blk * 128 + tl.arange(0, 128)
164
+ g = tl.load(GU_ptr + row * (2 * I) + offs).to(tl.float32)
165
+ u = tl.load(GU_ptr + row * (2 * I) + I + offs).to(tl.float32)
166
+ y = g * tl.sigmoid(g) * u
167
+ amax = tl.maximum(tl.max(tl.abs(y), axis=0), 1e-12)
168
+ s = amax / 448.0
169
+ q = tl.minimum(tl.maximum(tl.math.div_rn(y, s), -448.0), 448.0).to(tl.float8e4nv)
170
+ tl.store(SO_ptr + row * NB + blk, s)
171
+ tl.store(QO_ptr + row * I + offs, q)
172
+
173
+ @triton_op("basal::llama_rmsnorm", mutates_args=())
174
+ def op_rms(h: torch.Tensor, w: torch.Tensor, eps: float) -> torch.Tensor:
175
+ shape = h.shape
176
+ D = shape[-1]
177
+ h2 = h.reshape(-1, D).contiguous()
178
+ M = h2.shape[0]
179
+ xo = torch.empty_like(h2)
180
+ if M:
181
+ bd = triton.next_power_of_2(D)
182
+ wrap_triton(_add_rms_k)[(M,)](h2, h2, w.contiguous(), h2, xo, M, D, eps,
183
+ HAS_RES=False, BLOCK_D=bd, num_warps=4 if bd <= 2048 else 8)
184
+ return xo.reshape(shape)
185
+
186
+ @triton_op("basal::llama_add_rmsnorm", mutates_args=())
187
+ def op_add_rms(h: torch.Tensor, res: torch.Tensor, w: torch.Tensor,
188
+ eps: float) -> tuple[torch.Tensor, torch.Tensor]:
189
+ shape = h.shape
190
+ D = shape[-1]
191
+ h2 = h.reshape(-1, D).contiguous()
192
+ M = h2.shape[0]
193
+ r2 = res.reshape(-1, D).contiguous()
194
+ ho = torch.empty_like(h2)
195
+ xo = torch.empty_like(h2)
196
+ if M:
197
+ bd = triton.next_power_of_2(D)
198
+ wrap_triton(_add_rms_k)[(M,)](h2, r2, w.contiguous(), ho, xo, M, D, eps,
199
+ HAS_RES=True, BLOCK_D=bd, num_warps=4 if bd <= 2048 else 8)
200
+ return ho.reshape(shape), xo.reshape(shape)
201
+
202
+ @triton_op("basal::llama_rmsnorm_fp8", mutates_args=())
203
+ def op_rms_fp8(h: torch.Tensor, w: torch.Tensor, eps: float, xs: torch.Tensor) -> torch.Tensor:
204
+ shape = h.shape
205
+ D = shape[-1]
206
+ h2 = h.reshape(-1, D).contiguous()
207
+ M = h2.shape[0]
208
+ qo = torch.empty((M, D), dtype=E4M3, device=h.device)
209
+ if M:
210
+ bd = triton.next_power_of_2(D)
211
+ wrap_triton(_add_rms_fp8_k)[(M,)](h2, h2, w.contiguous(), h2, qo, xs, M, D, eps,
212
+ HAS_RES=False, BLOCK_D=bd, num_warps=4 if bd <= 2048 else 8)
213
+ return qo.reshape(shape)
214
+
215
+ @triton_op("basal::llama_add_rmsnorm_fp8", mutates_args=())
216
+ def op_add_rms_fp8(h: torch.Tensor, res: torch.Tensor, w: torch.Tensor,
217
+ eps: float, xs: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
218
+ shape = h.shape
219
+ D = shape[-1]
220
+ h2 = h.reshape(-1, D).contiguous()
221
+ M = h2.shape[0]
222
+ r2 = res.reshape(-1, D).contiguous()
223
+ ho = torch.empty_like(h2)
224
+ qo = torch.empty((M, D), dtype=E4M3, device=h.device)
225
+ if M:
226
+ bd = triton.next_power_of_2(D)
227
+ wrap_triton(_add_rms_fp8_k)[(M,)](h2, r2, w.contiguous(), ho, qo, xs, M, D, eps,
228
+ HAS_RES=True, BLOCK_D=bd, num_warps=4 if bd <= 2048 else 8)
229
+ return ho.reshape(shape), qo.reshape(shape)
230
+
231
+ @triton_op("basal::llama_qkv_rope", mutates_args=())
232
+ def op_qkv_rope(qkv: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor,
233
+ H: int, Hkv: int, D: int) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
234
+ B, L, _ = qkv.shape
235
+ M = B * L
236
+ q = torch.empty((B, L, H, D), dtype=qkv.dtype, device=qkv.device)
237
+ k = torch.empty((B, L, Hkv, D), dtype=qkv.dtype, device=qkv.device)
238
+ v = torch.empty((B, L, Hkv, D), dtype=qkv.dtype, device=qkv.device)
239
+ if M:
240
+ wrap_triton(_qkv_rope_k)[(M, H + 2 * Hkv)](
241
+ qkv.contiguous(), cos.contiguous(), sin.contiguous(), q, k, v,
242
+ M, H=H, HKV=Hkv, D=D, HALF=D // 2, HAS_Q=True, num_warps=2)
243
+ return q, k, v
244
+
245
+ @triton_op("basal::llama_kv_rope", mutates_args=())
246
+ def op_kv_rope(kv: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor,
247
+ Hkv: int, D: int) -> tuple[torch.Tensor, torch.Tensor]:
248
+ B, L, _ = kv.shape
249
+ M = B * L
250
+ k = torch.empty((B, L, Hkv, D), dtype=kv.dtype, device=kv.device)
251
+ v = torch.empty((B, L, Hkv, D), dtype=kv.dtype, device=kv.device)
252
+ if M:
253
+ wrap_triton(_qkv_rope_k)[(M, 2 * Hkv)](
254
+ kv.contiguous(), cos.contiguous(), sin.contiguous(), k, k, v,
255
+ M, H=0, HKV=Hkv, D=D, HALF=D // 2, HAS_Q=False, num_warps=2)
256
+ return k, v
257
+
258
+ @triton_op("basal::llama_q_rope", mutates_args=())
259
+ def op_q_rope(q: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor,
260
+ H: int, D: int) -> torch.Tensor:
261
+ B, L, _ = q.shape
262
+ M = B * L
263
+ qo = torch.empty((B, L, H, D), dtype=q.dtype, device=q.device)
264
+ if M:
265
+ wrap_triton(_q_rope_k)[(M, H)](
266
+ q.contiguous(), cos.contiguous(), sin.contiguous(), qo,
267
+ M, H=H, D=D, HALF=D // 2, num_warps=2)
268
+ return qo
269
+
270
+ @triton_op("basal::llama_swiglu", mutates_args=())
271
+ def op_swiglu(gu: torch.Tensor) -> torch.Tensor:
272
+ shape = gu.shape
273
+ I = shape[-1] // 2
274
+ g2 = gu.reshape(-1, 2 * I).contiguous()
275
+ M = g2.shape[0]
276
+ y = torch.empty((M, I), dtype=gu.dtype, device=gu.device)
277
+ if M:
278
+ blk = 256
279
+ wrap_triton(_swiglu_k)[(M, triton.cdiv(I, blk))](g2, y, M, I, BLOCK=blk, num_warps=4)
280
+ return y.reshape(*shape[:-1], I)
281
+
282
+ @triton_op("basal::llama_swiglu_fp8", mutates_args=())
283
+ def op_swiglu_fp8(gu: torch.Tensor, xs: torch.Tensor) -> torch.Tensor:
284
+ shape = gu.shape
285
+ I = shape[-1] // 2
286
+ g2 = gu.reshape(-1, 2 * I).contiguous()
287
+ M = g2.shape[0]
288
+ qo = torch.empty((M, I), dtype=E4M3, device=gu.device)
289
+ if M:
290
+ blk = 256
291
+ wrap_triton(_swiglu_fp8_k)[(M, triton.cdiv(I, blk))](g2, qo, xs, M, I, BLOCK=blk, num_warps=4)
292
+ return qo.reshape(*shape[:-1], I)
293
+
294
+ @triton_op("basal::llama_swiglu_fp8_block", mutates_args=())
295
+ def op_swiglu_fp8_blk(gu: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
296
+ shape = gu.shape
297
+ I = shape[-1] // 2
298
+ g2 = gu.reshape(-1, 2 * I).contiguous()
299
+ M = g2.shape[0]
300
+ nb = I // 128
301
+ qo = torch.empty((M, I), dtype=E4M3, device=gu.device)
302
+ so = torch.empty((M, nb), dtype=torch.float32, device=gu.device)
303
+ if M:
304
+ wrap_triton(_swiglu_fp8_blk_k)[(M, nb)](g2, qo, so, M, I, nb, num_warps=4)
305
+ return qo.reshape(*shape[:-1], I), so
306
+
307
+ return (op_rms, op_add_rms, op_rms_fp8, op_add_rms_fp8, op_qkv_rope, op_kv_rope, op_q_rope,
308
+ op_swiglu, op_swiglu_fp8, op_swiglu_fp8_blk)
309
+
310
+
311
+ def prepare():
312
+ if torch.cuda.is_available() and not _OPS:
313
+ _OPS.extend(_build())
314
+
315
+
316
+ def add_rmsnorm(h, res, w, eps):
317
+ """Fused residual add + RMSNorm -> (h_out, x_norm)."""
318
+ if h.is_cuda:
319
+ prepare()
320
+ if res is None:
321
+ return h, torch.ops.basal.llama_rmsnorm(h, w, float(eps))
322
+ return torch.ops.basal.llama_add_rmsnorm(h, res, w, float(eps))
323
+ ho = h if res is None else (h + res)
324
+ return ho, _rms_ref(ho, w, eps)
325
+
326
+
327
+ def add_rmsnorm_fp8(h, res, w, eps, xs):
328
+ """Fused residual add + RMSNorm + static FP8 quantization -> (h_out, q_fp8)."""
329
+ if h.is_cuda:
330
+ prepare()
331
+ if res is None:
332
+ return h, torch.ops.basal.llama_rmsnorm_fp8(h, w, float(eps), xs)
333
+ return torch.ops.basal.llama_add_rmsnorm_fp8(h, res, w, float(eps), xs)
334
+ ho = h if res is None else (h + res)
335
+ x = _rms_ref(ho, w, eps)
336
+ q = (x.float() / xs).clamp(-FP8_MAX, FP8_MAX).to(E4M3)
337
+ return ho, q
338
+
339
+
340
+ def qkv_rope(qkv, cos, sin, H, Hkv, D):
341
+ """Merged QKV [B, L, (H + 2*Hkv)*D] -> rotated (q [B,L,H,D], k [B,L,Hkv,D], v [B,L,Hkv,D]) in NHD layout."""
342
+ if qkv.is_cuda and D % 2 == 0 and (D & (D - 1)) == 0:
343
+ prepare()
344
+ return torch.ops.basal.llama_qkv_rope(qkv, cos, sin, H, Hkv, D)
345
+ B, L, _ = qkv.shape
346
+ q, k, v = qkv.split([H * D, Hkv * D, Hkv * D], -1)
347
+ q = _rot_ref(q.view(B, L, H, D), cos[:, :, None], sin[:, :, None])
348
+ k = _rot_ref(k.view(B, L, Hkv, D), cos[:, :, None], sin[:, :, None])
349
+ v = v.view(B, L, Hkv, D)
350
+ return q, k, v
351
+
352
+
353
+ def kv_rope(kv, cos, sin, Hkv, D):
354
+ """Merged KV [B, L, 2*Hkv*D] -> rotated (k [B,L,Hkv,D], v [B,L,Hkv,D]) in NHD layout."""
355
+ if kv.is_cuda and D % 2 == 0 and (D & (D - 1)) == 0:
356
+ prepare()
357
+ return torch.ops.basal.llama_kv_rope(kv, cos, sin, Hkv, D)
358
+ B, L, _ = kv.shape
359
+ k, v = kv.split([Hkv * D, Hkv * D], -1)
360
+ k = _rot_ref(k.view(B, L, Hkv, D), cos[:, :, None], sin[:, :, None])
361
+ v = v.view(B, L, Hkv, D)
362
+ return k, v
363
+
364
+
365
+ def q_rope(q, cos, sin, H, D):
366
+ """Q [B, L, H*D] -> rotated q [B, L, H, D] in NHD layout."""
367
+ if q.is_cuda and D % 2 == 0 and (D & (D - 1)) == 0:
368
+ prepare()
369
+ return torch.ops.basal.llama_q_rope(q, cos, sin, H, D)
370
+ B, L, _ = q.shape
371
+ return _rot_ref(q.view(B, L, H, D), cos[:, :, None], sin[:, :, None])
372
+
373
+
374
+ def swiglu(gu):
375
+ """Merged gate_up [..., 2*I] -> silu(gate) * up [..., I]."""
376
+ if gu.is_cuda:
377
+ prepare()
378
+ return torch.ops.basal.llama_swiglu(gu)
379
+ g, u = gu.chunk(2, -1)
380
+ return F.silu(g) * u
381
+
382
+
383
+ def swiglu_fp8(gu, xs):
384
+ """Merged gate_up [..., 2*I] -> static FP8 silu(gate) * up [..., I]."""
385
+ if gu.is_cuda:
386
+ prepare()
387
+ return torch.ops.basal.llama_swiglu_fp8(gu, xs)
388
+ g, u = gu.chunk(2, -1)
389
+ y = F.silu(g) * u
390
+ return (y.float() / xs).clamp(-FP8_MAX, FP8_MAX).to(E4M3)
391
+
392
+
393
+ def swiglu_fp8_block(gu):
394
+ """Merged gate_up [..., 2*I] -> 1x128 block FP8 (q [..., I], scales [M, I/128])."""
395
+ if gu.is_cuda and (gu.shape[-1] // 2) % 128 == 0:
396
+ prepare()
397
+ return torch.ops.basal.llama_swiglu_fp8_block(gu)
398
+ from . import fp8block
399
+ g, u = gu.chunk(2, -1)
400
+ y = F.silu(g) * u
401
+ q, s = fp8block.act_quant(y.reshape(-1, y.shape[-1]))
402
+ return q.reshape(y.shape), s
403
+
404
+
405
+ class LosslessMergedFP8Linear(torch.nn.Module):
406
+ """Merges ModelOpt FP8Linear layers (q/k/v or gate/up) WITHOUT dequantizing or re-quantizing their weights.
407
+ Each sub-projection keeps its exact original FP8 weight rows and exact original scalar weight_scale expanded to
408
+ a per-column scale vector [1, N_total]. When all sub-projections share the same static input_scale (the standard
409
+ ModelOpt calibration case on a shared post-RMSNorm input), one fp8_cast + one torch._scaled_mm runs all
410
+ projections in a single GEMM with zero quantization loss. Preserves concatenated bias vectors (Bielik 1.5B/4.5B).
411
+ """
412
+
413
+ def __init__(self, weight, weight_scale_col, input_scale, bias=None):
414
+ super().__init__()
415
+ self.out_features, self.in_features = weight.shape
416
+ self.register_buffer("weight", weight.contiguous())
417
+ self.register_buffer("weight_scale_col", weight_scale_col.float().reshape(1, -1).contiguous())
418
+ self.register_buffer("input_scale", input_scale.float().reshape(()))
419
+ self.bias = None if bias is None else torch.nn.Parameter(bias, requires_grad=False)
420
+
421
+ @classmethod
422
+ def from_fp8_linears(cls, mods):
423
+ """Merge a list of FP8Linear modules losslessly -> LosslessMergedFP8Linear, or None if input_scales differ."""
424
+ from .engine import FP8Linear
425
+ if not all(isinstance(m, FP8Linear) for m in mods):
426
+ return None
427
+ s0 = mods[0].input_scale
428
+ if not all(torch.equal(m.input_scale, s0) for m in mods[1:]):
429
+ return None
430
+ w = torch.cat([m.weight.detach() for m in mods], dim=0)
431
+ ws = torch.cat([m.weight_scale.float().reshape(1).expand(m.out_features) for m in mods], dim=0)
432
+ bias = None if mods[0].bias is None else torch.cat([m.bias.detach() for m in mods], dim=0)
433
+ return cls(w, ws, s0.detach(), bias)
434
+
435
+ def forward_quantized(self, q, out_dtype):
436
+ """Run GEMM directly on already-quantized FP8 input q [..., K] (from fused add_rmsnorm_fp8 / swiglu_fp8)."""
437
+ from .engine import FP8_FAST_ACCUM
438
+ shape = q.shape
439
+ q2 = q.reshape(-1, self.in_features)
440
+ if q2.is_cuda:
441
+ m = q2.shape[0]
442
+ if m % 16:
443
+ q2 = F.pad(q2.view(torch.uint8), (0, 0, 0, -m % 16)).view(E4M3)
444
+ sa = self.input_scale.reshape(1, 1).expand(q2.shape[0], 1).contiguous()
445
+ y = torch._scaled_mm(q2, self.weight.t(), scale_a=sa, scale_b=self.weight_scale_col,
446
+ bias=None if self.bias is None else self.bias.to(out_dtype), out_dtype=out_dtype,
447
+ use_fast_accum=FP8_FAST_ACCUM[0])[:m]
448
+ else:
449
+ y = (q2.float() * self.input_scale) @ (self.weight.float() * self.weight_scale_col.t()).t()
450
+ y = (y if self.bias is None else y + self.bias.float()).to(out_dtype)
451
+ return y.reshape(*shape[:-1], self.out_features)
452
+
453
+ def forward(self, x):
454
+ from .engine import fp8_cast
455
+ q = fp8_cast(x.reshape(-1, self.in_features), self.input_scale)
456
+ return self.forward_quantized(q.reshape(x.shape), x.dtype)
457
+
458
+
459
+ class HostStaging:
460
+ """Persistent pinned host staging buffers for GraphBackend static inputs: writes numpy arrays into reusable
461
+ pinned host memory and copies directly to the destination GPU tensor (non_blocking=True), avoiding per-forward
462
+ cudaHostAlloc / temporary GPU tensor / extra D2D copy overhead.
463
+
464
+ A buffer is written again only after the copy that last read it has run (its CUDA event): the copy is queued
465
+ behind the forwards before it, so when the host runs more than `slots` forwards ahead of the GPU, rewriting the
466
+ buffer at once would hand an earlier queued forward the inputs of a later one (3.0.1 / 3.0.2: two-way
467
+ multi-question requests under load read another forward's readout positions, a device-side assert in the readout
468
+ gather; with equal shapes, another forward's inputs, silently)."""
469
+
470
+ def __init__(self, device, slots=3):
471
+ self.dev = device
472
+ self.cuda = device.type == "cuda"
473
+ self.slots = slots
474
+ self._bufs = {} # (name, dtype) -> list of pinned 1D tensors
475
+ self._pos = {}
476
+ self._read = {} # (name, dtype, slot) -> CUDA event after the copy that last read that slot's buffer
477
+
478
+ def copy_to(self, name, dst, arr):
479
+ """Copy host numpy array or tensor `arr` into static GPU tensor `dst` asynchronously via pinned staging."""
480
+ import numpy as np
481
+ t = torch.from_numpy(arr) if isinstance(arr, np.ndarray) else arr
482
+ if not self.cuda:
483
+ return dst.copy_(t.to(dst.dtype))
484
+ key = (name, dst.dtype)
485
+ ring = self._bufs.setdefault(key, [None] * self.slots)
486
+ idx = self._pos.get(key, 0) % self.slots
487
+ self._pos[key] = idx + 1
488
+ read = self._read.get((key, idx))
489
+ if read is not None:
490
+ read.synchronize() # the queued copy that reads this buffer has run: it can be written again
491
+ n = t.numel()
492
+ buf = ring[idx]
493
+ if buf is None or buf.numel() < n:
494
+ buf = ring[idx] = torch.empty(max(n, 4096), dtype=dst.dtype, pin_memory=True)
495
+ view = buf[:n].view(t.shape)
496
+ view.copy_(t)
497
+ out = dst.copy_(view, non_blocking=True)
498
+ ev = torch.cuda.Event()
499
+ ev.record(torch.cuda.current_stream(dst.device))
500
+ self._read[(key, idx)] = ev
501
+ return out
502
+
503
+
504
+ # -- Self-contained sm_12x L2-chunked per-row FP8 GEMM (defers to basal.fp8rows when present on 3.1+) ---------------
505
+ _FP8_ROWS_ORIG = []
506
+ _FP8_ROWS_L2 = [0]
507
+ _FP8_ROWS_CHUNK = 0.7
508
+ _FP8_ROWS_TILE = 128
509
+
510
+
511
+ def _fp8_rows_for(K, N, l2=None):
512
+ l2 = _FP8_ROWS_L2[0] if l2 is None else l2
513
+ budget = _FP8_ROWS_CHUNK * l2
514
+ if not l2 or K * N <= budget:
515
+ return 0
516
+ return max(int(budget // K) // _FP8_ROWS_TILE * _FP8_ROWS_TILE, _FP8_ROWS_TILE)
517
+
518
+
519
+ def _fp8_row_split(M, rows):
520
+ if not rows or M <= rows:
521
+ return [(0, M)]
522
+ n = -(-M // rows)
523
+ step = -(-(-(-M // n)) // _FP8_ROWS_TILE) * _FP8_ROWS_TILE
524
+ return [(i, min(i + step, M)) for i in range(0, M, step)]
525
+
526
+
527
+ @torch.library.custom_op("basal::llama_scaled_mm_rows", mutates_args=())
528
+ def _llama_scaled_mm_rows(a: torch.Tensor, b: torch.Tensor, scale_a: torch.Tensor, scale_b: torch.Tensor,
529
+ bias: torch.Tensor | None, out_dtype: torch.dtype, use_fast_accum: bool,
530
+ rows: int) -> torch.Tensor:
531
+ kw = dict(scale_b=scale_b, bias=bias, out_dtype=out_dtype, use_fast_accum=use_fast_accum)
532
+ parts = _fp8_row_split(a.shape[0], rows)
533
+ if len(parts) == 1:
534
+ return torch._scaled_mm(a, b, scale_a=scale_a, **kw)
535
+ out = a.new_empty((a.shape[0], b.shape[1]), dtype=out_dtype)
536
+ for i, j in parts:
537
+ torch._scaled_mm(a[i:j], b, scale_a=scale_a[i:j], out=out[i:j], **kw)
538
+ return out
539
+
540
+
541
+ @_llama_scaled_mm_rows.register_fake
542
+ def _(a, b, scale_a, scale_b, bias, out_dtype, use_fast_accum, rows):
543
+ return a.new_empty((a.shape[0], b.shape[1]), dtype=out_dtype)
544
+
545
+
546
+ def install_fp8_row_chunks(cc, l2, shapes):
547
+ """Route torchao per-row FP8 GEMMs into L2-fitting row chunks on sm_12x (GB10: +1.50x on Bielik 4.5B,
548
+ bit-identical). Defers to basal.fp8rows when available (3.1+)."""
549
+ import os
550
+ try:
551
+ from . import fp8rows
552
+ return fp8rows.install(cc, l2, shapes)
553
+ except ImportError:
554
+ pass
555
+ if os.environ.get("BASAL_FP8_ROWS", "1") == "0" or tuple(cc)[0] != 12 or not l2:
556
+ return None
557
+ chunked = sorted({(K, N, _fp8_rows_for(K, N, l2)) for K, N in shapes if _fp8_rows_for(K, N, l2)})
558
+ if not chunked:
559
+ return None
560
+ try:
561
+ from torchao.quantization.quantize_.workflows.float8 import float8_tensor
562
+ except ImportError:
563
+ return None
564
+ if not _FP8_ROWS_ORIG:
565
+ if not hasattr(float8_tensor, "addmm_float8_unwrapped_inference"):
566
+ return None
567
+ _FP8_ROWS_ORIG.append(float8_tensor.addmm_float8_unwrapped_inference)
568
+
569
+ def _wrapped(a_data, a_scale, b_data, b_scale, output_dtype, output_scale=None, bias=None,
570
+ use_fast_accum=False):
571
+ rows = _fp8_rows_for(*b_data.shape) if a_data.dim() == 2 and b_data.dim() == 2 else 0
572
+ if (not rows or output_scale is not None or (output_dtype == torch.float32 and bias is not None)
573
+ or a_scale.dim() != 2 or a_scale.shape[-1] != 1
574
+ or b_scale.dim() != 2 or b_scale.shape[0] != 1):
575
+ return _FP8_ROWS_ORIG[0](a_data, a_scale, b_data, b_scale, output_dtype, output_scale=output_scale,
576
+ bias=bias, use_fast_accum=use_fast_accum)
577
+ return _llama_scaled_mm_rows(a_data, b_data, a_scale, b_scale, bias, output_dtype, use_fast_accum, rows)
578
+
579
+ float8_tensor.addmm_float8_unwrapped_inference = _wrapped
580
+ _FP8_ROWS_L2[0] = int(l2)
581
+ each = ", ".join(f"{K} -> {N}: {rows}" for K, N, rows in chunked)
582
+ return f"per-row FP8 GEMMs in L2 row chunks ({l2 >> 20} MB L2: {each})"
583
+
584
+
585
+ def fp8_rows_cache_key():
586
+ try:
587
+ from . import fp8rows
588
+ return fp8rows.cache_key()
589
+ except ImportError:
590
+ pass
591
+ if not _FP8_ROWS_ORIG or not _FP8_ROWS_L2[0]:
592
+ return None
593
+ return f"basal.llama_fp8rows:1:{_FP8_ROWS_CHUNK}:{_FP8_ROWS_TILE}:{_FP8_ROWS_L2[0]}"