Skip to content

native: add Qwen3.5-2B MLX affine 4-bit support - #435

Merged
ashhart merged 3 commits into
ashhart:zig-previewfrom
JRaxworthy:codex/qwen3-5-2b-support
Oct 6, 2026
Merged

ashhart merged 3 commits into
ashhart:zig-previewfrom
JRaxworthy:codex/qwen3-5-2b-support

Conversation

@JRaxworthy

@JRaxworthy JRaxworthy commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

Adds native Zig/Metal text support for the pinned Qwen3.5-2B MLX affine 4-bit checkpoint, which the existing native engine rejects. Its tied embedding and output projection share the packed checkpoint buffer; the hybrid DeltaNet/full-attention forward integrates with the existing lane engine and native server. Ordinary chat replies also honor the tokenizer's chat EOS when it differs from the model config's end token. Implements the bounded proposal in #431; no separate dependent PR or unrelated optimization.

Draft: the implementation runs on the tested M5 Max, but the required full zig build test command cannot finish on this host because the Metal command-line compiler is unavailable. This receipt records the successful runtime checks and the remaining qualification work. It does not claim completed qualification on other Macs or CUDA. No response to the proposal issue has been received; additional maintainer landing requirements remain to be established during review.

Receipt

  • Environment: upstream zig-preview base 73cbd2f269c8771046f65d5b4630be25b8f86f17; contribution 5dc7d540d87cf1b95d84fa789d1d2ce4092bf2a6 (initial measurements at d400abbd43ba8d4b76b2cde83d597a4c5df73255). Mac Studio, Apple M5 Max GPU, 18-core CPU, 64 GB unified memory; macOS 27.0 / 26A428; Command Line Tools with macOS SDK 27.0. Zig 0.17.0, builds use -Dcpu=apple_m1; pkgconf 3.0.7. Python 3.12.14, MLX 0.32.3, mlx-lm 0.32.0, NumPy 2.5.3, transformers 5.18.0, pytest 9.1.1. Native decoding/tokenization does not invoke Python or MLX. Runtime Metal compilation uses the checkout's MLX compile settings (safe math, fp32 functions fast, Metal 4.1 on this OS). CLI metal/metallib are absent.

  • Checkpoint: mlx-community/Qwen3.5-2B-MLX-4bit, revision 93760be4f1f69842a46bc13dbdc0f19e291392a3; model.safetensors SHA-256 713fe7e5d3c3965f7106b0d0ee17615f7869c23c8d327996df8c1196fbcf07d5. Reused weights outside the source checkout. Affine 4-bit/group 64, bf16 scales/biases, 24 layers, hidden 2048, FFN 6144, vocabulary 248320. Eighteen Gated DeltaNet layers (16 heads × 128) and six full-attention layers (8 Q / 2 KV heads × 256), partial rotary dimension 64. The sanitized convolution layout is loaded directly; norm weights receive no extra offset.

  • Exactness: tools/bench_concurrent.py --alone --serial at its default 4 streams × 3 repetitions × 256 output tokens, both public prompts and temperatures 1.0 and 0: 48/48 concurrent-versus-solo comparisons and 10/10 solo-versus-draft:false comparisons equal; 0 unequal, failed or unmeasured. These comparisons use the server's existing token_sha field. An additional --mixed --levels 2,8 --reps 3 --tokens 128 --alone --serial --stagger-ms 37 run passed 30/30 concurrent-versus-solo comparisons and all 8 distinct solo-versus-plain comparisons (the same 8 references appear in each level's summary). Default drafts stayed enabled; context-copy proposals were accepted. For example, one sampled raw-code request and its plain repetition both produced b82953975509: drafted rounds=171 accepted=84/90, plain rounds=255 accepted=0/0.

    tf-qwen35-exact passed 49/49 full-forward/cache checks, comparing every bf16 logit and committed attention KV, fp32 recurrence, convolution state, accepted-row logits and cache length. Prefixes 0/127/128/129/255/256; windows 1/2/7/8/15/16/17/32; partial acceptance followed by continuation; unequal 7/13-row streams and different physical KV capacities. Runtime width qualification also checks two unequal 16-row streams and partial keeps against one-row execution before enabling wider lanes. A numerical mismatch retains one-row shared lane rounds with a warning; GPU failures stop loading. This preserves the preview's M1–M4 qualification.

    The server regression passed thinking on/off, automatic tools and tool-result history, leading/later instructions, a rewritten earlier answer, unequal concurrent conversations and top-k on/off sampling. All five conversations matched plain and concurrent token hashes; native rendered prompt counts matched the checkpoint template/tokenizer. Context overflow, media, forced tool choice and structured output were rejected, then a valid request still matched. Cross-request prompt reuse/resume is not implemented in the native preview: repeated/follow-up requests run afresh (cached_tokens=0). No restored-prefix exactness claim is made.

  • Decode speed before/after: the upstream native baseline rejects qwen3_5 before loading. Last release v0.6.5 (609ca419abecebdc5a059498a613680bd3aa847f) also rejects this checkpoint in its packed Python admission function because the embedding head is tied; that release function was evaluated against the actual checkpoint config. Thus both before baselines are unsupported, with no throughput or improvement ratio. After measurements below are from unmodified tools/bench_openai.py --tokens 64 --reps 5 --temperatures 1.0,0, default warm-ups, seeds 1234–1238, drafts on, no competing validation/build work.

Public prompt Temperature Before After median tok/s All five tok/s Median TTFT ms
fibonacci-raw 1 Unsupported 182.92 182.92, 182.61, 182.40, 184.40, 183.18 9.58
gpu-chat-no-think 1 Unsupported 182.28 182.28, 182.63, 181.88, 181.08, 182.39 13.60
fibonacci-raw 0 Unsupported 185.34 185.02, 185.57, 187.97, 185.34, 184.86 9.58
gpu-chat-no-think 0 Unsupported 184.71 185.66, 184.15, 184.71, 186.87, 179.01 13.37
  • Prompt speed before/after: same unsupported baselines. After: public Python-standard-library fixtures built with tools/prefill_cold.py build; unmodified tools/prefill_cold.py run, default 2k/8k/16k/32k/64k lengths, three repetitions each, one 1k warm-up, two reply tokens, greedy/no thinking. Server context 70,000, parallel 8, prompt chunks up to 128, drafts enabled. Every measured request completed with positive endpoint prompt usage and two output tokens; all server receipts have cached=0. These are whole-request client TTFT and the tool's prompt-tokens/TTFT rate, including dependent attention and recurrence, rather than isolated kernel throughput. Measurements ran sequentially after all builds/tests; earlier runs that overlapped compilation were discarded. One nominal 8k fixture contains 8,191 actual tokens; the others contain the nominal count.
Nominal prompt tokens Before After median TTFT s Tool prompt tok/s All three TTFT s
2048 Unsupported 0.597 3428.8 0.5989, 0.5973, 0.5939
8192 Unsupported 2.736 2994.3 2.7319, 2.7359, 2.7497
16384 Unsupported 6.509 2517.0 6.5082, 6.5094, 6.5177
32768 Unsupported 17.628 1858.9 17.6278, 17.6355, 17.6070
65536 Unsupported 60.308 1086.7 60.3007, 60.3322, 60.3081

There is no before/after speed-up claim and no comparison claiming to outperform MLX. An independent same-machine backend comparison used the same two public fixtures, preloaded stock mlx_lm.stream_generate, greedy/no-thinking settings, 64 output tokens, ignored EOS and a 256 MiB MLX allocator cache behind a serial HTTP wrapper. Unmodified tools/bench_openai.py::stream made five measurements per prompt per block in native/MLX/MLX/native process order. MLX decode medians were 298.98 tok/s (raw code) and 309.18 tok/s (chat), versus native 181.98 and 190.30 tok/s. Native first-visible-token medians were 10.41/13.81 ms versus MLX18.90/20.21 ms. This comparison establishes support rather than a general speed advantage over MLX; it is a warm component benchmark, not a whole application or hardware-interference qualification. ABBA comparison ordering cannot be applied to an unsupported before engine. The native preview has no prompt reuse, so these cold figures do not describe cached follow-up turns. The configured 262,144-position maximum is not a memory/throughput qualification at that length.

  • Tests run: isolated .[test,tui] environment. Before full python -m pytest -q tests: 5,057 passed, 10 failed, 627 skipped, 6 subtests passed (597.57 s). Initial after suite: 5,061 passed, 10 failed, 627 skipped, 6 subtests passed (576.31 s). After independent peer review and the EOS repair, the complete suite with pinned weights/native tools reports 5,062 passed, 10 failed, 627 skipped, 6 subtests passed (338.12 s). The 10 failure names are unchanged: TUI small-logo snapshot; GLM fused index scores; seven test_tree_forward_fused_equals_unfused shapes and test_models_of_other_widths_in_one_process. No unrelated fixes are bundled. The final focused native suite, including the subsequently added server regression, passed 5/5, 0 failed/skipped (33.47 s); without the model dependency it passed 2, skipped 3, failed 0. The capability assertion fails against the saved pre-change native binary (no Qwen family); the baseline cannot build/run the new operation/forward tools.

    zig build native test-native check-generated tf-qwen35-check tf-qwen35-forward tf-qwen35-exact -Dcpu=apple_m1: 20/20 build steps, 1/1 test passed. Fresh-cache zig build test: 38/38 runnable tests passed, including shared parser/loader and sampler tests, but 16/24 build steps succeeded, 3 failed at xcrun metal and remaining dependent steps did not run. This command did not pass. A direct shared Metal checkpoint test also passed 3/3, 0 failed/skipped, checking unchanged full-shard views versus selected namespace views, retained bytes, relative offsets, absent namespaces and duplicate cleanup. Generated sources and Zig formatting checks and git diff --check pass. Host CUDA/shared-core tests run within the Zig host target; CUDA GPU tests skip without their dependencies/hardware.

    Independent ordinary-chat regression: before the repair, a greedy request to reply with the word amber produced amber<|im_end|>\n. The native text loader returned config EOS248044 before reading tokenizer EOS248046. It now retains declared model end IDs and adds the tokenizer EOS without duplicates, as the MLX tokenizer wrapper does. The added real-model server assertion fails before and passes afterwards, with draft/plain equality; all five native tests pass in the latest complete suite. The direct native text host test passes1/1 and checks distinct IDs, same-ID deduplication, added-token object syntax and tokenizer-only fallback. Independent original focused suite also passed5/5 (81.61 s). A subsequent zig build test reported9/9 executed host tests passed, other host tests cached,16/24 build steps succeeded and the same3 unavailable CLI-Metal compilation failures. This remains an incomplete command, not a full pass. The repair changes stop selection, not forward arithmetic; the fixed-length measurements above use ignore_eos:true and remain labeled with their original measured commit.

    Operation bring-up passed 109/109, 0 failed/skipped, with 93 checkpoint weight bindings checked by SHA-256. Exact captures validate native binding against the generated arithmetic and do not independently establish model fidelity. Separately, 112 stock-MLX operation comparisons were finite; maximum relative L2 difference was 0.008466 (row-one packed projection), with maximum absolute difference 0.03125. Rotary, embedding and cache-layout comparisons were exact in these captures.

    Trusted model fidelity: teacher-forced next-token NLL/top-one logits use stock mlx_lm with the same weights/tokenizer, independently of the native forward. Stock execution at one-row, 32-row chunks and full prompt supplies its own variation control. All native logits were finite; no cross-backend bitwise requirement was imposed.

Public fixture Tokens Native NLL MLX one-row NLL MLX chunk-32 NLL MLX full NLL Native/one-row top-1 MLX chunk/one-row top-1
fibonacci-raw 14 3.037712481 3.021992960 3.003202329 3.003202329 100.0000% 100.0000%
gpu-chat-no-think 31 2.728734356 2.722023307 2.741829814 2.741829814 100.0000% 100.0000%
public-contribution-guide-512 512 3.681377972 3.681148021 3.681162759 3.678870107 96.8750% 97.0703%
python-stdlib-2048 2048 1.440262262 1.439450994 1.439515494 1.439953699 98.8770% 98.7793%

The longer fixtures use the first 512 tokens of this base's public CONTRIBUTING.md and the first 2,048 tokens of the benchmark helper's public Python standard-library corpus (Python 3.12.14). No private prompts or fixtures. Maximum native-versus-stock one-row RMS logit difference across fixtures was 0.071394; maximum absolute difference was 1.515625. These measured differences are comparable to the reported stock shape variation on these fixtures; this is limited fixture evidence, not universal equivalence or a model-quality improvement claim.

Fidelity input token SHA-256 values
  • fibonacci-raw: b3fd1dfdf7de931abd0762f111185cd194b859ed6572c91c62c7ec8ccffb950d
  • gpu-chat-no-think: d3c4dba98f8291245251a7cf40145ee22ec9641b86a32e38a118c0241a92fce2
  • public-contribution-guide-512: df87f87833e33efa04b66eb39b4845dceae31e395354dddbbf42660d4e169045
  • python-stdlib-2048: d238f329029b6b204cf8886eda2bd67215fa53722e38d19806eac3e868d1bf63
  • Precision/arithmetic: bf16 activations, scales/biases and logits; fp32 projection accumulation and persistent DeltaNet recurrence. No duplicated tied head, weight expansion or precision change. Fixed eight-row simdgroup projection tiles preserve a row's FMA chains across prompt/window widths; their dequantization/FMA and reduction order differs from stock shape-selected quantized matmul. Norm/silu/gating reductions use the existing row arithmetic; DeltaNet Q/K normalization uses the stock model's epsilon convention (RMS epsilon 1e-6/128), and attention uses fixed causal 128-position partitions. These choices change cross-backend bits at the same precision and are disclosed in the recipe. The existing Python and Nemotron arithmetic is not changed.
  • Not run, and why: full Zig helper/metallib tests need the unavailable Xcode Metal command-line toolchain; their three compilation steps fail before test execution. No full-suite-pass claim. M1–M4, other M5/macOS/runtime combinations and CUDA GPUs were unavailable. No existing Nemotron checkpoint is present for an end-to-end native model regression; shared full-shard loader tests and the existing Python/host suites provide the available regression evidence. Native restored-prefix execution is absent. No optional physical-memory measurements or MLX server performance benchmark are claimed. No 262k prompt, other model/format, image/video or MTP-head qualification. Forced tool choice and grammar-constrained output remain unsupported native-server features and are explicitly rejected.
Checkpoint / hardware Status
Pinned Qwen3.5-2B affine 4-bit/group-64, M5 Max/macOS 27.0 Native operations, trusted forward, full cache/rollback and server exactness tested; prescribed decode/cold benchmarks measured. Full CLI-Metal suite remains unmet.
M1/M2/M3/M4 Untested for this model; simdgroup kernels do not require M5 tensor units. Preserve the preview's unresolved exactness qualification.
M5 on other OS/runtime versions Untested.
CUDA / non-Apple native Qwen engine Unsupported in this patch; no CUDA Qwen engine is introduced. CUDA GPU regression for shared parser changes untested.
Other checkpoint revisions, quantization formats/sizes, vision/video Outside qualified scope.

Remaining landing work: run the complete zig build test with the documented Metal toolchain; review the unchanged Python failures; qualify available M3/M5 hardware and the shared-parser CUDA path, with broader M1/M2/M4 validation as available. The portable recipe and operation/fidelity/cache tools are included for those reruns. An M5 result does not establish support on other Macs. The proposal/PR are the contribution-guide coordination; no separate outside contact is needed.

Portable build/run instructions: docs/recipes/qwen3.5-2b-native.md documents the pinned download outside the checkout, Zig 0.17.0/Metal requirements, native build/server launch, optional-dependency handling and public verification commands. Use the native binary directly on this preview branch; no Python-only fallback is presented as native support.

zig build native -Dcpu=apple_m1
zig-out/native/bin/tensorfold-native serve "$HOME/models/qwen35-2b" --name bench --port 8090 --parallel 8 --context 70000 --no-thinking
python tools/bench_concurrent.py http://127.0.0.1:8090 bench --alone --serial
python tools/bench_openai.py http://127.0.0.1:8090 bench --tokens 64 --reps 5 --temperatures 1.0,0
python tools/prefill_cold.py build "$HOME/models/qwen35-2b" prompts.json
python tools/prefill_cold.py run http://127.0.0.1:8090 bench prompts.json out.json

Checklist

  • Every token still goes through the lane rounds. No serial path, and nothing that needs drafts off.
  • Drafted output equals "draft": false, a resumed prompt equals a fresh one, and concurrent equals solo. Draft/plain and concurrent/solo pass on the tested M5; cross-request resumed native execution does not exist, so the full item is not marked complete.
  • No precision traded for speed. If the bits change, the description says which sums change and why.
  • Prompt processing is no slower than the last release. This checkpoint is unsupported by both before baselines; no comparative improvement or non-regression throughput claim is possible.
  • The description says which platforms I ran, Metal M1 to M5 and CUDA, and which I could not.
  • New tests fail before the change, pass after it, and skip cleanly without their dependency. The admission regression demonstrably fails before; new native tools cannot be built on that base. The final five tests pass after and dependency skips are verified; no blanket before-run claim for all new tools.
  • Comments and docstrings are one line. No measurements or history in the source.
  • No personal data, machine names, internal hosts or local paths. No AI attribution lines.

@ashhart

ashhart commented Oct 6, 2026

Copy link
Copy Markdown
Owner

Thank you, @JRaxworthy. The receipt is honest about what it couldn't run: zig build test needs the Metal command-line compiler you didn't have, so it claims only the runtime checks that did run on your M5 Max, including the tied embedding and output head sharing one packed buffer.

This is Zig work, so it's reviewed for landing rather than rewritten. Before it can land it has to pass the gates your receipt lists as remaining: zig build test and zig build native with the compiler, the op checks against MLX, teacher-forced agreement against the same checkpoint, and the lane receipts (window equality, partial acceptance and rollback, unequal stream lengths). The chat end-token change gets reviewed with it, since it touches replies beyond the 2B. We'll keep this open while that runs, and the family carries your credit.

@ashhart

ashhart commented Oct 6, 2026

Copy link
Copy Markdown
Owner

Thank you, @JRaxworthy. Your Qwen3.5-2B family is merged into zig-preview as your own three commits (tip 5dc7d54). We've been building on it for speed, and those changes will come to the public Zig branch with your work as the base.

jschmied pushed a commit to jschmied/TensorFold that referenced this pull request Oct 7, 2026
…joins everything on zig-flashnext

# Conflicts:
#	ZIG-PREVIEW.md
#	build.zig
#	zig/src/core/checkpoint_metal.zig
#	zig/src/native/metal.zig
#	zig/src/tensorfold.zig
BlivionIaG pushed a commit to BlivionIaG/TensorFold that referenced this pull request Oct 20, 2026
…joins everything on zig-flashnext

# Conflicts:
#	ZIG-PREVIEW.md
#	build.zig
#	zig/src/core/checkpoint_metal.zig
#	zig/src/native/metal.zig
#	zig/src/tensorfold.zig
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