mlx-bun 0.0.10 → 0.0.12

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 (216) hide show
  1. package/README.md +107 -32
  2. package/THIRD_PARTY_LICENSES.md +10 -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 +58 -35
  7. package/docs/design/batching-v2-plan.md +23 -9
  8. package/docs/design/bucketing-stage.md +2 -1
  9. package/docs/design/colibri-glm52-port.md +1479 -0
  10. package/docs/design/compat-cli-surface-design.md +4 -3
  11. package/docs/design/decode-speed-program.md +172 -0
  12. package/docs/design/docs-reorg-plan.md +1 -1
  13. package/docs/design/dspark-serving-program.md +371 -0
  14. package/docs/design/dspark-speculative-decoding.md +167 -5
  15. package/docs/design/faithful-l1-consolidation.md +310 -0
  16. package/docs/design/generic-model-support.md +8 -5
  17. package/docs/design/grammar-spec-batching-integration.md +301 -0
  18. package/docs/design/minicpm5-decode-megakernel.md +16 -11
  19. package/docs/design/mlx-lm-tool-parity-plan.md +11 -1
  20. package/docs/design/omlx-adoption-map.md +14 -6
  21. package/docs/design/orpo-training.md +34 -30
  22. package/docs/design/paged-kv-cache.md +214 -0
  23. package/docs/design/parallel-slots.md +82 -49
  24. package/docs/design/parity-tier-dag.md +43 -33
  25. package/docs/design/pre-colibri-stabilization.md +329 -0
  26. package/docs/design/repo-cleanup-plan.md +189 -0
  27. package/docs/design/runtime-isolation.md +19 -3
  28. package/docs/design/segmented-backward-training.md +3 -2
  29. package/docs/design/ssd-kv-cold-tier.md +130 -0
  30. package/docs/design/structured-output.md +484 -0
  31. package/docs/design/the-dreaming-master-plan.md +2 -3
  32. package/docs/design/turboquant-kv.md +235 -0
  33. package/docs/design/unified-engine-frontier-plan.md +774 -0
  34. package/docs/design/web-chat-beat-matrix.md +315 -0
  35. package/docs/design/web-chat-redesign.md +1112 -0
  36. package/docs/investigations/colibri-oracle-pin.md +1284 -0
  37. package/docs/investigations/dspark-handoff.md +182 -16
  38. package/docs/investigations/indexshare-performance-spike.md +357 -0
  39. package/docs/investigations/lab-build-journal.md +2 -2
  40. package/docs/investigations/openwiki-evaluation.md +249 -0
  41. package/docs/planning/IDEAS.md +14 -0
  42. package/docs/planning/PRODUCT_ROADMAP.md +2 -3
  43. package/docs/planning/chat-ui-vision-memory-first.md +199 -0
  44. package/docs/planning/chat-ui-vision.md +50 -0
  45. package/docs/planning/memory-docs-and-dag-plan.md +15 -6
  46. package/docs/planning/release-notes-v0.0.11.md +239 -0
  47. package/docs/planning/release-notes-v0.0.12.md +80 -0
  48. package/docs/reference/cli.md +63 -18
  49. package/docs/reference/distribution.md +37 -6
  50. package/docs/reference/embedding.md +40 -16
  51. package/docs/reference/features-matrix.md +99 -0
  52. package/docs/reference/library-api.md +69 -20
  53. package/docs/reference/memory.md +26 -6
  54. package/docs/reference/models.md +60 -3
  55. package/docs/reference/orpo-quickstart.md +3 -4
  56. package/docs/reference/server-api.md +717 -24
  57. package/docs/reference/server-config.md +265 -129
  58. package/docs/reference/training.md +24 -16
  59. package/package.json +5 -3
  60. package/src/anthropic.ts +67 -44
  61. package/src/audio/conformer.ts +647 -0
  62. package/src/audio/decode.ts +133 -0
  63. package/src/audio/features.ts +202 -0
  64. package/src/audio/transcode.ts +67 -0
  65. package/src/chat-template.ts +155 -10
  66. package/src/cli.ts +483 -113
  67. package/src/config.ts +116 -24
  68. package/src/diffusion/diffusion-generate.ts +14 -8
  69. package/src/download.ts +143 -12
  70. package/src/eval/README.md +7 -6
  71. package/src/eval/ifeval.ts +63 -120
  72. package/src/eval/kl.ts +59 -3
  73. package/src/eval/quality-db.ts +2 -2
  74. package/src/eval/runner.ts +17 -8
  75. package/src/eval/tasks/ifeval.ts +167 -31
  76. package/src/expert-io.ts +391 -0
  77. package/src/expert-offload.ts +15 -2
  78. package/src/expert-residency.ts +1134 -0
  79. package/src/expert-usage.ts +415 -0
  80. package/src/flags.ts +13 -0
  81. package/src/generate.ts +438 -35
  82. package/src/grammar.ts +585 -0
  83. package/src/hf-push.ts +1 -1
  84. package/src/hub-rest.ts +242 -0
  85. package/src/index.ts +14 -2
  86. package/src/jobs/runner.ts +37 -18
  87. package/src/kv-store.ts +586 -93
  88. package/src/lora.ts +85 -14
  89. package/src/md-modules.d.ts +42 -0
  90. package/src/media-fetch.ts +426 -0
  91. package/src/memory/rest.ts +245 -0
  92. package/src/memory/vault.ts +74 -0
  93. package/src/mlx/array.ts +149 -19
  94. package/src/mlx/autograd.ts +53 -16
  95. package/src/mlx/checkpoint.ts +46 -13
  96. package/src/mlx/custom-vjp.ts +83 -35
  97. package/src/mlx/ffi.ts +27 -3
  98. package/src/mlx/metal-kernel.ts +7 -4
  99. package/src/mlx/ops.ts +153 -23
  100. package/src/mlx/turboquant-ops.ts +831 -0
  101. package/src/mlx/turboquant-tables.ts +237 -0
  102. package/src/model/batched-mask.ts +62 -1
  103. package/src/model/batched-quant.ts +206 -0
  104. package/src/model/batched-rotating-quant.ts +346 -0
  105. package/src/model/batched-rotating.ts +46 -1
  106. package/src/model/compiled-decode.ts +4 -15
  107. package/src/model/factory.ts +103 -6
  108. package/src/model/gemma4-base.ts +395 -39
  109. package/src/model/gemma4.ts +122 -33
  110. package/src/model/generated/gemma4-12b.ts +9 -13
  111. package/src/model/generated/gemma4-26b.ts +10 -5
  112. package/src/model/generated/gemma4-e4b.ts +14 -9
  113. package/src/model/glm52-atlas.ts +511 -0
  114. package/src/model/glm52-cache.ts +706 -0
  115. package/src/model/glm52-config.ts +262 -0
  116. package/src/model/glm52-container.ts +305 -0
  117. package/src/model/glm52-coupling.ts +388 -0
  118. package/src/model/glm52-dsa.ts +602 -0
  119. package/src/model/glm52-expert-layout.ts +253 -0
  120. package/src/model/glm52-layout.ts +152 -0
  121. package/src/model/glm52-memory.ts +473 -0
  122. package/src/model/glm52-mla.ts +786 -0
  123. package/src/model/glm52-moe.ts +223 -0
  124. package/src/model/glm52-pilot.ts +537 -0
  125. package/src/model/glm52-reference.ts +445 -0
  126. package/src/model/glm52-residency.ts +557 -0
  127. package/src/model/glm52-resident-weights.ts +135 -0
  128. package/src/model/glm52-streamed-experts.ts +453 -0
  129. package/src/model/glm52-streamed-metal.ts +610 -0
  130. package/src/model/glm52-weights.ts +503 -0
  131. package/src/model/glm52.ts +1153 -0
  132. package/src/model/minicpm5.ts +58 -102
  133. package/src/model/paged-kv.ts +253 -0
  134. package/src/model/qwen3-delta.ts +76 -15
  135. package/src/model/qwen3-moe.ts +404 -0
  136. package/src/model/qwen3.ts +9 -8
  137. package/src/model/qwen3_5.ts +88 -23
  138. package/src/model/support.ts +19 -1
  139. package/src/model/universal/dense.ts +40 -5
  140. package/src/model/universal/rope.ts +36 -21
  141. package/src/native/expert_io.c +523 -0
  142. package/src/native-pack.ts +6 -4
  143. package/src/pi-web.ts +1299 -82
  144. package/src/preflight.ts +27 -8
  145. package/src/prompt-cache.ts +293 -33
  146. package/src/quantize/quantizer.ts +16 -1
  147. package/src/registry.ts +57 -2
  148. package/src/responses.ts +62 -49
  149. package/src/serve/batch-scheduler.ts +1050 -78
  150. package/src/serve/generation-gateway.ts +252 -24
  151. package/src/serve/isolate.ts +417 -0
  152. package/src/serve/lane-registry.ts +44 -0
  153. package/src/serve/session-search.ts +326 -0
  154. package/src/server.ts +1701 -175
  155. package/src/spec/assistant-source.ts +150 -0
  156. package/src/spec/deepspec-source.ts +143 -0
  157. package/src/spec/dflash-source.ts +124 -0
  158. package/src/spec/dspark/ab-stats.ts +136 -0
  159. package/src/spec/dspark/calibration.ts +112 -0
  160. package/src/spec/dspark/deepspec-module.ts +801 -0
  161. package/src/spec/dspark/generate-dflash.ts +72 -20
  162. package/src/spec/dspark/loader.ts +23 -0
  163. package/src/spec/dspark/module-dflash.ts +278 -36
  164. package/src/spec/dspark/quantize-drafter.ts +91 -0
  165. package/src/spec/generate.ts +59 -25
  166. package/src/spec/glm52-mtp-source.ts +392 -0
  167. package/src/spec/ngram-source.ts +132 -0
  168. package/src/spec/serve-loop.ts +617 -0
  169. package/src/spec/source.ts +118 -0
  170. package/src/spec/two-model.ts +171 -0
  171. package/src/ssd-cache.ts +111 -35
  172. package/src/tokenizer.ts +288 -2
  173. package/src/tool-approvals.ts +131 -0
  174. package/src/tool-call.ts +438 -22
  175. package/src/train/flash-cce.ts +2 -2
  176. package/src/train/job.ts +0 -12
  177. package/src/train/lora-params.ts +17 -6
  178. package/src/train/trainer.ts +60 -30
  179. package/src/vision/prompt.ts +217 -48
  180. package/src/web/app.html +1197 -1791
  181. package/src/web/app.js +5694 -0
  182. package/src/web/icon.svg +13 -0
  183. package/src/web/manifest.webmanifest +24 -0
  184. package/src/web/src/adapters-panel.ts +288 -0
  185. package/src/web/src/api.ts +57 -0
  186. package/src/web/src/assistant.ts +485 -0
  187. package/src/web/src/chat.ts +1050 -0
  188. package/src/web/src/composer.ts +959 -0
  189. package/src/web/src/dataset.ts +132 -0
  190. package/src/web/src/finetune.ts +267 -0
  191. package/src/web/src/hub.ts +428 -0
  192. package/src/web/src/main.ts +98 -0
  193. package/src/web/src/markdown.ts +0 -0
  194. package/src/web/src/memory-panel.ts +572 -0
  195. package/src/web/src/model-picker.ts +159 -0
  196. package/src/web/src/palette.ts +346 -0
  197. package/src/web/src/protocol.ts +62 -0
  198. package/src/web/src/quantize.ts +167 -0
  199. package/src/web/src/rag.ts +274 -0
  200. package/src/web/src/sessions.ts +469 -0
  201. package/src/web/src/shell.ts +804 -0
  202. package/src/web/src/status.ts +300 -0
  203. package/src/web/src/ui-catalog.ts +92 -0
  204. package/src/web/sw.js +71 -0
  205. package/src/web/vendor/README.md +61 -0
  206. package/src/web/vendor/hljs-LICENSE +29 -0
  207. package/src/web/vendor/hljs-theme.css +59 -0
  208. package/src/web/vendor/hljs.js +26 -0
  209. package/src/web-tools.ts +54 -2
  210. package/src/weights.ts +82 -19
  211. package/src/model/fused-decode-kernel.ts +0 -312
  212. package/src/model/fused-geglu-kernel.ts +0 -198
  213. package/src/model/fused-mlp-kernel.ts +0 -169
  214. package/src/model/fused-swiglu-kernel.ts +0 -240
  215. package/src/model/steel-linear-kernel.ts +0 -96
  216. package/src/status-page.html +0 -497
@@ -0,0 +1,801 @@
1
+ // DeepSpec's Gemma4DSparkModel — semi-autoregressive draft model, ported
2
+ // verbatim (copy-verbatim methodology: transcribe THEIR forward, then port
3
+ // op-for-op) from github.com/deepseek-ai/DeepSpec (MIT), files:
4
+ // deepspec/modeling/dspark/gemma4/modeling.py (Gemma4DSparkModel)
5
+ // deepspec/modeling/dspark/common.py (extract_context_feature)
6
+ // deepspec/modeling/dspark/markov_head.py (VanillaMarkov)
7
+ // deepspec/eval/dspark/draft_ops.py (inference-time draft loop)
8
+ // deepspec/utils/sampling.py (sample_tokens, temp=0 argmax)
9
+ // Cross-checked against the installed HF reference (transformers
10
+ // models/gemma4/modeling_gemma4.py) for Gemma4RMSNorm, apply_rotary_pos_emb,
11
+ // Gemma4TextRotaryEmbedding (rope_type "proportional" via
12
+ // modeling_rope_utils._compute_proportional_rope_parameters), and
13
+ // Gemma4TextScaledWordEmbedding — since Gemma4DSparkModel subclasses/reuses
14
+ // those directly rather than redefining them.
15
+ //
16
+ // This is a DRAFT model for target-Gemma4 speculative decoding: not
17
+ // causal, not autoregressive over the whole sequence — it predicts a
18
+ // γ-token block in one backbone pass (context-conditioned, bidirectional
19
+ // within the block), then a cheap sequential Markov correction walks the
20
+ // block left-to-right applying a low-rank transition bias per step.
21
+ //
22
+ // This module is STATELESS server-lifetime weights. Per-request context
23
+ // K/V (the incremental cache DeepSpec threads through consecutive draft
24
+ // rounds via a DynamicCache) is NOT stored here — see `projectContext` /
25
+ // `draftBlock` below for the seam.
26
+
27
+ import { Weights } from "../../weights";
28
+ import { MlxArray } from "../../mlx/array";
29
+ import { Dtype } from "../../mlx/ffi";
30
+ import * as ops from "../../mlx/ops";
31
+ import { parseQuantization, quantFor, type QuantizationConfig } from "../../config";
32
+
33
+ function disposing(old: MlxArray, next: MlxArray): MlxArray {
34
+ old.dispose();
35
+ return next;
36
+ }
37
+
38
+ // ---------------------------------------------------------------------------
39
+ // Weight representation: every matmul weight and gather table loads as either
40
+ // bf16 (the released checkpoint) or affine-quantized (a
41
+ // scripts/dspark-quantize-drafter.ts sibling). Detection is the house
42
+ // pattern — a `.scales` sibling key marks a quantized module; bits/group_size
43
+ // come from the config's `quantization` block (per-module overrides + the
44
+ // mlx `false` = kept-full-precision convention). Both formats flow through
45
+ // the same forward: the quantized matmul path is mlx QuantizedLinear
46
+ // semantics (x @ W^T via quantized_matmul transpose=true) and the quantized
47
+ // gather path is mlx QuantizedEmbedding semantics (gather packed/scales/bias
48
+ // rows, dequantize the gathered rows) — matching mlx-lm's numerics.
49
+ // ---------------------------------------------------------------------------
50
+
51
+ /** A Linear weight `W [out, in]`, used as `x @ W^T`. bf16 keeps the lazy
52
+ * transpose VIEW (see the memory note below); quant keeps packed storage. */
53
+ type MatW =
54
+ | { kind: "bf16"; t: MlxArray }
55
+ | { kind: "quant"; w: MlxArray; scales: MlxArray; biases: MlxArray | null; spec: ops.QuantSpec };
56
+
57
+ /** An embedding table `[vocab, dim]`, used via row gather. */
58
+ type TableW =
59
+ | { kind: "bf16"; w: MlxArray }
60
+ | { kind: "quant"; w: MlxArray; scales: MlxArray; biases: MlxArray | null; spec: ops.QuantSpec };
61
+
62
+ /** x @ W^T for either format. Output dtype follows x (bf16 on the real
63
+ * checkpoint) in BOTH branches — the model-dtype fidelity notes on the
64
+ * markov/confidence paths hold unchanged for the quantized path. */
65
+ function matmulW(x: MlxArray, m: MatW): MlxArray {
66
+ if (m.kind === "bf16") return ops.matmul(x, m.t);
67
+ return ops.quantizedMatmul(x, m.w, m.scales, m.biases, m.spec, true);
68
+ }
69
+
70
+ /** Row gather for either format (quant: QuantizedEmbedding.encode —
71
+ * dequantize returns the scales' dtype, bf16, same as the bf16 branch). */
72
+ function gatherW(t: TableW, idsU32: MlxArray): MlxArray {
73
+ if (t.kind === "bf16") return ops.takeAxis(t.w, idsU32, 0);
74
+ const rows = ops.takeAxis(t.w, idsU32, 0);
75
+ const scaleRows = ops.takeAxis(t.scales, idsU32, 0);
76
+ const biasRows = t.biases ? ops.takeAxis(t.biases, idsU32, 0) : null;
77
+ const out = ops.dequantize(rows, scaleRows, biasRows, t.spec);
78
+ rows.dispose();
79
+ scaleRows.dispose();
80
+ biasRows?.dispose();
81
+ return out;
82
+ }
83
+
84
+ function disposeW(m: MatW | TableW | null): void {
85
+ if (!m) return;
86
+ if (m.kind === "bf16") {
87
+ ("t" in m ? m.t : m.w).dispose();
88
+ return;
89
+ }
90
+ m.w.dispose();
91
+ m.scales.dispose();
92
+ m.biases?.dispose();
93
+ }
94
+
95
+ // ---------------------------------------------------------------------------
96
+ // Config (their config.json field names, verbatim keys — no renaming so the
97
+ // mapping to the checkpoint stays obvious).
98
+ // ---------------------------------------------------------------------------
99
+
100
+ export interface DeepspecConfig {
101
+ architectures: string[];
102
+ hidden_size: number;
103
+ num_hidden_layers: number;
104
+ num_attention_heads: number;
105
+ global_head_dim: number;
106
+ num_global_key_value_heads: number;
107
+ attention_k_eq_v: boolean;
108
+ intermediate_size: number;
109
+ hidden_activation: string;
110
+ rms_norm_eps: number;
111
+ final_logit_softcapping: number | null;
112
+ vocab_size: number;
113
+ block_size: number;
114
+ mask_token_id: number;
115
+ target_layer_ids: number[];
116
+ num_target_layers: number;
117
+ markov_rank: number;
118
+ markov_head_type: string;
119
+ enable_confidence_head: boolean;
120
+ confidence_head_with_markov: boolean;
121
+ rope_theta: number;
122
+ partial_rotary_factor: number;
123
+ /** Not in the checkpoint's config.json (draft_ops.py takes it as a call
124
+ * arg to build_dspark_proposal); default 0 = confidence head disabled
125
+ * functionally even when weights exist (threshold<=0 ⇒ full γ block). */
126
+ confidence_threshold: number;
127
+ }
128
+
129
+ function readConfig(raw: Record<string, any>): DeepspecConfig {
130
+ const arch = raw.architectures?.[0];
131
+ if (arch !== "Gemma4DSparkModel")
132
+ throw new Error(`DeepspecDrafter: expected architectures[0]==="Gemma4DSparkModel", got ${JSON.stringify(raw.architectures)}`);
133
+
134
+ // RoPE: their config nests rope params under rope_parameters.full_attention
135
+ // (matches Gemma4TextConfig / Gemma4TextRotaryEmbedding's per-layer-type
136
+ // dict); ground truth also allows a flat rope_theta/partial_rotary_factor
137
+ // for simplified checkpoints — accept either shape.
138
+ const ropeFull = raw.rope_parameters?.full_attention ?? raw.rope_parameters ?? {};
139
+ const ropeTheta = ropeFull.rope_theta ?? raw.rope_theta ?? 1e6;
140
+ const partialRotary = ropeFull.partial_rotary_factor ?? raw.partial_rotary_factor ?? 1.0;
141
+
142
+ const targetLayerIds: number[] = raw.target_layer_ids;
143
+ if (!Array.isArray(targetLayerIds) || targetLayerIds.length === 0)
144
+ throw new Error("DeepspecDrafter: config.target_layer_ids must be a non-empty array");
145
+
146
+ // Silent-wrongness guards (2026-07-06 port review): each of these variants
147
+ // would LOAD cleanly and compute wrong math — this module implements only
148
+ // the released-checkpoint shape. Refuse loudly instead.
149
+ if (!raw.attention_k_eq_v)
150
+ throw new Error(
151
+ "DeepspecDrafter: attention_k_eq_v=false checkpoints need a real v_proj path — not implemented (this module wires V ≡ K)",
152
+ );
153
+ if ((raw.markov_rank ?? 0) > 0 && (raw.markov_head_type ?? "vanilla") !== "vanilla")
154
+ throw new Error(
155
+ `DeepspecDrafter: markov_head_type "${raw.markov_head_type}" not implemented (gated/rnn heads ship markov_w1/w2 too and would silently get vanilla math) — only "vanilla"`,
156
+ );
157
+ if ((raw.hidden_activation ?? "gelu_pytorch_tanh") !== "gelu_pytorch_tanh")
158
+ throw new Error(
159
+ `DeepspecDrafter: hidden_activation "${raw.hidden_activation}" not implemented — the MLP hardcodes gelu_pytorch_tanh`,
160
+ );
161
+
162
+ return {
163
+ architectures: raw.architectures,
164
+ hidden_size: raw.hidden_size,
165
+ num_hidden_layers: raw.num_hidden_layers,
166
+ num_attention_heads: raw.num_attention_heads,
167
+ global_head_dim: raw.global_head_dim,
168
+ num_global_key_value_heads: raw.num_global_key_value_heads,
169
+ attention_k_eq_v: !!raw.attention_k_eq_v,
170
+ intermediate_size: raw.intermediate_size,
171
+ hidden_activation: raw.hidden_activation ?? "gelu_pytorch_tanh",
172
+ rms_norm_eps: raw.rms_norm_eps ?? 1e-6,
173
+ final_logit_softcapping: raw.final_logit_softcapping ?? null,
174
+ vocab_size: raw.vocab_size,
175
+ block_size: raw.block_size,
176
+ mask_token_id: raw.mask_token_id,
177
+ target_layer_ids: targetLayerIds,
178
+ num_target_layers: raw.num_target_layers,
179
+ markov_rank: raw.markov_rank ?? 0,
180
+ markov_head_type: raw.markov_head_type ?? "vanilla",
181
+ enable_confidence_head: !!raw.enable_confidence_head,
182
+ confidence_head_with_markov: !!raw.confidence_head_with_markov,
183
+ rope_theta: ropeTheta,
184
+ partial_rotary_factor: partialRotary,
185
+ confidence_threshold: raw.confidence_threshold ?? 0,
186
+ };
187
+ }
188
+
189
+ // ---------------------------------------------------------------------------
190
+ // Per-layer weights.
191
+ // ---------------------------------------------------------------------------
192
+
193
+ interface Layer {
194
+ qProj: MatW; // [nHeads*headDim, hidden] Linear storage, used as x@W^T
195
+ kProj: MatW; // [nKvHeads*headDim, hidden]
196
+ oProj: MatW; // [hidden, nHeads*headDim]
197
+ qNorm: MlxArray; // [headDim]
198
+ kNorm: MlxArray; // [headDim]
199
+ // v_norm has with_scale=False (Gemma4RMSNorm(..., with_scale=False)) — no
200
+ // weight tensor in the checkpoint; represented as `null` into ops.rmsNorm.
201
+ inputNorm: MlxArray;
202
+ postAttnNorm: MlxArray;
203
+ preFfNorm: MlxArray;
204
+ postFfNorm: MlxArray;
205
+ gateProj: MatW;
206
+ upProj: MatW;
207
+ downProj: MatW;
208
+ layerScalar: MlxArray; // [1]
209
+ }
210
+
211
+ /** Per-layer context K/V rows, already projected + normed + roped —
212
+ * cacheable across draft rounds (see projectContext doc). */
213
+ export interface ContextKV {
214
+ k: MlxArray; // [1, nKvHeads, ctxLen, headDim]
215
+ v: MlxArray; // [1, nKvHeads, ctxLen, headDim] (v ≡ k when attention_k_eq_v)
216
+ }
217
+
218
+ export interface DraftBlockResult {
219
+ /** Sequentially-sampled draft tokens, length 0..gamma (0 iff confidence
220
+ * truncation fires at the very first position — EMPTY proposal). */
221
+ tokens: number[];
222
+ /** Per-position sigmoid confidence, aligned with `tokens` (same length;
223
+ * empty when the confidence head is disabled). */
224
+ conf: number[];
225
+ /** Raw base_logits (post target-forward, PRE-Markov-bias, post-softcap)
226
+ * for the full block [1, gamma, vocab] (float32 COPY; sampling runs in
227
+ * model dtype separately) — caller disposes. NOTE: the reference
228
+ * verifier's temp>0 draft_probs come from the Markov-CORRECTED logits
229
+ * (draft_ops.py:140-143), NOT these — at temp 0 (our oracle regime) the
230
+ * distinction is moot (verify degenerates to argmax token-match), but a
231
+ * future temp>0 verify must add the per-position Markov bias first. */
232
+ baseLogits: MlxArray;
233
+ }
234
+
235
+ export class DeepspecDrafter {
236
+ readonly cfg: DeepspecConfig;
237
+ /** === config.target_layer_ids, alias for the ground-truth term. */
238
+ readonly tapLayers: number[];
239
+ /** === config.block_size (γ), alias for the ground-truth term. */
240
+ readonly gamma: number;
241
+ readonly hidden: number;
242
+ readonly nHeads: number;
243
+ readonly nKvHeads: number;
244
+ readonly headDim: number;
245
+ readonly eps: number;
246
+ readonly embedScale: number;
247
+ readonly ropeFreqs: MlxArray; // proportional-RoPE freqs, [headDim/2]
248
+
249
+ #w: Weights;
250
+ #embed: TableW; // [vocab, hidden]
251
+ #fc: MatW; // fc.weight [hidden, taps*hidden] Linear storage
252
+ #hiddenNorm: MlxArray; // [hidden]
253
+ #norm: MlxArray; // [hidden]
254
+ #lmHead: MatW; // lm_head.weight [vocab, hidden]
255
+ #layers: Layer[] = [];
256
+ #markovW1: TableW | null; // [vocab, markovRank] embedding
257
+ #markovW2: MatW | null; // markov_w2.weight [vocab, rank] Linear storage
258
+ #confProj: MatW | null; // proj.weight [1, confDim] Linear storage (bf16
259
+ // keeps the once-built transpose view — per-call
260
+ // transpose+cast leaked, 2026-07-06 review fix)
261
+ #confB: MlxArray | null; // [1]
262
+
263
+ private constructor(w: Weights, cfg: DeepspecConfig, quant: QuantizationConfig | null) {
264
+ this.#w = w;
265
+ this.cfg = cfg;
266
+ this.tapLayers = cfg.target_layer_ids;
267
+ this.gamma = cfg.block_size;
268
+ this.hidden = cfg.hidden_size;
269
+ this.nHeads = cfg.num_attention_heads;
270
+ this.nKvHeads = cfg.num_global_key_value_heads; // k_eq_v enforced in readConfig (no v_proj path)
271
+ this.headDim = cfg.global_head_dim;
272
+ this.eps = cfg.rms_norm_eps;
273
+ this.embedScale = Math.sqrt(cfg.hidden_size);
274
+
275
+ const T = (name: string) => w.tensor(name);
276
+ // Lazy transpose VIEW — no contiguous copy. The src/spec/drafter.ts
277
+ // pattern (contiguous + eval) would materialize every matmul weight a
278
+ // second time: on the real 6.86 GB checkpoint that's ~+4.8 GB resident
279
+ // (lm_head alone ~2 GB), decisive on a 24 GB box. mlx's steel GEMM
280
+ // dispatches a transposed-B operand natively, so the view costs nothing
281
+ // per matmul. (2026-07-06 port review, MEDIUM-memory finding.)
282
+ const transposed = (name: string): MlxArray => ops.transposeAxes(T(name), [1, 0]);
283
+ // Quantized-module detection + spec (house pattern: `.scales` sibling
284
+ // key gates; bits/group_size from the config quantization block).
285
+ const qspec = (base: string): ops.QuantSpec => {
286
+ const spec = quantFor(quant, base);
287
+ if (!spec)
288
+ throw new Error(
289
+ `DeepspecDrafter: ${base} has quantized tensors (.scales sibling) but no quantization config entry`,
290
+ );
291
+ return { bits: spec.bits, groupSize: spec.groupSize, mode: spec.mode };
292
+ };
293
+ const quantParts = (base: string) => ({
294
+ w: T(`${base}.weight`),
295
+ scales: T(`${base}.scales`),
296
+ biases: w.has(`${base}.biases`) ? T(`${base}.biases`) : null,
297
+ spec: qspec(base),
298
+ });
299
+ const mat = (base: string): MatW =>
300
+ w.has(`${base}.scales`)
301
+ ? { kind: "quant", ...quantParts(base) }
302
+ : { kind: "bf16", t: transposed(`${base}.weight`) };
303
+ const table = (base: string): TableW =>
304
+ w.has(`${base}.scales`)
305
+ ? { kind: "quant", ...quantParts(base) }
306
+ : { kind: "bf16", w: T(`${base}.weight`) };
307
+
308
+ this.#embed = table("embed_tokens");
309
+ this.#fc = mat("fc");
310
+ this.#hiddenNorm = T("hidden_norm.weight");
311
+ this.#norm = T("norm.weight");
312
+ this.#lmHead = mat("lm_head");
313
+
314
+ // Proportional RoPE freqs (mlx_lm.models.rope_utils.ProportionalRoPE,
315
+ // transformers._compute_proportional_rope_parameters): rotated_dims =
316
+ // int(head_dim * partial_rotary_factor); exponents over [0, rotated_dims)
317
+ // step 2, divided by FULL head_dim (not rotated_dims); tail padded with
318
+ // +inf ⇒ angle pos/∞ = 0 ⇒ cos=1, sin=0 — the identity rotation, i.e.
319
+ // passthrough on those dims (freqs is the wavelength array fast::rope
320
+ // divides position by, same convention as src/spec/drafter.ts's
321
+ // ProportionalRoPE port; verified vs mlx_lm rope_utils.ProportionalRoPE).
322
+ const rotatedDims = Math.floor(this.headDim * cfg.partial_rotary_factor);
323
+ const n = this.headDim / 2;
324
+ const freqs = new Float32Array(n).fill(Infinity);
325
+ for (let k = 0; k < rotatedDims / 2; k++) {
326
+ freqs[k] = Math.pow(cfg.rope_theta, (2 * k) / this.headDim);
327
+ }
328
+ this.ropeFreqs = MlxArray.fromFloat32(freqs, [n]);
329
+
330
+ for (let i = 0; i < cfg.num_hidden_layers; i++) {
331
+ const p = `layers.${i}`;
332
+ this.#layers.push({
333
+ qProj: mat(`${p}.self_attn.q_proj`),
334
+ kProj: mat(`${p}.self_attn.k_proj`),
335
+ oProj: mat(`${p}.self_attn.o_proj`),
336
+ qNorm: T(`${p}.self_attn.q_norm.weight`),
337
+ kNorm: T(`${p}.self_attn.k_norm.weight`),
338
+ inputNorm: T(`${p}.input_layernorm.weight`),
339
+ postAttnNorm: T(`${p}.post_attention_layernorm.weight`),
340
+ preFfNorm: T(`${p}.pre_feedforward_layernorm.weight`),
341
+ postFfNorm: T(`${p}.post_feedforward_layernorm.weight`),
342
+ gateProj: mat(`${p}.mlp.gate_proj`),
343
+ upProj: mat(`${p}.mlp.up_proj`),
344
+ downProj: mat(`${p}.mlp.down_proj`),
345
+ layerScalar: T(`${p}.layer_scalar`),
346
+ });
347
+ }
348
+
349
+ if (cfg.markov_rank > 0) {
350
+ this.#markovW1 = table("markov_head.markov_w1"); // [vocab, rank] embedding
351
+ this.#markovW2 = mat("markov_head.markov_w2"); // stored [vocab, rank] Linear
352
+ } else {
353
+ this.#markovW1 = null;
354
+ this.#markovW2 = null;
355
+ }
356
+
357
+ if (cfg.enable_confidence_head) {
358
+ this.#confProj = mat("confidence_head.proj"); // [1, confDim] Linear
359
+ this.#confB = T("confidence_head.proj.bias"); // [1]
360
+ } else {
361
+ this.#confProj = null;
362
+ this.#confB = null;
363
+ }
364
+ }
365
+
366
+ static async load(dir: string): Promise<DeepspecDrafter> {
367
+ const raw = (await Bun.file(`${dir}/config.json`).json()) as Record<string, any>;
368
+ const cfg = readConfig(raw);
369
+ // Quantized siblings (scripts/dspark-quantize-drafter.ts) carry the house
370
+ // quantization block; the released bf16 checkpoint has none → null.
371
+ const quant = parseQuantization(raw.quantization ?? raw.quantization_config);
372
+ const w = await Weights.open(dir);
373
+ return new DeepspecDrafter(w, cfg, quant);
374
+ }
375
+
376
+ /** f32-internal RMSNorm (Gemma4RMSNorm casts through float32 internally:
377
+ * `hidden_states.float()` → norm → `* weight.float()` → `.type_as`).
378
+ * weight=null reproduces `with_scale=False` (v_norm). */
379
+ #rms(x: MlxArray, weight: MlxArray | null): MlxArray {
380
+ const f = x.dtype === Dtype.float32 ? x : x.astype(Dtype.float32);
381
+ const n = ops.rmsNorm(f, weight, this.eps);
382
+ if (f !== x) f.dispose();
383
+ if (n.dtype === x.dtype) return n;
384
+ const back = n.astype(x.dtype);
385
+ n.dispose();
386
+ return back;
387
+ }
388
+
389
+ #geluTanhMlp(x: MlxArray, layer: Layer): MlxArray {
390
+ const g = matmulW(x, layer.gateProj);
391
+ const u = matmulW(x, layer.upProj);
392
+ const act = ops.geluApprox(g); // gelu_pytorch_tanh == config.hidden_activation
393
+ g.dispose();
394
+ let mlp = ops.mul(act, u);
395
+ act.dispose();
396
+ u.dispose();
397
+ mlp = disposing(mlp, matmulW(mlp, layer.downProj));
398
+ return mlp;
399
+ }
400
+
401
+ /**
402
+ * extract_context_feature (common.py):
403
+ * torch.cat([hidden_states[0 if lid==-1 else lid+1] for lid in layer_ids], -1)
404
+ * i.e. tap i (target_layer_ids[i], never -1 for this checkpoint) reads the
405
+ * TARGET's post-layer-i residual output (list-of-all-hidden-states
406
+ * convention: index 0 = embedding, index L+1 = output of layer L). The
407
+ * caller is expected to hand us exactly that: targetHiddens is the
408
+ * concatenation over taps, [1, L, taps*hidden], already ordered to match
409
+ * config.target_layer_ids (ascending, enforced upstream by
410
+ * validate_target_layer_ids).
411
+ *
412
+ * context = hidden_norm(fc(target_hiddens)) — modeling.py _forward_backbone:
413
+ * target_hidden_states = self.hidden_norm(self.fc(target_hidden_states))
414
+ *
415
+ * Returns the projected+normed context hidden [1, L, hidden] (still needs
416
+ * per-layer k_proj + k_norm + rope to become cacheable ContextKV — see
417
+ * projectContextKV).
418
+ */
419
+ projectContext(targetHiddens: MlxArray): MlxArray {
420
+ const proj = matmulW(targetHiddens, this.#fc); // [1,L,hidden]
421
+ return disposing(proj, this.#rms(proj, this.#hiddenNorm));
422
+ }
423
+
424
+ /**
425
+ * Per-layer context K/V rows, projected + normed + ROPE'd, ready to cache
426
+ * across draft rounds.
427
+ *
428
+ * Justification for caching at this stage (from modeling.py's
429
+ * Gemma4DSparkAttention.forward, transcribed above the port below):
430
+ * k_ctx = self.k_proj(target_hidden_states) # per-layer proj
431
+ * k = torch.cat([k_ctx, k_noise], dim=1).view(...) # concat BEFORE norm
432
+ * k = self.k_norm(k).transpose(1, 2) # norm over the concat
433
+ * k = apply_gemma4_rotary_pos_emb(k, cos, sin, ...) # rope over the concat
434
+ * if past_key_values is not None:
435
+ * k, v = past_key_values.update(k, v, self.layer_idx, cache_kwargs) # CACHE AFTER ROPE
436
+ *
437
+ * Gemma4RMSNorm normalizes over the LAST axis (head_dim) independently per
438
+ * row; concatenation happens along the sequence axis. So k_norm(cat(ctx,
439
+ * noise))[i] == k_norm(ctx)[i] for every ctx row i — norming the context
440
+ * rows alone and norming them as part of a larger concat batch produce
441
+ * IDENTICAL values (RMSNorm has no cross-row term). RoPE likewise applies
442
+ * per-position (absolute position index, stable per context row across
443
+ * rounds) independent of what else shares the batch. Caching post-norm,
444
+ * post-rope context K rows is therefore bit-exact equivalent to
445
+ * recomputing them fresh inside every round's concat — which is exactly
446
+ * what DeepSpec's own DynamicCache.update-after-rope does (it caches the
447
+ * already roped/normed tensor, then crop() drops only the noise suffix).
448
+ *
449
+ * v ≡ k when attention_k_eq_v (v_proj is absent; v_norm is the SAME
450
+ * concat-then-scale-less-norm, over k_proj's output — v gets NO rope).
451
+ */
452
+ projectContextKV(contextHidden: MlxArray, positions: number[]): ContextKV[] {
453
+ const L = contextHidden.shape[1]!;
454
+ if (positions.length !== L)
455
+ throw new Error(`projectContextKV: ${positions.length} positions for ${L} context rows`);
456
+ const out: ContextKV[] = [];
457
+ for (const layer of this.#layers) {
458
+ const kFlat = matmulW(contextHidden, layer.kProj); // [1,L,nKvHeads*headDim]
459
+ const k4 = ops.reshape(kFlat, [1, L, this.nKvHeads, this.headDim]);
460
+ kFlat.dispose();
461
+ // v ≡ k pre-norm (attention_k_eq_v: v_ctx = k_ctx, same tensor before
462
+ // the two norms diverge — v_norm has no weight).
463
+ const vNormed = this.#rms(k4, null); // scale-less
464
+ const kNormed = this.#rms(k4, layer.kNorm);
465
+ k4.dispose();
466
+
467
+ const kT = ops.transposeAxes(kNormed, [0, 2, 1, 3]); // [1,nKvHeads,L,headDim]
468
+ kNormed.dispose();
469
+ const vT = ops.transposeAxes(vNormed, [0, 2, 1, 3]);
470
+ vNormed.dispose();
471
+
472
+ // RoPE over context rows at their absolute positions. mx.fast.rope's
473
+ // static `offset` assumes contiguous positions starting at offset; our
474
+ // context rows ARE contiguous (0..L-1 by construction — the taps are
475
+ // read at the same prompt/verified positions every round), so a single
476
+ // rope(offset=positions[0]) call matches apply_gemma4_rotary_pos_emb
477
+ // row-for-row. Guard the assumption explicitly.
478
+ assertContiguous(positions);
479
+ const kRoped = ops.rope(kT, this.headDim, null, positions[0]!, this.ropeFreqs);
480
+ kT.dispose();
481
+ out.push({ k: kRoped, v: vT });
482
+ }
483
+ return out;
484
+ }
485
+
486
+ /**
487
+ * One backbone forward over the noise block, given cached context K/V —
488
+ * modeling.py Gemma4DSparkModel._forward_backbone + Gemma4DSparkAttention,
489
+ * transcribed inline per-layer below. Non-causal SDPA (scale=1.0) over
490
+ * [ctx rows ++ block rows]; q uses only the block's own positions.
491
+ *
492
+ * blockIds: token ids for the noise block, length gamma — [anchor, MASK,
493
+ * MASK, ..., MASK] (create_noise_embed: only position 0 gets the real
494
+ * anchor token when block_keep_mask; MASK elsewhere — at inference every
495
+ * anchor is "kept" so this is always [anchor, mask_token_id × (γ-1)]).
496
+ * blockPositions: absolute positions for the γ block rows (contiguous,
497
+ * anchorPos..anchorPos+γ-1 — create_position_ids's per-block arange).
498
+ */
499
+ #forwardBackbone(ctxKV: ContextKV[], blockIds: number[], blockPositions: number[]): MlxArray {
500
+ const G = blockIds.length;
501
+ assertContiguous(blockPositions);
502
+ const idsArr = ops.fromInt32(blockIds, [1, G]);
503
+ const idsU32 = idsArr.astype(Dtype.uint32);
504
+ idsArr.dispose();
505
+ const embRaw = gatherW(this.#embed, idsU32); // [1,G,hidden] (gather over vocab axis)
506
+ idsU32.dispose();
507
+ const embFlat = ops.reshape(embRaw, [1, G, this.hidden]);
508
+ embRaw.dispose();
509
+ // Gemma4TextScaledWordEmbedding.forward: embed(ids) * embed_scale
510
+ let h = ops.mulScalar(embFlat, this.embedScale);
511
+ embFlat.dispose();
512
+
513
+ for (let li = 0; li < this.#layers.length; li++) {
514
+ const layer = this.#layers[li]!;
515
+ const { k: kCtx, v: vCtx } = ctxKV[li]!;
516
+ const ctxLen = kCtx.shape[2]!;
517
+
518
+ const residual = h;
519
+ const x = this.#rms(h, layer.inputNorm);
520
+
521
+ // q = q_norm(q_proj(x).view(B,q_len,nHeads,headDim)).transpose(1,2)
522
+ const qFlat = matmulW(x, layer.qProj); // [1,G,nHeads*headDim]
523
+ const q4 = ops.reshape(qFlat, [1, G, this.nHeads, this.headDim]);
524
+ qFlat.dispose();
525
+ const qNormed = this.#rms(q4, layer.qNorm);
526
+ q4.dispose();
527
+ const qT = ops.transposeAxes(qNormed, [0, 2, 1, 3]); // [1,nHeads,G,headDim]
528
+ qNormed.dispose();
529
+ // rope on q uses the LAST q_len positions (cos[:, -q_len:, :]) — here
530
+ // q_len == G == the whole block, so "last q_len" is just the block's
531
+ // own positions, contiguous from blockPositions[0].
532
+ const qRoped = ops.rope(qT, this.headDim, null, blockPositions[0]!, this.ropeFreqs);
533
+ qT.dispose();
534
+
535
+ // k_noise = k_proj(x); norm+rope IDENTICALLY to the cached context
536
+ // rows (concat-then-norm == norm-then-concat per the RMSNorm argument
537
+ // in projectContextKV's doc comment).
538
+ const kNoiseFlat = matmulW(x, layer.kProj);
539
+ const kNoise4 = ops.reshape(kNoiseFlat, [1, G, this.nKvHeads, this.headDim]);
540
+ kNoiseFlat.dispose();
541
+ const vNoiseNormed = this.#rms(kNoise4, null);
542
+ const kNoiseNormed = this.#rms(kNoise4, layer.kNorm);
543
+ kNoise4.dispose();
544
+ const kNoiseT = ops.transposeAxes(kNoiseNormed, [0, 2, 1, 3]);
545
+ kNoiseNormed.dispose();
546
+ const vNoiseT = ops.transposeAxes(vNoiseNormed, [0, 2, 1, 3]);
547
+ vNoiseNormed.dispose();
548
+ const kNoiseRoped = ops.rope(kNoiseT, this.headDim, null, blockPositions[0]!, this.ropeFreqs);
549
+ kNoiseT.dispose();
550
+ x.dispose();
551
+
552
+ // k = cat([k_ctx, k_noise], dim=seq); v = cat([v_ctx, v_noise], dim=seq)
553
+ const kFull = ops.concatAxis([kCtx, kNoiseRoped], 2); // [1,nKvHeads,ctxLen+G,headDim]
554
+ kNoiseRoped.dispose();
555
+ const vFull = ops.concatAxis([vCtx, vNoiseT], 2);
556
+ vNoiseT.dispose();
557
+
558
+ // non-causal SDPA, scale=1.0 (QK-norm replaces the usual 1/sqrt(d))
559
+ const attnOut = ops.sdpa(qRoped, kFull, vFull, 1.0, "", null);
560
+ qRoped.dispose();
561
+ kFull.dispose();
562
+ vFull.dispose();
563
+ void ctxLen;
564
+
565
+ const attnT = ops.transposeAxes(attnOut, [0, 2, 1, 3]); // [1,G,nHeads,headDim]
566
+ attnOut.dispose();
567
+ const attnFlat = ops.reshape(attnT, [1, G, this.nHeads * this.headDim]);
568
+ attnT.dispose();
569
+ let attn = matmulW(attnFlat, layer.oProj);
570
+ attnFlat.dispose();
571
+ attn = disposing(attn, this.#rms(attn, layer.postAttnNorm));
572
+ h = ops.add(residual, attn);
573
+ residual.dispose();
574
+ attn.dispose();
575
+
576
+ const res2 = h;
577
+ const f = this.#rms(h, layer.preFfNorm);
578
+ let mlp = this.#geluTanhMlp(f, layer);
579
+ f.dispose();
580
+ mlp = disposing(mlp, this.#rms(mlp, layer.postFfNorm));
581
+ h = ops.add(res2, mlp);
582
+ res2.dispose();
583
+ mlp.dispose();
584
+
585
+ // Gemma4DSparkDecoderLayer.forward: `return hidden_states * self.layer_scalar`
586
+ // — the scalar multiplies the WHOLE layer output (residual-sum
587
+ // INCLUDED, not just the sublayer delta).
588
+ h = disposing(h, ops.mul(h, layer.layerScalar));
589
+ }
590
+
591
+ return disposing(h, this.#rms(h, this.#norm));
592
+ }
593
+
594
+ /** lm_head(h) then softcap: `tanh(logits/cap)*cap` (compute_logits). */
595
+ #computeLogits(h: MlxArray): MlxArray {
596
+ const logits = matmulW(h, this.#lmHead);
597
+ if (this.cfg.final_logit_softcapping === null) return logits;
598
+ const cap = this.cfg.final_logit_softcapping;
599
+ const capArr = ops.scalarLike(cap, logits);
600
+ const scaled = ops.div(logits, capArr);
601
+ logits.dispose();
602
+ const t = ops.tanh(scaled);
603
+ scaled.dispose();
604
+ const out = ops.mul(t, capArr);
605
+ t.dispose();
606
+ capArr.dispose();
607
+ return out;
608
+ }
609
+
610
+ /** B_k = markov_w2(markov_w1(prevTok)) — VanillaMarkov.compute_step_bias /
611
+ * project_bias(get_prev_embeddings(token_ids)). Returns [1,vocab] in MODEL
612
+ * dtype (bf16 on the real checkpoint) — the reference samples over the
613
+ * bf16 `logits + bias` sum, and softcapped logits in [-30,30] have bf16
614
+ * steps ~0.125-0.25, so an f32 sum here reorders near-ties vs torch and
615
+ * derails the sequential block (2026-07-06 port review, fidelity fix). */
616
+ #markovStepBias(prevTok: number): MlxArray {
617
+ if (!this.#markovW1 || !this.#markovW2)
618
+ throw new Error("markovStepBias: markov_rank == 0 (no markov head)");
619
+ const idxArr = ops.fromInt32([prevTok], [1]);
620
+ const idxU32 = idxArr.astype(Dtype.uint32);
621
+ idxArr.dispose();
622
+ const e1 = gatherW(this.#markovW1, idxU32); // [1,rank]
623
+ idxU32.dispose();
624
+ const bias = matmulW(e1, this.#markovW2); // [1,vocab], model dtype
625
+ e1.dispose();
626
+ return bias;
627
+ }
628
+
629
+ /** c_k = sigmoid(proj([h_k; markov_w1[prevTok]])). h1 is [1,hidden]
630
+ * (already the right dtype/shape row for this position). AcceptRatePredictor
631
+ * is nn.Linear(confDim,1) — proj.weight is [1,confDim]; we compute
632
+ * features @ proj.weight^T + bias without transposing storage (row-vector
633
+ * dot via matmul against a [confDim,1] view). */
634
+ #confidence(h1: MlxArray, prevTok: number): number {
635
+ if (!this.#confProj || !this.#confB)
636
+ throw new Error("confidence: confidence head disabled");
637
+ let feat = h1;
638
+ let ownFeat = false;
639
+ if (this.cfg.confidence_head_with_markov) {
640
+ if (!this.#markovW1) throw new Error("confidence_head_with_markov requires markov_rank > 0");
641
+ const idxArr = ops.fromInt32([prevTok], [1]);
642
+ const idxU32 = idxArr.astype(Dtype.uint32);
643
+ idxArr.dispose();
644
+ const e1 = gatherW(this.#markovW1, idxU32); // [1,rank]
645
+ idxU32.dispose();
646
+ const e1f = e1.dtype === h1.dtype ? e1 : disposing(e1, e1.astype(h1.dtype));
647
+ feat = ops.concatAxis([h1, e1f], 1); // [1, hidden+rank]
648
+ e1f.dispose();
649
+ ownFeat = true;
650
+ }
651
+ // Reference precision (AcceptRatePredictor / predict_confidence_step):
652
+ // the nn.Linear runs in MODEL dtype (bf16 on the real checkpoint) and is
653
+ // .float()ed AFTER — computing it in f32 here flipped borderline
654
+ // threshold comparisons vs torch (2026-07-06 port review). So: matmul +
655
+ // bias in feat's dtype (matmulW: the once-built transpose view for bf16,
656
+ // qmm transpose=true for a quantized head), then cast.
657
+ let z = matmulW(feat, this.#confProj);
658
+ if (ownFeat) feat.dispose();
659
+ z = disposing(z, ops.add(z, this.#confB));
660
+ if (z.dtype !== Dtype.float32) z = disposing(z, z.astype(Dtype.float32));
661
+ z = disposing(z, ops.sigmoid(z));
662
+ const v = z.toFloat32()[0]!;
663
+ z.dispose();
664
+ return v;
665
+ }
666
+
667
+ /**
668
+ * The whole per-round draft. Two-pass structure, matching the source
669
+ * exactly (draft_ops.py build_dspark_proposal calls sample_draft_tokens
670
+ * for the FULL block first, THEN predicts confidence over the full
671
+ * sampled sequence, THEN truncates — confidence does not short-circuit
672
+ * sampling):
673
+ *
674
+ * base_draft_logits = model.compute_logits(proposal_hidden_states) # [1,γ,V], softcapped
675
+ * sampled_tokens, draft_logits = model.sample_draft_tokens( # full γ, sequential Markov
676
+ * base_draft_logits, first_prev_token_ids=anchor, temperature=0)
677
+ * confidence_logits = predict_confidence_step( # full γ, over the SAMPLED prevs
678
+ * proposal_hidden_states,
679
+ * prev_token_ids=cat([anchor, sampled_tokens[:, :-1]]))
680
+ * proposal_draft_tokens = _confident_prefix_length(confidence_logits, threshold)
681
+ * verify_input_ids = cat([anchor, sampled_tokens[:, :proposal_draft_tokens]])
682
+ *
683
+ * Transcribed sequential Markov sampling (modeling.py sample_draft_tokens
684
+ * → markov_head.py VanillaMarkov.sample_block_tokens, temperature=0 ⇒
685
+ * sample_tokens's argmax branch — RNG-free):
686
+ * prev = first_prev_token_ids # == anchorTok
687
+ * for k in range(block_size):
688
+ * step_logits = base_logits[:,k] + markov_w2(markov_w1(prev))
689
+ * tok = argmax(step_logits)
690
+ * prev = tok
691
+ *
692
+ * Transcribed confidence truncation (draft_ops.py _confident_prefix_length):
693
+ * if threshold <= 0: return block_size # disabled — full γ
694
+ * below = sigmoid(confidence_logits) < threshold
695
+ * if not below.any(): return block_size
696
+ * return first index where below is True # ℓ can be 0 (EMPTY proposal)
697
+ *
698
+ * ctxKV: this round's cached context K/V (see projectContextKV/crop notes
699
+ * on the class doc — caller owns cache lifetime and crop-after-round).
700
+ * anchorTok: the just-verified/bonus token starting this block.
701
+ * anchorPos: its absolute sequence position (blockPositions[0]).
702
+ */
703
+ draftBlock(ctxKV: ContextKV[], anchorTok: number, anchorPos: number): DraftBlockResult {
704
+ const G = this.gamma;
705
+ const V = this.cfg.vocab_size;
706
+ const blockIds = [anchorTok, ...Array(G - 1).fill(this.cfg.mask_token_id)];
707
+ const blockPositions = Array.from({ length: G }, (_, i) => anchorPos + i);
708
+
709
+ const h = this.#forwardBackbone(ctxKV, blockIds, blockPositions); // [1,G,hidden]
710
+ const baseLogitsRaw = this.#computeLogits(h); // [1,G,vocab], softcapped, model dtype
711
+
712
+ // Pass 1: sequential Markov-biased argmax sampling over the FULL block —
713
+ // in MODEL dtype end to end (reference precision: modeling.py
714
+ // compute_logits → apply_step_logits → sample_tokens all run bf16; the
715
+ // argmax is over the bf16 sum. f32 here reordered near-ties vs torch —
716
+ // 2026-07-06 port review, fidelity fix).
717
+ const sampledTokens: number[] = [];
718
+ let prevTok = anchorTok;
719
+ for (let k = 0; k < G; k++) {
720
+ const base1 = baseLogitsRaw.slice([0, k, 0], [1, k + 1, V]);
721
+ const baseFlat = ops.reshape(base1, [1, V]);
722
+ base1.dispose();
723
+ let stepLogits = baseFlat;
724
+ if (this.#markovW1) {
725
+ const bias = this.#markovStepBias(prevTok); // [1,V], model dtype
726
+ stepLogits = ops.add(baseFlat, bias);
727
+ baseFlat.dispose();
728
+ bias.dispose();
729
+ }
730
+ const am = ops.argmaxAxis(stepLogits, -1);
731
+ const tok = ops.itemUint32(am);
732
+ am.dispose();
733
+ stepLogits.dispose();
734
+ sampledTokens.push(tok);
735
+ prevTok = tok;
736
+ }
737
+
738
+ // The returned artifact is an f32 COPY (callers read/compare host-side);
739
+ // sampling above never touches it.
740
+ const baseLogits =
741
+ baseLogitsRaw.dtype === Dtype.float32 ? baseLogitsRaw : disposing(baseLogitsRaw, baseLogitsRaw.astype(Dtype.float32));
742
+
743
+ // Pass 2: confidence over the full block, prev_token_ids = [anchor,
744
+ // sampled[:-1]] (_predict_confidence_logits) — independent of pass 1's
745
+ // truncation decision, computed for every position.
746
+ let proposalLen = G;
747
+ if (this.#confProj) {
748
+ const confVals: number[] = [];
749
+ let confPrev = anchorTok;
750
+ for (let k = 0; k < G; k++) {
751
+ const h1 = h.slice([0, k, 0], [1, k + 1, this.hidden]);
752
+ const h1Flat = ops.reshape(h1, [1, this.hidden]);
753
+ h1.dispose();
754
+ const cVal = this.#confidence(h1Flat, confPrev);
755
+ h1Flat.dispose();
756
+ confVals.push(cVal);
757
+ confPrev = sampledTokens[k]!;
758
+ }
759
+ if (this.cfg.confidence_threshold > 0) {
760
+ const idx = confVals.findIndex((c) => c < this.cfg.confidence_threshold);
761
+ proposalLen = idx === -1 ? G : idx;
762
+ }
763
+ const tokens = sampledTokens.slice(0, proposalLen);
764
+ const conf = confVals.slice(0, proposalLen);
765
+ h.dispose();
766
+ return { tokens, conf, baseLogits };
767
+ }
768
+
769
+ h.dispose();
770
+ return { tokens: sampledTokens, conf: [], baseLogits };
771
+ }
772
+
773
+ dispose(): void {
774
+ disposeW(this.#embed);
775
+ disposeW(this.#fc);
776
+ this.#hiddenNorm.dispose();
777
+ this.#norm.dispose();
778
+ disposeW(this.#lmHead);
779
+ this.ropeFreqs.dispose();
780
+ for (const l of this.#layers) {
781
+ disposeW(l.qProj); disposeW(l.kProj); disposeW(l.oProj);
782
+ l.qNorm.dispose(); l.kNorm.dispose();
783
+ l.inputNorm.dispose(); l.postAttnNorm.dispose();
784
+ l.preFfNorm.dispose(); l.postFfNorm.dispose();
785
+ disposeW(l.gateProj); disposeW(l.upProj); disposeW(l.downProj);
786
+ l.layerScalar.dispose();
787
+ }
788
+ disposeW(this.#markovW1);
789
+ disposeW(this.#markovW2);
790
+ disposeW(this.#confProj);
791
+ this.#confB?.dispose();
792
+ this.#w.dispose();
793
+ }
794
+ }
795
+
796
+ function assertContiguous(positions: number[]): void {
797
+ for (let i = 1; i < positions.length; i++) {
798
+ if (positions[i] !== positions[i - 1]! + 1)
799
+ throw new Error(`DeepspecDrafter: expected contiguous positions, got ${JSON.stringify(positions)}`);
800
+ }
801
+ }