Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 21 additions & 8 deletions app/serve.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@
// formats) on Vulkan0 (docs/lean.md)
// --mtp <head.gguf> on any llama.cpp route -> multi-token prediction: the model's MTP
// head drafts, the model verifies (docs/serve.md)
// --dflash <draft.gguf> on any llama.cpp route -> a DFlash block-diffusion draft model
// drafts a block per step (docs/serve.md)
// --mmproj <mmproj.gguf> on any llama.cpp route -> images: the vision encoder runs beside the
// model, and chat messages may carry image parts
// a Hugging Face id, --device mlx (macOS) -> lemon-mlx-engine's server
Expand Down Expand Up @@ -133,6 +135,7 @@ struct Options {
int prefill_min_tokens = 0;
bool lean = false;
std::string mtp;
std::string dflash; // DFlash block-diffusion draft model for the target
int moe_slots = 0; // --moe-slots N: stream routed experts from the model file, N held in RAM (-1: auto)
int moe_prefetch = 0; // --moe-prefetch N: gate-ahead prefetch N MoE layers ahead (0: off)
std::string moe_subst; // --moe-subst R: a resident expert scoring at least R x a missing one takes its place
Expand Down Expand Up @@ -600,8 +603,8 @@ Launch launch_for(const Options& o, const std::string& device, int child_port) {
if (device == "onnx") {
// ryzenai-server: `-m <dir> --port <p>`; the execution mode (CPU, NPU, hybrid) comes from
// the model's genai_config.json
if (o.parallel > 1 || !o.mtp.empty() || o.lean || !o.prefill_device.empty() || !o.mmproj.empty())
throw std::runtime_error("--device onnx takes no --parallel, --mtp, --lean, --prefill-device or --mmproj");
if (o.parallel > 1 || !o.mtp.empty() || !o.dflash.empty() || o.lean || !o.prefill_device.empty() || !o.mmproj.empty())
throw std::runtime_error("--device onnx takes no --parallel, --mtp, --dflash, --lean, --prefill-device or --mmproj");
argv = {default_onnx(), "-m", o.model, "--port", std::to_string(child_port)};
if (o.ctx_size > 0) { argv.push_back("--ctx-size"); argv.push_back(std::to_string(o.ctx_size)); }
return l;
Expand Down Expand Up @@ -692,12 +695,19 @@ Launch launch_for(const Options& o, const std::string& device, int child_port) {
if (device == "zinc" || device == "mlx" || device == "ds4") throw std::runtime_error("--parallel works on the llama.cpp devices (vulkan, hrx, rocm)");
argv.insert(argv.end(), {"-np", std::to_string(o.parallel)});
}
if (!o.mtp.empty()) {
// the MTP head drafts tokens on the same device; the model checks them in one batch
if (device == "zinc" || device == "mlx" || device == "ds4") throw std::runtime_error("--mtp works on the llama.cpp devices (vulkan, hrx, rocm)");
if (!o.mtp.empty() && !o.dflash.empty()) throw std::runtime_error("--mtp and --dflash are two drafters; pick one");
if (!o.mtp.empty() || !o.dflash.empty()) {
// the MTP head (--mtp) or a DFlash block-diffusion draft model (--dflash) drafts tokens
// on the same device; the model checks them in one batch
const char* flag = o.mtp.empty() ? "--dflash" : "--mtp";
if (device == "zinc" || device == "mlx" || device == "ds4") throw std::runtime_error(std::string(flag) + " works on the llama.cpp devices (vulkan, hrx, rocm)");
l.mtp = true;
argv.insert(argv.end(), {"--spec-type", "draft-mtp", "-md", o.mtp, "-ngld", "99"});
if (!o.mtp.empty()) argv.insert(argv.end(), {"--spec-type", "draft-mtp", "-md", o.mtp, "-ngld", "99"});
else argv.insert(argv.end(), {"--spec-type", "draft-dflash", "-md", o.dflash, "-ngld", "99"});
if (o.mtp_max > 0) { argv.push_back("--spec-draft-n-max"); argv.push_back(std::to_string(o.mtp_max)); }
// DFlash drafts a whole block per step and only pays with full blocks; llama-server's
// default draft length is 3, and it clamps a longer one to the drafter's trained block
else if (!o.dflash.empty()) argv.insert(argv.end(), {"--spec-draft-n-max", "16"});
if (!o.mtp_p_min.empty()) { argv.push_back("--spec-draft-p-min"); argv.push_back(o.mtp_p_min); }
}
if (!o.mmproj.empty()) {
Expand Down Expand Up @@ -798,6 +808,7 @@ int serve_child(const Options& o) {
Options overflow = o;
overflow.parallel = 16;
overflow.mtp.clear(); // batched requests gain little from drafting
overflow.dflash.clear();
overflow.llama_server.clear();
backends.push_back(launch_for(overflow, "rocm", free_port()));
} else if (!o.role.empty()) {
Expand All @@ -807,8 +818,8 @@ int serve_child(const Options& o) {
const std::string dev = o.device == "auto" ? "vulkan" : o.device;
if (dev != "vulkan" && dev != "hrx" && dev != "rocm")
throw std::runtime_error("--" + o.role + " runs on llama-server devices (vulkan, hrx, rocm), not " + dev);
if (o.adaptive || !o.mtp.empty() || !o.prefill_device.empty())
throw std::runtime_error("--" + o.role + " does not combine with --adaptive, --mtp or --prefill-device");
if (o.adaptive || !o.mtp.empty() || !o.dflash.empty() || !o.prefill_device.empty())
throw std::runtime_error("--" + o.role + " does not combine with --adaptive, --mtp, --dflash or --prefill-device");
Launch l = launch_for(o, dev, free_port());
const std::string batch = std::to_string(o.ctx_size > 0 ? o.ctx_size : 8192);
for (const std::string& a : {std::string("--") + o.role, std::string("-b"), batch, std::string("-ub"), batch})
Expand Down Expand Up @@ -1191,6 +1202,7 @@ void usage(FILE* out) {
" [--prefill-device hrx] [--prefill-min-tokens N] (with --device vulkan)\n"
" [--lean] ROCmFPX formats: ROCmFP4 on vulkan, ROCmI4 with --device rocm\n"
" [--mtp HEAD.gguf] [--mtp-max N] [--mtp-p-min P] multi-token prediction (vulkan, hrx, rocm)\n"
" [--dflash DRAFT.gguf] DFlash draft model instead of --mtp; --mtp-max/--mtp-p-min apply\n"
" [--moe-slots N|auto] [--moe-subst R] [--moe-prefetch N] stream MoE experts from the file,\n"
" N held in RAM (auto: what fits); R: resident experts stand in for missing\n"
" ones; prefetch N layers ahead (default 0) (vulkan; docs/moe-streaming.md)\n"
Expand Down Expand Up @@ -1233,6 +1245,7 @@ int run_serve(int argc, char** argv) {
else if (a == "--prefill-min-tokens") o.prefill_min_tokens = std::stoi(next());
else if (a == "--lean") o.lean = true;
else if (a == "--mtp") o.mtp = next();
else if (a == "--dflash") o.dflash = next();
else if (a == "--moe-slots") {
const std::string v = next();
o.moe_slots = v == "auto" ? -1 : std::stoi(v);
Expand Down
94 changes: 94 additions & 0 deletions blog/2026-09-28-qwen38-27b-dflash2-and-hadamard.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<!--
Copyright 2026 bong-water-water-bong
SPDX-License-Identifier: Apache-2.0

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
tags: qwen, speculative-decoding, quantization, rocm, vulkan

# Qwen3.8-27B at 45.7 tok/s: DFlash2 in `1bit serve`, and 4-bit activations with a Hadamard rotation

Qwen3.8-27B is a dense 27B model, and on Strix Halo its decode speed is set by memory
bandwidth: every token reads the whole 15 GB file, so plain decode sits near 11-12 tok/s.
Prompt processing is set by the GPU's matrix units instead. This week we pushed on both.
Every number below was measured on Strix Halo (Ryzen AI Max+ 395, Radeon 8060S), with the
method in the linked docs.

## Decode: DFlash2 drafts a whole block

Speculative decoding breaks the bandwidth limit by guessing several tokens and checking them
all in one pass of the big model. `1bit serve --mtp` already does this with the model's own
MTP head. [DFlash2](https://huggingface.co/z-lab/Qwen3.8-27B-DFlash2), from z-lab and Inco,
is a separate 2B draft model trained for Qwen3.8-27B. It emits a whole block of 8 tokens in
one pass, reading the big model's hidden states, and keeps the top 16 candidates at each
position so it can pick a coherent path through them. Upstream llama.cpp added it as
`draft-dflash`, and the Vulkan build the engine pins already carries it.

The new `1bit serve --dflash <draft.gguf>` wires it in. One detail mattered more than any
other: llama-server's default draft length is 3, and DFlash only pays when it drafts full
blocks. At length 3 it matched MTP; at full blocks it pulled well ahead. So `--dflash` now
drafts full blocks unless you say otherwise.

Qwen3.8-27B Q4_0 through `1bit serve --device vulkan`, decode tok/s on three chat prompts
(code / prose / short), back to back:

| Drafter | tok/s |
|---|---|
| none | 11.1 / 11.8 / 12.4 |
| `--mtp` | 31.7 / 25.8 / **28.2** |
| `--dflash` (DFlash2, Q8_0) | **45.7 / 28.3** / 17.8 |

That is 4.1x on code, and 44% over MTP. On prose DFlash2 edges ahead. On the short prompt,
a translation that ends after about 16 tokens, MTP still wins: there are too few tokens to
fill blocks. The drafter runs faster in Q8_0 than in BF16 (42.5 against 38.9 tok/s on code).
A drafted token is kept only when the model itself agrees, so the output is the model's own.
Converting the drafter needs only the target's config and tokenizer, not its weights
([docs/serve.md](../docs/serve.md#dflash-draft-models-dflash)).

## Prompt processing: 4-bit activations, rotated first

On the exact int8 path, prompt processing for this model tops out near 400 tok/s. The GPU
is not power-limited: it runs at about 158 W and 2.7 GHz through the whole prompt, and the
matmul kernel reaches about half of the int8 matrix rate. The matrix units run int4 × int4 at
twice the int8 rate, though, and ROCmFPX's W4A4 kernel uses exactly that instruction.

We pointed that kernel at Unsloth's plain Q4_0 file. A Q4_0 weight is already a 4-bit value
with an offset of 8, and flipping its top bit gives the same value in two's complement. So
the weights stay exactly what Unsloth shipped, and only the activations are rounded to 4 bits.
That is fast (461-488 tok/s) but lossy: mean KLD against the full model rose from 0.029 to
0.084. Leaving any single group of tensors at int8 did not fix it, because the error comes from
all of them.

A Hadamard rotation fixes much of it. A few large activation values in a block of 32 force a
coarse 4-bit scale on the other 31. Rotating each block by a 32-point Walsh-Hadamard transform
spreads that energy evenly before rounding. We rotate the weights the same way once, offline,
so the product is unchanged: on the exact int8 path the rotated file matches the plain one
(KLD 0.031 against 0.029). The rotation itself runs inside the activation quantizer, as three
lane shuffles and two in-register butterfly steps.

| Qwen3.8-27B Q4_0 on ROCm | pp512 | Mean KLD |
|---|---|---|
| exact int8 | ~400 | 0.029 |
| W4A4 | 461-488 | 0.084 |
| **W4A4, Hadamard-rotated** | **503** | **0.055** |

The rotation removes a third of the 4-bit error. Perplexity ends up 1.2% above the exact
path, and the error is still nearly double. So this is measured, not shipped: the patches are
not in the engine's pin yet ([docs/lean.md](../docs/lean.md)).

## What's next

DFlash2 is in `1bit serve` today. For prompts, the next steps are a better exact int8 matmul
for this GPU (about 15% would reach the W4A4 numbers without the error), and rotations
larger than 32, which spread outliers further. Packages ship on Sunday with the weekly
release.
27 changes: 27 additions & 0 deletions docs/lean.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,33 @@ stream uses about 200 of the bus's roughly 256 GB/s, and two different drivers f
gap better than two copies of one. Each stream slows down, so it pays for serving
several requests at once (one per backend), not for one chat.

## Experiment: W4A4 on plain Q4_0, with a Hadamard rotation (2026-09-28, not in the engine yet)

ROCmI4's W4A4 kernel can read Unsloth's ordinary Q4_0 files directly: a Q4_0 code `q` means
`q - 8`, and `q ^ 8` is exactly that as a signed 4-bit value, so the weights stay bit for bit
what Unsloth shipped and only the activations go to 4 bits. On Qwen3.8-27B that lifts prompt
processing from ~400 to 461-488 tok/s, but the 4-bit activations cost accuracy: mean KLD 0.084
against 0.029 for the same file on the exact int8 path. Keeping any one group of tensors
(`ffn_down`, or the FFN gate and up) on int8 did not help: the error comes from every group.

A 32-point Walsh-Hadamard rotation spreads each block's outliers before the activations are
rounded to 4 bits. The same rotation is applied to the weights offline, per 32-element block
along K, so `x . w = (Hx) . (Hw)` and every path stays exact in exact arithmetic: the rotated
file on the int8 path matches the plain one (KLD 0.031 against 0.029). The rotated file is
quantized from Unsloth's Q8_0 with Unsloth's imatrix (block means for the rotated tensors), and
the control is quantized from the same Q8_0 with the same settings.

| Qwen3.8-27B Q4_0, ROCm | pp512 | PPL | Mean KLD | Same top token |
|---|---|---|---|---|
| exact int8 | ~400 | 6.021 | 0.029 | 91.9% |
| W4A4 | 461-488 | 6.241 | 0.084 | 87.4% |
| **W4A4, Hadamard-rotated** | **503** | **6.096** | **0.055** | **89.3%** |

The rotation cuts the W4A4 error by a third, for +1.2% perplexity against the exact path.
Storing the 48 layers' small `ssm_alpha` / `ssm_beta` projections as Q4_0 (Unsloth keeps them
F32) moves them from an f32 GEMM onto the matmul kernel, which is part of the prompt gain.
KLD is against BF16 logits on wikitext-2 (40 x 512); pp512 from llama-bench, ub 512.

## Build

```
Expand Down
40 changes: 39 additions & 1 deletion docs/serve.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ OpenAI client.
[--device auto|npu|vulkan|hrx|rocm|zinc|ds4|mlx] [--ctx-size N] [--alias NAME]
[--llama-server PATH] [--zinc PATH] [--ds4 PATH] [--ssd-streaming] [--hrx-libhsa PATH] [--mlx-server PATH]
[--prefill-device hrx] [--prefill-min-tokens N] [--lean]
[--mtp HEAD.gguf] [--mtp-max N] [--mtp-p-min P] [--mmproj MMPROJ.gguf]
[--mtp HEAD.gguf | --dflash DRAFT.gguf] [--mtp-max N] [--mtp-p-min P] [--mmproj MMPROJ.gguf]
[--moe-slots N|auto] [--moe-subst R] [--moe-prefetch N]
[--parallel N] [--adaptive] [--adaptive-at N]
[--embed MODEL.gguf] [--rerank MODEL.gguf]
Expand Down Expand Up @@ -142,6 +142,44 @@ prompt. Adding n-gram drafting to MTP gains nothing. Small-active MoE models are
opposite case: on Qwen3-Coder-30B-A3B (3B active, 88 tok/s on Vulkan) every draft model
tried (Qwen3 0.6B / 1.7B / 4B) was slower than no drafting, even at 82-87% acceptance.

## DFlash draft models (`--dflash`)

`--dflash <draft.gguf>` uses a DFlash block-diffusion draft model instead of the MTP head: the
draft emits a whole block of tokens in one pass, reading the model's hidden states, and the
model checks the block in one batch. It turns on llama-server's `draft-dflash` (DFlash2's
candidate selector included). A drafter is trained for one target model; z-lab publishes them
on Hugging Face (for example
[z-lab/Qwen3.8-27B-DFlash2](https://huggingface.co/z-lab/Qwen3.8-27B-DFlash2), 2B, Apache-2.0).
`--dflash` and `--mtp` are exclusive. `--mtp-max` and `--mtp-p-min` set the draft length and
threshold for either; without `--mtp-max`, `--dflash` drafts full blocks (llama-server's own
default of 3 throws most of the gain away).

Convert the drafter with upstream llama.cpp's converter. It needs only the target's
`config.json` and tokenizer files, not its weights:

```sh
hf download Qwen/Qwen3.8-27B --include "*.json" "*.jinja" "merges.txt" "vocab.json" --local-dir Qwen3.8-27B-hf
hf download z-lab/Qwen3.8-27B-DFlash2 --local-dir DFlash2
python convert_hf_to_gguf.py DFlash2 --target-model-dir Qwen3.8-27B-hf --outtype bf16 --outfile dflash2-bf16.gguf
llama-quantize dflash2-bf16.gguf dflash2-q8_0.gguf Q8_0
1bit serve -m Qwen3.8-27B-Q4_0.gguf --device vulkan --dflash dflash2-q8_0.gguf
```

Measured through `1bit serve --device vulkan` on Strix Halo, Qwen3.8-27B Q4_0 (Unsloth), the
same three chat prompts as above (code / prose / short, decode tok/s), runs back to back on a
shared box, 2026-09-28:

| Drafter | tok/s | Prompt t/s (1,838 tokens) |
|---|---|---|
| none | 11.1 / 11.8 / 12.4 | 330 |
| `--mtp` (Q4_0 MTP head, draft length 3) | 31.7 / 25.8 / **28.2** | 267 |
| `--dflash` (DFlash2, Q8_0, full blocks) | **45.7** / **28.3** / 17.8 | 255 |

DFlash2 is the pick for code (4.1x, +44% over MTP) and ties or beats MTP on prose. MTP wins
short answers (the translation prompt stops after ~16 tokens, too few to fill blocks). The Q8_0
drafter is faster than BF16 (42.5 vs 38.9 on code, direct llama-server). A drafted token is
kept only when the model agrees, so the output is the model's own.

## MoE models larger than memory (`--moe-slots`)

`--moe-slots N` (with `--device vulkan`) keeps a MoE model's routed experts in the file and
Expand Down
3 changes: 3 additions & 0 deletions tests/smoke_serve.sh
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,8 @@ if [ "$(uname)" = Linux ]; then
check "no backend outlives serve (SIGKILL)" '! kill -0 "$child" 2>/dev/null'
fi

both=$("$bin" serve -m "$scratch/tiny.gguf" --device vulkan --mtp a.gguf --dflash b.gguf 2>&1); both_rc=$?
check "--mtp with --dflash is refused" '[ "$both_rc" != 0 ] && [[ "$both" == *"pick one"* ]]'

if [ $fail -ne 0 ]; then echo "--- serve log"; cat "$scratch/serve.log"; echo FAIL; exit 1; fi
echo PASS
Loading