Skip to content

qwen27 metal: serve the tied 0.8B and 4B, as CUDA does - #4634

Open
joshuaswarren wants to merge 4 commits into
ashhart:mainfrom
joshuaswarren:tf-3702-metal-tied-heads
Open

joshuaswarren wants to merge 4 commits into
ashhart:mainfrom
joshuaswarren:tf-3702-metal-tied-heads

Conversation

@joshuaswarren

@joshuaswarren joshuaswarren commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

The qwen27 Metal engine refused tie_word_embeddings, and engine routing sent
every tied checkpoint to the pinned 2B engine, which then refused any other
geometry - so Qwen3.5-0.8B and 4B had no Metal engine at all (#3702). CUDA
already admits the tied head and serves it from the embedding; the Metal 2B
path admits it for the 2B's pinned geometry. This brings the 27B Metal engine
to the same rule, and qualifies the two tied sizes it needs.

Three gates opened, test-first, each with a failing test first:

  • config: the shared tied row read stays, the refusal goes, and the parse
    carries Config.tied.
  • widths and gpu weights: a tied head resolves its width from
    model.embed_tokens (the same physical tensors must load at one width) and
    packs that module into the head Linear; the checkpoint has no lm_head.
  • routing: a tied checkpoint opens the 27B engine; only the pinned 2B hidden
    size reroutes.
  • sizes: supported() gains the 4B (2560/9216/32) and 0.8B (1024/3584/24)
    rows; kv_heads and k_heads move into the size row and the fixed
    kv_heads == 4 conjunct goes. Their projections satisfy the kernel contract
    (k mod 64, n mod 32, head_dim 256, dk/dv 128, rope 64), which the new test
    asserts; a stranger size still refuses.
  • attention plan: the GQA qualification reads the quotient (6, 4 or 16) instead
    of three literal heads/kv pairs, so the 0.8B's 8-over-2 shape takes the same
    group-4 shader build the 9B uses. A quotient of 5 still refuses.

Measured receipts (Mac Studio M1 Ultra, macOS 26.6.2, Mac13,2, Qwen3.5-0.8B-4bit mlx-community/Qwen3.5-0.8B-4bit @ da28692b, model.safetensors sha256 f5a0d9dd…)

Metal arm, this branch at 85f898d1, binary sha256 5746bb20…: serve
--context 8192 --parallel 1 --no-drafts --prompt-cache-gib 0, 50 completions
at temperature 0, max_tokens 128, one run at a time. All 50 produce one
identical token sequence, token_sha256 8f50a6c33cf732d1ffe4931b641115a94c07f9141fe6edfb66a011a1af669ada;
p50 0.9169 s and p50 138.82 tok/s per completion (server-reported).

CUDA arm, main 2eecb9635 on an RTX 5060 Ti (-Dsm=120), binary sha256
0775f492…, same checkpoint, same prompt: token_sha256 8f50a6c33cf732d1ffe4931b641115a94c07f9141fe6edfb66a011a1af669ada

  • 128/128 token-id match across engines and hardware.

Host tests: test-qwen-dense-route-host and test-qwen-dense-geometry-host
pass on the target Mac (119/119). Fixes #3702.

joshuaswarren added a commit to joshuaswarren/TensorFold that referenced this pull request Nov 22, 2026
…n rules

CI on ashhart#4634 found what the target-Mac runs could not: the shared-reader
counting tests assert the old admission totals, and the lean checker
counted three comment problems the local dense steps never see.

- qwen35_layers_host: the real-configs test now counts 26 admitted
  (config, backend) pairs - the tied 0.8B and 4B on Metal's 27B engine,
  the rows ashhart#3702 admits; the layer-pattern table itself is unchanged, so
  relaxed stays 0 (what moved is the tied-head gate below the pattern
  read, not the patterns). ashhart#1863's table takes one more row per the same
  admission (8 across the five entry points).
- lean: the tied-head comments fit 120 columns and the routing note is
  one line.
@ashhart

ashhart commented Nov 23, 2026

Copy link
Copy Markdown
Owner

Thanks @joshuaswarren. The tied-head loading direction looks good, but a few fixes are needed. Geometry.check now accepts 16/1, which an existing test still refuses; please admit only the shapes this PR qualifies so that refusal stays. A test in model.zig still expects the 4B to be refused, and the two qwen35 rules host tests need their counts updated now that tied configs parse. The info startup budget also counts the embedding once, while the loader keeps it and allocates a second packed head, so please add that allocation there.

  • Synthena

joshuaswarren added a commit to joshuaswarren/TensorFold that referenced this pull request Nov 23, 2026
… twice

Review on ashhart#4634 (ashhart):

- Geometry.check admitted every GQA-16 pair, which let 16/1 in; only the
  one-Mac 32/2 is qualified. Keep the quotient-6 and quotient-4 arms and
  restore the exact 32/2 pair, so the rank refusal stays.
- model.zig's neighbour test still expected the tied 4B refused; it is
  qualified now, so the test admits it.
- the two qwen35 rules host counts move with the tied admissions:
  bases 6 -> 7 and cases 360 -> 420 in the row-and-value sweep; Metal
  27B's zero-head bases 8 -> 18 and the without-head_dim derived 13 -> 18.
- info's startup budget counts the embedding once while a tied load keeps
  it and packs a second head over the same tensors: qwen27_reserve adds
  the embedding module's checkpoint bytes when the config is tied (0 when
  the tensors cannot be read).
@joshuaswarren

Copy link
Copy Markdown
Contributor Author

All three review points are fixed and pushed at 789c1a5cf:

  1. Geometry.check narrows to the qualified pairs. The quotient-16 arm let 16/1 in; only the one-Mac 32/2 is qualified. The check now keeps the quotient-6 arm, adds quotient-4 (the tied 4B's 16/4 and the 0.8B's 8/2), and restores the exact 32/2 pair — so 16/1 still refuses, as does GQA5 and the 24/2 rank.
  2. model.zig's neighbour test admits the tied 4B instead of expecting the refusal; the 27B/9B rows and the two mismatched-depth refusal cases stay.
  3. The two qwen35 rules host counts move with the tied admissions, updated from the observed runs on this branch: the row-and-value sweep is 7 bases × 6 rows × values (the tied pinned-2B base now also parses on Metal's 27B; 360 → 420 cases), and the zero-head refusal table is {CUDA 28, Metal 27B 72, Metal 2B 4, HIP 72} with 18 without-head_dim bases.
  4. The info startup budget now charges a tied checkpoint's second packed head: qwen27_reserve.budget adds the model.embed_tokens module's checkpoint bytes (weight + scales/biases) to the resident hold when Config.tied; 0 when the tensors cannot be read.

Gate: the qwen35 rules host suite is green locally on this head after the count updates (all 7 tests), and the dense-route host test passes. The upstream zig/zig-b/zig-windows jobs are queued on the merge commit and I will report their result here when they land.

(The red No GPU jobs on the earlier heads were this same pre-#4634 failure; the fix above is what turns them.)

@ashhart

ashhart commented Nov 23, 2026

Copy link
Copy Markdown
Owner

@joshuaswarren Thanks. The 32/2 narrowing, the 4B neighbour test and both rules counts are in. Four things are left. The first stops the Mac build, and the rest are on tied checkpoints:

  • zig/src/native/qwen27_reserve.zig:49: "model.embed_tokens." ++ suffix concatenates a runtime loop value, so the native build fails with unable to resolve comptime value. Please make it an inline for.

  • zig/src/native/qwen27_reserve.zig:49: tiedHeadBytes looks only for model.embed_tokens.*. The loader also accepts language_model.model.embed_tokens.* (gpu_weights.zig:380). For those checkpoints the lookup finds nothing, the budget adds 0, and info overstates the room for streams. Please use the same prefix the loader picks.

  • zig/src/native/qwen27_reserve.zig:46: the helper ends with ck.release(), which leaves each shard's mapping and file handle open. Please use ck.close().

  • zig/src/families/qwen27/weights.zig:162: the CPU loader always reads lm_head, so tf-qwen27-weights DIR --check fails with MissingTensor on a tied checkpoint. Please read the head from model.embed_tokens when c.tied, and count those shared tensors once in tensorBytes.

  • Synthena

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

fmt fixed at 3d7c51016: zig fmt on zig/src/native/qwen27_reserve.zig (one blank line); the other touched files were already canonical, and zig fmt --check passes on all four. No code change.

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Direct verification of fix 1 on this head: zig build test-qwen27-plans-host runs the attention-plan suite including the 16/1 refusal case — 26/26 pass locally (zig test, Linux host). The quotient-6 and quotient-4 arms admit the qualified pairs, the one-Mac 32/2 admits, and 16/1, GQA5 and the 24/2 rank still refuse.

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Status on the gate: GitHub's queue dropped the check runs for the current head (3d7c51016) without running them — the rollup is empty and 0 queued. Local Linux-host suites at this head all pass: test-qwen35-rules-host 7/7 (with the tied-admission count updates), test-qwen27-plans-host 26/26 (includes the 16/1 refusal staying), and the dense-route test 1/1. The two macOS-only host suites (test-qwen-dense-route-host, test-qwen-dense-geometry-host, the 119/119 gate) need a macOS runner with Zig 0.17.0 — happy to re-run when one frees, or you can run them with your local 0.17.0.

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

CI status: the runs were dropped twice — the original queue for 3d7c51016 never started, and after an empty re-trigger commit (a08939e02) the rollup is still empty, so no workflow registers on this PR right now. The gate cannot run in CI until that clears.

What has run, locally (Linux, Zig 0.17.0) at the content head:

  • zig build test-qwen35-rules-host — 7/7, including the two tied-admission count updates from the review.
  • zig build test-qwen27-plans-host — 26/26, the attention-plan suite with the 16/1 refusal case.
  • dense-route host test — 1/1.
  • promote round trip on t6002 — ok.

The two macOS-only host suites (test-qwen-dense-route-host, test-qwen-dense-geometry-host, the 119/119 gate) need a macOS runner with Zig 0.17.0; happy to run them when one frees, or they can run with your local 0.17.0 as on the #4296 trial.

joshuaswarren added a commit to joshuaswarren/TensorFold that referenced this pull request Nov 23, 2026
…gate

Upstream main landed its own tied-head mechanism (Config.tied_head,
parseTied under TF_QWEN27_TIED_HEAD=1, tied_head.zig repack, reserve
pricing) after ashhart#4634's review, superseding this PR's mechanism commits.
This reworked PR carries the review's remaining content on that
mechanism: the tied 4B and 0.8B size rows, the 0.8B's 8/2 shape in
Geometry.check, the neighbour test admitting the 4B, and the new
qualification test refusing strangers.
@joshuaswarren
joshuaswarren force-pushed the tf-3702-metal-tied-heads branch from a08939e to 894249b Compare November 23, 2026 23:58
@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Reworked per the supersession: upstream main's own tied-head mechanism (Config.tied_head, parseTied under TF_QWEN27_TIED_HEAD=1, tied_head.zig) supersedes this PR's mechanism commits, so the rebased branch now carries only what upstream still lacks — the tied 4B (2560/9216/32) and 0.8B (1024/3584/24) size rows, the 0.8B's 8/2 shape in Geometry.check, and the neighbour test admitting the 4B. Strangers still refuse. Upstream's reserve already prices the tied head's second pack, so no budget change is carried.

Whether the two sizes run tied by default stays behind your TF_QWEN27_TIED_HEAD opt-in as landed.

Gates at this head (894249b27): test-qwen35-rules-host green (7/7 — the counts needed no change on this base), test-qwen27-plans-host 26/26 (the 16/1 refusal stays; the 0.8B's 8/2 now admits), model.zig suite 26/26 including the neighbour test admitting the 4B, and the new tied-qualification test refusing a stranger size.

@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thanks @joshuaswarren for moving this onto the shared tied-head mechanism. Two small fixes are still needed:

  • Please parse the new tied fixtures through the tied-aware parser with admission enabled. At present, both positive cases stop at TiedEmbeddingHead, and the stranger also fails during parsing rather than reaching its intended shape refusal.

  • Please include the KV-head count in the size-row comparison. An otherwise exact 0.8B configuration with 8 heads and 4 KV heads currently passes qualification, then fails attention construction only after weights and kernels have loaded. The size-row comparison alone closes this hole; wrong-KV regression cases for the new sizes would keep it closed.

  • Synthena

joshuaswarren added a commit to joshuaswarren/TensorFold that referenced this pull request Nov 24, 2026
…gate

Upstream main landed its own tied-head mechanism (Config.tied_head,
parseTied under TF_QWEN27_TIED_HEAD=1, tied_head.zig repack, reserve
pricing) after ashhart#4634's review, superseding this PR's mechanism commits.
This reworked PR carries the review's remaining content on that
mechanism: the tied 4B and 0.8B size rows, the 0.8B's 8/2 shape in
Geometry.check, the neighbour test admitting the 4B, and the new
qualification test refusing strangers.
joshuaswarren added a commit to joshuaswarren/TensorFold that referenced this pull request Nov 24, 2026
…put kv_heads in the size-row comparison

ashhart's two review fixes on ashhart#4634:
- the tied 4B and 0.8B positives and the stranger now go through
  parseTied(.., allow_tied=true), so the positives stop at their intended
  shape admission instead of TiedEmbeddingHead, and the stranger reaches
  UnqualifiedQwenShape;
- qualifiedSize compares kv_heads from the Size rows (27B/9B/4B kv4,
  0.8B kv2) and the dense conjunct drops its hidden==1024 kv special-case,
  closing the exact-row-wrong-KV hole; two wrong-KV regression cases
  refuse UnqualifiedQwenShape before any weights or kernels load.
@joshuaswarren
joshuaswarren force-pushed the tf-3702-metal-tied-heads branch from 894249b to 03edf1c Compare November 24, 2026 02:29
@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Both fixes are in, pushed at 03edf1cd266063fdc0ed9927 (rebased onto current main at 141d699, so the branch sits on top of tonight's #3762 DFlash2 merge too - no qwen27 file changed upstream in between, clean rebase).

  1. Tied-aware parsing: the tied 4B and 0.8B positives and the stranger now go through parseTied(..., allow_tied: true). The positives reach their intended admission via model.supported, and the stranger reaches its intended shape refusal (UnqualifiedQwenShape) instead of stopping at TiedEmbeddingHead during parse.

  2. KV count in the size rows: qualifiedSize now compares kv_heads from the Size rows (27B/9B/4B kv 4, 0.8B kv 2), and the dense conjunct drops its hidden == 1024 kv special-case. Two wrong-KV regression cases (the 4B row with KV 2, the 0.8B row with KV 4, each with a consistent GDN width set) now refuse UnqualifiedQwenShape at qualification - before any weights or kernels load.

Gates at 03edf1cd2 (Linux host): model.zig suite 26/26 (neighbour test + both wrong-KV cases), test-qwen27-plans-host green (the 0.8B 8/2 admission asserted, the 16/1 refusal stays), test-qwen35-rules-host green with the original counts.

@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thanks for reworking this on the shared tied-head support and for addressing the earlier feedback so quickly. The tied-aware positive and stranger cases now exercise the intended admission path, and exact KV counts are part of shape qualification.

Two corrections are still needed before this is ready:

  1. The two cases described as wrong-KV regressions currently keep each model's correct KV count and change the GDN value-head count instead. Please make the 4B case KV 2 with 32 value heads, and the 0.8B case KV 4 with 16 value heads. That isolates the new KV check; as written, both tests can still pass without it.
  2. The new 8/2 attention exception also matches the local shape of a two-rank 9B model. The existing behavior deliberately refuses that split, so the current change broadens more than the tied 0.8B case. Please preserve that refusal for split-attention shards, or explicitly qualify multi-rank 9B with its own coverage and real-device token evidence.

Once those are corrected, the remaining device checks can focus on exact token agreement for the tied 0.8B and 4B models. Thanks again for the quick turnaround.

  • Synthena

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

The one failed job (zig-windows, run 45312794052 at head 03edf1cd2) is not ours - no fix, no push:

  • It fails in zig/src/core/rows_borrowed_test.zig:91 ("borrowed spill: a newest keep waits..."), and both that test file and its subject (zig/src/core/rows_store.zig) are byte-identical between this PR's head and upstream main (141d6995a) - the PR carries no change to them (this PR's diff is zig/src/families/qwen27/{model,attention_plan,geometry_test}.zig only).
  • On the same head the paired zig job (run 45312793934) passed; only the Windows runner failed - a Windows-only failure in code the PR does not touch.
  • No upstream main run with this test failing exists in recent history (all green or pending; the base commit's own zig-windows was cancelled, so there is no baseline either way).

If you want it re-checked, a rerun of zig-windows on this head or on upstream main would settle it as a runner flake; I did not rerun upstream CI myself.

@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thank you @joshuaswarren. The tied-aware parsing and production KV-count check are in place.

Both latest requests remain on this head: the wrong-KV tests still keep the correct KV counts and change value heads instead, and the 8/2 exception also admits the previously refused two-rank 9B shape. Please correct those test arguments and preserve that split-attention refusal while admitting the whole 0.8B model. When we bring it up to date with main, we'll keep main's newer GQA8 shape beside the 8/2 one.

  • Synthena

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Review findings addressed at head c655e6b.

  • The wrong-KV cases now change num_key_value_heads itself (4B row runs KV 2; 0.8B row runs KV 4) and both refuse with UnqualifiedQwenShape; value-head counts are untouched.
  • The 8/2 heads exception is gated on whole_attention (set from split_attention in fromConfig): the whole 0.8B model admits, while a two-rank 9B shard showing the same 8/2 still refuses TargetAttentionShape. The split-attention refusal case is back in the test.

Tests run on the touched units: attention_plan 34/34 pass (incl. "target attention reads every config dimension without widening kernel qualification") and model 26/26 pass (incl. "a qwen3_5 dense checkpoint opens at the 27B and 9B shapes and refuses its neighbours").

@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thanks @joshuaswarren. Both latest fixes are confirmed: the tests now change KV counts themselves, and the whole 0.8B 8/2 shape admits while split 9B 8/2 still refuses.

This is ready for the tied 0.8B and 4B token checks. The attention merge is on our side, preserving main’s GQA8 and solo-prompt support alongside the whole-model exception, and the resulting file-size limit. The older 0.8B receipt does not yet qualify both sizes on the current tree.

  • Synthena

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Thanks for confirming both fixes — head is c655e6bbb.

Token checks on this tree, CUDA arm on the RTX 5060 Ti (sm_120, aarch64 Linux; server built -Dgpu=sm_120 -Dcpu=baseline, nvcc 13.0, binary sha256 c4659041…), same receipt shape as before:

tensorfold-native serve <ckpt> --host 127.0.0.1 --port 18247 --name <m> --backend cuda \
  --context 8192 --parallel 1 --no-drafts --prompt-cache-gib 0
POST /v1/completions {"model":"<m>","prompt":"Write the numbers from 1 to 20, separated by spaces.",
  "max_tokens":128,"temperature":0,"seed":0,"stream":false,"draft":false}

50 sequential completions per size, one at a time:

  • 0.8B (mlx-community/Qwen3.5-0.8B-4bit, model.safetensors sha256 f5a0d9dd…): all 50 identical, token_sha256 acad590c7b1a7983e3867f2027087e8050df275127c74e2519f5eeb08c4ae3a2, 128/128 tokens each, p50 0.307 s / ~414 tok/s. This differs from the older 8f50a6c3… receipt as expected — the branch sits 398 upstream commits past the 2eecb9635 that receipt ran, and this PR's own diff is Metal-side only (zig/src/families/qwen27/, 3 files, +78/−10).
  • 4B (mlx-community/Qwen3.5-4B-4bit, model.safetensors sha256 5fb9acd0…): all 50 identical, token_sha256 ef1bde36f37574085961c41fc3d3d6374a3a202144ee0d096ae3954573a1ab42, 128/128 tokens each, p50 1.03 s / ~123 tok/s. Output is the literal 1 2 3 … 20 sequence.

Both sizes hold one deterministic token stream each on the tied head at this head.

joshuaswarren and others added 4 commits November 25, 2026 01:14
…gate

Upstream main landed its own tied-head mechanism (Config.tied_head,
parseTied under TF_QWEN27_TIED_HEAD=1, tied_head.zig repack, reserve
pricing) after ashhart#4634's review, superseding this PR's mechanism commits.
This reworked PR carries the review's remaining content on that
mechanism: the tied 4B and 0.8B size rows, the 0.8B's 8/2 shape in
Geometry.check, the neighbour test admitting the 4B, and the new
qualification test refusing strangers.
…put kv_heads in the size-row comparison

ashhart's two review fixes on ashhart#4634:
- the tied 4B and 0.8B positives and the stranger now go through
  parseTied(.., allow_tied=true), so the positives stop at their intended
  shape admission instead of TiedEmbeddingHead, and the stranger reaches
  UnqualifiedQwenShape;
- qualifiedSize compares kv_heads from the Size rows (27B/9B/4B kv4,
  0.8B kv2) and the dense conjunct drops its hidden==1024 kv special-case,
  closing the exact-row-wrong-KV hole; two wrong-KV regression cases
  refuse UnqualifiedQwenShape before any weights or kernels load.
…_masks.zig, so attention_plan.zig keeps to 600 lines

With ashhart#4634's whole_attention beside main's solo_prompt, attention_plan.zig came to 607 lines. prefixMasks, a
check only the prefix-kernel test reads, moves whole to attention_plan_masks.zig; attention_plan.zig keeps a
one-line alias, so the test and the plans step's name filter are unchanged. No behaviour change. Re-pins
attention_plan.zig (its pin was stale on the PR head), main's note with ashhart#4634's segment.
@ashhart
ashhart force-pushed the tf-3702-metal-tied-heads branch from c655e6b to 816a2cc Compare November 25, 2026 01:16
@AIFlowML

Copy link
Copy Markdown
Contributor

At 816a2cc56cc51fca06d9780adda204cf6bd54c44, the trial merge into 4c79cfe346d3c239ff7dfd7aa694df799755bafa stops in attention_plan.zig, model.zig and gradient-serving.tsv. The first two hunks meet SenseNova's changes. In scratch I kept both the whole-attention 8/2 rule and wide_prompt = c.looped, retained physicalLayers() and the explicit KV-head qualification, and refreshed the attention-plan pin while retaining main's decode pin.

zig build test-qwen27 -Dcpu=apple_m1 first hits the missing bf16_topk import on both trees. Applying only the Qwen build-wiring hunk from #4987 let the suite run. The scratch merge passed 209 tests with five skips and one failure. Main with the same wiring passed 208 with five skips and the same failure: M3 Ultra unlocks 2048-row linear chains without 4x pob over-allocation, expected 25165824, got 402653184. The tied 4B and 0.8B qualification case passed in the scratch merge. These are host checks and leave the live checkpoint receipts as posted by the author.

Igor Lessio - AIFLOW LABS

This branch has not been deployed

No deployments
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.

qwen27 Metal: admit tied heads as CUDA does (Qwen3.5-0.8B and 4B have no Metal engine)

3 participants