Skip to content

Preserve Bonsai row arithmetic and native fence ordering - #61

Merged
davidtai merged 16 commits into
mainfrom
fix/cluster-bonsai-row-arithmetic
Oct 28, 2026
Merged

davidtai merged 16 commits into
mainfrom
fix/cluster-bonsai-row-arithmetic

Conversation

@jonathan308

@jonathan308 jonathan308 commented Oct 23, 2026 •

Copy link
Copy Markdown

Native ordering dependency

This draft now includes MLX core #41: the fast GPU fence wait orders earlier kernels in the current concurrent pass. The core regression passes for both old and patched binaries, so it does not reproduce or prove repair of the installed Qwen TP stall. Matching installed-app validation is in progress; shared GLM paired verification remains a merge gate.

This draft corrects the packed projection path used by the registered Bonsai27B FP32 Hadamard policy. Eligible multi-row calls could enter architecture-dependent TF32 matrix arithmetic and disagree between the M5 Max and M3 Ultra. They now retain native packed M=1 arithmetic independently for each row.

The change is restricted to signed-Hadamard FP32 multi-row affine2/group128/block1024 inputs with stored FP16 scales. It preserves the signed transform, grouped GDN layout, constant-cache behavior, bias placement and singleton path. It adds no duplicate weight bank. Ordinary quantized callers and Bonsai9's block4096 policy retain their existing dispatch. The row-arithmetic delta changes Hadamard.swift, Quantized.swift and two focused test files. This draft also advances the nested MLX pin to MLX core #41; the C API, mirrored headers and shader sources are unchanged by that pin delta.

Before

flowchart TD
  A["Eligible FP32 Hadamard rows"] --> B["Signed transform"]
  B --> C["Wide packed matrix reduction"]
  C --> D["Architecture-dependent output bytes"]
  E["GPU producer in current pass"] --> F["No explicit barrier before spinning wait"]
  classDef default fill:#e8f0fe,stroke:#174ea6,color:#102a43,stroke-width:2px;
  classDef guard fill:#fff4ce,stroke:#8a6100,color:#332500,stroke-width:2px;
  classDef success fill:#d7f0df,stroke:#176b39,color:#103b23,stroke-width:2px;
  classDef failure fill:#fde2e2,stroke:#9b1c1c,color:#571111,stroke-width:2px;
  class B,C guard;
  class D,F failure;
Loading

After

flowchart TD
  A["Eligible FP32 Hadamard rows"] --> B["Same signed transform"]
  B --> C["Broadcast packed M=1 rows"]
  C --> D["Original bias and cached constants"]
  D --> E["Exact singleton and cross-chip byte oracle"]
  F["Matching core pin"] --> G["Current-pass barrier before GPU wait"]
  classDef default fill:#e8f0fe,stroke:#174ea6,color:#102a43,stroke-width:2px;
  classDef guard fill:#fff4ce,stroke:#8a6100,color:#332500,stroke-width:2px;
  classDef success fill:#d7f0df,stroke:#176b39,color:#103b23,stroke-width:2px;
  classDef failure fill:#fde2e2,stroke:#9b1c1c,color:#571111,stroke-width:2px;
  class A,B guard;
  class E,G success;
Loading

Validation: actual 30-source MLXNN module/object compilation; 14 canonical CPU tests covering arithmetic, grouped layout, bias, shapes, constant replacement and compiled state; and nine actual-weight projection shapes on each Mac under unchanged TF32/cache settings. Every candidate projection matches independently executed singleton bytes, and complete candidate outputs match between Macs. Independent source/refactor review found no remaining issue.

The exactness repair has a measured performance cost: at 511/512 rows, these projection fixtures cost 6.59–7.90 times the legacy path on M5 and 3.15–3.47 times on M3; singleton cost is approximately unchanged. These are projection measurements, not full-model timings. No throughput improvement is claimed.

This remains a draft. Full-artifact Bonsai27B numerical/context/endpoint qualification is not established by these layer probes. Existing failures and comparison thresholds are preserved. The c05 SDK base is 59ff16af8c5196f2b6eeccc68137a62875b4808f; the original fixture pins remain recorded with that evidence. The current nested core is 4e2455b0093cb63454fdc9d74914ed03e3777acc.

Base dependency: cluster native Swift PR #56, branch darkbloom/sealed-all-sum. Provider integration builds on d-inference #1407.

Canonical repository rerun commands (the recorded focused tests were compiled against the actual source closures in isolated CPU harnesses):

swift build -c release
swift test -c release --filter Float16ConstantCastTests
swift test -c release --filter HadamardLayerTests
Evidence identity SHA-256
BONSAI-ROW-ARITHMETIC-RESULT.md da363ac4960648a283d1fe55a877480be7fd9c42d0a6c233f14aeb0b2f933fb3
bonsai-row-candidate-gpu-01/summary.json 05e420d3e5402ce5de54b150ef4b61f23a32cb8c9ccae6abe1735b08cdcfe69d

Publication follow-up: the four changed Swift files were normalized with the required formatter. The formatter is byte-idempotent, all files parse, and GitHub formatting and fork checks pass. The GPU fixture evidence predates this formatting-only change; full build/test remains a separate gate.

Current integrated hardware gate — 2026-10-23

Normal signed c16 TP2 completed through the installed Darkbloom command/services/API on M3 Ultra256GB + M5 Max128GB (recursive source SHA d6f6adcedca1aeacfc5265ec427e3ef913633f5b77629b8c61cbdaf4ba278000). Stable endpoint37PASS/0FAIL/1intentional skip, context6/6 through32K, media/structured-output/mixed30/30 and cancellation/survivor/recovery3/3 pass. All61 matching native scopes retire with zero in-use KV;13 reach actual width2 on both ranks. Initial before/after-plan exact outputs remain29PASS/8FAIL/1SKIP. Aggregate throughput at offered concurrency1/2/4/8 is13.26/13.56/13.52/13.43tokens/s at native capacity2. Cleanup and restored idle services pass, but final workers exit1 after input closes; graceful shutdown remains a separate open gate. No full model or beta release is qualified.

Provider follow-up #1577 at signed/Verified b845e27771cb7c355ce1baa35731f343a16fec2c retains typed eager-fence diagnostic forwarding and completed-decode width counters. c17 is installed on both Macs. Its bounded FAST1+EAGER1 diagnostic completed FAIL:11PASS/7FAIL/6intentional skips. Both settings are verified in both fresh native pairs; a real width-two scope then stalls with an M3 JACCL timeout at60001ms and M5 lost input. Original service-job bytes and healthy idle services are restored on both hosts. Eager commits alone do not fix the fast-path stall. The same c17 build is now running short default-policy1/2/4 checks to measure actual batch utilization. Defaults remain the c16 event-synchronization policy for batched Qwen27.

Installed TP MTP remains disabled. The prepared foundation compiles and passes selected CPU checks, but only speculates singleton; true multirow target verification, whole-cohort memory accounting and full-artifact acceptance remain unfinished. The normal c14 fast-path stall and c15 exact-output mismatch remain preserved. No tolerance, memory guard or capability gate is relaxed.

Core#41 at9ec passes7 hosted checks; inherited recoverable UBSAN diagnostics remain recorded. Installed/downstream core still uses4e's Apple fence change;9ec portability changes are not propagated. Swift#61 has3 passing checks. SDK#352 at4f still fails:3613tests/622suites/847issue records plus one separate unit issue, including842 NemotronSuper assertions and two Prism error-contract regressions; four GLM issue records match foundation limitations. Serial CI uses event synchronization with matching reported runner image/OS/toolchain. A common cause with the cluster fast-path stall is not established. Final reviews, exact pins, SDK isolation and full-model checks remain gates.

🤖 Generated with Claude Code.

Progress 2026-10-26: main merged, stack re-pinned, validated on two M5 Ultra 256 GB

Head f70ddf7e: #56, #61's previous head 3832c0de and main merged; nests core #41 merged with MLX_QMV_BATCH_INVARIANT (caa9ed53) and mlx-c 73720efb.

Nothing merged or released; the owners sign and release.

Update 2026-10-26 17:15 PDT: main/master 0.10.3 merged through the stack

Head 31ffa0d: #56 merged; Source/Cmlx/mlx → core #41 ea318ee0. Every PR in the cluster stack (mlx #33 → #35 → #41, mlx-c #15, mlx-swift #54 → #56 → #61, SDK ml-explore#308 → ml-explore#352, d-inference #1407 → #1426 / #1577, platform #54) is again mergeable in that order, as drafts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jonathan308 jonathan308 changed the title Preserve singleton FP32 arithmetic for Bonsai packed rows Preserve Bonsai row arithmetic and native fence ordering Oct 23, 2026
jonathan308 and others added 8 commits October 25, 2026 09:23
Source/Cmlx/mlx moves to a5d6547b (Layr-Labs/mlx#41): helper ops such as
quantized_matmul's casts keep the caller's stream, and a GPU stream waits for
another GPU stream on a shared event instead of a spinning fast fence. A
widened Qwen tensor-parallel decode had put one graph on two GPU streams and
stalled.

- QuantizedLinear.independentRowsForward runs affine float32 rows through
  MLX's single-row (M=1) kernel, each as its own call would run it, with the
  FP32 widening of the BF16 scales and biases that callAsFunction caches (one
  copy for both, made on the caller's stream) instead of a fresh widening
  inside every batched quantized matmul.
- fork.yaml describes both.

Tests: the cluster runtime suites that run independentRowsForward passed on
the M5 Max with this pin (QwenTensorParallel CPU suites, GPU batch 14, GPU
MTP 30, in the provider's c44 candidate chain); on the two-Mac pair the
installed c44 acceptance kept every concurrent row byte-equal to solo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Source/Cmlx/mlx moves to 2e16455f (Layr-Labs/mlx#41): on a GPU without neural
accelerators, prompt-sized affine quantized matmuls take 64 x 32 (16-bit) or
32 x 64 (FP32) output tiles instead of 32 x 32, with every element's bits
unchanged.

- `GPU.withQuantizedMatmulSteelTile(_:_:)` runs a body with the steel tile the
  calling thread encodes (the C entry `mlx_metal_set_thread_qmm_steel_tile` is
  declared in the vendored `command_buffer_limits.h`), for tests and benches.
- fork.yaml describes both.

Tests: the cluster runtime's steel-tile byte tests and two-rank prompt-
submission GPU test (M5 Max), and the provider's c45 candidate chain.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Source/Cmlx/mlx moves to d11238f1 (Layr-Labs/mlx#41): MLX builds that load
kernels only from the precompiled library keep 32 x 32 steel tiles for affine
quantized matmuls rather than asking for wider tiles the library never
instantiated. mlx-swift compiles the core's kernels at run time
(jit_kernels.cpp), so its kernels and results are unchanged.

Tests: the core's C++ tests on the M3 Ultra, precompiled and JIT builds (see
the core commit), and mlx-swift's generated-Metal check with the new core
nested. mlx-swift itself was not rebuilt here; build-and-test runs it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rithmetic fix (#61)

Forward merge of the refreshed #56 into this branch. It carries main
6959486 through the refreshed #54, the swift-format fix of
MLXFastKernel.swift and the fork.yaml section for MLXArray.sharingArray().

Conflicts:
- Source/MLXNN/Quantized.swift, QuantizedLinear.constantCachedForward: kept
  this branch's independent-rows path (each FP32 row through the M=1 packed
  kernel) and main's NVFP4 global scale (upstream ml-explore#426), applied after either
  quantizedMM path. Without a global scale the scale step returns its input,
  so this branch's row arithmetic is unchanged.
- fork.yaml, "Submodule pins": the paragraph from the #56 merge, with this
  branch's fence-ordering, shared-event stream wait and caller-stream helper
  additions.

Gitlinks merged without conflict: Source/Cmlx/mlx stays at this branch's
2e16455f (the prompt-sized steel tiles on top of the fence-ordering core) and
Source/Cmlx/mlx-c at 8a50797b. HadamardLayerTests.swift auto-merged this
branch's row tests with main's formatting and its removal of the
setDefaultDevice() test helper; no test in the result calls it. The tree is the
refreshed #56 plus this branch's own delta.

Tests (Ultra A, Xcode 27.1). The committed gitlinks are not changed. For
the build, the nested repos were checked out at merged heads: core
668e46c6 (the core merge into mlx#41 with its steel-tile build fix;
dbe665ac before it gave the same results) and the temporary merge of mlx-c
main 004c735f into 8a50797b.
- swift build --build-tests: complete.
- Fork Tests, all 3 shards of the CI plan, with an AOT mlx.metallib from
  that core:
  - XCTest: 853 listed, 849 passed (including HadamardLayerTests and
    Float16ConstantCastTests), and the 2 permitted skips.
  - The fresh-process allocation-cap test and both multi-process ring
    suites passed.
  - Swift Testing: 749 of 749 passed.
  - test-shards.py verify: every test ran exactly once.
- The allocation-cap test is timing sensitive. Main's wrapped-page check
  (#64) failed in 2 of 34 fresh-process runs on this layer, both in the
  first minutes (23:21-23:23) while other jobs loaded this Mac. Buffers that
  Metal completion handlers released after the test's clearCache or baseline
  snapshot were still counted: 16 KiB cached in one run, 32 KiB live in the
  other. It passed the other 32 runs and 22 of 22 runs on #56. This layer's
  core delta over #56 does not touch that single-stream path.
- check-generated-metal-sources.py passes against that core.
- Lint (swift-format 603.0.0, as the Lint job runs it on the files this
  branch changes against #56): no changes.
- check_forkdiff.py --upstream-ref upstream/main: 213 of 213 files
  described.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The PR branch moved on GitHub after this refresh started: 3832c0d pins
Source/Cmlx/mlx to d11238f1 (Layr-Labs/mlx#41), the core that keeps
precompiled MLX builds on 32 x 32 steel tiles. Merging it makes this branch
a fast-forward of the published head. The merge is clean, and the gitlink
moves 2e16455f -> d11238f1. The forward merge of #56 and the restitch to the
merged #41 core (which contains d11238f1) follow.

Tests: run on the restitch commit that follows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…anch (#61)

Brings #56's forward merge of the restitched #54 and #56's own restitch
commit 3e1fc78 forward, so that this branch contains its base again.

Conflicts, resolved to this branch's side. The restitch commit that follows
sets this layer's pins and regenerates from them:
- Source/Cmlx/mlx (gitlink): kept d11238f1, this branch's #41 pin. #56 has
  its own core, 2b5253ad.
- fork.yaml, "Submodule pins" paragraph: kept this branch's paragraph.

Taken from #56 without conflict:
- Source/Cmlx/mlx-c moves 8a50797b -> 73720efb, the merge of mlx-c main into
  mlx-c#15. This layer pins the same C layer.
- The regenerated include-framework headers.

Tests: run on the restitch commit that follows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Restitches the nested pins after the merge of main 6959486:
- Source/Cmlx/mlx: d11238f1 -> ce21a37d. That is the merge of the refreshed
  mlx#35 into Layr-Labs/mlx#41, a fast-forward of the published d11238f1,
  plus the fix of the head-dim split NAX attention's run-time template.
  Without that fix, the JIT build that mlx-swift uses throws "Unable to
  build metal library from source" for head-dim 256 and 512 causal or masked
  prefill on NAX GPUs.
- Source/Cmlx/mlx-c: 73720efb (taken from #56), the merge of mlx-c main into
  mlx-c#15.

Regenerated as tools/update-mlx.sh does from those pins:
- The mirrored Source/Cmlx/include headers, the embedded JIT and CPU
  sources and the Xcode project match the regeneration.
- The include-framework copies of the core's metal/device.h and utils.h gain
  #41's steel-tile declarations: thread_qmm_steel_tile, qmm_steel_tile and
  its minimum-groups setting.
- Metal.hpp differs only in its "Autogenerated" line and is kept as it is.

fork.yaml's pin paragraph names the merged core and C.

Tests (Ultra A, Xcode 27.1, at these pins):
- tools/update-mlx.sh regeneration from the two pins matches the tree
  (Metal.hpp aside, as above).
- check-generated-metal-sources.py: pass.
- swift build --build-tests: complete.
- Fork Tests, all 3 shards of the CI plan, with an AOT mlx.metallib from
  this core:
  - XCTest: 853 listed, 849 passed (including HadamardLayerTests and
    Float16ConstantCastTests), and the 2 permitted skips.
  - The fresh-process allocation-cap test and both multi-process ring
    suites passed.
  - Swift Testing: 749 of 749 passed.
  - test-shards.py verify: every test ran exactly once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Source/Cmlx/mlx: ce21a37d -> caa9ed53 (Layr-Labs/mlx#41 merged with main + the opt-in switch that keeps quantized products of 2 to the vector limit - 1 rows on qmv_wide, so a request's rows get the same bits whatever shares their launch; off by default, main's routes unchanged). tools/update-mlx.sh regenerated from caa9ed53 + mlx-c 73720efb changes only include-framework/mlx-utils.h (the new env::qmv_batch_invariant(); Metal.hpp aside, as before: the regeneration used the vendored metal-cpp). Source/Cmlx/mlx-c unchanged (73720efb). No kernel source changed: the mlx-generated sources are identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit to Layr-Labs/mlx-swift-lm that referenced this pull request Oct 26, 2026
… with the batch-invariance switch

Package.swift: mlx-swift 3832c0de -> f70ddf7e = Layr-Labs/mlx-swift#61 merged with main 69594861 (89144f9f, which contains #61's head 3832c0de) + the nested core caa9ed53 (mlx#41 merged with main + MLX_QMV_BATCH_INVARIANT) and mlx-c 73720efb. Main's SDK needs the main-merged mlx-swift API.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Source/Cmlx/mlx -> ea318ee0 (core #41 with main 6bc9de5b merged; its head-dim split JIT fix now reads as main's); mlx-c stays 73720efb.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jonathan308
jonathan308 marked this pull request as ready for review October 27, 2026 18:50
@jonathan308
jonathan308 requested a review from davidtai October 27, 2026 18:50
- fork.yaml: DARKBLOOM_BONSAI_F16_CONSTANT_CACHE=0 turns off the FP16
  widening reuse only; it does not restore the multi-row kernel path.
  The Bonsai section now describes the per-row single-row (M=1) path.
- fork.yaml: the steel-tile section cited Swift tests that do not exist.
  It now cites the core's tests/quantized_tile_tests.cpp.
- GPU.withQuantizedMatmulSteelTile: 6464 uses a K depth of 64 only for
  16-bit inputs in groups of 64 or more, as the core does; a build
  without the Metal JIT keeps 32 x 32.
- QuantizedLinear.independentRowsForward: document its precondition.
- Float16ConstantCastTests: the mutation and compile-state tests moved
  from one row to three, so they lost the singleton FP16-reuse path.
  They now check both one and three rows.

No runtime code changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@davidtai

Copy link
Copy Markdown

Review 2026-10-27. No correctness findings in the row arithmetic, the tile wrapper, or the headers.

078a6e2 (docs and tests only, no runtime change):

  • fork.yaml: DARKBLOOM_BONSAI_F16_CONSTANT_CACHE=0 turns off FP16 reuse only and does not restore the multi-row path; the Bonsai section now describes the per-row M=1 path. The steel-tile section cited Swift tests that do not exist; it now cites the core's tests/quantized_tile_tests.cpp.
  • GPU.withQuantizedMatmulSteelTile doc: 6464 uses K depth 64 only for 16-bit inputs in groups of 64 or more; a build without the Metal JIT keeps 32 x 32.
  • QuantizedLinear.independentRowsForward: precondition documented.
  • Float16ConstantCastTests: the mutation and compile-state tests had moved from 1 row to 3 and lost the singleton FP16-reuse path; they now check 1 and 3 rows.

Open (not changed): eligible FP32 prompts now run one M=1 call per row. Prefill cost on the 16K/1024 workload is not measured in this PR.

@davidtai
davidtai changed the base branch from darkbloom/sealed-all-sum to main October 27, 2026 22:59
davidtai and others added 3 commits October 27, 2026 18:03
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Source/Cmlx/mlx moves from ea318ee0 to e637499f, the head of
Layr-Labs/mlx#41: the fast fence is updated before the event fence,
fenced inputs stay in device memory and take their waits first, a
sealed frame over INT_MAX is refused, and the JACCL mesh shares its
failure flag across wires and does all_gather offsets in 64 bits.
The range changes .cpp files that the package already compiles and
headers that it does not mirror (distributed/sealed.h, sealed_stream.h,
jaccl/lib). No Metal kernel, JIT source, CPU preamble input or CUDA
device file changes, so mlx-generated does not change. The Metal.hpp
commit stamp is written only by a cmake run and is left as it is.

Source/Cmlx/mlx-c moves from 73720efb to 2ac897e3, the head of
Layr-Labs/mlx-c#15. Only comments in mlx/c/distributed_group.h change;
both mirrored copies are refreshed as tools/update-mlx.sh and
tools/update-mlx-xcodeproj.sh copy them. The other 28 headers are
unchanged byte for byte.

fork.yaml: the Submodule pins prose names the new pins and fixes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Source/Cmlx/mlx moves from e637499f to 72dffa2d. The range changes only
tests/jaccl/progress_guard_tests.cpp and
tests/jaccl/startup_wait_budget_group_tests.cpp, which Package.swift
excludes, so no mirrored header or generated source changes. mlx-c
stays at 2ac897e3.

fork.yaml: the Submodule pins prose names the new core pin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@davidtai
davidtai merged commit 52c36f8 into main Oct 28, 2026
13 checks passed
@davidtai
davidtai deleted the fix/cluster-bonsai-row-arithmetic branch October 28, 2026 00:54
davidtai added a commit to Layr-Labs/d-inference that referenced this pull request Oct 28, 2026
Brings the cluster beta (PR 1407, PR 1426, PR 1577) and master 52f79ef to
dev, with the independent review's fixes: the EngineV2LogprobsChannel cap
tests are restored (T1), a member that refuses inference releases its service
reservation (B1), and a stop while the pair is forming retires the slot
before it returns (C1). The MLX closure is pinned to the reviewed heads:
libs/mlx 72dffa2d (Layr-Labs/mlx#41), libs/mlx-swift c633d221
(Layr-Labs/mlx-swift#61; mlx-c 2ac897e3), libs/mlx-swift-lm d5bd32b8
(Layr-Labs/mlx-swift-lm#352). PR CI 40602298933 green except the two Vercel
projects whose root console-ui/ master deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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