Merge perf-PR group batch (f-145-pp-batch)

This commit is contained in:
Niko1221 committed 2026-10-16 10:49:15 +02:00
commit e8b1edbcb7
25 files changed
+2105 -130

No files matched your search

+274
View File
@@ -0,0 +1,274 @@
// src/kernels/batch_rows_parity.cpp - the batch window's one-launch-for-all-rows kernels (#2234, STRATA_BATCH_ATTN_ROWS /
// STRATA_BATCH_GDN_GROUPS) against the per-row launches they replace, bitwise (GPU, synthetic, no model).
//
// 1. qsa_block_scores_rows == qsa_block_scores, one call per row, each row with its OWN indexer keys;
// 2. qsa_decode_attn_batch_rows == qsa_decode_attn_batch, one call per row, each row over its OWN K/V pools
// (int8 codes + scales, and fp16);
// 3. gdn_step_norm_groups == gdn_step_norm_multi, one call per slot group, in the window (all outputs, the state
// untouched) and in the 1-row commit (the state written after `keep` tokens).
// Every case compares with memcmp, not a tolerance. Usage: batch_rows_parity
#include "strata/kernels/qsa.hpp"
#include "strata/kernels/qsa_decode_attn.hpp"
#include "strata/kernels/qsa_select.hpp"
#include "strata/kernels/verify_kernels.hpp"
#include <cuda_fp16.h>
#include <cuda_runtime.h>
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <vector>
namespace k = strata::kernels;
namespace {
void ck(cudaError_t e, const char* w) {
if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); }
}
template <typename T> T* up(const std::vector<T>& h) {
T* d = nullptr;
ck(cudaMalloc(&d, h.size() * sizeof(T) + 64), "malloc");
ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload");
return d;
}
template <typename T> std::vector<T> down(const T* d, size_t n) {
std::vector<T> h(n);
ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "download");
return h;
}
uint16_t f2h(float f) { __half h = __float2half(f); return *reinterpret_cast<uint16_t*>(&h); }
int bad = 0;
void report(const char* what, bool same) {
std::printf(" %-64s %s\n", what, same ? "bitwise" : "*** DIFFERS ***");
if (!same) ++bad;
}
// ---- 1. the block scores ----
void scores_case(int rows) {
const k::QsaShapes s = k::qsa_real_shapes();
const int64_t max_blocks = 3000;
std::mt19937 rng(11 + rows);
std::normal_distribution<float> nd(0.f, 1.f);
k::QsaScoreRows sr;
sr.n = rows;
std::vector<const float*> pooled(rows), dead(rows);
std::vector<float> q((size_t) rows * s.idx_n_head * s.idx_dim);
for (auto& x : q) x = nd(rng);
std::vector<int32_t> steps((size_t) rows * k::kStepCount);
for (int r = 0; r < rows; ++r) {
std::vector<float> p((size_t) max_blocks * s.idx_dim), d((size_t) s.idx_dim);
for (auto& x : p) x = nd(rng);
for (auto& x : d) x = nd(rng);
pooled[r] = up(p);
dead[r] = up(d);
sr.pooled[r] = pooled[r];
sr.dead[r] = dead[r];
const int64_t pos = 700 + 997 * r + (r % 3) * 5; // different lengths, and an incomplete block at the tail
steps[(size_t) r * k::kStepCount + k::kStepPos] = (int32_t) pos;
steps[(size_t) r * k::kStepCount + k::kStepNKv] = (int32_t) (pos + 1);
steps[(size_t) r * k::kStepCount + k::kStepNBid] = (int32_t) ((pos + 1) / s.idx_block);
steps[(size_t) r * k::kStepCount + k::kStepWidth] = (int32_t) k::qsa_selection_width(pos + 1, s);
}
const float* d_q = up(q);
const int32_t* d_steps = up(steps);
float *d_rows = nullptr, *d_ref = nullptr;
const size_t n = (size_t) rows * max_blocks;
ck(cudaMalloc(&d_rows, n * 4), "malloc");
ck(cudaMalloc(&d_ref, n * 4), "malloc");
ck(cudaMemset(d_rows, 0, n * 4), "memset");
ck(cudaMemset(d_ref, 0, n * 4), "memset");
k::qsa_block_scores_rows(sr, d_q, d_steps, rows, max_blocks, s, d_rows, nullptr);
for (int r = 0; r < rows; ++r)
k::qsa_block_scores(pooled[r], dead[r], d_q + (size_t) r * s.idx_n_head * s.idx_dim, d_steps + (size_t) r * k::kStepCount, 1,
max_blocks, s, d_ref + (size_t) r * max_blocks, nullptr);
ck(cudaDeviceSynchronize(), "sync");
const std::vector<float> a = down(d_rows, n), b = down(d_ref, n);
char name[96];
std::snprintf(name, sizeof name, "qsa_block_scores_rows, %d rows (own keys each)", rows);
report(name, std::memcmp(a.data(), b.data(), n * 4) == 0);
// the window selects with one top-k launch over all rows (row-independent) where the per-row path ran one per row
const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s);
int32_t *i_rows = nullptr, *i_ref = nullptr;
ck(cudaMalloc(&i_rows, (size_t) rows * cap * 4), "malloc");
ck(cudaMalloc(&i_ref, (size_t) rows * cap * 4), "malloc");
ck(cudaMemset(i_rows, 0, (size_t) rows * cap * 4), "memset");
ck(cudaMemset(i_ref, 0, (size_t) rows * cap * 4), "memset");
k::qsa_block_topk(d_ref, d_steps, rows, max_blocks, cap, s, i_rows, nullptr);
for (int r = 0; r < rows; ++r)
k::qsa_block_topk(d_ref + (size_t) r * max_blocks, d_steps + (size_t) r * k::kStepCount, 1, max_blocks, cap, s,
i_ref + (size_t) r * cap, nullptr);
ck(cudaDeviceSynchronize(), "sync");
const std::vector<int32_t> ta = down(i_rows, (size_t) rows * cap), tb = down(i_ref, (size_t) rows * cap);
bool tsame = true;
for (int r = 0; r < rows; ++r) {
const int64_t w = steps[(size_t) r * k::kStepCount + k::kStepWidth];
tsame = tsame && std::memcmp(ta.data() + (size_t) r * cap, tb.data() + (size_t) r * cap, (size_t) w * 4) == 0;
}
std::snprintf(name, sizeof name, "qsa_block_topk over %d rows == one call per row", rows);
report(name, tsame);
}
// ---- 2. the decode attention ----
void attn_case(int rows, bool int8) {
const k::QsaShapes s = k::qsa_real_shapes();
const int64_t HD = s.head_dim, NKV = s.n_head_kv, NH = s.n_head, PS = s.page_size;
const int64_t ctx_max = 5000, pages = (ctx_max + PS - 1) / PS, prow = pages * NKV * PS;
const int64_t cap = k::qsa_selection_width(ctx_max, s);
std::mt19937 rng(23 + rows + int8);
std::normal_distribution<float> nd(0.f, 1.f);
std::uniform_int_distribution<int> code(-127, 127);
std::uniform_real_distribution<float> sc(0.005f, 0.03f);
k::QsaAttnPoolsRows pr;
pr.n = rows;
std::vector<float> q((size_t) rows * NH * HD);
for (auto& x : q) x = nd(rng) * 2.0f;
std::vector<int32_t> ids((size_t) rows * cap, 0), steps((size_t) rows * k::kStepCount, 0);
for (int r = 0; r < rows; ++r) {
k::QsaAttnPools& pl = pr.p[r];
if (int8) {
std::vector<int8_t> kq((size_t) prow * HD), vq((size_t) prow * HD);
std::vector<uint16_t> ks((size_t) prow * (HD / 64)), vs(ks.size());
for (auto& x : kq) x = (int8_t) code(rng);
for (auto& x : vq) x = (int8_t) code(rng);
for (auto& x : ks) x = f2h(sc(rng));
for (auto& x : vs) x = f2h(sc(rng));
pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs);
} else {
std::vector<uint16_t> kh((size_t) prow * HD), vh(kh.size());
for (auto& x : kh) x = f2h(nd(rng) * 1.5f);
for (auto& x : vh) x = f2h(nd(rng));
pl.k_pool = up(kh); pl.v_pool = up(vh);
}
std::vector<int32_t> table(pages);
for (int64_t i = 0; i < pages; ++i) table[i] = (int32_t) i;
std::shuffle(table.begin(), table.end(), rng); // each row's pool has its own page order
pl.page_table = up(table);
const int64_t nkv = 900 + 641 * r + (r % 2) * 3;
const int64_t w = k::qsa_selection_width(nkv, s);
std::vector<int32_t> all((size_t) nkv);
for (int64_t c = 0; c < nkv; ++c) all[c] = (int32_t) c;
std::shuffle(all.begin(), all.end(), rng);
std::sort(all.begin(), all.begin() + w);
std::copy(all.begin(), all.begin() + w, ids.begin() + (size_t) r * cap);
steps[(size_t) r * k::kStepCount + k::kStepPos] = (int32_t) (nkv - 1);
steps[(size_t) r * k::kStepCount + k::kStepNKv] = (int32_t) nkv;
steps[(size_t) r * k::kStepCount + k::kStepNBid] = (int32_t) (nkv / s.idx_block);
steps[(size_t) r * k::kStepCount + k::kStepWidth] = (int32_t) w;
}
const float* d_q = up(q);
const int32_t* d_ids = up(ids);
const int32_t* d_steps = up(steps);
const int64_t scr = (int64_t) k::qsa_decode_attn_scratch_floats(cap, s);
float *scratch = nullptr, *d_rows = nullptr, *d_ref = nullptr;
ck(cudaMalloc(&scratch, (size_t) rows * scr * 4), "malloc");
const size_t n = (size_t) rows * NH * HD;
ck(cudaMalloc(&d_rows, n * 4), "malloc");
ck(cudaMalloc(&d_ref, n * 4), "malloc");
ck(cudaMemset(d_rows, 0, n * 4), "memset");
ck(cudaMemset(d_ref, 0, n * 4), "memset");
k::qsa_decode_attn_batch_rows(d_q, pr, d_ids, d_steps, cap, s, scratch, d_rows, rows, nullptr);
for (int r = 0; r < rows; ++r)
k::qsa_decode_attn_batch(d_q + (size_t) r * NH * HD, pr.p[r], d_ids + (size_t) r * cap, d_steps + (size_t) r * k::kStepCount, cap,
s, scratch + (size_t) r * scr, d_ref + (size_t) r * NH * HD, 1, nullptr);
ck(cudaDeviceSynchronize(), "sync");
const std::vector<float> a = down(d_rows, n), b = down(d_ref, n);
char name[96];
std::snprintf(name, sizeof name, "qsa_decode_attn_batch_rows, %d rows, %s pools (own pools each)", rows, int8 ? "int8" : "fp16");
report(name, std::memcmp(a.data(), b.data(), n * 4) == 0);
}
// ---- 3. the GDN recurrence ----
void gdn_case(const std::vector<int>& ntok, bool commit) {
const int S = 128, h_k = 16, h_v = 48; // the artifact's geometry
const int qk = S * h_k, C = 2 * qk + S * h_v, vd = S * h_v;
const float eps = 1e-6f;
int T = 0;
for (int n : ntok) T += n;
const int G = (int) ntok.size();
std::mt19937 rng(31 + T * 7 + G + commit);
std::normal_distribution<float> nd(0.f, 1.f);
std::vector<float> h((size_t) T * C), gate((size_t) T * h_v), beta((size_t) T * h_v), z((size_t) T * vd), gamma(S);
for (auto& v : h) v = nd(rng) * 0.1f;
for (auto& v : gate) v = -(0.5f + 3.0f * (float) (rng() % 100) / 100.0f);
for (auto& v : beta) v = (float) (rng() % 100) / 100.0f;
for (auto& v : z) v = nd(rng);
for (auto& v : gamma) v = 1.0f + 0.1f * nd(rng);
const size_t st_n = (size_t) S * h_v * S;
std::vector<std::vector<float>> st0(G);
std::vector<float*> st_g(G), st_r(G);
std::vector<int32_t*> keep(G);
k::GdnGroups gg;
gg.n = G;
int first = 0;
for (int i = 0; i < G; ++i) {
st0[i].resize(st_n);
for (auto& v : st0[i]) v = nd(rng) * 0.1f;
st_g[i] = up(st0[i]);
st_r[i] = up(st0[i]);
const int32_t kp = commit ? ntok[i] : 0; // a commit group keeps all of its rows here
keep[i] = up(std::vector<int32_t>{kp});
gg.state[i] = st_g[i];
gg.keep[i] = commit ? keep[i] : nullptr;
gg.first[i] = first;
gg.ntok[i] = ntok[i];
first += ntok[i];
}
const float* d_h = up(h);
const float* d_gate = up(gate);
const float* d_beta = up(beta);
const float* d_z = up(z);
const float* d_gm = up(gamma);
float *d_y = nullptr, *d_yr = nullptr;
ck(cudaMalloc(&d_y, (size_t) T * vd * 4), "malloc");
ck(cudaMalloc(&d_yr, (size_t) T * vd * 4), "malloc");
ck(cudaMemset(d_y, 0, (size_t) T * vd * 4), "memset");
ck(cudaMemset(d_yr, 0, (size_t) T * vd * 4), "memset");
k::gdn_step_norm_groups(gg, d_h, C, d_gate, d_beta, d_z, d_gm, eps, d_y, h_k, h_v, commit, nullptr);
for (int i = 0; i < G; ++i) {
const int f = gg.first[i];
// the engine's per-slot call: a window group runs its rows with all outputs; a commit group (1 row) keeps them
k::gdn_step_norm_multi(st_r[i], d_h + (size_t) f * C, C, d_gate + (size_t) f * h_v, d_beta + (size_t) f * h_v,
d_z + (size_t) f * vd, d_gm, eps, d_yr + (size_t) f * vd, h_k, h_v, ntok[i],
commit ? keep[i] : nullptr, nullptr, 0);
}
ck(cudaDeviceSynchronize(), "sync");
bool same = true;
for (int i = 0; i < G; ++i) {
const std::vector<float> a = down(st_g[i], st_n), b = down(st_r[i], st_n);
same = same && std::memcmp(a.data(), b.data(), st_n * 4) == 0;
if (!commit) same = same && std::memcmp(a.data(), st0[i].data(), st_n * 4) == 0; // a window leaves the state alone
}
if (!commit) {
const std::vector<float> a = down(d_y, (size_t) T * vd), b = down(d_yr, (size_t) T * vd);
same = same && std::memcmp(a.data(), b.data(), a.size() * 4) == 0;
}
char name[96], rows[64] = "";
for (int i = 0; i < G && i < 8; ++i) std::snprintf(rows + std::strlen(rows), sizeof rows - std::strlen(rows), "%s%d", i ? "," : "", ntok[i]);
std::snprintf(name, sizeof name, "gdn_step_norm_groups %s, groups of %s rows", commit ? "commit" : "window", rows);
report(name, same);
}
} // namespace
int main() {
std::printf("batch rows parity (#2234 kernels against the per-row launches)\n");
for (int r : {1, 2, 4, 8}) scores_case(r);
for (int r : {1, 3, 8}) {
attn_case(r, true);
attn_case(r, false);
}
gdn_case({1}, false);
gdn_case({1, 1, 1, 1}, false);
gdn_case({2, 2, 2, 2}, false);
gdn_case({1, 3, 2, 1, 1}, false);
gdn_case({1, 1, 1, 1, 1, 1, 1, 1}, false);
gdn_case({1}, true);
gdn_case({1, 1, 1, 1}, true);
gdn_case({1, 1, 1, 1, 1, 1, 1, 1}, true);
std::printf("%s\n", bad ? "batch_rows_parity: FAILED" : "batch_rows_parity: ok");
return bad ? 1 : 0;
}
+68
View File
@@ -117,6 +117,8 @@ __device__ __forceinline__ int reduce12_head_of_lane(int lane) {
}
// The chunk kernel's body; `p` is the query's KV pools (the call's one set, or blockIdx.z's slot's set).
// (the body is a device function so the batch window's rows kernel below can run it over each query's own pools without
// the default kernel's signature, or the function-pointer types the pre-sm_75 / HIP selections build, changing)
template <int KV_MODE, bool LANE_CELL, bool QUERY_SWIZZLE, bool REDUCE12>
__device__ __forceinline__ void attn_chunk_body(const float* __restrict__ q, QsaAttnPools p,
const int32_t* __restrict__ ids, const int32_t* __restrict__ step,
@@ -309,6 +311,20 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_slots_kernel(const float*
part_acc, part_m, part_l, n_chunks, cap, scratch_stride);
}
// Batch windows: query blockIdx.z attends over its own slot's pools (rows.p[z]); the default kernel otherwise.
template <int KV_MODE>
__global__ void __launch_bounds__(THREADS) attn_chunk_rows_kernel(const float* __restrict__ q, QsaAttnPoolsRows rows,
const int32_t* __restrict__ ids,
const int32_t* __restrict__ step, int n_kv_heads,
int page_size, float scale,
float* __restrict__ part_acc,
float* __restrict__ part_m,
float* __restrict__ part_l, int n_chunks, int cap,
long long scratch_stride) {
attn_chunk_body<KV_MODE, false, false, false>(q, rows.p[blockIdx.z], ids, step, n_kv_heads, page_size, scale,
part_acc, part_m, part_l, n_chunks, cap, scratch_stride);
}
// PR #540 (sskver): the same attention with fewer shuffles and less shared-memory traffic, bit for bit the kernel
// above (same operands, same order); +7% prompt speed on a V100, where this kernel reads every prompt chunk. It
// uses more registers (80 vs 38 on sm_70), so on CUDA it runs on cards below sm_75 only, and exists only in the
@@ -966,6 +982,58 @@ bool qsa_decode_attn_slots(const float* q, const QsaAttnSlotPools& pools, const
return true;
}
void qsa_decode_attn_batch_rows(const float* q, const QsaAttnPoolsRows& rows, const int32_t* ids, const int32_t* steps,
int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream) {
if (n_q <= 0) return;
const QsaAttnPools& pools = rows.p[0];
if (rows.n != n_q || n_q > kAttnRowsMax || s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 ||
!scratch || !ids || !steps) {
std::fprintf(stderr, "qsa_decode_attn_batch_rows: unsupported geometry or missing buffers\n");
std::exit(1);
}
const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3
: (pools.k_q != nullptr ? 1 : 0));
const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK);
const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s);
float* part_acc = scratch;
float* part_m = scratch + (size_t) n_chunks * s.n_head * HD;
float* part_l = part_m + (size_t) n_chunks * s.n_head;
const float scale = 1.0f / sqrtf((float) HD);
const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q);
cudaStream_t st = (cudaStream_t) stream;
// The plain kernel is what qsa_decode_attn_batch runs unless one of its variants is on (lane-cell scoring, the
// pre-sm_75 / gfx103x kernel, the gfx906 swizzle): there each row goes through that call, one launch per row.
static const bool lane_cell_rows = [] { const char* v = std::getenv("STRATA_ATTN_LANECELL"); return v && v[0] == '1'; }();
bool per_row = lane_cell_rows;
#if defined(STRATA_ATTN_PRE75_BUILT)
per_row = per_row || pre75_attn();
#endif
#if defined(STRATA_HIP_GFX906)
per_row = true;
#endif
if (per_row) {
for (int64_t r = 0; r < n_q; ++r)
qsa_decode_attn_batch(q + (size_t) r * s.n_head * HD, rows.p[r], ids + (size_t) r * cap,
steps + (size_t) r * kStepCount, cap, s, scratch + (size_t) r * stride,
attn + (size_t) r * s.n_head * HD, 1, stream);
return;
}
#define STRATA_ATTN_ROWS(M) attn_chunk_rows_kernel<M><<<grid, THREADS, 0, st>>>(q, rows, ids, steps, (int) s.n_head_kv, \
(int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride)
if (kv_mode == 3) STRATA_ATTN_ROWS(3);
else if (kv_mode == 2) STRATA_ATTN_ROWS(2);
else if (kv_mode == 1) STRATA_ATTN_ROWS(1);
else STRATA_ATTN_ROWS(0);
#undef STRATA_ATTN_ROWS
launch_merge(attn_merge_v2(), part_acc, part_m, part_l, n_chunks, steps, attn, stride, (unsigned) s.n_head,
(unsigned) n_q, st);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "qsa_decode_attn_batch_rows: %s\n", cudaGetErrorString(e));
std::exit(1);
}
}
uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s) {
const int64_t chunks = (cap + CHUNK - 1) / CHUNK;
return (uint64_t) chunks * (uint64_t) s.n_head * (HD + 2) + 64;
+27 -7
View File
@@ -835,7 +835,8 @@ __device__ __forceinline__ void block_scores_multi_body(const float* __restrict_
const float* __restrict__ dead,
const float* __restrict__ q_idx,
const int32_t* __restrict__ steps, int nq, int64_t max_blocks,
float* __restrict__ out, bool early_exit) {
float* __restrict__ out, bool early_exit,
const QsaScoreRows& srow) {
__shared__ __align__(16) float qs[MQ * IDX_HEADS * IDX_DIM];
__shared__ int64_t s_nkv[MQ], s_nbid[MQ];
if (!early_exit)
@@ -858,12 +859,16 @@ __device__ __forceinline__ void block_scores_multi_body(const float* __restrict_
const int lane = threadIdx.x & 31;
const int64_t wstride = (int64_t) gridDim.x * SCORE_WARPS;
for (int64_t b = (int64_t) blockIdx.x * SCORE_WARPS + (threadIdx.x >> 5); b <= top && b < max_blocks; b += wstride) {
const float4 kp = *reinterpret_cast<const float4*>(pooled + b * IDX_DIM + lane * 4);
const float4 kd = *reinterpret_cast<const float4*>(dead + lane * 4);
// srow.n > 0: each query reads its own sequence's keys; else one set of keys for every query
const bool own = srow.n > 0;
const float4 kp = own ? float4{} : *reinterpret_cast<const float4*>(pooled + b * IDX_DIM + lane * 4);
const float4 kd = own ? float4{} : *reinterpret_cast<const float4*>(dead + lane * 4);
for (int qi = 0; qi < nq; ++qi) {
const int64_t n_bid = s_nbid[qi];
if (b > n_bid) continue;
const float4 k4 = (b == n_bid) ? kd : kp;
const float4 k4 = !own ? ((b == n_bid) ? kd : kp)
: (b == n_bid) ? *reinterpret_cast<const float4*>(srow.dead[qi] + lane * 4)
: *reinterpret_cast<const float4*>(srow.pooled[qi] + b * IDX_DIM + lane * 4);
const float* q = qs + qi * IDX_HEADS * IDX_DIM + lane * 4;
float score = 0.0f;
#pragma unroll
@@ -887,8 +892,8 @@ __global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_multi_kernel(co
const float* __restrict__ q_idx,
const int32_t* __restrict__ steps, int nq,
int64_t max_blocks, float* __restrict__ out,
bool early_exit) {
block_scores_multi_body(pooled, dead, q_idx, steps, nq, max_blocks, out, early_exit);
bool early_exit, QsaScoreRows srow = {}) {
block_scores_multi_body(pooled, dead, q_idx, steps, nq, max_blocks, out, early_exit, srow);
}
// Queries of different slots, each with its own indexer keys: blockIdx.y is the query, and its CTAs run exactly the
@@ -910,7 +915,8 @@ __global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_slots_kernel(Sc
for (unsigned i = 1; i < MQ; ++i)
if (z == i) { pooled = keys.pooled[i]; dead = keys.dead[i]; }
block_scores_multi_body(pooled, dead, q_idx + (size_t) z * IDX_HEADS * IDX_DIM,
steps + (size_t) z * kStepCount, 1, max_blocks, out + (size_t) z * max_blocks, early_exit);
steps + (size_t) z * kStepCount, 1, max_blocks, out + (size_t) z * max_blocks, early_exit,
QsaScoreRows{});
}
// QSAROWS (docs/QSAROWS.md, STRATA_QSA_ROWS=1): block_scores_multi_kernel's work for NQ <= 4 queries with less issue
@@ -1284,6 +1290,20 @@ bool qsa_block_scores_rows(const float* pooled, const float* dead, const float*
return true;
}
void qsa_block_scores_rows(const QsaScoreRows& rows, const float* q_idx, const int32_t* steps, int64_t nq,
int64_t max_blocks, const QsaShapes& s, float* scores, void* stream) {
if (nq <= 0) return;
if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R || nq > MQ || rows.n != nq) {
std::fprintf(stderr, "qsa_block_scores_rows: unsupported geometry\n");
std::exit(1);
}
static const bool early = [] { const char* v = std::getenv("STRATA_QSA_EARLY_EXIT"); return v == nullptr || std::atoi(v) != 0; }();
block_scores_multi_kernel<<<256, SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(nullptr, nullptr, q_idx, steps, (int) nq,
max_blocks, scores, early, rows);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores_rows: %s\n", cudaGetErrorString(e)); std::exit(1); }
}
bool qsa_block_scores_tc(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq,
int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks) {
if (nq <= 0) return true;
+106 -1
View File
@@ -291,7 +291,18 @@ __global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __re
const float* __restrict__ gamma, float eps,
float* __restrict__ y, int h_k, int h_v, int T,
const int32_t* __restrict__ n_keep, int t_out_begin,
GdnQ81* __restrict__ xq) {
GdnQ81* __restrict__ xq, GdnGroups grp = {}) {
if (grp.n > 0) { // group blockIdx.y - its slot's state and its rows of the window's buffers
const int gi = blockIdx.y, f = grp.first[gi];
state = grp.state[gi];
hbuf += (size_t) f * C;
gate += (size_t) f * h_v;
beta += (size_t) f * h_v;
z += (size_t) f * S * h_v;
y += (size_t) f * S * h_v;
T = grp.ntok[gi];
n_keep = grp.keep[gi];
}
__shared__ float sk[2][S], sq[2][S];
__shared__ float red_kv[RG][S];
__shared__ float red_o[RG][S];
@@ -1059,6 +1070,30 @@ void gdn_ab_multi(const float* x, const uint16_t* w_alpha, const uint16_t* w_bet
check("gdn_ab_multi");
}
void gdn_step_norm_groups(const GdnGroups& groups, const float* h, int conv_channels, const float* gate, const float* beta,
const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, bool commit,
void* stream) {
if (groups.n < 1 || groups.n > 8 || !h || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v % h_k) {
std::fprintf(stderr, "gdn_step_norm_groups: invalid arguments\n");
std::exit(1);
}
for (int i = 0; i < groups.n; ++i)
if (!groups.state[i] || groups.ntok[i] < 1 || groups.ntok[i] > kVerifyMaxT || (commit && !groups.keep[i])) {
std::fprintf(stderr, "gdn_step_norm_groups: invalid group %d\n", i);
std::exit(1);
}
const dim3 g1((unsigned) h_v, (unsigned) groups.n), b1(S, RG);
// the kernel gdn_step_norm_multi picks for these calls: a window's rows (all outputs, no keep) or a commit of
// one-row groups (keep, t_out_begin 0)
if (commit)
gdn_step_norm_multi_kernel<false, false><<<g1, b1, 0, (cudaStream_t) stream>>>(
nullptr, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, 0, nullptr, 0, nullptr, groups);
else
gdn_step_norm_multi_kernel<true, false><<<g1, b1, 0, (cudaStream_t) stream>>>(
nullptr, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, 0, nullptr, 0, nullptr, groups);
check("gdn_step_norm_groups");
}
void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta,
const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok,
const int32_t* n_keep, void* stream, int t_out_begin, void* xq_out) {
@@ -1121,8 +1156,78 @@ __global__ void wait_flag_ge_kernel(const volatile uint32_t* flag, uint32_t valu
while (*flag < value) strata_spin_pause();
__threadfence_system();
}
// the GPU's clock in ns (the same sources as gpu_stamp_kernel)
__device__ __forceinline__ unsigned long long strata_now_ns() {
unsigned long long t;
#if defined(STRATA_HIP_GFX906)
t = wall_clock64() * 40ull;
#elif defined(__HIPCC__)
t = wall_clock64() * 10ull;
#else
asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t));
#endif
return t;
}
// the overlapped split's hand-off wait, bounded: spin until *flag >= value, or give up after timeout_ns (0: never),
// marking *err = 1 (mapped) so the host fails the window instead of using a stale hand-off. The window's later
// kernels still run (on whatever the hand-off buffer holds) so the graph completes and no stream is left hanging.
__global__ void wait_handoff_kernel(const volatile uint32_t* flag, uint32_t value, uint32_t* err,
unsigned long long timeout_ns) {
const unsigned long long t0 = timeout_ns ? strata_now_ns() : 0ull;
while (*flag < value) {
strata_spin_pause();
if (timeout_ns && strata_now_ns() - t0 > timeout_ns) {
*(volatile uint32_t*) err = 1u;
__threadfence_system();
return;
}
}
__threadfence_system();
}
__global__ void handoff_publish_kernel(float* dst, const float* __restrict__ a, int64_t na, const float* __restrict__ b,
int64_t nb, const float* __restrict__ c, int64_t nc, uint32_t* counter,
uint32_t* flag, const volatile uint32_t* drop) {
const int64_t n = na + nb + nc;
volatile float* const out = dst;
for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x)
out[i] = i < na ? a[i] : i < na + nb ? b[i - na] : c[i - na - nb];
__threadfence_system(); // this thread's stores reach host memory before the block counts itself done
__syncthreads();
if (threadIdx.x == 0) {
const uint32_t prev = atomicAdd(counter, 1u);
if (prev == gridDim.x - 1) { // every block's payload is out: raise the next stage's flag
*(volatile uint32_t*) counter = 0u;
__threadfence_system();
if (drop == nullptr || *drop == 0u) { // test hook (STRATA_TEST_HANDOFF_DROP): a lost publish
*(volatile uint32_t*) flag = 1u;
__threadfence_system();
}
}
}
}
} // namespace
void wait_handoff(const uint32_t* flag, uint32_t value, uint32_t* err, unsigned long long timeout_ns, void* stream) {
wait_handoff_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(flag, value, err, timeout_ns);
check("wait_handoff");
}
void handoff_publish(float* dst, const float* a, int64_t na, const float* b, int64_t nb, const float* c, int64_t nc,
uint32_t* counter, uint32_t* flag, void* stream, const uint32_t* drop) {
const int64_t n = na + nb + nc;
if (n <= 0 || dst == nullptr || counter == nullptr || flag == nullptr) {
std::fprintf(stderr, "handoff_publish: invalid arguments\n");
std::exit(1);
}
const int64_t nb256 = (n + 255) / 256;
const int blocks = (int) (nb256 < 64 ? nb256 : 64);
handoff_publish_kernel<<<blocks, 256, 0, (cudaStream_t) stream>>>(dst, a, na, b, nb, c, nc, counter, flag, drop);
check("handoff_publish");
}
namespace {
// one thread per window entry: up to kVerifyMaxT tokens x 10 routed experts (80), so 128 (#646 had 64: a window of
// 7+ tokens lost its last entries)
+10
View File
@@ -18,6 +18,7 @@
#endif
#include <algorithm>
#include <atomic>
#include <mutex>
#include <thread>
#include <vector>
#include <stdexcept>
@@ -212,6 +213,8 @@ struct PleTable::Impl {
strata::ngram::PleReader::Ticket ticket;
bool pending = false;
bool locked = false;
// the table is shared by the prompt path and the decode windows; they can use it at once (one on a worker thread)
std::recursive_mutex mu;
uint32_t rows[PLE_N_HEADS] = {};
uint8_t raw[PLE_N_HEADS * PLE_ROW_BYTES_MAX] = {};
static constexpr size_t kMaxPrefetch = 16;
@@ -389,6 +392,7 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO
}
void PleTable::wait_prefetches() {
std::lock_guard<std::recursive_mutex> lk(impl_->mu);
if (impl_->n_prefetch == 0) return;
std::string dummy;
for (size_t i = 0; i < impl_->n_prefetch; ++i) (void) impl_->reader.collect(impl_->prefetch_tickets[i], dummy);
@@ -396,6 +400,7 @@ void PleTable::wait_prefetches() {
}
void PleTable::prefetch_rows(const uint32_t* rows16) {
std::lock_guard<std::recursive_mutex> lk(impl_->mu);
if (impl_->mode == PleIo::Direct && impl_->reader.is_open()) {
for (size_t i = 0; i < impl_->n_prefetch; ++i)
if (std::memcmp(impl_->prefetch_keys[i], rows16, sizeof(uint32_t) * PLE_N_HEADS) == 0) return;
@@ -444,6 +449,7 @@ uint64_t PleTable::rows() const { return impl_->n_rows; }
uint64_t PleTable::bytes_read() const { return impl_->bytes_read; }
void PleTable::read_row(uint32_t row, float* out160) const {
std::lock_guard<std::recursive_mutex> lk(impl_->mu);
if (impl_->mode == PleIo::Direct && impl_->reader.is_open()) {
uint8_t raw[PLE_ROW_BYTES_MAX];
std::string err;
@@ -465,6 +471,7 @@ void PleTable::read_row(uint32_t row, float* out160) const {
}
bool PleTable::issue(const uint32_t* rows16) {
std::lock_guard<std::recursive_mutex> lk(impl_->mu);
wait_prefetches();
std::memcpy(impl_->rows, rows16, sizeof impl_->rows);
if (impl_->mode == PleIo::Direct) {
@@ -491,6 +498,7 @@ bool PleTable::issue(const uint32_t* rows16) {
}
bool PleTable::collect(float* out2560, std::string& err) {
std::lock_guard<std::recursive_mutex> lk(impl_->mu);
if (!impl_->pending) { err = "PleTable::collect without issue"; return false; }
impl_->pending = false;
if (impl_->mode == PleIo::Direct) {
@@ -505,6 +513,7 @@ bool PleTable::collect(float* out2560, std::string& err) {
}
bool PleTable::gather_batch(const uint32_t* rows, size_t n_tokens, float* out, std::string& err) {
std::lock_guard<std::recursive_mutex> lk(impl_->mu);
if (impl_->pending) { err = "PleTable::gather_batch while a token is in flight"; return false; }
const size_t n = n_tokens * (size_t) PLE_N_HEADS;
if (impl_->mode == PleIo::Direct) {
@@ -605,6 +614,7 @@ std::string PleTable::io_report() const {
}
void PleTable::gather(const uint32_t* rows16, float* out2560) const {
std::lock_guard<std::recursive_mutex> lk(impl_->mu); // issue + collect as one
if (impl_->mode == PleIo::Direct) {
// `gather` stays const for its existing callers; the reader's state is the table's I/O state.
PleTable* self = const_cast<PleTable*>(this);