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++

perf(kv): batched K/V and indexer append for the verify window, the commit graph and the MTP catch-up (#783 PR-d)

Niko122144ffa86c53c6
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 5cd06a5e4..a902781ff 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -810,6 +810,11 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
target_include_directories(native_multi_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(native_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME native_multi_parity COMMAND native_multi_parity)
+ # #783 PR-d: the batched K/V append (INT8, Q4_0, the hybrid fold) against the per-cell appends, memcmp
+ add_executable(kv_steps_parity src/kernels/kv_steps_parity.cpp)
+ target_include_directories(kv_steps_parity PRIVATE ${_strata_gpu_include_directories})
+ target_link_libraries(kv_steps_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
+ add_test(NAME kv_steps_parity COMMAND kv_steps_parity)
if(STRATA_HIP_GFX906)
# the S6 router (STRATA_HIP_ROUTER_FAST=1 on gfx906) against the portable kernel, bitwise, on wave64
add_executable(hip_router_fast tests/hip/router_fast.cpp)
diff --git a/include/strata/kernels/kv_q4.hpp b/include/strata/kernels/kv_q4.hpp
index 930b628c1..2276d35a5 100644
--- a/include/strata/kernels/kv_q4.hpp
+++ b/include/strata/kernels/kv_q4.hpp
@@ -47,6 +47,10 @@ void kv_append_q4_step(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table,
const float* kcur, const float* vcur, const QsaShapes& s, void* stream,
const KvHostPools* host = nullptr);
+void kv_append_q4_steps(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, const int32_t* step,
+ int step_stride, int n_steps, const float* kcur, const float* vcur, const QsaShapes& s,
+ void* stream, const KvHostPools* host = nullptr);
+
/// The prompt path: T consecutive (rotated) cells from pos0, K/V [T, n_head_kv, 256]; also into `stage` (identity
/// layout, the one-layer staging pool of a streamed session) when given.
void kv_append_q4(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, int64_t pos0, int64_t T, const float* K,
diff --git a/include/strata/kernels/native_qsa_indexer.hpp b/include/strata/kernels/native_qsa_indexer.hpp
index fe66d4b06..092af4519 100644
--- a/include/strata/kernels/native_qsa_indexer.hpp
+++ b/include/strata/kernels/native_qsa_indexer.hpp
@@ -43,4 +43,10 @@ void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_dev
const QsaIndexerBuffers& buffers, const QsaShapes& shapes,
int64_t max_cells, const RopeScaling& scaling, void* stream);
+void native_qsa_indexer_append_steps(const float* raw, const int32_t* relative_pos_device,
+ int pos_stride, int n_steps, int32_t pos_base,
+ const float* gamma, float epsilon,
+ const QsaIndexerBuffers& buffers, const QsaShapes& shapes,
+ int64_t max_cells, const RopeScaling& scaling, void* stream);
+
} // namespace strata::kernels
diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp
index 9941e55ce..3bd18b270 100644
--- a/src/core/mtp.cpp
+++ b/src/core/mtp.cpp
@@ -701,23 +701,40 @@ bool MtpDrafter::record_front(int T, int row0, cudaStream_t cs, std::string& err
native_quantize_q8_1(mixed_, xq_, (int) N, T, cs);
native_mmvq(wt_k_proj, wp_k_proj, xq_, kcur_, (int) N, (int) (NKV * HD), T, cs);
native_mmvq(wt_v_proj, wp_v_proj, xq_, vcur_, (int) N, (int) (NKV * HD), T, cs);
+ // #783 PR-d (stuchapin909): the T tokens' K norm, K/V rotation and K/V append each run once over all T rows
+ // (every row is independent; the rope keeps its per-token positions). STRATA_NO_BATCH_KV_STEP=1 appends per token.
+ static const bool no_batch_kv = [] {
+ const char* v = std::getenv("STRATA_NO_BATCH_KV_STEP");
+ return v != nullptr && v[0] != '\0' && v[0] != '0';
+ }();
+ native_qsa_rms_norm_weighted(kcur_, f32("self_attn.k_norm.weight"), kcur_, (int) HD, (int) (T * NKV), EPS, cs);
for (int t = 0; t < T; ++t) {
- norm_rope(kcur_ + t * NKV * HD, f32("self_attn.k_norm.weight"), (int) NKV, (int) HD, pos + t * NH, cs);
- if (st_.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1
- fwht256_inplace_cuda(kcur_ + t * NKV * HD, NKV, cs);
- fwht256_inplace_cuda(vcur_ + t * NKV * HD, NKV, cs);
- }
- // stored in the state's own format (#293 appended rotated INT8 K/V as Q4_0, into pools INT8 never has)
- if (st_.kv_q4)
- kv_append_q4_step(st_.k_q4, st_.v_q4, st_.page_table, step + t * 4, kcur_ + t * NKV * HD,
- vcur_ + t * NKV * HD, s, cs, &st_.host);
- else if (st_.kv_int8)
- kv_append_q8_step(st_.k_q, st_.v_q, st_.k_scale, st_.v_scale, st_.page_table, step + t * 4,
- kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st_.host);
- else
- kv_append_step(st_.k_pool, st_.v_pool, st_.page_table, step + t * 4, kcur_ + t * NKV * HD,
- vcur_ + t * NKV * HD, s, cs, &st_.host);
+ float* kc = kcur_ + t * NKV * HD;
+ if (native_rope_enabled()) native_rope_apply(kc, kc, (int) NKV, (int) HD, (int) s.n_rot, rope_scaling(), pos + t * NH, cs);
+ else rope_neox_apply(kc, kc, (int) NKV, (int) HD, (int) s.n_rot, st_.cos_tab, st_.sin_tab, pos + t * NH, cs);
+ }
+ if (st_.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1
+ fwht256_inplace_cuda(kcur_, (int64_t) T * NKV, cs);
+ fwht256_inplace_cuda(vcur_, (int64_t) T * NKV, cs);
}
+ // stored in the state's own format (#293 appended rotated INT8 K/V as Q4_0, into pools INT8 never has)
+ if (!no_batch_kv && st_.kv_q4)
+ kv_append_q4_steps(st_.k_q4, st_.v_q4, st_.page_table, step, 4, T, kcur_, vcur_, s, cs, &st_.host);
+ else if (!no_batch_kv && st_.kv_int8)
+ kv_append_q8_steps(st_.k_q, st_.v_q, st_.k_scale, st_.v_scale, st_.page_table, step, 4, kcur_, vcur_,
+ (int) (NKV * HD), T, s, cs, &st_.host);
+ else
+ for (int t = 0; t < T; ++t) {
+ if (st_.kv_q4)
+ kv_append_q4_step(st_.k_q4, st_.v_q4, st_.page_table, step + t * 4, kcur_ + t * NKV * HD,
+ vcur_ + t * NKV * HD, s, cs, &st_.host);
+ else if (st_.kv_int8)
+ kv_append_q8_step(st_.k_q, st_.v_q, st_.k_scale, st_.v_scale, st_.page_table, step + t * 4,
+ kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st_.host);
+ else
+ kv_append_step(st_.k_pool, st_.v_pool, st_.page_table, step + t * 4, kcur_ + t * NKV * HD,
+ vcur_ + t * NKV * HD, s, cs, &st_.host);
+ }
} catch (const std::exception& e) {
err = std::string("mtp: ") + e.what();
return false;
diff --git a/src/core/verify.cpp b/src/core/verify.cpp
index 9b00e6eba..db5b6391f 100644
--- a/src/core/verify.cpp
+++ b/src/core/verify.cpp
@@ -89,6 +89,7 @@ const bool g_coherent = env_on("STRATA_VERIFY_COHERENT");
const bool g_doorbell_store = env_on("STRATA_DOORBELL_STORE");
#endif
const bool g_trace = env_on("STRATA_VERIFY_TRACE");
+const bool g_no_batch_kv = env_on("STRATA_NO_BATCH_KV_STEP"); // #783 PR-d: per-token K/V and indexer appends again
// The shared expert runs on its own stream, forked off and joined back per layer (`sh_fork` in record_window). The
// overlap pays off on CUDA, where it was added (cfd3b72). On HIP a cross-stream event dependency costs more than the
@@ -927,12 +928,28 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
slot_ss(t).qsa_states[qi].idx_tail, TS, cs);
} else
if (grp == 0) copy_from_mapped(tail_snap_ + (size_t) qi * TS, st.idx_tail, TS, cs);
- const bool kv_multi = g_lfuse() && !st.kv_hybrid && !st.kv_q4 && st.kv_int8 && n > 1; // S26 STRATA_LFUSE
- if (kv_multi)
- kv_append_q8_steps(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, step_ + tb * kStepCount,
- (int) kStepCount, kcur_ + tb * NKV * HD, vcur_ + tb * NKV * HD, (int) (NKV * HD), n,
- s, cs, &st.host);
- else
+ // #783 PR-d (stuchapin909): the window's K/V cells in one launch per pool instead of one per token (a
+ // batch's rows each have their own K/V, so that case keeps the loop)
+ if (dec_batch && !g_no_batch_kv && !batch_rec_) {
+ const int32_t* step_b = step_ + tb * kStepCount;
+ const float* kc_b = kcur_ + tb * NKV * HD;
+ const float* vc_b = vcur_ + tb * NKV * HD;
+ if (st.kv_hybrid) { // K8V4: the unused half's lanes folded onto the used pool (layer.cpp)
+ kv_append_q8_steps(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, step_b, kStepCount,
+ kc_b, kc_b, (int) (NKV * HD), n, s, cs, nullptr);
+ kv_append_q4_steps(st.v_q4, st.v_q4, st.page_table, step_b, kStepCount, n, vc_b, vc_b, s, cs,
+ nullptr);
+ } else if (st.kv_q4)
+ kv_append_q4_steps(st.k_q4, st.v_q4, st.page_table, step_b, kStepCount, n, kc_b, vc_b, s, cs,
+ &st.host);
+ else if (st.kv_int8)
+ kv_append_q8_steps(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, step_b, kStepCount,
+ kc_b, vc_b, (int) (NKV * HD), n, s, cs, &st.host);
+ else
+ for (int t = tb; t < te; ++t)
+ kv_append_step(st.k_pool, st.v_pool, st.page_table, step_ + t * kStepCount,
+ kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st.host);
+ } else
for (int t = tb; t < te; ++t) {
const QsaState& st = slot_ss(t).qsa_states[qi]; // the row's own K/V (ss's outside a batch)
const int32_t* step_t = step_ + t * kStepCount;
@@ -953,12 +970,19 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
kv_append_step(st.k_pool, st.v_pool, st.page_table, step_t, kcur_ + t * NKV * HD,
vcur_ + t * NKV * HD, s, cs, &st.host);
}
- for (int t = tb; t < te; ++t) {
- const QsaState& sx = slot_ss(t).qsa_states[qi];
- const QsaIndexerBuffers ib{sx.idx_tail, sx.idx_dead, sx.idx_pooled, sx.idx_block_pos};
- native_qsa_indexer_append(idx_raw + t * ID, step_ + t * kStepCount + kStepPos, 0,
- (const float*) wikn->data, EPS, ib, s, sx.max_cells,
- rope_scaling(), cs);
+ if (dec_batch && !g_no_batch_kv && !batch_rec_) {
+ const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};
+ native_qsa_indexer_append_steps(idx_raw + tb * ID, step_ + tb * kStepCount + kStepPos, kStepCount,
+ n, 0, (const float*) wikn->data, EPS, ib, s, st.max_cells,
+ rope_scaling(), cs);
+ } else {
+ for (int t = tb; t < te; ++t) {
+ const QsaState& sx = slot_ss(t).qsa_states[qi];
+ const QsaIndexerBuffers ib{sx.idx_tail, sx.idx_dead, sx.idx_pooled, sx.idx_block_pos};
+ native_qsa_indexer_append(idx_raw + t * ID, step_ + t * kStepCount + kStepPos, 0,
+ (const float*) wikn->data, EPS, ib, s, sx.max_cells,
+ rope_scaling(), cs);
+ }
}
stamp(l, 9, grp);
native_mmvq(wq->native_type, wq->native_data, xq_, qfull_ + tb * NH * 2 * HD, (int) N, (int) (NH * 2 * HD),
@@ -1521,10 +1545,15 @@ bool Verifier::capture_commit(std::string& err) {
if (!wikn) { ok = false; break; }
copy_from_mapped(st.idx_tail, tail_snap_ + (size_t) qsa_index * TS, TS, cs_);
const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};
- for (int64_t t = 0; t < MT; ++t)
- native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + t) * ID, commit_ + 2 + t, 0,
- (const float*) wikn->data, EPS, ib, s, st.max_cells,
- rope_scaling(), cs_);
+ if (!g_no_batch_kv) {
+ native_qsa_indexer_append_steps(idx_raw_L_ + (size_t) qsa_index * MT * ID, commit_ + 2, 1, (int) MT, 0,
+ (const float*) wikn->data, EPS, ib, s, st.max_cells, rope_scaling(), cs_);
+ } else {
+ for (int64_t t = 0; t < MT; ++t)
+ native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + t) * ID, commit_ + 2 + t, 0,
+ (const float*) wikn->data, EPS, ib, s, st.max_cells,
+ rope_scaling(), cs_);
+ }
++qsa_index;
}
}
diff --git a/src/kernels/cuda/kv_q4.cu b/src/kernels/cuda/kv_q4.cu
index b7de61fad..4c6c5441a 100644
--- a/src/kernels/cuda/kv_q4.cu
+++ b/src/kernels/cuda/kv_q4.cu
@@ -96,16 +96,18 @@ __device__ __forceinline__ void q4_store(uint8_t* pool, long long row, int b, in
if (lane < 16) blk->qs[lane] = byte;
}
-// One block = one 32-value group of one KV head of K (blockIdx.z = 0) or V (1); 32 threads. KV streaming: the VRAM
-// page only if the block is resident (table >= 0), the host copy always (identity layout) when there is one.
+// One block = one 32-value group of one KV head of K (plane 0) or V (plane 1) for token step_idx; 32 threads.
__global__ void kv_append_q4_kernel(uint8_t* __restrict__ k_q4, uint8_t* __restrict__ v_q4,
const int32_t* __restrict__ table, const int32_t* __restrict__ step,
+ int step_stride, int planes,
const float* __restrict__ kcur, const float* __restrict__ vcur,
int kv_heads, int head_dim, int page_size, KvHostPools host) {
- const long long pos = (long long) __ldg(step + kStepPos);
+ const int step_idx = (int) (blockIdx.z / (unsigned) planes);
+ const bool is_v = (blockIdx.z % (unsigned) planes) == 1u;
+ const long long pos = (long long) __ldg(step + (long long) step_idx * step_stride + kStepPos);
const int h = blockIdx.x, b = blockIdx.y, t = threadIdx.x;
- const bool is_v = blockIdx.z == 1;
- const float x = (is_v ? vcur : kcur)[h * head_dim + b * QK4_0 + t];
+ const long long step_off = (long long) step_idx * kv_heads * head_dim;
+ const float x = (is_v ? vcur : kcur)[step_off + h * head_dim + b * QK4_0 + t];
uint8_t byte;
const uint16_t d = q4_group(x, t, byte);
const long long page = (long long) table[pos / page_size];
@@ -190,17 +192,25 @@ void fwht256_cuda(const float* src, float* dst, int64_t n_rows, void* stream) {
check("fwht256 launch");
}
-void kv_append_q4_step(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, const int32_t* step,
- const float* kcur, const float* vcur, const QsaShapes& s, void* stream,
- const KvHostPools* host) {
+void kv_append_q4_steps(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, const int32_t* step,
+ int step_stride, int n_steps, const float* kcur, const float* vcur, const QsaShapes& s,
+ void* stream, const KvHostPools* host) {
+ if (n_steps <= 0) return;
need_256(s, "kv_append_q4");
- const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / QK4_0), 2);
+ const int planes = (v_q4 == nullptr || (v_q4 == k_q4 && vcur == kcur)) ? 1 : 2;
+ const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / QK4_0), (unsigned) (n_steps * planes));
kv_append_q4_kernel<<<grid, 32, 0, (cudaStream_t) stream>>>(
- k_q4, v_q4, page_table, step, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size,
- host ? *host : KvHostPools{});
+ k_q4, v_q4, page_table, step, step_stride, planes, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim,
+ (int) s.page_size, host ? *host : KvHostPools{});
check("kv_append_q4 launch");
}
+void kv_append_q4_step(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, const int32_t* step,
+ const float* kcur, const float* vcur, const QsaShapes& s, void* stream,
+ const KvHostPools* host) {
+ kv_append_q4_steps(k_q4, v_q4, page_table, step, 0, 1, kcur, vcur, s, stream, host);
+}
+
void kv_append_q4(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, int64_t pos0, int64_t T, const float* K,
const float* V, const QsaShapes& s, void* stream, const KvHostPools* host, const KvHostPools* stage) {
if (T <= 0) return;
diff --git a/src/kernels/cuda/native_qsa_indexer.cu b/src/kernels/cuda/native_qsa_indexer.cu
index 8147c7098..f919e8ca4 100644
--- a/src/kernels/cuda/native_qsa_indexer.cu
+++ b/src/kernels/cuda/native_qsa_indexer.cu
@@ -44,65 +44,74 @@ __device__ float warp_sum(float x) {
// with it merely skipped at run time, the compiled default path changed its results).
template <bool TAB>
__global__ void append(const float* __restrict__ raw, const int32_t* __restrict__ pos_dev,
+ int pos_stride, int n_steps,
int pos_base, const float* __restrict__ gamma, float epsilon,
float* __restrict__ tail, float* __restrict__ dead,
float* __restrict__ pooled, int32_t* __restrict__ block_pos,
int max_cells, float theta_scale, float freq_scale, float corr_low,
float corr_high, float ext_factor, float mscale,
const int32_t* __restrict__ mtab, RopeTab rt) {
- const int pos = *pos_dev, d = threadIdx.x;
- if (pos < 0 || pos >= max_cells) return;
- const int slot = pos % R;
- float incoming = 0.0f;
- if (d < D) {
- // SET_ROWS stores F16; GET_ROWS expands those exact values to F32.
- incoming = __half2float(__float2half_rn(raw[d]));
- if (slot < R - 1) tail[slot * D + d] = incoming;
- }
- if (pos != 0 && slot != R - 1) return;
__shared__ float values[D];
__shared__ float partials[32];
- float mean = 0.0f;
- if (d < D) {
- // The spare's four gather indices all name cell zero. Completed blocks
- // use chronological slices; each graph ADD materializes an F32 sum.
- float sum = pos == 0 ? incoming : tail[d];
+ const int d = threadIdx.x;
+ for (int step_idx = 0; step_idx < n_steps; ++step_idx) {
+ const int pos = pos_dev[(std::size_t) step_idx * pos_stride];
+ if (pos >= 0 && pos < max_cells) {
+ const float* raw_step = raw + (std::size_t) step_idx * D;
+ const int slot = pos % R;
+ float incoming = 0.0f;
+ if (d < D) {
+ // SET_ROWS stores F16; GET_ROWS expands those exact values to F32.
+ incoming = __half2float(__float2half_rn(raw_step[d]));
+ if (slot < R - 1) tail[slot * D + d] = incoming;
+ }
+ if (pos == 0 || slot == R - 1) {
+ float mean = 0.0f;
+ if (d < D) {
+ // The spare's four gather indices all name cell zero. Completed blocks
+ // use chronological slices; each graph ADD materializes an F32 sum.
+ float sum = pos == 0 ? incoming : tail[d];
#pragma unroll
- for (int j = 1; j < R; ++j)
- sum = __fadd_rn(sum, pos == 0 || j == R - 1 ? incoming : tail[j * D + d]);
- mean = __fmaf_rn(0.25f, sum, 0.0f); // SCALE includes a zero bias.
- }
- float square_sum = 0.0f;
- if (d < D) square_sum += mean * mean;
- 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);
- const float scale = rsqrtf(square_sum / D + epsilon);
- if (d < D) values[d] = scale * mean * gamma[d];
- __syncthreads();
- if (d >= D) return;
- const int b = pos / R;
- const int rope_pos = pos == 0 ? 0 : pos_base + R * b;
- float y = values[d];
- if (d < ROT) {
- const int pair = d % (ROT / 2);
- // The spare (pos == 0) keeps its zero angle; under YaRN the mscale magnitude still rides in
- // through cos(0) - which is exactly what the queries are scaled by, so the top-k is unmoved.
- float c, s;
- if (!(TAB && rope_tab_cs(rt, pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s))) {
- const float theta_extrap = (pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair));
- rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s);
+ for (int j = 1; j < R; ++j)
+ sum = __fadd_rn(sum, pos == 0 || j == R - 1 ? incoming : tail[j * D + d]);
+ mean = __fmaf_rn(0.25f, sum, 0.0f); // SCALE includes a zero bias.
+ }
+ float square_sum = 0.0f;
+ if (d < D) square_sum += mean * mean;
+ 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);
+ const float scale = rsqrtf(square_sum / D + epsilon);
+ if (d < D) values[d] = scale * mean * gamma[d];
+ __syncthreads();
+ if (d < D) {
+ const int b = pos / R;
+ const int rope_pos = pos == 0 ? 0 : pos_base + R * b;
+ float y = values[d];
+ if (d < ROT) {
+ const int pair = d % (ROT / 2);
+ // The spare (pos == 0) keeps its zero angle; under YaRN the mscale magnitude still rides in
+ // through cos(0) - which is exactly what the queries are scaled by, so the top-k is unmoved.
+ float c, s;
+ if (!(TAB && rope_tab_cs(rt, pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s))) {
+ const float theta_extrap = (pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair));
+ rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s);
+ }
+ const float a = values[pair], z = values[pair + ROT / 2];
+ y = d < ROT / 2 ? a * c - z * s : a * s + z * c;
+ }
+ pooled[std::size_t(b) * D + d] = y;
+ if (pos == 0) dead[d] = y;
+ else pooled[std::size_t(b + 1) * D + d] = dead[d];
+ if (d == 0 && pos != 0) *block_pos = rope_pos;
+ }
+ }
}
- const float a = values[pair], z = values[pair + ROT / 2];
- y = d < ROT / 2 ? a * c - z * s : a * s + z * c;
+ if (n_steps > 1) __syncthreads();
}
- pooled[std::size_t(b) * D + d] = y;
- if (pos == 0) dead[d] = y;
- 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,
@@ -225,15 +234,18 @@ bool overlaps(Span a, Span b) {
void native_qsa_indexer_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); }
bool native_qsa_indexer_enabled() { return enabled.load(std::memory_order_relaxed); }
-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& b,
- const QsaShapes& s, int64_t max_cells, const RopeScaling& scaling, void* stream) {
+void native_qsa_indexer_append_steps(const float* raw, const int32_t* relative_pos_device,
+ int pos_stride, int n_steps, int32_t pos_base,
+ const float* gamma, float epsilon, const QsaIndexerBuffers& b,
+ const QsaShapes& s, int64_t max_cells, const RopeScaling& scaling, void* stream) {
+ if (n_steps <= 0) return;
if (!stream || s.idx_dim != D || s.idx_block != R || s.n_rot != ROT ||
max_cells < 1 || max_cells > INT32_MAX || pos_base < 0 || pos_base % R ||
int64_t(pos_base) + max_cells > INT32_MAX || !std::isfinite(epsilon) || epsilon <= 0.0f ||
rope_scaling_invalid(scaling) != nullptr)
throw std::invalid_argument("native QSA indexer requires fixed geometry, aligned position base, positive capacity/epsilon, valid frequency/scaling and explicit stream");
- const Span spans[] = {{raw,D*4},{relative_pos_device,4},{gamma,D*4},{b.tail,(R-1)*D*4},
+ const std::size_t pos_span = (n_steps == 1 || pos_stride <= 0) ? 4 : (std::size_t(n_steps - 1) * pos_stride + 1) * 4;
+ const Span spans[] = {{raw,std::size_t(n_steps)*D*4},{relative_pos_device,pos_span},{gamma,D*4},{b.tail,(R-1)*D*4},
{b.dead,D*4},{b.pooled,std::size_t(max_cells/R+1)*D*4},{b.block_pos,4}};
for (const auto& span : spans) validate(span);
for (int i = 0; i < 7; ++i) for (int j = i + 1; j < 7; ++j)
@@ -242,16 +254,22 @@ void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_dev
const RopeKernelArgs k = scaling.kernel_args(ROT); // none: the identity constants
const RopeTab rt = rope_table_for(scaling);
if (rt.cos != nullptr)
- append<true><<<1,THREADS,0,static_cast<cudaStream_t>(stream)>>>(raw,relative_pos_device,pos_base,gamma,epsilon,
+ append<true><<<1,THREADS,0,static_cast<cudaStream_t>(stream)>>>(raw,relative_pos_device,pos_stride,n_steps,pos_base,gamma,epsilon,
b.tail,b.dead,b.pooled,b.block_pos,int(max_cells),theta_scale,k.freq_scale,
k.corr_low,k.corr_high,k.ext_factor,k.attn_factor,mrope_table(),rt);
else
- append<false><<<1,THREADS,0,static_cast<cudaStream_t>(stream)>>>(raw,relative_pos_device,pos_base,gamma,epsilon,
+ append<false><<<1,THREADS,0,static_cast<cudaStream_t>(stream)>>>(raw,relative_pos_device,pos_stride,n_steps,pos_base,gamma,epsilon,
b.tail,b.dead,b.pooled,b.block_pos,int(max_cells),theta_scale,k.freq_scale,
k.corr_low,k.corr_high,k.ext_factor,k.attn_factor,mrope_table(),rt);
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
+
+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& b,
+ const QsaShapes& s, int64_t max_cells, const RopeScaling& scaling, void* stream) {
+ native_qsa_indexer_append_steps(raw, relative_pos_device, 0, 1, pos_base, gamma, epsilon, b, s, max_cells, scaling, stream);
+}
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,
const RopeScaling& scaling, void* stream) {
diff --git a/src/kernels/kv_steps_parity.cpp b/src/kernels/kv_steps_parity.cpp
new file mode 100644
index 000000000..f50180006
--- /dev/null
+++ b/src/kernels/kv_steps_parity.cpp
@@ -0,0 +1,135 @@
+// src/kernels/kv_steps_parity.cpp - the batched K/V append (#783 PR-d): kv_append_q8_steps / kv_append_q4_steps for
+// n = 1..8 cells in one launch against n calls of the single-cell append, memcmp on every pool byte.
+//
+// Cells land at scattered positions through a non-identity page table; the K/V rows are random with small, large and
+// all-zero groups. Three layouts: INT8 K and V, Q4_0 K and V, and the K8V4 hybrid's folded call (the K pool passed as
+// both halves, one plane). GPU, synthetic, no model.
+#include "strata/kernels/kv_q4.hpp"
+#include "strata/kernels/kv_q8.hpp"
+#include "strata/kernels/qsa.hpp"
+
+#include <cuda_runtime.h>
+
+#include <algorithm>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <random>
+#include <vector>
+
+namespace k = strata::kernels;
+
+namespace {
+int g_fail = 0;
+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* dalloc(size_t n) {
+ T* p = nullptr;
+ ck(cudaMalloc(&p, n * sizeof(T) + 64), "malloc");
+ ck(cudaMemset(p, 0, n * sizeof(T) + 64), "memset");
+ return p;
+}
+template <typename T>
+std::vector<T> fetch(const T* d, size_t n) {
+ std::vector<T> h(n);
+ ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "d2h");
+ return h;
+}
+template <typename T>
+void zero(T* d, size_t n) { ck(cudaMemset(d, 0, n * sizeof(T) + 64), "zero"); }
+bool same(const void* a, const void* b, size_t bytes) { return std::memcmp(a, b, bytes) == 0; }
+} // namespace
+
+int main() {
+ k::QsaShapes s = k::qsa_real_shapes();
+ s.page_size = 64;
+ const int H = (int) s.n_head_kv, D = (int) s.head_dim, P = (int) s.page_size, G = D / k::KV_Q8_GROUP;
+ const int pages = 8, cells = pages * P;
+ std::mt19937 rng(783);
+ std::normal_distribution<float> nd(0.f, 1.f);
+ std::vector<int32_t> table(pages);
+ for (int i = 0; i < pages; ++i) table[i] = (i * 5 + 3) % pages;
+ int32_t* d_table = dalloc<int32_t>(pages);
+ ck(cudaMemcpy(d_table, table.data(), pages * 4, cudaMemcpyHostToDevice), "table");
+
+ const size_t q8n = (size_t) cells * H * D, q8s = (size_t) cells * H * G, q4n = (size_t) cells * H * D; // q4: <= 144 B per cell-head
+ int8_t *kq1 = dalloc<int8_t>(q8n), *vq1 = dalloc<int8_t>(q8n), *kq2 = dalloc<int8_t>(q8n), *vq2 = dalloc<int8_t>(q8n);
+ uint16_t *ks1 = dalloc<uint16_t>(q8s), *vs1 = dalloc<uint16_t>(q8s), *ks2 = dalloc<uint16_t>(q8s), *vs2 = dalloc<uint16_t>(q8s);
+ uint8_t *k41 = dalloc<uint8_t>(q4n), *v41 = dalloc<uint8_t>(q4n), *k42 = dalloc<uint8_t>(q4n), *v42 = dalloc<uint8_t>(q4n);
+ uint8_t *h41 = dalloc<uint8_t>(q4n), *h42 = dalloc<uint8_t>(q4n);
+ int8_t *hq1 = dalloc<int8_t>(q8n), *hq2 = dalloc<int8_t>(q8n);
+ uint16_t *hs1 = dalloc<uint16_t>(q8s), *hs2 = dalloc<uint16_t>(q8s);
+
+ int total_cases = 0;
+ for (int n = 1; n <= 8; ++n) {
+ for (int round = 0; round < 3; ++round) {
+ zero(kq1, q8n); zero(vq1, q8n); zero(kq2, q8n); zero(vq2, q8n);
+ zero(ks1, q8s); zero(vs1, q8s); zero(ks2, q8s); zero(vs2, q8s);
+ zero(k41, q4n); zero(v41, q4n); zero(k42, q4n); zero(v42, q4n); zero(h41, q4n); zero(h42, q4n);
+ zero(hq1, q8n); zero(hq2, q8n); zero(hs1, q8s); zero(hs2, q8s);
+ std::vector<int> positions(cells);
+ for (int i = 0; i < cells; ++i) positions[i] = i;
+ std::shuffle(positions.begin(), positions.end(), rng);
+ std::vector<float> hk((size_t) n * H * D), hv(hk.size());
+ for (int t = 0; t < n; ++t) {
+ const float scale = (t % 3 == 0) ? 1e-3f : (t % 5 == 0 ? 40.f : 1.f);
+ for (int i = 0; i < H * D; ++i) {
+ hk[(size_t) t * H * D + i] = nd(rng) * scale;
+ hv[(size_t) t * H * D + i] = nd(rng) * scale;
+ }
+ if (t % 4 == 1) std::fill(hk.begin() + (size_t) t * H * D, hk.begin() + (size_t) t * H * D + 64, 0.f);
+ }
+ std::vector<int32_t> hstep((size_t) n * k::kStepCount, 0);
+ for (int t = 0; t < n; ++t) {
+ hstep[(size_t) t * k::kStepCount + k::kStepPos] = positions[t];
+ hstep[(size_t) t * k::kStepCount + 1] = positions[t] + 1;
+ }
+ float *d_k = dalloc<float>(hk.size()), *d_v = dalloc<float>(hv.size());
+ int32_t* d_step = dalloc<int32_t>(hstep.size());
+ ck(cudaMemcpy(d_k, hk.data(), hk.size() * 4, cudaMemcpyHostToDevice), "k");
+ ck(cudaMemcpy(d_v, hv.data(), hv.size() * 4, cudaMemcpyHostToDevice), "v");
+ ck(cudaMemcpy(d_step, hstep.data(), hstep.size() * 4, cudaMemcpyHostToDevice), "step");
+
+ for (int t = 0; t < n; ++t) {
+ const int32_t* st = d_step + (size_t) t * k::kStepCount;
+ const float* kc = d_k + (size_t) t * H * D;
+ const float* vc = d_v + (size_t) t * H * D;
+ k::kv_append_q8_step(kq1, vq1, ks1, vs1, d_table, st, kc, vc, s, nullptr);
+ k::kv_append_q4_step(k41, v41, d_table, st, kc, vc, s, nullptr);
+ k::kv_append_q8_step(hq1, hq1, hs1, hs1, d_table, st, kc, kc, s, nullptr); // the hybrid's folded K call
+ k::kv_append_q4_step(h41, h41, d_table, st, vc, vc, s, nullptr); // ... and its folded V call
+ }
+ k::kv_append_q8_steps(kq2, vq2, ks2, vs2, d_table, d_step, k::kStepCount, d_k, d_v, H * D, n, s, nullptr, nullptr);
+ k::kv_append_q4_steps(k42, v42, d_table, d_step, k::kStepCount, n, d_k, d_v, s, nullptr);
+ k::kv_append_q8_steps(hq2, hq2, hs2, hs2, d_table, d_step, k::kStepCount, d_k, d_k, H * D, n, s, nullptr, nullptr);
+ k::kv_append_q4_steps(h42, h42, d_table, d_step, k::kStepCount, n, d_v, d_v, s, nullptr);
+ ck(cudaDeviceSynchronize(), "sync");
+
+ struct Chk { const char* name; bool ok; };
+ const Chk chks[] = {
+ {"INT8 K/V codes", same(fetch(kq1, q8n).data(), fetch(kq2, q8n).data(), q8n) && same(fetch(vq1, q8n).data(), fetch(vq2, q8n).data(), q8n)},
+ {"INT8 K/V scales", same(fetch(ks1, q8s).data(), fetch(ks2, q8s).data(), q8s * 2) && same(fetch(vs1, q8s).data(), fetch(vs2, q8s).data(), q8s * 2)},
+ {"Q4_0 K/V", same(fetch(k41, q4n).data(), fetch(k42, q4n).data(), q4n) && same(fetch(v41, q4n).data(), fetch(v42, q4n).data(), q4n)},
+ {"hybrid K (folded INT8)", same(fetch(hq1, q8n).data(), fetch(hq2, q8n).data(), q8n) && same(fetch(hs1, q8s).data(), fetch(hs2, q8s).data(), q8s * 2)},
+ {"hybrid V (folded Q4_0)", same(fetch(h41, q4n).data(), fetch(h42, q4n).data(), q4n)},
+ };
+ for (const Chk& c : chks) {
+ ++total_cases;
+ if (!c.ok) {
+ std::printf(" *** n=%d round %d: %s differ from the per-cell appends ***\n", n, round, c.name);
+ ++g_fail;
+ }
+ }
+ cudaFree(d_k); cudaFree(d_v); cudaFree(d_step);
+ }
+ }
+ std::printf("kv_steps: %d checks, %d failures\n", total_cases, g_fail);
+ if (g_fail) return 1;
+ std::printf("kv_steps_parity OK\n");
+ return 0;
+}
diff --git a/src/kernels/qsa_parity.cpp b/src/kernels/qsa_parity.cpp
index 55dec2d35..a23f0695d 100644
--- a/src/kernels/qsa_parity.cpp
+++ b/src/kernels/qsa_parity.cpp
@@ -1428,6 +1428,33 @@ int main(int argc, char** argv) {
strata::kernels::native_qsa_indexer_append(draw.p, dpos.p, BASE, dw_kn.p, EPS, bufsA, S, MC, sc, cs);
}
strata::kernels::native_qsa_indexer_append_batch(drawAll.p, NB, 0, BASE, dw_kn.p, EPS, bufsB, S, MC, sc, cs);
+ // #783 PR-d: native_qsa_indexer_append_steps - the verify window's n cells in one launch (positions at a
+ // stride: kStepCount in a window, 1 in the commit graph) - leaves the same buffers as the sequential calls
+ for (const int stride : {1, 5}) {
+ Dev<float> pooledC(prows), deadC(IDXD), tailC(trows);
+ Dev<int32_t> bposC(1), dposC((size_t) NB * stride);
+ check(cudaMemset(pooledC.p, 0, prows * 4), "zero");
+ check(cudaMemset(deadC.p, 0, IDXD * 4), "zero");
+ check(cudaMemset(tailC.p, 0, trows * 4), "zero");
+ check(cudaMemset(bposC.p, 0, 4), "zero");
+ std::vector<int32_t> hp((size_t) NB * stride, -1);
+ for (int64_t t = 0; t < NB; ++t) hp[(size_t) t * stride] = (int32_t) t;
+ check(cudaMemcpy(dposC.p, hp.data(), hp.size() * 4, cudaMemcpyHostToDevice), "pos");
+ strata::kernels::QsaIndexerBuffers bufsC{tailC.p, deadC.p, pooledC.p, bposC.p};
+ strata::kernels::native_qsa_indexer_append_steps(drawAll.p, dposC.p, stride, (int) NB, BASE, dw_kn.p, EPS,
+ bufsC, S, MC, sc, cs);
+ check(cudaStreamSynchronize(cs), "sync");
+ const std::vector<float> pc = pooledC.get(prows), dc = deadC.get((size_t) IDXD), tc = tailC.get(trows);
+ const std::vector<int32_t> bc = bposC.get(1);
+ const std::vector<float> pa2 = pooledA.get(prows), da2 = deadA.get((size_t) IDXD), ta2 = tailA.get(trows);
+ const std::vector<int32_t> ba2 = bposA.get(1);
+ const bool same = std::memcmp(pc.data(), pa2.data(), pc.size() * 4) == 0 &&
+ std::memcmp(dc.data(), da2.data(), dc.size() * 4) == 0 &&
+ std::memcmp(tc.data(), ta2.data(), tc.size() * 4) == 0 && bc[0] == ba2[0];
+ std::printf(" %-44s %s\n", (std::string("append_steps (stride ") + std::to_string(stride) + ") vs sequential, " + var.name).c_str(),
+ same ? "bit-identical" : "*** WRONG ***");
+ if (!same) ++g_bad;
+ }
check(cudaStreamSynchronize(cs), "sync");
const std::vector<float> pa = pooledA.get(prows), pb = pooledB.get(prows);
const std::vector<float> da = deadA.get((size_t) IDXD), db = deadB.get((size_t) IDXD);