Skip to content

feat(engine): one runner path via Runner.adopt; add Qwen 3.8 Flash-Next - #836

Closed
davidtai wants to merge 5 commits into
masterfrom
feat/qwen38-flash-next
Closed

davidtai wants to merge 5 commits into
masterfrom
feat/qwen38-flash-next

Conversation

@davidtai

@davidtai davidtai commented Sep 5, 2026 •

Copy link
Copy Markdown
Collaborator

Darkbloom consumes the runner package MLXRunners in the mlx-swift-lm fork
(Darkbloom runner contract §3, §5, §6.2 rule 4, §9, §12c), and gains the Qwen
3.8 Flash-Next (qwen4_exp, qwen4_exp_text) wiring.

ONE construction path, every slot, every family:

RunnerRegistry.resolve(modelType:)
  → Runner.adopt(model: <the container's loaded module>, tokenizer:, configuration:, directory:, options:)
  → runner.makeEngine(EngineBuild(<the slot's policy>))

Runner.adopt is what makes that possible without a second copy of the
weights: the slot lifecycle owns a resident ModelContainer, and adopt
derives the serving module, layer kinds, decoders and head provenance from
the module already in memory plus config.json. Reading a 113 GB checkpoint
the process is already holding is not a slow path, it is an OOM.

Dev pin

libs/mlx-swift-lm moves from c4089870 to 394ffdbb — the tip of
feat/qwen38-flash-next-runner, which is fork PR #140, the single
consolidated runner PR. A DEV PIN, not a fork main commit; it moves to
main after #140 merges. (#140 collapses the earlier per-piece fork PRs,
which are closed; this PR references #140 only.)

What the pin carries: the MLXRunners package with Runner.adopt /
loadDrafter / preloadedDrafter, adoption of the MLXVLM.Gemma4 and
MLXVLM.Qwen35 wrappers with the Qwen text extraction and its forward parity
gate now beside the runner, EngineBuild.pagedPool verified against the
constructed pool, fail-closed embedded-head provenance, the Qwen 3.8
Flash-Next runner, the n-gram LRU reader, the loader's tensor-name exclusion
seam, and the per-request timing stamps.

Found while pinning, and worth keeping in the record: Darkbloom's previous
pin c4089870 was not on fork main — it was the tip of an unmerged
request-timing branch that EngineV2Bridge+Profile.swift depends on, so the
first dev pins offered did not compile here at all. #140 carries that work
too.

What moved out of Darkbloom

Was in Darkbloom Now
Hand-kept advertised model_type list RunnerRegistry.contains(modelType:), exactly
Three family switches (layer kinds / capabilities / newCacheV2, adoptionBoundTokens, cbv2LayerKinds) Read off the runner, which read them off the module it adopted
KV backend + per-layer cache construction, engine assembly runner.makeEngine(EngineBuild)
Family-typed assistant loading (Qwen35InlineMTPAssistant, Gemma4AssistantDraftModel, …) Runner.loadDrafter; a resident drafter crosses back as RunnerLoadOptions.preloadedDrafter, so a rebuild binds rather than re-reads
The Gemma optimization snapshot inside the slot factory GemmaOptimizationReport.forServingModel, in a file its name announces
EngineV2ModelAdaptation.swift (the previous commit's consolidation) deleted

What stayed as policy (and crosses on EngineBuild)

KV backend selection and slot vetoes, the fleet kill switch, the crash-loop
guard, the paged physical-capacity plan, the degrade-or-refuse ladder, the KV
byte capacity after re-slicing and the physical clamp,
productionSchedulerConfig, the loop config, the SSD prefix-cache
construction gate, the MTP config, the environment. prepareProductionBackend
is now a DECISION (no backend, no caches) and assembleProductionBuild is one
call into the runner. ProductionBuild and the engine_v2_refusal path keep
their shape.

Refusal mapping: RunnerError.invalidCheckpoint / .unexpectedModel and
RunnerRegistry.RegistryError.unknownModelType → unsupported_model;
kvBackendRefused(requested: "paged") → paged_backend_unavailable;
everything else → engine_init_failed; one added case,
runner_resource_missing, for RunnerError.resourceMissing — an
operator-fixable staging mistake that must not hide in the catch-all.

Qwen 3.8 Flash-Next

  • qwen4_exp / qwen4_exp_text are advertised by the registry.
  • The n-gram row source is injected in-process through
    RunnerLoadOptions.resources, under the name the runner declares
    (Qwen4ExpRunner.ngramRowSourceResource = qwen4exp.ngramRowSource), as
    the DIRECTORY of the provider's model directory. A single file is
    refused by the reader, by name.
  • Capabilities come from the manifest; the tests assert the manifest rather
    than a copy of it. cbv2AuxiliaryStateLayerIndices are never validated
    against the layer count anywhere in Darkbloom.
  • MTP is decoder SELECTION: EngineV2Factory.runnerDecoder picks mtp only
    when runner.loadedDecoders reports it and refuses otherwise — never a
    silent downgrade, because mtp_active must not claim a head that is not
    running.
  • No real load was attempted. A 125B load through the fork's shared
    loader materializes ~29.8 GB of n-gram shard tensors before the model drops
    them; the exclusion seam lands on the fork and nothing here works around it.
  • Template fixes: no Qwen38 variant. Qwen35TemplateFix.applies already
    matches the qwen3.8 / qwen3_8 model-id forms, and no difference in the
    Qwen 3.8 chat template could be cited without the checkpoint (none is on
    this machine, and none may be downloaded).

Loading a subset of weights (WeightNameFiltering)

Darkbloom has no loader of its own for these families. The call path:
ProviderLoop.ensureModelLoaded / StandaloneServer →
ModelContainerLoading.loadContainer(from:) →
VLMModelFactory.shared.loadContainer or LLMModelFactory.shared.loadContainer
(both in libs/mlx-swift-lm/Libraries/MLXLMCommon) → the fork's shared
Load.swift, which consults the model's tensor-name predicate before
loadArrays. Qwen4ExpModel excludes .ngram_embedding.shard_, so the
n-gram shards are never materialized as parameters and stay on disk for the
row-source reader. The provider passes the checkpoint directory and nothing
else; every family gets the fork's filtering for free.

What the consolidated fork PR closed

The earlier revision of this PR reported two fork gaps and worked around
them: Gemma4TextRunner and Qwen35Runner accepted the LLM-side module but
not the MLXVLM.Gemma4 / MLXVLM.Qwen35 wrapper the provider actually
loads. #140 closes both. Consequently:

  • EngineV2VLMTextExtraction.swift is deleted — the re-key, the
    quantization structure and the load-time forward parity gate are the
    fork's MLXRunners/QwenVLMTextExtraction, applied by the runner while it
    adopts.
  • adoptRunner is a single call: the wrapper-owned-then-provider-built
    retry is gone.
  • The benchmark seam and slot sizing ask the runner for the serving module
    and its layer kinds instead of switching on a family.

Behaviour changes worth reviewing

  1. The fp32 control arm is restored. EngineBuild.pagedPool carries the
    page dtype from DARKBLOOM_CBV2_PAGED_KV_DTYPE, the .atFirstAdmission
    slab commitment, the capacity PagedKVPhysicalCapacityPolicy allowed, the
    device's buffer ceiling and the nominal context; the runner builds the
    pool from exactly that and compares the CONSTRUCTED pool against the plan,
    refusing pagedPoolDTypeUnsupported by name when they differ (classified
    paged_backend_unavailable). The interim refusal this PR carried at the
    previous revision is gone. EngineV2PagedPoolDTypeEnvTests pins the plan
    crossing on EngineBuild, the parse, and the mismatch refusal.
  2. Slot sizing needs the checkpoint path. SlotSizingSnapshot.build
    reads the runner's layer kinds now (adoption is tensor-free and its
    result is cached per wrapper, so the slot build reuses it); without a
    modelPath it falls back to the config-parse rate as before. Production
    always passes one.
  3. Capabilities come from the runner MANIFEST, not per-instance
    cbv2Capabilities. Same answers for every registered family on the two
    fields the provider reads (supportsPagedKV veto, supportsPrefixReuse
    cache gate).
  4. fp32 full-attention rows are derived from the model's own layer kinds
    (layerKinds.contains(\.hasSinks)) instead of a module-class test — same
    answer for every registered runner, and a per-model answer for a family
    the provider has never seen.
  5. The dense solo-prefill stripe is keyed on the checkpoint's declared
    model_type (qwen3_5, qwen3_5_text) instead of a module class.
  6. Advertised set widens by qwen3_5_text, qwen3_vl, qwen4_exp,
    qwen4_exp_text.
  7. makeProductionEngine / makeProductionBuild take modelDirectory: —
    the runner boundary needs the checkpoint identity. Six benchmark call
    sites updated.

Residue grep

$ grep -rn -E "Gemma4TextModel|GPTOSSModel|Qwen35Model|Qwen35TextModel|Qwen3VL|Qwen4ExpModel" \
    provider-swift/Sources/ProviderCore/Inference/
   9 EngineV2VisionPrefill.swift
   2 EngineV2VisionTowerRun.swift
   1 GemmaOptimizationReport.swift
   1 VisionTowerBudget.swift

Empty across the whole engine path — EngineV2Factory+Production.swift,
EngineV2SlotFactory.swift, EngineV2SlotFactory+MTP.swift,
EngineV2MTPAssistant.swift, EngineV2RunnerBuild.swift,
EngineV2Factory+Benchmark.swift, SlotSizingSnapshot.swift,
EngineV2SupportedModels.swift — and EngineV2VLMTextExtraction.swift is
gone.

What remains, and why it is not wiring:

  • The vision path (EngineV2VisionPrefill, EngineV2VisionTowerRun,
    VisionTowerBudget): image/video prefill — processors, grids, per-image
    tower runs and the buffer-size prediction that keeps MLX from being handed
    an impossible allocation. The Runner protocol has no vision surface at
    all (manifest.multimodal is a declaration, not an API), so there is
    nothing to hand this to yet.
  • GemmaOptimizationReport: one load-time snapshot of Gemma 4's kernel
    routing controls, emitted as telemetry. Not construction, and named for
    the family it reports on.

Docs

Verification

provider-swift, Xcode 26.4 toolchain (DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer;
the Command Line Tools toolchain has no XCTest/Testing module). Free
space checked before each build; 9–10 GiB throughout, never under the 4 GiB
abort line.

$ df -h /            → 14Gi avail
$ swift build -c debug
Build complete! (16.92s)
exit=0

$ swift test --filter "RunnerBoundary|EngineV2Runner|Qwen38Runner|SupportedSet|MTPSupportedModels|PrefixCacheWiring|SlotSizingDrift|PagedPoolDType|QwenVLMTarget|ProviderMTPFactory"
━ Test run with 72 tests in 11 suites passed after 0.105 seconds with 1 known issue.
exit=0

$ make docs-check
docs-check: 126 file(s) OK

The one known issue is by construction: the end-to-end fp32 test asks
PagedKVPhysicalCapacityPolicy for a pool, and this box has no live KV
headroom to plan one, so it records the policy's refusal instead of a false
pass. The plan-to-EngineBuild wiring it exists to prove is covered
hermetically by poolPlanCrossesOnEngineBuild.

New tests in EngineV2RunnerBoundaryTests: the gate equals the registry
manifest-for-manifest; the adopted MODULE and the load options (including the
n-gram resource) reach the runner; a table-driven pass over
RunnerRegistry.manifests() proving every registered model_type prepares
and builds through the same two functions; a missing resource refusing as
runner_resource_missing; decoder selection refusing rather than
downgrading.

Failures on this box, all pre-existing or environmental

  • EngineV2LivenessRecoveryTests ×3 and MTPResliceFallbackTests ×3
    (slotBridgeForTesting → nil): reproduced identically with every source
    and test change of this PR stashed.
  • EngineV2ProductionWiringTests and the paged half of
    EngineV2KVBackendGateTests: this laptop has 24 GiB with ~1.4 GiB of it in
    Chrome, and both suites measure LIVE memory —
    GlobalKVCacheBudget is bounded by SystemMemory.availableBytes()
    (token_budget_exhausted: … the shared KV budget has no headroom) and
    PagedKVPhysicalCapacityPolicy by
    KVHeadroomProbe.measuredLiveKVHeadroomBytes (safe pool 0 B is below the 1048576 B serviceability floor). Each passes when run alone.

CI

Two commits. The first removes swift package edit --path ../mlx-swift mlx-swift from both nested-build steps: at this pin the fork's manifest
path-depends on the sibling checkout when libs/mlx-swift/Package.swift
exists, and editing a path dependency is refused outright —

$ swift package edit --path ../mlx-swift mlx-swift
error: 'mlx-swift': local dependency 'mlx-swift' can't be edited

The second fixes what still failed after that: a .build restored from the
SwiftPM cache records mlx-swift as a source-control dependency from runs
under the old manifest, which SwiftPM cannot reconcile with the fileSystem
dependency now declared (exhausted attempts to resolve the dependencies graph). Both steps now drop the recorded state and that dependency's
checkout, keep compiled artifacts, and swift package resolve before
building; the SwiftPM cache key gains -pathdep.

$ swift package unedit --force mlx-swift || true
$ rm -f .build/workspace-state.json
$ rm -rf .build/checkouts/mlx-swift .build/repositories/mlx-swift-*
$ swift package resolve && swift build --build-tests
Build complete! (175.94s)

Unrelated red checks: Threat Model Review fails with a 401 invalid
ANTHROPIC_API_KEY on every branch today (repo secret), and the three Vercel
deployments fail on team-role permissions; neither is caused by this PR.

Before / after

flowchart LR
  subgraph Before
    A1[config.json model_type] --> B1[EngineV2SupportedModels<br/>hand-kept list]
    B1 --> C1[slot factory]
    C1 --> D1["family switch: Gemma4TextModel /<br/>GPTOSSModel / Qwen35Model / Qwen3VL"]
    D1 --> E1[provider builds backend + caches]
    E1 --> F1[EngineV2]
    C1 --> G1["family switch: assistant loader"]
  end
  subgraph After
    A2[config.json model_type] --> B2["RunnerRegistry.contains / .resolve"]
    B2 --> C2[slot factory<br/>POLICY unchanged]
    C2 --> H2["Runner.adopt(resident module)"]
    H2 --> I2["Runner.loadDrafter → preloadedDrafter"]
    C2 --> D2["EngineBuild(kvBackend, capacity,<br/>schedulerConfig, loopConfig,<br/>prefixCache, decoder, mtpConfig, env)"]
    I2 --> D2
    D2 --> E2["runner.makeEngine — fork builds backend + caches"]
    E2 --> F2[CBv2Engine]
  end
Loading

🤖 Generated with Claude Code

Refactor Pass

A dedicated refactor subagent reviewed the diff against the AGENTS.md structure, clean-code and refactor rules. Outcome: no change. The Flash-Next half is superseded.

Recommendation: close this PR. If Runner.adopt is still wanted, cut a new PR from current master, together with the matching mlx-swift-lm#140 work at a compatible pin.

Darkbloom becomes a consumer of the runner package `MLXRunners` in the
mlx-swift-lm fork (Darkbloom runner contract §3, §5, §6.2 rule 4, §9, §12c).

- DEV PIN: libs/mlx-swift-lm moves to 92be949 on the fork branch
  feat/qwen4exp-ngram-table. This is not a fork `main` commit; it also carries
  feat/cbv2-request-timing, which the previous pin (c4089870) held and fork
  main does not. It is re-pinned to main once fork PRs #131, #132, #133, #134,
  #135 and #136 merge.
- The advertise gate is `RunnerRegistry.contains(modelType:)`. The hand-kept
  `model_type` list is deleted, so a family is advertised if and only if a
  runner's manifest claims it. `qwen4_exp` / `qwen4_exp_text` arrive with the
  registry, as do `qwen3_vl` and `qwen3_5_text`, which the old list omitted.
- `EngineV2RunnerBuild.swift` is the runner boundary on the provider side:
  registry resolution, `Runner.load` with the load-time resources, decoder
  selection from `runner.loadedDecoders`, and `runner.makeEngine(EngineBuild)`.
  Every piece of POLICY still belongs to the provider and crosses on
  `EngineBuild`: the resolved KV backend, the byte capacity, the scheduler and
  loop configs, the SSD prefix cache, the decoder, the MTP config, and the
  environment. The `ProductionBuild` result shape and the `engine_v2_refusal`
  path are unchanged; runner refusals map onto the existing reasons, plus one
  new `runner_resource_missing` for `RunnerError.resourceMissing`.
- Qwen 3.8 Flash-Next: the n-gram row source is injected in-process under the
  name its runner declares, as the model DIRECTORY; the inline `mtp.*` head is
  added beside Qwen 3.5's, and on the runner path it is decoder selection that
  refuses rather than downgrades.
- The family switches leave `EngineV2Factory+Production.swift` and
  `EngineV2SlotFactory.swift`. They are consolidated into one seam,
  `EngineV2ModelAdaptation.swift`, for the families that still load through
  `ModelContainerLoading`: routing the serving slot through `Runner.load`
  today would load the weights twice. That file is deleted, not extended,
  when the slot lifecycle moves behind the registry.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@vercel

vercel Bot commented Sep 5, 2026

Copy link
Copy Markdown

Deployment failed for project d-inference with the following error:

You don't have permission to create a Preview Deployment for this Vercel project: d-inference.

View Documentation: https://vercel.com/docs/accounts/team-members-and-roles

Both "Build nested mlx-swift-lm tests" steps ran `swift package edit --path
../mlx-swift mlx-swift`, the workaround for the fork's former REMOTE
`mlx-swift` dependency. At the pin this PR sets, the fork's manifest
path-depends on the sibling `../mlx-swift` checkout whenever
`libs/mlx-swift/Package.swift` exists, and editing a path dependency makes
resolution fail: `exhausted attempts to resolve the dependencies graph …
'mlx-swift' at …/libs/mlx-swift`.

Drop the edit; keep `swift package unedit --force`, which clears an edit
recorded in a restored SwiftPM cache.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@vercel

vercel Bot commented Sep 5, 2026

Copy link
Copy Markdown

Deployment failed for project d-inference-console-ui-dev with the following error:

You don't have permission to create a Preview Deployment for this Vercel project: d-inference-console-ui-dev.

View Documentation: https://vercel.com/docs/accounts/team-members-and-roles

@vercel

vercel Bot commented Sep 5, 2026

Copy link
Copy Markdown

Deployment failed for project d-inference-landing with the following error:

You don't have permission to create a Preview Deployment for this Vercel project: d-inference-landing.

View Documentation: https://vercel.com/docs/accounts/team-members-and-roles

davidtai and others added 2 commits September 5, 2026 13:06
The load was the problem, not the engine. `Runner.adopt` takes over a module
the provider already has resident, so the runner boundary costs no second
copy of the weights — and with that gone there is no reason for the provider
to keep a construction path of its own.

Every slot, every family, is now built the same way:

    RunnerRegistry.resolve(modelType:)
      -> Runner.adopt(model: <the container's loaded module>, …)
      -> runner.makeEngine(EngineBuild(<the slot's policy>))

- `EngineV2ModelAdaptation` is DELETED. Layer kinds, capabilities, per-layer
  caches, the serving module and the drafter all come from the runner, which
  reads them off the module it adopted.
- The drafter is the family's own `Runner.loadDrafter`; the provider keeps
  the fail-open ladder, the slot-owned lifetime handle and the verification
  policy around it. A drafter the slot already holds crosses back in as
  `RunnerLoadOptions.preloadedDrafter`, so a rebuild binds rather than reads.
- `qwen4exp.ngramRowSource` is injected from the provider's model directory,
  DIRECTORY shape, under the name the runner declares.
- The advertise gate is `RunnerRegistry.contains(modelType:)` exactly:
  `qwen3_5_text`, `qwen4_exp` and `qwen4_exp_text` are advertised.
- Policy is untouched and crosses on `EngineBuild`: backend selection and
  vetoes, kill switch, crash-loop guard, the paged physical-capacity plan,
  the degrade-or-refuse ladder, KV capacity, scheduler and loop config, the
  SSD prefix cache, the MTP config, the environment.
- fp32 paged pages now REFUSE instead of serving fp16 under an fp32 label:
  `EngineBuild` carries no page dtype, so the knob is unreachable until the
  fork adds one. Named `paged_dtype_unsupported`.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The nested build still failed after the edit line came out: a `.build`
restored from the SwiftPM cache carries a `workspace-state.json` written
when `mlx-swift` was a SOURCE-CONTROL dependency (often an edited one), and
SwiftPM cannot reconcile that recorded kind with the fileSystem dependency
the fork's manifest now declares. It gives up with "exhausted attempts to
resolve the dependencies graph … 'mlx-swift' at …/libs/mlx-swift", which is
why a clean local `.build` passed and CI did not.

Both nested-build steps now drop the recorded state and that one
dependency's checkout before resolving. Compiled artifacts are kept, so a
warm run stays warm. The SwiftPM cache key gains a `-pathdep` suffix so the
next warm run starts from a `.build` built under the current manifest
rather than repairing an old one every time.

Verified at the pinned fork commit: `swift package edit --path ../mlx-swift
mlx-swift` is refused outright ("local dependency 'mlx-swift' can't be
edited"), and the replacement sequence (unedit, drop state + checkout,
resolve, build --build-tests) completes.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Re-pins libs/mlx-swift-lm to the one consolidated fork PR (#140,
`feat/qwen38-flash-next-runner` at 394ffdbb) and takes the two things it
unblocks.

Runners adopt multimodal wrappers now, so the provider stops resolving
towers:

- `EngineV2VLMTextExtraction.swift` is DELETED. The Qwen re-key, the
  quantization structure and the load-time forward parity gate live beside
  the family's runner as `MLXRunners/QwenVLMTextExtraction`, and the runner
  applies them while adopting the wrapper.
- `adoptRunner` is one call again: no wrapper-owned-then-provider-built
  retry, because a runner takes its own checkpoint's module whatever shape
  it loaded in.
- The benchmark seam asks the runner for the serving module instead of
  switching on a family, and slot sizing reads the runner's layer kinds
  rather than a switch of its own. `SlotSizingSnapshot.build` needs the
  checkpoint path for that, which production always passes.

`EngineBuild.pagedPool` carries the provider's paged policy intact:

- page dtype from `DARKBLOOM_CBV2_PAGED_KV_DTYPE`, slabs at first admission,
  the capacity `PagedKVPhysicalCapacityPolicy` allowed, the device's own
  buffer ceiling, and the context the groups size against;
- the runner builds the pool from that and compares the CONSTRUCTED pool
  against the plan, refusing `pagedPoolDTypeUnsupported` by name if they
  differ. The fp32 control arm the backend-parity harness needs works
  again, and the refusal I added in the previous commit is gone with the
  reason for it.

The residue grep over ProviderCore/Inference is down to the vision path
(`EngineV2VisionPrefill`, `EngineV2VisionTowerRun`, `VisionTowerBudget`) and
`GemmaOptimizationReport` — neither is a runner-boundary concern; the runner
protocol has no vision surface and the report is a kernel-routing diagnostic.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@davidtai

davidtai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

Closing: master landed native Flash-Next through #1030 and #1115. The Runner.adopt half targets a file layout master no longer has. The evidence is in the Refactor Pass section of this PR body.

@davidtai davidtai closed this Oct 5, 2026
@davidtai
davidtai deleted the feat/qwen38-flash-next branch October 5, 2026 00:42

This branch had an error being deployed

1 failed deployment
benchmarks — f2b83c25 Deployed Sep 5, 2026 by davidtai via E2E Benchmarks #749
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant