prefill: DeltaNet recurrence with the three value heads of a key head in one thread (1.44x), output norm without its dead FP32 store (1.5x); same bits
gdn_rec_cols_pipe_kernel is bound by shared memory, not by arithmetic: every thread of a warp needs the same 32 q and k values per token (the k twice), and a warp receives one such broadcast value per clock. The new kernel runs column c of the three value heads that share a key head (head % 16) in one thread, so every q/k value it loads feeds three heads and the token's k row is loaded into registers once for both of its uses. Its inputs come in blocks of 8 tokens, copied to shared memory by cp.async while the block before computes, and a token needs 2 __syncthreads instead of 5. 64 blocks instead of 192. Per value head and column the same arithmetic in the same order: gdn_rec_parity checks output, state and FP16 output bit for bit (T from 1 to 4099) and times it: 18.8 -> 13.0 ms per layer at 32768 tokens. The output norm stored the normalized value in FP32 as well, which nothing reads (the out projection takes the FP16 copy): 4.65 -> 3.05 ms per layer at 32768 tokens. Together 845 -> 579 ms per 32768-token block over the 36 DeltaNet layers; in the engine +2.3 % prefill tokens/s on 32000-token prompts and +2.2 % on 64000-token prompts, the same greedy answers. Measured on 0.1.32 on a 4080 SUPER (80 SMs); on 0.1.31 the same change gave 1.42x, 1.51x and +2.1 % / +2.0 %. CUDA sm_80+ (cp.async) on a card that holds all 64 blocks at once; otherwise, on Turing and with STRATA_GDN_KEYHEAD=0 the kernel as before. Squashed from #413 (5 commits: the kernel, gdn_rec_parity and its --bench SM bands; the 48-63 SM exception added and taken back).
This commit is contained in:
1 parent
482e22b7cd
commit
4e69f97477
4 files changed
+1065
-4
No files matched your search
@@ -558,6 +558,13 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
|
||||
target_include_directories(iq_multi_parity PRIVATE ${_strata_gpu_include_directories})
|
||||
target_link_libraries(iq_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
|
||||
add_test(NAME iq_multi_parity COMMAND iq_multi_parity)
|
||||
# the prompt path's DeltaNet recurrence: gdn_rec_kh_kernel against gdn_rec_cols_pipe_kernel, bitwise (GPU,
|
||||
# synthetic, no model; --bench adds timings)
|
||||
if(STRATA_ENABLE_CUDA)
|
||||
add_executable(gdn_rec_parity src/prefill/gdn_rec_parity.cu)
|
||||
target_link_libraries(gdn_rec_parity PRIVATE ${_strata_gpu_runtime_target})
|
||||
add_test(NAME gdn_rec_parity COMMAND gdn_rec_parity)
|
||||
endif()
|
||||
add_executable(shared_expert_parity src/kernels/shared_expert_parity.cpp)
|
||||
target_include_directories(shared_expert_parity PRIVATE ${_strata_gpu_include_directories})
|
||||
target_link_libraries(shared_expert_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
|
||||
|
||||
@@ -43,8 +43,8 @@ void gdn_gates(const float* ab, const float* dt, const float* ssm_a, float* gate
|
||||
/// The 4-tap causal conv + SiLU over the chunk (history [C][3] in, updated to the chunk's last three inputs), then
|
||||
/// the L2 norm of the q and k heads of every token. h: [T, C].
|
||||
void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, int64_t T, float eps, void* stream);
|
||||
/// The recurrence over the chunk, block per value head, state in registers; y[t] = rmsnorm(o) * gamma * sigmoid(z)
|
||||
/// (FP32 and FP16 bits: the out projection is quantized).
|
||||
/// The recurrence over the chunk, state in registers; y16[t] = rmsnorm(o) * gamma * sigmoid(z) in FP16 (what the
|
||||
/// out projection reads); y is FP32 scratch.
|
||||
void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z,
|
||||
const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream);
|
||||
|
||||
|
||||
@@ -0,0 +1,886 @@
|
||||
// src/prefill/gdn_rec_parity.cu - the prompt path's DeltaNet recurrence, bit for bit and timed.
|
||||
//
|
||||
// src/prefill/kernels.cu runs gdn_rec_kh_kernel (the three value heads that share a key head in one thread, the
|
||||
// inputs staged in blocks of 8 tokens) on CUDA sm_80+ cards that hold all 64 of its blocks at once, and
|
||||
// gdn_rec_cols_pipe_kernel elsewhere and with STRATA_GDN_KEYHEAD=0. Both are copied below verbatim, with the output
|
||||
// norm (gdn_out_norm_kernel) and the norm as it was before, which also stored the normalized value in FP32 although
|
||||
// nothing reads it. The two recurrences do the same arithmetic in the same order per value head and column, so the
|
||||
// output, the state after it and the FP16 output must be the same bits.
|
||||
//
|
||||
// Synthetic inputs of the model's shape (q/k L2-normalized per key head as gdn_l2_kernel leaves them), no model.
|
||||
// gdn_rec_parity the bit checks (T from 1 to 4099, a non-zero state as after an earlier chunk)
|
||||
// gdn_rec_parity --bench and the timings at T = 8192 and 32768 (one layer, all 48 value heads); the two
|
||||
// variants' launches alternate, since a card under load steps its clock down after a
|
||||
// fraction of a second (see native_grouped_parity); then both at 1 to 6 blocks per
|
||||
// SM, as on cards with more or fewer SMs (scale), and both with the engine's grids on
|
||||
// 32 to all of this card's SMs, the others held by a sleeping kernel (fewer_sms)
|
||||
#include <cuda_fp16.h>
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int S = 128, HK = 16, HV = 48, C = 10240; // as kernels.cu: head size, key heads, value heads, q|k|v width
|
||||
constexpr int RG = 4, RPG = S / RG;
|
||||
constexpr int CB = 32, NCB = S / CB;
|
||||
|
||||
void ck(cudaError_t e, const char* what) {
|
||||
if (e != cudaSuccess) {
|
||||
std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));
|
||||
std::exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
__device__ __forceinline__ float warp_sum(float v) {
|
||||
#pragma unroll
|
||||
for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
|
||||
return v;
|
||||
}
|
||||
__device__ __forceinline__ float sigm(float x) { return 1.0f / (1.0f + __expf(-x)); }
|
||||
__device__ __forceinline__ uint16_t hf(float f) { return __half_as_ushort(__float2half_rn(f)); }
|
||||
|
||||
// ------------------------------------------------------------------ the engine's kernels (src/prefill/kernels.cu)
|
||||
// gdn_rec_cols_kernel with the next token's inputs (q/k rows, v, gate, beta) loaded into registers while this token
|
||||
// computes (software pipelining). The same arithmetic in the same order: the same bits, and the same CB-column split.
|
||||
// STRATA_GDN_PIPELINE=0: gdn_rec_cols_kernel.
|
||||
__global__ void __launch_bounds__(CB * RG) gdn_rec_cols_pipe_kernel(float* __restrict__ state, const float* __restrict__ h,
|
||||
const float* __restrict__ gate,
|
||||
const float* __restrict__ beta,
|
||||
float* __restrict__ oc_out, int64_t T) {
|
||||
constexpr int NT = CB * RG, LPT = S / NT; // threads, q/k rows loaded per thread
|
||||
__shared__ float sk[S], sq[S], red[RG][CB];
|
||||
const int head = blockIdx.x / NCB, cb = blockIdx.x % NCB;
|
||||
const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c;
|
||||
const int qh = head % HK;
|
||||
float s[RPG];
|
||||
float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col;
|
||||
const size_t rs = (size_t) HV * S;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPG; ++r) s[r] = base[r * rs];
|
||||
float nq[LPT], nk[LPT], nv = 0.0f, ng = 0.0f, nb = 0.0f;
|
||||
auto fetch = [&](int64_t t) {
|
||||
const float* ht = h + t * C;
|
||||
#pragma unroll
|
||||
for (int u = 0; u < LPT; ++u) { nq[u] = ht[qh * S + tid + u * NT]; nk[u] = ht[HK * S + qh * S + tid + u * NT]; }
|
||||
nv = ht[2 * HK * S + head * S + col];
|
||||
ng = gate[t * HV + head];
|
||||
nb = beta[t * HV + head];
|
||||
};
|
||||
if (T > 0) fetch(0);
|
||||
for (int64_t t = 0; t < T; ++t) {
|
||||
float cq[LPT], ck[LPT];
|
||||
#pragma unroll
|
||||
for (int u = 0; u < LPT; ++u) { cq[u] = nq[u]; ck[u] = nk[u]; }
|
||||
const float cv = nv, cg = ng, cbt = nb;
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int u = 0; u < LPT; ++u) { sq[tid + u * NT] = cq[u]; sk[tid + u * NT] = ck[u]; }
|
||||
__syncthreads();
|
||||
if (t + 1 < T) fetch(t + 1);
|
||||
const float g = __expf(cg);
|
||||
float kv = 0.0f;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv);
|
||||
red[rg][c] = kv;
|
||||
__syncthreads();
|
||||
const float kv_col = red[0][c] + red[1][c] + red[2][c] + red[3][c];
|
||||
const float delta = (cv - g * kv_col) * cbt;
|
||||
float o = 0.0f;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPG; ++r) {
|
||||
s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta);
|
||||
o = fmaf(s[r], sq[rg * RPG + r], o);
|
||||
}
|
||||
__syncthreads();
|
||||
red[rg][c] = o;
|
||||
__syncthreads();
|
||||
if (rg == 0) oc_out[t * HV * S + head * S + col] = (red[0][c] + red[1][c] + red[2][c] + red[3][c]) * rsqrtf((float) S);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPG; ++r) base[r * rs] = s[r];
|
||||
}
|
||||
// The recurrence with one thread for the three value heads that share a key head (head % HK): column c of heads
|
||||
// qh, qh + 16 and qh + 32, row group rg. gdn_rec_cols_pipe_kernel spends its time in shared memory, not in
|
||||
// arithmetic: every thread of a warp needs the same 32 q and k values per token (the k twice), and a warp receives one
|
||||
// such broadcast value per clock however wide the load. Here every q/k value a thread loads feeds three heads, and a
|
||||
// token's k row goes into registers once for both of its uses. The inputs come in blocks of GDN_TB tokens, copied to
|
||||
// shared memory by cp.async while the block before computes (one token ahead is shorter than a load from L2 takes),
|
||||
// and the two cross-row-group sums have their own arrays, so a token needs 2 __syncthreads instead of 5: the second
|
||||
// one of a token orders every read of rkv before the next token's writes, the next token's first one every read of ro
|
||||
// before the writes after it. 64 blocks instead of 192. Per value head and column the same arithmetic in the same
|
||||
// order: the same bits (src/prefill/gdn_rec_parity.cu checks them and times the variants: 1.41x on a 4080 Super).
|
||||
// sm_80+ (gdn_keyhead_ok); STRATA_GDN_KEYHEAD=0: gdn_rec_cols_pipe_kernel.
|
||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
|
||||
#define STRATA_GDN_CP_ASYNC 0 // Turing builds: plain copies (never launched there, see gdn_keyhead_ok)
|
||||
#else
|
||||
#define STRATA_GDN_CP_ASYNC 1
|
||||
#endif
|
||||
__device__ __forceinline__ void gdn_cp4(float* smem, const float* gmem) {
|
||||
#if STRATA_GDN_CP_ASYNC
|
||||
asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem));
|
||||
#else
|
||||
*smem = *gmem;
|
||||
#endif
|
||||
}
|
||||
__device__ __forceinline__ void gdn_cp16(float* smem, const float* gmem) {
|
||||
#if STRATA_GDN_CP_ASYNC
|
||||
asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem));
|
||||
#else
|
||||
*reinterpret_cast<float4*>(smem) = *reinterpret_cast<const float4*>(gmem);
|
||||
#endif
|
||||
}
|
||||
__device__ __forceinline__ void gdn_cp_commit() {
|
||||
#if STRATA_GDN_CP_ASYNC
|
||||
asm volatile("cp.async.commit_group;\n" ::);
|
||||
#endif
|
||||
}
|
||||
__device__ __forceinline__ void gdn_cp_wait_prev() { // every group but the newest has landed
|
||||
#if STRATA_GDN_CP_ASYNC
|
||||
asm volatile("cp.async.wait_group 1;\n" ::);
|
||||
#endif
|
||||
}
|
||||
constexpr int GDN_TB = 8, VPK = HV / HK; // tokens per staged block, value heads per key head
|
||||
__global__ void __launch_bounds__(CB * RG) gdn_rec_kh_kernel(float* __restrict__ state, const float* __restrict__ h,
|
||||
const float* __restrict__ gate,
|
||||
const float* __restrict__ beta,
|
||||
float* __restrict__ oc_out, int64_t T) {
|
||||
constexpr int TB = GDN_TB, NT = CB * RG, QKP = S / 4, VP = CB / 4; // threads, 16-byte pieces of a q/k row, of v
|
||||
__shared__ __align__(16) float sq[2][TB][S];
|
||||
__shared__ __align__(16) float sk[2][TB][S];
|
||||
__shared__ __align__(16) float sv[2][TB][VPK][CB];
|
||||
__shared__ float sg[2][TB][VPK], sb[2][TB][VPK], rkv[VPK][RG][CB], ro[VPK][RG][CB];
|
||||
const int qh = blockIdx.x / NCB, cb = blockIdx.x % NCB;
|
||||
const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c;
|
||||
float s[VPK][RPG];
|
||||
const size_t rs = (size_t) HV * S;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPK; ++j) {
|
||||
const float* base = state + ((size_t) (rg * RPG) * HV + qh + j * HK) * S + col;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPG; ++r) s[j][r] = base[r * rs];
|
||||
}
|
||||
const int64_t nblk = (T + TB - 1) / TB;
|
||||
auto stage = [&](int64_t k) { // tokens [k * TB, k * TB + TB) into buffer k & 1
|
||||
const int bb = (int) (k & 1);
|
||||
const int64_t t0 = k * TB;
|
||||
for (int p = tid; p < TB * 2 * QKP; p += NT) {
|
||||
const int i = p / (2 * QKP), w = p % (2 * QKP), isk = w / QKP, jj = (w % QKP) * 4;
|
||||
if (t0 + i < T)
|
||||
gdn_cp16(isk ? &sk[bb][i][jj] : &sq[bb][i][jj], h + (t0 + i) * C + (isk ? HK * S : 0) + qh * S + jj);
|
||||
}
|
||||
for (int p = tid; p < TB * VPK * VP; p += NT) {
|
||||
const int i = p / (VPK * VP), w = p % (VPK * VP), j = w / VP, jj = (w % VP) * 4;
|
||||
if (t0 + i < T)
|
||||
gdn_cp16(&sv[bb][i][j][jj], h + (t0 + i) * C + 2 * HK * S + (qh + j * HK) * S + cb * CB + jj);
|
||||
}
|
||||
for (int p = tid; p < 2 * TB * VPK; p += NT) {
|
||||
const int isb = p / (TB * VPK), w = p % (TB * VPK), i = w / VPK, j = w % VPK;
|
||||
if (t0 + i < T)
|
||||
gdn_cp4(isb ? &sb[bb][i][j] : &sg[bb][i][j], (isb ? beta : gate) + (t0 + i) * HV + qh + j * HK);
|
||||
}
|
||||
};
|
||||
if (nblk > 0) stage(0);
|
||||
gdn_cp_commit();
|
||||
for (int64_t k = 0; k < nblk; ++k) {
|
||||
// buffer (k + 1) & 1 was read by block k - 1, whose last token's second __syncthreads every thread has passed
|
||||
if (k + 1 < nblk) stage(k + 1);
|
||||
gdn_cp_commit();
|
||||
gdn_cp_wait_prev();
|
||||
__syncthreads();
|
||||
const int bb = (int) (k & 1);
|
||||
const int n = (int) ((T - k * TB) < TB ? (T - k * TB) : TB);
|
||||
for (int i = 0; i < n; ++i) {
|
||||
const int64_t t = k * TB + i;
|
||||
float kc[RPG];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPG; ++r) kc[r] = sk[bb][i][rg * RPG + r];
|
||||
float g[VPK], kv[VPK], delta[VPK], o[VPK];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPK; ++j) { g[j] = __expf(sg[bb][i][j]); kv[j] = 0.0f; o[j] = 0.0f; }
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPG; ++r)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPK; ++j) kv[j] = fmaf(s[j][r], kc[r], kv[j]);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPK; ++j) rkv[j][rg][c] = kv[j];
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPK; ++j) {
|
||||
const float kv_col = rkv[j][0][c] + rkv[j][1][c] + rkv[j][2][c] + rkv[j][3][c];
|
||||
delta[j] = (sv[bb][i][j][c] - g[j] * kv_col) * sb[bb][i][j];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPG; ++r) {
|
||||
const float qr = sq[bb][i][rg * RPG + r];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPK; ++j) {
|
||||
s[j][r] = fmaf(g[j], s[j][r], kc[r] * delta[j]);
|
||||
o[j] = fmaf(s[j][r], qr, o[j]);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPK; ++j) ro[j][rg][c] = o[j];
|
||||
__syncthreads();
|
||||
if (rg < VPK) // row group j writes head j's output
|
||||
oc_out[t * HV * S + (qh + rg * HK) * S + col] =
|
||||
(ro[rg][0][c] + ro[rg][1][c] + ro[rg][2][c] + ro[rg][3][c]) * rsqrtf((float) S);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPK; ++j) {
|
||||
float* base = state + ((size_t) (rg * RPG) * HV + qh + j * HK) * S + col;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPG; ++r) base[r * rs] = s[j][r];
|
||||
}
|
||||
}
|
||||
// the output norm over a head's 128 columns, into the FP16 copy the out projection reads (the FP32 output before the
|
||||
// norm stays in its scratch buffer)
|
||||
__global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma,
|
||||
float eps, const float* __restrict__ y,
|
||||
uint16_t* __restrict__ y16) {
|
||||
__shared__ float wsum[4];
|
||||
const int64_t t = blockIdx.x;
|
||||
const int head = blockIdx.y, col = threadIdx.x;
|
||||
const size_t at = (size_t) t * HV * S + (size_t) head * S + col;
|
||||
const float oc = y[at];
|
||||
float sp = warp_sum(oc * oc);
|
||||
if ((col & 31) == 0) wsum[col >> 5] = sp;
|
||||
__syncthreads();
|
||||
const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
|
||||
const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * sigm(z[t * HV * S + head * S + col]);
|
||||
y16[at] = hf(v);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ the output norm before (0.1.31)
|
||||
__global__ void __launch_bounds__(S) gdn_out_norm_old_kernel(const float* __restrict__ z, const float* __restrict__ gamma,
|
||||
float eps, float* __restrict__ y,
|
||||
uint16_t* __restrict__ y16) {
|
||||
__shared__ float wsum[4];
|
||||
const int64_t t = blockIdx.x;
|
||||
const int head = blockIdx.y, col = threadIdx.x;
|
||||
const size_t at = (size_t) t * HV * S + (size_t) head * S + col;
|
||||
const float oc = y[at];
|
||||
float sp = warp_sum(oc * oc);
|
||||
if ((col & 31) == 0) wsum[col >> 5] = sp;
|
||||
__syncthreads();
|
||||
const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
|
||||
const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * sigm(z[t * HV * S + head * S + col]);
|
||||
y[at] = v;
|
||||
y16[at] = hf(v);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ synthetic inputs
|
||||
__device__ __forceinline__ uint32_t mix(uint64_t x) {
|
||||
x ^= x >> 33; x *= 0xff51afd7ed558ccdULL; x ^= x >> 33; x *= 0xc4ceb9fe1a85ec53ULL; x ^= x >> 33;
|
||||
return (uint32_t) x;
|
||||
}
|
||||
__device__ __forceinline__ float uni(uint64_t key) { return ((mix(key) >> 8) + 0.5f) * (1.0f / 16777216.0f); }
|
||||
__device__ __forceinline__ float gauss(uint64_t key) {
|
||||
const float u1 = uni(key * 2 + 1), u2 = uni(key * 2 + 2);
|
||||
return sqrtf(-2.0f * logf(u1)) * cosf(6.2831853f * u2);
|
||||
}
|
||||
__global__ void fill_gauss(float* x, int64_t n, float scale, uint64_t seed, float offset = 0.0f) {
|
||||
for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x)
|
||||
x[i] = offset + scale * gauss(seed * 0x9E3779B97F4A7C15ULL + (uint64_t) i);
|
||||
}
|
||||
// the q and k rows L2-normalized per key head, as gdn_l2_kernel leaves them for the recurrence
|
||||
__global__ void l2_rows(float* h, float eps) {
|
||||
float* x = h + (int64_t) blockIdx.y * C + (int64_t) blockIdx.x * S;
|
||||
const float v = x[threadIdx.x];
|
||||
__shared__ float part[4];
|
||||
const float sq = warp_sum(v * v);
|
||||
if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = sq;
|
||||
__syncthreads();
|
||||
x[threadIdx.x] = v * rsqrtf(part[0] + part[1] + part[2] + part[3] + eps);
|
||||
}
|
||||
// gate = log of the decay (mostly near 1, some strong), beta in (0, 1)
|
||||
__global__ void fill_gates(float* gate, float* beta, int64_t n, uint64_t seed) {
|
||||
for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) {
|
||||
const float u = uni(seed * 0x9E3779B97F4A7C15ULL + 7 * (uint64_t) i);
|
||||
gate[i] = -0.02f - 0.8f * u * u * u;
|
||||
beta[i] = 1.0f / (1.0f + expf(-gauss(seed * 0xD1B54A32D192ED03ULL + (uint64_t) i)));
|
||||
}
|
||||
}
|
||||
__global__ void count_diff(const uint32_t* a, const uint32_t* b, int64_t n, unsigned long long* out) {
|
||||
unsigned long long d = 0;
|
||||
for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x)
|
||||
d += a[i] != b[i];
|
||||
if (d) atomicAdd(out, d);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ holding SMs (fewer_sms)
|
||||
__device__ __forceinline__ uint64_t gtime() {
|
||||
uint64_t t;
|
||||
asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t));
|
||||
return t;
|
||||
}
|
||||
__device__ __forceinline__ int sm_id() {
|
||||
unsigned id;
|
||||
asm volatile("mov.u32 %0, %%smid;" : "=r"(id));
|
||||
return (int) id;
|
||||
}
|
||||
__device__ __forceinline__ void nap(unsigned ns) {
|
||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700
|
||||
__nanosleep(ns);
|
||||
#else
|
||||
(void) ns;
|
||||
#endif
|
||||
}
|
||||
// limits that a run that works never reaches (a launch here takes milliseconds); they keep a run that does not work
|
||||
// from waiting forever, and the host drops its time
|
||||
constexpr uint64_t kHoldLimitNs = 1000000000ull, kWaitLimitNs = 500000000ull;
|
||||
// One block per SM: it asks for all the shared memory a block may have (launched with that much dynamic shared
|
||||
// memory), so no block of another kernel fits beside it. It notes its SM and sleeps until release says gen.
|
||||
__global__ void hold_sm(unsigned long long* sitting, const volatile unsigned* release, unsigned gen, int* where,
|
||||
unsigned* late) {
|
||||
where[blockIdx.x] = sm_id();
|
||||
__threadfence();
|
||||
atomicAdd(sitting, 1ull);
|
||||
const uint64_t t0 = gtime();
|
||||
while (*release != gen) {
|
||||
if (gtime() - t0 > kHoldLimitNs) { atomicAdd(late, 1u); return; }
|
||||
nap(20000);
|
||||
}
|
||||
}
|
||||
// on the timed launch's stream, before it: returns once all holding blocks so far sit on their SMs
|
||||
__global__ void wait_sitting(const volatile unsigned long long* sitting, unsigned long long all, unsigned* late) {
|
||||
const uint64_t t0 = gtime();
|
||||
while (*sitting < all) {
|
||||
if (gtime() - t0 > kWaitLimitNs) { atomicAdd(late, 1u); return; }
|
||||
nap(1000);
|
||||
}
|
||||
}
|
||||
__global__ void release_sms(volatile unsigned* release, unsigned gen) { *release = gen; }
|
||||
// Where the blocks of a grid land: launched like the recurrence it stands for (the same grid and block size, and as
|
||||
// much dynamic shared memory as lets as many blocks share an SM), every block notes its SM and stays until all of them
|
||||
// have landed, so they all sit at once as the recurrence's blocks do for the whole chunk.
|
||||
__global__ void land(int* where, unsigned* landed, unsigned* apart) {
|
||||
extern __shared__ unsigned char land_smem[]; // only its size matters
|
||||
if (threadIdx.x != 0 || threadIdx.y != 0) return;
|
||||
where[blockIdx.x] = sm_id();
|
||||
atomicAdd(landed, 1u);
|
||||
const uint64_t t0 = gtime();
|
||||
while (*(volatile unsigned*) landed < gridDim.x) {
|
||||
if (gtime() - t0 > kWaitLimitNs) { atomicAdd(apart, 1u); return; } // they did not all fit at once
|
||||
nap(1000);
|
||||
}
|
||||
(void) land_smem;
|
||||
}
|
||||
|
||||
template <typename T> T* dalloc(size_t n) {
|
||||
T* p = nullptr;
|
||||
ck(cudaMalloc((void**) &p, n * sizeof(T) + 16), "cudaMalloc");
|
||||
return p;
|
||||
}
|
||||
unsigned long long diff_words(const void* a, const void* b, size_t bytes) {
|
||||
static unsigned long long* d = dalloc<unsigned long long>(1);
|
||||
ck(cudaMemset(d, 0, sizeof(*d)), "memset");
|
||||
count_diff<<<1024, 256>>>((const uint32_t*) a, (const uint32_t*) b, (int64_t) (bytes / 4), d);
|
||||
unsigned long long h = 0;
|
||||
ck(cudaMemcpy(&h, d, sizeof(h), cudaMemcpyDeviceToHost), "diff");
|
||||
return h;
|
||||
}
|
||||
|
||||
struct Inputs {
|
||||
int64_t T = 0;
|
||||
float *h = nullptr, *gate = nullptr, *beta = nullptr, *z = nullptr, *gamma = nullptr, *state0 = nullptr;
|
||||
explicit Inputs(int64_t t, uint64_t seed) : T(t) {
|
||||
h = dalloc<float>((size_t) T * C);
|
||||
gate = dalloc<float>((size_t) T * HV);
|
||||
beta = dalloc<float>((size_t) T * HV);
|
||||
z = dalloc<float>((size_t) T * HV * S);
|
||||
gamma = dalloc<float>(S);
|
||||
state0 = dalloc<float>((size_t) S * HV * S);
|
||||
fill_gauss<<<4096, 256>>>(h, T * C, 1.0f, seed);
|
||||
l2_rows<<<dim3(2 * HK, (unsigned) T), S>>>(h, 1e-6f);
|
||||
fill_gates<<<1024, 256>>>(gate, beta, T * HV, seed + 1);
|
||||
fill_gauss<<<4096, 256>>>(z, T * HV * S, 1.0f, seed + 2);
|
||||
fill_gauss<<<1, 128>>>(gamma, S, 0.1f, seed + 3, 1.0f);
|
||||
fill_gauss<<<1024, 256>>>(state0, (int64_t) S * HV * S, 0.05f, seed + 4);
|
||||
ck(cudaDeviceSynchronize(), "inputs");
|
||||
}
|
||||
Inputs(const Inputs&) = delete;
|
||||
Inputs& operator=(const Inputs&) = delete;
|
||||
~Inputs() { cudaFree(h); cudaFree(gate); cudaFree(beta); cudaFree(z); cudaFree(gamma); cudaFree(state0); }
|
||||
};
|
||||
|
||||
enum Rec { kBefore, kKeyHead, kRecCount };
|
||||
void run_rec(Rec v, float* state, const Inputs& in, float* oc, cudaStream_t s = 0) {
|
||||
if (v == kBefore)
|
||||
gdn_rec_cols_pipe_kernel<<<HV * NCB, dim3(CB, RG), 0, s>>>(state, in.h, in.gate, in.beta, oc, in.T);
|
||||
else
|
||||
gdn_rec_kh_kernel<<<HK * NCB, dim3(CB, RG), 0, s>>>(state, in.h, in.gate, in.beta, oc, in.T);
|
||||
}
|
||||
|
||||
int check_bits(int64_t T, uint64_t seed) {
|
||||
Inputs in(T, seed);
|
||||
const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S;
|
||||
float* state[kRecCount];
|
||||
float* oc[kRecCount];
|
||||
for (int v = 0; v < kRecCount; ++v) {
|
||||
state[v] = dalloc<float>(st);
|
||||
oc[v] = dalloc<float>(oc_n);
|
||||
ck(cudaMemcpy(state[v], in.state0, st * 4, cudaMemcpyDeviceToDevice), "state copy");
|
||||
run_rec((Rec) v, state[v], in, oc[v]);
|
||||
}
|
||||
ck(cudaDeviceSynchronize(), "recurrence");
|
||||
int fails = 0;
|
||||
const unsigned long long d_oc = diff_words(oc[kBefore], oc[kKeyHead], oc_n * 4),
|
||||
d_st = diff_words(state[kBefore], state[kKeyHead], st * 4);
|
||||
if (d_oc || d_st) {
|
||||
std::printf("FAIL T=%lld recurrence: %llu of %zu outputs and %llu of %zu state values differ\n", (long long) T,
|
||||
d_oc, oc_n, d_st, st);
|
||||
++fails;
|
||||
}
|
||||
// the output norm: before (in place, with the FP32 store) against now (the FP16 store only), on the same output
|
||||
uint16_t* y16a = dalloc<uint16_t>(oc_n);
|
||||
uint16_t* y16b = dalloc<uint16_t>(oc_n);
|
||||
float* yb = dalloc<float>(oc_n);
|
||||
ck(cudaMemcpy(yb, oc[kBefore], oc_n * 4, cudaMemcpyDeviceToDevice), "y copy");
|
||||
gdn_out_norm_kernel<<<dim3((unsigned) T, HV), S>>>(in.z, in.gamma, 1e-6f, yb, y16b);
|
||||
gdn_out_norm_old_kernel<<<dim3((unsigned) T, HV), S>>>(in.z, in.gamma, 1e-6f, oc[kBefore], y16a);
|
||||
ck(cudaDeviceSynchronize(), "norm");
|
||||
const unsigned long long d16 = diff_words(y16a, y16b, oc_n * 2);
|
||||
if (d16) {
|
||||
std::printf("FAIL T=%lld output norm: %llu of %zu FP16 pairs differ\n", (long long) T, d16, oc_n / 2);
|
||||
++fails;
|
||||
}
|
||||
std::printf("T=%-6lld %s\n", (long long) T, fails ? "DIFFERENT" : "the same bits (output, state, FP16 output)");
|
||||
for (int v = 0; v < kRecCount; ++v) { cudaFree(state[v]); cudaFree(oc[v]); }
|
||||
cudaFree(y16a); cudaFree(y16b); cudaFree(yb);
|
||||
return fails;
|
||||
}
|
||||
|
||||
float median(std::vector<float> v) {
|
||||
std::sort(v.begin(), v.end());
|
||||
return v.empty() ? 0.0f : v[v.size() / 2];
|
||||
}
|
||||
|
||||
void bench(int64_t T) {
|
||||
Inputs in(T, 0xB3);
|
||||
const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S;
|
||||
float* state = dalloc<float>(st);
|
||||
float* oc = dalloc<float>(oc_n);
|
||||
uint16_t* y16 = dalloc<uint16_t>(oc_n);
|
||||
cudaEvent_t e0, e1;
|
||||
ck(cudaEventCreate(&e0), "event");
|
||||
ck(cudaEventCreate(&e1), "event");
|
||||
auto timed = [&](auto&& launch) {
|
||||
ck(cudaMemcpy(state, in.state0, st * 4, cudaMemcpyDeviceToDevice), "state");
|
||||
cudaEventRecord(e0);
|
||||
launch();
|
||||
cudaEventRecord(e1);
|
||||
ck(cudaEventSynchronize(e1), "timed");
|
||||
float ms = 0.0f;
|
||||
cudaEventElapsedTime(&ms, e0, e1);
|
||||
return ms;
|
||||
};
|
||||
const int warm = 3, rounds = T >= 16384 ? 10 : 20;
|
||||
std::vector<float> t_rec[kRecCount], t_norm[2];
|
||||
for (int i = 0; i < warm + rounds; ++i) {
|
||||
for (int j = 0; j < kRecCount; ++j) {
|
||||
const Rec v = (Rec) ((i + j) % kRecCount); // a different variant first in each round
|
||||
const float ms = timed([&] { run_rec(v, state, in, oc); });
|
||||
if (i >= warm) t_rec[v].push_back(ms);
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < warm + rounds; ++i) {
|
||||
for (int j = 0; j < 2; ++j) {
|
||||
const int v = (i + j) % 2;
|
||||
const float ms = timed([&] {
|
||||
if (v == 0) gdn_out_norm_old_kernel<<<dim3((unsigned) T, HV), S>>>(in.z, in.gamma, 1e-6f, oc, y16);
|
||||
else gdn_out_norm_kernel<<<dim3((unsigned) T, HV), S>>>(in.z, in.gamma, 1e-6f, oc, y16);
|
||||
});
|
||||
if (i >= warm) t_norm[v].push_back(ms);
|
||||
}
|
||||
}
|
||||
const float r0 = median(t_rec[kBefore]), r1 = median(t_rec[kKeyHead]), n0 = median(t_norm[0]), n1 = median(t_norm[1]);
|
||||
std::printf(" T = %lld tokens, one layer (48 value heads), medians of %d alternating runs:\n", (long long) T, rounds);
|
||||
std::printf(" recurrence, before (gdn_rec_cols_pipe_kernel) %8.2f ms (%.3f us per token)\n", r0,
|
||||
1000.0f * r0 / (float) T);
|
||||
std::printf(" recurrence, gdn_rec_kh_kernel %8.2f ms (%.3f us per token) %.2fx\n", r1,
|
||||
1000.0f * r1 / (float) T, r0 / r1);
|
||||
std::printf(" output norm, before (FP32 and FP16 store) %8.2f ms\n", n0);
|
||||
std::printf(" output norm, FP16 store only %8.2f ms %.2fx\n", n1, n0 / n1);
|
||||
std::printf(" 36 DeltaNet layers per %lld-token block: recurrence + norm %.0f ms -> %.0f ms (-%.0f ms)\n",
|
||||
(long long) T, 36.0f * (r0 + n0), 36.0f * (r1 + n1), 36.0f * (r0 + n0 - r1 - n1));
|
||||
cudaEventDestroy(e0);
|
||||
cudaEventDestroy(e1);
|
||||
cudaFree(state); cudaFree(oc); cudaFree(y16);
|
||||
}
|
||||
|
||||
// The two kernels at a given number of blocks per SM, as on cards with more or fewer SMs than this one: the kernel
|
||||
// before puts ceil(192 / SMs) of its blocks on an SM, gdn_rec_kh_kernel ceil(64 / SMs), and the busiest SM sets the
|
||||
// pace (every block walks the whole chunk). b blocks per SM here: b rounds of one block per SM, each round one launch
|
||||
// of SMs blocks (the first heads; split in launches of at most the engine's grid), every launch on its own stream with
|
||||
// its own state and output, all started together, so the block scheduler puts one block of each round on every SM.
|
||||
// The kernels are the ones above, unchanged.
|
||||
void scale(int64_t T) {
|
||||
int dev = 0, sms = 0, per_sm[kRecCount] = {};
|
||||
ck(cudaGetDevice(&dev), "device");
|
||||
ck(cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev), "SMs");
|
||||
ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm[kBefore], gdn_rec_cols_pipe_kernel, CB * RG, 0), "occupancy");
|
||||
ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm[kKeyHead], gdn_rec_kh_kernel, CB * RG, 0), "occupancy");
|
||||
constexpr int kMaxB = 6, kMaxLaunches = 6;
|
||||
const int full[kRecCount] = {HV * NCB, HK * NCB}; // the grids as the engine launches them
|
||||
auto parts = [&](int v) { return (sms + full[v] - 1) / full[v]; }; // launches per round
|
||||
Inputs in(T, 0xC7);
|
||||
const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S;
|
||||
float* state[kMaxLaunches];
|
||||
float* oc[kMaxLaunches];
|
||||
cudaStream_t stream[kMaxLaunches];
|
||||
cudaEvent_t e0, e1, done[kMaxLaunches];
|
||||
ck(cudaEventCreate(&e0), "event");
|
||||
ck(cudaEventCreate(&e1), "event");
|
||||
for (int c = 0; c < kMaxLaunches; ++c) {
|
||||
state[c] = dalloc<float>(st);
|
||||
oc[c] = dalloc<float>(oc_n);
|
||||
ck(cudaStreamCreateWithFlags(&stream[c], cudaStreamNonBlocking), "stream");
|
||||
ck(cudaEventCreate(&done[c]), "event");
|
||||
}
|
||||
struct Case { int v, b; };
|
||||
std::vector<Case> cases;
|
||||
for (int v = 0; v < kRecCount; ++v)
|
||||
for (int b = 1; b <= std::min(kMaxB, per_sm[v]); ++b)
|
||||
if (b * parts(v) <= kMaxLaunches) cases.push_back({v, b});
|
||||
auto run = [&](const Case& cs) {
|
||||
for (int c = 0; c < kMaxLaunches; ++c) ck(cudaMemcpy(state[c], in.state0, st * 4, cudaMemcpyDeviceToDevice), "state");
|
||||
ck(cudaDeviceSynchronize(), "sync");
|
||||
const int np = parts(cs.v), n = cs.b * np;
|
||||
cudaEventRecord(e0, stream[0]);
|
||||
for (int c = 0; c < n; ++c) {
|
||||
const int k = c % np, grid = sms / np + (k < sms % np ? 1 : 0); // round c / np, part k
|
||||
if (c > 0) cudaStreamWaitEvent(stream[c], e0, 0);
|
||||
if (cs.v == kBefore)
|
||||
gdn_rec_cols_pipe_kernel<<<grid, dim3(CB, RG), 0, stream[c]>>>(state[c], in.h, in.gate, in.beta, oc[c], T);
|
||||
else
|
||||
gdn_rec_kh_kernel<<<grid, dim3(CB, RG), 0, stream[c]>>>(state[c], in.h, in.gate, in.beta, oc[c], T);
|
||||
cudaEventRecord(done[c], stream[c]);
|
||||
}
|
||||
for (int c = 1; c < n; ++c) cudaStreamWaitEvent(stream[0], done[c], 0);
|
||||
cudaEventRecord(e1, stream[0]);
|
||||
ck(cudaEventSynchronize(e1), "scale");
|
||||
float ms = 0.0f;
|
||||
cudaEventElapsedTime(&ms, e0, e1);
|
||||
return ms;
|
||||
};
|
||||
const int warm = 2, rounds = 9;
|
||||
std::vector<std::vector<float>> t(cases.size());
|
||||
for (int i = 0; i < warm + rounds; ++i)
|
||||
for (size_t j = 0; j < cases.size(); ++j) {
|
||||
const size_t k = (i + j) % cases.size(); // a different case first in each round
|
||||
const float ms = run(cases[k]);
|
||||
if (i >= warm) t[k].push_back(ms);
|
||||
}
|
||||
auto us = [&](int v, int b) { // per token, or < 0 if not measured
|
||||
for (size_t k = 0; k < cases.size(); ++k)
|
||||
if (cases[k].v == v && cases[k].b == b) return 1000.0f * median(t[k]) / (float) T;
|
||||
return -1.0f;
|
||||
};
|
||||
std::printf(" per token at a given number of blocks per SM (%lld tokens, medians of %d alternating runs; this card has "
|
||||
"%d SMs):\n", (long long) T, rounds, sms);
|
||||
std::printf(" blocks per SM before gdn_rec_kh_kernel\n");
|
||||
for (int b = 1; b <= kMaxB; ++b) {
|
||||
const float u0 = us(kBefore, b), u1 = us(kKeyHead, b);
|
||||
if (u0 < 0 && u1 < 0) continue;
|
||||
char a0[32] = "-", a1[32] = "-";
|
||||
if (u0 >= 0) std::snprintf(a0, sizeof a0, "%.3f us", u0);
|
||||
if (u1 >= 0) std::snprintf(a1, sizeof a1, "%.3f us", u1);
|
||||
std::printf(" %8d %-11s %s\n", b, a0, a1);
|
||||
}
|
||||
std::printf(" so on a card with N SMs (the kernel before puts ceil(192 / N) blocks on an SM, gdn_rec_kh_kernel "
|
||||
"ceil(64 / N), at most %d):\n", per_sm[kKeyHead]);
|
||||
const int bands[][2] = {{192, 0}, {96, 191}, {64, 95}, {48, 63}, {39, 47}, {32, 38}};
|
||||
for (const auto& bd : bands) {
|
||||
const int nsm = bd[0], b0 = (192 + nsm - 1) / nsm, b1 = (64 + nsm - 1) / nsm;
|
||||
const float u0 = us(kBefore, b0), u1 = us(kKeyHead, b1);
|
||||
char range[32];
|
||||
if (bd[1]) std::snprintf(range, sizeof range, "%d-%d SMs", bd[0], bd[1]);
|
||||
else std::snprintf(range, sizeof range, "%d+ SMs", bd[0]);
|
||||
if (u0 < 0 || u1 < 0)
|
||||
std::printf(" %-12s before %d / new %d per SM: not measured on this card\n", range, b0, b1);
|
||||
else
|
||||
std::printf(" %-12s before %d / new %d per SM: %.3f -> %.3f us per token, %.2fx\n", range, b0, b1, u0, u1,
|
||||
u0 / u1);
|
||||
}
|
||||
for (int c = 0; c < kMaxLaunches; ++c) {
|
||||
cudaFree(state[c]);
|
||||
cudaFree(oc[c]);
|
||||
cudaStreamDestroy(stream[c]);
|
||||
cudaEventDestroy(done[c]);
|
||||
}
|
||||
cudaEventDestroy(e0);
|
||||
cudaEventDestroy(e1);
|
||||
}
|
||||
|
||||
// The engine's grids on N of this card's SMs. scale() puts as many blocks on every SM as the busiest SM of a card with
|
||||
// N SMs gets; on that card only some SMs get that many (192 blocks on 80 SMs: 3 on 32 SMs, 2 on the other 48), the
|
||||
// rest of the card has less to do, and the estimate came out 4-9 % above the real launch on two cards. Here the
|
||||
// recurrences run as the engine launches them, while hold_sm keeps all but N SMs: its blocks go out first, a small
|
||||
// kernel on the timed launch's stream waits until they all sit, and one after the timed launch lets them go. land()
|
||||
// shows for every N where the two grids land: none on a held SM, and how many blocks share the busiest SM. The
|
||||
// recurrences are the ones above, unchanged; L2, memory and clock stay this card's.
|
||||
void fewer_sms(int64_t T) {
|
||||
int dev = 0, sms = 0, optin = 0, smem_sm = 0, reserved = 0, hold_per_sm = 0, per_sm[kRecCount] = {};
|
||||
ck(cudaGetDevice(&dev), "device");
|
||||
ck(cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev), "SMs");
|
||||
ck(cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev), "shared memory");
|
||||
ck(cudaDeviceGetAttribute(&smem_sm, cudaDevAttrMaxSharedMemoryPerMultiprocessor, dev), "shared memory");
|
||||
ck(cudaDeviceGetAttribute(&reserved, cudaDevAttrReservedSharedMemoryPerBlock, dev), "shared memory");
|
||||
for (const void* f : {(const void*) hold_sm, (const void*) land}) {
|
||||
ck(cudaFuncSetAttribute(f, cudaFuncAttributeMaxDynamicSharedMemorySize, optin), "shared memory");
|
||||
ck(cudaFuncSetAttribute(f, cudaFuncAttributePreferredSharedMemoryCarveout, (int) cudaSharedmemCarveoutMaxShared),
|
||||
"carveout");
|
||||
}
|
||||
// Loaded now rather than at a first launch: with lazy loading (CUDA 12's default) a kernel's first launch may wait
|
||||
// until the device is idle, and so for hold_sm, which waits for release_sms.
|
||||
cudaFuncAttributes fa[kRecCount], fx;
|
||||
ck(cudaFuncGetAttributes(&fa[kBefore], gdn_rec_cols_pipe_kernel), "attributes");
|
||||
ck(cudaFuncGetAttributes(&fa[kKeyHead], gdn_rec_kh_kernel), "attributes");
|
||||
for (const void* f : {(const void*) hold_sm, (const void*) wait_sitting, (const void*) release_sms, (const void*) land})
|
||||
ck(cudaFuncGetAttributes(&fx, f), "attributes");
|
||||
ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&hold_per_sm, hold_sm, 1, optin), "occupancy");
|
||||
ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm[kBefore], gdn_rec_cols_pipe_kernel, CB * RG, 0), "occupancy");
|
||||
ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm[kKeyHead], gdn_rec_kh_kernel, CB * RG, 0), "occupancy");
|
||||
const int grid[kRecCount] = {HV * NCB, HK * NCB}; // as the engine launches them
|
||||
std::printf(" the engine's grids on N of this card's %d SMs (%lld tokens; the other SMs held by a sleeping kernel, see "
|
||||
"fewer_sms):\n", sms, (long long) T);
|
||||
const int left = smem_sm - optin - reserved; // shared memory a holding block leaves on its SM
|
||||
if (hold_per_sm != 1 || (int) fa[kBefore].sharedSizeBytes + reserved <= left ||
|
||||
(int) fa[kKeyHead].sharedSizeBytes + reserved <= left) {
|
||||
std::printf(" not on this card: a block of a recurrence would fit beside a holding block (%d bytes left)\n",
|
||||
left);
|
||||
return;
|
||||
}
|
||||
// land(): as much dynamic shared memory as still lets as many of its blocks share an SM as of the recurrence
|
||||
int land_smem[kRecCount];
|
||||
for (int v = 0; v < kRecCount; ++v) {
|
||||
int lo = 0, hi = optin;
|
||||
while (lo < hi) {
|
||||
const int mid = (lo + hi + 1) / 2;
|
||||
int nb = 0;
|
||||
ck(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&nb, land, CB * RG, mid), "occupancy");
|
||||
if (nb >= per_sm[v]) lo = mid;
|
||||
else hi = mid - 1;
|
||||
}
|
||||
land_smem[v] = lo;
|
||||
}
|
||||
// N: all SMs, and below that the SM counts of cards and the band edges, as long as both grids fit at once
|
||||
std::vector<int> ns = {sms};
|
||||
for (const int n : {170, 144, 132, 128, 112, 108, 96, 95, 84, 82, 80, 76, 72, 70, 66, 64, 63, 60, 56, 52, 48, 47, 46, 44,
|
||||
40, 39, 38, 36, 34, 32})
|
||||
if (n < sms && (int64_t) n * per_sm[kBefore] >= grid[kBefore] && (int64_t) n * per_sm[kKeyHead] >= grid[kKeyHead])
|
||||
ns.push_back(n);
|
||||
|
||||
Inputs in(T, 0xD5);
|
||||
const size_t st = (size_t) S * HV * S, oc_n = (size_t) T * HV * S;
|
||||
float* state = dalloc<float>(st);
|
||||
float* oc = dalloc<float>(oc_n);
|
||||
unsigned long long* sitting = dalloc<unsigned long long>(1);
|
||||
unsigned* flags = dalloc<unsigned>(4);
|
||||
unsigned *release = flags, *late = flags + 1, *landed = flags + 2, *apart = flags + 3;
|
||||
int* where = dalloc<int>((size_t) sms + grid[kBefore]); // the holding blocks' SMs, then land()'s
|
||||
ck(cudaMemset(sitting, 0, sizeof(*sitting)), "memset");
|
||||
ck(cudaMemset(flags, 0, 4 * sizeof(unsigned)), "memset");
|
||||
cudaStream_t s_hold, s_run;
|
||||
ck(cudaStreamCreateWithFlags(&s_hold, cudaStreamNonBlocking), "stream");
|
||||
ck(cudaStreamCreateWithFlags(&s_run, cudaStreamNonBlocking), "stream");
|
||||
cudaEvent_t e0, e1;
|
||||
ck(cudaEventCreate(&e0), "event");
|
||||
ck(cudaEventCreate(&e1), "event");
|
||||
unsigned long long all = 0; // holding blocks launched so far: sitting counts every one that sat down
|
||||
unsigned gen = 0;
|
||||
auto hold = [&](int n) { // all but n SMs, before the next launch on s_run
|
||||
if (n >= sms) return;
|
||||
++gen;
|
||||
all += (unsigned long long) (sms - n);
|
||||
hold_sm<<<sms - n, 1, optin, s_hold>>>(sitting, release, gen, where, late);
|
||||
ck(cudaGetLastError(), "hold_sm");
|
||||
const cudaError_t q = cudaStreamQuery(s_hold); // hands the launch to the GPU now (Windows collects launches)
|
||||
if (q != cudaErrorNotReady) ck(q, "hold_sm");
|
||||
(void) cudaGetLastError(); // not ready is no error
|
||||
wait_sitting<<<1, 1, 0, s_run>>>(sitting, all, late);
|
||||
};
|
||||
auto let_go = [&](int n) {
|
||||
if (n < sms) release_sms<<<1, 1, 0, s_run>>>(release, gen);
|
||||
};
|
||||
auto settle = [&](const char* what) {
|
||||
ck(cudaStreamSynchronize(s_run), what);
|
||||
ck(cudaStreamSynchronize(s_hold), what);
|
||||
};
|
||||
auto count = [&](const unsigned* c) { // after settle()
|
||||
unsigned h = 0;
|
||||
ck(cudaMemcpy(&h, c, sizeof(h), cudaMemcpyDeviceToHost), "count");
|
||||
return h;
|
||||
};
|
||||
auto done = [&] {
|
||||
cudaEventDestroy(e0);
|
||||
cudaEventDestroy(e1);
|
||||
cudaStreamDestroy(s_hold);
|
||||
cudaStreamDestroy(s_run);
|
||||
cudaFree(state); cudaFree(oc); cudaFree(sitting); cudaFree(flags); cudaFree(where);
|
||||
};
|
||||
|
||||
// where the grids land, once per N
|
||||
struct Landing { bool held = true; int busiest[kRecCount] = {}, on[kRecCount] = {}; };
|
||||
std::vector<Landing> lands(ns.size());
|
||||
for (size_t i = 0; i < ns.size(); ++i) {
|
||||
const int n = ns[i];
|
||||
for (int v = 0; v < kRecCount; ++v) {
|
||||
bool sat = false;
|
||||
unsigned apart0 = 0;
|
||||
for (int attempt = 0; attempt < 2 && !sat; ++attempt) {
|
||||
const unsigned late0 = count(late);
|
||||
apart0 = count(apart);
|
||||
ck(cudaMemsetAsync(landed, 0, sizeof(unsigned), s_run), "memset");
|
||||
hold(n);
|
||||
land<<<grid[v], dim3(CB, RG), land_smem[v], s_run>>>(where + sms, landed, apart);
|
||||
ck(cudaGetLastError(), "land");
|
||||
let_go(n);
|
||||
settle("land");
|
||||
sat = count(late) == late0;
|
||||
}
|
||||
if (!sat) { // twice: the holding kernel and the launches beside it do not run at the same time here
|
||||
std::printf(" not on this card: the other SMs could not be held (the kernel holding them and the "
|
||||
"launches beside it did not run at the same time)\n");
|
||||
done();
|
||||
return;
|
||||
}
|
||||
std::vector<int> w((size_t) sms + grid[v]);
|
||||
ck(cudaMemcpy(w.data(), where, w.size() * sizeof(int), cudaMemcpyDeviceToHost), "where");
|
||||
std::map<int, int> held, blocks;
|
||||
for (int b = 0; b < (n < sms ? sms - n : 0); ++b) ++held[w[b]];
|
||||
for (int b = 0; b < grid[v]; ++b) ++blocks[w[sms + b]];
|
||||
bool ok = count(apart) == apart0 && (int) held.size() == (n < sms ? sms - n : 0) && (int) blocks.size() <= n;
|
||||
int most = 0, on = 0;
|
||||
for (const auto& sb : blocks) {
|
||||
if (held.count(sb.first)) ok = false;
|
||||
if (sb.second > most) { most = sb.second; on = 0; }
|
||||
if (sb.second == most) ++on;
|
||||
}
|
||||
lands[i].held = lands[i].held && ok;
|
||||
lands[i].busiest[v] = most;
|
||||
lands[i].on[v] = on;
|
||||
}
|
||||
}
|
||||
|
||||
// the timings: every N and recurrence once per round, a different one first in each round
|
||||
struct Case { size_t i; Rec v; };
|
||||
std::vector<Case> cases;
|
||||
for (size_t i = 0; i < ns.size(); ++i)
|
||||
if (lands[i].held)
|
||||
for (int v = 0; v < kRecCount; ++v) cases.push_back({i, (Rec) v});
|
||||
auto run = [&](const Case& cs) { // ms, or < 0 if the SMs were not held for the whole launch
|
||||
const int n = ns[cs.i];
|
||||
const unsigned late0 = count(late);
|
||||
ck(cudaMemcpyAsync(state, in.state0, st * 4, cudaMemcpyDeviceToDevice, s_run), "state");
|
||||
hold(n);
|
||||
ck(cudaEventRecord(e0, s_run), "event");
|
||||
run_rec(cs.v, state, in, oc, s_run);
|
||||
ck(cudaEventRecord(e1, s_run), "event");
|
||||
let_go(n);
|
||||
settle("fewer SMs");
|
||||
if (count(late) != late0) return -1.0f;
|
||||
float ms = 0.0f;
|
||||
ck(cudaEventElapsedTime(&ms, e0, e1), "event");
|
||||
return ms;
|
||||
};
|
||||
const int warm = 2, rounds = 15, max_dropped = 5;
|
||||
std::vector<std::vector<float>> t(cases.size());
|
||||
int dropped = 0;
|
||||
for (int r = 0; r < warm + rounds && dropped <= max_dropped; ++r)
|
||||
for (size_t j = 0; j < cases.size() && dropped <= max_dropped; ++j) {
|
||||
const size_t k = (r + j) % cases.size();
|
||||
const float ms = run(cases[k]);
|
||||
if (ms < 0.0f) ++dropped;
|
||||
else if (r >= warm) t[k].push_back(ms);
|
||||
}
|
||||
if (dropped > max_dropped) { // each such run waits for a limit of a second or so
|
||||
std::printf(" stopped: in %d runs the other SMs were not held for the whole launch\n", dropped);
|
||||
done();
|
||||
return;
|
||||
}
|
||||
auto us = [&](size_t i, int v) { // per token, or < 0 if not measured
|
||||
for (size_t k = 0; k < cases.size(); ++k)
|
||||
if (cases[k].i == i && cases[k].v == v && !t[k].empty()) return 1000.0f * median(t[k]) / (float) T;
|
||||
return -1.0f;
|
||||
};
|
||||
auto blocks_on = [](char* out, size_t size, int most, int on) {
|
||||
std::snprintf(out, size, "%d block%s on %d SM%s", most, most == 1 ? "" : "s", on, on == 1 ? "" : "s");
|
||||
};
|
||||
std::printf(" (medians of %d alternating runs; L2, memory and clock stay this card's)\n", rounds);
|
||||
std::printf(" N before: busiest SM new: busiest SM us per token, before -> new\n");
|
||||
for (size_t i = 0; i < ns.size(); ++i) {
|
||||
if (!lands[i].held) {
|
||||
std::printf(" %3d the other SMs were not held (a block landed on one, or a wait ran out)\n", ns[i]);
|
||||
continue;
|
||||
}
|
||||
char b0[40], b1[40];
|
||||
blocks_on(b0, sizeof b0, lands[i].busiest[kBefore], lands[i].on[kBefore]);
|
||||
blocks_on(b1, sizeof b1, lands[i].busiest[kKeyHead], lands[i].on[kKeyHead]);
|
||||
const float u0 = us(i, kBefore), u1 = us(i, kKeyHead);
|
||||
if (u0 < 0.0f || u1 < 0.0f) std::printf(" %3d %-20s %-20s not measured\n", ns[i], b0, b1);
|
||||
else std::printf(" %3d %-20s %-20s %.3f -> %.3f %.2fx\n", ns[i], b0, b1, u0, u1, u0 / u1);
|
||||
}
|
||||
if (dropped) std::printf(" (%d runs dropped: the other SMs were not held for the whole launch)\n", dropped);
|
||||
std::printf(" so on a card with N SMs, as measured here (the kernel before puts ceil(192 / N) blocks on the busiest SM, "
|
||||
"gdn_rec_kh_kernel ceil(64 / N)):\n");
|
||||
const int bands[][2] = {{96, 191}, {64, 95}, {48, 63}, {39, 47}, {32, 38}};
|
||||
for (const auto& bd : bands) {
|
||||
const int b0 = (192 + bd[0] - 1) / bd[0], b1 = (64 + bd[0] - 1) / bd[0];
|
||||
float lo = 0.0f, hi = 0.0f;
|
||||
int cnt = 0, nmin = 0, nmax = 0;
|
||||
for (size_t i = 0; i < ns.size(); ++i) {
|
||||
const float u0 = us(i, kBefore), u1 = us(i, kKeyHead);
|
||||
if (ns[i] < bd[0] || ns[i] > bd[1] || u0 < 0.0f || u1 < 0.0f) continue;
|
||||
const float x = u0 / u1;
|
||||
if (cnt == 0 || x < lo) lo = x;
|
||||
if (cnt == 0 || x > hi) hi = x;
|
||||
if (cnt == 0 || ns[i] < nmin) nmin = ns[i];
|
||||
if (cnt == 0 || ns[i] > nmax) nmax = ns[i];
|
||||
++cnt;
|
||||
}
|
||||
char range[32];
|
||||
std::snprintf(range, sizeof range, "%d-%d SMs", bd[0], bd[1]);
|
||||
if (cnt > 0)
|
||||
std::printf(" %-12s before %d / new %d per SM: %.2fx to %.2fx (%d to %d SMs)\n", range, b0, b1, lo, hi, nmin,
|
||||
nmax);
|
||||
else if (bd[0] > sms)
|
||||
std::printf(" %-12s before %d / new %d per SM: more SMs than this card has (see the estimate above)\n", range,
|
||||
b0, b1);
|
||||
else
|
||||
std::printf(" %-12s before %d / new %d per SM: not measured\n", range, b0, b1);
|
||||
}
|
||||
done();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
bool do_bench = false;
|
||||
for (int i = 1; i < argc; ++i)
|
||||
if (std::strcmp(argv[i], "--bench") == 0) do_bench = true;
|
||||
cudaDeviceProp p{};
|
||||
ck(cudaGetDeviceProperties(&p, 0), "device");
|
||||
std::printf("gdn_rec_parity on %s (sm_%d%d)\n", p.name, p.major, p.minor);
|
||||
int fails = 0;
|
||||
const int64_t Ts[] = {1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17, 31, 33, 257, 1000, 4099};
|
||||
uint64_t seed = 11;
|
||||
for (const int64_t T : Ts) fails += check_bits(T, seed++);
|
||||
if (do_bench) {
|
||||
std::printf("--bench: the prompt path's DeltaNet recurrence\n");
|
||||
bench(8192);
|
||||
bench(32768);
|
||||
scale(8192);
|
||||
fewer_sms(8192);
|
||||
}
|
||||
std::printf("gdn_rec_parity: %d failures\n", fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
+170
-2
@@ -433,8 +433,172 @@ __global__ void __launch_bounds__(CB * RG) gdn_rec_cols_pipe_kernel(float* __res
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPG; ++r) base[r * rs] = s[r];
|
||||
}
|
||||
#if !defined(__HIPCC__)
|
||||
// The recurrence with one thread for the three value heads that share a key head (head % HK): column c of heads
|
||||
// qh, qh + 16 and qh + 32, row group rg. gdn_rec_cols_pipe_kernel spends its time in shared memory, not in
|
||||
// arithmetic: every thread of a warp needs the same 32 q and k values per token (the k twice), and a warp receives one
|
||||
// such broadcast value per clock however wide the load. Here every q/k value a thread loads feeds three heads, and a
|
||||
// token's k row goes into registers once for both of its uses. The inputs come in blocks of GDN_TB tokens, copied to
|
||||
// shared memory by cp.async while the block before computes (one token ahead is shorter than a load from L2 takes),
|
||||
// and the two cross-row-group sums have their own arrays, so a token needs 2 __syncthreads instead of 5: the second
|
||||
// one of a token orders every read of rkv before the next token's writes, the next token's first one every read of ro
|
||||
// before the writes after it. 64 blocks instead of 192. Per value head and column the same arithmetic in the same
|
||||
// order: the same bits (src/prefill/gdn_rec_parity.cu checks them and times the variants: 1.41x on a 4080 Super).
|
||||
// sm_80+ cards that hold its 64 blocks at once (gdn_keyhead_ok); STRATA_GDN_KEYHEAD=0: gdn_rec_cols_pipe_kernel.
|
||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
|
||||
#define STRATA_GDN_CP_ASYNC 0 // Turing builds: plain copies (never launched there, see gdn_keyhead_ok)
|
||||
#else
|
||||
#define STRATA_GDN_CP_ASYNC 1
|
||||
#endif
|
||||
__device__ __forceinline__ void gdn_cp4(float* smem, const float* gmem) {
|
||||
#if STRATA_GDN_CP_ASYNC
|
||||
asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem));
|
||||
#else
|
||||
*smem = *gmem;
|
||||
#endif
|
||||
}
|
||||
__device__ __forceinline__ void gdn_cp16(float* smem, const float* gmem) {
|
||||
#if STRATA_GDN_CP_ASYNC
|
||||
asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem));
|
||||
#else
|
||||
*reinterpret_cast<float4*>(smem) = *reinterpret_cast<const float4*>(gmem);
|
||||
#endif
|
||||
}
|
||||
__device__ __forceinline__ void gdn_cp_commit() {
|
||||
#if STRATA_GDN_CP_ASYNC
|
||||
asm volatile("cp.async.commit_group;\n" ::);
|
||||
#endif
|
||||
}
|
||||
__device__ __forceinline__ void gdn_cp_wait_prev() { // every group but the newest has landed
|
||||
#if STRATA_GDN_CP_ASYNC
|
||||
asm volatile("cp.async.wait_group 1;\n" ::);
|
||||
#endif
|
||||
}
|
||||
constexpr int GDN_TB = 8, VPK = HV / HK; // tokens per staged block, value heads per key head
|
||||
__global__ void __launch_bounds__(CB * RG) gdn_rec_kh_kernel(float* __restrict__ state, const float* __restrict__ h,
|
||||
const float* __restrict__ gate,
|
||||
const float* __restrict__ beta,
|
||||
float* __restrict__ oc_out, int64_t T) {
|
||||
constexpr int TB = GDN_TB, NT = CB * RG, QKP = S / 4, VP = CB / 4; // threads, 16-byte pieces of a q/k row, of v
|
||||
__shared__ __align__(16) float sq[2][TB][S];
|
||||
__shared__ __align__(16) float sk[2][TB][S];
|
||||
__shared__ __align__(16) float sv[2][TB][VPK][CB];
|
||||
__shared__ float sg[2][TB][VPK], sb[2][TB][VPK], rkv[VPK][RG][CB], ro[VPK][RG][CB];
|
||||
const int qh = blockIdx.x / NCB, cb = blockIdx.x % NCB;
|
||||
const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c;
|
||||
float s[VPK][RPG];
|
||||
const size_t rs = (size_t) HV * S;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPK; ++j) {
|
||||
const float* base = state + ((size_t) (rg * RPG) * HV + qh + j * HK) * S + col;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPG; ++r) s[j][r] = base[r * rs];
|
||||
}
|
||||
const int64_t nblk = (T + TB - 1) / TB;
|
||||
auto stage = [&](int64_t k) { // tokens [k * TB, k * TB + TB) into buffer k & 1
|
||||
const int bb = (int) (k & 1);
|
||||
const int64_t t0 = k * TB;
|
||||
for (int p = tid; p < TB * 2 * QKP; p += NT) {
|
||||
const int i = p / (2 * QKP), w = p % (2 * QKP), isk = w / QKP, jj = (w % QKP) * 4;
|
||||
if (t0 + i < T)
|
||||
gdn_cp16(isk ? &sk[bb][i][jj] : &sq[bb][i][jj], h + (t0 + i) * C + (isk ? HK * S : 0) + qh * S + jj);
|
||||
}
|
||||
for (int p = tid; p < TB * VPK * VP; p += NT) {
|
||||
const int i = p / (VPK * VP), w = p % (VPK * VP), j = w / VP, jj = (w % VP) * 4;
|
||||
if (t0 + i < T)
|
||||
gdn_cp16(&sv[bb][i][j][jj], h + (t0 + i) * C + 2 * HK * S + (qh + j * HK) * S + cb * CB + jj);
|
||||
}
|
||||
for (int p = tid; p < 2 * TB * VPK; p += NT) {
|
||||
const int isb = p / (TB * VPK), w = p % (TB * VPK), i = w / VPK, j = w % VPK;
|
||||
if (t0 + i < T)
|
||||
gdn_cp4(isb ? &sb[bb][i][j] : &sg[bb][i][j], (isb ? beta : gate) + (t0 + i) * HV + qh + j * HK);
|
||||
}
|
||||
};
|
||||
if (nblk > 0) stage(0);
|
||||
gdn_cp_commit();
|
||||
for (int64_t k = 0; k < nblk; ++k) {
|
||||
// buffer (k + 1) & 1 was read by block k - 1, whose last token's second __syncthreads every thread has passed
|
||||
if (k + 1 < nblk) stage(k + 1);
|
||||
gdn_cp_commit();
|
||||
gdn_cp_wait_prev();
|
||||
__syncthreads();
|
||||
const int bb = (int) (k & 1);
|
||||
const int n = (int) ((T - k * TB) < TB ? (T - k * TB) : TB);
|
||||
for (int i = 0; i < n; ++i) {
|
||||
const int64_t t = k * TB + i;
|
||||
float kc[RPG];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPG; ++r) kc[r] = sk[bb][i][rg * RPG + r];
|
||||
float g[VPK], kv[VPK], delta[VPK], o[VPK];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPK; ++j) { g[j] = __expf(sg[bb][i][j]); kv[j] = 0.0f; o[j] = 0.0f; }
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPG; ++r)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPK; ++j) kv[j] = fmaf(s[j][r], kc[r], kv[j]);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPK; ++j) rkv[j][rg][c] = kv[j];
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPK; ++j) {
|
||||
const float kv_col = rkv[j][0][c] + rkv[j][1][c] + rkv[j][2][c] + rkv[j][3][c];
|
||||
delta[j] = (sv[bb][i][j][c] - g[j] * kv_col) * sb[bb][i][j];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPG; ++r) {
|
||||
const float qr = sq[bb][i][rg * RPG + r];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPK; ++j) {
|
||||
s[j][r] = fmaf(g[j], s[j][r], kc[r] * delta[j]);
|
||||
o[j] = fmaf(s[j][r], qr, o[j]);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPK; ++j) ro[j][rg][c] = o[j];
|
||||
__syncthreads();
|
||||
if (rg < VPK) // row group j writes head j's output
|
||||
oc_out[t * HV * S + (qh + rg * HK) * S + col] =
|
||||
(ro[rg][0][c] + ro[rg][1][c] + ro[rg][2][c] + ro[rg][3][c]) * rsqrtf((float) S);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < VPK; ++j) {
|
||||
float* base = state + ((size_t) (rg * RPG) * HV + qh + j * HK) * S + col;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPG; ++r) base[r * rs] = s[j][r];
|
||||
}
|
||||
}
|
||||
// gdn_rec_kh_kernel where it pays: a CUDA card with cp.async (sm_80+) that holds all 64 of its blocks at once (each
|
||||
// walks the whole chunk, so blocks left for a second wave would double the time). The busiest SM sets the pace: from
|
||||
// 64 SMs up this kernel has one block per SM, below that two on some SMs, while the kernel before has ceil(192 / SMs).
|
||||
// With the engine's grids on fewer SMs (gdn_rec_parity --bench), on a 4080 SUPER / a 3090: 1.40-1.42x / 1.28-1.29x at
|
||||
// 64 SMs and more, 1.02-1.04x / 1.03-1.06x at 48 to 63 (two blocks against four: a draw, slower on neither),
|
||||
// 1.28-1.31x / 1.28-1.30x at 39 to 47, 1.53-1.57x / 1.54-1.55x at 32 to 38. Per call, from the current device (a
|
||||
// layer split can mix cards).
|
||||
bool gdn_keyhead_ok() {
|
||||
static const bool off = [] { const char* v = std::getenv("STRATA_GDN_KEYHEAD"); return v != nullptr && std::atoi(v) == 0; }();
|
||||
if (off) return false;
|
||||
static int known[64] = {}; // per device: 0 not asked yet, 1 yes, 2 no
|
||||
int dev = 0;
|
||||
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
|
||||
if (known[dev] == 0) {
|
||||
int major = 0, sms = 0, per_sm = 0;
|
||||
const bool yes = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
|
||||
cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev) == cudaSuccess && major >= 8 &&
|
||||
cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm, gdn_rec_kh_kernel, CB * RG, 0) ==
|
||||
cudaSuccess &&
|
||||
(int64_t) per_sm * sms >= (int64_t) HK * NCB;
|
||||
if (!yes) cudaGetLastError();
|
||||
known[dev] = yes ? 1 : 2;
|
||||
}
|
||||
return known[dev] == 1;
|
||||
}
|
||||
#endif
|
||||
// the output norm over a head's 128 columns, into the FP16 copy the out projection reads (the FP32 output before the
|
||||
// norm stays in its scratch buffer)
|
||||
__global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma,
|
||||
float eps, float* __restrict__ y, uint16_t* __restrict__ y16) {
|
||||
float eps, const float* __restrict__ y,
|
||||
uint16_t* __restrict__ y16) {
|
||||
__shared__ float wsum[4];
|
||||
const int64_t t = blockIdx.x;
|
||||
const int head = blockIdx.y, col = threadIdx.x;
|
||||
@@ -445,7 +609,6 @@ __global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict
|
||||
__syncthreads();
|
||||
const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
|
||||
const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * sigm(z[t * HV * S + head * S + col]);
|
||||
y[at] = v;
|
||||
y16[at] = hf(v);
|
||||
}
|
||||
|
||||
@@ -748,6 +911,11 @@ void gdn_recurrence(float* state, const float* h, const float* gate, const float
|
||||
gdn_rec_kernel<<<HV, dim3(S, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, z, gamma, eps, y, y16, T);
|
||||
} else {
|
||||
static const bool pipe = [] { const char* v = std::getenv("STRATA_GDN_PIPELINE"); return v == nullptr || std::atoi(v) != 0; }();
|
||||
#if !defined(__HIPCC__)
|
||||
if (pipe && gdn_keyhead_ok()) // the value heads of a key head in one thread (same bits)
|
||||
gdn_rec_kh_kernel<<<HK * NCB, dim3(CB, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
|
||||
else
|
||||
#endif
|
||||
if (pipe) // the software-pipelined loads (same bits)
|
||||
gdn_rec_cols_pipe_kernel<<<HV * NCB, dim3(CB, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
|
||||
else
|
||||
|
||||
Reference in new issue
Block a user