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/mlx_kernels.py ADDED
@@ -0,0 +1,543 @@
1
+ """Custom pure-Metal layer kernels for Apple Silicon MLX (basal 3.0.1, --mlx-forward metal).
2
+
3
+ Compiled on first use via `mx.fast.metal_kernel` (zero Xcode/C++ build step, cached per dtype/shape):
4
+ - `add_rmsnorm(h, r, w, eps)` -> `(h_out, x_norm)`: fused residual add + RMSNorm in one pass.
5
+ - `swiglu(gu)` / `geglu(gu)` -> `out`: fused split + activation * up on merged `[..., 2*I]` output.
6
+ - `qkv_rope(qkv, pos, inv_freq, H, Hkv, D)` -> `(q, k, v)` in native NHD `[T, H, D]` layout.
7
+ - `kv_rope(kv, pos, inv_freq, Hkv, D)` -> `(k, v)` in native NHD `[T, Hkv, D]` layout (last layer).
8
+ - `q_rope(q_in, pos, inv_freq, H, D)` -> `q` in native NHD `[R, H, D]` layout (last-layer readouts).
9
+
10
+ All kernels preserve IEEE/fp32 intermediate precision (`compile_options={"math_mode": "safe"}`).
11
+ """
12
+ from functools import lru_cache
13
+
14
+ import mlx.core as mx
15
+ import mlx.nn as nn
16
+
17
+ # ---------------------------------------------------------------------------
18
+ # 1. Fused residual add + RMSNorm: (h, r, w) -> (h + r, rmsnorm(h + r, w, eps))
19
+ # ---------------------------------------------------------------------------
20
+
21
+ _ADD_RMSNORM_SRC = r"""
22
+ constexpr uint TG = 256;
23
+ uint row = threadgroup_position_in_grid.x;
24
+ uint tid = thread_position_in_threadgroup.x;
25
+ uint simd_lane = thread_index_in_simdgroup;
26
+ uint simd_id = simdgroup_index_in_threadgroup;
27
+ uint D = h_shape[h_ndim - 1];
28
+ float eps = eps_arr[0];
29
+
30
+ uint base = row * D;
31
+ float ss = 0.0f;
32
+
33
+ // Cache up to 16 elements per thread in registers (covers D <= 4096 in a single DRAM read).
34
+ float reg[16];
35
+ uint n_reg = 0;
36
+ for (uint col = tid; col < D; col += TG) {
37
+ T hv = T(float(h[base + col]) + float(r[base + col]) + (HAS_BIAS ? float(bias[col]) : 0.0f));
38
+ h_out[base + col] = hv;
39
+ float v = float(hv);
40
+ ss += v * v;
41
+ if (n_reg < 16) {
42
+ reg[n_reg++] = v;
43
+ }
44
+ }
45
+
46
+ // Two-level reduction: simd_sum (32 lanes) -> threadgroup shared (8 simdgroups).
47
+ ss = simd_sum(ss);
48
+ threadgroup float tg_buf[8];
49
+ if (simd_lane == 0) {
50
+ tg_buf[simd_id] = ss;
51
+ }
52
+ threadgroup_barrier(mem_flags::mem_threadgroup);
53
+
54
+ float total = 0.0f;
55
+ if (simd_id == 0) {
56
+ float val = (simd_lane < (TG / 32)) ? tg_buf[simd_lane] : 0.0f;
57
+ total = simd_sum(val);
58
+ if (simd_lane == 0) {
59
+ tg_buf[0] = metal::rsqrt(total / float(D) + eps);
60
+ }
61
+ }
62
+ threadgroup_barrier(mem_flags::mem_threadgroup);
63
+ float inv_rms = tg_buf[0];
64
+
65
+ uint idx = 0;
66
+ for (uint col = tid; col < D; col += TG) {
67
+ float v = (idx < 16) ? reg[idx] : float(h_out[base + col]);
68
+ idx++;
69
+ x_norm[base + col] = T(v * inv_rms * float(w[col]));
70
+ }
71
+ """
72
+
73
+
74
+ @lru_cache(maxsize=8)
75
+ def _add_rmsnorm_kernel():
76
+ return mx.fast.metal_kernel(
77
+ name="basal_add_rmsnorm",
78
+ input_names=["h", "r", "bias", "w", "eps_arr"],
79
+ output_names=["h_out", "x_norm"],
80
+ source=_ADD_RMSNORM_SRC,
81
+ ensure_row_contiguous=True,
82
+ compile_options={"math_mode": "safe"},
83
+ )
84
+
85
+
86
+ @lru_cache(maxsize=16)
87
+ def _eps_scalar(eps: float):
88
+ return mx.array([eps], dtype=mx.float32)
89
+
90
+
91
+ @lru_cache(maxsize=8)
92
+ def _dummy_bias(dt):
93
+ return mx.zeros((1,), dtype=dt)
94
+
95
+
96
+ def add_rmsnorm(h: mx.array, r: mx.array, w: mx.array, eps: float, bias: mx.array | None = None):
97
+ """Fused residual add (+ optional linear bias) + RMSNorm -> (h_out, x_norm)."""
98
+ shape = h.shape
99
+ D = shape[-1]
100
+ rows = h.size // D
101
+ h2 = h.reshape(rows, D)
102
+ r2 = r.reshape(rows, D)
103
+ has_bias = bias is not None
104
+ b = bias if has_bias else _dummy_bias(h.dtype)
105
+ h_out, x_norm = _add_rmsnorm_kernel()(
106
+ inputs=[h2, r2, b, w, _eps_scalar(float(eps))],
107
+ template=[("T", h.dtype), ("HAS_BIAS", int(has_bias))],
108
+ grid=(rows * 256, 1, 1),
109
+ threadgroup=(256, 1, 1),
110
+ output_shapes=[(rows, D), (rows, D)],
111
+ output_dtypes=[h.dtype, h.dtype],
112
+ )
113
+ return h_out.reshape(shape), x_norm.reshape(shape)
114
+
115
+
116
+ # ---------------------------------------------------------------------------
117
+ # 2. Fused SwiGLU & GeGLU (+ optional linear bias) on merged [..., 2*I] gate_up output
118
+ # ---------------------------------------------------------------------------
119
+
120
+ _SWIGLU_SRC = r"""
121
+ uint idx = thread_position_in_grid.x;
122
+ uint I = gu_shape[gu_ndim - 1] / 2;
123
+ uint total = gu_shape[0] * I;
124
+ if (idx >= total) return;
125
+ uint row = idx / I;
126
+ uint col = idx - row * I;
127
+ uint base = row * (2 * I);
128
+ float g = float(gu[base + col]) + (HAS_BIAS ? float(bias[col]) : 0.0f);
129
+ float u = float(gu[base + I + col]) + (HAS_BIAS ? float(bias[I + col]) : 0.0f);
130
+ float s = g / (1.0f + metal::exp(-g));
131
+ out[idx] = T(s * u);
132
+ """
133
+
134
+ _GEGLU_SRC = r"""
135
+ uint idx = thread_position_in_grid.x;
136
+ uint I = gu_shape[gu_ndim - 1] / 2;
137
+ uint total = gu_shape[0] * I;
138
+ if (idx >= total) return;
139
+ uint row = idx / I;
140
+ uint col = idx - row * I;
141
+ uint base = row * (2 * I);
142
+ float g = float(gu[base + col]) + (HAS_BIAS ? float(bias[col]) : 0.0f);
143
+ float u = float(gu[base + I + col]) + (HAS_BIAS ? float(bias[I + col]) : 0.0f);
144
+ constexpr float k = 0.7978845608028654f; // sqrt(2 / pi)
145
+ float s = 0.5f * g * (1.0f + metal::tanh(k * (g + 0.044715f * g * g * g)));
146
+ out[idx] = T(s * u);
147
+ """
148
+
149
+
150
+ @lru_cache(maxsize=4)
151
+ def _swiglu_kernel():
152
+ return mx.fast.metal_kernel(
153
+ name="basal_swiglu",
154
+ input_names=["gu", "bias"],
155
+ output_names=["out"],
156
+ source=_SWIGLU_SRC,
157
+ ensure_row_contiguous=True,
158
+ compile_options={"math_mode": "safe"},
159
+ )
160
+
161
+
162
+ @lru_cache(maxsize=4)
163
+ def _geglu_kernel():
164
+ return mx.fast.metal_kernel(
165
+ name="basal_geglu",
166
+ input_names=["gu", "bias"],
167
+ output_names=["out"],
168
+ source=_GEGLU_SRC,
169
+ ensure_row_contiguous=True,
170
+ compile_options={"math_mode": "safe"},
171
+ )
172
+
173
+
174
+ def swiglu(gu: mx.array, bias: mx.array | None = None) -> mx.array:
175
+ """Fused split (+ optional bias) + SiLU(gate) * up on merged [..., 2*I] -> [..., I]."""
176
+ shape = gu.shape
177
+ I = shape[-1] // 2
178
+ rows = gu.size // (2 * I)
179
+ total = rows * I
180
+ tg = 256
181
+ grid = ((total + tg - 1) // tg) * tg
182
+ has_bias = bias is not None
183
+ b = bias if has_bias else _dummy_bias(gu.dtype)
184
+ (out,) = _swiglu_kernel()(
185
+ inputs=[gu.reshape(rows, 2 * I), b],
186
+ template=[("T", gu.dtype), ("HAS_BIAS", int(has_bias))],
187
+ grid=(grid, 1, 1),
188
+ threadgroup=(tg, 1, 1),
189
+ output_shapes=[(rows, I)],
190
+ output_dtypes=[gu.dtype],
191
+ )
192
+ return out.reshape(*shape[:-1], I)
193
+
194
+
195
+ def geglu(gu: mx.array, bias: mx.array | None = None) -> mx.array:
196
+ """Fused split (+ optional bias) + GELU_approx(gate) * up on merged [..., 2*I] -> [..., I]."""
197
+ shape = gu.shape
198
+ I = shape[-1] // 2
199
+ rows = gu.size // (2 * I)
200
+ total = rows * I
201
+ tg = 256
202
+ grid = ((total + tg - 1) // tg) * tg
203
+ has_bias = bias is not None
204
+ b = bias if has_bias else _dummy_bias(gu.dtype)
205
+ (out,) = _geglu_kernel()(
206
+ inputs=[gu.reshape(rows, 2 * I), b],
207
+ template=[("T", gu.dtype), ("HAS_BIAS", int(has_bias))],
208
+ grid=(grid, 1, 1),
209
+ threadgroup=(tg, 1, 1),
210
+ output_shapes=[(rows, I)],
211
+ output_dtypes=[gu.dtype],
212
+ )
213
+ return out.reshape(*shape[:-1], I)
214
+
215
+
216
+ _SWIGLU_SEP_SRC = r"""
217
+ uint idx = thread_position_in_grid.x;
218
+ uint I = g_in_shape[g_in_ndim - 1];
219
+ uint total = g_in_shape[0] * I;
220
+ if (idx >= total) return;
221
+ uint col = idx - (idx / I) * I;
222
+ float g = float(g_in[idx]) + (HAS_BIAS ? float(g_bias[col]) : 0.0f);
223
+ float u = float(u_in[idx]) + (HAS_BIAS ? float(u_bias[col]) : 0.0f);
224
+ float s = g / (1.0f + metal::exp(-g));
225
+ out[idx] = T(s * u);
226
+ """
227
+
228
+
229
+ @lru_cache(maxsize=4)
230
+ def _swiglu_sep_kernel():
231
+ return mx.fast.metal_kernel(
232
+ name="basal_swiglu_sep",
233
+ input_names=["g_in", "u_in", "g_bias", "u_bias"],
234
+ output_names=["out"],
235
+ source=_SWIGLU_SEP_SRC,
236
+ ensure_row_contiguous=True,
237
+ compile_options={"math_mode": "safe"},
238
+ )
239
+
240
+
241
+ def swiglu_sep(g: mx.array, u: mx.array, g_bias: mx.array | None = None, u_bias: mx.array | None = None) -> mx.array:
242
+ """Fused (+ optional biases) SiLU(g) * u for separate `[..., I]` gate/up outputs -> `[..., I]`."""
243
+ shape = g.shape
244
+ I = shape[-1]
245
+ rows = g.size // I
246
+ total = rows * I
247
+ tg = 256
248
+ grid = ((total + tg - 1) // tg) * tg
249
+ has_bias = g_bias is not None and u_bias is not None
250
+ gb = g_bias if has_bias else _dummy_bias(g.dtype)
251
+ ub = u_bias if has_bias else _dummy_bias(u.dtype)
252
+ (out,) = _swiglu_sep_kernel()(
253
+ inputs=[g.reshape(rows, I), u.reshape(rows, I), gb, ub],
254
+ template=[("T", g.dtype), ("HAS_BIAS", int(has_bias))],
255
+ grid=(grid, 1, 1),
256
+ threadgroup=(tg, 1, 1),
257
+ output_shapes=[(rows, I)],
258
+ output_dtypes=[g.dtype],
259
+ )
260
+ return out.reshape(shape)
261
+
262
+
263
+ # ---------------------------------------------------------------------------
264
+ # 3. Fused QKV / KV / Q split + per-token RoPE -> native NHD [T, H, D] or BHD [1, H, T, D]
265
+ # Computes metal::sincos ONCE per (t, d) and reuses (cos, sin) across all H + Hkv heads!
266
+ # ---------------------------------------------------------------------------
267
+
268
+ _QKV_ROPE_SRC = r"""
269
+ uint d = thread_position_in_grid.x;
270
+ uint t = thread_position_in_grid.y;
271
+ uint half_d = D / 2;
272
+ uint T_len = uint(qkv_shape[0]);
273
+ if (d >= half_d || t >= T_len) return;
274
+
275
+ uint stride_in = (H + 2 * HKV) * D;
276
+ uint d0 = TRAD ? (2 * d) : d;
277
+ uint d1 = TRAD ? (2 * d + 1) : (d + half_d);
278
+
279
+ float angle = float(pos[t]) * inv_freq[d];
280
+ float s, c;
281
+ s = metal::sincos(angle, c);
282
+
283
+ uint row_base = t * stride_in;
284
+ for (uint h = 0; h < H; ++h) {
285
+ uint col0 = h * D + d0;
286
+ uint col1 = h * D + d1;
287
+ float x0 = float(qkv[row_base + col0]) + (HAS_BIAS ? float(bias[col0]) : 0.0f);
288
+ float x1 = float(qkv[row_base + col1]) + (HAS_BIAS ? float(bias[col1]) : 0.0f);
289
+ uint o_base = BHD ? ((h * T_len + t) * D) : ((t * H + h) * D);
290
+ q_out[o_base + d0] = T(x0 * c - x1 * s);
291
+ q_out[o_base + d1] = T(x0 * s + x1 * c);
292
+ }
293
+ for (uint hk = 0; hk < HKV; ++hk) {
294
+ uint col0 = (H + hk) * D + d0;
295
+ uint col1 = (H + hk) * D + d1;
296
+ float x0 = float(qkv[row_base + col0]) + (HAS_BIAS ? float(bias[col0]) : 0.0f);
297
+ float x1 = float(qkv[row_base + col1]) + (HAS_BIAS ? float(bias[col1]) : 0.0f);
298
+ uint o_base = BHD ? ((hk * T_len + t) * D) : ((t * HKV + hk) * D);
299
+ k_out[o_base + d0] = T(x0 * c - x1 * s);
300
+ k_out[o_base + d1] = T(x0 * s + x1 * c);
301
+ }
302
+ for (uint hv = 0; hv < HKV; ++hv) {
303
+ uint col0 = (H + HKV + hv) * D + d0;
304
+ uint col1 = (H + HKV + hv) * D + d1;
305
+ float x0 = float(qkv[row_base + col0]) + (HAS_BIAS ? float(bias[col0]) : 0.0f);
306
+ float x1 = float(qkv[row_base + col1]) + (HAS_BIAS ? float(bias[col1]) : 0.0f);
307
+ uint o_base = BHD ? ((hv * T_len + t) * D) : ((t * HKV + hv) * D);
308
+ v_out[o_base + d0] = T(x0);
309
+ v_out[o_base + d1] = T(x1);
310
+ }
311
+ """
312
+
313
+ _KV_ROPE_SRC = r"""
314
+ uint d = thread_position_in_grid.x;
315
+ uint h = thread_position_in_grid.y;
316
+ uint t = thread_position_in_grid.z;
317
+ uint half_d = D / 2;
318
+ uint T_len = uint(kv_shape[0]);
319
+ if (d >= half_d || t >= T_len) return;
320
+
321
+ uint stride_in = (2 * HKV) * D;
322
+ uint col0 = h * D + (TRAD ? (2 * d) : d);
323
+ uint col1 = h * D + (TRAD ? (2 * d + 1) : (d + half_d));
324
+ uint d0 = TRAD ? (2 * d) : d;
325
+ uint d1 = TRAD ? (2 * d + 1) : (d + half_d);
326
+
327
+ float x0 = float(kv[t * stride_in + col0]) + (HAS_BIAS ? float(bias[col0]) : 0.0f);
328
+ float x1 = float(kv[t * stride_in + col1]) + (HAS_BIAS ? float(bias[col1]) : 0.0f);
329
+
330
+ if (h < HKV) {
331
+ float angle = float(pos[t]) * inv_freq[d];
332
+ float s, c;
333
+ s = metal::sincos(angle, c);
334
+ uint o_base = BHD ? ((h * T_len + t) * D) : ((t * HKV + h) * D);
335
+ k_out[o_base + d0] = T(x0 * c - x1 * s);
336
+ k_out[o_base + d1] = T(x0 * s + x1 * c);
337
+ } else {
338
+ uint hv = h - HKV;
339
+ uint o_base = BHD ? ((hv * T_len + t) * D) : ((t * HKV + hv) * D);
340
+ v_out[o_base + d0] = T(x0);
341
+ v_out[o_base + d1] = T(x1);
342
+ }
343
+ """
344
+
345
+ _Q_ROPE_SRC = r"""
346
+ uint d = thread_position_in_grid.x;
347
+ uint h = thread_position_in_grid.y;
348
+ uint t = thread_position_in_grid.z;
349
+ uint half_d = D / 2;
350
+ uint R_len = uint(q_in_shape[0]);
351
+ if (d >= half_d || t >= R_len) return;
352
+
353
+ uint col0 = h * D + (TRAD ? (2 * d) : d);
354
+ uint col1 = h * D + (TRAD ? (2 * d + 1) : (d + half_d));
355
+ uint d0 = TRAD ? (2 * d) : d;
356
+ uint d1 = TRAD ? (2 * d + 1) : (d + half_d);
357
+
358
+ float x0 = float(q_in[t * (H * D) + col0]) + (HAS_BIAS ? float(bias[col0]) : 0.0f);
359
+ float x1 = float(q_in[t * (H * D) + col1]) + (HAS_BIAS ? float(bias[col1]) : 0.0f);
360
+ float angle = float(pos[t]) * inv_freq[d];
361
+ float s, c;
362
+ s = metal::sincos(angle, c);
363
+ uint o_base = BHD ? ((h * R_len + t) * D) : ((t * H + h) * D);
364
+ q_out[o_base + d0] = T(x0 * c - x1 * s);
365
+ q_out[o_base + d1] = T(x0 * s + x1 * c);
366
+ """
367
+
368
+
369
+ @lru_cache(maxsize=4)
370
+ def _qkv_rope_kernel():
371
+ return mx.fast.metal_kernel(
372
+ name="basal_qkv_rope",
373
+ input_names=["qkv", "bias", "pos", "inv_freq"],
374
+ output_names=["q_out", "k_out", "v_out"],
375
+ source=_QKV_ROPE_SRC,
376
+ ensure_row_contiguous=True,
377
+ compile_options={"math_mode": "safe"},
378
+ )
379
+
380
+
381
+ @lru_cache(maxsize=4)
382
+ def _kv_rope_kernel():
383
+ return mx.fast.metal_kernel(
384
+ name="basal_kv_rope",
385
+ input_names=["kv", "bias", "pos", "inv_freq"],
386
+ output_names=["k_out", "v_out"],
387
+ source=_KV_ROPE_SRC,
388
+ ensure_row_contiguous=True,
389
+ compile_options={"math_mode": "safe"},
390
+ )
391
+
392
+
393
+ @lru_cache(maxsize=4)
394
+ def _q_rope_kernel():
395
+ return mx.fast.metal_kernel(
396
+ name="basal_q_rope",
397
+ input_names=["q_in", "bias", "pos", "inv_freq"],
398
+ output_names=["q_out"],
399
+ source=_Q_ROPE_SRC,
400
+ ensure_row_contiguous=True,
401
+ compile_options={"math_mode": "safe"},
402
+ )
403
+
404
+
405
+ def rope_inv_freq(rope) -> tuple[mx.array, bool]:
406
+ """Extract float32 `inv_freq` [D/2] and `traditional` bool from an mlx-lm RoPE module.
407
+
408
+ Supports `nn.RoPE` (default/linear) and `Llama3RoPE` (which stores `_freqs` = periods).
409
+ Returns `(inv_freq, traditional)` where `angle = pos * inv_freq[d]`.
410
+ """
411
+ from mlx_lm.models.rope_utils import Llama3RoPE
412
+
413
+ if hasattr(rope, "rope"): # unwrap PositionRoPE if wrapped
414
+ rope = rope.rope
415
+ trad = bool(getattr(rope, "traditional", False))
416
+ if isinstance(rope, Llama3RoPE):
417
+ # Llama3RoPE passes `freqs=self._freqs` to mx.fast.rope, where theta = pos / freqs[d].
418
+ inv = (1.0 / rope._freqs.astype(mx.float32))
419
+ mx.eval(inv)
420
+ return inv, trad
421
+ if isinstance(rope, nn.RoPE):
422
+ dims = int(rope.dims)
423
+ base = float(rope.base)
424
+ scale = float(rope.scale)
425
+ idx = mx.arange(0, dims, 2, dtype=mx.float32)
426
+ inv = scale * (base ** (-idx / float(dims)))
427
+ mx.eval(inv)
428
+ return inv, trad
429
+ raise TypeError(f"unsupported RoPE for Metal kernels: {type(rope).__name__}")
430
+
431
+
432
+ def qkv_rope(
433
+ qkv: mx.array,
434
+ pos: mx.array,
435
+ inv_freq: mx.array,
436
+ H: int,
437
+ Hkv: int,
438
+ D: int,
439
+ traditional: bool = False,
440
+ bias: mx.array | None = None,
441
+ bhd: bool = False,
442
+ ):
443
+ """Split merged qkv `[T, (H + 2*Hkv)*D]` (+ optional bias) and apply RoPE (1 sincos per (t, d)).
444
+
445
+ Returns NHD `(q[T,H,D], k[T,Hkv,D], v[T,Hkv,D])` or BHD `(q[1,H,T,D], k[1,Hkv,T,D], v[1,Hkv,T,D])`.
446
+ """
447
+ T = qkv.shape[0]
448
+ half_d = D // 2
449
+ tg_x = min(half_d, 64)
450
+ tg_y = max(1, min(T, 256 // tg_x))
451
+ has_bias = bias is not None
452
+ b = bias if has_bias else _dummy_bias(qkv.dtype)
453
+ shapes = [(1, H, T, D), (1, Hkv, T, D), (1, Hkv, T, D)] if bhd else [(T, H, D), (T, Hkv, D), (T, Hkv, D)]
454
+ q, k, v = _qkv_rope_kernel()(
455
+ inputs=[qkv, b, pos.astype(mx.int32), inv_freq],
456
+ template=[
457
+ ("T", qkv.dtype),
458
+ ("H", H),
459
+ ("HKV", Hkv),
460
+ ("D", D),
461
+ ("TRAD", int(traditional)),
462
+ ("HAS_BIAS", int(has_bias)),
463
+ ("BHD", int(bhd)),
464
+ ],
465
+ grid=(half_d, T, 1),
466
+ threadgroup=(tg_x, tg_y, 1),
467
+ output_shapes=shapes,
468
+ output_dtypes=[qkv.dtype, qkv.dtype, qkv.dtype],
469
+ )
470
+ return q, k, v
471
+
472
+
473
+ def kv_rope(
474
+ kv: mx.array,
475
+ pos: mx.array,
476
+ inv_freq: mx.array,
477
+ Hkv: int,
478
+ D: int,
479
+ traditional: bool = False,
480
+ bias: mx.array | None = None,
481
+ bhd: bool = False,
482
+ ):
483
+ """Split merged kv `[T, 2*Hkv*D]` (+ optional bias) and apply RoPE to K -> NHD or BHD `(k, v)`."""
484
+ T = kv.shape[0]
485
+ half_d = D // 2
486
+ tot_h = 2 * Hkv
487
+ tg_x = min(half_d, 64)
488
+ tg_y = max(1, min(tot_h, 256 // tg_x))
489
+ has_bias = bias is not None
490
+ b = bias if has_bias else _dummy_bias(kv.dtype)
491
+ shapes = [(1, Hkv, T, D), (1, Hkv, T, D)] if bhd else [(T, Hkv, D), (T, Hkv, D)]
492
+ k, v = _kv_rope_kernel()(
493
+ inputs=[kv, b, pos.astype(mx.int32), inv_freq],
494
+ template=[
495
+ ("T", kv.dtype),
496
+ ("HKV", Hkv),
497
+ ("D", D),
498
+ ("TRAD", int(traditional)),
499
+ ("HAS_BIAS", int(has_bias)),
500
+ ("BHD", int(bhd)),
501
+ ],
502
+ grid=(half_d, tot_h, T),
503
+ threadgroup=(tg_x, tg_y, 1),
504
+ output_shapes=shapes,
505
+ output_dtypes=[kv.dtype, kv.dtype],
506
+ )
507
+ return k, v
508
+
509
+
510
+ def q_rope(
511
+ q_in: mx.array,
512
+ pos: mx.array,
513
+ inv_freq: mx.array,
514
+ H: int,
515
+ D: int,
516
+ traditional: bool = False,
517
+ bias: mx.array | None = None,
518
+ bhd: bool = False,
519
+ ):
520
+ """Reshape & apply RoPE (+ optional bias) to q_in `[R, H*D]` -> NHD `[R,H,D]` or BHD `[1,H,R,D]`."""
521
+ R = q_in.shape[0]
522
+ half_d = D // 2
523
+ tg_x = min(half_d, 64)
524
+ tg_y = max(1, min(H, 256 // tg_x))
525
+ has_bias = bias is not None
526
+ b = bias if has_bias else _dummy_bias(q_in.dtype)
527
+ shape = (1, H, R, D) if bhd else (R, H, D)
528
+ (q,) = _q_rope_kernel()(
529
+ inputs=[q_in.reshape(R, H * D), b, pos.astype(mx.int32), inv_freq],
530
+ template=[
531
+ ("T", q_in.dtype),
532
+ ("H", H),
533
+ ("D", D),
534
+ ("TRAD", int(traditional)),
535
+ ("HAS_BIAS", int(has_bias)),
536
+ ("BHD", int(bhd)),
537
+ ],
538
+ grid=(half_d, H, R),
539
+ threadgroup=(tg_x, tg_y, 1),
540
+ output_shapes=[shape],
541
+ output_dtypes=[q_in.dtype],
542
+ )
543
+ return q