diff --git a/crates/cuda-driver/src/experimental.rs b/crates/cuda-driver/src/experimental.rs index fa2df446..746a20f0 100644 --- a/crates/cuda-driver/src/experimental.rs +++ b/crates/cuda-driver/src/experimental.rs @@ -8,9 +8,13 @@ //! ([`ExperimentalError::NotEnabled`]) unless one of the modes that need it was explicitly enabled, then refuses //! again ([`ExperimentalError::Unpinned`]) while its PTX pin is zero or does not match the bytes. //! -//! STATUS: the six PTX assets were compiled with nvcc 13.2.86 and sealed on 2026-10-15; every pin below matches -//! the checked-in bytes, and [`admit_ptx`] still refuses any zero pin, malformed bytes or digest mismatch. -//! Loading on a GPU is verified separately by the host smokes; no numerical claim is made here. +//! STATUS: the six PTX assets were compiled with nvcc 13.2.86 and sealed on 2026-10-15; every PTX digest below +//! matches the checked-in bytes, and [`admit_ptx`] still refuses any zero pin, malformed bytes or digest mismatch. +//! On 2026-11-03 the `.cu` of four programs ([`PENDING_RESEAL`]) was re-synced to the upstream Original (Strata pin +//! `41cf05a0`, `docs/experiments/2026-10-14-experimental-modes-port.md`, "Re-sync") on a host without nvcc: their +//! PTX was not rebuilt, so `source_sha256` still names the previous source and [`admit`] refuses those programs +//! ([`source_is_sealed`]) until the server reseals them. Loading on a GPU is verified separately by the host +//! smokes; no numerical claim is made here. use crate::{Context, Error, qwen_ffi}; use leleka_experimental_ref::{cvec, keyless, kv_q8, layout::QsaShapes, q4_0}; @@ -196,7 +200,8 @@ pub enum ExperimentalError { Invalid(&'static str), /// No enabled experimental mode needs this program. NotEnabled(&'static str), - /// The PTX asset is not pinned (all-zero digests) or its bytes differ. + /// The PTX asset is not pinned (all-zero digests), its bytes differ, or it was sealed from an older source than + /// the checked-in `.cu` ([`source_is_sealed`]). Unpinned(&'static str), Driver(Error), } @@ -210,7 +215,7 @@ impl fmt::Display for ExperimentalError { ), Self::Unpinned(program) => write!( f, - "experimental program {program} PTX is not pinned (TODO-ROOT)" + "experimental program {program} PTX is not pinned for its checked-in source (TODO-ROOT: pin zero, PTX bytes or source digest differ)" ), Self::Driver(error) => write!(f, "{error}"), } @@ -320,12 +325,34 @@ pub fn admit_ptx(program: Program, ptx: &'static [u8], pin: &PtxPin) -> Result<( Ok(()) } -/// Both gates in order: opt-in, then the pin. No driver call happens before both pass. +/// Programs whose checked-in `.cu` was re-synced to the upstream Original after their PTX was sealed, and whose PTX +/// has not been rebuilt (the re-sync host has no nvcc). Their `PINS[..].source_sha256` is the digest of the +/// previous source, so [`admit`] refuses them. The server-side reseal (nvcc 13.2.86, group `experimental`, +/// `scripts/gpu-bringup/reseal_own.py --plan docs/cuda-seal-plan-additions-experimental.json`) refreshes both pin +/// fields and empties this list; the unit test `pending_reseal_lists_exactly_the_unsealed_sources` forces that. +pub const PENDING_RESEAL: &[Program] = &[ + Program::KvQ4, + Program::KvQ8, + Program::KvStream, + Program::QsaAttn, +]; + +/// Whether the PTX pinned for `program` was built from the checked-in `.cu` (the pin's `source_sha256` is the +/// digest of that source). +pub fn source_is_sealed(program: Program) -> bool { + qwen_ffi::sha256(program.source().as_bytes()) == program.pin().source_sha256 +} + +/// All gates in order: opt-in, the PTX pin, then the source seal. No driver call happens before all pass. pub fn admit(program: Program, opt_in: &OptIn) -> Result<()> { if !opt_in.enables(program) { return Err(ExperimentalError::NotEnabled(program.name())); } - admit_ptx(program, program.ptx(), program.pin()) + admit_ptx(program, program.ptx(), program.pin())?; + if !source_is_sealed(program) { + return Err(ExperimentalError::Unpinned(program.name())); + } + Ok(()) } // ------------------------------------------------------------------------------------- entry signatures @@ -905,8 +932,13 @@ mod tests { assert_ne!(pin.source_sha256, [0; 32], "{}", program.name()); assert_ne!(pin.ptx_sha256, [0; 32], "{}", program.name()); assert_eq!(pin.ptx_sha256, qwen_ffi::sha256(&ptx[..ptx.len() - 1]), "{}", program.name()); - assert_eq!(pin.source_sha256, qwen_ffi::sha256(program.source().as_bytes()), "{}", program.name()); - assert_eq!(admit(program, &all), Ok(()), "{}", program.name()); + // a program re-synced after the seal (PENDING_RESEAL) keeps its old PTX and refuses to open + let expected = if PENDING_RESEAL.contains(&program) { + Err(ExperimentalError::Unpinned(program.name())) + } else { + Ok(()) + }; + assert_eq!(admit(program, &all), expected, "{}", program.name()); // the opt-in gate still comes first assert_eq!( admit(program, &OptIn::NONE), @@ -931,6 +963,45 @@ mod tests { } } + #[test] + fn pending_reseal_lists_exactly_the_unsealed_sources() { + for program in Program::ALL { + assert_eq!( + source_is_sealed(program), + !PENDING_RESEAL.contains(&program), + "{}: PENDING_RESEAL and the source digest of the pin disagree (after a server reseal the list must shrink, after a .cu edit without reseal it must grow)", + program.name() + ); + } + for (i, program) in PENDING_RESEAL.iter().enumerate() { + assert!( + !PENDING_RESEAL[i + 1..].contains(program), + "{} listed twice", + program.name() + ); + } + } + + #[test] + fn a_program_whose_source_is_newer_than_its_ptx_refuses_even_with_a_matching_ptx_digest() { + let all = OptIn::NONE + .with(Mode::KvQ40) + .with(Mode::KvK8V4) + .with(Mode::KeylessVOnly) + .with(Mode::KvStreamed) + .with(Mode::ControlVectors); + for &program in PENDING_RESEAL { + // the PTX bytes are the sealed ones and match their digest ... + assert_eq!(admit_ptx(program, program.ptx(), program.pin()), Ok(())); + // ... but they were not built from the checked-in source: admit fails closed + assert!(!source_is_sealed(program)); + assert_eq!( + admit(program, &all), + Err(ExperimentalError::Unpinned(program.name())) + ); + } + } + #[test] fn a_matching_pin_admits_and_any_difference_refuses() { static GOOD: &[u8] = b".version 8.7\n.target sm_120\n\0"; diff --git a/crates/cuda-driver/src/experimental_kv_q4.cu b/crates/cuda-driver/src/experimental_kv_q4.cu index dff0da04..cbe43790 100644 --- a/crates/cuda-driver/src/experimental_kv_q4.cu +++ b/crates/cuda-driver/src/experimental_kv_q4.cu @@ -18,10 +18,14 @@ // leleka_kv_append_q4_batch (T, n_head_kv, head_dim / 32) twice, is_v = 0 then 1 / 32 // leleka_kv_gather_q4_step ceil(max_ids * n_head_kv * (head_dim / 32) / 4) / (32, 4) // -// STATUS: NOT COMPILED OR RUN. There is no nvcc on the authoring host. The PTX pin in experimental.rs is zero -// until Root compiles this file with the pinned toolchain and freezes its digests. Intended offline compile -// (docs/cuda-seal-plan-additions-experimental.json): nvcc 12.8.93 -ptx -O3 -arch=sm_120, precise math (no -// --use_fast_math; the Original compiles kv_q4.cu with the default flags). +// RE-SYNC 2026-11-03 (Strata pin 41cf05a0): kv_append_q4_kernel gained `step_stride` and `planes` (the Original's +// multi-token append: blockIdx.z = step_idx * planes + plane); the body is copied verbatim and the entry keeps its +// ABI by passing step_stride 0 and planes 2, which is the single-step launch of the Original (kv_append_q4_step -> +// kv_append_q4_steps(..., 0, 1)) and the old behaviour bit for bit. Not compiled after the re-sync (no nvcc on that +// host): the sealed PTX is the 2026-10-15 build of the previous source and experimental::PENDING_RESEAL makes the +// program refuse to open until the server reseals it. +// Sealed 2026-10-15 with nvcc 13.2.86 -ptx -O3 -arch=sm_120 -std=c++17, precise math (no --use_fast_math; the Original +// compiles kv_q4.cu with the default flags); recipe in docs/cuda-seal-plan-additions-experimental.json. #include #include @@ -207,16 +211,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. __device__ __forceinline__ void kv_append_q4_kernel_body(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]; @@ -301,7 +307,10 @@ extern "C" __global__ void __launch_bounds__(32) leleka_kv_append_q4_step( KvHostPools host{}; host.k_q4 = host_k_q4; host.v_q4 = host_v_q4; - kv_append_q4_kernel_body(k_q4, v_q4, table, step, kcur, vcur, kv_heads, head_dim, page_size, host); + // the Original's single-step wrapper (kv_append_q4_step -> kv_append_q4_steps(..., step_stride 0, n_steps 1)) with + // both planes: the launch is (n_head_kv, head_dim / 32, 2), so blockIdx.z is the plane and step_idx is 0 + kv_append_q4_kernel_body(k_q4, v_q4, table, step, /*step_stride=*/0, /*planes=*/2, kcur, vcur, kv_heads, head_dim, + page_size, host); } extern "C" __global__ void __launch_bounds__(32) leleka_kv_append_q4_batch( diff --git a/crates/cuda-driver/src/experimental_kv_q8.cu b/crates/cuda-driver/src/experimental_kv_q8.cu index 269603b5..0854a930 100644 --- a/crates/cuda-driver/src/experimental_kv_q8.cu +++ b/crates/cuda-driver/src/experimental_kv_q8.cu @@ -18,8 +18,15 @@ // leleka_kv_append_q8_step (n_head_kv, head_dim / 64, k_q ? 2 : 1) / 64 // leleka_kv_gather_q8_step ceil(max_ids * n_head_kv * (head_dim / 4) / 256) / 256 // -// STATUS: NOT COMPILED OR RUN (no nvcc here). PTX pin is zero until Root freezes it. Intended offline compile: -// nvcc 12.8.93 -ptx -O3 -arch=sm_120, precise math (the Original builds kv_q8.cu with default flags). +// RE-SYNC 2026-11-03 (Strata pin 41cf05a0): kv_append_q8_kernel became `template ` with `step_stride` / +// `cur_stride` (the Original's S26 multi-token append); the body is copied verbatim and the entry instantiates the +// single-token form (MULTI = false, strides 0), the old behaviour bit for bit, with its ABI unchanged. The MULTI +// branch is therefore not instantiated here. The Original's 8-wide gather (kv_gather_q8_wide_kernel) exists only +// under STRATA_EXPERIMENTAL_SM60 and is not part of this sm_120 program (tests/literal_port.rs lists it as excluded). +// Not compiled after the re-sync (no nvcc on that host): the sealed PTX is the 2026-10-15 build of the previous source +// and experimental::PENDING_RESEAL makes the program refuse to open until the server reseals it. +// Sealed 2026-10-15 with nvcc 13.2.86 -ptx -O3 -arch=sm_120 -std=c++17, precise math (the Original builds kv_q8.cu with +// default flags); recipe in docs/cuda-seal-plan-additions-experimental.json. #include #include @@ -121,14 +128,22 @@ STRATA_HD inline float f32_from_f16(uint16_t h) { namespace { // One block = one 64-value group of one KV head of K (blockIdx.z = 0) or V (1); 64 threads, one value each. +// MULTI (S26 STRATA_LFUSE): blockIdx.z = 2 * token + (K / V); token j reads step + j * step_stride and its rows at +// kcur / vcur + j * cur_stride - every token's code is the single launch's +template __device__ __forceinline__ void kv_append_q8_kernel_body(int8_t* __restrict__ k_q, int8_t* __restrict__ v_q, uint16_t* __restrict__ k_scale, uint16_t* __restrict__ v_scale, const int32_t* __restrict__ table, const int32_t* __restrict__ step, const float* __restrict__ kcur, const float* __restrict__ vcur, int kv_heads, - int head_dim, int page_size, KvHostPools host) { + int head_dim, int page_size, KvHostPools host, int step_stride = 0, + int cur_stride = 0) { + if constexpr (MULTI) { + const int j = blockIdx.z >> 1; + step += (size_t) j * step_stride; kcur += (size_t) j * cur_stride; vcur += (size_t) j * cur_stride; + } const long long pos = (long long) __ldg(step + kStepPos); const int h = blockIdx.x, g = blockIdx.y, t = threadIdx.x; - const bool is_v = k_q == nullptr || blockIdx.z == 1; + const bool is_v = k_q == nullptr || (MULTI ? (blockIdx.z & 1) == 1 : blockIdx.z == 1); // k_q == nullptr: V-only (keyless) arm const int groups = head_dim / KV_Q8_GROUP; const float x = (is_v ? vcur : kcur)[h * head_dim + g * KV_Q8_GROUP + t]; // max |x| over the 64 values: two warps, then combine through shared memory in a fixed order @@ -159,7 +174,8 @@ __device__ __forceinline__ void kv_append_q8_kernel_body(int8_t* __restrict__ k_ } } -// One thread = 4 consecutive values of one cell and head (as the FP16 gather does with uint2). +// One thread = 4 consecutive values of one cell and head (as the FP16 gather does with uint2). This is the gather +// the ready-made engine runs; the experimental build's 8-wide kernel is below it. __device__ __forceinline__ void kv_gather_q8_kernel_body(const int8_t* __restrict__ k_q, const int8_t* __restrict__ v_q, const uint16_t* __restrict__ k_scale, const uint16_t* __restrict__ v_scale, const int32_t* __restrict__ table, const int32_t* __restrict__ ids, diff --git a/crates/cuda-driver/src/experimental_kv_stream.cu b/crates/cuda-driver/src/experimental_kv_stream.cu index 98a2a48e..1c4c1027 100644 --- a/crates/cuda-driver/src/experimental_kv_stream.cu +++ b/crates/cuda-driver/src/experimental_kv_stream.cu @@ -21,8 +21,14 @@ // leleka_kv_ring_table 64 / 256 // leleka_kv_copy_u4 min(ceil(n_u4 / 128), 4096) / 128 // -// STATUS: NOT COMPILED OR RUN (no nvcc here). PTX pin is zero until Root freezes it. Intended offline compile: -// nvcc 12.8.93 -ptx -O3 -arch=sm_120, precise math (the Original builds kv_stream.cu with default flags). +// RE-SYNC 2026-11-03 (Strata pin 41cf05a0): resolve_kernel skips the shared atomicAdd of a thread that saw no lookup +// (`if (lookups > 0) atomicAdd(...)`, upstream #783), the same counter value. The Original's host side also grew a +// K8V4 (hybrid) block layout (runs_of, kv_block_bytes) and kv_unstage_to_host; those are host code and not part of +// this program (the copy entry already takes up to four runs). Not compiled after the re-sync (no nvcc on that host): +// the sealed PTX is the 2026-10-15 build of the previous source and experimental::PENDING_RESEAL makes the program +// refuse to open until the server reseals it. +// Sealed 2026-10-15 with nvcc 13.2.86 -ptx -O3 -arch=sm_120 -std=c++17, precise math (the Original builds kv_stream.cu +// with default flags); recipe in docs/cuda-seal-plan-additions-experimental.json. #include namespace strata { @@ -112,7 +118,7 @@ __device__ __forceinline__ void resolve_kernel_body(KvStreamMap m, const int32_t } } } - atomicAdd(&s_lookups, lookups); + if (lookups > 0) atomicAdd(&s_lookups, lookups); // (#783, stuchapin909) most threads see none: skip the shared atomic __syncthreads(); // 2. one victim per miss: a clock sweep from the hand. A slot this call uses (stamp == epoch) is never taken; // a referenced one loses its bit as the hand passes it and is taken on the next pass. diff --git a/crates/cuda-driver/src/experimental_qsa_attn.cu b/crates/cuda-driver/src/experimental_qsa_attn.cu index 5f4723d3..7fbf6c08 100644 --- a/crates/cuda-driver/src/experimental_qsa_attn.cu +++ b/crates/cuda-driver/src/experimental_qsa_attn.cu @@ -20,8 +20,15 @@ // leleka_qsa_attn_chunk_m2 / _m3 / _m4 (n_chunks, n_head_kv, n_q) / 256 // leleka_qsa_attn_merge (n_head, n_q) / 256 // -// STATUS: NOT COMPILED OR RUN (no nvcc here). PTX pin is zero until Root freezes it. Intended offline compile: -// nvcc 12.8.93 -ptx -O3 -arch=sm_120, precise math (the Original builds qsa_decode_attn.cu with default flags). +// RE-SYNC 2026-11-03 (Strata pin 41cf05a0): the chunk kernel's body is now the Original's `attn_chunk_body` (with reduce12_gfx906 / reduce12_head_of_lane), copied verbatim; the entries +// instantiate it with the three flags off, which is the previous kernel's arithmetic. The Original's alternate +// schedules and batch variants (attn_chunk_kernel_pre75 and its helpers, attn_merge_v2_kernel, the INT8 v3 kernel, +// the slot / row kernels) are not part of this program: tests/literal_port.rs lists each as excluded with its reason. +// Not compiled after the re-sync (no nvcc on that host): the sealed PTX is the 2026-10-15 build of the previous +// source and experimental::PENDING_RESEAL makes the program refuse to open until the server reseals it. +// Sealed 2026-10-15 with nvcc 13.2.86 -ptx -O3 -arch=sm_120 -std=c++17, precise math (the Original builds +// qsa_decode_attn.cu with default flags); recipe in docs/cuda-seal-plan-additions-experimental.json. #include #include @@ -142,13 +149,46 @@ __device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long lo } else load8_q4(p, value, row, d0, out); } -template -__device__ __forceinline__ void attn_chunk_kernel_body(const float* __restrict__ q, QsaAttnPools p, - 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 = 0, long long scratch_stride = 0) { +// Exact-intent score reduce-scatter: the same butterfly pairs as twelve warp_sum calls, +// with 16 shuffle exchanges instead of 60. Used only by the opt-in gfx906 INT8 +// query-swizzled specialization; softmax, value accumulation and merge are unchanged. +__device__ __forceinline__ float reduce12_gfx906(const float (&part)[16], int lane) { + float r8[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const bool hi = (lane & 16) != 0; + r8[i] = (hi ? part[i + 8] : part[i]) + __shfl_xor_sync(0xffffffffu, hi ? part[i] : part[i + 8], 16); + } + float r4[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const bool hi = (lane & 8) != 0; + r4[i] = (hi ? r8[i + 4] : r8[i]) + __shfl_xor_sync(0xffffffffu, hi ? r8[i] : r8[i + 4], 8); + } + float r2[2]; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const bool hi = (lane & 4) != 0; + r2[i] = (hi ? r4[i + 2] : r4[i]) + __shfl_xor_sync(0xffffffffu, hi ? r4[i] : r4[i + 2], 4); + } + const bool hi2 = (lane & 2) != 0; + const float r1 = (hi2 ? r2[1] : r2[0]) + __shfl_xor_sync(0xffffffffu, hi2 ? r2[0] : r2[1], 2); + return r1 + __shfl_xor_sync(0xffffffffu, r1, 1); +} +__device__ __forceinline__ int reduce12_head_of_lane(int lane) { + return ((lane >> 4) & 1) * 8 + ((lane >> 3) & 1) * 4 + ((lane >> 2) & 1) * 2 + ((lane >> 1) & 1); +} + +// 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 +__device__ __forceinline__ void attn_chunk_body(const float* __restrict__ q, QsaAttnPools p, + 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) { // batched form: query blockIdx.z, with its own q row, selection, step and scratch q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD; ids += (size_t) blockIdx.z * (size_t) cap; @@ -169,7 +209,15 @@ __device__ __forceinline__ void attn_chunk_kernel_body(const float* __restrict__ if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; } return; } - for (int i = t; i < G * HD; i += THREADS) sq[i / HD][i % HD] = q[(size_t) (kvh * G) * HD + i]; + // Opt-in gfx906 batched attention: a bijective XOR of query dimensions in LDS only. It swaps the two + // float4 halves of lanes whose bit 2 is set, retaining 16-byte alignment and the 12 KB tile. + // The scoring reads undo this permutation; FP operands and operation order are unchanged. + static_assert(!QUERY_SWIZZLE || !LANE_CELL, "query swizzle is for warp scoring only"); + for (int i = t; i < G * HD; i += THREADS) { + const int d = i % HD; + const int sd = QUERY_SWIZZLE ? (d ^ ((d >> 3) & 4)) : d; + sq[i / HD][sd] = q[(size_t) (kvh * G) * HD + i]; + } if (t < CHUNK) { long long r = -1; if (t < n_here) { @@ -182,12 +230,66 @@ __device__ __forceinline__ void attn_chunk_kernel_body(const float* __restrict__ srow[t] = r; } __syncthreads(); + if constexpr (LANE_CELL) { + // S25 (STRATA_ATTN_LANECELL=1): thread t scores cell t % 64 for heads 3 (t / 64) .. +2 by itself - the same + // 8-dimension partial per former lane (the identical expression), then the former warp_sum's butterfly as + // lane 0 ran it (a[l] += a[l + o] for o = 16 .. 1), so every score is bit-identical without 12 shuffle + // reductions per cell + constexpr int HPT = G * CHUNK / THREADS; // heads per thread (3) + const int c = t % CHUNK, h0 = (t / CHUNK) * HPT; + if (c >= n_here || srow[c] < 0) { +#pragma unroll + for (int j = 0; j < HPT; ++j) sp[h0 + j][c] = -FLT_MAX; + } else { + float a[HPT][32]; +#pragma unroll + for (int l = 0; l < 32; ++l) { + float k8[8]; + load8(p, false, srow[c], l * 8, k8); +#pragma unroll + for (int j = 0; j < HPT; ++j) { + const float4 qa = *reinterpret_cast(&sq[h0 + j][l * 8]); + const float4 qb = *reinterpret_cast(&sq[h0 + j][l * 8 + 4]); + float s = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w + + k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w; + a[j][l] = s; + } + } +#pragma unroll + for (int j = 0; j < HPT; ++j) { +#pragma unroll + for (int o = 16; o > 0; o >>= 1) +#pragma unroll + for (int l = 0; l < o; ++l) a[j][l] = a[j][l] + a[j][l + o]; + sp[h0 + j][c] = a[j][0] * scale; + } + } + } else // scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions. for (int c = warp; c < CHUNK; c += WARPS) { if (c >= n_here || srow[c] < 0) { if (lane < G) sp[lane][c] = -FLT_MAX; continue; } + if constexpr (REDUCE12) { + float k8[8]; + load8(p, false, srow[c], lane * 8, k8); + float part[16]; +#pragma unroll + for (int h = 0; h < G; ++h) { + const int qflip = QUERY_SWIZZLE ? (lane & 4) : 0; + const float4 qa = *reinterpret_cast(&sq[h][lane * 8 + qflip]); + const float4 qb = *reinterpret_cast(&sq[h][lane * 8 + (qflip ^ 4)]); + float s = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w + + k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w; + part[h] = s; + } +#pragma unroll + for (int h = G; h < 16; ++h) part[h] = 0.0f; + const float score = reduce12_gfx906(part, lane); + const int head = reduce12_head_of_lane(lane); + if ((lane & 1) == 0 && head < G) sp[head][c] = score * scale; + } else { float k8[8]; load8(p, KV_MODE == 4, srow[c], lane * 8, k8); if constexpr (KV_MODE == 4) { @@ -207,13 +309,15 @@ __device__ __forceinline__ void attn_chunk_kernel_body(const float* __restrict__ } #pragma unroll for (int h = 0; h < G; ++h) { - const float4 qa = *reinterpret_cast(&sq[h][lane * 8]); - const float4 qb = *reinterpret_cast(&sq[h][lane * 8 + 4]); + const int qflip = QUERY_SWIZZLE ? (lane & 4) : 0; + const float4 qa = *reinterpret_cast(&sq[h][lane * 8 + qflip]); + const float4 qb = *reinterpret_cast(&sq[h][lane * 8 + (qflip ^ 4)]); float s = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w + k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w; s = warp_sum(s); if (lane == 0) sp[h][c] = s * scale; } + } } __syncthreads(); // per-head chunk max and exp-sum: warp w handles heads w and w+8. @@ -298,8 +402,8 @@ extern "C" __global__ void __launch_bounds__(256) leleka_qsa_attn_chunk_m2( p.k_q4 = k_q4; p.v_q4 = v_q4; p.page_table = page_table; - attn_chunk_kernel_body<2>(q, p, ids, step, n_kv_heads, page_size, 1.0f / sqrtf((float) HD), part_acc, part_m, - part_l, n_chunks, cap, scratch_stride); + attn_chunk_body<2, false, false, false>(q, p, ids, step, n_kv_heads, page_size, 1.0f / sqrtf((float) HD), + part_acc, part_m, part_l, n_chunks, cap, scratch_stride); } extern "C" __global__ void __launch_bounds__(256) leleka_qsa_attn_chunk_m3( @@ -312,8 +416,8 @@ extern "C" __global__ void __launch_bounds__(256) leleka_qsa_attn_chunk_m3( p.k_scale = k_scale; p.v_q4 = v_q4; p.page_table = page_table; - attn_chunk_kernel_body<3>(q, p, ids, step, n_kv_heads, page_size, 1.0f / sqrtf((float) HD), part_acc, part_m, - part_l, n_chunks, cap, scratch_stride); + attn_chunk_body<3, false, false, false>(q, p, ids, step, n_kv_heads, page_size, 1.0f / sqrtf((float) HD), + part_acc, part_m, part_l, n_chunks, cap, scratch_stride); } extern "C" __global__ void __launch_bounds__(256) leleka_qsa_attn_chunk_m4( @@ -331,8 +435,8 @@ extern "C" __global__ void __launch_bounds__(256) leleka_qsa_attn_chunk_m4( p.keyless_sin = keyless_sin; p.keyless_mrope = keyless_mrope; p.keyless_n_rot = keyless_n_rot; - attn_chunk_kernel_body<4>(q, p, ids, step, n_kv_heads, page_size, 1.0f / sqrtf((float) HD), part_acc, part_m, - part_l, n_chunks, cap, scratch_stride); + attn_chunk_body<4, false, false, false>(q, p, ids, step, n_kv_heads, page_size, 1.0f / sqrtf((float) HD), + part_acc, part_m, part_l, n_chunks, cap, scratch_stride); } extern "C" __global__ void __launch_bounds__(256) leleka_qsa_attn_merge( diff --git a/crates/experimental-ref/tests/literal_port.rs b/crates/experimental-ref/tests/literal_port.rs index 164b49f2..38477b9a 100644 --- a/crates/experimental-ref/tests/literal_port.rs +++ b/crates/experimental-ref/tests/literal_port.rs @@ -2,6 +2,14 @@ //! Original (`engine/strata/src/kernels/cuda/*.cu`) must still appear, whitespace-normalised, in the checked-in //! port (`crates/cuda-driver/src/experimental_*.cu`). Signatures, host wrappers and error handling are the //! documented deviations; kernel bodies are not allowed to differ. +//! +//! A device function of the Original that the port deliberately does not carry is named in that pair's +//! `EXCLUDED` list with its reason. The list is the only way past the guard, it is checked both ways (a name that +//! no longer exists in the Original fails, so the list cannot rot), and a NEW device function of the Original +//! that is neither in the port nor in the list fails the test: the upstream sync has to be looked at. +//! +//! History: the 2026-10-25 sync of `engine/strata` to upstream `41cf05a0` moved the Original kernels and the +//! ports were re-synced on 2026-11-03 (`docs/experiments/2026-10-14-experimental-modes-port.md`, "Re-sync"). use std::collections::HashSet; @@ -9,12 +17,41 @@ fn norm(line: &str) -> String { line.split_whitespace().collect::>().join(" ") } -/// Normalised lines of the bodies of all device functions (text between the first `{` after the -/// `__global__` / `__device__` marker and its matching `}`), signatures excluded. -fn device_bodies(source: &str) -> Vec { +/// One `__global__` / `__device__` function of a source: its name and the normalised lines of its body. +#[derive(Debug)] +struct Body { + name: String, + lines: Vec, +} + +/// The function name of a signature (text between the `__global__` / `__device__` marker and the opening brace): +/// the identifier right before the first `(` once `__launch_bounds__(..)` is removed. +fn signature_name(signature: &str) -> String { + let mut text = signature.to_string(); + while let Some(i) = text.find("__launch_bounds__") { + let open = text[i..].find('(').map(|k| i + k); + let close = open.and_then(|o| text[o..].find(')').map(|k| o + k)); + match close { + Some(c) => text.replace_range(i..=c, " "), + None => break, + } + } + let head = match text.find('(') { + Some(i) => &text[..i], + None => &text[..], + }; + head.trim_end() + .rsplit(|c: char| !(c.is_alphanumeric() || c == '_')) + .next() + .unwrap_or("") + .to_string() +} + +/// Bodies of all device functions (text between the first `{` after the `__global__` / `__device__` marker and its +/// matching `}`), signatures excluded. +fn device_bodies(source: &str) -> Vec { let mut out = Vec::new(); - let bytes: Vec = source.chars().collect(); - let text: String = bytes.iter().collect(); + let text = source; let mut search = 0; while search < text.len() { let rest = &text[search..]; @@ -49,12 +86,17 @@ fn device_bodies(source: &str) -> Vec { } } let end = end.expect("unbalanced braces"); + let mut lines = Vec::new(); for line in after[b + 1..end].lines() { let l = norm(line); if l.len() >= 6 && !l.starts_with("//") { - out.push(l); + lines.push(l); } } + out.push(Body { + name: signature_name(&after[..b]), + lines, + }); search = from + end; } _ => break, @@ -63,31 +105,213 @@ fn device_bodies(source: &str) -> Vec { out } -fn check(name: &str, original: &str, port: &str) { +/// A device function of the Original that the port does not carry, and why. +type Excluded = (&'static str, &'static str); + +fn check(name: &str, original: &str, port: &str, excluded: &[Excluded]) { let have: HashSet = port.lines().map(norm).collect(); let flat = norm(port); let bodies = device_bodies(original); - assert!(bodies.len() > 5, "{name}: found no device bodies"); - let missing: Vec<&String> = bodies.iter().filter(|l| !have.contains(*l) && !flat.contains(l.as_str())).collect(); - assert!(missing.is_empty(), "{name}: {} original kernel-body lines are not in the port:\n{}", missing.len(), missing.iter().map(|l| l.as_str()).collect::>().join("\n")); - println!("{name}: {} kernel-body lines all present", bodies.len()); + let names: HashSet<&str> = bodies.iter().map(|b| b.name.as_str()).collect(); + for (function, reason) in excluded { + assert!( + names.contains(function), + "{name}: EXCLUDED names `{function}` ({reason}) but the Original has no such device function; remove or rename the entry" + ); + assert!( + !reason.is_empty(), + "{name}: `{function}` is excluded without a reason" + ); + } + let skip: HashSet<&str> = excluded.iter().map(|(f, _)| *f).collect(); + let kept: Vec<&Body> = bodies + .iter() + .filter(|b| !skip.contains(b.name.as_str())) + .collect(); + let lines: Vec<&String> = kept.iter().flat_map(|b| b.lines.iter()).collect(); + assert!(lines.len() > 5, "{name}: found no device bodies"); + let missing: Vec<&String> = lines + .iter() + .copied() + .filter(|l| !have.contains(*l) && !flat.contains(l.as_str())) + .collect(); + assert!( + missing.is_empty(), + "{name}: {} original kernel-body lines are not in the port:\n{}", + missing.len(), + missing + .iter() + .map(|l| l.as_str()) + .collect::>() + .join("\n") + ); + println!( + "{name}: {} kernel-body lines of {} device functions all present; {} functions excluded with a reason", + lines.len(), + kept.len(), + excluded.len() + ); } macro_rules! pair { - ($test:ident, $name:literal, $orig:literal, $port:literal) => { + ($test:ident, $name:literal, $orig:literal, $port:literal, $excluded:expr) => { #[test] fn $test() { check( $name, include_str!(concat!("../../../engine/strata/src/kernels/cuda/", $orig)), include_str!(concat!("../../cuda-driver/src/", $port)), + $excluded, ); } }; } -pair!(kv_q4_bodies_are_literal, "kv_q4", "kv_q4.cu", "experimental_kv_q4.cu"); -pair!(kv_q8_bodies_are_literal, "kv_q8", "kv_q8.cu", "experimental_kv_q8.cu"); -pair!(kv_stream_bodies_are_literal, "kv_stream", "kv_stream.cu", "experimental_kv_stream.cu"); -pair!(keyless_bodies_are_literal, "keyless", "keyless.cu", "experimental_keyless.cu"); -pair!(qsa_attn_bodies_are_literal, "qsa_attn", "qsa_decode_attn.cu", "experimental_qsa_attn.cu"); -pair!(cvec_bodies_are_literal, "cvec", "cvec.cu", "experimental_cvec.cu"); + +// kv_q8.cu: the 8-wide gather exists only in the experimental SM60 build of the Original (`#if +// defined(STRATA_EXPERIMENTAL_SM60)`, Pascal / Volta). The ready-made engine, and this port (sm_120, sm_86), run the +// 4-wide `kv_gather_q8_kernel`, which is ported. The Original states the wide kernel is bitwise the same. +const KV_Q8_EXCLUDED: &[Excluded] = &[ + ( + "q8_pair_to_f16x2", + "STRATA_EXPERIMENTAL_SM60 build only (sm_60/sm_70); compiled out of the ready-made engine", + ), + ( + "kv_gather_q8_wide_kernel", + "STRATA_EXPERIMENTAL_SM60 build only (sm_60/sm_70); bitwise the 4-wide gather, which is ported", + ), +]; + +// qsa_decode_attn.cu: the port carries the reference schedule of KV modes 2, 3 and 4 and the merge. The Original +// grew alternate schedules and batch variants of the same arithmetic, picked by architecture or environment, none +// of which the six closed programs expose as an entry. The Original proves the alternates bitwise equal to the +// reference schedule (its `qsa_merge_daily_parity` and `kv_hybrid_parity` harnesses, header comment of +// `qsa_decode_attn_chunks_only`); here the emulated reference schedule is compared with the Rust CPU reference +// (tests/emulated_kernels.rs). +const QSA_ATTN_EXCLUDED: &[Excluded] = &[ + ( + "attn_chunk_kernel", + "thin __global__ wrapper over attn_chunk_body; the extern \"C\" entries of the port are the equivalent wrappers", + ), + ( + "attn_chunk_slots_kernel", + "same body over a per-query pool set (QsaAttnSlotPools kernel argument): engine batch slots, not an experimental entry", + ), + ( + "attn_chunk_rows_kernel", + "same body over per-query pool rows (QsaAttnPoolsRows kernel argument): engine batch windows, not an experimental entry", + ), + ( + "attn_chunk_q8_v3_kernel", + "INT8 (KV_MODE 1) Turing schedule; the port instantiates modes 2, 3 and 4 only", + ), + ( + "attn_chunk_kernel_pre75", + "alternate schedule of attn_chunk_body (NC cells per step, reduce12); bitwise the reference schedule per the Original's parity harness; the Original selects it for pre-sm_75 cards and, by default, compute capability 12.0 (STRATA_ATTN_DAILY)", + ), + ("shfl_x", "helper of attn_chunk_kernel_pre75 only"), + ("warp_sum_x", "helper of attn_chunk_kernel_pre75 only"), + ("warp_max_x", "helper of attn_chunk_kernel_pre75 only"), + ( + "reduce12", + "helper of attn_chunk_kernel_pre75 only (reduce12_gfx906 is the ported twin used by attn_chunk_body)", + ), + ( + "head_of_lane", + "helper of attn_chunk_kernel_pre75 only (reduce12_head_of_lane is the ported twin)", + ), + ("load_v1", "helper of attn_chunk_kernel_pre75 only"), + ("merge_max_block", "helper of attn_merge_v2_kernel only"), + ("merge_sum_block", "helper of attn_merge_v2_kernel only"), + ( + "attn_merge_v2_kernel", + "alternate merge (width-bounded, batched loads); bitwise attn_merge_kernel per the Original's parity harness; follows STRATA_ATTN_DAILY", + ), +]; + +pair!( + kv_q4_bodies_are_literal, + "kv_q4", + "kv_q4.cu", + "experimental_kv_q4.cu", + &[] +); +pair!( + kv_q8_bodies_are_literal, + "kv_q8", + "kv_q8.cu", + "experimental_kv_q8.cu", + KV_Q8_EXCLUDED +); +pair!( + kv_stream_bodies_are_literal, + "kv_stream", + "kv_stream.cu", + "experimental_kv_stream.cu", + &[] +); +pair!( + keyless_bodies_are_literal, + "keyless", + "keyless.cu", + "experimental_keyless.cu", + &[] +); +pair!( + qsa_attn_bodies_are_literal, + "qsa_attn", + "qsa_decode_attn.cu", + "experimental_qsa_attn.cu", + QSA_ATTN_EXCLUDED +); +pair!( + cvec_bodies_are_literal, + "cvec", + "cvec.cu", + "experimental_cvec.cu", + &[] +); + +#[test] +fn the_guard_notices_a_changed_or_unlisted_device_function() { + let original = "__global__ void k(int a) {\n int x = a + 1;\n int y = x * 2;\n int u = y + x;\n int v = u + y;\n int z = y - 3;\n int w = z;\n return;\n}\n\ + __device__ __forceinline__ float helper(float v) {\n float s = v * 3.0f + 1.0f;\n return s * s;\n}\n"; + let port_same = original.replace("__global__ void k(int a)", "__device__ void k_body(int a)"); + check("synthetic", original, &port_same, &[]); + let changed = port_same.replace("int y = x * 2;", "int y = x * 3;"); + assert!(std::panic::catch_unwind(|| check("synthetic", original, &changed, &[])).is_err()); + let without_helper = port_same.replace("float s = v * 3.0f + 1.0f;", "float s = v;"); + assert!( + std::panic::catch_unwind(|| check("synthetic", original, &without_helper, &[])).is_err() + ); + // an exclusion lets the function go, a stale one is refused + check( + "synthetic", + original, + &without_helper, + &[("helper", "test")], + ); + assert!( + std::panic::catch_unwind(|| check("synthetic", original, &port_same, &[("gone", "test")])) + .is_err() + ); +} + +#[test] +fn signature_names_survive_launch_bounds_and_templates() { + assert_eq!( + signature_name( + " void __launch_bounds__(THREADS) attn_chunk_kernel_pre75(const float* q, int n)" + ), + "attn_chunk_kernel_pre75" + ); + assert_eq!( + signature_name(" __forceinline__ float warp_sum(float v)"), + "warp_sum" + ); + assert_eq!( + signature_name( + "\n__device__ __forceinline__ void attn_chunk_body(const float* __restrict__ q, QsaAttnPools p," + ), + "attn_chunk_body" + ); +} diff --git a/docs/ci-audit.md b/docs/ci-audit.md index 454906e8..6a799be1 100644 --- a/docs/ci-audit.md +++ b/docs/ci-audit.md @@ -144,12 +144,13 @@ The rebase brought a new workspace member and new code, and the gates found prob Rust unit test (`messages.rs:643`) expects the new order, the Python smoke expects the old one and also expects the Messages path to match the Responses path byte for byte. Either the smoke is stale or the prompt text of error results changed for Claude Code clients. This is an owner decision (tool-call integrity, AGENTS.md priority 2); I did not change it. -4. **The Oct-25 upstream sync left the experimental CUDA ports behind**: `leleka-experimental-ref` `literal_port` fails 4 of 6 +4. **The Oct-25 upstream sync left the experimental CUDA ports behind**: `leleka-experimental-ref` `literal_port` failed 4 of 6 tests (`kv_stream`, `kv_q4`, `kv_q8`, `qsa_attn`: 1, 5, 20 and 197 Original kernel-body lines missing from - `crates/cuda-driver/src/experimental_*.cu`). Already noted in `docs/windows.md`; red on Windows and Linux alike. Now reported as - debt, not hidden. Re-sync of those ports (kernel sources) is outside this audit. + `crates/cuda-driver/src/experimental_*.cu`). **Closed** on `claude/experimental-resync` (2026-11-03): the four `.cu` were re-synced, + `literal_port` passes and is a hard gate again; what drifted and what still needs a server-side PTX reseal is in + `docs/experiments/2026-10-14-experimental-modes-port.md` ("Re-sync"). 5. **`main` itself has red tests the CI would have shown**: `log_failure_sse::no_panicking_log_macros_in_the_serving_crate` since the - observability merge, and `literal_port` (finding 4). The first is fixed here; the second is reported. + observability merge, and `literal_port` (finding 4). The first is fixed here; the second is fixed on `claude/experimental-resync`. 6. **Tests that depend on the host instead of the code.** The `leleka-deploy` end-to-end tests read the real GPU through `nvidia-smi` (free VRAM) and the default loopback ports 18766/18080. On this laptop, with another agent's engine running, 5 of 6 failures were of this kind; `docs/deploy.md` ("all passing in WSL") was true only on an idle GPU. A CI host has no @@ -192,7 +193,7 @@ Commit "ci: build and test what ships ..." (CI and repairs): * `scripts/check-ci-coverage.py` + `scripts/ci-coverage.json`: fails when a workspace member is not listed, when a default-member is exempt, when an entry is stale, or when no workflow or `check-local.sh` step names a "tested" crate. * `scripts/ci/nvidia-smi`: stand-in used by the product job for the deploy tests. -* `check-local.sh`: `-p leleka-cuda-driver --features cuda-driver`; `literal_port` split out as debt; control-plane Clippy `--no-deps`. +* `check-local.sh`: `-p leleka-cuda-driver --features cuda-driver`; `literal_port` split out as debt (re-synced and made a hard gate again by `claude/experimental-resync`); control-plane Clippy `--no-deps`. * `desktop.yml`: hardware smoke with `--bin strata-desktop` (first commit); Lints with `--no-deps` (the "docs: ci-audit" commit). * Formatting of `leleka-backend-api` and `leleka-context`; a local type alias in `leleka-tokenizer` (`fast.rs`); four one-line Clippy fixes (`leleka-memory` `governor.rs` redundant cast, `leleka-deploy` `app.rs`, `wsl.rs`, `reconfigure.rs` test); diff --git a/docs/cuda-seal-plan-additions-experimental.json b/docs/cuda-seal-plan-additions-experimental.json index facadab3..2a9107ca 100644 --- a/docs/cuda-seal-plan-additions-experimental.json +++ b/docs/cuda-seal-plan-additions-experimental.json @@ -5,8 +5,8 @@ { "cu": "crates/cuda-driver/src/experimental_kv_q4.cu", "cu_pin": { - "sha256": "4b2ed68008f3aa87adf1445c608baee4439a0ca41213ac2e280a70e88448b420", - "bytes": 16598 + "sha256": "378058e82084b697e13e8ac3cd25520372d2848ed3ebec78ac5e369ee9a91720", + "bytes": 17507 }, "ptx": "crates/cuda-driver/src/experimental_kv_q4.ptx", "flags": [ @@ -41,8 +41,8 @@ { "cu": "crates/cuda-driver/src/experimental_kv_q8.cu", "cu_pin": { - "sha256": "93a45694250c1c9abecb372940ba52e158887bcbea58133215910e26a96a7174", - "bytes": 12008 + "sha256": "007f00692c702313a79dee0f1aa433c3412f6b4d73de620b02e136d960203c9f", + "bytes": 13448 }, "ptx": "crates/cuda-driver/src/experimental_kv_q8.ptx", "flags": [ @@ -77,8 +77,8 @@ { "cu": "crates/cuda-driver/src/experimental_kv_stream.cu", "cu_pin": { - "sha256": "ab873bf939f5235023dd92d706c8814ab78f955ab15e1293b8e0b96caa5cc153", - "bytes": 11751 + "sha256": "8c9fe1c0e4164ac2b40304a389710615829842a2ac47ab4b4ef92b3ace5d5a4f", + "bytes": 12456 }, "ptx": "crates/cuda-driver/src/experimental_kv_stream.ptx", "flags": [ @@ -149,8 +149,8 @@ { "cu": "crates/cuda-driver/src/experimental_qsa_attn.cu", "cu_pin": { - "sha256": "c65d991ad9fe700101ce012a80c94fc7de582117fae357c5eea8954370195d8f", - "bytes": 17458 + "sha256": "907ffc8f7504efd0655d2311ac4787fb131dfd1ef7cbf1aebfdddf1b9d31c505", + "bytes": 23119 }, "ptx": "crates/cuda-driver/src/experimental_qsa_attn.ptx", "flags": [ diff --git a/docs/experiments/2026-10-14-experimental-modes-port.md b/docs/experiments/2026-10-14-experimental-modes-port.md index ab0ad5f0..f19f0d08 100644 --- a/docs/experiments/2026-10-14-experimental-modes-port.md +++ b/docs/experiments/2026-10-14-experimental-modes-port.md @@ -2,7 +2,9 @@ Branch `claude/port-experimental` (based on `claude/port-main`). Everything here is **experimental and off by default**: `OptIn::default()` enables nothing, every closed program refuses to open without an enabled mode, and -every PTX pin is zero, so nothing reaches the driver until Root builds the PTX and freezes the digests. +refuses again while its PTX pin does not match. The six PTX were compiled with nvcc 13.2.86 and pinned on 2026-10-15 +(commit `53758bb69`); since the 2026-11-03 re-sync (below) four of them are older than their `.cu` and refuse to open until +the server rebuilds them. ## What exists @@ -32,7 +34,8 @@ Rust driver: `cuda-driver/src/experimental.rs` (modes, opt-in, pins, entry signa ## Open items (honest) -1. None of the six `.cu` files has been compiled or run. Root: build PTX, freeze `experimental::PINS`, run +1. None of the six programs has run on a GPU (compiled with nvcc 13.2.86 on 2026-10-15; four need a reseal after the + re-sync, see below). Root: reseal, then run `cargo test -p leleka-cuda-driver --features cuda-driver -- --ignored experimental_gpu`. 2. nvcc FMA contraction decides Q4_0 bytes (Separate vs Fused models are both fixtures); the Q4 smoke reports which model the device matches. `cvec` uses the fast `__expf` exactly as the Original: its pending-write path is not a @@ -47,3 +50,96 @@ Rust driver: `cuda-driver/src/experimental.rs` (modes, opt-in, pins, entry signa expert kernels need two devices. Selection, admission, grouping, metadata and scatter are tested; `experimental_routed` / `experimental_experts` prefill patches are not ported. 6. Host write-through (`host_*`/`stage_*` mapped pointers of the append kernels) is passed as null. + +## Re-sync to Strata pin `41cf05a0` (2026-11-03) + +The ports were made against the first import (`d9ab8435`, engine 0.1.35). The 2026-10-25 upstream sync (`docs/upstream.md`, pin +`41cf05a0`, engine 0.1.50) moved the Original kernels and the ports were not re-synced, so four of the six `literal_port` +tests failed on `main` (1, 5, 20 and 197 Original kernel-body lines missing). Branch `claude/experimental-resync` closes that. +It was done on a host without nvcc and without a GPU: the `.cu` text, the guard, the pins and the reseal tooling are done here; the PTX of four +programs has to be rebuilt on the server (list below). Nothing on the shipped 5090 serve path was touched: the six programs are +experimental, opt-in and off by default, and `engine/strata` is unmodified. + +### What drifted, and what was done + +| Program | Original change since the first import (device code) | Guard found missing | Decision | +| --- | --- | --- | --- | +| `kv_stream` | `resolve_kernel`: `if (lookups > 0) atomicAdd(&s_lookups, lookups)` (upstream #783), same counter value | 1 line | Re-ported literally | +| `kv_q4` | `kv_append_q4_kernel` gained `step_stride` and `planes` (multi-token append: `blockIdx.z = step_idx * planes + plane`) | 5 lines | Re-ported literally; the entry keeps its ABI and passes `step_stride = 0`, `planes = 2`, which is the Original's single-step launch | +| `kv_q8` | `kv_append_q8_kernel` with `step_stride` / `cur_stride` (S26 multi-token append, 4 lines); `kv_gather_q8_wide_kernel` and `q8_pair_to_f16x2` (16 lines, only under `STRATA_EXPERIMENTAL_SM60`) | 20 lines | Template re-ported literally and instantiated single-token (`MULTI = false`); the SM60-only gather is excluded in the guard (sm_60/sm_70 build, compiled out of the Original's own ready-made engine, not part of an sm_120 or sm_86 program) | +| `qsa_attn` | The chunk kernel became `attn_chunk_body` with `reduce12_gfx906` / `reduce12_head_of_lane`; new alternate schedules and batch variants of the same arithmetic: `attn_chunk_kernel_pre75` (+ `shfl_x`, `warp_sum_x`, `warp_max_x`, `reduce12`, `head_of_lane`, `load_v1`), `attn_merge_v2_kernel` (+ `merge_max_block`, `merge_sum_block`), `attn_chunk_q8_v3_kernel`, the slot and row kernels | 197 lines | `attn_chunk_body` and its two helpers re-ported literally (66 lines), instantiated with the three flags off, which is the previous kernel's arithmetic; the 14 alternates are excluded in the guard, each with its reason | +| `keyless`, `cvec` | none (`cvec.cu` gained a host accessor, `cvec_tables`, not device code) | 0 | unchanged | + +The 16 SM60 lines and the 131 lines of alternate schedules are named in `tests/literal_port.rs` (`KV_Q8_EXCLUDED`, `QSA_ATTN_EXCLUDED`) with the +reason. The lists are checked both ways: an entry that no longer exists in the Original fails, and so does a new, unlisted device function of the +Original. The Original itself checks the alternates bitwise against the reference schedule the port carries (`qsa_merge_daily_parity.cpp` for +`pre75` and `merge_v2`, `kv_steps_parity.cpp` for the multi-token appends); that is a statement about the Original, not something re-measured here. +The guard is now 8 tests: the six pairs, a self-test that a changed, removed or unlisted function and a stale exclusion are all caught, and one for +the function-name parser. + +### Verification (no GPU, no nvcc) + +* `cargo test -p leleka-experimental-ref` passes (`literal_port` 8 of 8, with the other golden and emulation tests), and Clippy `-D warnings` on the crate is clean. + `check-local.sh --fast` no longer carries `literal_port` as debt. Results per platform: see "Test results" below. +* The `.cu` text is executed, not only compared: the thread-emulation harness (`oracle/run_emulated_kernels.sh`, g++ 13 and glibc in WSL + Ubuntu) was run on the previous and on the re-synced sources. Every fixture value of `fwht`, `q4`, `q8` (INT8 K+V, streamed host copy, V-only, K8V4), + `route`, `cvec` and the four attention scenarios (`m2`, `m3`, `m4`, `m4_mrope`) is bitwise identical between the two, as the entry-level reasoning above predicts + (every new parameter is neutral at the entries). The streaming scenario's miss order and slot hashes differ from run to run, also between two runs of the same + source (device-side atomics, item 3 of the open list); `kv_stream_resolver_copy_and_ring_match_the_model` checks invariants and passes on a fixture produced from the + re-synced source. The committed `emulated_kernels.json` (made with another libm) is left as it was and still passes against the Rust references. +* Golden fixtures regenerated from the unmodified Original at `41cf05a0`: `kv_golden_separate.json`, `stream_plan_golden.json` and `cvec_golden.json` are byte-identical to the + committed ones (the host code they extract did not change in a way their inputs can see). `kv_golden_fused.json` regenerates differently only because g++ contracts + `x * id + 8.5f` differently from the clang that made the committed file; under g++ it is identical for the old and the new Original, so the committed file is kept. + `remote_golden.json`: see open item 8. +* `cargo test -p leleka-cuda-driver --features cuda-driver experimental` passes, including `every_entry_signature_matches_its_cuda_source` (parameter kinds and + `__launch_bounds__` of all 17 entries against the `.cu` text) and the two new pin tests below. + +### Test results (2026-11-03, laptop, no GPU) + +| Check | Windows | WSL Ubuntu 24.04 (g++ 13, glibc) | +| --- | --- | --- | +| `cargo test -p leleka-experimental-ref` | 63 unit + 25 integration pass (`literal_port` 8 of 8) | the same | +| `cargo clippy -p leleka-experimental-ref --all-targets --no-deps -- -D warnings` | clean | clean | +| `cargo test -p leleka-cuda-driver --features cuda-driver` | 431 passed, 0 failed, 74 ignored | 433 passed, 0 failed, 77 ignored (inside `check-local.sh --product`) | +| `cargo check --all-targets -p leleka-cuda-driver --features cuda-driver -p leleka-runtime` (compiles the Linux-gated `experimental_gpu`) | not applicable | pass | +| `scripts/check-local.sh --fast` | exit 0, only the two known-debt warnings (rustfmt of `leleka-model-format` / `leleka-experimental-ref`, Clippy of `leleka-model-format`) | not run | +| `scripts/check-local.sh --product` | not run (`cargo build --locked` of all default-members: pass) | in a private namespace: every step that touches these crates passes (fmt and Clippy hard gates, `leleka-runtime` 624 tests, cuda-driver 433); the two host-dependent deploy tests stay debt; two steps FAIL-ENV, the all-members `cargo build` and the CPU / iGPU / NPU crate tests, because the namespace has no network and `wgpu-hal` was not in the cargo registry cache | +| thread emulation of the `.cu` text (previous vs re-synced source) | not run (needs g++ and std::barrier) | bitwise identical, see above | + +### Pins: the sealed PTX is older than four of the sources + +The sealed PTX and `PINS[..].ptx_sha256` were left untouched. `PINS[..].source_sha256` is the digest of the `.cu` the PTX was built from; for `kv_q4`, +`kv_q8`, `kv_stream` and `qsa_attn` it now names the previous source. A stale PTX must not load, so `experimental::admit` has a third gate, `source_is_sealed` +(digest of the checked-in `.cu` equals the pin), and `PENDING_RESEAL` lists the four programs: they refuse to open with the typed `Unpinned` error (the +runtime reports "experimental PTX is not pinned") until they are resealed. The unit test `pending_reseal_lists_exactly_the_unsealed_sources` makes the list +exact in both directions, so a reseal that forgets to empty it, or a `.cu` edit without a reseal, turns the build red. No path to these programs exists +today anyway (`FORWARD_CONSUMER_WIRED` is false), so the gate costs nothing now. `docs/cuda-seal-plan-additions-experimental.json` carries the new `cu_pin` of +the four sources, so `compile_assets.py` builds exactly this text. `scripts/gpu-bringup/reseal_own.py` gained `--plan` (and refreshes the plan's `seal_sha256` / +`seal_length` when the entry has them) so that it can reseal these assets; its dry run was exercised here against the committed PTX (the four `source_sha256` +fields are patched, the PTX digests stay). + +### To do on the server (nvcc 13.2.86, scripts/gpu-bringup) + +PTX to reseal: `experimental_kv_q4` (`PINS[0]`), `experimental_kv_q8` (`PINS[1]`), `experimental_kv_stream` (`PINS[2]`), `experimental_qsa_attn` (`PINS[4]`). +`experimental_keyless` (`PINS[3]`) and `experimental_cvec` (`PINS[5]`) are unchanged and stay sealed. Group name `experimental`; the recipe is +`-ptx -O3 -arch=sm_120 -std=c++17`, precise math, from the plan. + +1. `scripts/gpu-bringup/compile_assets.py --toolkit --no-rope --group experimental --only experimental_kv_q4,experimental_kv_q8,experimental_kv_stream,experimental_qsa_attn --out DIR` + (it verifies the `cu_pin`, every `.entry` name and the parameter counts; the entries and their ABI did not change). +2. `scripts/gpu-bringup/reseal_own.py --ptx-dir DIR --plan docs/cuda-seal-plan-additions-experimental.json experimental_kv_q4 experimental_kv_q8 experimental_kv_stream experimental_qsa_attn` + (dry run), then again with `--write`: new PTX files, `PINS[0,1,2,4]` in `experimental.rs`, `seal_sha256` / `seal_length` in the plan. +3. Set `PENDING_RESEAL` in `crates/cuda-driver/src/experimental.rs` to `&[]`. +4. Rebuild the sm_86 companions and the generated table (`scripts/gpu-bringup/sm86_assets.py build`, `docs/sm86-assets.md`): `ptx-sm86/experimental_{kv_q4,kv_q8,kv_stream,qsa_attn}.ptx`, + `ptx-sm86/MANIFEST.json`, `sm86_table.rs` (the table is keyed by the digest of the sealed sm_120 body, so the four old companions stop matching after step 2). +5. `cargo test -p leleka-cuda-driver --features cuda-driver experimental`, then on a GPU `-- --ignored experimental_gpu` (smoke group `new-pins`). No numerical claim + exists for the new PTX until those run; the emulation above is of the `.cu` text. + +### Open items added by the re-sync + +7. The Original's multi-token appends (`kv_append_q4_steps`, `kv_append_q8_steps`, used by the verify and S26 paths) are in the ported kernel text but have no entry, no Rust + facade and no launch test: the entries instantiate the single-token launch. Adding them means new entries in the sealed ABI, so it belongs with the next reseal and a consumer. +8. Host-side drift that `literal_port` cannot see (no `.cu`): `remote_experts.cpp` changed (the helper may be any visible ordinal except the primary `STRATA_PRIMARY_DEVICE`, + `auto_size` slot admission against free memory, a `RemoteMeta` extension for the reduce path, Hadamard-folded experts). The Rust `remote_experts` reference and the generator + `oracle/gen_remote_golden.sh` still describe the old selection (the generator's `awk` fragments no longer compile against the new file), so `remote_golden.json` is the old + behaviour. K8V4 streaming (`--kv k8v4 --kv-resident`: `kKvHybrid` in the host code of `kv_stream.cu` and `layer.cpp`) exists in the Original and is still `NotStreamable` in + `layout.rs` / `kv_stream.rs`. Neither is reachable (no consumer); both need a Rust reference change and new goldens, which is outside the kernel re-sync. diff --git a/docs/windows.md b/docs/windows.md index 27477831..0eea581a 100644 --- a/docs/windows.md +++ b/docs/windows.md @@ -19,7 +19,7 @@ No performance claim is made anywhere in this document; nothing here has a quali | --- | --- | --- | | A. WSL2 bridge, real | **Works with the model** (2026-10-25): `up` to ready, one request, `status`, `reconfigure --prefix-cache-tail prompt`, a second request, `down` | section "Measured on this laptop" | | B. native engine, real | **Works with the model** (2026-10-25): staged volume, pins verified, `up --native --foreground` to ready (engine load 80-128 s), requests answered, `status`, `reconfigure`, `down`. Needed two fixes (MTP ranged reads, child shutdown), both committed | section "Measured on this laptop" | -| Whole tree builds and tests natively | `leleka-deploy` 116 unit + 2 Windows end-to-end + 5 recipe tests, control-plane, `leleka-runtime`, `strata-desktop-core`, `leleka-memory`, `leleka-model-format` and the rest of the workspace pass. Failures, also on Linux: `experimental-ref` `literal_port` (4 tests; kernel sources moved with the upstream sync), `arch_ptx` (`chain_window.ptx` has no sm_86 record) | `cargo test --workspace` on Windows; Linux `cargo check --release --workspace --tests` and `cargo test -p leleka-deploy --features test-fakes` in WSL | +| Whole tree builds and tests natively | `leleka-deploy` 116 unit + 2 Windows end-to-end + 5 recipe tests, control-plane, `leleka-runtime`, `strata-desktop-core`, `leleka-memory`, `leleka-model-format` and the rest of the workspace pass. Failures, also on Linux: `arch_ptx` (`chain_window.ptx` has no sm_86 record). `experimental-ref` `literal_port` (4 tests, kernel sources moved with the upstream sync) passes again since the 2026-11-03 re-sync | `cargo test --workspace` on Windows; Linux `cargo check --release --workspace --tests` and `cargo test -p leleka-deploy --features test-fakes` in WSL | | native supervisor, test doubles | start, readiness, `status`, `reconfigure` (HTTP and engine restart), Ctrl-Break drain, stop-file shutdown | `crates/deploy/tests/e2e_windows.rs` | | `leleka service` (Task Scheduler / user unit) | Task XML generated, unit-tested and **reviewed from `service install --dry-run`** on this machine; **never registered** (not authorized) | `service.rs` tests | | `stage-model.ps1`, `fetch-cublas.ps1` | **Both run for real**: the cuBLAS download (524 MiB, 18 s) matched the SHA-256 pin; the staging copied 138 GB in 614 s; the refusal path of `fetch-cublas.ps1` was also verified with wrong archives | measured section | diff --git a/scripts/check-local.sh b/scripts/check-local.sh index 5296abdf..b063eda5 100755 --- a/scripts/check-local.sh +++ b/scripts/check-local.sh @@ -57,10 +57,9 @@ fast_path() { debt cargo fmt -p leleka-model-format -p leleka-experimental-ref --check cargo clippy --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-experimental-ref --all-targets --no-deps -- -D warnings debt cargo clippy --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-model-format --all-targets --no-deps -- -D warnings - # literal_port is the drift guard between engine/strata/src/kernels/cuda and the checked-in experimental ports; it has failed since - # the 2026-10-25 upstream sync moved the kernels (docs/windows.md, docs/ci-audit.md): reported as debt until the ports are re-synced. - cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-experimental-ref -p leleka-model-format -- --skip _bodies_are_literal - debt cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-experimental-ref --test literal_port + # leleka-experimental-ref includes tests/literal_port.rs, the drift guard between engine/strata/src/kernels/cuda and the checked-in + # experimental ports (re-synced to the upstream 41cf05a0 kernels on 2026-11-03, docs/experiments/2026-10-14-experimental-modes-port.md). + cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-experimental-ref -p leleka-model-format } linux_typecheck() { diff --git a/scripts/gpu-bringup/reseal_own.py b/scripts/gpu-bringup/reseal_own.py index 5ea4b675..09d38158 100644 --- a/scripts/gpu-bringup/reseal_own.py +++ b/scripts/gpu-bringup/reseal_own.py @@ -10,10 +10,15 @@ the plan names (`rust_fields_to_fill`) with the SHA-256 of the .cu bytes and of reseal_own.py --ptx-dir DIR ASSET_ID [ASSET_ID ...] # dry run: prints what would change reseal_own.py --ptx-dir DIR --write ASSET_ID [ASSET_ID ...] +`--plan docs/cuda-seal-plan-additions-experimental.json` names another plan file (default: extra-seal-plan.json). The six +experimental programs (`experimental_{kv_q4,kv_q8,kv_stream,keyless,qsa_attn,cvec}`, group `experimental`) live there; when the +plan entry has `seal_sha256` / `seal_length` slots they are refreshed too (text-level, formatting untouched). + The sm_86 companions and the generated table are rebuilt afterwards with `scripts/gpu-bringup/sm86_assets.py build` (docs/sm86-assets.md). """ import argparse import json +import re import sys from pathlib import Path @@ -26,10 +31,12 @@ def main(): ap = argparse.ArgumentParser() ap.add_argument("--ptx-dir", required=True, type=Path) ap.add_argument("--write", action="store_true") + ap.add_argument("--plan", default="scripts/gpu-bringup/extra-seal-plan.json", help="repo-relative seal plan holding the assets (default: extra-seal-plan.json)") ap.add_argument("ids", nargs="+") args = ap.parse_args() root = L.REPO - plan = json.loads((root / "scripts/gpu-bringup/extra-seal-plan.json").read_text()) + plan_path = root / args.plan + plan = json.loads(plan_path.read_text(encoding="utf-8")) by_id = {Path(a["cu"]).stem: a for a in plan["assets"]} manifest = json.loads((args.ptx_dir / "build-manifest.json").read_text()) for asset_id in args.ids: @@ -44,13 +51,29 @@ def main(): v = R.PinValues(len(raw), L.sha256_digest(raw), L.sha256_digest(cu)) for consumer, specs in a["rust_fields_to_fill"].items(): path = next(root.glob(f"crates/*/src/{consumer}")) - text = path.read_text(encoding="utf-8", newline="") + with open(path, encoding="utf-8", newline="") as fh: # (Path.read_text has no newline= before Python 3.13) + text = fh.read() new = text for spec in specs: new = R.apply_field(new, spec, v) print(f"{asset_id}: {path.relative_to(root)} {'patched' if new != text else 'unchanged'} (ptx {len(raw)} B sha {v.ptx_sha256.hex()[:16]}, cu sha {v.source_sha256.hex()[:16]})") if args.write: - path.write_text(new, encoding="utf-8", newline="") + with open(path, "w", encoding="utf-8", newline="") as fh: + fh.write(new) + if "seal_sha256" in a and "seal_length" in a: + with open(plan_path, encoding="utf-8", newline="") as fh: + text = fh.read() + pat = re.compile(r'("ptx"\s*:\s*"' + re.escape(a["ptx"]) + r'"(?:(?!"cu"\s*:).)*?"seal_sha256"\s*:\s*)(null|"[0-9a-f]{64}")' + r'(\s*,\s*"seal_length"\s*:\s*)(null|\d+)', re.S) + ms = list(pat.finditer(text)) + if len(ms) != 1: + sys.exit(f"{args.plan}: expected one seal_sha256/seal_length slot for {a['ptx']}, found {len(ms)}") + m = ms[0] + patched = text[: m.start(2)] + f'"{L.sha256_hex(raw)}"' + m.group(3) + str(len(raw)) + text[m.end(4):] + print(f"{asset_id}: {args.plan} seal_sha256/seal_length {'patched' if patched != text else 'unchanged'}") + if args.write: + with open(plan_path, "w", encoding="utf-8", newline="") as fh: + fh.write(patched) if args.write: (root / a["ptx"]).write_bytes(raw) print(f"{asset_id}: wrote {a['ptx']}")