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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- Qwen3.8-Flash-Next on HIP fills prompts faster: its sparse attention runs a new kernel with the same sums as before (a lane holds a key and several heads, keys and values staged in the cache type), so replies are unchanged. On a Radeon 8060S (gfx1151), cold prompts of 2,048 to 63,728 tokens finish 29 to 41% sooner; other HIP chips take the kernel but weren't run (#1877). Thanks to @gilby.
- HIP on gfx12 under `--policy matrix=on`: Qwen3 dense checkpoints load each layer's gate and up weights interleaved as one weight, and one WMMA product writes silu(gate) x up in its epilogue instead of two products and `tf_silu_mul`, with the same output bytes: Qwen3-Reranker-8B ranks 16 documents in 0.657 to 0.661 s instead of 0.687 to 0.697 s and Qwen3-Embedding-8B embeds 100 short inputs in 0.901 to 0.911 s instead of 0.940 to 0.948 s on a Radeon AI PRO R9700. The kernel contract checks both fused blocks byte for byte against the unfused launches (part of #2245). Thanks to @laudney.
- Nemotron on Macs: the masked prompt shader calls the shared `tf_paged_row` page helper again, so its prompt sources compile; #2322 had used the name #2283 retired the same day (#2548).
- Server: control bytes in a request line (C0, DEL and C1) appear in the access log as `\xNN`, so a request cannot write terminal escapes into the log; ordinary lines are unchanged (#2542). Thanks to @chadhurley25075-png.

- Conversation states on disk (`--learn-conversations`): a row block or state file whose trailer sizes add up to the file only by wrapping past 2^64 is refused at open, where a safe build used to panic on the addition (#2544). Thanks to @chadhurley25075-png.
Expand Down
18 changes: 9 additions & 9 deletions zig/build/hip.zig
Original file line number Diff line number Diff line change
Expand Up @@ -513,15 +513,15 @@ const groups = [_]Source{
};
/// What the group sources include, so an edit to one rebuilds them.
const headers = [_][]const u8{
"attention/attention_fa.hip", "attention/prefill.hpp", "decode/pages.hpp", "decode/plan.hpp", "ops/attention.hpp",
"ops/common.hpp", "ops/draw.hpp", "ops/tp.hpp", "ops/elementwise.hpp", "ops/linear.hpp",
"ops/moe.hpp", "ops/norms.hpp", "ops/rope.hpp", "common/arch.hpp", "common/dot2.hpp",
"common/vec.hpp", "common/wmma.hpp", "quant/act.hpp", "quant/mlx.hpp", "quant/mlx_decoder.hpp",
"quant/mlx_pieces.hpp", "quant/mlx_tiles.hpp", "tiles/dot2.hpp", "tiles/epilogue.hpp", "tiles/gemm.hpp",
"tiles/gemm_kp.hpp", "tiles/matrix_gemm.hpp", "tiles/plan.hpp", "tiles/stream.hpp", "flashnext/streams.hpp",
"flashnext/ngram.hpp", "flashnext/indexer.hpp", "flashnext/sparse.hpp", "ops/nemotron_moe.hpp", "quant/bf16_decoder.hpp",
"quant/dense_tiles.hpp", "tiles/wmma12_gemm.hpp", "tiles/wmma12_gemm_k32_ref.hpp", "ops/columns.hpp", "columns_controls.hpp",
"ops/vision.hpp", "ops/dense_text.hpp", "ops/vl_position.hpp",
"attention/attention_fa.hip", "attention/prefill.hpp", "decode/pages.hpp", "decode/plan.hpp", "ops/attention.hpp",
"ops/common.hpp", "ops/draw.hpp", "ops/tp.hpp", "ops/elementwise.hpp", "ops/linear.hpp",
"ops/moe.hpp", "ops/norms.hpp", "ops/rope.hpp", "common/arch.hpp", "common/dot2.hpp",
"common/vec.hpp", "common/wmma.hpp", "quant/act.hpp", "quant/mlx.hpp", "quant/mlx_decoder.hpp",
"quant/mlx_pieces.hpp", "quant/mlx_tiles.hpp", "tiles/dot2.hpp", "tiles/epilogue.hpp", "tiles/gemm.hpp",
"tiles/gemm_kp.hpp", "tiles/matrix_gemm.hpp", "tiles/plan.hpp", "tiles/stream.hpp", "flashnext/streams.hpp",
"flashnext/ngram.hpp", "flashnext/indexer.hpp", "flashnext/sparse.hpp", "ops/nemotron_moe.hpp", "quant/bf16_decoder.hpp",
"quant/dense_tiles.hpp", "tiles/wmma12_gemm.hpp", "tiles/wmma12_gemm_k32_ref.hpp", "ops/columns.hpp", "columns_controls.hpp",
"ops/vision.hpp", "ops/dense_text.hpp", "ops/vl_position.hpp", "flashnext/sparse_lanes.hpp",
};
/// The flags of the kernels' first build: no contraction, wave32 on RDNA, C++20.
const flags = [_][]const u8{ "-D__HIP_PLATFORM_AMD__=1", "-DUSE_ROCM=1", "-DHIPBLAS_V2", "-fPIC", "-DCUDA_HAS_FP16=1", "-DHIP_ENABLE_WARP_SYNC_BUILTINS=1", "-std=c++20", "-fno-gpu-rdc", "-mno-wavefrontsize64", "-ffp-contract=off" };
Expand Down
1 change: 1 addition & 0 deletions zig/kernels/hip/flashnext/flashnext.hip
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@
#include "ngram.hpp"
#include "indexer.hpp"
#include "sparse.hpp"
#include "sparse_lanes.hpp"
209 changes: 209 additions & 0 deletions zig/kernels/hip/flashnext/sparse_lanes.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
#pragma once

#include "../ops/common.hpp"

// sparse_parts with the same fp32 operations in the same order: 16-bit staging, a lane a key and several heads.

namespace {

constexpr int kLanesTiles = 1;
constexpr int kLanesRow = kSparseMostDims + 8;

template <int kKind>
__device__ __forceinline__ float lanes_widen(uint32_t h) {
if constexpr (kKind == 1) return __half2float(__ushort_as_half(static_cast<uint16_t>(h)));
return bf16_to_float(static_cast<uint16_t>(h));
}

// Block (g, r, p) as sparse_parts over a kKind cache (1 fp16, 2 bf16): a lane a key and kHeads heads, 2 dims a thread.
template <int kSparseGroup, int kKind>
__device__ void sparse_lanes(const float* q, const void* k, const void* v, const int* ids, long long id_stride,
const int* count, const int* sparse, float* parts_o, float* parts_ms, int heads,
int kv_heads, int dims, long long cap, float scale, int parts) {
constexpr int kWavesTile = kSparseWaves / kLanesTiles;
constexpr int kHeads = (kSparseGroup + kWavesTile - 1) / kWavesTile;
constexpr int kHalf = (kSparseGroup + 1) / 2;
__shared__ __attribute__((aligned(16))) float qs[kSparseGroup][kSparseMostDims];
__shared__ __attribute__((aligned(16))) uint16_t kv[kLanesTiles][kSparseTile][kLanesRow];
__shared__ __attribute__((aligned(16))) float ps[kLanesTiles][kSparseGroup][kSparseTile];
__shared__ float tree[kLanesTiles][kSparseGroup], tops[kLanesTiles][kSparseGroup], sums[kLanesTiles][kSparseGroup];
__shared__ float fs[kLanesTiles][kSparseGroup], m[kSparseGroup], l[kSparseGroup];
__shared__ long long keys[kLanesTiles][kSparseTile];
const int g = blockIdx.x, r = blockIdx.y, part = blockIdx.z;
const int group = heads / kv_heads;
const int t = threadIdx.x, lane = t & 31, wave = t >> 5;
const int n = count[r];
const bool listed = ids != nullptr && sparse != nullptr && sparse[r] != 0;
const int lo = static_cast<int>(static_cast<long long>(part) * n / parts);
const int hi = static_cast<int>(static_cast<long long>(part + 1) * n / parts);
const long long head_base = static_cast<long long>(g) * cap * dims;
const uint16_t* k16 = static_cast<const uint16_t*>(k);
const uint16_t* v16 = static_cast<const uint16_t*>(v);
for (int i = t; i < group * dims; i += kSparseWaves * 32) {
const int h = i / dims, d = i % dims;
qs[h][d] = q[(static_cast<long long>(r) * heads + g * group + h) * dims + d] * scale;
}
if (t < kSparseGroup) {
m[t] = -INFINITY;
l[t] = 0.f;
}
// scores: this wave's tile and first head; values: this thread's dim pair and first head
const int slot = wave / kWavesTile, h0 = (wave % kWavesTile) * kHeads;
const int dp = (t & 127) * 2, hv0 = (t >> 7) * kHalf;
float o[kHalf][2];
#pragma unroll
for (int h = 0; h < kHalf; ++h) o[h][0] = o[h][1] = 0.f;
const int chunks = dims / 8;
for (int t0 = lo; t0 < hi; t0 += kLanesTiles * kSparseTile) {
int tn[kLanesTiles];
#pragma unroll
for (int s = 0; s < kLanesTiles; ++s) tn[s] = max(0, min(kSparseTile, hi - t0 - s * kSparseTile));
__syncthreads();
if (t < kLanesTiles * kSparseTile) {
const int s = t / kSparseTile, j = t % kSparseTile, at = t0 + s * kSparseTile + j;
if (j < tn[s]) keys[s][j] = listed ? ids[r * id_stride + at] : at;
}
__syncthreads();
for (int i = t; i < kLanesTiles * kSparseTile * chunks; i += kSparseWaves * 32) {
const int s = i / (kSparseTile * chunks), j = (i / chunks) % kSparseTile, c = i % chunks;
if (j < tn[s])
*reinterpret_cast<uint4*>(&kv[s][j][c * 8]) =
*reinterpret_cast<const uint4*>(k16 + head_base + keys[s][j] * dims + c * 8);
}
__syncthreads();
float sc[kHeads];
#pragma unroll
for (int a = 0; a < kHeads; ++a) sc[a] = 0.f;
const bool live = lane < tn[slot];
if (tn[slot] > 0) {
#pragma unroll 4
for (int d = 0; d < dims; d += 4) {
const uint2 w = *reinterpret_cast<const uint2*>(&kv[slot][lane][d]);
const float k0 = lanes_widen<kKind>(w.x & 0xffff), k1 = lanes_widen<kKind>(w.x >> 16);
const float k2 = lanes_widen<kKind>(w.y & 0xffff), k3 = lanes_widen<kKind>(w.y >> 16);
#pragma unroll
for (int a = 0; a < kHeads; ++a) {
const float4 x = *reinterpret_cast<const float4*>(&qs[min(h0 + a, kSparseGroup - 1)][d]);
sc[a] += x.x * k0;
sc[a] += x.y * k1;
sc[a] += x.z * k2;
sc[a] += x.w * k3;
}
}
#pragma unroll
for (int a = 0; a < kHeads; ++a) {
float top = live ? sc[a] : -INFINITY;
#pragma unroll
for (int mask = 16; mask > 0; mask >>= 1) top = fmaxf(top, __shfl_xor(top, mask, 32));
if (lane == 0 && h0 + a < group) tree[slot][h0 + a] = top;
}
}
__syncthreads();
// values replace the keys; each tile's top is folded into the running max in tile order
for (int i = t; i < kLanesTiles * kSparseTile * chunks; i += kSparseWaves * 32) {
const int s = i / (kSparseTile * chunks), j = (i / chunks) % kSparseTile, c = i % chunks;
if (j < tn[s])
*reinterpret_cast<uint4*>(&kv[s][j][c * 8]) =
*reinterpret_cast<const uint4*>(v16 + head_base + keys[s][j] * dims + c * 8);
}
if (tn[slot] > 0) {
#pragma unroll
for (int a = 0; a < kHeads; ++a) {
const int h = h0 + a;
if (h >= group) continue;
float top = fmaxf(tree[0][h], m[h]);
for (int s = 1; s <= slot; ++s) top = fmaxf(tree[s][h], top);
const float e = live ? expf(sc[a] - top) : 0.f;
float sum = e;
#pragma unroll
for (int mask = 16; mask > 0; mask >>= 1) sum += __shfl_xor(sum, mask, 32);
ps[slot][h][lane] = e;
if (lane == 0) {
tops[slot][h] = top;
sums[slot][h] = sum;
}
}
}
__syncthreads();
if (t < group) {
#pragma unroll
for (int s = 0; s < kLanesTiles; ++s) {
if (tn[s] == 0) break;
const float top = tops[s][t];
const float f = expf(m[t] - top);
fs[s][t] = f;
l[t] = l[t] * f + sums[s][t];
m[t] = top;
}
}
__syncthreads();
if (dp < dims) {
#pragma unroll
for (int s = 0; s < kLanesTiles; ++s) {
if (tn[s] == 0) break;
#pragma unroll
for (int h = 0; h < kHalf; ++h) {
const float f = fs[s][hv0 + h];
o[h][0] *= f;
o[h][1] *= f;
}
for (int j = 0; j < tn[s]; ++j) {
const uint32_t w = *reinterpret_cast<const uint32_t*>(&kv[s][j][dp]);
const float v0 = lanes_widen<kKind>(w & 0xffff), v1 = lanes_widen<kKind>(w >> 16);
#pragma unroll
for (int h = 0; h < kHalf; ++h) {
const float p = ps[s][hv0 + h][j];
o[h][0] += p * v0;
o[h][1] += p * v1;
}
}
}
}
}
__syncthreads();
for (int h = 0; h < kHalf; ++h) {
if (hv0 + h >= group || dp >= dims) continue;
const long long out = (static_cast<long long>(r) * heads + g * group + hv0 + h) * parts + part;
parts_o[out * dims + dp] = o[h][0];
parts_o[out * dims + dp + 1] = o[h][1];
}
if (t < group) {
const long long out = (static_cast<long long>(r) * heads + g * group + t) * parts + part;
parts_ms[out * 2] = m[t];
parts_ms[out * 2 + 1] = l[t];
}
}

extern "C" __global__ void __launch_bounds__(kSparseWaves * 32, 2)
tf_fn_sparse_lanes6_f16(const float* q, const void* k, const void* v, const int* ids, long long id_stride,
const int* count, const int* sparse, float* parts_o, float* parts_ms, int heads,
int kv_heads, int dims, long long cap, float scale, int parts) {
sparse_lanes<6, 1>(q, k, v, ids, id_stride, count, sparse, parts_o, parts_ms, heads, kv_heads, dims, cap, scale,
parts);
}

extern "C" __global__ void __launch_bounds__(kSparseWaves * 32, 2)
tf_fn_sparse_lanes6_bf16(const float* q, const void* k, const void* v, const int* ids, long long id_stride,
const int* count, const int* sparse, float* parts_o, float* parts_ms, int heads,
int kv_heads, int dims, long long cap, float scale, int parts) {
sparse_lanes<6, 2>(q, k, v, ids, id_stride, count, sparse, parts_o, parts_ms, heads, kv_heads, dims, cap, scale,
parts);
}

extern "C" __global__ void __launch_bounds__(kSparseWaves * 32, 2)
tf_fn_sparse_lanes12_f16(const float* q, const void* k, const void* v, const int* ids, long long id_stride,
const int* count, const int* sparse, float* parts_o, float* parts_ms, int heads,
int kv_heads, int dims, long long cap, float scale, int parts) {
sparse_lanes<12, 1>(q, k, v, ids, id_stride, count, sparse, parts_o, parts_ms, heads, kv_heads, dims, cap, scale,
parts);
}

extern "C" __global__ void __launch_bounds__(kSparseWaves * 32, 2)
tf_fn_sparse_lanes12_bf16(const float* q, const void* k, const void* v, const int* ids, long long id_stride,
const int* count, const int* sparse, float* parts_o, float* parts_ms, int heads,
int kv_heads, int dims, long long cap, float scale, int parts) {
sparse_lanes<12, 2>(q, k, v, ids, id_stride, count, sparse, parts_o, parts_ms, heads, kv_heads, dims, cap, scale,
parts);
}

} // namespace
2 changes: 1 addition & 1 deletion zig/src/core/contract/hip_records.zig
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,7 @@ const own_records = [own_count]Record{
},
},
} ++ @import("hip_records_pair.zig").records ++ @import("hip_records_prompt.zig").records ++
@import("hip_records_score.zig").records ++ @import("hip_records_embed.zig").records ++ @import("hip_records_tail.zig").records ++ @import("hip_records_tap.zig").records;
@import("hip_records_score.zig").records ++ @import("hip_records_embed.zig").records ++ @import("hip_records_tail.zig").records ++ @import("hip_records_tap.zig").records ++ @import("hip_records_sparse.zig").records;

pub const records = own_records ++ @import("hip_records_stream.zig").records ++ @import("hip_records_router.zig").records ++
@import("hip_records_item.zig").records ++ @import("hip_records_qwen3.zig").records ++ @import("hip_records_columns.zig").records ++
Expand Down
1 change: 1 addition & 0 deletions zig/src/core/contract/hip_records_families.zig
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ test "HIP record counts stay pinned in their owning files" {
@import("hip_records_qwen_vision.zig").records.len,
@import("hip_records_router.zig").records.len,
@import("hip_records_score.zig").records.len,
@import("hip_records_sparse.zig").records.len,
@import("hip_records_stream_plain.zig").records.len,
@import("hip_records_stream_swiglu.zig").records.len,
@import("hip_records_tail.zig").records.len,
Expand Down
21 changes: 21 additions & 0 deletions zig/src/core/contract/hip_records_sparse.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//! Gate 5's records of Flash Next's lanes sparse attention (tf_fn_sparse_lanes12_*).
const Record = @import("hip_records.zig").Record;

/// Flash Next's lanes sparse attention, 12 query heads a kv head, one cache kind (`early` VGPRs: gfx1030, gfx1100).
fn sparseLanes(comptime kind: []const u8, comptime early: u32, comptime late: u32) Record {
const symbol = "tf_fn_sparse_lanes12_" ++ kind;
return .{
.launch = .{ .name = "flashnext " ++ symbol, .symbol = symbol, .image = "flashnext", .threads = 256 },
.usage = .{
.{ .vgprs = early, .sgprs = 55, .lds = 31264, .private = 0, .bound = 256, .wave = 32 },
.{ .vgprs = early, .sgprs = 55, .lds = 31264, .private = 0, .bound = 256, .wave = 32 },
.{ .vgprs = late, .sgprs = 57, .lds = 31264, .private = 0, .bound = 256, .wave = 32 },
.{ .vgprs = late, .sgprs = 59, .lds = 31264, .private = 0, .bound = 256, .wave = 32 },
},
};
}

pub const records = [_]Record{
sparseLanes("f16", 74, 72),
sparseLanes("bf16", 84, 83),
};
1 change: 1 addition & 0 deletions zig/src/hip/kernel_tests.zig
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ test {
_ = @import("kernel_tests/flashnext.zig");
_ = @import("kernel_tests/flashnext_attn.zig");
_ = @import("kernel_tests/moe_gate.zig");
_ = @import("kernel_tests/flashnext_sparse.zig");
_ = @import("kernel_tests/nemotron/moe.zig");
_ = @import("kernel_tests/nemotron/pick.zig");
_ = @import("kernel_tests/nemotron/attention.zig");
Expand Down
Loading
Loading