Merge branch 'claude/chain-kernels' into claude/port-gpu-bringup

This commit is contained in:
Pavlo Ratushnyi
2026-10-24 20:54:12 +02:00
30 changed files with 61325 additions and 71 deletions
+789
View File
@@ -0,0 +1,789 @@
// claude/chain-kernels: latency-hoisted, bit-identical variants of the verify-window kernels that sit on the decode chain
// (docs/chain-kernels.md). Every kernel here computes EVERY output with the same operations in the same order as the
// kernel it replaces (original_verify.cu, mtp_original_full_fused_gr.cu); only the issue order of independent loads, the
// block shape and the number of launches change. Selected at record time by LELEKA_CHAIN_* switches.
//
// Compile flags (same as the sources they derive from): -ptx -O3 -arch=sm_120 --fmad=true --ftz=false -std=c++17
#include <cuda_runtime.h>
#include <stdint.h>
#include <stddef.h>
#include <cuda_fp16.h>
#include <cfloat>
#include "strata/kernels/fused_gr.hpp"
#include "strata/kernels/sampler.hpp"
using strata::kernels::FusedGrArgs;
constexpr int kFusedGrMaxT = strata::kernels::kFusedGrMaxT;
namespace {
__device__ __forceinline__ void strata_spin_pause() {
__nanosleep(100);
}
__device__ __forceinline__ float warp_sum(float v) {
#pragma unroll
for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
return v;
}
__device__ __forceinline__ float sigmoidf_(float x) { return 1.0f / (1.0f + __expf(-x)); }
// 8 bf16 packed in a uint4 against 8 floats (fused_gr.cu `dot8`).
__device__ __forceinline__ float dot8(const uint4 w, const float* x) {
float acc = 0.0f;
const uint32_t v[4] = {w.x, w.y, w.z, w.w};
#pragma unroll
for (int j = 0; j < 4; ++j) {
acc = fmaf(__uint_as_float(v[j] << 16), x[2 * j], acc);
acc = fmaf(__uint_as_float(v[j] & 0xffff0000u), x[2 * j + 1], acc);
}
return acc;
}
constexpr int N = 2560;
constexpr int HC = 4;
constexpr int D = N * HC;
constexpr int LR = 320;
constexpr int THREADS = 256;
constexpr int WARPS = THREADS / 32;
struct GrMulti {
FusedGrArgs a[kFusedGrMaxT];
float* xn;
int T;
};
} // namespace
static_assert(sizeof(FusedGrArgs) == 112, "Original FusedGrArgs ABI");
static_assert(sizeof(GrMulti) == 912, "Original GrMulti ABI");
// ------------------------------------------------------------------------------------------------------------------
// plan copy from mapped host memory: the Original's `verify_copy_i32_from_mapped_kernel` issued one volatile load per
// thread per round trip (648 words / 128 threads = 6 PCIe round trips). Here all words of a round are loaded first.
// ------------------------------------------------------------------------------------------------------------------
extern "C" __global__ void chain_copy_i32_from_mapped_kernel(int32_t* __restrict__ dst, const volatile int32_t* src, int n) {
// block of up to 1024 threads: n <= 8 * blockDim in one batch, anything larger loops over batches
for (int base = 0; base < n; base += 8 * blockDim.x) {
int32_t v[8];
#pragma unroll
for (int k = 0; k < 8; ++k) {
const int i = base + k * blockDim.x + threadIdx.x;
v[k] = i < n ? src[i] : 0;
}
#pragma unroll
for (int k = 0; k < 8; ++k) {
const int i = base + k * blockDim.x + threadIdx.x;
if (i < n) dst[i] = v[k];
}
}
}
// `verify_wait_flag_ge_kernel` + `verify_copy_i32_from_mapped_kernel` in ONE launch (the plan block follows its flag).
extern "C" __global__ void chain_wait_copy_i32_kernel(const volatile uint32_t* flag, uint32_t value, int32_t* __restrict__ dst,
const volatile int32_t* src, int n) {
if (threadIdx.x == 0) {
while (*flag < value) strata_spin_pause();
__threadfence_system();
}
__syncthreads();
for (int base = 0; base < n; base += 8 * blockDim.x) {
int32_t v[8];
#pragma unroll
for (int k = 0; k < 8; ++k) {
const int i = base + k * blockDim.x + threadIdx.x;
v[k] = i < n ? src[i] : 0;
}
#pragma unroll
for (int k = 0; k < 8; ++k) {
const int i = base + k * blockDim.x + threadIdx.x;
if (i < n) dst[i] = v[k];
}
}
}
// `verify_copy_rows_from_mapped_kernel`: rows of the CPU leg's partial outputs, zero-filled where the row is a hit row.
// The hit test is spread over the block, and the row's float4 are loaded before any is stored (5 PCIe round trips -> 1).
extern "C" __global__ void chain_copy_rows_from_mapped_kernel(float4* __restrict__ dst, const volatile float4* src, int64_t row4,
const int32_t* __restrict__ hit_rows, const int32_t* __restrict__ count) {
const int row = blockIdx.x;
const int c = *count;
int h = 0;
for (int i = threadIdx.x; i < c; i += blockDim.x) h |= hit_rows[i] == row;
const int hit = __syncthreads_or(h);
float4* d = dst + (int64_t) row * row4;
if (hit) {
for (int64_t i = threadIdx.x; i < row4; i += blockDim.x) d[i] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
} else {
const volatile float4* sr = src + (int64_t) row * row4;
for (int64_t base = 0; base < row4; base += 8 * (int64_t) blockDim.x) {
float4 v[8];
#pragma unroll
for (int k = 0; k < 8; ++k) {
const int64_t i = base + k * (int64_t) blockDim.x + threadIdx.x;
if (i < row4) v[k] = const_cast<const float4*>(sr)[i];
}
#pragma unroll
for (int k = 0; k < 8; ++k) {
const int64_t i = base + k * (int64_t) blockDim.x + threadIdx.x;
if (i < row4) d[i] = v[k];
}
}
}
}
// `verify_doorbell_publish_kernel` with the device reads of a round issued before the host-memory stores.
extern "C" __global__ void chain_doorbell_publish_kernel(const float* __restrict__ x, const int32_t* __restrict__ ids,
const float* __restrict__ w, int n, int k, float* x_out, int32_t* ids_out,
float* w_out, uint32_t* seq) {
for (int base = 0; base < n; base += 8 * blockDim.x) {
float v[8];
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int i = base + j * blockDim.x + threadIdx.x;
if (i < n) v[j] = x[i];
}
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int i = base + j * blockDim.x + threadIdx.x;
if (i < n) x_out[i] = v[j];
}
}
if ((int) threadIdx.x < k) { ids_out[threadIdx.x] = ids[threadIdx.x]; w_out[threadIdx.x] = w[threadIdx.x]; }
__threadfence_system();
__syncthreads();
if (threadIdx.x == 0) {
__threadfence_system();
*(volatile uint32_t*) seq = *(volatile uint32_t*) seq + 1u;
}
}
// ------------------------------------------------------------------------------------------------------------------
// GDN alpha / beta gates (`verify_gdn_ab_multi_kernel`): one warp per row; the ten weight chunks of a lane are loaded
// first (the Original loaded chunk j, then the activations of every token, then chunk j + 32 ...). The per-lane
// accumulation order (chunk j ascending, token t independent) is unchanged. n == 2560 is the fast path.
// ------------------------------------------------------------------------------------------------------------------
extern "C" __global__ void __launch_bounds__(128) chain_gdn_ab_multi_kernel(const float* __restrict__ x, const uint16_t* __restrict__ wa,
const uint16_t* __restrict__ wb, const float* __restrict__ dt,
const float* __restrict__ ssm_a, float* __restrict__ gate,
float* __restrict__ beta, int n, int h_v, int T) {
const int row = blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5), lane = threadIdx.x & 31;
if (row >= 2 * h_v) return;
const bool is_beta = row >= h_v;
const int r = is_beta ? row - h_v : row;
const uint4* w4 = reinterpret_cast<const uint4*>((is_beta ? wb : wa) + (size_t) r * n);
float acc[kFusedGrMaxT];
#pragma unroll
for (int t = 0; t < kFusedGrMaxT; ++t) acc[t] = 0.0f;
constexpr int CH = 2560 / 8 / 32; // 10 chunks per lane
if (n == 2560) {
uint4 wv[CH];
#pragma unroll
for (int q = 0; q < CH; ++q) wv[q] = __ldg(w4 + lane + 32 * q);
#pragma unroll
for (int q = 0; q < CH; ++q) {
const int j = lane + 32 * q;
#pragma unroll
for (int t = 0; t < kFusedGrMaxT; ++t) {
if (t >= T) break;
const float* xt = x + (size_t) t * n;
const float4 xa = *reinterpret_cast<const float4*>(xt + j * 8);
const float4 xb = *reinterpret_cast<const float4*>(xt + j * 8 + 4);
float a = acc[t];
a = fmaf(__uint_as_float(wv[q].x << 16), xa.x, a); a = fmaf(__uint_as_float(wv[q].x & 0xffff0000u), xa.y, a);
a = fmaf(__uint_as_float(wv[q].y << 16), xa.z, a); a = fmaf(__uint_as_float(wv[q].y & 0xffff0000u), xa.w, a);
a = fmaf(__uint_as_float(wv[q].z << 16), xb.x, a); a = fmaf(__uint_as_float(wv[q].z & 0xffff0000u), xb.y, a);
a = fmaf(__uint_as_float(wv[q].w << 16), xb.z, a); a = fmaf(__uint_as_float(wv[q].w & 0xffff0000u), xb.w, a);
acc[t] = a;
}
}
} else {
for (int j = lane; j < n / 8; j += 32) {
const uint4 wv = __ldg(w4 + j);
#pragma unroll
for (int t = 0; t < kFusedGrMaxT; ++t) {
if (t >= T) break;
const float* xt = x + (size_t) t * n;
const float4 xa = *reinterpret_cast<const float4*>(xt + j * 8);
const float4 xb = *reinterpret_cast<const float4*>(xt + j * 8 + 4);
float a = acc[t];
a = fmaf(__uint_as_float(wv.x << 16), xa.x, a); a = fmaf(__uint_as_float(wv.x & 0xffff0000u), xa.y, a);
a = fmaf(__uint_as_float(wv.y << 16), xa.z, a); a = fmaf(__uint_as_float(wv.y & 0xffff0000u), xa.w, a);
a = fmaf(__uint_as_float(wv.z << 16), xb.x, a); a = fmaf(__uint_as_float(wv.z & 0xffff0000u), xb.y, a);
a = fmaf(__uint_as_float(wv.w << 16), xb.z, a); a = fmaf(__uint_as_float(wv.w & 0xffff0000u), xb.w, a);
acc[t] = a;
}
}
}
#pragma unroll
for (int t = 0; t < kFusedGrMaxT; ++t) {
if (t >= T) break;
float a = acc[t];
for (int o = 16; o > 0; o >>= 1) a += __shfl_xor_sync(0xffffffffu, a, o);
if (lane != 0) continue;
if (is_beta) {
beta[(size_t) t * h_v + r] = 1.0f / (1.0f + __expf(-a));
} else {
const float v = a + dt[r];
const float sp = v > 20.0f ? v : log1pf(__expf(v));
gate[(size_t) t * h_v + r] = sp * ssm_a[r];
}
}
}
// ------------------------------------------------------------------------------------------------------------------
// hyper-connection read (staged variant of the Original): norm / down / up
// ------------------------------------------------------------------------------------------------------------------
// `gr_norm_split_kernel` (mtp_scalar_gr_split): the same per-thread elements in the same order for the sum of squares,
// but the R' values are kept in registers for the second pass instead of being re-read from global memory.
extern "C" __global__ void __launch_bounds__(THREADS) chain_gr_split(GrMulti m) {
__shared__ float part[WARPS];
__shared__ float s_rs;
const FusedGrArgs& a = m.a[blockIdx.x];
const int c = blockIdx.y;
float* xn = m.xn + (size_t) blockIdx.x * D;
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f;
constexpr int NM = D / (THREADS * 4); // 10 rounds of the original loop
float4 rr[NM];
float ss = 0.0f;
#pragma unroll
for (int mm = 0; mm < NM; ++mm) {
const int i = t * 4 + mm * (THREADS * 4);
if (i / N != c) continue;
const int d = i - c * N;
float4 r = *reinterpret_cast<const float4*>(a.R + i);
if (a.apply) {
const float4 b = *reinterpret_cast<const float4*>(a.bo_prev + d);
r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y);
r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w);
}
rr[mm] = r;
const float sq = r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w;
ss += sq;
}
const float v = warp_sum(ss);
if (lane == 0) part[warp] = v;
__syncthreads();
if (t == 0) {
float s = 0.0f;
for (int w = 0; w < WARPS; ++w) s += part[w];
s_rs = rsqrtf(s / (float) N + a.eps);
a.rs[c] = s_rs;
}
__syncthreads();
const float rs = s_rs;
#pragma unroll
for (int mm = 0; mm < NM; ++mm) {
const int i = t * 4 + mm * (THREADS * 4);
if (i / N != c) continue;
const float4 r = rr[mm];
const float4 g = *reinterpret_cast<const float4*>(a.w_norm + i);
const float px = r.x * g.x, py = r.y * g.y, pz = r.z * g.z, pw = r.w * g.w;
*reinterpret_cast<float4*>(xn + i) = make_float4(px * rs, py * rs, pz * rs, pw * rs);
}
}
// `gr_up_multi_kernel`: COLS columns per block (x 4 streams). The weight rows and epilogue inputs of ALL of a warp's rows
// are loaded before the first dot (the Original loaded them row by row behind the previous row's dependent reduction).
template <int COLS>
__device__ __forceinline__ void gr_up_body(const GrMulti& m) {
constexpr int ROWS = HC * COLS;
constexpr int RPW = ROWS / WARPS;
__shared__ __align__(16) float lo[kFusedGrMaxT][LR];
__shared__ float g[kFusedGrMaxT][HC][COLS];
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const int T = m.T;
const int d0 = blockIdx.x * COLS;
uint4 wa[RPW], wb[RPW];
float rv[RPW], wn[RPW], rsc[RPW], bo[RPW], ip[RPW];
bool apply = false;
if (lane < T) apply = m.a[lane].apply;
#pragma unroll
for (int q = 0; q < RPW; ++q) {
const int r = warp + q * WARPS;
const int c = r / COLS, dd = r - c * COLS, i = c * N + d0 + dd;
const uint4* w4 = reinterpret_cast<const uint4*>(m.a[0].w_up + (size_t) i * LR);
wa[q] = __ldg(w4 + lane);
wb[q] = lane < LR / 8 - 32 ? __ldg(w4 + 32 + lane) : make_uint4(0, 0, 0, 0);
rv[q] = wn[q] = rsc[q] = bo[q] = ip[q] = 0.0f;
if (lane < T) {
const FusedGrArgs& a = m.a[lane];
rv[q] = a.R[i];
wn[q] = a.w_norm[i];
rsc[q] = a.rs[c];
if (apply) { bo[q] = a.bo_prev[d0 + dd]; ip[q] = a.inj_prev[c]; }
}
}
for (int i = t; i < T * LR; i += THREADS) lo[i / LR][i % LR] = m.a[i / LR].lo[i % LR];
__syncthreads();
#pragma unroll
for (int q = 0; q < RPW; ++q) {
const int r = warp + q * WARPS;
const int c = r / COLS, dd = r - c * COLS, i = c * N + d0 + dd;
float mine = 0.0f;
#pragma unroll
for (int k = 0; k < kFusedGrMaxT; ++k) {
if (k >= T) break;
float acc = dot8(wa[q], lo[k] + lane * 8);
if (lane < LR / 8 - 32) acc += dot8(wb[q], lo[k] + (32 + lane) * 8);
acc = warp_sum(acc);
if (lane == k) mine = acc;
}
if (lane < T) {
float rvq = rv[q];
if (apply) {
rvq = fmaf(bo[q], 2.0f * sigmoidf_(ip[q] / (float) HC), rvq);
m.a[lane].R_out[i] = rvq;
}
const float x = rvq * wn[q] * rsc[q];
g[lane][c][dd] = x * sigmoidf_(mine);
}
}
__syncthreads();
for (int i = t; i < T * COLS; i += THREADS) {
const int k = i / COLS, col = i - k * COLS;
float s = 0.0f;
#pragma unroll
for (int c = 0; c < HC; ++c) s += g[k][c][col];
m.a[k].mixed[d0 + col] = s / (float) HC;
}
}
extern "C" __global__ void __launch_bounds__(THREADS) chain_gr_up16(GrMulti m) { gr_up_body<16>(m); }
extern "C" __global__ void __launch_bounds__(THREADS) chain_gr_up8(GrMulti m) { gr_up_body<8>(m); }
// ------------------------------------------------------------------------------------------------------------------
// QSA decode attention chunk (`leleka_qsa_decode_chunk`, qsa_native_decode.cu, INT8 KV mode 1). The Original walks a
// block's 64 cells one dependent global load at a time in both phases (~40 us for 64 cells); here the loads of a whole
// round (the warp's 8 key rows / the 8 value rows of the PV loop) are issued before the first FMA. Every sum is formed
// in the same order as before (per head: lanes xor-reduced; PV: cells ascending, masked cells skipped), so the outputs
// are bit-identical.
// ------------------------------------------------------------------------------------------------------------------
namespace {
constexpr int Q_HD = 256, Q_G = 12, Q_CHUNK = 64, Q_THREADS = 256, Q_WARPS = Q_THREADS / 32, Q_GROUP = 64, kStepCount = 4, kStepWidth = 3;
__device__ __forceinline__ float warp_sum_q(float v) {
#pragma unroll
for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
return v;
}
__device__ __forceinline__ float warp_max_q(float v) {
#pragma unroll
for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o));
return v;
}
} // namespace
extern "C" __global__ void __launch_bounds__(Q_THREADS) chain_qsa_decode_chunk(
const float* __restrict__ q, const int8_t* kq, const int8_t* vq, const uint16_t* ks, const uint16_t* vs, const int32_t* table,
const int32_t* __restrict__ ids, const int32_t* __restrict__ step, int n_kv_heads, int page_size, float scale,
float* __restrict__ part_acc, float* __restrict__ part_m, float* __restrict__ part_l, int n_chunks, int cap, long long scratch_stride) {
q += (size_t) blockIdx.z * (size_t) (n_kv_heads * Q_G) * Q_HD;
ids += (size_t) blockIdx.z * (size_t) cap;
step += (size_t) blockIdx.z * kStepCount;
part_acc += (size_t) blockIdx.z * (size_t) scratch_stride;
part_m += (size_t) blockIdx.z * (size_t) scratch_stride;
part_l += (size_t) blockIdx.z * (size_t) scratch_stride;
__shared__ __align__(16) float sq[Q_G][Q_HD];
__shared__ float sp[Q_G][Q_CHUNK];
__shared__ long long srow[Q_CHUNK];
const int n_ids = __ldg(step + kStepWidth);
const int chunk = blockIdx.x, kvh = blockIdx.y;
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const int c0 = chunk * Q_CHUNK;
const int n_here = min(Q_CHUNK, n_ids - c0);
const int slot = kvh * n_chunks + chunk;
if (n_here <= 0) {
if (t < Q_G) { part_m[slot * Q_G + t] = -FLT_MAX; part_l[slot * Q_G + t] = 0.0f; }
return;
}
for (int i = t; i < Q_G * Q_HD; i += Q_THREADS) sq[i / Q_HD][i % Q_HD] = q[(size_t) (kvh * Q_G) * Q_HD + i];
if (t < Q_CHUNK) {
long long r = -1;
if (t < n_here) {
const int cell = ids[c0 + t];
const long long page = (long long) table[cell / page_size];
if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
}
srow[t] = r;
}
__syncthreads();
// scores: warp w takes cells w, w+8, ... (8 per warp); load every key row of the warp first.
constexpr int CPW = Q_CHUNK / Q_WARPS; // 8
uint2 kraw[CPW];
float ksc[CPW];
#pragma unroll
for (int i = 0; i < CPW; ++i) {
const int c = warp + i * Q_WARPS;
kraw[i] = make_uint2(0, 0);
ksc[i] = 0.0f;
if (c < n_here && srow[c] >= 0) {
const long long row = srow[c];
const uint16_t sbits = ks[row * (Q_HD / Q_GROUP) + (lane * 8) / Q_GROUP];
ksc[i] = __half2float(__ushort_as_half(sbits));
kraw[i] = *reinterpret_cast<const uint2*>(kq + row * Q_HD + lane * 8);
}
}
#pragma unroll
for (int i = 0; i < CPW; ++i) {
const int c = warp + i * Q_WARPS;
if (c >= n_here || srow[c] < 0) {
if (lane < Q_G) sp[lane][c] = -FLT_MAX;
continue;
}
float k8[8];
const int8_t* cc = reinterpret_cast<const int8_t*>(&kraw[i]);
#pragma unroll
for (int j = 0; j < 8; ++j) k8[j] = (float) cc[j] * ksc[i];
#pragma unroll
for (int h = 0; h < Q_G; ++h) {
const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);
const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + 4]);
float s = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w +
k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w;
s = warp_sum_q(s);
if (lane == 0) sp[h][c] = s * scale;
}
}
__syncthreads();
for (int h = warp; h < Q_G; h += Q_WARPS) {
const float a = sp[h][lane], b = sp[h][lane + 32];
const float m = warp_max_q(fmaxf(a, b));
const float ea = (lane < n_here && srow[lane] >= 0) ? __expf(a - m) : 0.0f;
const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? __expf(b - m) : 0.0f;
sp[h][lane] = ea;
sp[h][lane + 32] = eb;
const float l = warp_sum_q(ea + eb);
if (lane == 0) { part_m[slot * Q_G + h] = m; part_l[slot * Q_G + h] = l; }
}
__syncthreads();
// values: thread t owns dimension t for all 12 heads; rounds of 8 cells with all loads in flight.
float acc[Q_G];
#pragma unroll
for (int h = 0; h < Q_G; ++h) acc[h] = 0.0f;
constexpr int R = 8;
for (int cb = 0; cb < n_here; cb += R) {
float v[R];
bool ok[R];
#pragma unroll
for (int j = 0; j < R; ++j) {
const int c = cb + j;
ok[j] = c < n_here && srow[c] >= 0;
v[j] = 0.0f;
if (ok[j]) {
const float sc = __half2float(__ushort_as_half(vs[srow[c] * (Q_HD / Q_GROUP) + t / Q_GROUP]));
v[j] = (float) vq[srow[c] * Q_HD + t] * sc;
}
}
#pragma unroll
for (int j = 0; j < R; ++j) {
if (!ok[j]) continue;
#pragma unroll
for (int h = 0; h < Q_G; ++h) acc[h] = fmaf(sp[h][cb + j], v[j], acc[h]);
}
}
#pragma unroll
for (int h = 0; h < Q_G; ++h) part_acc[((size_t) slot * Q_G + h) * Q_HD + t] = acc[h];
}
// ------------------------------------------------------------------------------------------------------------------
// hyper-connection DOWN projection (`gr_down_staged_kernel`): the same arithmetic (lane l accumulates chunks l + 32 q of
// every token in ascending order with dot8v, then the xor warp reduction), different shape: W warps per block (one row
// per warp, ceil(324 / W) blocks instead of 41), the warp's whole weight row (40 chunks) loaded into registers in the
// prologue, and NB activation tile buffers in flight instead of 2.
// ------------------------------------------------------------------------------------------------------------------
namespace {
constexpr int H_TILE = 1280;
constexpr int N_HTILES = D / H_TILE; // 8
constexpr int HQ = H_TILE / 8 / 32; // 5 chunks per lane per tile
constexpr int DOWN_ROWS = LR + HC; // 320 down rows + 4 inject rows
__device__ __forceinline__ void cp_async16(void* smem, const void* gmem) {
const unsigned sa = (unsigned) __cvta_generic_to_shared(smem);
asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(sa), "l"(gmem) : "memory");
}
__device__ __forceinline__ void cp_async_commit() { asm volatile("cp.async.commit_group;\n" ::: "memory"); }
template <int N>
__device__ __forceinline__ void cp_async_wait() { asm volatile("cp.async.wait_group %0;\n" ::"n"(N) : "memory"); }
__device__ __forceinline__ float dot8v(const uint4 w, const float4 x0, const float4 x1) {
float acc = 0.0f;
acc = fmaf(__uint_as_float(w.x << 16), x0.x, acc);
acc = fmaf(__uint_as_float(w.x & 0xffff0000u), x0.y, acc);
acc = fmaf(__uint_as_float(w.y << 16), x0.z, acc);
acc = fmaf(__uint_as_float(w.y & 0xffff0000u), x0.w, acc);
acc = fmaf(__uint_as_float(w.z << 16), x1.x, acc);
acc = fmaf(__uint_as_float(w.z & 0xffff0000u), x1.y, acc);
acc = fmaf(__uint_as_float(w.w << 16), x1.z, acc);
acc = fmaf(__uint_as_float(w.w & 0xffff0000u), x1.w, acc);
return acc;
}
template <int W>
__device__ __forceinline__ void stage_tile(const GrMulti& m, int T, int h, float4* buf, int t) {
for (int i = t; i < T * (H_TILE / 4); i += W * 32) {
const int k = i / (H_TILE / 4), s4 = i - k * (H_TILE / 4);
const float* src = m.xn + (size_t) k * D + (size_t) h * H_TILE + (size_t) s4 * 4;
cp_async16(buf + (size_t) k * (H_TILE / 4) + (s4 & 1) * (H_TILE / 8) + (s4 >> 1), src);
}
}
template <int W, int NB>
__device__ __forceinline__ void gr_down_body(const GrMulti& m) {
extern __shared__ __align__(16) float4 hbuf[]; // NB x [T][2][160] float4
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const int T = m.T;
const int row = blockIdx.x * W + warp; // 0..319 down rows, 320..323 inject rows
const bool inject = row >= LR;
const bool active = row < DOWN_ROWS && !(inject && m.a[0].w_inject == nullptr);
const uint16_t* wrow = (inject ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? (inject ? row - LR : row) : 0) * D;
const uint4* w4 = reinterpret_cast<const uint4*>(wrow);
const size_t buf_f4 = (size_t) T * (H_TILE / 4);
float acc[kFusedGrMaxT];
#pragma unroll
for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f;
uint4 wv[N_HTILES][HQ];
if (active) {
#pragma unroll
for (int h = 0; h < N_HTILES; ++h)
#pragma unroll
for (int q = 0; q < HQ; ++q) wv[h][q] = __ldg(w4 + h * (H_TILE / 8) + lane + 32 * q);
}
#pragma unroll
for (int b = 0; b < NB - 1; ++b) {
stage_tile<W>(m, T, b, hbuf + b * buf_f4, t);
cp_async_commit();
}
#pragma unroll
for (int h = 0; h < N_HTILES; ++h) {
cp_async_wait<NB - 2>();
__syncthreads();
const float4* cur = hbuf + (h % NB) * buf_f4;
if (active) {
#pragma unroll
for (int q = 0; q < HQ; ++q) {
const int j = lane + 32 * q;
#pragma unroll
for (int k = 0; k < kFusedGrMaxT; ++k) {
if (k < T) {
const float4* pk = cur + (size_t) k * (H_TILE / 4);
acc[k] += dot8v(wv[h][q], pk[j], pk[H_TILE / 8 + j]);
}
}
}
}
__syncthreads();
if (h + NB - 1 < N_HTILES) stage_tile<W>(m, T, h + NB - 1, hbuf + ((h + NB - 1) % NB) * buf_f4, t);
cp_async_commit();
}
if (!active) return;
float s[kFusedGrMaxT];
#pragma unroll
for (int k = 0; k < kFusedGrMaxT; ++k) s[k] = k < T ? warp_sum(acc[k]) : 0.0f;
#pragma unroll
for (int k = 0; k < kFusedGrMaxT; ++k) {
if (k >= T || lane != k) continue;
if (inject) {
m.a[k].inject_out[row - LR] = s[k];
} else {
const float x = s[k] / (float) HC;
m.a[k].lo[row] = x / (1.0f + __expf(-x));
}
}
}
} // namespace
#define CHAIN_GR_DOWN(W, NB) \
extern "C" __global__ void __launch_bounds__((W) * 32) chain_gr_down_w##W##_nb##NB(GrMulti m) { gr_down_body<W, NB>(m); }
CHAIN_GR_DOWN(4, 3)
CHAIN_GR_DOWN(8, 2) CHAIN_GR_DOWN(8, 3) CHAIN_GR_DOWN(8, 4)
// ------------------------------------------------------------------------------------------------------------------
// small fusions (group `tiny`)
// ------------------------------------------------------------------------------------------------------------------
namespace {
struct Q81Block {
__half2 ds;
int8_t qs[32];
};
static_assert(sizeof(Q81Block) == 36, "block_q8_1 layout");
} // namespace
// `swiglu_entries_kernel` + `quantize_q8_1_kernel` of the routed experts (iq_kernels.cu): h = silu(gate) * up, stored as the
// first kernel stored it, and quantized from the register instead of from memory (the same float, the same operations).
extern "C" __global__ void chain_swiglu_quant_kernel(const float* __restrict__ gate, const float* __restrict__ up, float* __restrict__ h,
Q81Block* __restrict__ y, long long n) {
const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x;
if (i >= n) return;
const float g = gate[i];
const float xi = (g / (1.0f + __expf(-g))) * up[i];
h[i] = xi;
float amax = fabsf(xi), sum = xi;
#pragma unroll
for (int o = 16; o > 0; o >>= 1) {
amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));
sum += __shfl_xor_sync(0xffffffffu, sum, o);
}
const float d = amax / 127.0f;
const int8_t q = amax == 0.0f ? 0 : roundf(xi / d);
const long long ib = i / 32, iqs = i % 32;
y[ib].qs[iqs] = q;
if (iqs == 0) y[ib].ds = make_half2(d, sum);
}
// `native_scalar_sigmoid(_multi)_kernel` + `scale_rows_kernel` of the shared expert: the gate scalar's sigmoid is evaluated
// by every block that scales a row (the same intrinsics on the same raw gate), the gate buffer itself is left raw.
extern "C" __global__ void chain_scale_rows_sigmoid_kernel(float* __restrict__ out, const float* __restrict__ g, int n) {
const int t = blockIdx.y;
const int i = blockIdx.x * blockDim.x + threadIdx.x;
const float gate = __fdividef(1.0f, 1.0f + __expf(-g[t]));
if (i < n) out[(size_t) t * n + i] *= gate;
}
// ------------------------------------------------------------------------------------------------------------------
// sampler (group `head`): the Original's one-block-per-token scans issue one dependent global load per element round; here a
// round of 8 loads is in flight before the first compare / add. Every thread still visits its elements in ascending order,
// so the picks (total order: larger value, lower index) and the sums are bit-identical.
// ------------------------------------------------------------------------------------------------------------------
extern "C" __global__ void chain_row_top_prob_kernel(const float* __restrict__ logits, int n_vocab, const int32_t* __restrict__ ids,
float* __restrict__ probs) {
__shared__ float part[32];
const int t = blockIdx.x;
const float* l = logits + (size_t) t * n_vocab;
const float m = l[ids[t]];
float s = 0.0f;
for (int base = 0; base < n_vocab; base += 8 * blockDim.x) {
float x[8];
#pragma unroll
for (int u = 0; u < 8; ++u) {
const int i = base + u * blockDim.x + threadIdx.x;
if (i < n_vocab) x[u] = l[i];
}
#pragma unroll
for (int u = 0; u < 8; ++u) {
const int i = base + u * blockDim.x + threadIdx.x;
if (i < n_vocab) s += __expf(x[u] - m);
}
}
for (int o = 16; o > 0; o >>= 1) s += __shfl_xor_sync(0xffffffffu, s, o);
if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = s;
__syncthreads();
if (threadIdx.x == 0) {
float tot = 0.0f;
for (int w = 0; w < (int) (blockDim.x >> 5); ++w) tot += part[w];
probs[t] = 1.0f / tot;
}
}
namespace {
__device__ __forceinline__ int history_count(const int* __restrict__ h, int n, int v) {
int c = 0;
for (int i = 0; i < n; ++i) if (h[i] == v) ++c;
return c;
}
__device__ __forceinline__ float apply_penalties(float logit, int count, const strata::kernels::SamplerParams& p) {
if (count <= 0) return logit;
if (logit <= 0.0f) logit *= p.penalty_repeat;
else logit /= p.penalty_repeat;
logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present;
return logit;
}
} // namespace
extern "C" __global__ void chain_sampler_greedy_kernel(const float* __restrict__ logits, int n_vocab, const int* __restrict__ history,
int history_len, const strata::kernels::SamplerParams p, int pmin, int plen,
int* __restrict__ out) {
const int t = blockIdx.x;
const float* l = logits + (size_t) t * n_vocab;
(void) pmin;
const int* hrow = history ? history + (size_t) t * history_len : nullptr;
int hlen = 0;
if (hrow) {
hlen = plen < history_len ? plen : history_len;
if (hlen < 0) hlen = 0;
hrow += history_len - hlen;
}
extern __shared__ unsigned int penal_bits[];
const int bits_words = (int) ((n_vocab + 31) / 32);
const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0;
if (use_bits) {
for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u;
__syncthreads();
for (int i = threadIdx.x; i < hlen; i += blockDim.x)
if (hrow[i] >= 0 && hrow[i] < n_vocab)
atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));
__syncthreads();
}
auto hit_count = [&](int v) -> int {
if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0;
return history_count(hrow, hlen, v);
};
float bv = __int_as_float(0xff800000);
int best = n_vocab;
for (int base = 0; base < n_vocab; base += 8 * blockDim.x) {
float x[8];
#pragma unroll
for (int u = 0; u < 8; ++u) {
const int v = base + u * blockDim.x + threadIdx.x;
if (v < n_vocab) x[u] = l[v];
}
#pragma unroll
for (int u = 0; u < 8; ++u) {
const int v = base + u * blockDim.x + threadIdx.x;
if (v < n_vocab) {
const float s = apply_penalties(x[u], hit_count(v), p);
if (s > bv) { bv = s; best = v; }
}
}
}
for (int off = 16; off > 0; off >>= 1) {
const float ov = __shfl_down_sync(0xFFFFFFFFu, bv, off);
const int oi = __shfl_down_sync(0xFFFFFFFFu, best, off);
if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; }
}
__shared__ float sv[32];
__shared__ int si[32];
const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31);
if (lane == 0) { sv[warp] = bv; si[warp] = best; }
__syncthreads();
if (warp == 0) {
const int nw = (int) ((blockDim.x + 31) >> 5);
float wv = lane < nw ? sv[lane] : __int_as_float(0xff800000);
int wi = lane < nw ? si[lane] : n_vocab;
for (int off = 16; off > 0; off >>= 1) {
const float ov = __shfl_down_sync(0xFFFFFFFFu, wv, off);
const int oi = __shfl_down_sync(0xFFFFFFFFu, wi, off);
if (ov > wv || (ov == wv && oi < wi)) { wv = ov; wi = oi; }
}
if (lane == 0) out[t] = (wi < n_vocab) ? wi : 0;
}
}
// `leleka_qsa_decode_merge` for graphs whose chunk grid is sized for the whole context (the MTP draft: 512 chunks): chunks past the
// row's last cell hold m = -FLT_MAX / l = 0 and are skipped by the Original's second loop and cannot raise its maximum, so looping over
// the chunks that hold cells (ceil(n_ids / 64), n_ids = step[3]) forms the same M, L and acc in the same order.
extern "C" __global__ void __launch_bounds__(Q_HD) chain_qsa_decode_merge_n(const float* __restrict__ part_acc, const float* __restrict__ part_m,
const float* __restrict__ part_l, int n_chunks,
float* __restrict__ attn, long long scratch_stride,
const int32_t* __restrict__ step) {
part_acc += (size_t) blockIdx.y * (size_t) scratch_stride;
part_m += (size_t) blockIdx.y * (size_t) scratch_stride;
part_l += (size_t) blockIdx.y * (size_t) scratch_stride;
attn += (size_t) blockIdx.y * (size_t) gridDim.x * Q_HD;
const int n_ids = __ldg(step + (size_t) blockIdx.y * kStepCount + kStepWidth);
const int used = min(n_chunks, (n_ids + Q_CHUNK - 1) / Q_CHUNK);
const int h = blockIdx.x;
const int kvh = h / Q_G, hl = h % Q_G;
const int d = threadIdx.x;
float M = -FLT_MAX;
for (int c = 0; c < used; ++c) M = fmaxf(M, part_m[(kvh * n_chunks + c) * Q_G + hl]);
float L = 0.0f, acc = 0.0f;
for (int c = 0; c < used; ++c) {
const int slot = kvh * n_chunks + c;
const float m = part_m[slot * Q_G + hl];
if (m == -FLT_MAX) continue;
const float w = __expf(m - M);
L = fmaf(part_l[slot * Q_G + hl], w, L);
acc = fmaf(part_acc[((size_t) slot * Q_G + hl) * Q_HD + d], w, acc);
}
attn[(size_t) h * Q_HD + d] = L > 0.0f ? acc / L : 0.0f;
}
File diff suppressed because it is too large Load Diff
+11
View File
@@ -3291,6 +3291,17 @@ pub use mtp_dense_kv::{
OriginalMtpGrVariant, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy,
OriginalMtpScalarPrefill,
};
/// `LELEKA_CHAIN` selects the chain-kernel group `mtp` (claude/chain-kernels): the draft step reads the hyper-connections with the
/// staged variant the Original runs on this card (bit-identical to the plain one) and uses the load-hoisted attention kernels.
#[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))]
pub fn chain_selects_mtp() -> bool {
original_verify::chain::flags().mtp
}
#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))]
pub fn chain_selects_mtp() -> bool {
false
}
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
@@ -659,7 +659,13 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
c.retain_driver();
})?;
let load = (|| {
for (p, e) in symbols::ASSETS {
for (p, e) in &symbols::ASSETS[..symbols::CHAIN_ASSET] {
o.modules.push(Rc::new(FM::load(p, e)?));
}
if chain_mtp_assets() {
// chain_window.ptx: loaded only when selected, and only if it is the sealed one
crate::original_verify::chain::CHAIN.sealed()?;
let (p, e) = &symbols::ASSETS[symbols::CHAIN_ASSET];
o.modules.push(Rc::new(FM::load(p, e)?));
}
Ok(())
@@ -859,6 +865,11 @@ fn push(
});
Ok(())
}
/// `LELEKA_CHAIN` selects a group that launches from the chain module inside the MTP draft program.
fn chain_mtp_assets() -> bool {
let f = crate::original_verify::chain::flags();
f.mtp || f.head
}
fn fixed_entry(asset: usize, name: &str) -> Result<usize> {
symbols::ASSETS
.get(asset)
@@ -1001,6 +1012,8 @@ impl OriginalMtpFullForward<'_> {
// chunk and merge entries. Ring owns pools/table/ident/scratch throughout.
// window command uses ring's actual KV module in the captured program.
let (pa, pm, pl, ident) = o.attention(p.ring)?;
let chain_mtp = crate::original_verify::chain::flags().mtp;
// the Original's chunk kernel in both modes (the load-hoisted variant measured no faster); only the merge changes
push(
&mut v,
19,
@@ -1028,21 +1041,25 @@ impl OriginalMtpFullForward<'_> {
F::I64(SCRATCH_FLOATS as i64),
],
)?;
let mut merge_args = vec![
F::U64(pa),
F::U64(pm),
F::U64(pl),
F::I32(CHUNKS as i32),
F::U64(attn),
F::I64(SCRATCH_FLOATS as i64),
];
if chain_mtp {
merge_args.push(F::U64(p.step)); // the row's step words: n_ids bounds the merge to the chunks that hold cells
}
push(
&mut v,
19,
1,
if chain_mtp { symbols::CHAIN_ASSET } else { 19 },
if chain_mtp { symbols::CHAIN_QSA_MERGE_N } else { 1 },
[24, 1, 1],
[256, 1, 1],
0,
vec![
F::U64(pa),
F::U64(pm),
F::U64(pl),
F::I32(CHUNKS as i32),
F::U64(attn),
F::I64(SCRATCH_FLOATS as i64),
],
merge_args,
)?;
self.finite_tail(&mut v, attn, 6144, 3)?;
push(
@@ -1434,10 +1451,11 @@ impl OriginalMtpFullForward<'_> {
let mut greedy = SamplerParams::default();
greedy.greedy = true;
greedy.temperature = 0.0;
let chain_head = crate::original_verify::chain::flags().head;
push(
&mut v,
15,
0,
if chain_head { symbols::CHAIN_ASSET } else { 15 },
if chain_head { symbols::CHAIN_SAMPLER_GREEDY } else { 0 },
[1, 1, 1],
[1024, 1, 1],
0,
@@ -1454,8 +1472,8 @@ impl OriginalMtpFullForward<'_> {
)?;
push(
&mut v,
12,
0,
if chain_head { symbols::CHAIN_ASSET } else { 12 },
if chain_head { symbols::CHAIN_ROW_TOP_PROB } else { 0 },
[1, 1, 1],
[1024, 1, 1],
0,
@@ -415,4 +415,21 @@ pub(super) const ASSETS: &[(&[u8], &[&CStr])] = &[
c"coupled_merge_kernel",
],
),
// 21: chain_window.ptx (claude/chain-kernels), loaded only when LELEKA_CHAIN selects a group that launches from it
// (`CHAIN_ASSET`); checked against its pin (`original_verify::chain::CHAIN`) before it is handed to the driver.
(
concat!(include_str!("chain_window.ptx"), "\0").as_bytes(),
&[
c"chain_qsa_decode_chunk",
c"chain_qsa_decode_merge_n",
c"chain_sampler_greedy_kernel",
c"chain_row_top_prob_kernel",
],
),
];
/// Index of the chain module in `ASSETS` (absent from the loaded modules unless `LELEKA_CHAIN` selects `mtp` or `head`).
pub(super) const CHAIN_ASSET: usize = 21;
pub(super) const CHAIN_QSA_CHUNK: usize = 0;
pub(super) const CHAIN_QSA_MERGE_N: usize = 1;
pub(super) const CHAIN_SAMPLER_GREEDY: usize = 2;
pub(super) const CHAIN_ROW_TOP_PROB: usize = 3;
+18 -4
View File
@@ -184,6 +184,10 @@ fn disjoint(a: &DeviceBuffer<'_>, b: &DeviceBuffer<'_>) -> Result<()> {
Ok(())
}
}
/// The greedy argmax entry: the Original's, or the load-hoisted chain variant (bit-identical picks) when `LELEKA_CHAIN=head`.
fn greedy_entry() -> &'static str {
if crate::original_verify::chain::flags().head { crate::original_verify::chain::E_SAMPLER_GREEDY } else { "sampler_greedy_kernel" }
}
fn cmd(name: &'static str, grid: [u32; 3], block: [u32; 3], args: Vec<Arg>) -> Result<Command> {
Command::new(name, grid, block, 0, args)
}
@@ -191,6 +195,8 @@ struct Kernels {
native: Option<Module>,
iq: Option<Module>,
sampler: Option<Module>,
/// `chain_window.ptx` (claude/chain-kernels), loaded only when a chain group that launches from the head module set is on.
chain: Option<Module>,
}
impl Kernels {
fn load() -> Result<Self> {
@@ -201,11 +207,16 @@ impl Kernels {
native: None,
iq: None,
sampler: None,
chain: None,
};
let op = (|| {
owner.native = Some(Module::load(n, NATIVE_ENTRIES)?);
owner.iq = Some(Module::load(i, IQ_ENTRIES)?);
owner.sampler = Some(Module::load(s, SAMPLER_ENTRIES)?);
if crate::original_verify::chain::flags().head {
let chain = &crate::original_verify::chain::CHAIN;
owner.chain = Some(Module::load(chain.sealed()?, chain.entries)?);
}
Ok(())
})();
if let Err(primary) = op {
@@ -214,7 +225,9 @@ impl Kernels {
Ok(owner)
}
fn module(&self, name: &str) -> Result<&Module> {
let m = if name.starts_with("head_n") || name == "head_quant" {
let m = if name.starts_with("chain_") {
&self.chain
} else if name.starts_with("head_n") || name == "head_quant" {
&self.native
} else if name.starts_with("head_i") || name.starts_with("head_embed") {
&self.iq
@@ -224,10 +237,11 @@ impl Kernels {
m.as_ref().ok_or(Error::ContextPoisoned)
}
fn close(mut self) -> Result<()> {
let c = self.chain.take().map_or(Ok(()), Module::close);
let s = self.sampler.take().map_or(Ok(()), Module::close);
let i = self.iq.take().map_or(Ok(()), Module::close);
let n = self.native.take().map_or(Ok(()), Module::close);
combine(combine(s, i), n)
combine(combine(combine(s, i), n), c)
}
}
struct SamplingScratch<'ctx> {
@@ -639,7 +653,7 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> {
p.greedy = true;
p.temperature = 0.0;
Command::new(
"sampler_greedy_kernel",
greedy_entry(),
[self.t as u32, 1, 1],
[1024, 1, 1],
0,
@@ -816,7 +830,7 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> {
c.try_reserve_exact(2).map_err(|_| Error::HostAllocation)?;
if p.greedy || p.temperature <= 0.0 {
c.push(Command::new(
"sampler_greedy_kernel",
greedy_entry(),
[self.t as u32, 1, 1],
[1024, 1, 1],
shared.try_into().map_err(|_| Error::InvalidSize)?,
@@ -14,6 +14,7 @@
#[path="original_verify_window_gr.rs"] pub(crate) mod gr;
#[path="original_verify_window_qsa.rs"] pub(crate) mod qsa;
#[path="original_verify_window_moe.rs"] pub(crate) mod moe;
#[path="original_verify_window_chain.rs"] pub(crate) mod chain;
#[path="original_verify_window_planner.rs"] pub(crate) mod planner;
#[cfg(test)] #[path="original_verify_window_gpu.rs"] mod window_gpu;
pub use layout::{OriginalVerifyGeometry,OriginalVerifyLayout,OriginalVerifySpan};
@@ -296,6 +297,10 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx>{
/// Real group doorbell after the original router. The host may borrow only
/// this completed group's mapped rows, while the captured GPU waits for M/A/B.
pub fn capture_doorbell(&self,capture:&mut OriginalCapture<'_, 'ctx>,begin:usize,end:usize)->Result<()>{let g=self.geometry();if begin>=end||end>g.max_t{return Err(Error::InvalidQwenShape)}let n=end-begin;
if chain::flags().glue{
let a=|name:&str,off:usize,bytes:usize|self.physical.span(name,off,bytes);
return self.submit_launches(capture,vec![kernels::Launch::new(&chain::CHAIN,chain::E_DOORBELL,[1,1,1],[1024,1,1],0,vec![kernels::A::P(a("mixed",begin*g.n*4,n*g.n*4)?),kernels::A::P(a("ids",begin*g.k*4,n*g.k*4)?),kernels::A::P(a("w",begin*g.k*4,n*g.k*4)?),kernels::A::I32((n*g.n)as i32),kernels::A::I32((n*g.k)as i32),kernels::A::P(self.physical.mapped_address(6,begin*g.n*4,n*g.n*4)?),kernels::A::P(self.physical.mapped_address(7,begin*g.k*4,n*g.k*4)?),kernels::A::P(self.physical.mapped_address(8,begin*g.k*4,n*g.k*4)?),kernels::A::P(self.physical.mapped_address(9,0,4)?)])?]);
}
self.submit(capture,vec![command("verify_doorbell_publish_kernel",[1,1,1],[1024,1,1],vec![Arg::Address(self.physical.span("mixed",begin*g.n*4,n*g.n*4)?),Arg::Address(self.physical.span("ids",begin*g.k*4,n*g.k*4)?),Arg::Address(self.physical.span("w",begin*g.k*4,n*g.k*4)?),Arg::I32((n*g.n)as i32),Arg::I32((n*g.k)as i32),Arg::Address(self.physical.mapped_address(6,begin*g.n*4,n*g.n*4)?),Arg::Address(self.physical.mapped_address(7,begin*g.k*4,n*g.k*4)?),Arg::Address(self.physical.mapped_address(8,begin*g.k*4,n*g.k*4)?),Arg::Address(self.physical.mapped_address(9,0,4)?)])?])
}
/// Exact batch convolution, BF16 MMVF alpha/beta, and recurrence. Canonical
@@ -310,6 +315,10 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx>{
commands.push(command("verify_gdn_conv_l2_multi_kernel",[80,n as u32,1],[128,1,1],vec![Arg::Address(self.canonical.span(layer,true)?),Arg::Address(qkv),Arg::Address(admit(c,w.conv,10240*4*4)?),Arg::Address(h),Arg::I32(10240),Arg::I32(32),Arg::F32(EPS),Arg::I32(begin as i32)])?);
commands.push(command("verify_gdn_ab_multi_kernel",[12,1,1],[256,1,1],vec![Arg::Address(self.physical.span("mixed",begin*g.n*4,n*g.n*4)?),Arg::Address(admit(c,w.alpha,48*2560*2)?),Arg::Address(admit(c,w.beta,48*2560*2)?),Arg::Address(admit(c,w.dt,48*4)?),Arg::Address(admit(c,w.a,48*4)?),Arg::Address(gate+(begin*48*4) as u64),Arg::Address(beta+(begin*48*4) as u64),Arg::I32(2560),Arg::I32(48),Arg::I32(n as i32)])?);
commands.push(command("verify_gdn_step_norm_multi_kernel",[48,1,1],[128,4,1],vec![Arg::Address(self.canonical.span(layer,false)?),Arg::Address(h),Arg::I32(10240),Arg::Address(gate),Arg::Address(beta),Arg::Address(self.physical.span("z",0,g.max_t*6144*4)?),Arg::Address(admit(c,w.norm,128*4)?),Arg::F32(EPS),Arg::Address(self.physical.span("y",0,g.max_t*6144*4)?),Arg::I32(16),Arg::I32(48),Arg::I32(end as i32),Arg::Address(0),Arg::I32(begin as i32)])?);
if chain::flags().ab&&matches!(stage,OriginalVerifyGdnStage::AlphaBeta){
let x=self.physical.span("mixed",begin*g.n*4,n*g.n*4)?;
return self.submit_launches(capture,vec![kernels::Launch::new(&chain::CHAIN,chain::E_GDN_AB,[96,1,1],[32,1,1],0,vec![kernels::A::P(x),kernels::A::P(admit(c,w.alpha,48*2560*2)?),kernels::A::P(admit(c,w.beta,48*2560*2)?),kernels::A::P(admit(c,w.dt,48*4)?),kernels::A::P(admit(c,w.a,48*4)?),kernels::A::P(gate+(begin*48*4) as u64),kernels::A::P(beta+(begin*48*4) as u64),kernels::A::I32(2560),kernels::A::I32(48),kernels::A::I32(n as i32)])?]);
}
let mut selected=Vec::new();selected.try_reserve_exact(1).map_err(|_|Error::HostAllocation)?;selected.push(commands.swap_remove(stage as usize));self.submit(capture,selected)
}
/// First node of the literal commit graph: accepted count/row/positions.
@@ -0,0 +1,153 @@
//! claude/chain-kernels: switches and the sealed asset of the latency-hoisted chain kernels (`chain_window.cu`).
//!
//! Every kernel of `chain_window.ptx` replaces one kernel (or kernel pair) of the Original-literal verify window and
//! computes every output with the same operations in the same order (bit-identical; probed model-free by
//! `tools/chain-probe/chain_probe.cpp`). They are OFF unless selected, so the default window is the Original's:
//!
//! * `LELEKA_CHAIN=all` (or `1`, `on`) turns every group on except `qsa` (measured slower, section 6 of docs/chain-kernels.md); a comma list (`glue,ab,gr,qsa`) selects some;
//! `LELEKA_CHAIN_<GROUP>=0|1` overrides one group (`GLUE`, `AB`, `GR`, `QSA`, `TINY`, `HEAD`, `MTP`).
//! * `glue`: plan copy (`wait flag A` + `copy_i32_from_mapped` in one launch), CPU-row copy, doorbell publish.
//! * `ab`: GDN alpha/beta gates with the weight loads hoisted.
//! * `gr`: hyper-connection read: norm with the R' values kept in registers, up projection with all loads hoisted.
//! * `qsa`: decode attention chunk with the key/value loads of a round issued together.
//! * `head`: the greedy argmax (and the MTP draft's top-probability sum) with the logit loads of a round issued together.
//! * `mtp`: the MTP draft chain step: staged hyper-connection read, the load-hoisted attention chunk, a merge over the used chunks only
//! (with `head`: the load-hoisted greedy argmax and top-probability sum).
//! * `tiny`: dead `to_bf16` of the shared expert dropped, sigmoid + row scale and swiglu + q8_1 quantization fused.
use super::kernels::AssetSpec;
pub(crate) const E_COPY_I32: &str = "chain_copy_i32_from_mapped_kernel";
pub(crate) const E_WAIT_COPY_I32: &str = "chain_wait_copy_i32_kernel";
pub(crate) const E_COPY_ROWS: &str = "chain_copy_rows_from_mapped_kernel";
pub(crate) const E_DOORBELL: &str = "chain_doorbell_publish_kernel";
pub(crate) const E_GDN_AB: &str = "chain_gdn_ab_multi_kernel";
pub(crate) const E_GR_SPLIT: &str = "chain_gr_split";
pub(crate) const E_GR_UP16: &str = "chain_gr_up16";
pub(crate) const E_GR_UP8: &str = "chain_gr_up8";
pub(crate) const E_GR_DOWN_NB2: &str = "chain_gr_down_w8_nb2";
pub(crate) const E_GR_DOWN_NB3: &str = "chain_gr_down_w8_nb3";
pub(crate) const E_QSA_CHUNK: &str = "chain_qsa_decode_chunk";
pub(crate) const E_SWIGLU_QUANT: &str = "chain_swiglu_quant_kernel";
pub(crate) const E_SCALE_SIGMOID: &str = "chain_scale_rows_sigmoid_kernel";
pub(crate) const E_SAMPLER_GREEDY: &str = "chain_sampler_greedy_kernel";
pub(crate) const E_ROW_TOP_PROB: &str = "chain_row_top_prob_kernel";
pub(crate) const E_QSA_MERGE_N: &str = "chain_qsa_decode_merge_n";
/// Sealed by `scripts/gpu-bringup/seal_pins.py` (extra-seal-plan.json, group chain-window).
pub(crate) static CHAIN: AssetSpec = AssetSpec {
name: "chain_window.ptx",
ptx: concat!(include_str!("chain_window.ptx"), "\0").as_bytes(),
sha: [179, 71, 154, 144, 78, 250, 34, 150, 223, 208, 102, 129, 88, 17, 29, 166, 253, 74, 178, 94, 35, 165, 15, 209, 196, 213, 62, 218, 241, 50, 6, 41],
entries: &[E_COPY_I32, E_WAIT_COPY_I32, E_COPY_ROWS, E_DOORBELL, E_GDN_AB, E_GR_SPLIT, E_GR_UP16, E_GR_UP8, E_GR_DOWN_NB2, E_GR_DOWN_NB3, E_QSA_CHUNK, E_SWIGLU_QUANT, E_SCALE_SIGMOID, E_SAMPLER_GREEDY, E_ROW_TOP_PROB, E_QSA_MERGE_N],
unsealed: "Original verifier asset unsealed: chain_window.ptx (latency-hoisted chain kernels)",
};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct ChainFlags {
pub glue: bool,
pub ab: bool,
pub gr: bool,
pub qsa: bool,
pub tiny: bool,
pub head: bool,
pub mtp: bool,
}
impl ChainFlags {
pub(crate) fn any(&self) -> bool {
self.glue || self.ab || self.gr || self.qsa || self.tiny || self.head || self.mtp
}
/// Parse the master switch and the per-group overrides from an environment lookup.
pub(crate) fn parse(get: impl Fn(&str) -> Option<String>) -> Self {
let master = get("LELEKA_CHAIN").unwrap_or_default().to_ascii_lowercase();
let all = matches!(master.as_str(), "all" | "1" | "on" | "yes" | "true");
let listed = |name: &str| master.split(',').any(|p| p.trim() == name);
let one = |name: &str, var: &str| match get(var).as_deref() {
Some("0") | Some("off") | Some("no") => false,
Some("1") | Some("on") | Some("yes") => true,
_ => all || listed(name),
};
Self {
glue: one("glue", "LELEKA_CHAIN_GLUE"),
ab: one("ab", "LELEKA_CHAIN_AB"),
gr: one("gr", "LELEKA_CHAIN_GR"),
// `all` leaves `qsa` out: the load-hoisted chunk measured slower than the Original's (30.2 against 29.0 us at 4 rows, job 9c1b)
qsa: match get("LELEKA_CHAIN_QSA").as_deref() {
Some("1") | Some("on") | Some("yes") => true,
Some("0") | Some("off") | Some("no") => false,
_ => listed("qsa"),
},
tiny: one("tiny", "LELEKA_CHAIN_TINY"),
head: one("head", "LELEKA_CHAIN_HEAD"),
mtp: one("mtp", "LELEKA_CHAIN_MTP"),
}
}
}
/// The switches, read once per process (they decide which kernels a window graph records).
pub(crate) fn flags() -> ChainFlags {
#[cfg(test)]
if let Some(f) = TEST_FLAGS.with(|c| c.get()) {
return f;
}
static FLAGS: std::sync::OnceLock<ChainFlags> = std::sync::OnceLock::new();
*FLAGS.get_or_init(|| ChainFlags::parse(|k| std::env::var(k).ok()))
}
#[cfg(test)]
thread_local! {
static TEST_FLAGS: std::cell::Cell<Option<ChainFlags>> = const { std::cell::Cell::new(None) };
}
/// Test-only: run `f` with the switches forced on this thread.
#[cfg(test)]
pub(crate) fn with_flags<R>(flags: ChainFlags, f: impl FnOnce() -> R) -> R {
let old = TEST_FLAGS.with(|c| c.replace(Some(flags)));
let r = f();
TEST_FLAGS.with(|c| c.set(old));
r
}
/// The hyper-connection up projection with 8 columns per block (320 blocks, 5.7 us at 4 rows against 7.7 us for 16 columns and 8.9 us for
/// the Original's, job 9c1); `LELEKA_CHAIN_UP8=0` selects the 16-column shape.
pub(crate) fn up8() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("LELEKA_CHAIN_UP8").map_or(true, |v| v != "0"))
}
/// The chain asset when any group is on (the window preloads it before capture).
pub(crate) fn assets() -> Vec<&'static AssetSpec> {
if flags().any() { vec![&CHAIN] } else { Vec::new() }
}
#[cfg(test)]
mod tests {
use super::*;
fn env(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
move |k| pairs.iter().find(|(n, _)| *n == k).map(|(_, v)| v.to_string())
}
#[test]
fn the_chain_asset_is_sealed_and_exports_every_entry() {
CHAIN.assert_sealed_and_fail_closed();
assert!(CHAIN.sealed().is_ok());
assert_eq!(CHAIN.entries.len(), 16);
}
#[test]
fn off_by_default_and_the_master_switch_selects_groups() {
assert_eq!(ChainFlags::parse(env(&[])), ChainFlags::default());
assert!(!ChainFlags::parse(env(&[])).any());
let all = ChainFlags::parse(env(&[("LELEKA_CHAIN", "all")]));
assert_eq!(all, ChainFlags { glue: true, ab: true, gr: true, qsa: false, tiny: true, head: true, mtp: true });
let some = ChainFlags::parse(env(&[("LELEKA_CHAIN", "glue, qsa")]));
assert_eq!(some, ChainFlags { glue: true, ab: false, gr: false, qsa: true, tiny: false, head: false, mtp: false });
}
#[test]
fn a_group_variable_overrides_the_master_switch() {
let f = ChainFlags::parse(env(&[("LELEKA_CHAIN", "all"), ("LELEKA_CHAIN_GR", "0")]));
assert_eq!(f, ChainFlags { glue: true, ab: true, gr: false, qsa: false, tiny: true, head: true, mtp: true });
let g = ChainFlags::parse(env(&[("LELEKA_CHAIN_AB", "1")]));
assert_eq!(g, ChainFlags { glue: false, ab: true, gr: false, qsa: false, tiny: false, head: false, mtp: false });
}
}
@@ -256,6 +256,12 @@ pub(crate) fn shared_attributes(cfg: &GrConfig) -> Vec<(&'static AssetSpec, &'st
if let Some(bytes) = cfg.attr_staged {
out.push((&GR_FUSED, E_STAGED, bytes as usize));
}
if super::chain::flags().gr {
// the chain down kernels stage up to 3 x 6 tokens (92,160 B) or 2 x 8 tokens (81,920 B) of activations
let bytes = cfg.usable_shared.min(3 * 6 * (STAGED_TILE * 4)) as usize;
out.push((&super::chain::CHAIN, super::chain::E_GR_DOWN_NB3, bytes));
out.push((&super::chain::CHAIN, super::chain::E_GR_DOWN_NB2, cfg.usable_shared.min(2 * 8 * (STAGED_TILE * 4)) as usize));
}
out
}
@@ -478,7 +484,10 @@ pub(crate) fn plan_hc_read(
let full = multi_words(&per_row, w, apply, xn);
// norm: variant >= split is [n, 4] blocks, the plain read [n] blocks
let norm = if cfg.variant == GrVariant::Plain {
let chain_gr = super::chain::flags().gr && cfg.variant == GrVariant::Staged;
let norm = if chain_gr {
Launch::new(&super::chain::CHAIN, super::chain::E_GR_SPLIT, [n as u32, HC as u32, 1], [THREADS, 1, 1], 0, vec![A::Words(full.clone())])?
} else if cfg.variant == GrVariant::Plain {
Launch::new(&GR_FUSED, E_NORM, [n as u32, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full.clone())])?
} else {
Launch::new(&GR_FUSED, E_SPLIT, [n as u32, HC as u32, 1], [THREADS, 1, 1], 0, vec![A::Words(full.clone())])?
@@ -500,6 +509,24 @@ pub(crate) fn plan_hc_read(
// the card cannot launch it (Original would fail the launch)
return Err(Error::InvalidProjectionShape);
}
if chain_gr && staged {
// same arithmetic as the staged kernel; the whole weight row in registers and three (two above six tokens) tile buffers in flight
let (entry, buffers) = if ct <= 6 { (super::chain::E_GR_DOWN_NB3, 3) } else { (super::chain::E_GR_DOWN_NB2, 2) };
let shared = buffers * ct as u32 * (STAGED_TILE * 4);
if shared > cfg.usable_shared {
return Err(Error::InvalidProjectionShape);
}
down.push(Launch::new(
&super::chain::CHAIN,
entry,
[DOWN_BLOCKS, 1, 1],
[THREADS, 1, 1],
shared,
vec![A::Words(chunk_words(&full, n, c0, ct))],
)?);
c0 += ct;
continue;
}
down.push(Launch::new(
&GR_FUSED,
cfg.down_entry(),
@@ -511,7 +538,13 @@ pub(crate) fn plan_hc_read(
c0 += ct;
}
let up = Launch::new(&GR_FUSED, E_UP, [UP_BLOCKS, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full)])?;
let up = if chain_gr {
// 16 columns per block (160 blocks) with every load of the block's rows hoisted; chain_gr_up8 (320 blocks) is the alternative shape
let (entry, blocks) = if super::chain::up8() { (super::chain::E_GR_UP8, UP_BLOCKS * 2) } else { (super::chain::E_GR_UP16, UP_BLOCKS) };
Launch::new(&super::chain::CHAIN, entry, [blocks, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full)])?
} else {
Launch::new(&GR_FUSED, E_UP, [UP_BLOCKS, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full)])?
};
Ok(HcReadPlan { norm, down, up })
}
@@ -620,7 +620,10 @@ pub(crate) fn plan_shared_expert(
let xm = f32s(arena, "mixed", tb * n_embd, n * n_embd)?;
let bf16 = |t: usize, c: usize| items(arena, "sh_bf16", t * n_embd, c * n_embd, 2);
let mut out = Vec::new();
if dec_batch {
let tiny = super::chain::flags().tiny;
// `sh_bf16` is read only by the scalar gate that runs without --native-bf16-extra
if tiny && knobs.native_bf16_extra {
} else if dec_batch {
out.push(plan_f32_to_bf16(xm, bf16(tb, n)?, n * n_embd)?);
} else {
for t in rows.begin..rows.end {
@@ -651,14 +654,18 @@ pub(crate) fn plan_shared_expert(
if knobs.native_bf16_extra && dec_batch && n > 1 {
// one GEMV for all rows (outputs identical), one sigmoid launch with thread t = token t
out.push(plan_bf16_gemv(xm, n_embd, w.gate_inp_shexp, gscalar, 1, n_embd, 1, n)?);
out.push(Launch::new(&SHARED, E_SIGMOID_MULTI, [1, 1, 1], [n as u32, 1, 1], 0, vec![A::P(gscalar)])?);
if !tiny {
out.push(Launch::new(&SHARED, E_SIGMOID_MULTI, [1, 1, 1], [n as u32, 1, 1], 0, vec![A::P(gscalar)])?);
}
} else {
for t in 0..n {
let g_t = f32s(arena, "sh_g", tb + t, 1)?;
if knobs.native_bf16_extra {
let x_t = f32s(arena, "mixed", (tb + t) * n_embd, n_embd)?;
out.push(plan_bf16_gemv(x_t, n_embd, w.gate_inp_shexp, g_t, 1, n_embd, 1, 1)?);
out.push(Launch::new(&SHARED, E_SIGMOID, [1, 1, 1], [1, 1, 1], 0, vec![A::P(g_t)])?);
if !tiny {
out.push(Launch::new(&SHARED, E_SIGMOID, [1, 1, 1], [1, 1, 1], 0, vec![A::P(g_t)])?);
}
} else {
out.push(Launch::new(
&SHARED,
@@ -671,6 +678,18 @@ pub(crate) fn plan_shared_expert(
}
}
}
if tiny && knobs.native_bf16_extra {
// sigmoid of the gate scalar folded into the row scale (the gate buffer is left raw)
out.push(Launch::new(
&super::chain::CHAIN,
super::chain::E_SCALE_SIGMOID,
[n_embd.div_ceil(128) as u32, n as u32, 1],
[128, 1, 1],
0,
vec![A::P(shared), A::P(gscalar), A::I32(n_embd as i32)],
)?);
return Ok(out);
}
out.push(Launch::new(
&SHARED,
E_SCALE_ROWS,
@@ -768,49 +787,65 @@ pub(crate) fn plan_expert_groups(
let out = f32s(arena, "hit_out", tb * g.k * n_embd, cap * n_embd)?;
let nh = cap * n_ff;
let words = blob.words();
Ok(vec![
Launch::new(
&EXPERTS,
gu_entry,
[(2 * n_ff).div_ceil(8) as u32, cap as u32, 1],
[256, 1, 1],
0,
vec![
A::P(grp_ptr),
A::P(grp_start),
A::P(n_groups),
A::P(ent_tok),
A::P(x_q8_1),
A::Words(words.clone()),
A::P(gate),
A::P(up),
],
)?,
Launch::new(
&HEAD_IQ_EXPERT,
E_SWIGLU_ENTRIES,
[nh.div_ceil(256) as u32, 1, 1],
[256, 1, 1],
0,
vec![A::P(gate), A::P(up), A::P(h), A::I64(nh as i64)],
)?,
Launch::new(
&HEAD_IQ_EXPERT,
E_QUANTIZE_Q8_1,
[nh.div_ceil(256) as u32, 1, 1],
[256, 1, 1],
0,
vec![A::P(h), A::P(hq), A::I64(nh as i64)],
)?,
Launch::new(
&EXPERTS,
down_entry,
[n_embd.div_ceil(8) as u32, cap as u32, 1],
[256, 1, 1],
0,
vec![A::P(grp_ptr), A::P(grp_start), A::P(n_groups), A::P(ent_dst), A::P(hq), A::Words(words), A::P(out)],
)?,
])
let tiny = super::chain::flags().tiny;
let swiglu_quant = |tiny: bool| -> Result<Vec<Launch>> {
if tiny {
return Ok(vec![Launch::new(
&super::chain::CHAIN,
super::chain::E_SWIGLU_QUANT,
[nh.div_ceil(256) as u32, 1, 1],
[256, 1, 1],
0,
vec![A::P(gate), A::P(up), A::P(h), A::P(hq), A::I64(nh as i64)],
)?]);
}
Ok(vec![
Launch::new(
&HEAD_IQ_EXPERT,
E_SWIGLU_ENTRIES,
[nh.div_ceil(256) as u32, 1, 1],
[256, 1, 1],
0,
vec![A::P(gate), A::P(up), A::P(h), A::I64(nh as i64)],
)?,
Launch::new(
&HEAD_IQ_EXPERT,
E_QUANTIZE_Q8_1,
[nh.div_ceil(256) as u32, 1, 1],
[256, 1, 1],
0,
vec![A::P(h), A::P(hq), A::I64(nh as i64)],
)?,
])
};
let mut launches = Vec::with_capacity(4);
launches.push(Launch::new(
&EXPERTS,
gu_entry,
[(2 * n_ff).div_ceil(8) as u32, cap as u32, 1],
[256, 1, 1],
0,
vec![
A::P(grp_ptr),
A::P(grp_start),
A::P(n_groups),
A::P(ent_tok),
A::P(x_q8_1),
A::Words(words.clone()),
A::P(gate),
A::P(up),
],
)?);
launches.extend(swiglu_quant(tiny)?);
launches.push(Launch::new(
&EXPERTS,
down_entry,
[n_embd.div_ceil(8) as u32, cap as u32, 1],
[256, 1, 1],
0,
vec![A::P(grp_ptr), A::P(grp_start), A::P(n_groups), A::P(ent_dst), A::P(hq), A::Words(words), A::P(out)],
)?);
Ok(launches)
}
/// `moe_hit_add(parts_ + tb*K*N, hit_out, p_dst, p_counts + 1, cap, N)`:
@@ -24,6 +24,7 @@
use super::*;
use super::gr::{self, GrConfig, OriginalVerifyGrBinding};
use super::kernels::{A, AssetSpec, Launch};
use super::chain;
use super::moe::{self, MoeLayerAddrs, OriginalVerifyExpertFormats, OriginalVerifyMoeBinding};
use super::planner::{Planner, WindowWeights};
use super::proj::{self, GdnProjectionAddrs, OriginalVerifyProjBinding, QsaProjectionAddrs};
@@ -211,6 +212,7 @@ impl<'a, 'ctx> OriginalVerifyWindowResources<'a, 'ctx> {
if self.moe.is_some() {
assets.extend(moe::assets());
}
assets.extend(chain::assets());
assets
}
/// Pre-capture work: load the sealed modules, read the card's fused-GR decisions, raise the dynamic
@@ -472,6 +474,21 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> {
self.plan_launch(|p| p.quantize_expert_input(rows))
}
fn wait_plan(&mut self, ring: u32, rows: Rows) -> Result<()> {
if chain::flags().glue {
// wait flag A and the plan block copy in one launch (chain_window.cu)
let layout = self.plan();
let flag = self.mapped_flag(11)?;
let device = self.journal().address("plan", self.plan_group_offset(rows.group), layout.words * 4)?;
let mapped = self.journal().physical.mapped_address(14, rows.group * layout.mapped_stride() * 4, layout.words * 4)?;
return self.launch(vec![Launch::new(
&chain::CHAIN,
chain::E_WAIT_COPY_I32,
[1, 1, 1],
[704, 1, 1],
0,
vec![A::P(flag), A::I32(ring as i32), A::P(device), A::P(mapped), A::I32(layout.words as i32)],
)?]);
}
self.wait_flag(11, ring)?;
// The pool's GPU plan, copied from mapped host memory into this group's device block.
let layout = self.plan();
@@ -536,6 +553,19 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> {
let bytes = n * g.k * g.n * 4;
let parts = self.journal().address("parts", first, bytes)?;
let mapped = self.journal().physical.mapped_address(13, first, bytes)?;
if only_cpu_hits && chain::flags().glue {
let layout = self.plan();
let hit_rows = self.plan_word(rows.group, layout.dst)?;
let count = self.plan_word(rows.group, layout.counts + 1)?;
return self.launch(vec![Launch::new(
&chain::CHAIN,
chain::E_COPY_ROWS,
[(n * g.k) as u32, 1, 1],
[128, 1, 1],
0,
vec![A::P(parts), A::P(mapped), A::I64((g.n / 4) as i64), A::P(hit_rows), A::P(count)],
)?]);
}
let command = if only_cpu_hits {
let layout = self.plan();
command(
@@ -512,6 +512,27 @@ mod tests {
assert_eq!(log.iter().filter(|s| *s == "tail q0").count(), 1);
}
#[test]
fn chain_switches_swap_in_the_hoisted_kernels_and_the_default_keeps_the_originals() {
use super::super::chain::{self, ChainFlags};
let base = record(4, 1, false);
assert!(base.iter().any(|s| s == "mtp_scalar_gr_split") && base.iter().any(|s| s == "mtp_scalar_gr_up"));
assert!(!base.iter().any(|s| s.starts_with("chain_")));
let on = chain::with_flags(ChainFlags { glue: true, ab: true, gr: true, qsa: true, tiny: true, head: true, mtp: true }, || record(4, 1, false));
// every hc read: split norm -> (unchanged staged down) -> up; 96 reads per window
assert_eq!(on.iter().filter(|s| *s == "chain_gr_split").count(), 96 + 0);
assert_eq!(on.iter().filter(|s| *s == "chain_gr_up8").count(), 96);
assert_eq!(on.iter().filter(|s| s.starts_with("chain_gr_down_w8_nb")).count(), 96, "the down projection is the 8-warp register-row kernel");
assert!(!on.iter().any(|s| s == "mtp_scalar_gr_staged"));
assert!(!on.iter().any(|s| s == "mtp_scalar_gr_split" || s == "mtp_scalar_gr_up"));
assert_eq!(on.iter().filter(|s| *s == "chain_qsa_decode_chunk").count(), 12);
assert!(!on.iter().any(|s| s == "leleka_qsa_decode_chunk"));
assert!(on.iter().any(|s| s == "leleka_qsa_decode_merge"), "merge is unchanged");
// the groups are independent
let only_gr = chain::with_flags(ChainFlags { gr: true, ..ChainFlags::default() }, || record(4, 1, false));
assert!(only_gr.iter().any(|s| s == "chain_gr_split") && only_gr.iter().any(|s| s == "leleka_qsa_decode_chunk"));
}
#[test]
fn the_head_mixes_every_row_then_the_head_owner_finishes() {
let log = record(3, 1, false);
@@ -707,9 +707,14 @@ impl<'a> QsaWindow<'a> {
// 1.0f / sqrtf(256.0f)
let scale = 1.0f32 / (hd as f32).sqrt();
let r = &w.kv.resident;
let (chunk_asset, chunk_entry) = if super::chain::flags().qsa {
(&super::chain::CHAIN, super::chain::E_QSA_CHUNK)
} else {
(&ATTENTION, "leleka_qsa_decode_chunk")
};
let chunk = Launch::new(
&ATTENTION,
"leleka_qsa_decode_chunk",
chunk_asset,
chunk_entry,
[grid_u32(chunks)?, grid_u32(nkv)?, grid_u32(s.n)?],
[256, 1, 1],
0,
@@ -172,6 +172,11 @@ impl RopeConstants {
/// The `--native` preset of generate.cpp (native router, combine, shared scalar, final GR) with the
/// default (plain) GR variant and FP16 final GR; INT8 draft K/V.
/// The draft's hyper-connection read: plain (this port's historic choice), or the staged variant the Original runs on this card when
/// `LELEKA_CHAIN` selects the `mtp` group (the variants are bit-identical: `fused_gr_check`).
fn mtp_gr_variant() -> OriginalMtpGrVariant {
if leleka_cuda_driver::chain_selects_mtp() { OriginalMtpGrVariant::Staged } else { OriginalMtpGrVariant::Plain }
}
pub(in crate::qwen_forward) fn mtp_full_policy(rope: &RopeConstants) -> OriginalMtpFullPolicy {
OriginalMtpFullPolicy {
native_router: true,
@@ -181,14 +186,14 @@ pub(in crate::qwen_forward) fn mtp_full_policy(rope: &RopeConstants) -> Original
old_grouped_s2: false,
native_final_gr: true,
fp32_final_gr: false,
gr: OriginalMtpGrVariant::Plain,
gr: mtp_gr_variant(),
kv: rope.draft_kv(),
coupled_j: None,
}
}
pub(in crate::qwen_forward) fn mtp_scalar_policy(rope: &RopeConstants) -> OriginalMtpScalarPolicy {
OriginalMtpScalarPolicy {
gr: OriginalMtpGrVariant::Plain,
gr: mtp_gr_variant(),
// `STRATA_MTP_PREFILL_SYNC` unset
per_group_sync: false,
kv: rope.draft_kv(),
+67
View File
@@ -0,0 +1,67 @@
# Chain kernels: the GPU chain of the decode verify window and of the MTP draft step (`claude/chain-kernels`)
Status: tables of section 2 are measured (ledger CUPTI traces, jobs 9062/9004). Sections 4-6 are filled as the model-free probe and A/B jobs
(`tools/chain-probe/`, jobs `9c*`) report; a number without a job name is not measured.
## 0. Summary
* In the hit-heavy regime of real agent sessions the verify window is the GPU chain plus the host/PCIe waits. The port's chain is **the Original's chain**: kernel for kernel the
same launch shapes and the same durations (12,561 us per 4-row window for both, section 2). Nothing in the window is slower than the Original's equivalent, and nothing is faster,
so "the port must be faster than the Original" needs kernels that the Original does not have.
* The chain is **latency-bound, not bandwidth-bound**: 2,418 kernels per 4-row window, 25 to 60 per layer, HBM busy about a quarter of the time. The biggest losses against the
bandwidth floor are small-grid kernels with serial dependent loads: the hyper-connection read (3.4 ms, 27 % of the chain, about 4x its floor), the CPU-leg row copy and the plan
copy from mapped host memory, the GDN alpha/beta gates, the QSA decode attention chunk, the hyper-connection up projection.
* `chain_window.cu` holds bit-identical variants of those kernels (same operations, same order, loads issued ahead), plus a few fusions; all behind `LELEKA_CHAIN` (off by default).
* Draft vocabulary: section 7.
## 1. Tools
| tool | what |
| --- | --- |
| `tools/chain-probe/window_table.py` | per-role kernel table of the verify windows of two CUPTI traces (`claude/ledger`'s `tools/cupti-trace`, `scripts/profile/lct.py`) |
| `tools/chain-probe/chain_probe.cpp` | model-free probe: loads the sealed Original PTX and `chain_window.ptx`, runs both on real-size random inputs, compares **every output byte**, times both inside a CUDA graph with cold weights |
| `tools/chain-probe/mb_pdl.cu` | graph kernel-to-kernel latency with and without programmatic dependent launch, and prefetch-ahead |
| `tools/chain-probe/jobs/` | holder jobs: `9c5` paired A/B (chain off / on), `9c6` CUPTI traces of both arms, `9c7` draft vocabulary on the CRM replay |
| `scripts/chain/{build_rt,test_driver,seal_chain}.sh` | WSL builds, driver unit tests, compile+seal of `chain_window.ptx` with `compile_assets.py` / `seal_pins.py` |
## 2. The window, kernel by kernel (port against Original, hit regime)
Traces: ledger job 9062, `port-corpus-hit` (rt-base, no draft vocabulary bound) and `orig-corpus-hit` (unmodified Original, `--dump-routing` profile of the corpus's own routing,
static 2048 slots, ledger tracer). Windows of 4 rows (49 port / 115 Original windows) and 6 rows (6 / 22). "chain" = every kernel that is not a host or PCIe wait.
### 2.1 Four-row window
TABLE4
### 2.2 Six-row window
TABLE6
### 2.3 Gaps inside the graph
Every window is one stream and one graph; consecutive kernels start 64 to 128 ns after the previous one ends (98 % of 112,000 gaps in the 64-128 ns bin): 218 us per port window
(1.7 % of the chain), 239 us for the Original. There are no event gaps (no cross-stream edges) in the window. The graph kernel gap is therefore not where the chain is lost; the loss
is the 0.7 to 1.0 us a tiny kernel takes between its first and last thread, and the serial dependent loads of the small-grid kernels. The only exception in the Original's trace is
an 0.9 us hole after the QSA K projection (`native_mmvq_multi -> norm`, 11 us per window) which the port does not have.
### 2.4 Ranking against the floor (4 rows, HBM 1.69 TB/s)
| rank | family | port us/window | floor us | gap us | what limits it |
| --- | --- | ---: | ---: | ---: | --- |
| 1 | hyper-connection read: norm + staged down + up (96 calls, 13.1 MB each) | 3,391 | 910 (7.7 us HBM + 1.5 norm per call) | 2,480 | 41-block down projection 13 us (8 serial cp.async tiles), up 7.5 us (8 rows per warp loaded one behind the other) |
| 2 | routed experts gate/up + down (hits + staged) | 2,434 | 950 (1.6 GB) | ~1,500 | grouped MMQ at 12.5 us per call; ramp and tail of many small groups; not touched here |
| 3 | dense projections (qkv, z, out, q, k, v, shared) | 2,250 | ~2,000 | ~250 | at the HBM floor already |
| 4 | CPU-leg rows copy + plan copy + doorbell + their waits' PCIe reads | 1,040 | ~250 | ~790 | serial volatile loads from mapped host memory: 5 and 6 PCIe round trips |
| 5 | QSA decode attention chunk | 470 | ~60 | ~410 | 64 cells walked one dependent load at a time |
| 6 | GDN alpha/beta | 368 | ~100 | ~270 | 12 blocks, 10 dependent weight/activation rounds |
| 7 | greedy argmax (248,320 logits, one block per token) | 79 | 10 | ~70 | 243 dependent loads per thread |
| 8 | ~25 tiny kernels per layer (quantize, swiglu, scale, sigmoid, ...) | ~900 | | ~450 | launch + ramp (0.7-1.0 us each) |
Which families are slower than the Original's equivalents: none beyond noise; routed experts gate/up and down are +100 us each in the port because the 4-row set contains more groups
(the port's hit regime differs by about 2 experts per layer between the two runs); `doorbell` is 142 us faster in the port. Extra kernels the port has: the split QSA scores/topk/resolve
(`qsa_decode_scores`, `qsa_topk_ref`, `leleka_qsa_resolve`, `leleka_qsa_miss_copy`) replace the Original's `block_scores_multi`, `block_topk_reg` (+60 us), and the PLE history snapshot copies;
no port-only guard kernels exist in the verify window (they are in the MTP step, section 5).
## 7. The MTP draft vocabulary (coordinator request)
DRAFTVOCAB
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env bash
# Build the leleka-runtime test binary of THIS worktree in WSL (never on the server).
# scripts/chain/build_rt.sh TAG [extra cargo args] run from Git Bash in the worktree; needs WSL distro "Ubuntu"
# Result: WSL ~/chain-bin/rt-TAG (also copied to <worktree>/../chain-bin-rt-TAG for scp from the Windows side).
set -euo pipefail
tag=${1:?tag}
shift || true
root=$(git rev-parse --show-toplevel)
tar_win="$root/../wt-chain-$tag.tar"
git -C "$root" -c core.autocrlf=false ls-files -co --exclude-standard -z | tar --force-local -C "$root" --null -T - -cf "$tar_win"
tar_wsl="/mnt/c/Users/pavel/work/wt-chain-$tag.tar"
wsl -d Ubuntu -e bash -lc "
set -e
source ~/.cargo/env
export PATH=\$HOME/cuda-toolkits/13.2.2/bin:\$HOME/.cargo/bin:/usr/local/bin:/usr/bin:/bin
rm -rf ~/chain-src && mkdir -p ~/chain-src ~/chain-bin && tar -xf '$tar_wsl' -C ~/chain-src
cd ~/chain-src
export CARGO_TARGET_DIR=\$HOME/chain-target
nice -n 10 cargo test --no-run --locked --release -p leleka-runtime --lib $* 2>&1 | tee ~/chain-build-$tag.log | grep -E 'Executable|^error|warning: unused' | tail -5
exe=\$(grep -o 'target/release/deps/leleka_runtime-[0-9a-f]*' ~/chain-build-$tag.log | tail -1)
cp \$CARGO_TARGET_DIR/\${exe#target/} ~/chain-bin/rt-$tag
cp ~/chain-bin/rt-$tag /mnt/c/Users/pavel/work/chain-bin-rt-$tag
ls -la ~/chain-bin/rt-$tag
"
rm -f "$tar_win"
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env python3
"""Put chain_window.ptx back to its unsealed placeholder state (seal_pins.py refuses to overwrite a pinned PTX)."""
import re
import sys
ptx = "crates/cuda-driver/src/chain_window.ptx"
rs = "crates/cuda-driver/src/original_verify_window_chain.rs"
with open(ptx, "w", newline="\n") as f:
f.write("// UNSEALED placeholder: chain_window.ptx (compile_assets.py / seal_pins.py install the real PTX)\n")
s = open(rs, newline="").read()
s2, n = re.subn(r'(name: "chain_window\.ptx",\n ptx: [^\n]*\n sha: )\[[^\]]*\]', lambda m: m.group(1) + "[0; 32]", s, count=1)
if n != 1:
sys.exit("reset_chain_pin: CHAIN.sha not found")
open(rs, "w", newline="").write(s2)
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
# Compile and seal chain_window.cu with the project tooling (WSL; the tree is patched in place).
# scripts/chain/seal_chain.sh (run from Git Bash in the worktree)
set -euo pipefail
root=$(git rev-parse --show-toplevel)
wsl -d Ubuntu -e bash -lc "
set -e
cd \$(wslpath -a '$root')
TK=\$HOME/cuda-toolkits/13.2.2
OUT=\$HOME/chain-seal
rm -rf \$OUT && mkdir -p \$OUT
python3 scripts/chain/reset_chain_pin.py
python3 scripts/gpu-bringup/compile_assets.py --toolkit \$TK --only chain_window --no-rope --out \$OUT 2>&1 | tail -4
python3 scripts/gpu-bringup/seal_pins.py --ptx-dir \$OUT --only chain_window --write --manifest-out \$OUT/SEALED-MANIFEST.json 2>&1 | grep -E 'REFUSED|touched|chain|written' | head
"
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
# Run the non-GPU unit tests of leleka-cuda-driver matching FILTER in WSL (never on the server).
# scripts/chain/test_driver.sh FILTER [extra test-binary args]
set -euo pipefail
filter=${1:?filter}
shift || true
root=$(git rev-parse --show-toplevel)
tar_win="$root/../wt-chain-test.tar"
git -C "$root" -c core.autocrlf=false ls-files -co --exclude-standard -z | tar --force-local -C "$root" --null -T - -cf "$tar_win"
wsl -d Ubuntu -e bash -lc "
set -e
source ~/.cargo/env
export PATH=\$HOME/cuda-toolkits/13.2.2/bin:\$HOME/.cargo/bin:/usr/local/bin:/usr/bin:/bin
rm -rf ~/chain-src-test && mkdir -p ~/chain-src-test && tar -xf /mnt/c/Users/pavel/work/wt-chain-test.tar -C ~/chain-src-test
cd ~/chain-src-test
export CARGO_TARGET_DIR=\$HOME/chain-target-test
nice -n 10 cargo test --locked --release -p leleka-cuda-driver --features cuda-driver --lib -- '$filter' $* 2>&1 | grep -v '^warning\|^ *|\|^ *=\|^ *-->\|^$' | tail -40
"
rm -f "$tar_win"
+33
View File
@@ -726,6 +726,39 @@
},
"group": "prefill-stage",
"optional": false
},
{
"cu": "crates/cuda-driver/src/chain_window.cu",
"ptx": "crates/cuda-driver/src/chain_window.ptx",
"flags": [
"-ptx",
"-O3",
"-arch=sm_120",
"-std=c++17",
"--fmad=true",
"--ftz=false"
],
"include_profile": "standard",
"policy": "precise (--fmad=true --ftz=false: the recipe of original_verify.cu, mtp_original_full_fused_gr.cu and mtp_original_full_attention.cu, whose kernels these replace bit for bit)",
"entries": [
"chain_copy_i32_from_mapped_kernel",
"chain_wait_copy_i32_kernel",
"chain_copy_rows_from_mapped_kernel",
"chain_doorbell_publish_kernel",
"chain_gdn_ab_multi_kernel",
"chain_gr_split",
"chain_gr_up16",
"chain_gr_up8",
"chain_qsa_decode_chunk"
],
"encoding": "concat_include_str",
"rust_fields_to_fill": {
"original_verify_window_chain.rs": [
"CHAIN.sha"
]
},
"group": "chain-window",
"optional": false
}
]
}
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env bash
# Build the chain-kernels probes in WSL (never on the server).
# tools/chain-probe/build.sh [OUTDIR] default OUTDIR=$HOME/chain-bin; also compiles chain_window.cu to OUTDIR/ptx/chain_window.ptx
set -euo pipefail
here="$(cd "$(dirname "$0")" && pwd)"
root="$(cd "$here/../.." && pwd)"
out="${1:-$HOME/chain-bin}"
nvcc="${NVCC:-$HOME/cuda-toolkits/13.2.2/bin/nvcc}"
mkdir -p "$out/ptx"
cd "$here"
"$nvcc" -O3 -std=c++17 -lineinfo -gencode arch=compute_120,code=sm_120 mb_pdl.cu -lcuda -o "$out/mb_pdl"
"$nvcc" -O2 -std=c++17 chain_probe.cpp -lcuda -o "$out/chain_probe"
# the sealed PTX the probe compares against, and the new one compiled with the recipe of its sources (precise math)
cd "$root"
for f in original_verify mtp_original_full_fused_gr mtp_original_full_attention mtp_original_full_head_iq mtp_original_full_shared native_head_sampler mtp_original_full_verify chain_window; do
if [ "$f" = chain_window ]; then
"$nvcc" -ptx -std=c++17 -O3 -arch=sm_120 --fmad=true --ftz=false -Iengine/strata/include crates/cuda-driver/src/$f.cu -o "$out/ptx/$f.ptx"
else
cp crates/cuda-driver/src/$f.ptx "$out/ptx/$f.ptx"
fi
done
"$nvcc" -ptx -std=c++17 -O3 -arch=sm_120 --fmad=true --ftz=false -I"$root/engine/strata/include" "$here/qsa_prof.cu" -o "$out/ptx/qsa_prof.ptx"
"$nvcc" -ptx -std=c++17 -O3 -arch=sm_120 --fmad=true --ftz=false -I"$root/engine/strata/include" "$here/gr_prof.cu" -o "$out/ptx/gr_prof.ptx"
ls -la "$out" "$out/ptx"
sha256sum "$out"/chain_probe "$out"/mb_pdl "$out"/ptx/* > "$out/SHA256SUMS"
+613
View File
@@ -0,0 +1,613 @@
// claude/chain-kernels: model-free probe comparing the chain-kernels PTX (crates/cuda-driver/src/chain_window.ptx) with the
// sealed Original-literal kernels it replaces, on real-size random inputs: bit-for-bit output comparison and a timing of
// each kernel inside a CUDA graph with cold weights (rotating weight sets larger than the L2).
// chain_probe PTXDIR [test ...] tests: copy_i32 copy_rows doorbell ab gr (default: all)
// PTXDIR holds original_verify.ptx, mtp_original_full_fused_gr.ptx and chain_window.ptx (copied from crates/cuda-driver/src).
// Prints "RESULT name key=value" lines; exits 1 if any comparison differs. Never touches the model.
#include <cuda.h>
#include <vector_types.h>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <functional>
#include <string>
#include <vector>
#define CU(x) do { CUresult r_ = (x); if (r_ != CUDA_SUCCESS) { const char* s_ = nullptr; cuGetErrorString(r_, &s_); fprintf(stderr, "CUDA error %s at %s:%d: %s\n", #x, __FILE__, __LINE__, s_ ? s_ : "?"); exit(2); } } while (0)
static int g_fail = 0;
static uint64_t g_rng = 0x9e3779b97f4a7c15ull;
static uint32_t rnd() { g_rng ^= g_rng << 13; g_rng ^= g_rng >> 7; g_rng ^= g_rng << 17; return (uint32_t)(g_rng >> 16); }
static float rndf() { return (float)(rnd() & 0xffffff) / 16777216.0f * 2.0f - 1.0f; } // [-1, 1)
static std::string read_file(const std::string& p) {
FILE* f = fopen(p.c_str(), "rb");
if (!f) { fprintf(stderr, "cannot open %s\n", p.c_str()); exit(2); }
std::string s; char buf[1 << 16]; size_t n;
while ((n = fread(buf, 1, sizeof buf, f)) > 0) s.append(buf, n);
fclose(f);
return s;
}
static CUmodule load_module(const std::string& p) {
std::string s = read_file(p);
s.push_back('\0');
CUmodule m; char log[8192] = {};
CUjit_option opt[] = {CU_JIT_ERROR_LOG_BUFFER, CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES};
void* val[] = {log, (void*)(uintptr_t)sizeof log};
CUresult r = cuModuleLoadDataEx(&m, s.data(), 2, opt, val);
if (r != CUDA_SUCCESS) { fprintf(stderr, "load %s failed: %d %s\n", p.c_str(), (int)r, log); exit(2); }
return m;
}
static CUfunction get_fn(CUmodule m, const char* name) {
CUfunction f; CUresult r = cuModuleGetFunction(&f, m, name);
if (r != CUDA_SUCCESS) { fprintf(stderr, "no entry %s\n", name); exit(2); }
return f;
}
struct Dev {
CUdeviceptr p = 0; size_t n = 0;
void alloc(size_t bytes) { n = bytes; CU(cuMemAlloc(&p, bytes ? bytes : 1)); CU(cuMemsetD8(p, 0, bytes ? bytes : 1)); CU(cuCtxSynchronize()); }
void put(const void* h, size_t bytes) { CU(cuMemcpyHtoD(p, h, bytes)); CU(cuCtxSynchronize()); }
std::vector<uint8_t> get() const { std::vector<uint8_t> v(n); CU(cuMemcpyDtoH(v.data(), p, n)); return v; }
};
static bool same(const char* what, const std::vector<uint8_t>& a, const std::vector<uint8_t>& b) {
if (a.size() != b.size()) { printf("MISMATCH %s: size %zu vs %zu\n", what, a.size(), b.size()); g_fail++; return false; }
size_t bad = 0, first = (size_t)-1;
for (size_t i = 0; i < a.size(); ++i) if (a[i] != b[i]) { if (first == (size_t)-1) first = i; ++bad; }
if (bad) { printf("MISMATCH %s: %zu of %zu bytes differ (first at %zu)\n", what, bad, a.size(), first); g_fail++; return false; }
return true;
}
static CUstream g_s;
// time `body(i)` for i in [0, reps) captured into one graph, launched `iters` times; returns microseconds per body call
static double time_graph(const std::function<void(int)>& body, int reps, int iters = 8) {
CUgraph g; CUgraphExec ge;
CU(cuStreamBeginCapture(g_s, CU_STREAM_CAPTURE_MODE_GLOBAL));
for (int i = 0; i < reps; ++i) body(i);
CU(cuStreamEndCapture(g_s, &g));
CU(cuGraphInstantiateWithFlags(&ge, g, 0));
for (int i = 0; i < 2; ++i) CU(cuGraphLaunch(ge, g_s));
CU(cuStreamSynchronize(g_s));
CUevent a, b; CU(cuEventCreate(&a, 0)); CU(cuEventCreate(&b, 0));
std::vector<double> v;
for (int i = 0; i < iters; ++i) {
CU(cuEventRecord(a, g_s)); CU(cuGraphLaunch(ge, g_s)); CU(cuEventRecord(b, g_s)); CU(cuEventSynchronize(b));
float ms; CU(cuEventElapsedTime(&ms, a, b)); v.push_back(ms * 1000.0 / reps);
}
std::sort(v.begin(), v.end());
CU(cuGraphExecDestroy(ge)); CU(cuGraphDestroy(g));
return v[v.size() / 2];
}
static void launch(CUfunction f, unsigned gx, unsigned gy, unsigned bx, unsigned shared, void** params) {
CU(cuLaunchKernel(f, gx, gy, 1, bx, 1, 1, shared, g_s, params, nullptr));
}
static CUmodule mVerify, mGr, mChain, mAttn, mIq, mShared, mSampler, mMtpVerify;
// ---------------------------------------------------------------------------------------------------------------
static void test_copy_i32() {
const int n = 648; // PlanLayout::new(80).words
int32_t* host; CU(cuMemHostAlloc((void**)&host, 4096, CU_MEMHOSTALLOC_DEVICEMAP | CU_MEMHOSTALLOC_PORTABLE));
for (int i = 0; i < n; ++i) host[i] = (int32_t)rnd();
CUdeviceptr hd; CU(cuMemHostGetDevicePointer(&hd, host, 0));
Dev d0, d1; d0.alloc(4 * n); d1.alloc(4 * n);
CUfunction fo = get_fn(mVerify, "verify_copy_i32_from_mapped_kernel"), fn = get_fn(mChain, "chain_copy_i32_from_mapped_kernel");
int nn = n;
{ void* a[] = {&d0.p, &hd, &nn}; launch(fo, 1, 1, 128, 0, a); }
{ void* a[] = {&d1.p, &hd, &nn}; launch(fn, 1, 1, 704, 0, a); }
CU(cuStreamSynchronize(g_s));
bool ok = same("copy_i32", d0.get(), d1.get());
// fused wait + copy: flag already satisfied
uint32_t* flag; CU(cuMemHostAlloc((void**)&flag, 64, CU_MEMHOSTALLOC_DEVICEMAP | CU_MEMHOSTALLOC_PORTABLE)); *flag = 5;
CUdeviceptr fd; CU(cuMemHostGetDevicePointer(&fd, flag, 0));
Dev d2; d2.alloc(4 * n);
CUfunction fw = get_fn(mChain, "chain_wait_copy_i32_kernel"), fwait = get_fn(mVerify, "verify_wait_flag_ge_kernel");
uint32_t val = 5;
{ void* a[] = {&fd, &val, &d2.p, &hd, &nn}; launch(fw, 1, 1, 704, 0, a); }
CU(cuStreamSynchronize(g_s));
ok &= same("wait_copy_i32", d0.get(), d2.get());
double to = time_graph([&](int) { void* w[] = {&fd, &val}; launch(fwait, 1, 1, 1, 0, w); void* a[] = {&d0.p, &hd, &nn}; launch(fo, 1, 1, 128, 0, a); }, 200);
double tn = time_graph([&](int) { void* a[] = {&d1.p, &hd, &nn}; launch(fn, 1, 1, 704, 0, a); void* w[] = {&fd, &val}; launch(fwait, 1, 1, 1, 0, w); }, 200);
double tf = time_graph([&](int) { void* a[] = {&d2.p, &fd, &val, &hd, &nn}; (void)a; void* b[] = {&fd, &val, &d2.p, &hd, &nn}; launch(fw, 1, 1, 704, 0, b); }, 200);
printf("RESULT copy_i32 ok=%d wait+old_copy_us=%.3f wait+new_copy_us=%.3f fused_wait_copy_us=%.3f\n", ok, to, tn, tf);
}
static void test_copy_rows() {
for (int rows : {4, 8, 40}) {
const int64_t row4 = 640; // N/4
size_t bytes = (size_t)rows * row4 * 16;
float4* host; CU(cuMemHostAlloc((void**)&host, bytes, CU_MEMHOSTALLOC_DEVICEMAP | CU_MEMHOSTALLOC_PORTABLE));
for (size_t i = 0; i < bytes / 4; ++i) ((float*)host)[i] = rndf();
CUdeviceptr hd; CU(cuMemHostGetDevicePointer(&hd, host, 0));
int32_t hit_h[16]; int cnt = rows >= 8 ? 3 : 1;
for (int i = 0; i < cnt; ++i) hit_h[i] = (i * 3 + 1) % rows;
Dev hit, count, d0, d1; hit.alloc(64); count.alloc(4); d0.alloc(bytes); d1.alloc(bytes);
hit.put(hit_h, 64); count.put(&cnt, 4);
std::vector<uint8_t> poison(bytes, 0xAB);
d0.put(poison.data(), bytes); d1.put(poison.data(), bytes);
CUfunction fo = get_fn(mVerify, "verify_copy_rows_from_mapped_kernel"), fn = get_fn(mChain, "chain_copy_rows_from_mapped_kernel");
void* a0[] = {&d0.p, &hd, (void*)&row4, &hit.p, &count.p};
void* a1[] = {&d1.p, &hd, (void*)&row4, &hit.p, &count.p};
launch(fo, rows, 1, 128, 0, a0); launch(fn, rows, 1, 128, 0, a1);
CU(cuStreamSynchronize(g_s));
bool ok = same("copy_rows", d0.get(), d1.get());
double to = time_graph([&](int) { launch(fo, rows, 1, 128, 0, a0); }, 200);
double tn = time_graph([&](int) { launch(fn, rows, 1, 128, 0, a1); }, 200);
printf("RESULT copy_rows rows=%d ok=%d old_us=%.3f new_us=%.3f\n", rows, ok, to, tn);
}
}
static void test_doorbell() {
for (int rows : {1, 4, 8}) {
int n = rows * 2560, k = 10;
Dev x, ids, w; x.alloc(4 * n); ids.alloc(64); w.alloc(64);
std::vector<float> xh(n); for (auto& v : xh) v = rndf();
int32_t idh[16]; float wh[16]; for (int i = 0; i < 16; ++i) { idh[i] = rnd() % 512; wh[i] = rndf(); }
x.put(xh.data(), 4 * n); ids.put(idh, 64); w.put(wh, 64);
float *xo0, *xo1, *wo0, *wo1; int32_t *io0, *io1; uint32_t *s0, *s1;
auto hm = [&](void** p, size_t b) { CU(cuMemHostAlloc(p, b, CU_MEMHOSTALLOC_DEVICEMAP | CU_MEMHOSTALLOC_PORTABLE)); memset(*p, 0, b); };
hm((void**)&xo0, 4 * n); hm((void**)&xo1, 4 * n); hm((void**)&wo0, 64); hm((void**)&wo1, 64); hm((void**)&io0, 64); hm((void**)&io1, 64); hm((void**)&s0, 64); hm((void**)&s1, 64);
CUdeviceptr dxo0, dxo1, dwo0, dwo1, dio0, dio1, ds0, ds1;
cuMemHostGetDevicePointer(&dxo0, xo0, 0); cuMemHostGetDevicePointer(&dxo1, xo1, 0); cuMemHostGetDevicePointer(&dwo0, wo0, 0); cuMemHostGetDevicePointer(&dwo1, wo1, 0);
cuMemHostGetDevicePointer(&dio0, io0, 0); cuMemHostGetDevicePointer(&dio1, io1, 0); cuMemHostGetDevicePointer(&ds0, s0, 0); cuMemHostGetDevicePointer(&ds1, s1, 0);
CUfunction fo = get_fn(mVerify, "verify_doorbell_publish_kernel"), fn = get_fn(mChain, "chain_doorbell_publish_kernel");
void* a0[] = {&x.p, &ids.p, &w.p, &n, &k, &dxo0, &dio0, &dwo0, &ds0};
void* a1[] = {&x.p, &ids.p, &w.p, &n, &k, &dxo1, &dio1, &dwo1, &ds1};
launch(fo, 1, 1, 1024, 0, a0); launch(fn, 1, 1, 1024, 0, a1);
CU(cuStreamSynchronize(g_s));
std::vector<uint8_t> A((uint8_t*)xo0, (uint8_t*)xo0 + 4 * n), B((uint8_t*)xo1, (uint8_t*)xo1 + 4 * n);
bool ok = same("doorbell x", A, B);
ok &= same("doorbell ids", std::vector<uint8_t>((uint8_t*)io0, (uint8_t*)io0 + 40), std::vector<uint8_t>((uint8_t*)io1, (uint8_t*)io1 + 40));
ok &= same("doorbell w", std::vector<uint8_t>((uint8_t*)wo0, (uint8_t*)wo0 + 40), std::vector<uint8_t>((uint8_t*)wo1, (uint8_t*)wo1 + 40));
ok &= (*s0 == *s1);
double to = time_graph([&](int) { launch(fo, 1, 1, 1024, 0, a0); }, 100);
double tn = time_graph([&](int) { launch(fn, 1, 1, 1024, 0, a1); }, 100);
printf("RESULT doorbell rows=%d ok=%d old_us=%.3f new_us=%.3f\n", rows, ok, to, tn);
}
}
static uint16_t bf16_of(float f) { uint32_t u; memcpy(&u, &f, 4); return (uint16_t)(u >> 16); }
static void test_ab() {
const int n = 2560, hv = 48, NS = 24;
size_t wbytes = (size_t)hv * n * 2;
for (int T : {1, 2, 4, 6, 8}) {
std::vector<uint16_t> wh(hv * n); for (auto& v : wh) v = bf16_of(rndf() * 0.05f);
std::vector<Dev> wa(NS), wb(NS);
for (int s = 0; s < NS; ++s) { wa[s].alloc(wbytes); wb[s].alloc(wbytes); wa[s].put(wh.data(), wbytes); wb[s].put(wh.data(), wbytes); }
Dev x, dt, sa, g0, b0, g1, b1; x.alloc(4 * T * n); dt.alloc(4 * hv); sa.alloc(4 * hv); g0.alloc(4 * T * hv); b0.alloc(4 * T * hv); g1.alloc(4 * T * hv); b1.alloc(4 * T * hv);
std::vector<float> xh(T * n), dh(hv), ah(hv); for (auto& v : xh) v = rndf(); for (auto& v : dh) v = rndf(); for (auto& v : ah) v = -fabsf(rndf());
x.put(xh.data(), 4 * T * n); dt.put(dh.data(), 4 * hv); sa.put(ah.data(), 4 * hv);
CUfunction fo = get_fn(mVerify, "verify_gdn_ab_multi_kernel"), fn = get_fn(mChain, "chain_gdn_ab_multi_kernel");
int nn = n, h = hv, t = T;
auto args0 = [&](int s, Dev& g, Dev& b, void** a, CUdeviceptr* wp) { wp[0] = wa[s].p; wp[1] = wb[s].p; a[0] = &x.p; a[1] = &wp[0]; a[2] = &wp[1]; a[3] = &dt.p; a[4] = &sa.p; a[5] = &g.p; a[6] = &b.p; a[7] = &nn; a[8] = &h; a[9] = &t; };
CUdeviceptr wp0[2], wp1[2]; void *a0[10], *a1[10];
args0(0, g0, b0, a0, wp0); args0(0, g1, b1, a1, wp1);
launch(fo, 12, 1, 256, 0, a0); launch(fn, 24, 1, 128, 0, a1);
CU(cuStreamSynchronize(g_s));
bool ok = same("ab gate", g0.get(), g1.get()) & same("ab beta", b0.get(), b1.get());
double to = time_graph([&](int i) { CUdeviceptr* wp = new CUdeviceptr[2]; void** a = new void*[10]; args0(i % NS, g0, b0, a, wp); launch(fo, 12, 1, 256, 0, a); }, 120);
double tn = time_graph([&](int i) { CUdeviceptr* wp = new CUdeviceptr[2]; void** a = new void*[10]; args0(i % NS, g1, b1, a, wp); launch(fn, 24, 1, 128, 0, a); }, 120);
double tn2 = time_graph([&](int i) { CUdeviceptr* wp = new CUdeviceptr[2]; void** a = new void*[10]; args0(i % NS, g1, b1, a, wp); launch(fn, 96, 1, 32, 0, a); }, 120);
printf("RESULT gdn_ab T=%d ok=%d old_us=%.3f new_8warp_blocks_us=%.3f new_1warp_blocks_us=%.3f\n", T, ok, to, tn, tn2);
for (int s = 0; s < NS; ++s) { cuMemFree(wa[s].p); cuMemFree(wb[s].p); }
}
}
// ---------------------------------------------------------------------------------------------------------------
struct GrState {
Dev R, bo, inj, injo, lo, rs, mixed, xn; // per-token buffers
int T;
};
struct GrWeights { Dev norm, down, up, inject; };
static std::vector<uint64_t> multi_words(const GrState& s, const GrWeights& w, bool apply) {
std::vector<uint64_t> words(114, 0);
for (int k = 0; k < s.T; ++k) {
uint64_t* a = &words[k * 14];
a[0] = s.R.p + (uint64_t)k * 10240 * 4; a[1] = a[0]; a[2] = apply ? 1 : 0;
a[3] = s.bo.p + (uint64_t)k * 2560 * 4; a[4] = s.inj.p + (uint64_t)k * 16; a[5] = w.norm.p; a[6] = w.down.p; a[7] = w.up.p; a[8] = w.inject.p;
float eps = 1e-6f; uint32_t eb; memcpy(&eb, &eps, 4); a[9] = eb;
a[10] = s.lo.p + (uint64_t)k * 320 * 4; a[11] = s.rs.p + (uint64_t)k * 16; a[12] = s.injo.p + (uint64_t)k * 16; a[13] = s.mixed.p + (uint64_t)k * 2560 * 4;
}
words[112] = s.xn.p; words[113] = s.T;
return words;
}
static void gr_alloc(GrState& s, int T) {
s.T = T; s.R.alloc((size_t)T * 10240 * 4); s.bo.alloc((size_t)T * 2560 * 4); s.inj.alloc((size_t)T * 16); s.injo.alloc((size_t)T * 16); s.lo.alloc((size_t)T * 320 * 4);
s.rs.alloc((size_t)T * 16); s.mixed.alloc((size_t)T * 2560 * 4); s.xn.alloc((size_t)T * 10240 * 4);
}
static void gr_copy_in(GrState& dst, const GrState& src) {
CU(cuMemcpyDtoD(dst.R.p, src.R.p, src.R.n)); CU(cuMemcpyDtoD(dst.bo.p, src.bo.p, src.bo.n)); CU(cuMemcpyDtoD(dst.inj.p, src.inj.p, src.inj.n));
CU(cuCtxSynchronize());
}
static bool gr_compare(const char* tag, GrState& a, GrState& b, bool xn = true) {
bool ok = same((std::string(tag) + " R").c_str(), a.R.get(), b.R.get());
ok &= same((std::string(tag) + " lo").c_str(), a.lo.get(), b.lo.get());
ok &= same((std::string(tag) + " rs").c_str(), a.rs.get(), b.rs.get());
ok &= same((std::string(tag) + " inject").c_str(), a.injo.get(), b.injo.get());
ok &= same((std::string(tag) + " mixed").c_str(), a.mixed.get(), b.mixed.get());
if (xn) ok &= same((std::string(tag) + " xn").c_str(), a.xn.get(), b.xn.get());
return ok;
}
static void test_gr() {
CUfunction fSplit = get_fn(mGr, "mtp_scalar_gr_split"), fStaged = get_fn(mGr, "mtp_scalar_gr_staged"), fUp = get_fn(mGr, "mtp_scalar_gr_up");
CUfunction nSplit = get_fn(mChain, "chain_gr_split"), nUp16 = get_fn(mChain, "chain_gr_up16"), nUp8 = get_fn(mChain, "chain_gr_up8");
CU(cuFuncSetAttribute(fStaged, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, 2 * 8 * 1280 * 4));
const int NS = 12; // weight sets: 12 x 13.2 MB
std::vector<GrWeights> W(NS);
{
std::vector<float> nh(10240); for (auto& v : nh) v = 0.5f + fabsf(rndf());
std::vector<uint16_t> dh((size_t)320 * 10240), uh((size_t)10240 * 320), ih((size_t)4 * 10240);
for (auto& v : dh) v = bf16_of(rndf() * 0.02f); for (auto& v : uh) v = bf16_of(rndf() * 0.2f); for (auto& v : ih) v = bf16_of(rndf() * 0.02f);
for (int s = 0; s < NS; ++s) {
W[s].norm.alloc(10240 * 4); W[s].down.alloc(dh.size() * 2); W[s].up.alloc(uh.size() * 2); W[s].inject.alloc(ih.size() * 2);
W[s].norm.put(nh.data(), 10240 * 4); W[s].down.put(dh.data(), dh.size() * 2); W[s].up.put(uh.data(), uh.size() * 2); W[s].inject.put(ih.data(), ih.size() * 2);
}
}
for (int T : {1, 2, 3, 4, 6, 8}) {
for (int apply = 0; apply < 2; ++apply) {
GrState base, a, c, d; gr_alloc(base, T); gr_alloc(a, T); gr_alloc(c, T); gr_alloc(d, T);
std::vector<float> rh((size_t)T * 10240), bh((size_t)T * 2560), ih((size_t)T * 4);
for (auto& v : rh) v = rndf() * 3; for (auto& v : bh) v = rndf(); for (auto& v : ih) v = rndf() * 2;
base.R.put(rh.data(), rh.size() * 4); base.bo.put(bh.data(), bh.size() * 4); base.inj.put(ih.data(), ih.size() * 4);
gr_copy_in(a, base); gr_copy_in(c, base); gr_copy_in(d, base);
auto wa = multi_words(a, W[0], apply), wc = multi_words(c, W[0], apply), wd = multi_words(d, W[0], apply);
void* pa[] = {wa.data()}; void* pc[] = {wc.data()}; void* pd[] = {wd.data()};
unsigned shared = T * 2 * 1280 * 4;
// old chain: split, staged down, up
launch(fSplit, T, 4, 256, 0, pa); launch(fStaged, 41, 1, 256, shared, pa); launch(fUp, 160, 1, 256, 0, pa);
// new split + old down + new up16 / up8
launch(nSplit, T, 4, 256, 0, pc); launch(fStaged, 41, 1, 256, shared, pc); launch(nUp16, 160, 1, 256, 0, pc);
launch(nSplit, T, 4, 256, 0, pd); launch(fStaged, 41, 1, 256, shared, pd); launch(nUp8, 320, 1, 256, 0, pd);
CU(cuStreamSynchronize(g_s));
char tag[64];
snprintf(tag, sizeof tag, "gr T=%d apply=%d new_split+up16", T, apply);
bool ok = gr_compare(tag, a, c);
snprintf(tag, sizeof tag, "gr T=%d apply=%d new_split+up8", T, apply);
ok &= gr_compare(tag, a, d);
printf("RESULT gr_exact T=%d apply=%d ok=%d\n", T, apply, ok);
}
}
// ---- the new down projection shapes: exactness against the Original's staged kernel, then timing
struct DV { const char* name; int W, NB; CUfunction f; };
std::vector<DV> dvs = {{"w4_nb3", 4, 3, 0}, {"w8_nb2", 8, 2, 0}, {"w8_nb3", 8, 3, 0}, {"w8_nb4", 8, 4, 0}};
for (auto& v : dvs) {
char nm[64]; snprintf(nm, sizeof nm, "chain_gr_down_%s", v.name);
v.f = get_fn(mChain, nm);
CU(cuFuncSetAttribute(v.f, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, 99 * 1024));
}
auto dshared = [](int T, int NB) { return (unsigned)(NB * T * 5120); };
for (int T : {1, 4, 6, 8}) {
for (int apply = 0; apply < 2; ++apply) {
GrState base, a; gr_alloc(base, T); gr_alloc(a, T);
std::vector<float> rh((size_t)T * 10240), bh((size_t)T * 2560), ih((size_t)T * 4);
for (auto& v : rh) v = rndf() * 3; for (auto& v : bh) v = rndf(); for (auto& v : ih) v = rndf() * 2;
base.R.put(rh.data(), rh.size() * 4); base.bo.put(bh.data(), bh.size() * 4); base.inj.put(ih.data(), ih.size() * 4);
gr_copy_in(a, base);
auto wa = multi_words(a, W[0], apply); void* pa[] = {wa.data()};
launch(fSplit, T, 4, 256, 0, pa); launch(fStaged, 41, 1, 256, T * 2 * 1280 * 4, pa); launch(fUp, 160, 1, 256, 0, pa);
for (auto& v : dvs) {
if (dshared(T, v.NB) > 99 * 1024) continue;
GrState d; gr_alloc(d, T); gr_copy_in(d, base);
auto wd = multi_words(d, W[0], apply); void* pd[] = {wd.data()};
launch(fSplit, T, 4, 256, 0, pd);
launch(v.f, (324 + v.W - 1) / v.W, 1, v.W * 32, dshared(T, v.NB), pd);
launch(fUp, 160, 1, 256, 0, pd);
CU(cuStreamSynchronize(g_s));
char tag[96]; snprintf(tag, sizeof tag, "gr_down %s T=%d apply=%d", v.name, T, apply);
bool ok = gr_compare(tag, a, d);
printf("RESULT gr_down_exact %s T=%d apply=%d ok=%d\n", v.name, T, apply, ok);
}
}
}
for (int T : {4, 6, 8}) {
GrState s; gr_alloc(s, T);
std::vector<float> rh((size_t)T * 10240); for (auto& v : rh) v = rndf() * 3; s.R.put(rh.data(), rh.size() * 4);
std::vector<std::vector<uint64_t>> ws(NS);
for (int i = 0; i < NS; ++i) ws[i] = multi_words(s, W[i], false);
double t0 = time_graph([&](int i) { void* p[] = {ws[i % NS].data()}; launch(fStaged, 41, 1, 256, T * 2 * 1280 * 4, p); }, 96);
printf("RESULT gr_down_time T=%d old_staged us=%.3f\n", T, t0);
for (auto& v : dvs) {
if (dshared(T, v.NB) > 99 * 1024) continue;
double t = time_graph([&](int i) { void* p[] = {ws[i % NS].data()}; launch(v.f, (324 + v.W - 1) / v.W, 1, v.W * 32, dshared(T, v.NB), p); }, 96);
printf("RESULT gr_down_time T=%d %s us=%.3f\n", T, v.name, t);
}
}
// timing (T=4): cold weights rotating over NS sets
for (int T : {4, 6}) {
GrState s; gr_alloc(s, T);
std::vector<float> rh((size_t)T * 10240); for (auto& v : rh) v = rndf() * 3; s.R.put(rh.data(), rh.size() * 4);
std::vector<std::vector<uint64_t>> ws(NS);
for (int i = 0; i < NS; ++i) ws[i] = multi_words(s, W[i], false);
unsigned shared = T * 2 * 1280 * 4;
auto run = [&](const char* name, std::function<void(int)> f) { double t = time_graph(f, 96); printf("RESULT gr_time T=%d %s us_per_call=%.3f\n", T, name, t); };
run("old_split", [&](int i) { void* p[] = {ws[i % NS].data()}; launch(fSplit, T, 4, 256, 0, p); });
run("old_staged_down", [&](int i) { void* p[] = {ws[i % NS].data()}; launch(fStaged, 41, 1, 256, shared, p); });
run("old_up", [&](int i) { void* p[] = {ws[i % NS].data()}; launch(fUp, 160, 1, 256, 0, p); });
run("old_chain", [&](int i) { void* p[] = {ws[i % NS].data()}; launch(fSplit, T, 4, 256, 0, p); launch(fStaged, 41, 1, 256, shared, p); launch(fUp, 160, 1, 256, 0, p); });
run("new_split", [&](int i) { void* p[] = {ws[i % NS].data()}; launch(nSplit, T, 4, 256, 0, p); });
run("new_up16", [&](int i) { void* p[] = {ws[i % NS].data()}; launch(nUp16, 160, 1, 256, 0, p); });
run("new_up8", [&](int i) { void* p[] = {ws[i % NS].data()}; launch(nUp8, 320, 1, 256, 0, p); });
run("new_split+old_down+new_up16", [&](int i) { void* p[] = {ws[i % NS].data()}; launch(nSplit, T, 4, 256, 0, p); launch(fStaged, 41, 1, 256, shared, p); launch(nUp16, 160, 1, 256, 0, p); });
run("new_split+old_down+new_up8", [&](int i) { void* p[] = {ws[i % NS].data()}; launch(nSplit, T, 4, 256, 0, p); launch(fStaged, 41, 1, 256, shared, p); launch(nUp8, 320, 1, 256, 0, p); });
}
}
static void test_qsa() {
const int nkv = 2, G = 12, HD = 256, cap = 2051, chunks = 33, page = 4, cells = 4096;
const int pages = cells / page;
const size_t rows = (size_t)pages * nkv * page;
std::vector<int8_t> kq(rows * HD), vq(rows * HD); std::vector<uint16_t> ks(rows * 4), vs(rows * 4);
for (auto& v : kq) v = (int8_t)(rnd() & 0xff); for (auto& v : vq) v = (int8_t)(rnd() & 0xff);
auto half_bits = [](float f) { // IEEE half conversion (round to nearest even), normal range only
uint32_t u; memcpy(&u, &f, 4); uint32_t sign = (u >> 16) & 0x8000; int e = ((u >> 23) & 0xff) - 127 + 15; uint32_t m = (u >> 13) & 0x3ff;
return (uint16_t)(sign | (e << 10) | m); };
for (auto& v : ks) v = half_bits(0.001f + 0.01f * fabsf(rndf())); for (auto& v : vs) v = half_bits(0.001f + 0.01f * fabsf(rndf()));
std::vector<int32_t> table(pages); for (int i = 0; i < pages; ++i) table[i] = (i * 7 + 3) % pages; // a permutation of pages (7 coprime to 1024)
table[5] = -1; // one unresident block (masked cells)
Dev dkq, dvq, dks, dvs, dtab; dkq.alloc(kq.size()); dvq.alloc(vq.size()); dks.alloc(ks.size() * 2); dvs.alloc(vs.size() * 2); dtab.alloc(pages * 4);
dkq.put(kq.data(), kq.size()); dvq.put(vq.data(), vq.size()); dks.put(ks.data(), ks.size() * 2); dvs.put(vs.data(), vs.size() * 2); dtab.put(table.data(), pages * 4);
CUfunction fo = get_fn(mAttn, "leleka_qsa_decode_chunk"), fn = get_fn(mChain, "chain_qsa_decode_chunk");
for (int T : {1, 4, 6, 8}) {
for (int n_ids : {cap, 1500, 63, 64, 65}) {
std::vector<int32_t> ids((size_t)T * cap), step((size_t)T * 4);
for (int r = 0; r < T; ++r) {
int pos = cells - 1 - r;
for (int j = 0; j < cap; ++j) ids[(size_t)r * cap + j] = (j * (pos / cap + 1) + (j % 3)) % cells;
std::sort(ids.begin() + (size_t)r * cap, ids.begin() + (size_t)(r + 1) * cap);
step[r * 4] = pos; step[r * 4 + 1] = pos + 1; step[r * 4 + 2] = (pos + 1) / 4; step[r * 4 + 3] = n_ids;
}
std::vector<float> qh((size_t)T * nkv * G * HD); for (auto& v : qh) v = rndf();
size_t stride = (size_t)chunks * 24 * (HD + 2) + 64;
Dev q, did, dstep, a0, a1; q.alloc(qh.size() * 4); did.alloc(ids.size() * 4); dstep.alloc(step.size() * 4); a0.alloc(stride * 4 * T); a1.alloc(stride * 4 * T);
q.put(qh.data(), qh.size() * 4); did.put(ids.data(), ids.size() * 4); dstep.put(step.data(), step.size() * 4);
int nk = nkv, ps = page, nch = chunks, cp = cap; float scale = 1.0f / sqrtf(256.0f); long long st = (long long)stride;
auto mk = [&](Dev& acc, void** a, CUdeviceptr* pm, CUdeviceptr* pl) {
*pm = acc.p + (uint64_t)chunks * 24 * HD * 4; *pl = *pm + (uint64_t)chunks * 24 * 4;
a[0] = &q.p; a[1] = &dkq.p; a[2] = &dvq.p; a[3] = &dks.p; a[4] = &dvs.p; a[5] = &dtab.p; a[6] = &did.p; a[7] = &dstep.p; a[8] = &nk; a[9] = &ps; a[10] = &scale;
a[11] = &acc.p; a[12] = pm; a[13] = pl; a[14] = &nch; a[15] = &cp; a[16] = &st; };
void *pa0[17], *pa1[17]; CUdeviceptr m0, l0, m1, l1; mk(a0, pa0, &m0, &l0); mk(a1, pa1, &m1, &l1);
auto go = [&](CUfunction f, void** a) { CU(cuLaunchKernel(f, chunks, nkv, T, 256, 1, 1, 0, g_s, a, nullptr)); };
go(fo, pa0); go(fn, pa1);
CU(cuStreamSynchronize(g_s));
// compare every scratch word that the kernel writes (the whole region it owns: acc, m, l per row)
bool ok = true; char tag[64]; snprintf(tag, sizeof tag, "qsa T=%d n_ids=%d", T, n_ids);
ok &= same(tag, a0.get(), a1.get());
if (n_ids == cap) {
double to = time_graph([&](int) { go(fo, pa0); }, 60);
double tn = time_graph([&](int) { go(fn, pa1); }, 60);
printf("RESULT qsa_chunk T=%d n_ids=%d ok=%d old_us=%.3f new_us=%.3f\n", T, n_ids, ok, to, tn);
} else printf("RESULT qsa_chunk_exact T=%d n_ids=%d ok=%d\n", T, n_ids, ok);
}
}
// MTP form: 512 chunks sized for the whole context; the merge over the used chunks only
{
const int chunks512 = 512;
CUfunction mo = get_fn(mAttn, "leleka_qsa_decode_merge"), mn = get_fn(mChain, "chain_qsa_decode_merge_n");
for (int n_ids : {2051, 1500, 64, 65, 3000, 1}) {
const int T = 1;
std::vector<int32_t> ids((size_t)32768);
for (int j = 0; j < 32768; ++j) ids[j] = j % cells;
std::vector<int32_t> step = {cells - 1, cells, cells / 4, n_ids};
std::vector<float> qh((size_t)T * nkv * G * HD); for (auto& v : qh) v = rndf();
size_t stride = (size_t)chunks512 * 24 * (HD + 2) + 64;
Dev q, did, dstep, a0, at0, at1; q.alloc(qh.size() * 4); did.alloc(ids.size() * 4); dstep.alloc(16); a0.alloc(stride * 4); at0.alloc(24 * HD * 4); at1.alloc(24 * HD * 4);
q.put(qh.data(), qh.size() * 4); did.put(ids.data(), ids.size() * 4); dstep.put(step.data(), 16);
int nk = nkv, ps = page, nch = chunks512, cp = 32768; float scale = 1.0f / 16.0f; long long st = (long long)stride;
CUdeviceptr pm = a0.p + (uint64_t)chunks512 * 24 * HD * 4, pl = pm + (uint64_t)chunks512 * 24 * 4;
void* pa[17] = {&q.p, &dkq.p, &dvq.p, &dks.p, &dvs.p, &dtab.p, &did.p, &dstep.p, &nk, &ps, &scale, &a0.p, &pm, &pl, &nch, &cp, &st};
CU(cuLaunchKernel(fo, chunks512, nkv, 1, 256, 1, 1, 0, g_s, pa, nullptr));
void* m0[] = {&a0.p, &pm, &pl, &nch, &at0.p, &st};
void* m1[] = {&a0.p, &pm, &pl, &nch, &at1.p, &st, &dstep.p};
CU(cuLaunchKernel(mo, 24, 1, 1, 256, 1, 1, 0, g_s, m0, nullptr));
CU(cuLaunchKernel(mn, 24, 1, 1, 256, 1, 1, 0, g_s, m1, nullptr));
CU(cuStreamSynchronize(g_s));
char tag[64]; snprintf(tag, sizeof tag, "qsa merge512 n_ids=%d", n_ids);
bool ok = same(tag, at0.get(), at1.get());
double to = time_graph([&](int) { CU(cuLaunchKernel(mo, 24, 1, 1, 256, 1, 1, 0, g_s, m0, nullptr)); }, 100);
double tn = time_graph([&](int) { CU(cuLaunchKernel(mn, 24, 1, 1, 256, 1, 1, 0, g_s, m1, nullptr)); }, 100);
printf("RESULT qsa_merge512 n_ids=%d ok=%d old_us=%.3f new_us=%.3f\n", n_ids, ok, to, tn);
}
}
}
static void test_tiny() {
const char* eSwi = "_ZN6strata7kernels65_GLOBAL__N__a184a76c_28_mtp_original_full_head_iq_cu_934c6f21_28421swiglu_entries_kernelEPKfS3_Pfx";
const char* eQ = "_ZN6strata7kernels65_GLOBAL__N__a184a76c_28_mtp_original_full_head_iq_cu_934c6f21_28420quantize_q8_1_kernelEPKfP10block_q8_1x";
const char* eSig = "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f34native_scalar_sigmoid_multi_kernelEPf";
const char* eScale = "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f17scale_rows_kernelEPfPKfi";
CUfunction fSwi = get_fn(mIq, eSwi), fQ = get_fn(mIq, eQ), fSig = get_fn(mShared, eSig), fScale = get_fn(mShared, eScale);
CUfunction nSQ = get_fn(mChain, "chain_swiglu_quant_kernel"), nSS = get_fn(mChain, "chain_scale_rows_sigmoid_kernel");
for (int cap : {10, 40, 80}) {
long long nh = (long long)cap * 640;
std::vector<float> gh(nh), uh(nh); for (auto& v : gh) v = rndf() * 8; for (auto& v : uh) v = rndf() * 3;
// include exact zeros and tiny values to hit the amax == 0 branch
for (int i = 0; i < 64 && i < nh; ++i) { gh[i] = 0.0f; uh[i] = 0.0f; }
Dev g, u, h0, h1, q0, q1; g.alloc(nh * 4); u.alloc(nh * 4); h0.alloc(nh * 4); h1.alloc(nh * 4); q0.alloc(nh / 32 * 36); q1.alloc(nh / 32 * 36);
g.put(gh.data(), nh * 4); u.put(uh.data(), nh * 4);
unsigned grid = (unsigned)((nh + 255) / 256);
{ void* a[] = {&g.p, &u.p, &h0.p, &nh}; launch(fSwi, grid, 1, 256, 0, a); }
{ void* a[] = {&h0.p, &q0.p, &nh}; launch(fQ, grid, 1, 256, 0, a); }
{ void* a[] = {&g.p, &u.p, &h1.p, &q1.p, &nh}; launch(nSQ, grid, 1, 256, 0, a); }
CU(cuStreamSynchronize(g_s));
bool ok = same("swiglu_quant h", h0.get(), h1.get()) & same("swiglu_quant q", q0.get(), q1.get());
if (!ok) { auto a = h0.get(), b = h1.get(); int shown = 0; for (long long i = 0; i < nh && shown < 4; ++i) { float x, y; memcpy(&x, &a[4 * i], 4); memcpy(&y, &b[4 * i], 4); if (memcmp(&x, &y, 4)) { printf(" diag h[%lld]: old %.9g new %.9g (g=%.9g up=%.9g)\n", i, x, y, gh[i], uh[i]); ++shown; } } }
double to = time_graph([&](int) { void* a[] = {&g.p, &u.p, &h0.p, &nh}; launch(fSwi, grid, 1, 256, 0, a); void* b[] = {&h0.p, &q0.p, &nh}; launch(fQ, grid, 1, 256, 0, b); }, 200);
double tn = time_graph([&](int) { void* a[] = {&g.p, &u.p, &h1.p, &q1.p, &nh}; launch(nSQ, grid, 1, 256, 0, a); }, 200);
printf("RESULT swiglu_quant cap=%d ok=%d old_us=%.3f new_us=%.3f\n", cap, ok, to, tn);
}
for (int T : {1, 2, 4, 6, 8}) {
const int n = 2560;
std::vector<float> oh((size_t)T * n), gh(T); for (auto& v : oh) v = rndf(); for (auto& v : gh) v = rndf() * 6;
Dev o0, o1, g0, g1; o0.alloc(4 * T * n); o1.alloc(4 * T * n); g0.alloc(4 * 16); g1.alloc(4 * 16);
o0.put(oh.data(), 4 * T * n); o1.put(oh.data(), 4 * T * n); g0.put(gh.data(), 4 * T); g1.put(gh.data(), 4 * T);
int nn = n;
{ void* a[] = {&g0.p}; launch(fSig, 1, 1, T, 0, a); void* b[] = {&o0.p, &g0.p, &nn}; launch(fScale, (n + 127) / 128, T, 128, 0, b); }
{ void* a[] = {&o1.p, &g1.p, &nn}; launch(nSS, (n + 127) / 128, T, 128, 0, a); }
CU(cuStreamSynchronize(g_s));
bool ok = same("scale_sigmoid out", o0.get(), o1.get());
double to = time_graph([&](int) { void* a[] = {&g0.p}; launch(fSig, 1, 1, T, 0, a); void* b[] = {&o0.p, &g0.p, &nn}; launch(fScale, (n + 127) / 128, T, 128, 0, b); }, 200);
double tn = time_graph([&](int) { void* a[] = {&o1.p, &g1.p, &nn}; launch(nSS, (n + 127) / 128, T, 128, 0, a); }, 200);
printf("RESULT scale_sigmoid T=%d ok=%d old_us=%.3f new_us=%.3f\n", T, ok, to, tn);
}
}
struct SamplerParamsH { // strata::kernels::SamplerParams (64 bytes)
int top_k = 20; float top_p = 0.95f, min_p = 0.0f, temperature = 1.0f; int min_keep = 1, penalty_last_n = 0;
float penalty_repeat = 1.0f, penalty_freq = 0.0f, penalty_present = 0.0f; uint64_t seed = 0, counter = 0; bool greedy = false;
};
static_assert(sizeof(SamplerParamsH) == 64, "SamplerParams ABI");
static void test_sampler() {
CUfunction fo = get_fn(mSampler, "sampler_greedy_kernel"), fn = get_fn(mChain, "chain_sampler_greedy_kernel");
CUfunction po = get_fn(mMtpVerify, "mtp_full_row_top_prob_kernel"), pn = get_fn(mChain, "chain_row_top_prob_kernel");
for (int V : {248320, 106299}) {
for (int T : {1, 4, 8}) {
for (int variant = 0; variant < 3; ++variant) { // 0: random, 1: heavy ties, 2: with a penalty history
std::vector<float> lh((size_t)T * V);
for (auto& v : lh) v = rndf() * 10;
if (variant == 1) for (auto& v : lh) v = floorf(v * 2.0f) / 2.0f; // many equal maxima
Dev l, o0, o1, hist; l.alloc(lh.size() * 4); o0.alloc(64); o1.alloc(64); hist.alloc((size_t)T * 64 * 4);
l.put(lh.data(), lh.size() * 4);
std::vector<int32_t> hh((size_t)T * 64, -1);
SamplerParamsH p; p.greedy = true; p.temperature = 0.0f;
int hlen = 0, last_n = 0;
if (variant == 2) {
hlen = 64; last_n = 64; p.penalty_last_n = 64; p.penalty_repeat = 1.3f; p.penalty_freq = 0.1f; p.penalty_present = 0.2f;
for (int t = 0; t < T; ++t) { // history = the top few candidates of the row so the penalty changes the pick
std::vector<int> idx(V); for (int i = 0; i < V; ++i) idx[i] = i;
std::partial_sort(idx.begin(), idx.begin() + 40, idx.end(), [&](int a, int b) { return lh[(size_t)t * V + a] > lh[(size_t)t * V + b]; });
for (int j = 0; j < 40; ++j) hh[(size_t)t * 64 + j] = idx[j];
for (int j = 40; j < 64; ++j) hh[(size_t)t * 64 + j] = (int)(rnd() % V);
}
hist.put(hh.data(), hh.size() * 4);
}
CUdeviceptr hp = variant == 2 ? hist.p : 0;
unsigned shared = variant == 2 ? (unsigned)(((V + 31) / 32) * 4) : 0;
int pm = last_n, pl = last_n, vv = V, hl = hlen;
void* a0[] = {&l.p, &vv, &hp, &hl, &p, &pm, &pl, &o0.p};
void* a1[] = {&l.p, &vv, &hp, &hl, &p, &pm, &pl, &o1.p};
launch(fo, T, 1, 1024, shared, a0); launch(fn, T, 1, 1024, shared, a1);
CU(cuStreamSynchronize(g_s));
char tag[64]; snprintf(tag, sizeof tag, "sampler V=%d T=%d variant=%d", V, T, variant);
bool ok = same(tag, o0.get(), o1.get());
if (!ok) { auto a = o0.get(), b = o1.get(); for (int t = 0; t < T; ++t) { int32_t x, y; memcpy(&x, &a[4 * t], 4); memcpy(&y, &b[4 * t], 4); if (x != y) printf(" diag row %d: old idx %d (logit %.9g) new idx %d (logit %.9g)\n", t, x, lh[(size_t)t * V + x], y, lh[(size_t)t * V + y]); } }
double to = time_graph([&](int) { launch(fo, T, 1, 1024, shared, a0); }, 50);
double tn = time_graph([&](int) { launch(fn, T, 1, 1024, shared, a1); }, 50);
printf("RESULT sampler_greedy V=%d T=%d variant=%d ok=%d old_us=%.3f new_us=%.3f\n", V, T, variant, ok, to, tn);
if (variant == 0) {
Dev ids, pr0, pr1; ids.alloc(64); pr0.alloc(64); pr1.alloc(64);
std::vector<int32_t> idh(16); for (int t = 0; t < T; ++t) idh[t] = (int)(rnd() % V);
ids.put(idh.data(), 64);
void* b0[] = {&l.p, &vv, &ids.p, &pr0.p}; void* b1[] = {&l.p, &vv, &ids.p, &pr1.p};
launch(po, T, 1, 1024, 0, b0); launch(pn, T, 1, 1024, 0, b1);
CU(cuStreamSynchronize(g_s));
snprintf(tag, sizeof tag, "row_top_prob V=%d T=%d", V, T);
bool ok2 = same(tag, pr0.get(), pr1.get());
double t0 = time_graph([&](int) { launch(po, T, 1, 1024, 0, b0); }, 50);
double t1 = time_graph([&](int) { launch(pn, T, 1, 1024, 0, b1); }, 50);
printf("RESULT row_top_prob V=%d T=%d ok=%d old_us=%.3f new_us=%.3f\n", V, T, ok2, t0, t1);
}
}
}
}
}
static void test_qsaprof(const std::string& dir) {
CUmodule m = load_module(dir + "/qsa_prof.ptx");
CUfunction f = get_fn(m, "qsa_chunk_prof");
const int nkv = 2, G = 12, HD = 256, cap = 2051, chunks = 33, page = 4, cells = 4096;
const int pages = cells / page; const size_t rows = (size_t)pages * nkv * page;
std::vector<int8_t> kq(rows * HD), vq(rows * HD); std::vector<uint16_t> ks(rows * 4, 0x2c00), vs(rows * 4, 0x2c00);
for (auto& v : kq) v = (int8_t)(rnd() & 0xff); for (auto& v : vq) v = (int8_t)(rnd() & 0xff);
std::vector<int32_t> table(pages); for (int i = 0; i < pages; ++i) table[i] = (i * 7 + 3) % pages;
Dev dkq, dvq, dks, dvs, dtab, stamps; dkq.alloc(kq.size()); dvq.alloc(vq.size()); dks.alloc(ks.size() * 2); dvs.alloc(vs.size() * 2); dtab.alloc(pages * 4); stamps.alloc(64);
dkq.put(kq.data(), kq.size()); dvq.put(vq.data(), vq.size()); dks.put(ks.data(), ks.size() * 2); dvs.put(vs.data(), vs.size() * 2); dtab.put(table.data(), pages * 4);
for (int T : {1, 4}) {
std::vector<int32_t> ids((size_t)T * cap), step((size_t)T * 4);
for (int r = 0; r < T; ++r) { for (int j = 0; j < cap; ++j) ids[(size_t)r * cap + j] = (j * 2 + (j % 3)) % cells; std::sort(ids.begin() + (size_t)r * cap, ids.begin() + (size_t)(r + 1) * cap); step[r * 4] = cells - 1; step[r * 4 + 1] = cells; step[r * 4 + 2] = cells / 4; step[r * 4 + 3] = cap; }
std::vector<float> qh((size_t)T * nkv * G * HD); for (auto& v : qh) v = rndf();
size_t stride = (size_t)chunks * 24 * (HD + 2) + 64;
Dev q, did, dstep, a0; q.alloc(qh.size() * 4); did.alloc(ids.size() * 4); dstep.alloc(step.size() * 4); a0.alloc(stride * 4 * T);
q.put(qh.data(), qh.size() * 4); did.put(ids.data(), ids.size() * 4); dstep.put(step.data(), step.size() * 4);
int nk = nkv, ps = page, nch = chunks, cp = cap; float scale = 1.0f / 16.0f; long long st = (long long)stride;
CUdeviceptr pm = a0.p + (uint64_t)chunks * 24 * HD * 4, pl = pm + (uint64_t)chunks * 24 * 4;
void* a[] = {&stamps.p, &q.p, &dkq.p, &dvq.p, &dks.p, &dvs.p, &dtab.p, &did.p, &dstep.p, &nk, &ps, &scale, &a0.p, &pm, &pl, &nch, &cp, &st};
for (int rep = 0; rep < 3; ++rep) { CU(cuLaunchKernel(f, chunks, nkv, T, 256, 1, 1, 0, g_s, a, nullptr)); CU(cuStreamSynchronize(g_s)); }
auto b = stamps.get(); unsigned long long v[4]; memcpy(v, b.data(), 32);
int clk = 0; cuDeviceGetAttribute(&clk, CU_DEVICE_ATTRIBUTE_CLOCK_RATE, 0);
printf("RESULT qsa_prof T=%d cycles setup=%llu scores=%llu softmax=%llu values=%llu (SM clock %d kHz: %.2f %.2f %.2f %.2f us)\n", T, v[0], v[1], v[2], v[3], clk,
v[0] * 1e3 / clk, v[1] * 1e3 / clk, v[2] * 1e3 / clk, v[3] * 1e3 / clk);
}
}
static void test_grprof(const std::string& dir) {
CUmodule m = load_module(dir + "/gr_prof.ptx");
CUfunction f = get_fn(m, "gr_down_prof_w8_nb3");
CU(cuFuncSetAttribute(f, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, 99 * 1024));
CUfunction fSplit = get_fn(mGr, "mtp_scalar_gr_split");
GrWeights W; std::vector<float> nh(10240); for (auto& v : nh) v = 0.5f + fabsf(rndf());
std::vector<uint16_t> dh((size_t)320 * 10240), uh((size_t)10240 * 320), ih((size_t)4 * 10240);
for (auto& v : dh) v = bf16_of(rndf() * 0.02f); for (auto& v : uh) v = bf16_of(rndf() * 0.2f); for (auto& v : ih) v = bf16_of(rndf() * 0.02f);
W.norm.alloc(10240 * 4); W.down.alloc(dh.size() * 2); W.up.alloc(uh.size() * 2); W.inject.alloc(ih.size() * 2);
W.norm.put(nh.data(), 10240 * 4); W.down.put(dh.data(), dh.size() * 2); W.up.put(uh.data(), uh.size() * 2); W.inject.put(ih.data(), ih.size() * 2);
for (int T : {4, 6}) {
GrState s; gr_alloc(s, T);
std::vector<float> rh((size_t)T * 10240); for (auto& v : rh) v = rndf() * 3; s.R.put(rh.data(), rh.size() * 4);
auto w = multi_words(s, W, false); void* p0[] = {w.data()};
Dev st; st.alloc(64); CUdeviceptr stp = st.p; void* p1[] = {w.data(), &stp};
launch(fSplit, T, 4, 256, 0, p0);
for (int rep = 0; rep < 3; ++rep) { CU(cuLaunchKernel(f, 41, 1, 1, 256, 1, 1, 3 * T * 5120, g_s, p1, nullptr)); CU(cuStreamSynchronize(g_s)); }
auto b = st.get(); unsigned long long v[4]; memcpy(v, b.data(), 32);
int clk = 0; cuDeviceGetAttribute(&clk, CU_DEVICE_ATTRIBUTE_CLOCK_RATE, 0);
printf("RESULT gr_down_prof T=%d total=%llu wait=%llu compute=%llu sync=%llu cycles (prologue+epilogue=%lld); %.2f / %.2f / %.2f / %.2f us\n", T, v[0], v[1], v[2], v[3],
(long long)v[0] - (long long)(v[1] + v[2] + v[3]), v[0] * 1e3 / clk, v[1] * 1e3 / clk, v[2] * 1e3 / clk, v[3] * 1e3 / clk);
}
}
int main(int argc, char** argv) {
if (argc < 2) { fprintf(stderr, "usage: chain_probe PTXDIR [tests...]\n"); return 2; }
std::string dir = argv[1];
std::vector<std::string> tests;
for (int i = 2; i < argc; ++i) tests.push_back(argv[i]);
if (tests.empty()) tests = {"copy_i32", "copy_rows", "doorbell", "ab", "gr", "qsa", "tiny", "sampler", "qsaprof", "grprof"};
CU(cuInit(0)); CUdevice dev; CU(cuDeviceGet(&dev, 0)); CUcontext ctx; CU(cuDevicePrimaryCtxRetain(&ctx, dev)); CU(cuCtxSetCurrent(ctx));
char name[256]; cuDeviceGetName(name, sizeof name, dev);
int maj, min; cuDeviceGetAttribute(&maj, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, dev); cuDeviceGetAttribute(&min, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, dev);
printf("# %s sm_%d%d\n", name, maj, min);
CU(cuStreamCreate(&g_s, CU_STREAM_NON_BLOCKING));
mVerify = load_module(dir + "/original_verify.ptx");
mGr = load_module(dir + "/mtp_original_full_fused_gr.ptx");
mChain = load_module(dir + "/chain_window.ptx");
mAttn = load_module(dir + "/mtp_original_full_attention.ptx");
mIq = load_module(dir + "/mtp_original_full_head_iq.ptx");
mShared = load_module(dir + "/mtp_original_full_shared.ptx");
mSampler = load_module(dir + "/native_head_sampler.ptx");
mMtpVerify = load_module(dir + "/mtp_original_full_verify.ptx");
for (auto& t : tests) {
if (t == "copy_i32") test_copy_i32();
else if (t == "copy_rows") test_copy_rows();
else if (t == "doorbell") test_doorbell();
else if (t == "ab") test_ab();
else if (t == "gr") test_gr();
else if (t == "qsa") test_qsa();
else if (t == "tiny") test_tiny();
else if (t == "sampler") test_sampler();
else if (t == "qsaprof") test_qsaprof(dir);
else if (t == "grprof") test_grprof(dir);
else fprintf(stderr, "unknown test %s\n", t.c_str());
}
printf("RESULT summary failures=%d\n", g_fail);
return g_fail ? 1 : 0;
}
+170
View File
@@ -0,0 +1,170 @@
// Instrumented copy of the chain GR down kernel (clock64 per phase of block 3); probe-only, never sealed.
// claude/chain-kernels: latency-hoisted, bit-identical variants of the verify-window kernels that sit on the decode chain
// (docs/chain-kernels.md). Every kernel here computes EVERY output with the same operations in the same order as the
// kernel it replaces (original_verify.cu, mtp_original_full_fused_gr.cu); only the issue order of independent loads, the
// block shape and the number of launches change. Selected at record time by LELEKA_CHAIN_* switches.
//
// Compile flags (same as the sources they derive from): -ptx -O3 -arch=sm_120 --fmad=true --ftz=false -std=c++17
#include <cuda_runtime.h>
#include <stdint.h>
#include <stddef.h>
#include <cuda_fp16.h>
#include <cfloat>
#include "strata/kernels/fused_gr.hpp"
#include "strata/kernels/sampler.hpp"
using strata::kernels::FusedGrArgs;
constexpr int kFusedGrMaxT = strata::kernels::kFusedGrMaxT;
namespace {
__device__ __forceinline__ void strata_spin_pause() {
__nanosleep(100);
}
__device__ __forceinline__ float warp_sum(float v) {
#pragma unroll
for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
return v;
}
__device__ __forceinline__ float sigmoidf_(float x) { return 1.0f / (1.0f + __expf(-x)); }
// 8 bf16 packed in a uint4 against 8 floats (fused_gr.cu `dot8`).
__device__ __forceinline__ float dot8(const uint4 w, const float* x) {
float acc = 0.0f;
const uint32_t v[4] = {w.x, w.y, w.z, w.w};
#pragma unroll
for (int j = 0; j < 4; ++j) {
acc = fmaf(__uint_as_float(v[j] << 16), x[2 * j], acc);
acc = fmaf(__uint_as_float(v[j] & 0xffff0000u), x[2 * j + 1], acc);
}
return acc;
}
constexpr int N = 2560;
constexpr int HC = 4;
constexpr int D = N * HC;
constexpr int LR = 320;
constexpr int THREADS = 256;
constexpr int WARPS = THREADS / 32;
struct GrMulti {
FusedGrArgs a[kFusedGrMaxT];
float* xn;
int T;
};
} // namespace
static_assert(sizeof(FusedGrArgs) == 112, "Original FusedGrArgs ABI");
static_assert(sizeof(GrMulti) == 912, "Original GrMulti ABI");
namespace {
constexpr int H_TILE = 1280;
constexpr int N_HTILES = D / H_TILE; // 8
constexpr int HQ = H_TILE / 8 / 32; // 5 chunks per lane per tile
constexpr int DOWN_ROWS = LR + HC; // 320 down rows + 4 inject rows
__device__ __forceinline__ void cp_async16(void* smem, const void* gmem) {
const unsigned sa = (unsigned) __cvta_generic_to_shared(smem);
asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(sa), "l"(gmem) : "memory");
}
__device__ __forceinline__ void cp_async_commit() { asm volatile("cp.async.commit_group;\n" ::: "memory"); }
template <int N>
__device__ __forceinline__ void cp_async_wait() { asm volatile("cp.async.wait_group %0;\n" ::"n"(N) : "memory"); }
__device__ __forceinline__ float dot8v(const uint4 w, const float4 x0, const float4 x1) {
float acc = 0.0f;
acc = fmaf(__uint_as_float(w.x << 16), x0.x, acc);
acc = fmaf(__uint_as_float(w.x & 0xffff0000u), x0.y, acc);
acc = fmaf(__uint_as_float(w.y << 16), x0.z, acc);
acc = fmaf(__uint_as_float(w.y & 0xffff0000u), x0.w, acc);
acc = fmaf(__uint_as_float(w.z << 16), x1.x, acc);
acc = fmaf(__uint_as_float(w.z & 0xffff0000u), x1.y, acc);
acc = fmaf(__uint_as_float(w.w << 16), x1.z, acc);
acc = fmaf(__uint_as_float(w.w & 0xffff0000u), x1.w, acc);
return acc;
}
template <int W>
__device__ __forceinline__ void stage_tile(const GrMulti& m, int T, int h, float4* buf, int t) {
for (int i = t; i < T * (H_TILE / 4); i += W * 32) {
const int k = i / (H_TILE / 4), s4 = i - k * (H_TILE / 4);
const float* src = m.xn + (size_t) k * D + (size_t) h * H_TILE + (size_t) s4 * 4;
cp_async16(buf + (size_t) k * (H_TILE / 4) + (s4 & 1) * (H_TILE / 8) + (s4 >> 1), src);
}
}
template <int W, int NB>
__device__ __forceinline__ void gr_down_body(const GrMulti& m, unsigned long long* st) {
const long long c0 = clock64();
extern __shared__ __align__(16) float4 hbuf[]; // NB x [T][2][160] float4
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const int T = m.T;
const int row = blockIdx.x * W + warp; // 0..319 down rows, 320..323 inject rows
const bool inject = row >= LR;
const bool active = row < DOWN_ROWS && !(inject && m.a[0].w_inject == nullptr);
const uint16_t* wrow = (inject ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? (inject ? row - LR : row) : 0) * D;
const uint4* w4 = reinterpret_cast<const uint4*>(wrow);
const size_t buf_f4 = (size_t) T * (H_TILE / 4);
long long w_wait = 0, w_comp = 0, w_sync = 0;
float acc[kFusedGrMaxT];
#pragma unroll
for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f;
uint4 wv[N_HTILES][HQ];
if (active) {
#pragma unroll
for (int h = 0; h < N_HTILES; ++h)
#pragma unroll
for (int q = 0; q < HQ; ++q) wv[h][q] = __ldg(w4 + h * (H_TILE / 8) + lane + 32 * q);
}
#pragma unroll
for (int b = 0; b < NB - 1; ++b) {
stage_tile<W>(m, T, b, hbuf + b * buf_f4, t);
cp_async_commit();
}
#pragma unroll
for (int h = 0; h < N_HTILES; ++h) {
const long long a0 = clock64();
cp_async_wait<NB - 2>();
__syncthreads();
const long long a1 = clock64(); w_wait += a1 - a0;
const float4* cur = hbuf + (h % NB) * buf_f4;
if (active) {
#pragma unroll
for (int q = 0; q < HQ; ++q) {
const int j = lane + 32 * q;
#pragma unroll
for (int k = 0; k < kFusedGrMaxT; ++k) {
if (k < T) {
const float4* pk = cur + (size_t) k * (H_TILE / 4);
acc[k] += dot8v(wv[h][q], pk[j], pk[H_TILE / 8 + j]);
}
}
}
}
const long long a2 = clock64(); w_comp += a2 - a1;
__syncthreads();
w_sync += clock64() - a2;
if (h + NB - 1 < N_HTILES) stage_tile<W>(m, T, h + NB - 1, hbuf + ((h + NB - 1) % NB) * buf_f4, t);
cp_async_commit();
}
if (blockIdx.x == 3 && threadIdx.x == 0) { st[0] = (unsigned long long)(clock64() - c0); st[1] = (unsigned long long)w_wait; st[2] = (unsigned long long)w_comp; st[3] = (unsigned long long)w_sync; }
if (!active) return;
float s[kFusedGrMaxT];
#pragma unroll
for (int k = 0; k < kFusedGrMaxT; ++k) s[k] = k < T ? warp_sum(acc[k]) : 0.0f;
#pragma unroll
for (int k = 0; k < kFusedGrMaxT; ++k) {
if (k >= T || lane != k) continue;
if (inject) {
m.a[k].inject_out[row - LR] = s[k];
} else {
const float x = s[k] / (float) HC;
m.a[k].lo[row] = x / (1.0f + __expf(-x));
}
}
}
} // namespace
extern "C" __global__ void __launch_bounds__(256) gr_down_prof_w8_nb3(GrMulti m, unsigned long long* st) { gr_down_body<8, 3>(m, st); }
+21
View File
@@ -0,0 +1,21 @@
# claude/chain-kernels: paired A/B of the port's own previous head against the chain kernels (same binary, LELEKA_CHAIN=0 / all), 3 interleaved
# repetitions (order B C / C B / B C) of the 6-prompt corpus x 2 passes x 128 tokens, spec 4 + suffix 3, min_p 0.5, static 2048 slots/layer ranked by the
# corpus's OWN routing (the high-hit regime of real agent sessions), the MTP draft vocabulary bound (LELEKA_ORIGINAL_SERVE_RT_DIR).
# Greedy ids must be identical between the arms of a repetition (static tier). Model job: ask the coordinator for the slot.
set -uo pipefail
export BIN=${BIN:-$HOME/work/chain-bin/rt-t3}
source ~/work/gpu-runs/holder2/dec-common.sh
export PROFILE=$HOME/work/ledger/corpus-profile.bin
COMMON="LELEKA_ORIGINAL_SERVE_RT_DIR=$A/data/mtp-rt LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 LELEKA_ORIGINAL_SERVE_MAX_CONTEXT=4096 LELEKA_ORIGINAL_SERVE_CAPACITY=2048"
CHAIN_ON=${CHAIN_ON:-all}
mem_check || { echo "abort: MemAvailable"; exit 3; }
arm() {
case $1 in
B) run_corpus chain-B-$2 $COMMON LELEKA_CHAIN=0 ;;
C) run_corpus chain-C-$2 $COMMON LELEKA_CHAIN=$CHAIN_ON ;;
esac
}
for spec in "1:B C" "2:C B" "3:B C"; do
rep=${spec%%:*}; for a in ${spec#*:}; do arm $a $rep; done
done
date -u +%FT%TZ
+11
View File
@@ -0,0 +1,11 @@
# claude/chain-kernels: CUPTI timeline of the decode windows, port previous head (LELEKA_CHAIN=0) against the chain kernels, high-hit regime (corpus-own static
# profile), MTP draft vocabulary bound; the window starts after the 7th finished request as in ledger job 9004. Analysis: tools/chain-probe/window_table.py.
source ~/work/ledger/ledger-common.sh
export BIN=${BIN:-$HOME/work/chain-bin/rt-t3}
mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; }
header
CP=$LD/corpus-profile.bin
CHAIN_ON=${CHAIN_ON:-all}
port_corpus chain-trace-base 7 10 LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$CP LELEKA_ORIGINAL_SERVE_RT_DIR=$A/data/mtp-rt LELEKA_CHAIN=0
port_corpus chain-trace-on 7 10 LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$CP LELEKA_ORIGINAL_SERVE_RT_DIR=$A/data/mtp-rt LELEKA_CHAIN=$CHAIN_ON
date -u +%FT%TZ
@@ -0,0 +1,39 @@
# claude/chain-kernels: effect of the MTP draft vocabulary on acceptance and decode speed in agent traffic (coordinator request): the first 30 requests of the
# two captured Codex sessions (943b tic-tac-toe, conversation cache; 945 CRM, prefix cache auto) replayed through the port with the reference configuration
# (auto per-layer expert slots, spec_min_p 0.5, LELEKA_CHAIN=0 so only the vocabulary differs), three draft vocabularies:
# V0 = none (full 248,320-row head), V1 = the Original's shipped subset (106,299 ids, English/code + CJK), V3 = V1 + every Cyrillic token (124,737 ids).
# Trimmed on the coordinator's decision: ONLY the CRM session (3 arms) plus one 6-prompt corpus arm with V3 (the Ukrainian prompt 3 tokens per round with the Cyrillic
# union; the none / shipped numbers of the same corpus are in ledger job 9004, port-corpus-b / port-corpus-rt). Model job, 4 arms of ~7 min.
set -uo pipefail
A=$HOME/leleka-gates/assets; G=$HOME/work/gpu-runs
export LD_LIBRARY_PATH=$HOME/cuda-toolkits/cublas-12.9.1.4/lib:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-}
export LELEKA_STRA169_KAR_PROVENANCE=$A/qwen-iq3-s-l2-v4.kar.provenance.json
export LELEKA_STRA169_IQ3S_SHARD0=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf
export LELEKA_STRA169_IQ3S_SHARD1=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf
export LELEKA_STRA169_MTP_PACK=$A/data/mtp-rt LELEKA_STRA169_MTP_STAGING=$G/mtp-staging-own
export LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.55 LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto
export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$G/baseline/profile.bin LELEKA_GRAPH_EXEC_REUSE=off LELEKA_SERVE_PROFILE=1
export LELEKA_ORIGINAL_SERVE_REPLAY=yes LELEKA_ORIGINAL_SERVE_BUDGET_GIB=30 LELEKA_REPLAY_COUNT=30 LELEKA_REPLAY_SPEC_MIN_P=0.5 LELEKA_CHAIN=0
BIN=${BIN:-$HOME/work/chain-bin/rt-t2}
OUT=$HOME/work/chain-bin/runs/9c7-vocab; mkdir -p $OUT
# V3 staging: the MTP pack's heavy files by symlink, the draft vocabulary replaced
V3=$HOME/work/chain-bin/rt-v3; mkdir -p $V3
for f in dense.bin dense.txt experts.bin; do ln -sf $A/data/mtp-rt/$f $V3/$f; done
cp $HOME/work/chain-bin/draft_vocab_plus_cyr.bin $V3/draft_vocab.bin
date -u +%FT%TZ; sha256sum $BIN $A/data/mtp-rt/draft_vocab.bin $V3/draft_vocab.bin
arm() { # name session rt_dir_or_none prefix_mib
echo "=== arm $1: session=$2 rt=$3"; date -u +%FT%TZ
local env_rt=()
[ "$3" != none ] && env_rt=(LELEKA_ORIGINAL_SERVE_RT_DIR=$3)
env "${env_rt[@]}" LELEKA_REPLAY_DIR=$HOME/work/codex-e2e/capture/$2 ${4:+LELEKA_REPLAY_PREFIX_MIB=$4} $BIN --ignored --test-threads=1 --nocapture original_serve_replay_smoke > $OUT/$1.log 2>&1
grep -E '^REPLAY (SUMMARY|config)|test result|panicked' $OUT/$1.log | cut -c1-400
awk '/^REPLAY #[0-9]+ file/{for(i=1;i<=NF;i++){split($i,k,"="); if(k[1]=="produced")p+=k[2]; if(k[1]=="rounds")r+=k[2]}} END{if(r>0) printf "tokens_per_round=%.3f (%d tokens / %d rounds)\n", p/r, p, r}' $OUT/$1.log
}
arm crm-V1 945-codex-crm $A/data/mtp-rt auto
arm crm-V0 945-codex-crm none auto
arm crm-V3 945-codex-crm $V3 auto
# the 6-prompt corpus with V3 (configuration of ledger job 9004 port-corpus-rt: static 2048 slots, standard profile)
( source ~/work/ledger/ledger-common.sh; export BIN
port_corpus chain-vocab-corpus-V3 0 0 LELEKA_ORIGINAL_SERVE_RT_DIR=$V3 LELEKA_CHAIN=0
grep -E "DBG corpus [0-9]+ output" $OUT/chain-vocab-corpus-V3.full | cut -c1-120 ) 2>&1 | tee $OUT/corpus-V3.log
date -u +%FT%TZ
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""Parse the log of a chain A/B job (9c5-*): per arm and pass the decode tok/s of the requests of 100+ tokens (decode-parity's metric) and the
greedy ids per corpus request; prints the paired table and whether the ids of the arms of each repetition are identical.
python3 ab_parse.py JOB.log
"""
import re
import sys
import statistics
import collections
arms = collections.OrderedDict()
cur = None
for line in open(sys.argv[1], errors="replace"):
m = re.match(r"=== port (chain-\w+-\d+):", line)
if m:
cur = m.group(1)
arms[cur] = {"ids": {}, "rate": collections.defaultdict(list), "tok": collections.defaultdict(float), "ms": collections.defaultdict(float)}
continue
if cur is None:
continue
m = re.search(r"DBG corpus (\d+) output(?: pass=(\d+))? \((\d+) tokens, rounds (\d+)\): (.*)$", line)
if m:
arms[cur]["ids"][(int(m.group(1)), int(m.group(2) or 0))] = m.group(5).strip()
continue
m = re.search(r"DBG timing corpus (\d+) pass (\d+): prompt ([\d.]+) ms, decode ([\d.]+) ms, produced (\d+), decode ([\d.]+) tok/s", line)
if m:
idx, p, dec_ms, produced = int(m.group(1)), int(m.group(2)), float(m.group(4)), int(m.group(5))
if produced >= 100:
arms[cur]["tok"][p] += produced
arms[cur]["ms"][p] += dec_ms
print("%-16s %12s %12s" % ("arm", "pass0 tok/s", "pass1 tok/s"))
res = {}
for a, d in arms.items():
r = [d["tok"][p] * 1000.0 / d["ms"][p] if d["ms"][p] else float("nan") for p in (0, 1)]
res[a] = r
print("%-16s %12.2f %12.2f" % (a, r[0], r[1]))
for tag in sorted({a.split("-")[1] for a in arms}):
for p in (0, 1):
v = [res[a][p] for a in arms if a.split("-")[1] == tag]
if v:
print("arm %s pass %d: mean %.2f [%.2f..%.2f] n=%d" % (tag, p, statistics.mean(v), min(v), max(v), len(v)))
reps = sorted({a.rsplit("-", 1)[1] for a in arms})
for rep in reps:
group = [a for a in arms if a.endswith("-" + rep)]
ids = [arms[a]["ids"] for a in group]
same = all(i == ids[0] for i in ids[1:]) and bool(ids[0])
print("repetition %s: ids identical across arms %s (%d requests)" % (rep, same, len(ids[0]) if ids else 0))
+206
View File
@@ -0,0 +1,206 @@
// claude/chain-kernels: model-free micro-benchmark of kernel-to-kernel latency inside a CUDA graph, with and without
// programmatic dependent launch (PDL, griddepcontrol), and of the L2-prefetch-before-wait trick for weight streaming.
// Prints "RESULT <name> key=value" lines. Build: tools/chain-probe/build.sh. Never touches the model.
#include <cuda_runtime.h>
#include <cstdio>
#include <cstdint>
#include <cstdlib>
#include <vector>
#include <algorithm>
#define CK(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { fprintf(stderr, "CUDA error %s at %d: %s\n", #x, __LINE__, cudaGetErrorString(e_)); exit(2); } } while (0)
__device__ __forceinline__ void pdl_wait() { asm volatile("griddepcontrol.wait;" ::: "memory"); }
__device__ __forceinline__ void pdl_trigger() { asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); }
// A tiny dependent kernel: x[i] = x[i] * 1.0001 + 1 on `n` floats. MODE 0 plain, 1 wait only, 2 trigger + wait.
template <int MODE>
__global__ void tiny(float* x, int n) {
if (MODE == 2) pdl_trigger();
if (MODE >= 1) pdl_wait();
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) x[i] = x[i] * 1.0001f + 1.0f;
}
// A weight-streaming matvec stand-in: y[r] = sum_c W[r][c] * x[c] (bf16 weights as uint4), one warp per row.
// MODE 0 plain; MODE 3 PDL with the first 4 weight chunks loaded into registers BEFORE griddepcontrol.wait;
// MODE 4 PDL, L2 prefetch of the warp's weight row before the wait, then the normal body.
template <int MODE>
__global__ void __launch_bounds__(256) mv(const uint4* __restrict__ W, const float* __restrict__ x, float* __restrict__ y, int cols8, int rows) {
if (MODE >= 3) pdl_trigger();
const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
const int row = blockIdx.x * 8 + warp;
const uint4* w4 = W + (size_t)row * cols8;
if (MODE == 4 && row < rows) {
for (int j = lane * 8; j < cols8; j += 32 * 8) asm volatile("prefetch.global.L2 [%0];" ::"l"(w4 + j));
}
uint4 reg[4];
reg[0] = reg[1] = reg[2] = reg[3] = make_uint4(0, 0, 0, 0);
if (MODE == 3 && row < rows) {
#pragma unroll
for (int q = 0; q < 4; ++q) reg[q] = (lane + 32 * q < cols8) ? __ldg(w4 + lane + 32 * q) : make_uint4(0, 0, 0, 0);
}
if (MODE >= 3) pdl_wait();
if (row >= rows) return;
float acc = 0.f;
for (int j = lane, q = 0; j < cols8; j += 32, ++q) {
uint4 w;
if (MODE == 3 && q < 4) w = reg[q]; else w = __ldg(w4 + j);
const float* xx = x + j * 8;
const uint32_t v[4] = {w.x, w.y, w.z, w.w};
#pragma unroll
for (int k = 0; k < 4; ++k) {
acc = fmaf(__uint_as_float(v[k] << 16), xx[2 * k], acc);
acc = fmaf(__uint_as_float(v[k] & 0xffff0000u), xx[2 * k + 1], acc);
}
}
#pragma unroll
for (int o = 16; o > 0; o >>= 1) acc += __shfl_xor_sync(0xffffffffu, acc, o);
if (lane == 0) y[row] = acc;
}
static void launch_cfg(const void* fn, dim3 g, dim3 b, cudaStream_t s, bool pdl, void** args) {
cudaLaunchConfig_t cfg = {};
cfg.gridDim = g; cfg.blockDim = b; cfg.dynamicSmemBytes = 0; cfg.stream = s;
cudaLaunchAttribute at[1];
at[0].id = cudaLaunchAttributeProgrammaticStreamSerialization;
at[0].val.programmaticStreamSerializationAllowed = 1;
cfg.attrs = at; cfg.numAttrs = pdl ? 1 : 0;
CK(cudaLaunchKernelExC(&cfg, fn, args));
}
static double time_graph(cudaGraphExec_t ge, cudaStream_t s, int reps) {
for (int i = 0; i < 3; ++i) CK(cudaGraphLaunch(ge, s));
CK(cudaStreamSynchronize(s));
std::vector<double> v;
cudaEvent_t a, b; CK(cudaEventCreate(&a)); CK(cudaEventCreate(&b));
for (int i = 0; i < reps; ++i) {
CK(cudaEventRecord(a, s)); CK(cudaGraphLaunch(ge, s)); CK(cudaEventRecord(b, s)); CK(cudaEventSynchronize(b));
float ms; CK(cudaEventElapsedTime(&ms, a, b)); v.push_back(ms * 1000.0);
}
std::sort(v.begin(), v.end());
return v[v.size() / 2];
}
template <int MODE>
static double chain_tiny(int nk, int blocks, float* x, int n, cudaStream_t s) {
cudaGraph_t g; cudaGraphExec_t ge;
CK(cudaStreamBeginCapture(s, cudaStreamCaptureModeGlobal));
for (int i = 0; i < nk; ++i) {
void* args[] = {&x, &n};
launch_cfg((const void*)tiny<MODE>, dim3(blocks), dim3(256), s, MODE != 0, args);
}
CK(cudaStreamEndCapture(s, &g));
CK(cudaGraphInstantiate(&ge, g, 0));
double us = time_graph(ge, s, 30);
CK(cudaGraphExecDestroy(ge)); CK(cudaGraphDestroy(g));
return us;
}
// chain of matvecs over `nm` distinct matrices (each rows x cols bf16) with a small dependent kernel between each pair
template <int MODE>
static double chain_mv(int nm, int rows, int cols, const uint4* W, float* x, float* y, float* z, int n, cudaStream_t s) {
cudaGraph_t g; cudaGraphExec_t ge;
CK(cudaStreamBeginCapture(s, cudaStreamCaptureModeGlobal));
int cols8 = cols / 8;
for (int i = 0; i < nm; ++i) {
const uint4* w = W + (size_t)i * rows * cols8;
const float* xc = x;
void* a1[] = {&w, &xc, &y, &cols8, &rows};
launch_cfg((const void*)mv<MODE>, dim3((rows + 7) / 8), dim3(256), s, MODE >= 3, a1);
float* zz = z; int nn = n;
void* a2[] = {&zz, &nn};
if (MODE >= 3) launch_cfg((const void*)tiny<2>, dim3(10), dim3(256), s, true, a2);
else launch_cfg((const void*)tiny<0>, dim3(10), dim3(256), s, false, a2);
}
CK(cudaStreamEndCapture(s, &g));
CK(cudaGraphInstantiate(&ge, g, 0));
double us = time_graph(ge, s, 20);
CK(cudaGraphExecDestroy(ge)); CK(cudaGraphDestroy(g));
return us;
}
// ---- test D: the previous (latency-bound) kernel prefetches the next kernel's weights into L2 ("prefetch ahead", no PDL needed).
// lat: every CTA sleeps `us` microseconds (a stand-in for a latency-bound kernel such as the hyper-connection read) and, when PF, issues
// prefetch.global.L2 for its share of `pf_bytes` at `pf` BEFORE sleeping.
template <int PF>
__global__ void lat(float* x, int us, const char* pf, size_t pf_bytes) {
if (PF) {
const size_t total = (size_t)gridDim.x * blockDim.x;
const size_t lines = pf_bytes / 128;
for (size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x; i < lines; i += total) asm volatile("prefetch.global.L2 [%0];" ::"l"(pf + i * 128));
}
for (int i = 0; i < us; ++i) __nanosleep(1000);
if (threadIdx.x == 0 && blockIdx.x == 0) x[0] += 1.0f;
}
template <int PF>
static double chain_lat_mv(int nm, int rows, int cols, const uint4* W, float* x, float* y, int us, int ctas, cudaStream_t s) {
cudaGraph_t g; cudaGraphExec_t ge;
CK(cudaStreamBeginCapture(s, cudaStreamCaptureModeGlobal));
const int cols8 = cols / 8;
const size_t per = (size_t)rows * cols * 2;
for (int i = 0; i < nm; ++i) {
const uint4* w = W + (size_t)i * rows * cols8;
const char* pf = (const char*)w;
size_t pfb = per;
float* xx = x; int uu = us;
void* a0[] = {&xx, &uu, &pf, &pfb};
launch_cfg((const void*)lat<PF>, dim3(ctas), dim3(256), s, false, a0);
const float* xc = x; int cc = cols8, rr = rows;
void* a1[] = {&w, &xc, &y, &cc, &rr};
launch_cfg((const void*)mv<0>, dim3((rows + 7) / 8), dim3(256), s, false, a1);
}
CK(cudaStreamEndCapture(s, &g));
CK(cudaGraphInstantiate(&ge, g, 0));
double t = time_graph(ge, s, 20);
CK(cudaGraphExecDestroy(ge)); CK(cudaGraphDestroy(g));
return t;
}
int main() {
cudaDeviceProp p; CK(cudaGetDeviceProperties(&p, 0));
printf("# %s sm_%d%d L2 %d MiB\n", p.name, p.major, p.minor, p.l2CacheSize >> 20);
cudaStream_t s; CK(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking));
float* x; CK(cudaMalloc(&x, 1 << 20)); CK(cudaMemset(x, 0, 1 << 20));
const int nk = 2000;
for (int blocks : {1, 10, 40, 160}) {
double a = chain_tiny<0>(nk, blocks, x, blocks * 256, s);
double b = chain_tiny<1>(nk, blocks, x, blocks * 256, s);
double c = chain_tiny<2>(nk, blocks, x, blocks * 256, s);
printf("RESULT tiny_chain blocks=%d plain_us_per_kernel=%.3f pdl_wait_us_per_kernel=%.3f pdl_trigger_wait_us_per_kernel=%.3f\n",
blocks, a / nk, b / nk, c / nk);
}
// weight streaming: matrices cycle through 1.5 GiB so every matrix is cold in L2
struct Shape { const char* name; int rows, cols; } shapes[] = {{"qkv_10240x2560", 10240, 2560}, {"gate_6144x2560", 6144, 2560}, {"out_2560x4096", 2560, 4096}, {"gr_320x10240", 320, 10240}};
for (auto& sh : shapes) {
size_t per = (size_t)sh.rows * sh.cols * 2;
int nm = (int)std::min<size_t>(40, (size_t)(1536ull << 20) / per);
uint4* W; CK(cudaMalloc(&W, per * nm)); CK(cudaMemset(W, 0x3c, per * nm));
float *xa, *ya, *za; CK(cudaMalloc(&xa, 4 * 16384)); CK(cudaMalloc(&ya, 4 * 16384)); CK(cudaMalloc(&za, 4 * 16384));
CK(cudaMemset(xa, 0, 4 * 16384)); CK(cudaMemset(ya, 0, 4 * 16384)); CK(cudaMemset(za, 0, 4 * 16384));
double a = chain_mv<0>(nm, sh.rows, sh.cols, W, xa, ya, za, 2560, s);
double b = chain_mv<3>(nm, sh.rows, sh.cols, W, xa, ya, za, 2560, s);
double c = chain_mv<4>(nm, sh.rows, sh.cols, W, xa, ya, za, 2560, s);
printf("RESULT mv_chain shape=%s mats=%d bytes_per_mat=%zu plain_us_per_pair=%.3f pdl_regpref_us_per_pair=%.3f pdl_l2pref_us_per_pair=%.3f floor_us=%.3f\n",
sh.name, nm, per, a / nm, b / nm, c / nm, per / 1.69e6);
CK(cudaFree(W)); CK(cudaFree(xa)); CK(cudaFree(ya)); CK(cudaFree(za));
}
// test D
for (auto& sh : shapes) {
size_t per = (size_t)sh.rows * sh.cols * 2;
int nm = (int)std::min<size_t>(40, (size_t)(1536ull << 20) / per);
uint4* W; CK(cudaMalloc(&W, per * nm)); CK(cudaMemset(W, 0x3c, per * nm));
float *xa, *ya; CK(cudaMalloc(&xa, 4 * 16384)); CK(cudaMalloc(&ya, 4 * 16384)); CK(cudaMemset(xa, 0, 4 * 16384));
for (int us : {0, 4, 8, 16, 32}) {
for (int ctas : {16, 160}) {
double a = chain_lat_mv<0>(nm, sh.rows, sh.cols, W, xa, ya, us, ctas, s);
double b = chain_lat_mv<1>(nm, sh.rows, sh.cols, W, xa, ya, us, ctas, s);
printf("RESULT prefetch_ahead shape=%s sleep_us=%d ctas=%d plain_us_per_pair=%.3f prefetched_us_per_pair=%.3f saved_us=%.3f\n", sh.name, us, ctas, a / nm, b / nm, (a - b) / nm);
}
}
CK(cudaFree(W)); CK(cudaFree(xa)); CK(cudaFree(ya));
}
return 0;
}
+204
View File
@@ -0,0 +1,204 @@
// Instrumented copy of the Original qsa_native_decode.cu chunk kernel (clock64 stamps per phase of block (5,0,0)); probe-only, never sealed.
// Literal Original qsa_decode_attn.cu fixed INT8 mode1; no prompt arithmetic substitution.
#include <cuda_fp16.h>
#include <cuda_runtime.h>
#include <cfloat>
#include <cstdint>
#include <cmath>
constexpr int KV_Q8_GROUP=64,QK4_0=32,kStepCount=4,kStepWidth=3;
struct block_q4_0{uint16_t d;uint8_t qs[16];};
struct QsaAttnPools{const int8_t*k_q,*v_q;const uint16_t*k_scale,*v_scale;const int32_t*page_table;
const uint16_t*k_pool=nullptr,*v_pool=nullptr;const uint8_t*k_q4=nullptr,*v_q4=nullptr;
int keyless_n_rot=0;const int32_t*keyless_mrope=nullptr;const float*keyless_cos=nullptr,*keyless_sin=nullptr;};
__device__ int mrope_pos(const int32_t*,int,int); // discarded KV_MODE4 branch, never linked or selected
constexpr int HD = 256; // head_dim
constexpr int G = 12; // query heads per KV head (24 / 2)
constexpr int CHUNK = 64; // cells per block
constexpr int THREADS = 256;
constexpr int WARPS = THREADS / 32;
__device__ __forceinline__ float warp_sum(float v) {
#pragma unroll
for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
return v;
}
__device__ __forceinline__ float warp_max(float v) {
#pragma unroll
for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o));
return v;
}
// 8 consecutive values of one cell's key or value row for KV head `kvh`, dimensions [d0, d0+8).
// Per-format bodies; `load8` below is the KV_MODE dispatcher. value=false is the K side, true the V side.
__device__ __forceinline__ void load8_f16(const QsaAttnPools& p, bool value, long long row, int d0, float* out) {
const uint16_t* base = (value ? p.v_pool : p.k_pool) + row * HD + d0;
const uint4 raw = *reinterpret_cast<const uint4*>(base);
const __half2* h2 = reinterpret_cast<const __half2*>(&raw);
#pragma unroll
for (int j = 0; j < 4; ++j) {
const float2 f = __half22float2(h2[j]);
out[2 * j] = f.x;
out[2 * j + 1] = f.y;
}
}
__device__ __forceinline__ void load8_q8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) {
const int8_t* codes = (value ? p.v_q : p.k_q) + row * HD + d0;
const uint16_t sbits = (value ? p.v_scale : p.k_scale)[row * (HD / KV_Q8_GROUP) + d0 / KV_Q8_GROUP];
const float sc = __half2float(__ushort_as_half(sbits));
const uint2 raw = *reinterpret_cast<const uint2*>(codes);
const int8_t* c = reinterpret_cast<const int8_t*>(&raw);
#pragma unroll
for (int j = 0; j < 8; ++j) out[j] = (float) c[j] * sc;
}
__device__ __forceinline__ void load8_q4(const QsaAttnPools& p, bool value, long long row, int d0, float* out) {
constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
const int b = d0 / QK4_0;
const int rem = d0 % QK4_0;
const block_q4_0* blk = reinterpret_cast<const block_q4_0*>((value ? p.v_q4 : p.k_q4) + row * bytes_per_head) + b;
const float d = __half2float(__ushort_as_half(blk->d));
const int j = (rem == 0 || rem == 16) ? 0 : 8;
const uint8_t* bytes = blk->qs + j;
if (rem < 16) {
#pragma unroll
for (int k = 0; k < 8; ++k) out[k] = (float) ((int)(bytes[k] & 0x0F) - 8) * d;
} else {
#pragma unroll
for (int k = 0; k < 8; ++k) out[k] = (float) ((int)(bytes[k] >> 4) - 8) * d;
}
}
template <int KV_MODE>
__device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) {
if constexpr (KV_MODE == 0) load8_f16(p, value, row, d0, out);
else if constexpr (KV_MODE == 1 || KV_MODE == 4) load8_q8(p, value, row, d0, out);
else if constexpr (KV_MODE == 3) {
// hybrid K8V4: both sides are defined - K unrotated INT8, V rotated Q4_0 - so a value=true call
// reads the Q4_0 pool instead of dereferencing the null v_q (no call site does today; PR review)
if (value) load8_q4(p, value, row, d0, out);
else load8_q8(p, value, row, d0, out);
} else load8_q4(p, value, row, d0, out);
}
constexpr int KV_MODE=1;
extern "C" __global__ void __launch_bounds__(THREADS) qsa_chunk_prof(unsigned long long* stamps, const float* __restrict__ q,const int8_t*kq,const int8_t*vq,const uint16_t*ks,const uint16_t*vs,const int32_t*table,
const int32_t* __restrict__ ids,
const int32_t* __restrict__ step, int n_kv_heads,
int page_size, float scale, float* __restrict__ part_acc,
float* __restrict__ part_m, float* __restrict__ part_l,
int n_chunks, int cap = 0, long long scratch_stride = 0) {
const long long c_start = clock64();
const QsaAttnPools p{kq,vq,ks,vs,table};
// batched form: query blockIdx.z, with its own q row, selection, step and scratch
q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD;
ids += (size_t) blockIdx.z * (size_t) cap;
step += (size_t) blockIdx.z * kStepCount;
part_acc += (size_t) blockIdx.z * (size_t) scratch_stride;
part_m += (size_t) blockIdx.z * (size_t) scratch_stride;
part_l += (size_t) blockIdx.z * (size_t) scratch_stride;
__shared__ __align__(16) float sq[G][HD]; // 12 KB: this KV head's query heads
__shared__ float sp[G][CHUNK]; // scores, then probabilities
__shared__ long long srow[CHUNK]; // pool row of each cell (page, kv head, slot)
const int n_ids = __ldg(step + kStepWidth);
const int chunk = blockIdx.x, kvh = blockIdx.y;
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const int c0 = chunk * CHUNK;
const int n_here = min(CHUNK, n_ids - c0);
const int slot = kvh * n_chunks + chunk;
if (n_here <= 0) {
if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; }
return;
}
for (int i = t; i < G * HD; i += THREADS) sq[i / HD][i % HD] = q[(size_t) (kvh * G) * HD + i];
if (t < CHUNK) {
long long r = -1;
if (t < n_here) {
const int cell = ids[c0 + t];
const long long page = (long long) p.page_table[cell / page_size];
// a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked
// (score -FLT_MAX, weight 0) instead of being read from before the pool.
if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
}
srow[t] = r;
}
__syncthreads();
const long long c1 = clock64();
// scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions.
for (int c = warp; c < CHUNK; c += WARPS) {
if (c >= n_here || srow[c] < 0) {
if (lane < G) sp[lane][c] = -FLT_MAX;
continue;
}
float k8[8];
load8<KV_MODE>(p, KV_MODE == 4, srow[c], lane * 8, k8);
if constexpr (KV_MODE == 4) {
const int d0 = lane * 8, half = p.keyless_n_rot / 2;
if (d0 < p.keyless_n_rot) {
float paired[8];
load8_q8(p, true, srow[c], d0 < half ? d0 + half : d0 - half, paired);
const int cell = ids[c0 + c];
for (int d = 0; d < 8; ++d) {
const int pair = (d0 + d) % half;
const int rotary_pos = mrope_pos(p.keyless_mrope, cell, pair);
const float co = p.keyless_cos[(size_t)rotary_pos * half + pair];
const float si = p.keyless_sin[(size_t)rotary_pos * half + pair];
k8[d] = d0 < half ? k8[d]*co - paired[d]*si : k8[d]*co + paired[d]*si;
}
}
}
#pragma unroll
for (int h = 0; h < G; ++h) {
const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);
const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + 4]);
float s = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w +
k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w;
s = warp_sum(s);
if (lane == 0) sp[h][c] = s * scale;
}
}
__syncthreads();
const long long c2 = clock64();
// per-head chunk max and exp-sum: warp w handles heads w and w+8.
for (int h = warp; h < G; h += WARPS) {
const float a = sp[h][lane], b = sp[h][lane + 32];
const float m = warp_max(fmaxf(a, b));
const float ea = (lane < n_here && srow[lane] >= 0) ? __expf(a - m) : 0.0f;
const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? __expf(b - m) : 0.0f;
sp[h][lane] = ea;
sp[h][lane + 32] = eb;
const float l = warp_sum(ea + eb);
if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; }
}
__syncthreads();
const long long c3 = clock64();
// values: thread t owns dimension t for all 12 heads.
float acc[G];
#pragma unroll
for (int h = 0; h < G; ++h) acc[h] = 0.0f;
for (int c = 0; c < n_here; ++c) {
if (srow[c] < 0) continue; // masked above, weight 0
float v;
if constexpr (KV_MODE == 0) {
v = __half2float(__ushort_as_half(p.v_pool[srow[c] * HD + t]));
} else if constexpr (KV_MODE == 1 || KV_MODE == 4) {
const float sc = __half2float(__ushort_as_half(p.v_scale[srow[c] * (HD / KV_Q8_GROUP) + t / KV_Q8_GROUP]));
v = (float) p.v_q[srow[c] * HD + t] * sc;
} else { // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
const int b = t / QK4_0;
const int rem = t % QK4_0;
const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + srow[c] * bytes_per_head) + b;
const float d = __half2float(__ushort_as_half(blk->d));
const int j = rem < 16 ? rem : (rem - 16);
const uint8_t byte = blk->qs[j];
const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
v = (float) nibble * d;
}
#pragma unroll
for (int h = 0; h < G; ++h) acc[h] = fmaf(sp[h][c], v, acc[h]);
}
#pragma unroll
for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
if (blockIdx.x == 5 && blockIdx.y == 0 && blockIdx.z == 0 && threadIdx.x == 0) {
const long long c4 = clock64();
stamps[0] = (unsigned long long)(c1 - c_start); stamps[1] = (unsigned long long)(c2 - c1); stamps[2] = (unsigned long long)(c3 - c2); stamps[3] = (unsigned long long)(c4 - c3);
}
}
+131
View File
@@ -0,0 +1,131 @@
#!/usr/bin/env python3
"""Per-kernel table of one decode verify window (port vs Original) from two CUPTI traces (tools/cupti-trace, scripts/profile/lct.py of
claude/ledger). Windows are the big graphs (>= 1000 kernels); `--rows R` keeps the windows of R rows (grid.y of the embedding gather).
python3 tools/chain-probe/window_table.py --lct PATH_TO_scripts_profile PORT.lct ORIG.lct [--rows 4] [--md]
Prints, per canonical kernel role: kernels per window, GPU microseconds per window and the share of the chain (everything that is not a host
or PCIe wait) for both engines, plus the idle gap between kernels inside the graph. Kernel names are mapped to the Original's names so the
rows line up (port: window_moe_gu_*, head_n*, mtp_scalar_gr_*, verify_*, ...).
"""
import argparse
import collections
import re
import sys
NAME_MAP = [
(r"^mtp_scalar_gr_split$|^gr_norm_split$|^chain_gr_split$", "GR norm (gr_norm_split)"),
(r"^mtp_scalar_gr_staged$|^gr_down_staged$|^chain_gr_down", "GR down (gr_down_staged)"),
(r"^mtp_scalar_gr_up$|^gr_up_multi$|^chain_gr_up", "GR up (gr_up_multi)"),
(r"^window_moe_gu|^native_gu_multi$", "routed experts gate/up"),
(r"^window_moe_down|^native_down_multi$", "routed experts down"),
(r"^swiglu_entries$|^chain_swiglu_quant", "experts swiglu (+quantize when fused)"),
(r"^verify_copy_rows_from_mapped$|^copy_rows_from_mapped$|^chain_copy_rows", "CPU-leg rows copy (copy_rows_from_mapped)"),
(r"^verify_copy_i32_from_mapped$|^copy_i32_from_mapped$|^chain_copy_i32|^chain_wait_copy", "plan copy (copy_i32_from_mapped)"),
(r"^verify_doorbell_publish$|^doorbell_publish$|^chain_doorbell", "doorbell publish"),
(r"^verify_gdn_ab_multi$|^gdn_ab_multi$|^chain_gdn_ab", "GDN alpha/beta"),
(r"^verify_gdn_step_norm_multi$|^gdn_step_norm_multi$", "GDN recurrence + out norm"),
(r"^verify_gdn_conv_l2_multi$|^gdn_conv_l2_multi$", "GDN conv + L2"),
(r"^leleka_qsa_decode_chunk$|^attn_chunk$|^chain_qsa_decode_chunk$", "QSA decode attention chunk"),
(r"^leleka_qsa_decode_merge$|^attn_merge$", "QSA decode attention merge"),
(r"^sampler_greedy|^chain_sampler", "greedy argmax"),
(r"^mtp_full_route$|^route$", "router top-10"),
(r"^mtp_full_combine$|^combine$", "MoE combine"),
(r"^add_hits$", "add_hits"),
(r"^head_quant$|^native_quantize_q8_1$", "activation quantize (q8_1, projections)"),
(r"^quantize_q8_1$", "quantize_q8_1 (experts / shared)"),
(r"^mtp_full_mmvf|^bf16_f32_mmvf", "bf16 mmvf (router logits, shared gate, head mix)"),
(r"^to_bf16$|^mtp_full_to_bf16$", "to_bf16 (dead with native shared gate)"),
(r"^native_swiglu$|^mtp_full_native_swiglu$", "shared swiglu"),
(r"^native_scalar_sigmoid|^mtp_full_native_scalar_sigmoid|^scale_rows$|^mtp_full_scale$|^chain_scale_rows", "shared sigmoid / scale_rows"),
(r"^wait_flag_ge$|^verify_wait_flag_ge$", "WAIT host/PCIe flags"),
(r"^fetch_blobs$", "WAIT PCIe copy kernel (Original)"),
(r"^rebase_ptrs$", "rebase_ptrs (Original)"),
]
PROJ = re.compile(r"^head_n\d+_|^native_.*mmvq|^native_mmvq_multi|^native_small_mmvq")
def role(fam, grid):
for rx, name in NAME_MAP:
if re.search(rx, fam):
return name
if PROJ.search(fam):
if grid >= 200000:
return "lm head projection (248,320 rows)"
if grid >= 2000:
return "dense projections (GDN qkv/z/out, QSA q/out)"
return "small projections (QSA k/v, shared expert)"
return "other: " + fam
def windows(trace, want_rows, L):
byc = collections.defaultdict(list)
for k in trace.kernels:
byc[k.corr].append(k)
out = []
for c, ks in byc.items():
if len(ks) < 1000:
continue
ks.sort(key=lambda k: k.start)
emb = [k for k in ks[:20] if "embed_rows" in trace.kname(k)]
rows = emb[0].gy if emb else -1
if rows == want_rows:
out.append(ks)
return out
def table(trace, want_rows, L):
ws = windows(trace, want_rows, L)
agg = collections.defaultdict(lambda: [0, 0])
span = ksum = 0
for ks in ws:
span += ks[-1].end - ks[0].start
for k in ks:
r = role(L.family(trace.kname(k)), k.gx * k.gy * k.gz)
agg[r][0] += 1
agg[r][1] += k.end - k.start
ksum += k.end - k.start
n = max(1, len(ws))
return n, {r: (v[0] / n, v[1] / n / 1e3) for r, v in agg.items()}, span / n / 1e3, ksum / n / 1e3
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--lct", required=True, help="scripts/profile directory of claude/ledger (lct.py)")
ap.add_argument("port")
ap.add_argument("orig")
ap.add_argument("--rows", type=int, default=4)
ap.add_argument("--md", action="store_true")
a = ap.parse_args()
sys.path.insert(0, a.lct)
import lct as L
tp = L.Trace(a.port)
to = L.Trace(a.orig)
np_, P, spanp, ksp = table(tp, a.rows, L)
no, O, spano, kso = table(to, a.rows, L)
waits = [r for r in set(P) | set(O) if r.startswith("WAIT")]
chain_p = sum(v[1] for r, v in P.items() if r not in waits)
chain_o = sum(v[1] for r, v in O.items() if r not in waits)
print("rows=%d: %d port windows, %d Original windows" % (a.rows, np_, no))
print("window GPU span: port %.0f us, Original %.0f us; kernel sum %.0f / %.0f us" % (spanp, spano, ksp, kso))
print("chain (kernels that are not host/PCIe waits): port %.0f us, Original %.0f us" % (chain_p, chain_o))
print("idle gaps inside the graph (span - kernel sum): port %.0f us, Original %.0f us" % (spanp - ksp, spano - kso))
sep = "|" if a.md else " "
rows = sorted(set(P) | set(O), key=lambda r: -(P.get(r, (0, 0))[1] + O.get(r, (0, 0))[1]))
if a.md:
print("\n| role | port n | port us | port % | Original n | Original us | Original % | port - Original us |")
print("| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |")
for r in rows:
pn, pu = P.get(r, (0, 0))
on, ou = O.get(r, (0, 0))
ps = 100 * pu / chain_p if r not in waits else 0
os_ = 100 * ou / chain_o if r not in waits else 0
if a.md:
print("| %s | %.1f | %.0f | %.1f | %.1f | %.0f | %.1f | %+.0f |" % (r, pn, pu, ps, on, ou, os_, pu - ou))
else:
print("%-52s port %6.1f x %8.0f us %5.1f%% | orig %6.1f x %8.0f us %5.1f%% | %+7.0f" % (r, pn, pu, ps, on, ou, os_, pu - ou))
if __name__ == "__main__":
main()