mlx-bun 0.0.9 → 0.0.11

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 (179) hide show
  1. package/README.md +66 -21
  2. package/THIRD_PARTY_LICENSES.md +1 -0
  3. package/docs/archive/mlx-bun-lab-report.html +275 -0
  4. package/docs/archive/wwdc-mlx-bun.html +848 -0
  5. package/docs/design/audio-input-plan.md +356 -0
  6. package/docs/design/batching-perf-path.md +255 -0
  7. package/docs/design/batching-v2-plan.md +23 -9
  8. package/docs/design/bucketing-stage.md +2 -1
  9. package/docs/design/compat-cli-surface-design.md +4 -3
  10. package/docs/design/decode-speed-program.md +172 -0
  11. package/docs/design/docs-reorg-plan.md +1 -1
  12. package/docs/design/dspark-serving-program.md +371 -0
  13. package/docs/design/dspark-speculative-decoding.md +167 -5
  14. package/docs/design/faithful-l1-consolidation.md +310 -0
  15. package/docs/design/generic-model-support.md +8 -5
  16. package/docs/design/grammar-spec-batching-integration.md +301 -0
  17. package/docs/design/minicpm5-decode-megakernel.md +16 -11
  18. package/docs/design/mlx-lm-tool-parity-plan.md +11 -1
  19. package/docs/design/omlx-adoption-map.md +98 -0
  20. package/docs/design/orpo-training.md +34 -30
  21. package/docs/design/paged-kv-cache.md +214 -0
  22. package/docs/design/parallel-slots.md +82 -49
  23. package/docs/design/parity-tier-dag.md +43 -33
  24. package/docs/design/repo-cleanup-plan.md +189 -0
  25. package/docs/design/runtime-isolation.md +19 -3
  26. package/docs/design/segmented-backward-training.md +18 -2
  27. package/docs/design/ssd-kv-cold-tier.md +288 -0
  28. package/docs/design/structured-output.md +484 -0
  29. package/docs/design/the-dreaming-master-plan.md +2 -3
  30. package/docs/design/turboquant-kv.md +235 -0
  31. package/docs/design/unified-engine-frontier-plan.md +774 -0
  32. package/docs/design/web-chat-beat-matrix.md +315 -0
  33. package/docs/design/web-chat-redesign.md +1112 -0
  34. package/docs/investigations/decode-roofline-lookagain.md +92 -6
  35. package/docs/investigations/dspark-handoff.md +182 -16
  36. package/docs/investigations/kernel-perf-review-2026-07.md +105 -26
  37. package/docs/investigations/lab-build-journal.md +2 -2
  38. package/docs/investigations/openwiki-evaluation.md +249 -0
  39. package/docs/planning/IDEAS.md +14 -0
  40. package/docs/planning/PRODUCT_ROADMAP.md +2 -3
  41. package/docs/planning/chat-ui-vision-memory-first.md +199 -0
  42. package/docs/planning/chat-ui-vision.md +50 -0
  43. package/docs/planning/memory-docs-and-dag-plan.md +15 -6
  44. package/docs/planning/release-notes-v0.0.10.md +57 -0
  45. package/docs/planning/release-notes-v0.0.11.md +239 -0
  46. package/docs/reference/cli.md +35 -16
  47. package/docs/reference/distribution.md +13 -6
  48. package/docs/reference/embedding.md +35 -14
  49. package/docs/reference/features-matrix.md +97 -0
  50. package/docs/reference/library-api.md +30 -9
  51. package/docs/reference/memory.md +26 -6
  52. package/docs/reference/models.md +11 -1
  53. package/docs/reference/orpo-quickstart.md +3 -4
  54. package/docs/reference/server-api.md +634 -22
  55. package/docs/reference/server-config.md +251 -119
  56. package/docs/reference/training.md +20 -16
  57. package/package.json +5 -3
  58. package/src/anthropic.ts +13 -0
  59. package/src/audio/conformer.ts +647 -0
  60. package/src/audio/decode.ts +133 -0
  61. package/src/audio/features.ts +202 -0
  62. package/src/audio/transcode.ts +67 -0
  63. package/src/cli.ts +402 -107
  64. package/src/config.ts +49 -2
  65. package/src/download.ts +40 -0
  66. package/src/eval/README.md +7 -6
  67. package/src/eval/kl.ts +59 -3
  68. package/src/eval/quality-db.ts +2 -2
  69. package/src/eval/runner.ts +3 -3
  70. package/src/expert-offload.ts +15 -2
  71. package/src/flags.ts +13 -0
  72. package/src/generate.ts +330 -16
  73. package/src/grammar.ts +585 -0
  74. package/src/hub-rest.ts +242 -0
  75. package/src/kv-store.ts +618 -122
  76. package/src/lora.ts +8 -0
  77. package/src/md-modules.d.ts +42 -0
  78. package/src/media-fetch.ts +284 -0
  79. package/src/memory/rest.ts +245 -0
  80. package/src/memory/vault.ts +74 -0
  81. package/src/mlx/array.ts +127 -19
  82. package/src/mlx/autograd.ts +2 -2
  83. package/src/mlx/ffi.ts +27 -3
  84. package/src/mlx/metal-kernel.ts +7 -4
  85. package/src/mlx/ops.ts +179 -23
  86. package/src/mlx/turboquant-ops.ts +831 -0
  87. package/src/mlx/turboquant-tables.ts +237 -0
  88. package/src/model/batched-mask.ts +62 -1
  89. package/src/model/batched-quant.ts +206 -0
  90. package/src/model/batched-rotating-quant.ts +346 -0
  91. package/src/model/batched-rotating.ts +46 -1
  92. package/src/model/compiled-decode.ts +4 -15
  93. package/src/model/factory.ts +10 -4
  94. package/src/model/gemma4-base.ts +391 -34
  95. package/src/model/gemma4.ts +122 -33
  96. package/src/model/generated/gemma4-12b.ts +9 -13
  97. package/src/model/generated/gemma4-26b.ts +10 -5
  98. package/src/model/generated/gemma4-e4b.ts +14 -9
  99. package/src/model/minicpm5.ts +58 -102
  100. package/src/model/paged-kv.ts +253 -0
  101. package/src/model/qwen3-delta.ts +123 -15
  102. package/src/model/qwen3-moe.ts +404 -0
  103. package/src/model/qwen3.ts +9 -8
  104. package/src/model/qwen3_5.ts +99 -25
  105. package/src/model/support.ts +12 -1
  106. package/src/model/universal/dense.ts +40 -5
  107. package/src/model/universal/rope.ts +36 -21
  108. package/src/pi-web.ts +1299 -82
  109. package/src/preflight.ts +27 -8
  110. package/src/prompt-cache.ts +338 -32
  111. package/src/quantize/quantizer.ts +16 -1
  112. package/src/registry.ts +61 -3
  113. package/src/serve/batch-scheduler.ts +1001 -76
  114. package/src/serve/generation-gateway.ts +292 -30
  115. package/src/serve/isolate.ts +417 -0
  116. package/src/serve/lane-registry.ts +44 -0
  117. package/src/serve/session-search.ts +326 -0
  118. package/src/server.ts +1460 -105
  119. package/src/spec/assistant-source.ts +150 -0
  120. package/src/spec/deepspec-source.ts +143 -0
  121. package/src/spec/dflash-source.ts +124 -0
  122. package/src/spec/dspark/ab-stats.ts +136 -0
  123. package/src/spec/dspark/calibration.ts +112 -0
  124. package/src/spec/dspark/deepspec-module.ts +801 -0
  125. package/src/spec/dspark/generate-dflash.ts +72 -20
  126. package/src/spec/dspark/loader.ts +23 -0
  127. package/src/spec/dspark/module-dflash.ts +278 -36
  128. package/src/spec/dspark/quantize-drafter.ts +91 -0
  129. package/src/spec/generate.ts +59 -25
  130. package/src/spec/ngram-source.ts +132 -0
  131. package/src/spec/serve-loop.ts +536 -0
  132. package/src/spec/source.ts +93 -0
  133. package/src/spec/two-model.ts +171 -0
  134. package/src/ssd-cache.ts +285 -0
  135. package/src/tokenizer.ts +288 -2
  136. package/src/tool-approvals.ts +131 -0
  137. package/src/tool-call.ts +408 -20
  138. package/src/train/flash-cce.ts +29 -26
  139. package/src/train/job.ts +0 -2
  140. package/src/train/loss.ts +53 -11
  141. package/src/train/prefix-shared.ts +30 -7
  142. package/src/train/segmented.ts +150 -46
  143. package/src/train/trainer.ts +22 -15
  144. package/src/vision/prompt.ts +217 -48
  145. package/src/web/app.html +1184 -1789
  146. package/src/web/app.js +5667 -0
  147. package/src/web/icon.svg +13 -0
  148. package/src/web/manifest.webmanifest +24 -0
  149. package/src/web/src/adapters-panel.ts +288 -0
  150. package/src/web/src/api.ts +57 -0
  151. package/src/web/src/assistant.ts +485 -0
  152. package/src/web/src/chat.ts +1050 -0
  153. package/src/web/src/composer.ts +959 -0
  154. package/src/web/src/dataset.ts +132 -0
  155. package/src/web/src/finetune.ts +267 -0
  156. package/src/web/src/hub.ts +428 -0
  157. package/src/web/src/main.ts +98 -0
  158. package/src/web/src/markdown.ts +0 -0
  159. package/src/web/src/memory-panel.ts +572 -0
  160. package/src/web/src/model-picker.ts +159 -0
  161. package/src/web/src/palette.ts +346 -0
  162. package/src/web/src/protocol.ts +62 -0
  163. package/src/web/src/quantize.ts +167 -0
  164. package/src/web/src/rag.ts +274 -0
  165. package/src/web/src/sessions.ts +469 -0
  166. package/src/web/src/shell.ts +804 -0
  167. package/src/web/src/status.ts +252 -0
  168. package/src/web/src/ui-catalog.ts +92 -0
  169. package/src/web/sw.js +71 -0
  170. package/src/web/vendor/README.md +61 -0
  171. package/src/web/vendor/hljs-LICENSE +29 -0
  172. package/src/web/vendor/hljs-theme.css +59 -0
  173. package/src/web/vendor/hljs.js +26 -0
  174. package/src/model/fused-decode-kernel.ts +0 -312
  175. package/src/model/fused-geglu-kernel.ts +0 -198
  176. package/src/model/fused-mlp-kernel.ts +0 -169
  177. package/src/model/fused-swiglu-kernel.ts +0 -240
  178. package/src/model/steel-linear-kernel.ts +0 -96
  179. package/src/status-page.html +0 -497
@@ -1,198 +0,0 @@
1
- // Fused GeGLU Metal kernel (optimization_plan Phase E, opportunity B/C):
2
- // gelu_approx(a)·b in ONE pass, replacing the ~9 element-wise kernels the
3
- // spelled-out path emits (power, ×3, +, ×, tanh, +, ×, × + a final mul).
4
- // Both GeGLU sites are this shape — MLP (gelu(gate)·up) and the e4b
5
- // per-layer gate (gelu(gate)·pli).
6
- //
7
- // MATCH-COMPAT precision: bf16 in/out, each intermediate rounded to bf16
8
- // op-for-op with the spelled-out path (the mlx-lm parity constraint). A
9
- // first full-f32 version drifted 0.22 KL on e4b (small per-element error
10
- // compounding over 42 MLPs) — match-compat keeps the distribution on the
11
- // trained path; the only residual is the pow/tanh math-lib difference, which
12
- // the KL gate quantifies. Still a perf kernel (not bit-exact) and never
13
- // inside a compiled-decode trace: CustomKernel has no output_shapes (same
14
- // rule as fusedDecodeSdpa) — the caller guards on !isCompiledTrace().
15
-
16
- import { MlxArray } from "../mlx/array";
17
- import { Dtype } from "../mlx/ffi";
18
- import { MetalKernel } from "../mlx/metal-kernel";
19
- import { CustomVjp } from "../mlx/custom-vjp";
20
- import * as ops from "../mlx/ops";
21
-
22
- /** ON by default: the match-compat kernel is BIT-EXACT with the spelled-out
23
- * path (kl --decode = 0 on e4b), so per the bit-parity-floor principle it
24
- * ships on — every optimization we can keep while staying bit-exact.
25
- * MLX_BUN_FUSED_GELU=0 opts out (e.g. the compile arm of the A/B). */
26
- export function fusedGeluEnabled(): boolean {
27
- return process.env.MLX_BUN_FUSED_GELU !== "0";
28
- }
29
-
30
- /** Dispatch counter (a gate test asserts the kernel actually ran). */
31
- export let fusedGeluCalls = 0;
32
-
33
- // Training-mode flag: when set, model GeGLU sites use the DIFFERENTIABLE wrapper
34
- // (Metal-kernel forward + hand-derived vjp) instead of the plain `fusedGeglu`
35
- // (a bare CustomKernel with no vjp — feeding it to autograd throws
36
- // "[Primitive::vjp] Not implemented for CustomKernel"). The differentiable
37
- // wrapper also recomputes the gelu in the backward from the primal `a` instead
38
- // of retaining the ~9 forward intermediates, so it lowers the MLP activation
39
- // memory the backward holds — the dominant resident at long context under
40
- // ops.sdpa (which never materializes the O(T²) scores). Set by the trainer
41
- // around the train loop; cleared in its finally. Off → inference behaviour
42
- // (plain `fusedGeglu`) is byte-for-byte unchanged.
43
- let _trainingGeglu = false;
44
- export function setFusedGeluTraining(on: boolean): void {
45
- _trainingGeglu = on;
46
- }
47
- export function fusedGeluTraining(): boolean {
48
- return _trainingGeglu;
49
- }
50
-
51
- // Pointwise: one thread per element. gelu_approx =
52
- // 0.5 x (1 + tanh(√(2/π)·(x + 0.044715 x³))) — composed in f32.
53
- const SOURCE = String.raw`
54
- const uint i = thread_position_in_grid.x;
55
- if (i >= SIZE) return;
56
- // Match-compat: round each intermediate (and the weak scalars) to T, op
57
- // for op with the spelled-out bf16 path, so the fused distribution tracks
58
- // the TRAINED path rather than drifting to "more accurate but different".
59
- // x^3 via pow (the reference uses mx.power, NOT x*x*x — they round
60
- // differently in bf16). The single remaining residual vs compat is the
61
- // pow/tanh math-lib difference, which the KL gate quantifies.
62
- const float C_CUBE = float(T(0.044715f));
63
- const float C_SQRT = float(T(0.7978845608028654f)); // √(2/π)
64
- const float C_HALF = float(T(0.5f));
65
- const float x = float(a[i]);
66
- const float x3 = float(T(metal::pow(x, 3.0f)));
67
- const float cx3 = float(T(x3 * C_CUBE));
68
- const float inn = float(T(x + cx3));
69
- const float scl = float(T(inn * C_SQRT));
70
- const float tnh = float(T(metal::precise::tanh(scl)));
71
- const float t1 = float(T(1.0f + tnh));
72
- const float hx = float(T(x * C_HALF));
73
- const float g = float(T(hx * t1));
74
- out[i] = T(g * float(b[i]));
75
- `;
76
-
77
- let kernel: MetalKernel | null = null;
78
- function getKernel(): MetalKernel {
79
- if (!kernel)
80
- kernel = new MetalKernel({
81
- name: "mlx_bun_fused_geglu",
82
- inputNames: ["a", "b"],
83
- outputNames: ["out"],
84
- source: SOURCE,
85
- ensureRowContiguous: true,
86
- });
87
- return kernel;
88
- }
89
-
90
- /** bf16/f16 only (the activation dtype the kernel reads/writes). */
91
- export function fusedGeluSupported(a: MlxArray): boolean {
92
- return a.dtype === Dtype.bfloat16 || a.dtype === Dtype.float16;
93
- }
94
-
95
- /** gelu_approx(a) · b, fused. a and b must share shape/dtype; out is a.dtype. */
96
- export function fusedGeglu(a: MlxArray, b: MlxArray): MlxArray {
97
- fusedGeluCalls++;
98
- const size = a.shape.reduce((x, y) => x * y, 1);
99
- const [out] = getKernel().apply([a, b], {
100
- outputs: [{ shape: a.shape, dtype: a.dtype }],
101
- grid: [size, 1, 1],
102
- threadGroup: [Math.min(size, 256), 1, 1],
103
- templateInts: { SIZE: size },
104
- templateDtypes: { T: a.dtype },
105
- });
106
- return out!;
107
- }
108
-
109
- // ---------------------------------------------------------------------------
110
- // Differentiable wrapper: Metal kernel forward + pure-MLX backward
111
- // ---------------------------------------------------------------------------
112
-
113
- // GELU tanh-approx constants
114
- const SQRT_2_PI = 0.7978845608028654;
115
- const C_CUBE = 0.044715;
116
-
117
- /** Compute gelu_approx(a) = 0.5 * a * (1 + tanh(sqrt(2/pi) * (a + 0.044715*a^3)))
118
- * and gelu'(a) using the MLX ops layer. All intermediates are disposed
119
- * before returning; caller owns the two returned arrays. */
120
- function geluAndGrad(a: MlxArray): { gelu: MlxArray; geluGrad: MlxArray } {
121
- // a^3 = a * a * a
122
- const a2 = ops.mul(a, a);
123
- const a3 = ops.mul(a2, a);
124
- // inner = a + 0.044715 * a^3
125
- const cx3 = ops.mulScalar(a3, C_CUBE);
126
- const inner = ops.add(a, cx3);
127
- // z = sqrt(2/pi) * inner
128
- const z = ops.mulScalar(inner, SQRT_2_PI);
129
- // t = tanh(z)
130
- const t = ops.tanh(z);
131
- // gelu = 0.5 * a * (1 + t)
132
- const one = ops.scalarLike(1, a);
133
- const t1 = ops.add(one, t);
134
- const halfA = ops.mulScalar(a, 0.5);
135
- const gelu = ops.mul(halfA, t1);
136
-
137
- // gelu'(a) = 0.5*(1+t) + 0.5*a*(1-t^2)*dz/da
138
- // dz/da = sqrt(2/pi) * (1 + 3*0.044715*a^2)
139
- // 1 - t^2 = sech^2(z)
140
- const halfT1 = ops.mulScalar(t1, 0.5); // 0.5*(1+t)
141
- const t2 = ops.mul(t, t); // t^2
142
- const sech2 = ops.sub(one, t2); // 1 - t^2
143
- const halfASech2 = ops.mul(halfA, sech2); // 0.5*a*(1-t^2)
144
- // dz/da
145
- const a2scaled = ops.mulScalar(a2, 3 * C_CUBE); // 3*0.044715*a^2
146
- const dzda = ops.add(one, a2scaled); // 1 + 3*0.044715*a^2
147
- const dzdaScaled = ops.mulScalar(dzda, SQRT_2_PI);// sqrt(2/pi)*dz_unnorm
148
- // chain: 0.5*a*(1-t^2)*dz/da
149
- const chainTerm = ops.mul(halfASech2, dzdaScaled);
150
- const geluGrad = ops.add(halfT1, chainTerm); // 0.5*(1+t) + chain
151
-
152
- // dispose all intermediates
153
- for (const arr of [a2, a3, cx3, inner, z, t, one, t1, halfA, halfT1, t2, sech2,
154
- halfASech2, a2scaled, dzda, dzdaScaled, chainTerm]) {
155
- arr.dispose();
156
- }
157
-
158
- return { gelu, geluGrad };
159
- }
160
-
161
- let _differentiableKernel: CustomVjp | null = null;
162
-
163
- function getDifferentiableKernel(): CustomVjp {
164
- if (!_differentiableKernel) {
165
- _differentiableKernel = new CustomVjp(
166
- // forward: use the Metal kernel
167
- ([a, b]: MlxArray[]) => [fusedGeglu(a!, b!)],
168
- // backward
169
- (primals: MlxArray[], cotangents: MlxArray[], _outputs: MlxArray[]) => {
170
- const [a, b] = primals as [MlxArray, MlxArray];
171
- const [dc] = cotangents as [MlxArray];
172
-
173
- const { gelu, geluGrad } = geluAndGrad(a);
174
-
175
- // grad_b = dc * gelu(a)
176
- const grad_b = ops.mul(dc, gelu);
177
-
178
- // grad_a = dc * b * gelu'(a)
179
- const dcb = ops.mul(dc, b);
180
- const grad_a = ops.mul(dcb, geluGrad);
181
-
182
- gelu.dispose();
183
- geluGrad.dispose();
184
- dcb.dispose();
185
-
186
- return [grad_a, grad_b];
187
- },
188
- );
189
- }
190
- return _differentiableKernel;
191
- }
192
-
193
- /** gelu_approx(a) · b with a hand-derived vjp. Uses the Metal kernel forward,
194
- * MLX-ops backward. For training only (inference uses the non-differentiable
195
- * fusedGeglu). */
196
- export function fusedGegluDifferentiable(a: MlxArray, b: MlxArray): MlxArray {
197
- return getDifferentiableKernel().apply([a, b])[0]!;
198
- }
@@ -1,169 +0,0 @@
1
- // The WHOLE MLP in ONE dispatch — down = (silu(x·Wgᵀ)·(x·Wuᵀ)) · Wdownᵀ — with no
2
- // intermediate `hidden` ever exposed to MLX. MLX runs this one kernel; there is no
3
- // boundary between our kernels for its planner to alias (the corruption only lives
4
- // at those boundaries). Built from the steel building blocks in steel-qmm-header.ts,
5
- // structured like the flash-CCE backward: each threadgroup owns one (M-block,I-block),
6
- // computes silu·up for that I-block ONCE (no recompute), then atomic-accumulates its
7
- // contribution to every down output — exactly how flash-CCE BWD atomic-adds dh.
8
- //
9
- // grid = (TGN, I/BI, M/BM); each tg: i-block i0 = tid.y*BI, m-block m0 = tid.z*BM
10
- // phase A: gate/up [BM,BI] = x[BM,H] @ {Wg,Wu}[i0,H]ᵀ (reduce H) → silu·up = Hs[BM,BI]
11
- // phase B: for each Ho-block no: D[BM,BN] = Hs @ Wdown[no,i0]ᵀ; atomic-add D → y[M,Ho]
12
- //
13
- // Per-weight quant constants (gate/up/down) are baked literals; H/I/Ho are templateInts;
14
- // M from x_shape. Output is f32 (atomic accumulation); the caller casts to the model
15
- // dtype at the MLP boundary. L3 (atomic-add ordering + bf16-rounded silu); gated by
16
- // teacher-forced KL like the rest of the controlled path.
17
-
18
- import { MlxArray } from "../mlx/array";
19
- import { Dtype } from "../mlx/ffi";
20
- import { MetalKernel } from "../mlx/metal-kernel";
21
- import { STEEL_QMM_HEADER } from "../train/steel-qmm-header";
22
- import * as ops from "../mlx/ops";
23
- import type { QuantSpec } from "../mlx/ops";
24
-
25
- const BM = 32, BN = 32, BK = 32, WM = 2, WN = 2;
26
- const TGN = WM * WN * 32; // 128 threads / threadgroup
27
-
28
- const SOURCE = String.raw`
29
- const uint M=x_shape[0];
30
- constexpr int I=I_T, H=H_T, Ho=HO_T;
31
- constexpr int gsG=GS_G,btsG=BITS_G, gsU=GS_U,btsU=BITS_U, gsD=GS_D,btsD=BITS_D;
32
- constexpr int pfG=get_pack_factor<btsG,8>(), bppG=get_bytes_per_pack<btsG>();
33
- constexpr int pfU=get_pack_factor<btsU,8>(), bppU=get_bytes_per_pack<btsU>();
34
- constexpr int pfD=get_pack_factor<btsD,8>(), bppD=get_bytes_per_pack<btsD>();
35
- constexpr int BKp=BK_T+16/sizeof(T);
36
- threadgroup T Xs[BM_T*BKp];
37
- threadgroup T Wgs[BN_T*BKp];
38
- threadgroup T Wus[BN_T*BKp];
39
- threadgroup T Lg[BM_T*BN_T];
40
- threadgroup T Lu[BM_T*BN_T];
41
- threadgroup T Hs[BM_T*BKp]; // silu·up for this I-block, padded leading dim BKp
42
- threadgroup T Wds[BN_T*BKp]; // a down-weight [BN, BI] tile
43
- using gu_mma=mlx::steel::BlockMMA<T,T,BM_T,BN_T,BK_T,WM_T,WN_T,false,true,BKp,BKp>;
44
- using lx_t =mlx::steel::BlockLoader<T,BM_T,BK_T,BKp,1,WM_T*WN_T*SIMD_SIZE>;
45
- using lwg_t =QuantizedBlockLoader<T,BN_T,BK_T,BKp,1,WM_T*WN_T*SIMD_SIZE,gsG,btsG>;
46
- using lwu_t =QuantizedBlockLoader<T,BN_T,BK_T,BKp,1,WM_T*WN_T*SIMD_SIZE,gsU,btsU>;
47
- using d_mma =mlx::steel::BlockMMA<T,T,BM_T,BN_T,BK_T,WM_T,WN_T,false,true,BKp,BKp>;
48
- using lwd_t =QuantizedBlockLoader<T,BN_T,BK_T,BKp,1,WM_T*WN_T*SIMD_SIZE,gsD,btsD>;
49
- const uint sg=simdgroup_index_in_threadgroup, sl=thread_index_in_simdgroup;
50
- const uint lid=thread_position_in_threadgroup.x;
51
- const int Hh=(int)H;
52
- const int KwG=Hh*bppG/pfG, KgG=Hh/gsG;
53
- const int KwU=Hh*bppU/pfU, KgU=Hh/gsU;
54
- const int KwD=I*bppD/pfD, KgD=I/gsD; // down weight rows are length I
55
- const int m0=(int)threadgroup_position_in_grid.z*BM_T;
56
- const int i0=(int)threadgroup_position_in_grid.y*BN_T;
57
- const short num_els=(short)min(BM_T,(int)M-m0);
58
-
59
- // ---- Phase A: hidden[BM,BI] = silu(x@Wg[i0]ᵀ)·(x@Wu[i0]ᵀ), reduce over H ----
60
- gu_mma mg(sg,sl), mu(sg,sl);
61
- lx_t lx (x + (int64_t)m0*Hh, Hh, Xs, sg, sl);
62
- lwg_t lwg((const device uint8_t*)wg + (int64_t)i0*KwG, sg_w + (int64_t)i0*KgG, bg_w + (int64_t)i0*KgG, Hh, Wgs, sg, sl);
63
- lwu_t lwu((const device uint8_t*)wu + (int64_t)i0*KwU, su_w + (int64_t)i0*KgU, bu_w + (int64_t)i0*KgU, Hh, Wus, sg, sl);
64
- for (int k=0;k<Hh;k+=BK_T){
65
- threadgroup_barrier(mem_flags::mem_threadgroup);
66
- if (num_els<BM_T) lx.load_safe(short2(BK_T,num_els)); else lx.load_unsafe();
67
- lwg.load_unsafe(); lwu.load_unsafe();
68
- threadgroup_barrier(mem_flags::mem_threadgroup);
69
- mg.mma(Xs,Wgs); mu.mma(Xs,Wus);
70
- lx.next(); lwg.next(); lwu.next();
71
- }
72
- threadgroup_barrier(mem_flags::mem_threadgroup);
73
- mg.Ctile.template store<T,WM_T,WN_T,BN_T,1>(Lg + mg.sm*BN_T + mg.sn);
74
- threadgroup_barrier(mem_flags::mem_threadgroup);
75
- mu.Ctile.template store<T,WM_T,WN_T,BN_T,1>(Lu + mu.sm*BN_T + mu.sn);
76
- threadgroup_barrier(mem_flags::mem_threadgroup);
77
- // silu·up into Hs (padded BKp leading dim, so the phase-B BlockMMA can read it as A)
78
- for (uint idx=lid; idx<(uint)(BM_T*BN_T); idx+=TGN_T){
79
- int r=(int)idx/BN_T, c=(int)idx%BN_T;
80
- T gT=Lg[idx], uT=Lu[idx];
81
- T sigT=(T)(1.0f/(1.0f+metal::precise::exp(-(float)gT)));
82
- T siluT=(T)((float)gT*(float)sigT);
83
- Hs[r*BKp + c] = (T)((float)siluT*(float)uT);
84
- }
85
- threadgroup_barrier(mem_flags::mem_threadgroup);
86
-
87
- // ---- Phase B: for each Ho-block, D[BM,BN] = Hs @ Wdown[no,i0]ᵀ; atomic-add → y ----
88
- for (int no=0; no<Ho; no+=BN_T){
89
- lwd_t lwd((const device uint8_t*)wd + (int64_t)no*KwD + (int64_t)i0*bppD/pfD,
90
- sd_w + (int64_t)no*KgD + i0/gsD, bd_w + (int64_t)no*KgD + i0/gsD, I, Wds, sg, sl);
91
- threadgroup_barrier(mem_flags::mem_threadgroup);
92
- lwd.load_unsafe(); // one BI-wide tile (BI==BK, single step)
93
- threadgroup_barrier(mem_flags::mem_threadgroup);
94
- d_mma D(sg,sl);
95
- D.mma(Hs, Wds); // D[BM,BN] = Hs[BM,BI] @ Wds[BN,BI]ᵀ
96
- threadgroup_barrier(mem_flags::mem_threadgroup);
97
- D.Ctile.template store<T,WM_T,WN_T,BN_T,1>(Lg + D.sm*BN_T + D.sn); // reuse Lg to stage D
98
- threadgroup_barrier(mem_flags::mem_threadgroup);
99
- for (uint idx=lid; idx<(uint)(BM_T*BN_T); idx+=TGN_T){
100
- int r=(int)idx/BN_T, c=(int)idx%BN_T;
101
- if (m0+r<(int)M){
102
- const int64_t off=(int64_t)(m0+r)*(int64_t)Ho + (no+c);
103
- // Absorb the residual: add h exactly once (only the i0==0 threadgroups,
104
- // which cover every (m,ho) once) so the kernel outputs h + mlp(x) and
105
- // nothing is left live across it for MLX to plan a buffer around.
106
- float add = (float)Lg[idx];
107
- if (i0==0) add += (float)h[off];
108
- atomic_fetch_add_explicit(&y[off], add, memory_order_relaxed);
109
- }
110
- }
111
- threadgroup_barrier(mem_flags::mem_threadgroup);
112
- }
113
- `;
114
-
115
- const _kernels = new Map<string, MetalKernel>();
116
- function getKernel(
117
- gsG: number, btsG: number, gsU: number, btsU: number, gsD: number, btsD: number,
118
- ): MetalKernel {
119
- const key = `${gsG}:${btsG}:${gsU}:${btsU}:${gsD}:${btsD}`;
120
- let k = _kernels.get(key);
121
- if (!k) {
122
- k = new MetalKernel({
123
- name: "mlx_bun_fused_mlp",
124
- inputNames: ["x", "wg", "sg_w", "bg_w", "wu", "su_w", "bu_w", "wd", "sd_w", "bd_w", "h"],
125
- outputNames: ["y"],
126
- source: SOURCE,
127
- header:
128
- `${STEEL_QMM_HEADER}\n` +
129
- `#define GS_G ${gsG}\n#define BITS_G ${btsG}\n#define GS_U ${gsU}\n#define BITS_U ${btsU}\n` +
130
- `#define GS_D ${gsD}\n#define BITS_D ${btsD}\n` +
131
- `#define BM_T ${BM}\n#define BN_T ${BN}\n#define BK_T ${BK}\n` +
132
- `#define WM_T ${WM}\n#define WN_T ${WN}\n#define TGN_T ${TGN}\n`,
133
- ensureRowContiguous: true,
134
- atomicOutputs: true,
135
- });
136
- _kernels.set(key, k);
137
- }
138
- return k;
139
- }
140
-
141
- /** The whole MLP, fused, as one dispatch. x is [M, H] (bf16/f16). Returns the MLP
142
- * output [M, Ho] in x.dtype (cast from the f32 atomic accumulator). gate/up have
143
- * shape [I, H*bits/32]; down has [Ho, I*bits/32]. Caller owns the result. */
144
- export function fusedMlp(
145
- x: MlxArray,
146
- wg: MlxArray, sg: MlxArray, bg: MlxArray, gateSpec: QuantSpec,
147
- wu: MlxArray, su: MlxArray, bu: MlxArray, upSpec: QuantSpec,
148
- wd: MlxArray, sd: MlxArray, bd: MlxArray, downSpec: QuantSpec,
149
- h: MlxArray, // the residual (layer input) — absorbed: output = h + mlp(x)
150
- ): MlxArray {
151
- const M = x.shape[0]!, I = wg.shape[0]!, H = x.shape[1]!, Ho = wd.shape[0]!;
152
- const [yF] = getKernel(
153
- gateSpec.groupSize, gateSpec.bits, upSpec.groupSize, upSpec.bits, downSpec.groupSize, downSpec.bits,
154
- ).apply([x, wg, sg, bg, wu, su, bu, wd, sd, bd, h], {
155
- // f32 atomic accumulator, zero-initialised; grid tiles (M, I) — every I-block
156
- // contributes to the output via atomic-add.
157
- outputShapeFn: (ins) => [{ shape: [ins[0]!.shape[0]!, Ho], dtype: Dtype.float32 }],
158
- grid: (ins) => [TGN, Math.ceil(I / BN), Math.ceil(ins[0]!.shape[0]! / BM)],
159
- threadGroup: [TGN, 1, 1],
160
- templateInts: { I_T: I, H_T: H, HO_T: Ho },
161
- templateDtypes: { T: x.dtype },
162
- initValue: 0,
163
- });
164
- void M;
165
- if (yF!.dtype === x.dtype) return yF!;
166
- const y = yF!.astype(x.dtype);
167
- yF!.dispose();
168
- return y;
169
- }
@@ -1,240 +0,0 @@
1
- // Fused SwiGLU MLP expansion kernel (cpm5-generate-and-fuse-inference): compute
2
- // hidden = silu(gate_proj(x)) · up_proj(x)
3
- // in ONE Metal dispatch, reusing MLX's verbatim steel quantized BlockMMA GEMM
4
- // (src/train/steel-qmm-header.ts — the same building block the ORPO flash-CCE
5
- // head uses). Replaces the spelled-out path's two quantized_matmul dispatches +
6
- // the gate/up/silu/product global-memory materialization (minicpm5.ts LlamaMLP):
7
- // gate = qmm(x, Wg); up = qmm(x, Wu); silu = gate·σ(gate); hidden = silu·up
8
- // down_proj is LEFT as a separate qmm so the `hidden` boundary stays bit-exact —
9
- // the existing minicpm5 L1/L2 parity goldens (maxDiff===0) gate this path directly
10
- // (their 6-token prompt prefill is an M>1 MLP call).
11
- //
12
- // WHERE THE WIN IS: prefill / M>1, where the BlockMMA GEMM is the right tool and
13
- // the [M, intermediate] materialization is real. At decode (M=1) the matmuls are
14
- // memory-bound GEMVs (reading Wg/Wu dominates), so the fused kernel only saves the
15
- // per-token dispatch + a tiny [1,I] round-trip — the caller falls back to unfused
16
- // below M_MIN. Benchmarks (prefill AND decode) decide the default.
17
- //
18
- // PRECISION (two variants, env-flagged — "flag and try both"):
19
- // - MATCH (default): T = the activation dtype (bf16/f16). The gate/up tiles are
20
- // stored bf16-rounded out of the float BlockMMA accumulator, exactly as MLX's
21
- // quantized_matmul casts its float accum to the input dtype; σ/·/· then run
22
- // op-for-op with ops.sigmoid+ops.mul+ops.mul on bf16. AIM: maxDiff===0 vs the
23
- // unfused path (like the fused-gelu kernel, kl=0). Only residual: the metal
24
- // exp() vs MLX's math lib — quantified by the parity test.
25
- // - F32 (MLX_BUN_FUSED_SWIGLU_F32=1): keep gate/up/silu in f32 through the fusion,
26
- // round to T only at the final store. More accurate, NOT bit-exact → L3, gated
27
- // by teacher-forced KL like the fused-decode kernel.
28
- //
29
- // Never inside a compiled-decode trace: a CustomKernel has no output_shapes (same
30
- // rule as fusedDecodeSdpa / fusedGeglu) — the caller guards on !isCompiledTrace().
31
-
32
- import { MlxArray } from "../mlx/array";
33
- import { Dtype } from "../mlx/ffi";
34
- import { MetalKernel } from "../mlx/metal-kernel";
35
- import { STEEL_QMM_HEADER } from "../train/steel-qmm-header";
36
- import * as ops from "../mlx/ops";
37
- import type { QuantSpec } from "../mlx/ops";
38
-
39
- /** OFF by default until the prefill/decode benchmark + parity delta are in (then
40
- * flip to on like FUSED_GELU if it lands bit-exact). MLX_BUN_FUSED_SWIGLU=1 opts in. */
41
- export function fusedSwigluEnabled(): boolean {
42
- return process.env.MLX_BUN_FUSED_SWIGLU === "1";
43
- }
44
-
45
- /** f32-internal variant (NOT bit-exact). Default off → the bit-exact MATCH path. */
46
- function f32Internal(): boolean {
47
- return process.env.MLX_BUN_FUSED_SWIGLU_F32 === "1";
48
- }
49
-
50
- /** Dispatch counter — a gate test asserts the kernel actually ran. */
51
- export let fusedSwigluCalls = 0;
52
-
53
- /** Debug bisect: cap how many fused calls actually run (rest fall back). */
54
- function maxCalls(): number {
55
- const v = Number(process.env.MLX_BUN_SWIGLU_MAXCALLS);
56
- return Number.isFinite(v) && v >= 0 ? v : Infinity;
57
- }
58
- export function swigluUnderCap(): boolean {
59
- return fusedSwigluCalls < maxCalls();
60
- }
61
-
62
- // Below this many rows (M) the matmuls are memory-bound GEMVs and the fusion win
63
- // is just dispatch overhead; the caller keeps the unfused path. Tunable via env
64
- // for the decode-vs-prefill sweep.
65
- export function swigluMMin(): number {
66
- const v = Number(process.env.MLX_BUN_FUSED_SWIGLU_MMIN);
67
- return Number.isFinite(v) && v > 0 ? v : 2;
68
- }
69
-
70
- const BM = 32, BN = 32, BK = 32, WM = 2, WN = 2;
71
- const TGN = WM * WN * 32; // 128 threads / threadgroup
72
-
73
- // One BM×BN output tile per threadgroup (grid.y = I-tiles, grid.z = M-tiles), the
74
- // K=H reduction looped inside. Xs is loaded once and fed to BOTH the gate and up
75
- // BlockMMA (the whole point of fusing — x is read from global once for two GEMMs).
76
- const SOURCE = String.raw`
77
- // M from the x_shape helper (varies per call); I, H BAKED as template literals
78
- // (model-constant) — no runtime `+"`shape`"+` input array to thread through the
79
- // lazy graph. The per-loader quant constants (GS_G/BITS_G gate, GS_U/BITS_U up)
80
- // are baked too — the de-branch from the known per-tensor mixed-precision config,
81
- // so the gate=4/up=8 layers fuse instead of falling back.
82
- const uint M=x_shape[0]; constexpr int I=I_T, H=H_T;
83
- constexpr int gsG=GS_G, btsG=BITS_G, gsU=GS_U, btsU=BITS_U;
84
- constexpr int pfG=get_pack_factor<btsG,8>(), bppG=get_bytes_per_pack<btsG>();
85
- constexpr int pfU=get_pack_factor<btsU,8>(), bppU=get_bytes_per_pack<btsU>();
86
- constexpr int BKp=BK_T+16/sizeof(T);
87
- threadgroup T Xs[BM_T*BKp];
88
- threadgroup T Wgs[BN_T*BKp];
89
- threadgroup T Wus[BN_T*BKp];
90
- threadgroup T Lg[BM_T*BN_T];
91
- threadgroup T Lu[BM_T*BN_T];
92
- using mma_t=mlx::steel::BlockMMA<T,T,BM_T,BN_T,BK_T,WM_T,WN_T,false,true,BKp,BKp>;
93
- using lx_t=mlx::steel::BlockLoader<T,BM_T,BK_T,BKp,1,WM_T*WN_T*SIMD_SIZE>;
94
- using lwg_t=QuantizedBlockLoader<T,BN_T,BK_T,BKp,1,WM_T*WN_T*SIMD_SIZE,gsG,btsG>;
95
- using lwu_t=QuantizedBlockLoader<T,BN_T,BK_T,BKp,1,WM_T*WN_T*SIMD_SIZE,gsU,btsU>;
96
- const uint sg=simdgroup_index_in_threadgroup, sl=thread_index_in_simdgroup;
97
- const uint lid=thread_position_in_threadgroup.x;
98
- const int Hh=(int)H;
99
- const int K_wG=Hh*bppG/pfG, K_gG=Hh/gsG; // gate: packed-row bytes, group count
100
- const int K_wU=Hh*bppU/pfU, K_gU=Hh/gsU; // up
101
- const int m0=(int)threadgroup_position_in_grid.z*BM_T;
102
- const int n0=(int)threadgroup_position_in_grid.y*BN_T;
103
- const short num_els=(short)min(BM_T,(int)M-m0);
104
- const short num_outs=(short)min(BN_T,(int)I-n0);
105
-
106
- #if SWIGLU_TGZERO
107
- // Diagnostic: zero threadgroup memory so a back-to-back dispatch can't read the
108
- // previous kernel's leftover staging (the cross-dispatch hazard hypothesis).
109
- for (uint z=lid; z<(uint)(BM_T*BKp); z+=TGN_T) Xs[z]=T(0);
110
- for (uint z=lid; z<(uint)(BN_T*BKp); z+=TGN_T){ Wgs[z]=T(0); Wus[z]=T(0); }
111
- for (uint z=lid; z<(uint)(BM_T*BN_T); z+=TGN_T){ Lg[z]=T(0); Lu[z]=T(0); }
112
- threadgroup_barrier(mem_flags::mem_threadgroup);
113
- #endif
114
- mma_t mg(sg,sl), mu(sg,sl);
115
- lx_t lx (x + (int64_t)m0*Hh, Hh, Xs, sg, sl);
116
- lwg_t lwg((const device uint8_t*)wg + (int64_t)n0*K_wG, sg_w + (int64_t)n0*K_gG, bg_w + (int64_t)n0*K_gG, Hh, Wgs, sg, sl);
117
- lwu_t lwu((const device uint8_t*)wu + (int64_t)n0*K_wU, su_w + (int64_t)n0*K_gU, bu_w + (int64_t)n0*K_gU, Hh, Wus, sg, sl);
118
-
119
- for (int k=0; k<Hh; k+=BK_T){
120
- threadgroup_barrier(mem_flags::mem_threadgroup);
121
- if (num_els<BM_T) lx.load_safe(short2(BK_T,num_els)); else lx.load_unsafe();
122
- if (num_outs<BN_T){ lwg.load_safe(short2(BK_T,num_outs)); lwu.load_safe(short2(BK_T,num_outs)); }
123
- else { lwg.load_unsafe(); lwu.load_unsafe(); }
124
- threadgroup_barrier(mem_flags::mem_threadgroup);
125
- mg.mma(Xs,Wgs);
126
- mu.mma(Xs,Wus);
127
- lx.next(); lwg.next(); lwu.next();
128
- }
129
- threadgroup_barrier(mem_flags::mem_threadgroup);
130
- // Stage both accumulators to threadgroup. store<T,...> casts the float accum to
131
- // T (bf16) — the SAME rounding MLX's quantized_matmul applies to its output, so
132
- // Lg/Lu hold the bf16 gate/up the unfused path would have written to global.
133
- // Xs/Wgs/Wus alias Lg/Lu only if a kernel reused the same tgmem — they don't here,
134
- // but the stores write threadgroup that the epilogue reads, so bracket with barriers.
135
- mg.Ctile.template store<T,WM_T,WN_T,BN_T,1>(Lg + mg.sm*BN_T + mg.sn);
136
- threadgroup_barrier(mem_flags::mem_threadgroup);
137
- mu.Ctile.template store<T,WM_T,WN_T,BN_T,1>(Lu + mu.sm*BN_T + mu.sn);
138
- threadgroup_barrier(mem_flags::mem_threadgroup);
139
-
140
- for (uint idx=lid; idx<(uint)(BM_T*BN_T); idx+=TGN_T){
141
- int r=(int)idx/BN_T, c=(int)idx%BN_T;
142
- if (m0+r>=(int)M || n0+c>=(int)I) continue;
143
- #if SWIGLU_DEBUG_GATE
144
- hidden[(int64_t)(m0+r)*(int64_t)I + n0+c] = Lg[idx]; // raw gate proj (debug)
145
- #elif SWIGLU_F32
146
- // f32-internal: gate/up stayed bf16 in Lg/Lu (the matmul output is the same),
147
- // but σ·/· run in f32 with no intermediate rounding → NOT bit-exact.
148
- float g=(float)Lg[idx], u=(float)Lu[idx];
149
- float sig=1.0f/(1.0f+metal::precise::exp(-g));
150
- hidden[(int64_t)(m0+r)*(int64_t)I + n0+c] = (T)(g*sig*u);
151
- #else
152
- // MATCH: round σ, silu, product to T op-for-op with ops.sigmoid+mul+mul on bf16.
153
- T gT=Lg[idx], uT=Lu[idx];
154
- T sigT=(T)(1.0f/(1.0f+metal::precise::exp(-(float)gT)));
155
- T siluT=(T)((float)gT*(float)sigT);
156
- hidden[(int64_t)(m0+r)*(int64_t)I + n0+c] = (T)((float)siluT*(float)uT);
157
- #endif
158
- }
159
- `;
160
-
161
- const _kernels = new Map<string, MetalKernel>();
162
- function getKernel(gsG: number, btsG: number, gsU: number, btsU: number, f32: boolean): MetalKernel {
163
- const key = `${gsG}:${btsG}:${gsU}:${btsU}:${f32 ? 1 : 0}`;
164
- let k = _kernels.get(key);
165
- if (!k) {
166
- k = new MetalKernel({
167
- name: "mlx_bun_fused_swiglu",
168
- inputNames: ["x", "wg", "sg_w", "bg_w", "wu", "su_w", "bu_w"],
169
- outputNames: ["hidden"],
170
- source: SOURCE,
171
- header:
172
- `${STEEL_QMM_HEADER}\n` +
173
- `#define GS_G ${gsG}\n#define BITS_G ${btsG}\n#define GS_U ${gsU}\n#define BITS_U ${btsU}\n` +
174
- `#define BM_T ${BM}\n#define BN_T ${BN}\n#define BK_T ${BK}\n` +
175
- `#define WM_T ${WM}\n#define WN_T ${WN}\n#define TGN_T ${TGN}\n` +
176
- `#define SWIGLU_F32 ${f32 ? 1 : 0}\n` +
177
- `#define SWIGLU_TGZERO ${process.env.MLX_BUN_SWIGLU_TGZERO === "1" ? 1 : 0}\n` +
178
- `#define SWIGLU_DEBUG_GATE ${process.env.MLX_BUN_SWIGLU_DEBUG_GATE === "1" ? 1 : 0}\n`,
179
- ensureRowContiguous: true,
180
- });
181
- _kernels.set(key, k);
182
- }
183
- return k;
184
- }
185
-
186
- /** Each loader's (bits, groupSize) is baked independently, so gate and up may
187
- * differ (the per-tensor mixed-precision layers). Requires bf16/f16 activations,
188
- * affine biases, group size a multiple of BK, and H % BK == 0. */
189
- export function fusedSwigluSupported(
190
- x: MlxArray, gateSpec: QuantSpec, upSpec: QuantSpec,
191
- gateBias: MlxArray | null, upBias: MlxArray | null,
192
- ): boolean {
193
- const H = x.shape[x.shape.length - 1]!;
194
- const specOk = (s: QuantSpec) =>
195
- (s.bits === 2 || s.bits === 4 || s.bits === 8) && s.groupSize % BK === 0 && BK <= s.groupSize;
196
- return (
197
- (x.dtype === Dtype.bfloat16 || x.dtype === Dtype.float16) &&
198
- gateBias != null && upBias != null &&
199
- specOk(gateSpec) && specOk(upSpec) &&
200
- H % BK === 0
201
- );
202
- }
203
-
204
- /** silu(gate_proj(x)) · up_proj(x), fused. `x` is [..., H] (collapsed to [M, H]);
205
- * wg/wu are the packed quantized weights [I, H*bits/32], with per-group
206
- * scales/biases [I, H/groupSize]. gate and up may use different quant specs.
207
- * Returns hidden [M, I] in x.dtype. Caller owns it. */
208
- export function fusedSwiglu(
209
- x: MlxArray,
210
- wg: MlxArray, sg: MlxArray, bg: MlxArray,
211
- wu: MlxArray, su: MlxArray, bu: MlxArray,
212
- gateSpec: QuantSpec, upSpec: QuantSpec = gateSpec,
213
- ): MlxArray {
214
- fusedSwigluCalls++;
215
- const H = x.shape[x.shape.length - 1]!;
216
- const M = x.shape.reduce((a, b) => a * b, 1) / H;
217
- const I = wg.shape[0]!;
218
- const x2 = x.shape.length === 2 ? x : ops.reshape(x, [M, H]);
219
- try {
220
- const [hidden] = getKernel(gateSpec.groupSize, gateSpec.bits, upSpec.groupSize, upSpec.bits, f32Internal()).apply(
221
- [x2, wg, sg, bg, wu, su, bu],
222
- {
223
- outputShapeFn: (ins) => [{ shape: [ins[0]!.shape[0]!, I], dtype: x.dtype }],
224
- grid: (ins) => [TGN, Math.ceil(I / BN), Math.ceil(ins[0]!.shape[0]! / BM)],
225
- threadGroup: [TGN, 1, 1],
226
- templateInts: { I_T: I, H_T: H },
227
- templateDtypes: { T: x.dtype },
228
- },
229
- );
230
- // Restore the leading dims the caller passed (e.g. [B, T, I]).
231
- if (x.shape.length !== 2) {
232
- const out = ops.reshape(hidden!, [...x.shape.slice(0, -1), I]);
233
- hidden!.dispose();
234
- return out;
235
- }
236
- return hidden!;
237
- } finally {
238
- if (x2 !== x && process.env.MLX_BUN_SWIGLU_NODISPOSE !== "1") x2.dispose();
239
- }
240
- }