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
package/src/cli/serve.ts
ADDED
|
@@ -0,0 +1,500 @@
|
|
|
1
|
+
import { runtimeValue } from "@mlx-bun/inference/runtime/config";
|
|
2
|
+
import { parseTurboQuantScheme } from "@mlx-bun/inference/artifacts/config";
|
|
3
|
+
import { isTranscriptionModelType } from "@mlx-bun/inference/models/support";
|
|
4
|
+
import { parseCommand, type CommandArgs } from "./args";
|
|
5
|
+
import { numericalPolicy } from "./numerical-policy";
|
|
6
|
+
import { storagePath } from "../storage/paths";
|
|
7
|
+
import { resolveModelAuto } from "./model-selection";
|
|
8
|
+
import type { ModelRecord } from "@mlx-bun/hub/registry";
|
|
9
|
+
import type { RequestPrepOptions } from "../server/request-prep";
|
|
10
|
+
import type { DraftKind } from "../engine/model-host";
|
|
11
|
+
import { installedModules, locateTaskModel, MEMORY_TASK_MODEL, type ModuleSettings } from "../modules";
|
|
12
|
+
import { createAppState, type AppState, type AppStateOptions, type AppStoragePaths, type ModelHostLink } from "./serve-state";
|
|
13
|
+
import type { ModelHostHooks } from "./serve-host";
|
|
14
|
+
import { resolveServingLimits, shutdownTimeoutMs, type RunningApp, type ServeOptions } from "./serve-options";
|
|
15
|
+
|
|
16
|
+
// The composition lives in two halves: serve-state (persistent, CPU-only) and
|
|
17
|
+
// serve-host (model-scoped). This module parses flags, composes both, and owns
|
|
18
|
+
// the process (signals, browser, shutdown deadline). The model half is
|
|
19
|
+
// imported only by the composition that runs it, so an isolated parent
|
|
20
|
+
// (serve-isolated.ts) never loads the engine.
|
|
21
|
+
export { resolveServingLimits, shutdownTimeoutMs, type RunningApp, type ServeOptions };
|
|
22
|
+
|
|
23
|
+
/** The saved-state root's default byte budget, across every model's directory (`--ssd-cache-max` overrides). */
|
|
24
|
+
export const DEFAULT_SAVED_STATE_BYTES = 20 * 2 ** 30;
|
|
25
|
+
|
|
26
|
+
/** What the app decides for the modules that run in the persistent state: the chat's read-only policy and working directory. */
|
|
27
|
+
export function stateModuleSettings(options: Pick<AppStateOptions, "readOnly" | "chatPaths">): ModuleSettings {
|
|
28
|
+
return { chat: { ...(options.readOnly ? { readOnly: true } : {}), ...(options.chatPaths?.cwd ? { cwd: options.chatPaths.cwd } : {}) } };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Validate before opening a registry, loading a model, or creating a listener. */
|
|
32
|
+
export function parseServeOptions(args: CommandArgs): ServeOptions {
|
|
33
|
+
const value = (name: string) => typeof args.values[name] === "string" ? args.values[name] as string : undefined;
|
|
34
|
+
const number = (name: string, lo = 0, hi = Infinity, integer = false): number | undefined => {
|
|
35
|
+
const raw = value(name);
|
|
36
|
+
if (raw === undefined) return undefined;
|
|
37
|
+
const parsed = Number(raw);
|
|
38
|
+
if (!raw.trim() || !Number.isFinite(parsed) || parsed < lo || parsed > hi || (integer && !Number.isSafeInteger(parsed)))
|
|
39
|
+
throw new Error(`--${name} expects ${integer ? "an integer" : "a number"} in [${lo}, ${hi}]`);
|
|
40
|
+
return parsed;
|
|
41
|
+
};
|
|
42
|
+
const thinking = value("thinking");
|
|
43
|
+
if (thinking !== undefined && !["on", "off", "1", "0", "true", "false"].includes(thinking))
|
|
44
|
+
throw new Error("--thinking expects on|off");
|
|
45
|
+
const policy = numericalPolicy(args);
|
|
46
|
+
// An explicit --kv-quant is the policy's own choice; reading it here keeps its
|
|
47
|
+
// accepted values and default in the generated configuration reference.
|
|
48
|
+
const kv = value("kv-quant") ?? policy.kv ?? "off";
|
|
49
|
+
// Main's TurboQuant spec, turbo (k8v3) or turbo:k<bits>v<bits>, is its own scheme beside affine KV.
|
|
50
|
+
const turboQuant = parseTurboQuantScheme(kv);
|
|
51
|
+
if (!turboQuant && !["off", "config", "4", "8"].includes(kv)) throw new Error("--kv-quant expects off|config|4|8|turbo[:k<bits>v<bits>]");
|
|
52
|
+
const cache: ServeOptions["cache"] = turboQuant ? { turboQuant }
|
|
53
|
+
: { kvQuant: kv === "4" || kv === "8" ? Number(kv) : kv as "off" | "config" };
|
|
54
|
+
const promptCache = number("prompt-cache");
|
|
55
|
+
if (promptCache !== undefined) cache.promptCacheBytes = promptCache * 2 ** 30;
|
|
56
|
+
// Saved prompt/KV state is on by default: under MLX_BUN_HOME/kv, one byte budget across every model's
|
|
57
|
+
// directory. `--ssd-cache <dir>` moves it and `--ssd-cache off` disables it. A model swap resumes from it.
|
|
58
|
+
const ssdRaw = value("ssd-cache");
|
|
59
|
+
if (ssdRaw !== undefined && !ssdRaw.trim()) throw new Error("--ssd-cache expects a directory or off");
|
|
60
|
+
const ssdOff = ssdRaw === "off";
|
|
61
|
+
if (ssdRaw !== undefined && !ssdOff && promptCache === 0) throw new Error("SSD cache requires a nonzero RAM prompt cache");
|
|
62
|
+
const ssd = ssdOff ? undefined : ssdRaw ?? (promptCache === 0 ? undefined : storagePath("kv"));
|
|
63
|
+
if (!ssd && ["ssd-cache-max", "ssd-demote-idle", "generation-checkpoint", "ssd-cache-verify"].some(name => args.values[name] !== undefined))
|
|
64
|
+
throw new Error(ssdOff ? "SSD cache options need saved state, and --ssd-cache off disables it" : "SSD cache options require a nonzero RAM prompt cache");
|
|
65
|
+
if (ssd) {
|
|
66
|
+
cache.ssdCacheDir = ssd;
|
|
67
|
+
const max = number("ssd-cache-max"), idle = number("ssd-demote-idle"), checkpoint = number("generation-checkpoint", 1, Number.MAX_SAFE_INTEGER, true);
|
|
68
|
+
cache.ssdCacheMaxBytes = max === undefined ? DEFAULT_SAVED_STATE_BYTES : max === 0 ? Infinity : max * 2 ** 30;
|
|
69
|
+
if (idle !== undefined) cache.ssdDemoteIdleSec = idle;
|
|
70
|
+
if (checkpoint !== undefined) cache.generationCheckpointTokens = checkpoint;
|
|
71
|
+
cache.ssdCacheVerify = args.values["ssd-cache-verify"] === true;
|
|
72
|
+
}
|
|
73
|
+
const temperature = number("temperature", 0, 5) ?? number("temp", 0, 5);
|
|
74
|
+
const topP = number("top-p", 0, 1), topK = number("top-k", 0, 1_000_000);
|
|
75
|
+
const hlg = value("hlg-sampling");
|
|
76
|
+
if (hlg !== undefined && !["on", "off", "1", "0", "true", "false"].includes(hlg))
|
|
77
|
+
throw new Error("--hlg-sampling expects on|off");
|
|
78
|
+
const request: RequestPrepOptions = {
|
|
79
|
+
...(thinking !== undefined ? { defaultThinking: ["on", "1", "true"].includes(thinking) } : {}),
|
|
80
|
+
...(temperature !== undefined ? { defaultTemperature: temperature } : {}),
|
|
81
|
+
...(topP !== undefined ? { defaultTopP: topP } : {}),
|
|
82
|
+
...(topK !== undefined ? { defaultTopK: topK } : {}),
|
|
83
|
+
// Main's HLG knobs in nats; the mid gain folds from --temperature.
|
|
84
|
+
...(hlg !== undefined && ["on", "1", "true"].includes(hlg) ? { hlg: { enabled: true,
|
|
85
|
+
width: number("hlg-width", 0, 100) ?? 4, shoulder: number("hlg-shoulder", 0, 100) ?? 4,
|
|
86
|
+
toe: number("hlg-toe", 0, 100) ?? 6, pivotOffset: number("hlg-pivot-offset", 0, 100) ?? 6, pivot: "top" } } : {}),
|
|
87
|
+
};
|
|
88
|
+
const adapterDir = value("adapter") ?? value("adapter-path");
|
|
89
|
+
if (adapterDir !== undefined && !adapterDir.trim()) throw new Error("--adapter expects a directory");
|
|
90
|
+
// Main's speculative flags, validated before model selection with its messages.
|
|
91
|
+
const draftModel = value("draft-model");
|
|
92
|
+
if (draftModel !== undefined && !draftModel.trim()) throw new Error("--draft-model expects a path or query");
|
|
93
|
+
const numDraftRaw = value("num-draft-tokens");
|
|
94
|
+
// `adaptive`: each round's count, up to the drafter's own width, comes from the graph's verify costs.
|
|
95
|
+
const adaptiveDepth = numDraftRaw === "adaptive";
|
|
96
|
+
const numDraftTokens = numDraftRaw === undefined || adaptiveDepth ? undefined : Number(numDraftRaw);
|
|
97
|
+
if (numDraftTokens !== undefined && (!Number.isInteger(numDraftTokens) || numDraftTokens < 1))
|
|
98
|
+
throw new Error(`--num-draft-tokens expects an integer >= 1 or "adaptive" (got "${numDraftRaw}")`);
|
|
99
|
+
const draftKinds: DraftKind[] = ["dspark", "deepspec", "assistant", "two-model", "ngram", "mtp"];
|
|
100
|
+
const draftKindRaw = value("draft-kind");
|
|
101
|
+
if (draftKindRaw !== undefined && !draftKinds.includes(draftKindRaw as DraftKind))
|
|
102
|
+
throw new Error(`--draft-kind expects two-model|assistant|dspark|deepspec|mtp|ngram (got "${draftKindRaw}")`);
|
|
103
|
+
const draftKind = draftKindRaw as DraftKind | undefined;
|
|
104
|
+
const ngramInt = (name: string): number | undefined => {
|
|
105
|
+
const raw = value(name);
|
|
106
|
+
if (raw === undefined) return undefined;
|
|
107
|
+
const parsed = Number(raw);
|
|
108
|
+
if (!Number.isInteger(parsed) || parsed < 1) throw new Error(`--${name} expects an integer >= 1 (got "${raw}")`);
|
|
109
|
+
return parsed;
|
|
110
|
+
};
|
|
111
|
+
const ngramMax = ngramInt("ngram-max"), ngramMin = ngramInt("ngram-min");
|
|
112
|
+
if (ngramMax !== undefined && ngramMin !== undefined && ngramMin > ngramMax)
|
|
113
|
+
throw new Error(`--ngram-min (${ngramMin}) must be <= --ngram-max (${ngramMax})`);
|
|
114
|
+
if ((ngramMax !== undefined || ngramMin !== undefined) && draftKind !== "ngram")
|
|
115
|
+
console.warn("--ngram-max/--ngram-min only apply with --draft-kind ngram — ignored");
|
|
116
|
+
const mtpRaw = value("mtp");
|
|
117
|
+
if (mtpRaw !== undefined && !["on", "off", "1", "0", "true", "false"].includes(mtpRaw)) throw new Error(`--mtp expects on|off (got "${mtpRaw}")`);
|
|
118
|
+
// Main's speech-to-text companion: explicit checkpoint + residency policy.
|
|
119
|
+
const whisperModel = value("whisper-model");
|
|
120
|
+
if (whisperModel !== undefined && !whisperModel.trim()) throw new Error("--whisper-model expects a path or query");
|
|
121
|
+
const whisperIdleRaw = value("whisper-idle-unload");
|
|
122
|
+
const whisperIdle = whisperIdleRaw === undefined ? undefined : Number(whisperIdleRaw);
|
|
123
|
+
if (whisperIdle !== undefined && (!whisperIdleRaw!.trim() || !Number.isFinite(whisperIdle) || whisperIdle < 0))
|
|
124
|
+
throw new Error(`--whisper-idle-unload expects seconds >= 0 (got "${whisperIdleRaw}")`);
|
|
125
|
+
const whisperResident = args.values["whisper-resident"] === true, preload = args.values.preload === true;
|
|
126
|
+
const whisper = whisperModel !== undefined || whisperIdle !== undefined || whisperResident || preload
|
|
127
|
+
? { ...(whisperModel !== undefined ? { model: whisperModel } : {}), ...(whisperIdle !== undefined ? { idleUnloadSec: whisperIdle } : {}),
|
|
128
|
+
...(whisperResident ? { resident: true } : {}), ...(preload ? { preload: true } : {}) } : undefined;
|
|
129
|
+
const draft =draftModel !== undefined || draftKind !== undefined || numDraftTokens !== undefined || ngramMax !== undefined || ngramMin !== undefined || adaptiveDepth
|
|
130
|
+
? { ...(draftModel !== undefined ? { model: draftModel } : {}), ...(draftKind ? { kind: draftKind } : {}),
|
|
131
|
+
...(numDraftTokens !== undefined ? { numTokens: numDraftTokens } : {}), ...(adaptiveDepth ? { adaptiveDepth } : {}),
|
|
132
|
+
...(ngramMax !== undefined ? { ngramMax } : {}), ...(ngramMin !== undefined ? { ngramMin } : {}) } : undefined;
|
|
133
|
+
// Main's paged KV: the flag or its env mirror; the block size and the direct read only with paging.
|
|
134
|
+
const pagedKv = args.values["paged-kv"] === true || runtimeValue("MLX_BUN_PAGED_KV") === "1";
|
|
135
|
+
const blockSize = number("paged-kv-block-size", 1, Number.MAX_SAFE_INTEGER, true);
|
|
136
|
+
const direct = args.values["paged-kv-direct"] === true;
|
|
137
|
+
if (blockSize !== undefined && !pagedKv) throw new Error("--paged-kv-block-size requires --paged-kv");
|
|
138
|
+
if (direct && !pagedKv) throw new Error("--paged-kv-direct requires --paged-kv");
|
|
139
|
+
if (pagedKv) cache.pagedKv = { ...(blockSize !== undefined ? { blockSize } : {}), ...(direct ? { direct } : {}) };
|
|
140
|
+
const memoryBudget = number("memory-budget");
|
|
141
|
+
const modelBudget = number("model-budget");
|
|
142
|
+
if (modelBudget !== undefined && modelBudget <= 0) throw new Error("--model-budget expects a number of GB above 0");
|
|
143
|
+
const contextTokens = number("context-length", 1, Number.MAX_SAFE_INTEGER, true);
|
|
144
|
+
const host = value("host") ?? "127.0.0.1";
|
|
145
|
+
if (!host.trim()) throw new Error("--host expects an address");
|
|
146
|
+
const kvBudget = number("kv-budget");
|
|
147
|
+
const maxTokens = number("max-tokens", 1, 10_000_000);
|
|
148
|
+
const inProcess = args.values["in-process"] === true;
|
|
149
|
+
if (args.values.isolate === true) console.warn("--isolate is the default now and is ignored; use --in-process to load the models in this process");
|
|
150
|
+
const profileLimit = profileContextLimit();
|
|
151
|
+
return {
|
|
152
|
+
query: value("model") ?? args.positionals[0] ?? value("query") ?? null,
|
|
153
|
+
hostname: host, port: number("port", 0, 65535, true) ?? 8080,
|
|
154
|
+
// Main's --decode-concurrency is an alias of --batch: the same cap on the continuous scheduler's rows.
|
|
155
|
+
capacity: number("batch", 1, Number.MAX_SAFE_INTEGER, true) ?? number("decode-concurrency", 1, Number.MAX_SAFE_INTEGER, true) ?? 8,
|
|
156
|
+
contextLimit: profileLimit,
|
|
157
|
+
defaultGeneratedTokens: maxTokens === undefined ? undefined : Math.floor(maxTokens),
|
|
158
|
+
...(kvBudget ? { kvBudgetBytes: kvBudget * 1e9 } : {}),
|
|
159
|
+
...(memoryBudget ? { memoryBudgetBytes: memoryBudget * 1e9 } : {}),
|
|
160
|
+
...(modelBudget ? { modelBudgetBytes: modelBudget * 1e9 } : {}),
|
|
161
|
+
...(contextTokens !== undefined ? { contextTokens } : {}),
|
|
162
|
+
forceWire: args.values["force-wire"] === true, expertOffload: args.values["expert-offload"] === true,
|
|
163
|
+
allowPrivateMedia: args.values["allow-private-media"] === true,
|
|
164
|
+
...(adapterDir ? { adapterDir } : {}),
|
|
165
|
+
...(draft ? { draft } : {}),
|
|
166
|
+
...(mtpRaw !== undefined ? { mtp: ["on", "1", "true"].includes(mtpRaw) } : {}),
|
|
167
|
+
...(whisper ? { whisper } : {}),
|
|
168
|
+
readOnly: false, noOpen: args.values["no-open"] === true, ...(inProcess ? { inProcess } : {}),
|
|
169
|
+
cache, request, fusedSdpa: policy.fusedSdpa,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Main's MLX_BUN_RD_CONTEXT_LIMIT: the enforced context cap when set, else none. */
|
|
174
|
+
export function profileContextLimit(): number | null {
|
|
175
|
+
const profileContext = runtimeValue("MLX_BUN_RD_CONTEXT_LIMIT");
|
|
176
|
+
const profileLimit = profileContext === undefined ? null : Number(profileContext);
|
|
177
|
+
if (profileLimit !== null && (!Number.isSafeInteger(profileLimit) || profileLimit < 1))
|
|
178
|
+
throw new Error("MLX_BUN_RD_CONTEXT_LIMIT must be a positive integer");
|
|
179
|
+
return profileLimit;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Internal (the worker app form, `cli/worker-entry.ts`), never a CLI flag:
|
|
183
|
+
* listen on a Unix socket, let the worker's admin surface wrap the routes and
|
|
184
|
+
* close ahead of the app's producers, and see the model host's link while it
|
|
185
|
+
* is attached (the admin lease reaches the gateway through it). */
|
|
186
|
+
export interface AppSocketHooks extends Pick<ModelHostHooks, "unix" | "routes" | "beforeDrain"> {
|
|
187
|
+
link?: { current?: ModelHostLink };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Lend the host's link to the state and keep it in `holder` while attached. */
|
|
191
|
+
function observeLink(state: AppState, holder: { current?: ModelHostLink }): AppState {
|
|
192
|
+
return { ...state, attach(link) {
|
|
193
|
+
const detach = state.attach(link);
|
|
194
|
+
holder.current = link;
|
|
195
|
+
return () => { if (holder.current === link) holder.current = undefined; detach(); };
|
|
196
|
+
} };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** The app's lifetime around one model host (the CLI's and `mlx-bun/server`'s):
|
|
200
|
+
* the persistent state first, then the host that borrows it. The host loads
|
|
201
|
+
* the installed modules (`src/modules.ts`) over its own core services and stops
|
|
202
|
+
* them in its drain. `start` makes the host's drain step close the state's
|
|
203
|
+
* producers while the engine is alive; a failed start closes the state. Close
|
|
204
|
+
* resolves with the host's own result once the state has closed too. */
|
|
205
|
+
export async function startApp<Host extends { close(): Promise<unknown> }>(options: AppStateOptions, storagePaths: AppStoragePaths,
|
|
206
|
+
start: (state: AppState) => Promise<Host>) {
|
|
207
|
+
const state = await createAppState(options, storagePaths, client => installedModules("state", { ...stateModuleSettings(options), memory: { client } }));
|
|
208
|
+
let host: Host;
|
|
209
|
+
try {
|
|
210
|
+
host = await start(state);
|
|
211
|
+
} catch (error) {
|
|
212
|
+
try { await state.close(); } catch (failure) { throw new AggregateError([error, failure], "startup and cleanup failed"); }
|
|
213
|
+
throw error;
|
|
214
|
+
}
|
|
215
|
+
return { state, host, async close(): Promise<Awaited<ReturnType<Host["close"]>>> {
|
|
216
|
+
const errors: unknown[] = [];
|
|
217
|
+
let result: unknown;
|
|
218
|
+
try { result = await host.close(); } catch (error) { errors.push(error); }
|
|
219
|
+
// The host's drain already closed the state; a repeated failure here is the same one.
|
|
220
|
+
try { await state.close(); } catch (error) { errors.push(error); }
|
|
221
|
+
if (errors.length) throw errors[0];
|
|
222
|
+
return result as Awaited<ReturnType<Host["close"]>>;
|
|
223
|
+
} };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** CLI composition: the persistent state first, then the model host that
|
|
227
|
+
* borrows it. The host stops the state's producers inside its drain step, so
|
|
228
|
+
* jobs and downloads end while the engine is alive, as before the split. */
|
|
229
|
+
export async function startModelServer(model: ModelRecord, options: ServeOptions, hooks: AppSocketHooks = {}): Promise<RunningApp> {
|
|
230
|
+
// The default: the same persistent state, with each model's host in a worker process behind a proxy. A worker's own app
|
|
231
|
+
// (the launch socket) and `--in-process` load the models in this process.
|
|
232
|
+
if (!options.inProcess && !hooks.unix) {
|
|
233
|
+
return (await import("./serve-isolated")).startIsolatedServer(model, options, { modules: client => installedModules("state", { ...stateModuleSettings(options), memory: { client } }), taskSnapshot: () => locateTaskModel(MEMORY_TASK_MODEL) });
|
|
234
|
+
}
|
|
235
|
+
const [{ startModelHost }, { createInProcessMemoryClient }] = await Promise.all([import("./serve-host"), import("./memory-engine")]);
|
|
236
|
+
// Memory synthesis gets main's own task model, loaded by the first run (the isolated parent has none).
|
|
237
|
+
const app = await startApp({ ...options, memoryTaskModel: () => createInProcessMemoryClient() }, options.storagePaths ?? {},
|
|
238
|
+
state => startModelHost(hooks.link ? observeLink(state, hooks.link) : state, model, options, {
|
|
239
|
+
...(hooks.unix ? { unix: hooks.unix } : {}), ...(hooks.routes ? { routes: hooks.routes } : {}),
|
|
240
|
+
beforeDrain: async () => { try { await hooks.beforeDrain?.(); } finally { await state.close(); } } }));
|
|
241
|
+
return { ...("port" in app.host ? { port: app.host.port } : {}), downloads: app.state.downloads, async close() { await app.close(); } };
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Main's `serve <whisper checkpoint>`: the transcription-only host has no
|
|
245
|
+
* chat model, jobs, downloads, or web app, so no persistent state is composed. */
|
|
246
|
+
export async function startTranscriptionServer(model: ModelRecord, options: ServeOptions,
|
|
247
|
+
hooks: Pick<ModelHostHooks, "unix" | "routes" | "beforeDrain"> = {}): Promise<RunningApp> {
|
|
248
|
+
return (await import("./serve-host")).startTranscriptionHost(model, options, hooks);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** Internal (the worker app form; a parent may call it to fail fast before
|
|
252
|
+
* spawning): serve arguments parsed and validated exactly as the CLI does,
|
|
253
|
+
* minus what cannot run behind a launch socket. `--host`, `--port`, and
|
|
254
|
+
* `--no-open` are accepted and never steer the socket bind. A worker's app always loads its models in its own process
|
|
255
|
+
* (`--in-process` is implied, and `--isolate` is ignored). A missing or empty model is refused: automatic selection may
|
|
256
|
+
* download the starter model. */
|
|
257
|
+
export function validateAppLaunchArgv(argv: readonly string[]): CommandArgs {
|
|
258
|
+
const args = parseCommand("serve", [...argv]);
|
|
259
|
+
if (!parseServeOptions(args).query?.trim())
|
|
260
|
+
throw new Error("a worker app launch needs a non-empty --model: automatic selection may download the starter model");
|
|
261
|
+
return args;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
export interface SignalPort {
|
|
265
|
+
on(signal: "SIGINT" | "SIGTERM", listener: () => void): unknown;
|
|
266
|
+
removeListener(signal: "SIGINT" | "SIGTERM", listener: () => void): unknown;
|
|
267
|
+
}
|
|
268
|
+
/** Keep listeners installed until teardown finishes, so a second signal cannot race it. */
|
|
269
|
+
export function installShutdownHandlers(close: () => Promise<void>, input: {
|
|
270
|
+
signals: SignalPort; exit(code: number): void; error(error: unknown): void; timeoutMs?: number;
|
|
271
|
+
}) {
|
|
272
|
+
let stopping = false;
|
|
273
|
+
const remove = () => { input.signals.removeListener("SIGINT", stop); input.signals.removeListener("SIGTERM", stop); };
|
|
274
|
+
const stop = () => {
|
|
275
|
+
if (stopping) return;
|
|
276
|
+
stopping = true;
|
|
277
|
+
// Keep the deadline at the process owner. Resource owners keep joining
|
|
278
|
+
// their work; timing out must not free model weights under a live borrower.
|
|
279
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
280
|
+
const deadline = new Promise<never>((_, reject) => {
|
|
281
|
+
timer = setTimeout(() => reject(new Error("Shutdown exceeded its deadline; persistence may be incomplete")), input.timeoutMs ?? 120_000);
|
|
282
|
+
timer.unref();
|
|
283
|
+
});
|
|
284
|
+
const work = (async () => { await close(); })();
|
|
285
|
+
void Promise.race([work, deadline]).then(() => input.exit(0), error => {
|
|
286
|
+
input.error(error); input.exit(1);
|
|
287
|
+
}).finally(() => { if (timer) clearTimeout(timer); remove(); });
|
|
288
|
+
};
|
|
289
|
+
input.signals.on("SIGINT", stop); input.signals.on("SIGTERM", stop);
|
|
290
|
+
return remove;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export function browserUrl(hostname: string, port: number): string {
|
|
294
|
+
const host = hostname === "0.0.0.0" || hostname === "::" ? "localhost" : hostname;
|
|
295
|
+
return `http://${host.includes(":") && !host.startsWith("[") ? `[${host}]` : host}:${port}/#/chat`;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** Main's AppleScript that focuses the first tab whose URL contains `match` in a
|
|
299
|
+
* literal-named browser, returning "ok"/"miss". The app name MUST be a literal
|
|
300
|
+
* (not a variable): AppleScript loads an app's scripting dictionary by literal
|
|
301
|
+
* name at COMPILE time, so `tell application someVar` can't resolve app-specific
|
|
302
|
+
* terms like `active tab index` (fails with -2740). Referencing an uninstalled
|
|
303
|
+
* app by literal name is also a compile error a `try` can't catch — hence we
|
|
304
|
+
* only ever run a browser's script when pgrep says it's running (= installed). */
|
|
305
|
+
export function focusTabScript(app: string, kind: "chromium" | "safari", match: string): string {
|
|
306
|
+
const m = JSON.stringify(match); // safe AppleScript string literal
|
|
307
|
+
if (kind === "safari") {
|
|
308
|
+
return `tell application "${app}"
|
|
309
|
+
repeat with w in windows
|
|
310
|
+
repeat with t in tabs of w
|
|
311
|
+
if URL of t contains ${m} then
|
|
312
|
+
set current tab of w to t
|
|
313
|
+
activate
|
|
314
|
+
return "ok"
|
|
315
|
+
end if
|
|
316
|
+
end repeat
|
|
317
|
+
end repeat
|
|
318
|
+
end tell
|
|
319
|
+
return "miss"`;
|
|
320
|
+
}
|
|
321
|
+
return `tell application "${app}"
|
|
322
|
+
repeat with w in windows
|
|
323
|
+
set k to 0
|
|
324
|
+
repeat with t in tabs of w
|
|
325
|
+
set k to k + 1
|
|
326
|
+
if URL of t contains ${m} then
|
|
327
|
+
set active tab index of w to k
|
|
328
|
+
set index of w to 1
|
|
329
|
+
activate
|
|
330
|
+
return "ok"
|
|
331
|
+
end if
|
|
332
|
+
end repeat
|
|
333
|
+
end repeat
|
|
334
|
+
end tell
|
|
335
|
+
return "miss"`;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Runs a command to completion: its exit code and stdout. */
|
|
339
|
+
export type CommandRunner = (argv: string[], timeoutMs?: number) => Promise<{ code: number; stdout: string }>;
|
|
340
|
+
const runCommand: CommandRunner = async (argv, timeoutMs) => {
|
|
341
|
+
const child = Bun.spawn(argv, { stdout: "pipe", stderr: "ignore", ...(timeoutMs ? { timeout: timeoutMs } : {}) });
|
|
342
|
+
const stdout = await new Response(child.stdout).text();
|
|
343
|
+
return { code: await child.exited, stdout };
|
|
344
|
+
};
|
|
345
|
+
|
|
346
|
+
/** Main's browsers whose tabs serve can focus, each scripted by its own literal name. */
|
|
347
|
+
const TAB_BROWSERS: Array<{ proc: string; kind: "chromium" | "safari" }> = [
|
|
348
|
+
{ proc: "Google Chrome", kind: "chromium" },
|
|
349
|
+
{ proc: "Arc", kind: "chromium" },
|
|
350
|
+
{ proc: "Brave Browser", kind: "chromium" },
|
|
351
|
+
{ proc: "Microsoft Edge", kind: "chromium" },
|
|
352
|
+
{ proc: "Safari", kind: "safari" },
|
|
353
|
+
];
|
|
354
|
+
|
|
355
|
+
/** Main's chat opener: reuse an already-open tab on this host:port instead of
|
|
356
|
+
* spawning a duplicate. Each browser's literal-named AppleScript runs ONLY when
|
|
357
|
+
* pgrep confirms it's running (so the literal `tell` always compiles). Falls back
|
|
358
|
+
* to a plain `open` (new tab) when no running browser has the tab, for browsers
|
|
359
|
+
* we don't script (e.g. Firefox), or if AppleScript is blocked. The first focus
|
|
360
|
+
* may trigger a one-time macOS "control your browser" permission prompt;
|
|
361
|
+
* declining it just falls back to opening a new tab. */
|
|
362
|
+
export async function openChatUi(url: string, run: CommandRunner = runCommand): Promise<void> {
|
|
363
|
+
// `host:port/` with the port always explicit: URL drops a default :80, and without
|
|
364
|
+
// the slash localhost:80 would match a tab on localhost:8080.
|
|
365
|
+
const { hostname, port, protocol } = new URL(url);
|
|
366
|
+
const hostPort = `${hostname}:${port || (protocol === "https:" ? "443" : "80")}/`;
|
|
367
|
+
for (const b of TAB_BROWSERS) {
|
|
368
|
+
try {
|
|
369
|
+
if ((await run(["pgrep", "-x", b.proc])).code !== 0) continue; // not running → skip (and don't compile its tell)
|
|
370
|
+
const focused = await run(["osascript", "-e", focusTabScript(b.proc, b.kind, hostPort)], 8000);
|
|
371
|
+
if (focused.code === 0 && focused.stdout.trim() === "ok") return; // focused an existing tab
|
|
372
|
+
} catch { /* try the next browser */ }
|
|
373
|
+
}
|
|
374
|
+
if ((await run(["open", url])).code !== 0) throw new Error("Browser could not be opened");
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Main's collision check: the models a server already on the bind address answers
|
|
378
|
+
* for (GET /v1/models, the served row first), or null when nothing serves there. */
|
|
379
|
+
export async function probeServer(hostname: string, port: number, timeoutMs = 1500): Promise<string[] | null> {
|
|
380
|
+
try {
|
|
381
|
+
const res = await fetch(new URL("/v1/models", browserUrl(hostname, port)), { signal: AbortSignal.timeout(timeoutMs) });
|
|
382
|
+
if (!res.ok) return null;
|
|
383
|
+
const rows = ((await res.json()) as { data?: Array<{ id: string; context_window?: number }> }).data ?? [];
|
|
384
|
+
const served = rows.find(m => m.context_window !== undefined) ?? rows[0];
|
|
385
|
+
return served ? [served.id] : null;
|
|
386
|
+
} catch {
|
|
387
|
+
return null;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
export interface ServeDependencies {
|
|
392
|
+
resolve: typeof resolveModelAuto;
|
|
393
|
+
/** The startup step, every launch before the chat model loads: compile any Neural Engine program the system
|
|
394
|
+
* cache lacks (`ensureAneInstall`). */
|
|
395
|
+
installAne(): Promise<void>;
|
|
396
|
+
start: typeof startModelServer;
|
|
397
|
+
startTranscription: typeof startTranscriptionServer;
|
|
398
|
+
interactive: boolean;
|
|
399
|
+
/** The models already served on the TCP port, checked before selection loads any weights (null: free). */
|
|
400
|
+
probe(hostname: string, port: number): Promise<string[] | null>;
|
|
401
|
+
open(url: string): void | Promise<void>;
|
|
402
|
+
log(message: string): void;
|
|
403
|
+
signals: SignalPort;
|
|
404
|
+
exit(code: number): void;
|
|
405
|
+
error(error: unknown): void;
|
|
406
|
+
}
|
|
407
|
+
const defaults: ServeDependencies = {
|
|
408
|
+
resolve: resolveModelAuto, installAne: async () => (await import("./ane-install")).ensureAneInstall(),
|
|
409
|
+
start: startModelServer, startTranscription: startTranscriptionServer, interactive: !!process.stdout.isTTY,
|
|
410
|
+
probe: (hostname, port) => probeServer(hostname, port), open: url => openChatUi(url),
|
|
411
|
+
log: message => console.log(message), signals: process, exit: code => process.exit(code),
|
|
412
|
+
error: error => console.error(error instanceof Error ? error.message : String(error)),
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
/** `aborted`: a stop signal landed during startup, so the app is already
|
|
416
|
+
* closed and was never announced (no URL, no browser). */
|
|
417
|
+
export interface ServedApp extends RunningApp { readonly aborted: boolean }
|
|
418
|
+
|
|
419
|
+
/** runServe's rejection when a stop signal cancels startup before an app
|
|
420
|
+
* exists. A load failure, or a failed close of an app a stop interrupted,
|
|
421
|
+
* rejects with its own error instead. */
|
|
422
|
+
export class StartupCancelledError extends Error {
|
|
423
|
+
constructor() { super("startup cancelled by signal"); this.name = "StartupCancelledError"; }
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
export async function runServe(args: CommandArgs, supplied: Partial<ServeDependencies> = {}): Promise<ServedApp> {
|
|
427
|
+
let options = parseServeOptions(args);
|
|
428
|
+
const deps = { ...defaults, ...supplied };
|
|
429
|
+
// Main's friendly collision check before loading gigabytes of weights (port 0 always binds a free port).
|
|
430
|
+
if (options.port !== 0) {
|
|
431
|
+
const running = await deps.probe(options.hostname, options.port);
|
|
432
|
+
if (running) throw new Error([`port ${options.port} is already serving ${running.join(", ")}.`,
|
|
433
|
+
"reuse it, stop it, or pick --port <other>.",
|
|
434
|
+
"NOTE: a second server is a second model in memory — check `mlx-bun fit` first."].join("\n"));
|
|
435
|
+
}
|
|
436
|
+
// A signal before the app exists cancels selection (a starter download stays
|
|
437
|
+
// resumable) and, once the model has loaded, closes the app right away; the
|
|
438
|
+
// shutdown handlers take over as soon as the listener is up.
|
|
439
|
+
const startup = new AbortController();
|
|
440
|
+
const cancelStartup = () => startup.abort(new StartupCancelledError());
|
|
441
|
+
deps.signals.on("SIGINT", cancelStartup); deps.signals.on("SIGTERM", cancelStartup);
|
|
442
|
+
let running: RunningApp | undefined, selection: Awaited<ReturnType<typeof resolveModelAuto>> | undefined, removeSignals = () => {};
|
|
443
|
+
let closed: Promise<void> | undefined;
|
|
444
|
+
const close = () => closed ??= (async () => { try { await running?.close(); } finally { removeSignals(); } })();
|
|
445
|
+
try {
|
|
446
|
+
selection = await deps.resolve(options.query, {}, startup.signal);
|
|
447
|
+
// A signal that landed during selection must not start a native load.
|
|
448
|
+
startup.signal.throwIfAborted();
|
|
449
|
+
if (isTranscriptionModelType(selection.m.modelType)) {
|
|
450
|
+
// Main: a Whisper checkpoint as the main model starts the transcription-only server.
|
|
451
|
+
deps.log(`Serving ${selection.m.repoId} as a transcription-only server${options.whisper?.preload ? " (loading the weights first)" : ""}`);
|
|
452
|
+
running = await deps.startTranscription(selection.m, options);
|
|
453
|
+
} else {
|
|
454
|
+
// Main resolves the draft model like the main model (a query never downloads).
|
|
455
|
+
if (options.draft?.model) {
|
|
456
|
+
const draft = await deps.resolve(options.draft.model, {}, startup.signal);
|
|
457
|
+
startup.signal.throwIfAborted();
|
|
458
|
+
options = { ...options, draft: { ...options.draft, modelDir: draft.m.path } };
|
|
459
|
+
}
|
|
460
|
+
// Main resolves --whisper-model the same way and refuses a non-Whisper checkpoint before loading.
|
|
461
|
+
if (options.whisper?.model) {
|
|
462
|
+
const whisper = await deps.resolve(options.whisper.model, {}, startup.signal);
|
|
463
|
+
startup.signal.throwIfAborted();
|
|
464
|
+
if (!isTranscriptionModelType(whisper.m.modelType))
|
|
465
|
+
throw new Error(`--whisper-model ${options.whisper.model} resolved to ${whisper.m.repoId} (model_type ${whisper.m.modelType}), not a Whisper checkpoint`);
|
|
466
|
+
options = { ...options, whisper: { ...options.whisper, modelDir: whisper.m.path, modelId: whisper.m.repoId } };
|
|
467
|
+
}
|
|
468
|
+
await deps.installAne();
|
|
469
|
+
startup.signal.throwIfAborted();
|
|
470
|
+
deps.log(`Loading ${selection.m.repoId}${selection.picked ? " (auto-selected)" : ""}`);
|
|
471
|
+
running = await deps.start(selection.m, options);
|
|
472
|
+
}
|
|
473
|
+
removeSignals = installShutdownHandlers(close, { signals: deps.signals, exit: deps.exit, error: deps.error, timeoutMs: shutdownTimeoutMs() });
|
|
474
|
+
} finally { deps.signals.removeListener("SIGINT", cancelStartup); deps.signals.removeListener("SIGTERM", cancelStartup); }
|
|
475
|
+
const app: ServedApp = { port: running.port, downloads: running.downloads, close, aborted: false };
|
|
476
|
+
if (startup.signal.aborted) { await close(); return { ...app, aborted: true }; }
|
|
477
|
+
if (selection.recommended) {
|
|
478
|
+
// Main started this transfer during selection and dropped its handle; the
|
|
479
|
+
// app's owner now carries it, reports it on /downloads, and joins it at shutdown.
|
|
480
|
+
try { running.downloads.start(selection.recommended); } catch (error) { deps.error(error); }
|
|
481
|
+
}
|
|
482
|
+
// Socket mode (the worker app form) has no URL to announce and no browser to open.
|
|
483
|
+
const url = running.port === undefined ? undefined : browserUrl(options.hostname, running.port);
|
|
484
|
+
if (isTranscriptionModelType(selection.m.modelType)) {
|
|
485
|
+
// No web app: nothing to open. Residency is the policy the flags set.
|
|
486
|
+
const idle = options.whisper?.idleUnloadSec ?? 0;
|
|
487
|
+
const residency = options.whisper?.resident ? "always resident" : idle === 0 ? "released after every take" : `idle unload ${idle}s`;
|
|
488
|
+
deps.log(`POST ${url ? url.replace("/#/chat", "/v1/audio/transcriptions") : "/v1/audio/transcriptions over the Unix socket"} (${residency}; ${options.whisper?.preload ? "loaded" : "loads on first request"})${url ? "\nStop: Ctrl+C" : ""}`);
|
|
489
|
+
return app;
|
|
490
|
+
}
|
|
491
|
+
if (!url) {
|
|
492
|
+
deps.log(`Serving ${selection.m.repoId} with continuous batching (capacity ${options.capacity}) over the Unix socket`);
|
|
493
|
+
return app;
|
|
494
|
+
}
|
|
495
|
+
deps.log(`Serving ${selection.m.repoId} with continuous batching (capacity ${options.capacity})${options.inProcess ? " in this process" : " in isolated model workers"}\nApp ${url}\nAPI ${url.replace("/#/chat", "/v1")}\nStop: Ctrl+C`);
|
|
496
|
+
if (deps.interactive && !options.noOpen) {
|
|
497
|
+
try { await deps.open(url); } catch (error) { deps.error(error); }
|
|
498
|
+
}
|
|
499
|
+
return app;
|
|
500
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// The `modelHost` core service for the persistent services (serve-state.ts):
|
|
2
|
+
// the model the attached serving host runs, reached over its own HTTP surface.
|
|
3
|
+
// The serving host owns residency (it is loaded before it serves and released
|
|
4
|
+
// when it closes), so this host reports that one model as resident and pinned,
|
|
5
|
+
// never evicts it, and leases it for `generate`: a wire request (OpenAI, Anthropic or
|
|
6
|
+
// Responses) sent to the host's listener, over its Unix socket when it has one. A serving
|
|
7
|
+
// host whose residency can evict supplies `hold`, and each lease holds the model resident
|
|
8
|
+
// through it until released. The composition may lend companion operations from its
|
|
9
|
+
// existing host; consumers get the same service for both without taking over its lifecycle.
|
|
10
|
+
import type { AcquireOptions, AdapterOperation, ModelHost, ModelId, ModelLease, ModelOperation, ModelOperations, ModelStats, ResidentModel } from "@mlx-bun/app-core";
|
|
11
|
+
import { ModelHostFailure } from "@mlx-bun/app-services/portable";
|
|
12
|
+
|
|
13
|
+
const OPERATIONS: readonly ModelOperation[] = ["generate"];
|
|
14
|
+
|
|
15
|
+
/** What a serving host lends: its model and where its listener is (`ModelHostLink` adds the rest). */
|
|
16
|
+
export interface ServedHostLink {
|
|
17
|
+
/** The served model: what modules lease for `generate` (its id and weight bytes). */
|
|
18
|
+
readonly model: { readonly id: string; readonly bytes: number };
|
|
19
|
+
/** Holds the model resident until released; a leased model is never evicted under its holder. Absent on a host that never evicts it. */
|
|
20
|
+
hold?(model: string, signal?: AbortSignal): Promise<{ release(): void }>;
|
|
21
|
+
/** The public port modules leasing the served model target. */
|
|
22
|
+
readonly port: number;
|
|
23
|
+
/** Internal (worker app form): the Unix socket the host listens on instead of TCP; the URL's port is then a placeholder. */
|
|
24
|
+
readonly unix?: string;
|
|
25
|
+
/** Makes a local model the served one (`POST /api/hub/serve`): loaded beside the resident ones when it fits, else in place of the least recently used. Rejects with a coded `ModelHostError`; absent on a host that serves one model. */
|
|
26
|
+
serve?(model: string, signal: AbortSignal): Promise<void>;
|
|
27
|
+
/** Every model the host holds resident, for the library's "loaded" marks and cache cleanup's protection; absent on a host that holds only its served model. */
|
|
28
|
+
resident?(): readonly ResidentModel[];
|
|
29
|
+
/** The served model's adapter operation: each call holds the model resident and runs under its execution lease, in the process that holds it. */
|
|
30
|
+
readonly adapters?: AdapterOperation;
|
|
31
|
+
/** Operations and residency owned by the composition's companion host. The forwarding service borrows it. */
|
|
32
|
+
readonly companions?: ModelHost;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface ServedModelHostOptions<Link extends ServedHostLink> {
|
|
36
|
+
/** The attached serving host; none before one attaches and after it detaches. */
|
|
37
|
+
link(): Link | undefined;
|
|
38
|
+
/** Sends a request to a host's listener, over its socket when it has one. */
|
|
39
|
+
fetch(request: Request, link: Link): Promise<Response>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function createServedModelHost<Link extends ServedHostLink>(options: ServedModelHostOptions<Link>): ModelHost {
|
|
43
|
+
const attached = () => options.link() ?? (() => { throw new ModelHostFailure("closed", "no model host is attached"); })();
|
|
44
|
+
let leases = 0, lastUsedAt = 0;
|
|
45
|
+
const resident = (link: Link): ResidentModel => ({ id: link.model.id, role: "primary", state: "ready", operations: OPERATIONS,
|
|
46
|
+
bytes: link.model.bytes, pinned: true, leases, lastUsedAt });
|
|
47
|
+
return {
|
|
48
|
+
get policy() {
|
|
49
|
+
const link = options.link();
|
|
50
|
+
return { budgetBytes: link?.model.bytes ?? 0, pinned: link ? [...new Set([link.model.id, ...(link.companions?.policy.pinned ?? [])])] : [], idleUnloadSec: 0 };
|
|
51
|
+
},
|
|
52
|
+
async acquire(id: ModelId, acquire: AcquireOptions = {}): Promise<ModelLease> {
|
|
53
|
+
acquire.signal?.throwIfAborted();
|
|
54
|
+
const link = attached();
|
|
55
|
+
if (id !== link.model.id && link.companions) return link.companions.acquire(id, acquire);
|
|
56
|
+
if (id !== link.model.id) throw new ModelHostFailure("does-not-fit", `model ${id} is not the served model (${link.model.id})`);
|
|
57
|
+
const missing = (acquire.need ?? []).filter(operation => !OPERATIONS.includes(operation));
|
|
58
|
+
if (missing.length) throw new ModelHostFailure("does-not-fit", `model ${id} does not declare ${missing.join(", ")}`);
|
|
59
|
+
// The host's own lease pins the model for as long as this one is held (it may load it again if it was evicted since).
|
|
60
|
+
const held = await link.hold?.(id, acquire.signal);
|
|
61
|
+
leases++; lastUsedAt = Date.now();
|
|
62
|
+
let released = false;
|
|
63
|
+
const operations: Partial<ModelOperations> = { generate: request => {
|
|
64
|
+
const url = new URL(request.url);
|
|
65
|
+
return options.fetch(new Request(`http://127.0.0.1:${link.port}${url.pathname}${url.search}`, request), link);
|
|
66
|
+
}, ...(link.adapters ? { adapters: link.adapters } : {}) };
|
|
67
|
+
return { model: resident(link), loadMs: 0, operations,
|
|
68
|
+
release() { if (!released) { released = true; leases--; lastUsedAt = Date.now(); held?.release(); } } };
|
|
69
|
+
},
|
|
70
|
+
async defaultFor(operation) {
|
|
71
|
+
const link = options.link();
|
|
72
|
+
return link && OPERATIONS.includes(operation) ? link.model.id : link?.companions?.defaultFor(operation);
|
|
73
|
+
},
|
|
74
|
+
async plan(id) {
|
|
75
|
+
const link = options.link();
|
|
76
|
+
if (link && id !== link.model.id && link.companions) return link.companions.plan(id);
|
|
77
|
+
return { fits: id === link?.model.id, requiredBytes: 0, freeBytes: 0, evict: [] };
|
|
78
|
+
},
|
|
79
|
+
async serve(id, serveOptions = {}) {
|
|
80
|
+
const link = attached();
|
|
81
|
+
if (!link.serve) throw new ModelHostFailure("not-switchable", "this host serves one model; switching needs a restart");
|
|
82
|
+
await link.serve(id, serveOptions.signal ?? new AbortController().signal);
|
|
83
|
+
},
|
|
84
|
+
async unload(id, unload) {
|
|
85
|
+
const link = attached();
|
|
86
|
+
if (id !== link.model.id && link.companions) return link.companions.unload(id, unload);
|
|
87
|
+
throw new ModelHostFailure("in-use", "the serving host releases its model when it closes");
|
|
88
|
+
},
|
|
89
|
+
pin(id) { const link = options.link(); if (id !== link?.model.id) link?.companions?.pin(id); },
|
|
90
|
+
unpin(id) { const link = options.link(); if (id !== link?.model.id) link?.companions?.unpin(id); },
|
|
91
|
+
resident() {
|
|
92
|
+
const link = options.link();
|
|
93
|
+
if (!link) return [];
|
|
94
|
+
return [...new Map([...(link.resident?.() ?? [resident(link)]), ...(link.companions?.resident() ?? [])].map(model => [model.id, model])).values()];
|
|
95
|
+
},
|
|
96
|
+
stats(id): ModelStats {
|
|
97
|
+
const link = options.link();
|
|
98
|
+
if (link && id !== link.model.id && link.companions) return link.companions.stats(id);
|
|
99
|
+
return { resident: id === link?.model.id, loads: 1, unloads: 0, lastLoadMs: 0, idleUnloadSec: null };
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
}
|