Skip to content

feat: Qwen 3.8 Flash-Next runner stack (CBv2 runners, bench-worker, model port, n-gram LRU) - #140

Closed
davidtai wants to merge 86 commits into
mainfrom
feat/qwen38-flash-next-runner
Closed

davidtai wants to merge 86 commits into
mainfrom
feat/qwen38-flash-next-runner

Conversation

@davidtai

@davidtai davidtai commented Sep 5, 2026 •

Copy link
Copy Markdown

What this PR is

This is the single landing of the Qwen 3.8 Flash-Next runner program on the fork. It replaces the stack of branch PRs below. Each of those PRs is contained in this one, and none of them needs to land on its own.

Layer map

Engine seams (MLXLMCommon / MLXLM). The request timing box, which is Darkbloom's production pin c408987 landing on main. The per-round MTP audit journal. The pre-load weight-name filter that runs before tensors are materialized. The keepMask seam on the layer cache.

Runner package (Libraries/MLXRunners). The Runner protocol and its one construction path: load is defined in terms of adopt, so an in-process caller and a spawned worker build the same runner. The manifest, the registry, the teacher-forced stepper, the four family runners (Qwen 3.5, Qwen 3-VL, Gemma 4 text, GPT-OSS), the VLM wrapper adoption that pulls the text tower out of a multimodal module, and PagedPoolPlan.

Executable (Executables/bench-worker). The worker process, its argument parsing, and its hello.

Qwen 3.8 Flash-Next. The model files, Qwen4ExpRunner, and the n-gram reader as an LRU.

Verification

Test line obtained on each branch tip, using the Xcode toolchain:

Tip Branch Result
31682f1 feat/qwen4exp-runner 77 tests in 12 suites passed
0eda8ed feat/qwen4exp-ngram-table 78 tests in 12 suites passed
394ffdb feat/qwen4exp-ngram-lru (this head) 78 tests in 12 suites passed

The 12 suites include the two checks that pin the worker's outside edges:

  • The shared wire fixture. engine-wire-v1-adapter.ndjson is replayed byte for byte. The same bytes are pinned on the benchd side, so both repos digest one fixture.
  • The argv ordering check. The bench-worker launch arguments are asserted in order, so the spawned command line cannot drift from what the runner declares.

Suites that need the full AOT metallib, and were NOT run here. These abort at once on a machine whose default.metallib is the partial build, because they build a real MLX tower and touch Metal:

  • Qwen4ExpAdoptTests and Qwen4ExpNGramResourceTests (MLXRunnersTests)
  • Qwen4ExpNGramTableTests (MLXLMTests)
  • BenchCBv2Tests and the CBv2MTP* suites

They were skipped on every tip above. No run in this pass covered them. They need a machine with the full AOT metallib, which is the CI item in the open list below.

Dependencies

Known open items

  • Resident bench-worker mode. The worker still loads per dispatch. The resident mode is not in this PR.
  • The residency probe and the warm pass need a box measurement on the real table. The LRU hot-row budget and the prewarm order are reasoned, not measured. They need a run against the real n-gram table on a box.
  • The metallib CI step needs an owner. Until a CI step builds the full AOT metallib, the suites listed above cannot run anywhere, and the runner's model-facing behaviour stays unverified by tests.

🤖 Generated with Claude Code

Dependencies

This PR: Qwen 3.8 Flash-Next runner stack: request-timing pin to main, MTP audit journal, weight filter, keepMask seam, MLXRunners scaffold + bench-worker, Qwen4ExpRunner, n-gram reader as LRU. Supersedes #130-#137.

Depends on: mlxfast-bench-dev #268, mlxfast-bench-dev #269.

Needed by: mlxfast-qwen38-125b-a6b-engine-dev #43, d-inference #836.

--verbose load summary

A box hit the step-0 parity failure and the worker's stderr was empty on every run, so nothing was triageable. --verbose (or BENCH_WORKER_VERBOSE=1), on runtime-worker and resident, writes a load summary to stderr, before the hello, one key=value per line prefixed bench-worker:. It states what the load DECIDED, not that it succeeded, and it is emitted before the first verb so it survives a failure on that verb.

The generic half comes from the runner boundary: runner id and manifest digest, weights dir, model_type, attending layers and their model indices, decoders loaded, mtp head bound, head provenance, keepMask requirement, kv backends, eos ids, and the argmax tie-break rule by name (two implementations that disagree on a tie disagree wherever a parity run diverges).

The Qwen4Exp half leads with the resolved rms_norm_weight_offset and its source — top_level, text_config, or family_default — followed by the validator's own statistic over the loaded tensors: tensors read, disagreements, implied offset, and a sample tensor's negative fraction and mean. That pair is exactly what would have named today's defect on the first run; the value alone does not say whether the checkpoint spoke. Then the architecture the runner reads, the synthetic aux-state indices, tensor and quantized-projection counts, resources accepted, and the stage timing.

stdout is untouched. The fixture replay is asserted byte-identical with the summary enabled, and no summary line appears in the transcript — stdout is the wire.

Residency is not a backend

The conformance kit compares hello.backend to the manifest's backend and refused the box run: backend_matches: hello backend Some("mlx-resident") is not the manifest backend "mlx". Correctly so — backend names the COMPUTE backend, while residency is a topology fact about where the weights live. The attaching worker no longer rewrites it; residency rides only in the resident {pid, load_epoch} block, which benchd admits and seals. The ds4 precedent labelled the backend because it had no such block; this one does.

The weights-path verification and the gating are unchanged, and the relayed hello is now byte-identical to the in-process one when the identity block is gated off — the replay test asserts that directly instead of substituting a token, which is a stronger check than it replaced.

Step-0 parity: the checkpoint bakes the norm offset

Root cause of the box's step-0 teacher-forced parity failure, from work/qwen4exp-step0-parity-differential.md. The fork carried rmsNormWeightOffset with a ?? 1 fallback and nothing ever set it, so the tower computed y * (1 + w) on a checkpoint whose non-gated norm tensors already store 1 + w. That scales every non-gated norm in the tower by about one unit: argmax 198 (a newline) at 12.71 with a flat, low top-8, where the previous engine gives 6184 at 22.58 — while every shape, tensor count and digest still checked out. Confirmed on the box: with the offset at 0 the step-0 argmax is 6184 and the top-7 sits within ~0.5 logits of the old engine (margin 6.7 vs 7.4), and the bf16 conversion is proven irrelevant.

The configuration decides it, because the module's weightOffset is a let fixed at init — by the time a container or a runner holds the module it is far too late. rms_norm_weight_offset is honoured wherever it appears: at the top level of the transformed tree, whose transform flattens text_config away, and inside text_config on the raw HF checkpoint, with nested winning when both name it. Absent from both, this family defaults to 0, citing the previous engine's pinned MLXFastConstants.rmsNormConvention == .offsetBaked (Constants.swift:139-144,176). A separate rmsNormWeightOffsetIsExplicit records whether the checkpoint spoke at all, which is a different fact from the value.

And adopt proves it. Qwen4ExpNormConvention ports the old engine's validateLoadedNormConvention (Qwen4ExpNormConventionBind.swift:60-230) with its thresholds unchanged — the classifier is the SIGN PATTERN, not the mean, because mtp.pre_fc_norm_embedding averages 0.236 while every one of its entries is positive. Qwen4ExpRunner.adopt runs it (so load does too, through adopt) and refuses RunnerError.normConventionMismatch when the loaded tensors contradict the configured offset. It reads only resident tensors, so adopt's no-tensor-read contract still holds; the gated deltanet norm is a different type, carries no evidence either way, and is not read.

No manifest field changed — bench-worker manifest --runner layr/qwen4exp-125b-a6b --digest still prints 474efd9965aef3453e1e8324e99f9711d8e44bb2dceb0366d9c14c7d8e9ecebe, and the printed bytes still hash to it independently.

Configuration-decode tests (all six placements: absent flattened, absent nested, top level, nested, root reaching a silent text_config, nested beating root) run everywhere. The validator tests build MLXArrays and are GPU-gated like the other Qwen4Exp suites.

Resident teardown, and a descriptor double-close

Two defects, one reported from M5 #4 and one it exposed.

SIGTERM trapped instead of tearing down. The signal handler was a closure written in main.swift, whose top-level code is @MainActor-isolated, so dispatch ran a MainActor-isolated @Sendable thunk on the signal source's own thread, Swift concurrency checked the executor, and the process died with EXC_BREAKPOINT — before the socket or pidfile were removed, on a resident holding 113 GB. The handler now only ASKS: requestShutdown() is nonisolated, takes a lock, sets a flag and closes the listener, which is what wakes the blocked accept(). The loop returns and its OWNER performs the teardown and exits 0. Installation moved into BenchWorkerResidentTermination, away from main.swift's isolation. No isolation assertion was relaxed to make the trap go away. Teardown is idempotent, and --pidfile is written at listen and removed at teardown.

close() was not idempotent, and deinit calls it too. A descriptor closed twice is not a harmless mistake: the number returns to the process at once and the kernel reissues it to the next accept, so the second close shuts down an unrelated connection. It surfaced as an intermittent "resident sent no hello" — a phase whose freshly accepted socket had been closed by the PREVIOUS phase's deinit. The descriptor is now surrendered under a lock before the close(2). Five consecutive full runs pass; before the fix one in three failed.

The termination test drives SIGUSR2 rather than SIGTERM: the mechanism is signal-number agnostic, while a real SIGTERM reaches the whole test process and disturbs residents other suites run in parallel. BenchWorkerResidentTermination.signals == [SIGINT, SIGTERM] is asserted separately.

manifest subcommand and usage screens

The box found that nothing could emit a real runner's manifest JSON, so the conformance kit's --manifest had no file to read.

bench-worker manifest (--runner <id> | --weights <dir>) [--digest] prints the CANONICAL manifest bytes — the §6.0 serialization the sha256 is computed over, newline-terminated — and exits 0. That equality is the whole point: a kit that hashes what it reads gets the digest the hello reports, rather than a re-encoding that agrees today and drifts later. --digest prints the hex alone.

It loads no weights. A manifest is static data on the runner TYPE, so --runner reads nothing at all and --weights reads only config.json, whose model_type picks the runner through the registry. Unknown id, unclaimed model_type, both target flags, or neither: refusal on stderr, exit 2.

--help (alone or after a subcommand) prints one screen and exits 0, and wins over the rest of the line — someone asking how to run this should not first have to get the line right. A mistyped subcommand is named as one and answered with the whole usage screen on stderr, exit 2; "unknown argument residnet" tells a caller about one word when what they need is the vocabulary.

$ bench-worker manifest --runner layr/qwen4exp-125b-a6b --digest
474efd9965aef3453e1e8324e99f9711d8e44bb2dceb0366d9c14c7d8e9ecebe
exit=0

$ bench-worker manifest --runner layr/qwen4exp-125b-a6b | shasum -a 256
474efd9965aef3453e1e8324e99f9711d8e44bb2dceb0366d9c14c7d8e9ecebe

$ bench-worker manifest --weights <dir with only config.json + index> --digest
474efd9965aef3453e1e8324e99f9711d8e44bb2dceb0366d9c14c7d8e9ecebe
exit=0

$ bench-worker manifest --runner layr/nope
bench-worker: no runner with id layr/nope
exit=2

$ bench-worker manifest --runner layr/gptoss --weights /nonexistent
bench-worker: manifest takes --runner or --weights, not both
exit=2

$ bench-worker residnet --weights /x
bench-worker: unknown subcommand residnet
<usage screen>
exit=2

$ bench-worker --help; bench-worker manifest --help
exit=0 (both)

The independent shasum is the load-bearing line: the bytes the command prints hash to the pinned vector without any of this repo's own code doing the hashing.

Resident mode — one weight load per window (contract §12f)

benchd starts a worker per PHASE — warmup, timed prefill, timed decode, correctness, per leg, per cohort pair — so a worker that loads at startup reads a 113 GB checkpoint a dozen times for one window. The ranked pipeline has twenty minutes; it does not fit. David's rule (2026-08-30) is one weight load per window, so the weights get an owner.

bench-worker resident --weights <dir> [--runner] [--drafter] [--trusted] [--speculative-protocol v1.1] [--resource ...] --socket <path> is one process for one window: the same argv validation as today (nothing under --weights is read until it passes), then ONE load, then a Unix socket bound after the load, so an attach can never race it. Each phase's bench-worker runtime-worker attaches when BENCH_WORKER_RESIDENT_SOCKET names that socket, and loads nothing. With no socket named, runtime-worker serves in process exactly as before.

A connection is a phase. The allocator is drained on accept, before the client's first byte, so a phase can never inherit the one before it; hello goes out at connection start with a fresh nonce; an error discards that session. Exactly ONE connection is served at a time — a second gets one ok:false line and is closed. That is the deliberate difference from the CUDA track's ds4-resident, which parks a second attach in the listen backlog: a resident serving two attached workers stalls the window, and a queued phase looks like a slow engine rather than a double attach, so the failure is made to name itself. A SEQUENTIAL phase arriving while the previous session's thread is still noticing EOF is not a concurrent attach; the doorman waits out that handover (0.5s, three orders of magnitude over a teardown measured in microseconds) before refusing.

Identity. The attached hello appends a resident object with the resident's pid and load_epoch, so an artifact can SHOW that every phase of a window ran against one load instead of assuming it. backend is left alone — see "Residency is not a backend" above. load_epoch is stamped when the load finished and never moves again; a changed value is a reload that should not have happened. Every other response line is forwarded as untouched bytes — the hello is the only line that makes a claim about where the work ran.

Gating, and what bench-dev must do first. resident rides behind BOTH the --speculative-protocol v1.1 gate (like every other additive hello field) AND an explicit BENCH_WORKER_RESIDENT_HELLO=1, because benchd's envelope is closed (deny_unknown_fields) and a benchd that does not know the field rejects the whole hello line and fails the phase. Before this ships, bench-dev must admit resident on WorkerResponse and add BENCH_WORKER_ to the engine child environment allowlist beside DS4_ so the socket name reaches the spawned worker. Until then the object stays off by default and residency is otherwise fully usable.

Every resident failure is a refusal, one stderr line and exit 2 — unreachable, refusing, or holding a checkpoint other than the one this phase asked for. Never a fall-through to serving in process, which would load 113 GB inside a timed phase and report the result as if it had not. The weights check is why the resident states its own path on the socket hop (resident_weights, stripped before anything reaches benchd).

Verification

swift test --filter MLXRunnersTests (skipping the three suites that build real Qwen4Exp modules and cannot run without a GPU on this box — Qwen4ExpAdoptTests, Qwen4ExpRunnerTests, Qwen4ExpNGramResourceTests and Qwen4ExpNormConventionValidatorTests):

✔ Test run with 124 tests in 17 suites passed after 0.533 seconds.

18 of those are the resident: the shared fixture replayed byte for byte through the attach path with the hello difference asserted exactly, the second concurrent connection refused with its own line, a weights-path mismatch refused, an absent socket refused, an unreadable or refusing hello refused, load_epoch and pid constant across two sequential phases with a fresh nonce each, both identity gates, and the subcommand/flag refusals proved from argv alone.

Built binary:

$ bench-worker resident --weights /nonexistent --socket /tmp/x.sock
bench-worker: runner: checkpoint unusable (cannot read /nonexistent/config.json)
exit=2                      # argv passed, then the checkpoint refused it

$ bench-worker resident --weights /nonexistent
bench-worker: resident requires --socket <path>
exit=2                      # argv, before any checkpoint read

$ bench-worker runtime-worker --weights /nonexistent --socket /tmp/x.sock
bench-worker: --socket is only accepted by resident, not runtime-worker
exit=2

$ BENCH_WORKER_RESIDENT_SOCKET=/nonexistent/s.sock bench-worker runtime-worker --weights /nonexistent
bench-worker: resident at /nonexistent/s.sock is unreachable (cannot reach the resident at /nonexistent/s.sock: No such file or directory)
exit=2                      # names the socket; mentions config.json 0 times

The third binary check — a live resident over the mock runner — is NOT possible from the binary: MockRunner is a test type and RunnerRegistry claims no mock model_type, so the executable can only host a real family, which needs a checkpoint and a GPU. The one-connection rule and the full relayed session are covered in process instead, over a real Unix socket, in BenchWorkerResidentTests.

Merge order in this repository: #140 only (one PR for the whole program).

Program map: see work/darkbloom-runner-contract.md section 16 (Runner Program) in the layr-labs workspace.

Refactor Pass

A dedicated refactor subagent reviewed the diff against the Layr-Labs AGENTS.md structure, clean-code and refactor rules (d-inference #1338). Outcome: no change. The model half is superseded by main.

  • Main has its own native Qwen4, starting with c388c5e (2026-09-13), with later fixes and kernel tests. d-inference pins 1ee8675, which is on main.
  • LLMModelFactory.swift:63-64 on main already registers qwen4_exp and qwen4_exp_text to main's own Qwen4ExpModel. Both Qwen4Exp.swift and Qwen4ExpMTP.swift exist on main with different content. A trial merge gives 11 conflicts, two of them add/add.
  • The MLXRunners and bench-worker layer (39 files) is not on main. It binds to this PR's own Qwen4ExpModel, which clashes with main's type of the same name, and its only consumer, d-inference#836, is superseded.

Recommendation: close this PR. If the generic runner layer is still wanted, port it onto main's Qwen4 types without this PR's model, MTP and n-gram files. The KVCacheSimple/ArraysCache change from public to open could be its own small PR.

Gajesh2007 and others added 30 commits September 3, 2026 12:05
Export `CBv2RequestTiming` on the terminal `CBv2Usage` (numerics only:
nanosecond offsets from the engine enqueue instant plus step-participation,
prefill-chunk, MTP, pause, detok-delay and prefix-cache counters), stamped
on `CBv2ScheduledRequest` from the step's existing clock reads:

- enqueue: one `DispatchTime` read is the origin of every offset
- launch (`executeMixed` / `executeMTPRound`): admission, KV allocation
  and prefill-chunk stamps reuse `wallStartedNanos`; one-token prompts are
  decode-shaped but still counted as the row's prefill chunk
- finalize: ONE new unconditional read (readback-done) serves every
  per-row stamp (first token / prompt computed, batch rows, step latency,
  decode steps), the MTP accept walk, `finishedNanos` for finishes driven
  by that finalize, and the cumulative `stepWallNanosTotal`
- markAdmitted counts re-admissions; ensureKVState counts capacity
  requeues; setPaused accumulates paused time on the injectable clock
- prefix lookup is timed on the submit thread and rides `CBv2PrefixLookup`
  into enqueue; `applyAdoption` is timed once per adoption
- first-token detok delay is measured inside `CBv2OutputStream`'s own lock
  (armed by `reserveEmission`, read by the deferred `emit`) and folded into
  the usage at terminal delivery; the scheduler record is never written
  from the detokenization queue

`CBv2CapacitySnapshot` gains monotonic `stepWallNanosTotal` and
`decodeRowsTotal`, published under the existing gauges lock. `engineStep`
is wrapped in an `OSSignposter` "step" interval guarded by `isEnabled`.

`CBv2Usage.timing` is stored boxed: the Swift 6.3 runtime frees `async let`
result buffers above a size threshold out of order ("freed pointer was not
the last allocation"), reproduced on the unmodified engine by padding a
test result struct; keeping `CBv2Usage` one pointer larger avoids it.

No new locks, evals or per-row clock reads on the step path; hostSyncs
unchanged. Tests: `CBv2RequestTimingTests` (B=1, B=4, chunked/striped
prefill, stop-string path, preemption, backpressure, prefix hit, monotonic
counters, Equatable + numeric-only shape).
… clock read, one timing box per request, exact hasSpans
Sparse-attention families (Qwen 3.8 Flash-Next QSA) need to remove keys
that the causal mask admits. Add an optional per-row boolean keep mask to
CBv2AttendingLayerCache.updateAndAttend.

- Contract: new overload with a refusing default, so every existing
  conformer keeps its behavior and gains a refusal by name. The paged
  backend takes that default.
- Contiguous backend honors it: composed with the causal or window mask in
  absolute coordinates, sliced per query block, exact.
- CBv2LayerCacheProvider.supportsKeepMask (default false), affirmed by
  CBv2LayerCacheBank when every cache claims CBv2KeepMaskCapableCache.
- EngineV2 refuses at construction when a model declares
  CBv2KeepMaskRequiringModel and the provider cannot serve it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Port of the MIT mlx-lm reference (PR 1788, qwen4_exp.py @ c961f839); the
embedded MTP head follows the Apache-2.0 vLLM reference (PR 53896,
mtp.py @ 2a4cd640). 48 layers: 12 full-attention layers with a QSA
indexer, 36 gated-deltanet layers, hyper-connection residual streams, and
one PLE layer whose n-gram rows come from an injected row source.

Legacy LLMModel/KVCache path only; the ContinuousBatchingV2 conformances
follow. Registers qwen4_exp and qwen4_exp_text.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Compact attention layout (one row per full-attention layer, modelLayerIndex
mapped), recurrent-state spec for the gated-deltanet layers, explicit
capabilities, positioned recurrent forwards, prompt-output narrowing and the
recurrent MTP target seam.

Qwen4ExpCBv2LayerCache keeps the QSA indexer key tape as a second per-row
tape and truncates it to the row's own absoluteOffset before every append,
so an engine-driven rollback of the key-value tape moves it in step. The
indexer keep mask reaches attention through the keepMask seam.

The PLE short-convolution state and the n-gram token history ride the
recurrent-state spec under synthetic layer indices past the last real layer
(conv for the convolution state, int32 ssm for the history ids). Runners
read cbv2AuxiliaryStateLayerIndices instead of rebuilding the convention.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The head lives in the target checkpoint under mtp.*, rides the target's
embed_tokens and lm_head, and consumes the PRE-final-mixer multi stream, so
every draft round re-embeds the hc_count * hidden tensor rather than the
collapsed hidden.

Depth 1...3. Serial target verification, batch one, greedy acceptance with
the lowest-token-id argmax tie-break the verifier uses. Rollback trims the
head's own caches, which slices the indexer tape with the key-value tape.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Records the compact layer layout, the QSA keep mask, the indexer tape
rollback rule, the multi stream the MTP head reads, and the auxiliary
recurrent-state index convention. States that a recurrent-state index is
never compared with the layer count: the PLE slots are past the last layer
on purpose.

Also applies swift-format to the files this branch touches.

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

14 tests on a tiny seeded-random fixture; no model is downloaded.

Qwen4ExpCBv2Tests covers the compact layer-kind layout, the recurrent-state
spec, the auxiliary PLE/n-gram index convention (pinned so the runner lane
cannot drift from it), the explicit capability set, and that a row rollback
carries the QSA indexer tape with it.

CBv2KeepMaskSeamTests covers the seam: an all-true mask reproduces the dense
result, a restricted mask equals attention over exactly the gathered columns,
a permissive mask cannot admit future keys, the contiguous and Qwen4Exp caches
claim support while an unclaiming cache disqualifies its provider, the paged
cache claims nothing, and the engine refuses at construction.

Two supporting fixes found by running these:
- The gated-deltanet Metal kernel needs a key head dimension that is a
  multiple of 32; the fixture documents this and uses the smallest legal one.
- The QSA block scores now use an explicit matmul instead of MLX.einsum,
  shared by the legacy and CBv2 indexer paths so they cannot disagree.
  einsum reached a kernel that is absent from some built metallibs.

Also fixes a DocC symbol link that pointed across modules.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
DocC requires that a symbol which documents one parameter documents all of
them. Adds args, isLinear, mtpLayerCount and stepIndex, which clears the
last documentation error this branch introduced.

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

Qwen4ExpForwardParityTests covers the two remaining brief items:

- (b) The CBv2 forward is token-exact against the legacy KVCache forward over
  prefill plus several decode steps, both below the indexer budget (the keep
  mask never fires) and above it (every full-attention layer runs sparse).
  The above-budget case asserts the tape really passed the budget, so it
  cannot silently degrade into a second dense test.
- (c) Greedy generation driven by the embedded MTP head equals serial output
  at depths 1, 2 and 3, with the accept walk the engine's serial-target
  verification performs.

These need the FULL ahead-of-time metallib. A single-token decode through the
MoE shared expert gate is Linear(hidden, 1), which MLX lowers to the
dot_product specialization (matmul.cpp, M == 1 && N == 1). mlx-swift's Cmlx
target does not compile the Metal kernels through SwiftPM, and the partial
library it ships carries neither dot_product nor gemm, so the kernel is
missing and MLX aborts the process. Building the metallib the way the
production recipe does (cmake, MLX_METAL_JIT=OFF) supplies it: 17322 symbols
against 459, dot_product present. CI must build and install that metallib
before running the tests.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The three tests in Qwen4ExpForwardParityTests each drive a single-token
decode, and a decode through the mixture-of-experts shared expert gate is
Linear(hidden, 1). MLX lowers that to its dot_product specialization, which
the metallib the standard xcodebuild build produces does not carry. A missing
Metal kernel aborts the PROCESS, so without this gate the three tests would
take the whole MLXLMTests bundle down on any machine, CI included.

They now skip unless MLXLM_FULL_AOT_METALLIB is set. The skip message names
the requirement, the cmake command that satisfies it, and the CI step that is
still missing. No assertion changed; the tests pass unchanged once a full
ahead-of-time metallib is installed.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The runner boundary from the Darkbloom runner contract: one model family
behind the CBv2 engine, a static digest-stable manifest, and two consumers
(Darkbloom in process, benchd over Engine Protocol v1) that carry no
family-specific construction code of their own.

Libraries/MLXRunners
  Runner.swift          protocol Runner, RunnerManifest (canonicalJSON +
                        sha256Digest in the frozen field order), the
                        declaration vocabulary, RunnerLoadOptions,
                        EngineBuild, and the one shared EngineV2 assembly
                        lifted from d-inference's production factory with
                        the policy left behind for the caller.
  RunnerRegistry.swift  model_type -> runner type, with the four family
                        runners pre-registered and a marked insertion point.
  Stepper.swift         TeacherForcedStepper + the generic one-row
                        CBv2SingleRowStepper over the SAME model forward the
                        engine drives (recurrent families included).
  Gemma4TextRunner / GPTOSSRunner / Qwen35Runner / Qwen3VLRunner
                        one explicit manifest each, engine capabilities
                        spelled out, drafters loaded where the fork has one.
  BenchWorkerWire.swift Engine Protocol v1 wire types, hand-written writer
                        (JSONEncoder cannot render 0.0 or hold key order).
  BenchWorker.swift     the protocol server: hello derived entirely from the
                        manifest and the loaded state, the section 8 verb
                        table, the section 9 fixed contiguous build, and no
                        timing ever emitted.

Executables/bench-worker  a shim over BenchWorkerServer; nothing may depend
on an executable target without hijacking the swift-testing host.

gemma4LayerKinds / gemma4SharedKVSources / gptossLayerKinds move out of the
engine's LayerKindDerivation.swift and into the model files whose
constructors they mirror. The engine directory keeps no family name.

Tests pin the four manifest digests and the cross-repo section 11 vector as
exact canonical bytes, the hello derivation, registry resolution, the wire
round trip, and a byte-for-byte replay of the shared conformance fixture.

Qwen4ExpRunner and the keepMask seam land separately from
feat/qwen4-exp-cbv2.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
bench-dev regenerated the shared conformance fixture (feat/bench-adapter
23bdcf1) so its hello carries the `runner` block; lines 2-29 are unchanged.
The replay test no longer appends that block itself — the hello is compared
like every other line.

The mock runner therefore carries the contract's section 11 manifest
VERBATIM, because the fixture's hello pins that manifest's digest and
`manifest_sha256` must be what this runner's OWN manifest hashes to. A hello
quoting some other manifest's digest is the hand-written hello field section
6.1 forbids. Declaration data only: nothing loads, registers or serves that
family here, and the registry test now registers the teacher-forced mock so
no `qwen4_exp` model_type is ever claimed.

ONE byte-group is substituted, and it is a fixture defect rather than a
difference of opinion: the fixture spells `"backend":"mock"` while pinning
the section 11 digest, and that manifest declares `"backend":"mlx"`. Section
6.1 derives `hello.backend` from `manifest.backend`, so a worker cannot
report "mock" and hash to 474efd99... at the same time — the two bytes are
the same fact told twice. Substituting keeps the assertion exact instead of
loosening it. The fixture wants `"backend":"mlx"`, or a mock-backend
manifest and its own digest.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…l case

benchd checked in the mock adapter's own manifest beside the fixture
(feat/bench-adapter 03203ca): the section 11 declaration with
"backend":"mock" and "runnerID":"layr/mock-adapter", section 6.0 digest
850ef7df26..., and the fixture's hello regenerated to quote it.

MockRunner now DECODES that file rather than declaring a twin in Swift, so
both repos digest the same bytes and the hello's `backend` and
`runner.manifest_sha256` are two readings of ONE declaration. That closes
the last inconsistency: the worker no longer has to report a backend its
manifest does not name.

The replay test therefore compares the hello byte for byte exactly like
lines 2-29 — no substitution, no appended block, no special case anywhere in
the file. A new case asserts the decoded manifest's canonical bytes and its
850ef7df26... digest, that the section 11 constant still digests to
474efd99..., and that the two differ (a decoder that dropped either changed
field would collide them).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Qwen4ExpRunner puts the 125B-A6B family behind the runner contract, with the
section 11 manifest exactly as the contract writes it: contiguous storage only,
serial plus the embedded mtp head at depth 1...3, single-stream free-run and
teacher-forced regimes, recurrent layers, requiresKeepMask. Its canonical bytes
hash to the cross-repo vector 474efd99..., which benchd pins too, so the
scaffold's stand-in declaration in RunnerManifestTests is replaced by the
runner's own manifest.

The runner reads layer kinds, caches and capabilities from the model, reports
the mtp decoder only when the checkpoint carries the head, and builds the engine
and the one-row stepper over one model instance. Paged is refused by the shared
assembly because the manifest declares contiguous alone.

Two seams the scaffold did not have:

  RunnerResources on RunnerLoadOptions. The n-gram table is 29.8 GiB, is never
  model parameters, and the disk-resident implementation lives in the track
  repo, so the caller injects a Qwen4ExpNGramRowSource. The seam is opaque and
  keyed by name, so a track repo can hand a fork runner an implementation the
  fork does not know.

  RunnerError.resourceMissing. A checkpoint with PLE layers and no row source
  cannot run a forward pass, so the load refuses rather than trapping at the
  first token.

Tests: the section 11 digest, the hello derivation for this manifest, both
model types resolving through the registry, and the serial-only hello when the
head is absent, all model-free in MLXRunnersTests; the paged refusal and
stepper-against-engine token agreement over the tiny fixture in MLXLMTests,
where the fixture lives. The agreement test is gated on
MLXLM_FULL_AOT_METALLIB=1 for the same reason Qwen4ExpForwardParityTests is.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…feat/qwen4exp-runner

# Conflicts:
#	Tests/MLXRunnersTests/RunnerManifestTests.swift
Add `CBv2MTPRoundAuditRecord` and `CBv2MTPMetrics.roundAudits`. Every
finalized VERIFY round now leaves one snapshot record built at the
existing finalize host-sync boundary from values already on the host:
the draft ids, the target argmaxes, the accept boundary, the rollback
width, and the row's post-round scheduler accounting. No extra MLX
evaluation and no new host readback.

Retention is bounded at 8192 records with oldest-first eviction. A
consumer that reconciles audits against committed streams refuses when
the count reaches the cap, because a truncated head cannot prove
coverage.

No consumer or seam is wired here.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The gated tests also run under swift test once the complete metallib sits
beside the package test binary, so the note now gives that path as well as the
xcodebuild one, and names the runner test the gate also covers.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The bench-worker free-run audit reads that journal, so this branch builds on
it. No conflicts: #132 touches only the MTP finalize/driver seam and its own
tests.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Contract section 12c. RunnerCheckpoint.provenance(ofEmbeddedHeadAt:) is the
single implementation and its doc comment is the rule: find the mtp.* tensors
through the checkpoint index (or the shard headers when there is no index),
hash the whole bytes of the shards that carry them in index order followed by
the sorted index entries, and report those shards' size and count. A checkpoint
with no mtp.* tensor answers nil, not a digest of the target weights.

Qwen4ExpRunner and Qwen35Runner both call it. Neither hashes the whole
checkpoint any more, which for a 125B target was a second full read of the
weights at load and a digest that said nothing about the head.

The test builds a synthetic checkpoint of two shards and an index that puts the
head in one of them. Rewriting the other shard leaves the digest alone;
rewriting the head shard moves it; renaming a head tensor over identical bytes
moves it too. GPU-free.

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

Wire the free-run audit to `CBv2MTPMetrics.roundAudits` (#132), so a
free_decode_run response states what the engine journaled rather than what
the worker could infer from the tokens it drained.

`FreeRunRoundAudit.assemble` groups the records — one per (row, round), in
finalize order — by row and reads them position-wise: a row's r-th record IS
its r-th round, and a row that stopped early simply has no record past its
last one, which is what makes `active_streams_by_round` non-increasing
without computing it from anything else. From that:

  acceptance_lengths   per-round committed width (rows must agree; a cohort
                       commits ONE common width, and disagreement refuses)
  drafted_total        sum of every record's k
  accepted_total       sum of min(accepted, confirmed) — the `observedAccepted`
                       the engine's own cumulative counter accumulates
  committed_total      the drained count, which the schema requires equal
                       tokens.len(); the journal's own sum EXCEEDING it
                       refuses, while under-counting is legitimate (a
                       target-only decode step commits without a round)
  rounds, natural_accepted_by_stream, active_streams_by_round
                       the v1.2 COHORT trio, emitted only in the cohort form
  depth_clamp_reasons  the controller's skip/fallback counts, windowed

`spec_decoder` and `verify_replay_disagreements` have no journal field at
this pin and stay ABSENT — naming the request's own mode back is not a
report, and absent is not 0.

A journal at its 8192-record cap REFUSES the response by name: a truncated
head cannot prove coverage of the window, mirroring the 125B worker's rule.
The window opens after the seed forward, so the seed's records are never
counted as the timed run's.

Also: bench-worker's runtime-worker gains a repeatable
`--resource <name>=<path>`. Each occurrence becomes an entry in
RunnerLoadOptions.resources. A name may appear once, the path must exist and
be a regular file or a directory, and both refusals fire BEFORE the load —
a bad path found after a multi-minute weight load has wasted the box's time
to report something argv already knew. Values pass through opaque; the
worker never opens them. `RunnerResources` and `RunnerError.resourceMissing`
are declared identically to #133 so that branch rebases cleanly.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The disk-resident n-gram row source moves from the track engine repo into
this fork, beside `Qwen4ExpNGram.swift`, which owns the
`Qwen4ExpNGramRowSource` protocol. The reader is ONE conformer of that
protocol; `Qwen4ExpNGramRowSourceLoader` is the one construction entry
point, so a later computed-function conformer needs no runner change.

Origin:
Layr-Labs/mlxfast-qwen38-125b-a6b-engine-dev@b0b8d28:Sources/MLXFastModel/Qwen4ExpNGramTable.swift

The fork gains no dependency on the track. Every MLXFastCore use is
replaced: `MLXFastError.invalidInput` becomes `Qwen4ExpNGramTableError`,
and `MLXFastCore.Safetensors` becomes a minimal file-private header
reader that returns offsets only. The geometry still comes from
`Qwen4ExpTextConfiguration` through the model's PLE layers.

The resource has ONE shape: the directory of n-gram shard files that the
offline transform writes. A path to a single file is refused by name.

`Qwen4ExpRunner` builds the source from the `ngramRowSource` resource
when it arrives as a URL or a String path, and still accepts an already
built row source from an in-process caller.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Ported from the track's `Qwen4ExpNGramCacheExactnessTests`, over a tiny
synthetic table directory that the test writes. Byte level only, so no
GPU and no MLX runtime: the rows are compared as the raw checkpoint
bytes the cache holds, which is where the invariant lives.

The suite pins the row cost of the pinned checkpoint, the ceiling
resolution order, identical row bytes at three ceilings (off, evicting,
whole table), the eviction counters, the row bytes against the file
read directly, and the refusals by name for a missing shard, a single
file, and a directory with no shard file.

`Qwen4ExpRunner.resolveNGramRowSource` becomes internal so the runner
tests can drive it without a checkpoint.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
davidtai and others added 11 commits September 5, 2026 18:30
On the box the free run and the teacher-forced path disagree after a
1024-token seed and agree on an 8-token seed; every value is deterministic
run to run. The two paths prefill in different SHAPES: the engine loop
chunks the seed at the scheduler's 512 while the stepper prefills in one
forward. The fixture model cannot reproduce the difference, so the box
needs to swap the shapes.

Two environment knobs, off by default and announced on stderr by name when
set: BENCH_WORKER_DIAG_PREFILL_CHUNK sets the free-run engine's prefill
chunk size; BENCH_WORKER_DIAG_STEPPER_CHUNK prefills the teacher-forced row
in chunks of that many tokens. Neither touches a scored configuration
unless an operator sets it, and a set knob is printed so no run can carry
one silently.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
a44f6b9 did not compile (prefillChunkSize must precede maxWaiting); the
suite that reported green ran on the previous binary.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The correctness oracle (teacher-forced stepper) and the goldens it is
checked against prefill the seed in ONE forward. The engine loop's default
chunks a prompt at 512 tokens, and on the 125B a chunked prefill is a
different computation: a box measured every chunk size (128/256/512) moving
the post-seed distribution by 0.1 to 0.9 logits against the single forward
(48 layers of bf16 GDN scan, PLE dilated conv and indexer blocks carried
across boundaries); at 512 the shift landed two tokens within 0.2 and the
free run diverged from the golden at step 1, while a one-chunk prefill
reproduced it through nine tokens. The fixture model shows the same effect
at 5e-5 in float32.

Free runs now build the engine with prefillChunkSize = max(default, seed
length), so the timed window is prefilled in the oracle's shape. The
diagnostic knob BENCH_WORKER_DIAG_PREFILL_CHUNK still overrides, by name.
Chunking stays a serving option outside scoring.

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

On the 125B the free run and the teacher-forced oracle agree for nine
tokens after a one-forward prefill and part at the tenth, on both drivers,
while the old engine — which vendors the same legacy forward and cache code
this fork carries — reproduces the golden past that step. The fixture model
does not show it, so the question goes to the real weights.

`bench-worker diag-parity --weights <dir> --golden <json> [--steps <n>]
[--resource ...]` loads once, then teacher-forces the golden's seed and
expected tokens through the fork's LEGACY path (`model(ids, cache:
makeCache())`, one forward for the seed) and the CBv2 stepper side by side,
printing per step both top-4 rows, whether each matches the golden, the
L-infinity delta between the two logit rows, and finally the first step the
legacy path misses the golden and the first step the two paths' argmax
split. Whichever pair parts first names the layer the defect lives in.
Serves nothing; diagnostic only. `CBv2SingleRowStepper.forwardLogits`
exposes the raw last-position row the top-k was reduced from.

`--golden`/`--steps` are refused on the serving subcommands and required
by this one. MLXRunnersTests 114/114.

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

A recorder attaching to the resident hit "runtime worker failed to clear
the MLX allocator cache at phase start (cache_memory=327680, expected 0)"
on one connection in five. The resident drained on accept, but a drain
only returns buffers whose work has finished: arrays the previous phase
left in flight (its last asyncEval, its teardown) came back to the cache
after the drain, and the next phase's barrier read them. The session now
synchronizes the default stream before draining, at phase start and again
after the connection closes, so the handover window never leaves cached
bytes for the next phase. Not unit-testable without Metal; the box's next
window is the proof.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…he session

9fe772c synchronized in the resident's session, which the mock-runner
resident tests also run: `Stream()` in a process that never touched MLX
aborts (no device stream yet), and the suite died. The settle belongs to
the allocator it protects: `MLXMemoryReporter.drain` now synchronizes the
default stream before clearing the cache, so every drain — the resident's
at both ends of a session, the worker's at phase_diagnostics — reads the
settled state, and the fixture reporter stays a no-op. MLXRunnersTests
114/114.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
… the track's golden shapes

1. The phase-close barrier on a resident still read 384 bytes of cache after
the settled drain (down from 320 KiB). Dropping the last reference to the
free-run engine does not free its arrays at that instant: the loop's task
tears them down on its own thread, and frees landing after the drain sit
in the cache the barrier reads. phase_diagnostics now awaits the engine's
shutdown before releasing the sessions, then drains until the allocator
reads zero (bounded at four passes). The in-process worker takes the same
path, so both spawn shapes report the same invariant.

2. diag-parity decoded the golden window at the top level; the pool
goldens keep decode_seed_tokens / expected_decode_seed_token /
expected_decode_tokens under `benchmark`, and the public gate golden has
only cases[]. The loader now takes any of the three shapes (top level,
`benchmark`, or cases[0].prompt_tokens + expected_tokens as the chain) and
refuses by name when none is present.

MLXRunnersTests 114/114.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
A resident died after 62 minutes of continuous free-decode oracle windows:
EXC_BAD_ACCESS on 0x8000000000000010 in RowCache.value(for:) under
gather(ids:...) from rows(globalIds:). The row cache is a plain LRU over one
arena and two index tables with no synchronization; two forwards gathering
at once — the engine loop's next step built while the previous one's host
readback is still inside rows(globalIds:), or a draft round beside a verify
— mutate it under each other, and the corruption shows only after enough
evictions. Every gather now holds one lock for its duration. A gather is
host work over a few hundred rows, so the cost is not measurable; the
table's exactness now holds under concurrency, not only single-threaded.

Qwen4ExpNGramTableTests 20/20, MLXRunnersTests 114/114.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Forward to readback, per step, so the parity run also says what one
decode step costs on the legacy forward and on the CBv2 stepper.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…STEP_PROFILE=1

The engine loop already records per-phase timings under CBV2_STEP_PROFILE=1
but nothing in the worker printed them. phase_diagnostics now writes the
summary table to stderr, one per phase, and resets. Diagnostic only.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Prints the per-step decode cost of a 48-layer real-shaped model with
negligible weights, so the fixed kernel/graph cost of a layer can be
measured on a laptop: ~71 ms/step in release (~1.3 ms/layer), the same
overhead the 125B pays on the box before its weights. Knobs for layers,
experts, top-k, attention interval and quantization. Skips unless
MLXLM_STEP_COST=1; needs the full metallib.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
davidtai and others added 11 commits September 6, 2026 07:36
…code step

The PLE embedding hashed the row ids on the device and read them back to
gather the table rows: a GPU→CPU→GPU sync in the MIDDLE of every step's
graph (the layers before the PLE layer evaluated alone, then the rest). The
ids are a pure function of the last ngram_size token ids, which the host
already holds as inputs, and the table's gather is host work anyway.

`Qwen4ExpNGramHostRowSource` takes host ids; `Qwen4ExpNGramEmbedding`
computes `hostRowIds` on the host (the same hash over Int64: wrapping
multiply, XOR, Python-style remainder as MLX's `%` computes it, the EOS
segment reset of `shiftRight`) and hands the device ONE input array, so the
step submits as one graph. The disk table conforms with no readback at all;
a plain device-id source keeps the old path. Bit-exactness test: host ids
equal the device hash on histories with EOS inside the window and ids
whose product wraps negative; the embedding is identical on both paths.
Qwen4Exp parity suites and MLXRunnersTests unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The metallib-gated suite never ran where the cap moved to 6 (5891033); it
asserted the old literal at every depth. MTP rounds are lossless at depths
1...6 on the fixture with the full metallib.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Lever (1a) of the decode-speed program. The hyper-connection mixer ran
silu(x / hc), sigmoid, the stream-weighted mean, 2 * sigmoid(x / hc) and
the inject broadcast-multiply-add as one kernel per op, twice per layer.
They are now four `compile(shapeless:)` functions, one kernel each; the
reshapes that make the inject operands broadcast-ready stay outside the
compiled function (views, no kernel; a shapeless trace must not carry a
reshape whose dimensions differ between prefill and decode). The ops and
their order are unchanged; a fused kernel keeps float32 between ops where
the unfused chain rounded to the activation dtype.

Harness (Qwen4ExpDecodeStepCostTests, release, 48-layer real-shaped model,
same binary, MLXLM_HC_FUSION=0/1 interleaved, three rounds, min of 60
steps): unfused 33.9 / 36.3 / 34.8 ms, fused 27.4 / 31.5 / 31.0 ms —
about 5 ms per step, roughly 6 µs per elementwise op removed at this
graph size. Exactness test: fused vs the unfused chain on float32 inputs
at S = 1 and 7, rtol 1e-5. Qwen4Exp parity suites green with the full
metallib; MLXRunnersTests 114/114. MLXLM_HC_FUSION=0 keeps the unfused
path for A/B.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…nd dropped

Lever (2) of the decode-speed program. What ships: the decay/beta gate
chain (exp, exp, softplus, add, multiply, negate, sigmoid, two casts) as one
`compile(shapeless:)` function, and a `gatedDeltaUpdate` overload that takes
the gates precomputed. Exactness test rtol 1e-5 against the unfused chain.
MLXLM_GDN_FUSION=0 keeps the unfused chain for A/B.

What was measured and dropped: three MLXFast.metalKernel kernels for the
rest of the GDN chain — concat+conv+silu+split+state slice in one launch,
both q/k RMS norms with their scales in one, the weighted gated output norm
in one — exact to activation precision (bf16 within 2e-2, float32 rtol
1e-5), parity suites green, and SLOWER. Release microbench at the 125B's
GDN dims, min of 40: the fused conv+norm pair 0.472 ms against 0.223 ms for
the unfused seven-op chain; the gate kernel 0.129 against 0.139, a tie; the
48-layer harness minimum went from 31–35 ms to 42–50 ms with them on. An
MLXFast custom-kernel launch costs ~0.13–0.2 ms of CPU on this MLX (the
primitive is built and source-hashed per call), more than the 12–20 µs
built-in dispatches it replaces. A custom kernel pays only when one launch
replaces many heavy ops, which the recurrence kernel does and these did not.
The kernels are not kept in the tree; the finding is what matters: on MLX
the levers are heavy-kernel merges by weight concat, compile-fusion of
elementwise chains (~6 µs per node), precomputed constants, and fewer
nodes — not one-for-one ports of fused Metal kernels.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…he rope rotation

Light-chain fusions, same rule as the hyper-connection chains: one
`compile(shapeless:)` function per elementwise chain, every slice and
reshape outside the trace (a shapeless trace can carry neither).

  * MoE tail: (experts * weights).sum(-2).asType + sigmoid(gate) * shared
    — the multiply, cast, sigmoid, multiply and add fuse around the
    reduction (was 7 nodes per layer).
  * attention output gate: out * sigmoid(gate) (was 2, 12 layers).
  * partial rope: the two rotated halves as two fused kernels fed the
    pre-split cos/sin halves (was negate, concat, two multiplies, add per
    call, two calls per attention layer).

About 300 nodes fewer per step at ~6 µs each on the earlier measurement.
Exactness tests rtol 1e-5 on float32 for all three; the Qwen4Exp parity
suites are green with the full metallib. MLXLM_LIGHT_FUSION=0 keeps the
unfused chains for A/B. The harness A/B was run on a laptop at load average
62 (concurrent release builds) and is inconclusive there: minima 40.9–53.5
fused against 42.7–50.5 unfused; the box measurement stands in for it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Reverts a1a3cac (MoE tail, attention gate, rope halves), cea9bc7 (GDN gate
chain) and 05652e4 (hyper-connection chains). Measured on box 4 against the
re-authored tapes, botany serial free-run 128, fork a1a3cac, per switch:
all on — not exact (first mismatch at token 19), 119–133 ms/step; hc off —
exact, 119.8; gdn off — not exact, 118.3; light off — not exact, 117.2;
all off — exact, 115.2 (= cd82c28). The hyper-connection chain is the
numerics break on its own (a fused kernel keeps float32 between ops where
the unfused chain rounds to bf16, and a near tie flips); and none of the
three is faster at real dimensions — each adds 2–5 ms/step, the compile()
per-call overhead the tiny harness did not surface. Exact on the fixture
at rtol 1e-5 was not the gate that matters; the 125B free run against the
tapes is.

The served code is byte-identical to cd82c28 again; the opt-in step-cost
harness and the host-side n-gram ids stay.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
`maximum(abs(gate), MLXArray(Float(1e-6)))` used a float32 array, not a
weak scalar, so MLX promoted the gate, the gated value and the PLE output
to float32, and `stream + ple` carried the hyper stream in float32 for
every layer after the PLE layer. On the 125B that is 47 of 48 layers,
including every routed expert gather, and it cost 87 of the 115 ms decode
step (e5 ablation, box 4: 114.8 ms/step exact vs the tapes, 27.4 ms/step
with the floor in the gate's dtype = 36.6 tok/s serial on the ranked
path). The reference clamps with a Python scalar and stays in the model
dtype. Both forward paths carried the line.

This changes the numerics of the whole tower after the PLE layer, so the
recorded tapes, goldens and calibration must be re-authored on this
runner.

Tripwires: the PLE block's output dtype equals the model dtype for bf16
and f16 (red without the change, green with it), and diag-parity refuses
at step 0 when the raw logits, which carry the stream's dtype at the last
layer, are not in the model dtype.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The drafter required serial target verification because the family had
no captured verify window, so every round cost 1 + k single-token target
forwards, each with its own blocking evaluation: on the 125B a depth-1
round was 2.00 serial steps, depth 2 2.91, depth 3 3.81 (e5 profile,
box 4: verify.build 56.15 / 85.44 ms against a 27 ms serial step), and
every depth leg refused on the decode floor.

The target now implements the captured window like Qwen 3.5:

- Qwen4ExpGatedDeltaNet.cbv2ForwardCaptured runs the causal convolution
  over the padded window in one call and the delta rule one position at
  a time, staging the state after every position (stageCaptured).
- Qwen4ExpPLELayer stages per-position short-conv tails and n-gram
  context slices the same way.
- captureRecurrentWindow is threaded layer -> tower -> model;
  Qwen4ExpModel conforms to CBv2RecurrentCaptureMTPForwardable and
  CBv2MTPPolicyTopTwoProviding (the exact top-two kernel, lowest id on a
  tie, which is the drafter's argMax rule).
- Qwen4ExpCBv2LayerCache conforms to CBv2MTPRectangularSerializing by
  forwarding the flag to the wrapped cache, so attention evaluates one
  query position at a time during a round; the protocol and the flags
  are public in MLXLMCommon now.
- The drafter no longer requires serial verification; the engine's
  configured mode applies.
- free_decode_run replies on a window that verified carry
  verification_mode, rectangular_verification_rounds and
  serial_verification_rounds, so an artifact can prove the path. Frozen
  fixture windows verify no rounds and stay byte-identical.

Tests: a 3-token window through cbv2ForwardWithHiddenCaptured equals the
same tokens fed one at a time, logits bit-equal at every position and the
committed conv/ssm/context state after commit(keepPositions: j) equal to
the sequential state after j tokens for j = 1...3; a depth-2 engine free
run produces the serial engine's tokens with rectangular rounds > 0 and
serial rounds == 0; the CBv2-vs-legacy and MTP-lossless-at-depths-1...6
suites and the worker fixture replays stay green.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…he free-run audit

With the captured verify window the MTP planner runs a plain SEED step when a
row has no carry -- the first step of every free_decode_run window, and after
a stale carry. That step commits one token and writes no round record, so the
audit assembled from the round journal stated one token fewer than the window
returned (count 128: 89 rounds summing to 127; count 12: 6 rounds summing to
11), and benchd refused the leg on its consistency triple
(sum(acceptance_lengths) != N).

The session now tracks the driver's `seedSteps` counter beside the journal
cursor and states each seed step taken inside the window as a round of width
one with nothing drafted and nothing accepted, placed ahead of the rounds it
seeded. completed_work follows the audit's round count, so it stays R + 1.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
A fresh process pays its first prefill cold and its second still on the ramp
(the Qwen 3.8 125B box reads 3.56, 0.87, then 0.635 ms/token steady). benchd's
official path warms one leg and times the next, so the timed prefill landed
mid-ramp (0.66-0.76 ms/token across boots) and the ±5 % prefill band refused
otherwise-passing runs at random (ranked runs 34063346502, 34063475882,
34063495545, 34065137349, 34074978259). ds4 warms its serve at boot; the
resident now does the same: one deterministic 1024-token prefill through the
runner's stepper, eight single-token forwards, then the allocator is drained,
all before the first connection is served. Fixed shape, no settling loop,
nothing on the wire; BENCH_WORKER_RESIDENT_WARM=0 opts out for diagnostics.
One stderr line reports the pass under the load summary.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The Qwen 3.8 Flash-Next model files (Libraries/MLXLLM/Models/Qwen4Exp*.swift
and Libraries/MLXLMCommon/Qwen4ExpCaches.swift) must compile OUTSIDE this
fork, as an editable copy in a track repository. Seven declarations blocked
that. This changes their access level only. No behaviour changes.

- Libraries/MLXLLM/Models/Qwen35MTPTopTwo.swift
  qwen35MTPTopTwoRows(_:)          internal -> public
    Qwen4ExpCBv2 calls it for the MTP top-2 reduction.

- Libraries/MLXLMCommon/KVCache.swift
  KVCacheSimple (class)            public -> open
  KVCacheSimple.innerState()       public override -> open override
  KVCacheSimple.state              public override -> open override
  KVCacheSimple.trim(_:)           public override -> open override
  KVCacheSimple.copy()             public override -> open override
  ArraysCache (class)              public -> open
  ArraysCache.copy()               public override -> open override
    Qwen4ExpAttentionCache subclasses KVCacheSimple and overrides those
    four members. Qwen4ExpLayerCache subclasses ArraysCache and overrides
    copy(). ArraysCache.extract(_:) was already open.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
davidtai and others added 2 commits September 9, 2026 05:08
…mpile outside the fork

Open KVCacheSimple and ArraysCache so a track repo can carry the Qwen 3.8 model files
Brings #139 (GPT-OSS prefill pruning, fused experts, per-request timing) and
#141 (paged checkpoints, complete-checkpoint prefix reuse, observed forward
receipts) onto the Qwen 3.8 Flash-Next runner branch. Every conflict keeps
both sides: main's new parameters and fields are threaded through the
branch's keep-mask and MTP-audit paths, and the branch's parameters are
threaded through main's new call sites.

Conflicts and resolutions

- Package.swift: keep the branch's sibling-checkout `mlxSwiftDependency`
  helper and move main's pinned mlx-swift revision 37572f1f into its remote
  fallback. Every product and target from both sides is retained.
- Libraries/MLXLMCommon/Load.swift: keep both new protocols — the branch's
  `WeightNameFiltering` and main's `IncrementalCheckpointMaterializing`.
- Libraries/MLXLLM/Models/Qwen35MTPTopTwo.swift: keep main's delegation to
  the shared `cbv2TopTwoRows` and keep the branch's `public` access level,
  which the out-of-fork Qwen 3.8 model files need.
- Libraries/MLXLMCommon/ContinuousBatchingV2/AttentionV1.swift: one merged
  signature per call layer — `keepMask` (branch) beside `metadata`/`packet`
  (main) on `updateAndAttend`, `updateAndAttendRow` and `attend`, threaded
  through every call site.
- Libraries/MLXLMCommon/ContinuousBatchingV2/LayerCacheV2.swift: pass both
  `keepMask` and the observation handles to `CBv2AttentionV1.updateAndAttend`.
  A keep-masked forward now refuses the capture by name
  (`keep_masked_attention_not_replayable`) instead of beginning one: the
  replay reference in `CBv2AttentionReplay` attends the whole retained KV
  with no mask, so a sparse keep mask can never replay from its receipt.
- Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2Contracts.swift: keep the
  branch's prefix-outcome documentation and add main's `pagedStorage` field
  to `CBv2CapacitySnapshot`, including its initializer parameter and store.
- Libraries/MLXLMCommon/ContinuousBatchingV2/EngineLoopV2.swift: take main's
  resident prefix preview plan, `adoptedHybridTokens`, paged-stage capacity
  skip, per-row diagnostic and attention confirmations, chained-step
  `forwardShapes`, and `pagedStorage` gauge, all beside the branch's
  per-request timing stamps.
- Libraries/MLXLMCommon/ContinuousBatchingV2/EngineV2.swift: take main's
  hybrid and complete prefix-cache lookup routing inside the branch's timed
  `makePrefixLookup`.
- Libraries/MLXLMCommon/ContinuousBatchingV2/SchedulerV2.swift: keep the
  branch's `enqueuedNanos` and main's `reserveFullSequenceTokens` on
  `CBv2ScheduledRequest.init` and on `enqueue`.
- Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTP.swift:
  call the now-throwing `mtpBuildRoundGraph` with `try`.
- Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPExecution.swift:
  make `mtpBuildRoundGraph` throwing and call `multimodalChunkForward` with
  `try`, as main does.
- Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPFinalize.swift:
  keep the branch's round-audit comment above the shared `mtp.recordRound`
  call that carries the audit record.
- Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPTargetVerification.swift:
  take main's per-column evaluation-target list, which adds the logit
  diagnostic targets, and keep the branch's host-sync counter after it.

Manifest capability decode

#141 added `supportsRecurrentCheckpointReuse` and `requiresNativePagedKV` to
`CBv2ModelCapabilities`. The branch's Engine Protocol v1 manifest fixture,
`Tests/MLXRunnersTests/Resources/engine-wire-v1-adapter.manifest.json`, is
pinned byte for byte against benchd and states only the six engine flags the
v1 wire shape froze (`RunnerManifest.canonicalJSON` still emits exactly
those six). The synthesized decoder therefore refused the pinned file and
`MockRunner` trapped. `CBv2ModelCapabilities` now has an explicit
`init(from:)` that keeps the six frozen flags mandatory and defaults any
flag added after the freeze. The fixture bytes and every digest are
unchanged.

BenchLoad fix

`Sources/BenchLoad/main.swift` carried an `@main` type but is named
`main.swift`, which makes the module a top-level-code module.
`xcodebuild build-for-testing` rejected it with "'main' attribute cannot be
used in a module that contains top-level code". The file holds no top-level
statements, so it is renamed to `Sources/BenchLoad/BenchLoadMain.swift` —
the same shape `Sources/BenchCBv2/BenchCBv2Main.swift` already uses. No
behaviour change.

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

davidtai commented Sep 9, 2026

Copy link
Copy Markdown
Author

origin/main merged in — conflicts resolved

Merge commit 859f4d9 (signed). main brought #139 (GPT-OSS prefill pruning, fused experts, per-request timing) and #141 (paged checkpoints, complete-checkpoint prefix reuse, observed forward receipts). Every conflict keeps both sides.

Per-file resolution

File Resolution
Package.swift Kept the branch's sibling-checkout mlxSwiftDependency helper and moved main's pinned mlx-swift revision 37572f1f into its remote fallback. Every product and target from both sides is present.
Libraries/MLXLMCommon/Load.swift Kept both new protocols: the branch's WeightNameFiltering and main's IncrementalCheckpointMaterializing.
Libraries/MLXLLM/Models/Qwen35MTPTopTwo.swift Kept main's delegation to the shared cbv2TopTwoRows and the branch's public access level (PR #143 needs it outside the fork).
…/ContinuousBatchingV2/AttentionV1.swift One merged signature per layer: keepMask (branch) beside metadata/packet (main) on updateAndAttend, updateAndAttendRow and attend, threaded through every call site.
…/ContinuousBatchingV2/LayerCacheV2.swift Passes both keepMask and the observation handles down. A keep-masked forward now refuses the capture by name (keep_masked_attention_not_replayable) instead of beginning one — CBv2AttentionReplay attends the whole retained KV with no mask, so a sparse keep mask can never replay from its receipt.
…/ContinuousBatchingV2/CBv2Contracts.swift Kept the branch's prefix-outcome docs; added main's pagedStorage field to CBv2CapacitySnapshot (property, init parameter and store).
…/ContinuousBatchingV2/EngineLoopV2.swift Took main's resident prefix preview plan, adoptedHybridTokens, paged-stage capacity skip, per-row diagnostic/attention confirmations, chained-step forwardShapes and pagedStorage gauge, all beside the branch's per-request timing stamps.
…/ContinuousBatchingV2/EngineV2.swift Took main's hybrid and complete prefix-cache lookup routing inside the branch's timed makePrefixLookup.
…/ContinuousBatchingV2/SchedulerV2.swift Kept the branch's enqueuedNanos and main's reserveFullSequenceTokens on both CBv2ScheduledRequest.init and enqueue.
…/MTP/EngineLoopV2+MTP.swift Calls the now-throwing mtpBuildRoundGraph with try.
…/MTP/EngineLoopV2+MTPExecution.swift Made mtpBuildRoundGraph throwing; multimodalChunkForward called with try.
…/MTP/EngineLoopV2+MTPFinalize.swift Kept the branch's round-audit comment above the shared mtp.recordRound call that carries the audit record.
…/MTP/EngineLoopV2+MTPTargetVerification.swift Took main's per-column evaluation-target list (adds the logit-diagnostic targets) and kept the branch's host-sync counter.

Verified mechanically: every line either side added over the merge base 30da946 is present in the merged tree, except the signature/argument lines that were deliberately rewritten to carry both sides' parameters.

Two integration fixes

Manifest capability decode. #141 added supportsRecurrentCheckpointReuse and requiresNativePagedKV to CBv2ModelCapabilities. The Engine Protocol v1 fixture Tests/MLXRunnersTests/Resources/engine-wire-v1-adapter.manifest.json is pinned byte for byte against benchd and states only the six engine flags the v1 wire shape froze — RunnerManifest.canonicalJSON still emits exactly those six. The synthesized decoder refused the pinned file and MockRunner trapped. CBv2ModelCapabilities now has an explicit init(from:) that keeps the six frozen flags mandatory and defaults any flag added after the freeze. The fixture bytes and every digest are unchanged.

BenchLoad. Sources/BenchLoad/main.swift carried an @main type while being named main.swift, so the module counted as a top-level-code module and xcodebuild build-for-testing failed with 'main' attribute cannot be used in a module that contains top-level code. The file holds no top-level statements, so it is renamed to Sources/BenchLoad/BenchLoadMain.swift, the shape Sources/BenchCBv2/BenchCBv2Main.swift already uses. No behaviour change. This defect is on origin/main as well: origin/main alone fails the same build the same way.

Build and test

Xcode 26.6 (17F113), macOS 26.5 SDK, DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer.

swift build -c release --scratch-path .build-merge          Build complete! (561.52s)
xcodebuild build-for-testing -scheme mlx-swift-lm-Package \
  -destination 'platform=macOS' \
  -skipPackagePluginValidation -skipMacroValidation         ** TEST BUILD SUCCEEDED **
xcodebuild test-without-building … -only-testing:MLXRunnersTests
xcodebuild test-without-building … -only-testing:MLXLMTests

-skipPackagePluginValidation -skipMacroValidation are needed only because this machine has not trusted the CudaBuild plugin that ships with the pinned mlx-swift; without them xcodebuild refuses before it compiles anything.

MLXRunnersTests — 146 tests pass, then the process aborts inside Qwen4ExpNormConventionValidatorTests / "Baked weights with offset 0 are accepted" with MLXNN/Module.swift:1421: Fatal error: please call update() on the array rather than setting it, and three Qwen4ExpAdoptTests cases fail. Pre-existing, not caused by this merge. d087c306 run the same way aborts at the same test with the same message and the same three Qwen4ExpAdoptTests failures (147 passing before the abort, exit 65 on both). Libraries/MLXRunners/, Tests/MLXRunnersTests/ and every Qwen4Exp* model file are byte-identical between d087c306 and the merge, and mlx-swift resolves to the same commit on both (Layr-Labs/mlx-swift main is 37572f1f). The manifest fixture test that this merge fixed — "The shared mock-adapter manifest decodes and digests as pinned" — passes.

MLXLMTests — the MLX-runtime suites cannot run in this environment. The Metal library that xcodebuild build-for-testing produces is partial, so the process aborts with [metal::Device] Unable to load kernel dot_product_float32_it32_tg512_sg16, and the paged suites refuse with .backendIneligible / missing SwiftPM resource pagedattention.metal because the SwiftPM resource bundle Xcode emits nests the file under Contents/Resources/ while PagedAttentionResources.locate looks for it at the bundle root. Pre-existing, not caused by this merge. origin/main run the same way produces the same fatal kernel-load errors, the same .backendIneligible refusals (171 of them) and the same GPTOSSPrefillOutputTests tolerance failures (44), and exits 65. PagedAttentionResources.swift, the MLXLMCommon resource declaration, the GPT-OSS math files and GPTOSSPrefillOutputTests.swift are byte-identical between origin/main and the merge.

Everything that does run passes. Nothing that fails here is reachable from the merge resolution; a box with the full AOT Metal library is what these suites need.

The repository's own pull_request.yml jobs are all gated if: github.repository == 'ml-explore/mlx-swift-lm', so none of them run on this fork.

🤖 Generated with Claude Code

@davidtai

davidtai commented Oct 5, 2026

Copy link
Copy Markdown
Author

Closing: main has its own native Qwen4 (c388c5e and later) under the same type names. 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-runner branch October 5, 2026 00:42
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.

2 participants