mlx-bun 0.4.0 → 1.0.0
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.
- package/README.md +1453 -88
- package/THIRD_PARTY_NOTICES.md +882 -0
- package/bin/mlx-bun.convert.mjs +4 -0
- package/bin/mlx-bun.fuse.mjs +4 -0
- package/bin/mlx-bun.generate.mjs +4 -0
- package/bin/mlx-bun.lora.mjs +4 -0
- package/bin/mlx-bun.mjs +13 -21
- package/bin/mlx-bun.server.mjs +4 -0
- package/bin/mlx-bun.upload.mjs +4 -0
- package/dist/web/app.js +9584 -0
- package/package.json +50 -53
- package/src/cli/ane-install.ts +76 -0
- package/src/cli/args.ts +179 -0
- package/src/cli/engine-entry.ts +68 -0
- package/src/cli/inference.ts +214 -0
- package/src/cli/job-entry.ts +97 -0
- package/src/cli/library-host.ts +117 -0
- package/src/cli/main.ts +57 -0
- package/src/cli/memory-engine.ts +163 -0
- package/src/cli/memory.ts +36 -0
- package/src/cli/mlx-lm-aliases.ts +309 -0
- package/src/cli/model-choice.ts +33 -0
- package/src/cli/model-selection.ts +84 -0
- package/src/cli/module-host.ts +11 -0
- package/src/cli/module-verbs.ts +50 -0
- package/src/cli/numerical-policy.ts +12 -0
- package/src/cli/perplexity.ts +89 -0
- package/src/cli/serve-host.ts +423 -0
- package/src/cli/serve-isolated.ts +217 -0
- package/src/cli/serve-options.ts +106 -0
- package/src/cli/serve-state.ts +205 -0
- package/src/cli/serve.ts +500 -0
- package/src/cli/served-model-host.ts +102 -0
- package/src/cli/server-entry.ts +148 -0
- package/src/cli/serving-unit.ts +177 -0
- package/src/{tui.ts → cli/terminal.ts} +13 -8
- package/src/cli/worker-adapters.ts +34 -0
- package/src/cli/worker-entry.ts +272 -0
- package/src/cli/worker-unit.ts +179 -0
- package/src/engine/adapter-operation.ts +26 -0
- package/src/engine/cache-services.ts +114 -0
- package/src/engine/completion.ts +39 -0
- package/src/engine/generation-gateway.ts +358 -0
- package/src/engine/index.ts +59 -0
- package/src/engine/kv-budget.ts +120 -0
- package/src/engine/media-preparation.ts +232 -0
- package/src/engine/model-binding.ts +24 -0
- package/src/engine/model-host.ts +513 -0
- package/src/engine/model-serving.ts +89 -0
- package/src/{serve → engine}/preparation.ts +10 -8
- package/src/{serve → engine}/session-completion-engine.ts +6 -6
- package/src/engine/telemetry.ts +109 -0
- package/src/hub/downloads.ts +116 -0
- package/src/jobs/db.ts +16 -7
- package/src/jobs/events.ts +29 -0
- package/src/jobs/executable.ts +5 -0
- package/src/jobs/host.ts +51 -0
- package/src/jobs/in-process.ts +55 -0
- package/src/{contracts/jobs.ts → jobs/protocol.ts} +7 -9
- package/src/jobs/runner.ts +150 -231
- package/src/jobs/service.ts +75 -0
- package/src/jobs/sse.ts +59 -23
- package/src/jobs/worker-memory.ts +46 -0
- package/src/jobs/worker-process.ts +163 -0
- package/src/jobs/worker-supervisor.ts +258 -0
- package/src/modules.ts +58 -0
- package/src/publishing/catalog-hub.ts +18 -0
- package/src/publishing/credentials.ts +31 -0
- package/src/publishing/upload.ts +37 -0
- package/src/residency/leased-adapters.ts +21 -0
- package/src/residency/local-records.ts +16 -0
- package/src/residency/model-residency.ts +405 -0
- package/src/residency/record-index.ts +28 -0
- package/src/residency/resident-estimate.ts +50 -0
- package/src/{anthropic.ts → server/anthropic.ts} +3 -81
- package/src/server/cache-routes.ts +36 -0
- package/src/{serve → server}/chat-request.ts +12 -10
- package/src/{serve → server}/chat-stage.ts +27 -22
- package/src/{client.ts → server/client.ts} +28 -2
- package/src/{serve → server}/completion-executor.ts +42 -42
- package/src/server/decision-body.ts +55 -0
- package/src/server/decision-routes.ts +134 -0
- package/src/server/decision-wire.ts +228 -0
- package/src/{serve → server}/discovery-routes.ts +42 -83
- package/src/server/generated-token-history.ts +57 -0
- package/src/{serve → server}/http.ts +25 -13
- package/src/{serve → server}/inference-request.ts +5 -5
- package/src/server/job-routes.ts +20 -0
- package/src/server/media-prompt.ts +63 -0
- package/src/server/memory-completion-client.ts +46 -0
- package/src/server/model-routes.ts +192 -0
- package/src/{serve → server}/openai-wire.ts +3 -2
- package/src/{serve → server}/pipeline.ts +1 -1
- package/src/server/prompt-builder.ts +13 -0
- package/src/server/prompt-contracts.ts +17 -0
- package/src/server/proxy-routes.ts +187 -0
- package/src/server/publishing-routes.ts +41 -0
- package/src/{serve → server}/request-plan.ts +8 -8
- package/src/{serve → server}/request-prep.ts +82 -68
- package/src/{serve → server}/responses-client.ts +30 -13
- package/src/{responses.ts → server/responses.ts} +12 -93
- package/src/server/routes.ts +205 -0
- package/src/server/start.ts +72 -0
- package/src/server/status-routes.ts +108 -0
- package/src/{serve → server}/text-completion-stage.ts +25 -4
- package/src/server/text-prompt.ts +12 -0
- package/src/{serve → server}/token-streams.ts +36 -38
- package/src/server/worker-routes.ts +311 -0
- package/src/storage/paths.ts +61 -0
- package/src/web/assets.ts +37 -0
- package/src/web/{src → browser}/api.ts +5 -23
- package/src/web/browser/chat-host.ts +17 -0
- package/src/web/browser/installed-panels.ts +6 -0
- package/src/web/browser/main.ts +55 -0
- package/src/web/browser/markdown.ts +279 -0
- package/src/web/browser/memory-panel.ts +9 -0
- package/src/web/browser/palette.ts +64 -0
- package/src/web/browser/protocol.ts +13 -0
- package/src/web/browser/shell.ts +467 -0
- package/src/web/{src → browser}/status.ts +32 -36
- package/src/web/build.ts +51 -0
- package/src/web/public/app.html +1054 -0
- package/src/web/{sw.js → public/sw.js} +4 -3
- package/src/web/{vendor → public/vendor}/hljs-theme.css +2 -2
- package/src/web/{vendor → public/vendor}/hljs.js +2 -2
- package/THIRD_PARTY_LICENSES.md +0 -51
- package/docs/README.md +0 -94
- package/docs/archive/hlg-sampling.md +0 -350
- package/docs/archive/investigations/audio-input-plan.md +0 -356
- package/docs/archive/investigations/chunk-finetune-experiment.md +0 -84
- package/docs/archive/investigations/colibri-glm52-port.md +0 -1486
- package/docs/archive/investigations/colibri-oracle-pin.md +0 -1284
- package/docs/archive/investigations/curve-bisector-routing.md +0 -123
- package/docs/archive/investigations/decode-roofline-lookagain.md +0 -348
- package/docs/archive/investigations/diffusion-gemma-port.md +0 -602
- package/docs/archive/investigations/dspark-handoff.md +0 -224
- package/docs/archive/investigations/expert-offload-single-user-moe.md +0 -292
- package/docs/archive/investigations/faithful-l1-consolidation.md +0 -310
- package/docs/archive/investigations/hlg-sampling-investigation.md +0 -970
- package/docs/archive/investigations/indexshare-performance-spike.md +0 -357
- package/docs/archive/investigations/kernel-perf-review-2026-07.md +0 -171
- package/docs/archive/investigations/lab-build-journal.md +0 -157
- package/docs/archive/investigations/minicpm5-decode-megakernel.md +0 -489
- package/docs/archive/investigations/openjarvis-fit.md +0 -198
- package/docs/archive/investigations/openwiki-evaluation.md +0 -249
- package/docs/archive/investigations/optimization_plan.md +0 -346
- package/docs/archive/investigations/orpo-base-uf-experiment-and-directions.md +0 -120
- package/docs/archive/investigations/orpo-flash-cce-pin-leak.md +0 -167
- package/docs/archive/investigations/orpo-uf-testing-handoff.md +0 -126
- package/docs/archive/investigations/pareto-specialized-runtime-findings.md +0 -92
- package/docs/archive/investigations/pi-builtin-investigation.md +0 -308
- package/docs/archive/investigations/pre-colibri-stabilization.md +0 -329
- package/docs/archive/investigations/qwen38-27b-campaign-log.md +0 -1092
- package/docs/archive/investigations/segmented-backward-handoff.md +0 -148
- package/docs/archive/investigations/starter-model-port-handoff.md +0 -342
- package/docs/archive/investigations/steel-flash-cce-handoff.md +0 -489
- package/docs/archive/investigations/the-dreaming-handoff.md +0 -141
- package/docs/archive/investigations/trainer-validation-experiment.md +0 -173
- package/docs/archive/planning/chat-ui-vision-memory-first.md +0 -199
- package/docs/archive/planning/chat-ui-vision.md +0 -50
- package/docs/archive/planning/chunk-task-roadmap.md +0 -77
- package/docs/archive/planning/curve-sampler-research-plan.md +0 -331
- package/docs/archive/planning/journal.md +0 -316
- package/docs/archive/planning/memory-docs-and-dag-plan.md +0 -194
- package/docs/archive/planning/pi-integration-review.md +0 -178
- package/docs/archive/planning/release-notes-v0.0.10.md +0 -57
- package/docs/archive/planning/release-notes-v0.0.11.md +0 -239
- package/docs/archive/planning/release-notes-v0.0.12.md +0 -80
- package/docs/archive/planning/release-notes-v0.0.13.md +0 -77
- package/docs/archive/planning/release-notes-v0.0.9.md +0 -122
- package/docs/archive/planning/release-notes-v0.2.0.md +0 -49
- package/docs/archive/planning/release-notes-v0.3.0.md +0 -35
- package/docs/archive/planning/web-ui-pass-plan.md +0 -213
- package/docs/archive/planning/website-readme-pass-plan.md +0 -224
- package/docs/design/batching.md +0 -1841
- package/docs/design/decode-speed-program.md +0 -2349
- package/docs/design/dreaming-nightly-pipeline.md +0 -684
- package/docs/design/generic-model-support.md +0 -705
- package/docs/design/kv-cache.md +0 -824
- package/docs/design/orpo-training.md +0 -680
- package/docs/design/speculative-decoding.md +0 -1990
- package/docs/design/turboquant.md +0 -2212
- package/docs/design/unified-engine-frontier-plan.md +0 -1880
- package/docs/design/web-chat-redesign.md +0 -695
- package/docs/planning/PRODUCT_ROADMAP.md +0 -594
- package/docs/planning/ResearchTopics.md +0 -119
- package/docs/planning/release-notes-v0.4.0.md +0 -45
- package/docs/planning/video-series.md +0 -421
- package/docs/reference/benchmarks.md +0 -3613
- package/docs/reference/cli.md +0 -585
- package/docs/reference/distribution.md +0 -355
- package/docs/reference/environment.md +0 -398
- package/docs/reference/glossary.md +0 -39
- package/docs/reference/library-api.md +0 -674
- package/docs/reference/memory.md +0 -260
- package/docs/reference/models.md +0 -334
- package/docs/reference/server-api.md +0 -1775
- package/docs/reference/server-config.md +0 -846
- package/docs/reference/training.md +0 -462
- package/docs/reference/troubleshooting.md +0 -158
- package/src/admission-plan.ts +0 -18
- package/src/audio/conformer.ts +0 -647
- package/src/audio/decode.ts +0 -133
- package/src/audio/features.ts +0 -202
- package/src/audio/transcode.ts +0 -67
- package/src/backends/mlx/assistant-target.ts +0 -46
- package/src/backends/mlx/autoregressive-draft-rows.ts +0 -120
- package/src/backends/mlx/autoregressive.ts +0 -108
- package/src/backends/mlx/batch-group.ts +0 -1790
- package/src/backends/mlx/cache-attachment.ts +0 -67
- package/src/backends/mlx/cache-layout.ts +0 -31
- package/src/backends/mlx/checkpoint-state.ts +0 -53
- package/src/backends/mlx/continuation-persistence.ts +0 -106
- package/src/backends/mlx/continuation-request.ts +0 -43
- package/src/backends/mlx/continuation.ts +0 -77
- package/src/backends/mlx/diffusion.ts +0 -39
- package/src/backends/mlx/draft-target.ts +0 -32
- package/src/backends/mlx/evaluation.ts +0 -105
- package/src/backends/mlx/fill-append.ts +0 -45
- package/src/backends/mlx/full-kv-row-append.ts +0 -32
- package/src/backends/mlx/full-kv-row-donor.ts +0 -54
- package/src/backends/mlx/full-transitioning-kv-rows.ts +0 -65
- package/src/backends/mlx/gateway-binding.ts +0 -130
- package/src/backends/mlx/graph.ts +0 -38
- package/src/backends/mlx/kv-codec.ts +0 -9
- package/src/backends/mlx/kv-maintenance.ts +0 -133
- package/src/backends/mlx/kv-tensor-rows.ts +0 -212
- package/src/backends/mlx/memory-client.ts +0 -189
- package/src/backends/mlx/methods.ts +0 -90
- package/src/backends/mlx/model-prompt.ts +0 -164
- package/src/backends/mlx/model-serving.ts +0 -79
- package/src/backends/mlx/prefill-cohort.ts +0 -89
- package/src/backends/mlx/prefill-rows.ts +0 -200
- package/src/backends/mlx/prefill.ts +0 -33
- package/src/backends/mlx/projected-context-rows.ts +0 -72
- package/src/backends/mlx/request-policy.ts +0 -20
- package/src/backends/mlx/request-state-policy.ts +0 -41
- package/src/backends/mlx/rollback.ts +0 -89
- package/src/backends/mlx/row-sampling.ts +0 -49
- package/src/backends/mlx/serial-executor.ts +0 -242
- package/src/backends/mlx/speculative-group.ts +0 -359
- package/src/backends/mlx/speculative-round.ts +0 -161
- package/src/backends/mlx/speculative.ts +0 -114
- package/src/backends/mlx/state-rows.ts +0 -104
- package/src/backends/mlx/state-views.ts +0 -46
- package/src/backends/mlx/target-layout-capability.ts +0 -35
- package/src/backends/mlx/text-engine.ts +0 -73
- package/src/backends/mlx/transitioning-kv-rows.ts +0 -165
- package/src/chat-template.ts +0 -382
- package/src/cli.ts +0 -3168
- package/src/config.ts +0 -399
- package/src/contracts/completion.ts +0 -16
- package/src/contracts/execution.ts +0 -60
- package/src/contracts/generation.ts +0 -103
- package/src/contracts/host.ts +0 -7
- package/src/contracts/pi-provider.ts +0 -30
- package/src/contracts/pi.ts +0 -259
- package/src/contracts/prefix-cache.ts +0 -23
- package/src/contracts/resources.ts +0 -25
- package/src/contracts/sampling.ts +0 -23
- package/src/contracts/scheduling.ts +0 -45
- package/src/contracts/tsconfig.json +0 -14
- package/src/dataset/generators.ts +0 -1087
- package/src/dataset/index.ts +0 -12
- package/src/dataset/job.ts +0 -81
- package/src/dataset/llm.ts +0 -71
- package/src/dataset/registry.ts +0 -528
- package/src/diffusion/diffusion-generate.ts +0 -507
- package/src/download.ts +0 -505
- package/src/embed.ts +0 -77
- package/src/engine/admission.ts +0 -59
- package/src/engine/cancellation.ts +0 -38
- package/src/engine/engine.ts +0 -56
- package/src/engine/execution-coordinator.ts +0 -70
- package/src/engine/execution-plan.ts +0 -53
- package/src/engine/resources.ts +0 -53
- package/src/engine/scheduler.ts +0 -72
- package/src/engine/session.ts +0 -247
- package/src/eval/README.md +0 -130
- package/src/eval/ifeval.ts +0 -81
- package/src/eval/kl-prompts.ts +0 -29
- package/src/eval/kl.ts +0 -590
- package/src/eval/perplexity.ts +0 -164
- package/src/eval/quality-db.ts +0 -92
- package/src/eval/reference-logits.ts +0 -207
- package/src/eval/runner.ts +0 -124
- package/src/eval/score.ts +0 -49
- package/src/eval/tasks/bfcl.ts +0 -535
- package/src/eval/tasks/gsm8k.ts +0 -98
- package/src/eval/tasks/hashhop.ts +0 -139
- package/src/eval/tasks/humaneval.ts +0 -275
- package/src/eval/tasks/ifeval.ts +0 -525
- package/src/eval/tasks/mmlu.ts +0 -157
- package/src/eval/ultrafeedback.ts +0 -60
- package/src/evaldb.ts +0 -199
- package/src/expert-io.ts +0 -393
- package/src/expert-offload-build.ts +0 -77
- package/src/expert-offload.ts +0 -76
- package/src/expert-residency.ts +0 -1134
- package/src/expert-usage.ts +0 -415
- package/src/fill/echo-index.ts +0 -188
- package/src/fill/fill-session.ts +0 -452
- package/src/fill/proposal.ts +0 -68
- package/src/fill/schema-rows.ts +0 -506
- package/src/fill/tool-boundary.ts +0 -103
- package/src/fit.ts +0 -249
- package/src/generate.ts +0 -1346
- package/src/grammar.ts +0 -591
- package/src/harness-pi.ts +0 -184
- package/src/hf-push.ts +0 -628
- package/src/hub-rest.ts +0 -242
- package/src/index.ts +0 -63
- package/src/inference/denoising.ts +0 -17
- package/src/inference/draft-acceptance.ts +0 -41
- package/src/inference/draft-output.ts +0 -49
- package/src/inference/graph.ts +0 -33
- package/src/inference/prefill.ts +0 -39
- package/src/inference/rollback.ts +0 -7
- package/src/jobs/index.ts +0 -31
- package/src/jobs/job-entry.ts +0 -107
- package/src/jobs/task-client.ts +0 -19
- package/src/jobs/types.ts +0 -2
- package/src/kv-scheme.ts +0 -257
- package/src/kv-store.ts +0 -1099
- package/src/lab/README.md +0 -18
- package/src/lab/curve/curve-designer.html +0 -303
- package/src/lab/curve/curve-sampler.ts +0 -122
- package/src/lab/expert-trace/expert-trace.ts +0 -69
- package/src/lab/paged-kv/paged-kv-rows.ts +0 -83
- package/src/lab/paged-kv/paged-kv.ts +0 -270
- package/src/library.ts +0 -40
- package/src/lora.ts +0 -408
- package/src/md-modules.d.ts +0 -49
- package/src/media-fetch.ts +0 -442
- package/src/memory/article.ts +0 -558
- package/src/memory/chunk-validation.ts +0 -150
- package/src/memory/chunk.ts +0 -318
- package/src/memory/cluster.ts +0 -351
- package/src/memory/coverage.ts +0 -134
- package/src/memory/crosslink.ts +0 -0
- package/src/memory/db.ts +0 -253
- package/src/memory/entity.ts +0 -203
- package/src/memory/gate.ts +0 -187
- package/src/memory/history.ts +0 -152
- package/src/memory/ingest.ts +0 -335
- package/src/memory/model.ts +0 -183
- package/src/memory/normalize.ts +0 -671
- package/src/memory/parse.ts +0 -22
- package/src/memory/pipeline.ts +0 -275
- package/src/memory/prompts.ts +0 -65
- package/src/memory/query.ts +0 -334
- package/src/memory/reconcile.ts +0 -734
- package/src/memory/redirect.ts +0 -108
- package/src/memory/reindex.ts +0 -325
- package/src/memory/resolve.ts +0 -307
- package/src/memory/rest.ts +0 -245
- package/src/memory/route.ts +0 -272
- package/src/memory/schedule.ts +0 -165
- package/src/memory/stages.ts +0 -777
- package/src/memory/synthesize.ts +0 -1638
- package/src/memory/tools.ts +0 -749
- package/src/memory/vault.ts +0 -1194
- package/src/memory/wikify.ts +0 -1064
- package/src/mlx/array.ts +0 -388
- package/src/mlx/autograd.ts +0 -304
- package/src/mlx/checkpoint.ts +0 -149
- package/src/mlx/compile.ts +0 -168
- package/src/mlx/custom-vjp.ts +0 -188
- package/src/mlx/ffi.ts +0 -512
- package/src/mlx/materialize.ts +0 -23
- package/src/mlx/metal-kernel.ts +0 -159
- package/src/mlx/ops.ts +0 -1021
- package/src/mlx/quantized-rows.ts +0 -36
- package/src/mlx/token-bitmask.ts +0 -52
- package/src/mlx/turboquant-kv-decode.ts +0 -82
- package/src/mlx/turboquant-kv-inverse.ts +0 -122
- package/src/mlx/turboquant-ops.ts +0 -861
- package/src/mlx/turboquant-tables.ts +0 -237
- package/src/mmap.ts +0 -90
- package/src/model/artifact-identity.ts +0 -73
- package/src/model/batched-kv.ts +0 -235
- package/src/model/batched-mask.ts +0 -279
- package/src/model/batched-quant.ts +0 -212
- package/src/model/batched-quantized-kv.ts +0 -144
- package/src/model/batched-rotating-quant.ts +0 -353
- package/src/model/batched-rotating-state.ts +0 -149
- package/src/model/batched-rotating.ts +0 -338
- package/src/model/batched-row-storage.ts +0 -179
- package/src/model/batched-ssm.ts +0 -52
- package/src/model/batched-turboquant-kv.ts +0 -93
- package/src/model/compiled-decode.ts +0 -712
- package/src/model/decoded-kv-donor.ts +0 -12
- package/src/model/delayed-quantized-kv.ts +0 -72
- package/src/model/delayed-rotating-quantized-kv.ts +0 -93
- package/src/model/delayed-turboquant-kv.ts +0 -55
- package/src/model/diffusion-gemma.ts +0 -1026
- package/src/model/factory.ts +0 -189
- package/src/model/fingerprint.ts +0 -33
- package/src/model/flash-attention.ts +0 -694
- package/src/model/full-prefill-padding.ts +0 -56
- package/src/model/full-prefill-row.ts +0 -105
- package/src/model/gemma4-base.ts +0 -2351
- package/src/model/gemma4.ts +0 -1315
- package/src/model/generated/gemma4-12b.ts +0 -429
- package/src/model/generated/gemma4-26b.ts +0 -448
- package/src/model/generated/gemma4-e4b.ts +0 -717
- package/src/model/generated/index.ts +0 -18
- package/src/model/glm52-atlas.ts +0 -511
- package/src/model/glm52-cache.ts +0 -792
- package/src/model/glm52-config.ts +0 -262
- package/src/model/glm52-container.ts +0 -305
- package/src/model/glm52-coupling.ts +0 -388
- package/src/model/glm52-dsa.ts +0 -606
- package/src/model/glm52-expert-layout.ts +0 -253
- package/src/model/glm52-layout.ts +0 -152
- package/src/model/glm52-memory.ts +0 -500
- package/src/model/glm52-mla.ts +0 -792
- package/src/model/glm52-moe.ts +0 -223
- package/src/model/glm52-pilot.ts +0 -537
- package/src/model/glm52-reference.ts +0 -445
- package/src/model/glm52-residency.ts +0 -557
- package/src/model/glm52-resident-weights.ts +0 -135
- package/src/model/glm52-streamed-experts.ts +0 -453
- package/src/model/glm52-streamed-metal.ts +0 -610
- package/src/model/glm52-weights.ts +0 -503
- package/src/model/glm52.ts +0 -1132
- package/src/model/implementation.ts +0 -69
- package/src/model/kv-attention-view.ts +0 -67
- package/src/model/minicpm5.ts +0 -376
- package/src/model/profile.ts +0 -443
- package/src/model/qwen-append.ts +0 -12
- package/src/model/qwen-conv.ts +0 -52
- package/src/model/qwen3-delta-state.ts +0 -74
- package/src/model/qwen3-delta.ts +0 -451
- package/src/model/qwen3-moe.ts +0 -404
- package/src/model/qwen3-mrope.ts +0 -252
- package/src/model/qwen3.ts +0 -277
- package/src/model/qwen3_5-checkpoint.ts +0 -164
- package/src/model/qwen3_5.ts +0 -819
- package/src/model/rotating-kv-donor.ts +0 -35
- package/src/model/rotating-kv-layout.ts +0 -262
- package/src/model/rotating-row-transaction.ts +0 -35
- package/src/model/speculative-rotating-kv.ts +0 -101
- package/src/model/ssm-prefill-padding.ts +0 -39
- package/src/model/support.ts +0 -102
- package/src/model/trellis-balanced-scatter.ts +0 -51
- package/src/model/trellis-linear.ts +0 -672
- package/src/model/trellis-shared-m.ts +0 -151
- package/src/model/trellis-shared-scatter.ts +0 -144
- package/src/model/trellis-splitk-prefill.ts +0 -158
- package/src/model/trellis-tiled-prefill.ts +0 -136
- package/src/model/trellis-vector-expand.ts +0 -62
- package/src/model/trellis-wide-prefill.ts +0 -94
- package/src/model/turboquant-codec.ts +0 -83
- package/src/model/universal/archs.ts +0 -332
- package/src/model/universal/dense.ts +0 -612
- package/src/model/universal/modules.ts +0 -170
- package/src/model/universal/rope.ts +0 -381
- package/src/native/expert_io.c +0 -523
- package/src/native/frame_extract.swift +0 -140
- package/src/native-pack.ts +0 -162
- package/src/pi-provider.ts +0 -53
- package/src/pi-session.ts +0 -81
- package/src/pi-terminal.ts +0 -274
- package/src/pi-web.ts +0 -1932
- package/src/preflight.ts +0 -158
- package/src/prompt-cache.ts +0 -460
- package/src/quantize/allocator.ts +0 -627
- package/src/quantize/atomic-output.ts +0 -38
- package/src/quantize/calibration.ts +0 -181
- package/src/quantize/config-writer.ts +0 -145
- package/src/quantize/index.ts +0 -84
- package/src/quantize/job.ts +0 -162
- package/src/quantize/quantizer.ts +0 -666
- package/src/quantize/rotate.ts +0 -603
- package/src/quantize/safetensors-writer.ts +0 -249
- package/src/quantize/sensitivity.ts +0 -216
- package/src/quantize/trellis.ts +0 -586
- package/src/quantize/weight-transform.ts +0 -292
- package/src/registry.ts +0 -602
- package/src/runtime-config.ts +0 -81
- package/src/safetensors.ts +0 -158
- package/src/sampler.ts +0 -1011
- package/src/serve/admin-routes.ts +0 -184
- package/src/serve/assets/curve-terrain.html +0 -105
- package/src/serve/assets/training-inference-map.html +0 -575
- package/src/serve/aux-routes.ts +0 -132
- package/src/serve/batch-scheduler.ts +0 -8
- package/src/serve/checkpoint-identity.ts +0 -64
- package/src/serve/generation-gateway.ts +0 -496
- package/src/serve/isolate.ts +0 -609
- package/src/serve/kv-budget.ts +0 -14
- package/src/serve/lab-routes.ts +0 -341
- package/src/serve/lane-registry.ts +0 -45
- package/src/serve/model-admin-routes.ts +0 -155
- package/src/serve/model-binding.ts +0 -43
- package/src/serve/model-host.ts +0 -511
- package/src/serve/parent-application.ts +0 -56
- package/src/serve/prompt-response-trace.ts +0 -147
- package/src/serve/response-lease.ts +0 -24
- package/src/serve/session-search.ts +0 -326
- package/src/serve/static-routes.ts +0 -101
- package/src/server.ts +0 -1314
- package/src/spec/assistant-rows.ts +0 -92
- package/src/spec/assistant-source.ts +0 -126
- package/src/spec/cache-identity.ts +0 -22
- package/src/spec/deepspec-rows.ts +0 -29
- package/src/spec/deepspec-source.ts +0 -145
- package/src/spec/dflash-source.ts +0 -149
- package/src/spec/drafter.ts +0 -304
- package/src/spec/dspark/ab-stats.ts +0 -136
- package/src/spec/dspark/calibration.ts +0 -112
- package/src/spec/dspark/data-dflash.ts +0 -156
- package/src/spec/dspark/data.ts +0 -201
- package/src/spec/dspark/deepspec-module.ts +0 -776
- package/src/spec/dspark/generate-dflash.ts +0 -245
- package/src/spec/dspark/generate.ts +0 -290
- package/src/spec/dspark/loader.ts +0 -23
- package/src/spec/dspark/loss.ts +0 -213
- package/src/spec/dspark/module-dflash.ts +0 -560
- package/src/spec/dspark/module.ts +0 -540
- package/src/spec/dspark/quantize-drafter.ts +0 -91
- package/src/spec/dspark/sample.ts +0 -112
- package/src/spec/generate.ts +0 -276
- package/src/spec/glm52-mtp-graph.ts +0 -29
- package/src/spec/glm52-mtp-rows.ts +0 -132
- package/src/spec/glm52-mtp-source.ts +0 -317
- package/src/spec/glm52-mtp-state.ts +0 -33
- package/src/spec/ngram-source.ts +0 -204
- package/src/spec/projected-draft-rows.ts +0 -73
- package/src/spec/qwen-mtp-module.ts +0 -171
- package/src/spec/qwen-mtp-rows.ts +0 -219
- package/src/spec/qwen-mtp-source.ts +0 -383
- package/src/spec/qwen-mtp-state.ts +0 -30
- package/src/spec/serve-loop.ts +0 -585
- package/src/spec/source.ts +0 -215
- package/src/spec/two-model-rows.ts +0 -61
- package/src/spec/two-model.ts +0 -113
- package/src/ssd-cache.ts +0 -372
- package/src/ssd-durability.ts +0 -211
- package/src/tokenizer.ts +0 -335
- package/src/tool-approvals.ts +0 -131
- package/src/tool-call.ts +0 -695
- package/src/train/dataset.ts +0 -484
- package/src/train/diffusion-lora.ts +0 -216
- package/src/train/export.ts +0 -32
- package/src/train/flash-cce.ts +0 -1234
- package/src/train/forward.ts +0 -266
- package/src/train/fuse.ts +0 -243
- package/src/train/index.ts +0 -46
- package/src/train/job.ts +0 -205
- package/src/train/lora-params.ts +0 -254
- package/src/train/loss.ts +0 -1591
- package/src/train/merge.ts +0 -195
- package/src/train/optimizer.ts +0 -183
- package/src/train/prefix-shared.ts +0 -490
- package/src/train/rank.ts +0 -137
- package/src/train/segmented.ts +0 -1828
- package/src/train/steel-qmm-header.ts +0 -1461
- package/src/train/trainer.ts +0 -1221
- package/src/train/watch.ts +0 -542
- package/src/vision/diffusion-vision.ts +0 -620
- package/src/vision/embedder.ts +0 -168
- package/src/vision/preprocess.ts +0 -247
- package/src/vision/prompt.ts +0 -373
- package/src/vision/qwen3vl-preprocess.ts +0 -409
- package/src/vision/qwen3vl-prompt.ts +0 -196
- package/src/vision/qwen3vl-tower.ts +0 -555
- package/src/vision/siglip.ts +0 -599
- package/src/vision/video-frames.ts +0 -148
- package/src/web/app.html +0 -2143
- package/src/web/app.js +0 -5703
- package/src/web/skills/memory/SKILL.md +0 -120
- package/src/web/skills/web-research/SKILL.md +0 -46
- package/src/web/skills.ts +0 -97
- package/src/web/src/adapters-panel.ts +0 -288
- package/src/web/src/assistant.ts +0 -451
- package/src/web/src/chat.ts +0 -1057
- package/src/web/src/composer.ts +0 -959
- package/src/web/src/dataset.ts +0 -132
- package/src/web/src/finetune.ts +0 -267
- package/src/web/src/hub.ts +0 -428
- package/src/web/src/main.ts +0 -98
- package/src/web/src/markdown.ts +0 -0
- package/src/web/src/memory-panel.ts +0 -572
- package/src/web/src/model-picker.ts +0 -159
- package/src/web/src/palette.ts +0 -346
- package/src/web/src/protocol.ts +0 -26
- package/src/web/src/quantize.ts +0 -167
- package/src/web/src/rag.ts +0 -274
- package/src/web/src/sessions.ts +0 -469
- package/src/web/src/shell.ts +0 -804
- package/src/web/src/ui-catalog.ts +0 -78
- package/src/web/vendor/README.md +0 -61
- package/src/web-assets.ts +0 -47
- package/src/web-tools.ts +0 -478
- package/src/weights.ts +0 -255
- /package/src/{serve → server}/completion-sink.ts +0 -0
- /package/src/web/{icon.svg → public/icon.svg} +0 -0
- /package/src/web/{manifest.webmanifest → public/manifest.webmanifest} +0 -0
- /package/src/web/{vendor → public/vendor}/hljs-LICENSE +0 -0
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { fileURLToPath } from "node:url";
|
|
2
|
+
import { runModuleMemory, vaultRoot, memoryManifest, type MemoryDependencies, type MemoryCommandArgs as CommandArgs } from "../modules";
|
|
3
|
+
import { verbHelp } from "@mlx-bun/app-services";
|
|
4
|
+
import { executablePath } from "../jobs/executable";
|
|
5
|
+
import { userHome } from "../storage/paths";
|
|
6
|
+
import { createInProcessMemoryClient } from "./memory-engine";
|
|
7
|
+
import { banner, boxLines, renderHelp, step, style, gradient } from "./terminal";
|
|
8
|
+
import pkg from "../../package.json" with { type: "json" };
|
|
9
|
+
export type { MemoryDependencies } from "../modules";
|
|
10
|
+
|
|
11
|
+
/** The app's executable, terminal and task-model adapters; memory policy belongs to its module. */
|
|
12
|
+
export function defaultMemoryDependencies(): MemoryDependencies {
|
|
13
|
+
const entry = fileURLToPath(new URL("./main.ts", import.meta.url));
|
|
14
|
+
return {
|
|
15
|
+
log: console.log, error: console.error, banner: () => banner(pkg.version),
|
|
16
|
+
box: lines => { for (const line of boxLines(lines)) console.log(line); }, step, style: { ...style, gradient },
|
|
17
|
+
help: () => renderHelp(verbHelp("mlx-bun", memoryManifest.verbs[0])), vault: vaultRoot(), home: userHome(),
|
|
18
|
+
program: entry.includes("$bunfs") ? [executablePath] : [executablePath, entry],
|
|
19
|
+
taskModel: () => createInProcessMemoryClient(),
|
|
20
|
+
async open(args) { return await Bun.spawn(["open", ...args], { stdout: "ignore", stderr: "ignore" }).exited; },
|
|
21
|
+
async ask(question, fallback) {
|
|
22
|
+
if (!process.stdin.isTTY) return fallback;
|
|
23
|
+
const { createInterface } = await import("node:readline/promises");
|
|
24
|
+
const reader = createInterface({ input: process.stdin, output: process.stdout });
|
|
25
|
+
try { return (await reader.question(question)).trim() || fallback; } finally { reader.close(); }
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export async function runMemory(args: CommandArgs, supplied: Partial<MemoryDependencies> = {}): Promise<void> {
|
|
30
|
+
const defaults = defaultMemoryDependencies();
|
|
31
|
+
const deps = { ...defaults, ...supplied };
|
|
32
|
+
// Injected output callbacks also capture the existing boxed presentation in the CLI tests.
|
|
33
|
+
if (supplied.log && !supplied.box) deps.box = lines => { for (const line of boxLines(lines)) supplied.log!(line); };
|
|
34
|
+
const code = await runModuleMemory(args, deps);
|
|
35
|
+
if (code) process.exitCode = code;
|
|
36
|
+
}
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
// `mlx-bun.<cmd>`: mlx-lm's console commands (mlx_lm.<cmd>) under mlx-bun's own
|
|
2
|
+
// names. Each alias runs the matching mlx-bun verb with mlx_lm's argument
|
|
3
|
+
// spellings translated; the verb's own options stay accepted, so an alias is a
|
|
4
|
+
// superset of the mlx_lm command. Defaults, output locations (~/.mlx-bun) and
|
|
5
|
+
// behavior are the verb's; an explicit path behaves exactly as in mlx-lm.
|
|
6
|
+
// Flags mlx-bun cannot honor exit with an error naming the mlx_lm flag.
|
|
7
|
+
import { readFileSync } from "node:fs";
|
|
8
|
+
import { basename, dirname } from "node:path";
|
|
9
|
+
import { checkPositionals, commandOptions, help, isCommand, type CommandArgs } from "./args";
|
|
10
|
+
|
|
11
|
+
type Value = string | boolean;
|
|
12
|
+
export type AliasValues = Record<string, Value | undefined>;
|
|
13
|
+
|
|
14
|
+
interface MlxLmFlag {
|
|
15
|
+
kind: "string" | "boolean" | "list";
|
|
16
|
+
/** Single-dash spelling, without the dash (`p` for -p, `qa` for -qa). */
|
|
17
|
+
short?: string;
|
|
18
|
+
/** The verb's option that receives the value (default: the same name). */
|
|
19
|
+
to?: string;
|
|
20
|
+
/** Accepted with no effect; the reason is shown in help. */
|
|
21
|
+
ignored?: string;
|
|
22
|
+
/** Not supported; the reason follows the error. */
|
|
23
|
+
unsupported?: string;
|
|
24
|
+
/** Custom translation of the parsed value into the verb's values. */
|
|
25
|
+
set?(value: Value | string[], values: AliasValues): void;
|
|
26
|
+
}
|
|
27
|
+
interface Alias {
|
|
28
|
+
verb: string;
|
|
29
|
+
/** mlx_lm's flags that need translation, refusal, or acceptance; every other mlx_lm flag is the verb's own option. */
|
|
30
|
+
flags: Record<string, MlxLmFlag>;
|
|
31
|
+
/** Final adjustments once every flag (and the config file) is applied. */
|
|
32
|
+
finish?(values: AliasValues, given: ReadonlySet<string>): void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const no = (kind: MlxLmFlag["kind"], unsupported: string, extra: Partial<MlxLmFlag> = {}): MlxLmFlag => ({ kind, unsupported, ...extra });
|
|
36
|
+
const trustRemoteCode: MlxLmFlag = { kind: "boolean", ignored: "mlx-bun never executes code from a model repository" };
|
|
37
|
+
|
|
38
|
+
const ONE_SHOT = "mlx-bun's one-shot generate has no such option";
|
|
39
|
+
const GENERATE: Alias = {
|
|
40
|
+
verb: "generate",
|
|
41
|
+
flags: {
|
|
42
|
+
model: { kind: "string", to: "query" },
|
|
43
|
+
"trust-remote-code": trustRemoteCode,
|
|
44
|
+
prompt: { kind: "string", short: "p", set: (value, values) => {
|
|
45
|
+
// mlx_lm.generate reads the escapes \n and \t as characters; `-` (stdin) passes through.
|
|
46
|
+
values.prompt = String(value).replaceAll("\\n", "\n").replaceAll("\\t", "\t");
|
|
47
|
+
} },
|
|
48
|
+
"max-tokens": { kind: "string", short: "m" },
|
|
49
|
+
"ignore-chat-template": { kind: "boolean", to: "raw" },
|
|
50
|
+
verbose: { kind: "string", ignored: "mlx-bun prints only the generated text" },
|
|
51
|
+
"kv-bits": { kind: "string", set: (value, values) => {
|
|
52
|
+
if (value !== "4" && value !== "8") throw new Error(`--kv-bits ${value}: mlx-bun's affine KV cache supports 4 or 8 bits`);
|
|
53
|
+
values["kv-quant"] = value;
|
|
54
|
+
// mlx_lm starts quantizing at token 5000 unless told otherwise; mlx-bun's own --kv-quant starts at 0.
|
|
55
|
+
values["quantized-kv-start"] ??= "5000";
|
|
56
|
+
} },
|
|
57
|
+
"kv-group-size": { kind: "string", set: value => {
|
|
58
|
+
if (value !== "64") throw new Error(`--kv-group-size ${value}: mlx-bun's affine KV cache uses group size 64`);
|
|
59
|
+
} },
|
|
60
|
+
"extra-eos-token": no("list", "the model's own end-of-sequence tokens stop generation"),
|
|
61
|
+
"prefill-response": no("string", ONE_SHOT),
|
|
62
|
+
"use-default-chat-template": no("boolean", "the model's own chat template is always used"),
|
|
63
|
+
"chat-template-config": no("string", "chat template arguments are not configurable here"),
|
|
64
|
+
"max-kv-size": no("string", "mlx-bun has no rotating KV size cap flag"),
|
|
65
|
+
"prompt-cache-file": no("string", "saved prompt caches are not supported; `serve` caches prompts itself"),
|
|
66
|
+
"quantize-activations": no("boolean", "activation quantization is not supported", { short: "qa" }),
|
|
67
|
+
"draft-model": no("string", "speculative decoding runs in `serve` (--draft-model)"),
|
|
68
|
+
"num-draft-tokens": no("string", "speculative decoding runs in `serve` (--num-draft-tokens)"),
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const SERVE: Alias = {
|
|
73
|
+
verb: "serve",
|
|
74
|
+
flags: {
|
|
75
|
+
"trust-remote-code": trustRemoteCode,
|
|
76
|
+
"allowed-origins": no("string", "CORS origins are not configurable"),
|
|
77
|
+
"log-level": no("string", "the server has no log-level switch"),
|
|
78
|
+
"chat-template": no("string", "the model's own chat template is always used"),
|
|
79
|
+
"use-default-chat-template": no("boolean", "the model's own chat template is always used"),
|
|
80
|
+
"chat-template-args": no("string", "send chat_template_kwargs with the request instead"),
|
|
81
|
+
"min-p": no("string", "send min_p with the request instead"),
|
|
82
|
+
"prompt-concurrency": no("string", "the scheduler decides how prompts join; --batch sets the capacity"),
|
|
83
|
+
"prefill-step-size": no("string", "prefill chunking is not configurable"),
|
|
84
|
+
"prompt-cache-size": no("string", "use --prompt-cache (GiB)"),
|
|
85
|
+
"prompt-cache-bytes": no("string", "use --prompt-cache (GiB)"),
|
|
86
|
+
pipeline: no("boolean", "distributed pipelining is not supported"),
|
|
87
|
+
},
|
|
88
|
+
// mlx_lm.server is headless; the web app is mlx-bun's addition, opened only on request.
|
|
89
|
+
finish: (values, given) => { if (!given.has("no-open")) values["no-open"] = true; },
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const CONVERT: Alias = { verb: "convert", flags: { "trust-remote-code": trustRemoteCode } };
|
|
93
|
+
const FUSE: Alias = { verb: "fuse", flags: {} };
|
|
94
|
+
const UPLOAD: Alias = { verb: "upload", flags: {} };
|
|
95
|
+
|
|
96
|
+
const LORA_UNSUPPORTED = (what: string) => `${what} is not supported by mlx-bun's LoRA trainer`;
|
|
97
|
+
const LORA: Alias = {
|
|
98
|
+
verb: "train",
|
|
99
|
+
flags: {
|
|
100
|
+
model: { kind: "string", to: "query" },
|
|
101
|
+
train: { kind: "boolean" },
|
|
102
|
+
test: no("boolean", "test-set evaluation is not supported"),
|
|
103
|
+
"test-batches": no("string", "test-set evaluation is not supported"),
|
|
104
|
+
"fine-tune-type": { kind: "string", set: value => {
|
|
105
|
+
if (value === "dora" || value === "full") throw new Error(`--fine-tune-type ${value}: ${LORA_UNSUPPORTED(value)}; only lora`);
|
|
106
|
+
if (value !== "lora") throw new Error(`--fine-tune-type: invalid choice: '${value}' (choose from lora, dora, full)`);
|
|
107
|
+
} },
|
|
108
|
+
optimizer: { kind: "string", set: (value, values) => {
|
|
109
|
+
// mlx.optimizers.Adam has no weight decay; AdamW (mlx-bun's optimizer) defaults to 0.01.
|
|
110
|
+
if (value === "adam") values["optimizer-adam"] = true;
|
|
111
|
+
else if (value !== "adamw") throw new Error(`--optimizer ${value}: only adam and adamw are supported`);
|
|
112
|
+
} },
|
|
113
|
+
"mask-prompt": { kind: "boolean", ignored: "mlx-bun's SFT always masks the prompt (loss on the response only)" },
|
|
114
|
+
"batch-size": { kind: "string", to: "batch" },
|
|
115
|
+
"val-batches": { kind: "string", set: (value, values) => { values["val-batches"] = String(value); } },
|
|
116
|
+
"learning-rate": { kind: "string", to: "lr" },
|
|
117
|
+
"grad-accumulation-steps": { kind: "string", to: "grad-accum" },
|
|
118
|
+
"resume-adapter-file": { kind: "string", set: (value, values) => {
|
|
119
|
+
// mlx-bun resumes from an adapter directory; mlx-lm names the weights file in it.
|
|
120
|
+
const path = String(value);
|
|
121
|
+
values.resume = path.endsWith(".safetensors") ? dirname(path) : path;
|
|
122
|
+
} },
|
|
123
|
+
"adapter-path": { kind: "string", to: "adapter" },
|
|
124
|
+
"max-seq-length": { kind: "string", to: "seq" },
|
|
125
|
+
config: { kind: "string", short: "c", set: (value, values) => { values["config-file"] = String(value); } },
|
|
126
|
+
"clear-cache-threshold": no("string", "the allocator cache policy is not configurable"),
|
|
127
|
+
"report-to": no("string", "experiment reporting is not supported"),
|
|
128
|
+
"project-name": no("string", "experiment reporting is not supported"),
|
|
129
|
+
},
|
|
130
|
+
finish: (values, given) => {
|
|
131
|
+
if (values.method === undefined) values.method = "sft"; // mlx_lm.lora is supervised fine-tuning
|
|
132
|
+
if (values["optimizer-adam"] && !given.has("weight-decay")) values["weight-decay"] = "0";
|
|
133
|
+
delete values["optimizer-adam"];
|
|
134
|
+
const batches = values["val-batches"];
|
|
135
|
+
if (typeof batches === "string") {
|
|
136
|
+
// mlx-lm counts validation batches; mlx-bun caps validation examples.
|
|
137
|
+
const n = Number(batches), size = Number(values.batch ?? 1);
|
|
138
|
+
values["val-size"] = String(n < 0 ? Number.MAX_SAFE_INTEGER : n * size);
|
|
139
|
+
delete values["val-batches"];
|
|
140
|
+
}
|
|
141
|
+
if (values.train !== true) throw new Error("Must provide --train (mlx-bun's LoRA trainer has no --test-only mode)");
|
|
142
|
+
delete values.train;
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
/** mlx_lm.lora's YAML config keys that are not plain flag spellings. */
|
|
147
|
+
const LORA_CONFIG_UNSUPPORTED = ["lr_schedule"];
|
|
148
|
+
|
|
149
|
+
export const ALIASES: Record<string, Alias> = { server: SERVE, generate: GENERATE, convert: CONVERT, fuse: FUSE, lora: LORA, upload: UPLOAD };
|
|
150
|
+
|
|
151
|
+
/** mlx-lm's other console scripts (0.31.3): no mlx-bun counterpart, so no alias. */
|
|
152
|
+
export const ALIAS_GAPS: Record<string, string> = {
|
|
153
|
+
chat: "no interactive terminal chat; use the web app (`mlx-bun`) or `mlx-bun.server`",
|
|
154
|
+
benchmark: "no benchmark verb; the repository's scripts/bench-serve.ts measures a running server",
|
|
155
|
+
cache_prompt: "no saved prompt-cache files; `serve` keeps its own prompt cache",
|
|
156
|
+
evaluate: "no lm-evaluation-harness runner; the repository's scripts/eval-serve.ts scores a running server",
|
|
157
|
+
perplexity: "use `mlx-bun perplexity <model> --data-path <local file>` (main's verb, mlx_lm.perplexity's method over a local file)",
|
|
158
|
+
manage: "no cache-management verb with mlx_lm.manage's semantics; see `mlx-bun ls` and `mlx-bun gc`",
|
|
159
|
+
share: "no distributed file sharing",
|
|
160
|
+
awq: "no AWQ quantization; `mlx-bun convert --target-bpw` is the mixed-precision path",
|
|
161
|
+
dwq: "no DWQ quantization; `mlx-bun convert --target-bpw` is the mixed-precision path",
|
|
162
|
+
dynamic_quant: "no dynamic quantization; `mlx-bun convert --target-bpw` is the mixed-precision path",
|
|
163
|
+
gptq: "no GPTQ quantization; `mlx-bun convert --target-bpw` is the mixed-precision path",
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
const PREFIX = "mlx-bun.";
|
|
167
|
+
|
|
168
|
+
/** The alias an invocation asked for, from the name the command was started as:
|
|
169
|
+
* the executable's own name in the standalone binary, the launcher file's name
|
|
170
|
+
* (bin/mlx-bun.<cmd>.mjs) when run from source. Null for plain `mlx-bun`. */
|
|
171
|
+
export function invokedAlias(input: { argv0?: string; argv1?: string; main?: string } = {}): string | null {
|
|
172
|
+
const main = input.main ?? Bun.main;
|
|
173
|
+
const name = basename(main.startsWith("/$bunfs/") ? input.argv0 ?? process.argv0 : input.argv1 ?? process.argv[1] ?? "").replace(/\.mjs$/, "");
|
|
174
|
+
return name.startsWith(PREFIX) ? name.slice(PREFIX.length) : null;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const NEGATIVE_NUMBER = /^-(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?$/;
|
|
178
|
+
const looksLikeFlag = (token: string) => token.startsWith("-") && token !== "-" && !NEGATIVE_NUMBER.test(token);
|
|
179
|
+
|
|
180
|
+
export type AliasResult = { help: string } | { command: string; parsed: CommandArgs };
|
|
181
|
+
|
|
182
|
+
function requireAlias(name: string): Alias {
|
|
183
|
+
const alias = Object.hasOwn(ALIASES, name) ? ALIASES[name] : undefined;
|
|
184
|
+
if (alias) return alias;
|
|
185
|
+
const gap = Object.hasOwn(ALIAS_GAPS, name) ? ALIAS_GAPS[name] : undefined;
|
|
186
|
+
throw new Error(gap ? `${PREFIX}${name}: mlx_lm.${name} has no mlx-bun counterpart (${gap})`
|
|
187
|
+
: `${PREFIX}${name}: unknown mlx-lm alias; available: ${Object.keys(ALIASES).map(key => PREFIX + key).join(", ")}`);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Translate `mlx-bun.<name> <argv>`: mlx_lm's spellings first, then the verb's own options. */
|
|
191
|
+
export function translateAlias(name: string, argv: string[], readConfig: (path: string) => unknown = readYaml): AliasResult {
|
|
192
|
+
const alias = requireAlias(name), tag = `${PREFIX}${name}`;
|
|
193
|
+
if (argv.includes("--help") || argv.includes("-h")) return { help: aliasHelp(name) };
|
|
194
|
+
const own = commandOptions(alias.verb);
|
|
195
|
+
const lookup = (token: string): { key: string; flag: MlxLmFlag } | undefined => {
|
|
196
|
+
const long = token.startsWith("--");
|
|
197
|
+
const bare = token.slice(long ? 2 : 1);
|
|
198
|
+
if (long) {
|
|
199
|
+
const mapped = alias.flags[bare];
|
|
200
|
+
if (mapped) return { key: bare, flag: mapped };
|
|
201
|
+
const option = own[bare];
|
|
202
|
+
return option ? { key: bare, flag: { kind: option.type } } : undefined;
|
|
203
|
+
}
|
|
204
|
+
for (const [key, flag] of Object.entries(alias.flags)) if (flag.short === bare) return { key, flag };
|
|
205
|
+
for (const [key, option] of Object.entries(own)) if (option.short === bare) return { key, flag: { kind: option.type } };
|
|
206
|
+
return undefined;
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
const values: AliasValues = {}, given = new Set<string>(), positionals: string[] = [];
|
|
210
|
+
/** A translation's own refusal reads as the alias's. */
|
|
211
|
+
const tagged = <T>(work: () => T): T => {
|
|
212
|
+
try { return work(); }
|
|
213
|
+
catch (error) { throw new Error(error instanceof Error && !error.message.startsWith(tag) ? `${tag}: ${error.message}` : String(error)); }
|
|
214
|
+
};
|
|
215
|
+
const apply = (key: string, flag: MlxLmFlag, value: Value | string[]) => {
|
|
216
|
+
if (flag.unsupported) throw new Error(`${tag}: --${key} is an mlx_lm.${name} option mlx-bun does not support: ${flag.unsupported}`);
|
|
217
|
+
given.add(flag.to ?? key);
|
|
218
|
+
if (flag.ignored) return;
|
|
219
|
+
if (flag.set) return tagged(() => flag.set!(value, values));
|
|
220
|
+
values[flag.to ?? key] = Array.isArray(value) ? value.join(" ") : value;
|
|
221
|
+
};
|
|
222
|
+
for (let index = 0; index < argv.length; index++) {
|
|
223
|
+
const token = argv[index]!;
|
|
224
|
+
if (token === "--") { positionals.push(...argv.slice(index + 1)); break; }
|
|
225
|
+
if (!looksLikeFlag(token)) { positionals.push(token); continue; }
|
|
226
|
+
const equals = token.startsWith("--") ? token.indexOf("=") : -1;
|
|
227
|
+
const spelled = equals === -1 ? token : token.slice(0, equals);
|
|
228
|
+
const found = lookup(spelled);
|
|
229
|
+
if (!found) throw new Error(`${tag}: unrecognized argument: ${spelled}`);
|
|
230
|
+
const { key, flag } = found;
|
|
231
|
+
if (flag.kind === "boolean") {
|
|
232
|
+
if (equals !== -1) throw new Error(`${tag}: argument ${spelled}: ignored explicit argument '${token.slice(equals + 1)}'`);
|
|
233
|
+
apply(key, flag, true);
|
|
234
|
+
} else if (flag.kind === "list") {
|
|
235
|
+
const items: string[] = equals === -1 ? [] : [token.slice(equals + 1)];
|
|
236
|
+
while (equals === -1 && index + 1 < argv.length && !looksLikeFlag(argv[index + 1]!)) items.push(argv[++index]!);
|
|
237
|
+
if (!items.length) throw new Error(`${tag}: argument ${spelled}: expected at least one argument`);
|
|
238
|
+
apply(key, flag, items);
|
|
239
|
+
} else {
|
|
240
|
+
const next = equals === -1 ? argv[index + 1] : token.slice(equals + 1);
|
|
241
|
+
if (next === undefined || (equals === -1 && looksLikeFlag(next))) throw new Error(`${tag}: argument ${spelled}: expected one argument`);
|
|
242
|
+
if (equals === -1) index++;
|
|
243
|
+
apply(key, flag, next);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
if (name === "lora" && values["config-file"] !== undefined) applyLoraConfig(values, given, String(values["config-file"]), readConfig, tag, lookup, apply);
|
|
247
|
+
delete values["config-file"];
|
|
248
|
+
tagged(() => alias.finish?.(values, given));
|
|
249
|
+
// Positionals belong to the verb (`generate [query] [prompt]`); mlx_lm's commands take none.
|
|
250
|
+
const parsed: CommandArgs = { values, positionals };
|
|
251
|
+
// A module's verb checks its own positionals against its manifest when the host runs it.
|
|
252
|
+
if (isCommand(alias.verb)) checkPositionals(alias.verb, parsed);
|
|
253
|
+
return { command: alias.verb, parsed };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function readYaml(path: string): unknown { return Bun.YAML.parse(readFileSync(path, "utf8")); }
|
|
257
|
+
|
|
258
|
+
/** mlx_lm.lora's `-c/--config`: the file's keys are the flags' names with underscores; a flag on the command line wins. */
|
|
259
|
+
function applyLoraConfig(values: AliasValues, given: Set<string>, path: string, read: (path: string) => unknown, tag: string,
|
|
260
|
+
lookup: (token: string) => { key: string; flag: MlxLmFlag } | undefined, apply: (key: string, flag: MlxLmFlag, value: Value | string[]) => void): void {
|
|
261
|
+
let config: unknown;
|
|
262
|
+
try { config = read(path); }
|
|
263
|
+
catch (error) { throw new Error(`${tag}: cannot read config ${path}: ${error instanceof Error ? error.message : String(error)}`); }
|
|
264
|
+
if (config === null || typeof config !== "object" || Array.isArray(config)) throw new Error(`${tag}: config ${path} must be a YAML mapping`);
|
|
265
|
+
const entries = config as Record<string, unknown>;
|
|
266
|
+
const set = (name: string, value: unknown) => {
|
|
267
|
+
if (value === null || value === undefined) return;
|
|
268
|
+
const found = lookup(`--${name}`);
|
|
269
|
+
if (!found) throw new Error(`${tag}: config ${path}: unrecognized key ${name.replaceAll("-", "_")}`);
|
|
270
|
+
if (given.has(found.flag.to ?? found.key)) return; // the command line wins
|
|
271
|
+
if (found.flag.kind === "boolean") { if (value === true) apply(found.key, found.flag, true); return; }
|
|
272
|
+
apply(found.key, found.flag, String(value));
|
|
273
|
+
};
|
|
274
|
+
for (const [rawKey, value] of Object.entries(entries)) {
|
|
275
|
+
const key = rawKey.replaceAll("_", "-");
|
|
276
|
+
if (LORA_CONFIG_UNSUPPORTED.includes(rawKey) && value !== null) throw new Error(`${tag}: config ${path}: ${rawKey} is not supported`);
|
|
277
|
+
if (rawKey === "lora_parameters") {
|
|
278
|
+
const parameters = value as Record<string, unknown> | null;
|
|
279
|
+
for (const [parameter, parameterValue] of Object.entries(parameters ?? {})) {
|
|
280
|
+
if (parameterValue === null) continue;
|
|
281
|
+
if (!["rank", "scale", "dropout"].includes(parameter)) throw new Error(`${tag}: config ${path}: lora_parameters.${parameter} is not supported`);
|
|
282
|
+
set(parameter, parameterValue);
|
|
283
|
+
}
|
|
284
|
+
} else if (rawKey === "optimizer_config") {
|
|
285
|
+
const chosen = (value as Record<string, Record<string, unknown> | null> | null)?.[String(entries.optimizer ?? "adam")];
|
|
286
|
+
for (const [option, optionValue] of Object.entries(chosen ?? {})) {
|
|
287
|
+
if (optionValue === null) continue;
|
|
288
|
+
if (option !== "weight_decay") throw new Error(`${tag}: config ${path}: optimizer_config.${option} is not supported`);
|
|
289
|
+
set("weight-decay", optionValue);
|
|
290
|
+
}
|
|
291
|
+
} else set(key, value);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** `mlx-bun.<cmd> --help`: what the alias translates, then the verb's own help. */
|
|
296
|
+
export function aliasHelp(name: string): string {
|
|
297
|
+
const alias = requireAlias(name), verb = alias.verb;
|
|
298
|
+
const group = (pick: (flag: MlxLmFlag) => string | undefined) => Object.entries(alias.flags)
|
|
299
|
+
.flatMap(([key, flag]) => { const detail = pick(flag); return detail === undefined ? [] : [` ${flag.short ? `-${flag.short}, ` : ""}--${key}${detail ? ` ${detail}` : ""}`]; });
|
|
300
|
+
const mapped = group(flag => flag.to ? `→ --${flag.to}` : flag.set && !flag.ignored && !flag.unsupported ? "(translated)" : undefined);
|
|
301
|
+
const ignored = group(flag => flag.ignored);
|
|
302
|
+
const unsupported = group(flag => flag.unsupported);
|
|
303
|
+
const section = (title: string, rows: string[]) => rows.length ? `\n${title}:\n${rows.join("\n")}\n` : "";
|
|
304
|
+
return `${PREFIX}${name} — mlx_lm.${name}-compatible alias of \`mlx-bun ${verb}\`\n\nUsage: ${PREFIX}${name} [options]\n\n` +
|
|
305
|
+
`Accepts mlx_lm.${name}'s arguments and every \`mlx-bun ${verb}\` option. Defaults and output locations (~/.mlx-bun) are\n` +
|
|
306
|
+
`mlx-bun's; an explicit path behaves as in mlx-lm.\n` +
|
|
307
|
+
section("mlx_lm spellings mapped", mapped) + section("Accepted, no effect", ignored) + section("mlx_lm options not supported", unsupported) +
|
|
308
|
+
`\nOptions of \`mlx-bun ${verb}\`:\n${help(verb).split("\nOptions:\n")[1]}`;
|
|
309
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// The public `mlx-bun/selection` entry: main's pure model-selection helpers
|
|
2
|
+
// (src/fit.ts). A leaf module with no imports, so it loads without native MLX;
|
|
3
|
+
// model-selection.ts applies these choices to the registry and fit.
|
|
4
|
+
// Application choices, not hub policy: discovery and fit remain reusable libraries.
|
|
5
|
+
|
|
6
|
+
/** The model automatic selection prefers (e4b). */
|
|
7
|
+
export const DEFAULT_REPO_ID = "mlx-community/gemma-4-e4b-it-OptiQ-4bit";
|
|
8
|
+
/** Downloaded first when no supported model is cached. */
|
|
9
|
+
export const STARTER_REPO_ID = "mlx-community/MiniCPM5-1B-OptiQ-4bit";
|
|
10
|
+
/** Fraction of RAM an automatically selected model may use while leaving room for other apps. */
|
|
11
|
+
export const COEXIST_FRACTION = 0.6;
|
|
12
|
+
|
|
13
|
+
/** Prefer e4b when it fits; otherwise retain room for other apps where possible.
|
|
14
|
+
* Explicit model selection does not use these advisory fit predicates. */
|
|
15
|
+
export function chooseAutoModel<T extends { repoId: string; sizeBytes: number }>(
|
|
16
|
+
candidates: readonly T[], preferredRepo: string,
|
|
17
|
+
fitsFull: (candidate: T) => boolean, fitsCoexist: (candidate: T) => boolean,
|
|
18
|
+
): T | undefined {
|
|
19
|
+
const preferred = candidates.find(candidate => candidate.repoId === preferredRepo);
|
|
20
|
+
if (preferred && fitsFull(preferred)) return preferred;
|
|
21
|
+
const largest = [...candidates].sort((a, b) => b.sizeBytes - a.sizeBytes);
|
|
22
|
+
return largest.find(fitsCoexist) ?? largest.find(fitsFull);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Largest Gemma a RAM tier can comfortably hold: the 26B at 48 GiB or more,
|
|
26
|
+
* the 12B at 24 GiB or more, otherwise DEFAULT_REPO_ID. An explicit opt-in:
|
|
27
|
+
* automatic selection never calls it. Pass the RAM, e.g. `os.totalmem()`. */
|
|
28
|
+
export function largestRecommendedRepoId(ramBytes: number): string {
|
|
29
|
+
const gb = ramBytes / 2 ** 30;
|
|
30
|
+
if (gb >= 48) return "mlx-community/gemma-4-26B-A4B-it-OptiQ-4bit";
|
|
31
|
+
if (gb >= 24) return "mlx-community/gemma-4-12B-it-OptiQ-4bit";
|
|
32
|
+
return DEFAULT_REPO_ID;
|
|
33
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { basename, join, resolve } from "node:path";
|
|
3
|
+
import { scanSnapshot, type ModelRecord, type Registry } from "@mlx-bun/hub/registry";
|
|
4
|
+
import { downloadModel } from "@mlx-bun/hub/download";
|
|
5
|
+
import { fit, thisMachine, type MachineSpec } from "@mlx-bun/inference/execution/fit";
|
|
6
|
+
import { loadModelConfig } from "@mlx-bun/inference/artifacts/config";
|
|
7
|
+
import { isSupportedModelRecord } from "@mlx-bun/inference/models/support";
|
|
8
|
+
import { chooseAutoModel, COEXIST_FRACTION, DEFAULT_REPO_ID, STARTER_REPO_ID } from "./model-choice";
|
|
9
|
+
import { openRegistry } from "../storage/paths";
|
|
10
|
+
|
|
11
|
+
type ModelRegistry = Pick<Registry, "list" | "resolve" | "scan" | "close">;
|
|
12
|
+
export interface ModelSelectionDependencies {
|
|
13
|
+
registry(): ModelRegistry;
|
|
14
|
+
scanSnapshot: typeof scanSnapshot;
|
|
15
|
+
download: typeof downloadModel;
|
|
16
|
+
machine(): MachineSpec;
|
|
17
|
+
assess(model: ModelRecord, machine: MachineSpec): Promise<{ full: boolean; coexist: boolean }>;
|
|
18
|
+
log(message: string): void;
|
|
19
|
+
}
|
|
20
|
+
const defaults: ModelSelectionDependencies = {
|
|
21
|
+
registry: () => openRegistry(), scanSnapshot, download: downloadModel, machine: thisMachine,
|
|
22
|
+
async assess(model, machine) {
|
|
23
|
+
const config = await loadModelConfig(model.path);
|
|
24
|
+
return {
|
|
25
|
+
full: fit(config, model.sizeBytes, 8192, machine, undefined, model.expertsBytes).fits,
|
|
26
|
+
coexist: fit(config, model.sizeBytes, 8192, machine, undefined, model.expertsBytes, machine.ramBytes * COEXIST_FRACTION).fits,
|
|
27
|
+
};
|
|
28
|
+
},
|
|
29
|
+
log: message => console.log(message),
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** Resolve a path/query, or select a cached supported model. An empty supported
|
|
33
|
+
* cache gets the starter first, as in main; the larger recommended model is
|
|
34
|
+
* returned for the caller to fetch in the background under its own owner.
|
|
35
|
+
* `signal` cancels the starter download (its partial stays resumable). */
|
|
36
|
+
export async function resolveModelAuto(query: string | null, supplied: Partial<ModelSelectionDependencies> = {},
|
|
37
|
+
signal?: AbortSignal): Promise<{ m: ModelRecord; picked: boolean; recommended?: string }> {
|
|
38
|
+
const deps = { ...defaults, ...supplied };
|
|
39
|
+
if (query && existsSync(join(query, "config.json"))) {
|
|
40
|
+
const directory = resolve(query);
|
|
41
|
+
const hf = /models--([^/]+)--([^/]+)\/snapshots\//.exec(directory);
|
|
42
|
+
const repoId = hf ? `${hf[1]}/${hf[2]}` : basename(directory);
|
|
43
|
+
const model = await deps.scanSnapshot(directory, repoId);
|
|
44
|
+
if (!model) throw new Error(`${directory} has config.json but no weights (*.safetensors)`);
|
|
45
|
+
return { m: model, picked: false };
|
|
46
|
+
}
|
|
47
|
+
const registry = deps.registry();
|
|
48
|
+
try {
|
|
49
|
+
if (registry.list().length === 0) await registry.scan();
|
|
50
|
+
if (query) return { m: registry.resolve(query), picked: false };
|
|
51
|
+
const supported = () => registry.list().filter(model => isSupportedModelRecord(model.modelType));
|
|
52
|
+
let candidates = supported();
|
|
53
|
+
let recommended: string | undefined;
|
|
54
|
+
if (candidates.length === 0) {
|
|
55
|
+
signal?.throwIfAborted();
|
|
56
|
+
deps.log(`Downloading starter model ${STARTER_REPO_ID}`);
|
|
57
|
+
const reported = new Map<string, number>();
|
|
58
|
+
await deps.download(STARTER_REPO_ID, {
|
|
59
|
+
signal,
|
|
60
|
+
onProgress(file, received, total) {
|
|
61
|
+
// Keep redirected startup logs bounded while still showing large transfers.
|
|
62
|
+
const bucket = total ? Math.floor(received / total * 10) : Math.floor(received / 100_000_000);
|
|
63
|
+
if (reported.get(file) === bucket) return;
|
|
64
|
+
reported.set(file, bucket);
|
|
65
|
+
const progress = total ? `${Math.floor(received / total * 100)}%` : `${received} bytes`;
|
|
66
|
+
deps.log(`Starter model: ${file} (${progress})`);
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
await registry.scan();
|
|
70
|
+
deps.log(`Starter ready; downloading ${DEFAULT_REPO_ID} in the background for the next start.`);
|
|
71
|
+
recommended = DEFAULT_REPO_ID;
|
|
72
|
+
candidates = supported();
|
|
73
|
+
}
|
|
74
|
+
signal?.throwIfAborted();
|
|
75
|
+
const machine = deps.machine();
|
|
76
|
+
const assessments = new Map<string, { full: boolean; coexist: boolean }>();
|
|
77
|
+
for (const model of candidates) assessments.set(model.repoId, await deps.assess(model, machine));
|
|
78
|
+
const chosen = chooseAutoModel(candidates, DEFAULT_REPO_ID,
|
|
79
|
+
model => assessments.get(model.repoId)?.full ?? false,
|
|
80
|
+
model => assessments.get(model.repoId)?.coexist ?? false);
|
|
81
|
+
if (!chosen) throw new Error("No downloaded supported model fits this machine — pick one explicitly (mlx-bun ls).");
|
|
82
|
+
return { m: chosen, picked: true, ...(recommended ? { recommended } : {}) };
|
|
83
|
+
} finally { registry.close(); }
|
|
84
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// Loading the installed modules (`src/modules.ts`) over a host's core services
|
|
2
|
+
// (`@mlx-bun/app-services`); the serve composition supplies the generation
|
|
3
|
+
// gateway's execution lock so decoding never overlaps chat.
|
|
4
|
+
import type { LoadedModules } from "@mlx-bun/app-host";
|
|
5
|
+
import { activateModules, type HostServices } from "@mlx-bun/app-services";
|
|
6
|
+
import { installedModules, type ModuleScope } from "../modules";
|
|
7
|
+
|
|
8
|
+
/** Activate the installed modules of a scope (see `ModuleScope`) over the host's core services. */
|
|
9
|
+
export async function loadInstalledModules(host: Pick<HostServices, "bindings">, scope: ModuleScope = "model"): Promise<LoadedModules> {
|
|
10
|
+
return activateModules(await installedModules(scope), host);
|
|
11
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// The CLI verbs the installed modules declare (`src/modules.ts`): their
|
|
2
|
+
// manifests are plain data, so the command list, `--help` and argument parsing
|
|
3
|
+
// read them without activating anything. Running one activates the verb's
|
|
4
|
+
// module over this app's core services and hands the verb what the host parsed.
|
|
5
|
+
import type { CliVerbSpec } from "@mlx-bun/app-core";
|
|
6
|
+
import { manifests } from "../modules";
|
|
7
|
+
|
|
8
|
+
export const PROGRAM = "mlx-bun";
|
|
9
|
+
|
|
10
|
+
/** Verb name to its declared spec, in installation order. */
|
|
11
|
+
export function installedVerbs(): ReadonlyMap<string, CliVerbSpec> {
|
|
12
|
+
return new Map(manifests.flatMap(manifest => (manifest.verbs ?? []).map(spec => [spec.name, spec] as const)));
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Run an installed module's verb, from its argv or from the values another spelling of the verb (`mlx-bun.convert`) already parsed; resolves to the exit code. */
|
|
16
|
+
export async function runInstalledVerb(name: string, input: string[] | { values: Readonly<Record<string, unknown>>; positionals: readonly string[] }): Promise<number> {
|
|
17
|
+
const spec = installedVerbs().get(name);
|
|
18
|
+
if (!spec) throw new Error(`Unknown command: ${name}`);
|
|
19
|
+
// The module code and its services load only now, so the command list and help stay light.
|
|
20
|
+
const [{ createHostServices, runVerb }, { installedModules }, { createCatalogHub }, terminal, { createJobHost }, { createJobService }, { JobStore }, { fileURLToPath }, fs, os, path] = await Promise.all([
|
|
21
|
+
import("@mlx-bun/app-services"), import("../modules"), import("../publishing/catalog-hub"), import("./terminal"), import("../jobs/host"), import("../jobs/service"), import("../jobs/db"),
|
|
22
|
+
import("node:url"), import("node:fs"), import("node:os"), import("node:path") ]);
|
|
23
|
+
// A one-shot verb records the jobs it starts in a store of its own, created on first use and removed when it ends:
|
|
24
|
+
// nothing of it is left in the app's job history. Its children hold no lease: no model is loaded beside them.
|
|
25
|
+
const scratch = path.join(os.tmpdir(), `mlx-bun-verb-${crypto.randomUUID()}`);
|
|
26
|
+
const jobs = createJobHost({ entry: fileURLToPath(new URL("./job-entry.ts", import.meta.url)), acquire: async () => ({ dispose() {} }),
|
|
27
|
+
createStore: () => new JobStore(path.join(scratch, "jobs.db"), path.join(scratch, "logs")) });
|
|
28
|
+
const jobService = createJobService(jobs);
|
|
29
|
+
// A verb that names no model runs on the app's automatic choice (`cli/model-selection.ts`), the same one `serve` makes.
|
|
30
|
+
const host = createHostServices({ log() {}, hub: { ...createCatalogHub(), async pickDefault(signal) {
|
|
31
|
+
const { m } = await (await import("./model-selection")).resolveModelAuto(null, {}, signal);
|
|
32
|
+
return { id: m.repoId, directory: m.path };
|
|
33
|
+
} } });
|
|
34
|
+
const memoryDependencies = name === "memory" || name === "setup" ? (await import("./memory")).defaultMemoryDependencies() : undefined;
|
|
35
|
+
try {
|
|
36
|
+
return await runVerb({ program: PROGRAM, spec, ...(Array.isArray(input) ? { argv: input } : input), services: { ...host, bindings: { ...host.bindings, jobs: () => jobService, ...(memoryDependencies ? { storage: (scope) => {
|
|
37
|
+
const storage = host.bindings.storage!(scope);
|
|
38
|
+
return { path: (key, options) => key === "vault" ? memoryDependencies.vault : storage.path(key, options) };
|
|
39
|
+
} } : {}) } },
|
|
40
|
+
// Only the verb's own module activates (a verb of one module never starts another's runners).
|
|
41
|
+
modules: async () => installedModules(manifest => manifest.verbs?.some(verb => verb.name === name) ?? false,
|
|
42
|
+
name === "memory" || name === "setup" ? { memory: { cli: () => (memoryDependencies!) } } : {}),
|
|
43
|
+
activated: loaded => jobService.serve(loaded.jobs),
|
|
44
|
+
terminal: { step: terminal.step, box: lines => terminal.box([...lines]), heading: terminal.h1,
|
|
45
|
+
table: (columns, rows) => terminal.table(columns.map(column => ({ ...column })), rows.map(row => [...row])),
|
|
46
|
+
style: { ...terminal.style, gradient: terminal.gradient } } });
|
|
47
|
+
} finally {
|
|
48
|
+
try { await jobs.close(); } finally { fs.rmSync(scratch, { recursive: true, force: true }); }
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { CommandArgs } from "./args";
|
|
2
|
+
|
|
3
|
+
/** Resolve main's numerical aliases once, before model loading. An explicit
|
|
4
|
+
* KV choice overrides the preset; the explicit kernel choice overrides both. */
|
|
5
|
+
export function numericalPolicy(args: CommandArgs): { kv: string | undefined; fusedSdpa: boolean } {
|
|
6
|
+
const value = (name: string) => typeof args.values[name] === "string" ? args.values[name] as string : undefined;
|
|
7
|
+
const kv = value("kv-quant") ?? (args.values.l2 === true ? "config" : args.values.l1 === true ? "off" : undefined);
|
|
8
|
+
const fused = value("fused-sdpa");
|
|
9
|
+
if (fused !== undefined && !["on", "off", "1", "0", "true", "false"].includes(fused))
|
|
10
|
+
throw new Error("--fused-sdpa expects on|off");
|
|
11
|
+
return { kv, fusedSdpa: fused === undefined ? kv === "config" : ["on", "1", "true"].includes(fused) };
|
|
12
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
3
|
+
import type { CommandArgs } from "./args";
|
|
4
|
+
import { openRegistry } from "../storage/paths";
|
|
5
|
+
import pkg from "../../package.json" with { type: "json" };
|
|
6
|
+
|
|
7
|
+
// Main's `mlx-bun perplexity` (02d723a:src/cli.ts): mlx_lm.perplexity's method over
|
|
8
|
+
// a LOCAL dataset file (never a Hugging Face download), scored in process.
|
|
9
|
+
|
|
10
|
+
export const PERPLEXITY_USAGE = "usage: mlx-bun perplexity <model-query-or-path> --data-path <file.txt|file.jsonl> [--sequence-length 512] [--num-samples 256] [--batch-size 8] [--seed 123]";
|
|
11
|
+
|
|
12
|
+
export interface PerplexityOptions { model: string; dataPath: string; sequenceLength: number; numSamples: number; batchSize: number; seed: number; }
|
|
13
|
+
|
|
14
|
+
/** Main's flags, defaults and validation; -1 (all rows) is accepted for --num-samples only. */
|
|
15
|
+
export function perplexityOptions(parsed: CommandArgs): PerplexityOptions {
|
|
16
|
+
const { values, positionals } = parsed;
|
|
17
|
+
const model = positionals[0] ?? values.model ?? values.query, dataPath = values["data-path"];
|
|
18
|
+
if (typeof model !== "string" || typeof dataPath !== "string") throw new Error(PERPLEXITY_USAGE);
|
|
19
|
+
const int = (name: string, fallback: number, lo: number) => {
|
|
20
|
+
const raw = values[name] === undefined ? String(fallback) : String(values[name]), v = Number(raw);
|
|
21
|
+
if (!Number.isInteger(v) || (v < lo && !(name === "num-samples" && v === -1)))
|
|
22
|
+
throw new Error(`--${name} expects an integer >= ${lo} (got "${raw}")`);
|
|
23
|
+
return v;
|
|
24
|
+
};
|
|
25
|
+
return { model, dataPath, sequenceLength: int("sequence-length", 512, 2), numSamples: int("num-samples", 256, 1),
|
|
26
|
+
batchSize: int("batch-size", 8, 1), seed: int("seed", 123, 0) };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const gb = (bytes: number) => `${(bytes / 2 ** 30).toFixed(2)} GB`;
|
|
30
|
+
|
|
31
|
+
export async function runPerplexity(parsed: CommandArgs): Promise<void> {
|
|
32
|
+
const o = perplexityOptions(parsed);
|
|
33
|
+
if (!existsSync(o.dataPath)) throw new Error(`data file not found: ${o.dataPath} (a local .txt or .jsonl — HF datasets are not downloaded)`);
|
|
34
|
+
let modelDir = o.model;
|
|
35
|
+
if (!existsSync(join(o.model, "config.json"))) {
|
|
36
|
+
const reg = openRegistry();
|
|
37
|
+
try {
|
|
38
|
+
if (reg.list().length === 0) await reg.scan();
|
|
39
|
+
modelDir = reg.resolve(o.model).path;
|
|
40
|
+
} finally { reg.close(); }
|
|
41
|
+
}
|
|
42
|
+
modelDir = resolve(modelDir);
|
|
43
|
+
|
|
44
|
+
// The startup step: compile any Neural Engine program the system cache lacks before the model loads.
|
|
45
|
+
await (await import("./ane-install")).ensureAneInstall();
|
|
46
|
+
const { banner, step, box, style } = await import("./terminal");
|
|
47
|
+
banner(pkg.version);
|
|
48
|
+
const sLoad = step(`loading ${modelDir}`);
|
|
49
|
+
// The library dlopens MLX on import: load it only once the inputs are known good.
|
|
50
|
+
const { loadModelConfig, Weights, createModel, loadTokenizer } = await import("@mlx-bun/inference");
|
|
51
|
+
const { parseSamples, packRows, evalPpl } = await import("@mlx-bun/inference/scoring");
|
|
52
|
+
const { resolveModelProfile } = await import("@mlx-bun/inference/models/profile");
|
|
53
|
+
const { peakMemory, resetPeakMemory } = await import("@mlx-bun/mlx/ffi");
|
|
54
|
+
const config = await loadModelConfig(modelDir);
|
|
55
|
+
// Colibri-container checkpoints (GLM-5.2) need the streamed runtime; scoring runs the
|
|
56
|
+
// synchronous forward over createModel, as main's verb did, so refuse them before loading.
|
|
57
|
+
if (resolveModelProfile(config).profile.execution.loader === "colibri") {
|
|
58
|
+
sLoad.fail("Colibri-container checkpoint");
|
|
59
|
+
throw new Error(`${modelDir} is a Colibri-container checkpoint (GLM-5.2); perplexity scores createModel graphs only`);
|
|
60
|
+
}
|
|
61
|
+
const model = createModel(await Weights.open(modelDir), config);
|
|
62
|
+
const tok = await loadTokenizer(modelDir);
|
|
63
|
+
sLoad.done(`model loaded ${style.dim(`· ${modelDir}`)}`);
|
|
64
|
+
|
|
65
|
+
const sData = step(`tokenizing ${o.dataPath}`);
|
|
66
|
+
const samples = parseSamples(await Bun.file(o.dataPath).text(), o.dataPath);
|
|
67
|
+
const rows = packRows(samples.map(t => tok.encode(t)), { sequenceLength: o.sequenceLength, numSamples: o.numSamples, seed: o.seed });
|
|
68
|
+
if (rows.length === 0) {
|
|
69
|
+
sData.fail(`dataset too small: fewer than ${o.sequenceLength} tokens (need at least one full row)`);
|
|
70
|
+
throw new Error(`dataset too small: fewer than ${o.sequenceLength} tokens (need at least one full row)`);
|
|
71
|
+
}
|
|
72
|
+
sData.done(`${rows.length} row(s) × ${o.sequenceLength} tokens ${style.dim(`· ${samples.length} sample(s), seed ${o.seed}`)}`);
|
|
73
|
+
|
|
74
|
+
const sEval = step(`evaluating (batch ${o.batchSize})`);
|
|
75
|
+
resetPeakMemory();
|
|
76
|
+
const t0 = performance.now();
|
|
77
|
+
const r = evalPpl(model, rows, o.batchSize, (done, total) => sEval.update(`batch ${done}/${total}`));
|
|
78
|
+
const seconds = (performance.now() - t0) / 1000;
|
|
79
|
+
sEval.done(`evaluated ${r.tokens.toLocaleString()} tokens ${style.dim(`in ${seconds.toFixed(1)} s`)}`);
|
|
80
|
+
console.log();
|
|
81
|
+
box([
|
|
82
|
+
`${style.green("●")} ${style.bold("perplexity")} ${style.dim(`· ${modelDir.split("/snapshots/")[0]?.split("/").at(-1) ?? modelDir}`)}`,
|
|
83
|
+
"",
|
|
84
|
+
`ppl ${style.green(style.bold(r.ppl.toFixed(3)))} ${style.dim(`± ${r.standardError.toFixed(3)}`)}`,
|
|
85
|
+
`mean CE ${style.bold(r.meanLoss.toFixed(4))} ${style.dim("nats/token")}`,
|
|
86
|
+
`tokens ${style.bold(r.tokens.toLocaleString())} ${style.dim(`· ${r.rows} row(s) × ${o.sequenceLength}`)}`,
|
|
87
|
+
`speed ${style.dim(`${(r.tokens / seconds).toFixed(0)} tok/s · peak ${gb(peakMemory())}`)}`,
|
|
88
|
+
]);
|
|
89
|
+
}
|