Repository navigation
feat(qwen4): add opt-in low-RAM Host-MoE (Q3_A32/Q2_A32) with NPUxCPU overlap - #1269
This-Is-NPC wants to merge 2 commits into
Conversation
…native MTP speculative decoding
tawei-amd
left a comment
There was a problem hiding this comment.
Thanks for this. Running Qwen4-35B-A3B on 16-24 GB machines is a real gap: with ~18 GiB free, the 21 GB pinned expert set pushes main into swap, and decode is unusable there. We'd like to take the low-RAM path, but in a different shape. Requesting changes. Summary first, details below.
Proposed direction: a separate model tag, opt-in only
The Q3/Q2 expert modes change output quality a lot (numbers below), so they should never be picked automatically from MemAvailable. That makes output depend on whatever else is running at load time. Please:
- Ship the low-RAM mode as its own model tag, e.g.
qwen4-lowmem:35b-a3b, with its own HF repo holding the pre-quantized routed experts (imatrix-calibrated, produced offline by your quantizer).qwen4:35b-a3bstays exactly as it is today.-
Remove the
MemAvailableauto-selection and the load-time Q4_K -> Q3/Q2 requantization from the default path. -
The engine selects host-MoE because the package contains
.q3_a64/.q2_a32tensors (you already detecthas_prequant), not because of free RAM. -
If we want both a ~24 GB and a ~16 GB option, that's two tags (or one; let's decide from the KLD numbers).
-
Hosting: the weights for the new tag need to live in our official repos: Hugging Face
FastFlowLM/Qwen4-35B-A3B-lowmem-NPU2and ModelScopeamd/Qwen4-35B-A3B-lowmem-NPU2(final names TBD), like every other FLM model, soflm pullworks from both. Would that be possible on your side? Concretely, we'd need:- the pre-quantized package (or a link we can fetch it from);
- the exact recipe to reproduce it: quantizer command and profile, the imatrix file and how it was collected (calibration data), and the source checkpoint revision;
- your OK for us to redistribute it under the base model's license.
We'll rebuild it from the recipe, check that it matches, and do the HF/ModelScope upload ourselves. The model card will credit you.
-
- Report quality next to the speed table. We gate on top-100 KLD against BF16. The model card should state the trade-off plainly.
- Split MTP into a follow-up PR. By your own table it currently lowers decode (7.25 -> 6.01 tok/s), and the accept test isn't exact (see below). Happy to review it once a small-batch verify path makes it faster than plain decode.
- Source only: please drop
src/lib/xrt/libqwen4_moe_npu.so. CI builds the engine libraries.
Quality: what the Q3/Q2 modes cost
We measured llama.cpp stand-ins for your modes: q3_k for Q3_A64 and q2_k for Q2_A32_256, using your exact per-layer layout (mid layers 4..35, edges 0..3 / 36..39). Everything else uses the shipped recipe with an imatrix, quantized from BF16. Scores are teacher-forced against BF16 on 21 x 2048-token chunks of held-out text:
| mode | mean KLD | same top-1 | PPL ratio |
|---|---|---|---|
shipped qwen4:35b-a3b (Q4_K experts) |
0.033 | 92.8% | 1.004 |
q3 (your 24 GB auto mode) |
0.070 | 89.8% | 1.008 |
q2_hq (your 16 GB auto mode) |
0.131 | 85.9% | 1.037 |
q2 / q2_sweet |
0.161 | 84.6% | 1.043 |
These numbers are a lower bound. The current auto path requantizes from Q4_K at load time without an imatrix, which will score worse. Please run the same kind of KLD check on your actual kernels/packages. That's also how we'd choose between q3 and q2_hq for the tag.
Bugs to fix (in the low-RAM PR)
qwen4_moe_decode.cpp:929:a_sh_only/runs[il].sh_onlyare only created when!P.pst, butP.pstdefaults to true. After a persistent-decode stall or timeout,P.pstflips to false andmoe()executes the never-created run (lines ~1206/1213). That's a crash or hang. Always createsh_onlyfor host layers.qwen4_moe_forward.cpp:1809:postedis now true for anyT<=8.ple_productsthen runspar_foron the side thread concurrently with layer 0'spar_foron the main thread, for every small prefill tail. Before, this only happened forT==1, wherepar_foris serial. Keep the old condition unless the pool is shown to be reentrant.Makefile:36:CXX ?= g++-13is a no-op because make predefinesCXX. Useifeq ($(origin CXX),default).qwen4_moe_vnni.hpp:2701:h_f32[M_TOK][512]has no bounds check oninter. Add astatic_assertor runtime check. Also add the missing<cstdlib>(vnni.hpp) and<array>(mtp.cpp) includes; MSVC CI will need them.qwen4_moe_host.cpp:500: duplicateevict_mmap_pages(an exported copy of the static one at line 262). Delete it.qwen4_moe_decode.cpp:1096:experts_gate_up/down(il)dereference null for host-MoE layers. Throw a clear error instead.qwen4_moe_npu.cpp:61: please drop the hardcodedQwen4-35B-A3B-NPU2xclbin fallback. The new tag's package should carry, or reference, its xclbins through the normal model metadata.
Performance
- Host-MoE prefill (
eval_host_moe_batch) walks tokens in blocks of 8 and re-reads each active expert's weights per block. That's ~64x per layer on a 512-token chunk. Grouping the chunk by expert (per-expert token lists, tiles of 8) streams each expert once and should lift the 22-46 tok/s prefill a lot. - For the speed table, please include a machine with enough RAM as the reference. Main does ~15 tok/s decode there, so the comparison is 7.25 tok/s at 16-24 GB against 15 tok/s at 32 GB+, rather than "13.7x".
For the MTP follow-up (not this PR)
qwen4_moe_mtp.cpp:193:build_sparse_distbuilds its own truncated distribution (top 256 whentop_k<=0, own temperature/min_p/top_p order). The accept test must use the same distribution as the regular sampler, or speculative output is biased.qwen4_moe_npu.cpp:290: MTP state isn't reset on checkpoint restore, rows-only restore, or prefix-cache load.qwen4_moe_mtp.cpp:607:record_trunkadvancespos_baseonly by the trimmed part of each chunk. A 1000-token prompt advances it by ~360, not ~870, so RoPE positions drift.qwen4_moe_mtp.cpp:570: the full-max_lenK/V allocation at load and the ~60 MB-per-step snapshots work against the 16 GB target. Allocate lazily.modeling_qwen4.cpp:3267:sampler->temperatureis dereferenced whensampleris null (the line above guards it, this one doesn't).
Thanks again. The overlap of the NPU shared expert with host routed experts is a nice idea, and we'd be glad to see it land as the low-RAM tag.
…iew bugs & group prefill by expert
|
Thanks for the thorough review and the KLD stand-in numbers — super helpful! I have updated PR #1269 to follow your proposed direction (opt-in pre-quantized low-RAM tag only, source-only, MTP split out) and addressed every bug and performance item you flagged: Scope & bug fixes
Prefill optimization & quantization upgrade
Real KLD + speed table (measured on actual kernels/packages)Evaluated with the same top-100 KLD + tail-bucket metric as
Based on these numbers, Hosting & reproducible recipeYou have my full OK to redistribute the pre-quantized package(s) on Hugging Face ( Exact recipe to reproduce:
Let me know which profile ( |
|
Wow, thank you! That was a fast and really thorough turnaround. You covered every point from the first round within a day, and a few things stood out:
We'd love to ship this as a new model, The plan1. Quantize from BF16 with unsloth's imatrix. This is where we think the remaining quality is.
Could you extend
2. We can run the quantization here, if that works for you. We already have the BF16 checkpoint, the imatrix files and our KLD setup, so you wouldn't need a staging repo. We'd build the packages with your tool, share the numbers in this PR, and upload to 3. Then pick 3-bit or 2-bit together, from data. Your numbers point to
Then we'll post the results here and decide with you. Our guess today is 4. The A few fixes before mergeThese came out of a second pass over the new code. They're mostly about failing loudly instead of silently:
One number to double-checkYour table shows the shipped Performance ideas for later (not blocking)
On our side
Thanks again for driving this. Making a 35B model usable on 16-24 GB laptops is a real win for a lot of people, and the NPU-shared-expert + CPU-routed-expert overlap is a neat design. Let us know what you think of the plan! |
Summary
This PR builds directly on top of the merged Qwen4-35B-A3B engine (#1266) to add two complementary optimizations — 100% backward-compatible with the official
FastFlowLM/Qwen4-35B-A3B-NPU2checkpoint, vision tower, prefix cache,flm_state_api, andcausal_lmvtable ABI (144 B unchanged):1. 16 GB / 24 GB Mixed-Precision
imatrixHost-MoE (Q3_A64/Q2_A32_256) + Async NPU×CPU Overlap~450 MiB/layerofQ4_Krouted experts across 40 layers). On 16 GB / 24 GB machines (or 32–48 GB developer laptops with<23 GiBfree RAM), this pushes the memory-mapped 21 GB engram table and page cache into swap, collapsing decode throughput to~0.5 tok/s._mm512_dpbusd_epi32) mixed-precision host-MoE kernels inqwen4_moe_vnni.hpp:Q3_A64(asymmetric 3-bit, group-64, 28 B / 64 weights = 3.50 bpw)Q2_A32_256(asymmetric 2-bit, group-32 super-blocks, 84 B / 256 weights = 2.625 bpw, with optionalimatrix-weighted MSE-ALS calibration)P.gu[il]/P.dn[il]NPU BOs for host-MoE layers, reducing pinned NPU memory from 21.35 GB → 2.73 GB (-87.2%) and NPU weight packing time from 41.3 s → 3.0–7.0 s.sh_task(il)on the existingdecode.xclbin, zero new xclbins) with CPU router + top-8 + AVX-512 VNNI routed experts.MemAvailable < 16.5 GiB→q2_hq,16.5–23 GiB→q3,>= 23 GiB→ unchanged losslessQ4_Kon NPU), manual override viaFLM_QWEN4_MOE_QUANT=none|q3|q3_all|q2_hq|q2|q2_ultra,madvise(MADV_DONTNEED)eviction of dead on-the-flyQ4_Kmmap pages, and zero-copy mmap loading of pre-quantized.q3_a64/.q2_a32tensors.imatrixcollector (FLM_QWEN4_DUMP_IMATRIX) and streaming offline quantizer (tools/qwen4_q4nx_quantizer.cpp,make quantizer).2. Native MTP (
blk.40) Speculative Decoding (Greedy + Exact Stochastic Rejection Sampling)qwen4_moe_mtp.{hpp,cpp}andQwen4::_speculative_generate(...)inmodeling_qwen4.cppfollowing theQwen3_8MTPcontract (causal_lm::supports_speculation/speculate/last_speculation_prime_us, plusFLM_DISABLE_SPECULATION=1and chooser fallback for grammar/penalties/ignore_eos).mtp.q4nx(blk.40withQ3_A64routed experts + multilingual top-64KQ4_Kdraft LM head,~16–20 ms/draft). Silently inactive with zero overhead whenmtp.q4nxis absent.model::rewind_speculate) across all 30 GDN layers + layer-1 PLE conv history, plusstep_snapscapture duringmodel::forward.min(1, p(d)/q(d))) fortemperature > 0(top_k/top_p/min_p), achieving 60.4% draft acceptance (2.21 tok/cycle) at Qwen4's official default sampling (temperature=1.0, top_p=0.95, top_k=20).3. Minor Linux GCC 14+/16 Build Fixes
#include <climits>forUCHAR_MAXinnpu_cmd.hpp.CXX ?= g++-13overridable and auto-detected-mavx512vnniindetail/qwen4_moe_npu/Makefile.Live NPU Benchmarks (
/dev/accel/accel0, OfficialFastFlowLM/Qwen4-35B-A3B-NPU2)Measured on a Ryzen AI NPU2 Linux laptop with 18 GiB available RAM (real-world developer desktop workload), identical prompt (
--ctx-len 4096,/set r-eff none,/set gen-lim 160):mainbaseline (Q4_KNPU)Q2_HQHost-MoE + NPU×CPU OverlapQ2_SWEET(16 GB) Host-MoE + OverlapQ2_SWEET+ Native MTP (greedytemp=0)Q2_HQ+ Native MTP (defaulttemp=1.0, top_p=0.95, top_k=20)Verification
libqwen4_moe_npu.so,qwen4_q4nx_quantizer, andsrc/build/flmcleanly with zero errors.readelf -sWvtable size_ZTV13qwen4_moe_npu == 144bytes (exact ABI match withlibqwen3_8mtp_npu.so).Q3_A64andQ2_A32_256AVX-512 VNNI kernels +imatrixMSE-ALS gain (+0.0144cosine similarity /-26%MSE on outlier channels).FastFlowLM/Qwen4-35B-A3B-NPU2across baseline,Q2_HQ,Q2_SWEET, greedy MTP, and stochastic MTP (temp=1.0, top_p=0.95, top_k=20).(Follow-up optimization PR superseding #1267, rebased cleanly onto #1266.)