Skip to content
Closed
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
102 changes: 95 additions & 7 deletions engine/src/poly/qwen4.cu
Original file line number Diff line number Diff line change
Expand Up @@ -897,14 +897,16 @@ q4_qsa_merge_kernel(const float* __restrict__ part_acc, const float* __restrict_
}

// Single-pass batched sparse GQA kernel for prefill (rows > 16): grid = (n_kv, rows), block = 256.
template <bool IS_Q8, int G_MAX>
// G8: exactly eight query heads a KV head (Qwen4), the instance with the register path below.
template <bool IS_Q8, int G_MAX, bool G8 = false>
__global__ void __launch_bounds__(256)
q4_qsa_attend_batch_kernel(const float* __restrict__ q, const uint16_t* __restrict__ keys,
const uint16_t* __restrict__ vals, Kvq8 kq8, Kvq8 vq8,
const int32_t* __restrict__ sel_ids, int sel_cap, const int32_t* __restrict__ sel_count,
float* __restrict__ out, int dim, int n_head, int n_kv, float scale, int ring) {
__shared__ __align__(16) float sq[G_MAX][256];
__shared__ float sp[G_MAX][kQsaChunk];
__shared__ __align__(16) float spt[kQsaChunk][G_MAX]; // the chunk's weights by key, for float4 reads in the V sum
__shared__ int scell[kQsaChunk];
__shared__ float s_m[G_MAX];
__shared__ float s_l[G_MAX];
Expand Down Expand Up @@ -932,6 +934,22 @@ q4_qsa_attend_batch_kernel(const float* __restrict__ q, const uint16_t* __restri
#pragma unroll
for (int h = 0; h < G_MAX; ++h) acc[h] = 0.0f;

// Eight query heads a KV head (Qwen4): each lane keeps its eight dimensions of the eight queries in registers
// instead of reading them from shared memory for every key, and the eight dot products are summed across the warp
// in one transposed reduction (9 shuffles instead of 40). The pairs added are the ones warp_sum() adds (xor 16, 8,
// 4, 2, 1), so every score has the same bits.
static_assert(!G8 || G_MAX == 8, "G8 is the eight-head instance");
constexpr bool g8 = G8;
float qr[8][8];
if constexpr (g8) {
const int d0 = lane * 8;
#pragma unroll
for (int h = 0; h < 8; ++h) {
#pragma unroll
for (int j = 0; j < 8; ++j) qr[h][j] = (d0 < dim) ? sq[h][d0 + j] : 0.0f;
}
}

for (int c0 = 0; c0 < n_ids; c0 += kQsaChunk) {
const int n_here = min(kQsaChunk, n_ids - c0);
if (tid < kQsaChunk) {
Expand All @@ -941,6 +959,45 @@ q4_qsa_attend_batch_kernel(const float* __restrict__ q, const uint16_t* __restri
}
__syncthreads();

if constexpr (g8) {
for (int c = warp; c < n_here; c += 8) {
const size_t row = (size_t) scell[c];
float dot[8];
#pragma unroll
for (int h = 0; h < 8; ++h) dot[h] = 0.0f;
const int d0 = lane * 8;
if (d0 < dim) {
float k8[8];
load_k8<IS_Q8>(keys, kq8, row, kvh, n_kv, dim, d0, k8);
#pragma unroll
for (int h = 0; h < 8; ++h) {
dot[h] += k8[0] * qr[h][0] + k8[1] * qr[h][1] + k8[2] * qr[h][2] + k8[3] * qr[h][3] +
k8[4] * qr[h][4] + k8[5] * qr[h][5] + k8[6] * qr[h][6] + k8[7] * qr[h][7];
}
}
const bool b16 = (lane & 16) != 0;
float r4[4];
#pragma unroll
for (int j = 0; j < 4; ++j) {
const float keep = b16 ? dot[j + 4] : dot[j];
const float send = b16 ? dot[j] : dot[j + 4];
r4[j] = keep + __shfl_xor_sync(0xffffffffu, send, 16, WARP);
}
const bool b8 = (lane & 8) != 0;
float r2[2];
#pragma unroll
for (int j = 0; j < 2; ++j) {
const float keep = b8 ? r4[j + 2] : r4[j];
const float send = b8 ? r4[j] : r4[j + 2];
r2[j] = keep + __shfl_xor_sync(0xffffffffu, send, 8, WARP);
}
const bool b4 = (lane & 4) != 0;
float t = (b4 ? r2[1] : r2[0]) + __shfl_xor_sync(0xffffffffu, b4 ? r2[0] : r2[1], 4, WARP);
t += __shfl_xor_sync(0xffffffffu, t, 2, WARP);
t += __shfl_xor_sync(0xffffffffu, t, 1, WARP);
if ((lane & 3) == 0) sp[(b4 ? 1 : 0) + (b8 ? 2 : 0) + (b16 ? 4 : 0)][c] = t * scale;
}
} else
for (int c = warp; c < n_here; c += 8) {
const size_t row = (size_t) scell[c];
float dot[G_MAX];
Expand Down Expand Up @@ -973,8 +1030,8 @@ q4_qsa_attend_batch_kernel(const float* __restrict__ q, const uint16_t* __restri
const float w0 = (lane < n_here) ? expf(s0 - m_new) : 0.0f;
const float w1 = (lane + 32 < n_here) ? expf(s1 - m_new) : 0.0f;
const float l_chunk = warp_sum(w0 + w1);
if (lane < n_here) sp[h][lane] = w0;
if (lane + 32 < n_here) sp[h][lane + 32] = w1;
if (lane < n_here) sp[h][lane] = w0, spt[lane][h] = w0;
if (lane + 32 < n_here) sp[h][lane + 32] = w1, spt[lane + 32][h] = w1;
if (lane == 0) {
s_alpha[h] = alpha;
s_m[h] = m_new;
Expand All @@ -985,9 +1042,25 @@ q4_qsa_attend_batch_kernel(const float* __restrict__ q, const uint16_t* __restri

if (tid < dim) {
for (int h = 0; h < G; ++h) acc[h] *= s_alpha[h];
for (int c = 0; c < n_here; ++c) {
const float v = load_v1<IS_Q8>(vals, vq8, (size_t) scell[c], kvh, n_kv, dim, tid);
for (int h = 0; h < G; ++h) acc[h] = fmaf(sp[h][c], v, acc[h]);
if constexpr (g8) {
for (int c = 0; c < n_here; ++c) {
const float v = load_v1<IS_Q8>(vals, vq8, (size_t) scell[c], kvh, n_kv, dim, tid);
const float4 wa = *reinterpret_cast<const float4*>(&spt[c][0]);
const float4 wb = *reinterpret_cast<const float4*>(&spt[c][4]);
acc[0] = fmaf(wa.x, v, acc[0]);
acc[1] = fmaf(wa.y, v, acc[1]);
acc[2] = fmaf(wa.z, v, acc[2]);
acc[3] = fmaf(wa.w, v, acc[3]);
acc[4] = fmaf(wb.x, v, acc[4]);
acc[5] = fmaf(wb.y, v, acc[5]);
acc[6] = fmaf(wb.z, v, acc[6]);
acc[7] = fmaf(wb.w, v, acc[7]);
}
} else {
for (int c = 0; c < n_here; ++c) {
const float v = load_v1<IS_Q8>(vals, vq8, (size_t) scell[c], kvh, n_kv, dim, tid);
for (int h = 0; h < G; ++h) acc[h] = fmaf(sp[h][c], v, acc[h]);
}
}
}
__syncthreads();
Expand Down Expand Up @@ -1924,6 +1997,12 @@ void q4_qsa_topk(const float* score, int score_stride, int32_t* sel_ids, int sel
launched("q4_qsa_topk");
}

namespace {
bool g_qsa_g8 = true; // q4_qsa_attend_g8(): tests compare the two batch instances
} // namespace

void q4_qsa_attend_g8(bool on) { g_qsa_g8 = on; }

void q4_qsa_attend(const float* q, const uint16_t* keys, const uint16_t* vals, Kvq8 kq8, Kvq8 vq8,
const int32_t* sel_ids, int sel_cap, const int32_t* sel_count,
float* out, float* part_buf, size_t part_floats,
Expand Down Expand Up @@ -1966,7 +2045,16 @@ void q4_qsa_attend(const float* q, const uint16_t* keys, const uint16_t* vals, K
part_acc, part_m, part_l, out, n_chunks, dim, n_head);
} else {
const dim3 blocks(n_kv, rows);
if (is_q8) {
if (G == 8 && g_qsa_g8) {
if (is_q8)
q4_qsa_attend_batch_kernel<true, 8, true><<<blocks, 256, 0, cs(stream)>>>(
q, nullptr, nullptr, kq8, vq8, sel_ids, sel_cap, sel_count,
out, dim, n_head, n_kv, scale, ring);
else
q4_qsa_attend_batch_kernel<false, 8, true><<<blocks, 256, 0, cs(stream)>>>(
q, keys, vals, Kvq8{}, Kvq8{}, sel_ids, sel_cap, sel_count,
out, dim, n_head, n_kv, scale, ring);
} else if (is_q8) {
if (G <= 8)
q4_qsa_attend_batch_kernel<true, 8><<<blocks, 256, 0, cs(stream)>>>(
q, nullptr, nullptr, kq8, vq8, sel_ids, sel_cap, sel_count,
Expand Down
3 changes: 3 additions & 0 deletions engine/src/poly/qwen4_kernels.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,9 @@ void q4_qsa_attend(const float* q, const uint16_t* keys, const uint16_t* vals, K
const int32_t* sel_ids, int sel_cap, const int32_t* sel_count,
float* out, float* part_buf, size_t part_floats,
int dim, int n_head, int n_kv, int rows, float scale, int ring, void* stream);
/// For tests: false makes q4_qsa_attend() take the general batch kernel for eight query heads a KV head too, the
/// code the eight-head instance stands in for, so the two can be compared bit for bit (default true).
void q4_qsa_attend_g8(bool on);

// ---- 4. MTP (blk.40) Input Fusion ----

Expand Down
77 changes: 77 additions & 0 deletions engine/src/poly/qwen4_test.cu
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,82 @@ void test_qsa_kernels(std::mt19937& rng) {
std::printf("PASS qsa_kernels (cross-batch pool>16, score, radix top-k, split+batch sparse GQA)\n");
}

// The eight-heads-a-KV-head batch instance (q4_qsa_attend_batch_kernel<.., 8, true>) against the general one it stands
// in for (q4_qsa_attend_g8(false)), bit for bit: FP16 and Q8_0 caches, head dims 128 and 256, 40 rows (the batch path),
// selections of 1, 63, 64, 65, 2,051 cells and random counts, cells repeated and out of order.
void test_qsa_g8_bits(std::mt19937& rng) {
const int n_head = 16, n_kv = 2, rows = 40, n_cells = 3000, sel_cap = 2051;
int checked = 0, differ = 0;
for (const int dim : {128, 256}) {
for (const bool q8 : {false, true}) {
const size_t row_vals = (size_t) n_kv * dim;
auto q = rand_vec((size_t) rows * n_head * dim, rng, 0.5f);
std::vector<uint16_t> kf16(n_cells * row_vals), vf16(n_cells * row_vals);
for (size_t i = 0; i < kf16.size(); ++i) {
const __half k = __float2half(std::normal_distribution<float>(0.f, 0.5f)(rng));
const __half v = __float2half(std::normal_distribution<float>(0.f, 0.5f)(rng));
std::memcpy(&kf16[i], &k, 2); std::memcpy(&vf16[i], &v, 2);
}
std::vector<int8_t> kc(n_cells * row_vals), vc(n_cells * row_vals);
std::vector<uint16_t> ks(n_cells * row_vals / 32), vs(n_cells * row_vals / 32);
for (auto& c : kc) c = (int8_t) ((int) (rng() % 255) - 127);
for (auto& c : vc) c = (int8_t) ((int) (rng() % 255) - 127);
for (auto* sc : {&ks, &vs})
for (auto& x : *sc) { const __half h = __float2half(0.002f + 0.01f * (float) (rng() % 1000) / 1000.f); std::memcpy(&x, &h, 2); }
std::vector<int32_t> sel((size_t) rows * sel_cap), cnt(rows);
const int fixed[] = {1, 63, 64, 65, sel_cap};
for (int r = 0; r < rows; ++r) {
cnt[r] = r < 5 ? fixed[r] : 1 + (int) (rng() % sel_cap);
for (int j = 0; j < sel_cap; ++j) sel[(size_t) r * sel_cap + j] = (int) (rng() % n_cells);
}
float *d_q, *d_out;
uint16_t *d_kf, *d_vf, *d_ks, *d_vs;
int8_t *d_kc, *d_vc;
int32_t *d_sel, *d_cnt;
ck(cudaMalloc(&d_q, q.size() * 4), "m");
ck(cudaMalloc(&d_out, q.size() * 4), "m");
ck(cudaMalloc(&d_kf, kf16.size() * 2), "m");
ck(cudaMalloc(&d_vf, vf16.size() * 2), "m");
ck(cudaMalloc(&d_kc, kc.size()), "m");
ck(cudaMalloc(&d_vc, vc.size()), "m");
ck(cudaMalloc(&d_ks, ks.size() * 2), "m");
ck(cudaMalloc(&d_vs, vs.size() * 2), "m");
ck(cudaMalloc(&d_sel, sel.size() * 4), "m");
ck(cudaMalloc(&d_cnt, cnt.size() * 4), "m");
ck(cudaMemcpy(d_q, q.data(), q.size() * 4, cudaMemcpyHostToDevice), "c");
ck(cudaMemcpy(d_kf, kf16.data(), kf16.size() * 2, cudaMemcpyHostToDevice), "c");
ck(cudaMemcpy(d_vf, vf16.data(), vf16.size() * 2, cudaMemcpyHostToDevice), "c");
ck(cudaMemcpy(d_kc, kc.data(), kc.size(), cudaMemcpyHostToDevice), "c");
ck(cudaMemcpy(d_vc, vc.data(), vc.size(), cudaMemcpyHostToDevice), "c");
ck(cudaMemcpy(d_ks, ks.data(), ks.size() * 2, cudaMemcpyHostToDevice), "c");
ck(cudaMemcpy(d_vs, vs.data(), vs.size() * 2, cudaMemcpyHostToDevice), "c");
ck(cudaMemcpy(d_sel, sel.data(), sel.size() * 4, cudaMemcpyHostToDevice), "c");
ck(cudaMemcpy(d_cnt, cnt.data(), cnt.size() * 4, cudaMemcpyHostToDevice), "c");
Kvq8 kq, vq;
if (q8) { kq.codes = d_kc; kq.scales = d_ks; vq.codes = d_vc; vq.scales = d_vs; }
const float scale = 1.0f / std::sqrt((float) dim);
std::vector<float> out8(q.size()), outg(q.size());
for (const bool g8 : {true, false}) {
q4_qsa_attend_g8(g8);
ck(cudaMemset(d_out, 0xff, q.size() * 4), "z");
q4_qsa_attend(d_q, q8 ? nullptr : d_kf, q8 ? nullptr : d_vf, kq, vq, d_sel, sel_cap, d_cnt, d_out,
nullptr, 0, dim, n_head, n_kv, rows, scale, 0, nullptr);
ck(cudaDeviceSynchronize(), "qsa_g8");
ck(cudaMemcpy((g8 ? out8 : outg).data(), d_out, q.size() * 4, cudaMemcpyDeviceToHost), "c");
}
q4_qsa_attend_g8(true);
for (size_t i = 0; i < q.size(); ++i, ++checked) differ += std::memcmp(&out8[i], &outg[i], 4) != 0;
cudaFree(d_q); cudaFree(d_out); cudaFree(d_kf); cudaFree(d_vf); cudaFree(d_kc); cudaFree(d_vc);
cudaFree(d_ks); cudaFree(d_vs); cudaFree(d_sel); cudaFree(d_cnt);
}
}
if (differ != 0) {
std::fprintf(stderr, "FAIL qsa_g8_bits: %d of %d outputs differ from the general kernel\n", differ, checked);
std::exit(1);
}
std::printf("PASS qsa_g8_bits (eight heads a KV head: %d outputs, the general kernel's bits)\n", checked);
}

void test_gdn_sigmoid(std::mt19937& rng) {
// Verify gdn_step_sigmoid uses sigmoid(z) rather than silu(z) by comparing against gdn_step * 1/z!
const int dim = 128, n_head = 4, k_heads = 2, rows = 3;
Expand Down Expand Up @@ -938,6 +1014,7 @@ int main() {
test_gr_kernels(rng, st);
test_ple_kernels(rng);
test_qsa_kernels(rng);
test_qsa_g8_bits(rng);
test_gdn_sigmoid(rng);
test_gdn_decode_fused(rng, st);
#if !defined(STRATA_GPU_METAL)
Expand Down