Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

C-1, C-2: the prompt path's QSA select grid reaches only the active blocks; the indexer appends a chunk at once

Niko12210c26102af4eb
diff --git a/include/strata/kernels/native_qsa_indexer.hpp b/include/strata/kernels/native_qsa_indexer.hpp
index a79fd47ce..560b12b5b 100644
--- a/include/strata/kernels/native_qsa_indexer.hpp
+++ b/include/strata/kernels/native_qsa_indexer.hpp
@@ -27,6 +27,13 @@ bool native_qsa_indexer_enabled();
// max_cells is a positive fixed capacity; pos_base+max_cells must fit int32.
// Out-of-range device positions are ignored defensively, not host-validated.
// This adapter does not alter score accumulation, top-k, or finite 1e9 tail bias.
+// perf-review C-2: the appends of cells [p0, p0 + n) at once, leaving the buffers exactly as n calls of the
+// single append in order would (the prompt path appends a chunk before any query reads the state). raw [n, 128].
+// Host-side positions (not for a captured graph).
+void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, int32_t pos_base, const float* gamma,
+ float epsilon, const QsaIndexerBuffers& b, const QsaShapes& s, int64_t max_cells,
+ float freq_base, void* stream);
+
void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_device,
int32_t pos_base, const float* gamma, float epsilon,
const QsaIndexerBuffers& buffers, const QsaShapes& shapes,
diff --git a/include/strata/kernels/qsa_select.hpp b/include/strata/kernels/qsa_select.hpp
index d04009d58..962c76916 100644
--- a/include/strata/kernels/qsa_select.hpp
+++ b/include/strata/kernels/qsa_select.hpp
@@ -24,7 +24,9 @@ namespace strata::kernels {
/// scores [nq, max_blocks]; q_idx [nq, idx_n_head, idx_dim] (normed and rotated); steps [nq, kStepCount].
void qsa_block_scores(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 max_blocks, const QsaShapes& s, float* scores, void* stream,
+ int64_t active_blocks = -1); ///< perf-review C-1: > 0 launches only this many blocks (the
+ ///< batch's largest n_bid + 1; not for a captured graph)
/// ids [nq, cap] (cells, ascending); `cap` >= the largest selection width.
void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,
diff --git a/src/kernels/cuda/native_qsa_indexer.cu b/src/kernels/cuda/native_qsa_indexer.cu
index b80009b52..8a5ecbc3c 100644
--- a/src/kernels/cuda/native_qsa_indexer.cu
+++ b/src/kernels/cuda/native_qsa_indexer.cu
@@ -93,6 +93,97 @@ __global__ void append(const float* __restrict__ raw, const int32_t* __restrict_
else pooled[std::size_t(b + 1) * D + d] = dead[d];
if (d == 0 && pos != 0) *block_pos = rope_pos;
}
+// ---- C-2: the batched append. The pooled key of a completed block b (its last cell pos = 4b+3), computed with
+// the single append's arithmetic: keys rounded through F16, summed tail[0]+tail[1]+tail[2]+incoming in that order,
+// the RMS norm, gamma, the rotation at pos_base + 4b. `k(j)` is the key of the block's cell j: a row of this batch
+// (cell >= p0) or the tail the previous batch left (cell < p0). Only the batch's last completed block writes the
+// spare after it (every earlier one's is overwritten by the next block in order).
+__device__ __forceinline__ float pooled_value(const float* values, int d, int rope_pos, float theta_scale,
+ const int32_t* mtab, bool zero_pos) {
+ float y = values[d];
+ if (d < ROT) {
+ const int pair = d % (ROT / 2);
+ const float theta = (zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair));
+ const float c = cosf(theta), s = sinf(theta);
+ const float a = values[pair], z = values[pair + ROT / 2];
+ y = d < ROT / 2 ? a * c - z * s : a * s + z * c;
+ }
+ return y;
+}
+__device__ __forceinline__ float norm_scale(float mean, float* partials, int d) {
+ float square_sum = d < D ? mean * mean : 0.0f;
+ square_sum = warp_sum(square_sum);
+ const int lane = d % 32;
+ if (lane == 0) partials[d / 32] = square_sum;
+ __syncthreads();
+ square_sum = lane < THREADS / 32 ? partials[lane] : 0.0f;
+ square_sum = warp_sum(square_sum);
+ return square_sum;
+}
+// cell 0 of a sequence: the spare (every gather index names cell 0), written to pooled[0] and dead
+__global__ void append_first(const float* __restrict__ raw, const float* __restrict__ gamma, float epsilon,
+ float* __restrict__ dead, float* __restrict__ pooled, float theta_scale,
+ const int32_t* __restrict__ mtab) {
+ const int d = threadIdx.x;
+ __shared__ float values[D];
+ __shared__ float partials[32];
+ float mean = 0.0f;
+ if (d < D) {
+ const float incoming = __half2float(__float2half_rn(raw[d]));
+ float sum = incoming;
+#pragma unroll
+ for (int j = 1; j < R; ++j) sum = __fadd_rn(sum, incoming);
+ mean = __fmaf_rn(0.25f, sum, 0.0f);
+ }
+ const float square_sum = norm_scale(mean, partials, d);
+ const float scale = rsqrtf(square_sum / D + epsilon);
+ if (d < D) values[d] = scale * mean * gamma[d];
+ __syncthreads();
+ if (d >= D) return;
+ const float y = pooled_value(values, d, 0, theta_scale, mtab, true);
+ pooled[d] = y;
+ dead[d] = y;
+}
+__global__ void append_blocks(const float* __restrict__ raw, int64_t n, int64_t p0, int pos_base,
+ const float* __restrict__ gamma, float epsilon, const float* __restrict__ tail,
+ const float* __restrict__ dead, float* __restrict__ pooled, int32_t* __restrict__ block_pos,
+ int64_t first_block, int64_t last_block, float theta_scale, const int32_t* __restrict__ mtab) {
+ const int64_t b = first_block + blockIdx.x;
+ const int d = threadIdx.x;
+ __shared__ float values[D];
+ __shared__ float partials[32];
+ float mean = 0.0f;
+ if (d < D) {
+ auto key = [&](int j) -> float {
+ const int64_t cell = b * R + j;
+ return cell >= p0 ? __half2float(__float2half_rn(raw[(cell - p0) * D + d])) : tail[j * D + d];
+ };
+ float sum = key(0);
+#pragma unroll
+ for (int j = 1; j < R; ++j) sum = __fadd_rn(sum, key(j));
+ mean = __fmaf_rn(0.25f, sum, 0.0f);
+ }
+ const float square_sum = norm_scale(mean, partials, d);
+ const float scale = rsqrtf(square_sum / D + epsilon);
+ if (d < D) values[d] = scale * mean * gamma[d];
+ __syncthreads();
+ if (d >= D) return;
+ const int rope_pos = pos_base + R * (int) b;
+ pooled[std::size_t(b) * D + d] = pooled_value(values, d, rope_pos, theta_scale, mtab, false);
+ if (b == last_block) {
+ pooled[std::size_t(b + 1) * D + d] = dead[d];
+ if (d == 0) *block_pos = rope_pos;
+ }
+}
+// the tail after the batch: slot s holds the key of the batch's last cell with cell % 4 == s (s < 3), if any
+__global__ void append_tail(const float* __restrict__ raw, int64_t n, int64_t p0, float* __restrict__ tail) {
+ const int s = blockIdx.x, d = threadIdx.x;
+ if (d >= D) return;
+ const int64_t last = p0 + n - 1;
+ int64_t cell = last - ((last % R) - s + R) % R; // the last cell <= last with cell % 4 == s
+ if (cell < p0) return;
+ tail[s * D + d] = __half2float(__float2half_rn(raw[(cell - p0) * D + d]));
+}
struct Span { const void* p; std::size_t n; };
void validate(Span s) {
const auto p = reinterpret_cast<std::uintptr_t>(s.p);
@@ -126,4 +217,27 @@ void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_dev
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
+void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, int32_t pos_base, const float* gamma,
+ float epsilon, const QsaIndexerBuffers& b, const QsaShapes& s, int64_t max_cells,
+ float freq_base, void* stream) {
+ if (n <= 0) return;
+ if (!stream || s.idx_dim != D || s.idx_block != R || s.n_rot != ROT || p0 < 0 || p0 + n > max_cells ||
+ max_cells > INT32_MAX || pos_base < 0 || pos_base % R || int64_t(pos_base) + max_cells > INT32_MAX ||
+ !std::isfinite(epsilon) || epsilon <= 0.0f || !std::isfinite(freq_base) || freq_base <= 1.0f)
+ throw std::invalid_argument("native QSA indexer (batch): bad geometry, positions or parameters");
+ const float theta_scale = powf(freq_base, -2.0f / ROT);
+ const cudaStream_t st = static_cast<cudaStream_t>(stream);
+ const int32_t* mtab = mrope_table();
+ if (p0 == 0) append_first<<<1, THREADS, 0, st>>>(raw, gamma, epsilon, b.dead, b.pooled, theta_scale, mtab);
+ // completed blocks: those whose last cell (4b+3) lies in [p0, p0 + n)
+ const int64_t first = p0 <= R - 1 ? 0 : (p0 - (R - 1) + R - 1) / R; // the smallest b with 4b+3 >= p0
+ const int64_t hi = p0 + n - 1 >= R - 1 ? (p0 + n - 1 - (R - 1)) / R : -1; // the largest b with 4b+3 <= p0+n-1
+ if (hi >= first)
+ append_blocks<<<(unsigned) (hi - first + 1), THREADS, 0, st>>>(raw, n, p0, pos_base, gamma, epsilon, b.tail,
+ b.dead, b.pooled, b.block_pos, first, hi,
+ theta_scale, mtab);
+ append_tail<<<R - 1, D, 0, st>>>(raw, n, p0, b.tail);
+ const auto error = cudaGetLastError();
+ if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
+}
} // namespace strata::kernels
diff --git a/src/kernels/cuda/qsa_select.cu b/src/kernels/cuda/qsa_select.cu
index 6b13b2ff1..468d21e71 100644
--- a/src/kernels/cuda/qsa_select.cu
+++ b/src/kernels/cuda/qsa_select.cu
@@ -151,13 +151,15 @@ __global__ void __launch_bounds__(TOPK_T) block_topk_kernel(const float* __restr
} // namespace
void qsa_block_scores(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 max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks) {
if (nq <= 0) return;
if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R || nq > 65535) {
std::fprintf(stderr, "qsa_block_scores: unsupported indexer geometry\n");
std::exit(1);
}
- const dim3 grid((unsigned) ((max_blocks + SCORE_WARPS - 1) / SCORE_WARPS), (unsigned) nq);
+ // a block past a query's n_bid returns at once: the grid need only reach the batch's largest n_bid (C-1)
+ const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks;
+ const dim3 grid((unsigned) ((reach + SCORE_WARPS - 1) / SCORE_WARPS), (unsigned) nq);
block_scores_kernel<<<grid, SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(pooled, dead, q_idx, steps, max_blocks,
scores);
const cudaError_t e = cudaGetLastError();
diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp
index 83ac0b8c3..474367b5c 100644
--- a/src/prefill/prefill.cpp
+++ b/src/prefill/prefill.cpp
@@ -1070,20 +1070,31 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
// a query reads completed blocks (final once completed) and `dead` for its own tail block
const strata::kernels::QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};
pt.mark(kPfQsaIdx, cs);
- for (int64_t t = 0; t < T; ++t) {
- const int32_t* step_t = m.steps_dev + t * strata::kernels::kStepCount;
- try {
+ // C-2: the chunk's appends in three launches instead of one per token (the same end state:
+ // the queries below read it only after the whole chunk is appended). STRATA_INDEXER_PER_TOKEN=1: the old
+ try {
+ static const bool per_token = std::getenv("STRATA_INDEXER_PER_TOKEN") != nullptr;
+ if (!per_token) {
+ strata::kernels::native_qsa_indexer_append_batch(m.idx_raw, T, p0, 0, (const float*) wikn->data,
+ EPS, ib, s, st.max_cells,
+ (float) strata::kernels::qsa_freq_base(), m.cs);
+ }
+ for (int64_t t = 0; per_token && t < T; ++t) {
+ const int32_t* step_t = m.steps_dev + t * strata::kernels::kStepCount;
strata::kernels::native_qsa_indexer_append(m.idx_raw + t * 128, step_t + strata::kernels::kStepPos, 0,
(const float*) wikn->data, EPS, ib, s, st.max_cells,
(float) strata::kernels::qsa_freq_base(), m.cs);
- } catch (const std::exception& e) { err = std::string("prefill indexer: ") + e.what(); return false; }
- }
+ }
+ } catch (const std::exception& e) { err = std::string("prefill indexer: ") + e.what(); return false; }
pt.mark(kPfQsaSel, cs);
for (int64_t t0 = 0; t0 < T; t0 += m.sel_batch) {
const int64_t nb = std::min(m.sel_batch, T - t0);
const int32_t* steps0 = m.steps_dev + t0 * strata::kernels::kStepCount;
+ // C-1: the grid reaches the batch's last query's n_bid (they rise with the position)
+ const int64_t active = (int64_t) m.steps_host[(size_t) ((t0 + nb - 1) * strata::kernels::kStepCount +
+ strata::kernels::kStepNBid)] + 1;
strata::kernels::qsa_block_scores(st.idx_pooled, st.idx_dead, m.q_idx + t0 * 512, steps0, nb,
- m.max_blocks, s, m.sel_scores, m.cs);
+ m.max_blocks, s, m.sel_scores, m.cs, active);
strata::kernels::qsa_block_topk(m.sel_scores, steps0, nb, m.max_blocks, m.cap, s,
m.sel_ids + t0 * m.cap, m.cs);
}