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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ Windows and 1bit OS ([docs/releases.md](docs/releases.md)).
> ([docs/vulkan.md](docs/vulkan.md#zaya1-zyphra-from-our-llamacpp)); the rest of Zyphra's
> family (Zamba, Zamba2, BlackMamba) runs on Vulkan too, and so do its vision models, ZAYA1-VL-8B
> and Zamba2-VL, through `1bit serve --mmproj`. Qwen3.8-27B runs in one ROCm server with Hadamard
> W4A4 prompt processing and DFlash2 decode: 477 tok/s on a 1,838-token prompt and 41.1 tok/s
> W4A4 prompt processing and DFlash2 decode: 516 tok/s on a 1,800-token prompt and 42 tok/s
> decode on code ([docs/lean.md](docs/lean.md#hadamard-rotated-q4_0-w4a4-prompt-processing)). W4A4 covers MoE
> experts too, and `1bit serve --long-model` sends long prompts there and short ones to Vulkan: on
> Qwen3-Coder-30B-A3B a 16K-token prompt gets its answer at 13.1 effective tok/s against 8.6 on
Expand Down
25 changes: 19 additions & 6 deletions docs/lean.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,17 @@ The rotation removes a third of the 4-bit error. Against the exact path the rota
with delta-net layers (Qwen3.8, Qwen3.6) uses on ROCm: a delta-net prefill kernel that keeps
each state column's rows in registers and stages the per-token inputs in shared memory, and a
tiled transpose for the concatenation that feeds the delta-net convolution. Both pass
`test-backend-ops` against the CPU (GATED_DELTA_NET 42/42, CONCAT 129/129).
`test-backend-ops` against the CPU (GATED_DELTA_NET 54/54, CONCAT 129/129).

A KernelForge campaign later made the delta-net prefill kernel 5-7x faster, at 3.02 -> 0.41 ms per
512-token layer (ROCmFPX#5, [tools/kernelforge](../tools/kernelforge/README.md)). It uses:

- DPP reductions instead of shuffles;
- two state columns per lane, which halves the shared-memory reads;
- rows interleaved across banks;
- 16-byte staging.

The rotated 27B's prompt gains about 11% with or without a drafter (the table below).

**One server: W4A4 prompts and DFlash2 decode.** Without a drafter this route decodes
Qwen3.8-27B at about 13 tok/s. With the DFlash2 drafter ([serve.md](serve.md#dflash-draft-models---dflash))
Expand Down Expand Up @@ -292,14 +302,17 @@ The same ROCmFPX change also fixed the drafter's input on long prompts: the mode
for a batch of several micro-batches were all written at the first one's place, so the DFlash
(and EAGLE3) encoder read stale features for all but the last.

Measured through `1bit serve` on Strix Halo, 2026-09-29, quiet box: the 1,838-token prompt (best
/ median of 5, as `serve` reports it, context checkpoints included) and 256 tokens of greedy
decode on the code / prose / short prompts of [serve.md](serve.md) (best of 3):
Measured with [`tools/bench.py`](bench.md) through `1bit serve` on Strix Halo, 2026-09-29, 2
interleaved rounds under the box lock. The prompt is its default (the first 8,000 characters of
`docs/*.md`, about 1,800 tokens; best / median of 10, as `serve` reports it, context checkpoints
included). Decode is 256 greedy tokens on the code / prose / short prompts (best / median of 6):

| Qwen3.8-27B-Q4_0-H32, lean ROCm route | Prompt t/s | Decode tok/s |
|---|---|---|
| no drafter | 497 / 495 | 13.2 / 13.2 / 13.6 |
| `--dflash` (DFlash2 Q8_0) | **477** / **472** | **41.1** / **26.7** / 15.0 |
| no drafter | 558 / 550 | 13.2 / 13.2 / 13.6 |
| `--dflash` (DFlash2 Q8_0) | **521** / **516** | **42.1** / **24.9** / 13.6 |

Before the prefill kernel of ROCmFPX#5, the same run measured 502 / 494 and 470 / 467.

Mean accepted block: 6.54 tokens on code, 4.23 on prose, in line with upstream on this drafter
(6.71 / 4.25). Greedy output matches the no-drafter run on the code and short prompts; on prose
Expand Down
2 changes: 1 addition & 1 deletion docs/serve.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ drafter is faster than BF16 (42.5 vs 38.9 on code, direct llama-server). A draft
kept only when the model agrees, so the output is the model's own.

`--dflash` also works on the lean ROCm route: a Hadamard-rotated Q4_0 file gets W4A4 prompt
processing and DFlash2 decode from one server, 477 t/s prompt and 41.1 / 26.7 tok/s decode
processing and DFlash2 decode from one server, 516 t/s prompt and 42.1 / 24.9 tok/s decode
([lean.md](lean.md#hadamard-rotated-q4_0-w4a4-prompt-processing)). `--dflash` sets
`--spec-draft-p-min 0` unless `--mtp-p-min` is given, and without `--mtp-max` drafts the
drafter's block minus one (its `dflash.block_size`; 16 when the file does not say).
Expand Down
2 changes: 1 addition & 1 deletion third_party/llama.cpp-rocmfpx
27 changes: 27 additions & 0 deletions tools/kernelforge/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,33 @@ A kept kernel is only a candidate. It goes back into ROCmFPX's `gated_delta_net.
has to pass `test-backend-ops -o GATED_DELTA_NET`. Then it is measured through `1bit serve`
with [`tools/bench.py`](../../docs/bench.md).

## Results

**gdn-prefill, 2026-09-29.** A 2-hour campaign, about $33 of Claude usage, kept 2 changes: 7.47x on
the task's own benchmark (2.95 -> 0.40 ms). One part of them was wrong. A gate-factored state
turned NaN with hard gates: about 1.1 million non-finite values with log-gates in [-20, 0). The
task driver's gentler gate range had let it pass. The rest went into ROCmFPX#5:

- DPP reductions on RDNA;
- two state columns per lane;
- rows interleaved across banks;
- 16-byte staging.

| Result | Before | After |
|---|---|---|
| One layer, 512 tokens | 3.02 ms | 0.41 ms (7.4x) |
| Same, with 8 snapshots | 2.46 ms | 0.49 ms (5.0x) |
| Qwen3.8-27B-H32 serve prompt | 484-495 tok/s | 542-555 tok/s |
| Same, with DFlash2 | 456-465 tok/s | 510-522 tok/s |

The driver now draws gates from ggml's own test range. Two setup traps:

- **Login.** KernelForge runs its planning and implementer sessions as `claude --bare`, which
ignores a logged-in subscription and accepts only an API key. Our Hyperloom checkout on strixhalo
carries a local switch, `FORGE_CLAUDE_OAUTH=1`, that drops `--bare`.
- **Stale process check.** `pgrep -f "kernelforge forge-loop"` also matches the ssh command that
runs it.

## Check a task without KernelForge

```sh
Expand Down
4 changes: 3 additions & 1 deletion tools/kernelforge/gdn-prefill/driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ def r(*shape):
q = torch.nn.functional.normalize(r(T, Hk, S_V), dim=-1)
k = torch.nn.functional.normalize(r(T, Hk, S_V), dim=-1)
v = r(T, H, S_V)
g = -torch.rand(T, H, generator=gen) * 0.5 # log decay, as the model's gate produces
# log decay over ggml's own test range (test-backend-ops GATED_DELTA_NET): hard gates make any
# product of gates underflow, which a gentler range let a campaign miss (tools/kernelforge/README.md)
g = -1e-4 - torch.rand(T, H, generator=gen) * (20.0 - 1e-4)
beta = torch.sigmoid(r(T, H))
state = r(H, S_V, S_V) * 0.1
return [t.to(device=device, dtype=torch.float32).contiguous() for t in (q, k, v, g, beta, state)]
Expand Down
158 changes: 120 additions & 38 deletions tools/kernelforge/gdn-prefill/gdn_prefill_kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"""The gated delta-net prefill kernel, the target a KernelForge campaign optimizes.

A standalone copy of gated_delta_net_prefill_cuda from the engine's ROCmFPX pin
(ggml/src/ggml-cuda/gated_delta_net.cu, ROCmFPX#1 and #4), for gfx1151 (Strix Halo). One call
(ggml/src/ggml-cuda/gated_delta_net.cu, ROCmFPX#1, #4 and #5), for gfx1151 (Strix Halo). One call
runs a whole micro-batch of tokens through the delta rule for every value head:

for each token t, head h, state column c (S is kept transposed: S[h][c][i]):
Expand All @@ -41,93 +41,175 @@
_HIP_SRC = r"""
#include <hip/hip_runtime.h>
#include <cmath>
#include <type_traits>

// XOR-reduce across the 4 lanes of a quad and broadcast. __shfl_xor lowers to ds_bpermute on RDNA,
// which issues on the *LDS pipe* -- the same pipe the k_s/q_s reads contend for, and it needs an
// lgkmcnt drain that also retires those reads, dragging them onto the token recurrence. DPP
// quad_perm is a VALU modifier instead: no LDS traffic and no wait.
template <int WIDTH>
__device__ __forceinline__ float group_sum(float x) {
#pragma unroll
for (int o = WIDTH / 2; o > 0; o >>= 1) x += __shfl_xor(x, o, WIDTH);
static_assert(WIDTH == 4 || WIDTH == 8, "DPP reduction covers SPLIT 4 and 8");
// row_half_mirror is the XOR-7 butterfly over each group of 8 lanes; composing it with the two
// quad_perms covers {1,2,3,4,5,6,7}, i.e. a full 8-lane reduce-and-broadcast in three DPP adds.
if constexpr (WIDTH == 8)
x += __builtin_bit_cast(float, __builtin_amdgcn_update_dpp(
0, __builtin_bit_cast(int, x), 0x141, 0xF, 0xF, true));
// quad_perm[1,0,3,2] = XOR 1, quad_perm[2,3,0,1] = XOR 2.
x += __builtin_bit_cast(float, __builtin_amdgcn_update_dpp(
0, __builtin_bit_cast(int, x), 0xB1, 0xF, 0xF, true));
x += __builtin_bit_cast(float, __builtin_amdgcn_update_dpp(
0, __builtin_bit_cast(int, x), 0x4E, 0xF, 0xF, true));
return x;
}

// 4 lanes per state column, 32 columns per block, 32-token chunks of k/q/v/g/beta in shared memory.
template <int S_v, int SPLIT, int COLS, int CHUNK, bool KEEP>
__global__ void __launch_bounds__(COLS * SPLIT)
// Lane -> state-row map. The blocked map (row = part * ROWS) puts the SPLIT lanes of a column on
// LDS dwords 0, 32, 64, 96 of the same token row, i.e. all four on bank 0: a 4-way conflict on
// every k_s/q_s read. Interleaving in groups of 4 instead --
// row(r) = (r >> 2) * (SPLIT * 4) + part * 4 + (r & 3)
// -- is still a bijection onto 0..S_v-1, still gives each lane four *consecutive* dwords (so the
// ds_load_b128 survives, base part*16, immediates 64 * (r >> 2)), but spreads the four lanes over
// banks 4 * part .. 4 * part + 3, which is conflict-free. Row padding cannot fix the blocked map:
// part * ROWS is a multiple of 32 for any row stride. The state tensor layout is unchanged --
// s[r] simply denotes a different row -- so only the partial-sum partition of the reduction moves.
#define GDN_ROW(r) ((((r) >> 2) * (SPLIT * 4)) + part * 4 + ((r) & 3))

// SPLIT lanes per state column *group*, CPL columns per lane, COLS columns per block, CHUNK-token
// chunks of k/q/v/g/beta in shared memory.
//
// Why CPL > 1: k_s/q_s do not depend on the column, so every column in the block re-reads the same
// dwords. A work unit of (column, token) costs 2 * S_v LDS dwords no matter how SPLIT is chosen --
// the only way to cut LDS traffic is to serve several columns from one set of reads. CPL = 2 halves
// the dwords per column-token; raising SPLIT to 8 at the same time keeps ROWS (and so the register
// footprint) and the total wave count -- H * (S_v / CPL) * SPLIT lanes -- exactly where they were.
template <int S_v, int SPLIT, int CPL, int COLS, int CHUNK, bool KEEP>
__global__ void __launch_bounds__((COLS / CPL) * SPLIT)
gdn_prefill(const float * __restrict__ q, const float * __restrict__ k, const float * __restrict__ v,
const float * __restrict__ g, const float * __restrict__ beta, const float * __restrict__ state_in,
float * __restrict__ out, float * __restrict__ state_out,
int H, int Hk, int n_tokens, int K, float scale) {
constexpr int ROWS = S_v / SPLIT;
constexpr int NTHREADS = COLS * SPLIT;
constexpr int NTHREADS = (COLS / CPL) * SPLIT;

__shared__ float k_s[CHUNK][S_v];
__shared__ float q_s[CHUNK][S_v];
__shared__ float v_s[CHUNK][COLS];
__shared__ float g_s[CHUNK];
__shared__ float b_s[CHUNK];
// (g, beta) for a token in one 16 B slot: one ds_load_b128 instead of two ds_load_b32.
__shared__ float4 gb_s[CHUNK];

const int h = blockIdx.x;
const int hk = h % Hk;
const int tid = threadIdx.x;
const int col_loc = tid / SPLIT;
const int part = tid % SPLIT;
const int cloc = (tid / SPLIT) * CPL; // first of this lane's CPL columns, block-local
const int col0 = blockIdx.z * COLS;
const int col = col0 + col_loc;
const int row0 = part * ROWS;
const int col = col0 + cloc;
static_assert(ROWS % 4 == 0, "row map needs ROWS a multiple of 4");

const float * s_in = state_in + (size_t) h * S_v * S_v;
float * s_out = state_out + (size_t) h * S_v * S_v;
const size_t slot_stride = (size_t) H * S_v * S_v;

float s[ROWS];
float s[CPL][ROWS];
#pragma unroll
for (int r = 0; r < ROWS; r++) s[r] = s_in[col * S_v + row0 + r];
for (int cc = 0; cc < CPL; cc++)
#pragma unroll
for (int r = 0; r < ROWS; r++) s[cc][r] = s_in[(col + cc) * S_v + GDN_ROW(r)];

for (int t0 = 0; t0 < n_tokens; t0 += CHUNK) {
const int nt = min(CHUNK, n_tokens - t0);
__syncthreads();
for (int idx = tid; idx < nt * S_v; idx += NTHREADS) {
// float4 staging: S_v and COLS are multiples of 4, so a vector never straddles a token row
// and every base is 16 B aligned (torch bases are >= 256 B aligned).
for (int idx = tid * 4; idx < nt * S_v; idx += NTHREADS * 4) {
const int tt = idx / S_v, i = idx % S_v;
k_s[tt][i] = k[((size_t) (t0 + tt) * Hk + hk) * S_v + i];
q_s[tt][i] = q[((size_t) (t0 + tt) * Hk + hk) * S_v + i];
const size_t b = ((size_t) (t0 + tt) * Hk + hk) * S_v + i;
*reinterpret_cast<float4 *>(&k_s[tt][i]) = *reinterpret_cast<const float4 *>(k + b);
*reinterpret_cast<float4 *>(&q_s[tt][i]) = *reinterpret_cast<const float4 *>(q + b);
}
for (int idx = tid; idx < nt * COLS; idx += NTHREADS) {
for (int idx = tid * 4; idx < nt * COLS; idx += NTHREADS * 4) {
const int tt = idx / COLS, c = idx % COLS;
v_s[tt][c] = v[((size_t) (t0 + tt) * H + h) * S_v + col0 + c];
*reinterpret_cast<float4 *>(&v_s[tt][c]) =
*reinterpret_cast<const float4 *>(v + ((size_t) (t0 + tt) * H + h) * S_v + col0 + c);
}
static_assert(NTHREADS >= CHUNK, "g/beta staging needs one thread per chunk token");
if (tid < nt) {
g_s[tid] = expf(g[(size_t) (t0 + tid) * H + h]);
b_s[tid] = beta[(size_t) (t0 + tid) * H + h];
const float gv = expf(g[(size_t) (t0 + tid) * H + h]);
gb_s[tid] = make_float4(gv, beta[(size_t) (t0 + tid) * H + h], 1.0f / gv, 0.0f);
}
__syncthreads();

// The snapshot block fires on only the last K of n_tokens tokens, yet its `slot < K` guard
// costs scalar-compare/branch slots -- and breaks up the VOPD pairs around it -- on every
// token of every chunk. The predicate is wave-uniform and chunk-monotone, so hoist it to
// chunk granularity: a chunk that cannot reach the snapshot window runs the byte-identical
// K = 1 token loop. The per-token `slot < K` test stays inside the snapshotting copy, which
// is what keeps partial chunks and K > CHUNK correct.
auto token_loop = [&](auto snap_tag) {
constexpr bool SNAP = decltype(snap_tag)::value;
for (int tt = 0; tt < nt; tt++) {
const float g_val = g_s[tt], beta_val = b_s[tt];
float kv[4] = {0.0f, 0.0f, 0.0f, 0.0f};
const float4 gb = gb_s[tt];
const float beta_val = gb.y;
const float g_val = gb.x;

float kr[ROWS];
float kv[CPL][4] = {};
#pragma unroll
for (int r = 0; r < ROWS; r++) {
kr[r] = k_s[tt][GDN_ROW(r)];
#pragma unroll
for (int cc = 0; cc < CPL; cc++) kv[cc][r % 4] += s[cc][r] * kr[r];
}
float delta[CPL];
#pragma unroll
for (int r = 0; r < ROWS; r++) kv[r % 4] += s[r] * k_s[tt][row0 + r];
const float kv_col = group_sum<SPLIT>((kv[0] + kv[1]) + (kv[2] + kv[3]));
const float delta_col = (v_s[tt][col_loc] - g_val * kv_col) * beta_val;
for (int cc = 0; cc < CPL; cc++) {
const float khat = group_sum<SPLIT>((kv[cc][0] + kv[cc][1]) + (kv[cc][2] + kv[cc][3]));
delta[cc] = (v_s[tt][cloc + cc] - g_val * khat) * beta_val;
}

float at[4] = {0.0f, 0.0f, 0.0f, 0.0f};
float at[CPL][4] = {};
#pragma unroll
for (int r = 0; r < ROWS; r++) {
s[r] = g_val * s[r] + k_s[tt][row0 + r] * delta_col;
at[r % 4] += s[r] * q_s[tt][row0 + r];
const float qr = q_s[tt][GDN_ROW(r)];
#pragma unroll
for (int cc = 0; cc < CPL; cc++) {
s[cc][r] = g_val * s[cc][r] + kr[r] * delta[cc];
at[cc][r % 4] += s[cc][r] * qr;
}
}
const float attn_col = group_sum<SPLIT>((at[0] + at[1]) + (at[2] + at[3]));
if (part == 0) out[((size_t) (t0 + tt) * H + h) * S_v + col] = attn_col * scale;
if constexpr (KEEP) {
const float gscale = scale;
// One exec-masked region and one naturally aligned float2: col is a multiple of CPL = 2,
// so the wave's active lanes write whole 32 B spans instead of two half-empty ones.
float2 o;
o.x = group_sum<SPLIT>((at[0][0] + at[0][1]) + (at[0][2] + at[0][3])) * gscale;
o.y = group_sum<SPLIT>((at[1][0] + at[1][1]) + (at[1][2] + at[1][3])) * gscale;
static_assert(CPL == 2, "the float2 out store pairs exactly two columns");
if (part == 0) *reinterpret_cast<float2 *>(&out[((size_t) (t0 + tt) * H + h) * S_v + col]) = o;

if constexpr (SNAP) {
const int slot = n_tokens - 1 - (t0 + tt);
if (slot < K) {
#pragma unroll
for (int r = 0; r < ROWS; r++) s_out[slot * slot_stride + col * S_v + row0 + r] = s[r];
for (int cc = 0; cc < CPL; cc++)
#pragma unroll
for (int r = 0; r < ROWS; r++)
s_out[slot * slot_stride + (col + cc) * S_v + GDN_ROW(r)] = s[cc][r];
}
}
}
};
if constexpr (KEEP) {
if (t0 + nt > n_tokens - K) token_loop(std::true_type{});
else token_loop(std::false_type{});
} else {
token_loop(std::false_type{});
}
}
if constexpr (!KEEP) {
#pragma unroll
for (int r = 0; r < ROWS; r++) s_out[col * S_v + row0 + r] = s[r];
for (int cc = 0; cc < CPL; cc++)
#pragma unroll
for (int r = 0; r < ROWS; r++) s_out[(col + cc) * S_v + GDN_ROW(r)] = s[cc][r];
}
}

Expand All @@ -136,14 +218,14 @@
extern "C" void gdn_prefill_hip(const float * q, const float * k, const float * v, const float * g,
const float * beta, const float * state, float * out, float * state_out,
int T, int H, int Hk, int K, hipStream_t stream) {
constexpr int SPLIT = 4, COLS = 32, CHUNK = 32;
dim3 grid(H, 1, 128 / COLS), block(COLS * SPLIT);
constexpr int SPLIT = 8, CPL = 2, COLS = 64, CHUNK = 16;
dim3 grid(H, 1, 128 / COLS), block((COLS / CPL) * SPLIT);
const float scale = 1.0f / sqrtf(128.0f);
if (K > 1) {
hipLaunchKernelGGL((gdn_prefill<128, SPLIT, COLS, CHUNK, true>), grid, block, 0, stream,
hipLaunchKernelGGL((gdn_prefill<128, SPLIT, CPL, COLS, CHUNK, true>), grid, block, 0, stream,
q, k, v, g, beta, state, out, state_out, H, Hk, T, K, scale);
} else {
hipLaunchKernelGGL((gdn_prefill<128, SPLIT, COLS, CHUNK, false>), grid, block, 0, stream,
hipLaunchKernelGGL((gdn_prefill<128, SPLIT, CPL, COLS, CHUNK, false>), grid, block, 0, stream,
q, k, v, g, beta, state, out, state_out, H, Hk, T, 1, scale);
}
}
Expand Down
5 changes: 5 additions & 0 deletions tools/kernelforge/gdn-prefill/program.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ Profile with `rocprofv3`; the MFMA counters do not exist here.
a block, 32-token chunks in LDS. The others kept more state per lane and spilled registers, or
reduced across more lanes.
- The K=8 case adds the snapshot writes (8 × 48 × 64 KB per call) on top of the K=1 case.
- Gates are hard: log-gates reach -20 (the driver draws them from [-20, -1e-4], as ggml's test
does). A product of gates over a few tokens underflows float32, so do not factor the gates out
of the state (S = prod(g) * S_hat): an earlier campaign's kept candidate did and returned NaN.
- The current kernel already has the first campaign's layout (DPP reductions, 2 columns per lane,
interleaved rows, 16-byte staging); its K=1 case runs in about 0.41 ms.

## Ideas worth trying

Expand Down
Loading
Loading