okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
269f33859
main
1// src/kernels/cuda/fused_gr.cu - see include/strata/kernels/fused_gr.hpp. 2#include "strata/core/emulate.hpp" 3#include "strata/core/sm75_series.hpp" 4#include "strata/core/sm120_series.hpp" 5#include "strata/core/dispatch_stats.hpp" 6#include "strata/core/defaults_026.hpp" 7#define STRATA_Q81_FASTMATH_DIV 1 // #3948: the q8_1 tails divide as native_mmvq.cu (--use_fast_math) does, see q8_1_finite.hpp 8#include "strata/kernels/q8_1_finite.hpp" // #606: q8_1_ds 9#include "strata/core/geometry.hpp" 10#include "strata/core/bw_dense_defaults.hpp" 11#include "strata/kernels/fused_gr.hpp" 12#include "strata/kernels/bf16_bits.hpp" 13#include "strata/kernels/verify_kernels.hpp" 14#include "strata/kernels/gfx_arch.hpp" 15#include "s26_tsum.cuh" 16 17#include <cuda_fp16.h> 18#include <cuda_runtime.h> 19 20#include <atomic> 21#include <mutex> 22#include <type_traits> 23#include <cmath> 24#include <cstdio> 25#include <cstdlib> 26#include <cstring> 27#include <random> 28#include <string> 29#include <vector> 30 31namespace strata::kernels { 32namespace { 33 34constexpr int N = strata::core::kCompiledGeometry.n_embd; // 2560 in Flash-Next 35constexpr int HC = strata::core::kCompiledGeometry.hc; // streams 36constexpr int D = N * HC; // 10240 37constexpr int LR = strata::core::kCompiledGeometry.hc_lr; // 320 38// the latency-hidden norm/up (gr_norm_fast_kernel / gr_up_fast_kernel, STRATA_GR_FAST): gfx906's, built for CUDA too 39#if defined(STRATA_HIP_GFX906) || !defined(__HIPCC__) 40#define STRATA_GR_FAST_BUILD 1 41#else 42#define STRATA_GR_FAST_BUILD 0 43#endif 44static_assert(N == strata::core::kCompiledGeometry.n_embd && HC == strata::core::kCompiledGeometry.hc && LR == strata::core::kCompiledGeometry.hc_lr, "fused_gr is compiled for core/geometry.hpp"); 45constexpr int THREADS = 256; 46constexpr int WARPS = THREADS / 32; 47constexpr int DOWN_BLOCKS = LR / WARPS; // 40 blocks of 8 rows; one more for the inject rows 48constexpr int UP_COLS = 32; // columns d per `up` block (x 4 streams = 128 rows) 49constexpr int UP_BLOCKS = N / UP_COLS; // 80 50 51__device__ __forceinline__ float warp_sum(float v) { 52#pragma unroll 53 for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); 54 return v; 55} 56// warp_sum of 8 independent values at once, token t's total ending in every lane whose bits 4..2 spell t ((lane >> 2) & 7). The same 57// additions as warp_sum(a[t]) in the same order (offset 16, 8, 4, 2, 1; a + b = b + a, so a lane adding its partner's value to its own gets the 58// bits the plain butterfly gets): each level only exchanges the half of the values the partner keeps, 4 + 2 + 1 + 1 + 1 shuffles instead of 40. 59__device__ __forceinline__ float warp_sum8(const float (&a)[8], int lane) { 60 const bool h4 = (lane & 16) != 0, h3 = (lane & 8) != 0, h2 = (lane & 4) != 0; 61 float b[4], c[2]; 62#pragma unroll 63 for (int j = 0; j < 4; ++j) { 64 const float send = h4 ? a[j] : a[j + 4], keep = h4 ? a[j + 4] : a[j]; 65 b[j] = keep + __shfl_xor_sync(0xffffffffu, send, 16); 66 } 67#pragma unroll 68 for (int j = 0; j < 2; ++j) { 69 const float send = h3 ? b[j] : b[j + 2], keep = h3 ? b[j + 2] : b[j]; 70 c[j] = keep + __shfl_xor_sync(0xffffffffu, send, 8); 71 } 72 const float send = h2 ? c[0] : c[1], keep = h2 ? c[1] : c[0]; 73 float d = keep + __shfl_xor_sync(0xffffffffu, send, 4); 74 d += __shfl_xor_sync(0xffffffffu, d, 2); 75 d += __shfl_xor_sync(0xffffffffu, d, 1); 76 return d; 77} 78__device__ __forceinline__ float sigmoidf_(float x) { return 1.0f / (1.0f + __expf(-x)); } 79 80// 8 bf16 packed in a uint4, unpacked to two float4 once when reused across tokens. 81struct Bf16x8 { float4 a, b; }; 82__device__ __forceinline__ Bf16x8 unpack8(const uint4 w) { 83 return { 84 make_float4(__uint_as_float(w.x << 16), __uint_as_float(w.x & 0xffff0000u), 85 __uint_as_float(w.y << 16), __uint_as_float(w.y & 0xffff0000u)), 86 make_float4(__uint_as_float(w.z << 16), __uint_as_float(w.z & 0xffff0000u), 87 __uint_as_float(w.w << 16), __uint_as_float(w.w & 0xffff0000u)) 88 }; 89} 90__device__ __forceinline__ float dot8u(const Bf16x8& w, const float4 x0, const float4 x1) { 91 float acc = 0.0f; 92 acc = fmaf(w.a.x, x0.x, acc); 93 acc = fmaf(w.a.y, x0.y, acc); 94 acc = fmaf(w.a.z, x0.z, acc); 95 acc = fmaf(w.a.w, x0.w, acc); 96 acc = fmaf(w.b.x, x1.x, acc); 97 acc = fmaf(w.b.y, x1.y, acc); 98 acc = fmaf(w.b.z, x1.z, acc); 99 acc = fmaf(w.b.w, x1.w, acc); 100 return acc; 101} 102__device__ __forceinline__ float dot8u_ptr(const Bf16x8& w, const float* x) { 103 const float4* x4 = reinterpret_cast<const float4*>(x); 104 return dot8u(w, x4[0], x4[1]); 105} 106 107// 8 bf16 packed in a uint4 against 8 16-byte-aligned floats (same 8-FMA order). 108__device__ __forceinline__ float dot8(const uint4 w, const float* x) { 109 return dot8u_ptr(unpack8(w), x); 110} 111 112// STRATA_HC_Q8: a weight chunk of 8 values in one uint4 register either way - bf16 (4 words), or Q8 (8 int8 codes in 113// .x/.y and the chunk's 32-value block scale in .z), so the kernels keep their register budget. 114__device__ __forceinline__ float dot8q(const uint32_t a, const uint32_t b, const float* x) { 115 float acc = 0.0f; 116#pragma unroll 117 for (int i = 0; i < 4; ++i) acc = fmaf((float) (int8_t) (a >> (8 * i)), x[i], acc); 118#pragma unroll 119 for (int i = 0; i < 4; ++i) acc = fmaf((float) (int8_t) (b >> (8 * i)), x[4 + i], acc); 120 return acc; 121} 122/// STRATA_HC_REQ8: the chunk at element `e` (a multiple of 8) of a matrix - bf16 `wb`, or (Q8 and `sq` non-null) 123/// int8 codes with scales `sq`, packed into the same uint4 register as 8 int8 codes in .x/.y and the 32-value block's 124/// scale in .z. Q8 is a template parameter: the BF16 instantiations compile exactly as before. 125template <bool Q8> 126__device__ __forceinline__ uint4 ldw(const uint16_t* wb, const float* sq, size_t e) { 127 if constexpr (Q8) { 128 if (sq != nullptr) { 129 const uint2 v = __ldg(reinterpret_cast<const uint2*>(reinterpret_cast<const int8_t*>(wb) + e)); 130 return make_uint4(v.x, v.y, __float_as_uint(__ldg(sq + e / 32)), 0u); 131 } 132 } 133 return __ldg(reinterpret_cast<const uint4*>(wb + e)); 134} 135template <bool Q8> 136__device__ __forceinline__ float dotw(const bool q8, const uint4 w, const float* x) { 137 if constexpr (Q8) { 138 if (q8) return __uint_as_float(w.z) * dot8q(w.x, w.y, x); 139 } 140 return dot8(w, x); 141} 142 143// The single-token down kernel keeps the whole normalised hidden row (D floats) in shared memory: static while it fits the 144// 48 KB a static allocation may take (Flash-Next: 40 KB), dynamic (opted in at the launch) beyond (hidden 3072 and up). 145constexpr bool kDownDynXn = (size_t) D * 4 + 512 > 48 * 1024; 146template <bool Q8 = false> 147__global__ void __launch_bounds__(THREADS) gr_down_kernel(FusedGrArgs a) { 148 __shared__ __align__(16) float xn_static[kDownDynXn ? 1 : D]; 149 extern __shared__ __align__(16) float xn_dyn[]; 150 float* const xn = kDownDynXn ? xn_dyn : xn_static; 151 __shared__ float part[WARPS][HC]; 152 __shared__ float s_rs[HC]; 153 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; 154 float gw[HC]; 155#pragma unroll 156 for (int c = 0; c < HC; ++c) gw[c] = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; 157 // 1. R' * w_norm into shared memory, and the per-stream sums of squares of R'. 158 float ss[HC] = {0.0f, 0.0f, 0.0f, 0.0f}; 159 for (int i = t * 4; i < D; i += THREADS * 4) { 160 const int c = i / N, d = i - c * N; 161 float4 r = *reinterpret_cast<const float4*>(a.R + i); 162 if (a.apply) { 163 const float4 b = *reinterpret_cast<const float4*>(a.bo_prev + d); 164 r.x = fmaf(b.x, gw[c], r.x); r.y = fmaf(b.y, gw[c], r.y); 165 r.z = fmaf(b.z, gw[c], r.z); r.w = fmaf(b.w, gw[c], r.w); 166 } 167 const float4 g = *reinterpret_cast<const float4*>(a.w_norm + i); 168 float sq = r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; 169#pragma unroll 170 for (int cc = 0; cc < HC; ++cc) if (cc == c) ss[cc] += sq; 171 *reinterpret_cast<float4*>(xn + i) = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w); 172 } 173#pragma unroll 174 for (int c = 0; c < HC; ++c) { 175 const float v = warp_sum(ss[c]); 176 if (lane == 0) part[warp][c] = v; 177 } 178 __syncthreads(); 179 if (t < HC) { 180 float s = 0.0f; 181 for (int w = 0; w < WARPS; ++w) s += part[w][t]; 182 s_rs[t] = rsqrtf(s / (float) N + a.eps); 183 if (blockIdx.x == 0) a.rs[t] = s_rs[t]; 184 } 185 __syncthreads(); 186 for (int i = t; i < D; i += THREADS) xn[i] *= s_rs[i / N]; 187 __syncthreads(); 188 // 2. one warp per output row: 10240 bf16 = 1280 chunks of 8, 40 per lane. 189 const bool inject_block = blockIdx.x == DOWN_BLOCKS; 190 const int row = inject_block ? warp : blockIdx.x * WARPS + warp; 191 if (inject_block && (a.w_inject == nullptr || warp >= HC)) return; 192 const uint16_t* wmat = inject_block ? a.w_inject : a.w_down; 193 const float* sq = (Q8 && !inject_block) ? a.s_down : nullptr; // the inject rows stay bf16 194 const bool q8 = Q8 && !inject_block; 195 float acc = 0.0f; 196#pragma unroll 4 197 for (int j = lane; j < D / 8; j += 32) acc += dotw<Q8>(q8, ldw<Q8>(wmat, sq, (size_t) row * D + (size_t) j * 8), xn + j * 8); 198 acc = warp_sum(acc); 199 if (lane != 0) return; 200 if (inject_block) { 201 a.inject_out[row] = acc; 202 } else { 203 const float x = acc / (float) HC; 204 a.lo[row] = x / (1.0f + __expf(-x)); 205 } 206} 207 208template <bool Q8 = false> 209__global__ void __launch_bounds__(THREADS) gr_up_kernel(FusedGrArgs a) { 210 __shared__ __align__(16) float lo[LR]; 211 __shared__ float g[HC][UP_COLS]; 212 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; 213 const int d0 = blockIdx.x * UP_COLS; 214 for (int k = t; k < LR; k += THREADS) lo[k] = a.lo[k]; 215 __syncthreads(); 216 // 128 rows (4 streams x 32 columns), 16 per warp: 320 bf16 = 40 chunks of 8. 217 for (int r = warp; r < HC * UP_COLS; r += WARPS) { 218 const int c = r / UP_COLS, dd = r - c * UP_COLS, i = c * N + d0 + dd; 219 const bool q8 = Q8; 220 float acc = dotw<Q8>(q8, ldw<Q8>(a.w_up, a.s_up, (size_t) i * LR + (size_t) lane * 8), lo + lane * 8); 221 if (lane < LR / 8 - 32) 222 acc += dotw<Q8>(q8, ldw<Q8>(a.w_up, a.s_up, (size_t) i * LR + (size_t) (32 + lane) * 8), lo + (32 + lane) * 8); 223 acc = warp_sum(acc); 224 if (lane == 0) { 225 float rv = a.R[i]; 226 if (a.apply) { 227 rv = fmaf(a.bo_prev[d0 + dd], 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC), rv); 228 a.R_out[i] = rv; // this block owns column d0+dd of every stream 229 } 230 const float x = rv * a.w_norm[i] * a.rs[c]; 231 g[c][dd] = x * sigmoidf_(acc); 232 } 233 } 234 __syncthreads(); 235 if (t < UP_COLS) { 236 float s = 0.0f; 237#pragma unroll 238 for (int c = 0; c < HC; ++c) s += g[c][t]; 239 a.mixed[d0 + t] = s / (float) HC; 240 } 241} 242 243// ================================ plan v0.3 P6: T tokens, one weight read ================================ 244struct GrMulti { 245 FusedGrArgs a[kFusedGrMaxT]; 246 float* xn; 247 int T; 248}; 249 250 251// S26 STRATA_QFUSE=1: the q8_1 image of `mixed`, written by the up kernels below. A q8_1 block is 32 columns and an 252// up block owns UPM_COLS = 16, so the second of the two blocks that own a 32-column group (a per-group counter, 253// incremented after the block's writes are fenced, reset by that block for the next launch) reads the 32 values back 254// and quantizes them with native_quantize_q8_1_kernel's quantizer: one warp per token, the same XOR-tree max and sum, 255// d = amax / 127, roundf(x / d), ds = (d, sum) - the bytes the separate launch writes. 256struct GrQ81 { half2 ds; int8_t qs[32]; }; 257static_assert(2 * 16 == 32, "two up blocks per q8_1 group"); 258__device__ __forceinline__ void gr_q8_tail(const GrMulti& m, int d0) { 259 __shared__ int last; 260 __threadfence(); 261 __syncthreads(); 262 if (threadIdx.x == 0) { 263 unsigned* c = m.a[0].q8_cnt + d0 / 32; 264 last = atomicAdd(c, 1u) == 1u; 265 if (last) atomicExch(c, 0u); 266 } 267 __syncthreads(); 268 if (!last) return; 269 __threadfence(); 270 const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; 271 if (warp >= m.T) return; 272 const int c0 = (d0 / 32) * 32; 273 const float xi = *reinterpret_cast<const volatile float*>(m.a[warp].mixed + c0 + lane); 274 float amax = fabsf(xi), sum = xi; 275#pragma unroll 276 for (int o = 16; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); 277#pragma unroll 278 for (int o = 16; o > 0; o >>= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); 279 const float d = q8_1_finite(q81_div(amax, 127.0f)); // #606: as native_quantize_q8_1_kernel - finite blocks bit for bit 280 const int8_t q = q8_1_quant(xi, d, amax); 281 GrQ81* y = reinterpret_cast<GrQ81*>(m.a[warp].q8_mixed) + c0 / 32; 282 y->qs[lane] = q; 283 if (lane == 0) y->ds = q8_1_ds(d, sum); // #606: clamped scale/sum - an unclamped pair NaN-poisons the dot path 284} 285// Step 1 of `gr_down_kernel`, one block per token, same threads and reduction order: rs[t] and xn[t] to global. 286__global__ void __launch_bounds__(THREADS) gr_norm_multi_kernel(GrMulti m) { 287 __shared__ float part[WARPS][HC]; 288 __shared__ float s_rs[HC]; 289 const FusedGrArgs& a = m.a[blockIdx.x]; 290 float* xn = m.xn + (size_t) blockIdx.x * D; 291 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; 292 float gw[HC]; 293#pragma unroll 294 for (int c = 0; c < HC; ++c) gw[c] = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; 295 float ss[HC] = {0.0f, 0.0f, 0.0f, 0.0f}; 296 for (int i = t * 4; i < D; i += THREADS * 4) { 297 const int c = i / N, d = i - c * N; 298 float4 r = *reinterpret_cast<const float4*>(a.R + i); 299 if (a.apply) { 300 const float4 b = *reinterpret_cast<const float4*>(a.bo_prev + d); 301 r.x = fmaf(b.x, gw[c], r.x); r.y = fmaf(b.y, gw[c], r.y); 302 r.z = fmaf(b.z, gw[c], r.z); r.w = fmaf(b.w, gw[c], r.w); 303 } 304 const float4 g = *reinterpret_cast<const float4*>(a.w_norm + i); 305 float sq = r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; 306#pragma unroll 307 for (int cc = 0; cc < HC; ++cc) if (cc == c) ss[cc] += sq; 308 *reinterpret_cast<float4*>(xn + i) = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w); 309 } 310#pragma unroll 311 for (int c = 0; c < HC; ++c) { 312 const float v = warp_sum(ss[c]); 313 if (lane == 0) part[warp][c] = v; 314 } 315 __syncthreads(); 316 if (t < HC) { 317 float s = 0.0f; 318 for (int w = 0; w < WARPS; ++w) s += part[w][t]; 319 s_rs[t] = rsqrtf(s / (float) N + a.eps); 320 a.rs[t] = s_rs[t]; 321 } 322 __syncthreads(); 323 for (int i = t; i < D; i += THREADS) xn[i] *= s_rs[i / N]; 324} 325 326// Step 2 of `gr_down_kernel` for T tokens. One warp per row (so each lane accumulates the same chunks in the 327// same order as the single-token kernel); per tile the lane's weight chunks are loaded BEFORE the activation 328// tile is staged, so the DRAM and L2 traffic are in flight together. 329// 330// TILEV = xn floats per token staged at a time. The tile only changes the staging granularity: the lane's chunk 331// order (lane + 32*q within the tile, tiles ascending) is strictly increasing for either value, so the results are 332// bitwise identical to `gr_down_kernel` for both. 2560 stages 320 chunks of 8 per tile (10 per lane); cards whose 333// opt-in below 8 * 2560 * 4 B slices the tokens - sm_75 (64 KiB) carries 6 tokens of it - run TILEV 1280 instead, 334// which fits all eight tokens in one 40 KiB launch and stages 160 chunks of 8 (5 per lane, half the registers held 335// for the weight prefetch); smaller tiles raise how many blocks share an SM (the 41-block grid), e.g. three blocks 336// of four tokens instead of one on sm_75. 337template <int TILEV, int MAX_T = kFusedGrMaxT, bool Q8 = false> 338__global__ void __launch_bounds__(THREADS) gr_down_multi_kernel(GrMulti m) { 339 constexpr int TQ = TILEV / 8 / 32; // uint4 weight chunks per lane per tile 340 extern __shared__ __align__(16) float tile[]; // [T][TILEV] 341 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; 342 const int T = m.T; 343 const bool inject_block = blockIdx.x == DOWN_BLOCKS; 344 const int row = inject_block ? warp : blockIdx.x * WARPS + warp; 345 const bool active = !(inject_block && (m.a[0].w_inject == nullptr || warp >= HC)); 346 const uint16_t* wmat = inject_block ? m.a[0].w_inject : m.a[0].w_down; 347 const float* sq = (Q8 && !inject_block) ? m.a[0].s_down : nullptr; // the inject rows stay bf16 348 const bool q8 = Q8 && !inject_block; 349 const size_t row0 = (size_t) (active ? row : 0) * D; 350 float acc[MAX_T]; 351#pragma unroll 352 for (int k = 0; k < MAX_T; ++k) acc[k] = 0.0f; 353 for (int base = 0; base < D; base += TILEV) { 354 uint4 wv[TQ]; 355 if (active) { 356#pragma unroll 357 for (int q = 0; q < TQ; ++q) wv[q] = ldw<Q8>(wmat, sq, row0 + (size_t) base + (size_t) (lane + 32 * q) * 8); 358 } 359 __syncthreads(); // the previous tile is consumed 360 const float4* src4 = reinterpret_cast<const float4*>(m.xn); 361 float4* tile4 = reinterpret_cast<float4*>(tile); 362 for (int i = t; i < T * (TILEV / 4); i += THREADS) { 363 const int k = i / (TILEV / 4), off = i - k * (TILEV / 4); 364 tile4[i] = src4[((size_t) k * D + base) / 4 + off]; 365 } 366 __syncthreads(); 367 if (!active) continue; 368#pragma unroll 369 for (int q = 0; q < TQ; ++q) { 370 const int j = lane + 32 * q; 371#pragma unroll 372 for (int k = 0; k < MAX_T; ++k) 373 if (k < T) acc[k] += dotw<Q8>(q8, wv[q], tile + k * TILEV + j * 8); 374 } 375 } 376 if (!active) return; 377 float s[MAX_T]; 378#pragma unroll 379 for (int k = 0; k < MAX_T; ++k) s[k] = k < T ? warp_sum(acc[k]) : 0.0f; 380 // lane k writes token k (every lane holds every sum after the xor reduction) 381#pragma unroll 382 for (int k = 0; k < MAX_T; ++k) { 383 if (k >= T || lane != k) continue; 384 if (inject_block) { 385 m.a[k].inject_out[row] = s[k]; 386 } else { 387 const float x = s[k] / (float) HC; 388 m.a[k].lo[row] = x / (1.0f + __expf(-x)); 389 } 390 } 391} 392 393constexpr int UPM_COLS = 16; // columns per block (x 4 streams = 64 rows, 8 per warp) 394constexpr int UPM_BLOCKS = N / UPM_COLS; // 160 395 396// `gr_up_kernel` for T tokens: each row of w_up read once; the T dots reduced by xor so every lane holds every 397// sum, and lane k runs token k's epilogue - the T epilogues in parallel instead of one after another. 398template <int MAX_T = kFusedGrMaxT, bool EXACT_T = false, bool Q8 = false> 399__global__ void __launch_bounds__(THREADS) gr_up_multi_kernel(GrMulti m) { 400 __shared__ __align__(16) float lo[MAX_T][LR]; 401 __shared__ float g[MAX_T][HC][UPM_COLS]; 402 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; 403 const int T = EXACT_T ? MAX_T : m.T; 404 const int d0 = blockIdx.x * UPM_COLS; 405 for (int i = t; i < T * LR; i += THREADS) lo[i / LR][i % LR] = m.a[i / LR].lo[i % LR]; 406 __syncthreads(); 407 for (int r = warp; r < HC * UPM_COLS; r += WARPS) { 408 const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; 409 uint4 qa = make_uint4(0, 0, 0, 0), qb = make_uint4(0, 0, 0, 0); 410 Bf16x8 wa{}, wb{}; 411 if constexpr (Q8) { 412 qa = ldw<true>(m.a[0].w_up, m.a[0].s_up, (size_t) i * LR + (size_t) lane * 8); 413 if (lane < LR / 8 - 32) qb = ldw<true>(m.a[0].w_up, m.a[0].s_up, (size_t) i * LR + (size_t) (32 + lane) * 8); 414 } else { 415 const uint4* w4 = reinterpret_cast<const uint4*>(m.a[0].w_up + (size_t) i * LR); 416 wa = unpack8(__ldg(w4 + lane)); 417 wb = unpack8(lane < LR / 8 - 32 ? __ldg(w4 + 32 + lane) : make_uint4(0, 0, 0, 0)); 418 } 419 // the epilogue inputs of this lane's token, fetched while the dots run 420 float rv = 0.0f, wn = 0.0f, rsc = 0.0f, bo = 0.0f, ip = 0.0f; 421 bool apply = false; 422 if (lane < T) { 423 const FusedGrArgs& a = m.a[lane]; 424 rv = a.R[i]; 425 wn = a.w_norm[i]; 426 rsc = a.rs[c]; 427 apply = a.apply; 428 if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; } 429 } 430 float mine = 0.0f; 431#pragma unroll 432 for (int k = 0; k < MAX_T; ++k) { 433 if (!EXACT_T && k >= T) break; 434 float acc; 435 if constexpr (Q8) { 436 acc = dotw<true>(true, qa, lo[k] + lane * 8); 437 if (lane < LR / 8 - 32) acc += dotw<true>(true, qb, lo[k] + (32 + lane) * 8); 438 } else { 439 acc = dot8u_ptr(wa, lo[k] + lane * 8); 440 if (lane < LR / 8 - 32) acc += dot8u_ptr(wb, lo[k] + (32 + lane) * 8); 441 } 442 acc = warp_sum(acc); 443 if (lane == k) mine = acc; 444 } 445 if (lane < T) { 446 if (apply) { 447 rv = fmaf(bo, 2.0f * sigmoidf_(ip / (float) HC), rv); 448 m.a[lane].R_out[i] = rv; 449 } 450 const float x = rv * wn * rsc; 451 g[lane][c][dd] = x * sigmoidf_(mine); 452 } 453 } 454 __syncthreads(); 455 for (int i = t; i < T * UPM_COLS; i += THREADS) { 456 const int k = i / UPM_COLS, col = i - k * UPM_COLS; 457 float s = 0.0f; 458#pragma unroll 459 for (int c = 0; c < HC; ++c) s += g[k][c][col]; 460 m.a[k].mixed[d0 + col] = s / (float) HC; 461 } 462 if (m.a[0].q8_mixed != nullptr) gr_q8_tail(m, d0); // S26 STRATA_QFUSE 463} 464 465// 149-cuda: the same up projection with one warp per row instead of eight rows per warp. A block still covers 466// all HC streams x a few columns, so the cross-stream sum stays in shared memory, and every row's dot, xor tree 467// and epilogue are gr_up_multi_kernel's - bitwise the same outputs. 8 warps cover 2 columns x 4 streams (8 468// rows), so the grid grows from UPM_BLOCKS (160) to N/2 (1280): the card's SMs get ~8x the warps, which is what 469// this read is short of on a 12.0 card (160 blocks do not fill 192 SMs; measured 2.6 ms per round for 1.26 GB, 470// about 0.5 TB/s). Not used when the S26 q8_1 tail is on (its counter assumes UPM_COLS columns a block). 471constexpr int UPW_COLS = 2; 472constexpr int UPW_BLOCKS = N / UPW_COLS; 473 474/// STRATA_GR_UP_WIDE: the wide up read. ON BY DEFAULT on a 12.0 card (sm120_series.hpp; STRATA_SM120_PERF=0 or 475/// STRATA_GR_UP_WIDE=0 turns it off, =1 forces it on any card). Measured on the RTX PRO 5000 (IQ3_S, all experts 476/// resident, 5 interleaved pairs of fresh engines): story 197.6 -> 201.3 tok/s (+1.9%), code 243.5 -> 245.1 (+0.7%), 477/// the produced token ids identical in 6/6 runs; the isolated read (fused_gr_bench) is bitwise the old kernel's. 478bool gr_up_wide_on() { 479#if defined(__HIPCC__) 480 // A HIP build never takes it: gfx1200 / gfx1201 report compute capability 12.0 too, and sm120_default() would turn the 481 // CUDA-measured kernel on there (unmeasured on AMD). The persistent HC read is the HIP card's own opt-in. 482 return false; 483#else 484 static const int env = [] { 485 const char* v = std::getenv("STRATA_GR_UP_WIDE"); 486 return v != nullptr ? (std::atoi(v) != 0 ? 1 : 0) : -1; 487 }(); 488 if (env >= 0) return env != 0; 489 static int per_dev[64]; // 0 unknown, 1 no, 2 yes 490 int dev = 0; 491 if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false; 492 if (!per_dev[dev]) { 493 int major = 0, minor = 0; 494 cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); 495 cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev); 496 per_dev[dev] = strata::gr_up_wide_default(false, major, minor, strata::qwen_defaults_026()) ? 2 : 1; 497 cudaGetLastError(); // drop what an attribute query on a CPU-only box leaves behind 498 } 499 return per_dev[dev] == 2; 500#endif 501} 502 503template <int MAX_T = kFusedGrMaxT, bool EXACT_T = false> 504__global__ void __launch_bounds__(THREADS) gr_up_wide_kernel(GrMulti m) { 505 __shared__ __align__(16) float lo[MAX_T][LR]; 506 __shared__ float g[MAX_T][HC][UPW_COLS]; 507 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; 508 const int T = EXACT_T ? MAX_T : m.T; 509 const int d0 = blockIdx.x * UPW_COLS; 510 for (int i = t; i < T * LR; i += THREADS) lo[i / LR][i % LR] = m.a[i / LR].lo[i % LR]; 511 __syncthreads(); 512 if (warp < HC * UPW_COLS) { 513 const int c = warp / UPW_COLS, dd = warp - c * UPW_COLS, i = c * N + d0 + dd; 514 const uint4* w4 = reinterpret_cast<const uint4*>(m.a[0].w_up + (size_t) i * LR); 515 const Bf16x8 wa = unpack8(__ldg(w4 + lane)); 516 const Bf16x8 wb = unpack8(lane < LR / 8 - 32 ? __ldg(w4 + 32 + lane) : make_uint4(0, 0, 0, 0)); 517 float rv = 0.0f, wn = 0.0f, rsc = 0.0f, bo = 0.0f, ip = 0.0f; 518 bool apply = false; 519 if (lane < T) { 520 const FusedGrArgs& a = m.a[lane]; 521 rv = a.R[i]; 522 wn = a.w_norm[i]; 523 rsc = a.rs[c]; 524 apply = a.apply; 525 if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; } 526 } 527 float mine = 0.0f; 528#pragma unroll 529 for (int k = 0; k < MAX_T; ++k) { 530 if (!EXACT_T && k >= T) break; 531 float acc = dot8u_ptr(wa, lo[k] + lane * 8); 532 if (lane < LR / 8 - 32) acc += dot8u_ptr(wb, lo[k] + (32 + lane) * 8); 533 acc = warp_sum(acc); 534 if (lane == k) mine = acc; 535 } 536 if (lane < T) { 537 if (apply) { 538 rv = fmaf(bo, 2.0f * sigmoidf_(ip / (float) HC), rv); 539 m.a[lane].R_out[i] = rv; 540 } 541 const float x = rv * wn * rsc; 542 g[lane][c][dd] = x * sigmoidf_(mine); 543 } 544 } 545 __syncthreads(); 546 for (int i = t; i < T * UPW_COLS; i += THREADS) { 547 const int k = i / UPW_COLS, col = i - k * UPW_COLS; 548 float s = 0.0f; 549#pragma unroll 550 for (int c = 0; c < HC; ++c) s += g[k][c][col]; 551 m.a[k].mixed[d0 + col] = s / (float) HC; 552 } 553} 554 555// Turing (sm_75): gr_up_multi_kernel's rows, sums and epilogue with the latency taken out of the warp's chain. A warp's 556// 8 rows of w_up are all loaded before any dot (was: one row's load after the previous row's epilogue: ~9k of the 557// warp's ~22k cycles were waits on memory, ncu on an RTX 2080 Ti); a token's 8 activations per lane are read from 558// shared memory once for the 8 rows; and the 8 rows' xor reductions run interleaved (8 independent shuffles per stage 559// instead of one chain of 5 per row). A row's last 8 chunks (lanes 0-7 of gr_up_multi_kernel) are held 4 rows to a 560// uint4 - lane 8 i + j holds chunk 32 + j of row i - and their dot is shuffled to lane j before it is added, so lane j 561// still sums its two dots in gr_up_multi_kernel's order. Every row's lane sums, xor tree and epilogue are 562// gr_up_multi_kernel's: the same bits. STRATA_GR_UP75=0 keeps gr_up_multi_kernel. 563template <int MAX_T = kFusedGrMaxT, bool EXACT_T = false> 564__global__ void __launch_bounds__(THREADS, 4) gr_up75_kernel(GrMulti m) { 565 constexpr int RPW = HC * UPM_COLS / WARPS; // 8 rows per warp: row r = warp + WARPS i -> stream i / 2 566 static_assert(RPW == 8 && UPM_COLS == 2 * WARPS && HC == 4, "geometry"); // the tail of 8 chunks (LR == 320) is checked where the kernel is launched (up75_on) 567 __shared__ __align__(16) float lo[MAX_T][LR]; 568 __shared__ float g[MAX_T][HC][UPM_COLS]; 569 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; 570 const int T = EXACT_T ? MAX_T : m.T; 571 const int d0 = blockIdx.x * UPM_COLS; 572 const int tj = lane & 7, ti = lane >> 3; // tail: chunk 32 + tj of row 4 b + ti 573 float mine[RPW]; 574#pragma unroll 575 for (int i = 0; i < RPW; ++i) mine[i] = 0.0f; 576#pragma unroll 577 for (int bt = 0; bt < 2; ++bt) { // two batches of 4 rows: 4 loads in flight, registers for 4 blocks 578 uint4 wa[4], wt; 579#pragma unroll 580 for (int i = 0; i < 4; ++i) { 581 const int r = 4 * bt + i, c = r >> 1, dd = warp + WARPS * (r & 1), row = c * N + d0 + dd; 582 wa[i] = __ldg(reinterpret_cast<const uint4*>(m.a[0].w_up + (size_t) row * LR) + lane); 583 } 584 { 585 const int r = 4 * bt + ti, c = r >> 1, dd = warp + WARPS * (r & 1), row = c * N + d0 + dd; 586 wt = __ldg(reinterpret_cast<const uint4*>(m.a[0].w_up + (size_t) row * LR) + 32 + tj); 587 } 588 if (bt == 0) { 589 for (int i = t; i < T * LR; i += THREADS) lo[i / LR][i % LR] = m.a[i / LR].lo[i % LR]; 590 __syncthreads(); 591 } 592#pragma unroll 1 593 for (int k = 0; k < T; ++k) { 594 const float4* la = reinterpret_cast<const float4*>(lo[k] + lane * 8); 595 const float4* lb = reinterpret_cast<const float4*>(lo[k] + (32 + tj) * 8); 596 const float tb = dot8u(unpack8(wt), lb[0], lb[1]); 597 const float4 x0 = la[0], x1 = la[1]; 598 float p[4]; 599#pragma unroll 600 for (int i = 0; i < 4; ++i) { 601 const float b = __shfl_sync(0xffffffffu, tb, i * 8 + tj); 602 float acc = dot8u(unpack8(wa[i]), x0, x1); 603 if (lane < 8) acc += b; 604 p[i] = acc; 605 } 606#pragma unroll 607 for (int o = 16; o > 0; o >>= 1) { 608#pragma unroll 609 for (int i = 0; i < 4; ++i) p[i] += __shfl_xor_sync(0xffffffffu, p[i], o); 610 } 611 if (lane == k) { 612#pragma unroll 613 for (int i = 0; i < 4; ++i) mine[4 * bt + i] = p[i]; 614 } 615 } 616 } 617 if (lane < T) { 618 const FusedGrArgs& a = m.a[lane]; 619 const bool apply = a.apply; 620 float rv[RPW], wn[RPW], bo[RPW]; 621#pragma unroll 622 for (int i = 0; i < RPW; ++i) { 623 const int c = i >> 1, dd = warp + WARPS * (i & 1), row = c * N + d0 + dd; 624 rv[i] = a.R[row]; 625 wn[i] = a.w_norm[row]; 626 bo[i] = apply ? a.bo_prev[d0 + dd] : 0.0f; 627 } 628#pragma unroll 629 for (int i = 0; i < RPW; ++i) { 630 const int c = i >> 1, dd = warp + WARPS * (i & 1), row = c * N + d0 + dd; 631 float x0 = rv[i]; 632 if (apply) { 633 x0 = fmaf(bo[i], 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC), x0); 634 a.R_out[row] = x0; 635 } 636 const float x = x0 * wn[i] * a.rs[c]; 637 g[lane][c][dd] = x * sigmoidf_(mine[i]); 638 } 639 } 640 __syncthreads(); 641 for (int i = t; i < T * UPM_COLS; i += THREADS) { 642 const int k = i / UPM_COLS, col = i - k * UPM_COLS; 643 float s = 0.0f; 644#pragma unroll 645 for (int c = 0; c < HC; ++c) s += g[k][c][col]; 646 m.a[k].mixed[d0 + col] = s / (float) HC; 647 } 648 if (m.a[0].q8_mixed != nullptr) gr_q8_tail(m, d0); // S26 STRATA_QFUSE, as gr_up_multi_kernel 649} 650 651 652// 143-amdk (STRATA_QFUSE_HC): gr_up_multi_kernel with 32 columns a block (512 threads, 80 blocks, the same 8 rows a warp), so a block owns a whole 653// q8_1 group of `mixed` and writes its image itself. STRATA_QFUSE's version (16 columns a block) needs a counter, two fences and a last block 654// to finish the group; this one needs none. Every row's math is gr_up_multi_kernel's. Needs q8_mixed set for every token. 655constexpr int Q32_COLS = 32, Q32_THREADS = 512, Q32_WARPS = Q32_THREADS / 32, Q32_BLOCKS = N / Q32_COLS; 656template <int MAX_T = kFusedGrMaxT, bool EXACT_T = false> 657__global__ void __launch_bounds__(Q32_THREADS) gr_up_q32_kernel(GrMulti m) { 658 __shared__ __align__(16) float lo[MAX_T][LR]; 659 __shared__ float g[MAX_T][HC][Q32_COLS]; 660 __shared__ float mixed_s[MAX_T][Q32_COLS]; 661 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; 662 const int T = EXACT_T ? MAX_T : m.T; 663 const int d0 = blockIdx.x * Q32_COLS; 664 for (int i = t; i < T * LR; i += Q32_THREADS) lo[i / LR][i % LR] = m.a[i / LR].lo[i % LR]; 665 __syncthreads(); 666 for (int r = warp; r < HC * Q32_COLS; r += Q32_WARPS) { 667 const int c = r / Q32_COLS, dd = r - c * Q32_COLS, i = c * N + d0 + dd; 668 const uint4* w4 = reinterpret_cast<const uint4*>(m.a[0].w_up + (size_t) i * LR); 669 const Bf16x8 wa = unpack8(__ldg(w4 + lane)); 670 const Bf16x8 wb = unpack8(lane < LR / 8 - 32 ? __ldg(w4 + 32 + lane) : make_uint4(0, 0, 0, 0)); 671 // the epilogue inputs of this lane's token, fetched while the dots run 672 float rv = 0.0f, wn = 0.0f, rsc = 0.0f, bo = 0.0f, ip = 0.0f; 673 bool apply = false; 674 if (lane < T) { 675 const FusedGrArgs& a = m.a[lane]; 676 rv = a.R[i]; 677 wn = a.w_norm[i]; 678 rsc = a.rs[c]; 679 apply = a.apply; 680 if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; } 681 } 682 float mine = 0.0f; 683#pragma unroll 684 for (int k = 0; k < MAX_T; ++k) { 685 if (!EXACT_T && k >= T) break; 686 float acc = dot8u_ptr(wa, lo[k] + lane * 8); 687 if (lane < LR / 8 - 32) acc += dot8u_ptr(wb, lo[k] + (32 + lane) * 8); 688 acc = warp_sum(acc); 689 if (lane == k) mine = acc; 690 } 691 if (lane < T) { 692 if (apply) { 693 rv = fmaf(bo, 2.0f * sigmoidf_(ip / (float) HC), rv); 694 m.a[lane].R_out[i] = rv; 695 } 696 const float x = rv * wn * rsc; 697 g[lane][c][dd] = x * sigmoidf_(mine); 698 } 699 } 700 __syncthreads(); 701 for (int i = t; i < T * Q32_COLS; i += Q32_THREADS) { 702 const int k = i / Q32_COLS, col = i - k * Q32_COLS; 703 float s = 0.0f; 704#pragma unroll 705 for (int c = 0; c < HC; ++c) s += g[k][c][col]; 706 const float v = s / (float) HC; 707 m.a[k].mixed[d0 + col] = v; 708 mixed_s[k][col] = v; 709 } 710 __syncthreads(); 711 // the block owns the whole q8_1 group (32 columns): quantize it here, no counter, no fence. One warp a token, the 712 // quantizer of gr_q8_tail (native_quantize_q8_1's: XOR-tree max and sum, d = amax / 127, roundf(x / d)). 713 if (warp < T) { 714 const float xi = mixed_s[warp][lane]; 715 float amax = fabsf(xi), sum = xi; 716#pragma unroll 717 for (int o = 16; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); 718#pragma unroll 719 for (int o = 16; o > 0; o >>= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); 720 const float d = q8_1_finite(q81_div(amax, 127.0f)); 721 const int8_t q = q8_1_quant(xi, d, amax); 722 GrQ81* y = reinterpret_cast<GrQ81*>(m.a[warp].q8_mixed) + d0 / 32; 723 y->qs[lane] = q; 724 if (lane == 0) y->ds = q8_1_ds(d, sum); 725 } 726} 727 728 729 730// ================================ hc read v3 (opt-in: STRATA_GR_V3=1) - two kernels, stream-split ================ 731// The norm kernel runs on only T blocks (~16 us of pure latency per call) and `down` on 41 blocks (~280 GB/s). 732// v3: `down` is split over (row group, stream[, column half]) = 164 or 328 blocks; each block stages its slice of 733// R' * w_norm for the T tokens, reduces that slice's sum of squares itself, and writes UNSCALED partial dots. The 734// rms scale is per stream, so w_down . xn = sum_c rs[c] * (w_down[:, c] . (R'[c] * w_norm[c])) - `up` applies it 735// in its prologue (lo, inject, rs). Same maths, ANOTHER SUMMATION ORDER: not bitwise the default kernels, hence 736// opt-in. Dynamic shared memory is T * (N / S) floats: S (1 or 2 column halves) is the smallest that fits the 737// card's opt-in limit at kFusedGrMaxT tokens (Ampere 99 KB: S = 1; Turing / HIP 64 KB: S = 2); a card where 738// neither fits keeps the default kernels. 739constexpr int PR = LR + HC; // partial rows per (token, stream): 320 down + 4 inject 740 741// BW-DENSE (STRATA_GR_V3_PF): the v3 kernels issue their weight loads FIRST, into registers, so the DRAM fetch overlaps the 742// prologue (gr_down: staging R / bo / w_norm into shared memory; gr_up: the partial sums -> lo) instead of starting behind it. 743// The same loads, the same values, the same arithmetic in the same order: bitwise the kernels without it (gr_v3_screen). 744// ld.global.nc as a volatile asm so the compiler cannot sink the load back to its first use, behind the barrier. 745__device__ __forceinline__ uint4 ldg_v4(const uint4* p) { 746#if defined(__HIPCC__) 747 return *p; // (PTX does not exist on HIP; the plain load) 748#else 749 uint4 v; 750 asm volatile("ld.global.nc.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(v.x), "=r"(v.y), "=r"(v.z), "=r"(v.w) : "l"(p)); 751 return v; 752#endif 753} 754constexpr int TQ3 = N / 8 / 32; // uint4 weight chunks per lane in one stream's slice (10) 755 756// PF (BW-DENSE, bitwise the PF = 0 kernel): bit 0 issues the staging's loads (R, bo, w_norm of every token) before using any 757// of them; bit 1 loads the warp's weight row into registers first. R2V == 1, S == 1 only. 758// RB (DF2-MORE, STRATA_GR_V3_PF bit 7 (windows of 5+ rows, 2 rows a warp) / bit 8 (4 rows, any window), R2V > 1 only, bitwise the RB = false kernel): the dot phase loops over the lane's chunks first, then the tokens, then 759// the warp's R2V rows, so a token's 8 activations are read from shared memory once for all R2V rows (it was once per row). Each (row, token) accumulator 760// adds the same chunk dots in the same ascending order, then the same warp reduction. 761template <int S, int MAX_T = kFusedGrMaxT, bool EXACT_T = false, int R2V = 1, int PF = 0, bool RB = false> 762__global__ void __launch_bounds__(THREADS) gr_down_v3_kernel(GrMulti m, float* __restrict__ part, float* __restrict__ ssg) { 763 extern __shared__ __align__(16) float xs[]; // [T][N / S] 764 constexpr int R2 = R2V; // down rows per warp (R2V > 1: fewer blocks, each stages its stream slice once for R2V x the rows; the same dots) 765 __shared__ float red[WARPS][MAX_T]; 766 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; 767 const int T = EXACT_T ? MAX_T : m.T; 768 // S = 2: each stream's 2560 columns in two halves (blockIdx.y = stream * S + half): twice the blocks 769 constexpr int SL = N / S, TQS = SL / 8 / 32; 770 const int rg = blockIdx.x, c = blockIdx.y / S, h = blockIdx.y - (blockIdx.y / S) * S; 771 constexpr int NDB = LR / (WARPS * R2); // down row blocks per stream; block NDB = the inject rows 772 const bool inject_block = rg == NDB; 773 // warp w owns rows row0 + w * R2 + r (r < R2); the inject block: warps 0-3, one row each 774 const int row0 = inject_block ? warp : (rg * WARPS + warp) * R2; 775 const int nrows = inject_block ? ((m.a[0].w_inject != nullptr && warp < HC) ? 1 : 0) : R2; 776 const bool active = nrows > 0; 777 const uint16_t* wbase = inject_block ? m.a[0].w_inject : m.a[0].w_down; 778 uint4 wq[(PF & 2) ? TQS : 1]; // PF bit 1: this warp's row of weights, loaded before the staging below 779 if constexpr (PF != 0) static_assert(R2V == 1 && S == 1, "the prefetch variants are for the one-row-a-warp kernels"); 780 if constexpr ((PF & 2) != 0) { 781 if (active) { 782 const uint4* w4 = reinterpret_cast<const uint4*>(wbase + (size_t) row0 * D + (size_t) c * N + (size_t) h * SL); 783#pragma unroll 784 for (int q = 0; q < TQS; ++q) wq[q] = ldg_v4(w4 + lane + 32 * q); 785 } 786 } 787 float ssp[MAX_T]; 788 if constexpr ((PF & 1) != 0) { 789 // the same per-thread sums in the same order (items i = t, t + THREADS, ... ascending, tokens in order), with the 790 // loads of a group of tokens in flight together instead of one dependent L2 round trip per item 791 constexpr int NI = (SL / 4 + THREADS - 1) / THREADS; 792 constexpr int TG = MAX_T < 4 ? MAX_T : 4; 793 float4 gv[NI]; 794#pragma unroll 795 for (int ii = 0; ii < NI; ++ii) { 796 const int i = t + ii * THREADS; 797 gv[ii] = i < SL / 4 ? reinterpret_cast<const float4*>(m.a[0].w_norm + (size_t) c * N + (size_t) h * SL)[i] : make_float4(0.f, 0.f, 0.f, 0.f); 798 } 799#pragma unroll 800 for (int k0 = 0; k0 < MAX_T; k0 += TG) { 801 float4 rv[TG][NI], bv[TG][NI]; 802#pragma unroll 803 for (int kk = 0; kk < TG; ++kk) { 804 const int k = k0 + kk; 805 if (k >= MAX_T || (!EXACT_T && k >= T)) continue; 806 const FusedGrArgs& a = m.a[k]; 807 const float4* R4 = reinterpret_cast<const float4*>(a.R + (size_t) c * N + (size_t) h * SL); 808 const float4* B4 = reinterpret_cast<const float4*>(a.bo_prev + (size_t) h * SL); 809#pragma unroll 810 for (int ii = 0; ii < NI; ++ii) { 811 const int i = t + ii * THREADS; 812 rv[kk][ii] = i < SL / 4 ? R4[i] : make_float4(0.f, 0.f, 0.f, 0.f); 813 bv[kk][ii] = (a.apply && i < SL / 4) ? B4[i] : make_float4(0.f, 0.f, 0.f, 0.f); 814 } 815 } 816#pragma unroll 817 for (int kk = 0; kk < TG; ++kk) { 818 const int k = k0 + kk; 819 if (k >= MAX_T) continue; 820 ssp[k] = 0.0f; 821 if (!EXACT_T && k >= T) continue; 822 const FusedGrArgs& a = m.a[k]; 823 const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; 824 float4* X4 = reinterpret_cast<float4*>(xs + (size_t) k * SL); 825#pragma unroll 826 for (int ii = 0; ii < NI; ++ii) { 827 const int i = t + ii * THREADS; 828 if (i < SL / 4) { 829 float4 r = rv[kk][ii]; 830 if (a.apply) { 831 const float4 b = bv[kk][ii]; 832 r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y); 833 r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w); 834 } 835 const float4 g = gv[ii]; 836 ssp[k] += r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; 837 X4[i] = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w); 838 } 839 } 840 } 841 } 842 } else { 843#pragma unroll 844 for (int k = 0; k < MAX_T; ++k) { 845 ssp[k] = 0.0f; 846 if (!EXACT_T && k >= T) continue; 847 const FusedGrArgs& a = m.a[k]; 848 const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; 849 const float4* R4 = reinterpret_cast<const float4*>(a.R + (size_t) c * N + (size_t) h * SL); 850 const float4* G4 = reinterpret_cast<const float4*>(a.w_norm + (size_t) c * N + (size_t) h * SL); 851 const float4* B4 = reinterpret_cast<const float4*>(a.bo_prev + (size_t) h * SL); 852 float4* X4 = reinterpret_cast<float4*>(xs + (size_t) k * SL); 853 for (int i = t; i < SL / 4; i += THREADS) { 854 float4 r = R4[i]; 855 if (a.apply) { 856 const float4 b = B4[i]; 857 r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y); 858 r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w); 859 } 860 const float4 g = G4[i]; 861 ssp[k] += r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; 862 X4[i] = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w); 863 } 864 } 865 } 866#pragma unroll 867 for (int k = 0; k < MAX_T; ++k) { 868 if (!EXACT_T && k >= T) break; 869 const float v = warp_sum(ssp[k]); 870 if (lane == 0) red[warp][k] = v; 871 } 872 __syncthreads(); 873 if (rg == 0 && t < T) { 874 float sum = 0.0f; 875 for (int w = 0; w < WARPS; ++w) sum += red[w][t]; 876 ssg[(t * HC + c) * S + h] = sum; 877 } 878 if (!active) return; 879 if constexpr (RB && R2V > 1) { 880 static_assert(S == 1 && EXACT_T && PF == 0, "the register-blocked down dots are for the exact-T, one-half, plain-staging kernels"); 881 float accr[R2][MAX_T]; 882#pragma unroll 883 for (int r = 0; r < R2; ++r) 884#pragma unroll 885 for (int k = 0; k < MAX_T; ++k) accr[r][k] = 0.0f; 886 const uint4* w4r[R2]; 887#pragma unroll 888 for (int r = 0; r < R2; ++r) 889 w4r[r] = reinterpret_cast<const uint4*>(wbase + (size_t) (row0 + (r < nrows ? r : 0)) * D + (size_t) c * N + (size_t) h * SL); 890 uint4 wch[R2][TQS]; 891#pragma unroll 892 for (int q = 0; q < TQS; ++q) 893#pragma unroll 894 for (int r = 0; r < R2; ++r) wch[r][q] = __ldg(w4r[r] + lane + 32 * q); 895#pragma unroll 896 for (int q = 0; q < TQS; ++q) { 897 const int j = lane + 32 * q; 898 Bf16x8 wv[R2]; 899#pragma unroll 900 for (int r = 0; r < R2; ++r) wv[r] = unpack8(wch[r][q]); 901#pragma unroll 902 for (int k = 0; k < MAX_T; ++k) { 903 const float4* x4 = reinterpret_cast<const float4*>(xs + (size_t) k * SL + j * 8); 904 const float4 x0 = x4[0], x1 = x4[1]; 905#pragma unroll 906 for (int r = 0; r < R2; ++r) accr[r][k] += dot8u(wv[r], x0, x1); 907 } 908 } 909#pragma unroll 910 for (int r = 0; r < R2; ++r) { 911 if (r >= nrows) break; 912 const int prow = inject_block ? LR + warp : row0 + r; 913 if constexpr (MAX_T >= 5 && MAX_T <= 8) { 914 float accs[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; 915#pragma unroll 916 for (int k = 0; k < MAX_T; ++k) accs[k] = accr[r][k]; 917 const float d8 = warp_sum8(accs, lane); 918 const int k = (lane >> 2) & 7; 919 if ((lane & 3) == 0 && k < MAX_T) part[(((size_t) k * HC + c) * S + h) * PR + prow] = d8; 920 } else { 921#pragma unroll 922 for (int k = 0; k < MAX_T; ++k) { 923 const float v = warp_sum(accr[r][k]); 924 if (lane == 0) part[(((size_t) k * HC + c) * S + h) * PR + prow] = v; 925 } 926 } 927 } 928 return; 929 } 930#pragma unroll 931 for (int r = 0; r < R2; ++r) { 932 if (r >= nrows) break; 933 const uint4* w4 = reinterpret_cast<const uint4*>(wbase + (size_t) (row0 + r) * D + (size_t) c * N + (size_t) h * SL); 934 float acc[MAX_T]; 935#pragma unroll 936 for (int k = 0; k < MAX_T; ++k) acc[k] = 0.0f; 937#pragma unroll 938 for (int q = 0; q < TQS; ++q) { 939 const int j = lane + 32 * q; 940 Bf16x8 wvq; 941 if constexpr ((PF & 2) != 0) wvq = unpack8(wq[q]); 942 else wvq = unpack8(__ldg(w4 + j)); 943#pragma unroll 944 for (int k = 0; k < MAX_T; ++k) 945 if (EXACT_T || k < T) acc[k] += dot8u_ptr(wvq, xs + (size_t) k * SL + j * 8); 946 } 947 const int prow = inject_block ? LR + warp : row0 + r; 948 if constexpr (EXACT_T && MAX_T >= 5 && MAX_T <= 8) { // warp_sum8: token k's total sits in lanes 4k..4k+3 949 float accs[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; 950#pragma unroll 951 for (int k = 0; k < MAX_T; ++k) accs[k] = acc[k]; 952 const float d8 = warp_sum8(accs, lane); 953 const int k = (lane >> 2) & 7; 954 if ((lane & 3) == 0 && k < MAX_T) part[(((size_t) k * HC + c) * S + h) * PR + prow] = d8; 955 } else { 956#pragma unroll 957 for (int k = 0; k < MAX_T; ++k) { 958 if (!EXACT_T && k >= T) break; 959 const float v = warp_sum(acc[k]); 960 if (lane == 0) part[(((size_t) k * HC + c) * S + h) * PR + prow] = v; 961 } 962 } 963 } 964} 965 966// PF (BW-DENSE, bitwise the PF = 0 kernel): bit 0 issues the loads of the partial sums and of every row's R / w_norm / bo / inj before 967// their first use (the in-place store of R in the row loop otherwise ends each row's loads at a full latency); bit 1 loads the 968// warp's w_up rows first. S == 1, EXACT_T only. 969// PF (BW-DENSE, bitwise the PF = 0 kernel): bit 0 issues the loads of the partial sums and of every row's R / w_norm / bo / inj before 970// their first use (the in-place store of R in the row loop otherwise ends each row's loads at a full latency); bit 1 loads the 971// warp's w_up rows first. S == 1, EXACT_T only. 972template <int S, int MAX_T = kFusedGrMaxT, bool EXACT_T = false, int PF = 0> 973__global__ void __launch_bounds__(THREADS) gr_up_v3_kernel(GrMulti m, const float* __restrict__ part, 974 const float* __restrict__ ssg) { 975 __shared__ __align__(16) float lo[MAX_T][LR]; 976 __shared__ float rsS[MAX_T][HC]; 977 __shared__ float g[MAX_T][HC][UPM_COLS]; 978 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; 979 const int T = EXACT_T ? MAX_T : m.T; 980 const int d0 = blockIdx.x * UPM_COLS; 981 constexpr int RPW = HC * UPM_COLS / WARPS; // 8 rows per warp 982 uint4 pwa[(PF & 2) ? RPW : 1], pwb[(PF & 2) ? RPW : 1]; // PF bit 1: the warp's 8 rows of w_up, loaded before the prologue 983 if constexpr (PF != 0) static_assert(S == 1 && EXACT_T, "the prefetch variants are for the exact-T, one-half kernels"); 984 if constexpr ((PF & 2) != 0) { 985#pragma unroll 986 for (int q = 0; q < RPW; ++q) { 987 const int r = warp + q * WARPS; 988 const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; 989 const uint4* w4 = reinterpret_cast<const uint4*>(m.a[0].w_up + (size_t) i * LR); 990 pwa[q] = ldg_v4(w4 + lane); 991 pwb[q] = lane < LR / 8 - 32 ? ldg_v4(w4 + 32 + lane) : make_uint4(0, 0, 0, 0); 992 } 993 } 994 constexpr int NIT = (MAX_T * LR + THREADS - 1) / THREADS; 995 float ppv[(PF & 1) ? NIT : 1][HC]; // PF bit 0: the partial sums lo is built from 996 float prv[(PF & 1) ? RPW : 1], pwn[(PF & 1) ? RPW : 1], pbo[(PF & 1) ? RPW : 1], pip[(PF & 1) ? RPW : 1]; 997 if constexpr ((PF & 1) != 0) { 998#pragma unroll 999 for (int it = 0; it < NIT; ++it) { 1000 const int i = t + it * THREADS; 1001#pragma unroll 1002 for (int c = 0; c < HC; ++c) { 1003 ppv[it][c] = 0.0f; 1004 if (i < MAX_T * LR) { 1005 const int k = i / LR, r = i - k * LR; 1006 ppv[it][c] = part[(((size_t) k * HC + c) * S + 0) * PR + r]; 1007 } 1008 } 1009 } 1010 if (lane < T) { 1011 const FusedGrArgs& a = m.a[lane]; 1012#pragma unroll 1013 for (int q = 0; q < RPW; ++q) { 1014 const int r = warp + q * WARPS; 1015 const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; 1016 prv[q] = a.R[i]; 1017 pwn[q] = a.w_norm[i]; 1018 pbo[q] = 0.0f; 1019 pip[q] = 0.0f; 1020 if (a.apply) { pbo[q] = a.bo_prev[d0 + dd]; pip[q] = a.inj_prev[c]; } 1021 } 1022 } 1023 } 1024 if (t < T * HC) { 1025 const int k = t / HC, c = t - k * HC; 1026 float ss = 0.0f; 1027#pragma unroll 1028 for (int h = 0; h < S; ++h) ss += ssg[t * S + h]; 1029 const float r = rsqrtf(ss / (float) N + m.a[k].eps); 1030 rsS[k][c] = r; 1031 if (blockIdx.x == 0) m.a[k].rs[c] = r; 1032 } 1033 __syncthreads(); 1034 if constexpr ((PF & 1) != 0) { 1035#pragma unroll 1036 for (int it = 0; it < NIT; ++it) { 1037 const int i = t + it * THREADS; 1038 if (i < MAX_T * LR) { 1039 const int k = i / LR, r = i - k * LR; 1040 float sum = 0.0f; 1041#pragma unroll 1042 for (int c = 0; c < HC; ++c) { 1043 float p = 0.0f; 1044 p += ppv[it][c]; 1045 sum = fmaf(rsS[k][c], p, sum); 1046 } 1047 const float x = sum / (float) HC; 1048 lo[k][r] = x / (1.0f + __expf(-x)); 1049 } 1050 } 1051 } else 1052 for (int i = t; i < T * LR; i += THREADS) { 1053 const int k = i / LR, r = i - k * LR; 1054 float sum = 0.0f; 1055#pragma unroll 1056 for (int c = 0; c < HC; ++c) { 1057 float p = 0.0f; 1058#pragma unroll 1059 for (int h = 0; h < S; ++h) p += part[(((size_t) k * HC + c) * S + h) * PR + r]; 1060 sum = fmaf(rsS[k][c], p, sum); 1061 } 1062 const float x = sum / (float) HC; 1063 lo[k][r] = x / (1.0f + __expf(-x)); 1064 } 1065 if (blockIdx.x == 0 && t < T * HC) { 1066 const int k = t / HC, cc = t - k * HC; 1067 if (m.a[k].w_inject != nullptr) { 1068 float sum = 0.0f; 1069#pragma unroll 1070 for (int c = 0; c < HC; ++c) { 1071 float p = 0.0f; 1072#pragma unroll 1073 for (int h = 0; h < S; ++h) p += part[(((size_t) k * HC + c) * S + h) * PR + LR + cc]; 1074 sum = fmaf(rsS[k][c], p, sum); 1075 } 1076 m.a[k].inject_out[cc] = sum; 1077 } 1078 } 1079 __syncthreads(); 1080#pragma unroll 1081 for (int q = 0; q < RPW; ++q) { 1082 const int r = warp + q * WARPS; 1083 const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; 1084 Bf16x8 wa, wb; 1085 if constexpr ((PF & 2) != 0) { 1086 wa = unpack8(pwa[q]); 1087 wb = unpack8(pwb[q]); 1088 } else { 1089 const uint4* w4 = reinterpret_cast<const uint4*>(m.a[0].w_up + (size_t) i * LR); 1090 wa = unpack8(__ldg(w4 + lane)); 1091 wb = unpack8(lane < LR / 8 - 32 ? __ldg(w4 + 32 + lane) : make_uint4(0, 0, 0, 0)); 1092 } 1093 float rv = 0.0f, wn = 0.0f, bo = 0.0f, ip = 0.0f; 1094 bool apply = false; 1095 if (lane < T) { 1096 const FusedGrArgs& a = m.a[lane]; 1097 apply = a.apply; 1098 if constexpr ((PF & 1) != 0) { rv = prv[q]; wn = pwn[q]; bo = pbo[q]; ip = pip[q]; } 1099 else { 1100 rv = a.R[i]; 1101 wn = a.w_norm[i]; 1102 if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; } 1103 } 1104 } 1105 float mine = 0.0f; 1106 if constexpr (EXACT_T && MAX_T >= 5 && MAX_T <= 8) { // the tokens' warp sums together (warp_sum8, missing tokens 0): the same bits 1107 float accs[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; 1108#pragma unroll 1109 for (int k = 0; k < MAX_T; ++k) { 1110 float acc = dot8u_ptr(wa, lo[k] + lane * 8); 1111 if (lane < LR / 8 - 32) acc += dot8u_ptr(wb, lo[k] + (32 + lane) * 8); 1112 accs[k] = acc; 1113 } 1114 const float d8 = warp_sum8(accs, lane); 1115 mine = __shfl_sync(0xffffffffu, d8, (lane & 7) << 2); 1116 } else { 1117#pragma unroll 1118 for (int k = 0; k < MAX_T; ++k) { 1119 if (!EXACT_T && k >= T) break; 1120 float acc = dot8u_ptr(wa, lo[k] + lane * 8); 1121 if (lane < LR / 8 - 32) acc += dot8u_ptr(wb, lo[k] + (32 + lane) * 8); 1122 acc = warp_sum(acc); 1123 if (lane == k) mine = acc; 1124 } 1125 } 1126 if (lane < T) { 1127 if (apply) { 1128 rv = fmaf(bo, 2.0f * sigmoidf_(ip / (float) HC), rv); 1129 m.a[lane].R_out[i] = rv; 1130 } 1131 const float x = rv * wn * rsS[lane][c]; 1132 g[lane][c][dd] = x * sigmoidf_(mine); 1133 } 1134 } 1135 __syncthreads(); 1136 for (int i = t; i < T * UPM_COLS; i += THREADS) { 1137 const int k = i / UPM_COLS, col = i - k * UPM_COLS; 1138 float sum = 0.0f; 1139#pragma unroll 1140 for (int c = 0; c < HC; ++c) sum += g[k][c][col]; 1141 m.a[k].mixed[d0 + col] = sum / (float) HC; 1142 } 1143} 1144// ================================ #315: split / staged - the same arithmetic, split differently ================== 1145// The multi read's variants beside the plain read (0.1.31's default; not main's opt-in STRATA_GR_V3 read, which sums 1146// in another order). Every variant computes each output with exactly the plain read's operations in its order (so 1147// bitwise the plain read and the single-token read); only who does what, and when, changes. `fused_gr_check` 1148// compares them on the card before a verify window uses them (STRATA_HC_SPLIT below). 1149// - the norm (split and staged): one block per token AND stream instead of one per token. Each thread visits 1150// exactly the elements, in the order, it visited for that stream in the plain read, so every sum of squares and rs 1151// is the same; it stores R' * w_norm and scales it in place, with the plain read's two roundings. 1152// Before this scratch reuse, the split norm measured 0.23 ms per 4-token round (96 launches) on an RTX 4080 1153// SUPER, compared with 0.58 ms for the plain read's norm. 1154// - the down projection, split: the plain read's kernel. 1155// - the down projection, staged: the plain read's 8 rows per block and lane order, but the activations arrive by 1156// cp.async in half-stream tiles, two in flight, so no thread waits on a chain of loads, and they sit in shared 1157// memory as two planes (floats 0-3 and 4-7 of every 8), so a warp's reads hit no bank twice. The next tile's 1158// weights are loaded while the current one is used. A tile is 160 = 5 x 32 chunks of 8, so a lane still 1159// accumulates its chunks lane + 32 q in ascending order, as in the plain read with either tile. Before sm_80 1160// (and on HIP) the staging is a plain copy: the same bits, only not asynchronous. 1161constexpr int kHcPlain = 1, kHcSplit = 2, kHcStaged = 3; 1162constexpr int H_TILE = N / 2; // staged tile: half a stream = 160 chunks of 8, 5 per lane (1280 for Flash-Next) 1163constexpr int HQ = H_TILE / 8 / 32; 1164constexpr int N_HTILES = D / H_TILE; // 8 1165static_assert(N % H_TILE == 0 && N % 512 == 0, "a staged tile never straddles two streams"); 1166static_assert(H_TILE % 256 == 0, "a staged tile holds whole rounds of 32 chunks: the plain read's lane order"); 1167 1168__global__ void __launch_bounds__(THREADS) gr_norm_split_kernel(GrMulti m) { 1169 __shared__ float part[WARPS]; 1170 __shared__ float s_rs; 1171 const FusedGrArgs& a = m.a[blockIdx.x]; 1172 const int c = blockIdx.y; 1173 float* xn = m.xn + (size_t) blockIdx.x * D; 1174 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; 1175 const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; 1176 float ss = 0.0f; 1177 for (int i = t * 4; i < D; i += THREADS * 4) { 1178 if (i / N != c) continue; // another stream's element: another block's 1179 const int d = i - c * N; 1180 float4 r = *reinterpret_cast<const float4*>(a.R + i); 1181 if (a.apply) { 1182 const float4 b = *reinterpret_cast<const float4*>(a.bo_prev + d); 1183 r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y); 1184 r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w); 1185 } 1186 const float sq = r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; 1187 ss += sq; 1188 // Retain the unscaled product in the existing scratch instead of reloading R 1189 // and recomputing the pending write after the reduction. 1190 const float4 g = *reinterpret_cast<const float4*>(a.w_norm + i); 1191 *reinterpret_cast<float4*>(xn + i) = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w); 1192 } 1193 const float v = warp_sum(ss); 1194 if (lane == 0) part[warp] = v; 1195 __syncthreads(); 1196 if (t == 0) { 1197 float s = 0.0f; 1198 for (int w = 0; w < WARPS; ++w) s += part[w]; 1199 s_rs = rsqrtf(s / (float) N + a.eps); 1200 a.rs[c] = s_rs; 1201 } 1202 __syncthreads(); 1203 const float rs = s_rs; 1204 for (int d = t; d < N; d += THREADS) xn[c * N + d] *= rs; 1205} 1206 1207// 143-amdk: gr_norm_split_kernel with the loads of a thread's (at most three) float4 issued together and the scaled 1208// product written once from registers. The same elements go through the same operations in the same order (the 1209// thread's own sum of squares ascends in k; the warp sum, part[] sum and rsqrt are the kernel's), so rs and xn are 1210// bitwise the same; what goes is the loop's one-iteration-at-a-time loads and the second pass that read xn back from 1211// global memory (a write, a barrier, a read: two memory latencies). 1212__global__ void __launch_bounds__(THREADS) gr_norm_split_fast_kernel(GrMulti m) { 1213 __shared__ float part[WARPS]; 1214 __shared__ float s_rs; 1215 const FusedGrArgs& a = m.a[blockIdx.x]; 1216 const int c = blockIdx.y; 1217 float* xn = m.xn + (size_t) blockIdx.x * D; 1218 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; 1219 const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; 1220 // the thread's float4 of stream c: i = 4 t + 1024 k in [c N, (c + 1) N), ascending k; N / 1024 = 2.5 -> at most 3 1221 constexpr int KS = 3; 1222 int k0 = (c * N - 4 * t + THREADS * 4 - 1) / (THREADS * 4); 1223 if (k0 < 0) k0 = 0; 1224 float4 r[KS], g[KS]; 1225 bool ok[KS]; 1226#pragma unroll 1227 for (int j = 0; j < KS; ++j) { 1228 const int i = t * 4 + (k0 + j) * THREADS * 4; 1229 ok[j] = i < (c + 1) * N; 1230 if (ok[j]) { 1231 r[j] = *reinterpret_cast<const float4*>(a.R + i); 1232 g[j] = *reinterpret_cast<const float4*>(a.w_norm + i); 1233 if (a.apply) { 1234 const float4 b = *reinterpret_cast<const float4*>(a.bo_prev + (i - c * N)); 1235 r[j].x = fmaf(b.x, gw, r[j].x); r[j].y = fmaf(b.y, gw, r[j].y); 1236 r[j].z = fmaf(b.z, gw, r[j].z); r[j].w = fmaf(b.w, gw, r[j].w); 1237 } 1238 } 1239 } 1240 float ss = 0.0f; 1241#pragma unroll 1242 for (int j = 0; j < KS; ++j) { 1243 if (ok[j]) { 1244 const float sq = r[j].x * r[j].x + r[j].y * r[j].y + r[j].z * r[j].z + r[j].w * r[j].w; 1245 ss += sq; 1246 r[j] = make_float4(r[j].x * g[j].x, r[j].y * g[j].y, r[j].z * g[j].z, r[j].w * g[j].w); 1247 } 1248 } 1249 const float v = warp_sum(ss); 1250 if (lane == 0) part[warp] = v; 1251 __syncthreads(); 1252 if (t == 0) { 1253 float s = 0.0f; 1254 for (int w = 0; w < WARPS; ++w) s += part[w]; 1255 s_rs = rsqrtf(s / (float) N + a.eps); 1256 a.rs[c] = s_rs; 1257 } 1258 __syncthreads(); 1259 const float rs = s_rs; 1260#pragma unroll 1261 for (int j = 0; j < KS; ++j) 1262 if (ok[j]) 1263 *reinterpret_cast<float4*>(xn + t * 4 + (k0 + j) * THREADS * 4) = 1264 make_float4(r[j].x * rs, r[j].y * rs, r[j].z * rs, r[j].w * rs); 1265} 1266 1267#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 && !defined(__HIPCC__) 1268#define STRATA_GR_CP_ASYNC 1 1269#endif 1270__device__ __forceinline__ void cp_async16(void* smem, const void* gmem) { 1271#if defined(STRATA_GR_CP_ASYNC) 1272 const unsigned sa = (unsigned) __cvta_generic_to_shared(smem); 1273 asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(sa), "l"(gmem) : "memory"); 1274#else 1275 *reinterpret_cast<float4*>(smem) = *reinterpret_cast<const float4*>(gmem); 1276#endif 1277} 1278__device__ __forceinline__ void cp_async_commit() { 1279#if defined(STRATA_GR_CP_ASYNC) 1280 asm volatile("cp.async.commit_group;\n" ::: "memory"); 1281#endif 1282} 1283__device__ __forceinline__ void cp_async_wait1() { 1284#if defined(STRATA_GR_CP_ASYNC) 1285 asm volatile("cp.async.wait_group 1;\n" ::: "memory"); 1286#endif 1287} 1288__device__ __forceinline__ void cp_async_wait0() { 1289#if defined(STRATA_GR_CP_ASYNC) 1290 asm volatile("cp.async.wait_group 0;\n" ::: "memory"); 1291#endif 1292} 1293 1294// `dot8` with its 8 activations as two float4: the same eight fmaf in the same order 1295__device__ __forceinline__ float dot8v(const uint4 w, const float4 x0, const float4 x1) { 1296 float acc = 0.0f; 1297 acc = fmaf(__uint_as_float(w.x << 16), x0.x, acc); 1298 acc = fmaf(__uint_as_float(w.x & 0xffff0000u), x0.y, acc); 1299 acc = fmaf(__uint_as_float(w.y << 16), x0.z, acc); 1300 acc = fmaf(__uint_as_float(w.y & 0xffff0000u), x0.w, acc); 1301 acc = fmaf(__uint_as_float(w.z << 16), x1.x, acc); 1302 acc = fmaf(__uint_as_float(w.z & 0xffff0000u), x1.y, acc); 1303 acc = fmaf(__uint_as_float(w.w << 16), x1.z, acc); 1304 acc = fmaf(__uint_as_float(w.w & 0xffff0000u), x1.w, acc); 1305 return acc; 1306} 1307 1308// Stage tile `h` of every token into `buf`: [T][2 planes][160 chunks] float4, plane 0 = floats 0-3 of a chunk. 1309__device__ __forceinline__ void stage_htile(const GrMulti& m, int T, int h, float4* buf, int t, int k0 = 0) { 1310 for (int i = t; i < T * (H_TILE / 4); i += THREADS) { 1311 const int k = i / (H_TILE / 4), s4 = i - k * (H_TILE / 4); // s4: float4 of the tile, chunk s4/2, half s4&1 1312 const float* src = m.xn + (size_t) (k0 + k) * D + (size_t) h * H_TILE + (size_t) s4 * 4; 1313 cp_async16(buf + (size_t) k * (H_TILE / 4) + (s4 & 1) * (H_TILE / 8) + (s4 >> 1), src); 1314 } 1315} 1316 1317template <int MAX_T = kFusedGrMaxT, bool EXACT_T = false> 1318__global__ void __launch_bounds__(THREADS) gr_down_staged_kernel(GrMulti m) { 1319 extern __shared__ __align__(16) float4 hbuf[]; // 2 buffers x [T][2][160] float4 1320 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; 1321 const int T = EXACT_T ? MAX_T : m.T; 1322 // sm_75: a launch of EXACT_T groups of MAX_T tokens, one per blockIdx.y (gridDim.y 1: the whole launch); every 1323 // (row, token) is summed by one warp exactly as before - only more blocks share the card (#down-tg) 1324 const int k0 = EXACT_T ? (int) blockIdx.y * MAX_T : 0; 1325 const bool inject_block = blockIdx.x == DOWN_BLOCKS; 1326 const int row = inject_block ? warp : blockIdx.x * WARPS + warp; 1327 const bool active = !(inject_block && (m.a[0].w_inject == nullptr || warp >= HC)); 1328 const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D; 1329 const uint4* w4 = reinterpret_cast<const uint4*>(wrow); 1330 const size_t buf_f4 = (size_t) T * (H_TILE / 4); // float4 per buffer (the second one follows the first) 1331 float acc[MAX_T]; 1332#pragma unroll 1333 for (int k = 0; k < MAX_T; ++k) acc[k] = 0.0f; 1334 uint4 wv[HQ], wnext[HQ]; 1335 if (active) { 1336#pragma unroll 1337 for (int q = 0; q < HQ; ++q) wv[q] = __ldg(w4 + lane + 32 * q); 1338 } 1339 stage_htile(m, T, 0, hbuf, t, k0); 1340 cp_async_commit(); 1341 stage_htile(m, T, 1, hbuf + buf_f4, t, k0); 1342 cp_async_commit(); 1343#pragma unroll 1 1344 for (int h = 0; h < N_HTILES; ++h) { 1345 if (active && h + 1 < N_HTILES) { 1346#pragma unroll 1347 for (int q = 0; q < HQ; ++q) wnext[q] = __ldg(w4 + (h + 1) * (H_TILE / 8) + lane + 32 * q); 1348 } 1349 if (h + 1 < N_HTILES) cp_async_wait1(); // tile h has landed (h + 1 may still be on its way) 1350 else cp_async_wait0(); 1351 __syncthreads(); 1352 const float4* cur = hbuf + (h & 1) * buf_f4; 1353 if (active) { 1354#pragma unroll 1355 for (int q = 0; q < HQ; ++q) { 1356 const int j = lane + 32 * q; 1357 const Bf16x8 wvq = unpack8(wv[q]); 1358#pragma unroll 1359 for (int k = 0; k < MAX_T; ++k) { 1360 if (EXACT_T || k < T) { 1361 const float4* pk = cur + (size_t) k * (H_TILE / 4); 1362 acc[k] += dot8u(wvq, pk[j], pk[H_TILE / 8 + j]); 1363 } 1364 } 1365 } 1366 } 1367 __syncthreads(); // every warp is done with buffer h & 1 1368 if (h + 2 < N_HTILES) stage_htile(m, T, h + 2, hbuf + (h & 1) * buf_f4, t, k0); 1369 cp_async_commit(); // an empty group at the end keeps the wait counts simple 1370 if (h + 1 < N_HTILES) { 1371#pragma unroll 1372 for (int q = 0; q < HQ; ++q) wv[q] = wnext[q]; 1373 } 1374 } 1375 if (!active) return; 1376 float s[MAX_T]; 1377#pragma unroll 1378 for (int k = 0; k < MAX_T; ++k) s[k] = (EXACT_T || k < T) ? warp_sum(acc[k]) : 0.0f; 1379 // lane k writes token k (every lane holds every sum after the xor reduction) 1380#pragma unroll 1381 for (int k = 0; k < MAX_T; ++k) { 1382 if ((!EXACT_T && k >= T) || lane != k) continue; 1383 if (inject_block) { 1384 m.a[k0 + k].inject_out[row] = s[k]; 1385 } else { 1386 const float x = s[k] / (float) HC; 1387 m.a[k0 + k].lo[row] = x / (1.0f + __expf(-x)); 1388 } 1389 } 1390} 1391 1392// the current device is Volta (sm_70): the fast norm/up is its default 1393bool cur_dev_volta() { 1394#if defined(__HIPCC__) 1395 return false; 1396#else 1397 static int per_dev[64]; // 0 unknown, 1 no, 2 yes 1398 int dev = 0; 1399 if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false; 1400 if (!per_dev[dev]) { 1401 int major = 0, minor = 0; 1402 cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); 1403 cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev); 1404 per_dev[dev] = major == 7 && minor == 0 ? 2 : 1; 1405 } 1406 return per_dev[dev] == 2; 1407#endif 1408} 1409 1410// The tokens a down kernel may carry in one launch on the current card, and the plain read's tile: the plain read 1411// stages n_tok * TILEV floats ((N / 2) on sm_75, N elsewhere), staged two tiles of n_tok * H_TILE. The shared-memory 1412// opt-in is set here once per device (a per-DEVICE setting: a layer split runs these kernels on two cards). 1413int down_chunk(bool staged, int* tile_out) { 1414 static bool attr[64] = {}; 1415 static int chunk[64] = {}; // tokens the plain down kernel may carry in one launch on this card 1416 static int chunk_staged[64] = {}; // the same for staged 1417 static int tile[64] = {}; // the plain down kernel's TILEV on this card ((N / 2) on sm_75, N elsewhere) 1418 int dev = 0; 1419 cudaGetDevice(&dev); 1420 if (dev < 0 || dev >= 64) { 1421 *tile_out = N; 1422 return kFusedGrMaxT; 1423 } 1424 if (!attr[dev]) { 1425 int optin = 0; 1426 cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev); 1427 optin = strata::smem_optin_of(optin); // STRATA_EMULATE_CC (tests only) 1428 // the down kernel stages n_tok*TILEV floats of dynamic shared memory - 80 KB at the full 8 tokens of the 1429 // CUDA tile. sm_75 gets the smaller tile: all eight tokens fit one 40 KiB launch there (no more slicing), 1430 // the TQ-5 prefetch holds half the registers, and the smaller blocks raise how many of the 41-block grid 1431 // share an SM. Cards whose opt-in is still below that (or that report no opt-in at all) slice the tokens; 1432 // the down kernel's outputs (lo, inject_out) are strictly per-token, so the chunk boundaries are safe, and 1433 // the up kernel below still sees every token of the batch in one launch. 1434#if defined(__HIPCC__) 1435#if defined(STRATA_HIP_GFX906) 1436 const bool small_tile = false; // gfx906: 64 KiB LDS, the N tile as before (8 tokens slice into launches) 1437#else 1438 const bool small_tile = true; // all eight tokens fit gfx1100's 64 KiB LDS at this tile 1439#endif 1440#else 1441 int cc_maj = 0, cc_min = 0; 1442 cudaDeviceGetAttribute(&cc_maj, cudaDevAttrComputeCapabilityMajor, dev); 1443 cudaDeviceGetAttribute(&cc_min, cudaDevAttrComputeCapabilityMinor, dev); 1444 const bool small_tile = strata::cc_major_of(cc_maj) * 10 + strata::cc_minor_of(cc_min) == 75; 1445#endif 1446 const int tv = small_tile ? (N / 2) : N; 1447 tile[dev] = tv; 1448 int want = (int) (kFusedGrMaxT * tv * sizeof(float)); 1449 if (optin > 0 && want > optin) want = optin; 1450 if (small_tile) { 1451 cudaFuncSetAttribute(gr_down_multi_kernel<(N / 2)>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); 1452 cudaFuncSetAttribute(gr_down_multi_kernel<(N / 2), kFusedGrMaxT, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); 1453 cudaFuncSetAttribute(gr_down_multi_kernel<(N / 2), 4, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); 1454 } else { 1455 cudaFuncSetAttribute(gr_down_multi_kernel<N>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); 1456 cudaFuncSetAttribute(gr_down_multi_kernel<N, kFusedGrMaxT, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); 1457 cudaFuncSetAttribute(gr_down_multi_kernel<N, 4, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); 1458 } 1459 auto set_staged_attr = [&](auto kernel, int max_t) { 1460 int ws = (int) (2 * max_t * H_TILE * sizeof(float)); 1461 if (optin > 0 && ws > optin) ws = optin; 1462 if (ws > 48 * 1024) 1463 cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, ws); 1464 cudaFuncSetAttribute(kernel, cudaFuncAttributePreferredSharedMemoryCarveout, 100); 1465 }; 1466 set_staged_attr(gr_down_staged_kernel<1, true>, 1); 1467 set_staged_attr(gr_down_staged_kernel<2, true>, 2); 1468 set_staged_attr(gr_down_staged_kernel<3, true>, 3); 1469 set_staged_attr(gr_down_staged_kernel<4, true>, 4); 1470 set_staged_attr(gr_down_staged_kernel<5, true>, 5); 1471 set_staged_attr(gr_down_staged_kernel<6, true>, 6); 1472 set_staged_attr(gr_down_staged_kernel<4, false>, 4); 1473 set_staged_attr(gr_down_staged_kernel<kFusedGrMaxT, false>, kFusedGrMaxT); 1474 cudaGetLastError(); // drop any error the attempt left behind 1475 // The opt-in is a promise a pre-Volta card does not keep: an sm_60 answers 65536 and accepts the 1476 // cudaFuncSetAttribute for 61440 B, then fails the LAUNCH with "invalid argument". What such a card 1477 // will launch is its per-block limit, so the capacity comes from that below sm_70 - the same tokens 1478 // the "no opt-in" branch assumes, but taken from the attribute that is actually enforced. 1479#if defined(__HIPCC__) 1480 const int usable = optin > 0 ? optin : 48 * 1024; 1481#else 1482 int cc = 0, per_block = 0; 1483 cudaDeviceGetAttribute(&cc, cudaDevAttrComputeCapabilityMajor, dev); 1484 cudaDeviceGetAttribute(&per_block, cudaDevAttrMaxSharedMemoryPerBlock, dev); 1485 cc = strata::cc_major_of(cc); 1486 const int usable = (cc >= 7 && optin > 0) ? optin : per_block; 1487#endif 1488 const int capacity = usable / (int) (tv * sizeof(float)); 1489 chunk[dev] = capacity < 1 ? 1 : (capacity > kFusedGrMaxT ? kFusedGrMaxT : capacity); 1490 const int capacity_staged = usable / (int) (2 * H_TILE * sizeof(float)); 1491 chunk_staged[dev] = capacity_staged < 1 ? 1 : (capacity_staged > kFusedGrMaxT ? kFusedGrMaxT : capacity_staged); 1492 attr[dev] = true; 1493 } 1494 *tile_out = tile[dev] ? tile[dev] : N; 1495 return staged ? chunk_staged[dev] : chunk[dev]; 1496} 1497 1498// The multi read as `variant` (kHcPlain, kHcSplit or kHcStaged): the norm, the down projection in launches of as 1499// many tokens as fit the card, the up projection; the profile's stamps after the norm and after the down projection. 1500// kHcPlain is the default read exactly as before (never main's opt-in STRATA_GR_V3 path, which fused_gr_read_multi 1501// takes first). 1502#if STRATA_GR_FAST_BUILD 1503__global__ void __launch_bounds__(THREADS) gr_norm_fast_kernel(GrMulti m); // below, with the AMD fast path 1504__global__ void __launch_bounds__(THREADS) gr_up_fast_kernel(GrMulti m); 1505} // namespace 1506static bool gr_fast(); 1507namespace { 1508#endif 1509// STRATA_GR_DOWN_MAX4=1 (opt-in): launches of up to 4 tokens hold 4 tokens' sums per thread instead of kFusedGrMaxT (the 1510// same bits; checked bitwise on the 5070 for 0.1.40). Default off: a 10-pair interleaved decode A/B on the RTX 5070 (Q2_0, 1511// default config) did not show the +2.8-3.5% of bench #832 (medians 0.97-0.99 of the off arm). 1512bool gr_down_max4() { 1513 static const bool on = [] { 1514 const char* v = std::getenv("STRATA_GR_DOWN_MAX4"); 1515 return v != nullptr && std::atoi(v) != 0; 1516 }(); 1517 return on; 1518} 1519 1520// the split norm with registers (gr_norm_split_fast_kernel): on by default on gfx12; CUDA opt-in (measured on sm_70 only); 1521// STRATA_GR_NORM_FAST=0 / 1 forces it off / on 1522bool norm_fast_on() { 1523#if defined(__HIPCC__) 1524 static const int env = [] { const char* e = std::getenv("STRATA_GR_NORM_FAST"); return e != nullptr ? (std::atoi(e) != 0 ? 1 : 0) : -1; }(); 1525 if (env >= 0) return env != 0; 1526 static int per_dev[64]; // 0 unknown, 1 no, 2 yes 1527 int dev = 0; 1528 if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false; 1529 if (!per_dev[dev]) { 1530 cudaDeviceProp p; 1531 per_dev[dev] = cudaGetDeviceProperties(&p, dev) == cudaSuccess && strata::kernels::gfx_arch_is_gfx12(p.gcnArchName) ? 2 : 1; 1532 } 1533 return per_dev[dev] == 2; 1534#else 1535 // CUDA: opt-in with STRATA_GR_NORM_FAST=1 (measured on sm_70 only) 1536 static const bool on = [] { const char* e = std::getenv("STRATA_GR_NORM_FAST"); return e != nullptr && std::atoi(e) != 0; }(); 1537 return on; 1538#endif 1539} 1540 1541// STRATA_QFUSE_HC_LOCAL=0 puts the atomic-tail up kernel back under STRATA_QFUSE_HC (default: the 32-column kernel) 1542bool qfuse_hc_local() { 1543 const char* e = std::getenv("STRATA_QFUSE_HC_LOCAL"); 1544 return e == nullptr || std::atoi(e) != 0; 1545} 1546// Turing: gr_up75_kernel for 3+ tokens (bitwise gr_up_multi_kernel; fused_gr_bench cold on an RTX 2080 Ti, up incl. a 1547// stamp: T 3 27.3 -> 24.6 us, T 4 33.2 -> 28.7, T 6 46.6 -> 36.6); STRATA_GR_UP75=0 / 1 forces it off / on 1548bool up75_on() { 1549 if (LR != 320) return false; // the kernel holds the row's last 8 chunks 4 rows to a uint4: a tail of exactly 8 chunks 1550#if defined(__HIPCC__) 1551 return false; 1552#else 1553 static const int env = [] { const char* v = std::getenv("STRATA_GR_UP75"); return v ? (std::atoi(v) != 0 ? 1 : 0) : -1; }(); 1554 if (env >= 0) return env != 0; 1555 static int per_dev[64]; // 0 unknown, 1 no, 2 yes 1556 int dev = 0; 1557 if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false; 1558 if (!per_dev[dev]) { 1559 int major = 0, minor = 0; 1560 cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); 1561 cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev); 1562 // Turing (STRATA_SM75_PERF=1), and a 12.0 card (sm120_series.hpp: RTX PRO 5000, a 4-token verify round -1.7%) 1563 per_dev[dev] = strata::sm75_default(major, minor) || strata::sm120_default(major, minor) ? 2 : 1; 1564 } 1565 return per_dev[dev] == 2; 1566#endif 1567} 1568// sm_75 / a 12.0 card: the staged down kernel's tokens per block (gridDim.y = ct / tg), 0 = one block row for all of them. 1569// STRATA_GR_DOWN_TG=n forces n where it divides the launch (0 = off). 1570int down_tg(int ct) { 1571#if defined(__HIPCC__) 1572 (void) ct; 1573 return 0; 1574#else 1575 static const int env = [] { const char* v = std::getenv("STRATA_GR_DOWN_TG"); return v ? std::atoi(v) : -1; }(); 1576 if (ct < 2) return 0; 1577 if (env >= 0) return env > 0 && env <= 3 && ct % env == 0 ? env : 0; 1578 // fused_gr_bench cold on an RTX 2080 Ti (down incl. a stamp): T 4 29.1 -> 27.3 us, T 6 38.5 -> 32.2 with pairs; 1579 // one token per block is slower at every T (the weights are read from L2 once per group) 1580 static int per_dev[64]; // 0 unknown, 1 no, 2 sm_75, 3 a 12.0 card with 80+ SMs, 4 a smaller 12.0 card 1581 int dev = 0; 1582 if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return 0; 1583 if (!per_dev[dev]) { 1584 int major = 0, minor = 0, sms = 0; 1585 cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); 1586 cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev); 1587 cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev); 1588 per_dev[dev] = strata::sm75_default(major, minor) ? 2 : strata::sm120_default(major, minor) ? (sms >= 80 ? 3 : 4) : 1; // Turing, STRATA_SM75_PERF=1 1589 } 1590 // a 12.0 card (sm120_series.hpp) with 80+ SMs: one token a block row for every launch of 2+ tokens (RTX PRO 5000, fixed 1591 // rounds against token pairs: 2 tokens -2.1%, 3 -2.3%, 4 -0.2%, 5 -2.5%; pairs against no split at 4 tokens -2.4%); a 1592 // smaller one (RTX 5070, 48 SMs: 1 and 2 could not be told apart, an earlier run leaned to 2) token pairs at every even launch 1593 if (per_dev[dev] == 3) return ct >= 2 ? 1 : 0; 1594 if (per_dev[dev] == 4) return ct % 2 == 0 ? 2 : 0; 1595 return per_dev[dev] == 2 && (ct == 4 || ct == 6) ? 2 : 0; 1596#endif 1597} 1598// STRATA_GR_R2 (v3 read, 5..8-token launches; default 2): 0 = the generic kernels as before, 1 / 2 / 4 = the exact-T kernels with that many down 1599// rows per warp (the same dots in the same order, so the same bits; fewer blocks stage the same activations less often) 1600static int gr_r2() { 1601 static const int v = [] { const char* e = std::getenv("STRATA_GR_R2"); return e != nullptr ? std::atoi(e) : 2; }(); 1602 return v == 1 || v == 2 || v == 4 ? v : 0; 1603} 1604void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long long* stamp_buf, int stamp_i0) { 1605 const int n_tok = m.T; 1606 const bool q8w = m.a[0].s_down != nullptr; // STRATA_HC_REQ8: w_down / w_up hold int8 codes 1607#if STRATA_GR_FAST_BUILD 1608 // gfx906: the latency-hidden norm/up (STRATA_GR_FAST=0: off) - the same sums in the same order as the kernels 1609 // they replace (gr_parity checks the multi-token read against single-token calls bitwise) 1610 const bool fast = gr_fast(); 1611 if (variant >= kHcSplit) { 1612 if (norm_fast_on()) gr_norm_split_fast_kernel<<<dim3((unsigned) n_tok, HC), THREADS, 0, st>>>(m); 1613 else gr_norm_split_kernel<<<dim3((unsigned) n_tok, HC), THREADS, 0, st>>>(m); 1614 } else if (fast) gr_norm_fast_kernel<<<n_tok, THREADS, 0, st>>>(m); 1615 else gr_norm_multi_kernel<<<n_tok, THREADS, 0, st>>>(m); 1616#else 1617 if (variant >= kHcSplit) { 1618 if (norm_fast_on()) gr_norm_split_fast_kernel<<<dim3((unsigned) n_tok, HC), THREADS, 0, st>>>(m); 1619 else gr_norm_split_kernel<<<dim3((unsigned) n_tok, HC), THREADS, 0, st>>>(m); 1620 } else gr_norm_multi_kernel<<<n_tok, THREADS, 0, st>>>(m); 1621#endif 1622 if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, (void*) st); 1623 // STRATA_HC_Q8: the staged down kernel reads bf16 only, so Q8 weights take split's down kernel (the plain one) 1624 const bool staged = variant >= kHcStaged && m.a[0].s_down == nullptr; 1625 int tv = N; 1626 const int chunk_tok = down_chunk(staged, &tv); 1627 // BW-MEASURE: the hyper-connection read's form: var = layout variant (0 plain, 1 split, 2 staged), type = 1 for Q8 weights, n_in = down tile, 1628 // n_out = tokens a down launch, ncols = tokens 1629 strata::dispatch::kernel(strata::dispatch::kHc, variant, m.a[0].s_down != nullptr ? 1 : 0, tv, chunk_tok, n_tok); 1630 const size_t per_tok = (staged ? (size_t) 2 * H_TILE : (size_t) tv) * sizeof(float); 1631 static const bool no_multi_gr = [] { 1632 const char* no = std::getenv("STRATA_NO_MULTI_GR"); 1633 return no != nullptr && no[0] != '\0' && no[0] != '0'; 1634 }(); 1635 const bool exact_t = !no_multi_gr; 1636 for (int c0 = 0; c0 < n_tok; c0 += chunk_tok) { 1637 const int ct = n_tok - c0 < chunk_tok ? n_tok - c0 : chunk_tok; 1638 GrMulti c{}; 1639 if (ct == n_tok) { 1640 c = m; 1641 } else { 1642 c.xn = m.xn + (size_t) c0 * D; 1643 c.T = ct; 1644 for (int k = 0; k < ct; ++k) c.a[k] = m.a[c0 + k]; 1645 } 1646 const size_t smem = (size_t) ct * per_tok; 1647 // #443, STRATA_GR_DOWN_MAX4: launches of up to 4 tokens hold 4 tokens' sums per thread instead of 1648 // kFusedGrMaxT - the same tile, block size, accumulation order and plain/split/staged path, so the same bits 1649 // (decided once per device: this runs per layer when decode is not captured) 1650 const bool max4 = ct <= 4 && gr_down_max4(); 1651 if (staged) { 1652 // #783 PR-g (stuchapin909): a launch of exactly ct <= 6 tokens is its own instantiation, the loop bounds 1653 // are compile-time (the same sums in the same order); STRATA_NO_MULTI_GR=1 keeps the generic kernels 1654 const int tg = down_tg(ct); 1655 if (exact_t && tg > 0 && tg < ct) { 1656 const dim3 grid(DOWN_BLOCKS + 1, (unsigned) (ct / tg)); 1657 const size_t sm_g = (size_t) tg * per_tok; 1658 if (tg == 1) gr_down_staged_kernel<1, true><<<grid, THREADS, sm_g, st>>>(c); 1659 else if (tg == 2) gr_down_staged_kernel<2, true><<<grid, THREADS, sm_g, st>>>(c); 1660 else gr_down_staged_kernel<3, true><<<grid, THREADS, sm_g, st>>>(c); 1661 } else 1662 if (exact_t && ct == 1) gr_down_staged_kernel<1, true><<<DOWN_BLOCKS + 1, THREADS, smem, st>>>(c); 1663 else if (exact_t && ct == 2) gr_down_staged_kernel<2, true><<<DOWN_BLOCKS + 1, THREADS, smem, st>>>(c); 1664 else if (exact_t && ct == 3) gr_down_staged_kernel<3, true><<<DOWN_BLOCKS + 1, THREADS, smem, st>>>(c); 1665 else if (exact_t && ct == 4) gr_down_staged_kernel<4, true><<<DOWN_BLOCKS + 1, THREADS, smem, st>>>(c); 1666 else if (exact_t && ct == 5) gr_down_staged_kernel<5, true><<<DOWN_BLOCKS + 1, THREADS, smem, st>>>(c); 1667 else if (exact_t && ct == 6) gr_down_staged_kernel<6, true><<<DOWN_BLOCKS + 1, THREADS, smem, st>>>(c); 1668 else if (max4) gr_down_staged_kernel<4><<<DOWN_BLOCKS + 1, THREADS, smem, st>>>(c); 1669 else gr_down_staged_kernel<><<<DOWN_BLOCKS + 1, THREADS, smem, st>>>(c); 1670 } else if (tv == (N / 2)) { 1671 if (q8w) { // STRATA_HC_REQ8 1672 if (max4) gr_down_multi_kernel<(N / 2), 4, true><<<DOWN_BLOCKS + 1, THREADS, smem, st>>>(c); 1673 else gr_down_multi_kernel<(N / 2), kFusedGrMaxT, true><<<DOWN_BLOCKS + 1, THREADS, smem, st>>>(c); 1674 } else if (max4) gr_down_multi_kernel<(N / 2), 4><<<DOWN_BLOCKS + 1, THREADS, smem, st>>>(c); 1675 else gr_down_multi_kernel<(N / 2)><<<DOWN_BLOCKS + 1, THREADS, smem, st>>>(c); 1676 } else { 1677 if (q8w) { // STRATA_HC_REQ8 1678 if (max4) gr_down_multi_kernel<N, 4, true><<<DOWN_BLOCKS + 1, THREADS, smem, st>>>(c); 1679 else gr_down_multi_kernel<N, kFusedGrMaxT, true><<<DOWN_BLOCKS + 1, THREADS, smem, st>>>(c); 1680 } else if (max4) gr_down_multi_kernel<N, 4><<<DOWN_BLOCKS + 1, THREADS, smem, st>>>(c); 1681 else gr_down_multi_kernel<N><<<DOWN_BLOCKS + 1, THREADS, smem, st>>>(c); 1682 } 1683 } 1684 if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, (void*) st); 1685 // 149-cuda: the wide up read (test arm; STRATA_GR_UP_WIDE=1). The q8_1 tail of S26 needs the 16-column 1686 // blocks, so the wide kernel is only used when no q8_1 image is written. 1687 if (!q8w && m.a[0].q8_mixed == nullptr && gr_up_wide_on()) { 1688 switch (no_multi_gr ? kFusedGrMaxT : n_tok) { 1689 case 1: gr_up_wide_kernel<1, true><<<UPW_BLOCKS, THREADS, 0, st>>>(m); break; 1690 case 2: gr_up_wide_kernel<2, true><<<UPW_BLOCKS, THREADS, 0, st>>>(m); break; 1691 case 3: gr_up_wide_kernel<3, true><<<UPW_BLOCKS, THREADS, 0, st>>>(m); break; 1692 case 4: gr_up_wide_kernel<4, true><<<UPW_BLOCKS, THREADS, 0, st>>>(m); break; 1693 case 5: gr_up_wide_kernel<5, true><<<UPW_BLOCKS, THREADS, 0, st>>>(m); break; 1694 case 6: gr_up_wide_kernel<6, true><<<UPW_BLOCKS, THREADS, 0, st>>>(m); break; 1695 default: gr_up_wide_kernel<kFusedGrMaxT, false><<<UPW_BLOCKS, THREADS, 0, st>>>(m); break; 1696 } 1697 } else 1698#if STRATA_GR_FAST_BUILD 1699 if (fast && !q8w) gr_up_fast_kernel<<<UPM_BLOCKS, THREADS, 0, st>>>(m); 1700 else 1701#endif 1702#if !STRATA_GR_FAST_BUILD 1703 if (!q8w && m.a[0].q8_mixed != nullptr && qfuse_hc_local()) { 1704 switch (no_multi_gr ? kFusedGrMaxT : n_tok) { 1705 case 1: gr_up_q32_kernel<1, true><<<Q32_BLOCKS, Q32_THREADS, 0, st>>>(m); break; 1706 case 2: gr_up_q32_kernel<2, true><<<Q32_BLOCKS, Q32_THREADS, 0, st>>>(m); break; 1707 case 3: gr_up_q32_kernel<3, true><<<Q32_BLOCKS, Q32_THREADS, 0, st>>>(m); break; 1708 case 4: gr_up_q32_kernel<4, true><<<Q32_BLOCKS, Q32_THREADS, 0, st>>>(m); break; 1709 case 5: gr_up_q32_kernel<5, true><<<Q32_BLOCKS, Q32_THREADS, 0, st>>>(m); break; 1710 case 6: gr_up_q32_kernel<6, true><<<Q32_BLOCKS, Q32_THREADS, 0, st>>>(m); break; 1711 default: gr_up_q32_kernel<kFusedGrMaxT, false><<<Q32_BLOCKS, Q32_THREADS, 0, st>>>(m); break; 1712 } 1713 return; 1714 } 1715#endif 1716 if (q8w) { // STRATA_HC_REQ8: the up kernel on int8 rows 1717 switch (no_multi_gr ? kFusedGrMaxT : n_tok) { 1718 case 1: gr_up_multi_kernel<1, true, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1719 case 2: gr_up_multi_kernel<2, true, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1720 case 3: gr_up_multi_kernel<3, true, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1721 case 4: gr_up_multi_kernel<4, true, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1722 case 5: gr_up_multi_kernel<5, true, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1723 case 6: gr_up_multi_kernel<6, true, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1724 default: gr_up_multi_kernel<kFusedGrMaxT, false, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1725 } 1726 } else if (n_tok >= 3 && up75_on()) { // T 1-2: gr_up_multi_kernel is as fast or faster (fused_gr_bench, cold) 1727 switch (no_multi_gr ? kFusedGrMaxT : n_tok) { 1728 case 1: gr_up75_kernel<1, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1729 case 2: gr_up75_kernel<2, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1730 case 3: gr_up75_kernel<3, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1731 case 4: gr_up75_kernel<4, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1732 case 5: gr_up75_kernel<5, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1733 case 6: gr_up75_kernel<6, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1734 default: gr_up75_kernel<kFusedGrMaxT, false><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1735 } 1736 } else 1737 switch (no_multi_gr ? kFusedGrMaxT : n_tok) { 1738 case 1: gr_up_multi_kernel<1, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1739 case 2: gr_up_multi_kernel<2, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1740 case 3: gr_up_multi_kernel<3, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1741 case 4: gr_up_multi_kernel<4, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1742 case 5: gr_up_multi_kernel<5, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1743 case 6: gr_up_multi_kernel<6, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1744 default: gr_up_multi_kernel<kFusedGrMaxT, false><<<UPM_BLOCKS, THREADS, 0, st>>>(m); break; 1745 } 1746} 1747 1748/// STRATA_HC_SPLIT: unset or 2 = the newest the check accepts (staged), 1 = at most split, 0 = the plain read 1749int env_variant() { 1750 const char* e = std::getenv("STRATA_HC_SPLIT"); 1751 if (e == nullptr || e[0] == '\0') return kHcStaged; 1752 if (e[0] == '0') return kHcPlain; 1753 if (e[0] == '1') return kHcSplit; 1754 return kHcStaged; 1755} 1756 1757// per device: the variant `fused_gr_check` chose (0 = not checked yet) 1758std::atomic<int> g_variant[64]; 1759 1760 1761#if STRATA_GR_FAST_BUILD 1762// ---- AMD fast path (STRATA_GR_FAST, default 1; 0 = the old kernels): the same arithmetic per value in the same order, latency 1763// hidden. gr_norm: one block per token (as before) but a thread's 10 float4 of R / bo / w_norm are loaded 1764// before any is used, and xn stays in registers until rs is known (was: store, then re-read the 40 KB). 1765// 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 1766// after another). 1767constexpr int NQ = D / (THREADS * 4); // 10 float4 per thread 1768static_assert(D % (THREADS * 4) == 0, "whole float4 per thread"); 1769__global__ void __launch_bounds__(THREADS) gr_norm_fast_kernel(GrMulti m) { 1770 __shared__ float part[WARPS][HC]; 1771 __shared__ float s_rs[HC]; 1772 const FusedGrArgs& a = m.a[blockIdx.x]; 1773 float* xn = m.xn + (size_t) blockIdx.x * D; 1774 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; 1775 float gw[HC]; 1776#pragma unroll 1777 for (int c = 0; c < HC; ++c) gw[c] = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; 1778 float4 r[NQ], g[NQ]; 1779#pragma unroll 1780 for (int k = 0; k < NQ; ++k) { 1781 const int i = t * 4 + k * THREADS * 4; 1782 r[k] = *reinterpret_cast<const float4*>(a.R + i); 1783 g[k] = *reinterpret_cast<const float4*>(a.w_norm + i); 1784 } 1785 if (a.apply) { 1786#pragma unroll 1787 for (int k = 0; k < NQ; ++k) { 1788 const int i = t * 4 + k * THREADS * 4, c = i / N, d = i - c * N; 1789 const float4 b = *reinterpret_cast<const float4*>(a.bo_prev + d); 1790 r[k].x = fmaf(b.x, gw[c], r[k].x); r[k].y = fmaf(b.y, gw[c], r[k].y); 1791 r[k].z = fmaf(b.z, gw[c], r[k].z); r[k].w = fmaf(b.w, gw[c], r[k].w); 1792 } 1793 } 1794 float ss[HC] = {0.0f, 0.0f, 0.0f, 0.0f}; 1795#pragma unroll 1796 for (int k = 0; k < NQ; ++k) { 1797 const int i = t * 4 + k * THREADS * 4, c = i / N; 1798 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; 1799#pragma unroll 1800 for (int cc = 0; cc < HC; ++cc) if (cc == c) ss[cc] += sq; 1801 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); 1802 } 1803#pragma unroll 1804 for (int c = 0; c < HC; ++c) { 1805 const float v = warp_sum(ss[c]); 1806 if (lane == 0) part[warp][c] = v; 1807 } 1808 __syncthreads(); 1809 if (t < HC) { 1810 float s = 0.0f; 1811 for (int w = 0; w < WARPS; ++w) s += part[w][t]; 1812 s_rs[t] = rsqrtf(s / (float) N + a.eps); 1813 a.rs[t] = s_rs[t]; 1814 } 1815 __syncthreads(); 1816#pragma unroll 1817 for (int k = 0; k < NQ; ++k) { 1818 const int i = t * 4 + k * THREADS * 4; 1819 const float sr = s_rs[i / N]; 1820 *reinterpret_cast<float4*>(xn + i) = make_float4(r[k].x * sr, r[k].y * sr, r[k].z * sr, r[k].w * sr); 1821 } 1822} 1823// 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 1824// 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 1825// 4, 2, 1 are shuffles inside the 8 - the same tree, bitwise the same sum, 3 shuffles a token instead of 5 and no 1826// idle lanes on the tail chunks. A block's 64 rows are 2 passes of 32 groups, their weights loaded up front. 1827__device__ __forceinline__ float xor8(float v) { 1828#pragma unroll 1829#if defined(__HIPCC__) 1830 for (int o = 4; o > 0; o >>= 1) v += __shfl_xor(v, o, 64); 1831#else 1832 for (int o = 4; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); 1833#endif 1834 return v; 1835} 1836__global__ void __launch_bounds__(THREADS) gr_up_fast_kernel(GrMulti m) { 1837 __shared__ __align__(16) float lo[kFusedGrMaxT][LR]; 1838 __shared__ float g[kFusedGrMaxT][HC][UPM_COLS]; 1839 const int t = threadIdx.x, j = t & 7, grp = t >> 3; 1840 const int T = m.T; 1841 const int d0 = blockIdx.x * UPM_COLS; 1842 static_assert(LR % 64 == 0 && LR >= 256 && LR <= 512 && HC * UPM_COLS == 64 && THREADS == 256, "geometry"); 1843 constexpr int TM = (LR / 8 - 32) / 8; // 8-chunk tails past the first 32 chunks: 0 (LR 256), 1 (320, Flash-Next), 2 (384), 4 (512) 1844 uint4 w[2][4 + TM + (TM == 0)]; 1845 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}; 1846 const bool apply = j < T && m.a[j < T ? j : 0].apply; 1847#pragma unroll 1848 for (int p = 0; p < 2; ++p) { 1849 const int r = grp + 32 * p, c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; 1850 const uint4* w4 = reinterpret_cast<const uint4*>(m.a[0].w_up + (size_t) i * LR); 1851#pragma unroll 1852 for (int q = 0; q < 4; ++q) w[p][q] = __ldg(w4 + j + 8 * q); 1853#pragma unroll 1854 for (int mm = 0; mm < TM; ++mm) w[p][4 + mm] = __ldg(w4 + 32 + j + 8 * mm); 1855 if (j < T) { 1856 const FusedGrArgs& a = m.a[j]; 1857 rv[p] = a.R[i]; 1858 wn[p] = a.w_norm[i]; 1859 rsc[p] = a.rs[c]; 1860 if (apply) { bo[p] = a.bo_prev[d0 + dd]; ip[p] = a.inj_prev[c]; } 1861 } 1862 } 1863 for (int i = t; i < T * LR; i += THREADS) lo[i / LR][i % LR] = m.a[i / LR].lo[i % LR]; 1864 __syncthreads(); 1865#pragma unroll 1866 for (int p = 0; p < 2; ++p) { 1867 const int r = grp + 32 * p, c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; 1868 float mine = 0.0f; 1869#pragma unroll 1870 for (int k = 0; k < kFusedGrMaxT; ++k) { 1871 if (k >= T) break; 1872 const float* l = lo[k]; 1873 // old lane j + 8 m: its chunk, then (when the row has a tail chunk 32 + j + 8 m) the tail's dot added to it 1874 float p0, p1, p2, p3; 1875 if constexpr (TM == 1) { // Flash-Next: the expressions this replaced (device code unchanged) 1876 p0 = dot8(w[p][0], l + j * 8) + dot8(w[p][4], l + (32 + j) * 8); // old lane j 1877 p1 = dot8(w[p][1], l + (j + 8) * 8); // old lane j + 8 1878 p2 = dot8(w[p][2], l + (j + 16) * 8); // old lane j + 16 1879 p3 = dot8(w[p][3], l + (j + 24) * 8); // old lane j + 24 1880 } else { 1881 float pq[4]; 1882#pragma unroll 1883 for (int mm = 0; mm < 4; ++mm) { 1884 pq[mm] = dot8(w[p][mm], l + (j + 8 * mm) * 8); 1885 if (mm < TM) pq[mm] += dot8(w[p][4 + mm], l + (32 + j + 8 * mm) * 8); 1886 } 1887 p0 = pq[0]; p1 = pq[1]; p2 = pq[2]; p3 = pq[3]; 1888 } 1889 const float s = xor8((p0 + p2) + (p1 + p3)); // stage 16: (j, j+16), (j+8, j+24); stage 8; then 4, 2, 1 1890 if (j == k) mine = s; 1891 } 1892 if (j < T) { 1893 float x0 = rv[p]; 1894 if (apply) { 1895 x0 = fmaf(bo[p], 2.0f * sigmoidf_(ip[p] / (float) HC), x0); 1896 m.a[j].R_out[i] = x0; 1897 } 1898 const float x = x0 * wn[p] * rsc[p]; 1899 g[j][c][dd] = x * sigmoidf_(mine); 1900 } 1901 } 1902 __syncthreads(); 1903 for (int i = t; i < T * UPM_COLS; i += THREADS) { 1904 const int k = i / UPM_COLS, col = i - k * UPM_COLS; 1905 float s = 0.0f; 1906#pragma unroll 1907 for (int c = 0; c < HC; ++c) s += g[k][c][col]; 1908 m.a[k].mixed[d0 + col] = s / (float) HC; 1909 } 1910 if (m.a[0].q8_mixed != nullptr) gr_q8_tail(m, d0); // S26 STRATA_QFUSE, as gr_up_multi_kernel 1911} 1912#endif 1913 1914#if defined(STRATA_HIP_GFX906) 1915// ---- AMD: `gr_down_multi` split along K. The CUDA kernel is one warp per row of w_down (320 + 4 rows), 41 1916// 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 1917// 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 1918// blocks, and a second kernel adds the 5 slice sums in a fixed order and runs the epilogue. A token's result does 1919// not depend on how many tokens share the window (each column is reduced on its own). 1920constexpr int GS_SL = 2048; // K per slice 1921constexpr int GS_S = D / GS_SL; // 5 slices 1922constexpr int GS_ROWS = LR + HC; // 324: the down rows, then the inject rows 1923constexpr int GS_WAVES = 8; 1924static_assert(D % GS_SL == 0 && GS_SL == 64 * 8 * 4, "a lane takes 4 chunks of 8 per slice"); 1925// the slice sums: a module-scope device array is per device by construction, and needs no allocation during a 1926// graph capture 1927__device__ float g_gr_part[GS_S * kFusedGrMaxT * GS_ROWS]; 1928__global__ void __launch_bounds__(GS_WAVES * 64) gr_down_split_kernel(GrMulti m) { 1929 float* part = g_gr_part; 1930 extern __shared__ __align__(16) float tile[]; // [T][GS_SL] 1931 const int t = threadIdx.x, lane = t & 63, wave = t >> 6; 1932 const int T = m.T, sl = blockIdx.y; 1933 const bool inject_block = blockIdx.x == DOWN_BLOCKS; 1934 const int row = inject_block ? wave : blockIdx.x * GS_WAVES + wave; 1935 const bool active = !(inject_block && (m.a[0].w_inject == nullptr || wave >= HC)); 1936 const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D; 1937 const uint4* w4 = reinterpret_cast<const uint4*>(wrow) + sl * (GS_SL / 8); 1938 uint4 wv[4]; 1939 if (active) { 1940#pragma unroll 1941 for (int q = 0; q < 4; ++q) wv[q] = __ldg(w4 + lane + 64 * q); 1942 } 1943 const float4* src4 = reinterpret_cast<const float4*>(m.xn); 1944 float4* tile4 = reinterpret_cast<float4*>(tile); 1945 for (int i = t; i < T * (GS_SL / 4); i += GS_WAVES * 64) { 1946 const int k = i / (GS_SL / 4), off = i - k * (GS_SL / 4); 1947 tile4[i] = src4[((size_t) k * D + (size_t) sl * GS_SL) / 4 + off]; 1948 } 1949 __syncthreads(); 1950 if (!active) return; 1951 float acc[kFusedGrMaxT]; 1952#pragma unroll 1953 for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f; 1954#pragma unroll 1955 for (int q = 0; q < 4; ++q) { 1956 const int j = lane + 64 * q; 1957#pragma unroll 1958 for (int k = 0; k < kFusedGrMaxT; ++k) 1959 if (k < T) acc[k] += dot8(wv[q], tile + k * GS_SL + j * 8); 1960 } 1961#pragma unroll 1962 for (int k = 0; k < kFusedGrMaxT; ++k) { 1963 if (k >= T) break; 1964 float v = acc[k]; 1965#pragma unroll 1966 for (int off = 32; off > 0; off >>= 1) v += __shfl_xor(v, off, 64); 1967 if (lane == 0) part[((size_t) sl * kFusedGrMaxT + k) * GS_ROWS + (inject_block ? LR + row : row)] = v; 1968 } 1969} 1970__global__ void gr_down_finish_kernel(GrMulti m) { 1971 const float* part = g_gr_part; 1972 const int i = blockIdx.x * blockDim.x + threadIdx.x; 1973 const int k = i / GS_ROWS, r = i - k * GS_ROWS; 1974 if (k >= m.T) return; 1975 const bool inject = r >= LR; 1976 if (inject && m.a[0].w_inject == nullptr) return; 1977 float s = 0.0f; 1978#pragma unroll 1979 for (int sl = 0; sl < GS_S; ++sl) s += part[((size_t) sl * kFusedGrMaxT + k) * GS_ROWS + r]; 1980 if (inject) { 1981 m.a[k].inject_out[r - LR] = s; 1982 } else { 1983 const float x = s / (float) HC; 1984 m.a[k].lo[r] = x / (1.0f + __expf(-x)); 1985 } 1986} 1987 1988#endif 1989 1990// ================================ S23 experiment (STRATA_HC_Q8=1): the read with the GGUF's Q8_0 projections ====== 1991// The pack holds the hyper-connection projections as BF16 (iq_pack.py --compat-bf16 rounds the GGUF's Q8_0 values to 1992// 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, 1993// not a rounding of them). The layout is the stream split of the v3 read above, at 4 chunks per stream: `down` runs 1994// on (10 groups of 32 rows + the inject rows) x 16 chunks of 640 columns = 176 blocks, each staging its chunk of 1995// R' * w_norm (unscaled) for the T tokens and writing the chunk's partial dots and sums of squares; `up` sums them 1996// per stream in a fixed order, applies rs, SwiGLU-free silu, and runs the default epilogue. Another summation order 1997// and other weights than the default read: an output-changing step (measured, quality-checked). 1998constexpr int Q8B = 34; // Q8_0 block: fp16 d + 32 int8 1999constexpr int Q8_RPW = 4; // down rows per warp 2000constexpr int Q8_RG = LR / (WARPS * Q8_RPW); // 10 row groups (+1: the inject rows) 2001// the chunk width: the largest multiple of 128 up to 1024 that divides n_embd (Flash-Next's 2560: 640, as before; q4_lite's 2048: 1024; 3072: 1024; 2002// 4096: 1024: at most 16 chunks of the scratch's room), so a stream is a whole number of chunks and no column of D is left out (a fixed 640 left D % 640 columns unread at 2048/3072/4096) 2003constexpr int q8_chunk_cols(int n) { int best = 128; for (int k = 128; k <= 1024; k += 128) if (n % k == 0) best = k; return best; } 2004constexpr int Q8_KC = q8_chunk_cols(N), Q8_NKC = D / Q8_KC; // 16 chunks, 4 per stream in Flash-Next 2005static_assert(N % Q8_KC == 0 && D % Q8_KC == 0, "fused_gr Q8_0 read: n_embd must be a multiple of 128 (chunks of the largest such width <= 1024)"); 2006static_assert(LR % (WARPS * 4) == 0, "fused_gr Q8_0 read: hc_lr must be a multiple of 32"); 2007constexpr int Q8_CPS = N / Q8_KC; // chunks per stream 2008constexpr int Q8_UPS = (LR + 127) / 128; // steps of 128 values along an up row: 3 up to hc_lr 384 (Flash-Next 320), 4 for 512 (a fixed 3 dropped columns 384-511) 2009constexpr int Q8_SPB = Q8_KC / 128; // 5 steps of 4 Q8_0 blocks (8 lanes x 4 values each) 2010__device__ __forceinline__ uint32_t q8_ld16(const uint8_t* p) { return *(const uint16_t*) p; } 2011__device__ __forceinline__ float q8_half(uint32_t h) { return __half2float(__ushort_as_half((unsigned short) h)); } 2012__device__ __forceinline__ float4 q8_four(uint32_t q, float d) { 2013 return make_float4(d * (float) (int8_t) (q & 255u), d * (float) (int8_t) ((q >> 8) & 255u), 2014 d * (float) (int8_t) ((q >> 16) & 255u), d * (float) (int8_t) (q >> 24)); 2015} 2016 2017template <int T> 2018__global__ void __launch_bounds__(THREADS) gr_down_q8_kernel(GrMulti m, float* __restrict__ part, float* __restrict__ ssg) { 2019 __shared__ __align__(16) float xs[T][Q8_KC]; 2020 __shared__ float red[WARPS][T]; 2021 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; 2022 const int rg = blockIdx.x, kc = blockIdx.y, c = kc / Q8_CPS; 2023 const bool inj = rg == Q8_RG; 2024 // S25: the inject rows are F32 in the GGUF with BF16-exact values, so by default they are read as the pack's BF16 2025 // (exact); a Q8_0 copy (STRATA_HC_Q8_INJECT=1) is the other option 2026 const bool inj_bf16 = inj && m.a[0].q8_inject == nullptr; 2027 const int nrows = inj ? (((m.a[0].q8_inject != nullptr || m.a[0].w_inject != nullptr) && warp < HC) ? 1 : 0) : Q8_RPW; 2028 const int row0 = inj ? warp : (rg * WARPS + warp) * Q8_RPW; 2029 const uint8_t* wb = inj ? m.a[0].q8_inject : m.a[0].q8_down; 2030 const int sub = lane & 7, bl = lane >> 3; // lanes 8b..8b+7: one Q8_0 block, 4 values each 2031 uint32_t q[Q8_RPW][Q8_SPB]; 2032 float dq[Q8_RPW][Q8_SPB]; 2033#pragma unroll 2034 for (int r = 0; r < Q8_RPW; ++r) { 2035 if (r >= nrows || inj_bf16) break; 2036 const uint8_t* row = wb + (size_t) (row0 + r) * (D / 32) * Q8B + (size_t) kc * (Q8_KC / 32) * Q8B; 2037#pragma unroll 2038 for (int s = 0; s < Q8_SPB; ++s) { 2039 const uint8_t* blk = row + (4 * s + bl) * Q8B; 2040 dq[r][s] = q8_half(q8_ld16(blk)); 2041 q[r][s] = q8_ld16(blk + 2 + 4 * sub) | q8_ld16(blk + 4 + 4 * sub) << 16; 2042 } 2043 } 2044 float ssp[T]; 2045#pragma unroll 2046 for (int k = 0; k < T; ++k) { 2047 ssp[k] = 0.0f; 2048 const FusedGrArgs& a = m.a[k]; 2049 const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; 2050 for (int i = t; i < Q8_KC / 4; i += THREADS) { 2051 const int col = kc * Q8_KC + 4 * i; 2052 float4 r = *reinterpret_cast<const float4*>(a.R + col); 2053 if (a.apply) { 2054 const float4 b = *reinterpret_cast<const float4*>(a.bo_prev + (col - c * N)); 2055 r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y); 2056 r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w); 2057 } 2058 const float4 g = *reinterpret_cast<const float4*>(a.w_norm + col); 2059 ssp[k] += r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; 2060 *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); 2061 } 2062 } 2063#pragma unroll 2064 for (int k = 0; k < T; ++k) { 2065 const float v = warp_sum(ssp[k]); 2066 if (lane == 0) red[warp][k] = v; 2067 } 2068 __syncthreads(); 2069 if (rg == 0 && t < T) { 2070 float s = 0.0f; 2071 for (int w = 0; w < WARPS; ++w) s += red[w][t]; 2072 ssg[t * Q8_NKC + kc] = s; 2073 } 2074 if (nrows == 0) return; 2075#pragma unroll 2076 for (int r = 0; r < Q8_RPW; ++r) { 2077 if (r >= nrows) break; 2078 float acc[T]; 2079#pragma unroll 2080 for (int k = 0; k < T; ++k) acc[k] = 0.0f; 2081#pragma unroll 2082 for (int s = 0; s < Q8_SPB; ++s) { 2083 const int v = 32 * (4 * s + bl) + 4 * sub; 2084 float4 w; 2085 if (inj_bf16) { 2086 const uint2 b = *reinterpret_cast<const uint2*>(m.a[0].w_inject + (size_t) row0 * D + (size_t) kc * Q8_KC + v); 2087 w = make_float4(__uint_as_float(b.x << 16), __uint_as_float(b.x & 0xffff0000u), 2088 __uint_as_float(b.y << 16), __uint_as_float(b.y & 0xffff0000u)); 2089 } else { 2090 w = q8_four(q[r][s], dq[r][s]); 2091 } 2092#pragma unroll 2093 for (int k = 0; k < T; ++k) { 2094 const float4 x = *reinterpret_cast<const float4*>(&xs[k][v]); 2095 acc[k] = fmaf(w.x, x.x, acc[k]); acc[k] = fmaf(w.y, x.y, acc[k]); 2096 acc[k] = fmaf(w.z, x.z, acc[k]); acc[k] = fmaf(w.w, x.w, acc[k]); 2097 } 2098 } 2099 const int prow = inj ? LR + warp : row0 + r; 2100#pragma unroll 2101 for (int k = 0; k < T; ++k) { 2102 const float v = warp_sum(acc[k]); 2103 if (lane == 0) part[((size_t) k * Q8_NKC + kc) * PR + prow] = v; 2104 } 2105 } 2106} 2107 2108template <int T> 2109__global__ void __launch_bounds__(THREADS) gr_up_q8_kernel(GrMulti m, const float* __restrict__ part, 2110 const float* __restrict__ ssg) { 2111 __shared__ __align__(16) float lo[T][LR]; 2112 __shared__ float rsS[T][HC]; 2113 __shared__ float g[T][HC][UPM_COLS]; 2114 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; 2115 const int d0 = blockIdx.x * UPM_COLS; 2116 if (t < T * HC) { 2117 const int k = t / HC, c = t - k * HC; 2118 float ss = 0.0f; 2119#pragma unroll 2120 for (int j = 0; j < Q8_CPS; ++j) ss += ssg[k * Q8_NKC + c * Q8_CPS + j]; 2121 const float r = rsqrtf(ss / (float) N + m.a[k].eps); 2122 rsS[k][c] = r; 2123 if (blockIdx.x == 0) m.a[k].rs[c] = r; 2124 } 2125 __syncthreads(); 2126 for (int i = t; i < T * PR; i += THREADS) { 2127 const int k = i / PR, r = i - k * PR; 2128 if (r >= LR && (blockIdx.x != 0 || m.a[k].w_inject == nullptr)) continue; 2129 float sum = 0.0f; 2130#pragma unroll 2131 for (int c = 0; c < HC; ++c) { 2132 float p = 0.0f; 2133#pragma unroll 2134 for (int j = 0; j < Q8_CPS; ++j) p += part[((size_t) k * Q8_NKC + c * Q8_CPS + j) * PR + r]; 2135 sum = fmaf(rsS[k][c], p, sum); 2136 } 2137 if (r < LR) { 2138 const float x = sum / (float) HC; 2139 lo[k][r] = x / (1.0f + __expf(-x)); 2140 } else { 2141 m.a[k].inject_out[r - LR] = sum; 2142 } 2143 } 2144 __syncthreads(); 2145 constexpr int RPW8 = HC * UPM_COLS / WARPS; // 8 rows per warp 2146#pragma unroll 1 2147 for (int qq = 0; qq < RPW8; ++qq) { 2148 const int r = warp + qq * WARPS; 2149 const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; 2150 const uint8_t* row = m.a[0].q8_up + (size_t) i * (LR / 32) * Q8B; 2151 float4 w[Q8_UPS]; 2152#pragma unroll 2153 for (int s = 0; s < Q8_UPS; ++s) { // lane: values 4 lane + 128 s (the third step: lanes 0-15) 2154 const int v = 4 * lane + 128 * s; 2155 if (v < LR) { 2156 const uint8_t* blk = row + (v >> 5) * Q8B; 2157 w[s] = q8_four(q8_ld16(blk + 2 + (v & 31)) | q8_ld16(blk + 4 + (v & 31)) << 16, q8_half(q8_ld16(blk))); 2158 } else { 2159 w[s] = make_float4(0.0f, 0.0f, 0.0f, 0.0f); 2160 } 2161 } 2162 float rv = 0.0f, wn = 0.0f, bo = 0.0f, ip = 0.0f; 2163 bool apply = false; 2164 if (lane < T) { 2165 const FusedGrArgs& a = m.a[lane]; 2166 rv = a.R[i]; 2167 wn = a.w_norm[i]; 2168 apply = a.apply; 2169 if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; } 2170 } 2171 float mine = 0.0f; 2172#pragma unroll 2173 for (int k = 0; k < T; ++k) { 2174 float acc = 0.0f; 2175#pragma unroll 2176 for (int s = 0; s < Q8_UPS; ++s) { 2177 const int v = 4 * lane + 128 * s; 2178 if (v < LR) { 2179 const float4 x = *reinterpret_cast<const float4*>(&lo[k][v]); 2180 acc = fmaf(w[s].x, x.x, acc); acc = fmaf(w[s].y, x.y, acc); 2181 acc = fmaf(w[s].z, x.z, acc); acc = fmaf(w[s].w, x.w, acc); 2182 } 2183 } 2184 acc = warp_sum(acc); 2185 if (lane == k) mine = acc; 2186 } 2187 if (lane < T) { 2188 if (apply) { 2189 rv = fmaf(bo, 2.0f * sigmoidf_(ip / (float) HC), rv); 2190 m.a[lane].R_out[i] = rv; 2191 } 2192 const float x = rv * wn * rsS[lane][c]; 2193 g[lane][c][dd] = x * sigmoidf_(mine); 2194 } 2195 } 2196 __syncthreads(); 2197 for (int i = t; i < T * UPM_COLS; i += THREADS) { 2198 const int k = i / UPM_COLS, col = i - k * UPM_COLS; 2199 float sum = 0.0f; 2200#pragma unroll 2201 for (int c = 0; c < HC; ++c) sum += g[k][c][col]; 2202 m.a[k].mixed[d0 + col] = sum / (float) HC; 2203 } 2204 if (m.a[0].q8_mixed != nullptr) gr_q8_tail(m, d0); // S26 STRATA_QFUSE 2205} 2206 2207 2208// STRATA_HC_Q8 on HIP gfx12: gr_up_q8_kernel with 32 columns / 512 threads a block, so a block owns a whole q8_1 group 2209// (STRATA_QFUSE_HC: no counter, no fence; the same arithmetic per value as gr_up_q8_kernel) 2210template <int T, int G = 1> 2211__global__ void __launch_bounds__(Q32_THREADS) gr_up_q8_q32_kernel(GrMulti m, const float* __restrict__ part, 2212 const float* __restrict__ ssg) { 2213 __shared__ __align__(16) float lo[T][LR]; 2214 __shared__ float rsS[T][HC]; 2215 __shared__ float g[T][HC][Q32_COLS]; 2216 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; 2217 const int d0 = blockIdx.x * Q32_COLS; 2218 constexpr int RPW8 = HC * Q32_COLS / Q32_WARPS; // 8 rows per warp 2219 constexpr int NG = RPW8 / G; 2220 constexpr int NB = 1; 2221 float4 w[NB][G][Q8_UPS]; 2222 float rvA[NB][G], wnA[NB][G], boA[NB][G], ipA[NB][G]; 2223 bool applyA[NB][G]; 2224 // G rows a warp are loaded together (weights, R, w_norm, bo, inj) before the first of them is computed and stored: the in-place 2225 // R_out store of one row otherwise ends the loads the compiler could issue for the next (G = 1 is the plain one-row loop). (A 2226 // pipelined variant, STRATA_GR_Q32_PL, was removed in 0.2.13: no gain over G = 2.) 2227 // Every row's arithmetic is unchanged, so the outputs are bitwise the same. 2228 auto load_grp = [&](int qq0, int bf) { 2229#pragma unroll 2230 for (int gg = 0; gg < G; ++gg) { 2231 const int r = warp + (qq0 + gg) * Q32_WARPS; 2232 const int c = r / Q32_COLS, dd = r - c * Q32_COLS, i = c * N + d0 + dd; 2233 const uint8_t* row = m.a[0].q8_up + (size_t) i * (LR / 32) * Q8B; 2234#pragma unroll 2235 for (int s = 0; s < Q8_UPS; ++s) { // lane: values 4 lane + 128 s (the third step: lanes 0-15) 2236 const int v = 4 * lane + 128 * s; 2237 if (v < LR) { 2238 const uint8_t* blk = row + (v >> 5) * Q8B; 2239 w[bf][gg][s] = q8_four(q8_ld16(blk + 2 + (v & 31)) | q8_ld16(blk + 4 + (v & 31)) << 16, q8_half(q8_ld16(blk))); 2240 } else { 2241 w[bf][gg][s] = make_float4(0.0f, 0.0f, 0.0f, 0.0f); 2242 } 2243 } 2244 rvA[bf][gg] = 0.0f; wnA[bf][gg] = 0.0f; boA[bf][gg] = 0.0f; ipA[bf][gg] = 0.0f; 2245 applyA[bf][gg] = false; 2246 if (lane < T) { 2247 const FusedGrArgs& a = m.a[lane]; 2248 rvA[bf][gg] = a.R[i]; 2249 wnA[bf][gg] = a.w_norm[i]; 2250 applyA[bf][gg] = a.apply; 2251 if (applyA[bf][gg]) { boA[bf][gg] = a.bo_prev[d0 + dd]; ipA[bf][gg] = a.inj_prev[c]; } 2252 } 2253 } 2254 }; 2255 if (t < T * HC) { 2256 const int k = t / HC, c = t - k * HC; 2257 float ss = 0.0f; 2258#pragma unroll 2259 for (int j = 0; j < Q8_CPS; ++j) ss += ssg[k * Q8_NKC + c * Q8_CPS + j]; 2260 const float r = rsqrtf(ss / (float) N + m.a[k].eps); 2261 rsS[k][c] = r; 2262 if (blockIdx.x == 0) m.a[k].rs[c] = r; 2263 } 2264 __syncthreads(); 2265 for (int i = t; i < T * PR; i += Q32_THREADS) { 2266 const int k = i / PR, r = i - k * PR; 2267 if (r >= LR && (blockIdx.x != 0 || m.a[k].w_inject == nullptr)) continue; 2268 float sum = 0.0f; 2269#pragma unroll 2270 for (int c = 0; c < HC; ++c) { 2271 float p = 0.0f; 2272#pragma unroll 2273 for (int j = 0; j < Q8_CPS; ++j) p += part[((size_t) k * Q8_NKC + c * Q8_CPS + j) * PR + r]; 2274 sum = fmaf(rsS[k][c], p, sum); 2275 } 2276 if (r < LR) { 2277 const float x = sum / (float) HC; 2278 lo[k][r] = x / (1.0f + __expf(-x)); 2279 } else { 2280 m.a[k].inject_out[r - LR] = sum; 2281 } 2282 } 2283 __syncthreads(); 2284#pragma unroll 2285 for (int sg = 0; sg < NG; ++sg) { 2286 const int bf = 0; 2287 load_grp(sg * G, 0); 2288#pragma unroll 2289 for (int gg = 0; gg < G; ++gg) { 2290 const int r = warp + (sg * G + gg) * Q32_WARPS; 2291 const int c = r / Q32_COLS, dd = r - c * Q32_COLS, i = c * N + d0 + dd; 2292 float rv = rvA[bf][gg]; 2293 float mine = 0.0f; 2294#pragma unroll 2295 for (int k = 0; k < T; ++k) { 2296 float acc = 0.0f; 2297#pragma unroll 2298 for (int s = 0; s < Q8_UPS; ++s) { 2299 const int v = 4 * lane + 128 * s; 2300 if (v < LR) { 2301 const float4 x = *reinterpret_cast<const float4*>(&lo[k][v]); 2302 acc = fmaf(w[bf][gg][s].x, x.x, acc); acc = fmaf(w[bf][gg][s].y, x.y, acc); 2303 acc = fmaf(w[bf][gg][s].z, x.z, acc); acc = fmaf(w[bf][gg][s].w, x.w, acc); 2304 } 2305 } 2306 acc = warp_sum(acc); 2307 if (lane == k) mine = acc; 2308 } 2309 if (lane < T) { 2310 if (applyA[bf][gg]) { 2311 rv = fmaf(boA[bf][gg], 2.0f * sigmoidf_(ipA[bf][gg] / (float) HC), rv); 2312 m.a[lane].R_out[i] = rv; 2313 } 2314 const float x = rv * wnA[bf][gg] * rsS[lane][c]; 2315 g[lane][c][dd] = x * sigmoidf_(mine); 2316 } 2317 } 2318 } 2319 __syncthreads(); 2320 for (int i = t; i < T * Q32_COLS; i += Q32_THREADS) { 2321 const int k = i / Q32_COLS, col = i - k * Q32_COLS; 2322 float sum = 0.0f; 2323#pragma unroll 2324 for (int c = 0; c < HC; ++c) sum += g[k][c][col]; 2325 m.a[k].mixed[d0 + col] = sum / (float) HC; 2326 } 2327 __syncthreads(); 2328 // the block owns the whole q8_1 group (32 columns): quantize it here (gr_up_q32_kernel's tail), no counter, no fence 2329 if (m.a[0].q8_mixed != nullptr && warp < T) { 2330 const float xi = m.a[warp].mixed[d0 + lane]; 2331 float amax = fabsf(xi), sum = xi; 2332#pragma unroll 2333 for (int o = 16; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); 2334#pragma unroll 2335 for (int o = 16; o > 0; o >>= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); 2336 const float d = q8_1_finite(q81_div(amax, 127.0f)); 2337 const int8_t q = q8_1_quant(xi, d, amax); 2338 GrQ81* y = reinterpret_cast<GrQ81*>(m.a[warp].q8_mixed) + d0 / 32; 2339 y->qs[lane] = q; 2340 if (lane == 0) y->ds = q8_1_ds(d, sum); 2341 } 2342} 2343 2344 2345 2346// 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 2347// squares) as one transposed butterfly (s26_tsum.cuh): bitwise the same values (S26 ws4 harness, every output equal, 2348// 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 2349// slower (0.92-1.03x) and is off. 2350using s26ts::tsum; 2351using s26ts::tsum_token; 2352using s26ts::tsum_lane; 2353using s26ts::pow2_ceil; 2354// gr_down_q8_kernel / gr_up_q8_kernel with every per-token warp sum done as one transposed butterfly per row (tsum) 2355template <int T, int RPW = Q8_RPW, bool PFS = false> 2356__global__ void __launch_bounds__(THREADS) gr_down_q8_fast_kernel(GrMulti m, float* __restrict__ part, float* __restrict__ ssg) { 2357 constexpr int P = pow2_ceil(T); 2358 constexpr int RG_ = LR / (WARPS * RPW); 2359 __shared__ __align__(16) float xs[T][Q8_KC]; 2360 __shared__ float red[WARPS][T]; 2361 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; 2362 const int rg = blockIdx.x, kc = blockIdx.y, c = kc / Q8_CPS; 2363 const bool inj = rg == RG_; 2364 const bool inj_bf16 = inj && m.a[0].q8_inject == nullptr; 2365 const int nrows = inj ? (((m.a[0].q8_inject != nullptr || m.a[0].w_inject != nullptr) && warp < HC) ? 1 : 0) : RPW; 2366 const int row0 = inj ? warp : (rg * WARPS + warp) * RPW; 2367 const uint8_t* wb = inj ? m.a[0].q8_inject : m.a[0].q8_down; 2368 const int sub = lane & 7, bl = lane >> 3; 2369 const int tk = tsum_token<P>(lane); 2370 const bool owner = lane == tsum_lane<P>(tk) && tk < T; 2371 uint32_t q[RPW][Q8_SPB]; 2372 float dq[RPW][Q8_SPB]; 2373#pragma unroll 2374 for (int r = 0; r < RPW; ++r) { 2375 if (r >= nrows || inj_bf16) break; 2376 const uint8_t* row = wb + (size_t) (row0 + r) * (D / 32) * Q8B + (size_t) kc * (Q8_KC / 32) * Q8B; 2377#pragma unroll 2378 for (int s = 0; s < Q8_SPB; ++s) { 2379 const uint8_t* blk = row + (4 * s + bl) * Q8B; 2380 dq[r][s] = q8_half(q8_ld16(blk)); 2381 q[r][s] = q8_ld16(blk + 2 + 4 * sub) | q8_ld16(blk + 4 + 4 * sub) << 16; 2382 } 2383 } 2384 float ssp[P]; 2385#pragma unroll 2386 for (int k = 0; k < P; ++k) ssp[k] = 0.0f; 2387 if constexpr (PFS) { 2388 // the staging loads of all T tokens issued together (Q8_KC / 4 = 160 <= THREADS, so each thread has at most one chunk a token): 2389 // the plain loop below ends every token's loads with a store to shared memory and waits a memory latency a token. The same 2390 // values in the same operation order. 2391 static_assert(Q8_KC / 4 <= THREADS, "one staging chunk a thread"); 2392 if (t < Q8_KC / 4) { 2393 const int col = kc * Q8_KC + 4 * t; 2394 float4 rr[T], bb[T], gn[T]; 2395 float gwk[T]; 2396#pragma unroll 2397 for (int k = 0; k < T; ++k) { 2398 const FusedGrArgs& a = m.a[k]; 2399 rr[k] = *reinterpret_cast<const float4*>(a.R + col); 2400 gn[k] = *reinterpret_cast<const float4*>(a.w_norm + col); 2401 gwk[k] = 0.0f; 2402 if (a.apply) { 2403 bb[k] = *reinterpret_cast<const float4*>(a.bo_prev + (col - c * N)); 2404 gwk[k] = 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC); 2405 } 2406 } 2407#pragma unroll 2408 for (int k = 0; k < T; ++k) { 2409 float4 r = rr[k]; 2410 if (m.a[k].apply) { 2411 const float4 b = bb[k]; 2412 r.x = fmaf(b.x, gwk[k], r.x); r.y = fmaf(b.y, gwk[k], r.y); 2413 r.z = fmaf(b.z, gwk[k], r.z); r.w = fmaf(b.w, gwk[k], r.w); 2414 } 2415 const float4 g = gn[k]; 2416 ssp[k] += r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; 2417 *reinterpret_cast<float4*>(&xs[k][4 * t]) = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w); 2418 } 2419 } 2420 } else { 2421#pragma unroll 2422 for (int k = 0; k < T; ++k) { 2423 const FusedGrArgs& a = m.a[k]; 2424 const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; 2425 for (int i = t; i < Q8_KC / 4; i += THREADS) { 2426 const int col = kc * Q8_KC + 4 * i; 2427 float4 r = *reinterpret_cast<const float4*>(a.R + col); 2428 if (a.apply) { 2429 const float4 b = *reinterpret_cast<const float4*>(a.bo_prev + (col - c * N)); 2430 r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y); 2431 r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w); 2432 } 2433 const float4 g = *reinterpret_cast<const float4*>(a.w_norm + col); 2434 ssp[k] += r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; 2435 *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); 2436 } 2437 } 2438 } 2439 { 2440 const float v = tsum<P>(ssp, lane); 2441 if (owner) red[warp][tk] = v; 2442 } 2443 __syncthreads(); 2444 if (rg == 0 && t < T) { 2445 float s = 0.0f; 2446 for (int w = 0; w < WARPS; ++w) s += red[w][t]; 2447 ssg[t * Q8_NKC + kc] = s; 2448 } 2449 if (nrows == 0) return; 2450#pragma unroll 2451 for (int r = 0; r < RPW; ++r) { 2452 if (r >= nrows) break; 2453 float acc[P]; 2454#pragma unroll 2455 for (int k = 0; k < P; ++k) acc[k] = 0.0f; 2456#pragma unroll 2457 for (int s = 0; s < Q8_SPB; ++s) { 2458 const int v = 32 * (4 * s + bl) + 4 * sub; 2459 float4 w; 2460 if (inj_bf16) { 2461 const uint2 b = *reinterpret_cast<const uint2*>(m.a[0].w_inject + (size_t) row0 * D + (size_t) kc * Q8_KC + v); 2462 w = make_float4(__uint_as_float(b.x << 16), __uint_as_float(b.x & 0xffff0000u), 2463 __uint_as_float(b.y << 16), __uint_as_float(b.y & 0xffff0000u)); 2464 } else { 2465 w = q8_four(q[r][s], dq[r][s]); 2466 } 2467#pragma unroll 2468 for (int k = 0; k < T; ++k) { 2469 const float4 x = *reinterpret_cast<const float4*>(&xs[k][v]); 2470 acc[k] = fmaf(w.x, x.x, acc[k]); acc[k] = fmaf(w.y, x.y, acc[k]); 2471 acc[k] = fmaf(w.z, x.z, acc[k]); acc[k] = fmaf(w.w, x.w, acc[k]); 2472 } 2473 } 2474 const int prow = inj ? LR + warp : row0 + r; 2475 const float v = tsum<P>(acc, lane); 2476 if (owner) part[((size_t) tk * Q8_NKC + kc) * PR + prow] = v; 2477 } 2478} 2479 2480template <int T, bool PF = false> 2481__global__ void __launch_bounds__(THREADS) gr_up_q8_fast_kernel(GrMulti m, const float* __restrict__ part, 2482 const float* __restrict__ ssg) { 2483 constexpr int P = pow2_ceil(T); 2484 constexpr int RPW8 = HC * UPM_COLS / WARPS; 2485 __shared__ __align__(16) float lo[T][LR]; 2486 __shared__ float rsS[T][HC]; 2487 __shared__ float g[T][HC][UPM_COLS]; 2488 const int t = threadIdx.x, lane = t & 31, warp = t >> 5; 2489 const int d0 = blockIdx.x * UPM_COLS; 2490 const int tk = tsum_token<P>(lane); 2491 const bool owner = lane == tsum_lane<P>(tk) && tk < T; 2492 // PF: every row's weights in registers before the part / lo phase (its latency hides the weight read) 2493 uint32_t pq[PF ? RPW8 : 1][Q8_UPS]; 2494 float pd[PF ? RPW8 : 1][Q8_UPS]; 2495 if constexpr (PF) { 2496#pragma unroll 2497 for (int qq = 0; qq < RPW8; ++qq) { 2498 const int r = warp + qq * WARPS; 2499 const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; 2500 const uint8_t* row = m.a[0].q8_up + (size_t) i * (LR / 32) * Q8B; 2501#pragma unroll 2502 for (int s = 0; s < Q8_UPS; ++s) { 2503 const int v = 4 * lane + 128 * s; 2504 if (v < LR) { 2505 const uint8_t* blk = row + (v >> 5) * Q8B; 2506 pq[qq][s] = q8_ld16(blk + 2 + (v & 31)) | q8_ld16(blk + 4 + (v & 31)) << 16; 2507 pd[qq][s] = q8_half(q8_ld16(blk)); 2508 } else { 2509 pq[qq][s] = 0u; pd[qq][s] = 0.0f; 2510 } 2511 } 2512 } 2513 } 2514 if (t < T * HC) { 2515 const int k = t / HC, c = t - k * HC; 2516 float ss = 0.0f; 2517#pragma unroll 2518 for (int j = 0; j < Q8_CPS; ++j) ss += ssg[k * Q8_NKC + c * Q8_CPS + j]; 2519 const float r = rsqrtf(ss / (float) N + m.a[k].eps); 2520 rsS[k][c] = r; 2521 if (blockIdx.x == 0) m.a[k].rs[c] = r; 2522 } 2523 __syncthreads(); 2524 for (int i = t; i < T * PR; i += THREADS) { 2525 const int k = i / PR, r = i - k * PR; 2526 if (r >= LR && (blockIdx.x != 0 || m.a[k].w_inject == nullptr)) continue; 2527 float sum = 0.0f; 2528#pragma unroll 2529 for (int c = 0; c < HC; ++c) { 2530 float p = 0.0f; 2531#pragma unroll 2532 for (int j = 0; j < Q8_CPS; ++j) p += part[((size_t) k * Q8_NKC + c * Q8_CPS + j) * PR + r]; 2533 sum = fmaf(rsS[k][c], p, sum); 2534 } 2535 if (r < LR) { 2536 const float x = sum / (float) HC; 2537 lo[k][r] = x / (1.0f + __expf(-x)); 2538 } else { 2539 m.a[k].inject_out[r - LR] = sum; 2540 } 2541 } 2542 __syncthreads(); 2543#pragma unroll(PF ? RPW8 : 2) 2544 for (int qq = 0; qq < RPW8; ++qq) { 2545 const int r = warp + qq * WARPS; 2546 const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; 2547 const uint8_t* row = m.a[0].q8_up + (size_t) i * (LR / 32) * Q8B; 2548 float4 w[Q8_UPS]; 2549#pragma unroll 2550 for (int s = 0; s < Q8_UPS; ++s) { 2551 const int v = 4 * lane + 128 * s; 2552 if (PF) { 2553 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); 2554 } else if (v < LR) { 2555 const uint8_t* blk = row + (v >> 5) * Q8B; 2556 w[s] = q8_four(q8_ld16(blk + 2 + (v & 31)) | q8_ld16(blk + 4 + (v & 31)) << 16, q8_half(q8_ld16(blk))); 2557 } else { 2558 w[s] = make_float4(0.0f, 0.0f, 0.0f, 0.0f); 2559 } 2560 } 2561 float rv = 0.0f, wn = 0.0f, bo = 0.0f, ip = 0.0f; 2562 bool apply = false; 2563 if (owner) { 2564 const FusedGrArgs& a = m.a[tk]; 2565 rv = a.R[i]; 2566 wn = a.w_norm[i]; 2567 apply = a.apply; 2568 if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; } 2569 } 2570 float acc[P]; 2571#pragma unroll 2572 for (int k = 0; k < P; ++k) acc[k] = 0.0f; 2573#pragma unroll 2574 for (int k = 0; k < T; ++k) { 2575#pragma unroll 2576 for (int s = 0; s < Q8_UPS; ++s) { 2577 const int v = 4 * lane + 128 * s; 2578 if (v < LR) { 2579 const float4 x = *reinterpret_cast<const float4*>(&lo[k][v]); 2580 acc[k] = fmaf(w[s].x, x.x, acc[k]); acc[k] = fmaf(w[s].y, x.y, acc[k]); 2581 acc[k] = fmaf(w[s].z, x.z, acc[k]); acc[k] = fmaf(w[s].w, x.w, acc[k]); 2582 } 2583 } 2584 } 2585 const float mine = tsum<P>(acc, lane); 2586 if (owner) { 2587 if (apply) { 2588 rv = fmaf(bo, 2.0f * sigmoidf_(ip / (float) HC), rv); 2589 m.a[tk].R_out[i] = rv; 2590 } 2591 const float x = rv * wn * rsS[tk][c]; 2592 g[tk][c][dd] = x * sigmoidf_(mine); 2593 } 2594 } 2595 __syncthreads(); 2596 for (int i = t; i < T * UPM_COLS; i += THREADS) { 2597 const int k = i / UPM_COLS, col = i - k * UPM_COLS; 2598 float sum = 0.0f; 2599#pragma unroll 2600 for (int c = 0; c < HC; ++c) sum += g[k][c][col]; 2601 m.a[k].mixed[d0 + col] = sum / (float) HC; 2602 } 2603 if (m.a[0].q8_mixed != nullptr) gr_q8_tail(m, d0); // S26 STRATA_QFUSE 2604} 2605 2606template <int T> void launch_q8_t(const GrMulti& m, float* part, float* ssg, cudaStream_t st, unsigned long long* stamp_buf, 2607 int stamp_i0) { 2608 static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }(); 2609 if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, (void*) st); 2610 static const bool pfs = [] { const char* v = std::getenv("STRATA_GR_Q8_PFS"); return v != nullptr && std::atoi(v) != 0; }(); 2611 if (ts && pfs) gr_down_q8_fast_kernel<T, 4, true><<<dim3(LR / (WARPS * 4) + 1, Q8_NKC), THREADS, 0, st>>>(m, part, ssg); 2612 else if (ts) gr_down_q8_fast_kernel<T, 4><<<dim3(LR / (WARPS * 4) + 1, Q8_NKC), THREADS, 0, st>>>(m, part, ssg); 2613 else gr_down_q8_kernel<T><<<dim3(Q8_RG + 1, Q8_NKC), THREADS, 0, st>>>(m, part, ssg); 2614 if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, (void*) st); 2615#if !STRATA_GR_FAST_BUILD 2616 if (m.a[0].q8_mixed != nullptr && qfuse_hc_local()) { // HIP (not gfx906): the block owns a q8_1 group 2617 static const int upg = [] { const char* v = std::getenv("STRATA_GR_Q32_G"); const int g = v ? std::atoi(v) : 1; return g == 2 || g == 4 || g == 8 ? g : 1; }(); 2618 if (upg == 2) gr_up_q8_q32_kernel<T, 2><<<Q32_BLOCKS, Q32_THREADS, 0, st>>>(m, part, ssg); 2619 else if (upg == 4) gr_up_q8_q32_kernel<T, 4><<<Q32_BLOCKS, Q32_THREADS, 0, st>>>(m, part, ssg); 2620 else if (upg == 8) gr_up_q8_q32_kernel<T, 8><<<Q32_BLOCKS, Q32_THREADS, 0, st>>>(m, part, ssg); 2621 else gr_up_q8_q32_kernel<T, 1><<<Q32_BLOCKS, Q32_THREADS, 0, st>>>(m, part, ssg); 2622 return; 2623 } 2624#endif 2625 if (ts) gr_up_q8_fast_kernel<T, false><<<UPM_BLOCKS, THREADS, 0, st>>>(m, part, ssg); 2626 else gr_up_q8_kernel<T><<<UPM_BLOCKS, THREADS, 0, st>>>(m, part, ssg); 2627} 2628void launch_q8(const GrMulti& m, float* scratch, cudaStream_t st, unsigned long long* stamp_buf, int stamp_i0) { 2629 float* part = scratch; 2630 float* ssg = scratch + (size_t) m.T * Q8_NKC * PR; 2631 switch (m.T) { 2632 case 1: launch_q8_t<1>(m, part, ssg, st, stamp_buf, stamp_i0); break; 2633 case 2: launch_q8_t<2>(m, part, ssg, st, stamp_buf, stamp_i0); break; 2634 case 3: launch_q8_t<3>(m, part, ssg, st, stamp_buf, stamp_i0); break; 2635 case 4: launch_q8_t<4>(m, part, ssg, st, stamp_buf, stamp_i0); break; 2636 case 5: launch_q8_t<5>(m, part, ssg, st, stamp_buf, stamp_i0); break; 2637 case 6: launch_q8_t<6>(m, part, ssg, st, stamp_buf, stamp_i0); break; 2638 case 7: launch_q8_t<7>(m, part, ssg, st, stamp_buf, stamp_i0); break; 2639 default: launch_q8_t<8>(m, part, ssg, st, stamp_buf, stamp_i0); break; 2640 } 2641} 2642 2643} // namespace 2644 2645#if STRATA_GR_FAST_BUILD 2646int g_gr_fast = -1; // fused_gr_set_fast (the bench); -1 = STRATA_GR_FAST, else the card's default 2647static bool gr_fast() { 2648 static const int env = [] { const char* v = std::getenv("STRATA_GR_FAST"); return v ? (std::atoi(v) != 0 ? 1 : 0) : -1; }(); 2649 if (g_gr_fast >= 0) return g_gr_fast != 0; 2650 if (env >= 0) return env != 0; 2651#if defined(__HIPCC__) 2652 return true; 2653#else 2654 { const char* v = std::getenv("STRATA_SM70_TABLE"); return cur_dev_volta() && v != nullptr && std::atoi(v) != 0; } // PR 1401: opt-in // CUDA: on Volta (V100-SXM2: 50.9 -> 46.7 us a read at T 1, bitwise); elsewhere opt-in 2655#endif 2656} 2657#else 2658int g_gr_fast = -1; 2659#endif 2660void fused_gr_set_fast(int on) { g_gr_fast = on; } 2661 2662// STRATA_GR_V3: the stream-split hyper-connection read (gr_down_v3_kernel / gr_up_v3_kernel). Another summation order than the default 2663// read (~1e-7; a greedy tie can flip, so the answers are not byte-identical to 0.2.6's). 0.2.7: ON by default on a compute capability 12.0 2664// card (RTX 50 / RTX PRO Blackwell: sm120_series.hpp, STRATA_SM120_PERF=0 turns the set off) with more than 13 GiB of memory, discrete; 2665// measured on the RTX PRO 5000 72 GB with every expert resident: code decode 245.1 -> 248.1 tok/s (+1.2%, identical tokens), a story prompt 2666// +6.4% (tokens changed, not a claim), held-out document prompt +4.3%, with STRATA_PROMPT_ATTN_IMMA=1 +1.5% decode / +1.6-1.8% prompt together, 2667// 5 pairs. NOT a default elsewhere: it measured -3.0% / -5.9% on 2x RTX A4000 (sm_86) and +1.0% / -3.4% on an RTX 3060 (sm_86), and a 12 GB 2668// sm_120 card (RTX 5070: streams most experts, the read is a small share of its window) is unmeasured. STRATA_GR_V3=0 / 1 forces it off / on 2669// on any card; never in a HIP build (gfx12 reports compute capability 12.0 too). Decided per card, first asked in fused_gr_check (before any 2670// graph capture). 2671static bool gr_v3_default_on(int dev) { 2672#if defined(__HIPCC__) 2673 (void) dev; 2674 return false; 2675#else 2676 static int per_dev[64]; // 0 unknown, 1 no, 2 yes 2677 if (dev < 0 || dev >= 64) return false; 2678 if (!per_dev[dev]) { 2679 cudaDeviceProp p; 2680 const bool ok = cudaGetDeviceProperties(&p, dev) == cudaSuccess; 2681 if (!ok) cudaGetLastError(); 2682 per_dev[dev] = ok && strata::gr_v3_default(false, p.major, p.minor, p.integrated != 0, (double) p.totalGlobalMem, strata::qwen_defaults_026()) ? 2 : 1; 2683 } 2684 return per_dev[dev] == 2; 2685#endif 2686} 2687 2688 2689// BW-DENSE STRATA_GR_V3_PF: the v3 read's load-ordering variants, bitwise the kernels without them (gr_v3_screen: 0 differing, T 1-8). 2690// Bits 0-1 gr_down (1 = the staging's loads of every token in flight together, 2 = weight prefetch), bits 2-3 gr_up (1 = partial sums and 2691// per-row inputs loaded before use, 2 = weight prefetch), bits 4-5 gr_down rows a warp 2 / 4 (T <= 4). Measured on the RTX PRO 5000 (cold 2692// weights, 16 sets, read = down + up): 5 (= down 1, up 1) is 4-8% faster at T 1-8 (T4 26.45 -> 24.90 us); weight prefetch and 2 / 4 rows a 2693// warp are slower (2 = +17% at T4) and stay off. Default: 5 on a compute capability 12.0 card, 0 elsewhere (unmeasured there); 2694// STRATA_GR_V3_PF=0 restores the plain kernels, any value forces that mask. 2695static int v3_pf_mask() { 2696 static const int env = [] { const char* e = std::getenv("STRATA_GR_V3_PF"); return e != nullptr ? std::atoi(e) : -1; }(); 2697 if (env >= 0) return env; 2698#if defined(__HIPCC__) 2699 return 0; 2700#else 2701 static int per_dev[64]; // 0 unknown, else mask + 1 2702 int dev = 0; 2703 if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return 0; } 2704 if (!per_dev[dev]) { 2705 int ma = 0, mi = 0; 2706 const bool ok = cudaDeviceGetAttribute(&ma, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess && 2707 cudaDeviceGetAttribute(&mi, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess; 2708 if (!ok) cudaGetLastError(); 2709 per_dev[dev] = 1 + (ok ? strata::gr_v3_pf_default(ma, mi) : 0); 2710 } 2711 return per_dev[dev] - 1; 2712#endif 2713} 2714static int g_v3_pf_force = -1; // fused_gr_v3_pf (tests, benchmarks): the mask for every read; -1 = STRATA_GR_V3_PF 2715// A kernel's dynamic shared memory opt-in (and its carveout) belongs to the DEVICE it is set on, not to the process: a layer split or a tensor-parallel run launches the 2716// same kernel on several cards, and a process-wide `static const bool once` set it on the first card that got there only. The second card then launched past the 2717// 48 KB default and failed ("invalid argument", reported inside a graph capture as "operation failed due to a previous error during capture", 0 tokens). 2718// `done` is one flag per device; the first launch on each device sets the attributes (under a mutex: two cards' threads may arrive together). 2719template <class F> 2720static void set_attr_once_per_device(bool (&done)[64], F&& set) { 2721 static std::mutex mu; 2722 int dev = 0; 2723 if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { (void) cudaGetLastError(); set(); return; } 2724 std::lock_guard<std::mutex> lk(mu); 2725 if (!done[dev]) { 2726 set(); 2727 done[dev] = true; 2728 } 2729} 2730template <int K, int PF> 2731static void gr_down_pf_launch(const GrMulti& m, float* part, float* ssg, cudaStream_t st) { 2732 constexpr size_t sm = (size_t) K * N * sizeof(float); 2733 static bool done[64] = {}; 2734 set_attr_once_per_device(done, [] { 2735 cudaFuncSetAttribute(gr_down_v3_kernel<1, K, true, 1, PF>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) sm); 2736 cudaFuncSetAttribute(gr_down_v3_kernel<1, K, true, 1, PF>, cudaFuncAttributePreferredSharedMemoryCarveout, 100); 2737 }); 2738 gr_down_v3_kernel<1, K, true, 1, PF><<<dim3(LR / WARPS + 1, HC), THREADS, sm, st>>>(m, part, ssg); 2739} 2740template <int PF> 2741static bool gr_down_pf_dispatch_k(int n_tok, const GrMulti& m, float* part, float* ssg, cudaStream_t st) { 2742 switch (n_tok) { 2743 case 1: gr_down_pf_launch<1, PF>(m, part, ssg, st); return true; 2744 case 2: gr_down_pf_launch<2, PF>(m, part, ssg, st); return true; 2745 case 3: gr_down_pf_launch<3, PF>(m, part, ssg, st); return true; 2746 case 4: gr_down_pf_launch<4, PF>(m, part, ssg, st); return true; 2747 case 5: gr_down_pf_launch<5, PF>(m, part, ssg, st); return true; 2748 case 6: gr_down_pf_launch<6, PF>(m, part, ssg, st); return true; 2749 case 7: if (kFusedGrMaxT >= 7) { gr_down_pf_launch<7, PF>(m, part, ssg, st); return true; } return false; 2750 case 8: if (kFusedGrMaxT >= 8) { gr_down_pf_launch<8, PF>(m, part, ssg, st); return true; } return false; 2751 default: return false; 2752 } 2753} 2754// the exact-T down kernels of 1..4 tokens with R2V rows a warp (2 or 4: half / a quarter of the blocks, each staging the stream's 2755// activations once for R2V times the rows; the same dots) 2756template <int K, int R2V> 2757static void gr_down_r2_launch(const GrMulti& m, float* part, float* ssg, cudaStream_t st) { 2758 constexpr size_t sm = (size_t) K * N * sizeof(float); 2759 gr_down_v3_kernel<1, K, true, R2V><<<dim3(LR / (WARPS * R2V) + 1, HC), THREADS, sm, st>>>(m, part, ssg); 2760} 2761// the same with the register-blocked dot phase (RB, STRATA_GR_V3_PF bit 7): its shared memory opt-in is set on first use 2762template <int K, int R2V> 2763static void gr_down_rb_launch(const GrMulti& m, float* part, float* ssg, cudaStream_t st) { 2764 constexpr size_t sm = (size_t) K * N * sizeof(float); 2765 static bool done[64] = {}; 2766 set_attr_once_per_device(done, [] { 2767 cudaFuncSetAttribute(gr_down_v3_kernel<1, K, true, R2V, 0, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) sm); 2768 cudaFuncSetAttribute(gr_down_v3_kernel<1, K, true, R2V, 0, true>, cudaFuncAttributePreferredSharedMemoryCarveout, 100); 2769 }); 2770 gr_down_v3_kernel<1, K, true, R2V, 0, true><<<dim3(LR / (WARPS * R2V) + 1, HC), THREADS, sm, st>>>(m, part, ssg); 2771} 2772template <int R2V> 2773static bool gr_down_rb_dispatch_k(int n_tok, const GrMulti& m, float* part, float* ssg, cudaStream_t st) { 2774 switch (n_tok) { 2775 case 1: gr_down_rb_launch<1, R2V>(m, part, ssg, st); return true; 2776 case 2: gr_down_rb_launch<2, R2V>(m, part, ssg, st); return true; 2777 case 3: gr_down_rb_launch<3, R2V>(m, part, ssg, st); return true; 2778 case 4: gr_down_rb_launch<4, R2V>(m, part, ssg, st); return true; 2779 case 5: gr_down_rb_launch<5, R2V>(m, part, ssg, st); return true; 2780 case 6: gr_down_rb_launch<6, R2V>(m, part, ssg, st); return true; 2781 case 7: if (kFusedGrMaxT >= 7) { gr_down_rb_launch<7, R2V>(m, part, ssg, st); return true; } return false; 2782 case 8: if (kFusedGrMaxT >= 8) { gr_down_rb_launch<8, R2V>(m, part, ssg, st); return true; } return false; 2783 default: return false; 2784 } 2785} 2786template <int R2V> 2787static bool gr_down_r2_dispatch_k(int n_tok, const GrMulti& m, float* part, float* ssg, cudaStream_t st) { 2788 switch (n_tok) { 2789 case 1: gr_down_r2_launch<1, R2V>(m, part, ssg, st); return true; 2790 case 2: gr_down_r2_launch<2, R2V>(m, part, ssg, st); return true; 2791 case 3: gr_down_r2_launch<3, R2V>(m, part, ssg, st); return true; 2792 case 4: gr_down_r2_launch<4, R2V>(m, part, ssg, st); return true; 2793 default: return false; 2794 } 2795} 2796static bool gr_down_pf_dispatch(int pf, int n_tok, const GrMulti& m, float* part, float* ssg, cudaStream_t st) { 2797 switch (pf & 3) { 2798 case 1: return gr_down_pf_dispatch_k<1>(n_tok, m, part, ssg, st); 2799 case 2: return gr_down_pf_dispatch_k<2>(n_tok, m, part, ssg, st); 2800 case 3: return gr_down_pf_dispatch_k<3>(n_tok, m, part, ssg, st); 2801 default: return false; 2802 } 2803} 2804template <int PF> 2805static bool gr_up_pf_dispatch_k(int n_tok, const GrMulti& m, const float* part, const float* ssg, cudaStream_t st) { 2806#define GR_UP_PF(K) case K: gr_up_v3_kernel<1, K, true, PF><<<UPM_BLOCKS, THREADS, 0, st>>>(m, part, ssg); return true; 2807 switch (n_tok) { 2808 GR_UP_PF(1) GR_UP_PF(2) GR_UP_PF(3) GR_UP_PF(4) GR_UP_PF(5) GR_UP_PF(6) 2809 case 7: if (kFusedGrMaxT >= 7) { gr_up_v3_kernel<1, 7, true, PF><<<UPM_BLOCKS, THREADS, 0, st>>>(m, part, ssg); return true; } return false; 2810 case 8: if (kFusedGrMaxT >= 8) { gr_up_v3_kernel<1, 8, true, PF><<<UPM_BLOCKS, THREADS, 0, st>>>(m, part, ssg); return true; } return false; 2811 default: return false; 2812 } 2813#undef GR_UP_PF 2814} 2815static bool gr_up_pf_dispatch(int pf, int n_tok, const GrMulti& m, const float* part, const float* ssg, cudaStream_t st) { 2816 switch (pf & 3) { 2817 case 1: return gr_up_pf_dispatch_k<1>(n_tok, m, part, ssg, st); 2818 case 2: return gr_up_pf_dispatch_k<2>(n_tok, m, part, ssg, st); 2819 case 3: return gr_up_pf_dispatch_k<3>(n_tok, m, part, ssg, st); 2820 default: return false; 2821 } 2822} 2823 2824// One read of at most kFusedGrMaxT tokens: the kernels below are built for that many (the instantiations, the shared 2825// memory, the by-value launch argument), whatever the window is. 2826static bool fused_gr_read_multi_slice(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, 2827 unsigned long long* stamp_buf, int stamp_i0) { 2828 if (n_tok < 1 || n_tok > kFusedGrMaxT || xn_scratch == nullptr) { 2829 std::fprintf(stderr, "fused_gr_read_multi: invalid arguments\n"); 2830 std::exit(1); 2831 } 2832 GrMulti m; 2833 for (int t = 0; t < n_tok; ++t) { 2834 m.a[t] = a[t]; 2835 const FusedGrArgs& x = a[t]; 2836 if (!x.R || !x.w_norm || !((x.w_down && x.w_up) || (x.q8_down && x.q8_up)) || !x.lo || !x.rs || !x.mixed || (x.w_inject && !x.inject_out) || 2837 (x.apply && (!x.bo_prev || !x.inj_prev || !x.R_out)) || x.w_down != a[0].w_down || x.w_up != a[0].w_up || 2838 x.w_inject != a[0].w_inject || x.w_norm != a[0].w_norm || x.q8_down != a[0].q8_down || 2839 x.q8_up != a[0].q8_up || x.q8_inject != a[0].q8_inject) { 2840 std::fprintf(stderr, "fused_gr_read_multi: invalid arguments for token %d\n", t); 2841 std::exit(1); 2842 } 2843 } 2844 // S26 STRATA_QFUSE: every token needs its q8_1 destination; gr_up_q32_kernel / gr_up_q8_q32_kernel own whole 32-col 2845 // groups and need no atomic counter buffer (q8_cnt is only used when STRATA_QFUSE_HC_LOCAL=0 or STRATA_HC_REQ8) 2846#if !STRATA_GR_FAST_BUILD 2847 const bool q32_no_cnt = qfuse_hc_local() && a[0].s_down == nullptr; 2848#else 2849 const bool q32_no_cnt = false; 2850#endif 2851 bool q8 = a[0].q8_cnt != nullptr || q32_no_cnt; 2852 for (int t = 0; t < n_tok; ++t) q8 = q8 && a[t].q8_mixed != nullptr; 2853 if (!q8) 2854 for (int t = 0; t < n_tok; ++t) m.a[t].q8_mixed = nullptr; 2855 m.xn = xn_scratch; 2856 m.T = n_tok; 2857 cudaStream_t st = (cudaStream_t) stream; 2858 if (a[0].q8_down != nullptr && a[0].q8_up != nullptr) { // inject: Q8_0 copy, or the BF16 rows 2859 launch_q8(m, xn_scratch, st, stamp_buf, stamp_i0); // S23 experiment: STRATA_HC_Q8=1 2860 const cudaError_t eq = cudaGetLastError(); 2861 if (eq != cudaSuccess) { 2862 std::fprintf(stderr, "fused_gr_read_multi q8: %s\n", cudaGetErrorString(eq)); 2863 std::exit(1); 2864 } 2865 return q8; 2866 } 2867 // the two-kernel read above (another summation order): STRATA_GR_V3=0 / 1, unset = gr_v3_default_on (a 12.0 card with > 13 GiB) 2868 static const int v3_env = [] { const char* v = std::getenv("STRATA_GR_V3"); return v != nullptr ? (std::atoi(v) != 0 ? 1 : 0) : -1; }(); 2869 static int split3[64] = {}; // per device: 0 = not decided yet, 1 / 2 = column halves S, -1 = does not fit 2870 int dev3 = 0; 2871 cudaGetDevice(&dev3); 2872 const bool v3 = v3_env >= 0 ? v3_env == 1 : gr_v3_default_on(dev3); 2873 if (v3) { 2874 if (dev3 >= 0 && dev3 < 64 && split3[dev3] == 0) { 2875 int optin = 0; 2876 cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev3); 2877 const int limit = optin > 0 ? optin : 48 * 1024; 2878 const int need1 = (int) (kFusedGrMaxT * N * sizeof(float)), need6 = (int) (6 * N * sizeof(float)), 2879 need5 = (int) (5 * N * sizeof(float)), need2 = need1 / 2; 2880 int split = -1; 2881 if (need1 <= limit && 2882 cudaFuncSetAttribute(gr_down_v3_kernel<1, kFusedGrMaxT, false>, cudaFuncAttributeMaxDynamicSharedMemorySize, need1) == cudaSuccess && 2883 cudaFuncSetAttribute(gr_down_v3_kernel<1, 6, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, need6) == cudaSuccess && 2884 cudaFuncSetAttribute(gr_down_v3_kernel<1, 5, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, need5) == cudaSuccess) { 2885 if (kFusedGrMaxT >= 8) { // the exact 7- and 8-token instantiations (STRATA_GR_R2: rows per warp 1 / 2 / 4) 2886 const int need7 = (int) (7 * N * sizeof(float)), need8 = (int) (8 * N * sizeof(float)); 2887 cudaFuncSetAttribute(gr_down_v3_kernel<1, 5, true, 2>, cudaFuncAttributeMaxDynamicSharedMemorySize, need5); 2888 cudaFuncSetAttribute(gr_down_v3_kernel<1, 6, true, 2>, cudaFuncAttributeMaxDynamicSharedMemorySize, need6); 2889 cudaFuncSetAttribute(gr_down_v3_kernel<1, 7, true, 1>, cudaFuncAttributeMaxDynamicSharedMemorySize, need7); 2890 cudaFuncSetAttribute(gr_down_v3_kernel<1, 7, true, 2>, cudaFuncAttributeMaxDynamicSharedMemorySize, need7); 2891 cudaFuncSetAttribute(gr_down_v3_kernel<1, 7, true, 4>, cudaFuncAttributeMaxDynamicSharedMemorySize, need7); 2892 cudaFuncSetAttribute(gr_down_v3_kernel<1, 8, true, 1>, cudaFuncAttributeMaxDynamicSharedMemorySize, need8); 2893 cudaFuncSetAttribute(gr_down_v3_kernel<1, 8, true, 2>, cudaFuncAttributeMaxDynamicSharedMemorySize, need8); 2894 cudaFuncSetAttribute(gr_down_v3_kernel<1, 8, true, 4>, cudaFuncAttributeMaxDynamicSharedMemorySize, need8); 2895 } 2896 cudaFuncSetAttribute(gr_down_v3_kernel<1, 1, true>, cudaFuncAttributePreferredSharedMemoryCarveout, 100); 2897 cudaFuncSetAttribute(gr_down_v3_kernel<1, 2, true>, cudaFuncAttributePreferredSharedMemoryCarveout, 100); 2898 cudaFuncSetAttribute(gr_down_v3_kernel<1, 3, true>, cudaFuncAttributePreferredSharedMemoryCarveout, 100); 2899 cudaFuncSetAttribute(gr_down_v3_kernel<1, 4, true>, cudaFuncAttributePreferredSharedMemoryCarveout, 100); 2900 cudaFuncSetAttribute(gr_down_v3_kernel<1, 5, true>, cudaFuncAttributePreferredSharedMemoryCarveout, 100); 2901 cudaFuncSetAttribute(gr_down_v3_kernel<1, 6, true>, cudaFuncAttributePreferredSharedMemoryCarveout, 100); 2902 cudaFuncSetAttribute(gr_down_v3_kernel<1, 4, false>, cudaFuncAttributePreferredSharedMemoryCarveout, 100); 2903 cudaFuncSetAttribute(gr_down_v3_kernel<1, kFusedGrMaxT, false>, cudaFuncAttributePreferredSharedMemoryCarveout, 100); 2904 split = 1; 2905 } else if (need2 <= limit) 2906 // #375 (kenh0u): the S = 2 split (a 64 KB opt-in card: Turing) disagrees with itself in gr_parity 2907 // (graph replay vs direct call) - such a card keeps the default read until that split is fixed 2908 std::fprintf(stderr, "strata: STRATA_GR_V3=1 needs the two-half split on this card, which fails its " 2909 "checks (#375): the default read is used\n"); 2910 cudaGetLastError(); // drop any error the attempts left behind 2911 split3[dev3] = split; 2912 } 2913 } 2914 const int split = v3 && dev3 >= 0 && dev3 < 64 && a[0].s_down == nullptr && a[0].s_up == nullptr ? split3[dev3] : -1; 2915 if (split > 0) { // 2 kernels; scratch = partials + sums of squares 2916 float* part = xn_scratch; 2917 float* ssg = xn_scratch + (size_t) n_tok * HC * 2 * PR; // room for S = 2 2918 strata::dispatch::kernel(strata::dispatch::kHc, 20 + split, 0, N, LR, n_tok); // BW-MEASURE: the stream-split (v3) bf16 read; it declines Q8 weights (s_down set) 2919 const size_t sm = (size_t) n_tok * (N / split) * sizeof(float); 2920 if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, stream); 2921 const int pfm = g_v3_pf_force >= 0 ? g_v3_pf_force : v3_pf_mask(); 2922 if (split == 2) gr_down_v3_kernel<2><<<dim3(LR / WARPS + 1, HC * 2), THREADS, sm, st>>>(m, part, ssg); 2923 else if ((pfm & 128) != 0 && n_tok >= 5 && gr_down_rb_dispatch_k<2>(n_tok, m, part, ssg, st)) {} 2924 else if ((pfm & 256) != 0 && gr_down_rb_dispatch_k<4>(n_tok, m, part, ssg, st)) {} 2925 else if (((pfm >> 4) & 3) == 1 && gr_down_r2_dispatch_k<2>(n_tok, m, part, ssg, st)) {} 2926 else if (((pfm >> 4) & 3) == 2 && gr_down_r2_dispatch_k<4>(n_tok, m, part, ssg, st)) {} 2927 else if ((pfm & 3) != 0 && gr_down_pf_dispatch(pfm & 3, n_tok, m, part, ssg, st)) {} 2928 else if (n_tok == 1) gr_down_v3_kernel<1, 1, true><<<dim3(LR / WARPS + 1, HC), THREADS, sm, st>>>(m, part, ssg); 2929 else if (n_tok == 2) gr_down_v3_kernel<1, 2, true><<<dim3(LR / WARPS + 1, HC), THREADS, sm, st>>>(m, part, ssg); 2930 else if (n_tok == 3) gr_down_v3_kernel<1, 3, true><<<dim3(LR / WARPS + 1, HC), THREADS, sm, st>>>(m, part, ssg); 2931 else if (n_tok == 4) gr_down_v3_kernel<1, 4, true><<<dim3(LR / WARPS + 1, HC), THREADS, sm, st>>>(m, part, ssg); 2932 else if (n_tok == 5 && gr_r2() == 2) gr_down_v3_kernel<1, 5, true, 2><<<dim3(LR / (WARPS * 2) + 1, HC), THREADS, sm, st>>>(m, part, ssg); 2933 else if (n_tok == 5) gr_down_v3_kernel<1, 5, true><<<dim3(LR / WARPS + 1, HC), THREADS, sm, st>>>(m, part, ssg); 2934 else if (n_tok == 6 && gr_r2() == 2) gr_down_v3_kernel<1, 6, true, 2><<<dim3(LR / (WARPS * 2) + 1, HC), THREADS, sm, st>>>(m, part, ssg); 2935 else if (n_tok == 6) gr_down_v3_kernel<1, 6, true><<<dim3(LR / WARPS + 1, HC), THREADS, sm, st>>>(m, part, ssg); 2936 else if (n_tok == 7 && kFusedGrMaxT >= 7 && gr_r2() == 2) gr_down_v3_kernel<1, 7, true, 2><<<dim3(LR / (WARPS * 2) + 1, HC), THREADS, sm, st>>>(m, part, ssg); 2937 else if (n_tok == 7 && kFusedGrMaxT >= 7 && gr_r2() == 4) gr_down_v3_kernel<1, 7, true, 4><<<dim3(LR / (WARPS * 4) + 1, HC), THREADS, sm, st>>>(m, part, ssg); 2938 else if (n_tok == 7 && kFusedGrMaxT >= 7 && gr_r2() == 1) gr_down_v3_kernel<1, 7, true, 1><<<dim3(LR / WARPS + 1, HC), THREADS, sm, st>>>(m, part, ssg); 2939 else if (n_tok == 8 && kFusedGrMaxT >= 8 && gr_r2() == 2) gr_down_v3_kernel<1, 8, true, 2><<<dim3(LR / (WARPS * 2) + 1, HC), THREADS, sm, st>>>(m, part, ssg); 2940 else if (n_tok == 8 && kFusedGrMaxT >= 8 && gr_r2() == 4) gr_down_v3_kernel<1, 8, true, 4><<<dim3(LR / (WARPS * 4) + 1, HC), THREADS, sm, st>>>(m, part, ssg); 2941 else if (n_tok == 8 && kFusedGrMaxT >= 8 && gr_r2() == 1) gr_down_v3_kernel<1, 8, true, 1><<<dim3(LR / WARPS + 1, HC), THREADS, sm, st>>>(m, part, ssg); 2942 else gr_down_v3_kernel<1, kFusedGrMaxT, false><<<dim3(LR / WARPS + 1, HC), THREADS, sm, st>>>(m, part, ssg); 2943 if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, stream); 2944 if (split == 2) gr_up_v3_kernel<2><<<UPM_BLOCKS, THREADS, 0, st>>>(m, part, ssg); 2945 else if (((pfm >> 2) & 3) != 0 && gr_up_pf_dispatch((pfm >> 2) & 3, n_tok, m, part, ssg, st)) {} 2946 else if (n_tok == 1) gr_up_v3_kernel<1, 1, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m, part, ssg); 2947 else if (n_tok == 2) gr_up_v3_kernel<1, 2, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m, part, ssg); 2948 else if (n_tok == 3) gr_up_v3_kernel<1, 3, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m, part, ssg); 2949 else if (n_tok == 4) gr_up_v3_kernel<1, 4, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m, part, ssg); 2950 else if (n_tok == 5) gr_up_v3_kernel<1, 5, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m, part, ssg); 2951 else if (n_tok == 6) gr_up_v3_kernel<1, 6, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m, part, ssg); 2952 else if (n_tok == 7 && kFusedGrMaxT >= 7 && gr_r2() > 0) gr_up_v3_kernel<1, 7, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m, part, ssg); 2953 else if (n_tok == 8 && kFusedGrMaxT >= 8 && gr_r2() > 0) gr_up_v3_kernel<1, 8, true><<<UPM_BLOCKS, THREADS, 0, st>>>(m, part, ssg); 2954 else gr_up_v3_kernel<1, kFusedGrMaxT, false><<<UPM_BLOCKS, THREADS, 0, st>>>(m, part, ssg); 2955 const cudaError_t e3 = cudaGetLastError(); 2956 if (e3 != cudaSuccess) { 2957 std::fprintf(stderr, "fused_gr_read_multi v3: %s\n", cudaGetErrorString(e3)); 2958 std::exit(1); 2959 } 2960 return false; // the v3 read: no q8_1 (the caller quantizes) 2961 } 2962#if defined(STRATA_HIP_GFX906) 2963 // gfx906, opt-in STRATA_GR_SPLIT=1: the latency-hidden norm/up (STRATA_GR_FAST) with the K-split down (~3% faster 2964 // per verify window). Its fixed-order finish sums the K slices in another order than the single-token 2965 // fused_gr_read, so the multi-token read is then no longer bitwise equal to T single-token calls (gr_parity's 2966 // contract); off by default for that reason. 2967 static const bool split_on = std::getenv("STRATA_GR_SPLIT") && std::string(std::getenv("STRATA_GR_SPLIT")) == "1"; 2968 if (split_on && a[0].s_down == nullptr) { // its K-split down reads bf16 rows (not STRATA_HC_REQ8) 2969 const bool fast = gr_fast(); 2970 if (fast) gr_norm_fast_kernel<<<n_tok, THREADS, 0, st>>>(m); 2971 else gr_norm_multi_kernel<<<n_tok, THREADS, 0, st>>>(m); 2972 if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, stream); 2973 gr_down_split_kernel<<<dim3(DOWN_BLOCKS + 1, GS_S), GS_WAVES * 64, (size_t) n_tok * GS_SL * sizeof(float), st>>>( 2974 m); 2975 gr_down_finish_kernel<<<(unsigned) ((n_tok * GS_ROWS + 255) / 256), 256, 0, st>>>(m); 2976 if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, stream); 2977 if (fast) gr_up_fast_kernel<<<UPM_BLOCKS, THREADS, 0, st>>>(m); 2978 else gr_up_multi_kernel<<<UPM_BLOCKS, THREADS, 0, st>>>(m); 2979 const cudaError_t e = cudaGetLastError(); 2980 if (e != cudaSuccess) { 2981 std::fprintf(stderr, "fused_gr_read_multi: %s\n", cudaGetErrorString(e)); 2982 std::exit(1); 2983 } 2984 return false; // the gfx906 STRATA_GR_SPLIT read: no q8_1 (the caller quantizes), like the v3 path above 2985 } 2986#endif 2987 // the default read (STRATA_GR_V3 unset): v1, or the bitwise-equal v2 / v3 this card's check accepted 2988 launch_multi(m, fused_gr_variant(), st, stamp_buf, stamp_i0); 2989 const cudaError_t e = cudaGetLastError(); 2990 if (e != cudaSuccess) { 2991 std::fprintf(stderr, "fused_gr_read_multi: %s\n", cudaGetErrorString(e)); 2992 std::exit(1); 2993 } 2994 return q8; 2995} 2996 2997// The multi read for a window of up to kFusedGrWideT tokens. Up to kFusedGrMaxT tokens it is the read above untouched 2998// (the same kernels, the same bits). A wider window (9..16 rows: the batch groups of a four-card split) is read in 2999// slices of at most kFusedGrMaxT tokens, in order on the stream. Every token's outputs are strictly its own (no value 3000// crosses tokens), so the slices are bitwise the one wide read; the cost is the hyper-connection weights read once per 3001// slice. The STRATA_QFUSE counters belong to token 0: each slice's first token carries them (the kernels zero them 3002// again for the next launch); the profile stamps are the first slice's. 3003void fused_gr_v3_pf(int mask) { g_v3_pf_force = mask; } 3004// The bench only: registers, spills, shared memory and resident blocks a multiprocessor of the v3 kernels (T = 4) on the current card, one line each. 3005void fused_gr_v3_print_resources() { 3006#if defined(__HIPCC__) 3007 std::printf("gr_v3 resources: not printed on HIP\n"); 3008 return; 3009#else 3010 auto one = [](const char* name, const void* f, size_t dyn) { 3011 cudaFuncAttributes a; 3012 int blocks = 0; 3013 if (cudaFuncGetAttributes(&a, f) == cudaSuccess && 3014 cudaOccupancyMaxActiveBlocksPerMultiprocessor(&blocks, f, THREADS, dyn) == cudaSuccess) 3015 std::printf("gr_v3 %-22s regs %3d local %4zu B static smem %5zu B dyn smem %6zu B blocks/SM %d\n", name, a.numRegs, a.localSizeBytes, 3016 a.sharedSizeBytes, dyn, blocks); 3017 else { 3018 cudaGetLastError(); 3019 std::printf("gr_v3 %-22s (no attributes)\n", name); 3020 } 3021 }; 3022 const size_t sm4 = (size_t) 4 * N * sizeof(float); 3023 one("down T4 plain", (const void*) gr_down_v3_kernel<1, 4, true, 1, 0>, sm4); 3024 one("down T4 pf1 (batched)", (const void*) gr_down_v3_kernel<1, 4, true, 1, 1>, sm4); 3025 one("down T4 pf2 (weights)", (const void*) gr_down_v3_kernel<1, 4, true, 1, 2>, sm4); 3026 one("down T4 pf3", (const void*) gr_down_v3_kernel<1, 4, true, 1, 3>, sm4); 3027 one("up T4 plain", (const void*) gr_up_v3_kernel<1, 4, true, 0>, 0); 3028 one("up T4 pf1 (batched)", (const void*) gr_up_v3_kernel<1, 4, true, 1>, 0); 3029 one("up T4 pf2 (weights)", (const void*) gr_up_v3_kernel<1, 4, true, 2>, 0); 3030 one("up T4 pf3", (const void*) gr_up_v3_kernel<1, 4, true, 3>, 0); 3031#endif 3032} 3033bool fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf, 3034 int stamp_i0) { 3035 if (n_tok <= kFusedGrMaxT) return fused_gr_read_multi_slice(a, n_tok, xn_scratch, stream, stamp_buf, stamp_i0); 3036 if (n_tok > kFusedGrWideT || a == nullptr || xn_scratch == nullptr) { 3037 std::fprintf(stderr, "fused_gr_read_multi: invalid arguments (%d tokens)\n", n_tok); 3038 std::exit(1); 3039 } 3040 bool q8 = false; 3041 for (int c0 = 0; c0 < n_tok; c0 += kFusedGrMaxT) { 3042 const int ct = n_tok - c0 < kFusedGrMaxT ? n_tok - c0 : kFusedGrMaxT; 3043 FusedGrArgs s[kFusedGrMaxT]; 3044 for (int k = 0; k < ct; ++k) s[k] = a[c0 + k]; 3045 s[0].q8_cnt = a[0].q8_cnt; 3046 q8 = fused_gr_read_multi_slice(s, ct, xn_scratch + (size_t) c0 * D, stream, c0 == 0 ? stamp_buf : nullptr, stamp_i0); 3047 } 3048 return q8; 3049} 3050 3051// STRATA_HC_Q8 on a bf16 pack: one warp a Q8_0 block, ggml's reference rounding (d = amax / 127 as fp16, q = round(x * (1 / d))) 3052__global__ void __launch_bounds__(256) gr_quantize_q8_0_kernel(const uint16_t* __restrict__ w, uint8_t* __restrict__ out, int64_t nb) { 3053 const int64_t b = (int64_t) blockIdx.x * 8 + (threadIdx.x >> 5); 3054 const int lane = threadIdx.x & 31; 3055 if (b >= nb) return; 3056 const float v = __uint_as_float((uint32_t) w[b * 32 + lane] << 16); 3057 float amax = fabsf(v); 3058#pragma unroll 3059 for (int o = 16; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); 3060 const float d = amax / 127.0f, id = d != 0.0f ? 1.0f / d : 0.0f; 3061 uint8_t* o = out + b * 34; 3062 if (lane == 0) { 3063 const unsigned short h = __half_as_ushort(__float2half_rn(d)); 3064 o[0] = (uint8_t) (h & 255u); 3065 o[1] = (uint8_t) (h >> 8); 3066 } 3067 o[2 + lane] = (uint8_t) (int8_t) lrintf(roundf(v * id)); 3068} 3069 3070__global__ void __launch_bounds__(256) gr_dequant_q8_0_kernel(const uint8_t* __restrict__ q8, uint16_t* __restrict__ out, int64_t nb) { 3071 const int64_t b = (int64_t) blockIdx.x * 8 + (threadIdx.x >> 5); 3072 const int lane = threadIdx.x & 31; 3073 if (b >= nb) return; 3074 const uint8_t* p = q8 + b * 34; 3075 const float d = __half2float(__ushort_as_half((unsigned short) (p[0] | (p[1] << 8)))); 3076 out[b * 32 + lane] = bf16_from_f32(d * (float) (int8_t) p[2 + lane]); 3077} 3078 3079void fused_gr_dequant_q8_0(const uint8_t* q8, uint16_t* bf16, int64_t n_blocks, void* stream) { 3080 gr_dequant_q8_0_kernel<<<(unsigned) ((n_blocks + 7) / 8), 256, 0, (cudaStream_t) stream>>>(q8, bf16, n_blocks); 3081} 3082 3083void fused_gr_quantize_q8_0(const uint16_t* bf16, uint8_t* out, int64_t n_blocks, void* stream) { 3084 gr_quantize_q8_0_kernel<<<(unsigned) ((n_blocks + 7) / 8), 256, 0, (cudaStream_t) stream>>>(bf16, out, n_blocks); 3085} 3086 3087bool fused_gr_supported(int64_t n_embd, int64_t hc, int64_t hc_lr) { 3088 return n_embd == N && hc == HC && hc_lr == LR; 3089} 3090 3091void fused_gr_read(const FusedGrArgs& a, void* stream) { 3092 if (!a.R || !a.w_norm || !a.w_down || !a.w_up || !a.lo || !a.rs || !a.mixed || 3093 (a.w_inject && !a.inject_out) || (a.apply && (!a.bo_prev || !a.inj_prev || !a.R_out)) || 3094 (a.apply && a.inj_prev == a.inject_out)) { 3095 std::fprintf(stderr, "fused_gr_read: invalid arguments\n"); 3096 std::exit(1); 3097 } 3098 cudaStream_t st = (cudaStream_t) stream; 3099 constexpr size_t down_smem = kDownDynXn ? (size_t) D * 4 : 0; 3100 if (kDownDynXn) { 3101 static bool done[64] = {}; // the attribute belongs to each device, not the process (a layer split runs this on several cards) 3102 set_attr_once_per_device(done, [] { 3103 cudaFuncSetAttribute(gr_down_kernel<false>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) down_smem); 3104 cudaFuncSetAttribute(gr_down_kernel<true>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) down_smem); 3105 }); 3106 } 3107 if (a.s_down != nullptr) { // STRATA_HC_REQ8 3108 gr_down_kernel<true><<<DOWN_BLOCKS + 1, THREADS, down_smem, st>>>(a); 3109 gr_up_kernel<true><<<UP_BLOCKS, THREADS, 0, st>>>(a); 3110 } else { 3111 gr_down_kernel<<<DOWN_BLOCKS + 1, THREADS, down_smem, st>>>(a); 3112 gr_up_kernel<<<UP_BLOCKS, THREADS, 0, st>>>(a); 3113 } 3114 const cudaError_t e = cudaGetLastError(); 3115 if (e != cudaSuccess) { 3116 std::fprintf(stderr, "fused_gr_read: %s\n", cudaGetErrorString(e)); 3117 std::exit(1); 3118 } 3119} 3120 3121 3122namespace { 3123 3124/// The plain read, split, staged and (for one token) the single-token read on random bf16 weights and random inputs, 3125/// 1..8 tokens, with and without the pending write; every output of split and staged compared with the plain read's 3126/// bit for bit (and the plain read's with the single-token read's). `why[v]` gets the first difference of variant 3127/// v; false if the check itself could not run. 3128bool fused_gr_selftest(bool ok_variant[4], std::string why[4]) { 3129 constexpr int TM = kFusedGrMaxT; 3130 constexpr int NV = 4; // sets: 0 = plain, 1 = split, 2 = staged, 3 = single-token 3131 std::mt19937 rng(20260930u); 3132 std::normal_distribution<float> nd(0.0f, 1.0f); 3133 std::vector<uint16_t> h_down((size_t) LR * D), h_up((size_t) D * LR), h_inj((size_t) HC * D); 3134 std::vector<float> h_norm(D), h_R((size_t) TM * D), h_bo((size_t) TM * N), h_ip((size_t) TM * HC); 3135 for (auto& w : h_down) w = bf16_from_f32(0.02f * nd(rng)); 3136 for (auto& w : h_up) w = bf16_from_f32(0.05f * nd(rng)); 3137 for (auto& w : h_inj) w = bf16_from_f32(0.02f * nd(rng)); 3138 for (auto& w : h_norm) w = 1.0f + 0.1f * nd(rng); 3139 for (auto& x : h_R) x = nd(rng); 3140 for (auto& x : h_bo) x = 0.5f * nd(rng); 3141 for (auto& x : h_ip) x = 2.0f * nd(rng); 3142 for (int v = 0; v < 4; ++v) { ok_variant[v] = v == 1; why[v].clear(); } 3143 3144 const size_t n_set = (size_t) TM * (D + D + LR + HC + HC + N); // R_out, xn, lo, rs, inject, mixed (floats) 3145 const size_t bytes = h_down.size() * 2 + h_up.size() * 2 + h_inj.size() * 2 + 3146 (h_norm.size() + h_R.size() + h_bo.size() + h_ip.size() + NV * n_set) * 4 + 32 * 256; 3147 uint8_t* base = nullptr; 3148 if (cudaMalloc((void**) &base, bytes) != cudaSuccess) { 3149 cudaGetLastError(); 3150 why[0] = "no room for the check (" + std::to_string(bytes >> 20) + " MiB)"; 3151 return false; 3152 } 3153 size_t off = 0; 3154 auto take = [&](size_t b) { void* p = base + off; off += (b + 255) / 256 * 256; return p; }; 3155 uint16_t* d_down = (uint16_t*) take(h_down.size() * 2); 3156 uint16_t* d_up = (uint16_t*) take(h_up.size() * 2); 3157 uint16_t* d_inj = (uint16_t*) take(h_inj.size() * 2); 3158 float* d_norm = (float*) take(h_norm.size() * 4); 3159 float* d_R = (float*) take(h_R.size() * 4); 3160 float* d_bo = (float*) take(h_bo.size() * 4); 3161 float* d_ip = (float*) take(h_ip.size() * 4); 3162 struct Set { float *R_out, *xn, *lo, *rs, *inj, *mixed; } set[NV]; 3163 for (Set& x : set) { 3164 x.R_out = (float*) take((size_t) TM * D * 4); x.xn = (float*) take((size_t) TM * D * 4); 3165 x.lo = (float*) take((size_t) TM * LR * 4); x.rs = (float*) take((size_t) TM * HC * 4); 3166 x.inj = (float*) take((size_t) TM * HC * 4); x.mixed = (float*) take((size_t) TM * N * 4); 3167 } 3168 cudaStream_t st = nullptr; 3169 bool ok = off <= bytes && cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking) == cudaSuccess && 3170 cudaMemcpyAsync(d_down, h_down.data(), h_down.size() * 2, cudaMemcpyHostToDevice, st) == cudaSuccess && 3171 cudaMemcpyAsync(d_up, h_up.data(), h_up.size() * 2, cudaMemcpyHostToDevice, st) == cudaSuccess && 3172 cudaMemcpyAsync(d_inj, h_inj.data(), h_inj.size() * 2, cudaMemcpyHostToDevice, st) == cudaSuccess && 3173 cudaMemcpyAsync(d_norm, h_norm.data(), h_norm.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess && 3174 cudaMemcpyAsync(d_R, h_R.data(), h_R.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess && 3175 cudaMemcpyAsync(d_bo, h_bo.data(), h_bo.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess && 3176 cudaMemcpyAsync(d_ip, h_ip.data(), h_ip.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess; 3177 if (!ok) why[0] = "setting up the check failed"; 3178 std::vector<float> h1, h2; 3179 // true when equal; false with the first difference in `w` (or a read-back failure in `ok`) 3180 auto same = [&](const float* d1, const float* d2, size_t n, const char* what, int T, int apply, std::string& w) { 3181 h1.resize(n); 3182 h2.resize(n); 3183 if (cudaMemcpyAsync(h1.data(), d1, n * 4, cudaMemcpyDeviceToHost, st) != cudaSuccess || 3184 cudaMemcpyAsync(h2.data(), d2, n * 4, cudaMemcpyDeviceToHost, st) != cudaSuccess || 3185 cudaStreamSynchronize(st) != cudaSuccess) { 3186 why[0] = "reading back the check failed"; 3187 ok = false; 3188 return false; 3189 } 3190 for (size_t i = 0; i < n; ++i) { 3191 uint32_t u1, u2; 3192 std::memcpy(&u1, &h1[i], 4); 3193 std::memcpy(&u2, &h2[i], 4); 3194 if (u1 != u2) { 3195 char buf[192]; 3196 std::snprintf(buf, sizeof buf, "%s differs for %d token(s)%s at %zu (%08x, not %08x)", what, T, 3197 apply ? " with the pending write" : "", i, u2, u1); 3198 w = buf; 3199 return false; 3200 } 3201 } 3202 return true; 3203 }; 3204 auto all_same = [&](const Set& s1, const Set& s2, int T, int apply, std::string& w) { 3205 return same(s1.lo, s2.lo, (size_t) T * LR, "lo", T, apply, w) && 3206 same(s1.rs, s2.rs, (size_t) T * HC, "rs", T, apply, w) && 3207 same(s1.inj, s2.inj, (size_t) T * HC, "inject", T, apply, w) && 3208 same(s1.mixed, s2.mixed, (size_t) T * N, "mixed", T, apply, w) && 3209 same(s1.R_out, s2.R_out, (size_t) T * D, "R", T, apply, w); 3210 }; 3211 ok_variant[2] = ok_variant[3] = ok; 3212 bool single_ok = ok; 3213 for (int apply = 0; apply < 2 && ok; ++apply) { 3214 for (int T = 1; T <= TM && ok; ++T) { 3215 FusedGrArgs a[NV][TM]; 3216 for (int v = 0; v < NV; ++v) { 3217 const size_t span = (size_t) ((uint8_t*) (set[v].mixed + (size_t) TM * N) - (uint8_t*) set[v].R_out); 3218 ok = ok && cudaMemsetAsync(set[v].R_out, 0xFF, span, st) == cudaSuccess; // the whole set 3219 for (int k = 0; k < T; ++k) { 3220 FusedGrArgs& x = a[v][k]; 3221 x.R = d_R + (size_t) k * D; x.R_out = set[v].R_out + (size_t) k * D; x.apply = apply != 0; 3222 x.bo_prev = d_bo + (size_t) k * N; x.inj_prev = d_ip + (size_t) k * HC; 3223 x.w_norm = d_norm; x.w_down = d_down; x.w_up = d_up; x.w_inject = d_inj; x.eps = 1e-6f; 3224 x.lo = set[v].lo + (size_t) k * LR; x.rs = set[v].rs + (size_t) k * HC; 3225 x.inject_out = set[v].inj + (size_t) k * HC; x.mixed = set[v].mixed + (size_t) k * N; 3226 } 3227 } 3228 for (int v = 0; v < 3; ++v) { 3229 GrMulti m; 3230 for (int k = 0; k < T; ++k) m.a[k] = a[v][k]; 3231 m.xn = set[v].xn; 3232 m.T = T; 3233 launch_multi(m, v + 1, st, nullptr, 0); 3234 } 3235 if (T == 1) fused_gr_read(a[3][0], st); 3236 if (cudaGetLastError() != cudaSuccess || cudaStreamSynchronize(st) != cudaSuccess) { 3237 why[0] = "a kernel of the check failed"; 3238 ok = false; 3239 break; 3240 } 3241 if (ok_variant[2] && !all_same(set[0], set[1], T, apply, why[2])) ok_variant[2] = false; 3242 if (ok && ok_variant[3] && !all_same(set[0], set[2], T, apply, why[3])) ok_variant[3] = false; 3243 if (ok && T == 1 && single_ok && !all_same(set[3], set[0], T, apply, why[1])) single_ok = false; 3244 } 3245 } 3246 if (!single_ok && ok) { // the plain read itself disagrees with the single-token read 3247 why[2] = why[3] = "the plain read differs from the single-token read: " + why[1]; 3248 ok_variant[2] = ok_variant[3] = false; 3249 } 3250 if (st != nullptr) { 3251 cudaStreamSynchronize(st); 3252 cudaStreamDestroy(st); 3253 } 3254 cudaFree(base); 3255 cudaGetLastError(); 3256 if (!ok) ok_variant[2] = ok_variant[3] = false; 3257 return ok; 3258} 3259 3260} // namespace 3261 3262int fused_gr_variant() { 3263 int dev = 0; 3264 cudaGetDevice(&dev); 3265 const int v = dev >= 0 && dev < 64 ? g_variant[dev].load() : 0; 3266 if (v > 0) return v; 3267 // not checked on this card: the plain read, unless STRATA_HC_SPLIT names a variant (a test such as gr_parity) 3268 const char* e = std::getenv("STRATA_HC_SPLIT"); 3269 return e != nullptr && (e[0] == '1' || e[0] == '2') ? env_variant() : kHcPlain; 3270} 3271 3272void fused_gr_check() { 3273 int dev = 0; 3274 cudaGetDevice(&dev); 3275 (void) gr_v3_default_on(dev); // decided here, before any graph capture asks 3276 if (dev < 0 || dev >= 64 || g_variant[dev].load() > 0) return; 3277 const int want = env_variant(); 3278 if (want == kHcPlain) { 3279 g_variant[dev].store(kHcPlain); 3280 std::fprintf(stderr, "strata hc: CUDA%d: the hyper-connection read runs as the plain one (STRATA_HC_SPLIT=0)\n", 3281 dev); 3282 return; 3283 } 3284 bool okv[4]; 3285 std::string why[4]; 3286 const bool ran = fused_gr_selftest(okv, why); 3287 int use = kHcPlain; 3288 if (want >= kHcStaged && okv[kHcStaged]) use = kHcStaged; 3289 else if (okv[kHcSplit]) use = kHcSplit; 3290 g_variant[dev].store(use); 3291 if (!ran) 3292 std::fprintf(stderr, "strata hc: CUDA%d: the check of split/staged could not run (%s)\n", dev, why[0].c_str()); 3293 static const char* const name[4] = {"", "plain", "split", "staged"}; 3294 for (int v = kHcStaged; v >= kHcSplit; --v) 3295 if (v <= want && !okv[v] && ran) 3296 std::fprintf(stderr, "strata hc: CUDA%d: the %s read differs from the plain read on this card - not used: " 3297 "%s\n", dev, name[v], why[v].c_str()); 3298 static const char* const what[4] = { 3299 "", "the plain read (the norm per token, the down projection on 41 blocks)", 3300 "split (the norm per token and stream, then the plain read's down projection)", 3301 "staged (the norm per token and stream, the down projection's activations staged ahead by cp.async)"}; 3302 std::fprintf(stderr, "strata hc: CUDA%d: the hyper-connection read runs as %s%s\n", dev, what[use], 3303 use >= kHcSplit ? "; checked bit for bit against the plain read on this card (STRATA_HC_SPLIT=1 or 0 " 3304 "for the earlier ones)" : ""); 3305} 3306 3307 3308namespace { 3309__global__ void hc_q8_bf16_kernel(const int8_t* __restrict__ q, const float* __restrict__ sc, uint16_t* __restrict__ out, 3310 long long n) { 3311 const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; 3312 if (i >= n) return; 3313 const float v = sc[i / 32] * (float) q[i]; 3314 uint32_t b = __float_as_uint(v); 3315 b += 0x7fffu + ((b >> 16) & 1u); // round to nearest even (the values are finite) 3316 out[i] = (uint16_t) (b >> 16); 3317} 3318} // namespace 3319 3320void hc_q8_to_bf16(const void* codes, const float* scales, uint16_t* out, long long n, void* stream) { 3321 hc_q8_bf16_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, (cudaStream_t) stream>>>((const int8_t*) codes, scales, out, n); 3322} 3323 3324// ================================== the read as ONE persistent kernel (opt-in STRATA_HC_PERSIST=1, CUDA + HIP) ============== 3325// 80 blocks that must all be resident (a start-up run per T decides; larger T keep the default read) and two grid 3326// barriers on an atomic counter. Block b: (A) stages R' * w_norm for columns [128 b, 128 b + 128) (one stream) and writes 3327// that slice's sum of squares and the UNSCALED partial dots of the 320 down + 4 inject rows (the v3 identity 3328// w . xn = sum_c rs[c] (w[:, c] . x'[c])); barrier; (B) rs per stream, then rows (k, r) = b + 80 j reduced to lo / inject; 3329// barrier; (C) the up projection read straight from VRAM, a thread pair per row, the epilogue as gr_up_kernel. 3330// ANOTHER SUMMATION ORDER than the default read (not bitwise; the init check bounds the difference). Only the verifier's hyper-connection reads use it: they run on one stream per card (both pipeline 3331// verifiers share it), so two of these kernels never wait on each other; the drafter's reads keep the default kernels. 3332#if defined(__HIPCC__) || defined(__CUDACC__) 3333namespace { 3334namespace hcp { 3335// CUDA spells the shuffle with an explicit mask; HIP without. One helper so the kernel body below stays portable. 3336template <typename T> 3337__device__ __forceinline__ T shfl_xor_persist(T v, int mask) { 3338#if defined(__HIPCC__) 3339 return __shfl_xor(v, mask); 3340#else 3341 return __shfl_xor_sync(0xffffffffu, v, mask); 3342#endif 3343} 3344// Measured on gfx1030 (bench/results/2026-10-12-hc-persist-gfx1030): the gain over the three-kernel read is (1) the down 3345// projection split by column slices over all 80 blocks (the default read runs 41 blocks staging the activations through 3346// LDS) and (2) one launch with two grid barriers instead of three launches and the gaps between them. Prefetching the 3347// up weights (into registers or by touching them into L2 / Infinity Cache) and the epilogue inputs measured no gain on 3348// gfx1030 and is gone: the 13 MB are read once from VRAM whichever way. 3349constexpr int NB = N / 32, SL = D / NB, SPS = N / SL, UPC = N / NB, NR = LR + HC; // 80 blocks for Flash-Next: 32 up columns a block 3350static_assert(UPC * HC * 2 == THREADS, "a thread pair per up row"); 3351struct PArgs { 3352 FusedGrArgs a[kFusedGrMaxT]; 3353 float* part; // [T][NR][NB] 3354 float* ssp; // [T][NB] 3355 unsigned* bar; // [0] count, [32] generation, [48] abort (a barrier that timed out) 3356 unsigned long long timeout_ticks; // s_memrealtime ticks (100 MHz) a barrier waits before it aborts the read 3357 double* partd; // STRATA_HC_PERSIST=3 (a reference only): the partial dots and sums of squares in double 3358 double* sspd; 3359}; 3360// Returns false when the read was aborted: a block waited longer than `ticks` (the 80 blocks were not all resident - the 3361// start-up check finds that out by running every T with a short timeout) or another block aborted. Then every block 3362// leaves the kernel; the outputs are not written completely and bar[48] stays set until the host clears the words. 3363__device__ __forceinline__ bool grid_sync(unsigned* bar, unsigned long long ticks) { 3364#if defined(__GFX11__) || defined(__GFX12__) 3365 // gfx11 and gfx12 have no s_memrealtime (clang: "needs target feature s-memrealtime"), so no barrier clock: this read is not 3366 // offered there (fused_gr_persist_init refuses it; an R9700 measured it neutral to 1% slower in #2226), and a launch that gets 3367 // here anyway aborts at once instead of waiting for a barrier it cannot time. 3368 (void) ticks; 3369 if (threadIdx.x == 0) __hip_atomic_store(&bar[48], 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); 3370 return false; 3371#elif defined(__CUDACC__) 3372 // CUDA: the same generation barrier. clock64() counts SM clocks (~2 GHz), so the tick constants below are scaled; 3373 // the timeout turns a card that cannot hold all NB blocks resident into a wrong-but-slow read rather than a hang. 3374 __shared__ int s_abort; 3375 volatile unsigned* vb = bar; 3376 __syncthreads(); 3377 if (threadIdx.x == 0) { 3378 int ab = 0; 3379 const unsigned gen = vb[32]; 3380 __threadfence(); 3381 const unsigned arrived = atomicAdd(&bar[0], 1u); 3382 if (arrived == NB - 1) { 3383 atomicExch(&bar[0], 0u); 3384 __threadfence(); 3385 atomicAdd(&bar[32], 1u); 3386 } else { 3387 const long long t0 = clock64(); 3388 while (vb[32] == gen) { 3389 if (vb[48] != 0u) { ab = 1; break; } 3390 if (clock64() - t0 > (long long) ticks) { atomicExch(&bar[48], 1u); ab = 1; break; } 3391#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700 3392 __nanosleep(64); // (sm_60 has no nanosleep: the barrier spins) 3393#endif 3394 } 3395 } 3396 if (vb[48] != 0u) ab = 1; 3397 s_abort = ab; 3398 } 3399 __syncthreads(); 3400 __threadfence(); 3401 return s_abort == 0; 3402#else 3403 __shared__ int s_abort; 3404 __syncthreads(); 3405 if (threadIdx.x == 0) { 3406 int ab = 0; 3407 const unsigned gen = __hip_atomic_load(&bar[32], __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); 3408 __threadfence(); 3409 const unsigned arrived = __hip_atomic_fetch_add(&bar[0], 1u, __ATOMIC_ACQ_REL, __HIP_MEMORY_SCOPE_AGENT); 3410 if (arrived == NB - 1) { 3411 __hip_atomic_store(&bar[0], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); 3412 __hip_atomic_fetch_add(&bar[32], 1u, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT); 3413 } else { 3414 const unsigned long long t0 = __builtin_amdgcn_s_memrealtime(); 3415 while (__hip_atomic_load(&bar[32], __ATOMIC_ACQUIRE, __HIP_MEMORY_SCOPE_AGENT) == gen) { 3416 if (__hip_atomic_load(&bar[48], __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) != 0u) { ab = 1; break; } 3417 if (__builtin_amdgcn_s_memrealtime() - t0 > ticks) { 3418 __hip_atomic_store(&bar[48], 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); 3419 ab = 1; 3420 break; 3421 } 3422 __builtin_amdgcn_s_sleep(1); 3423 } 3424 } 3425 if (__hip_atomic_load(&bar[48], __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) != 0u) ab = 1; 3426 s_abort = ab; 3427 } 3428 __syncthreads(); 3429 __threadfence(); 3430 return s_abort == 0; 3431#endif 3432} 3433// STRATA_HC_PERSIST=3 (a reference only, slow): every dot and sum accumulated in double 3434__device__ __forceinline__ double dot8d(const uint4 w, const float* x) { 3435 double acc = 0.0; 3436 const unsigned u[4] = {w.x, w.y, w.z, w.w}; 3437#pragma unroll 3438 for (int q = 0; q < 4; ++q) { 3439 acc += (double) __uint_as_float(u[q] << 16) * (double) x[2 * q]; 3440 acc += (double) __uint_as_float(u[q] & 0xffff0000u) * (double) x[2 * q + 1]; 3441 } 3442 return acc; 3443} 3444template <int T, bool DP = false> 3445__global__ void __launch_bounds__(THREADS) persist_kernel(PArgs f) { 3446 using A = typename std::conditional<DP, double, float>::type; 3447 __shared__ __align__(16) float xs[T][SL]; 3448 __shared__ __align__(16) float lo[T][LR]; 3449 __shared__ float s_rs[T][HC]; 3450 __shared__ float g[T][HC][UPC]; 3451 const int tid = threadIdx.x, lane = tid & 31, b = blockIdx.x; 3452 const FusedGrArgs& a0 = f.a[0]; 3453 // (A) block b: columns [128 b, 128 b + 128) of D (one stream): R' * w_norm into LDS, the slice's sum of squares, and 3454 // the UNSCALED partial dots of the 320 down + 4 inject rows (w . xn = sum_c rs[c] (w[:, c] . x'[c])) 3455 const int c_b = b / SPS, col0 = b * SL; 3456 if (tid < T * (SL / 4)) { 3457 const int k = tid / (SL / 4), o4 = tid - k * (SL / 4); 3458 const FusedGrArgs& a = f.a[k]; 3459 const int i = col0 + o4 * 4, d = i - c_b * N; 3460 float4 r = *reinterpret_cast<const float4*>(a.R + i); 3461 if (a.apply) { 3462 const float gw = 2.0f * sigmoidf_(a.inj_prev[c_b] / (float) HC); 3463 const float4 bo = *reinterpret_cast<const float4*>(a.bo_prev + d); 3464 r.x = fmaf(bo.x, gw, r.x); r.y = fmaf(bo.y, gw, r.y); r.z = fmaf(bo.z, gw, r.z); r.w = fmaf(bo.w, gw, r.w); 3465 } 3466 const float4 gn = *reinterpret_cast<const float4*>(a.w_norm + i); 3467 if constexpr (DP) { 3468 double ss = (double) r.x * r.x + (double) r.y * r.y + (double) r.z * r.z + (double) r.w * r.w; 3469#pragma unroll 3470 for (int o = 16; o > 0; o >>= 1) ss += shfl_xor_persist(ss, o); 3471 if (lane == 0) f.sspd[k * NB + b] = ss; 3472 } else { 3473 const float ss = warp_sum(r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w); // warp k = token k 3474 if (lane == 0) f.ssp[k * NB + b] = ss; 3475 } 3476 *reinterpret_cast<float4*>(&xs[k][o4 * 4]) = make_float4(r.x * gn.x, r.y * gn.y, r.z * gn.z, r.w * gn.w); 3477 } 3478 __syncthreads(); 3479 const int hw = tid >> 4, hl = tid & 15; 3480 const bool inj = a0.w_inject != nullptr; 3481 const int nrows = inj ? NR : LR; 3482#pragma unroll 3 3483 for (int r = hw; r < nrows; r += 16) { 3484 const uint16_t* wrow = r < LR ? a0.w_down + (size_t) r * D : a0.w_inject + (size_t) (r - LR) * D; 3485 const uint4 w = __ldg(reinterpret_cast<const uint4*>(wrow + col0) + hl); 3486 A acc[T]; 3487#pragma unroll 3488 for (int k = 0; k < T; ++k) { 3489 A v; 3490 if constexpr (DP) v = dot8d(w, &xs[k][hl * 8]); else v = dot8(w, &xs[k][hl * 8]); 3491#pragma unroll 3492 for (int o = 8; o > 0; o >>= 1) v += shfl_xor_persist(v, o); 3493 acc[k] = v; 3494 } 3495#pragma unroll 3496 for (int k = 0; k < T; ++k) 3497 if (hl == k) { 3498 if constexpr (DP) f.partd[((size_t) k * NR + r) * NB + b] = acc[k]; 3499 else f.part[((size_t) k * NR + r) * NB + b] = (float) acc[k]; 3500 } 3501 } 3502 if (!grid_sync(f.bar, f.timeout_ticks)) return; 3503 // (B) rs per stream (every block), then rows (k, r) = b + 80 j reduced to lo / inject by the blocks in turn 3504 if (tid < T * HC) { 3505 const int k = tid / HC, c = tid - k * HC; 3506 float rr; 3507 if constexpr (DP) { 3508 double sd = 0.0; 3509 for (int j = 0; j < SPS; ++j) sd += f.sspd[k * NB + c * SPS + j]; 3510 rr = (float) (1.0 / sqrt(sd / (double) N + (double) f.a[k].eps)); 3511 } else { 3512 float s = 0.0f; 3513 for (int j = 0; j < SPS; ++j) s += f.ssp[k * NB + c * SPS + j]; 3514 rr = rsqrtf(s / (float) N + f.a[k].eps); 3515 } 3516 s_rs[k][c] = rr; 3517 if (b == 0) f.a[k].rs[c] = rr; 3518 } 3519 __syncthreads(); 3520 for (int idx = b + NB * tid; idx < T * nrows; idx += NB * THREADS) { 3521 const int k = idx / nrows, r = idx - k * nrows; 3522 A sum = 0; 3523 if constexpr (DP) { 3524 const double* p1 = f.partd + ((size_t) k * NR + r) * NB; 3525 for (int c = 0; c < HC; ++c) { 3526 double p = 0.0; 3527 for (int j = 0; j < SPS; ++j) p += p1[c * SPS + j]; 3528 sum += (double) s_rs[k][c] * p; 3529 } 3530 } else { 3531 const float4* p4 = reinterpret_cast<const float4*>(f.part + ((size_t) k * NR + r) * NB); 3532#pragma unroll 3533 for (int c = 0; c < HC; ++c) { 3534 float p = 0.0f; 3535#pragma unroll 3536 for (int j = 0; j < SPS / 4; ++j) { 3537 const float4 v = p4[c * (SPS / 4) + j]; 3538 p += (v.x + v.y) + (v.z + v.w); 3539 } 3540 sum = fmaf(s_rs[k][c], p, sum); 3541 } 3542 } 3543 if (r < LR) { 3544 const A x = sum / (A) HC; 3545 f.a[k].lo[r] = (float) (x / ((A) 1 + (DP ? (A) exp((double) -x) : (A) __expf((float) -x)))); 3546 } else { 3547 f.a[k].inject_out[r - LR] = (float) sum; 3548 } 3549 } 3550 if (!grid_sync(f.bar, f.timeout_ticks)) return; 3551 for (int idx = tid; idx < T * LR; idx += THREADS) { 3552 const int k = idx / LR, r = idx - k * LR; 3553 lo[k][r] = f.a[k].lo[r]; 3554 } 3555 __syncthreads(); 3556 // (C) the up projection, a thread pair per row (block b: columns 32 b .. 32 b + 31 of all four streams), then the 3557 // epilogue as gr_up_kernel 3558 { 3559 const int d0 = b * UPC; 3560 const int ur = tid >> 1, uh = tid & 1, uc = ur / UPC, udd = ur - uc * UPC, ui = uc * N + d0 + udd; 3561 const uint4* w4u = reinterpret_cast<const uint4*>(a0.w_up + (size_t) ui * LR) + uh * 20; 3562 A v[T]; 3563#pragma unroll 3564 for (int k = 0; k < T; ++k) v[k] = 0; 3565#pragma unroll 1 3566 for (int j0 = 0; j0 < 20; j0 += 5) { // five chunks a batch (all twenty at once costs registers) 3567 uint4 w[5]; 3568#pragma unroll 3569 for (int q = 0; q < 5; ++q) w[q] = __ldg(w4u + j0 + q); 3570#pragma unroll 3571 for (int q = 0; q < 5; ++q) 3572#pragma unroll 3573 for (int k = 0; k < T; ++k) { 3574 if constexpr (DP) v[k] += dot8d(w[q], &lo[k][uh * 160] + (j0 + q) * 8); 3575 else v[k] += dot8(w[q], &lo[k][uh * 160] + (j0 + q) * 8); 3576 } 3577 } 3578 float acc[T]; 3579#pragma unroll 3580 for (int k = 0; k < T; ++k) acc[k] = (float) (v[k] + shfl_xor_persist(v[k], 1)); 3581 if (uh == 0) { 3582 const float wn = a0.w_norm[ui]; 3583#pragma unroll 3584 for (int k = 0; k < T; ++k) { 3585 const FusedGrArgs& a = f.a[k]; 3586 float rv = a.R[ui]; 3587 if (a.apply) { 3588 rv = fmaf(a.bo_prev[d0 + udd], 2.0f * sigmoidf_(a.inj_prev[uc] / (float) HC), rv); 3589 a.R_out[ui] = rv; 3590 } 3591 g[k][uc][udd] = rv * wn * s_rs[k][uc] * sigmoidf_(acc[k]); 3592 } 3593 } 3594 } 3595 __syncthreads(); 3596 for (int idx = tid; idx < T * UPC; idx += THREADS) { 3597 const int k = idx / UPC, col = idx - k * UPC; 3598 float s = 0.0f; 3599#pragma unroll 3600 for (int c = 0; c < HC; ++c) s += g[k][c][col]; 3601 f.a[k].mixed[b * UPC + col] = s / (float) HC; 3602 } 3603} 3604struct DevState { 3605 float* part = nullptr; 3606 float* ssp = nullptr; 3607 double* partd = nullptr; 3608 double* sspd = nullptr; 3609 unsigned* bar = nullptr; 3610 int max_t = 0; // 0: off on this card 3611 bool tried = false; 3612}; 3613DevState g_dev[64]; 3614using KFn = void (*)(PArgs); 3615template <bool DP> 3616KFn kernel_t(int T) { 3617 switch (T) { 3618 case 1: return persist_kernel<1, DP>; 3619 case 2: return persist_kernel<2, DP>; 3620 case 3: return persist_kernel<3, DP>; 3621 case 4: return persist_kernel<4, DP>; 3622 case 5: return persist_kernel<5, DP>; 3623 case 6: return persist_kernel<6, DP>; 3624 case 7: return persist_kernel<7, DP>; 3625 case 8: return persist_kernel<8, DP>; 3626 } 3627 return nullptr; 3628} 3629bool dp_on() { 3630 static const bool dp = [] { const char* v = std::getenv("STRATA_HC_PERSIST"); return v != nullptr && std::atoi(v) == 3; }(); 3631 return dp; 3632} 3633KFn kernel_for(int T) { return dp_on() ? kernel_t<true>(T) : kernel_t<false>(T); } 3634// s_memrealtime runs at 100 MHz on RDNA: a barrier gives up after 2 s in a read (never in a working run; it only turns a 3635// hang into a wrong read) and after 50 ms in the start-up check (where a timeout means "not resident here") 3636#if defined(__CUDACC__) 3637// clock64() counts SM clocks (~2 GHz on these cards): 2 s a read, 50 ms the start-up check, the same wall times the 3638// HIP constants give at s_memrealtime's 100 MHz 3639constexpr unsigned long long kTicksRun = 4000000000ULL, kTicksCheck = 100000000ULL; 3640#else 3641constexpr unsigned long long kTicksRun = 200000000ULL, kTicksCheck = 5000000ULL; 3642#endif 3643void launch(const FusedGrArgs* a, int n_tok, const DevState& st, cudaStream_t s, unsigned long long ticks) { 3644 PArgs f; 3645 for (int t = 0; t < n_tok; ++t) f.a[t] = a[t]; 3646 f.part = st.part; f.ssp = st.ssp; f.bar = st.bar; f.partd = st.partd; f.sspd = st.sspd; f.timeout_ticks = ticks; 3647 kernel_for(n_tok)<<<NB, THREADS, 0, s>>>(f); 3648} 3649bool env_on() { 3650 static const bool on = [] { const char* v = std::getenv("STRATA_HC_PERSIST"); return v != nullptr && std::atoi(v) != 0; }(); 3651 return on; 3652} 3653} // namespace hcp 3654} // namespace 3655 3656void fused_gr_persist_init() { 3657 if (!hcp::env_on()) return; 3658 int dev = 0; 3659 cudaGetDevice(&dev); 3660 if (dev < 0 || dev >= 64 || hcp::g_dev[dev].tried) return; 3661 hcp::DevState& st = hcp::g_dev[dev]; 3662 st.tried = true; 3663 cudaDeviceProp prop{}; 3664 cudaGetDeviceProperties(&prop, dev); 3665 if (prop.warpSize != 32) { 3666 std::fprintf(stderr, "strata hc: CUDA%d: STRATA_HC_PERSIST=1 is off here: the kernel is written for 32-lane waves " 3667 "(this card runs %d)\n", dev, prop.warpSize); 3668 return; 3669 } 3670#if defined(__HIPCC__) 3671 if (strata::kernels::gfx_arch_is_gfx12(prop.gcnArchName) || strata::kernels::gfx_arch_is_gfx11_wmma(prop.gcnArchName)) { 3672 std::fprintf(stderr, "strata hc: CUDA%d: STRATA_HC_PERSIST=1 is off here: gfx11 / gfx12 have no s_memrealtime for the barrier " 3673 "timeout (written and measured for gfx1030; an R9700 saw no gain from it, #2226)\n", dev); 3674 return; 3675 } 3676#endif 3677 const int mp = prop.multiProcessorCount; // only for the confirmation line (WGPs on RDNA) 3678 bool ok = cudaMalloc((void**) &st.part, (size_t) kFusedGrMaxT * hcp::NR * hcp::NB * sizeof(float)) == cudaSuccess && 3679 cudaMalloc((void**) &st.ssp, (size_t) kFusedGrMaxT * hcp::NB * sizeof(float)) == cudaSuccess && 3680 cudaMalloc((void**) &st.bar, 64 * sizeof(unsigned)) == cudaSuccess && 3681 cudaMalloc((void**) &st.partd, (size_t) kFusedGrMaxT * hcp::NR * hcp::NB * sizeof(double)) == cudaSuccess && 3682 cudaMalloc((void**) &st.sspd, (size_t) kFusedGrMaxT * hcp::NB * sizeof(double)) == cudaSuccess && 3683 cudaMemset(st.bar, 0, 64 * sizeof(unsigned)) == cudaSuccess; 3684 if (!ok) { 3685 cudaGetLastError(); 3686 std::fprintf(stderr, "strata hc: CUDA%d: STRATA_HC_PERSIST=1 is off here: workspace allocation failed\n", dev); 3687 return; 3688 } 3689 // the check: random weights and inputs with the pending write and the inject rows, against the default read; the 3690 // persistent read sums in another order, so it is bounded, not bitwise. Every T is RUN with a 50 ms barrier timeout; a 3691 // timeout means "not resident here" and larger T keep the default read. No occupancy API in front of it: it promised 3692 // more than the card holds on 30 WGPs under HSA_CU_MASK (a hang without the timeout) and less than it holds with 3693 // the HIP 7.1 runtime (1 block per WGP on 40 WGPs, which turned the read off although it runs resident). 3694 std::mt19937 rng(11); 3695 std::normal_distribution<float> nd(0.f, 1.f); 3696 auto bf = [](float x) { uint32_t u; std::memcpy(&u, &x, 4); return (uint16_t) ((u + 0x7fff + ((u >> 16) & 1)) >> 16); }; 3697 const int TM = kFusedGrMaxT; 3698 std::vector<float> R((size_t) TM * D), bo((size_t) TM * N), inj((size_t) TM * HC), wn(D); 3699 for (auto& x : R) x = nd(rng); 3700 for (auto& x : bo) x = 0.5f * nd(rng); 3701 for (auto& x : inj) x = nd(rng); 3702 for (auto& x : wn) x = 1.0f + 0.3f * nd(rng); 3703 std::vector<uint16_t> wd((size_t) LR * D), wu((size_t) D * LR), wi((size_t) HC * D); 3704 for (auto& x : wd) x = bf(0.02f * nd(rng)); 3705 for (auto& x : wu) x = bf(0.05f * nd(rng)); 3706 for (auto& x : wi) x = bf(0.02f * nd(rng)); 3707 float *dR, *dbo, *dinj, *dwn, *dxn, *dlo, *drs, *dio, *dmix; 3708 uint16_t *dwd, *dwu, *dwi; 3709 cudaMalloc((void**) &dR, R.size() * 4); cudaMalloc((void**) &dbo, bo.size() * 4); 3710 cudaMalloc((void**) &dinj, inj.size() * 4); cudaMalloc((void**) &dwn, wn.size() * 4); 3711 cudaMalloc((void**) &dxn, (size_t) TM * D * 4); cudaMalloc((void**) &dlo, (size_t) TM * LR * 4); 3712 cudaMalloc((void**) &drs, (size_t) TM * HC * 4); cudaMalloc((void**) &dio, (size_t) TM * HC * 4); 3713 cudaMalloc((void**) &dmix, (size_t) TM * N * 4); 3714 cudaMalloc((void**) &dwd, wd.size() * 2); cudaMalloc((void**) &dwu, wu.size() * 2); cudaMalloc((void**) &dwi, wi.size() * 2); 3715 cudaMemcpy(dbo, bo.data(), bo.size() * 4, cudaMemcpyHostToDevice); 3716 cudaMemcpy(dinj, inj.data(), inj.size() * 4, cudaMemcpyHostToDevice); 3717 cudaMemcpy(dwn, wn.data(), wn.size() * 4, cudaMemcpyHostToDevice); 3718 cudaMemcpy(dwd, wd.data(), wd.size() * 2, cudaMemcpyHostToDevice); 3719 cudaMemcpy(dwu, wu.data(), wu.size() * 2, cudaMemcpyHostToDevice); 3720 cudaMemcpy(dwi, wi.data(), wi.size() * 2, cudaMemcpyHostToDevice); 3721 double worst = 0.0; 3722 int bad_t = 0, timeouts = 0; 3723 // 0: the read agrees with the default read; 1: a barrier timed out (not resident); 2: wrong or a device error 3724 auto check = [&](int T) -> int { 3725 FusedGrArgs a[kFusedGrMaxT]; 3726 for (int t = 0; t < T; ++t) { 3727 a[t] = FusedGrArgs{}; 3728 a[t].R = dR + (size_t) t * D; a[t].R_out = dR + (size_t) t * D; a[t].apply = true; 3729 a[t].bo_prev = dbo + (size_t) t * N; a[t].inj_prev = dinj + (size_t) t * HC; 3730 a[t].w_norm = dwn; a[t].w_down = dwd; a[t].w_up = dwu; a[t].w_inject = dwi; a[t].eps = 1e-6f; 3731 a[t].lo = dlo + (size_t) t * LR; a[t].rs = drs + (size_t) t * HC; 3732 a[t].inject_out = dio + (size_t) t * HC; a[t].mixed = dmix + (size_t) t * N; 3733 } 3734 std::vector<float> out[2]; 3735 for (int which = 0; which < 2; ++which) { 3736 cudaMemcpy(dR, R.data(), R.size() * 4, cudaMemcpyHostToDevice); 3737 cudaMemset(dmix, 0xff, (size_t) TM * N * 4); 3738 cudaMemset(dio, 0xff, (size_t) TM * HC * 4); 3739 cudaDeviceSynchronize(); 3740 if (which == 0) fused_gr_read_multi(a, T, dxn, nullptr); 3741 else hcp::launch(a, T, st, nullptr, hcp::kTicksCheck); 3742 if (cudaDeviceSynchronize() != cudaSuccess) { cudaGetLastError(); return 2; } 3743 if (which == 1) { 3744 unsigned abort_word = 0; 3745 cudaMemcpy(&abort_word, st.bar + 48, sizeof abort_word, cudaMemcpyDeviceToHost); 3746 if (abort_word != 0u) { 3747 cudaMemset(st.bar, 0, 64 * sizeof(unsigned)); 3748 cudaDeviceSynchronize(); 3749 return 1; 3750 } 3751 } 3752 out[which].resize((size_t) T * (N + HC + D)); 3753 cudaMemcpy(out[which].data(), dmix, (size_t) T * N * 4, cudaMemcpyDeviceToHost); 3754 cudaMemcpy(out[which].data() + (size_t) T * N, dio, (size_t) T * HC * 4, cudaMemcpyDeviceToHost); 3755 cudaMemcpy(out[which].data() + (size_t) T * (N + HC), dR, (size_t) T * D * 4, cudaMemcpyDeviceToHost); 3756 } 3757 double mref = 0.0, md = 0.0; 3758 bool finite = true; 3759 for (size_t i = 0; i < out[0].size(); ++i) { 3760 finite = finite && std::isfinite(out[1][i]); 3761 mref = std::fmax(mref, std::fabs((double) out[0][i])); 3762 md = std::fmax(md, std::fabs((double) out[1][i] - out[0][i])); 3763 } 3764 const double rel = md / (mref > 0 ? mref : 1.0); 3765 worst = std::fmax(worst, rel); 3766 return finite && rel < 1e-4 ? 0 : 2; 3767 }; 3768 int max_t = 0; 3769 for (int T = 1; T <= kFusedGrMaxT && ok; ++T) { 3770 const int r = check(T); 3771 if (r == 1) ++timeouts; else if (r == 2) { bad_t = T; ok = false; } 3772 if (r != 0) break; 3773 max_t = T; 3774 } 3775 cudaFree(dR); cudaFree(dbo); cudaFree(dinj); cudaFree(dwn); cudaFree(dxn); cudaFree(dlo); cudaFree(drs); 3776 cudaFree(dio); cudaFree(dmix); cudaFree(dwd); cudaFree(dwu); cudaFree(dwi); 3777 cudaMemset(st.bar, 0, 64 * sizeof(unsigned)); 3778 cudaDeviceSynchronize(); 3779 cudaGetLastError(); 3780 if (!ok) { 3781 std::fprintf(stderr, "strata hc: CUDA%d: STRATA_HC_PERSIST=1 is off here: the check failed at %d tokens " 3782 "(max relative difference %.3g)\n", dev, bad_t, worst); 3783 return; 3784 } 3785 if (max_t == 0) { 3786 std::fprintf(stderr, "strata hc: CUDA%d: STRATA_HC_PERSIST=1 is off here: 80 blocks are not resident at once on %d " 3787 "multiprocessors (the check timed out)\n", dev, mp); 3788 return; 3789 } 3790 st.max_t = max_t; 3791 std::fprintf(stderr, "strata hc: CUDA%d: STRATA_HC_PERSIST=1: the verifier's hyper-connection read runs as one " 3792 "persistent kernel (80 blocks on %d multiprocessors, up to %d tokens; %d token counts timed out in " 3793 "the check; checked against the default read, max relative difference %.2g)\n", dev, mp, max_t, 3794 timeouts, worst); 3795} 3796 3797bool fused_gr_read_persist(const FusedGrArgs* a, int n_tok, void* stream) { 3798 if (!hcp::env_on() || n_tok < 1) return false; 3799 int dev = 0; 3800 cudaGetDevice(&dev); 3801 if (dev < 0 || dev >= 64) return false; 3802 const hcp::DevState& st = hcp::g_dev[dev]; 3803 if (n_tok > st.max_t) return false; 3804 if (a[0].q8_down != nullptr || a[0].q8_up != nullptr) return false; // STRATA_HC_Q8: the default read 3805 for (int t = 0; t < n_tok; ++t) 3806 if (a[t].q8_mixed != nullptr) return false; // STRATA_QFUSE: the default read 3807 hcp::launch(a, n_tok, st, (cudaStream_t) stream, hcp::kTicksRun); 3808 return true; 3809} 3810#else 3811void fused_gr_persist_init() {} 3812bool fused_gr_read_persist(const FusedGrArgs*, int, void*) { return false; } 3813#endif 3814 3815} // namespace strata::kernels 3816 3817 3818