From 7499dbaf92d6fd80fc7406c2d836f9fee1f060bb Mon Sep 17 00:00:00 2001 From: yhirose Date: Sat, 7 Nov 2026 14:08:04 -0500 Subject: [PATCH 1/2] cuda: the graph's decode attention sums its live splits alone The graph form launches S_max splits, sized at the cache's capacity, so that one graph serves every position. Past the live count each split still staged and wrote a neutral partial, and tl_attn_combine read all S_max of them: at 4096 cached tokens of capacity, Gemma 4 E2B's 512-wide layers wrote and read 1.3 MB a layer at any depth, and a short cache paid for the capacity's splits. - attn_dec_core: an empty range (a dpos split past the live count) writes its heads' m alone, at attn_m_empty, and returns before any barrier. attn_m_empty names the softmax's starting m, which the core and the combine share. - tl_attn_combine: the max still reads every split's m (16 loads in flight, as before), and counts up to the last split whose m is not empty; the sums stop there. Live splits come first, so that is the live count, read from the partials themselves: no d_pos, no rule, no second combine kernel. The host path's splits are never empty, so it sums all S. The sums run over the same splits in the same order as the host path's, so the output stays bit-identical to it. Two forms tried first and dropped: a combine that derives the live count from d_pos (the load and the rule's divisions sit before its sums, +0.3 to +0.6 us a call where every split is live), and one that skips an empty split inside the sums loop (the branch on each loaded m serializes the loads, +1 us). --- bench/cuda/check/check_attn64.cpp | 4 +++- bench/cuda/speed/bench_qwen_ctx.cpp | 6 ++--- include/cuda_llm.h | 7 +++--- kernels/cuda_llm.cuh | 9 ++++---- kernels/cuda_nn.cuh | 34 ++++++++++++++++++++++------- 5 files changed, 41 insertions(+), 19 deletions(-) diff --git a/bench/cuda/check/check_attn64.cpp b/bench/cuda/check/check_attn64.cpp index 693f79c..057206c 100644 --- a/bench/cuda/check/check_attn64.cpp +++ b/bench/cuda/check/check_attn64.cpp @@ -103,7 +103,9 @@ int main() { // Lockstep guard: attn_dpos (split-KV on the capacity-static grid, // *d_pos = pos so ctx matches) must be BIT-identical to attn — the // device attn_dpos_chunk twins the host attn_split_count/attn_split_chunk - // heuristic, and the capacity grid's empty splits combine as exact zeros. + // heuristic, and an empty split's m alone is written, which the + // combine's max must see (the windowed passes after the unwindowed + // one leave its later splits' partials behind). upload_u32(dp, (unsigned)pos); cache.attn_dpos({q, 0}, {o2, 0}, HQ, {dp, 0}, scale); flush(); diff --git a/bench/cuda/speed/bench_qwen_ctx.cpp b/bench/cuda/speed/bench_qwen_ctx.cpp index c6e31e0..b590f3b 100644 --- a/bench/cuda/speed/bench_qwen_ctx.cpp +++ b/bench/cuda/speed/bench_qwen_ctx.cpp @@ -119,9 +119,9 @@ int main(int argc, char** argv) { void* d_pos = cu::alloc(4, nullptr); // Value guard alongside the timing: at each ctx, layer 0's host-path output // vs the dpos-path output must be BIT-IDENTICAL (the dpos kernel replicates - // the host chunk heuristic; empty splits combine as exact zeros). This is the - // long-ctx complement to bench_qwen_decode's dpos-vs-hostpos check (pos 32, - // which never leaves the S=1 regime). + // the host chunk heuristic, and the combine's sums stop at the empty + // splits). This is the long-ctx complement to bench_qwen_decode's + // dpos-vs-hostpos check (pos 32, which never leaves the S=1 regime). float *ref_host = nullptr, *got_host = nullptr; void* refb = cu::alloc(C.NH * C.HD * 4, &ref_host); void* gotb = cu::alloc(C.NH * C.HD * 4, &got_host); diff --git a/include/cuda_llm.h b/include/cuda_llm.h index 9153f0e..af59732 100644 --- a/include/cuda_llm.h +++ b/include/cuda_llm.h @@ -182,9 +182,10 @@ inline unsigned attn_dpos_splits(int64_t n_q_heads, int64_t n_kv_heads, int64_t // gridDim.y = S_max = attn_dpos_splits at max_ctx, a constant for the cache's // lifetime — so the launch is capturable — while each block derives its live // split bounds from *d_pos (attn_dpos_chunk, under attn_split_rule passed as -// arguments). Splits past the live count write neutral partials that combine -// as exact zeros, so the output is bit-identical to the host attn_decode at -// every pos, and the captured path stays split-KV-flat at long ctx. +// arguments). Splits past the live count write an empty m alone, and the +// combine's sums stop before them, so the output is bit-identical to the +// host attn_decode at every pos, a short cache costs its own splits rather +// than the capacity's, and the captured path stays split-KV-flat at long ctx. // `partials` is a caller-OWNED device buffer of attn_dpos_partials_bytes — // like d_pos, it is graph-lifetime state (a captured graph bakes its address // in), so it must not be a shared growable scratch; kv_cache owns one per diff --git a/kernels/cuda_llm.cuh b/kernels/cuda_llm.cuh index 20ee129..9ffe010 100644 --- a/kernels/cuda_llm.cuh +++ b/kernels/cuda_llm.cuh @@ -11,10 +11,11 @@ // DYNAMIC position: each block recomputes the host launcher's split heuristic // from *d_pos, so one instantiated graph replays correctly at every pos AND // stays split-KV-flat at long ctx. Splits past ceil(ctx/chunk) see k0 >= ctx -// and write the neutral partial that contributes exact zeros in -// tl_attn_combine, so the output is bit-identical to the host path (single -// pass or split) at the same pos. Body is attn_dec_core, as the by-value -// kernels'. +// and write their m alone, empty (attn_m_empty), and tl_attn_combine sums +// up to the last split that is not, so the output is bit-identical to the +// host path (single pass or split) at the same pos, and a short cache reads +// its own splits' partials rather than the capacity's. Body is +// attn_dec_core, as the by-value kernels'. // // attn_dpos_chunk is gpu::policy::split_parts + split_chunk on the device, under // the rule the launcher passes (cuda_nn.h's attn_split_rule), so the host and diff --git a/kernels/cuda_nn.cuh b/kernels/cuda_nn.cuh index 76d1c75..1737ee0 100644 --- a/kernels/cuda_nn.cuh +++ b/kernels/cuda_nn.cuh @@ -3092,6 +3092,11 @@ template constexpr int attn_dec_warps = AD == 512 ? 4 : 8; template constexpr int attn_dec_threads = 32 * attn_dec_warps; +// A softmax state's m before any key. A split's partial left at it (a dpos +// split past the live count writes nothing else) weighs exp(-1e30 - max) = 0 +// in the merge, so tl_attn_combine reads no l or acc past the last split that +// is not. +constexpr float attn_m_empty = -1e30f; // The decode attention's core. Block blockIdx.x is one kv head and a slice of // GB of the q heads that share it (GQA): it reads each of its keys [k0, k1) @@ -3107,8 +3112,8 @@ constexpr int attn_dec_threads = 32 * attn_dec_warps; // memory, one barrier for all heads. FINAL normalizes and stores the output; // else each head writes its partial (m, l, acc at the local max) for // tl_attn_combine, at split blockIdx.y of gridDim.y. An empty range (k0 >= -// k1, a dpos split past the live count) writes the neutral partial (m = -1e30, -// l = 0, acc = 0), which combines as exact zeros. +// k1, a dpos split past the live count) writes its heads' m alone, at +// attn_m_empty, and returns before any barrier (the whole block alike). template __device__ __forceinline__ void attn_dec_core(const float* __restrict__ q, const KT* __restrict__ K, const KT* __restrict__ V, float* __restrict__ out, @@ -3124,6 +3129,10 @@ __device__ __forceinline__ void attn_dec_core(const float* __restrict__ q, const const KT* Kh = K + (size_t)kv_h * kv_stride; const KT* Vh = V + (size_t)kv_h * kv_stride; const unsigned tid = threadIdx.x, lane = tid & 31u, warp = tid >> 5; + if (!FINAL && k0 >= k1) { + if (tid < gn) pm[(size_t)(h0 + tid) * gridDim.y + blockIdx.y] = attn_m_empty; + return; + } // The queries straight from global (each warp reads the same few KB, from // L1), so their loads go out with the first keys' rather than behind a @@ -3131,7 +3140,7 @@ __device__ __forceinline__ void attn_dec_core(const float* __restrict__ q, const float qr[GB][NR], acc[GB][NR], m[GB], l[GB]; #pragma unroll for (int g = 0; g < GB; g++) { - m[g] = -1e30f; + m[g] = attn_m_empty; l[g] = 0.0f; #pragma unroll for (int r = 0; r < NR; r++) { @@ -3274,18 +3283,27 @@ TL_ATTN_SPLIT(256, __half, f16) TL_ATTN_SPLIT(512, __half, f16) #undef TL_ATTN_SPLIT -// Merge the S per-head partials (each already at its local max) into out. Not -// templated: the per-dim thread stride D == blockDim.x, so head_dim is implicit. +// Merge the S per-head partials (each already at its local max) into out, the +// sums stopping after the last split whose m is not attn_m_empty (the +// splits after it are empty: a dpos step's past its live count). Not +// templated: the per-dim thread stride D == blockDim.x, so head_dim is +// implicit. extern "C" __global__ void tl_attn_combine(const float* __restrict__ pm, const float* __restrict__ pl, const float* __restrict__ pacc, float* __restrict__ out, unsigned S) { const unsigned h = blockIdx.x, tid = threadIdx.x, D = blockDim.x; const size_t base = (size_t)h * S; - float gm = -1e30f; - for (unsigned s = 0; s < S; s++) gm = fmaxf(gm, pm[base + s]); - float gl = 0.0f, o = 0.0f; + float gm = attn_m_empty; + unsigned n = 0; +#pragma unroll 16 // as many m loads in flight as the max alone gets for (unsigned s = 0; s < S; s++) { + const float m = pm[base + s]; + gm = fmaxf(gm, m); + n = m != attn_m_empty ? s + 1 : n; + } + float gl = 0.0f, o = 0.0f; + for (unsigned s = 0; s < n; s++) { float e = __expf(pm[base + s] - gm); gl += pl[base + s] * e; o += pacc[(base + s) * D + tid] * e; From 7b74b8df15abd99a235755dcc7b47c50fec26512 Mon Sep 17 00:00:00 2001 From: yhirose Date: Sat, 7 Nov 2026 16:31:27 -0500 Subject: [PATCH 2/2] cuda: the empty split is the partials' contract, said once Cleanups from /simplify on the live-splits change. - The empty split's rule (its m alone, at attn_m_empty; empty splits come after the rest, so the combine's sums stop after the last that is not) is part of the partials' layout, and is now said once, on attn_partials. The kernels and launcher that relied on it in their own words point there. - attn_dec_core's warp merge starts from attn_m_empty, as its states do, rather than a second spelling of -1e30. - attn64's comment says what the empty m guards: the combine never reads the partials the windowed passes leave behind. The PTX is the same, instruction for instruction. --- bench/cuda/check/check_attn64.cpp | 6 +++--- include/cuda_llm.h | 8 ++++---- include/cuda_nn.h | 6 +++++- kernels/cuda_llm.cuh | 8 +++----- kernels/cuda_nn.cuh | 15 ++++++--------- 5 files changed, 21 insertions(+), 22 deletions(-) diff --git a/bench/cuda/check/check_attn64.cpp b/bench/cuda/check/check_attn64.cpp index 057206c..e946a8e 100644 --- a/bench/cuda/check/check_attn64.cpp +++ b/bench/cuda/check/check_attn64.cpp @@ -103,9 +103,9 @@ int main() { // Lockstep guard: attn_dpos (split-KV on the capacity-static grid, // *d_pos = pos so ctx matches) must be BIT-identical to attn — the // device attn_dpos_chunk twins the host attn_split_count/attn_split_chunk - // heuristic, and an empty split's m alone is written, which the - // combine's max must see (the windowed passes after the unwindowed - // one leave its later splits' partials behind). + // heuristic, and an empty split writes its m (attn_m_empty), so the + // combine never reads the partials the windowed passes after the + // unwindowed one leave behind in its later splits. upload_u32(dp, (unsigned)pos); cache.attn_dpos({q, 0}, {o2, 0}, HQ, {dp, 0}, scale); flush(); diff --git a/include/cuda_llm.h b/include/cuda_llm.h index af59732..3b1c226 100644 --- a/include/cuda_llm.h +++ b/include/cuda_llm.h @@ -182,10 +182,10 @@ inline unsigned attn_dpos_splits(int64_t n_q_heads, int64_t n_kv_heads, int64_t // gridDim.y = S_max = attn_dpos_splits at max_ctx, a constant for the cache's // lifetime — so the launch is capturable — while each block derives its live // split bounds from *d_pos (attn_dpos_chunk, under attn_split_rule passed as -// arguments). Splits past the live count write an empty m alone, and the -// combine's sums stop before them, so the output is bit-identical to the -// host attn_decode at every pos, a short cache costs its own splits rather -// than the capacity's, and the captured path stays split-KV-flat at long ctx. +// arguments). Splits past the live count are empty (attn_partials), which the +// combine's sums stop before, so the output is bit-identical to the host +// attn_decode at every pos, and the captured path stays split-KV-flat at long +// ctx. // `partials` is a caller-OWNED device buffer of attn_dpos_partials_bytes — // like d_pos, it is graph-lifetime state (a captured graph bakes its address // in), so it must not be a shared growable scratch; kv_cache owns one per diff --git a/include/cuda_nn.h b/include/cuda_nn.h index 80d276c..2f469d3 100644 --- a/include/cuda_nn.h +++ b/include/cuda_nn.h @@ -768,7 +768,11 @@ inline unsigned attn_split_chunk(unsigned rows, int64_t ctx) { // Split-KV partials scratch: ONE buffer laid out pm[H*S] | pl[H*S] | pacc[H*S*D] // (hs = H*S). bytes/the carve constructor/combine() keep that layout contract in // a single place — attn_decode's split branch and attn_decode_dpos both bake -// these pointers into launches (the dpos ones into a captured graph). +// these pointers into launches (the dpos ones into a captured graph). An empty +// split (a graph step's past its live count) writes its m alone, at +// attn_m_empty, and empty splits come after the rest (a split's first key +// grows with its index), so the combine's sums stop after the last split that +// is not: a short cache reads its own splits' partials, not the capacity's. struct attn_partials { float *pm, *pl, *pacc; attn_partials(float* base, size_t hs) : pm(base), pl(pm + hs), pacc(pl + hs) {} diff --git a/kernels/cuda_llm.cuh b/kernels/cuda_llm.cuh index 9ffe010..e2c970c 100644 --- a/kernels/cuda_llm.cuh +++ b/kernels/cuda_llm.cuh @@ -11,11 +11,9 @@ // DYNAMIC position: each block recomputes the host launcher's split heuristic // from *d_pos, so one instantiated graph replays correctly at every pos AND // stays split-KV-flat at long ctx. Splits past ceil(ctx/chunk) see k0 >= ctx -// and write their m alone, empty (attn_m_empty), and tl_attn_combine sums -// up to the last split that is not, so the output is bit-identical to the -// host path (single pass or split) at the same pos, and a short cache reads -// its own splits' partials rather than the capacity's. Body is -// attn_dec_core, as the by-value kernels'. +// and are empty (attn_partials, cuda_nn.h), which tl_attn_combine sums past, +// so the output is bit-identical to the host path (single pass or split) at +// the same pos. Body is attn_dec_core, as the by-value kernels'. // // attn_dpos_chunk is gpu::policy::split_parts + split_chunk on the device, under // the rule the launcher passes (cuda_nn.h's attn_split_rule), so the host and diff --git a/kernels/cuda_nn.cuh b/kernels/cuda_nn.cuh index 1737ee0..333d6a2 100644 --- a/kernels/cuda_nn.cuh +++ b/kernels/cuda_nn.cuh @@ -3092,10 +3092,8 @@ template constexpr int attn_dec_warps = AD == 512 ? 4 : 8; template constexpr int attn_dec_threads = 32 * attn_dec_warps; -// A softmax state's m before any key. A split's partial left at it (a dpos -// split past the live count writes nothing else) weighs exp(-1e30 - max) = 0 -// in the merge, so tl_attn_combine reads no l or acc past the last split that -// is not. +// A softmax state's m before any key, and all an empty split writes of its +// partial (attn_partials, cuda_nn.h): it weighs exp(-1e30 - max) = 0 in a merge. constexpr float attn_m_empty = -1e30f; // The decode attention's core. Block blockIdx.x is one kv head and a slice of @@ -3197,8 +3195,8 @@ __device__ __forceinline__ void attn_dec_core(const float* __restrict__ q, const } } - // Merge the warps' states (a warp whose keys were none carries m = -1e30, - // l = 0 and adds exp(-inf) = 0), every head at once. + // Merge the warps' states (a warp whose keys were none carries m = + // attn_m_empty, l = 0 and adds exp(-inf) = 0), every head at once. __shared__ float sm[NWB][GB], sl[NWB][GB], sacc[NWB][GB][AD]; #pragma unroll for (int g = 0; g < GB; g++) { @@ -3212,7 +3210,7 @@ __device__ __forceinline__ void attn_dec_core(const float* __restrict__ q, const __syncthreads(); for (unsigned e = tid; e < gn * AD; e += attn_dec_threads) { const unsigned g = e / AD, d = e % AD; - float gm = -1e30f; + float gm = attn_m_empty; #pragma unroll for (int w = 0; w < NWB; w++) gm = fmaxf(gm, sm[w][g]); float gl = 0.0f, o = 0.0f; @@ -3284,8 +3282,7 @@ TL_ATTN_SPLIT(512, __half, f16) #undef TL_ATTN_SPLIT // Merge the S per-head partials (each already at its local max) into out, the -// sums stopping after the last split whose m is not attn_m_empty (the -// splits after it are empty: a dpos step's past its live count). Not +// sums stopping after the last split that is not empty (attn_partials). Not // templated: the per-dim thread stride D == blockDim.x, so head_dim is // implicit. extern "C" __global__ void tl_attn_combine(const float* __restrict__ pm,