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++
Merge the Aurora gfx1151 branch (f-halo-int + HCD_EXACT + the expert bundle) onto 0.1.39
Niko1221bc6b6f87a969
diff --cc cmake/hip_backend.cmakeindex d59bba9a8,7fb62ecd7..676ce31b5--- a/cmake/hip_backend.cmake+++ b/cmake/hip_backend.cmake@@@ -8,10 -8,11 +8,11 @@@ endif(# maintainers; gfx1101 (RX 7800 XT, #254) and gfx1200 (RX 9060 XT, #256) by their owners. gfx1102 (RX 7600) has the# same LDS limit and dot4 instruction and passed ctest (#192), but no model run has been reported yet. RDNA2 gfx1030 (RX 6800 / 6900) has the# same LDS limit and wave32 but an older dot4 instruction (v_dot4_i32_i8, hip_compat/intrinsics.hpp); a community- # report ran it (#311), the maintainers have not.+ # report ran it (#311), the maintainers have not. gfx1151 (Ryzen AI Max / Strix Halo, Radeon 8060S, RDNA3.5) is the+ # same wave32 / 64 KiB LDS / sudot4 family as gfx1100, on a unified-memory APU; experimental.set(_strata_hip_validated gfx1100 gfx1201)set(_strata_hip_community gfx1101 gfx1200)- set(_strata_hip_unvalidated gfx1012 gfx1102 gfx1030 gfx1031)-set(_strata_hip_unvalidated gfx1102 gfx1030 gfx1151)++set(_strata_hip_unvalidated gfx1012 gfx1102 gfx1030 gfx1031 gfx1151)# CMake hands HIP a ';' list, but a -DCMAKE_HIP_ARCHITECTURES typed by hand (or ROCm's own Windows tooling) may use# spaces, which foreach(IN LISTS) would otherwise treat as one element.string(REPLACE " " ";" _strata_hip_norm "${CMAKE_HIP_ARCHITECTURES}")@@@ -74,10 -68,11 +75,15 @@@ add_library(strata_hip_runtime INTERFACtarget_include_directories(strata_hip_runtime BEFORE INTERFACE"${STRATA_HIP_COMPAT_INCLUDE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include")target_compile_definitions(strata_hip_runtime INTERFACE STRATA_USE_HIP=1 "STRATA_HIP_ARCHS=\"${STRATA_HIP_ARCHS}\"")+option(STRATA_GFX1012_PORTABLE_DOT "Use the portable signed-byte dot control on gfx1012" OFF)+if(STRATA_GFX1012_PORTABLE_DOT)+ target_compile_definitions(strata_hip_runtime INTERFACE STRATA_GFX1012_PORTABLE_DOT=1)+endif()+ # #313: the RDNA3 WMMA GEMM's intrinsics only compile for gfx11 targets and the host pass does not define+ # __gfx11xx__, so the build supplies the macro for gfx11 configs (the kernels also gate on the device at runtime)+ if(CMAKE_HIP_ARCHITECTURES MATCHES "gfx11")+ target_compile_definitions(strata_hip_runtime INTERFACE STRATA_WMMA_GFX11=1)+ endif()target_link_libraries(strata_hip_runtime INTERFACE hip::host)# The shim renames the CUDA runtime to HIP, force-included into every host and device source. On Windows the host# compiler is ROCm's clang++ too (tools/hip/build_windows.bat: CMake refuses to mix cl.exe with Clang HIP), which takesdiff --cc include/strata/core/verify.hppindex e68f7b3a4,011c8f594..3fbfe6a17--- a/include/strata/core/verify.hpp+++ b/include/strata/core/verify.hpp@@@ -255,9 -173,10 +255,11 @@@ privatebool head_sampling_ = true; ///< set_head_samplingint device_ = -1; ///< the device `init` ran on: run/commit switch to it (layer split)std::atomic<bool> released_{false}; ///< #267: release_gpu_waits ran (maybe on the watchdog thread): no more windows+ bool all_resident_ = false; ///< 100% of experts in [lb_, le_) resident in VRAM: zero-doorbell graphbool device_plan_ = false; ///< E-6: resident-only layers planned on the device (STRATA_VERIFY_DEVICE_PLAN)+ bool resident_ = false; ///< STRATA_VERIFY_RESIDENT: every expert resident, no host step per layeruint32_t* skip_ = nullptr; ///< E-6: per group, the ring whose plan the device built (0: the host's)+ unsigned* qcnt_ = nullptr; ///< S26 STRATA_QFUSE: the HC read's q8_1 group counters (n_embd / 32)unsigned long long* slot_off_d_ = nullptr; ///< E-6: the slot offsets on the deviceint64_t lb_ = 0, le_ = -1; ///< set_stage: the layers this verifier runs (-1: to the last)const float* hand_in_ = nullptr;diff --cc include/strata/hip_compat/cuda_runtime.hindex 8ea907a94,f6d551960..f9d7e5480--- a/include/strata/hip_compat/cuda_runtime.h+++ b/include/strata/hip_compat/cuda_runtime.h@@@ -20,9 -19,8 +20,10 @@@#define cudaDevAttrClockRate hipDeviceAttributeClockRate#define cudaDevAttrComputeCapabilityMajor hipDeviceAttributeComputeCapabilityMajor#define cudaDevAttrComputeCapabilityMinor hipDeviceAttributeComputeCapabilityMinor+ #define cudaDevAttrIntegrated hipDeviceAttributeIntegrated#define cudaDeviceGetAttribute hipDeviceGetAttribute+#define cudaDeviceCanAccessPeer hipDeviceCanAccessPeer+#define cudaDeviceEnablePeerAccess hipDeviceEnablePeerAccess#define cudaDeviceProp hipDeviceProp_t#define cudaDeviceSynchronize hipDeviceSynchronize#define cudaDriverGetVersion hipDriverGetVersiondiff --cc include/strata/kernels/fused_gr.hppindex b5f95fcb9,d56f21b33..982b33bdb--- a/include/strata/kernels/fused_gr.hpp+++ b/include/strata/kernels/fused_gr.hpp@@@ -46,11 -55,10 +55,12 @@@ void fused_gr_read(const FusedGrArgs& a/// weight pointers and eps must be the same for every t); `xn_scratch` is n_tok * hc * n_embd floats. Every/// token's outputs are bitwise `fused_gr_read(a[t])`.constexpr int kFusedGrMaxT = 8;- void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream,+ /// Returns true when it also wrote the q8_1 images (every token's q8_mixed set and this read supports it).+ bool fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream,unsigned long long* stamp_buf = nullptr, int stamp_i0 = 0);+/// The bench only: the AMD latency-hidden kernels on (1) or off (0); -1 = STRATA_GR_FAST.+void fused_gr_set_fast(int on);/// The multi read's variants (#315; not main's opt-in STRATA_GR_V3 read, which sums in another order), all computing/// every output with the plain read's operations in its order, so bitwise the plain read's and the single-token/// read's: plain (0.1.31's default: the norm one block per token, the down projection on 41 blocks), split (the normdiff --cc include/strata/prefill/gemm.hppindex 60d1c7174,7a17ec103..ab148380b--- a/include/strata/prefill/gemm.hpp+++ b/include/strata/prefill/gemm.hpp@@@ -26,10 -26,13 +26,15 @@@ publicstd::string& err);/// Y[T, N] (fp32, row stride ldy) = X[T, K] (bf16, row-major) . W[N, K]^T (bf16, row-major). `beta` = 1 adds.+ /// Below sm_80 (no BF16 tensor cores): Volta converts both to FP16 and runs the FP16 tensor-core GEMM (Turing with+ /// STRATA_BF16_TC=1), Pascal widens both to fp32 (cublasSgemm); see gemm.cu.void bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy = 0,- float beta = 0.0f);+ float beta = 0.0f, int64_t ldx = 0);++ /// S (STRATA_HCD_EXACT): the HC down projection (N 320, K 10240) by the WMMA kernel that reproduces hipBLASLt's+ /// solution 1176 / 1177 bit for bit; false (nothing launched) unless hipBLASLt would take one of those for this+ /// shape (so the caller falls back to bf16(), with the same ldx).+ bool bf16_hcd_exact(const uint16_t* X, int64_t ldx, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K);/// Y = X . W^T with both in FP16 (bits).void f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy = 0,diff --cc include/strata/prefill/kernels.hppindex 3358bea65,da22f98b4..18f51be15--- a/include/strata/prefill/kernels.hpp+++ b/include/strata/prefill/kernels.hpp@@@ -43,10 -54,17 +54,17 @@@ void gdn_gates(const float* ab, const f/// The 4-tap causal conv + SiLU over the chunk (history [C][3] in, updated to the chunk's last three inputs), then/// the L2 norm of the q and k heads of every token. h: [T, C].void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, int64_t T, float eps, void* stream);-/// The recurrence over the chunk, block per value head, state in registers; y[t] = rmsnorm(o) * gamma * sigmoid(z)-/// (FP32 and FP16 bits: the out projection is quantized).+/// The recurrence over the chunk, state in registers; y16[t] = rmsnorm(o) * gamma * sigmoid(z) in FP16 (what the+/// out projection reads); y is FP32 scratch.void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z,- const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream);+ const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream,+ int64_t ld16 = 0); // ld16: y16's row stride (0 = 6144; S23 STRATA_PF_PAD pads it)+ /// The kernels behind gdn_recurrence, for the parity test: 0 = the column-split kernels + the norm kernel (or the+ /// one-block-per-head kernel under STRATA_GDN_REC_HEADS), 1 = four lanes per column (no barrier per token) + the grid-stride norm, 2 = the+ /// one-block-per-head kernel (its fused norm rounds differently). 0 and 1 give the same bits.+ void gdn_recurrence_variant(int variant, float* state, const float* h, const float* gate, const float* beta,+ const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T,+ void* stream, int64_t ld16 = 0);// ---- MoE/// softmax over 512, top-10 (ties to the lower id), weights renormalised over the ten (the native router).diff --cc src/core/mtp.cppindex e9953e300,be954b3bb..130dc275e--- a/src/core/mtp.cpp+++ b/src/core/mtp.cpp@@@ -38,12 -35,11 +38,16 @@@#include <fstream>#include <sstream>#include <vector>+#if defined(_WIN32)+#include <intrin.h>+#elif defined(__x86_64__)+#include <immintrin.h>+#endif+ #ifdef STRATA_NATIVE_EXPERTS+ #include "ggml.h" // --mtp-q4: the head rows' and projections' formats, dequantized and requantized at load+ #endif+namespace strata::core {namespace {@@@ -582,18 -700,13 +709,18 @@@ bool MtpDrafter::record_forward(int T,moe_grouped_s2(grp_ptr_, grp_start_, grp_counts_, hit_dst_, hit_slot_, (int64_t) T * K, (int64_t) T * K, hit_xq_,hit_xs_, hit_scratch_, parts_, cs);NativeSharedWeights nsw;- nsw.gate_type = GGML_Q8_0; nsw.gate_data = q8("mlp.shared_expert.gate_proj.weight");- nsw.up_type = GGML_Q8_0; nsw.up_data = q8("mlp.shared_expert.up_proj.weight");- nsw.down_type = GGML_Q8_0; nsw.down_data = q8("mlp.shared_expert.down_proj.weight");+ nsw.gate_data = wq("mlp.shared_expert.gate_proj.weight", nsw.gate_type);+ nsw.up_data = wq("mlp.shared_expert.up_proj.weight", nsw.up_type);+ nsw.down_data = wq("mlp.shared_expert.down_proj.weight", nsw.down_type);nsw.q8_1 = xq_;const SForm none{};+ const bool need_bf16_x = !shared_expert_native_bf16_enabled();+ static const bool fuse_head_gr = [] {+ const char* v = std::getenv("STRATA_FUSE_HEAD_GR");+ return v != nullptr && std::atoi(v) != 0;+ }();for (int t = 0; t < T; ++t) {- f32_to_bf16_bulk(mixed_ + t * N, x_bf16_, N, cs);+ if (need_bf16_x) f32_to_bf16_bulk(mixed_ + t * N, x_bf16_, N, cs);shared_expert(nullptr, nullptr, x_bf16_, none, nullptr, nullptr, nullptr, none, nullptr, nullptr, nullptr, none,nullptr, nullptr, nullptr, bf16("mlp.shared_expert_gate.weight"), sh_scratch_, shared_ + t * N,N, g.n_ff, 32, cs, mixed_ + t * N, &nsw);diff --cc src/core/native_dense.cppindex e0609fdc5,348c813d3..b5c33a8bb--- a/src/core/native_dense.cpp+++ b/src/core/native_dense.cpp@@@ -15,12 -18,55 +19,61 @@@namespace strata::core {namespace {+int g_layer_lb = -1, g_layer_le = -1; // set_layer_range; -1: every layer+bool in_range(const std::string& name) {+ if (g_layer_lb < 0 || name.rfind("blk.", 0) != 0) return true;+ const int l = std::atoi(name.c_str() + 4);+ return l >= g_layer_lb && l < g_layer_le;+}+ // S23 experiment (STRATA_HC_Q8=1): the hyper-connection projections' Q8_0 bytes for the verify read+ bool hc_q8_requested() {+ static const bool on = [] { const char* v = std::getenv("STRATA_HC_Q8"); return v != nullptr && v[0] == '1'; }();+ return on;+ }+ bool hc_q8_name(const std::string& name) {+ if (name == "output_hc_down.weight" || name == "output_hc_up.weight") return true; // S25: the final mixer too+ if (name.rfind("blk.", 0) != 0) return false;+ static const char* suffixes[] = {".hc_attn_down.weight", ".hc_attn_up.weight", ".hc_attn_inject.weight",+ ".hc_ffn_down.weight", ".hc_ffn_up.weight", ".hc_ffn_inject.weight"};+ for (const char* suffix : suffixes) if (name.ends_with(suffix)) return true;+ return false;+ }+ // S25: the GGUF keeps the inject rows as F32 - quantized here to Q8_0 (ggml's reference rounding) so the Q8_0 read+ // covers every hc projection+ uint16_t half_bits(float f) {+ uint32_t x;+ std::memcpy(&x, &f, 4);+ const uint32_t sign = (x >> 16) & 0x8000u;+ int32_t e = (int32_t) ((x >> 23) & 0xff) - 127 + 15;+ uint32_t m = x & 0x7fffffu;+ if (e <= 0) { // subnormal or zero+ if (e < -10) return (uint16_t) sign;+ m |= 0x800000u;+ const uint32_t shift = (uint32_t) (14 - e);+ uint32_t h = m >> shift;+ const uint32_t rem = m & ((1u << shift) - 1), half = 1u << (shift - 1);+ if (rem > half || (rem == half && (h & 1u))) ++h;+ return (uint16_t) (sign | h);+ }+ if (e >= 31) return (uint16_t) (sign | 0x7c00u);+ uint32_t h = ((uint32_t) e << 10) | (m >> 13);+ const uint32_t rem = m & 0x1fffu;+ if (rem > 0x1000u || (rem == 0x1000u && (h & 1u))) ++h;+ return (uint16_t) (sign | h);+ }+ std::vector<uint8_t> q8_0_of(const float* x, uint64_t n) {+ std::vector<uint8_t> out((size_t) (n / 32 * 34));+ for (uint64_t b = 0; b < n / 32; ++b) {+ float amax = 0.0f;+ for (int j = 0; j < 32; ++j) amax = (std::max)(amax, std::fabs(x[b * 32 + j]));+ const float d = amax / 127.0f, id = d != 0.0f ? 1.0f / d : 0.0f;+ uint8_t* o = out.data() + b * 34;+ const uint16_t hb = half_bits(d);+ std::memcpy(o, &hb, 2);+ for (int j = 0; j < 32; ++j) o[2 + j] = (uint8_t) (int8_t) std::lround(x[b * 32 + j] * id);+ }+ return out;+ }bool eligible(const strata::TensorInfo& tensor, bool include_ple_key) {const auto& name = tensor.name;if (name.rfind("blk.", 0) != 0) return false;diff --cc src/core/verify.cppindex dd5362bac,0ee3d184d..d7f47e919--- a/src/core/verify.cpp+++ b/src/core/verify.cpp@@@ -279,18 -181,10 +285,19 @@@ Verifier::~Verifier()for (auto& e : exec_)if (e) cudaGraphExecDestroy(e);if (commit_exec_) cudaGraphExecDestroy(commit_exec_);+ for (auto& kv : exec_bm_)+ if (kv.second) cudaGraphExecDestroy(kv.second);+ for (auto& kv : commit_bm_)+ if (kv.second) cudaGraphExecDestroy(kv.second);+ if (arena_b_) cudaFree(arena_b_);+ if (h_commitb_) cudaFreeHost(h_commitb_);+ if (qcnt_) cudaFree(qcnt_);if (cs_) cudaStreamDestroy(cs_);+ if (sh_cs_) cudaStreamDestroy(sh_cs_);if (copy_) { cudaStreamSynchronize(copy_); cudaStreamDestroy(copy_); }if (commit_done_) cudaEventDestroy(commit_done_);+ if (ev_fork_) cudaEventDestroy(ev_fork_);+ if (ev_join_) cudaEventDestroy(ev_join_);if (arena_) cudaFree(arena_);void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_,h_flagA_, h_plan_, h_flagB_};@@@ -511,22 -364,46 +519,50 @@@ bool Verifier::init(const WeightTable&// exact, but neutral on RIBPC 1-2 GPUs: off by default){const char* v = std::getenv("STRATA_VERIFY_DEVICE_PLAN");- device_plan_ = v != nullptr && std::atoi(v) != 0;+ device_plan_ = !all_resident_ && (v != nullptr && std::atoi(v) != 0);}+ // STRATA_VERIFY_RESIDENT=1 (opt-in): when EVERY routed expert of every layer is resident in the VRAM/UMA tier+ // (checked here, once; a full cache never evicts), the window graph is recorded without the host round trip:+ // no doorbell, no flag waits, no plan copy from mapped memory, no PCIe/CPU share (fetch, rebase, its grouped+ // launch, the mapped-row copy); the device plans each group (the host's exact loop, E-6) and the combine reads+ // the hit rows as `0.0f + hit` (what the zeroed CPU rows + moe_hit_add gave). Same tokens, same arithmetic.+ {+ const char* v = std::getenv("STRATA_VERIFY_RESIDENT");- if (v != nullptr && std::atoi(v) != 0 && lb_ == 0 && le_ == g.n_layers && next_ == nullptr) {++ if (v != nullptr && std::atoi(v) != 0 && lb_ == 0 && le_ == g.n_layers && next_ == nullptr &&++ remote_opt_ == nullptr && hits.d_res != nullptr) {+ std::vector<int32_t> res((size_t) (g.n_layers * g.n_expert));+ bool all = cudaMemcpy(res.data(), hits.d_res, res.size() * sizeof(int32_t), cudaMemcpyDeviceToHost) ==+ cudaSuccess;+ for (size_t i = 0; all && i < res.size(); ++i) all = res[i] >= 0;- if (all) device_plan_ = true;++ if (all) { device_plan_ = true; all_resident_ = false; } // (this window's own resident path)+ resident_ = all;+ std::fprintf(stderr, "strata verify: STRATA_VERIFY_RESIDENT=1: %s\n",+ all ? "every expert resident, the window runs without the host round trip"+ : "not every expert is resident - the host-planned window stays");+ }+ }+ if (g_qfuse) { // S26: the HC read's q8_1 group counters, zeroed once (each launch leaves them zero)+ if (cudaMalloc((void**) &qcnt_, sizeof(unsigned) * (size_t) (g.n_embd / 32)) != cudaSuccess ||+ cudaMemset(qcnt_, 0, sizeof(unsigned) * (size_t) (g.n_embd / 32)) != cudaSuccess) {+ cudaGetLastError();+ if (qcnt_) cudaFree(qcnt_);+ qcnt_ = nullptr;+ }+ }- if (device_plan_) {- bool ok2 = cudaMalloc((void**) &skip_, 64) == cudaSuccess && cudaMemset(skip_, 0, 64) == cudaSuccess;+ if (all_resident_ || device_plan_) {+ bool ok2 = true;+ if (device_plan_)+ ok2 = cudaMalloc((void**) &skip_, 64) == cudaSuccess && cudaMemset(skip_, 0, 64) == cudaSuccess;if (ok2 && hits.slot_off != nullptr && hits.n_slots > 0) {ok2 = cudaMalloc((void**) &slot_off_d_, (size_t) hits.n_slots * sizeof(unsigned long long)) == cudaSuccess &&cudaMemcpy(slot_off_d_, hits.slot_off, (size_t) hits.n_slots * sizeof(unsigned long long),cudaMemcpyHostToDevice) == cudaSuccess;}- if (!ok2) { cudaGetLastError(); all_resident_ = false; device_plan_ = false; }- if (!ok2) { cudaGetLastError(); device_plan_ = false; resident_ = false; }++ if (!ok2) { cudaGetLastError(); all_resident_ = false; device_plan_ = false; resident_ = false; }}- std::fprintf(stderr, "strata verify: window up to %d tokens, %.1f MiB of device buffers\n", max_t,- (double) count.used / 1048576.0);+ std::fprintf(stderr, "strata verify: window up to %d tokens, %.1f MiB of device buffers%s\n", max_t,+ (double) count.used / 1048576.0,+ all_resident_ ? " (100% VRAM resident: zero-doorbell graph)" : "");return true;}@@@ -558,18 -435,17 +594,24 @@@ bool Verifier::record_window(int T, cudconst int64_t TS = (s.idx_block - 1) * ID;const bool ple_on = ss.ple.ready() && ple_stage();auto Rt = [&](int t) { return R_ + (size_t) t * HC * N; };- const int G = (split_ && T >= 2) ? 2 : 1;+ const int G = (split_ && T >= 2 && !batch_rec_) ? 2 : 1; // a batch window is one groupstatic const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }();- auto stamp = [&](int64_t l, int i, int grp) { if (prof_on_ && grp == 0) gpu_stamp(prof_, (int) (l * kProfPer + i), cs); };+ auto stamp = [&](int64_t l, int i, int grp) {+ if (prof_on_ && grp == 0) gpu_stamp(prof_, (int) (l * kProfPer + i), cs);+ if (trace_m_ != nullptr) gpu_stamp(trace_m_, (int) ((l * kProfPer + i) * 2 + grp), cs); // #649+ };const int tb_[2] = {0, (T + 1) / 2}, te_[2] = {G == 2 ? (T + 1) / 2 : T, T};+ // S26 STRATA_LFUSE=1: where the shared expert's gate / scale fusions apply (the paths they replace are the ones taken)+ auto lfuse_on = [&](int n) {+ return g_lfuse && resident_ && native_moe_combine_enabled() && dec_batch && n > 1 && n <= 8 &&- shared_expert_native_bf16();++ shared_expert_native_bf16_enabled();+ };+ bool sg_gated_[2] = {false, false}; // per group: the combine applies the shared gate- groups_[T] = G;+ if (!batch_rec_) groups_[T] = G;+ const int64_t nQall = g.n_qsa_layers();+ // a batch window: row t is slot t, whose state lives in its own session+ auto slot_ss = [&](int t) -> SessionState& { return batch_rec_ ? *slots_[(size_t) brow_[t]] : ss; };+ const int hrow0 = batch_rec_ ? row_base_ : 0; // a slot group's own hand-off rows// ---- the window's inputs, from mapped stagingcopy_i32_from_mapped(tok_, m_tok_, T, cs);@@@ -634,43 -512,39 +676,66 @@@// already applied it)bool pending = l > 0 && !cvec().covers(l - 1);if (l == 1 && ple_on) {+ if (grp == 0) {+ if (all_resident_) wait_flag_ge(m_flag_, 1, cs);+ copy_from_mapped(ple_, m_ple_, (int64_t) T * N, cs);+ }float* normalized = (float*) ((uint8_t*) ss.ple.scratch + ple_block_scratch_bytes());+ static const bool ple_batch_env = [] {+ const char* e = std::getenv("STRATA_PLE_BATCH");+ return !e || e[0] != '0';+ }();+ const bool ple_batch_kv = ple_batch_env && dec_batch && n > 1 && ss.ple.w.key_bf16 != nullptr &&+ ss.ple.w.value_bf16 != nullptr && ple_native_bf16_enabled() &&+ ple_native_postops_enabled();+ // S25 (STRATA_PLE_BATCH=1): the key and value projections depend only on each row's n-gram embedding, so+ // the group's rows run through the multi-row forms of the same kernels (the weights read once); every+ // row's arithmetic is the single-row call's. The history-dependent rest stays row by row.+ static const bool ple_batch = [] { const char* e = std::getenv("STRATA_PLE_BATCH"); return e && e[0] == '1'; }();+ PleWeights pw = ss.ple.w;+ const bool nkey = pw.key_native_data != nullptr && pw.key_bf16 == nullptr;- const bool batched = ple_batch && n > 1 && (pw.key_bf16 != nullptr || nkey) && ple_native_bf16();- if (batched) {++ const bool batched = !ple_batch_kv && ple_batch && n > 1 && (pw.key_bf16 != nullptr || nkey) && ple_native_bf16_enabled();+ if (ple_batch_kv) {+ try {+ bf16_gemv_fp32_mmvf_multi(ple_ + (size_t) tb * N, N, ss.ple.w.key_bf16,+ xn_ + (size_t) tb * HC * N, HC * N, N, HC * N, n, cs);+ bf16_gemv_fp32_mmvf_multi(ple_ + (size_t) tb * N, N, ss.ple.w.value_bf16,+ z_ + (size_t) tb * N, N, N, N, n, cs);+ } catch (const std::exception& e) {+ err = std::string("verify PLE multi: ") + e.what();+ return false;+ }++ } else if (batched) {+ try {+ if (pw.key_bf16 != nullptr)+ bf16_gemv_fp32_mmvf_multi(ple_ + tb * N, N, pw.key_bf16, ple_key_ + (size_t) tb * NG_HC_DIM,+ NG_HC_DIM, N, NG_HC_DIM, n, cs);+ else {+ native_quantize_q8_1(ple_ + tb * N, xq_, (int) N, n, cs);+ native_mmvq(pw.key_native_type, pw.key_native_data, xq_, ple_key_ + (size_t) tb * NG_HC_DIM,+ (int) N, NG_HC_DIM, n, cs);+ }+ bf16_gemv_fp32_mmvf_multi(ple_ + tb * N, N, pw.value_bf16, ple_val_ + tb * N, N, N, N, n, cs);+ } catch (const std::exception& e) {+ err = std::string("verify PLE batch: ") + e.what();+ return false;+ }}for (int t = tb; t < te; ++t) {+ if (batched) { pw.pre_key = ple_key_ + (size_t) t * NG_HC_DIM; pw.pre_value = ple_val_ + t * N; }gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs);PleOut po;po.normalized = normalized;po.result = Rt(t);+ float* hist = batch_rec_ ? slot_ss(t).ple_hist : ss.ple.hist; // the row's own historytry {- ple_block(ple_ + t * N, Rt(t), ss.ple.hist, pw, po, ss.ple.scratch, cs);- ple_history_advance(ss.ple.hist, normalized, cs);+ if (ple_batch_kv) {+ ple_block_projected(xn_ + (size_t) t * HC * N, z_ + (size_t) t * N, Rt(t), hist,+ ss.ple.w, po, ss.ple.scratch, cs);+ } else {- ple_block(ple_ + t * N, Rt(t), hist, ss.ple.w, po, ss.ple.scratch, cs);++ ple_block(ple_ + t * N, Rt(t), hist, pw, po, ss.ple.scratch, cs);+ }+ ple_history_advance(hist, normalized, cs);} catch (const std::exception& e) {err = std::string("verify PLE: ") + e.what();return false;@@@ -715,18 -596,9 +787,18 @@@float* hb = h_L_ + (size_t) gi * MT * C;float* gate = gate_L_ + (size_t) gi * MT * HV;float* beta = beta_L_ + (size_t) gi * MT * HV;- native_quantize_q8_1(xm, xq_, (int) N, n, cs);+ if (!q8_attn) native_quantize_q8_1(xm, xq_, (int) N, n, cs);native_mmvq(wqkv->native_type, wqkv->native_data, xq_, qkv + (size_t) tb * C, (int) N, (int) C, n, cs);stamp(l, 2, grp);+ if (batch_rec_) { // each row from its own slot's conv history, one row each+ for (int t = tb; t < te; ++t) {+ SessionState& sx = slot_ss(t);+ const float* cx = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats ++ (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;+ gdn_conv_l2_multi(cx, qkv + (size_t) t * C, (const float*) wc->data, hb + (size_t) t * C, (int) C,+ (int) (2 * HK), EPS, 1, cs, 0);+ }+ } elsegdn_conv_l2_multi(conv, qkv, (const float*) wc->data, hb, (int) C, (int) (2 * HK), EPS, n, cs, tb);stamp(l, 3, grp);gdn_ab_multi(xm, (const uint16_t*) wa->data, (const uint16_t*) wb->data, (const float*) wdt->data,@@@ -736,19 -608,10 +808,19 @@@native_mmvq(wg->native_type, wg->native_data, xq_, z_ + (size_t) tb * ZV, (int) N, (int) ZV, n, cs);stamp(l, 5, grp);// the recurrence from the untouched state over tokens [0, te); outputs only for this group's+ if (batch_rec_) { // each row's recurrence from its own slot's state, one token+ for (int t = tb; t < te; ++t) {+ SessionState& sx = slot_ss(t);+ float* stx = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats;+ gdn_step_norm_multi(stx, hb + (size_t) t * C, (int) C, gate + (size_t) t * HV, beta + (size_t) t * HV,+ z_ + (size_t) t * ZV, (const float*) wnm->data, EPS, y_ + (size_t) t * ZV,+ (int) HK, (int) HV, 1, nullptr, cs, 0);+ }+ } elsegdn_step_norm_multi(state, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS, y_, (int) HK,- (int) HV, te, nullptr, cs, tb);+ (int) HV, te, nullptr, cs, tb, g_qfuse ? (void*) xq_ : nullptr);stamp(l, 6, grp);- native_quantize_q8_1(y_ + (size_t) tb * ZV, xq_, (int) ZV, n, cs);+ if (!g_qfuse) native_quantize_q8_1(y_ + (size_t) tb * ZV, xq_, (int) ZV, n, cs); // STRATA_QFUSE: done abovenative_mmvq(wout->native_type, wout->native_data, xq_, bo_ + tb * N, (int) ZV, (int) N, n, cs);} else {// ======================= QSA =======================@@@ -789,14 -652,14 +861,20 @@@fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);}stamp(l, 8, grp);+ if (batch_rec_) { // every slot's indexer tail, restored by its commit+ for (int t = tb; t < te; ++t)+ copy_from_mapped(tail_snap_b_ + ((size_t) brow_[t] * nQall + qi) * TS, slot_ss(t).qsa_states[qi].idx_tail,+ TS, cs);+ } elseif (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);+ elsefor (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;if (st.kv_hybrid) { // K8V4: the unused half's lanes folded onto the used pool (layer.cpp)kv_append_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, step_t,@@@ -899,17 -745,7 +977,17 @@@return false;}stamp(l, 16, grp);- gr_read_group(1, true, inj_, inj2_);- const bool q8_ffn = gr_read_group(1, true, inj_, inj2_); // true: nat_xq_ holds the MoE input's q8_1++ const bool q8_ffn = gr_read_group(1, true, inj_, inj2_); // true: nat_xq_ holds the MoE input's q8_1 (STRATA_QFUSE)+ static const bool sh_stream_env = [] {+ const char* e = std::getenv("STRATA_SH_STREAM");+ return !e || e[0] != '0';+ }();+ const bool sh_fork = sh_stream_env && !prof_on_ && sh_cs_ != nullptr && ev_fork_ != nullptr && ev_join_ != nullptr;+ cudaStream_t sh_stream = sh_fork ? sh_cs_ : cs;+ if (sh_fork) {+ cudaEventRecord(ev_fork_, cs);+ cudaStreamWaitEvent(sh_cs_, ev_fork_, 0);+ }// the window's rows routed in 2 launches (one router GEMV reading the weight once, one// top-10) instead of 2 per token; every row's arithmetic is the single-token call's (STRATA_DEC_BATCH=0: old)const WeightRef* w_router = v.get("ffn_gate_inp.weight");@@@ -934,31 -770,14 +1021,33 @@@mb.logits = logits_ + t * NE; mb.ids = ids_ + t * K; mb.weights = w_ + t * K;if (!moe_route(wt, g, l, K, mb, mixed_ + t * N, cs, err, nullptr)) return false;}- if (device_plan_) // E-6: every routed expert resident: this group's plan without the host+ if (all_resident_) {resident_plan(ids_ + tb * K, n * (int) K, (int) K, hits_.d_res + l * g.n_expert, (int) g.n_expert,hits_.cache_base, slot_off_d_, (long long) hits_.blob,- plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, skip_ + grp,- (uint32_t) ((l - lb_) * G + grp + 1), cs);- if (!resident_) // STRATA_VERIFY_RESIDENT: no host step, so no doorbell- doorbell_publish(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N,- m_ids_ + tb * K, m_w_ + tb * K, m_seq_, cs);+ plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, nullptr, 0, cs);+ } else {+ if (device_plan_) // E-6: every routed expert resident: this group's plan without the host+ resident_plan(ids_ + tb * K, n * (int) K, (int) K, hits_.d_res + l * g.n_expert, (int) g.n_expert,+ hits_.cache_base, slot_off_d_, (long long) hits_.blob,+ plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, skip_ + grp,+ (uint32_t) ((l - lb_) * G + grp + 1), cs);++ if (!resident_) { // STRATA_VERIFY_RESIDENT: no host step, so no doorbell+#if defined(STRATA_USE_HIP)+ if (g_doorbell_store) // #649 A/B: the step's ring stored, not incremented over PCIe+ doorbell_publish_value(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N,+ m_ids_ + tb * K, m_w_ + tb * K, m_seq_, (uint32_t) ((l - lb_) * G + grp + 1), cs);+ else+#endif+ if (remote_opt_) // #578: the helper GPUs reduce with the routing weights - publish them+ doorbell_publish(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N,+ m_ids_ + tb * K, m_w_ + tb * K, m_seq_, cs);+ else {+ const int32_t* layer_res = hits_.d_res != nullptr ? (hits_.d_res + l * g.n_expert) : nullptr;+ doorbell_publish_res(xm, ids_ + tb * K, layer_res, (int) g.n_expert, (int64_t) n * N, (int64_t) n * K,+ m_x_ + tb * N, m_ids_ + tb * K, m_seq_, cs);+ }++ }+ }stamp(l, 17, grp);{const WeightRef *wgi = need(v, "ffn_gate_inp_shexp.weight", err), *wsg = need(v, "ffn_gate_shexp.weight", err),@@@ -971,23 -790,31 +1060,32 @@@nsw.gate_type = wsg->native_type; nsw.gate_data = wsg->native_data;nsw.up_type = wsu->native_type; nsw.up_data = wsu->native_data;nsw.down_type = wsd->native_type; nsw.down_data = wsd->native_data;- nsw.q8_1 = xq_;- // STRATA_VERIFY_QDEDUP=1: the experts' q8_1 image of xm is made first and the shared expert's gate/up- // read it (quantize_q8_1_rows and native_quantize_q8_1 write the same bytes), and the BF16 copy of xm- // is skipped when the shared expert's native BF16 gate (which never reads it) is on.- const bool qdedup = g_qdedup && strata::kernels::cpu::expert_layout().native;+ nsw.q8_1 = sh_fork ? sh_xq_ : xq_;++ // STRATA_VERIFY_QDEDUP=1 (not with the forked shared-expert stream, which quantizes into its own buffer): the++ // experts' q8_1 image of xm is made first and the shared expert's gate/up read it (quantize_q8_1_rows and++ // native_quantize_q8_1 write the same bytes)++ const bool qdedup = g_qdedup && !sh_fork && strata::kernels::cpu::expert_layout().native;+ if (qdedup && !q8_ffn) quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs);- if (!(qdedup && shared_expert_native_bf16())) {- if (dec_batch) f32_to_bf16_bulk(mixed_ + tb * N, sh_bf16_ + tb * N, (int64_t) n * N, cs); // contiguous rows- else for (int t = tb; t < te; ++t) f32_to_bf16_bulk(mixed_ + t * N, sh_bf16_ + t * N, N, cs);+ if (!shared_expert_native_bf16_enabled()) {+ if (dec_batch) f32_to_bf16_bulk(mixed_ + tb * N, sh_bf16_ + tb * N, (int64_t) n * N, sh_stream); // contiguous rows+ else for (int t = tb; t < te; ++t) f32_to_bf16_bulk(mixed_ + t * N, sh_bf16_ + t * N, N, sh_stream);}try {shared_expert_multi(n, xm, sh_bf16_ + tb * N, nsw, (const uint16_t*) wgi->data, sh_gate_ + (size_t) tb * g.n_ff,- sh_up_ + (size_t) tb * g.n_ff, sh_g_ + tb, shared_ + tb * N, N, g.n_ff, sh_stream);- sh_up_ + (size_t) tb * g.n_ff, sh_g_ + tb, shared_ + tb * N, N, g.n_ff, cs,++ sh_up_ + (size_t) tb * g.n_ff, sh_g_ + tb, shared_ + tb * N, N, g.n_ff, sh_stream,+ qdedup ? (const void*) (nat_xq_ + (size_t) tb * (N / 32) * 36) : nullptr,+ (sg_ready ? 1 : 0) | (lfuse_on(n) && g_lfuse_pair ? 2 : 0));+ sg_gated_[grp] = sg_ready;} catch (const std::exception& e) {err = std::string("verify shared expert: ") + e.what();return false;}+ if (sh_fork) cudaEventRecord(ev_join_, sh_cs_);}- if (strata::kernels::cpu::expert_layout().native)- quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs);- else+ if (strata::kernels::cpu::expert_layout().native) {+ if (!(g_qdedup && strata::kernels::cpu::expert_layout().native))+ if (!q8_ffn) quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs);+ } elsequantize_q8_0_scaled(xm, hit_xq_ + (size_t) tb * (N / 32) * 34, hit_xs_ + (size_t) tb * (N / 32), (int64_t) n * N, cs);stamp(l, 18, grp);return true;@@@ -1005,6 -826,16 +1103,7 @@@const uint32_t ring = (uint32_t) ((l - lb_) * G + grp + 1);const int64_t cap = (int64_t) n * K, capx = (int64_t) max_t_ * K;int32_t* pl = plan_ + (size_t) grp * (size_t) (plan_i32_ + 16);- if (resident_) {- // STRATA_VERIFY_RESIDENT: resident_plan (pre) wrote this group's plan into `pl`; nothing to wait for- } else if (device_plan_) { // E-6: skipped when the device planned this group (all its experts resident)- wait_flag_ge_or(m_flagA_, ring, skip_ + grp, cs);- copy_i32_from_mapped_unless(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, skip_ + grp, ring, cs);- } else {- wait_flag_ge(m_flagA_, ring, cs); // the pool published this group's GPU plan- copy_i32_from_mapped(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, cs);- }- stamp(l, 19, grp);++ bool combined = false; // STRATA_VERIFY_RESIDENT: the combine below already wrote bo_const int32_t* p_counts = pl;const int32_t* p_start = pl + 4;const int32_t* p_dst = p_start + capx + 1;@@@ -1024,60 -853,56 +1123,85 @@@const auto& f = lay.fmt[(size_t) l];const NativeExpertLayout L = native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff);native_expert_grouped(L, gp, gs, gn, p_dst, p_tok, cap, cap,- nat_xq_ + (size_t) tb * (N / 32) * 36, hit_scratch_, hit_out, cs);+ nat_xq_ + (size_t) tb * (N / 32) * 36, hit_scratch_, dst_buf, cs, gy);} else {moe_grouped_s2(gp, gs, gn, p_dst, p_tok, cap, cap, hit_xq_ + (size_t) tb * (N / 32) * 34,- hit_xs_ + (size_t) tb * (N / 32), hit_scratch_, hit_out, cs);+ hit_xs_ + (size_t) tb * (N / 32), hit_scratch_, dst_buf, cs);}};- if (all_resident_) {- grouped(p_ptr, p_start, p_counts);- stamp(l, 20, grp);- if (resident_ && native_moe_combine_enabled()) {- // every row is a hit: combine straight from hit_out as 0.0f + hit (= the zeroed row + moe_hit_add)- try {- if (sg_gated_[grp])- native_moe_combine_multi_hits_gated(hit_out, w_ + tb * K, shared_ + tb * N, sh_g_ + tb, bo_ + tb * N,- N, K, n, cs);- else- native_moe_combine_multi_hits(hit_out, w_ + tb * K, shared_ + tb * N, bo_ + tb * N, N, K, n, cs);- } catch (const std::exception& e) { err = "verify combine: " + std::string(e.what()); return false; }- } else {+ if (resident_) {- if (cudaMemsetAsync(parts_ + (size_t) tb * K * N, 0, sizeof(float) * (size_t) n * K * N, cs) != cudaSuccess) {- err = "verify: zeroing the parts failed";- return false;++ // STRATA_VERIFY_RESIDENT: every expert is resident and resident_plan (pre) wrote this group's plan: no host step++ stamp(l, 19, grp);++ grouped(p_ptr, p_start, p_counts, 0, hit_out);++ stamp(l, 20, grp);++ if (!prof_on_ && sh_cs_ != nullptr && ev_fork_ != nullptr && ev_join_ != nullptr)++ cudaStreamWaitEvent(cs, ev_join_, 0); // the shared expert's rows are read below++ if (native_moe_combine_enabled()) {++ // every row is a hit: combine straight from hit_out as 0.0f + hit (= the zeroed row + moe_hit_add)++ try {++ if (sg_gated_[grp])++ native_moe_combine_multi_hits_gated(hit_out, w_ + tb * K, shared_ + tb * N, sh_g_ + tb, bo_ + tb * N,++ N, K, n, cs);++ else++ native_moe_combine_multi_hits(hit_out, w_ + tb * K, shared_ + tb * N, bo_ + tb * N, N, K, n, cs);++ } catch (const std::exception& e) { err = "verify combine: " + std::string(e.what()); return false; }++ combined = true;++ } else {++ if (cudaMemsetAsync(parts_out, 0, sizeof(float) * (size_t) n * K * N, cs) != cudaSuccess) {++ err = "verify: zeroing the parts failed";++ return false;++ }++ moe_hit_add(parts_out, hit_out, p_dst, p_counts + 1, cap, N, cs);+ }++ } else if (all_resident_) {+ stamp(l, 19, grp);+ grouped(p_ptr, p_start, p_counts, 0, parts_out);+ stamp(l, 20, grp);} else {- if (device_plan_) wait_flag_ge_or(m_flagB_, ring, skip_ + grp, cs);- else wait_flag_ge(m_flagB_, ring, cs); // the PCIe share is in staging (DMA) or mapped- if (sink_.pcie_mode == 2) { // stage it with a copy kernel, then point at staging- const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs;- uint8_t* stage = staging_ + (size_t) (grp * per) * lay.max_blob;- fetch_blobs(p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), (int) per, cs);- rebase_ptrs((unsigned long long*) p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), cs);+ if (device_plan_) { // E-6: skipped when the device planned this group (all its experts resident)+ wait_flag_ge_or(m_flagA_, ring, skip_ + grp, cs);+ copy_i32_from_mapped_unless(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, skip_ + grp, ring, cs);+ } else {+ wait_flag_ge(m_flagA_, ring, cs); // the pool published this group's GPU plan+ copy_i32_from_mapped(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, cs);+ }+ stamp(l, 19, grp);+ grouped(p_ptr, p_start, p_counts, 0, hit_out);+ stamp(l, 20, grp);+ if (device_plan_) wait_flag_ge_or(m_flagB_, ring, skip_ + grp, cs);+ else wait_flag_ge(m_flagB_, ring, cs); // the PCIe share is in staging (DMA) or mapped+ if (sink_.pcie_mode == 2) { // stage it with a copy kernel, then point at staging+ const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs;+ uint8_t* stage = staging_ + (size_t) (grp * per) * lay.max_blob;+ fetch_blobs(p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), (int) per, cs);+ rebase_ptrs((unsigned long long*) p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), cs);+ }+ stamp(l, 21, grp);+ // the PCIe share is pcie_frac of the misses: a few groups when the cache is cold, usually none (always none at+ // pcie_frac 0), so its launch is kPcieGroupRows block rows striding over the groups, not cap of them+ grouped(p_ptr2, p_start2, p_counts + 2, kPcieGroupRows, hit_out);+ stamp(l, 22, grp);+ if (device_plan_) { // no CPU share when the device planned the group: its rows are zeros+ wait_flag_ge_or(m_flag_, ring, skip_ + grp, cs);+ copy_or_zero_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (long long) n * K * N,+ skip_ + grp, ring, cs);+ } else {+ wait_flag_ge(m_flag_, ring, cs); // the CPU's share is in the mapped rows+ stamp(l, 23, grp);+ if (remote_opt_) // #578: the helper's rows come back reduced; skip them as well+ remote_opt_->copy_rows(parts_out, m_ymiss_ + (size_t) tb * K * N, tb, n, p_dst, p_counts + 1, cs);+ else if (dec_batch) // only the CPU rows cross PCIe (p_dst[0, counts[1]) = the GPU's own rows)+ copy_rows_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K, N,+ p_dst, p_counts + 1, cs);+ else+ copy_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K * N, cs);+ }+ moe_hit_add(parts_out, hit_out, p_dst, p_counts + 1, cap, N, cs);}- stamp(l, 21, grp);- grouped(p_ptr2, p_start2, p_counts + 2);- stamp(l, 22, grp);- if (device_plan_) { // no CPU share when the device planned the group: its rows are zeros- wait_flag_ge_or(m_flag_, ring, skip_ + grp, cs);- copy_or_zero_from_mapped(parts_ + (size_t) tb * K * N, m_ymiss_ + (size_t) tb * K * N, (long long) n * K * N,- skip_ + grp, ring, cs);- } else {- wait_flag_ge(m_flag_, ring, cs); // the CPU's share is in the mapped rows- stamp(l, 23, grp);- if (dec_batch) // only the CPU rows cross PCIe (p_dst[0, counts[1]) = the GPU's own rows)- copy_rows_from_mapped(parts_ + (size_t) tb * K * N, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K, N,- p_dst, p_counts + 1, cs);- else- copy_from_mapped(parts_ + (size_t) tb * K * N, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K * N, cs);+ if (!prof_on_ && sh_cs_ != nullptr && ev_fork_ != nullptr && ev_join_ != nullptr) {+ cudaStreamWaitEvent(cs, ev_join_, 0);}- } // !resident_- moe_hit_add(parts_ + (size_t) tb * K * N, hit_out, p_dst, p_counts + 1, cap, N, cs);++ if (!combined) {if (dec_batch && n > 1 && native_moe_combine_enabled()) { // one launch for the window's rowstry {native_moe_combine_multi(parts_ + (size_t) tb * K * N, w_ + tb * K, shared_ + tb * N, bo_ + tb * N, N, K, n, cs);@@@ -1088,14 -913,11 +1212,15 @@@mb.weights = w_ + t * K; mb.shared = shared_ + t * N;if (!moe_combine_parts(g, l, K, mb, parts_ + (size_t) t * K * N, bo_ + t * N, cs, err)) return false;}- } // the resident combine from hit_out++ } // !combined+ if (remote_opt_) remote_opt_->combine(bo_ + tb * N, y_dummy_ + tb * N, tb, n,+ device_plan_ ? skip_ + grp : nullptr, ring, cs);stamp(l, 24, grp);if (l == g.n_layers - 1) {- for (int t = tb; t < te; ++t) gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs);- if (cvec().covers(l)) cvec_apply(Rt(tb), l, n, HC * N, nullptr, 0, nullptr, 0, false, cs);+ if (!fuse_head_gr) {+ for (int t = tb; t < te; ++t) gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs);+ if (cvec().covers(l)) cvec_apply(Rt(tb), l, n, HC * N, nullptr, 0, nullptr, 0, false, cs);+ }} else if (cvec().covers(l)) {cvec_apply(Rt(tb), l, n, HC * N, bo_ + tb * N, N, inj2_ + tb * HC, HC, true, cs);}@@@ -1123,33 -946,30 +1248,49 @@@const WeightRef *hn = wt.find("output_hc_norm.weight"), *hd = wt.find("output_hc_down.weight"),*hu = wt.find("output_hc_up.weight");if (!hn || !hd || !hu) { err = "verify: an output_hc_* weight is missing"; return false; }- if (fuse_head_gr) {+ // S25 (STRATA_HC_Q8=1): the final mixer from the GGUF's Q8_0 projections too, through the same multi read+ // (no pending write, no inject)+ const bool mix_q8 = hd->hc_q8 != nullptr && hu->hc_q8 != nullptr && head_ != nullptr && head_->loaded();+ if (mix_q8) {+ FusedGrArgs fa[kFusedGrMaxT];+ for (int t = 0; t < T; ++t) {+ FusedGrArgs& a = fa[t];+ a.R = Rt(t); a.R_out = Rt(t); a.apply = false;+ a.w_norm = (const float*) hn->data; a.w_down = (const uint16_t*) hd->data;+ a.w_up = (const uint16_t*) hu->data; a.w_inject = nullptr;+ a.q8_down = (const uint8_t*) hd->hc_q8; a.q8_up = (const uint8_t*) hu->hc_q8;+ a.eps = EPS; a.lo = lo_ + t * g.hc_lr; a.rs = rs_ + t * HC;+ a.mixed = head_mixed_ + t * N;+ }+ fused_gr_read_multi(fa, T, xn_, cs);+ }- for (int t = 0; t < T && !mix_q8; ++t) {- BlockBuffers bb = ss.block;- bb.R = Rt(t);- bb.mixed = head_mixed_ + t * N;- if (head_ != nullptr && head_->loaded()) {- if (!lm_head_mix(wt, g, bb, cs, err)) return false;- } else if (!lm_head(wt, g, bb, head_logits_ + (size_t) t * n_vocab_, cs, err)) {- return false;++ else if (fuse_head_gr) {+ FusedGrArgs fa[kFusedGrMaxT];+ for (int t = 0; t < T; ++t) {+ FusedGrArgs& a = fa[t];+ a.R = Rt(t); a.R_out = Rt(t); a.apply = true;+ a.bo_prev = bo_ + t * N; a.inj_prev = inj2_ + t * HC;+ a.w_norm = (const float*) hn->data;+ a.w_down = (const uint16_t*) hd->data;+ a.w_up = (const uint16_t*) hu->data;+ a.w_inject = nullptr;+ a.eps = EPS;+ a.lo = lo_ + t * g.hc_lr;+ a.rs = rs_ + t * HC;+ a.inject_out = head_inj_;+ a.mixed = head_mixed_ + t * N;+ }+ fused_gr_read_multi(fa, T, xn_, cs);+ } else {+ for (int t = 0; t < T; ++t) {+ BlockBuffers bb = ss.block;+ bb.R = Rt(t);+ bb.mixed = head_mixed_ + t * N;+ if (head_ != nullptr && head_->loaded()) {+ if (!lm_head_mix(wt, g, bb, cs, err)) return false;+ } else if (!lm_head(wt, g, bb, head_logits_ + (size_t) t * n_vocab_, cs, err)) {+ return false;+ }}}if (head_ != nullptr && head_->loaded()) {@@@ -1427,20 -1199,8 +1569,20 @@@ bool Verifier::run(int T, const int32_tvolatile uint32_t* const flag = h_flag_;const int G = groups_[T] > 0 ? groups_[T] : 1;const int gtb[2] = {0, (T + 1) / 2}, gte[2] = {G == 2 ? (T + 1) / 2 : T, T};- const int64_t steps = (le_ - lb_) * G;+ const int64_t steps = resident_ ? 0 : (le_ - lb_) * G; // STRATA_VERIFY_RESIDENT: the GPU never ringsconst bool test_stall = g_test_stall > 0 && windows + 1 == g_test_stall; // #267 test hook (off: false)+ if (all_resident_ && !test_stall) {+ if (do_ple) {+ const Clock::time_point tp = Clock::now();+ if (!ss.ple.table->gather_batch(ple_rows, (size_t) T, h_ple_, err)) return false;+ std::atomic_thread_fence(std::memory_order_seq_cst);+ _mm_sfence();+ *flag = 1;+ ms_host += ms_since(tp);+ } else {+ *flag = 1;+ }+ } elsefor (int64_t k = 0; k < steps; ++k) {const int64_t l = lb_ + k / G;const int grp = (int) (k % G);diff --cc src/kernels/cuda/fused_gr.cuindex 71012ffcd,dfca46c67..2d70514e1--- a/src/kernels/cuda/fused_gr.cu+++ b/src/kernels/cuda/fused_gr.cu@@@ -829,231 -836,471 +867,693 @@@ int env_variant()// per device: the variant `fused_gr_check` chose (0 = not checked yet)std::atomic<int> g_variant[64];++#if defined(STRATA_HIP_GFX906)+// ---- AMD fast path (STRATA_GR_FAST, default 1; 0 = the old kernels): the same arithmetic per value in the same order, latency+// hidden. gr_norm: one block per token (as before) but a thread's 10 float4 of R / bo / w_norm are loaded+// before any is used, and xn stays in registers until rs is known (was: store, then re-read the 40 KB).+// gr_up: a warp's 8 rows of w_up and their epilogue inputs are loaded before the dots (was: one row's load chain+// after another).+constexpr int NQ = D / (THREADS * 4); // 10 float4 per thread+static_assert(D % (THREADS * 4) == 0, "whole float4 per thread");+__global__ void __launch_bounds__(THREADS) gr_norm_fast_kernel(GrMulti m) {+ __shared__ float part[WARPS][HC];+ __shared__ float s_rs[HC];+ const FusedGrArgs& a = m.a[blockIdx.x];+ float* xn = m.xn + (size_t) blockIdx.x * D;+ const int t = threadIdx.x, lane = t & 31, warp = t >> 5;+ float gw[HC];+#pragma unroll+ for (int c = 0; c < HC; ++c) gw[c] = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f;+ float4 r[NQ], g[NQ];+#pragma unroll+ for (int k = 0; k < NQ; ++k) {+ const int i = t * 4 + k * THREADS * 4;+ r[k] = *reinterpret_cast<const float4*>(a.R + i);+ g[k] = *reinterpret_cast<const float4*>(a.w_norm + i);+ }+ if (a.apply) {+#pragma unroll+ for (int k = 0; k < NQ; ++k) {+ const int i = t * 4 + k * THREADS * 4, c = i / N, d = i - c * N;+ const float4 b = *reinterpret_cast<const float4*>(a.bo_prev + d);+ r[k].x = fmaf(b.x, gw[c], r[k].x); r[k].y = fmaf(b.y, gw[c], r[k].y);+ r[k].z = fmaf(b.z, gw[c], r[k].z); r[k].w = fmaf(b.w, gw[c], r[k].w);+ }+ }+ float ss[HC] = {0.0f, 0.0f, 0.0f, 0.0f};+#pragma unroll+ for (int k = 0; k < NQ; ++k) {+ const int i = t * 4 + k * THREADS * 4, c = i / N;+ const float sq = r[k].x * r[k].x + r[k].y * r[k].y + r[k].z * r[k].z + r[k].w * r[k].w;+#pragma unroll+ for (int cc = 0; cc < HC; ++cc) if (cc == c) ss[cc] += sq;+ r[k] = make_float4(r[k].x * g[k].x, r[k].y * g[k].y, r[k].z * g[k].z, r[k].w * g[k].w);+ }+#pragma unroll+ for (int c = 0; c < HC; ++c) {+ const float v = warp_sum(ss[c]);+ if (lane == 0) part[warp][c] = v;+ }+ __syncthreads();+ if (t < HC) {+ float s = 0.0f;+ for (int w = 0; w < WARPS; ++w) s += part[w][t];+ s_rs[t] = rsqrtf(s / (float) N + a.eps);+ a.rs[t] = s_rs[t];+ }+ __syncthreads();+#pragma unroll+ for (int k = 0; k < NQ; ++k) {+ const int i = t * 4 + k * THREADS * 4;+ const float sr = s_rs[i / N];+ *reinterpret_cast<float4*>(xn + i) = make_float4(r[k].x * sr, r[k].y * sr, r[k].z * sr, r[k].w * sr);+ }+}+// gr_up: 8 lanes per row instead of a 32-lane warp. Lane j holds the old lanes j, j+8, j+16, j+24 (and chunk+// 32+j, the old lane j's second chunk): the xor tree's stages 16 and 8 are its own adds (a + b == b + a), stages+// 4, 2, 1 are shuffles inside the 8 - the same tree, bitwise the same sum, 3 shuffles a token instead of 5 and no+// idle lanes on the tail chunks. A block's 64 rows are 2 passes of 32 groups, their weights loaded up front.+__device__ __forceinline__ float xor8(float v) {+#pragma unroll+ for (int o = 4; o > 0; o >>= 1) v += __shfl_xor(v, o, 64);+ return v;+}+__global__ void __launch_bounds__(THREADS) gr_up_fast_kernel(GrMulti m) {+ __shared__ __align__(16) float lo[kFusedGrMaxT][LR];+ __shared__ float g[kFusedGrMaxT][HC][UPM_COLS];+ const int t = threadIdx.x, j = t & 7, grp = t >> 3;+ const int T = m.T;+ const int d0 = blockIdx.x * UPM_COLS;+ static_assert(LR == 40 * 8 && HC * UPM_COLS == 64 && THREADS == 256, "geometry");+ uint4 w[2][5];+ float rv[2] = {0.0f, 0.0f}, wn[2] = {0.0f, 0.0f}, rsc[2] = {0.0f, 0.0f}, bo[2] = {0.0f, 0.0f}, ip[2] = {0.0f, 0.0f};+ const bool apply = j < T && m.a[j < T ? j : 0].apply;+#pragma unroll+ for (int p = 0; p < 2; ++p) {+ const int r = grp + 32 * p, c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd;+ const uint4* w4 = reinterpret_cast<const uint4*>(m.a[0].w_up + (size_t) i * LR);+#pragma unroll+ for (int q = 0; q < 4; ++q) w[p][q] = __ldg(w4 + j + 8 * q);+ w[p][4] = __ldg(w4 + 32 + j);+ if (j < T) {+ const FusedGrArgs& a = m.a[j];+ rv[p] = a.R[i];+ wn[p] = a.w_norm[i];+ rsc[p] = a.rs[c];+ if (apply) { bo[p] = a.bo_prev[d0 + dd]; ip[p] = a.inj_prev[c]; }+ }+ }+ for (int i = t; i < T * LR; i += THREADS) lo[i / LR][i % LR] = m.a[i / LR].lo[i % LR];+ __syncthreads();+#pragma unroll+ for (int p = 0; p < 2; ++p) {+ const int r = grp + 32 * p, c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd;+ float mine = 0.0f;+#pragma unroll+ for (int k = 0; k < kFusedGrMaxT; ++k) {+ if (k >= T) break;+ const float* l = lo[k];+ const float p0 = dot8(w[p][0], l + j * 8) + dot8(w[p][4], l + (32 + j) * 8); // old lane j+ const float p1 = dot8(w[p][1], l + (j + 8) * 8); // old lane j + 8+ const float p2 = dot8(w[p][2], l + (j + 16) * 8); // old lane j + 16+ const float p3 = dot8(w[p][3], l + (j + 24) * 8); // old lane j + 24+ const float s = xor8((p0 + p2) + (p1 + p3)); // stage 16: (j, j+16), (j+8, j+24); stage 8; then 4, 2, 1+ if (j == k) mine = s;+ }+ if (j < T) {+ float x0 = rv[p];+ if (apply) {+ x0 = fmaf(bo[p], 2.0f * sigmoidf_(ip[p] / (float) HC), x0);+ m.a[j].R_out[i] = x0;+ }+ const float x = x0 * wn[p] * rsc[p];+ g[j][c][dd] = x * sigmoidf_(mine);+ }+ }+ __syncthreads();+ for (int i = t; i < T * UPM_COLS; i += THREADS) {+ const int k = i / UPM_COLS, col = i - k * UPM_COLS;+ float s = 0.0f;+#pragma unroll+ for (int c = 0; c < HC; ++c) s += g[k][c][col];+ m.a[k].mixed[d0 + col] = s / (float) HC;+ }+}+#endif++#if defined(STRATA_HIP_GFX906)+// ---- AMD: `gr_down_multi` split along K. The CUDA kernel is one warp per row of w_down (320 + 4 rows), 41+// blocks: on a 60-CU gfx906 that left most of the card idle and read the 6.5 MB matrix at ~100 GB/s. Here a block+// is 8 wavefronts = 8 rows of one K-slice of 2048 (the slice of every token's xn staged in LDS once), 41 x 5+// blocks, and a second kernel adds the 5 slice sums in a fixed order and runs the epilogue. A token's result does+// not depend on how many tokens share the window (each column is reduced on its own).+constexpr int GS_SL = 2048; // K per slice+constexpr int GS_S = D / GS_SL; // 5 slices+constexpr int GS_ROWS = LR + HC; // 324: the down rows, then the inject rows+constexpr int GS_WAVES = 8;+static_assert(D % GS_SL == 0 && GS_SL == 64 * 8 * 4, "a lane takes 4 chunks of 8 per slice");+// the slice sums: a module-scope device array is per device by construction, and needs no allocation during a+// graph capture+__device__ float g_gr_part[GS_S * kFusedGrMaxT * GS_ROWS];+__global__ void __launch_bounds__(GS_WAVES * 64) gr_down_split_kernel(GrMulti m) {+ float* part = g_gr_part;+ extern __shared__ __align__(16) float tile[]; // [T][GS_SL]+ const int t = threadIdx.x, lane = t & 63, wave = t >> 6;+ const int T = m.T, sl = blockIdx.y;+ const bool inject_block = blockIdx.x == DOWN_BLOCKS;+ const int row = inject_block ? wave : blockIdx.x * GS_WAVES + wave;+ const bool active = !(inject_block && (m.a[0].w_inject == nullptr || wave >= HC));+ const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D;+ const uint4* w4 = reinterpret_cast<const uint4*>(wrow) + sl * (GS_SL / 8);+ uint4 wv[4];+ if (active) {+#pragma unroll+ for (int q = 0; q < 4; ++q) wv[q] = __ldg(w4 + lane + 64 * q);+ }+ const float4* src4 = reinterpret_cast<const float4*>(m.xn);+ float4* tile4 = reinterpret_cast<float4*>(tile);+ for (int i = t; i < T * (GS_SL / 4); i += GS_WAVES * 64) {+ const int k = i / (GS_SL / 4), off = i - k * (GS_SL / 4);+ tile4[i] = src4[((size_t) k * D + (size_t) sl * GS_SL) / 4 + off];+ }+ __syncthreads();+ if (!active) return;+ float acc[kFusedGrMaxT];+#pragma unroll+ for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f;+#pragma unroll+ for (int q = 0; q < 4; ++q) {+ const int j = lane + 64 * q;+#pragma unroll+ for (int k = 0; k < kFusedGrMaxT; ++k)+ if (k < T) acc[k] += dot8(wv[q], tile + k * GS_SL + j * 8);+ }+#pragma unroll+ for (int k = 0; k < kFusedGrMaxT; ++k) {+ if (k >= T) break;+ float v = acc[k];+#pragma unroll+ for (int off = 32; off > 0; off >>= 1) v += __shfl_xor(v, off, 64);+ if (lane == 0) part[((size_t) sl * kFusedGrMaxT + k) * GS_ROWS + (inject_block ? LR + row : row)] = v;+ }+}+__global__ void gr_down_finish_kernel(GrMulti m) {+ const float* part = g_gr_part;+ const int i = blockIdx.x * blockDim.x + threadIdx.x;+ const int k = i / GS_ROWS, r = i - k * GS_ROWS;+ if (k >= m.T) return;+ const bool inject = r >= LR;+ if (inject && m.a[0].w_inject == nullptr) return;+ float s = 0.0f;+#pragma unroll+ for (int sl = 0; sl < GS_S; ++sl) s += part[((size_t) sl * kFusedGrMaxT + k) * GS_ROWS + r];+ if (inject) {+ m.a[k].inject_out[r - LR] = s;+ } else {+ const float x = s / (float) HC;+ m.a[k].lo[r] = x / (1.0f + __expf(-x));+ }+}++#endif++ // ================================ S23 experiment (STRATA_HC_Q8=1): the read with the GGUF's Q8_0 projections ======+ // The pack holds the hyper-connection projections as BF16 (iq_pack.py --compat-bf16 rounds the GGUF's Q8_0 values to+ // BF16: 1.20 GiB per verify step); this read takes the Q8_0 bytes as stored (0.65 GiB - and the GGUF's own values,+ // not a rounding of them). The layout is the stream split of the v3 read above, at 4 chunks per stream: `down` runs+ // on (10 groups of 32 rows + the inject rows) x 16 chunks of 640 columns = 176 blocks, each staging its chunk of+ // R' * w_norm (unscaled) for the T tokens and writing the chunk's partial dots and sums of squares; `up` sums them+ // per stream in a fixed order, applies rs, SwiGLU-free silu, and runs the default epilogue. Another summation order+ // and other weights than the default read: an output-changing step (measured, quality-checked).+ constexpr int Q8B = 34; // Q8_0 block: fp16 d + 32 int8+ constexpr int Q8_RPW = 4; // down rows per warp+ constexpr int Q8_RG = LR / (WARPS * Q8_RPW); // 10 row groups (+1: the inject rows)+ constexpr int Q8_KC = 640, Q8_NKC = D / Q8_KC; // 16 chunks, 4 per stream+ constexpr int Q8_CPS = N / Q8_KC; // chunks per stream+ constexpr int Q8_SPB = Q8_KC / 128; // 5 steps of 4 Q8_0 blocks (8 lanes x 4 values each)+ __device__ __forceinline__ uint32_t q8_ld16(const uint8_t* p) { return *(const uint16_t*) p; }+ __device__ __forceinline__ float q8_half(uint32_t h) { return __half2float(__ushort_as_half((unsigned short) h)); }+ __device__ __forceinline__ float4 q8_four(uint32_t q, float d) {+ return make_float4(d * (float) (int8_t) (q & 255u), d * (float) (int8_t) ((q >> 8) & 255u),+ d * (float) (int8_t) ((q >> 16) & 255u), d * (float) (int8_t) (q >> 24));+ }++ template <int T>+ __global__ void __launch_bounds__(THREADS) gr_down_q8_kernel(GrMulti m, float* __restrict__ part, float* __restrict__ ssg) {+ __shared__ __align__(16) float xs[T][Q8_KC];+ __shared__ float red[WARPS][T];+ const int t = threadIdx.x, lane = t & 31, warp = t >> 5;+ const int rg = blockIdx.x, kc = blockIdx.y, c = kc / Q8_CPS;+ const bool inj = rg == Q8_RG;+ // S25: the inject rows are F32 in the GGUF with BF16-exact values, so by default they are read as the pack's BF16+ // (exact); a Q8_0 copy (STRATA_HC_Q8_INJECT=1) is the other option+ const bool inj_bf16 = inj && m.a[0].q8_inject == nullptr;+ const int nrows = inj ? (((m.a[0].q8_inject != nullptr || m.a[0].w_inject != nullptr) && warp < HC) ? 1 : 0) : Q8_RPW;+ const int row0 = inj ? warp : (rg * WARPS + warp) * Q8_RPW;+ const uint8_t* wb = inj ? m.a[0].q8_inject : m.a[0].q8_down;+ const int sub = lane & 7, bl = lane >> 3; // lanes 8b..8b+7: one Q8_0 block, 4 values each+ uint32_t q[Q8_RPW][Q8_SPB];+ float dq[Q8_RPW][Q8_SPB];+ #pragma unroll+ for (int r = 0; r < Q8_RPW; ++r) {+ if (r >= nrows || inj_bf16) break;+ const uint8_t* row = wb + (size_t) (row0 + r) * (D / 32) * Q8B + (size_t) kc * (Q8_KC / 32) * Q8B;+ #pragma unroll+ for (int s = 0; s < Q8_SPB; ++s) {+ const uint8_t* blk = row + (4 * s + bl) * Q8B;+ dq[r][s] = q8_half(q8_ld16(blk));+ q[r][s] = q8_ld16(blk + 2 + 4 * sub) | q8_ld16(blk + 4 + 4 * sub) << 16;+ }+ }+ float ssp[T];+ #pragma unroll+ for (int k = 0; k < T; ++k) {+ ssp[k] = 0.0f;+ const FusedGrArgs& a = m.a[k];+ const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f;+ for (int i = t; i < Q8_KC / 4; i += THREADS) {+ const int col = kc * Q8_KC + 4 * i;+ float4 r = *reinterpret_cast<const float4*>(a.R + col);+ if (a.apply) {+ const float4 b = *reinterpret_cast<const float4*>(a.bo_prev + (col - c * N));+ r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y);+ r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w);+ }+ const float4 g = *reinterpret_cast<const float4*>(a.w_norm + col);+ ssp[k] += r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w;+ *reinterpret_cast<float4*>(&xs[k][4 * i]) = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w);+ }+ }+ #pragma unroll+ for (int k = 0; k < T; ++k) {+ const float v = warp_sum(ssp[k]);+ if (lane == 0) red[warp][k] = v;+ }+ __syncthreads();+ if (rg == 0 && t < T) {+ float s = 0.0f;+ for (int w = 0; w < WARPS; ++w) s += red[w][t];+ ssg[t * Q8_NKC + kc] = s;+ }+ if (nrows == 0) return;+ #pragma unroll+ for (int r = 0; r < Q8_RPW; ++r) {+ if (r >= nrows) break;+ float acc[T];+ #pragma unroll+ for (int k = 0; k < T; ++k) acc[k] = 0.0f;+ #pragma unroll+ for (int s = 0; s < Q8_SPB; ++s) {+ const int v = 32 * (4 * s + bl) + 4 * sub;+ float4 w;+ if (inj_bf16) {+ const uint2 b = *reinterpret_cast<const uint2*>(m.a[0].w_inject + (size_t) row0 * D + (size_t) kc * Q8_KC + v);+ w = make_float4(__uint_as_float(b.x << 16), __uint_as_float(b.x & 0xffff0000u),+ __uint_as_float(b.y << 16), __uint_as_float(b.y & 0xffff0000u));+ } else {+ w = q8_four(q[r][s], dq[r][s]);+ }+ #pragma unroll+ for (int k = 0; k < T; ++k) {+ const float4 x = *reinterpret_cast<const float4*>(&xs[k][v]);+ acc[k] = fmaf(w.x, x.x, acc[k]); acc[k] = fmaf(w.y, x.y, acc[k]);+ acc[k] = fmaf(w.z, x.z, acc[k]); acc[k] = fmaf(w.w, x.w, acc[k]);+ }+ }+ const int prow = inj ? LR + warp : row0 + r;+ #pragma unroll+ for (int k = 0; k < T; ++k) {+ const float v = warp_sum(acc[k]);+ if (lane == 0) part[((size_t) k * Q8_NKC + kc) * PR + prow] = v;+ }+ }+ }++ template <int T>+ __global__ void __launch_bounds__(THREADS) gr_up_q8_kernel(GrMulti m, const float* __restrict__ part,+ const float* __restrict__ ssg) {+ __shared__ __align__(16) float lo[T][LR];+ __shared__ float rsS[T][HC];+ __shared__ float g[T][HC][UPM_COLS];+ const int t = threadIdx.x, lane = t & 31, warp = t >> 5;+ const int d0 = blockIdx.x * UPM_COLS;+ if (t < T * HC) {+ const int k = t / HC, c = t - k * HC;+ float ss = 0.0f;+ #pragma unroll+ for (int j = 0; j < Q8_CPS; ++j) ss += ssg[k * Q8_NKC + c * Q8_CPS + j];+ const float r = rsqrtf(ss / (float) N + m.a[k].eps);+ rsS[k][c] = r;+ if (blockIdx.x == 0) m.a[k].rs[c] = r;+ }+ __syncthreads();+ for (int i = t; i < T * PR; i += THREADS) {+ const int k = i / PR, r = i - k * PR;+ if (r >= LR && (blockIdx.x != 0 || m.a[k].w_inject == nullptr)) continue;+ float sum = 0.0f;+ #pragma unroll+ for (int c = 0; c < HC; ++c) {+ float p = 0.0f;+ #pragma unroll+ for (int j = 0; j < Q8_CPS; ++j) p += part[((size_t) k * Q8_NKC + c * Q8_CPS + j) * PR + r];+ sum = fmaf(rsS[k][c], p, sum);+ }+ if (r < LR) {+ const float x = sum / (float) HC;+ lo[k][r] = x / (1.0f + __expf(-x));+ } else {+ m.a[k].inject_out[r - LR] = sum;+ }+ }+ __syncthreads();+ constexpr int RPW8 = HC * UPM_COLS / WARPS; // 8 rows per warp+ #pragma unroll 1+ for (int qq = 0; qq < RPW8; ++qq) {+ const int r = warp + qq * WARPS;+ const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd;+ const uint8_t* row = m.a[0].q8_up + (size_t) i * (LR / 32) * Q8B;+ float4 w[3];+ #pragma unroll+ for (int s = 0; s < 3; ++s) { // lane: values 4 lane + 128 s (the third step: lanes 0-15)+ const int v = 4 * lane + 128 * s;+ if (v < LR) {+ const uint8_t* blk = row + (v >> 5) * Q8B;+ w[s] = q8_four(q8_ld16(blk + 2 + (v & 31)) | q8_ld16(blk + 4 + (v & 31)) << 16, q8_half(q8_ld16(blk)));+ } else {+ w[s] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);+ }+ }+ float rv = 0.0f, wn = 0.0f, bo = 0.0f, ip = 0.0f;+ bool apply = false;+ if (lane < T) {+ const FusedGrArgs& a = m.a[lane];+ rv = a.R[i];+ wn = a.w_norm[i];+ apply = a.apply;+ if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; }+ }+ float mine = 0.0f;+ #pragma unroll+ for (int k = 0; k < T; ++k) {+ float acc = 0.0f;+ #pragma unroll+ for (int s = 0; s < 3; ++s) {+ const int v = 4 * lane + 128 * s;+ if (v < LR) {+ const float4 x = *reinterpret_cast<const float4*>(&lo[k][v]);+ acc = fmaf(w[s].x, x.x, acc); acc = fmaf(w[s].y, x.y, acc);+ acc = fmaf(w[s].z, x.z, acc); acc = fmaf(w[s].w, x.w, acc);+ }+ }+ acc = warp_sum(acc);+ if (lane == k) mine = acc;+ }+ if (lane < T) {+ if (apply) {+ rv = fmaf(bo, 2.0f * sigmoidf_(ip / (float) HC), rv);+ m.a[lane].R_out[i] = rv;+ }+ const float x = rv * wn * rsS[lane][c];+ g[lane][c][dd] = x * sigmoidf_(mine);+ }+ }+ __syncthreads();+ for (int i = t; i < T * UPM_COLS; i += THREADS) {+ const int k = i / UPM_COLS, col = i - k * UPM_COLS;+ float sum = 0.0f;+ #pragma unroll+ for (int c = 0; c < HC; ++c) sum += g[k][c][col];+ m.a[k].mixed[d0 + col] = sum / (float) HC;+ }+ if (m.a[0].q8_mixed != nullptr) gr_q8_tail(m, d0); // S26 STRATA_QFUSE+ }+++ // S26 STRATA_TSUM=1: gr_down_q8_kernel / gr_up_q8_kernel with each row's T per-token warp sums (and the sums of+ // squares) as one transposed butterfly (s26_tsum.cuh): bitwise the same values (S26 ws4 harness, every output equal,+ // T 1-4: 1.00 / 1.03 / 1.03 / 1.15x per read). PF (all rows' weights in registers before the part / lo phase) was+ // slower (0.92-1.03x) and is off.+ using s26ts::tsum;+ using s26ts::tsum_token;+ using s26ts::tsum_lane;+ using s26ts::pow2_ceil;+ // gr_down_q8_kernel / gr_up_q8_kernel with every per-token warp sum done as one transposed butterfly per row (tsum)+ template <int T, int RPW = Q8_RPW>+ __global__ void __launch_bounds__(THREADS) gr_down_q8_fast_kernel(GrMulti m, float* __restrict__ part, float* __restrict__ ssg) {+ constexpr int P = pow2_ceil(T);+ constexpr int RG_ = LR / (WARPS * RPW);+ __shared__ __align__(16) float xs[T][Q8_KC];+ __shared__ float red[WARPS][T];+ const int t = threadIdx.x, lane = t & 31, warp = t >> 5;+ const int rg = blockIdx.x, kc = blockIdx.y, c = kc / Q8_CPS;+ const bool inj = rg == RG_;+ const bool inj_bf16 = inj && m.a[0].q8_inject == nullptr;+ const int nrows = inj ? (((m.a[0].q8_inject != nullptr || m.a[0].w_inject != nullptr) && warp < HC) ? 1 : 0) : RPW;+ const int row0 = inj ? warp : (rg * WARPS + warp) * RPW;+ const uint8_t* wb = inj ? m.a[0].q8_inject : m.a[0].q8_down;+ const int sub = lane & 7, bl = lane >> 3;+ const int tk = tsum_token<P>(lane);+ const bool owner = lane == tsum_lane<P>(tk) && tk < T;+ uint32_t q[RPW][Q8_SPB];+ float dq[RPW][Q8_SPB];+ #pragma unroll+ for (int r = 0; r < RPW; ++r) {+ if (r >= nrows || inj_bf16) break;+ const uint8_t* row = wb + (size_t) (row0 + r) * (D / 32) * Q8B + (size_t) kc * (Q8_KC / 32) * Q8B;+ #pragma unroll+ for (int s = 0; s < Q8_SPB; ++s) {+ const uint8_t* blk = row + (4 * s + bl) * Q8B;+ dq[r][s] = q8_half(q8_ld16(blk));+ q[r][s] = q8_ld16(blk + 2 + 4 * sub) | q8_ld16(blk + 4 + 4 * sub) << 16;+ }+ }+ float ssp[P];+ #pragma unroll+ for (int k = 0; k < P; ++k) ssp[k] = 0.0f;+ #pragma unroll+ for (int k = 0; k < T; ++k) {+ const FusedGrArgs& a = m.a[k];+ const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f;+ for (int i = t; i < Q8_KC / 4; i += THREADS) {+ const int col = kc * Q8_KC + 4 * i;+ float4 r = *reinterpret_cast<const float4*>(a.R + col);+ if (a.apply) {+ const float4 b = *reinterpret_cast<const float4*>(a.bo_prev + (col - c * N));+ r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y);+ r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w);+ }+ const float4 g = *reinterpret_cast<const float4*>(a.w_norm + col);+ ssp[k] += r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w;+ *reinterpret_cast<float4*>(&xs[k][4 * i]) = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w);+ }+ }+ {+ const float v = tsum<P>(ssp, lane);+ if (owner) red[warp][tk] = v;+ }+ __syncthreads();+ if (rg == 0 && t < T) {+ float s = 0.0f;+ for (int w = 0; w < WARPS; ++w) s += red[w][t];+ ssg[t * Q8_NKC + kc] = s;+ }+ if (nrows == 0) return;+ #pragma unroll+ for (int r = 0; r < RPW; ++r) {+ if (r >= nrows) break;+ float acc[P];+ #pragma unroll+ for (int k = 0; k < P; ++k) acc[k] = 0.0f;+ #pragma unroll+ for (int s = 0; s < Q8_SPB; ++s) {+ const int v = 32 * (4 * s + bl) + 4 * sub;+ float4 w;+ if (inj_bf16) {+ const uint2 b = *reinterpret_cast<const uint2*>(m.a[0].w_inject + (size_t) row0 * D + (size_t) kc * Q8_KC + v);+ w = make_float4(__uint_as_float(b.x << 16), __uint_as_float(b.x & 0xffff0000u),+ __uint_as_float(b.y << 16), __uint_as_float(b.y & 0xffff0000u));+ } else {+ w = q8_four(q[r][s], dq[r][s]);+ }+ #pragma unroll+ for (int k = 0; k < T; ++k) {+ const float4 x = *reinterpret_cast<const float4*>(&xs[k][v]);+ acc[k] = fmaf(w.x, x.x, acc[k]); acc[k] = fmaf(w.y, x.y, acc[k]);+ acc[k] = fmaf(w.z, x.z, acc[k]); acc[k] = fmaf(w.w, x.w, acc[k]);+ }+ }+ const int prow = inj ? LR + warp : row0 + r;+ const float v = tsum<P>(acc, lane);+ if (owner) part[((size_t) tk * Q8_NKC + kc) * PR + prow] = v;+ }+ }++ template <int T, bool PF = false>+ __global__ void __launch_bounds__(THREADS) gr_up_q8_fast_kernel(GrMulti m, const float* __restrict__ part,+ const float* __restrict__ ssg) {+ constexpr int P = pow2_ceil(T);+ constexpr int RPW8 = HC * UPM_COLS / WARPS;+ __shared__ __align__(16) float lo[T][LR];+ __shared__ float rsS[T][HC];+ __shared__ float g[T][HC][UPM_COLS];+ const int t = threadIdx.x, lane = t & 31, warp = t >> 5;+ const int d0 = blockIdx.x * UPM_COLS;+ const int tk = tsum_token<P>(lane);+ const bool owner = lane == tsum_lane<P>(tk) && tk < T;+ // PF: every row's weights in registers before the part / lo phase (its latency hides the weight read)+ uint32_t pq[PF ? RPW8 : 1][3];+ float pd[PF ? RPW8 : 1][3];+ if constexpr (PF) {+ #pragma unroll+ for (int qq = 0; qq < RPW8; ++qq) {+ const int r = warp + qq * WARPS;+ const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd;+ const uint8_t* row = m.a[0].q8_up + (size_t) i * (LR / 32) * Q8B;+ #pragma unroll+ for (int s = 0; s < 3; ++s) {+ const int v = 4 * lane + 128 * s;+ if (v < LR) {+ const uint8_t* blk = row + (v >> 5) * Q8B;+ pq[qq][s] = q8_ld16(blk + 2 + (v & 31)) | q8_ld16(blk + 4 + (v & 31)) << 16;+ pd[qq][s] = q8_half(q8_ld16(blk));+ } else {+ pq[qq][s] = 0u; pd[qq][s] = 0.0f;+ }+ }+ }+ }+ if (t < T * HC) {+ const int k = t / HC, c = t - k * HC;+ float ss = 0.0f;+ #pragma unroll+ for (int j = 0; j < Q8_CPS; ++j) ss += ssg[k * Q8_NKC + c * Q8_CPS + j];+ const float r = rsqrtf(ss / (float) N + m.a[k].eps);+ rsS[k][c] = r;+ if (blockIdx.x == 0) m.a[k].rs[c] = r;+ }+ __syncthreads();+ for (int i = t; i < T * PR; i += THREADS) {+ const int k = i / PR, r = i - k * PR;+ if (r >= LR && (blockIdx.x != 0 || m.a[k].w_inject == nullptr)) continue;+ float sum = 0.0f;+ #pragma unroll+ for (int c = 0; c < HC; ++c) {+ float p = 0.0f;+ #pragma unroll+ for (int j = 0; j < Q8_CPS; ++j) p += part[((size_t) k * Q8_NKC + c * Q8_CPS + j) * PR + r];+ sum = fmaf(rsS[k][c], p, sum);+ }+ if (r < LR) {+ const float x = sum / (float) HC;+ lo[k][r] = x / (1.0f + __expf(-x));+ } else {+ m.a[k].inject_out[r - LR] = sum;+ }+ }+ __syncthreads();+ #pragma unroll(PF ? RPW8 : 2)+ for (int qq = 0; qq < RPW8; ++qq) {+ const int r = warp + qq * WARPS;+ const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd;+ const uint8_t* row = m.a[0].q8_up + (size_t) i * (LR / 32) * Q8B;+ float4 w[3];+ #pragma unroll+ for (int s = 0; s < 3; ++s) {+ const int v = 4 * lane + 128 * s;+ if (PF) {+ w[s] = v < LR ? q8_four(pq[PF ? qq : 0][s], pd[PF ? qq : 0][s]) : make_float4(0.0f, 0.0f, 0.0f, 0.0f);+ } else if (v < LR) {+ const uint8_t* blk = row + (v >> 5) * Q8B;+ w[s] = q8_four(q8_ld16(blk + 2 + (v & 31)) | q8_ld16(blk + 4 + (v & 31)) << 16, q8_half(q8_ld16(blk)));+ } else {+ w[s] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);+ }+ }+ float rv = 0.0f, wn = 0.0f, bo = 0.0f, ip = 0.0f;+ bool apply = false;+ if (owner) {+ const FusedGrArgs& a = m.a[tk];+ rv = a.R[i];+ wn = a.w_norm[i];+ apply = a.apply;+ if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; }+ }+ float acc[P];+ #pragma unroll+ for (int k = 0; k < P; ++k) acc[k] = 0.0f;+ #pragma unroll+ for (int k = 0; k < T; ++k) {+ #pragma unroll+ for (int s = 0; s < 3; ++s) {+ const int v = 4 * lane + 128 * s;+ if (v < LR) {+ const float4 x = *reinterpret_cast<const float4*>(&lo[k][v]);+ acc[k] = fmaf(w[s].x, x.x, acc[k]); acc[k] = fmaf(w[s].y, x.y, acc[k]);+ acc[k] = fmaf(w[s].z, x.z, acc[k]); acc[k] = fmaf(w[s].w, x.w, acc[k]);+ }+ }+ }+ const float mine = tsum<P>(acc, lane);+ if (owner) {+ if (apply) {+ rv = fmaf(bo, 2.0f * sigmoidf_(ip / (float) HC), rv);+ m.a[tk].R_out[i] = rv;+ }+ const float x = rv * wn * rsS[tk][c];+ g[tk][c][dd] = x * sigmoidf_(mine);+ }+ }+ __syncthreads();+ for (int i = t; i < T * UPM_COLS; i += THREADS) {+ const int k = i / UPM_COLS, col = i - k * UPM_COLS;+ float sum = 0.0f;+ #pragma unroll+ for (int c = 0; c < HC; ++c) sum += g[k][c][col];+ m.a[k].mixed[d0 + col] = sum / (float) HC;+ }+ if (m.a[0].q8_mixed != nullptr) gr_q8_tail(m, d0); // S26 STRATA_QFUSE+ }++ template <int T> void launch_q8_t(const GrMulti& m, float* part, float* ssg, cudaStream_t st, unsigned long long* stamp_buf,+ int stamp_i0) {+ static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }();+ if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, (void*) st);+ if (ts) gr_down_q8_fast_kernel<T, 4><<<dim3(LR / (WARPS * 4) + 1, Q8_NKC), THREADS, 0, st>>>(m, part, ssg);+ else gr_down_q8_kernel<T><<<dim3(Q8_RG + 1, Q8_NKC), THREADS, 0, st>>>(m, part, ssg);+ if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, (void*) st);+ if (ts) gr_up_q8_fast_kernel<T, false><<<UPM_BLOCKS, THREADS, 0, st>>>(m, part, ssg);+ else gr_up_q8_kernel<T><<<UPM_BLOCKS, THREADS, 0, st>>>(m, part, ssg);+ }+ void launch_q8(const GrMulti& m, float* scratch, cudaStream_t st, unsigned long long* stamp_buf, int stamp_i0) {+ float* part = scratch;+ float* ssg = scratch + (size_t) m.T * Q8_NKC * PR;+ switch (m.T) {+ case 1: launch_q8_t<1>(m, part, ssg, st, stamp_buf, stamp_i0); break;+ case 2: launch_q8_t<2>(m, part, ssg, st, stamp_buf, stamp_i0); break;+ case 3: launch_q8_t<3>(m, part, ssg, st, stamp_buf, stamp_i0); break;+ case 4: launch_q8_t<4>(m, part, ssg, st, stamp_buf, stamp_i0); break;+ case 5: launch_q8_t<5>(m, part, ssg, st, stamp_buf, stamp_i0); break;+ case 6: launch_q8_t<6>(m, part, ssg, st, stamp_buf, stamp_i0); break;+ case 7: launch_q8_t<7>(m, part, ssg, st, stamp_buf, stamp_i0); break;+ default: launch_q8_t<8>(m, part, ssg, st, stamp_buf, stamp_i0); break;+ }+ }+} // namespace+#if defined(STRATA_HIP_GFX906)+int g_gr_fast = -1; // fused_gr_set_fast (the bench); -1 = STRATA_GR_FAST+static bool gr_fast() {+ static const bool env = [] { const char* v = std::getenv("STRATA_GR_FAST"); return v ? std::atoi(v) != 0 : true; }();+ return g_gr_fast >= 0 ? g_gr_fast != 0 : env;+}+#else+int g_gr_fast = -1;+#endif+void fused_gr_set_fast(int on) { g_gr_fast = on; }+- void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf,+ bool fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf,int stamp_i0) {if (n_tok < 1 || n_tok > kFusedGrMaxT || xn_scratch == nullptr) {std::fprintf(stderr, "fused_gr_read_multi: invalid arguments\n");@@@ -1125,33 -1377,8 +1640,33 @@@std::fprintf(stderr, "fused_gr_read_multi v3: %s\n", cudaGetErrorString(e3));std::exit(1);}- return;+ return false; // the v3 read: no q8_1 (the caller quantizes)}+#if defined(STRATA_HIP_GFX906)+ // gfx906, opt-in STRATA_GR_SPLIT=1: the latency-hidden norm/up (STRATA_GR_FAST) with the K-split down (~3% faster+ // per verify window). Its fixed-order finish sums the K slices in another order than the single-token+ // fused_gr_read, so the multi-token read is then no longer bitwise equal to T single-token calls (gr_parity's+ // contract); off by default for that reason.+ static const bool split_on = std::getenv("STRATA_GR_SPLIT") && std::string(std::getenv("STRATA_GR_SPLIT")) == "1";+ if (split_on) {+ const bool fast = gr_fast();+ if (fast) gr_norm_fast_kernel<<<n_tok, THREADS, 0, st>>>(m);+ else gr_norm_multi_kernel<<<n_tok, THREADS, 0, st>>>(m);+ if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, stream);+ gr_down_split_kernel<<<dim3(DOWN_BLOCKS + 1, GS_S), GS_WAVES * 64, (size_t) n_tok * GS_SL * sizeof(float), st>>>(+ m);+ gr_down_finish_kernel<<<(unsigned) ((n_tok * GS_ROWS + 255) / 256), 256, 0, st>>>(m);+ if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, stream);+ if (fast) gr_up_fast_kernel<<<UPM_BLOCKS, THREADS, 0, st>>>(m);+ else gr_up_multi_kernel<<<UPM_BLOCKS, THREADS, 0, st>>>(m);+ const cudaError_t e = cudaGetLastError();+ if (e != cudaSuccess) {+ std::fprintf(stderr, "fused_gr_read_multi: %s\n", cudaGetErrorString(e));+ std::exit(1);+ }+ return;+ }+#endif// the default read (STRATA_GR_V3 unset): v1, or the bitwise-equal v2 / v3 this card's check acceptedlaunch_multi(m, fused_gr_variant(), st, stamp_buf, stamp_i0);const cudaError_t e = cudaGetLastError();diff --cc src/kernels/cuda/iq_kernels.cuindex 5c552fa76,f74749488..3fe38ecbe--- a/src/kernels/cuda/iq_kernels.cu+++ b/src/kernels/cuda/iq_kernels.cu@@@ -6,7 -6,7 +6,8 @@@// included unchanged.#include "strata/kernels/iq_kernels.hpp"#include "strata/kernels/dp4a.hpp"+#include "strata/kernels/q8_1_finite.hpp"+ #include "s26_tsum.cuh"#include <cuda_fp16.h>#include <cuda_runtime.h>@@@ -16,8 -16,8 +17,9 @@@#include "ggml-common.h"#include <cstdio>+ #include <utility>#include <cstdlib>+#include <type_traits>namespace strata::kernels {namespace {@@@ -1725,26 -1302,668 +1727,682 @@@ void launch_mmvq(const uint8_t* W, sizeconst dim3 grid((unsigned) ((n_out + 3) / 4)), block(32, 4);if constexpr (!kSplit<TY>) mmvq_kernel<TY><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);else if (g_old_kernels) mmvq_kernel<TY><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);- else if (ncols <= 1) mmvq_multi_kernel<TY, 1><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);- else if (ncols == 2) mmvq_multi_kernel<TY, 2><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);- else if (ncols <= 4) mmvq_multi_kernel<TY, 4><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);- else mmvq_multi_kernel<TY, 8><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols); // 8 at a time past 8+ else if constexpr (kStageIqGrid<TY>) {+ if (!g_stage_grid_mmvq) {+ if (ncols <= 1) mmvq_multi_kernel<TY, 1, false><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);+ else if (ncols == 2) mmvq_multi_kernel<TY, 2, false><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);+ else if (ncols <= 4) mmvq_multi_kernel<TY, 4, false><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);+ else mmvq_multi_kernel<TY, 8, false><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);+ return;+ }+ if (ncols <= 1) mmvq_multi_kernel<TY, 1><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);+ else if (ncols == 2) mmvq_multi_kernel<TY, 2><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);+ else if (ncols <= 4) mmvq_multi_kernel<TY, 4><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);+ else mmvq_multi_kernel<TY, 8><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);+ } else {+ if (ncols <= 1) mmvq_multi_kernel<TY, 1><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);+ else if (ncols == 2) mmvq_multi_kernel<TY, 2><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);+ else if (ncols <= 4) mmvq_multi_kernel<TY, 4><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);+ else mmvq_multi_kernel<TY, 8><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols); // 8 at a time past 8+ }}++ // ---------------------------------------------------------------- S26 STRATA_EXPERT_V2=1 (opt-in): IQ3_S gate/up + IQ4_NL down+ // Bitwise equal to native_gu_multi_kernel / native_down_multi_kernel (S26 harness, real UD-IQ4_XS expert blobs, T 1-3,+ // memcmp of every output): each row's lane sums and warp_sum are the same; a warp interleaves RPW rows (more loads in+ // flight) and reads the chunk's activation rows from LDS and, for IQ3_S, the grid table from LDS (the same values).+ template<bool NT> __device__ __forceinline__ int ld16i(const uint16_t* p) {+ if constexpr (NT) return (int) __builtin_nontemporal_load(p); else return (int) *p;+ }+ template<bool NT> __device__ __forceinline__ int ldb2(const void* x, int i32) {+ const uint16_t* x16 = (const uint16_t*) x;+ int x32 = ld16i<NT>(x16 + 2 * i32 + 0) << 0;+ x32 |= ld16i<NT>(x16 + 2 * i32 + 1) << 16;+ return x32;+ }+ template<bool NT> __device__ __forceinline__ int ld8i(const uint8_t* p) {+ if constexpr (NT) return (int) __builtin_nontemporal_load(p); else return (int) *p;+ }+ template<bool NT> __device__ __forceinline__ float ldhalf(const half* p) {+ return __half2float(__ushort_as_half((unsigned short) ld16i<NT>(reinterpret_cast<const uint16_t*>(p))));+ }+ template<int TY, bool NT> struct S26Split;+ template<bool NT> struct S26Split<21, NT> { // IQ3_S: Split<21>::load with the loads made explicit+ using W = Split<21>::W;+ __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx;+ const int2 qs_packed = make_int2(ldb2<NT>(bq3->qs, iqs + 0), ldb2<NT>(bq3->qs, iqs + 1));+ const uint8_t* qs = (const uint8_t*) &qs_packed;+ const int qh = ld8i<NT>(bq3->qh + iqs / 2);+ const int signs_packed_32 = ldb2<NT>(bq3->signs, iqs / 2);+ const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;+ W r;+ #pragma unroll+ for (int l0 = 0; l0 < 8; l0 += 2) {+ const int2 grid_pos = make_int2(iq3s_grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)],+ iq3s_grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]);+ const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);+ const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);+ r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0);+ r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1);+ }+ r.ls = 1 + 2 * ((ld8i<NT>(bq3->scales + iqs / 4) >> ((iqs << 1) & 0x04)) & 0x0F);+ r.dw = ldhalf<NT>(&bq3->d);+ return r;+ }+ __device__ static float apply(const W& r, const block_q8_1* __restrict__ b, int iqs) { return Split<21>::apply(r, b, iqs); }+ };+ template<bool NT> struct S26Split<20, NT> { // IQ4_NL+ using W = Split<20>::W;+ __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ const block_iq4_nl* bq4 = (const block_iq4_nl*) vbq + kbx;+ W r;+ #pragma unroll+ for (int l = 0; l < 2; ++l) r.v[l] = get_int_from_table_16(ldb2<NT>(bq4->qs, iqs + l), kvalues_iq4nl);+ r.dw = ldhalf<NT>(&bq4->d);+ return r;+ }+ __device__ static float apply(const W& r, const block_q8_1* __restrict__ b, int iqs) { return Split<20>::apply(r, b, iqs); }+ };++ // S26 v13+: v6 (4 interleaved rows per warp) with the IQ3_S grid table (LT) and / or the chunk's activation rows (LX)+ // read from LDS: the same table values and the same q8_1 bytes, so the same arithmetic and bits.+ struct S26IQ3S { // Split<21>::load with the grid from `grid` (LT) or iq3s_grid itself+ using W = Split<21>::W;+ template<bool LT = true>+ __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* grid) {+ const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx;+ const int2 qs_packed = make_int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1));+ const uint8_t* qs = (const uint8_t*) &qs_packed;+ const int qh = bq3->qh[iqs / 2];+ const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2);+ const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;+ W r;+ #pragma unroll+ for (int l0 = 0; l0 < 8; l0 += 2) {+ const int i0 = qs[l0 + 0] | ((qh << (8 - l0)) & 0x100), i1 = qs[l0 + 1] | ((qh << (7 - l0)) & 0x100);+ const int2 grid_pos = LT ? make_int2(grid[i0], grid[i1]) : make_int2(iq3s_grid[i0], iq3s_grid[i1]);+ const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);+ const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);+ r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0);+ r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1);+ }+ r.ls = 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F);+ r.dw = __half2float(bq3->d);+ return r;+ }+ };++ constexpr int S26_XMAX = 2560 / 32; // q8_1 blocks of one activation row (n_embd 2560)++ // S26 BAL: step I of a warp's RPW x NI items (item p = 32 I + lane): rows QA / QB (lanes >= THR take QB)+ template<int I, int NI, int RPW> struct S26Bal {+ static constexpr int P0 = 32 * I, QA = P0 / NI, QB0 = (P0 + 31) / NI, QB = QB0 < RPW ? QB0 : RPW - 1;+ static constexpr int THR = (QA + 1) * NI - P0;+ static_assert(NI >= 32, "a step spans at most two rows");+ };++ template<bool LT, bool LX, int RPW, bool SL = false, bool TS = false>+ __global__ void __launch_bounds__(256) s26_gu_l_kernel(const unsigned long long* __restrict__ grp_ptr,+ const int32_t* __restrict__ grp_start,+ const int32_t* __restrict__ n_groups,+ const int32_t* __restrict__ ent_tok,+ const block_q8_1* __restrict__ xq, NativeExpertLayout L,+ float* __restrict__ gate, float* __restrict__ up) {+ __shared__ uint32_t s_grid[LT ? 512 : 1];+ __shared__ block_q8_1 s_x[LX ? GRP_NC * S26_XMAX : 1];+ const int g = blockIdx.y;+ if (g >= *n_groups) return;+ if constexpr (LT)+ for (int i = threadIdx.x; i < 512; i += 256) s_grid[i] = iq3s_grid[i];+ const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;+ const int row0 = blockIdx.x * GU_ROWS * RPW + warp;+ const bool live = row0 + GU_ROWS * (RPW - 1) < 2 * L.n_ff;+ const uint8_t* blob = (const uint8_t*) grp_ptr[g];+ const uint8_t* wr[RPW];+ int rr[RPW];+ bool upq[RPW];+ #pragma unroll+ for (int q = 0; q < RPW; ++q) {+ const int row = row0 + q * GU_ROWS;+ upq[q] = row >= L.n_ff;+ rr[q] = upq[q] ? row - (int) L.n_ff : row;+ wr[q] = blob + (upq[q] ? L.up_off : 0) + (size_t) rr[q] * L.gu_row;+ }+ const uint32_t* grid = LT ? s_grid : reinterpret_cast<const uint32_t*>(iq3s_grid);+ const int nb = (int) (L.n_embd / 256), xb = (int) (L.n_embd / 32);+ const int e0 = grp_start[g], e1 = grp_start[g + 1];+ for (int e = e0; e < e1; e += GRP_NC) {+ const int n = min(GRP_NC, e1 - e);+ const block_q8_1* xbase = xq;+ int off[GRP_NC];+ if constexpr (LX) {+ __syncthreads(); // the previous chunk is done with s_x+ for (int i = threadIdx.x; i < n * xb; i += 256) {+ const int c = i / xb, j = i - c * xb;+ s_x[c * S26_XMAX + j] = xq[(size_t) ent_tok[e + c] * xb + j];+ }+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * S26_XMAX;+ xbase = s_x;+ } else {+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c) off[c] = ent_tok[e + min(c, n - 1)] * xb;+ }+ if constexpr (LT || LX) __syncthreads(); // s_grid / s_x ready+ if (!live) continue;+ float s[RPW][GRP_NC];+ #pragma unroll+ for (int q = 0; q < RPW; ++q)+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f;+ for (int k = lane; k < nb * 8; k += 32) {+ const int kbx = k / 8, iqs = 2 * (k % 8);+ Split<21>::W w[RPW];+ #pragma unroll+ for (int q = 0; q < RPW; ++q) { if constexpr (SL && !LT) w[q] = S26Split<21, false>::load(wr[q], kbx, iqs); else w[q] = S26IQ3S::load<LT>(wr[q], kbx, iqs, grid); }+ #pragma unroll+ for (int q = 0; q < RPW; ++q)+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n) s[q][c] += Split<21>::apply(w[q], xbase + off[c] + kbx * 8, iqs);+ }+ if constexpr (TS) { // S26: all RPW x GRP_NC sums in one transposed butterfly (bitwise the same sums)+ constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC);+ float v[P];+ #pragma unroll+ for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f;+ const float sum = s26ts::tsum<P>(v, lane);+ const int j = s26ts::tsum_token<P>(lane);+ if (lane == s26ts::tsum_lane<P>(j) && j < RPW * GRP_NC) {+ const int c = j % GRP_NC;+ #pragma unroll+ for (int q = 0; q < RPW; ++q)+ if (j / GRP_NC == q && c < n) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = sum;+ }+ continue;+ }+ #pragma unroll+ for (int q = 0; q < RPW; ++q)+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n) s[q][c] = warp_sum(s[q][c]);+ #pragma unroll+ for (int q = 0; q < RPW; ++q)+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n && lane == c) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = s[q][c];+ }+ }++ constexpr int S26_HMAX = 640 / 32; // q8_1 blocks of one SwiGLU row (n_ff 640)++ template<bool LX, int RPW, bool SL = false, bool TS = false, int BAL = 0>+ __global__ void __launch_bounds__(256) s26_down_l_kernel(const unsigned long long* __restrict__ grp_ptr,+ const int32_t* __restrict__ grp_start,+ const int32_t* __restrict__ n_groups,+ const int32_t* __restrict__ ent_dst,+ const block_q8_1* __restrict__ hq, NativeExpertLayout L,+ float* __restrict__ out) {+ __shared__ block_q8_1 s_h[LX ? GRP_NC * S26_HMAX : 1];+ const int g = blockIdx.y;+ if (g >= *n_groups) return;+ const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;+ const int r0 = blockIdx.x * 8 * RPW + warp;+ const bool live = r0 + 8 * (RPW - 1) < L.n_embd;+ const uint8_t* blob = (const uint8_t*) grp_ptr[g];+ const uint8_t* wr[RPW];+ #pragma unroll+ for (int q = 0; q < RPW; ++q) wr[q] = blob + L.down_off + (size_t) (r0 + 8 * q) * L.d_row;+ const int nb = (int) (L.n_ff / 32), hb = (int) (L.n_ff / 32);+ const int e0 = grp_start[g], e1 = grp_start[g + 1];+ for (int e = e0; e < e1; e += GRP_NC) {+ const int n = min(GRP_NC, e1 - e);+ const block_q8_1* hbase = hq;+ int off[GRP_NC];+ if constexpr (LX) {+ __syncthreads();+ for (int i = threadIdx.x; i < n * hb; i += 256) {+ const int c = i / hb, j = i - c * hb;+ s_h[c * S26_HMAX + j] = hq[(size_t) (e + c) * hb + j];+ }+ __syncthreads();+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * S26_HMAX;+ hbase = s_h;+ } else {+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c) off[c] = (e + min(c, n - 1)) * hb;+ }+ if (!live) continue;+ float s[RPW][GRP_NC];+ #pragma unroll+ for (int q = 0; q < RPW; ++q)+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f;+ if constexpr (BAL > 0) { // S26: 5 items per lane instead of 8 / 4, in BAL groups (loads first)+ constexpr int NI = 2 * S26_HMAX, IT = RPW * NI / 32;+ static_assert(RPW * NI % 32 == 0, "whole steps");+ auto group = [&]<int G0, int... J>(std::integer_sequence<int, J...>) {+ Split<20>::W w[sizeof...(J)];+ int kk[sizeof...(J)];+ bool hh[sizeof...(J)];+ ([&] {+ using B = S26Bal<G0 + J, NI, RPW>;+ hh[J] = B::QB != B::QA && lane >= B::THR;+ kk[J] = B::P0 + lane - (hh[J] ? B::QB : B::QA) * NI;+ const uint8_t* rp = hh[J] ? wr[B::QB] : wr[B::QA];+ if constexpr (SL) w[J] = S26Split<20, false>::load(rp, kk[J] / 2, 2 * (kk[J] % 2));+ else w[J] = Split<20>::load(rp, kk[J] / 2, 2 * (kk[J] % 2));+ }(), ...);+ ([&] {+ using B = S26Bal<G0 + J, NI, RPW>;+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n) {+ const float v = Split<20>::apply(w[J], hbase + off[c] + kk[J] / 2, 2 * (kk[J] % 2));+ if (hh[J]) s[B::QB][c] += v; else s[B::QA][c] += v;+ }+ }(), ...);+ };+ constexpr int G = (IT + BAL - 1) / BAL;+ [&]<int... Q>(std::integer_sequence<int, Q...>) {+ (group.template operator()<Q * G>(std::make_integer_sequence<int, (IT - Q * G < G ? IT - Q * G : G)>{}), ...);+ }(std::make_integer_sequence<int, BAL>{});+ } else+ for (int k = lane; k < nb * 2; k += 32) {+ const int kbx = k / 2, iqs = 2 * (k % 2);+ Split<20>::W w[RPW];+ #pragma unroll+ for (int q = 0; q < RPW; ++q) { if constexpr (SL) w[q] = S26Split<20, false>::load(wr[q], kbx, iqs); else w[q] = Split<20>::load(wr[q], kbx, iqs); }+ #pragma unroll+ for (int q = 0; q < RPW; ++q)+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n) s[q][c] += Split<20>::apply(w[q], hbase + off[c] + kbx, iqs);+ }+ if constexpr (TS) { // S26: all RPW x GRP_NC sums in one transposed butterfly (bitwise the same sums)+ constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC);+ float v[P];+ #pragma unroll+ for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f;+ const float sum = s26ts::tsum<P>(v, lane);+ const int j = s26ts::tsum_token<P>(lane);+ const int q = j / GRP_NC, c = j % GRP_NC;+ if (lane == s26ts::tsum_lane<P>(j) && j < RPW * GRP_NC && c < n)+ out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = sum;+ continue;+ }+ #pragma unroll+ for (int q = 0; q < RPW; ++q)+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n) s[q][c] = warp_sum(s[q][c]);+ #pragma unroll+ for (int q = 0; q < RPW; ++q)+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = s[q][c];+ }+ }+++ // S26: swiglu_entries_kernel + quantize_q8_1_kernel in one launch (the same h expression, then the same block quantizer,+ // contraction off so the product cannot fuse into the first sum); h is still written (it is the scratch the old pair used)+ __global__ void s26_swiglu_q8_1_kernel(const float* __restrict__ gate, const float* __restrict__ up, float* __restrict__ h,+ block_q8_1* __restrict__ y, long long n) {+ #pragma clang fp contract(off)+ const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x;+ if (i >= n) return; // n is a multiple of 32: whole warps only+ const float g = gate[i];+ const float xi = (g / (1.0f + __expf(-g))) * up[i];+ h[i] = xi;+ float amax = fabsf(xi), sum = xi;+ #pragma unroll+ for (int o = 16; o > 0; o >>= 1) {+ amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));+ sum += __shfl_xor_sync(0xffffffffu, sum, o);+ }+ const float d = amax / 127.0f;+ const int8_t q = amax == 0.0f ? 0 : roundf(xi / d);+ const long long ib = i / 32, iqs = i % 32;+ y[ib].qs[iqs] = q;+ if (iqs == 0) y[ib].ds = make_half2(d, sum);+ }+ template<bool LT, bool LX, int RG, int RD, bool SL = false, bool FQ = false, bool TS = false, int BD = 0>+ void s26_launch_l(const NativeExpertLayout& L, int64_t cap_groups, cudaStream_t s, const unsigned long long* grp_ptr,+ const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok,+ const block_q8_1* X, float* gate, float* up, float* h, block_q8_1* hq, float* out, long long nh) {+ const dim3 ggu((unsigned) (2 * L.n_ff / (GU_ROWS * RG)), (unsigned) cap_groups);+ s26_gu_l_kernel<LT, LX, RG, SL, TS><<<ggu, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);+ if (FQ) {+ s26_swiglu_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, hq, nh);+ } else {+ swiglu_entries_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, nh);+ quantize_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(h, hq, nh);+ }+ const dim3 gd((unsigned) (L.n_embd / (8 * RD)), (unsigned) cap_groups);+ s26_down_l_kernel<LX, RD, SL, TS, BD><<<gd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);+ }+ // ---------------------------------------------------------------- stream B: UD-Q4_K_XL grouped decode experts+ // STRATA_EXPERT_V2K=1: s26_gu_l_kernel / s26_down_l_kernel's structure (4 interleaved rows per warp, the chunk's q8_1+ // activation rows in LDS, SwiGLU + q8_1 fused, optionally STRATA_TSUM's transposed butterfly) for Q4_K / Q5_K gate/up+ // and Q5_1 / Q8_0 down, which otherwise run native_gu_kernel / native_down_kernel (one entry at a time, the weight+ // words re-read per column). Each Fmt<TY>::dot is split into S27<TY>::load (everything that depends on the weight) and+ // apply (the activation words and the same integer / float expression), the same impl functions, so a row's lane-strided+ // k order, its terms and warp_sum are the old kernels': every output is bitwise the old one's (iq harness, memcmp).+ template<int TY> struct S27;+ template<> struct S27<12> { // Q4_K+ struct W { int v[2]; uint16_t aux[2]; half2 dm; };+ __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ const block_q4_K* b = (const block_q4_K*) vbq + kbx;+ W r;+ const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2));+ const int* q4 = (const int*) (b->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));+ r.v[0] = q4[0];+ r.v[1] = q4[4];+ k_scale_min(b->scales, bq8_offset, r.aux);+ r.dm = b->dm;+ return r;+ }+ __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {+ const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2));+ int u[2 * QR4_K];+ float d8[QR4_K];+ #pragma unroll+ for (int i = 0; i < QR4_K; ++i) {+ const block_q8_1* bq8i = bq8_1 + bq8_offset + i;+ d8[i] = __low2float(bq8i->ds);+ const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4);+ u[2 * i + 0] = q8[0];+ u[2 * i + 1] = q8[4];+ }+ const uint8_t* sc = (const uint8_t*) r.aux;+ const uint8_t* m = sc + 2;+ return vec_dot_q4_K_q8_1_impl_vmmq(r.v, u, sc, m, r.dm, d8);+ }+ };+ template<> struct S27<13> { // Q5_K+ struct W { int vl[2]; int vh[2]; uint16_t aux[2]; half2 dm; };+ __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ const block_q5_K* b = (const block_q5_K*) vbq + kbx;+ W r;+ const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2));+ const int* ql = (const int*) (b->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));+ const int* qh = (const int*) (b->qh + 4 * ((iqs / 2) % 4));+ r.vl[0] = ql[0];+ r.vl[1] = ql[4];+ r.vh[0] = qh[0] >> bq8_offset;+ r.vh[1] = qh[4] >> bq8_offset;+ k_scale_min(b->scales, bq8_offset, r.aux);+ r.dm = b->dm;+ return r;+ }+ __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {+ const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2));+ int u[2 * QR5_K];+ float d8[QR5_K];+ #pragma unroll+ for (int i = 0; i < QR5_K; ++i) {+ const block_q8_1* bq8i = bq8_1 + bq8_offset + i;+ d8[i] = __low2float(bq8i->ds);+ const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4);+ u[2 * i + 0] = q8[0];+ u[2 * i + 1] = q8[4];+ }+ const uint8_t* sc = (const uint8_t*) r.aux;+ const uint8_t* m = sc + 2;+ return vec_dot_q5_K_q8_1_impl_vmmq(r.vl, r.vh, u, sc, m, r.dm, d8);+ }+ };+ template<> struct S27<7> { // Q5_1+ struct W { int vl[VDR_Q5_1]; int qh; half2 dm; };+ __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ const block_q5_1* b = (const block_q5_1*) vbq + kbx;+ W r;+ #pragma unroll+ for (int i = 0; i < VDR_Q5_1; ++i) r.vl[i] = get_int_b4(b->qs, iqs + i);+ r.qh = get_int_b4(b->qh, 0);+ r.dm = b->dm;+ return r;+ }+ __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {+ int sumi = 0, sumu = 0;+ #pragma unroll+ for (int i = 0; i < VDR_Q5_1; ++i) {+ const int vl = r.vl[i];+ const int vh = r.qh >> (4 * (iqs + i));+ const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI5_1);+ int vi0 = (vl >> 0) & 0x0F0F0F0F;+ vi0 |= (vh << 4) & 0x00000010;+ vi0 |= (vh << 11) & 0x00001000;+ vi0 |= (vh << 18) & 0x00100000;+ vi0 |= (vh << 25) & 0x10000000;+ sumi = ggml_cuda_dp4a(vi0, u0, sumi);+ int vi1 = (vl >> 4) & 0x0F0F0F0F;+ vi1 |= (vh >> 12) & 0x00000010;+ vi1 |= (vh >> 5) & 0x00001000;+ vi1 |= (vh << 2) & 0x00100000;+ vi1 |= (vh << 9) & 0x10000000;+ sumi = ggml_cuda_dp4a(vi1, u1, sumi);+ sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu));+ }+ const float2 dm5 = __half22float2(r.dm);+ const float d8 = __low2float(bq8_1->ds);+ return sumi * (dm5.x * d8) + sumu * (dm5.y * d8);+ }+ };+ template<> struct S27<8> { // Q8_0+ struct W { int q[VDR_Q8_0]; float d; };+ __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {+ const block_q8_0* b = (const block_q8_0*) vbq + kbx;+ W r;+ #pragma unroll+ for (int i = 0; i < VDR_Q8_0; ++i) r.q[i] = get_int_b2(b->qs, iqs + i);+ r.d = __half2float(b->d);+ return r;+ }+ __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {+ int sumi = 0;+ #pragma unroll+ for (int i = 0; i < VDR_Q8_0; ++i) sumi = ggml_cuda_dp4a(r.q[i], get_int_b4(bq8_1->qs, iqs + i), sumi);+ const float d8_1 = __low2float(bq8_1->ds);+ return r.d * d8_1 * ((float) sumi);+ }+ };++ template<int TG, bool LX, int RPW, bool TS>+ __global__ void __launch_bounds__(256) s27_gu_kernel(const unsigned long long* __restrict__ grp_ptr,+ const int32_t* __restrict__ grp_start,+ const int32_t* __restrict__ n_groups,+ const int32_t* __restrict__ ent_tok,+ const block_q8_1* __restrict__ xq, NativeExpertLayout L,+ float* __restrict__ gate, float* __restrict__ up) {+ using F = Fmt<TG>;+ using S = S27<TG>;+ __shared__ block_q8_1 s_x[LX ? GRP_NC * S26_XMAX : 1];+ const int g = blockIdx.y;+ if (g >= *n_groups) return;+ const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;+ const int row0 = blockIdx.x * GU_ROWS * RPW + warp;+ const bool live = row0 + GU_ROWS * (RPW - 1) < 2 * L.n_ff;+ const uint8_t* blob = (const uint8_t*) grp_ptr[g];+ const uint8_t* wr[RPW];+ int rr[RPW];+ bool upq[RPW];+ #pragma unroll+ for (int q = 0; q < RPW; ++q) {+ const int row = row0 + q * GU_ROWS;+ upq[q] = row >= L.n_ff;+ rr[q] = upq[q] ? row - (int) L.n_ff : row;+ wr[q] = blob + (upq[q] ? L.up_off : 0) + (size_t) rr[q] * L.gu_row;+ }+ const int nb = (int) (L.n_embd / F::qk), xb = (int) (L.n_embd / 32);+ const int e0 = grp_start[g], e1 = grp_start[g + 1];+ for (int e = e0; e < e1; e += GRP_NC) {+ const int n = min(GRP_NC, e1 - e);+ const block_q8_1* xbase = xq;+ int off[GRP_NC];+ if constexpr (LX) {+ __syncthreads(); // the previous chunk is done with s_x+ for (int i = threadIdx.x; i < n * xb; i += 256) {+ const int c = i / xb, j = i - c * xb;+ s_x[c * S26_XMAX + j] = xq[(size_t) ent_tok[e + c] * xb + j];+ }+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * S26_XMAX;+ xbase = s_x;+ __syncthreads();+ } else {+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c) off[c] = ent_tok[e + min(c, n - 1)] * xb;+ }+ if (!live) continue;+ float s[RPW][GRP_NC];+ #pragma unroll+ for (int q = 0; q < RPW; ++q)+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f;+ for (int k = lane; k < nb * F::ipb; k += 32) {+ const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);+ typename S::W w[RPW];+ #pragma unroll+ for (int q = 0; q < RPW; ++q) w[q] = S::load(wr[q], kbx, iqs);+ #pragma unroll+ for (int q = 0; q < RPW; ++q)+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n) s[q][c] += S::apply(w[q], xbase + off[c] + kbx * (F::qk / 32), iqs);+ }+ if constexpr (TS) {+ constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC);+ float v[P];+ #pragma unroll+ for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f;+ const float sum = s26ts::tsum<P>(v, lane);+ const int j = s26ts::tsum_token<P>(lane);+ if (lane == s26ts::tsum_lane<P>(j) && j < RPW * GRP_NC) {+ const int c = j % GRP_NC;+ #pragma unroll+ for (int q = 0; q < RPW; ++q)+ if (j / GRP_NC == q && c < n) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = sum;+ }+ continue;+ }+ #pragma unroll+ for (int q = 0; q < RPW; ++q)+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n) s[q][c] = warp_sum(s[q][c]);+ #pragma unroll+ for (int q = 0; q < RPW; ++q)+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n && lane == c) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = s[q][c];+ }+ }++ template<int TD, bool LX, int RPW, bool TS>+ __global__ void __launch_bounds__(256) s27_down_kernel(const unsigned long long* __restrict__ grp_ptr,+ const int32_t* __restrict__ grp_start,+ const int32_t* __restrict__ n_groups,+ const int32_t* __restrict__ ent_dst,+ const block_q8_1* __restrict__ hq, NativeExpertLayout L,+ float* __restrict__ out) {+ using F = Fmt<TD>;+ using S = S27<TD>;+ __shared__ block_q8_1 s_h[LX ? GRP_NC * S26_HMAX : 1];+ const int g = blockIdx.y;+ if (g >= *n_groups) return;+ const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;+ const int r0 = blockIdx.x * 8 * RPW + warp;+ const bool live = r0 + 8 * (RPW - 1) < L.n_embd;+ const uint8_t* blob = (const uint8_t*) grp_ptr[g];+ const uint8_t* wr[RPW];+ #pragma unroll+ for (int q = 0; q < RPW; ++q) wr[q] = blob + L.down_off + (size_t) (r0 + 8 * q) * L.d_row;+ const int nb = (int) (L.n_ff / F::qk), hb = (int) (L.n_ff / 32);+ const int e0 = grp_start[g], e1 = grp_start[g + 1];+ for (int e = e0; e < e1; e += GRP_NC) {+ const int n = min(GRP_NC, e1 - e);+ const block_q8_1* hbase = hq;+ int off[GRP_NC];+ if constexpr (LX) {+ __syncthreads();+ for (int i = threadIdx.x; i < n * hb; i += 256) {+ const int c = i / hb, j = i - c * hb;+ s_h[c * S26_HMAX + j] = hq[(size_t) (e + c) * hb + j];+ }+ __syncthreads();+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * S26_HMAX;+ hbase = s_h;+ } else {+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c) off[c] = (e + min(c, n - 1)) * hb;+ }+ if (!live) continue;+ float s[RPW][GRP_NC];+ #pragma unroll+ for (int q = 0; q < RPW; ++q)+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f;+ for (int k = lane; k < nb * F::ipb; k += 32) {+ const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);+ typename S::W w[RPW];+ #pragma unroll+ for (int q = 0; q < RPW; ++q) w[q] = S::load(wr[q], kbx, iqs);+ #pragma unroll+ for (int q = 0; q < RPW; ++q)+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n) s[q][c] += S::apply(w[q], hbase + off[c] + kbx * (F::qk / 32), iqs);+ }+ if constexpr (TS) {+ constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC);+ float v[P];+ #pragma unroll+ for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f;+ const float sum = s26ts::tsum<P>(v, lane);+ const int j = s26ts::tsum_token<P>(lane);+ const int q = j / GRP_NC, c = j % GRP_NC;+ if (lane == s26ts::tsum_lane<P>(j) && j < RPW * GRP_NC && c < n)+ out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = sum;+ continue;+ }+ #pragma unroll+ for (int q = 0; q < RPW; ++q)+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n) s[q][c] = warp_sum(s[q][c]);+ #pragma unroll+ for (int q = 0; q < RPW; ++q)+ #pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = s[q][c];+ }+ }++ template<int TG, int TD, bool LX, int RG, int RD, bool TS>+ void s27_launch(const NativeExpertLayout& L, int64_t cap_groups, cudaStream_t s, const unsigned long long* grp_ptr,+ const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok,+ const block_q8_1* X, float* gate, float* up, float* h, block_q8_1* hq, float* out, long long nh) {+ const dim3 ggu((unsigned) (2 * L.n_ff / (GU_ROWS * RG)), (unsigned) cap_groups);+ s27_gu_kernel<TG, LX, RG, TS><<<ggu, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);+ s26_swiglu_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, hq, nh);+ const dim3 gd((unsigned) (L.n_embd / (8 * RD)), (unsigned) cap_groups);+ s27_down_kernel<TD, LX, RD, TS><<<gd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);+ }+ template<int TG, int TD>+ void s27_launch_ts(bool ts, const NativeExpertLayout& L, int64_t cap_groups, cudaStream_t s,+ const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups,+ const int32_t* ent_dst, const int32_t* ent_tok, const block_q8_1* X, float* gate, float* up, float* h,+ block_q8_1* hq, float* out, long long nh) {+ if (ts) s27_launch<TG, TD, true, 4, 4, true>(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, hq, out, nh);+ else s27_launch<TG, TD, true, 4, 4, false>(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, hq, out, nh);+ }+template<int TG>void launch_gu(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start,const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X, const NativeExpertLayout& L,@@@ -2458,59 -2108,35 +3116,87 @@@ void native_expert_grouped(const Nativefloat* h = (float*) ((uint8_t*) scratch + 2 * fa);block_q8_1* hq = (block_q8_1*) ((uint8_t*) scratch + 3 * fa);const auto* X = (const block_q8_1*) x_q8_1;+ static const bool v2 = [] { const char* v = std::getenv("STRATA_EXPERT_V2"); return v && v[0] == '1'; }();+ if (v2 && L.gu_type == 21 && L.d_type == 20 && L.n_embd == 2560 && L.n_ff == 640) { // S26: see s26_gu_l_kernel+ // S26 STRATA_TSUM=1: the sums as one transposed butterfly per warp (s26_tsum.cuh; bitwise the same values)+ static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }();+ // (+ down rows' items spread evenly over the lanes, one load group: bitwise, harness 1.09-1.12x vs 1.03-1.06x;+ // the same for gate / up was 0.6-0.8x)+ if (ts) s26_launch_l<true, true, 4, 4, true, true, true, 1>(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h,+ hq, out, (long long) cap_entries * L.n_ff);+ else s26_launch_l<true, true, 4, 4, true, true>(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h,+ hq, out, (long long) cap_entries * L.n_ff);+ check("native_expert_grouped (v2)");+ return;+ }+ // stream B: UD-Q4_K_XL's Q4_K / Q5_K gate/up and Q5_1 / Q8_0 down (see S27 above)+ static const bool v2k = [] { const char* v = std::getenv("STRATA_EXPERT_V2K"); return v && v[0] == '1'; }();+ if (v2k && (L.gu_type == 12 || L.gu_type == 13) && (L.d_type == 7 || L.d_type == 8) && L.n_embd == 2560 &&+ L.n_ff == 640) {+ static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }();+ const long long nh = (long long) cap_entries * L.n_ff;+ #define STRATA_V2K(G, D) s27_launch_ts<G, D>(ts, L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, hq, out, nh)+ if (L.gu_type == 12 && L.d_type == 7) STRATA_V2K(12, 7);+ else if (L.gu_type == 12) STRATA_V2K(12, 8);+ else if (L.d_type == 7) STRATA_V2K(13, 7);+ else STRATA_V2K(13, 8);+ #undef STRATA_V2K+ check("native_expert_grouped (v2k)");+ return;+ }- const dim3 ggu((unsigned) ((2 * L.n_ff + GU_ROWS - 1) / GU_ROWS), (unsigned) cap_groups);+ const bool v1 = g_grouped_v1;+ const int64_t gy = (v1 || grid_groups <= 0 || grid_groups > cap_groups) ? cap_groups : grid_groups;+ const dim3 ggu((unsigned) ((2 * L.n_ff + GU_ROWS - 1) / GU_ROWS), (unsigned) gy);+#if defined(STRATA_HIP_GFX906)+ const int em0 = exp_mode();+#endif+#if defined(STRATA_HIP_GFX906)+ const bool fused_gu = em0 == 8 && (L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23) &&+ L.n_ff % 32 == 0;+ if (fused_gu && g_exp_phase != 2) {+ const dim3 gl((unsigned) (L.n_ff / 32), (unsigned) cap_groups);+ const size_t sh = (size_t) LDS_NT * (size_t) (L.n_embd / 32) * sizeof(block_q8_1);+ switch (L.gu_type) {+ case 18: native_gu_fused_kernel<18><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;+ case 21: native_gu_fused_kernel<21><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;+ case 23: native_gu_fused_kernel<23><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;+ default: native_gu_fused_kernel<22><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;+ }+ check("native_expert_grouped/gu fused");+ }+ if (g_exp_phase != 2 && !fused_gu) {+#else+ if (g_exp_phase != 2) {+#endif+#if defined(STRATA_HIP_GFX906)+ const bool lds_gu = (em0 == 5 || em0 == 6 || em0 == 7 || em0 == 8) && (L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23);+ if (lds_gu) {+ const dim3 gl((unsigned) ((2 * L.n_ff + LDS_RB - 1) / LDS_RB), (unsigned) cap_groups);+ const size_t sh = (size_t) LDS_NT * (size_t) (L.n_embd / 32) * sizeof(block_q8_1);+ switch (L.gu_type) {+ case 18: if (em0 >= 7) native_gu_lds_kernel<18, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<18, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<18, 0><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;+ case 21: if (em0 >= 7) native_gu_lds_kernel<21, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<21, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<21, 0><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;+ case 23: if (em0 >= 7) native_gu_lds_kernel<23, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<23, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;+ default: if (em0 >= 7) native_gu_lds_kernel<22, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<22, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<22, 0><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;+ }+ } else {+ const int em = exp_mode() >= 5 ? 2 : exp_mode();+ const dim3 ggu_amd((unsigned) ((2 * L.n_ff + (em == 1 ? 3 : em == 4 ? 31 : 15)) / (em == 1 ? 4 : em == 4 ? 32 : 16)), (unsigned) cap_groups);+#define STRATA_GU_AMD(T) \+ case T: if (em == 1) native_gu_amd_kernel<T, 1><<<ggu_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); \+ else if (em == 4) native_gu_amd_kernel<T, 4><<<ggu_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); \+ else native_gu_amd_kernel<T, 2><<<ggu_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;+ // the AMD layouts cover the IQ packs' gate/up types; Unsloth's Q4_K / Q5_K take the CUDA layout below+ const bool amd_gu = L.gu_type == 16 || L.gu_type == 17 || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 ||+ L.gu_type == 23 || L.gu_type == 29 || L.gu_type == 42;+ if ((em == 1 || em == 2 || em == 4) && amd_gu) {+ switch (L.gu_type) {+ STRATA_GU_AMD(16) STRATA_GU_AMD(17) STRATA_GU_AMD(18) STRATA_GU_AMD(21) STRATA_GU_AMD(22) STRATA_GU_AMD(23)+ STRATA_GU_AMD(29) STRATA_GU_AMD(42)+ }+ } else+#undef STRATA_GU_AMD+#endifswitch (L.gu_type) {#define STRATA_GU(T) case T: launch_gu<T>(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;STRATA_GU_FMTS(STRATA_GU)diff --cc src/kernels/cuda/native_mmvq.cuindex e0d11bf18,261ca0926..29b1b6b22--- a/src/kernels/cuda/native_mmvq.cu+++ b/src/kernels/cuda/native_mmvq.cu@@@ -25,8 -25,8 +25,9 @@@#include "strata/kernels/native_mmvq.hpp"#include "strata/kernels/dp4a.hpp"+#include "strata/kernels/q8_1_finite.hpp"#include "strata/kernels/iq_kernels.hpp"+ #include "s26_tsum.cuh"#include <cuda_fp16.h>#include <cuda_runtime.h>@@@ -1026,14 -1003,27 +1032,27 @@@ struct SmallTraits// equal to ncols = 1 only to float rounding (the cross-warp reduction groups partial sums differently).bool g_multi_exact = true; // until the upstream layout is timed on an idle GPU (plan rule: default only what is measured)- template<typename F, int NCOLS, int NW, int ROWS>+ // S26 STRATA_TSUM=1 (TS): warp 0's NCOLS x ROWS sums as one transposed butterfly (s26_tsum.cuh), bitwise the same+ static bool s26_tsum_on() {+ static const bool on = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }();+ return on;+ }++ // S26 STRATA_LFUSE (PAIR): blocks n_out.. compute the same rows of w2 into y2 (two matrices of one shape on one+ // input in one launch; each output's code is the single matrix's)+ template<typename F, int NCOLS, int NW, int ROWS, bool TS = false, bool PAIR = false>-__launch_bounds__(NW * WARP, 1)+__launch_bounds__(NW * WARP, (ROWS <= 2 ? 4 : 1))__global__ void native_mmvq_multi_kernel(const typename F::Block* __restrict__ w,const Q81Block* __restrict__ x,- float* __restrict__ y, int n_in, int n_out) {+ float* __restrict__ y, int n_in, int n_out,+ const typename F::Block* __restrict__ w2 = nullptr, float* __restrict__ y2 = nullptr) {constexpr int BPI = F::BPI * NW / WARPS; // blocks per iteration scale with the warp countconst int tid = WARP * int(threadIdx.y) + int(threadIdx.x);- const int row0 = ROWS * int(blockIdx.x);+ int bxi = int(blockIdx.x);+ if constexpr (PAIR) {+ if (bxi >= n_out / ROWS) { bxi -= n_out / ROWS; w = w2; y = y2; }+ }+ const int row0 = ROWS * bxi;const int blocks_per_row = n_in / F::DIV;const int x_stride = n_in / Q8K; // Q8_1 blocks per activation columnfloat tmp[NCOLS][ROWS] = {};@@@ -1084,11 -1093,12 +1122,13 @@@ void launch_multi_n(const void* weights}const dim3 threads(WARP, WARPS);if (n_in / F::DIV < F::BPI) {- const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);- if (s26_tsum_on()) native_mmvq_multi_kernel<F, NCOLS, WARPS, WARPS, true><<<blocks, threads, 0, s>>>(w, x, y, n_in, n_out);- else native_mmvq_multi_kernel<F, NCOLS, WARPS, WARPS><<<blocks, threads, 0, s>>>(w, x, y, n_in, n_out);+ constexpr int ROWS = 2;+ const unsigned blocks = unsigned((std::size_t(n_out) + ROWS - 1) / ROWS);- native_mmvq_multi_kernel<F, NCOLS, WARPS, ROWS><<<blocks, threads, 0, s>>>(w, x, y, n_in, n_out);++ if (s26_tsum_on()) native_mmvq_multi_kernel<F, NCOLS, WARPS, ROWS, true><<<blocks, threads, 0, s>>>(w, x, y, n_in, n_out);++ else native_mmvq_multi_kernel<F, NCOLS, WARPS, ROWS><<<blocks, threads, 0, s>>>(w, x, y, n_in, n_out);} else {- native_mmvq_multi_kernel<F, NCOLS, WARPS, 1><<<unsigned(n_out), threads, 0, s>>>(w, x, y, n_in, n_out);+ if (s26_tsum_on()) native_mmvq_multi_kernel<F, NCOLS, WARPS, 1, true><<<unsigned(n_out), threads, 0, s>>>(w, x, y, n_in, n_out);+ else native_mmvq_multi_kernel<F, NCOLS, WARPS, 1><<<unsigned(n_out), threads, 0, s>>>(w, x, y, n_in, n_out);}}diff --cc src/kernels/cuda/qsa_decode_attn.cuindex f487c4f3e,d8c260c28..37c241207--- a/src/kernels/cuda/qsa_decode_attn.cu+++ b/src/kernels/cuda/qsa_decode_attn.cu@@@ -466,18 -262,21 +501,28 @@@ void qsa_decode_attn_batch(const floatconst float scale = 1.0f / sqrtf((float) HD);const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q);cudaStream_t st = (cudaStream_t) stream;+ // S25: STRATA_ATTN_LANECELL=1 - the score phase one cell per thread (bit-identical scores, no shuffle reductions)+ static const bool lane_cell = [] { const char* v = std::getenv("STRATA_ATTN_LANECELL"); return v && v[0] == '1'; }();-#define STRATA_ATTN_LAUNCH(M, LC) attn_chunk_kernel<M, LC><<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride)++#define STRATA_ATTN_LC(M) attn_chunk_kernel<M, true><<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride)+ if (lane_cell) {- if (kv_mode == 3) STRATA_ATTN_LAUNCH(3, true);- else if (kv_mode == 2) STRATA_ATTN_LAUNCH(2, true);- else if (kv_mode == 1) STRATA_ATTN_LAUNCH(1, true);- else STRATA_ATTN_LAUNCH(0, true);- } else {- if (kv_mode == 3) STRATA_ATTN_LAUNCH(3, false);- else if (kv_mode == 2) STRATA_ATTN_LAUNCH(2, false);- else if (kv_mode == 1) STRATA_ATTN_LAUNCH(1, false);- else STRATA_ATTN_LAUNCH(0, false);- }-#undef STRATA_ATTN_LAUNCH++ if (kv_mode == 3) STRATA_ATTN_LC(3);++ else if (kv_mode == 2) STRATA_ATTN_LC(2);++ else if (kv_mode == 1) STRATA_ATTN_LC(1);++ else STRATA_ATTN_LC(0);++ } else++#undef STRATA_ATTN_LC+ if (kv_mode == 3)+ STRATA_ATTN_CHUNK(3)<<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,+ scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);+ else if (kv_mode == 2)+ STRATA_ATTN_CHUNK(2)<<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,+ scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);+ else if (kv_mode == 1)+ STRATA_ATTN_CHUNK(1)<<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,+ scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);+ else+ STRATA_ATTN_CHUNK(0)<<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,+ scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);attn_merge_kernel<<<dim3((unsigned) s.n_head, (unsigned) n_q), HD, 0, st>>>(part_acc, part_m, part_l, n_chunks,attn, stride);const cudaError_t e = cudaGetLastError();diff --cc src/kernels/cuda/shared_expert.cuindex 28bb7edc1,3d34c276b..2214c7f90--- a/src/kernels/cuda/shared_expert.cu+++ b/src/kernels/cuda/shared_expert.cu@@@ -69,6 -69,27 +69,7 @@@ __global__ void native_swiglu_kernel(coout[i] = __fdividef(gate[i], 1.0f + __expf(-gate[i])) * up[i];}+-// STRATA_VERIFY_QDEDUP: native_swiglu_kernel and native_quantize_q8_1_kernel in one launch. Each thread computes-// the same swiglu expression (and still writes it to `out`), then the 32-lane block's q8_1 exactly as-// native_quantize_q8_1_kernel does (XOR-tree max / sum, d = amax / 127, roundf(x / d), ds = (d, sum)).-struct SwqQ81 { half2 ds; int8_t qs[32]; };-__global__ void native_swiglu_q8_1_kernel(const float* gate, const float* up, float* out, SwqQ81* __restrict__ y,- int n) {- const int i = blockIdx.x * 256 + threadIdx.x;- if (i >= n) return; // n is a multiple of 32: only whole warps return- const float xi = __fdividef(gate[i], 1.0f + __expf(-gate[i])) * up[i];- out[i] = xi;- float amax = fabsf(xi), sum = xi;-#pragma unroll- for (int offset = 16; offset > 0; offset >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffff, amax, offset, 32));-#pragma unroll- for (int offset = 16; offset > 0; offset >>= 1) sum += __shfl_xor_sync(0xffffffff, sum, offset, 32);- const float d = amax / 127.0f;- const int8_t q = amax == 0.0f ? 0 : roundf(xi / d);- y[i / 32].qs[i % 32] = q;- if (i % 32 == 0) y[i / 32].ds = make_half2(d, sum);-}__global__ void to_f16_kernel(const float* __restrict__ in, uint16_t* __restrict__ out, int n) {const int i = blockIdx.x * blockDim.x + threadIdx.x;if (i < n) out[i] = f16_from_f32(in[i]);@@@ -191,42 -196,42 +193,52 @@@ void shared_expert_multi(int n_tok, conif (n_tok < 1 || n_tok > 8 || !nw.q8_1 || !nw.gate_data || !nw.up_data || !nw.down_data || !stream)throw std::invalid_argument("shared_expert_multi: needs 1..8 tokens, native weights, scratch and a stream");cudaStream_t cs = (cudaStream_t) stream;- const void* x_q8_1 = nw.x_q8_1;- const void* xq = x_q8_1_ready ? x_q8_1_ready : nw.q8_1;- if (!x_q8_1_ready) native_quantize_q8_1(x, nw.q8_1, (int) n_embd, n_tok, stream);++ // the activation's q8_1: the caller's (STRATA_VERIFY_QDEDUP, x_q8_1_ready) or the descriptor's, else quantized here++ const void* x_q8_1 = x_q8_1_ready ? x_q8_1_ready : nw.x_q8_1;+ if (!x_q8_1) {+ native_quantize_q8_1(x, nw.q8_1, (int) n_embd, n_tok, stream);+ x_q8_1 = nw.q8_1;+ }- native_mmvq(nw.gate_type, nw.gate_data, x_q8_1, gate, (int) n_embd, (int) n_ff, n_tok, stream);- native_mmvq(nw.up_type, nw.up_data, x_q8_1, up, (int) n_embd, (int) n_ff, n_tok, stream);+ // S26 STRATA_LFUSE (gate_deferred): gate and up in one launch where the pair applies (bitwise the two calls)+ if (!(pair && nw.gate_type == nw.up_type &&- native_mmvq_pair(nw.gate_type, nw.gate_data, nw.up_data, xq, gate, up, (int) n_embd, (int) n_ff, n_tok, stream))) {- native_mmvq(nw.gate_type, nw.gate_data, xq, gate, (int) n_embd, (int) n_ff, n_tok, stream);- native_mmvq(nw.up_type, nw.up_data, xq, up, (int) n_embd, (int) n_ff, n_tok, stream);++ native_mmvq_pair(nw.gate_type, nw.gate_data, nw.up_data, x_q8_1, gate, up, (int) n_embd, (int) n_ff, n_tok, stream))) {++ native_mmvq(nw.gate_type, nw.gate_data, x_q8_1, gate, (int) n_embd, (int) n_ff, n_tok, stream);++ native_mmvq(nw.up_type, nw.up_data, x_q8_1, up, (int) n_embd, (int) n_ff, n_tok, stream);+ }const int n = (int) (n_ff * n_tok);- if (x_q8_1_ready != nullptr && (n_ff % 32) == 0) { // STRATA_VERIFY_QDEDUP: swiglu + its q8_1 in one launch- native_swiglu_q8_1_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, cs>>>(gate, up, gate, (SwqQ81*) nw.q8_1, n);+ if (fused_swiglu_q81_enabled()) {+ native_swiglu_quantize_q8_1(gate, up, nw.q8_1, (int) n_ff, n_tok, stream);} else {native_swiglu_kernel<<<(unsigned) ((n + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate, up, gate, n);native_quantize_q8_1(gate, nw.q8_1, (int) n_ff, n_tok, stream);}native_mmvq(nw.down_type, nw.down_data, nw.q8_1, out, (int) n_ff, (int) n_embd, n_tok, stream);+ if (gate_deferred) { // the caller computed g (raw) with the router and scales `out` in the combine+ const cudaError_t e = cudaGetLastError();+ if (e != cudaSuccess) throw std::runtime_error(std::string("shared_expert_multi: ") + cudaGetErrorString(e));+ return;+ }static const bool batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }();- if (native_bf16 && batch && n_tok > 1) { // one gemv for all rows (outputs identical), one sigmoid launch+ if (native_bf16 && batch && n_tok > 1) { // one gemv for all rows (outputs identical), fused sigmoid+scalebf16_gemv_fp32_mmvf_multi(x, n_embd, gate_inp_bf16, g, 1, n_embd, 1, n_tok, stream);- native_scalar_sigmoid_multi_kernel<<<1, n_tok, 0, cs>>>(g);- } else- for (int t = 0; t < n_tok; ++t) {- if (native_bf16) {- bf16_gemv_fp32_mmvf(x + (size_t) t * n_embd, gate_inp_bf16, g + t, n_embd, 1, stream);- native_scalar_sigmoid_kernel<<<1, 1, 0, cs>>>(g + t);- } else {- scalar_gate_kernel<<<1, 256, 0, cs>>>(x_bf16 + (size_t) t * n_embd, gate_inp_bf16, g + t, (int) n_embd);+ sigmoid_scale_rows_kernel<<<dim3((unsigned) ((n_embd + THREADS - 1) / THREADS), (unsigned) n_tok), THREADS, 0, cs>>>(+ out, g, (int) n_embd);+ } else if (native_bf16 && n_tok == 1) {+ bf16_gemv_fp32_mmvf(x, gate_inp_bf16, g, n_embd, 1, stream);+ sigmoid_scale_rows_kernel<<<dim3((unsigned) ((n_embd + THREADS - 1) / THREADS), 1u), THREADS, 0, cs>>>(+ out, g, (int) n_embd);+ } else {+ for (int t = 0; t < n_tok; ++t) {+ if (native_bf16) {+ bf16_gemv_fp32_mmvf(x + (size_t) t * n_embd, gate_inp_bf16, g + t, n_embd, 1, stream);+ native_scalar_sigmoid_kernel<<<1, 1, 0, cs>>>(g + t);+ } else {+ scalar_gate_kernel<<<1, 256, 0, cs>>>(x_bf16 + (size_t) t * n_embd, gate_inp_bf16, g + t, (int) n_embd);+ }}+ scale_rows_kernel<<<dim3((unsigned) ((n_embd + THREADS - 1) / THREADS), (unsigned) n_tok), THREADS, 0, cs>>>(+ out, g, (int) n_embd);}- scale_rows_kernel<<<dim3((unsigned) ((n_embd + THREADS - 1) / THREADS), (unsigned) n_tok), THREADS, 0, cs>>>(- out, g, (int) n_embd);const cudaError_t e = cudaGetLastError();if (e != cudaSuccess) throw std::runtime_error(std::string("shared_expert_multi: ") + cudaGetErrorString(e));}diff --cc src/kernels/cuda/verify_kernels.cuindex f7c484389,7637538b6..d48015dab--- a/src/kernels/cuda/verify_kernels.cu+++ b/src/kernels/cuda/verify_kernels.cu@@@ -113,50 -113,25 +114,69 @@@ __global__ void __launch_bounds__(64) g}}+// State-only commit kernel: each head's 128 independent state columns are split across 4 blocks of 32 columns+// (48 * 4 = 192 blocks of 128 threads across all SMs, vs 48 blocks of 512 threads), with no sq/o/norm/z/y work.+__global__ void __launch_bounds__(32 * RG) gdn_step_commit_kernel(float* __restrict__ state,+ const float* __restrict__ hbuf, int C,+ const float* __restrict__ gate,+ const float* __restrict__ beta,+ int h_k, int h_v,+ const int32_t* __restrict__ n_keep) {+ const int n = *n_keep;+ if (n <= 0) return;+ __shared__ float sk[S];+ __shared__ float red[RG][32];+ const int head = blockIdx.x;+ const int col_local = threadIdx.x;+ const int col = blockIdx.y * 32 + col_local;+ const int rg = threadIdx.y;+ const int tid = rg * 32 + col_local; // 0 .. 127+ const int qh = head % h_k;+ const int qk = S * h_k;+ float s[RPG];+ float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;+ const size_t row_stride = (size_t) h_v * S;+#pragma unroll+ for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride];+ for (int t = 0; t < n; ++t) {+ const float* ht = hbuf + (size_t) t * C;+ __syncthreads();+ sk[tid] = ht[qk + qh * S + tid];+ __syncthreads();+ const float g = __expf(gate[(size_t) t * h_v + head]);+ float kv = 0.0f;+#pragma unroll+ for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv);+ red[rg][col_local] = kv;+ __syncthreads();+ const float kv_col = red[0][col_local] + red[1][col_local] + red[2][col_local] + red[3][col_local];+ const float delta = (ht[2 * qk + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head];+#pragma unroll+ for (int r = 0; r < RPG; ++r) s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta);+ }+#pragma unroll+ for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r];+}++ // S26 (STRATA_QFUSE=1): the q8_1 image of a 32-column block, written by the warp that holds those columns with+ // native_quantize_q8_1_kernel's quantizer (the same XOR-tree max and sum, d = amax / 127, roundf(x / d), ds = (d, sum)).+ struct GdnQ81 { half2 ds; int8_t qs[32]; };+ __device__ __forceinline__ void gdn_q8_1_store(GdnQ81* __restrict__ xq, size_t idx, float xi) {+ // no contraction: xi is a product here, and fma(a, b, shfl) would round the first sum unlike the separate+ // quantizer, which reads xi from memory (S26 harness: ds.sum differed by 1 ulp without this)+ #pragma clang fp contract(off)+ float amax = fabsf(xi), sum = xi;+ #pragma unroll+ for (int o = 16; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));+ #pragma unroll+ for (int o = 16; o > 0; o >>= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);+ const float d = amax / 127.0f;+ const int8_t q = amax == 0.0f ? 0 : roundf(xi / d);+ xq[idx / 32].qs[idx % 32] = q;+ if (idx % 32 == 0) xq[idx / 32].ds = make_half2(d, sum);+ }++ template<bool Q>__global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __restrict__ state,const float* __restrict__ hbuf, int C,const float* __restrict__ gate,@@@ -478,17 -617,30 +678,40 @@@ void gdn_step_norm_multi(float* state,std::fprintf(stderr, "gdn_step_norm_multi: invalid arguments\n");std::exit(1);}+ static const bool split = [] { const char* v = std::getenv("STRATA_GDN_SPLIT"); return v && v[0] == '1'; }();+ // S26: the split runs where it is faster (gfx1151 harness, h_v 48: the commit 8-19% per call; a window of 2+ rows+ // 3-13%; one row: no gain, the old kernel stays) - bitwise equal in every case+ if (split && (t_out_begin >= n_tok || n_tok - t_out_begin >= 2)) {+ const dim3 grid((unsigned) h_v, S / GS_COLS), block(GS_COLS, RG);+ if (t_out_begin >= n_tok) { // no outputs (the commit): the state only+ gdn_state_replay_kernel<kVerifyMaxT><<<grid, block, 0, (cudaStream_t) stream>>>(+ state, h, conv_channels, gate, beta, h_k, h_v, n_tok, n_keep);+ } else {+ gdn_step_split_kernel<true><<<grid, block, 0, (cudaStream_t) stream>>>(+ state, h, conv_channels, gate, beta, y, h_k, h_v, n_tok, n_keep, t_out_begin);+ const dim3 ng((unsigned) h_v, (unsigned) (n_tok - t_out_begin));+ if (xq) gdn_out_norm_kernel<true><<<ng, dim3(S, RG), 0, (cudaStream_t) stream>>>(z, gamma, eps, y, h_v, n_tok, n_keep, t_out_begin, xq);+ else gdn_out_norm_kernel<false><<<ng, dim3(S, RG), 0, (cudaStream_t) stream>>>(z, gamma, eps, y, h_v, n_tok, n_keep, t_out_begin, nullptr);+ }+ check("gdn_step_norm_multi (split)");+ return;+ }+ static const bool commit_split = [] {+ const char* e = std::getenv("STRATA_GDN_COMMIT_SPLIT");+ return !e || e[0] != '0';+ }();+ if (commit_split && n_keep != nullptr && t_out_begin >= n_tok) {+ gdn_step_commit_kernel<<<dim3((unsigned) h_v, 4u), dim3(32, RG), 0, (cudaStream_t) stream>>>(+ state, h, conv_channels, gate, beta, h_k, h_v, n_keep);- } else {- gdn_step_norm_multi_kernel<<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>(- state, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, n_tok, n_keep, t_out_begin);++ check("gdn_step_commit");++ return;+ }+ if (xq && t_out_begin < n_tok)+ gdn_step_norm_multi_kernel<true><<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>(+ state, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, n_tok, n_keep, t_out_begin, xq);+ else+ gdn_step_norm_multi_kernel<false><<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>(+ state, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, n_tok, n_keep, t_out_begin, nullptr);check("gdn_step_norm_multi");}@@@ -559,39 -668,96 +782,104 @@@ __global__ void __launch_bounds__(kResiconst long long ptr_off = ((4 + (capx + 1) + 2 * capx) + 1) & ~1ll;unsigned long long* ptr = (unsigned long long*) (pl + ptr_off);int32_t* start2 = pl + ptr_off + 4 * capx;- int groups = 0, entries = 0;- for (int i0 = 0; i0 < n; ++i0) {- bool first = true;- for (int j = 0; j < i0; ++j) if (ids[j] == ids[i0]) { first = false; break; }- if (!first) continue;- const int32_t slot = res[ids[i0]];- ptr[groups] = (unsigned long long) (cache_base + (slot_off ? (size_t) slot_off[slot] : (size_t) slot * (size_t) blob));- start[groups] = entries;- for (int i = i0; i < n; ++i)- if (ids[i] == ids[i0]) {- // an entry belongs to i0's group when its first occurrence is i0: the same expert id- dst[entries] = i;- tok[entries] = i / k;- ++entries;- }- ++groups;++ if (tid < n && first_j == tid) {+ int grp_idx = 0;+ int ent_start = 0;+ for (int j = 0; j < tid; ++j) {+ grp_idx += s_first[j];+ ent_start += s_cnt[j];+ }+ ptr[grp_idx] = s_ptr[tid];+ start[grp_idx] = ent_start;+ s_gstart[tid] = ent_start;+ }+ __syncthreads();++ if (tid < n) {+ const int out_idx = s_gstart[first_j] + rank_in_group;+ dst[out_idx] = tid;+ tok[out_idx] = tid / k;+ }+ if (tid == 0) {+ int groups = 0;+ for (int j = 0; j < n; ++j) groups += s_first[j];+ start[groups] = n;+ start2[0] = n;+ counts[0] = groups;+ counts[1] = n;+ counts[2] = 0;+ if (skip != nullptr) {+ __threadfence();+ *skip = ring;+ }}- start[groups] = entries;- start2[0] = entries;- counts[0] = groups;- counts[1] = entries;- counts[2] = 0;- __threadfence();- *skip = ring;}+ // The same plan in one block of 128 threads (n <= 128): thread i owns entry i. Groups are the distinct experts in+ // order of first occurrence; group g's entries are its occurrences in increasing i - exactly the loop above+ // (S26: the one-thread loop took ~44 us per call on gfx1151, 48 per window).+ __global__ void resident_plan_par_kernel(const int32_t* __restrict__ ids, int n, int k, const int32_t* __restrict__ res,+ int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off,+ long long blob, int32_t* __restrict__ pl, long long capx, uint32_t* skip,+ uint32_t ring) {+ __shared__ int32_t s_id[128];+ __shared__ int s_first[128], s_size[128];+ __shared__ int s_bad;+ const int i = threadIdx.x;+ if (i == 0) s_bad = 0;+ __syncthreads();+ int32_t e = -1;+ if (i < n) {+ e = ids[i];+ s_id[i] = e;+ if (e < 0 || e >= n_expert || res[e] < 0) s_bad = 1;+ }+ __syncthreads();+ if (s_bad) { if (i == 0) *skip = 0; return; }+ int first = i, rank = 0, size = 0;+ if (i < n) {+ for (int j = 0; j < n; ++j) {+ const bool same = s_id[j] == e;+ if (same && j < first) first = j;+ if (same && j < i) ++rank;+ size += same;+ }+ }+ if (i < n) { s_first[i] = first; s_size[i] = size; }+ __syncthreads();+ int32_t* counts = pl;+ int32_t* start = pl + 4;+ int32_t* dst = start + capx + 1;+ int32_t* tok = dst + capx;+ const long long ptr_off = ((4 + (capx + 1) + 2 * capx) + 1) & ~1ll;+ unsigned long long* ptr = (unsigned long long*) (pl + ptr_off);+ int32_t* start2 = pl + ptr_off + 4 * capx;+ if (i < n) {+ // group of entry i = the number of first occurrences before `first`; its start = their sizes' sum+ int group = 0, gstart = 0;+ for (int j = 0; j < first; ++j)+ if (s_first[j] == j) { ++group; gstart += s_size[j]; }+ if (i == first) {+ const int32_t slot = res[e];+ ptr[group] = (unsigned long long) (cache_base + (slot_off ? (size_t) slot_off[slot] : (size_t) slot * (size_t) blob));+ start[group] = gstart;+ }+ dst[gstart + rank] = i;+ tok[gstart + rank] = i / k;+ if (i == 0) {+ int groups = 0;+ for (int j = 0; j < n; ++j) groups += s_first[j] == j;+ start[groups] = n;+ start2[0] = n;+ counts[0] = groups;+ counts[1] = n;+ counts[2] = 0;+ }+ }+ __threadfence();+ __syncthreads();+ if (i == 0) *skip = ring;+ }__global__ void wait_flag_ge_or_kernel(const volatile uint32_t* flag, uint32_t value, const volatile uint32_t* skip) {if (*skip == value) return;while (*flag < value) strata_spin_pause();diff --cc src/kernels/qsa_prompt_attn_parity.cppindex 4a0921db6,e1edc38b9..3c8867c56--- a/src/kernels/qsa_prompt_attn_parity.cpp+++ b/src/kernels/qsa_prompt_attn_parity.cpp@@@ -125,20 -97,65 +125,76 @@@ int run(int fmt, int64_t ctx, int64_t nstd::sort(v.begin(), v.end());std::copy(v.begin(), v.end(), sel);}+ // QA_SAME=1 (S23 probe): every query reads the same first-w cells - the best case of any K/V sharing between queries+ // (all loads hit the caches); QA_SAME=2: query i reads a window of w cells at i / 4 * 64 (neighbours share ~90%)+ if (const char* sm = std::getenv("QA_SAME")) {+ const int mode = std::atoi(sm);+ for (int64_t i = 0; i < nq; ++i) {+ const int64_t w = steps[i * k::kStepCount + k::kStepWidth], nkv = ctx - nq + i + 1;+ if (w == nkv) continue;+ if (mode == 3 || mode == 4) { // 3: w random cells per query (no overlap beyond chance); 4: a 4-query group shares+ // one random set of w - 512 cells (the union of 4 queries = 1x), the last 512 cells recent+ std::mt19937 r3((unsigned) (mode == 3 ? i : i / 4) * 2654435761u + 7);+ std::vector<int32_t> all((size_t) (nkv - 512));+ for (int64_t c = 0; c < nkv - 512; ++c) all[c] = (int32_t) c;+ std::shuffle(all.begin(), all.end(), r3);+ std::vector<int32_t> v(all.begin(), all.begin() + (w - 512));+ for (int64_t c = nkv - 512; c < nkv; ++c) v.push_back((int32_t) c);+ std::sort(v.begin(), v.end());+ std::copy(v.begin(), v.end(), ids.data() + i * cap);+ continue;+ }+ const int64_t base = mode == 1 ? 0 : std::min<int64_t>(i / 4 * 64, nkv - w);+ for (int64_t c = 0; c < w; ++c) ids[i * cap + c] = (int32_t) (base + c);+ }+ }+ // QA_DUMP=<file> QA_LAYER=n (S23 probe): the engine's own selections (STRATA_QSA_DUMP records {layer, pos0, T, cap} ++ // T*cap cells): the last record of that layer, whose T must be nq and pos0 + T ctx+ if (const char* df = std::getenv("QA_DUMP")) {+ const int want = std::getenv("QA_LAYER") ? std::atoi(std::getenv("QA_LAYER")) : 3;+ std::FILE* f = std::fopen(df, "rb");+ if (!f) { std::fprintf(stderr, "QA_DUMP: cannot open\n"); std::exit(2); }+ int32_t h[4];+ long at = -1;+ while (std::fread(h, 4, 4, f) == 4) {+ const long data = std::ftell(f);+ if (h[0] == want && h[2] == nq && h[1] + h[2] == ctx && h[3] == cap) at = data;+ std::fseek(f, (long) h[2] * h[3] * 4, SEEK_CUR);+ }+ if (at < 0) { std::fprintf(stderr, "QA_DUMP: no record for layer %d, T %lld, ctx %lld\n", want, (long long) nq, (long long) ctx); std::exit(2); }+ std::fseek(f, at, SEEK_SET);+ if (std::fread(ids.data(), 4, ids.size(), f) != ids.size()) std::exit(2);+ std::fclose(f);+ for (int grp : {2, 4, 8, 16}) { // the union of `grp` neighbouring queries' cells against grp x the width+ double su = 0, sw = 0;+ for (int64_t i0 = 0; i0 + grp <= nq; i0 += grp * 16) {+ std::vector<int32_t> u;+ for (int g2 = 0; g2 < grp; ++g2) {+ const int64_t w = steps[(i0 + g2) * k::kStepCount + k::kStepWidth];+ u.insert(u.end(), ids.begin() + (i0 + g2) * cap, ids.begin() + (i0 + g2) * cap + w);+ sw += (double) w;+ }+ std::sort(u.begin(), u.end());+ su += (double) (std::unique(u.begin(), u.end()) - u.begin());+ }+ std::printf("QA_DUMP overlap: %d-query groups read %.2fx the cells of one query (%.1f%% of %d x)\n", grp,+ su * grp / sw, 100.0 * su / sw, grp);+ }+ }k::QsaAttnPools pl;- if (fmt == 1) { pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs); }+ if (fmt == 2) { pl.k_q4 = up(k4); pl.v_q4 = up(v4); }+ else if (fmt == 1) { pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs); }else { pl.k_pool = up(kh); pl.v_pool = up(vh); }+ // a q4_0 value: block d / 32 of the row, element j = d % 32 in the low nibble of byte j (j < 16), else the high+ // nibble of byte j - 16, minus 8, times the block's scale+ auto q4v = [&](const std::vector<uint8_t>& pool, int64_t row, int64_t d) {+ const uint8_t* blk = pool.data() + row * ROW4 + (d / 32) * B4;+ uint16_t sc;+ std::memcpy(&sc, blk, 2);+ const int j = (int) (d % 32);+ const int code = j < 16 ? (blk[2 + j] & 0x0F) : (blk[2 + j - 16] >> 4);+ return (double) (code - 8) * h2f(sc);+ };pl.page_table = up(table);const int32_t* d_ids = up(ids);const int32_t* d_steps = up(steps);diff --cc src/prefill/gemm.cuindex a35daeb2a,a752371eb..8377ae382--- a/src/prefill/gemm.cu+++ b/src/prefill/gemm.cu@@@ -2,13 -2,13 +2,17 @@@#include "strata/prefill/gemm.hpp"#include "strata/kernels/dequant_bf16.hpp"+ #ifdef STRATA_USE_HIP+ #include "wmma_gemm.h"+ #endif+#include <cublas_v2.h>+#include <cuda_fp16.h>#include <cuda_runtime.h>+#include <algorithm>+#include <atomic>+#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)// The HIP compatibility shim maps CUDA shuffle spellings to Strata helpers.// hipBLASLt's public headers declare native HIP shuffle functions, so keep@@@ -378,93 -387,33 +393,115 @@@ bool Gemm::init(void* stream, int64_t sreturn true;}+#if !defined(__HIPCC__)+// ---- below sm_80: BF16 GEMMs without BF16 tensor cores (PR #655, #540, #395) ----------------------------------------+// Turing and Volta have no BF16 tensor cores: cublasGemmEx on CUDA_R_16BF inputs falls back to a SIMT fp32 kernel+// (magma_sgemmEx), a fifth of a 4K prompt on an RTX 2080 Ti (#655) and ~10% of a V100's prompt (#540). BF16 -> FP16+// is exact for every value inside FP16's normal range (the 7-bit mantissa fits in 10 bits); weights and normalized+// activations sit there. With the FP16 path, the weight is converted once per call and the activations in row+// slices, into the instance's own buffers, and the product runs as the FP16 GEMM (fp32 accumulate) on the tensor+// cores. Finite values beyond FP16's range are clamped to +-65504 (#540) instead of becoming Inf. A beta = 1+// product (STRATA_PREFILL_BF16X2's remainder, ~2^-9 of the original, deep in FP16's subnormal band) keeps cuBLAS.+// Default: on for compute capability 7.0 - 7.4 (Volta: only the experimental STRATA_EXPERIMENTAL_SM60 build runs+// there), OFF for 7.5 (RTX 20 in the ready-made engine: the sums round differently, so it is opt-in until it has+// been gated). STRATA_BF16_TC=1 / =0 turns it on / off on any 7.x card (=2, a test mode: on any card).+// Pascal (6.x) has no tensor cores and cuBLAS has no BF16 GEMM for it (#395, measured NOT_SUPPORTED on a P40): both+// operands are widened to fp32 by an exact shift and the product is cublasSgemm with the same fp32 accumulator.+namespace {+__global__ void bf16_to_f16_kernel(const uint16_t* __restrict__ in, __half* __restrict__ out, int64_t n) {+ const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;+ if (i < n) {+ float f = __uint_as_float((uint32_t) in[i] << 16);+ if (f > 65504.0f && !isinf(f)) f = 65504.0f;+ else if (f < -65504.0f && !isinf(f)) f = -65504.0f;+ out[i] = __float2half_rn(f);+ }+}+void bf16_to_f16(const uint16_t* in, uint16_t* out, int64_t n, cudaStream_t st) {+ if (n <= 0) return;+ bf16_to_f16_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, st>>>(in, reinterpret_cast<__half*>(out), n);+}+#if defined(STRATA_EXPERIMENTAL_SM60) // Pascal runs only the experimental build+__global__ void bf16_to_f32_kernel(const uint16_t* __restrict__ in, float* __restrict__ out, int64_t n) {+ const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;+ if (i < n) out[i] = __uint_as_float((uint32_t) in[i] << 16);+}+void bf16_to_f32(const uint16_t* in, float* out, int64_t n, cudaStream_t st) {+ if (n <= 0) return;+ bf16_to_f32_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, st>>>(in, out, n);+}+#endif+// The current device's compute capability as 10 * major + minor, per device (a layer split can mix cards); 0: not+// known, read as "not an old card" so a failed query keeps the cuBLAS BF16 call.+int current_cc() {+ static std::atomic<int> cc[64] = {};+ int dev = 0;+ if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return 0; }+ int v = cc[dev].load(std::memory_order_relaxed);+ if (v == 0) {+ int major = 0, minor = 0;+ if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess ||+ cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) {+ cudaGetLastError();+ return 0;+ }+ v = 10 * major + minor;+ cc[dev].store(v, std::memory_order_relaxed);+ }+ return v;+}+// 0: cuBLAS's BF16 GEMM, 1: through FP16 (tensor cores), 2: through FP32 (Pascal)+int bf16_path() {+ static const int forced = [] {+ const char* v = std::getenv("STRATA_BF16_TC");+ return v != nullptr && v[0] != '\0' ? std::atoi(v) : -1;+ }();+ const int cc = current_cc();+ if (forced == 2 && cc > 0) return 1; // a test mode: the FP16 path on any card (gemm_bf16_parity on sm_80+)+ if (cc <= 0 || cc >= 80) return 0;+ if (cc < 70) return 2;+ if (forced >= 0) return forced != 0 ? 1 : 0;+ return cc < 75 ? 1 : 0;+}+bool grow(uint16_t*& p, int64_t& have, int64_t want) { // `have`, `want`: 2-byte elements+ if (have >= want) return true;+ if (p) cudaFree(p);+ p = nullptr;+ have = 0;+ if (cudaMalloc((void**) &p, (size_t) want * 2) != cudaSuccess) { cudaGetLastError(); p = nullptr; return false; }+ have = want;+ return true;+}+constexpr int64_t kXSliceElems = 16ll << 20; // 32 MiB of FP16 activations per slice (64 MiB as fp32)+} // namespace+#endif+ bool Gemm::bf16_hcd_exact(const uint16_t* X, int64_t ldx, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K) {+ #if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)+ if (!hipblaslt_state_ || N != 320 || K != 10240 || T < 1) return false;+ const int id = hipblaslt_solution_for(hipblaslt_state_, strata::prefill::hipblaslt::InputType::bf16, T, N, K, N, 0.0f);+ if (id != 1176 && id != 1177) return false;+ return strata_pf_hcdown_exact_bf16(X, ldx, W, Y, T, N, K, stream_);+ #else+ (void) X; (void) ldx; (void) W; (void) Y; (void) T; (void) N; (void) K;+ return false;+ #endif+ }void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy,- float beta) {+ float beta, int64_t ldx) {if (T <= 0 || N <= 0) return;if (ldy <= 0) ldy = N;+ if (ldx <= K) ldx = 0;+ #ifdef STRATA_USE_HIP+ // #313 (opt-in STRATA_WMMA_GEMM=1; STRATA_WMMA_BF16=0 excludes bf16): RDNA3 / RDNA3.5 WMMA dense GEMM, before+ // hipBLASLt; it returns false for shapes it does not take (and off gfx11) and this falls through+ static const bool wmma_on = [] { const char* v = std::getenv("STRATA_WMMA_GEMM"); return v && v[0] != 0 && v[0] != '0'; }();+ static const bool bf16_on = [] { const char* v = std::getenv("STRATA_WMMA_BF16"); return !v || (v[0] != 0 && v[0] != '0'); }();+ if (wmma_on && bf16_on && ldx == 0 && T >= 16 && (beta == 0.0f || beta == 1.0f) &&+ strata_wmma_gemm_bf16(X, W, Y, T, N, K, ldy, beta, stream_)) {+ return;+ }+ #endifconst float alpha = 1.0f;#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::bf16, X, W, Y, T, N, K, ldy,diff --cc src/prefill/kernels.cuindex 4ad67b1ad,f9a20cb5b..38586df66--- a/src/prefill/kernels.cu+++ b/src/prefill/kernels.cu@@@ -5,8 -5,8 +5,9 @@@#include <cuda_fp16.h>#include <cuda_runtime.h>+#include <algorithm>+ #include <algorithm>#include <cfloat>#include <cmath>#include <cstdio>@@@ -434,172 -540,415 +541,578 @@@ __global__ void __launch_bounds__(CB *#pragma unrollfor (int r = 0; r < RPG; ++r) base[r * rs] = s[r];}+#if !defined(__HIPCC__)+// The recurrence with one thread for the three value heads that share a key head (head % HK): column c of heads+// qh, qh + 16 and qh + 32, row group rg. gdn_rec_cols_pipe_kernel spends its time in shared memory, not in+// arithmetic: every thread of a warp needs the same 32 q and k values per token (the k twice), and a warp receives one+// such broadcast value per clock however wide the load. Here every q/k value a thread loads feeds three heads, and a+// token's k row goes into registers once for both of its uses. The inputs come in blocks of GDN_TB tokens, copied to+// shared memory by cp.async while the block before computes (one token ahead is shorter than a load from L2 takes),+// and the two cross-row-group sums have their own arrays, so a token needs 2 __syncthreads instead of 5: the second+// one of a token orders every read of rkv before the next token's writes, the next token's first one every read of ro+// before the writes after it. 64 blocks instead of 192. Per value head and column the same arithmetic in the same+// order: the same bits (src/prefill/gdn_rec_parity.cu checks them and times the variants: 1.41x on a 4080 Super).+// sm_80+ cards that hold its 64 blocks at once (gdn_keyhead_ok); STRATA_GDN_KEYHEAD=0: gdn_rec_cols_pipe_kernel.+#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800+#define STRATA_GDN_CP_ASYNC 0 // Turing builds: plain copies (never launched there, see gdn_keyhead_ok)+#else+#define STRATA_GDN_CP_ASYNC 1+#endif+__device__ __forceinline__ void gdn_cp4(float* smem, const float* gmem) {+#if STRATA_GDN_CP_ASYNC+ asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem));+#else+ *smem = *gmem;+#endif+}+__device__ __forceinline__ void gdn_cp16(float* smem, const float* gmem) {+#if STRATA_GDN_CP_ASYNC+ asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem));+#else+ *reinterpret_cast<float4*>(smem) = *reinterpret_cast<const float4*>(gmem);+#endif+}+__device__ __forceinline__ void gdn_cp_commit() {+#if STRATA_GDN_CP_ASYNC+ asm volatile("cp.async.commit_group;\n" ::);+#endif+}+__device__ __forceinline__ void gdn_cp_wait_prev() { // every group but the newest has landed+#if STRATA_GDN_CP_ASYNC+ asm volatile("cp.async.wait_group 1;\n" ::);+#endif+}+constexpr int GDN_TB = 8, VPK = HV / HK; // tokens per staged block, value heads per key head+__global__ void __launch_bounds__(CB * RG) gdn_rec_kh_kernel(float* __restrict__ state, const float* __restrict__ h,+ const float* __restrict__ gate,+ const float* __restrict__ beta,+ float* __restrict__ oc_out, int64_t T) {+ constexpr int TB = GDN_TB, NT = CB * RG, QKP = S / 4, VP = CB / 4; // threads, 16-byte pieces of a q/k row, of v+ __shared__ __align__(16) float sq[2][TB][S];+ __shared__ __align__(16) float sk[2][TB][S];+ __shared__ __align__(16) float sv[2][TB][VPK][CB];+ __shared__ float sg[2][TB][VPK], sb[2][TB][VPK], rkv[VPK][RG][CB], ro[VPK][RG][CB];+ const int qh = blockIdx.x / NCB, cb = blockIdx.x % NCB;+ const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c;+ float s[VPK][RPG];+ const size_t rs = (size_t) HV * S;+#pragma unroll+ for (int j = 0; j < VPK; ++j) {+ const float* base = state + ((size_t) (rg * RPG) * HV + qh + j * HK) * S + col;+#pragma unroll+ for (int r = 0; r < RPG; ++r) s[j][r] = base[r * rs];+ }+ const int64_t nblk = (T + TB - 1) / TB;+ auto stage = [&](int64_t k) { // tokens [k * TB, k * TB + TB) into buffer k & 1+ const int bb = (int) (k & 1);+ const int64_t t0 = k * TB;+ for (int p = tid; p < TB * 2 * QKP; p += NT) {+ const int i = p / (2 * QKP), w = p % (2 * QKP), isk = w / QKP, jj = (w % QKP) * 4;+ if (t0 + i < T)+ gdn_cp16(isk ? &sk[bb][i][jj] : &sq[bb][i][jj], h + (t0 + i) * C + (isk ? HK * S : 0) + qh * S + jj);+ }+ for (int p = tid; p < TB * VPK * VP; p += NT) {+ const int i = p / (VPK * VP), w = p % (VPK * VP), j = w / VP, jj = (w % VP) * 4;+ if (t0 + i < T)+ gdn_cp16(&sv[bb][i][j][jj], h + (t0 + i) * C + 2 * HK * S + (qh + j * HK) * S + cb * CB + jj);+ }+ for (int p = tid; p < 2 * TB * VPK; p += NT) {+ const int isb = p / (TB * VPK), w = p % (TB * VPK), i = w / VPK, j = w % VPK;+ if (t0 + i < T)+ gdn_cp4(isb ? &sb[bb][i][j] : &sg[bb][i][j], (isb ? beta : gate) + (t0 + i) * HV + qh + j * HK);+ }+ };+ if (nblk > 0) stage(0);+ gdn_cp_commit();+ for (int64_t k = 0; k < nblk; ++k) {+ // buffer (k + 1) & 1 was read by block k - 1, whose last token's second __syncthreads every thread has passed+ if (k + 1 < nblk) stage(k + 1);+ gdn_cp_commit();+ gdn_cp_wait_prev();+ __syncthreads();+ const int bb = (int) (k & 1);+ const int n = (int) ((T - k * TB) < TB ? (T - k * TB) : TB);+ for (int i = 0; i < n; ++i) {+ const int64_t t = k * TB + i;+ float kc[RPG];+#pragma unroll+ for (int r = 0; r < RPG; ++r) kc[r] = sk[bb][i][rg * RPG + r];+ float g[VPK], kv[VPK], delta[VPK], o[VPK];+#pragma unroll+ for (int j = 0; j < VPK; ++j) { g[j] = __expf(sg[bb][i][j]); kv[j] = 0.0f; o[j] = 0.0f; }+#pragma unroll+ for (int r = 0; r < RPG; ++r)+#pragma unroll+ for (int j = 0; j < VPK; ++j) kv[j] = fmaf(s[j][r], kc[r], kv[j]);+#pragma unroll+ for (int j = 0; j < VPK; ++j) rkv[j][rg][c] = kv[j];+ __syncthreads();+#pragma unroll+ for (int j = 0; j < VPK; ++j) {+ const float kv_col = rkv[j][0][c] + rkv[j][1][c] + rkv[j][2][c] + rkv[j][3][c];+ delta[j] = (sv[bb][i][j][c] - g[j] * kv_col) * sb[bb][i][j];+ }+#pragma unroll+ for (int r = 0; r < RPG; ++r) {+ const float qr = sq[bb][i][rg * RPG + r];+#pragma unroll+ for (int j = 0; j < VPK; ++j) {+ s[j][r] = fmaf(g[j], s[j][r], kc[r] * delta[j]);+ o[j] = fmaf(s[j][r], qr, o[j]);+ }+ }+#pragma unroll+ for (int j = 0; j < VPK; ++j) ro[j][rg][c] = o[j];+ __syncthreads();+ if (rg < VPK) // row group j writes head j's output+ oc_out[t * HV * S + (qh + rg * HK) * S + col] =+ (ro[rg][0][c] + ro[rg][1][c] + ro[rg][2][c] + ro[rg][3][c]) * rsqrtf((float) S);+ }+ }+#pragma unroll+ for (int j = 0; j < VPK; ++j) {+ float* base = state + ((size_t) (rg * RPG) * HV + qh + j * HK) * S + col;+#pragma unroll+ for (int r = 0; r < RPG; ++r) base[r * rs] = s[j][r];+ }+}+// gdn_rec_kh_kernel where it pays: a CUDA card with cp.async (sm_80+) that holds all 64 of its blocks at once (each+// walks the whole chunk, so blocks left for a second wave would double the time). The busiest SM sets the pace: from+// 64 SMs up this kernel has one block per SM, below that two on some SMs, while the kernel before has ceil(192 / SMs).+// With the engine's grids on fewer SMs (gdn_rec_parity --bench), on a 4080 SUPER / a 3090: 1.40-1.42x / 1.28-1.29x at+// 64 SMs and more, 1.02-1.04x / 1.03-1.06x at 48 to 63 (two blocks against four: a draw, slower on neither),+// 1.28-1.31x / 1.28-1.30x at 39 to 47, 1.53-1.57x / 1.54-1.55x at 32 to 38. Per call, from the current device (a+// layer split can mix cards).+bool gdn_keyhead_ok() {+ static const bool off = [] { const char* v = std::getenv("STRATA_GDN_KEYHEAD"); return v != nullptr && std::atoi(v) == 0; }();+ if (off) return false;+ static int known[64] = {}; // per device: 0 not asked yet, 1 yes, 2 no+ int dev = 0;+ if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }+ if (known[dev] == 0) {+ int major = 0, sms = 0, per_sm = 0;+ const bool yes = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&+ cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev) == cudaSuccess && major >= 8 &&+ cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm, gdn_rec_kh_kernel, CB * RG, 0) ==+ cudaSuccess &&+ (int64_t) per_sm * sms >= (int64_t) HK * NCB;+ if (!yes) cudaGetLastError();+ known[dev] = yes ? 1 : 2;+ }+ return known[dev] == 1;+}+#endif- // the output norm over a head's 128 columns, into the FP16 copy the out projection reads (the FP32 output before the- // norm stays in its scratch buffer)++#if defined(__HIPCC__) // the Aurora (gfx11) recurrence kernels: AMD builds only+ // Aurora (S23): the recurrence with the column-split grid of gdn_rec_cols_pipe_kernel (four 32-column blocks per value+ // head) but FOUR LANES per column, lane g holding the column's state rows 32g .. 32g + 31 in registers - exactly the+ // row group the old kernel's thread (col, rg = g) held - so a token needs no __syncthreads: the four kv / o partials+ // meet through wave shuffles and are added in the old order red[0] + red[1] + red[2] + red[3] (the same bits;+ // tests/hip/gdn_rec_head.cpp). The q/k rows, v, gate and beta are staged in LDS HT tokens at a time, the next chunk+ // loaded into registers while this one computes, and a token's k and q rows are read into registers before its+ // products (one LDS latency per token, not one per load). The old kernels took ~4 barriers per token and ~3.5 us+ // per token and layer on the Radeon 8060S; the output norm runs after it in gdn_out_norm_warp_kernel.+ // STRATA_GDN_HEAD=0: the old kernels.+ constexpr int HT = 4; // tokens per staged chunk (LDS ~10 KB: all 192 blocks resident)+ constexpr int QCB = 32; // columns per block+ constexpr int QTH = QCB * 4; // threads per block: 4 lanes per column+ constexpr int QRS = 36; // staged row-group stride (32 rows + 4 pad: the 4 groups' reads+ // land in different LDS banks)+ constexpr int QPF = HT * 2 * S / 4 / QTH; // float4 of q/k each thread prefetches per chunk (2)+ __global__ void __launch_bounds__(QTH) gdn_rec_quad_kernel(float* __restrict__ state, const float* __restrict__ h,+ const float* __restrict__ gate, const float* __restrict__ beta,+ float* __restrict__ oc_out, int64_t T) {+ __shared__ __align__(16) float sqk[2][HT][2][4 * QRS]; // [buffer][token][q | k][group][row (padded)]+ __shared__ float sgb[2][2][HT]; // [buffer][gate | beta][token]+ __shared__ float sv[2][HT][QCB]; // [buffer][token][column] v+ const int head = blockIdx.x / (S / QCB), cb = blockIdx.x % (S / QCB);+ const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;+ const int g = lane >> 3, cl = wave * 8 + (lane & 7), col = cb * QCB + cl; // row group, column in block / head+ const int qh = head % HK;+ float s[32];+ {+ const float* base = state + ((size_t) (g * 32) * HV + head) * S + col;+ #pragma unroll+ for (int r = 0; r < 32; ++r) s[r] = base[(size_t) r * HV * S];+ }+ float4 pf[QPF];+ float pv[HT], pgb = 0.0f;+ // chunk c's inputs into registers: q/k (float4 i of the chunk's [token][q|k][S/4] block), the column's v (lanes of+ // group 0) and gate (threads 0..HT-1) / beta (HT..2HT-1) of token `tid % HT`+ auto fetch = [&](int64_t c) {+ const int64_t t0 = c * HT;+ #pragma unroll+ for (int u = 0; u < QPF; ++u) {+ const int i = tid + u * QTH;+ const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);+ const int64_t t = t0 + tt;+ pf[u] = t < T ? *reinterpret_cast<const float4*>(h + t * C + part * HK * S + qh * S + r4 * 4)+ : make_float4(0.f, 0.f, 0.f, 0.f);+ }+ if (g == 0) {+ #pragma unroll+ for (int tt = 0; tt < HT; ++tt) {+ const int64_t t = t0 + tt;+ pv[tt] = t < T ? h[t * C + 2 * HK * S + head * S + col] : 0.0f;+ }+ }+ if (tid < 2 * HT) {+ const int64_t t = t0 + (tid % HT);+ pgb = t < T ? (tid < HT ? gate : beta)[t * HV + head] : 0.0f;+ }+ };+ const float rs_s = rsqrtf((float) S);+ const int src0 = lane & 7; // lane of group 0 for this column; group j is src0 + 8 j+ const int64_t nch = (T + HT - 1) / HT;+ if (nch > 0) fetch(0);+ for (int64_t c = 0; c < nch; ++c) {+ const int b = (int) (c & 1);+ if (g == 0) {+ #pragma unroll+ for (int tt = 0; tt < HT; ++tt) sv[b][tt][cl] = pv[tt];+ }+ #pragma unroll+ for (int u = 0; u < QPF; ++u) {+ const int i = tid + u * QTH;+ const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);+ const int row = r4 * 4;+ *reinterpret_cast<float4*>(&sqk[b][tt][part][(row >> 5) * QRS + (row & 31)]) = pf[u];+ }+ if (tid < 2 * HT) sgb[b][tid / HT][tid % HT] = pgb;+ __syncthreads(); // chunk c staged (buffer b was last read two chunks ago)+ if (c + 1 < nch) fetch(c + 1);+ const int64_t t0 = c * HT;+ const int nt = (int) (T - t0 < HT ? T - t0 : HT);+ for (int tt = 0; tt < nt; ++tt) {+ float k[32], q[32];+ {+ const float4* k4 = reinterpret_cast<const float4*>(&sqk[b][tt][1][g * QRS]);+ const float4* q4 = reinterpret_cast<const float4*>(&sqk[b][tt][0][g * QRS]);+ #pragma unroll+ for (int j = 0; j < 8; ++j) {+ const float4 kk = k4[j], qq = q4[j];+ k[4 * j] = kk.x; k[4 * j + 1] = kk.y; k[4 * j + 2] = kk.z; k[4 * j + 3] = kk.w;+ q[4 * j] = qq.x; q[4 * j + 1] = qq.y; q[4 * j + 2] = qq.z; q[4 * j + 3] = qq.w;+ }+ }+ const float g_exp = __expf(sgb[b][0][tt]);+ float kv = 0.0f;+ #pragma unroll+ for (int r = 0; r < 32; ++r) kv = fmaf(s[r], k[r], kv);+ const float p0 = __shfl_sync(0xffffffffu, kv, src0), p1 = __shfl_sync(0xffffffffu, kv, src0 + 8),+ p2 = __shfl_sync(0xffffffffu, kv, src0 + 16), p3 = __shfl_sync(0xffffffffu, kv, src0 + 24);+ const float kv_col = p0 + p1 + p2 + p3;+ const float cvt = sv[b][tt][cl], cbt = sgb[b][1][tt];+ const float delta = (cvt - g_exp * kv_col) * cbt;+ float o = 0.0f;+ #pragma unroll+ for (int r = 0; r < 32; ++r) {+ s[r] = fmaf(g_exp, s[r], k[r] * delta);+ o = fmaf(s[r], q[r], o);+ }+ const float o0 = __shfl_sync(0xffffffffu, o, src0), o1 = __shfl_sync(0xffffffffu, o, src0 + 8),+ o2 = __shfl_sync(0xffffffffu, o, src0 + 16), o3 = __shfl_sync(0xffffffffu, o, src0 + 24);+ if (g == 0) oc_out[(t0 + tt) * HV * S + head * S + col] = (o0 + o1 + o2 + o3) * rs_s;+ }+ }+ {+ float* base = state + ((size_t) (g * 32) * HV + head) * S + col;+ #pragma unroll+ for (int r = 0; r < 32; ++r) base[(size_t) r * HV * S] = s[r];+ }+ }+ // Aurora (S23, opt-in STRATA_GDN_PP=1): gdn_rec_quad_kernel with the same arithmetic in the same order, two changes in+ // how it is compiled. (1) The VGPR count: the 32 state-row addresses of the first loads were kept live across the+ // whole walk to be reused by the final stores (64 VGPRs, 196 in all = 7 waves a SIMD for the 192 blocks of 4 waves+ // that need 9.6): the stores' lane offset goes through an asm so the addresses are made again, 133 VGPRs, all blocks+ // resident. (2) A full chunk's four tokens run with the state alternating between two register sets (the update+ // writes the other set), so the compiler emits no 32 register copies after the update.+ __global__ void __launch_bounds__(QTH) gdn_rec_quad_pp_kernel(float* __restrict__ state, const float* __restrict__ h,+ const float* __restrict__ gate, const float* __restrict__ beta,+ float* __restrict__ oc_out, int64_t T) {+ __shared__ __align__(16) float sqk[2][HT][2][4 * QRS]; // [buffer][token][q | k][group][row (padded)]+ __shared__ float sgb[2][2][HT]; // [buffer][gate | beta][token]+ __shared__ float sv[2][HT][QCB]; // [buffer][token][column] v+ const int head = blockIdx.x / (S / QCB), cb = blockIdx.x % (S / QCB);+ const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;+ const int g = lane >> 3, cl = wave * 8 + (lane & 7), col = cb * QCB + cl; // row group, column in block / head+ const int qh = head % HK;+ float s[32];+ {+ const float* sb = state + (size_t) head * S;+ const uint32_t voff = (uint32_t) ((g * 32) * HV * S + col);+ #pragma unroll+ for (int r = 0; r < 32; ++r) s[r] = sb[(size_t) r * HV * S + voff];+ }+ float4 pf[QPF];+ float pv[HT], pgb = 0.0f;+ // chunk c's inputs into registers: q/k (float4 i of the chunk's [token][q|k][S/4] block), the column's v (lanes of+ // group 0) and gate (threads 0..HT-1) / beta (HT..2HT-1) of token `tid % HT`+ auto fetch = [&](int64_t c) {+ const int64_t t0 = c * HT;+ #pragma unroll+ for (int u = 0; u < QPF; ++u) {+ const int i = tid + u * QTH;+ const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);+ const int64_t t = t0 + tt;+ pf[u] = t < T ? *reinterpret_cast<const float4*>(h + t * C + part * HK * S + qh * S + r4 * 4)+ : make_float4(0.f, 0.f, 0.f, 0.f);+ }+ if (g == 0) {+ #pragma unroll+ for (int tt = 0; tt < HT; ++tt) {+ const int64_t t = t0 + tt;+ pv[tt] = t < T ? h[t * C + 2 * HK * S + head * S + col] : 0.0f;+ }+ }+ if (tid < 2 * HT) {+ const int64_t t = t0 + (tid % HT);+ pgb = t < T ? (tid < HT ? gate : beta)[t * HV + head] : 0.0f;+ }+ };+ const float rs_s = rsqrtf((float) S);+ const int src0 = lane & 7; // lane of group 0 for this column; group j is src0 + 8 j+ const int64_t nch = (T + HT - 1) / HT;+ if (nch > 0) fetch(0);+ for (int64_t c = 0; c < nch; ++c) {+ const int b = (int) (c & 1);+ if (g == 0) {+ #pragma unroll+ for (int tt = 0; tt < HT; ++tt) sv[b][tt][cl] = pv[tt];+ }+ #pragma unroll+ for (int u = 0; u < QPF; ++u) {+ const int i = tid + u * QTH;+ const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);+ const int row = r4 * 4;+ *reinterpret_cast<float4*>(&sqk[b][tt][part][(row >> 5) * QRS + (row & 31)]) = pf[u];+ }+ if (tid < 2 * HT) sgb[b][tid / HT][tid % HT] = pgb;+ __syncthreads(); // chunk c staged (buffer b was last read two chunks ago)+ if (c + 1 < nch) fetch(c + 1);+ const int64_t t0 = c * HT;+ const int nt = (int) (T - t0 < HT ? T - t0 : HT);+ auto token = [&](int tt, float (&sin)[32], float (&sout)[32]) {+ float k[32], q[32];+ {+ const float4* k4 = reinterpret_cast<const float4*>(&sqk[b][tt][1][g * QRS]);+ const float4* q4 = reinterpret_cast<const float4*>(&sqk[b][tt][0][g * QRS]);+ #pragma unroll+ for (int j = 0; j < 8; ++j) {+ const float4 kk = k4[j], qq = q4[j];+ k[4 * j] = kk.x; k[4 * j + 1] = kk.y; k[4 * j + 2] = kk.z; k[4 * j + 3] = kk.w;+ q[4 * j] = qq.x; q[4 * j + 1] = qq.y; q[4 * j + 2] = qq.z; q[4 * j + 3] = qq.w;+ }+ }+ const float g_exp = __expf(sgb[b][0][tt]);+ float kv = 0.0f;+ #pragma unroll+ for (int r = 0; r < 32; ++r) kv = fmaf(sin[r], k[r], kv);+ const float p0 = __shfl_sync(0xffffffffu, kv, src0), p1 = __shfl_sync(0xffffffffu, kv, src0 + 8),+ p2 = __shfl_sync(0xffffffffu, kv, src0 + 16), p3 = __shfl_sync(0xffffffffu, kv, src0 + 24);+ const float kv_col = p0 + p1 + p2 + p3;+ const float cvt = sv[b][tt][cl], cbt = sgb[b][1][tt];+ const float delta = (cvt - g_exp * kv_col) * cbt;+ float o = 0.0f;+ #pragma unroll+ for (int r = 0; r < 32; ++r) {+ sout[r] = fmaf(g_exp, sin[r], k[r] * delta);+ o = fmaf(sout[r], q[r], o);+ }+ const float o0 = __shfl_sync(0xffffffffu, o, src0), o1 = __shfl_sync(0xffffffffu, o, src0 + 8),+ o2 = __shfl_sync(0xffffffffu, o, src0 + 16), o3 = __shfl_sync(0xffffffffu, o, src0 + 24);+ if (g == 0) oc_out[(t0 + tt) * HV * S + head * S + col] = (o0 + o1 + o2 + o3) * rs_s;+ };+ if (nt == HT) { // the state alternates between two register sets: no copy after the update+ float s2[32];+ token(0, s, s2);+ token(1, s2, s);+ token(2, s, s2);+ token(3, s2, s);+ } else {+ for (int tt = 0; tt < nt; ++tt) {+ float s2[32];+ token(tt, s, s2);+ #pragma unroll+ for (int r = 0; r < 32; ++r) s[r] = s2[r];+ }+ }+ }+ {+ float* sb = state + (size_t) head * S;+ uint32_t voff = (uint32_t) ((g * 32) * HV * S + col);+ asm volatile("" : "+v"(voff)); // (so the loads' 32 addresses are not kept alive across the whole loop)+ #pragma unroll+ for (int r = 0; r < 32; ++r) sb[(size_t) r * HV * S + voff] = s[r];+ }+ }++ // Aurora (S23, opt-in STRATA_GDN_PP=2): gdn_rec_quad_kernel with two columns per lane (a wave: 4 row groups x 8 lanes x+ // 2 columns = 16 columns; a block of 4 waves 64 columns, 96 blocks). A lane's two columns share the k / q rows it+ // reads from shared memory (half the LDS reads and shuffles per column, the kernel's limit) and give each wave two+ // independent dependency chains; the 384 waves fit in one round at 230 VGPRs. Per column the same arithmetic in+ // the same order (the same bits as gdn_rec_quad_kernel). The store of the state goes through an asm for the reason+ // given at gdn_rec_quad_pp_kernel.++ // ---- C2: two columns per lane (a wave: 4 row groups x 8 lanes x 2 columns = 16 columns; a block of 4 waves 64+ // columns). A lane's two columns share the k / q rows it reads from LDS (half the LDS reads and shuffles per column+ // and two independent dependency chains in each wave). Per column the same arithmetic in the same order.+ constexpr int C2CB = 64; // columns per block+ constexpr int C2PF = HT * 2 * S / 4 / QTH; // float4 of q/k each thread prefetches per chunk (2)+ __global__ void __launch_bounds__(QTH) gdn_rec_quad2c_kernel(float* __restrict__ state, const float* __restrict__ h,+ const float* __restrict__ gate, const float* __restrict__ beta,+ float* __restrict__ oc_out, int64_t T) {+ __shared__ __align__(16) float sqk[2][HT][2][4 * QRS];+ __shared__ float sgb[2][2][HT];+ __shared__ float sv[2][HT][C2CB];+ const int head = blockIdx.x / (S / C2CB), cb = blockIdx.x % (S / C2CB);+ const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;+ const int g = lane >> 3, cl0 = wave * 16 + (lane & 7), cl1 = cl0 + 8; // the lane's two columns in the block+ const int col0 = cb * C2CB + cl0, col1 = cb * C2CB + cl1;+ const int qh = head % HK;+ float s0[32], s1[32];+ {+ const float* sb = state + (size_t) head * S;+ const uint32_t voff = (uint32_t) ((g * 32) * HV * S);+ #pragma unroll+ for (int r = 0; r < 32; ++r) { s0[r] = sb[(size_t) r * HV * S + voff + col0]; s1[r] = sb[(size_t) r * HV * S + voff + col1]; }+ }+ float4 pf[C2PF];+ float pv[2][HT], pgb = 0.0f;+ auto fetch = [&](int64_t c) {+ const int64_t t0 = c * HT;+ #pragma unroll+ for (int u = 0; u < C2PF; ++u) {+ const int i = tid + u * QTH;+ const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);+ const int64_t t = t0 + tt;+ pf[u] = t < T ? *reinterpret_cast<const float4*>(h + t * C + part * HK * S + qh * S + r4 * 4)+ : make_float4(0.f, 0.f, 0.f, 0.f);+ }+ if (g == 0) {+ #pragma unroll+ for (int tt = 0; tt < HT; ++tt) {+ const int64_t t = t0 + tt;+ pv[0][tt] = t < T ? h[t * C + 2 * HK * S + head * S + col0] : 0.0f;+ pv[1][tt] = t < T ? h[t * C + 2 * HK * S + head * S + col1] : 0.0f;+ }+ }+ if (tid < 2 * HT) {+ const int64_t t = t0 + (tid % HT);+ pgb = t < T ? (tid < HT ? gate : beta)[t * HV + head] : 0.0f;+ }+ };+ const float rs_s = rsqrtf((float) S);+ const int src0 = lane & 7;+ const int64_t nch = (T + HT - 1) / HT;+ if (nch > 0) fetch(0);+ for (int64_t c = 0; c < nch; ++c) {+ const int b = (int) (c & 1);+ if (g == 0) {+ #pragma unroll+ for (int tt = 0; tt < HT; ++tt) { sv[b][tt][cl0] = pv[0][tt]; sv[b][tt][cl1] = pv[1][tt]; }+ }+ #pragma unroll+ for (int u = 0; u < C2PF; ++u) {+ const int i = tid + u * QTH;+ const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);+ const int row = r4 * 4;+ *reinterpret_cast<float4*>(&sqk[b][tt][part][(row >> 5) * QRS + (row & 31)]) = pf[u];+ }+ if (tid < 2 * HT) sgb[b][tid / HT][tid % HT] = pgb;+ __syncthreads();+ if (c + 1 < nch) fetch(c + 1);+ const int64_t t0 = c * HT;+ const int nt = (int) (T - t0 < HT ? T - t0 : HT);+ for (int tt = 0; tt < nt; ++tt) {+ float k[32], q[32];+ {+ const float4* k4 = reinterpret_cast<const float4*>(&sqk[b][tt][1][g * QRS]);+ const float4* q4 = reinterpret_cast<const float4*>(&sqk[b][tt][0][g * QRS]);+ #pragma unroll+ for (int j = 0; j < 8; ++j) {+ const float4 kk = k4[j], qq = q4[j];+ k[4 * j] = kk.x; k[4 * j + 1] = kk.y; k[4 * j + 2] = kk.z; k[4 * j + 3] = kk.w;+ q[4 * j] = qq.x; q[4 * j + 1] = qq.y; q[4 * j + 2] = qq.z; q[4 * j + 3] = qq.w;+ }+ }+ const float g_exp = __expf(sgb[b][0][tt]);+ float kv0 = 0.0f, kv1 = 0.0f;+ #pragma unroll+ for (int r = 0; r < 32; ++r) { kv0 = fmaf(s0[r], k[r], kv0); kv1 = fmaf(s1[r], k[r], kv1); }+ const float a0 = __shfl_sync(0xffffffffu, kv0, src0), a1 = __shfl_sync(0xffffffffu, kv0, src0 + 8),+ a2 = __shfl_sync(0xffffffffu, kv0, src0 + 16), a3 = __shfl_sync(0xffffffffu, kv0, src0 + 24);+ const float b0 = __shfl_sync(0xffffffffu, kv1, src0), b1 = __shfl_sync(0xffffffffu, kv1, src0 + 8),+ b2 = __shfl_sync(0xffffffffu, kv1, src0 + 16), b3 = __shfl_sync(0xffffffffu, kv1, src0 + 24);+ const float kvc0 = a0 + a1 + a2 + a3, kvc1 = b0 + b1 + b2 + b3;+ const float cbt = sgb[b][1][tt];+ const float d0 = (sv[b][tt][cl0] - g_exp * kvc0) * cbt, d1 = (sv[b][tt][cl1] - g_exp * kvc1) * cbt;+ float o0 = 0.0f, o1 = 0.0f;+ #pragma unroll+ for (int r = 0; r < 32; ++r) {+ s0[r] = fmaf(g_exp, s0[r], k[r] * d0);+ s1[r] = fmaf(g_exp, s1[r], k[r] * d1);+ o0 = fmaf(s0[r], q[r], o0);+ o1 = fmaf(s1[r], q[r], o1);+ }+ const float x0 = __shfl_sync(0xffffffffu, o0, src0), x1 = __shfl_sync(0xffffffffu, o0, src0 + 8),+ x2 = __shfl_sync(0xffffffffu, o0, src0 + 16), x3 = __shfl_sync(0xffffffffu, o0, src0 + 24);+ const float y0 = __shfl_sync(0xffffffffu, o1, src0), y1 = __shfl_sync(0xffffffffu, o1, src0 + 8),+ y2 = __shfl_sync(0xffffffffu, o1, src0 + 16), y3 = __shfl_sync(0xffffffffu, o1, src0 + 24);+ if (g == 0) {+ oc_out[(t0 + tt) * HV * S + head * S + col0] = (x0 + x1 + x2 + x3) * rs_s;+ oc_out[(t0 + tt) * HV * S + head * S + col1] = (y0 + y1 + y2 + y3) * rs_s;+ }+ }+ }+ {+ float* sb = state + (size_t) head * S;+ uint32_t voff = (uint32_t) ((g * 32) * HV * S);+ asm volatile("" : "+v"(voff));+ #pragma unroll+ for (int r = 0; r < 32; ++r) { sb[(size_t) r * HV * S + voff + col0] = s0[r]; sb[(size_t) r * HV * S + voff + col1] = s1[r]; }+ }+ }++ // gdn_out_norm_kernel's body over a grid-stride walk of the (token, head) rows: the old kernel launched a 128-thread+ // block per row (T * 48 blocks; ~45 GB/s on the 8060S). The same code per row (the same compiled arithmetic: a wave+ // per row with four values per lane rounded differently in its first xor step).+ template <bool WY>+ __global__ void __launch_bounds__(S) gdn_out_norm_loop_kernel(const float* __restrict__ z, const float* __restrict__ gamma,+ float eps, float* __restrict__ y, uint16_t* __restrict__ y16,+ int64_t rows, int64_t ld16) {+ __shared__ float wsum[4];+ const int col = threadIdx.x;+ for (int64_t row = blockIdx.x; row < rows; row += gridDim.x) {+ const size_t at = (size_t) row * S + col;+ const float oc = y[at];+ // (warp_sum as the compiler built it: the first xor step adds the partner's rounded square to an unrounded own+ // one, an fma; spelled out so neither instance's contraction can differ)+ float sp = __fmaf_rn(oc, oc, __shfl_xor_sync(0xffffffffu, __fmul_rn(oc, oc), 16));+ #pragma unroll+ for (int o = 8; o > 0; o >>= 1) sp = __fadd_rn(sp, __shfl_xor_sync(0xffffffffu, sp, o));+ __syncthreads(); // the previous row's sums are read+ if ((col & 31) == 0) wsum[col >> 5] = sp;+ __syncthreads();+ const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];+ const float bp = oc * rsqrtf(ss / (float) S + eps) * gamma[col], sg = sigm(z[at]);+ const size_t o16 = (size_t) (row / HV) * ld16 + (size_t) (row % HV) * S + col;+ if constexpr (WY) {+ const float v = bp * sg;+ y[at] = v;+ y16[o16] = hf(v);+ } else {+ // STRATA_GDN_NOY=1: nothing reads the FP32 result (403 MB per 16K chunk). The FP16 value is what the+ // compiler makes of hf(v) next to the store: v_fma_mixlo_f16, the product rounded to FP16 once+ unsigned r;+ asm("v_fma_mixlo_f16 %0, %1, %2, 0" : "=v"(r) : "v"(sg), "v"(bp));+ y16[o16] = (uint16_t) r;+ }+ }+ }++#endif // __HIPCC____global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma,- float eps, const float* __restrict__ y,- uint16_t* __restrict__ y16) {+ float eps, float* __restrict__ y, uint16_t* __restrict__ y16,+ int64_t ld16) {__shared__ float wsum[4];const int64_t t = blockIdx.x;const int head = blockIdx.y, col = threadIdx.x;@@@ -610,7 -959,8 +1123,7 @@@__syncthreads();const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * sigm(z[t * HV * S + head * S + col]);- y16[at] = hf(v);- y[at] = v;- y16[(size_t) t * ld16 + (size_t) head * S + col] = hf(v);++ y16[(size_t) t * ld16 + (size_t) head * S + col] = hf(v); // (the FP32 normalized value is not stored: nothing reads it)}// ---------------------------------------------------------------- MoE@@@ -905,18 -1389,54 +1552,63 @@@ void gdn_conv(float* history, const flogdn_l2_kernel<<<dim3(2 * HK, (unsigned) T), S, 0, (cudaStream_t) stream>>>(h, eps);check("gdn_conv");}- void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z,- const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream) {+ void gdn_recurrence_variant(int variant, float* state, const float* h, const float* gate, const float* beta,+ const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T,+ void* stream, int64_t ld16) {+ if (ld16 <= 0) ld16 = (int64_t) HV * S;++#if defined(__HIPCC__)+ if (variant == 3) { // diagnostics: the quad recurrence + the old norm kernel+ if (T > 0) {+ gdn_rec_quad_kernel<<<HV * (S / QCB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);+ gdn_out_norm_kernel<<<dim3((unsigned) T, HV), S, 0, (cudaStream_t) stream>>>(z, gamma, eps, y, y16, ld16);+ }+ return;+ }+ if (variant == 4 || variant == 5) { // diagnostics: the quad recurrence's PP / two-column kernels + the norm+ if (T > 0) {+ if (variant == 5)+ gdn_rec_quad2c_kernel<<<HV * (S / C2CB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);+ else+ gdn_rec_quad_pp_kernel<<<HV * (S / QCB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);+ gdn_out_norm_loop_kernel<true><<<(unsigned) std::min<int64_t>(T * HV, 4096), S, 0, (cudaStream_t) stream>>>(+ z, gamma, eps, y, y16, T * HV, ld16);+ }+ check("gdn_recurrence (quad pp)");+ return;+ }+ if (variant == 1) {+ if (T > 0) {+ static const int pp = [] { const char* v = std::getenv("STRATA_GDN_PP"); return v ? std::atoi(v) : 0; }();+ if (pp == 2)+ gdn_rec_quad2c_kernel<<<HV * (S / C2CB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);+ else if (pp)+ gdn_rec_quad_pp_kernel<<<HV * (S / QCB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);+ else+ gdn_rec_quad_kernel<<<HV * (S / QCB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);+ static const bool noy = [] { const char* v = std::getenv("STRATA_GDN_NOY"); return v && std::atoi(v) != 0; }();+ if (noy)+ gdn_out_norm_loop_kernel<false><<<(unsigned) std::min<int64_t>(T * HV, 4096), S, 0, (cudaStream_t) stream>>>(+ z, gamma, eps, y, y16, T * HV, ld16);+ else+ gdn_out_norm_loop_kernel<true><<<(unsigned) std::min<int64_t>(T * HV, 4096), S, 0, (cudaStream_t) stream>>>(+ z, gamma, eps, y, y16, T * HV, ld16);+ }+ check("gdn_recurrence (quad)");+ return;+ }++#else++ (void) variant; // the quad recurrence kernels are AMD-only++#endifstatic const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr; // the one-block-per-head kernel (A/B)- if (serial || T <= 0) {- gdn_rec_kernel<<<HV, dim3(S, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, z, gamma, eps, y, y16, T);+ if (serial || T <= 0 || variant == 2) {+ gdn_rec_kernel<<<HV, dim3(S, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, z, gamma, eps, y, y16, T, ld16);} else {static const bool pipe = [] { const char* v = std::getenv("STRATA_GDN_PIPELINE"); return v == nullptr || std::atoi(v) != 0; }();+#if !defined(__HIPCC__)+ if (pipe && gdn_keyhead_ok()) // the value heads of a key head in one thread (same bits)+ gdn_rec_kh_kernel<<<HK * NCB, dim3(CB, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);+ else+#endifif (pipe) // the software-pipelined loads (same bits)gdn_rec_cols_pipe_kernel<<<HV * NCB, dim3(CB, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);else@@@ -925,6 -1445,14 +1617,15 @@@}check("gdn_recurrence");}+ void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z,+ const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream, int64_t ld16) {+ // Aurora (S23): four lanes per column + the grid-stride norm, the same bits (tests/hip/gdn_rec_head.cpp);- // STRATA_GDN_HEAD=0 (or STRATA_GDN_REC_HEADS) keeps the earlier kernels- static const bool head = [] { const char* v = std::getenv("STRATA_GDN_HEAD"); return v == nullptr || std::atoi(v) != 0; }();++ // STRATA_GDN_HEAD=1 (on by default on gfx1151; off with STRATA_GDN_HEAD=0 or STRATA_GDN_REC_HEADS) takes them++ // (AMD builds only; the arch defaults set STRATA_GDN_HEAD=1 on gfx1151 and leave other cards on the earlier kernels)++ static const bool head = [] { const char* v = std::getenv("STRATA_GDN_HEAD"); return v != nullptr && std::atoi(v) != 0; }();+ static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr;+ gdn_recurrence_variant(head && !serial ? 1 : 0, state, h, gate, beta, z, gamma, eps, y, y16, T, stream, ld16);+ }void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, void* stream) {if (n_expert == 512)route_kernel<16><<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T);diff --cc src/prefill/moe_fused.cuindex 19d1c949c,0e21cd3da..abcbe7290--- a/src/prefill/moe_fused.cu+++ b/src/prefill/moe_fused.cu@@@ -364,10 -598,23 +598,27 @@@ const DevInfo& dev_info()DevInfo& d = g_dev[dev & 31];if (d.done) return d;d.done = true;-#if defined(__HIPCC__)+#if defined(STRATA_HIP_GFX906)+ // gfx906 reports compute capability 9.0 through HIP, but the mma.sync bodies above are CUDA sm_80+ only and+ // empty in a hipcc build: never available here (the prompt path keeps its own expert GEMMs)+ return d;++#elif defined(__HIPCC__)+ { // gfx11 (RDNA3 / RDNA3.5) with this build's code for it: the WMMA kernels+ cudaDeviceProp prop;+ cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev);+ hipFuncAttributes fa{};+ if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess || std::strncmp(prop.gcnArchName, "gfx11", 5) != 0 ||+ hipFuncGetAttributes(&fa, reinterpret_cast<const void*>(expert_w11_kernel<true>)) != hipSuccess) {+ cudaGetLastError();+ return d;+ }+ if (hipOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_gu, expert_w11_kernel<true>, W_THREADS, 0) != hipSuccess ||+ hipOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_d, expert_w11_kernel<false>, W_THREADS, 0) != hipSuccess)+ d.occ_gu = d.occ_d = 0;+ d.cc = d.occ_gu >= 1 && d.occ_d >= 1 ? 80 : 0;+ cudaGetLastError();+ return d;+ }#elseint major = 0, minor = 0;cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);@@@ -390,8 -637,8 +641,9 @@@cudaOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_d, expert_kernel<false>, THREADS, smem_bytes(false));if (d.occ_gu < 1 || d.occ_d < 1) d.cc = 0; // does not fit this card: the MMQ pathcudaGetLastError();+#endifreturn d;+ #endif}} // namespacediff --cc src/prefill/moe_fused_iq.cuindex b2d990869,d61cc29bc..c05573f09--- a/src/prefill/moe_fused_iq.cu+++ b/src/prefill/moe_fused_iq.cu@@@ -540,10 -937,24 +937,28 @@@ const DevInfo& dev_info()DevInfo& d = g_dev[dev & 31];if (d.done) return d;d.done = true;-#if defined(__HIPCC__)+#if defined(STRATA_HIP_GFX906)+ // gfx906 reports compute capability 9.0 through HIP, but the mma.sync bodies above are CUDA sm_80+ only and+ // empty in a hipcc build: never available here (the prompt path keeps its own expert GEMMs)+ return d;++#elif defined(__HIPCC__)+ { // gfx11 with this build's code: the WMMA kernels (one occupancy for all: the same shape and LDS budget)+ cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev);+ cudaDeviceProp prop;+ hipFuncAttributes fa{};+ if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess || std::strncmp(prop.gcnArchName, "gfx11", 5) != 0 ||+ hipFuncGetAttributes(&fa, reinterpret_cast<const void*>(native_w11_kernel<T_IQ3_XXS, true>)) != hipSuccess) {+ cudaGetLastError();+ return d;+ }+ int o = 0;+ if (hipOccupancyMaxActiveBlocksPerMultiprocessor(&o, native_w11_kernel<T_IQ2_S, true>, NW_THREADS, 0) != hipSuccess)+ o = 0;+ d.ok = o >= 1;+ d.occ = d.ok ? o : 1;+ cudaGetLastError();+ return d;+ }#elseint major = 0;cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);@@@ -555,14 -966,33 +970,34 @@@setup_one<T_Q2_0, false>(occ) && setup_one<T_IQ4_NL, false>(occ);d.occ = d.ok ? occ : 1;cudaGetLastError();+#endifreturn d;+ #endif}+ // opt-in on top of STRATA_PF_FUSED=1: STRATA_PF_FUSED_KQ=1 takes UD-Q4_K_XL's formats (the output differs from the FP16+ // expert path's at rounding level; KL-gated, see aurora_s23.md)+ bool kq_on() {+ static const bool on = [] {+ const char* v = std::getenv("STRATA_PF_FUSED_KQ");+ return v != nullptr && v[0] == '1';+ }();+ return on;+ }bool gu_covered(int t) {- return t == T_IQ2_XXS || t == T_IQ2_XS || t == T_IQ2_S || t == T_IQ3_XXS || t == T_IQ3_S || t == T_IQ4_XS;+ return t == T_IQ2_XXS || t == T_IQ2_XS || t == T_IQ2_S || t == T_IQ3_XXS || t == T_IQ3_S || t == T_IQ4_XS+ #if defined(__HIPCC__)+ || ((t == T_Q4_K || t == T_Q5_K) && kq_on()) // the gfx11 kernels only+ #endif+ ;+ }+ bool d_covered(int t) {+ return t == T_Q2_0 || t == T_IQ4_NL+ #if defined(__HIPCC__)+ || ((t == T_Q5_1 || t == T_Q8_0) && kq_on())+ #endif+ ;}- bool d_covered(int t) { return t == T_Q2_0 || t == T_IQ4_NL; }template <int T, bool GU>void launch(int ww, unsigned grid, const Batch& b, const NativeGeom& g, const Tables& tb, const void* act,diff --cc src/prefill/prefill.cppindex e76fb6ddc,13d273d09..9ff9d1ba5--- a/src/prefill/prefill.cpp+++ b/src/prefill/prefill.cpp@@@ -1364,19 -1028,8 +1424,19 @@@ uint64_t Prefill::bytes_needed(const coo.take<uint16_t>((size_t) GEMM_SCRATCH, ok);o.take<uint8_t>(GEMM_WS, ok);auto f = [&](size_t n) { o.take<float>(n, ok); };- f(T * N); f(T * D); f(T * D); o.take<uint16_t>(T * (D + (hc_pad() ? XN_PAD : 0)), ok); f(T * LR);- o.take<uint16_t>(T * LR, ok);+ // `carve`'s order, buffer for buffer: emb, R, xn, grs, xn16, lo, lo16, gated, inj, mixed, mixed_bf, mixed_h,+ // bo. This counted `xn` unconditionally (carve takes it only under STRATA_GR_UNFUSED) and never counted+ // `grs`. Net over-count T*(D-HC)*4 bytes: 42 MB at a 1024-token chunk, 252 MB (48 Q8_0 slots) at 6144 - the+ // prompt path was told it had less room than it did. Safe - the direction is over-estimating, and `take`+ // still bounds-checks - but it under-sizes every loan, so every chunk the scan picks is one step smaller.+ if (ring_bytes_on()) {+ f(T * N); f(T * D);+ if (gr_unfused()) f(T * D);+ f(T * HC);+ } else { // STRATA_RING_BYTES=0: 0.1.39's count+ f(T * N); f(T * D); f(T * D);+ }- o.take<uint16_t>(T * D, ok); f(T * LR); o.take<uint16_t>(T * LR, ok);++ o.take<uint16_t>(T * (D + (hc_pad() ? XN_PAD : 0)), ok); f(T * LR); o.take<uint16_t>(T * LR, ok);f(T * D); f(T * HC); f(T * N); o.take<uint16_t>(T * N, ok); o.take<uint16_t>(T * N, ok); f(T * N);if (bf16x2_hc()) { o.take<uint16_t>(T * D, ok); o.take<uint16_t>(T * LR, ok); }if (bf16x2()) o.take<uint16_t>(T * N, ok);@@@ -2262,13 -1778,10 +2374,14 @@@ bool Prefill::run_impl(const int64_t* tconst bool use_mmq = mmq_plan().any && mmq_plan().layer[(size_t) l];const int mmq_gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42;const int mmq_dt = lay.native ? lay.fmt[(size_t) l].d_type : 42;+ // --peer-device: MMQ only, whether or not the peer took the prompt path (set_peer can decline), as+ // fused_ring() sized the ring and the buffers for it+ const bool no_peer = !core::peer_portable();- const bool fused_nat = use_mmq && stream_all && no_peer && lay.native && fused::native_supported(mmq_gt, mmq_dt);+ const bool fused_only = mmq_plan().any && mmq_plan().fo[(size_t) l];- const bool fused_nat = (use_mmq || fused_only) && stream_all && lay.native && fused::native_supported(mmq_gt, mmq_dt);- const bool fused_l = (use_mmq && stream_all && !lay.native && fused::enabled()) || fused_nat;++ const bool fused_nat = (use_mmq || fused_only) && stream_all && no_peer && lay.native && fused::native_supported(mmq_gt, mmq_dt);+ const bool fused_l = (use_mmq && stream_all && no_peer && !lay.native && fused::enabled()) || fused_nat;size_t n_order = 0; // the routed experts (the debug report; unknown when fused)+ bool peer_now = false; // multi-GPU: the peer computed rows of this layer (MMQ path only)if (fused_l) {if (static bool said = false; !said) {said = true;@@@ -2393,20 -1868,24 +2506,28 @@@slot_h[(size_t) i] = p;src_h[(size_t) p] = (int32_t) (i / K);}- if (grp_mapped) {- copy_i32(m.slot_dev, m.grp_dev + m.grp_tk, T * K, m.cs);- copy_i32(m.src_dev, m.grp_dev + 2 * m.grp_tk, T * K, m.cs);- } else {- cudaMemcpyAsync(m.slot_dev, m.slot_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs);- cudaMemcpyAsync(m.src_dev, m.src_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs);- }// the experts, in id order: resident ones from VRAM, the others through the staging ring- std::vector<int32_t> order;- for (int32_t e = 0; e < m.g->n_expert; ++e) if (m.cnt[(size_t) e] > 0) order.push_back(e);+ std::vector<int32_t> order, order_peer;+ for (int32_t e = 0; e < m.g->n_expert; ++e)+ if (m.cnt[(size_t) e] > 0 && (on_peer.empty() || on_peer[(size_t) e] != 2))+ (!on_peer.empty() && on_peer[(size_t) e] ? order_peer : order).push_back(e);+ for (int32_t e = 0; e < m.g->n_expert && !on_peer.empty(); ++e) // the peer-streamed ones last:+ if (on_peer[(size_t) e] == 2) order_peer.push_back(e); // their copies get the most time+ // Aurora (STRATA_MMQ_RESIDENT_SORT_NE=1, opt-in): a layer whose experts are ALL resident and+ // run through MMQ groups takes them in row-count order, so each 16-expert group's max_rows+ // (its padded tile rows) is close to its experts' own; slot/src/off are rebuilt coherently+ // before the upload, the routed ids, weights and the within-expert row order stay as they are.- if (detail::mmq_resident_sort_eligible(detail::mmq_resident_sort_requested(), use_mmq, lay.native,++ if (detail::mmq_resident_sort_eligible(detail::mmq_resident_sort_requested() && on_peer.empty(), use_mmq, lay.native,+ m.cache != nullptr, m.host_res ? m.host_res + (size_t) l * m.g->n_expert : nullptr,+ m.g->n_expert, stream_all, !stream_all || seq_start[(size_t) l] == seq_start[(size_t) l + 1]))+ detail::mmq_resident_sort_rows(ids_h, T * K, (int32_t) K, m.cnt, m.off, order, slot_h, src_h);+ if (grp_mapped) {+ copy_i32(m.slot_dev, m.grp_dev + m.grp_tk, T * K, m.cs);+ copy_i32(m.src_dev, m.grp_dev + 2 * m.grp_tk, T * K, m.cs);+ } else {+ cudaMemcpyAsync(m.slot_dev, m.slot_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs);+ cudaMemcpyAsync(m.src_dev, m.src_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs);+ }n_order = order.size();const size_t mmq_gub = use_mmq ? mmq::matrix_bytes(mmq_gt, 1280, N) : 0;const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, 640) : 0;diff --cc src/program/generate.cppindex 085c3d8ce,804af6d77..04b8041ff--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@@ -3200,12 -2726,32 +3263,12 @@@ int main(int argc, char** argv)// numbers if the slots do not fit, instead of handing back a cache smaller than it was asked for.mem_mark("the weights, the session and the drafter");strata::core::ExpertCache xcache;- // THE HEAD BEFORE THE CACHE. The expert cache takes what is free minus the reserve, so everything allocated- // after it comes out of the reserve. The native head (~0.5 GB with IQ3_S) was loaded after it and ate most of- // the 700 MiB: 128K IQ3_S ended with 30 MiB free, the driver paged, and a request stalled for good at its first- // verify window. Loaded first, the cache is sized around it.- const strata::core::WeightRef* wo = wt.find("output.weight");- if (wo == nullptr) { std::fprintf(stderr, "strata generate: output.weight is missing\n"); return 1; }- const int64_t n_vocab = wo->ne1;- strata::core::NativeHead native_head;- if (!o.native_head_gguf.empty() && !multi_gpu) { // a layer split's head is on its last stage- if (!native_head.load(o.native_head_shards, g.n_embd, n_vocab, err)) {- std::fprintf(stderr, "strata generate: %s\n", err.c_str());- return 1;- }- std::fprintf(stderr, "strata generate: experimental native Q5_K head, %llu bytes\n",- (unsigned long long) native_head.weight_bytes());- }- std::vector<float> logits((size_t) n_vocab);- float* d_logits = nullptr;- if (cudaMalloc(&d_logits, (size_t) n_vocab * 4) != cudaSuccess) {- std::fprintf(stderr, "strata generate: the logits buffer failed\n");- return 1;- }+ // THE HEAD BEFORE THE CACHE: the native head and the logits are allocated above, before the expert arena (#620)const bool auto_cache = o.expert_cache < 0;+ bool reserve_adapted = false; // #496: the auto sizing lowered the reserve so a small card's cache fitsif (o.expert_cache < 0) {size_t free_b = 0, total_b = 0;- cudaMemGetInfo(&free_b, &total_b);+ free_b = strata::core::device_free_bytes(); (void) total_b;// Plan v0.3 P5: the batched prompt path's chunk buffers are allocated later, so they are reserved here -// under WDDM an over-subscribed allocation does not fail, it pages to system memory and crawls.// (with borrowing - the default with a profile - the prompt path lends cache slots instead; `pf_borrow` is@@@ -7338,52 -5792,18 +7438,60 @@@// DONE <generated> <prompt> <prompt ms> <decode ms> <finish> <drafts accepted> <drafts offered> <reused> [hits] [lookups]// [RAM blobs] [file blobs] [file MB] (CS-T tiers; appended, so an older server reads the rest)// [prompt tokens read] (#471: fewer than <prompt> - <reused> when a cancel stopped the read)+ // [offloaded] (#588: the decode's routed experts the GPU read over PCIe or another GPU computed;+ // not in [lookups])- if (yielded_at >= 0) std::printf("YIELDED %d %lld\n", yielded_slot, (long long) yielded_at);- std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld %lld\n",+ // [lookup-chain accepted] [lookup-chain offered] [suffix accepted] [suffix offered] [windows]+ // (only with --lookup-chain)+ char chain_txt[128] = "";+ if (o.lookup_chain > 0)+ std::snprintf(chain_txt, sizeof(chain_txt), " %lld %lld %lld %lld %lld", (long long) chain_ok,+ (long long) chain_drafts, (long long) sfx_ok, (long long) sfx_drafts, (long long) dec_windows);- std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld%s\n", (long long) produced_n,++ if (yielded_at >= 0) std::printf("YIELDED %d %lld++", yielded_slot, (long long) yielded_at);++ std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld %lld%s++",+ (long long) produced_n,(long long) n, prompt_ms, decode_ms, finish, (long long) draft_accepted, (long long) draft_offered,(long long) resume, (long long) req_hits, (long long) req_look,(long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0),- (double) (src.file_read_bytes() - file_bytes0) / 1e6, (long long) read_n, chain_txt);+ (double) (src.file_read_bytes() - file_bytes0) / 1e6, (long long) read_n,- (long long) req_offload);++ (long long) req_offload, chain_txt);std::fflush(stdout);+ if (admit_slot >= 0) { // --batch: BADM <slot> <1 = continues in the batch windows | 0 = done>+ bool cont = !cancelled && produced_n == 1 && admit_max_new > 1 && std::strcmp(finish, "length") == 0 &&+ (int64_t) live.size() == p;+ const auto tc0 = Clock::now();+ if (cont && !copy_to_slot(admit_slot, live, err)) {+ std::fprintf(stderr, "strata serve: batch admission failed: %s\n", err.c_str());+ bs[(size_t) admit_slot].cached = false; // its sessions may be half written+ cont = false;+ }+ if (cont) {+ ver.set_slot_sampling(admit_slot, req_sp); // the request's own sampling, row by row+ BSlot& sl = bs[(size_t) admit_slot];+ sl = BSlot{};+ sl.active = true;+ sl.x = x;+ sl.p = p;+ sl.produced = 1;+ sl.max_new = admit_max_new;+ sl.t0 = Clock::now();+ sl.ids = live;+ sl.cvec = cvec_cached;+ sl.img = !live_imgs.empty(); // pictures: not matched again by tokens alone, so not cached+ const ConvCheckpoint* best = nullptr;+ for (const ConvCheckpoint& c : checks)+ if (c.ids.size() < live.size() && (best == nullptr || c.ids.size() > best->ids.size()) &&+ std::equal(c.ids.begin(), c.ids.end(), live.begin()))+ best = &c;+ if (best != nullptr && !sl.img) sl.checks.push_back(*best);+ std::fprintf(stderr, "strata batch: slot %d takes %lld tokens (copied in %.1f ms)\n", admit_slot,+ (long long) live.size(), std::chrono::duration<double, std::milli>(Clock::now() - tc0).count());+ }+ std::printf("BADM %d %d\n", admit_slot, cont ? 1 : 0);+ std::fflush(stdout);+ admit_slot = -1;+ }if (drive.routing != nullptr) std::fflush(drive.routing); // the routing trace survives a crash and is watchable mid-session// "12288 of 98179" when cancelled mid-read (#471), the rate from what was readchar read_txt[64];