prefill: LELEKA_PREFILL_GDN_TC (EXPERIMENTAL, LOSSY, off by default): the prompt GDN recurrence as a chunked scan on the tensor cores (ledger U1)
Port of Strata upstream gdn_tc.cuh (strata-upstream/main 504b1433; history 8c2a84694, 06f212aef 99-KB split plan, 51567de1a two value tiles per head from 96 SMs) as a new standalone sealed asset gdn_prefill_tc.cu/.ptx (sm_120, precise recipe of prefill_stage, extra-seal-plan group gdn-prefill-tc, ptx-sm86 manifest: not built, the plan refuses cc < 12). Kernels: leleka_gdn_tc_prep (chunk algebra A, T = (I + A)^-1, P, f16 hi/lo images), leleka_gdn_tc_scan_t1 (48 blocks x 256) and _t2 (96 blocks x 128, the RTX 5090 plan, 170 SMs), 97,808 B of dynamic shared memory, 254 registers, no spill. Same interface as leleka_prefill_gdn_rec_kh: state_in -> state_out, readout y, the non-finite state witness from the final state. The fused norm, the 124-KB plan and the NP experiments are not ported; our out-norm kernel runs after as before. Switch: typed setting prefill_gdn_tc (LELEKA_PREFILL_GDN_TC=1|on, serve_tests), GdnPromptOptions.tensor_core_scan through Context::original_gdn_prompt_device_with; no env read in cuda-driver. Dispatch (gdn_prefill_tc::plan/ScanPlan::takes, host tests of the whole decision table): switch on, cc >= 12, >= 48 SMs, >= 97,808 B opt-in shared memory, a run of >= 128 tokens; else the sequential kernels unchanged, with one stderr line why. The scratch (942,272 B a chunk, 60,305,408 B at upstream's 64 chunks) is the prompt device's dequantization scratch, idle during the recurrence on the one stream, so the super-block is 55 chunks (1,760 tokens) and the switch costs no device memory. KernelModule gets launch_dynamic (cuFuncSetAttribute opt-in above 48 KiB) and device_geometry. Identity is NOT bitwise, by design: the reduction order changes (WY chunking, f16x3 splits on mma.sync). Upstream first-token KL against the sequential path: mean 0.0019, max 0.0125. The gates that decide are docs/quality-gate.md (first-token KL, q_tail_gate, logprob envelope) and the harness gate 1e-4 (ignored GPU test gdn_tensor_core_scan_stays_within_the_gate_of_the_sequential_recurrence). Not run on a GPU here: no parity, quality or speed result yet, no speedup claim. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
cca8f3cbab
commit
c5a8b77942
@@ -2726,6 +2726,13 @@
|
||||
"problems": [
|
||||
"not built for sm_86 by design (claude/draft-round): LELEKA_DRAFT_FUSED_COMMIT is opt-in and original_verify_schedule.rs::record_commit fuses only on a compute capability 12 card, so an sm_86 build never loads this module"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "gdn_prefill_tc.ptx",
|
||||
"sm120_path": "crates/cuda-driver/src/gdn_prefill_tc.ptx",
|
||||
"problems": [
|
||||
"not built for sm_86 by design (claude/prefill-gdn-tensor-core): LELEKA_PREFILL_GDN_TC is opt-in and experimental and gdn_prefill_tc.rs::plan refuses every device below compute capability 12, so an sm_86 build never loads this module (the kernels use only sm_80 features and would retarget; the 3080 plan needs its own parity and quality run first)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"portable_no_companion_needed": [
|
||||
|
||||
@@ -342,7 +342,7 @@ mod gpu;
|
||||
// Original physical prompt arena producer: old whole-owner API remains exact.
|
||||
#[path = "gdn_prompt_device.rs"]
|
||||
mod prompt_device;
|
||||
pub use prompt_device::{OriginalGdnPromptDevice, OriginalGdnPromptState, OriginalGdnPromptWeights};
|
||||
pub use prompt_device::{GdnPromptOptions, OriginalGdnPromptDevice, OriginalGdnPromptState, OriginalGdnPromptWeights};
|
||||
|
||||
#[path = "gdn_native_batch/pinned.rs"]
|
||||
mod pinned;
|
||||
|
||||
@@ -0,0 +1,549 @@
|
||||
// Offline compilation source; not a runtime/toolkit dependency.
|
||||
// EXPERIMENTAL, LOSSY (LELEKA_PREFILL_GDN_TC, off by default): the prompt GDN recurrence as a chunked scan on the tensor cores.
|
||||
//
|
||||
// Port of Strata upstream `src/prefill/gdn_tc.cuh` (strata-upstream/main 504b1433, history 8c2a84694 -> 06f212aef (the 99-KB
|
||||
// split plan for sm_86 / sm_89 / sm_120) -> ee0511484 -> 51567de1a (two value tiles a head on cards with >= 96 SMs)), restricted
|
||||
// to the plan the RTX 5090 (sm_120, 99 KB of shared memory a block, 170 SMs) runs: SPLIT shared-memory plan, three f16 passes a
|
||||
// product (NP = 3), output norm NOT fused (our separate leleka_prefill_gdn_out_norm* kernel runs after the recurrence as before),
|
||||
// one value tile (leleka_gdn_tc_scan_t1, 48 blocks) or two (leleka_gdn_tc_scan_t2, 96 blocks of 128 threads). The fused norm, the
|
||||
// one-pass and 124-KB plans, and the NP experiments are not ported.
|
||||
//
|
||||
// What it replaces: leleka_prefill_gdn_rec / leleka_prefill_gdn_rec_kh (prefill_stage.cu), the token-serial recurrence of the
|
||||
// Original. Same interface and layout: state_in -> state_out ([128 rows][48 heads][128 cols] f32), h = the convolved and L2-normalised
|
||||
// qkv rows ([T][10240]: q | k | v), gate (log decay) and beta ([T][48]), the readout `oc_out` ([T][48][128], already x rsqrt(128))
|
||||
// and the state witness (bit 0 of *witness raised when the FINAL state holds a non-finite value, as leleka_prefill_gdn_rec_kh).
|
||||
//
|
||||
// NOT BITWISE EQUAL to those kernels, by design: the recurrence is re-associated into the chunked WY form of
|
||||
// gdn_chunk_scan_kernel and every product runs on f16 mma.sync with f16x3 splits (x = hi + lo, hi.hi + hi.lo + lo.hi, lo.lo dropped,
|
||||
// operands scaled by powers of two so that lo stays normal): within 3 x 2^-22 |a||b| of each exact product, 1e-4 of the sequential
|
||||
// kernel in the upstream harness. Upstream's end-to-end first-token KL against the sequential path: mean 0.0019, max 0.0125. The gate
|
||||
// that decides is docs/quality-gate.md (first-token KL / q_tail_gate / logprob envelope), not an identity probe.
|
||||
//
|
||||
// Three kernels, a prompt chunk of T tokens runs in super-blocks of nch chunks (32 tokens each) held in a scratch the host provides:
|
||||
// leleka_gdn_tc_prep grid nch * 16 (block b: chunk b / 16, key head b % 16), 256 threads, 43,264 B dynamic shared memory:
|
||||
// A, T = (I + A)^-1 and P of the chunk, the k / q f16 hi / lo images, the token scalars, into the scratch
|
||||
// leleka_gdn_tc_scan_t1 grid 48 (a block per value head), 256 threads, 97,808 B
|
||||
// leleka_gdn_tc_scan_t2 grid 96 (value head x 2 column tiles), 128 threads, 97,808 B
|
||||
// The scan launches of one prompt run in order and the second one on reads the state the first wrote (state_in == state_out is
|
||||
// supported: a block reads and writes only its own columns).
|
||||
//
|
||||
// Scratch (bytes, a chunk of the super-block): T images 196,608 + T scales 192 + token scalars 24,576 + k / q images 524,288 + P images
|
||||
// 196,608 = 942,272 B; 64 chunks (2048 tokens, upstream's GSB) are 60,305,408 B. Every sub-buffer starts on a 16-B boundary (cp.async).
|
||||
//
|
||||
// Intended offline compile (the recipe of the other precise assets): pinned NVCC 13.2.86, -std=c++17 -O3 -ptx -arch=sm_120
|
||||
// --ftz=false --prec-div=true --prec-sqrt=true --fmad=true.
|
||||
#include <cuda_fp16.h>
|
||||
#include <stdint.h>
|
||||
|
||||
namespace {
|
||||
constexpr int S = 128, HK = 16, HV = 48, C = 10240; // head size, key heads, value heads, qkv row width
|
||||
constexpr int VPK = HV / HK; // value heads a key head
|
||||
constexpr int GCH = 32; // tokens a chunk (the prep's solve is a lane per token)
|
||||
constexpr int GTP = GCH + 1; // padded T / P rows of the prep
|
||||
static_assert(GCH == 32, "a lane per token of the chunk");
|
||||
static_assert(C == 2 * HK * S + HV * S, "qkv row: q | k | v");
|
||||
|
||||
__device__ __forceinline__ void gdn_cp4(float* smem, const float* gmem) {
|
||||
asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem));
|
||||
}
|
||||
__device__ __forceinline__ void gdn_cp16(float* smem, const float* gmem) {
|
||||
asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem));
|
||||
}
|
||||
__device__ __forceinline__ void gdn_cp_commit() { asm volatile("cp.async.commit_group;\n" ::); }
|
||||
__device__ __forceinline__ void gdn_cp_wait_all() { asm volatile("cp.async.wait_all;\n" ::); }
|
||||
|
||||
constexpr int GTC_KP = S + 8; // f16 k / q rows: a 272-B stride puts the 8 rows of a ldmatrix 8x8 on 8 distinct 16-B lanes
|
||||
constexpr int GTC_VP = S + 4; // f32 v rows: lane (gid, tig) reads word 264 tig + gid, 32 distinct banks
|
||||
constexpr int GTC_PP = GCH + 8; // f16 T / P rows: an 80-B stride, 8 rows on distinct 16-B lanes
|
||||
constexpr int GTC_CW = S / 16; // consumer warps a block: 16 value columns each
|
||||
// The SPLIT shared-memory plan (the 99-KB cards): only k / q hi / lo and the token scalars stay double-buffered; v, T and P (one
|
||||
// buffer) are staged for the next chunk after this chunk's last read of them, so that load overlaps the state update.
|
||||
constexpr size_t kTcScanSmemSplit = 2 * (4 * GCH * GTC_KP * 2 + GCH * 16) + GCH * GTC_VP * 4 + 4 * GCH * GTC_PP * 2 + 16;
|
||||
static_assert(kTcScanSmemSplit == 97808, "the split shared-memory plan");
|
||||
constexpr size_t kTcPrepSmem = (size_t) 4 * GCH * GTC_KP * 2 + 2 * GCH * GTP * 4; // the images, then k_t.k_i and q_t.k_i
|
||||
static_assert(kTcPrepSmem == 43264, "the prep shared-memory plan");
|
||||
static_assert(VPK * GCH * GTP * 4 <= 4 * GCH * GTC_KP * 2, "gdn_tc_prep: A fits where the images were");
|
||||
|
||||
// the warp's largest of non-negative floats: their bits order as unsigned integers, so one redux.sync. Under the full mask (the
|
||||
// first call of the scan follows a lane-divergent branch, so __activemask() would not do).
|
||||
__device__ __forceinline__ float gtc_warp_max(float v) {
|
||||
return __uint_as_float(__reduce_max_sync(0xffffffffu, __float_as_uint(v)));
|
||||
}
|
||||
__device__ __forceinline__ float gtc_pow2(int e) { return __int_as_float((e + 127) << 23); } // 2^e, |e| < 127
|
||||
// the power of two that puts m = max |x| >= 0 in [2^14, 2^15): f16 hi never overflows (65504) and the low part of every entry within
|
||||
// 2^-17 of the max stays normal; clamped so that the compensating powers stay far from f32's range
|
||||
__device__ __forceinline__ int gtc_scale_exp(float m) {
|
||||
if (m == 0.0f) return 0;
|
||||
const int e = 14 - ((__float_as_int(m) >> 23) - 127);
|
||||
return e < -40 ? -40 : (e > 40 ? 40 : e);
|
||||
}
|
||||
|
||||
// ---- the tensor-core wrappers (PTX ISA "Matrix Fragments": lane = 4 gid + tig)
|
||||
// m16n8k16 f16: A a0 = (row gid, cols 2tig, 2tig+1) a1 = (gid+8, ..) a2 = (gid, 2tig+8..) a3 = (gid+8, 2tig+8..);
|
||||
// B b0 = (k 2tig, 2tig+1; n gid) b1 = (k 2tig+8..; n gid); C/D c0 = (gid, 2tig) c1 = (gid, 2tig+1)
|
||||
// c2 = (gid+8, 2tig) c3 = (gid+8, 2tig+1) - so two adjacent C tiles ARE the next product's A fragment
|
||||
// ldmatrix m8n8.x4.b16: lanes 8m..8m+7 give the row addresses of matrix m; a lane gets (row gid, cols 2tig, 2tig+1)
|
||||
// of each matrix (the lower column in the low half), or with .trans (rows 2tig, 2tig+1; col gid)
|
||||
__device__ __forceinline__ void gtc_ldsm_x4(uint32_t (&r)[4], const void* smem) {
|
||||
asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];"
|
||||
: "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3])
|
||||
: "r"((unsigned) __cvta_generic_to_shared(smem)));
|
||||
}
|
||||
__device__ __forceinline__ void gtc_ldsm_x4_trans(uint32_t (&r)[4], const void* smem) {
|
||||
asm volatile("ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {%0,%1,%2,%3}, [%4];"
|
||||
: "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3])
|
||||
: "r"((unsigned) __cvta_generic_to_shared(smem)));
|
||||
}
|
||||
__device__ __forceinline__ void gtc_mma_f16(float (&c)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t b1) {
|
||||
asm("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};"
|
||||
: "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
|
||||
: "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1));
|
||||
}
|
||||
// the three passes of a split product, small terms first: lo.hi, hi.lo, hi.hi
|
||||
__device__ __forceinline__ void gtc_mma3_f16(float (&c)[4], const uint32_t (&ah)[4], const uint32_t (&al)[4], uint32_t bh0,
|
||||
uint32_t bh1, uint32_t bl0, uint32_t bl1) {
|
||||
gtc_mma_f16(c, al, bh0, bh1);
|
||||
gtc_mma_f16(c, ah, bl0, bl1);
|
||||
gtc_mma_f16(c, ah, bh0, bh1);
|
||||
}
|
||||
// x0, x1 -> packed f16 hi (x0 in the low half) and lo = f16(x - hi): x - hi is exact in f32 (hi carries x's exponent)
|
||||
__device__ __forceinline__ void gtc_split_f16x2(float x0, float x1, uint32_t& hi, uint32_t& lo) {
|
||||
union { __half2 h; uint32_t u; } cv;
|
||||
cv.h = __floats2half2_rn(x0, x1);
|
||||
hi = cv.u;
|
||||
const float2 r = __half22float2(cv.h);
|
||||
cv.h = __floats2half2_rn(x0 - r.x, x1 - r.y);
|
||||
lo = cv.u;
|
||||
}
|
||||
// four consecutive elements of an f16 hi / lo row from a float4 x scale (an 8-byte store each)
|
||||
__device__ __forceinline__ void gtc_split_store4(uint16_t* hi, uint16_t* lo, float4 v, float scale) {
|
||||
uint32_t h0, l0, h1, l1;
|
||||
gtc_split_f16x2(v.x * scale, v.y * scale, h0, l0);
|
||||
gtc_split_f16x2(v.z * scale, v.w * scale, h1, l1);
|
||||
*reinterpret_cast<uint2*>(hi) = make_uint2(h0, h1);
|
||||
*reinterpret_cast<uint2*>(lo) = make_uint2(l0, l1);
|
||||
}
|
||||
// a float4 from shared memory the compiler does not keep: the per-token scalars are read in three phases of a chunk, a component
|
||||
// each, and kept across them they cost 24 registers a thread
|
||||
__device__ __forceinline__ float4 gtc_lds128(const float4* p) {
|
||||
float4 v;
|
||||
asm volatile("ld.shared.v4.f32 {%0,%1,%2,%3}, [%4];"
|
||||
: "=f"(v.x), "=f"(v.y), "=f"(v.z), "=f"(v.w)
|
||||
: "r"((unsigned) __cvta_generic_to_shared(p)));
|
||||
return v;
|
||||
}
|
||||
|
||||
// ---- the products of a chunk, a warp each
|
||||
// X^T = S^T K^T and QS^T = S^T Q^T: A = the state fragments x sA (= 2^es) split in f16 hi / lo just in time per k16-step (tiles 2kk and
|
||||
// 2kk + 1 of S^T are that step's A fragment), B = the f16 hi / lo images of k and q ([GCH][GTC_KP] in shared memory, rows = tokens) by
|
||||
// ldmatrix: matrices (n-tile 2hf + (lane >> 4), k-half (lane >> 3) & 1), a lane's row is token 8 n-tile + (lane & 7). The accumulators
|
||||
// come out as 2^(8 + es) times the products. 2 x 96 mma.
|
||||
__device__ __forceinline__ void gtc_prod_state(const float (&s)[16][4], float sA, const uint16_t* kh, const uint16_t* kl,
|
||||
const uint16_t* qh, const uint16_t* ql, float (&xt)[4][4], float (&qs)[4][4]) {
|
||||
const int lane = threadIdx.x & 31;
|
||||
const int off = (8 * (lane >> 4) + (lane & 7)) * GTC_KP + 8 * ((lane >> 3) & 1);
|
||||
#pragma unroll
|
||||
for (int kk = 0; kk < S / 16; ++kk) {
|
||||
uint32_t ah[4], al[4];
|
||||
gtc_split_f16x2(s[2 * kk][0] * sA, s[2 * kk][1] * sA, ah[0], al[0]);
|
||||
gtc_split_f16x2(s[2 * kk][2] * sA, s[2 * kk][3] * sA, ah[1], al[1]);
|
||||
gtc_split_f16x2(s[2 * kk + 1][0] * sA, s[2 * kk + 1][1] * sA, ah[2], al[2]);
|
||||
gtc_split_f16x2(s[2 * kk + 1][2] * sA, s[2 * kk + 1][3] * sA, ah[3], al[3]);
|
||||
#pragma unroll
|
||||
for (int hf = 0; hf < 2; ++hf) {
|
||||
const int o = off + 16 * hf * GTC_KP + 16 * kk;
|
||||
uint32_t bh[4], bl[4];
|
||||
gtc_ldsm_x4(bh, kh + o);
|
||||
gtc_ldsm_x4(bl, kl + o);
|
||||
gtc_mma3_f16(xt[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]);
|
||||
gtc_mma3_f16(xt[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]);
|
||||
gtc_ldsm_x4(bh, qh + o);
|
||||
gtc_ldsm_x4(bl, ql + o);
|
||||
gtc_mma3_f16(qs[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]);
|
||||
gtc_mma3_f16(qs[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// o^T += (sD D^T) (2^8 P^T) on f16x3: A = the D^T tiles x sD (= 2^ed) split per k16-step, B = the f16 hi / lo images of P x 2^8
|
||||
// ([GCH][GTC_PP], rows = tokens t) by ldmatrix as in gtc_prod_state. The tiles above P's diagonal are left out: tokens t < 16 (n-tiles
|
||||
// 0, 1) see no i >= 16 (k-step 1). 18 mma. D^T += (sY Y^T) (2^et T^T) is the same product on the T images (T is zero above its
|
||||
// diagonal too), the accumulator x 2^(ey + et).
|
||||
__device__ __forceinline__ void gtc_prod_dt(const float (&dt)[4][4], float sD, const uint16_t* ph, const uint16_t* pl,
|
||||
float (&ot)[4][4]) {
|
||||
const int lane = threadIdx.x & 31;
|
||||
const int off = (8 * (lane >> 4) + (lane & 7)) * GTC_PP + 8 * ((lane >> 3) & 1);
|
||||
#pragma unroll
|
||||
for (int ks = 0; ks < GCH / 16; ++ks) {
|
||||
uint32_t ah[4], al[4];
|
||||
gtc_split_f16x2(dt[2 * ks][0] * sD, dt[2 * ks][1] * sD, ah[0], al[0]);
|
||||
gtc_split_f16x2(dt[2 * ks][2] * sD, dt[2 * ks][3] * sD, ah[1], al[1]);
|
||||
gtc_split_f16x2(dt[2 * ks + 1][0] * sD, dt[2 * ks + 1][1] * sD, ah[2], al[2]);
|
||||
gtc_split_f16x2(dt[2 * ks + 1][2] * sD, dt[2 * ks + 1][3] * sD, ah[3], al[3]);
|
||||
#pragma unroll
|
||||
for (int hf = 0; hf < 2; ++hf) {
|
||||
if (ks == 1 && hf == 0) continue;
|
||||
const int o = off + 16 * hf * GTC_PP + 16 * ks;
|
||||
uint32_t bh[4], bl[4];
|
||||
gtc_ldsm_x4(bh, ph + o);
|
||||
gtc_ldsm_x4(bl, pl + o);
|
||||
gtc_mma3_f16(ot[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]);
|
||||
gtc_mma3_f16(ot[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// S^T += Dd^T (2^8 K) on f16x3: A = the (already scaled) Dd^T tiles split per k16-step, B = the same k images read the other way by
|
||||
// ldmatrix.trans: matrices (n-tile 2hf + (lane >> 4), k-half (lane >> 3) & 1), a lane's row is token 16 ks + 8 k-half + (lane & 7), its
|
||||
// 16-B piece state rows 8 n-tile.. 96 mma.
|
||||
__device__ __forceinline__ void gtc_update_state(float (&s)[16][4], const float (&dd)[4][4], const uint16_t* kh,
|
||||
const uint16_t* kl) {
|
||||
const int lane = threadIdx.x & 31;
|
||||
const int off = (8 * ((lane >> 3) & 1) + (lane & 7)) * GTC_KP + 8 * (lane >> 4);
|
||||
#pragma unroll
|
||||
for (int ks = 0; ks < GCH / 16; ++ks) {
|
||||
uint32_t ah[4], al[4];
|
||||
gtc_split_f16x2(dd[2 * ks][0], dd[2 * ks][1], ah[0], al[0]);
|
||||
gtc_split_f16x2(dd[2 * ks][2], dd[2 * ks][3], ah[1], al[1]);
|
||||
gtc_split_f16x2(dd[2 * ks + 1][0], dd[2 * ks + 1][1], ah[2], al[2]);
|
||||
gtc_split_f16x2(dd[2 * ks + 1][2], dd[2 * ks + 1][3], ah[3], al[3]);
|
||||
#pragma unroll
|
||||
for (int hf = 0; hf < S / 16; ++hf) {
|
||||
const int o = off + 16 * ks * GTC_KP + 16 * hf;
|
||||
uint32_t bh[4], bl[4];
|
||||
gtc_ldsm_x4_trans(bh, kh + o);
|
||||
gtc_ldsm_x4_trans(bl, kl + o);
|
||||
gtc_mma3_f16(s[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]);
|
||||
gtc_mma3_f16(s[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the scan of one super-block: a block per value head (or per head and column tile), warps of 16 value columns each walking
|
||||
// every chunk with their state slice in registers, the prep's scratch staged by cp.async. NTL value tiles a head (a launch of HV x NTL
|
||||
// blocks of GTC_CW / NTL warps): block (vh, tile) owns the state columns [tile S / NTL, (tile + 1) S / NTL). The k / q / T / P images
|
||||
// are staged by every tile of the head, v only for its columns.
|
||||
extern __shared__ __align__(16) unsigned char gtc_sm[]; // the scan's dynamic shared memory (97,808 B)
|
||||
|
||||
template <int NTL>
|
||||
__device__ __forceinline__ void gtc_scan_body(const float* state_in, float* state_out, const float* __restrict__ h,
|
||||
const uint16_t* __restrict__ tig_, const float* __restrict__ teg,
|
||||
const float4* __restrict__ scg, const uint16_t* __restrict__ kqg,
|
||||
const uint16_t* __restrict__ pig, float* __restrict__ oc_out, int64_t t0,
|
||||
int nch, int64_t T, unsigned* witness) {
|
||||
static_assert(GTC_CW % NTL == 0, "tiles of whole warps");
|
||||
constexpr int NT = (GTC_CW / NTL) * 32;
|
||||
uint16_t* kh = reinterpret_cast<uint16_t*>(gtc_sm); // [2][GCH][GTC_KP] f16 of k x 2^8 (hi)
|
||||
uint16_t* kl = kh + 2 * GCH * GTC_KP; // [2][GCH][GTC_KP] what hi left out (lo)
|
||||
uint16_t* qh = kl + 2 * GCH * GTC_KP; // q likewise
|
||||
uint16_t* ql = qh + 2 * GCH * GTC_KP;
|
||||
float* sv = reinterpret_cast<float*>(ql + 2 * GCH * GTC_KP); // [GCH][GTC_VP] v (one buffer)
|
||||
uint16_t* th = reinterpret_cast<uint16_t*>(sv + GCH * GTC_VP); // [GCH][GTC_PP] T x 2^et hi / lo
|
||||
uint16_t* tl = th + GCH * GTC_PP;
|
||||
uint16_t* ph = tl + GCH * GTC_PP; // [GCH][GTC_PP] P x 2^8 hi / lo
|
||||
uint16_t* pl = ph + GCH * GTC_PP;
|
||||
float4* sc = reinterpret_cast<float4*>(pl + GCH * GTC_PP); // [2][GCH] (beta, exp(gamma), exp(gL - gamma), gamma)
|
||||
float* ste = reinterpret_cast<float*>(sc + 2 * GCH); // [2] 2^-et
|
||||
const int vh = blockIdx.x / NTL, qhd = vh % HK, cb = (blockIdx.x % NTL) * (S / NTL); // the tile's first column
|
||||
const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31, gid = lane >> 2, tig = lane & 3;
|
||||
const size_t rs = (size_t) HV * S;
|
||||
// chunk ch into buffer b, this thread's 16-B pieces (one cp.async group): the four k / q images (4 x GCH rows of 16 pieces: 8 a
|
||||
// thread), v (4 a thread), the two T images (1), the two P images (1), the scalars (threads < GCH), T's scale (thread 0, 4 B)
|
||||
// parts: bit 0 = the k / q images, the scalars and T's scale (buffer b); bit 1 = v, T and P (the one buffer)
|
||||
auto stage = [&](int ch, int b, int parts) {
|
||||
const int64_t c_t0 = t0 + (int64_t) ch * GCH;
|
||||
const int n = (int) min((int64_t) GCH, T - c_t0);
|
||||
if (parts & 1) {
|
||||
const uint16_t* img = kqg + ((size_t) ch * HK + qhd) * 4 * GCH * S;
|
||||
#pragma unroll
|
||||
for (int m = 0; m < 4 * GCH * S / 8 / NT; ++m) {
|
||||
const int pc = tid + NT * m, im = pc / (GCH * S / 8), t = (pc % (GCH * S / 8)) / (S / 8), r = (pc % (S / 8)) * 8;
|
||||
uint16_t* dst = (im == 0 ? kh : im == 1 ? kl : im == 2 ? qh : ql) + (b * GCH + t) * GTC_KP + r;
|
||||
gdn_cp16(reinterpret_cast<float*>(dst), reinterpret_cast<const float*>(img + (im * GCH + t) * S + r));
|
||||
}
|
||||
if (tid < GCH) gdn_cp16(reinterpret_cast<float*>(sc + b * GCH + tid), reinterpret_cast<const float*>(scg + ((int64_t) ch * HV + vh) * GCH + tid));
|
||||
if (tid == 0) gdn_cp4(ste + b, teg + (int64_t) ch * HV + vh);
|
||||
}
|
||||
if (parts & 2) {
|
||||
#pragma unroll
|
||||
for (int m = 0; m < GCH * (S / NTL) / 4 / NT; ++m) {
|
||||
const int p = tid + NT * m, t = p / (S / NTL / 4), r = (p % (S / NTL / 4)) * 4;
|
||||
float* dst = sv + t * GTC_VP + r;
|
||||
if (t < n) gdn_cp16(dst, h + (c_t0 + t) * C + 2 * HK * S + vh * S + cb + r);
|
||||
else *reinterpret_cast<float4*>(dst) = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int m = 0; m < 2 * GCH * GCH / 8 / NT; ++m) {
|
||||
const int pc = tid + NT * m, im = pc / (GCH * GCH / 8), t = (pc % (GCH * GCH / 8)) / (GCH / 8), i = (pc % (GCH / 8)) * 8;
|
||||
const int64_t src = ((((int64_t) ch * HV + vh) * 2 + im) * GCH + t) * GCH + i;
|
||||
const int dst = t * GTC_PP + i;
|
||||
gdn_cp16(reinterpret_cast<float*>((im ? tl : th) + dst), reinterpret_cast<const float*>(tig_ + src));
|
||||
gdn_cp16(reinterpret_cast<float*>((im ? pl : ph) + dst), reinterpret_cast<const float*>(pig + src));
|
||||
}
|
||||
}
|
||||
gdn_cp_commit();
|
||||
};
|
||||
const int c0 = 16 * warp; // the warp's value columns c0 + gid and c0 + gid + 8 of the tile (v in shared memory)
|
||||
const int ca = cb + c0; // the same in the head (state, output)
|
||||
// the state slice as S^T fragments: tile j = rows 8j..8j+7; s[j][0] = S[8j + 2tig][c0 + gid], [1] the row after, [2] column + 8, [3]
|
||||
// both (64 scalar loads a lane, 32-B runs, once a launch)
|
||||
float s[16][4];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 16; ++j) {
|
||||
const float* p = state_in + (size_t) (8 * j + 2 * tig) * rs + (size_t) vh * S + ca + gid;
|
||||
s[j][0] = p[0]; s[j][1] = p[rs]; s[j][2] = p[8]; s[j][3] = p[rs + 8];
|
||||
}
|
||||
stage(0, 0, 3);
|
||||
const float out_scale = rsqrtf((float) S);
|
||||
for (int ch = 0; ch < nch; ++ch) {
|
||||
const int b = ch & 1;
|
||||
const int64_t c_t0 = t0 + (int64_t) ch * GCH;
|
||||
const int n = (int) min((int64_t) GCH, T - c_t0);
|
||||
gdn_cp_wait_all(); // this thread's pieces of chunk ch
|
||||
__syncthreads(); // every thread's: chunk ch's buffer complete; every read of the other one done
|
||||
if (ch + 1 < nch) stage(ch + 1, b ^ 1, 1);
|
||||
const uint16_t* bkh = kh + b * GCH * GTC_KP;
|
||||
const uint16_t* bkl = kl + b * GCH * GTC_KP;
|
||||
const uint16_t* bqh = qh + b * GCH * GTC_KP;
|
||||
const uint16_t* bql = ql + b * GCH * GTC_KP;
|
||||
const float4* bsc = sc + b * GCH;
|
||||
// (a) X^T = S0^T K^T and QS^T = S0^T Q^T, the state x 2^es (its largest entry in [2^14, 2^15)). The lane's maximum over eight
|
||||
// chains (nvcc keeps the order written: one chain was 64 dependent FMNMX before the first mma)
|
||||
float m8[8] = {};
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 16; ++j)
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) m8[(2 * j + (q >> 1)) & 7] = fmaxf(m8[(2 * j + (q >> 1)) & 7], fabsf(s[j][q]));
|
||||
const float m = fmaxf(fmaxf(fmaxf(m8[0], m8[1]), fmaxf(m8[2], m8[3])), fmaxf(fmaxf(m8[4], m8[5]), fmaxf(m8[6], m8[7])));
|
||||
const int es = gtc_scale_exp(gtc_warp_max(m));
|
||||
float xt[4][4] = {}, qs[4][4] = {};
|
||||
gtc_prod_state(s, gtc_pow2(es), bkh, bkl, bqh, bql, xt, qs);
|
||||
// (b) Y^T = beta_i (V^T - e'_i X^T), e'_i = exp(gamma_i) 2^-(8 + es): lane (gid, tig) holds tokens 8nt + 2tig and + 1, columns
|
||||
// c0 + gid and + 8
|
||||
const float eS = gtc_pow2(-(8 + es));
|
||||
float yt[4][4];
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < 4; ++nt) {
|
||||
const float4 s0 = gtc_lds128(bsc + 8 * nt + 2 * tig), s1 = gtc_lds128(bsc + 8 * nt + 2 * tig + 1);
|
||||
const float* v = sv + (8 * nt + 2 * tig) * GTC_VP + c0 + gid;
|
||||
const float e0 = s0.y * eS, e1 = s1.y * eS;
|
||||
yt[nt][0] = s0.x * fmaf(-e0, xt[nt][0], v[0]);
|
||||
yt[nt][1] = s1.x * fmaf(-e1, xt[nt][1], v[GTC_VP]);
|
||||
yt[nt][2] = s0.x * fmaf(-e0, xt[nt][2], v[8]);
|
||||
yt[nt][3] = s1.x * fmaf(-e1, xt[nt][3], v[GTC_VP + 8]);
|
||||
}
|
||||
// (c) D^T = Y^T T^T on f16x3: Y^T x 2^ey (its largest entry in [2^14, 2^15)), T's images x 2^et from the prep; the accumulator
|
||||
// comes out x 2^(ey + et) (T above its diagonal skipped)
|
||||
float my4[4] = {};
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < 4; ++nt)
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) my4[q] = fmaxf(my4[q], fabsf(yt[nt][q]));
|
||||
const int ey = gtc_scale_exp(gtc_warp_max(fmaxf(fmaxf(my4[0], my4[1]), fmaxf(my4[2], my4[3]))));
|
||||
float dt[4][4] = {};
|
||||
gtc_prod_dt(yt, gtc_pow2(ey), th, tl, dt);
|
||||
const float sYT = gtc_pow2(-ey) * ste[b];
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < 4; ++nt)
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) dt[nt][q] *= sYT;
|
||||
// (d) o^T = e_t QS^T + D^T P^T: the accumulator starts as 2^(ed + 8) e_t QS^T (QS^T came out x 2^(8 + es)), D^T goes in x 2^ed, P
|
||||
// x 2^8; the output is the accumulator x 2^-(ed + 8), then rsqrt(S)
|
||||
float md4[4] = {};
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < 4; ++nt)
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) md4[q] = fmaxf(md4[q], fabsf(dt[nt][q]));
|
||||
const int ed = gtc_scale_exp(gtc_warp_max(fmaxf(fmaxf(md4[0], md4[1]), fmaxf(md4[2], md4[3]))));
|
||||
const float sD = gtc_pow2(ed), sO = gtc_pow2(ed + 8), sOi = gtc_pow2(-(ed + 8)), eO = gtc_pow2(ed - es);
|
||||
float ot[4][4];
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < 4; ++nt) {
|
||||
const float e0 = gtc_lds128(bsc + 8 * nt + 2 * tig).y * eO, e1 = gtc_lds128(bsc + 8 * nt + 2 * tig + 1).y * eO;
|
||||
ot[nt][0] = qs[nt][0] * e0; ot[nt][1] = qs[nt][1] * e1; ot[nt][2] = qs[nt][2] * e0; ot[nt][3] = qs[nt][3] * e1;
|
||||
}
|
||||
gtc_prod_dt(dt, sD, ph, pl, ot);
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < 4; ++nt)
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
const int t = 8 * nt + 2 * tig + (q & 1);
|
||||
if (t < n) oc_out[(c_t0 + t) * rs + (size_t) vh * S + ca + gid + 8 * (q >> 1)] = (ot[nt][q] * sOi) * out_scale;
|
||||
}
|
||||
// v, T and P of this chunk are dead: every warp is past (d); the next chunk's land during (e)
|
||||
__syncthreads();
|
||||
if (ch + 1 < nch) stage(ch + 1, 0, 2);
|
||||
// (e) S^T = eL S0^T + Dd^T K, Dd^T = f_i D^T: the accumulator x (eL 2^(ed + 8)) before (one rounding), Dd^T in x 2^ed, K x 2^8,
|
||||
// the accumulator x 2^-(ed + 8) after
|
||||
const float sPre = gtc_lds128(bsc + GCH - 1).y * sO; // exp(gL)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 16; ++j)
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) s[j][q] *= sPre;
|
||||
float dd[4][4];
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < 4; ++nt) {
|
||||
const float f0 = gtc_lds128(bsc + 8 * nt + 2 * tig).z * sD, f1 = gtc_lds128(bsc + 8 * nt + 2 * tig + 1).z * sD;
|
||||
dd[nt][0] = dt[nt][0] * f0; dd[nt][1] = dt[nt][1] * f1; dd[nt][2] = dt[nt][2] * f0; dd[nt][3] = dt[nt][3] * f1;
|
||||
}
|
||||
gtc_update_state(s, dd, bkh, bkl);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 16; ++j)
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) s[j][q] *= sOi;
|
||||
}
|
||||
// the final state and its witness (a non-finite state value never becomes finite again, so the final state is enough)
|
||||
unsigned bad = 0;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 16; ++j) {
|
||||
float* p = state_out + (size_t) (8 * j + 2 * tig) * rs + (size_t) vh * S + ca + gid;
|
||||
p[0] = s[j][0]; p[rs] = s[j][1]; p[8] = s[j][2]; p[rs + 8] = s[j][3];
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) bad |= (__float_as_uint(s[j][q]) & 0x7f800000u) == 0x7f800000u;
|
||||
}
|
||||
if (bad) atomicOr(witness, 1u);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// ---- the prep, a block per (chunk, key head): the same A, solve, T and P as the chunk algebra, but the Gram products k_t.k_i and
|
||||
// q_t.k_i on the tensor cores (f16x3 from the k and q hi / lo images x 2^8, which the block builds first in shared memory straight from
|
||||
// the float4 registers the rows arrive in, rows past the chunk's end zero), and it writes what the scan stages by cp.async with no
|
||||
// conversion of its own: the same k / q images, P as f16 hi / lo images x 2^8 and the token scalars (beta, exp(gamma), exp(gL - gamma),
|
||||
// gamma) as a float4 a token, T as f16 hi / lo images x 2^et, et from the warp's largest |T| (2^-et beside them in te). The Gram
|
||||
// entries are within 3 x 2^-22 of exact, so T and P differ from the sequential algebra's by that.
|
||||
// Grid: nch * HK blocks, block b = chunk b / HK of the super-block, key head b % HK (a 1-D grid: KernelModule's contract).
|
||||
extern "C" __global__ void __launch_bounds__(256) leleka_gdn_tc_prep(
|
||||
const float* __restrict__ h, const float* __restrict__ gate, const float* __restrict__ beta, uint16_t* __restrict__ ti,
|
||||
float* __restrict__ te, float4* __restrict__ sc, uint16_t* __restrict__ kq, uint16_t* __restrict__ pi, int64_t t0,
|
||||
int64_t T) {
|
||||
extern __shared__ __align__(16) float gsm[];
|
||||
uint16_t* im = reinterpret_cast<uint16_t*>(gsm); // [4][GCH][GTC_KP] k hi, k lo, q hi, q lo (x 2^8)
|
||||
float* skk = gsm + 4 * GCH * GTC_KP / 2; // [GCH][GTP] k_t.k_i
|
||||
float* sqk = skk + GCH * GTP; // [GCH][GTP] q_t.k_i
|
||||
float* sa = gsm; // [VPK][GCH][GTP] A, then T below the diagonal (over the images: read by then)
|
||||
const int qh = blockIdx.x % HK, ch = blockIdx.x / HK, tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
|
||||
const int64_t tb = t0 + (int64_t) ch * GCH;
|
||||
const int n = (int) min((int64_t) GCH, T - tb);
|
||||
// after the Gram: warps j and VPK + j take value head j (lane i: token i), the first A, the solve and T, the second P and the token
|
||||
// scalars; their beta and gate (past the end: gate 0, beta 0, no effect on S) are loaded now so that they are in by then
|
||||
const int j = warp % VPK, vh = qh + j * HK, i = lane;
|
||||
const bool pv = warp < 2 * VPK && i < n;
|
||||
const float b = pv ? beta[(tb + i) * HV + vh] : 0.0f;
|
||||
float gam = pv ? gate[(tb + i) * HV + vh] : 0.0f;
|
||||
{ // k and q as float4, every load issued before the first store; the images to shared and to global
|
||||
constexpr int NP = GCH * S / 4 / 256; // float4 a thread, each of k and q
|
||||
float4 kv[NP], qv[NP];
|
||||
#pragma unroll
|
||||
for (int m = 0; m < NP; ++m) {
|
||||
const int p = tid + 256 * m, t = p / (S / 4), r = (p % (S / 4)) * 4;
|
||||
kv[m] = t < n ? *reinterpret_cast<const float4*>(h + (tb + t) * C + HK * S + qh * S + r) : make_float4(0.f, 0.f, 0.f, 0.f);
|
||||
qv[m] = t < n ? *reinterpret_cast<const float4*>(h + (tb + t) * C + qh * S + r) : make_float4(0.f, 0.f, 0.f, 0.f);
|
||||
}
|
||||
uint16_t* img = kq + ((size_t) ch * HK + qh) * 4 * GCH * S;
|
||||
#pragma unroll
|
||||
for (int m = 0; m < NP; ++m) {
|
||||
const int p = tid + 256 * m, t = p / (S / 4), r = (p % (S / 4)) * 4;
|
||||
const int o = t * GTC_KP + r;
|
||||
gtc_split_store4(im + o, im + GCH * GTC_KP + o, kv[m], 256.0f);
|
||||
gtc_split_store4(im + 2 * GCH * GTC_KP + o, im + 3 * GCH * GTC_KP + o, qv[m], 256.0f);
|
||||
gtc_split_store4(img + t * S + r, img + GCH * S + t * S + r, kv[m], 256.0f);
|
||||
gtc_split_store4(img + 2 * GCH * S + t * S + r, img + 3 * GCH * S + t * S + r, qv[m], 256.0f);
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
{ // the Gram products: warp w takes product w >> 2 (k_t.k_i, q_t.k_i), rows 16 ((w >> 1) & 1).. (the A tile, by ldmatrix as a
|
||||
// row-major [t][r] 16 x 16), columns 16 (w & 1).. (two n-tiles: B = k^T, stored [n][k] = the k rows, by ldmatrix as the scan's
|
||||
// gtc_prod_state); the accumulators come out x 2^16
|
||||
const int pr = warp >> 2, mt = (warp >> 1) & 1, np = warp & 1;
|
||||
const uint16_t* ah_ = im + 2 * pr * GCH * GTC_KP + (16 * mt + (lane & 7) + 8 * ((lane >> 3) & 1)) * GTC_KP + 8 * (lane >> 4);
|
||||
const uint16_t* bh_ = im + (16 * np + 8 * (lane >> 4) + (lane & 7)) * GTC_KP + 8 * ((lane >> 3) & 1);
|
||||
float c[2][4] = {};
|
||||
#pragma unroll
|
||||
for (int kk = 0; kk < S / 16; ++kk) {
|
||||
uint32_t ah[4], al[4], bh[4], bl[4];
|
||||
gtc_ldsm_x4(ah, ah_ + 16 * kk);
|
||||
gtc_ldsm_x4(al, ah_ + GCH * GTC_KP + 16 * kk);
|
||||
gtc_ldsm_x4(bh, bh_ + 16 * kk);
|
||||
gtc_ldsm_x4(bl, bh_ + GCH * GTC_KP + 16 * kk);
|
||||
gtc_mma3_f16(c[0], ah, al, bh[0], bh[1], bl[0], bl[1]);
|
||||
gtc_mma3_f16(c[1], ah, al, bh[2], bh[3], bl[2], bl[3]);
|
||||
}
|
||||
float* g = pr ? sqk : skk;
|
||||
const int gid = lane >> 2, tig = lane & 3;
|
||||
#pragma unroll
|
||||
for (int jj = 0; jj < 2; ++jj)
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
const int t = 16 * mt + gid + 8 * (q >> 1), ii = 16 * np + 8 * jj + 2 * tig + (q & 1);
|
||||
g[t * GTP + ii] = ii <= t ? c[jj][q] * gtc_pow2(-16) : 0.0f;
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if (warp >= 2 * VPK) return;
|
||||
#pragma unroll
|
||||
for (int o = 1; o < 32; o <<= 1) {
|
||||
const float u = __shfl_up_sync(0xffffffffu, gam, o);
|
||||
if (lane >= o) gam += u;
|
||||
}
|
||||
if (warp >= VPK) { // P = exp(gamma_t - gamma_i) q_t.k_i (i <= t) x 2^8 as f16 hi / lo; the scalars
|
||||
uint16_t* Ph = pi + ((int64_t) ch * HV + vh) * 2 * GCH * GCH;
|
||||
uint16_t* Pl = Ph + GCH * GCH;
|
||||
#pragma unroll
|
||||
for (int t = 0; t < GCH; ++t) {
|
||||
const float gt = __shfl_sync(0xffffffffu, gam, t);
|
||||
const float p = (i <= t ? expf(gt - gam) * sqk[t * GTP + i] : 0.0f) * 256.0f;
|
||||
const __half hi = __float2half_rn(p);
|
||||
Ph[t * GCH + i] = __half_as_ushort(hi);
|
||||
Pl[t * GCH + i] = __half_as_ushort(__float2half_rn(p - __half2float(hi)));
|
||||
}
|
||||
const float gL = __shfl_sync(0xffffffffu, gam, GCH - 1);
|
||||
sc[((int64_t) ch * HV + vh) * GCH + i] = make_float4(b, expf(gam), expf(gL - gam), gam);
|
||||
return;
|
||||
}
|
||||
float* a = sa + j * GCH * GTP;
|
||||
#pragma unroll
|
||||
for (int t = 0; t < GCH; ++t) {
|
||||
const float gt = __shfl_sync(0xffffffffu, gam, t), bt = __shfl_sync(0xffffffffu, b, t);
|
||||
a[t * GTP + i] = i < t ? bt * expf(gt - gam) * skk[t * GTP + i] : (i == t ? 1.0f : 0.0f);
|
||||
}
|
||||
__syncwarp();
|
||||
// T = (I + A)^-1 by forward substitution, row by row: T[t][i] = -sum_{k < t} A[t][k] T[k][i] over the finished rows (diagonal 1,
|
||||
// zeros above it: the terms k < i add an exact 0, so the same bits as summing from k = i). Lane i keeps its column T[.][i] in
|
||||
// registers, so a row needs only A's row t (a broadcast load a term) and A is never written: no store and no __syncwarp a row
|
||||
float tv[GCH];
|
||||
tv[0] = i == 0 ? 1.0f : 0.0f;
|
||||
#pragma unroll
|
||||
for (int t = 1; t < GCH; ++t) {
|
||||
float v = 0.0f;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < t; ++k) v = fmaf(-a[t * GTP + k], tv[k], v);
|
||||
tv[t] = i < t ? v : (i == t ? 1.0f : 0.0f);
|
||||
}
|
||||
// T's images x 2^et (its largest entry in [2^14, 2^15), as the scan scales its own operands)
|
||||
float mt4[4] = {};
|
||||
#pragma unroll
|
||||
for (int t = 0; t < GCH; ++t) mt4[t & 3] = fmaxf(mt4[t & 3], fabsf(tv[t]));
|
||||
const int et = gtc_scale_exp(gtc_warp_max(fmaxf(fmaxf(mt4[0], mt4[1]), fmaxf(mt4[2], mt4[3]))));
|
||||
const float sT = gtc_pow2(et);
|
||||
uint16_t* Th = ti + ((int64_t) ch * HV + vh) * 2 * GCH * GCH;
|
||||
uint16_t* Tl = Th + GCH * GCH;
|
||||
#pragma unroll
|
||||
for (int t = 0; t < GCH; ++t) {
|
||||
const float x = tv[t] * sT;
|
||||
const __half hi = __float2half_rn(x);
|
||||
Th[t * GCH + i] = __half_as_ushort(hi);
|
||||
Tl[t * GCH + i] = __half_as_ushort(__float2half_rn(x - __half2float(hi)));
|
||||
}
|
||||
if (i == 0) te[(int64_t) ch * HV + vh] = gtc_pow2(-et);
|
||||
}
|
||||
|
||||
// ---- the two scan entries. Arguments: state_in, state_out, h, ti, te, sc, kq, pi, oc_out, t0 (first token of the super-block), nch (its
|
||||
// chunks), T (tokens of the whole prompt chunk), witness.
|
||||
extern "C" __global__ void __launch_bounds__(GTC_CW * 32, 1) leleka_gdn_tc_scan_t1(
|
||||
const float* state_in, float* state_out, const float* h, const uint16_t* ti, const float* te, const float4* sc,
|
||||
const uint16_t* kq, const uint16_t* pi, float* oc_out, int64_t t0, int nch, int64_t T, unsigned* witness) {
|
||||
gtc_scan_body<1>(state_in, state_out, h, ti, te, sc, kq, pi, oc_out, t0, nch, T, witness);
|
||||
}
|
||||
extern "C" __global__ void __launch_bounds__(GTC_CW * 32, 1) leleka_gdn_tc_scan_t2(
|
||||
const float* state_in, float* state_out, const float* h, const uint16_t* ti, const float* te, const float4* sc,
|
||||
const uint16_t* kq, const uint16_t* pi, float* oc_out, int64_t t0, int nch, int64_t T, unsigned* witness) {
|
||||
gtc_scan_body<2>(state_in, state_out, h, ti, te, sc, kq, pi, oc_out, t0, nch, T, witness);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,299 @@
|
||||
//! Fixed asset `gdn_prefill_tc.cu` (EXPERIMENTAL, LOSSY, off by default): the prompt GDN recurrence as a chunked
|
||||
//! scan on the tensor cores, a port of Strata upstream `src/prefill/gdn_tc.cuh` (step-ledger row U1).
|
||||
//!
|
||||
//! This module is the host side that needs no device: the sealed PTX with its pin, the launch geometry, the scratch
|
||||
//! layout, the decision table "may this run take the tensor-core scan?" and the launch list of one prompt chunk. The
|
||||
//! device owner (`gdn_prompt_device`) loads the module, reads the device and executes the list.
|
||||
//!
|
||||
//! The scan is NOT bitwise equal to `leleka_prefill_gdn_rec_kh` (the reduction order changes; every product is an f16x3
|
||||
//! split on `mma.sync`). Whether it may ever be a default is decided by the lossy gate of docs/quality-gate.md.
|
||||
use crate::kar_decode_levels::{KarDecodeError, PtxPin, admit_ptx};
|
||||
use crate::ple_batch_ffi::{BatchArg, DeviceGeometry};
|
||||
use crate::{Error, Result, ffi::BufferHandle};
|
||||
use std::ffi::CStr;
|
||||
|
||||
/// The PTX plus the single ABI NUL, like every other fixed asset.
|
||||
pub(crate) static PTX: &[u8] = concat!(include_str!("gdn_prefill_tc.ptx"), "\0").as_bytes();
|
||||
/// Module entry order: the index passed to `KernelModule::launch_dynamic`.
|
||||
pub(crate) const ENTRIES: &[&CStr] = &[c"leleka_gdn_tc_prep", c"leleka_gdn_tc_scan_t1", c"leleka_gdn_tc_scan_t2"];
|
||||
const PREP: usize = 0;
|
||||
const SCAN_ONE_TILE: usize = 1;
|
||||
const SCAN_TWO_TILES: usize = 2;
|
||||
|
||||
/// Frozen by `scripts/gpu-bringup/reseal_own.py` after `compile_assets.py` (extra-seal-plan.json, group
|
||||
/// gdn-prefill-tc).
|
||||
pub(crate) const PIN: PtxPin = PtxPin {
|
||||
source_sha256: [
|
||||
140, 121, 176, 81, 97, 167, 229, 92, 123, 79, 111, 249, 182, 76, 245, 54, 123, 180, 179, 251, 37, 236, 33, 38,
|
||||
136, 203, 250, 118, 228, 111, 207, 65,
|
||||
],
|
||||
ptx_sha256: [
|
||||
84, 91, 216, 169, 217, 214, 20, 131, 163, 13, 60, 51, 198, 226, 196, 128, 60, 146, 243, 71, 219, 96, 55, 223,
|
||||
64, 7, 233, 68, 123, 153, 107, 33,
|
||||
],
|
||||
};
|
||||
pub(crate) fn admit() -> std::result::Result<(), KarDecodeError> {
|
||||
admit_ptx(PTX, &PIN)
|
||||
}
|
||||
|
||||
/// Tokens a chunk of the scan (the prep solves a lane per token).
|
||||
pub(crate) const CHUNK_TOKENS: usize = 32;
|
||||
/// Upstream `kGdnTcMin`: the prep and scan launches cost about 20 us, below this the sequential kernel wins.
|
||||
pub(crate) const MIN_TOKENS: usize = 128;
|
||||
const KEY_HEADS: usize = 16;
|
||||
const VALUE_HEADS: usize = 48;
|
||||
/// Dynamic shared memory of one scan block (`kTcScanSmemSplit`, the 99-KB plan) and of one prep block.
|
||||
pub(crate) const SCAN_SMEM: u32 = 97_808;
|
||||
pub(crate) const PREP_SMEM: u32 = 43_264;
|
||||
const PREP_THREADS: u32 = 256;
|
||||
/// Upstream `GSB / GCH`: chunks of one super-block at the frozen scratch of 60,305,408 bytes.
|
||||
pub(crate) const UPSTREAM_CHUNKS: usize = 64;
|
||||
/// Scratch bytes a chunk, in the order the kernels take them: T images, T scales, token scalars, k/q images, P images.
|
||||
const SCRATCH_PARTS: [usize; 5] = [
|
||||
VALUE_HEADS * 2 * CHUNK_TOKENS * CHUNK_TOKENS * 2,
|
||||
VALUE_HEADS * 4,
|
||||
VALUE_HEADS * CHUNK_TOKENS * 16,
|
||||
KEY_HEADS * 4 * CHUNK_TOKENS * 128 * 2,
|
||||
VALUE_HEADS * 2 * CHUNK_TOKENS * CHUNK_TOKENS * 2,
|
||||
];
|
||||
/// Scratch bytes a chunk (942,272).
|
||||
pub(crate) const SCRATCH_PER_CHUNK: usize =
|
||||
SCRATCH_PARTS[0] + SCRATCH_PARTS[1] + SCRATCH_PARTS[2] + SCRATCH_PARTS[3] + SCRATCH_PARTS[4];
|
||||
|
||||
/// Chunks of one super-block that a scratch of `bytes` holds, at most upstream's 64.
|
||||
pub(crate) fn chunks_fitting(bytes: usize) -> usize {
|
||||
(bytes / SCRATCH_PER_CHUNK).min(UPSTREAM_CHUNKS)
|
||||
}
|
||||
|
||||
/// Why a run does not take the scan; the device owner prints it once.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Refusal {
|
||||
NotRequested,
|
||||
/// The sealed image is sm_120: the compute capability major of the device is below 12.
|
||||
ComputeCapability(u32),
|
||||
/// Fewer multiprocessors than value heads: the scan would run in several waves.
|
||||
Multiprocessors(u32),
|
||||
/// The opt-in shared memory a block is below the plan's 97,808 bytes.
|
||||
SharedMemory(u32),
|
||||
/// The scratch holds no chunk.
|
||||
Scratch,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Refusal {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::NotRequested => write!(f, "not requested"),
|
||||
Self::ComputeCapability(major) => write!(f, "compute capability {major}.x, the sealed image is sm_120"),
|
||||
Self::Multiprocessors(n) => write!(f, "{n} multiprocessors, fewer than the {VALUE_HEADS} value heads"),
|
||||
Self::SharedMemory(n) => write!(f, "{n} bytes of shared memory a block, the plan needs {SCAN_SMEM}"),
|
||||
Self::Scratch => write!(f, "the scratch holds no chunk"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a device owner decided once: value tiles a head and chunks of a super-block.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct ScanPlan {
|
||||
tiles: u32,
|
||||
chunks: usize,
|
||||
}
|
||||
|
||||
/// The decision table. Upstream's runtime gate (compute capability >= 8, one multiprocessor per value head, shared
|
||||
/// memory) plus this repository's: the image is sealed for sm_120. Two value tiles a head on cards with at least
|
||||
/// twice as many multiprocessors as value heads (upstream 51567de1a: one wave of 96 blocks; an RTX A6000 with 84 SMs
|
||||
/// was 1.25x slower with two tiles, a card with 110 SMs 1.47x faster).
|
||||
pub(crate) fn plan(
|
||||
requested: bool,
|
||||
device: DeviceGeometry,
|
||||
scratch_bytes: usize,
|
||||
) -> std::result::Result<ScanPlan, Refusal> {
|
||||
if !requested {
|
||||
return Err(Refusal::NotRequested);
|
||||
}
|
||||
if device.cc_major < 12 {
|
||||
return Err(Refusal::ComputeCapability(device.cc_major));
|
||||
}
|
||||
if (device.multiprocessors as usize) < VALUE_HEADS {
|
||||
return Err(Refusal::Multiprocessors(device.multiprocessors));
|
||||
}
|
||||
if device.shared_optin < SCAN_SMEM {
|
||||
return Err(Refusal::SharedMemory(device.shared_optin));
|
||||
}
|
||||
let chunks = chunks_fitting(scratch_bytes);
|
||||
if chunks == 0 {
|
||||
return Err(Refusal::Scratch);
|
||||
}
|
||||
let tiles = if device.multiprocessors as usize >= 2 * VALUE_HEADS { 2 } else { 1 };
|
||||
Ok(ScanPlan { tiles, chunks })
|
||||
}
|
||||
|
||||
impl ScanPlan {
|
||||
/// Value tiles a head (1: 48 blocks of 256 threads, 2: 96 blocks of 128 threads).
|
||||
pub(crate) fn tiles(&self) -> u32 {
|
||||
self.tiles
|
||||
}
|
||||
/// Chunks of one super-block (the scratch holds this many).
|
||||
pub(crate) fn chunks(&self) -> usize {
|
||||
self.chunks
|
||||
}
|
||||
/// Per-run dispatch: a prompt chunk of `tokens` takes the scan from `MIN_TOKENS` on.
|
||||
pub(crate) fn takes(&self, tokens: usize) -> bool {
|
||||
tokens >= MIN_TOKENS
|
||||
}
|
||||
/// `(first token, chunks)` of every super-block of a run of `tokens`.
|
||||
pub(crate) fn super_blocks(&self, tokens: usize) -> Vec<(usize, usize)> {
|
||||
let span = self.chunks * CHUNK_TOKENS;
|
||||
(0..tokens.div_ceil(span)).map(|i| (i * span, (tokens - i * span).min(span).div_ceil(CHUNK_TOKENS))).collect()
|
||||
}
|
||||
/// Tests only: the same plan with `tiles` value tiles a head (1 or 2).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_tiles(self, tiles: u32) -> Self {
|
||||
Self { tiles, ..self }
|
||||
}
|
||||
/// Tests only: the same plan with super-blocks of `chunks` chunks (small values chain the state through many
|
||||
/// launches).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_chunks(self, chunks: usize) -> Self {
|
||||
Self { chunks, ..self }
|
||||
}
|
||||
fn scan_entry(&self) -> usize {
|
||||
if self.tiles == 2 { SCAN_TWO_TILES } else { SCAN_ONE_TILE }
|
||||
}
|
||||
/// `(grid, block)` of the scan launch.
|
||||
pub(crate) fn scan_shape(&self) -> (u32, u32) {
|
||||
let heads = VALUE_HEADS as u32;
|
||||
if self.tiles == 2 { (heads * 2, 128) } else { (heads, 256) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The buffers of one run: the recurrence's own interface (as `leleka_prefill_gdn_rec_kh`) and the scratch.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct RecurrenceIo {
|
||||
pub(crate) state_in: BufferHandle,
|
||||
pub(crate) state_out: BufferHandle,
|
||||
pub(crate) h: BufferHandle,
|
||||
pub(crate) gate: BufferHandle,
|
||||
pub(crate) beta: BufferHandle,
|
||||
pub(crate) y: BufferHandle,
|
||||
pub(crate) witness: BufferHandle,
|
||||
pub(crate) scratch: BufferHandle,
|
||||
}
|
||||
|
||||
/// One kernel launch of the list: module entry, grid and block (1-D), dynamic shared memory and arguments.
|
||||
pub(crate) struct TcLaunch {
|
||||
pub(crate) entry: usize,
|
||||
pub(crate) grid: u32,
|
||||
pub(crate) block: u32,
|
||||
pub(crate) smem: u32,
|
||||
pub(crate) args: Vec<BatchArg>,
|
||||
}
|
||||
|
||||
/// The five sub-buffers of the scratch, `chunks` chunks each.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Scratch {
|
||||
ti: BufferHandle,
|
||||
te: BufferHandle,
|
||||
sc: BufferHandle,
|
||||
kq: BufferHandle,
|
||||
pi: BufferHandle,
|
||||
}
|
||||
|
||||
impl Scratch {
|
||||
/// Carves a scratch allocation of `len` bytes starting at `base`.
|
||||
fn carve(base: BufferHandle, len: usize, chunks: usize) -> Result<Self> {
|
||||
let mut offset = 0;
|
||||
let mut parts = [base; 5];
|
||||
for (part, bytes) in parts.iter_mut().zip(SCRATCH_PARTS) {
|
||||
let bytes = bytes * chunks;
|
||||
*part = base.checked_subspan(len, offset, bytes)?;
|
||||
offset += bytes;
|
||||
}
|
||||
let [ti, te, sc, kq, pi] = parts;
|
||||
Ok(Self { ti, te, sc, kq, pi })
|
||||
}
|
||||
}
|
||||
|
||||
/// One super-block: first token, chunks, and the tokens of the whole run.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Block {
|
||||
t0: i64,
|
||||
chunks: i32,
|
||||
tokens: i64,
|
||||
}
|
||||
|
||||
fn prep_launch(io: &RecurrenceIo, s: &Scratch, b: Block) -> TcLaunch {
|
||||
let a = BatchArg::Address;
|
||||
TcLaunch {
|
||||
entry: PREP,
|
||||
grid: b.chunks as u32 * KEY_HEADS as u32,
|
||||
block: PREP_THREADS,
|
||||
smem: PREP_SMEM,
|
||||
args: vec![
|
||||
a(io.h),
|
||||
a(io.gate),
|
||||
a(io.beta),
|
||||
a(s.ti),
|
||||
a(s.te),
|
||||
a(s.sc),
|
||||
a(s.kq),
|
||||
a(s.pi),
|
||||
BatchArg::I64(b.t0),
|
||||
BatchArg::I64(b.tokens),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
fn scan_launch(plan: &ScanPlan, (io, s): (&RecurrenceIo, &Scratch), (state_in, b): (BufferHandle, Block)) -> TcLaunch {
|
||||
let a = BatchArg::Address;
|
||||
let (grid, block) = plan.scan_shape();
|
||||
TcLaunch {
|
||||
entry: plan.scan_entry(),
|
||||
grid,
|
||||
block,
|
||||
smem: SCAN_SMEM,
|
||||
args: vec![
|
||||
a(state_in),
|
||||
a(io.state_out),
|
||||
a(io.h),
|
||||
a(s.ti),
|
||||
a(s.te),
|
||||
a(s.sc),
|
||||
a(s.kq),
|
||||
a(s.pi),
|
||||
a(io.y),
|
||||
BatchArg::I64(b.t0),
|
||||
BatchArg::I32(b.chunks),
|
||||
BatchArg::I64(b.tokens),
|
||||
a(io.witness),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/// The launches of one prompt chunk of `tokens` tokens (the caller asks `ScanPlan::takes` first; the kernels
|
||||
/// themselves run any `tokens >= 1`, which the parity test uses): per super-block the prep and the scan, in stream
|
||||
/// order. The first scan reads `state_in`, the later ones the `state_out` the scan before wrote (in place: a block
|
||||
/// reads and writes only its own columns). The witness word is raised by every scan whose final state is not finite.
|
||||
pub(crate) fn launches(
|
||||
plan: &ScanPlan,
|
||||
io: &RecurrenceIo,
|
||||
(scratch_len, tokens): (usize, usize),
|
||||
) -> Result<Vec<TcLaunch>> {
|
||||
if tokens == 0 || scratch_len < SCRATCH_PER_CHUNK * plan.chunks {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let scratch = Scratch::carve(io.scratch, scratch_len, plan.chunks)?;
|
||||
let blocks = plan.super_blocks(tokens);
|
||||
let mut list = Vec::new();
|
||||
list.try_reserve_exact(2 * blocks.len()).map_err(|_| Error::HostAllocation)?;
|
||||
for (index, (t0, chunks)) in blocks.into_iter().enumerate() {
|
||||
let b = Block { t0: t0 as i64, chunks: chunks as i32, tokens: tokens as i64 };
|
||||
list.push(prep_launch(io, &scratch, b));
|
||||
let from = if index == 0 { io.state_in } else { io.state_out };
|
||||
list.push(scan_launch(plan, (io, &scratch), (from, b)));
|
||||
}
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "gdn_prefill_tc_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,201 @@
|
||||
//! Host tests of `gdn_prefill_tc`: layout, launch parameters, the dispatch decision table and the launch list.
|
||||
//! No device.
|
||||
use super::*;
|
||||
|
||||
fn device(cc_major: u32, multiprocessors: u32, shared_optin: u32) -> DeviceGeometry {
|
||||
DeviceGeometry { cc_major, multiprocessors, shared_optin }
|
||||
}
|
||||
/// The RTX 5090: compute capability 12.0, 170 SMs, 101,376 bytes of opt-in shared memory a block.
|
||||
const RTX_5090: DeviceGeometry = DeviceGeometry { cc_major: 12, multiprocessors: 170, shared_optin: 101_376 };
|
||||
/// The prompt device's dequantization scratch the scan runs in.
|
||||
const SCRATCH: usize = 52_428_800;
|
||||
|
||||
fn handle(address: u64) -> BufferHandle {
|
||||
BufferHandle::synthetic(address)
|
||||
}
|
||||
fn io() -> RecurrenceIo {
|
||||
let [state_in, state_out, h, gate, beta, y, witness, scratch] =
|
||||
[0x1000u64, 0x2000, 0x3000, 0x4000, 0x5000, 0x6000, 0x7000, 0x1_0000_0000].map(handle);
|
||||
RecurrenceIo { state_in, state_out, h, gate, beta, y, witness, scratch }
|
||||
}
|
||||
fn address(arg: &BatchArg) -> u64 {
|
||||
match arg {
|
||||
BatchArg::Address(h) => h.qwen_address(),
|
||||
_ => panic!("not an address"),
|
||||
}
|
||||
}
|
||||
fn int(arg: &BatchArg) -> i64 {
|
||||
match arg {
|
||||
BatchArg::I64(x) => *x,
|
||||
BatchArg::I32(x) => i64::from(*x),
|
||||
_ => panic!("not an integer"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_shared_memory_and_scratch_plans_are_the_frozen_ones() {
|
||||
// kTcScanSmemSplit: 2 (4 GCH KP 2 + GCH 16) + GCH VP 4 + 4 GCH PP 2 + 16,
|
||||
// with KP = 136, VP = 132, PP = 40, GCH = 32
|
||||
assert_eq!(2 * (4 * 32 * 136 * 2 + 32 * 16) + 32 * 132 * 4 + 4 * 32 * 40 * 2 + 16, SCAN_SMEM as usize);
|
||||
assert_eq!(4 * 32 * 136 * 2 + 2 * 32 * 33 * 4, PREP_SMEM as usize);
|
||||
// the 99-KB opt-in of sm_86 / sm_89 / sm_120 holds the scan
|
||||
const { assert!(SCAN_SMEM <= 101_376 && PREP_SMEM <= 48 * 1024) };
|
||||
assert_eq!(SCRATCH_PER_CHUNK, 942_272);
|
||||
assert_eq!(SCRATCH_PER_CHUNK * UPSTREAM_CHUNKS, 60_305_408, "upstream's frozen scratch for HV 48 / HK 16");
|
||||
// cp.async copies 16-byte pieces: every part starts on a 16-byte boundary for any chunk count (the 4-byte scales
|
||||
// are 192 bytes a chunk)
|
||||
for chunks in 1..=UPSTREAM_CHUNKS {
|
||||
let mut offset = 0;
|
||||
for (i, bytes) in SCRATCH_PARTS.iter().enumerate() {
|
||||
assert_eq!(offset % 16, 0, "part {i} at {offset} with {chunks} chunks");
|
||||
offset += bytes * chunks;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_source_names_the_same_plans() {
|
||||
let source = include_str!("gdn_prefill_tc.cu");
|
||||
for needle in
|
||||
["kTcScanSmemSplit == 97808", "kTcPrepSmem == 43264", "constexpr int S = 128, HK = 16, HV = 48, C = 10240"]
|
||||
{
|
||||
assert!(source.contains(needle), "gdn_prefill_tc.cu lacks {needle:?}");
|
||||
}
|
||||
for entry in ENTRIES {
|
||||
let name = entry.to_str().expect("ascii");
|
||||
assert!(source.contains(name), "gdn_prefill_tc.cu lacks the entry {name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_dequantization_scratch_holds_55_chunks_so_the_scan_costs_no_extra_memory() {
|
||||
assert_eq!(chunks_fitting(SCRATCH), 55);
|
||||
assert_eq!(chunks_fitting(60_305_408), UPSTREAM_CHUNKS);
|
||||
assert_eq!(chunks_fitting(2 * 60_305_408), UPSTREAM_CHUNKS);
|
||||
assert_eq!(chunks_fitting(SCRATCH_PER_CHUNK - 1), 0);
|
||||
const { assert!(55 * SCRATCH_PER_CHUNK <= SCRATCH && 56 * SCRATCH_PER_CHUNK > SCRATCH) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_decision_table_refuses_every_card_the_plan_does_not_fit() {
|
||||
let plan_of = |d, bytes| plan(true, d, bytes);
|
||||
assert_eq!(plan(false, RTX_5090, SCRATCH), Err(Refusal::NotRequested), "off unless asked");
|
||||
assert_eq!(
|
||||
plan_of(device(8, 170, 101_376), SCRATCH),
|
||||
Err(Refusal::ComputeCapability(8)),
|
||||
"sm_86 has no companion image"
|
||||
);
|
||||
assert_eq!(plan_of(device(11, 170, 101_376), SCRATCH), Err(Refusal::ComputeCapability(11)));
|
||||
assert_eq!(
|
||||
plan_of(device(12, 47, 101_376), SCRATCH),
|
||||
Err(Refusal::Multiprocessors(47)),
|
||||
"fewer SMs than value heads"
|
||||
);
|
||||
assert_eq!(plan_of(device(12, 170, SCAN_SMEM - 1), SCRATCH), Err(Refusal::SharedMemory(SCAN_SMEM - 1)));
|
||||
assert_eq!(plan_of(device(12, 170, 48 * 1024), SCRATCH), Err(Refusal::SharedMemory(48 * 1024)), "no opt-in");
|
||||
assert_eq!(plan_of(RTX_5090, SCRATCH_PER_CHUNK - 1), Err(Refusal::Scratch));
|
||||
assert!(plan_of(device(12, 48, SCAN_SMEM), SCRATCH).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_value_tiles_a_head_from_96_multiprocessors() {
|
||||
let tiles = |sms| plan(true, device(12, sms, 101_376), SCRATCH).expect("plan").tiles();
|
||||
assert_eq!([tiles(48), tiles(84), tiles(95), tiles(96), tiles(110), tiles(170)], [1, 1, 1, 2, 2, 2]);
|
||||
let five_thousand_ninety = plan(true, RTX_5090, SCRATCH).expect("plan");
|
||||
assert_eq!((five_thousand_ninety.tiles(), five_thousand_ninety.chunks()), (2, 55));
|
||||
assert_eq!(five_thousand_ninety.scan_shape(), (96, 128), "96 blocks of 4 warps, one wave on 170 SMs");
|
||||
assert_eq!(plan(true, device(12, 84, 101_376), SCRATCH).expect("plan").scan_shape(), (48, 256));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_takes_the_scan_from_128_tokens_and_walks_super_blocks_of_the_scratch() {
|
||||
let p = plan(true, RTX_5090, SCRATCH).expect("plan");
|
||||
assert!(!p.takes(1) && !p.takes(127) && p.takes(128) && p.takes(8192));
|
||||
assert_eq!(p.super_blocks(128), [(0, 4)]);
|
||||
assert_eq!(p.super_blocks(129), [(0, 5)], "a partial chunk is a chunk");
|
||||
assert_eq!(p.super_blocks(1760), [(0, 55)]);
|
||||
assert_eq!(p.super_blocks(1761), [(0, 55), (1760, 1)]);
|
||||
let all = p.super_blocks(8192);
|
||||
assert_eq!(all.len(), 5);
|
||||
assert_eq!(all.iter().map(|b| b.1).sum::<usize>(), 256, "8192 tokens are 256 chunks");
|
||||
assert_eq!(all[4], (7040, 36));
|
||||
for t in [128usize, 200, 1759, 1760, 1761, 3520, 3521, 4099, 8191, 8192] {
|
||||
let blocks = p.super_blocks(t);
|
||||
assert_eq!(blocks[0].0, 0);
|
||||
for pair in blocks.windows(2) {
|
||||
assert_eq!(pair[1].0, pair[0].0 + pair[0].1 * CHUNK_TOKENS, "t={t}: contiguous");
|
||||
}
|
||||
let (last_t0, last) = *blocks.last().unwrap();
|
||||
assert!(last_t0 < t && last_t0 + last * CHUNK_TOKENS >= t && last_t0 + (last - 1) * CHUNK_TOKENS < t, "t={t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launch_list_orders_prep_and_scan_and_chains_the_state() {
|
||||
let p = plan(true, RTX_5090, SCRATCH).expect("plan");
|
||||
let io = io();
|
||||
let list = launches(&p, &io, (SCRATCH, 8192)).expect("launches");
|
||||
assert_eq!(list.len(), 10, "a prep and a scan for each of the 5 super-blocks");
|
||||
for (i, pair) in list.chunks(2).enumerate() {
|
||||
let (prep, scan) = (&pair[0], &pair[1]);
|
||||
assert_eq!((prep.entry, prep.block, prep.smem, prep.args.len()), (0, 256, PREP_SMEM, 10));
|
||||
assert_eq!(prep.grid as usize, [55, 55, 55, 55, 36][i] * 16, "a block a (chunk, key head)");
|
||||
assert_eq!((scan.entry, scan.grid, scan.block, scan.smem, scan.args.len()), (2, 96, 128, SCAN_SMEM, 13));
|
||||
// state: the first scan reads the prior state, the others what the scan before wrote; all write state_out
|
||||
assert_eq!(address(&scan.args[0]), if i == 0 { 0x1000 } else { 0x2000 });
|
||||
assert_eq!(address(&scan.args[1]), 0x2000);
|
||||
assert_eq!(int(&scan.args[9]), (i * 1760) as i64, "first token of the super-block");
|
||||
assert_eq!(int(&scan.args[10]), [55, 55, 55, 55, 36][i]);
|
||||
assert_eq!(int(&scan.args[11]), 8192, "tokens of the whole run");
|
||||
assert_eq!(address(&scan.args[12]), 0x7000, "the state witness word");
|
||||
assert_eq!(address(&scan.args[8]), 0x6000, "the readout buffer");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launch_list_stays_inside_the_scratch_and_refuses_what_does_not_fit() {
|
||||
let p = plan(true, RTX_5090, SCRATCH).expect("plan");
|
||||
let io = io();
|
||||
let list = launches(&p, &io, (SCRATCH, 4096)).expect("launches");
|
||||
let base = 0x1_0000_0000u64;
|
||||
let mut parts: Vec<(u64, usize)> = list[0].args[3..8].iter().map(address).map(|a| (a, 0)).collect();
|
||||
parts.iter_mut().zip(SCRATCH_PARTS).for_each(|(p, bytes)| p.1 = bytes * 55);
|
||||
assert_eq!(parts[0].0, base, "T images first");
|
||||
for pair in parts.windows(2) {
|
||||
assert_eq!(pair[1].0, pair[0].0 + pair[0].1 as u64, "parts follow each other");
|
||||
}
|
||||
let end = parts[4].0 + parts[4].1 as u64;
|
||||
assert!(end - base <= SCRATCH as u64, "the five parts end at {} of {SCRATCH}", end - base);
|
||||
assert!(launches(&p, &io, (SCRATCH, 0)).is_err(), "an empty run launches nothing");
|
||||
assert_eq!(
|
||||
launches(&p, &io, (SCRATCH, 1)).expect("one token").len(),
|
||||
2,
|
||||
"the kernels run any length; takes() is the dispatch"
|
||||
);
|
||||
assert!(launches(&p, &io, (SCRATCH - 1_000_000, 4096)).is_err(), "a scratch shorter than the plan's chunks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sealed_image_is_pinned_and_exports_the_three_entries() {
|
||||
assert!(admit().is_ok(), "gdn_prefill_tc.ptx must match PIN (scripts/gpu-bringup/reseal_own.py)");
|
||||
let ptx = std::str::from_utf8(&PTX[..PTX.len() - 1]).expect("ascii");
|
||||
assert!(ptx.lines().any(|l| l == ".target sm_120") && ptx.lines().any(|l| l == ".address_size 64"));
|
||||
for entry in ENTRIES {
|
||||
let name = entry.to_str().expect("ascii");
|
||||
assert!(ptx.contains(&format!(".visible .entry {name}(")), "{name}");
|
||||
}
|
||||
assert_eq!(ptx.matches(".entry ").count(), ENTRIES.len(), "no other kernel in the asset");
|
||||
assert!(!ptx.contains("UNSEALED"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_super_blocks_chain_the_state_through_state_out() {
|
||||
let p = plan(true, RTX_5090, SCRATCH).expect("plan").with_chunks(3).with_tiles(1);
|
||||
assert_eq!(p.super_blocks(200), [(0, 3), (96, 3), (192, 1)]);
|
||||
let list = launches(&p, &io(), (SCRATCH, 200)).expect("launches");
|
||||
let scans: Vec<_> = list.iter().filter(|l| l.entry == 1).collect();
|
||||
assert_eq!(scans.len(), 3);
|
||||
assert_eq!(scans.iter().map(|l| (l.grid, l.block)).collect::<Vec<_>>(), [(48, 256); 3]);
|
||||
assert_eq!(scans.iter().map(|l| address(&l.args[0])).collect::<Vec<_>>(), [0x1000, 0x2000, 0x2000]);
|
||||
assert!(scans.iter().all(|l| address(&l.args[1]) == 0x2000), "every scan writes state_out");
|
||||
}
|
||||
@@ -18,8 +18,21 @@ pub struct OriginalGdnPromptDevice<'ctx> {
|
||||
history: [Option<DeviceBuffer<'ctx>>; 2],
|
||||
/// `prefill_stage.cu`: element-parallel weight dequantization and the kernels with their guards folded in.
|
||||
stage: Option<KernelModule>,
|
||||
options: GdnPromptOptions,
|
||||
/// The EXPERIMENTAL tensor-core scan of the recurrence (`gdn_prefill_tc.cu`): off unless `options` ask, decided
|
||||
/// once.
|
||||
tensor_core: TensorCoreState,
|
||||
failed: bool,
|
||||
}
|
||||
/// What the operator chose for the prompt GDN device. Every field is off by default.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct GdnPromptOptions {
|
||||
/// `LELEKA_PREFILL_GDN_TC` (EXPERIMENTAL, LOSSY): runs of 128 tokens and more take the chunked tensor-core scan
|
||||
/// of the recurrence when the device fits it (sm_120, 48 or more SMs, 97,808 bytes of shared memory a block);
|
||||
/// anything else keeps the sequential kernel. Not bitwise equal to it; the lossy gate of docs/quality-gate.md
|
||||
/// decides.
|
||||
pub tensor_core_scan: bool,
|
||||
}
|
||||
/// Actual complete role owners; source/row/current prior are authenticated by runtime.
|
||||
pub struct OriginalGdnPromptWeights<'w, 'ctx> {
|
||||
pub matrices: [&'w DeviceBuffer<'ctx>; 5], // QKV,Z,Out,Alpha,Beta
|
||||
@@ -57,6 +70,14 @@ enum DeviceCommand {
|
||||
block: u32,
|
||||
args: KernelArguments,
|
||||
},
|
||||
/// A kernel of the experimental tensor-core scan module (1-D grid, dynamic shared memory).
|
||||
TensorCore {
|
||||
entry: usize,
|
||||
grid: u32,
|
||||
block: u32,
|
||||
smem: u32,
|
||||
args: KernelArguments,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -67,5 +88,6 @@ mod stage_gpu_tests;
|
||||
mod context;
|
||||
#[path = "gdn_prompt_device/original_gdn_prompt_device.rs"]
|
||||
mod original_gdn_prompt_device;
|
||||
use original_gdn_prompt_device::TensorCoreState;
|
||||
#[path = "gdn_prompt_device/original_gdn_prompt_device_drop.rs"]
|
||||
mod original_gdn_prompt_device_drop;
|
||||
|
||||
@@ -9,6 +9,15 @@ impl<'ctx> Context<'ctx> {
|
||||
capacity: usize,
|
||||
profile: crate::GrNativeProfile,
|
||||
) -> Result<OriginalGdnPromptDevice<'ctx>> {
|
||||
OriginalGdnPromptDevice::new(self, capacity, profile)
|
||||
self.original_gdn_prompt_device_with(capacity, profile, GdnPromptOptions::default())
|
||||
}
|
||||
/// `original_gdn_prompt_device` with the operator's options (all off by default).
|
||||
pub fn original_gdn_prompt_device_with(
|
||||
&'ctx self,
|
||||
capacity: usize,
|
||||
profile: crate::GrNativeProfile,
|
||||
options: GdnPromptOptions,
|
||||
) -> Result<OriginalGdnPromptDevice<'ctx>> {
|
||||
OriginalGdnPromptDevice::new(self, (capacity, profile), options)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,5 +15,8 @@ mod original_gdn_prompt_device_drain;
|
||||
mod prompt_block_produce;
|
||||
#[path = "original_gdn_prompt_device/prompt_command_list.rs"]
|
||||
mod prompt_command_list;
|
||||
#[path = "original_gdn_prompt_device/prompt_tensor_core_scan.rs"]
|
||||
mod prompt_tensor_core_scan;
|
||||
#[allow(unused_imports)]
|
||||
use gdn_prompt_run_buffer_binder::{Binder, Carve, Carved, Handles, Phase};
|
||||
pub(super) use prompt_tensor_core_scan::TensorCoreState;
|
||||
|
||||
+4
-2
@@ -12,8 +12,8 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
}
|
||||
pub(in super::super) fn new(
|
||||
context: &'ctx Context<'ctx>,
|
||||
capacity: usize,
|
||||
profile: crate::GrNativeProfile,
|
||||
(capacity, profile): (usize, crate::GrNativeProfile),
|
||||
options: GdnPromptOptions,
|
||||
) -> Result<Self> {
|
||||
Self::admit_budget(context, capacity)?;
|
||||
let mut owner = Self {
|
||||
@@ -24,6 +24,8 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
scratch: None,
|
||||
history: [None, None],
|
||||
stage: None,
|
||||
options,
|
||||
tensor_core: TensorCoreState::new(options.tensor_core_scan),
|
||||
failed: false,
|
||||
};
|
||||
let operation = owner.open();
|
||||
|
||||
+2
-1
@@ -26,6 +26,7 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
if let Some(m) = self.stage.take() {
|
||||
result = combine(result, self.release_stage(m));
|
||||
}
|
||||
result = combine(result, self.release_tensor_core());
|
||||
if let Some(b) = self.batch.take() {
|
||||
result = combine(result, self.release_batch(b));
|
||||
}
|
||||
@@ -35,7 +36,7 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
}
|
||||
result
|
||||
}
|
||||
fn release_stage(&self, m: KernelModule) -> Result<()> {
|
||||
pub(super) fn release_stage(&self, m: KernelModule) -> Result<()> {
|
||||
if self.context.is_poisoned() {
|
||||
std::mem::forget(m);
|
||||
return Err(Error::ContextPoisoned);
|
||||
|
||||
+5
-1
@@ -40,6 +40,7 @@ fn command_label(cmd: &DeviceCommand) -> &'static str {
|
||||
DeviceCommand::Kernel { .. } => "kernel",
|
||||
DeviceCommand::Gemm { .. } => "gemm",
|
||||
DeviceCommand::Stage { .. } => "stage",
|
||||
DeviceCommand::TensorCore { .. } => "tensor-core",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +57,7 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
let host = self.execute(workspace, (commands, host), run)?;
|
||||
self.decode_run(host)
|
||||
}
|
||||
fn fail_context(&mut self) {
|
||||
pub(super) fn fail_context(&mut self) {
|
||||
self.failed = true;
|
||||
self.context.poison();
|
||||
self.context.retain_driver();
|
||||
@@ -172,6 +173,9 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
Some(module) => module.launch(*index, LinearLaunch::new(*grid, *block, blas.stream()), args),
|
||||
None => Err(Error::ContextPoisoned),
|
||||
},
|
||||
DeviceCommand::TensorCore { entry, grid, block, smem, args } => {
|
||||
self.launch_tensor_core(blas, (*entry, *grid, *block, *smem), args)
|
||||
}
|
||||
}
|
||||
}
|
||||
fn read_back(&self, hd: &Handles, host: &mut Host) -> Result<()> {
|
||||
|
||||
+1
@@ -19,6 +19,7 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
let t = read.rows();
|
||||
self.admit(&read, workspace, history)?;
|
||||
let handles = self.admit_handles(read.lease(), (workspace, t), &weights, (state, next_state))?;
|
||||
self.prepare_tensor_core()?;
|
||||
let commands = self.build_commands(&handles, weights.formats, t)?;
|
||||
let values = self.drain(workspace, commands, history, (&handles, t))?;
|
||||
Ok((read.from_completed_block(), values))
|
||||
|
||||
+47
-7
@@ -3,6 +3,7 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::gdn_prefill_tc as tc;
|
||||
|
||||
/// The commands of one run under construction.
|
||||
struct Cmds<'f, 'ctx> {
|
||||
@@ -14,6 +15,8 @@ struct Cmds<'f, 'ctx> {
|
||||
/// its FP16 image ride on the kernels that read or write those tensors (same status words).
|
||||
fused: bool,
|
||||
fast_dequant: bool,
|
||||
/// The experimental tensor-core scan of the recurrence, when the device owner admitted it.
|
||||
tensor_core: Option<tc::ScanPlan>,
|
||||
list: Vec<DeviceCommand>,
|
||||
}
|
||||
|
||||
@@ -44,10 +47,11 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
t: usize,
|
||||
) -> Result<Vec<DeviceCommand>> {
|
||||
let mut list = Vec::new();
|
||||
list.try_reserve_exact(48).map_err(|_| Error::HostAllocation)?;
|
||||
list.try_reserve_exact(64).map_err(|_| Error::HostAllocation)?;
|
||||
let funcs = self.batch.as_ref().ok_or(Error::ContextPoisoned)?.functions.as_ref();
|
||||
let funcs = funcs.ok_or(Error::ContextPoisoned)?;
|
||||
let mut c = Cmds::new(funcs, self.context, (*hd, t), list);
|
||||
c.tensor_core = self.tensor_core.plan();
|
||||
c.begin()?;
|
||||
c.projections(formats)?;
|
||||
c.gates()?;
|
||||
@@ -67,7 +71,8 @@ impl<'f, 'ctx> Cmds<'f, 'ctx> {
|
||||
) -> Self {
|
||||
let (hd, t) = run;
|
||||
let fused = crate::prefill_stage::fused_scans() && t > 64;
|
||||
Self { funcs, context, hd, t, fused, fast_dequant: crate::prefill_stage::fast_dequant(), list }
|
||||
let fast_dequant = crate::prefill_stage::fast_dequant();
|
||||
Self { funcs, context, hd, t, fused, fast_dequant, tensor_core: None, list }
|
||||
}
|
||||
fn kernel(&mut self, kernel: Kernel, geometry: ([u32; 3], [u32; 3]), args: &[ffi::KernelArg]) -> Result<()> {
|
||||
self.list.push(DeviceCommand::Kernel {
|
||||
@@ -260,16 +265,51 @@ impl<'f, 'ctx> Cmds<'f, 'ctx> {
|
||||
self.kernel(Kernel::L2, ([32, t as u32, 1], [128, 1, 1]), &args)?;
|
||||
self.scan(GdnBatchStage::Qk, h)
|
||||
}
|
||||
/// The state recurrence: the staged kernel when requested or usable, the original pipe kernel otherwise.
|
||||
/// The state recurrence: the experimental tensor-core scan when the device admitted it and the run is long
|
||||
/// enough, else the sequential kernels.
|
||||
fn recurrence(&mut self) -> Result<()> {
|
||||
let witness = self.word(GdnBatchStage::StateSteps)?;
|
||||
if crate::prefill_stage::fast_rec() || crate::prefill_stage::gdn_kh_usable(self.context) {
|
||||
self.recurrence_staged(witness);
|
||||
} else {
|
||||
self.recurrence_pipe(witness)?;
|
||||
if !self.recurrence_tensor_core(witness)? {
|
||||
self.recurrence_sequential(witness)?;
|
||||
}
|
||||
self.scan(GdnBatchStage::NextState, self.hd.sout)
|
||||
}
|
||||
/// The token-serial recurrence: the staged kernel when requested or usable, the original pipe kernel otherwise.
|
||||
fn recurrence_sequential(&mut self, witness: ffi::BufferHandle) -> Result<()> {
|
||||
if crate::prefill_stage::fast_rec() || crate::prefill_stage::gdn_kh_usable(self.context) {
|
||||
self.recurrence_staged(witness);
|
||||
Ok(())
|
||||
} else {
|
||||
self.recurrence_pipe(witness)
|
||||
}
|
||||
}
|
||||
/// `LELEKA_PREFILL_GDN_TC` (EXPERIMENTAL, LOSSY): the prep and scan launches of every super-block of the run, same
|
||||
/// interface as the kernels they replace (state in/out, readout `y`, the state witness). False: not taken.
|
||||
fn recurrence_tensor_core(&mut self, witness: ffi::BufferHandle) -> Result<bool> {
|
||||
let Some(plan) = self.tensor_core.filter(|p| p.takes(self.t)) else { return Ok(false) };
|
||||
let (hd, p) = (self.hd, self.hd.c.p);
|
||||
let io = tc::RecurrenceIo {
|
||||
state_in: hd.sin,
|
||||
state_out: hd.sout,
|
||||
h: p.h,
|
||||
gate: p.gate,
|
||||
beta: p.beta,
|
||||
y: p.y,
|
||||
witness,
|
||||
scratch: hd.scratch,
|
||||
};
|
||||
for l in tc::launches(&plan, &io, (SCRATCH, self.t))? {
|
||||
let args = KernelArguments::new(l.args);
|
||||
self.list.push(DeviceCommand::TensorCore {
|
||||
entry: l.entry,
|
||||
grid: l.grid,
|
||||
block: l.block,
|
||||
smem: l.smem,
|
||||
args,
|
||||
});
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
fn recurrence_staged(&mut self, witness: ffi::BufferHandle) {
|
||||
let kh = !crate::prefill_stage::fast_rec();
|
||||
let index = if kh { crate::prefill_stage::GDN_REC_KH } else { crate::prefill_stage::GDN_REC };
|
||||
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
//! The EXPERIMENTAL tensor-core scan of the prompt GDN recurrence, device-owner side (`LELEKA_PREFILL_GDN_TC`, off
|
||||
//! by default; kernels and launch list: `gdn_prefill_tc.rs` / `gdn_prefill_tc.cu`, ledger row U1). It loads the
|
||||
//! sealed module once, reads the device, and decides once whether this device takes the scan. Nothing here
|
||||
//! allocates: the scan runs in the dequantization scratch the owner already holds, which is idle during the
|
||||
//! recurrence (every command of a run is on one stream; the projections' dequantization wrote it before and the
|
||||
//! output projection's rewrites it after), so it costs no device memory and the prefill budget is unchanged.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::gdn_prefill_tc as tc;
|
||||
use crate::ple_batch_ffi::LinearLaunch;
|
||||
|
||||
/// The loaded module and the plan the device admitted.
|
||||
pub(in super::super) struct TensorCoreScan {
|
||||
pub(super) module: KernelModule,
|
||||
pub(super) plan: tc::ScanPlan,
|
||||
}
|
||||
|
||||
/// `Off` until asked for; `Pending` until the first run decides; then `Ready` or `Refused` for good.
|
||||
pub(in super::super) enum TensorCoreState {
|
||||
Off,
|
||||
Pending,
|
||||
Ready(TensorCoreScan),
|
||||
Refused,
|
||||
}
|
||||
|
||||
impl TensorCoreState {
|
||||
pub(in super::super) fn new(requested: bool) -> Self {
|
||||
if requested { Self::Pending } else { Self::Off }
|
||||
}
|
||||
/// The plan of the scan when this device runs it.
|
||||
pub(super) fn plan(&self) -> Option<tc::ScanPlan> {
|
||||
match self {
|
||||
Self::Ready(scan) => Some(scan.plan),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
/// Decides once, before the first command list of the device is recorded. A device that does not fit the scan
|
||||
/// (or a module that does not load) keeps the sequential kernel and says so once on stderr; only a context
|
||||
/// failure is an error.
|
||||
pub(in super::super) fn prepare_tensor_core(&mut self) -> Result<()> {
|
||||
if !matches!(self.tensor_core, TensorCoreState::Pending) {
|
||||
return Ok(());
|
||||
}
|
||||
let guard = self.context.enter()?;
|
||||
let probed = combine(Self::probe_tensor_core(), guard.finish());
|
||||
if probed.is_err() {
|
||||
self.fail_context();
|
||||
}
|
||||
self.tensor_core = match probed? {
|
||||
Ok(scan) => {
|
||||
Self::say_tensor_core_taken(&scan.plan);
|
||||
TensorCoreState::Ready(scan)
|
||||
}
|
||||
Err(why) => {
|
||||
eprintln!("leleka: LELEKA_PREFILL_GDN_TC=1 requested, the sequential GDN recurrence stays: {why}");
|
||||
TensorCoreState::Refused
|
||||
}
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
fn say_tensor_core_taken(plan: &tc::ScanPlan) {
|
||||
eprintln!(
|
||||
"leleka: LELEKA_PREFILL_GDN_TC=1 (EXPERIMENTAL, LOSSY): the prompt GDN recurrence of runs of {} tokens \
|
||||
and more runs on the tensor cores ({} value tile(s) a head, {} chunks of {} tokens a super-block)",
|
||||
tc::MIN_TOKENS,
|
||||
plan.tiles(),
|
||||
plan.chunks(),
|
||||
tc::CHUNK_TOKENS
|
||||
);
|
||||
}
|
||||
/// Loads the module and reads the device (the context is current). `Err(reason)` inside is a refusal, not a
|
||||
/// failure.
|
||||
fn probe_tensor_core() -> Result<std::result::Result<TensorCoreScan, String>> {
|
||||
if let Err(e) = tc::admit() {
|
||||
return Ok(Err(format!("the sealed PTX does not match its pin ({e:?})")));
|
||||
}
|
||||
let module = match KernelModule::load(tc::PTX, tc::ENTRIES) {
|
||||
Ok(m) => m,
|
||||
Err(e) => return Ok(Err(format!("the module does not load on this device ({e:?})"))),
|
||||
};
|
||||
let geometry = module.device_geometry()?;
|
||||
Ok(match tc::plan(true, geometry, SCRATCH) {
|
||||
Ok(plan) => Ok(TensorCoreScan { module, plan }),
|
||||
Err(refusal) => {
|
||||
module.close()?;
|
||||
Err(refusal.to_string())
|
||||
}
|
||||
})
|
||||
}
|
||||
/// Closes the scan's module (the owner's `close_inner`).
|
||||
pub(in super::super) fn release_tensor_core(&mut self) -> Result<()> {
|
||||
match std::mem::replace(&mut self.tensor_core, TensorCoreState::Refused) {
|
||||
TensorCoreState::Ready(scan) => self.release_stage(scan.module),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
/// One command of the scan on the batch stream: `(entry, grid, block, dynamic shared bytes)`.
|
||||
pub(in super::super) fn launch_tensor_core(
|
||||
&self,
|
||||
blas: &crate::ple_batch_ffi::Blas,
|
||||
(entry, grid, block, smem): (usize, u32, u32, u32),
|
||||
args: &mut KernelArguments,
|
||||
) -> Result<()> {
|
||||
let TensorCoreState::Ready(scan) = &self.tensor_core else { return Err(Error::ContextPoisoned) };
|
||||
scan.module.launch_dynamic(entry, LinearLaunch::new(grid, block, blas.stream()), smem, args)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_scan_is_off_unless_the_options_ask_for_it() {
|
||||
assert!(!GdnPromptOptions::default().tensor_core_scan);
|
||||
assert!(matches!(TensorCoreState::new(false), TensorCoreState::Off));
|
||||
assert!(matches!(TensorCoreState::new(true), TensorCoreState::Pending));
|
||||
for state in [TensorCoreState::Off, TensorCoreState::Pending, TensorCoreState::Refused] {
|
||||
assert!(state.plan().is_none(), "only a Ready scan has a plan");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -215,6 +215,7 @@ mod sealed_ptx;
|
||||
#[cfg(feature = "sm86")]
|
||||
mod sm86_table;
|
||||
|
||||
mod gdn_prefill_tc;
|
||||
mod launch_ex;
|
||||
mod native_prompt_device;
|
||||
mod prefill_stage;
|
||||
|
||||
@@ -63,6 +63,14 @@ impl LinearLaunch {
|
||||
Self { grid, block, stream }
|
||||
}
|
||||
}
|
||||
/// What a kernel module's host code needs to know about the current device: compute capability major, multiprocessor
|
||||
/// count and the opt-in limit of dynamic shared memory a block.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct DeviceGeometry {
|
||||
pub(crate) cc_major: u32,
|
||||
pub(crate) multiprocessors: u32,
|
||||
pub(crate) shared_optin: u32,
|
||||
}
|
||||
/// The grid `[x, y]`, `block` threads, cluster width and dynamic shared memory of one cluster launch.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct ClusterShape {
|
||||
|
||||
@@ -79,18 +79,63 @@ impl KernelModule {
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn launch(&self, index: usize, launch: LinearLaunch, args: &mut KernelArguments) -> Result<()> {
|
||||
self.launch_dynamic(index, launch, 0, args)
|
||||
}
|
||||
/// `launch` with `smem` bytes of dynamic shared memory. Above the 48 KiB default the function is first opted in
|
||||
/// with `cuFuncSetAttribute(MAX_DYNAMIC_SHARED_SIZE_BYTES)` (the device's opt-in limit is the caller's check).
|
||||
pub(crate) fn launch_dynamic(
|
||||
&self,
|
||||
index: usize,
|
||||
launch: LinearLaunch,
|
||||
smem: u32,
|
||||
args: &mut KernelArguments,
|
||||
) -> Result<()> {
|
||||
let LinearLaunch { grid, block, stream } = launch;
|
||||
if grid == 0 || !matches!(block, 128 | 256 | 512 | 1024) || stream == 0 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let function = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?;
|
||||
if smem > 48 * 1024 {
|
||||
self.allow_dynamic_shared(function, smem)?;
|
||||
}
|
||||
args.pack()?;
|
||||
// SAFETY: owned boxed command fields and exact producer-declared
|
||||
// ABI persist until drain; Driver copies the parameter pointer array
|
||||
// during this call. No pointer/entry escapes to public callers.
|
||||
let (function, stream, pointers) = (function as *mut c_void, stream as *mut c_void, args.pointers.as_mut_ptr());
|
||||
check("cuLaunchKernel", unsafe {
|
||||
(self.launch)(function, grid, 1, 1, block, 1, 1, 0, stream, pointers, std::ptr::null_mut())
|
||||
(self.launch)(function, grid, 1, 1, block, 1, 1, smem, stream, pointers, std::ptr::null_mut())
|
||||
})
|
||||
}
|
||||
/// `cuFuncSetAttribute(MAX_DYNAMIC_SHARED_SIZE_BYTES, smem)` of one function of this module.
|
||||
fn allow_dynamic_shared(&self, function: usize, smem: u32) -> Result<()> {
|
||||
let library = self._library.as_ref().ok_or(Error::LibraryUnavailable)?;
|
||||
let set_attribute = symbol!(library, c"cuFuncSetAttribute", FuncSetAttribute);
|
||||
let attribute = crate::launch_ex::FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED;
|
||||
// SAFETY: the function belongs to this live module and the context is current (the launch contract).
|
||||
check("cuFuncSetAttribute", unsafe { set_attribute(function as *mut c_void, attribute, smem as c_int) })
|
||||
}
|
||||
/// Compute capability, multiprocessor count and opt-in shared memory of the device that is current (the caller runs
|
||||
/// inside `Context::enter`).
|
||||
pub(crate) fn device_geometry(&self) -> Result<crate::ple_batch_ffi::DeviceGeometry> {
|
||||
type CtxGetDevice = unsafe extern "C" fn(*mut c_int) -> c_int;
|
||||
type DeviceAttribute = unsafe extern "C" fn(*mut c_int, c_int, c_int) -> c_int;
|
||||
let library = self._library.as_ref().ok_or(Error::LibraryUnavailable)?;
|
||||
let device = symbol!(library, c"cuCtxGetDevice", CtxGetDevice);
|
||||
let attribute = symbol!(library, c"cuDeviceGetAttribute", DeviceAttribute);
|
||||
let mut d: c_int = 0;
|
||||
// SAFETY: a valid out-pointer to a live local; a current context is the caller's precondition.
|
||||
check("cuCtxGetDevice", unsafe { device(&mut d) })?;
|
||||
let read = |id: c_int, what: &'static str| -> Result<u32> {
|
||||
let mut value: c_int = 0;
|
||||
// SAFETY: valid out-pointer to a live local and the device just returned by the driver.
|
||||
check(what, unsafe { attribute(&mut value, id, d) })?;
|
||||
u32::try_from(value).map_err(|_| Error::InvalidDriverValue(what))
|
||||
};
|
||||
Ok(crate::ple_batch_ffi::DeviceGeometry {
|
||||
cc_major: read(75, "cuDeviceGetAttribute(compute capability major)")?,
|
||||
multiprocessors: read(16, "cuDeviceGetAttribute(multiprocessors)")?,
|
||||
shared_optin: read(97, "cuDeviceGetAttribute(shared memory opt-in)")?,
|
||||
})
|
||||
}
|
||||
/// `cuLaunchKernelEx` with a thread-block cluster (sm_90+): grid `[x, y, 1]`, `block` threads, cluster `[cx, 1,
|
||||
|
||||
@@ -55,6 +55,12 @@ impl KernelModule {
|
||||
pub(crate) fn launch_cluster(&self, _: usize, _: ClusterShape, _: usize, _: &mut KernelArguments) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn launch_dynamic(&self, _: usize, _: LinearLaunch, _: u32, _: &mut KernelArguments) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn device_geometry(&self) -> Result<DeviceGeometry> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn close(self) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -32,3 +32,5 @@ use enable_types::Rng;
|
||||
mod gdn_recurrence_equals_the_original;
|
||||
#[path = "prefill_stage_gdn_gpu/gdn_stage_kernels_equal.rs"]
|
||||
mod gdn_stage_kernels_equal;
|
||||
#[path = "prefill_stage_gdn_gpu/gdn_tensor_core_scan_parity.rs"]
|
||||
mod gdn_tensor_core_scan_parity;
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
//! GPU parity of the EXPERIMENTAL tensor-core scan of the prompt GDN recurrence (`gdn_prefill_tc.cu`, ledger row U1)
|
||||
//! against the sequential `leleka_prefill_gdn_rec` kernel (bit-identical to the Original's recurrence). The scan is
|
||||
//! LOSSY by design: this test is the upstream harness's gate (1e-4 absolute / relative, `gdn_rec_parity`), not an
|
||||
//! identity probe, and the quality gate of docs/quality-gate.md decides whether it may ever be used. Needs a CUDA
|
||||
//! device with compute capability 12 and no model:
|
||||
//! LELEKA_PREFILL_STAGE_GPU=yes cargo test -p leleka-cuda-driver --features cuda-driver --release --lib \
|
||||
//! gdn_tensor_core_scan -- --ignored --nocapture
|
||||
//! Every case is run and printed before the verdict, so one run shows all failures (`PREFILL-GDN-TC` lines).
|
||||
|
||||
use super::gdn_recurrence_equals_the_original::{Rig, with_rig};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::gdn_prefill_tc as tc;
|
||||
use crate::ple_batch_ffi::LinearLaunch;
|
||||
|
||||
const STATE_LEN: usize = 128 * 48 * 128;
|
||||
/// The prompt device's dequantization scratch the scan runs in.
|
||||
const SCRATCH: usize = 52_428_800;
|
||||
/// Upstream's gate: |scan - sequential| <= 1e-4 max(1, |sequential|), element by element.
|
||||
const TOLERANCE: f32 = 1e-4;
|
||||
/// Ill-conditioned inputs (identical keys, no decay): T = (I + A)^-1 grows; reported, with a looser bound.
|
||||
const STRESS_TOLERANCE: f32 = 1e-3;
|
||||
|
||||
/// What a case feeds the recurrence.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Inputs {
|
||||
/// Unit q/k, decay exp(-0.02..-0.7), beta 0.05..1, v and state O(1): the shape of a real prompt.
|
||||
Typical,
|
||||
/// Almost no decay and beta near 1: the state keeps everything it was given.
|
||||
NoDecay,
|
||||
/// v 8x and the state 4x larger than typical (the per-chunk power-of-two scales move).
|
||||
Large,
|
||||
/// Every token of a key head has (almost) the same k, beta 1, no decay: T = (I + A)^-1 spans 2^30.
|
||||
CollinearKeys,
|
||||
/// One infinite value in the prior state: both kernels must raise the witness.
|
||||
InfiniteState,
|
||||
}
|
||||
|
||||
impl Inputs {
|
||||
fn stress(self) -> bool {
|
||||
matches!(self, Self::CollinearKeys | Self::NoDecay)
|
||||
}
|
||||
}
|
||||
|
||||
/// A unit vector of `n` values from the generator (the L2 norm of the real chain).
|
||||
fn unit(rng: &mut Rng, out: &mut [f32]) {
|
||||
out.iter_mut().for_each(|x| *x = rng.f(1.0));
|
||||
let norm = out.iter().map(|x| x * x).sum::<f32>().sqrt().max(1e-6);
|
||||
out.iter_mut().for_each(|x| *x /= norm);
|
||||
}
|
||||
|
||||
/// One run's inputs on the host: state [128][48][128], h [t][10240] (q | k | v), gate and beta [t][48].
|
||||
struct Host {
|
||||
state: Vec<f32>,
|
||||
h: Vec<f32>,
|
||||
gate: Vec<f32>,
|
||||
beta: Vec<f32>,
|
||||
}
|
||||
|
||||
fn generate(rng: &mut Rng, t: usize, kind: Inputs) -> Host {
|
||||
let (state_scale, v_scale) = if kind == Inputs::Large { (4.0, 8.0) } else { (0.5, 1.0) };
|
||||
let mut state: Vec<f32> = (0..STATE_LEN).map(|_| rng.f(state_scale)).collect();
|
||||
if kind == Inputs::InfiniteState {
|
||||
state[1234] = f32::INFINITY;
|
||||
}
|
||||
let mut h = vec![0.0f32; t * 10240];
|
||||
let first_k: Vec<f32> = (0..16 * 128).map(|_| rng.f(1.0)).collect();
|
||||
for row in h.chunks_mut(10240) {
|
||||
for head in 0..16 {
|
||||
unit(rng, &mut row[head * 128..(head + 1) * 128]);
|
||||
let k = &mut row[2048 + head * 128..2048 + (head + 1) * 128];
|
||||
unit(rng, k);
|
||||
if kind == Inputs::CollinearKeys {
|
||||
k.iter_mut().zip(&first_k[head * 128..]).for_each(|(x, f)| *x = f + 1e-3 * *x);
|
||||
let norm = k.iter().map(|x| x * x).sum::<f32>().sqrt();
|
||||
k.iter_mut().for_each(|x| *x /= norm);
|
||||
}
|
||||
}
|
||||
row[4096..].iter_mut().for_each(|x| *x = rng.f(v_scale));
|
||||
}
|
||||
let (gate, beta) = match kind {
|
||||
Inputs::NoDecay | Inputs::CollinearKeys => (vec![-1e-3; t * 48], vec![0.95; t * 48]),
|
||||
_ => (
|
||||
(0..t * 48).map(|_| -0.02 - rng.f(0.34).abs() * 2.0).collect(),
|
||||
(0..t * 48).map(|_| 0.05 + (rng.f(0.5) + 0.5).abs() * 0.95).collect(),
|
||||
),
|
||||
};
|
||||
Host { state, h, gate, beta }
|
||||
}
|
||||
|
||||
/// The device side of one case; `_s` the sequential kernel's outputs, `_t` the scan's.
|
||||
struct Device<'c> {
|
||||
sin: DeviceBuffer<'c>,
|
||||
h: DeviceBuffer<'c>,
|
||||
gate: DeviceBuffer<'c>,
|
||||
beta: DeviceBuffer<'c>,
|
||||
sout_s: DeviceBuffer<'c>,
|
||||
sout_t: DeviceBuffer<'c>,
|
||||
y_s: DeviceBuffer<'c>,
|
||||
y_t: DeviceBuffer<'c>,
|
||||
w_s: DeviceBuffer<'c>,
|
||||
w_t: DeviceBuffer<'c>,
|
||||
scratch: DeviceBuffer<'c>,
|
||||
}
|
||||
|
||||
impl<'c> Device<'c> {
|
||||
fn new(context: &'c Context<'c>, host: &Host, t: usize) -> Self {
|
||||
let zero = |bytes: usize| upload(context, &vec![0u8; bytes]);
|
||||
Self {
|
||||
sin: upload(context, &f32_bytes(&host.state)),
|
||||
h: upload(context, &f32_bytes(&host.h)),
|
||||
gate: upload(context, &f32_bytes(&host.gate)),
|
||||
beta: upload(context, &f32_bytes(&host.beta)),
|
||||
sout_s: zero(STATE_LEN * 4),
|
||||
sout_t: zero(STATE_LEN * 4),
|
||||
y_s: zero(t * 6144 * 4),
|
||||
y_t: zero(t * 6144 * 4),
|
||||
w_s: zero(16),
|
||||
w_t: zero(16),
|
||||
scratch: context.allocate(SCRATCH).expect("scratch"),
|
||||
}
|
||||
}
|
||||
fn io(&self) -> tc::RecurrenceIo {
|
||||
tc::RecurrenceIo {
|
||||
state_in: hd(&self.sin),
|
||||
state_out: hd(&self.sout_t),
|
||||
h: hd(&self.h),
|
||||
gate: hd(&self.gate),
|
||||
beta: hd(&self.beta),
|
||||
y: hd(&self.y_t),
|
||||
witness: hd(&self.w_t),
|
||||
scratch: hd(&self.scratch),
|
||||
}
|
||||
}
|
||||
/// A sequential kernel (`entry` of the stage module, `grid` blocks of 128 threads) into the `_s` buffers.
|
||||
fn run_sequential(&self, rig: &Rig<'_>, t: usize, (entry, grid): (usize, u32)) {
|
||||
let mut args = KernelArguments::new(vec![
|
||||
A::Address(hd(&self.sin)),
|
||||
A::Address(hd(&self.sout_s)),
|
||||
A::Address(hd(&self.h)),
|
||||
A::Address(hd(&self.gate)),
|
||||
A::Address(hd(&self.beta)),
|
||||
A::Address(hd(&self.y_s)),
|
||||
A::I64(t as i64),
|
||||
A::Address(hd(&self.w_s)),
|
||||
]);
|
||||
let guard = rig.context.enter().expect("enter");
|
||||
let launch = LinearLaunch::new(grid, 128, rig.stream);
|
||||
rig.stage.launch(entry, launch, &mut args).expect("launch sequential");
|
||||
rig.context.driver.api.synchronize().expect("sync");
|
||||
guard.finish().expect("finish");
|
||||
}
|
||||
/// The prep and scan launches of the plan into the `_t` buffers, `reps` times (the state is re-read from `sin`).
|
||||
fn run_scan(&self, (rig, module): (&Rig<'_>, &KernelModule), plan: &tc::ScanPlan, (t, reps): (usize, usize)) {
|
||||
let guard = rig.context.enter().expect("enter");
|
||||
let mut keep = Vec::new();
|
||||
for _ in 0..reps {
|
||||
for l in tc::launches(plan, &self.io(), (SCRATCH, t)).expect("launches") {
|
||||
let mut args = KernelArguments::new(l.args);
|
||||
let launch = LinearLaunch::new(l.grid, l.block, rig.stream);
|
||||
module.launch_dynamic(l.entry, launch, l.smem, &mut args).expect("launch scan");
|
||||
keep.push(args);
|
||||
}
|
||||
}
|
||||
rig.context.driver.api.synchronize().expect("sync");
|
||||
guard.finish().expect("finish");
|
||||
}
|
||||
}
|
||||
|
||||
/// Worst element of one tensor against the gate `|a - b| <= tolerance max(1, |b|)`.
|
||||
#[derive(Default, Clone, Copy)]
|
||||
struct Worst {
|
||||
/// the largest |a - b| / max(1, |b|)
|
||||
scaled: f32,
|
||||
/// the largest |b|
|
||||
reference: f32,
|
||||
non_finite: usize,
|
||||
}
|
||||
|
||||
fn compare(scan: &[u8], reference: &[u8]) -> Worst {
|
||||
let to_f32 = |b: &[u8]| -> Vec<f32> { b.chunks(4).map(|c| f32::from_le_bytes(c.try_into().unwrap())).collect() };
|
||||
let (a, b) = (to_f32(scan), to_f32(reference));
|
||||
let mut worst = Worst::default();
|
||||
for (x, y) in a.iter().zip(&b) {
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
worst.non_finite += usize::from(x.is_finite() != y.is_finite());
|
||||
continue;
|
||||
}
|
||||
worst.scaled = worst.scaled.max((x - y).abs() / y.abs().max(1.0));
|
||||
worst.reference = worst.reference.max(y.abs());
|
||||
}
|
||||
worst
|
||||
}
|
||||
|
||||
/// One row of the table.
|
||||
struct Row {
|
||||
label: String,
|
||||
readout: Worst,
|
||||
state: Worst,
|
||||
witness: (u32, u32),
|
||||
tolerance: f32,
|
||||
}
|
||||
|
||||
impl Row {
|
||||
fn failure(&self, kind: Inputs) -> Option<String> {
|
||||
let (w_scan, w_ref) = self.witness;
|
||||
let expect_bad = kind == Inputs::InfiniteState;
|
||||
if (w_ref != 0) != expect_bad || (w_scan != 0) != expect_bad {
|
||||
return Some(format!("witness scan {w_scan} sequential {w_ref} (expected {})", u32::from(expect_bad)));
|
||||
}
|
||||
if expect_bad {
|
||||
return None;
|
||||
}
|
||||
let bad = |w: &Worst| w.scaled > self.tolerance || w.non_finite > 0;
|
||||
(bad(&self.readout) || bad(&self.state)).then(|| "beyond the gate".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// One token count, one input kind, one plan: the sequential kernel, then the scan, then the comparison.
|
||||
fn case(rig: &Rig<'_>, module: &KernelModule, host_of: (&Host, Inputs), (t, plan): (usize, &tc::ScanPlan)) -> Row {
|
||||
let (host, kind) = host_of;
|
||||
let device = Device::new(rig.context, host, t);
|
||||
device.run_sequential(rig, t, (crate::prefill_stage::GDN_REC, 192));
|
||||
device.run_scan((rig, module), plan, (t, 1));
|
||||
let readout = compare(&download(&device.y_t, t * 6144 * 4), &download(&device.y_s, t * 6144 * 4));
|
||||
let state = compare(&download(&device.sout_t, STATE_LEN * 4), &download(&device.sout_s, STATE_LEN * 4));
|
||||
Row {
|
||||
label: format!("t={t} {kind:?} tiles={} chunks/block={}", plan.tiles(), plan.chunks()),
|
||||
readout,
|
||||
state,
|
||||
witness: (words(&device.w_t, 1)[0], words(&device.w_s, 1)[0]),
|
||||
tolerance: if kind.stress() { STRESS_TOLERANCE } else { TOLERANCE },
|
||||
}
|
||||
}
|
||||
|
||||
fn print(row: &Row) {
|
||||
let w = |w: &Worst| format!("{:.2e} (max|ref| {:.3}, {} non-finite)", w.scaled, w.reference, w.non_finite);
|
||||
eprintln!(
|
||||
"PREFILL-GDN-TC {}: readout {} state {} witness scan {} seq {} gate {:.0e}",
|
||||
row.label,
|
||||
w(&row.readout),
|
||||
w(&row.state),
|
||||
row.witness.0,
|
||||
row.witness.1,
|
||||
row.tolerance
|
||||
);
|
||||
}
|
||||
|
||||
/// The device's plan, or None (with the reason printed) when this card cannot run the asset.
|
||||
fn device_plan(module: &KernelModule, rig: &Rig<'_>) -> Option<tc::ScanPlan> {
|
||||
let guard = rig.context.enter().expect("enter");
|
||||
let geometry = module.device_geometry().expect("device geometry");
|
||||
guard.finish().expect("finish");
|
||||
match tc::plan(true, geometry, SCRATCH) {
|
||||
Ok(plan) => Some(plan),
|
||||
Err(refusal) => {
|
||||
eprintln!("PREFILL-GDN-TC skipped: {refusal} ({geometry:?})");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_module(rig: &Rig<'_>) -> KernelModule {
|
||||
tc::admit().expect("gdn_prefill_tc.ptx must match its pin");
|
||||
let guard = rig.context.enter().expect("enter");
|
||||
let module = KernelModule::load(tc::PTX, tc::ENTRIES).expect("tensor-core scan module");
|
||||
guard.finish().expect("finish");
|
||||
module
|
||||
}
|
||||
|
||||
/// Token counts of the gate: every chunk edge near 32, 128 (the dispatch minimum), the super-block edge of the
|
||||
/// scratch (1,760) and of upstream's 2,048, the harness's 4,099 and a full 8,192-token prompt chunk, then eight
|
||||
/// pseudo-random lengths up to 4,099.
|
||||
fn token_counts(rng: &mut Rng) -> Vec<usize> {
|
||||
let mut counts = vec![
|
||||
1, 2, 31, 32, 33, 63, 64, 65, 127, 128, 129, 200, 255, 256, 257, 1000, 1759, 1760, 1761, 2047, 2048, 2049,
|
||||
3520, 3521, 4096, 4097, 4099, 8192,
|
||||
];
|
||||
counts.extend((0..8).map(|_| 1 + (rng.next() % 4099) as usize));
|
||||
counts
|
||||
}
|
||||
|
||||
/// The cases run so far, and what they run on.
|
||||
struct Gate<'a> {
|
||||
rig: &'a Rig<'a>,
|
||||
module: KernelModule,
|
||||
rng: Rng,
|
||||
table: Vec<(Row, Inputs)>,
|
||||
}
|
||||
|
||||
impl Gate<'_> {
|
||||
fn run(&mut self, t: usize, kind: Inputs, plan: &tc::ScanPlan) {
|
||||
let host = generate(&mut self.rng, t, kind);
|
||||
let row = case(self.rig, &self.module, (&host, kind), (t, plan));
|
||||
print(&row);
|
||||
self.table.push((row, kind));
|
||||
}
|
||||
/// Typical inputs, every length, both value-tile plans of the 99-KB card.
|
||||
fn typical_lengths(&mut self, plan: &tc::ScanPlan) {
|
||||
for t in token_counts(&mut self.rng) {
|
||||
for tiles in [1, 2] {
|
||||
self.run(t, Inputs::Typical, &plan.with_tiles(tiles));
|
||||
}
|
||||
}
|
||||
// small super-blocks chain the state through many launches (in place, as the product does)
|
||||
for t in [200, 1000, 4099] {
|
||||
self.run(t, Inputs::Typical, &plan.with_chunks(3));
|
||||
}
|
||||
}
|
||||
fn stress(&mut self, plan: &tc::ScanPlan) {
|
||||
for kind in [Inputs::NoDecay, Inputs::Large, Inputs::CollinearKeys, Inputs::InfiniteState] {
|
||||
for t in [128, 129, 1000, 2049, 8192] {
|
||||
self.run(t, kind, plan);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn verdict(&self) {
|
||||
let fails = |(r, k): &(Row, Inputs)| r.failure(*k).map(|why| format!("{}: {why}", r.label));
|
||||
let failures: Vec<String> = self.table.iter().filter_map(fails).collect();
|
||||
let (n, list) = (self.table.len(), failures.join("\n"));
|
||||
assert!(failures.is_empty(), "{} of {n} cases fail:\n{list}", failures.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Root-only: needs a CUDA device with compute capability 12"]
|
||||
fn gdn_tensor_core_scan_stays_within_the_gate_of_the_sequential_recurrence() {
|
||||
with_rig(6usize << 30, 2048, |rig| {
|
||||
let module = load_module(rig);
|
||||
let Some(plan) = device_plan(&module, rig) else { return };
|
||||
let mut gate = Gate { rig, module, rng: Rng(0x7e57_0c0d_e5ca_17ed), table: Vec::new() };
|
||||
gate.typical_lengths(&plan);
|
||||
gate.stress(&plan);
|
||||
gate.verdict();
|
||||
});
|
||||
}
|
||||
|
||||
/// Timing on warm data, a SYNTHETIC kernel number (not an end-to-end prefill gain): 20 runs of the scan's prep + scan
|
||||
/// against 20 of the kh recurrence (64 blocks, the product's sequential kernel), for the lengths of a prompt chunk.
|
||||
/// The span to compare in a real run is the `gdn` stage of the prefill profile.
|
||||
#[test]
|
||||
#[ignore = "Root-only: needs a CUDA device with compute capability 12"]
|
||||
fn gdn_tensor_core_scan_timing_against_the_kh_recurrence() {
|
||||
with_rig(6usize << 30, 2048, |rig| {
|
||||
let module = load_module(rig);
|
||||
let Some(plan) = device_plan(&module, rig) else { return };
|
||||
let mut rng = Rng(0x71_3e_71_3e_71_3e);
|
||||
for t in [512usize, 2048, 8192] {
|
||||
let device = Device::new(rig.context, &generate(&mut rng, t, Inputs::Typical), t);
|
||||
let reps = 20;
|
||||
let started = std::time::Instant::now();
|
||||
for _ in 0..reps {
|
||||
device.run_sequential(rig, t, (crate::prefill_stage::GDN_REC_KH, 64));
|
||||
}
|
||||
let sequential = started.elapsed().as_secs_f64() * 1e3 / reps as f64;
|
||||
let started = std::time::Instant::now();
|
||||
device.run_scan((rig, &module), &plan, (t, reps));
|
||||
let scan = started.elapsed().as_secs_f64() * 1e3 / reps as f64;
|
||||
eprintln!(
|
||||
"PREFILL-GDN-TC timing t={t} tiles={}: kh recurrence {sequential:.3} ms (one sync each), \
|
||||
tensor-core prep+scan {scan:.3} ms (mean of {reps}, warm; synthetic)",
|
||||
plan.tiles()
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -86,8 +86,8 @@ pub(crate) use qwen_dispatch::gdn_native_batch::GdnGeometry;
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))]
|
||||
pub use qwen_dispatch::gdn_native_batch::{
|
||||
GDN_BATCH_EPSILON, GDN_BATCH_MAX_TOKENS, GdnBatchCompletion, GdnBatchPrefix, GdnBatchStage, GdnGemm,
|
||||
GdnNativeFormat, GdnPrefillBatch, GdnStream, GemmShape, OriginalGdnPromptDevice, OriginalGdnPromptState,
|
||||
OriginalGdnPromptWeights,
|
||||
GdnNativeFormat, GdnPrefillBatch, GdnPromptOptions, GdnStream, GemmShape, OriginalGdnPromptDevice,
|
||||
OriginalGdnPromptState, OriginalGdnPromptWeights,
|
||||
};
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))]
|
||||
pub use qwen_dispatch::moe_prefill_batch::{
|
||||
|
||||
+4
-2
@@ -2,7 +2,7 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use leleka_cuda_driver::NativeBatchWorkspace;
|
||||
use leleka_cuda_driver::{GdnPromptOptions, NativeBatchWorkspace};
|
||||
|
||||
impl<'ctx> OriginalPromptExecutor<'ctx> {
|
||||
/// Eager model/session owners precede expert prefix planning. The twelve
|
||||
@@ -99,7 +99,9 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
|
||||
let (context, capacity) = (self.context, self.capacity);
|
||||
let prompt = context.original_prompt_device(capacity, PleBf16Mode::HighOnly, GrNativeProfile::HighOnly);
|
||||
self.prompt = Some(prompt.map_err(driver_error)?);
|
||||
let gdn = context.original_gdn_prompt_device(capacity, GrNativeProfile::HighOnly);
|
||||
// LELEKA_PREFILL_GDN_TC (EXPERIMENTAL, LOSSY, off by default): the tensor-core scan of the prompt recurrence
|
||||
let options = GdnPromptOptions { tensor_core_scan: crate::settings::process().serve.prefill_gdn_tc };
|
||||
let gdn = context.original_gdn_prompt_device_with(capacity, GrNativeProfile::HighOnly, options);
|
||||
self.gdn = Some(gdn.map_err(driver_error)?);
|
||||
let qsa = context.original_qsa_resident_prompt_device(capacity, QsaNativePacking::HighOnly);
|
||||
self.qsa = Some(qsa.map_err(driver_error)?);
|
||||
|
||||
@@ -31,6 +31,10 @@ pub(crate) struct ServeSettings {
|
||||
/// `LELEKA_DRAFT_CHAIN_PIPELINE` is `1` or `on`: the MTP chain steps of a greedy draft run back to back, one
|
||||
/// stream drain for the run (identity and paired A/B of docs/experiments/decode-tail-5090.md).
|
||||
pub(crate) draft_chain_pipeline: bool,
|
||||
/// `LELEKA_PREFILL_GDN_TC` is `1` or `on` (EXPERIMENTAL, LOSSY, off by default): the prompt GDN recurrence runs
|
||||
/// as a chunked scan on the tensor cores (f16x3 products; not bitwise equal to the sequential kernel). Decided
|
||||
/// by the first-token KL / logprob gates of docs/quality-gate.md, never by an identity probe.
|
||||
pub(crate) prefill_gdn_tc: bool,
|
||||
}
|
||||
|
||||
impl ServeSettings {
|
||||
@@ -47,6 +51,7 @@ impl ServeSettings {
|
||||
cpu_pool_plan: equals(env, "LELEKA_CPU_POOL_PLAN", "on"),
|
||||
prefill_loan_tiers: one_of(env, "LELEKA_PREFILL_LOAN_TIERS", &["1", "on"]),
|
||||
draft_chain_pipeline: one_of(env, "LELEKA_DRAFT_CHAIN_PIPELINE", &["1", "on"]),
|
||||
prefill_gdn_tc: one_of(env, "LELEKA_PREFILL_GDN_TC", &["1", "on"]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,3 +96,13 @@ fn the_draft_chain_pipeline_is_one_or_on_and_off_by_default() {
|
||||
assert_eq!(serve(&[("LELEKA_DRAFT_CHAIN_PIPELINE", value)]).draft_chain_pipeline, want, "pipeline {value:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_prefill_gdn_tensor_core_scan_is_one_or_on_and_off_by_default() {
|
||||
assert!(!serve(&[]).prefill_gdn_tc);
|
||||
for (value, want) in
|
||||
[("1", true), ("on", true), ("0", false), ("off", false), ("yes", false), ("true", false), ("", false)]
|
||||
{
|
||||
assert_eq!(serve(&[("LELEKA_PREFILL_GDN_TC", value)]).prefill_gdn_tc, want, "gdn tc {value:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,6 +160,21 @@ binary measures old against new.
|
||||
| element-parallel dequantization (GDN, QSA) | `LELEKA_PREFILL_FAST_DEQUANT=0` | one thread per 32 values, ~6 GB/s on the laptop |
|
||||
| GDN chunk starts from the mirror's device state | `LELEKA_PREFILL_GDN_MIRROR=0` | canonical host state converted and uploaded for every layer of every chunk |
|
||||
| two-barrier GDN recurrence (EXPERIMENTAL, off) | `LELEKA_PREFILL_FAST_REC=1` | `gdn_rec_cols_pipe_kernel` |
|
||||
| chunked tensor-core GDN recurrence (EXPERIMENTAL, LOSSY, off) | `LELEKA_PREFILL_GDN_TC=1` | `leleka_prefill_gdn_rec` / `_kh` for runs of >= 128 tokens; NOT bitwise, see below |
|
||||
|
||||
Tensor-core GDN recurrence (`LELEKA_PREFILL_GDN_TC=1`, EXPERIMENTAL, LOSSY, off by default; ledger row U1). A port of Strata
|
||||
upstream `gdn_tc.cuh` (`strata-upstream/main` 504b1433): the recurrence of a prompt chunk in WY form, 32-token chunks, every product an
|
||||
f16x3 `mma.sync` (x = hi + lo, hi.hi + hi.lo + lo.hi, power-of-two scaling per chunk). New sealed asset `gdn_prefill_tc.cu` (group
|
||||
`gdn-prefill-tc`, kernels `leleka_gdn_tc_prep`, `_scan_t1`, `_scan_t2`; no sm_86 companion, the plan refuses cc < 12). Plan for the
|
||||
RTX 5090: the 99-KB split plan (97,808 bytes of dynamic shared memory), two value tiles per head (upstream 51567de1a: 96 blocks of
|
||||
128 threads from 96 SMs; the card has 170) and a prep of `chunks * 16` blocks of 256 threads. The scratch (942,272 bytes a chunk,
|
||||
60,305,408 for upstream's 64 chunks) is the prompt device's dequantization scratch, idle during the recurrence, so the super-block is
|
||||
55 chunks (1,760 tokens) and the switch costs no device memory. Dispatch: switch on, cc >= 12, >= 48 SMs, >= 97,808 bytes of
|
||||
opt-in shared memory, run of >= 128 tokens; anything else runs the sequential kernels unchanged (one stderr line says why). The state
|
||||
in/out, the readout and the non-finite state witness are those of `leleka_prefill_gdn_rec_kh`. Not bitwise equal (upstream first-token
|
||||
KL mean 0.0019, max 0.0125): the gate is `docs/quality-gate.md` (first-token KL / q_tail_gate / logprob envelope), never an identity
|
||||
probe. GPU checks: `gdn_tensor_core_scan_stays_within_the_gate_of_the_sequential_recurrence` (1e-4, upstream's gate) and
|
||||
`gdn_tensor_core_scan_timing_against_the_kh_recurrence` (synthetic); the end-to-end number is the `gdn` stage of the prefill profile.
|
||||
|
||||
Input staging: the rows of a chunk (16 per token) are resolved against the cache map on the host, the packets of the
|
||||
misses are read in parallel (`pread`, up to 32 threads), and one kernel decodes all of them straight into the arena's
|
||||
|
||||
@@ -927,6 +927,35 @@
|
||||
},
|
||||
"group": "draft-round",
|
||||
"optional": false
|
||||
},
|
||||
{
|
||||
"cu": "crates/cuda-driver/src/gdn_prefill_tc.cu",
|
||||
"ptx": "crates/cuda-driver/src/gdn_prefill_tc.ptx",
|
||||
"flags": [
|
||||
"-ptx",
|
||||
"-O3",
|
||||
"-arch=sm_120",
|
||||
"-std=c++17",
|
||||
"--ftz=false",
|
||||
"--prec-div=true",
|
||||
"--prec-sqrt=true",
|
||||
"--fmad=true"
|
||||
],
|
||||
"policy": "precise (the recipe of prefill_stage; EXPERIMENTAL and LOSSY by design, LELEKA_PREFILL_GDN_TC: the prompt GDN recurrence as a chunked scan on f16x3 tensor-core products, a port of Strata upstream gdn_tc.cuh, not bitwise equal to leleka_prefill_gdn_rec_kh; the lossy gate of docs/quality-gate.md decides)",
|
||||
"entries": [
|
||||
"leleka_gdn_tc_prep",
|
||||
"leleka_gdn_tc_scan_t1",
|
||||
"leleka_gdn_tc_scan_t2"
|
||||
],
|
||||
"encoding": "concat_include_str",
|
||||
"rust_fields_to_fill": {
|
||||
"gdn_prefill_tc.rs": [
|
||||
"PIN.source_sha256",
|
||||
"PIN.ptx_sha256"
|
||||
]
|
||||
},
|
||||
"group": "gdn-prefill-tc",
|
||||
"optional": false
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user