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,557 @@
1
+ import { ExpertIOSlabStore } from "../expert-io";
2
+ import {
3
+ ExpertUsageLedger,
4
+ planExpertAutoPins,
5
+ selectExpertLfruCandidates,
6
+ type ExpertAutoPinPlan,
7
+ } from "../expert-usage";
8
+ import { join } from "node:path";
9
+ import {
10
+ buildExpertHintSegments,
11
+ ExpertResidencyManager,
12
+ DEFAULT_EXPERT_WORKING_SLOTS,
13
+ planExpertResidency,
14
+ type ExpertDemandTelemetry,
15
+ type ExpertLatencySummary,
16
+ type ExpertPolicyTelemetry,
17
+ type ExpertRepinEvent,
18
+ type ExpertResidencyPlan,
19
+ type ExpertResidencyManagerOptions,
20
+ } from "../expert-residency";
21
+ import type { Glm52Config } from "./glm52-config";
22
+ import { ColibriGlm52Container } from "./glm52-container";
23
+ import {
24
+ buildGlm52ExpertSlotLayout,
25
+ type Glm52ExpertSlotLayout,
26
+ } from "./glm52-expert-layout";
27
+ import type {
28
+ Glm52PilotTelemetry,
29
+ Glm52PilotTracker,
30
+ } from "./glm52-pilot";
31
+ import { Glm52StockStreamedExpertExecutor } from "./glm52-streamed-experts";
32
+
33
+ export interface Glm52ExpertRuntimeOptions {
34
+ readonly budgetBytes: number;
35
+ /** Dense/shared/router + KV/transient/allocator/Bun/OS reserve. */
36
+ readonly fixedBytes: number;
37
+ readonly workingSlots?: number;
38
+ readonly maxSlotsPerLayer?: number;
39
+ readonly pinned?: ReadonlyArray<{ layer: number; expertId: number }>;
40
+ readonly workers?: number;
41
+ readonly noCache?: boolean;
42
+ readonly libraryPath?: string;
43
+ readonly decodeKernel?: "stock" | "metal";
44
+ /** Native MTP verify width. The int8 working tier reserves topK*gamma
45
+ * scratch slots plus one persistent LRU slot. */
46
+ readonly mtpDraftTokens?: number;
47
+ readonly enableMtp?: boolean;
48
+ /** Persistent Colibri-compatible route profile. Defaults to
49
+ * `<modelDir>/.coli_usage`; false disables persistence. */
50
+ readonly usagePath?: string | false;
51
+ /** Opt-in G6 candidate. Explicit `pinned` entries take precedence. */
52
+ readonly autoPin?: boolean;
53
+ /** Opt-in G6 candidate: adapt at generation safe points, max four swaps. */
54
+ readonly liveRepin?: boolean;
55
+ /** Opt-in G6 observation: score next-layer router predictions, no I/O. */
56
+ readonly pilotMeasure?: boolean;
57
+ /** Opt-in G6 advisory prefetch width. Zero disables WILLNEED hints. */
58
+ readonly pilotHintK?: number;
59
+ /** Opt-in G6 measurement: score Colibri's shared-expert-corrected route. */
60
+ readonly pilotTwoStep?: boolean;
61
+ /** Opt-in G6 route trace observer for the main target tier only. */
62
+ readonly routeObserver?: ExpertResidencyManagerOptions["routeObserver"];
63
+ }
64
+
65
+ export interface Glm52MtpExpertRuntime {
66
+ readonly plan: ExpertResidencyPlan;
67
+ readonly store: ExpertIOSlabStore;
68
+ readonly manager: ExpertResidencyManager;
69
+ readonly executor: Glm52StockStreamedExpertExecutor;
70
+ readonly slotBytes: number;
71
+ readonly layer: number;
72
+ }
73
+
74
+ export interface Glm52ExpertTierTelemetry {
75
+ readonly demand: ExpertDemandTelemetry;
76
+ readonly policy: ExpertPolicyTelemetry;
77
+ readonly layerForward: ExpertLatencySummary;
78
+ }
79
+
80
+ export interface Glm52ExpertTurnTelemetry {
81
+ readonly main: Glm52ExpertTierTelemetry;
82
+ readonly mtp: Glm52ExpertTierTelemetry | null;
83
+ readonly pilot: Glm52PilotTelemetry | null;
84
+ }
85
+
86
+ export class Glm52ExpertRuntime {
87
+ readonly plan: ExpertResidencyPlan;
88
+ readonly store: ExpertIOSlabStore;
89
+ readonly manager: ExpertResidencyManager;
90
+ readonly executor: Glm52StockStreamedExpertExecutor;
91
+ readonly slotBytes: number;
92
+ readonly sparseLayerIds: readonly number[];
93
+ readonly mtp: Glm52MtpExpertRuntime | null;
94
+ readonly mtpExecutor: Glm52StockStreamedExpertExecutor | null;
95
+ readonly usage: ExpertUsageLedger | null;
96
+ readonly autoPin: ExpertAutoPinPlan | null;
97
+ readonly pilotMeasureEnabled: boolean;
98
+ readonly pilotHintK: number;
99
+ readonly pilotTwoStep: boolean;
100
+ lastRepin: readonly ExpertRepinEvent[] = Object.freeze([]);
101
+ lastTelemetry: Glm52ExpertTurnTelemetry | null = null;
102
+ #liveRepin: boolean;
103
+ #pilot: Glm52PilotTracker | null = null;
104
+ #layouts = new Map<string, Glm52ExpertSlotLayout>();
105
+ #mtpLayouts = new Map<string, Glm52ExpertSlotLayout>();
106
+
107
+ private constructor(
108
+ plan: ExpertResidencyPlan,
109
+ store: ExpertIOSlabStore,
110
+ manager: ExpertResidencyManager,
111
+ executor: Glm52StockStreamedExpertExecutor,
112
+ slotBytes: number,
113
+ sparseLayerIds: readonly number[],
114
+ mtp: Glm52MtpExpertRuntime | null,
115
+ usage: ExpertUsageLedger | null,
116
+ autoPin: ExpertAutoPinPlan | null,
117
+ liveRepin: boolean,
118
+ pilotMeasure: boolean,
119
+ pilotHintK: number,
120
+ pilotTwoStep: boolean,
121
+ ) {
122
+ this.plan = plan;
123
+ this.store = store;
124
+ this.manager = manager;
125
+ this.executor = executor;
126
+ this.slotBytes = slotBytes;
127
+ this.sparseLayerIds = sparseLayerIds;
128
+ this.mtp = mtp;
129
+ this.mtpExecutor = mtp?.executor ?? null;
130
+ this.usage = usage;
131
+ this.autoPin = autoPin;
132
+ this.#liveRepin = liveRepin;
133
+ this.pilotMeasureEnabled = pilotMeasure;
134
+ this.pilotHintK = pilotHintK;
135
+ this.pilotTwoStep = pilotTwoStep;
136
+ }
137
+
138
+ static async open(
139
+ modelDir: string,
140
+ config: Glm52Config,
141
+ options: Glm52ExpertRuntimeOptions,
142
+ ): Promise<Glm52ExpertRuntime> {
143
+ const container = ColibriGlm52Container.open(modelDir);
144
+ const sparseLayerIds = Array.from(
145
+ { length: config.numHiddenLayers - config.firstKDenseReplace },
146
+ (_, index) => config.firstKDenseReplace + index,
147
+ );
148
+ if (sparseLayerIds.length === 0)
149
+ throw new Error("GLM expert residency requires at least one sparse layer");
150
+ const representative = buildGlm52ExpertSlotLayout(
151
+ container,
152
+ config,
153
+ sparseLayerIds[0]!,
154
+ 0,
155
+ );
156
+ const capabilities = container.capabilities(config);
157
+ const mtpLayer = config.numHiddenLayers;
158
+ const mtpRepresentative = capabilities.hasMtp && options.enableMtp !== false
159
+ ? buildGlm52ExpertSlotLayout(container, config, mtpLayer, 0)
160
+ : null;
161
+ const mtpDraftTokens = options.mtpDraftTokens ?? 3;
162
+ if (!Number.isSafeInteger(mtpDraftTokens) || mtpDraftTokens < 1)
163
+ throw new Error("GLM MTP draft token count must be a positive safe integer");
164
+ const pilotHintK = options.pilotHintK ?? 0;
165
+ if (!Number.isSafeInteger(pilotHintK) || pilotHintK < 0 ||
166
+ pilotHintK > config.numExpertsPerToken) {
167
+ throw new Error(
168
+ `GLM PILOT hint K must be in 0..${config.numExpertsPerToken}`,
169
+ );
170
+ }
171
+ const pilotTwoStep = options.pilotTwoStep === true;
172
+ if (pilotTwoStep && pilotHintK > 0) {
173
+ throw new Error(
174
+ "GLM PILOT two-step measurement cannot submit baseline-only hints",
175
+ );
176
+ }
177
+ const mtpWorkingSlots = mtpRepresentative
178
+ ? Math.min(
179
+ config.numRoutedExperts,
180
+ config.numExpertsPerToken * mtpDraftTokens,
181
+ )
182
+ : 0;
183
+ const usagePath = options.usagePath === false
184
+ ? null
185
+ : options.usagePath ?? join(modelDir, ".coli_usage");
186
+ const usage = usagePath === null
187
+ ? null
188
+ : ExpertUsageLedger.open({
189
+ path: usagePath,
190
+ layers: mtpRepresentative
191
+ ? [...sparseLayerIds, mtpLayer]
192
+ : sparseLayerIds,
193
+ expertsPerLayer: config.numRoutedExperts,
194
+ onWarning: (message) => console.warn(message),
195
+ });
196
+ if ((options.autoPin || options.liveRepin) && !usage)
197
+ throw new Error("GLM expert learning policies require persistent usage");
198
+ const autoPin = options.autoPin && options.pinned === undefined && usage
199
+ ? planExpertAutoPins({
200
+ ledger: usage,
201
+ residentTierBudgetBytes: Math.max(
202
+ 0,
203
+ options.budgetBytes - options.fixedBytes -
204
+ (options.workingSlots ?? DEFAULT_EXPERT_WORKING_SLOTS) *
205
+ representative.slotBytes -
206
+ mtpWorkingSlots * (mtpRepresentative?.slotBytes ?? 0),
207
+ ),
208
+ mandatoryResidentBytes:
209
+ sparseLayerIds.length * representative.slotBytes +
210
+ (mtpRepresentative?.slotBytes ?? 0),
211
+ slotBytes: (layer) => {
212
+ if (layer === mtpLayer && mtpRepresentative)
213
+ return mtpRepresentative.slotBytes;
214
+ if (sparseLayerIds.includes(layer)) return representative.slotBytes;
215
+ throw new RangeError(`auto-pin layer ${layer} is not managed`);
216
+ },
217
+ })
218
+ : null;
219
+ const autoPins = autoPin?.pins ?? [];
220
+ const pinned = options.pinned ?? autoPins
221
+ .filter((item) => item.layer !== mtpLayer)
222
+ .map(({ layer, expertId }) => ({ layer, expertId }));
223
+ const mtpPinned = autoPins
224
+ .filter((item) => item.layer === mtpLayer)
225
+ .map(({ layer, expertId }) => ({ layer, expertId }));
226
+ for (const item of pinned) {
227
+ if (!sparseLayerIds.includes(item.layer) || item.expertId < 0 ||
228
+ item.expertId >= config.numRoutedExperts ||
229
+ !Number.isSafeInteger(item.expertId)) {
230
+ throw new RangeError(`invalid pinned expert ${item.layer}:${item.expertId}`);
231
+ }
232
+ }
233
+ const mtpPlan = mtpRepresentative
234
+ ? planExpertResidency({
235
+ // physicalFootprint() is process-wide, not slab-local. Give the
236
+ // auxiliary manager the same global ceiling as the main manager;
237
+ // the main plan below is the single source of accounting truth and
238
+ // includes this MTP slab in fixedBytes.
239
+ budgetBytes: options.budgetBytes,
240
+ fixedBytes: 0,
241
+ slotBytes: mtpRepresentative.slotBytes,
242
+ sparseLayers: 1,
243
+ workingSlots: mtpWorkingSlots,
244
+ pinnedExperts: mtpPinned.length,
245
+ maxSlotsPerLayer: 1,
246
+ })
247
+ : null;
248
+ const plan = planExpertResidency({
249
+ budgetBytes: options.budgetBytes,
250
+ fixedBytes: options.fixedBytes + (mtpPlan?.slabBytes ?? 0),
251
+ slotBytes: representative.slotBytes,
252
+ sparseLayers: sparseLayerIds.length,
253
+ workingSlots: options.workingSlots,
254
+ pinnedExperts: pinned.length,
255
+ maxSlotsPerLayer: options.maxSlotsPerLayer,
256
+ });
257
+ const mainFiles = container.files
258
+ .filter((file) => file.family === "main")
259
+ .map((file) => file.path);
260
+ const fileIndex = new Map(
261
+ mainFiles.map((path, index) => [path, index]),
262
+ );
263
+ const mtpFiles = container.files
264
+ .filter((file) => file.family === "mtp")
265
+ .map((file) => file.path);
266
+ const mtpFileIndex = new Map(
267
+ mtpFiles.map((path, index) => [path, index]),
268
+ );
269
+ const layouts = new Map<string, Glm52ExpertSlotLayout>();
270
+ const layout = (layer: number, expertId: number): Glm52ExpertSlotLayout => {
271
+ const key = `${layer}:${expertId}`;
272
+ let value = layouts.get(key);
273
+ if (!value) {
274
+ value = buildGlm52ExpertSlotLayout(
275
+ container,
276
+ config,
277
+ layer,
278
+ expertId,
279
+ );
280
+ if (value.slotBytes !== representative.slotBytes)
281
+ throw new Error(
282
+ `${key}: expert slot ${value.slotBytes} != ${representative.slotBytes}`,
283
+ );
284
+ layouts.set(key, value);
285
+ }
286
+ return value;
287
+ };
288
+ const store = new ExpertIOSlabStore(mainFiles, {
289
+ slots: plan.totalSlots,
290
+ slotBytes: representative.slotBytes,
291
+ workers: options.workers,
292
+ noCache: options.noCache,
293
+ // These slots are the bounded resident/working expert cache, not an
294
+ // expendable file cache. Letting macOS compress them turns every warm
295
+ // forward into decompression churn and invalidates the G5 equation.
296
+ wireSlots: true,
297
+ libraryPath: options.libraryPath,
298
+ });
299
+ let mtpStore: ExpertIOSlabStore | null = null;
300
+ let executor: Glm52StockStreamedExpertExecutor | null = null;
301
+ let mtpExecutor: Glm52StockStreamedExpertExecutor | null = null;
302
+ try {
303
+ if (mtpPlan && mtpRepresentative) {
304
+ mtpStore = new ExpertIOSlabStore(mtpFiles, {
305
+ slots: mtpPlan.totalSlots,
306
+ slotBytes: mtpRepresentative.slotBytes,
307
+ workers: options.workers,
308
+ noCache: options.noCache,
309
+ wireSlots: true,
310
+ libraryPath: options.libraryPath,
311
+ });
312
+ }
313
+ const manager = new ExpertResidencyManager({
314
+ plan,
315
+ sparseLayerIds,
316
+ backend: store,
317
+ pinned,
318
+ usage: usage ?? undefined,
319
+ routeObserver: options.routeObserver,
320
+ locate: (layer, expertId) => {
321
+ const value = layout(layer, expertId);
322
+ const segments = value.segments.map((segment) => {
323
+ const file = fileIndex.get(segment.file);
324
+ if (file === undefined)
325
+ throw new Error(`${layer}:${expertId}: non-main expert shard`);
326
+ return {
327
+ file,
328
+ offset: segment.sourceOffset,
329
+ destination: segment.destinationOffset,
330
+ length: segment.length,
331
+ };
332
+ });
333
+ const hintSegments = buildExpertHintSegments(
334
+ segments,
335
+ value.scaleOffset,
336
+ options.noCache !== false,
337
+ );
338
+ return {
339
+ layer,
340
+ expertId,
341
+ segments,
342
+ hintSegments,
343
+ };
344
+ },
345
+ });
346
+ executor = new Glm52StockStreamedExpertExecutor({
347
+ manager,
348
+ store,
349
+ layout,
350
+ hiddenSize: config.hiddenSize,
351
+ // G1/G3 quiet-machine selection: custom Metal wins eligible M=1
352
+ // expert jobs; the hybrid executor falls back to stock MLX for
353
+ // multi-row ragged/prefill jobs. Keep an explicit "stock" override
354
+ // for oracle and diagnostic runs.
355
+ decodeKernel: options.decodeKernel ?? "metal",
356
+ });
357
+ let mtp: Glm52MtpExpertRuntime | null = null;
358
+ const mtpLayouts = new Map<string, Glm52ExpertSlotLayout>();
359
+ if (mtpPlan && mtpRepresentative && mtpStore) {
360
+ const mtpLayout = (
361
+ layer: number,
362
+ expertId: number,
363
+ ): Glm52ExpertSlotLayout => {
364
+ if (layer !== mtpLayer)
365
+ throw new Error(`MTP expert layer ${layer} != ${mtpLayer}`);
366
+ const key = `${layer}:${expertId}`;
367
+ let value = mtpLayouts.get(key);
368
+ if (!value) {
369
+ value = buildGlm52ExpertSlotLayout(
370
+ container,
371
+ config,
372
+ layer,
373
+ expertId,
374
+ );
375
+ if (value.bits !== 8)
376
+ throw new Error(`${key}: MTP expert must be signed int8`);
377
+ if (value.slotBytes !== mtpRepresentative.slotBytes) {
378
+ throw new Error(
379
+ `${key}: MTP expert slot ${value.slotBytes} != ` +
380
+ `${mtpRepresentative.slotBytes}`,
381
+ );
382
+ }
383
+ mtpLayouts.set(key, value);
384
+ }
385
+ return value;
386
+ };
387
+ const mtpManager = new ExpertResidencyManager({
388
+ plan: mtpPlan,
389
+ sparseLayerIds: [mtpLayer],
390
+ backend: mtpStore,
391
+ pinned: mtpPinned,
392
+ usage: usage ?? undefined,
393
+ locate: (layer, expertId) => {
394
+ const value = mtpLayout(layer, expertId);
395
+ return {
396
+ layer,
397
+ expertId,
398
+ segments: value.segments.map((segment) => {
399
+ const file = mtpFileIndex.get(segment.file);
400
+ if (file === undefined)
401
+ throw new Error(`${layer}:${expertId}: non-MTP expert shard`);
402
+ return {
403
+ file,
404
+ offset: segment.sourceOffset,
405
+ destination: segment.destinationOffset,
406
+ length: segment.length,
407
+ };
408
+ }),
409
+ };
410
+ },
411
+ });
412
+ mtpExecutor = new Glm52StockStreamedExpertExecutor({
413
+ manager: mtpManager,
414
+ store: mtpStore,
415
+ layout: mtpLayout,
416
+ hiddenSize: config.hiddenSize,
417
+ // The signed-Q8 custom kernel is one fixed family for both S=1
418
+ // drafts and S>1 accepted-token absorption (SPEC_PIN equivalent).
419
+ // Preserve the explicit stock-kernel diagnostic escape hatch across
420
+ // both the target and MTP tiers.
421
+ decodeKernel: options.decodeKernel ?? "metal",
422
+ });
423
+ mtp = {
424
+ plan: mtpPlan,
425
+ store: mtpStore,
426
+ manager: mtpManager,
427
+ executor: mtpExecutor,
428
+ slotBytes: mtpRepresentative.slotBytes,
429
+ layer: mtpLayer,
430
+ };
431
+ }
432
+ const runtime = new Glm52ExpertRuntime(
433
+ plan,
434
+ store,
435
+ manager,
436
+ executor,
437
+ representative.slotBytes,
438
+ Object.freeze(sparseLayerIds),
439
+ mtp,
440
+ usage,
441
+ autoPin,
442
+ options.liveRepin === true,
443
+ options.pilotMeasure === true || pilotHintK > 0 || pilotTwoStep,
444
+ pilotHintK,
445
+ pilotTwoStep,
446
+ );
447
+ await manager.preloadPinned();
448
+ await mtp?.manager.preloadPinned();
449
+ runtime.#layouts = layouts;
450
+ runtime.#mtpLayouts = mtpLayouts;
451
+ return runtime;
452
+ } catch (error) {
453
+ mtpExecutor?.dispose();
454
+ executor?.dispose();
455
+ mtpStore?.close();
456
+ store.close();
457
+ throw error;
458
+ }
459
+ }
460
+
461
+ close(): void {
462
+ let flushError: unknown = null;
463
+ try {
464
+ this.flushUsage();
465
+ } catch (error) {
466
+ flushError = error;
467
+ }
468
+ this.mtp?.executor.dispose();
469
+ this.mtp?.store.close();
470
+ this.executor.dispose();
471
+ this.store.close();
472
+ if (flushError) throw flushError;
473
+ }
474
+
475
+ /** Generation safe-point: atomically publish target + MTP route counts. */
476
+ flushUsage(): void {
477
+ this.usage?.flush();
478
+ }
479
+
480
+ attachPilot(pilot: Glm52PilotTracker): void {
481
+ if (!this.pilotMeasureEnabled)
482
+ throw new Error("cannot attach GLM PILOT when measurement is disabled");
483
+ if (this.#pilot)
484
+ throw new Error("GLM PILOT tracker is already attached");
485
+ this.#pilot = pilot;
486
+ }
487
+
488
+ /** Turn boundary: adapt the shared target/MTP tier, decay heat, then save. */
489
+ async finishUsage(): Promise<void> {
490
+ const mainDemand = this.manager.drainDemandTelemetry();
491
+ const mainForward = this.executor.drainForwardTelemetry();
492
+ const mtpDemand = this.mtp?.manager.drainDemandTelemetry() ?? null;
493
+ const mtpForward = this.mtp?.executor.drainForwardTelemetry() ?? null;
494
+ const pilot = this.#pilot?.drainTelemetry() ?? null;
495
+ const publishTelemetry = (): void => {
496
+ this.lastTelemetry = {
497
+ main: {
498
+ demand: mainDemand,
499
+ policy: this.manager.drainPolicyTelemetry(),
500
+ layerForward: mainForward,
501
+ },
502
+ mtp: this.mtp && mtpDemand && mtpForward
503
+ ? {
504
+ demand: mtpDemand,
505
+ policy: this.mtp.manager.drainPolicyTelemetry(),
506
+ layerForward: mtpForward,
507
+ }
508
+ : null,
509
+ pilot,
510
+ };
511
+ };
512
+ if (!this.#liveRepin || !this.usage) {
513
+ this.lastRepin = Object.freeze([]);
514
+ publishTelemetry();
515
+ this.flushUsage();
516
+ return;
517
+ }
518
+ const candidates = [
519
+ ...this.manager.repinCandidates().map((candidate) => ({
520
+ manager: this.manager,
521
+ candidate,
522
+ })),
523
+ ...(this.mtp?.manager.repinCandidates() ?? []).map((candidate) => ({
524
+ manager: this.mtp!.manager,
525
+ candidate,
526
+ })),
527
+ ];
528
+ const selected = new Set(selectExpertLfruCandidates(
529
+ candidates.map((item) => item.candidate),
530
+ 4,
531
+ ));
532
+ const planned = candidates.filter((item) => selected.has(item.candidate));
533
+ const events: ExpertRepinEvent[] = [];
534
+ let repinError: unknown = null;
535
+ try {
536
+ for (const item of planned)
537
+ events.push(await item.manager.applyRepin(item.candidate));
538
+ } catch (error) {
539
+ repinError = error;
540
+ }
541
+ this.lastRepin = Object.freeze(events.slice());
542
+ this.usage.decayHeat();
543
+ publishTelemetry();
544
+ try {
545
+ this.flushUsage();
546
+ } catch (flushError) {
547
+ if (repinError) {
548
+ throw new AggregateError(
549
+ [repinError, flushError],
550
+ "live repin and expert usage flush both failed",
551
+ );
552
+ }
553
+ throw flushError;
554
+ }
555
+ if (repinError) throw repinError;
556
+ }
557
+ }
@@ -0,0 +1,135 @@
1
+ import type { MlxArray } from "../mlx/array";
2
+ import type { Glm52WeightSource } from "./glm52";
3
+ import { ColibriGlm52Container } from "./glm52-container";
4
+ import { ColibriGlm52Weights } from "./glm52-weights";
5
+
6
+ const ROUTED_EXPERT = /\.mlp\.experts\.\d+\./;
7
+
8
+ /**
9
+ * Dense/shared/router-only view of the direct Colibri artifact. Even if an
10
+ * owning safetensors shard also contains routed tensors, this boundary refuses
11
+ * their names so the streamed model cannot silently fall back to mmap.
12
+ */
13
+ export class ColibriGlm52ResidentWeights implements Glm52WeightSource {
14
+ readonly container: ColibriGlm52Container;
15
+ readonly weightsBytes: number;
16
+ readonly source: ColibriGlm52Weights;
17
+ readonly #allowed: ReadonlySet<string>;
18
+
19
+ private constructor(
20
+ container: ColibriGlm52Container,
21
+ source: ColibriGlm52Weights,
22
+ allowed: ReadonlySet<string>,
23
+ weightsBytes: number,
24
+ ) {
25
+ this.container = container;
26
+ this.source = source;
27
+ this.#allowed = allowed;
28
+ this.weightsBytes = weightsBytes;
29
+ }
30
+
31
+ static open(
32
+ modelDir: string,
33
+ options: { includeMtp?: boolean } = {},
34
+ ): ColibriGlm52ResidentWeights {
35
+ const container = ColibriGlm52Container.open(modelDir);
36
+ const names = [...container.tensors.values()]
37
+ .filter((tensor) =>
38
+ (options.includeMtp !== false || tensor.family !== "mtp") &&
39
+ !ROUTED_EXPERT.test(tensor.name))
40
+ .map((tensor) => tensor.name);
41
+ const allowed = new Set(names);
42
+ const weightsBytes = names.reduce(
43
+ (total, name) => total + container.info(name).byteLength,
44
+ 0,
45
+ );
46
+ const source = ColibriGlm52Weights.openSelected(modelDir, names);
47
+ return new ColibriGlm52ResidentWeights(
48
+ container,
49
+ source,
50
+ allowed,
51
+ weightsBytes,
52
+ );
53
+ }
54
+
55
+ get mappedShardCount(): number {
56
+ return this.source.mappedShardCount;
57
+ }
58
+
59
+ get mappedShardBytes(): number {
60
+ return this.source.mappedShardBytes;
61
+ }
62
+
63
+ has(name: string): boolean {
64
+ return this.#allowed.has(name);
65
+ }
66
+
67
+ tensor(name: string): MlxArray {
68
+ this.#check(name);
69
+ return this.source.tensor(name);
70
+ }
71
+
72
+ dequantized(
73
+ name: string,
74
+ outputRows: number,
75
+ inputColumns: number,
76
+ ): MlxArray {
77
+ this.#check(name);
78
+ return this.source.dequantized(name, outputRows, inputColumns);
79
+ }
80
+
81
+ linear(
82
+ input: MlxArray,
83
+ name: string,
84
+ outputRows: number,
85
+ inputColumns: number,
86
+ ): MlxArray {
87
+ this.#check(name);
88
+ const info = this.container.info(name);
89
+ const descriptor = info.dtype === "U8"
90
+ ? this.source.quantized(name, outputRows, inputColumns)
91
+ : null;
92
+ if (name === "lm_head.weight" && descriptor?.bits === 8) {
93
+ return this.source.linearInt8Tiled(
94
+ input,
95
+ name,
96
+ outputRows,
97
+ inputColumns,
98
+ );
99
+ }
100
+ if (
101
+ descriptor?.bits === 4 &&
102
+ inputColumns >= 32 &&
103
+ inputColumns % 32 === 0
104
+ ) {
105
+ return this.source.linearQ4(
106
+ input,
107
+ name,
108
+ outputRows,
109
+ inputColumns,
110
+ );
111
+ }
112
+ return this.source.linear(input, name, outputRows, inputColumns);
113
+ }
114
+
115
+ embedding(
116
+ ids: MlxArray,
117
+ name: string,
118
+ vocabSize: number,
119
+ hiddenSize: number,
120
+ ): MlxArray {
121
+ this.#check(name);
122
+ return this.source.embeddingRows(ids, name, vocabSize, hiddenSize);
123
+ }
124
+
125
+ dispose(): void {
126
+ this.source.dispose();
127
+ }
128
+
129
+ #check(name: string): void {
130
+ if (ROUTED_EXPERT.test(name))
131
+ throw new Error(`${name}: routed experts require the slab residency backend`);
132
+ if (!this.#allowed.has(name))
133
+ throw new Error(`${name}: tensor is outside the resident GLM weight set`);
134
+ }
135
+ }