Repository navigation
Qwen3.8-27B on Macs without tensor units: --mtp-drafts drafts with the checkpoint's MTP head, through the lane core's drafter as on CUDA - #2464
Conversation
77077c7 to
046d0ba
Compare
|
One gap from the pair side (#1434): the refused set doesn't name a pair. A two-Mac serve with |
|
@akol1 yes please, thanks. A |
|
Thanks, @jschmied. This follows what #2368 settled: the 27B first, a head file converted from the release's
If you have an M1, M2 or M4, main-against-branch numbers there would help too. |
|
Thanks, @ashhart. All four are in eb801b5, a plain commit on 046d0ba.
Source: Run (numpy 2.5.4, Output: 238,934,744 bytes and 31 tensors, sha256 What the script does:
#!/usr/bin/env python3
"""Build mtp-4bit.safetensors for Qwen3.8-27B from a bf16 mtp.* shard. Run: python3 -I build.py SRC OUT (needs numpy, lib.py beside it)."""
import os,sys,json,struct
sys.path.insert(0,os.path.dirname(os.path.abspath(sys.argv[0])))
from lib import *
src,out=sys.argv[1:3]
QUANT={'mtp.fc','mtp.layers.0.self_attn.q_proj','mtp.layers.0.self_attn.k_proj','mtp.layers.0.self_attn.v_proj','mtp.layers.0.self_attn.o_proj','mtp.layers.0.mlp.gate_proj','mtp.layers.0.mlp.up_proj','mtp.layers.0.mlp.down_proj'}
_,h=hdr(src); keys=sorted(k for k in h if k.startswith('mtp.'))
assert len(keys)==15 and all(h[k]['dtype']=='BF16' for k in keys),keys
parts={}
for k in keys:
raw=tensor(src,k,np.uint16); b=k[:-len('.weight')]; L='language_model.'+b
if b not in QUANT:
# Qwen's RMSNorm scales by 1 + w: stored with the 1 added, as the 35B's MTP file and MLX's converted norms are
assert raw.ndim==1; parts[L+'.weight']=bf16_near((f32of(raw)+np.float32(1)).astype(np.float32)); continue
assert raw.ndim==2 and raw.shape[1]%64==0
r,c=raw.shape; g=f32of(raw).reshape(r,-1,64); assert np.isfinite(g).all()
s,z=scale_zero(g); q=np.clip(round_away((g-z[...,None])/s[...,None]),0,15)
parts[L+'.weight']=pack(q.reshape(r,c)); parts[L+'.scales']=bf16_near(s); parts[L+'.biases']=bf16_near(z)
assert len(parts)==31
order=sorted(parts,key=lambda k:(parts[k].dtype!=np.uint32,k)) # u32 first: every word 4-aligned in the file
meta={'__metadata__':{'format':'mlx'}}; off=0
for k in order:
a=parts[k]; meta[k]={'dtype':'U32' if a.dtype==np.uint32 else 'BF16','shape':list(a.shape),'data_offsets':[off,off+a.nbytes]}; off+=a.nbytes
j=json.dumps(meta,separators=(',',':')).encode(); j+=b' '*(-(8+len(j))%8)
tmp=out+'.tmp'
with open(tmp,'wb') as f:
f.write(struct.pack('<Q',len(j))+j)
for k in order: parts[k].tofile(f)
os.replace(tmp,out); print('wrote',out,os.path.getsize(out))
import json,struct
import numpy as np
def hdr(p):
with open(p,'rb') as f:
n=struct.unpack('<Q',f.read(8))[0]; return 8+n,json.loads(f.read(n))
def tensor(p,k,dt):
o,h=hdr(p); s,e=h[k]['data_offsets']
return np.fromfile(p,dtype=dt,count=(e-s)//np.dtype(dt).itemsize,offset=o+s).reshape(h[k]['shape'])
def f32of(u): return ((u.astype(np.uint32))<<16).view(np.float32) if u.dtype==np.uint16 else u
def bf16_near(x):
"""f32 to bf16 bits, nearest, ties to even."""
b=x.view(np.uint32); hi=(b>>16).astype(np.uint32); lo=b&0xffff
up=(lo>0x8000)|((lo==0x8000)&((hi&1)==1)); return (hi+up).astype(np.uint16)
def round_away(x):
"""round half away from zero, exact (Metal/C round(), not numpy's half-even)."""
t=np.trunc(x); return t+np.where(np.abs(x-t)>=0.5,np.sign(x),np.float32(0))
def scale_zero(v):
"""MLX affine on [..,64] groups of f32, as in mlx/ops.cpp; returns f32 scale, zero."""
lo=v.min(-1); hi=v.max(-1); st=np.maximum((hi-lo)/np.float32(15),np.float32(1e-7))
m=np.abs(lo)>np.abs(hi); s=np.where(m,st,-st); e=np.where(m,lo,hi)
q0=round_away(e/s); ok=q0!=0
s=np.where(ok,e/np.where(ok,q0,1),s); z=np.where(ok,e,np.float32(0))
return s.astype(np.float32),z.astype(np.float32)
def pack(q):
q=q.reshape(q.shape[0],-1,8).astype(np.uint32)
return (q<<(4*np.arange(8,dtype=np.uint32))).sum(-1,dtype=np.uint32)Other Macs: the only Mac I have is an M3 Pro (36 GB), so I have no M1, M2 or M4 numbers. The PR's numbers are main Checked on eb801b5 (M3 Pro): |
|
Thanks, @jschmied. All four points from our 7 Nov review are covered:
One thing is left: please paste
The CHANGELOG conflict is ours to settle when it lands, and @akol1's |
|
@ashhart both scripts are in my comment from 7 Nov, with the source shard's revision and sha256 and the output's: #2464 (comment) ( |
|
Thanks @jschmied. The scripts were already in your 7 Nov comment, with both sha256s, so that's all we need to rebuild the head file. Two things changed on main since this branch, so the rebase needs a little more than the CHANGELOG:
The CHANGELOG conflict is ours. Once it's rebased, the device checks listed on 8 Nov are next. |
eb801b5 to
28aa4bf
Compare
|
@ashhart thanks. Rebased onto main
Checks on |
|
Thanks @jschmied. The three points are covered:
We'll place the CHANGELOG line. |
28aa4bf to
b30faaf
Compare
|
@ashhart thanks, all four done. The head is now
|
|
Thanks @jschmied, all four are in. Each commit now builds on its own ( Main moved again after your push: #2436 landed the 27B's keys-only prompt tail, and
We'll place the CHANGELOG line. After the rebase we'll run the M5 Ultra (flag off against main, and the refusal) and |
b30faaf to
24698b8
Compare
|
@ashhart thanks, all three done. The head is now
|
|
Thanks @jschmied. The What's left is the run on
Please also refresh the description's checks and receipt. They still name
|
|
Thanks @ashhart. On
|
|
Thanks @jschmied, that covers everything on Nothing more is needed from you. Next we run the 8 Nov checks on an M3 Ultra Mac and the flag-off and refusal cells on an M5 Ultra Mac, and we'll place the CHANGELOG line.
|
, ashhart#2464, ashhart#2375, ashhart#2634) and adds row 29, DSpine (ashhart#2633) Rebased onto main after ashhart#2760's row 28 (Scale index), which stays as on main. DSpine is row 29 with ashhart#2633's final GB10 ranges: agent 2-20 % faster, chat and code 10-19 % slower.
|
Thanks @jschmied. The flag-off half of the M3 check is done: on an M3 Ultra at Next on the M3 is the flag-on half from our 8 Nov list: we build the head file with your
|
6cb2ffc to
1e212a6
Compare
|
I ran the M5 refusal cell on exact head With the flag omitted or set to zero, both loopback servers accepted the same two greedy requests at context 512 and parallel 1. The 26- and 180-token prompts produced identical token IDs, hashes and usage across settings. All four HTTP requests returned 200 and both servers drained. This covers the M5 refusal and plain rounds at one stream. The M3 flag-on tests still need that hardware. The trial merge into Igor Lessio - AIFLOW LABS |
354df84 to
455fc4d
Compare
…s on the runner's attention
…g slot 0's chains on Macs without tensor units
…t and the disk identity, no head pass in shared rounds
…4d4795 Main's b4d4795 (ashhart#2761) moved the prompt fit into qwen27_reserve.zig's reserve.fit and reserve.rows, the same memory.Fit as before. The previous commit's inline fit added the MTP head's keys and values to the ring term; this passes the same head_kv into reserve.fit's ring argument. Nothing else changes.
…does The head is a lanes.drafter.Drafter behind lanes.drafted.Drafted: per-stream contexts, a shared round's streams absorbed and chained in one pass a level, each draft priced by its chance. The Metal backend gives the drafter the last pass's tapped rows by slot (features, prepare_features); its MTP hooks go. A chain steps from the head's normed rows, as CUDA's does, and a head pass may run beside a round left to keep, which reads nothing it writes.
…it is on; docs for --mtp-drafts and TF_Q27_DRAFT_SLOTS
…L_KV_PAGES=1 The head's layer joins the runner's attention count and so the page arena, but its chained rows take no pages. The M5 refusal and this one are one host-tested function, checked before the head loads.
…ts own file Pure moves, no behaviour change: decode_round.zig and native/qwen27_served.zig are under 600 lines after the merge.
…pe names the K/V pages refusal
…rule, so decode_round.zig is under 600 lines Pure move: Runner.keysOnly and keysForward become prompt_tail.on and prompt_tail.keysForward; layerCaches is pub.
…ines Main's startup-line wording and the PR's MTP fields took this file to 605. Six standalone comments move onto their statements; no code, flag or token path changes.
main's kv_pages.on() now returns an error union, so the MTP device refusal takes try on pagesOn().
…rompt tail now declares block
455fc4d to
9d99036
Compare
|
Thank you @jschmied. This is merged into main with your commits under your own name, so you're listed as a TensorFold contributor. It ships in the next release, credited to you in the changelog and the release notes. |
What this changes
Before, Qwen3.8-27B on a Mac drafted only with DFlash2 (
--drafter), and the Metal build refused--mtp-draftsand--mtp-confidence. Now, on M1 to M4,--mtp-drafts Nloads the checkpoint's MTP head frommtp-4bit.safetensorsbeside it and drafts chains of up to N tokens for every stream, alone or in shared rounds.--mtp-confidencestops a chain where its cumulative chance falls below the floor, bycore/lanes/mtp_policy.zig's rule, with CUDA's flag names. It is off unless--mtp-draftsis given. Replies are byte-equal to"draft": false.Same structure as CUDA. The head is a
core/lanes/drafter.zigDrafterbehindcore/lanes/drafted.zig'sDrafted, asqwen3_5/cuda_mtp.zigis on CUDA. Only the head's forward is per backend.native/qwen27_mtp.zig:chances), so the core's depth rule and--mtp-confidencesize the verify windows.The chain steps from the head's output after
mtp.norm, as CUDA's does. The head reads the target's last-layer row before the final norm (tap layer 63), as CUDA's does (qwen3_5/cuda_mtp.zig).The target side (
native/qwen27_features.zig):prepare_featuresmakes the runner tap the drafter's layer;featuresgives a stream's rows from the last pass, which the runner now records by slot (decode_round.Runner.tapped: cache start, first frame row, rows). The Metal backend has no MTP code of its own.The head's forward runs through qwen27's own layer program, with no new kernels:
fcover [norm_e(embed(token)) | norm_h(hidden)] (embedding, two head norms,q27_tap_gatherfor the concatenation,fc);forward.Stages' pre, mixer and post at block indexlayers(forward.layerAt), on the runner's own attention;mtp.normand the shared head into the head's own logits buffer, so the target's rows stay readable.A head pass may run beside a round left to keep. The core asks a shared round's drafts before its keep; that keep reads only the target layers' bindings, the DeltaNet states and its own staging rows, none of which a head pass writes.
The head's keys and values are one more attention layer in the runner: its bindings and per-slot caches include it. Kept states, snapshots and disk states carry them, so a resumed prompt drafts as a fresh one does. The disk identity includes whether the head is on.
Refused by name:
--mtp-confidenceoutside 0 to 1, or without--mtp-drafts;--mtp-draftswith--drafter(DFlash2; the two are exclusive);mtp-4bit.safetensorsbeside it.The memory fit counts the head's keys and values per slot.
Issue: refs Proposal: MTP drafts on Qwen's Metal path: is it wanted, and on which checkpoint? #2368. Not done here:
TF_QWEN27_METAL_KV_PAGES=1(qwen27 metal: keys and values in core pool pages behind TF_QWEN27_METAL_KV_PAGES=1 (#1293) #2283's K/V pages, on main):--mtp-draftsis refused by name with it, since the head's layer is not paged.queue, plain mode) does not reach the head, as on CUDA; its next absorb starts at the target's row.Stacked on: main (33ada77); it merges cleanly with main cd6060a. No CHANGELOG commit (placed by the maintainer). Commits:
mtp-4bit.safetensorsbeside a deferred model.--mtp-draftsand--mtp-confidence, the served driver.DrafterbehindDrafted, as CUDA's does.--mtp-draftsandTF_Q27_DRAFT_SLOTS.--mtp-draftsrefused by name withTF_QWEN27_METAL_KV_PAGES=1.prompt_tail.zig), sodecode_round.zigis 586 lines.The branch touches (21 files, +900 −105):
How mtp-4bit.safetensors was made
mtp.*weights of nvidia/Qwen3.8-27B-NVFP4 at revision dbb8f445, file model-00003-of-00003.safetensors: 1,970,287,672 bytes, sha256 0506ad35dc21469708e7813bd76c592cef08bd0317b4a1fe899745ebe2435271, equal to the publisher's LFS oid. Its 15mtp.*tensors are BF16 (the NVFP4 quantization leaves the MTP layer in BF16).python3 -I build.py model-00003-of-00003.safetensors mtp-4bit.safetensors(numpy 2.5.4; build.py, 30 lines, and its helper lib.py, 26 lines; not part of this PR):mtp.fcand the layer's q, k, v, o, gate, up and down projections.language_model.mtp.*.Checks on this head
zig build native -Dcpu=apple_m1).python3 tools/zig/lean_check.py, throughtools/pr_check.py --base 33ada77c3: lean 386 vs 386, 0 new; pr_check 0 errors (one advisory warning: no Unreleased bullet, which the maintainer places).zig build test-qwen27 --summary all, with TF_QWEN27_DIR, TF_QWEN27_MTP_DIR and TF_QWEN27_MTP_PROMPT set: 46/46 steps, 187/189 tests passed, 2 skipped.zig build test-qwen27-mtp-flags-host: 3/3.zig build test-qwen27-startup-host: 2/2.mtp_load_test.zig: the head loads beside a deferred model (fc 5120×10240, an attention layer), a second load keeps it, and loading after the files close (MtpAfterFilesClosed) or without the file (MissingMtpFile) is refused. It skips without the environment.mtp_step_test.zig, on the target's own greedy continuation of a 22-token code prompt, 128 rows:qwen27_mtp_flags.zig: each refusal by name; no flag,--mtp-drafts 0beside--drafter, and the bounds are admitted.zig fmt --check build.zig zig: clean.git diff --check 33ada77c3 HEAD: clean. Files the branch touches: 586 lines at most.core/lanesis unchanged.Receipt
Environment, with the TensorFold commit, Zig and backend toolchain, machine and GPU, checkpoint and revision:
mtp-4bit.safetensors.zig build native -Dcpu=apple_m1; served withtensorfold-native serve. The Mac was in daily use.Paths and platforms the change reaches, which I ran and which I could not:
--mtp-drafts N(N > 0), on Qwen3.8-27B on Macs without tensor units. Without the flag no head loads, no drafter is in front, and the served path is main's.Exactness (earlier head):
tools/bench_concurrent.py --levels 1,3 --tokens 256 --reps 1 --temperatures 0,0.7 --alone --serial, prompts code and chat, served--parallel 3 --context 2048 --prompt-cache-gib 0 --mtp-drafts 3(the widest this Mac admits): every cell alone 1/1 at one stream and 3/3 at three, serial equal against"draft": false, greedy and seeded sampling, 0 failed.--parallel 1 --context 8192 --prompt-cache-gib 2 --mtp-drafts 3. A second turn resumed 1,536 and then 1,648 of its 1,678 prompt tokens. Both replies' token_sha256 e70a8a1b… equal a fresh cache-off server's, at the same decode rate (15.08 and 15.19 against 15.06 tok/s).Exactness on this head (24698b8), Qwen3.8-27B served
--parallel 1 --context 8192 --mtp-drafts 3:--prompt-cache-gib 0 --no-thinking, 256 tokens, each reply against"draft": falseon the same server. Same runs on b30faaf for comparison:"draft": falsetemperature1.0,top_p0.95,seed20464. Tokens a verify = tokens / rounds. Hashes, rounds and accepted counts are equal on both heads in all 12 cells, so the head's acceptance is unchanged by the keys-only tail on main: with MTP on, the last layer stays whole.--prompt-cache-gib 0.5, smaller than one slot's full state at 8,192 rows, so the server keeps a rewind buffer (slot 0 keeps a rewind point of 146 MiB at each prompt's history end). Thinking on:--parallel 3 --context 2048 --prompt-cache-gib 0,bench_concurrent.py --levels 1,2,3 --tokens 256 --temperatures 0, code and chat: 12 of 12 token_sha256 equal.Decode (earlier head), main against this branch, ABBA (main, MTP, MTP, main):
--parallel 3 --context 2048 --prompt-cache-gib 0, the branch adding--mtp-drafts 3.bench_concurrent.py --levels 1,2,3 --tokens 256 --temperatures 0, steady tok/s:MTP side by side with DFlash2 (earlier head), alternating (MTP, DFlash2, DFlash2, MTP):
--drafter-bits 4(prepared 4-bit). MTP:--mtp-drafts 3.--parallel 2and--parallel 3are refused at a 2,048-token context (and at 1,024 and 4,096), needing 5.0 to 5.7 GiB with 4.2 GiB left. So the comparison is at one stream only, served--parallel 1 --context 2048 --prompt-cache-gib 0,bench_concurrent.py --levels 1 --tokens 256 --temperatures 0:Prompt speed (earlier head): cold 4,096-token prompt, a fresh server per run, ABBA twice:
Licence of any new weights or drafter: the MTP head file is converted from nvidia/Qwen3.8-27B-NVFP4's
mtp.*weights; its licence is that checkpoint's, Apache-2.0 by its model card's metadata (read at the card's current revision 482ca0f383; the shard was taken at dbb8f445). DFlash2 (comparison only): Apache-2.0.Checklist
"draft": false, a resumed prompt equals a fresh one, and concurrent equals solo.--mtp-draftson (opt-in), main's without it.