chain: 'all' leaves qsa out; MTP keeps the Original chunk kernel

This commit is contained in:
Pavlo Ratushnyi
2026-10-24 03:07:58 +02:00
parent 548b2083e6
commit c73379efd7
7 changed files with 211 additions and 9 deletions
@@ -1013,10 +1013,11 @@ impl OriginalMtpFullForward<'_> {
// 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,
if chain_mtp { symbols::CHAIN_ASSET } else { 19 },
if chain_mtp { symbols::CHAIN_QSA_CHUNK } else { 0 },
19,
0,
[CHUNKS as u32, 2, 1],
[256, 1, 1],
0,
@@ -4,7 +4,7 @@
//! 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; a comma list (`glue,ab,gr,qsa`) selects some;
//! * `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.
@@ -70,7 +70,12 @@ impl ChainFlags {
glue: one("glue", "LELEKA_CHAIN_GLUE"),
ab: one("ab", "LELEKA_CHAIN_AB"),
gr: one("gr", "LELEKA_CHAIN_GR"),
qsa: one("qsa", "LELEKA_CHAIN_QSA"),
// `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"),
@@ -133,7 +138,7 @@ mod tests {
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: true, tiny: true, head: true, mtp: true });
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 });
}
@@ -141,7 +146,7 @@ mod tests {
#[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: true, tiny: true, head: true, mtp: true });
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 });
}
+1
View File
@@ -20,5 +20,6 @@ for f in original_verify mtp_original_full_fused_gr mtp_original_full_attention
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"
+26 -1
View File
@@ -552,12 +552,36 @@ static void test_qsaprof(const std::string& dir) {
}
}
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"};
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);
@@ -581,6 +605,7 @@ int main(int argc, char** argv) {
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);
+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); }
+1 -1
View File
@@ -3,7 +3,7 @@
# 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-t2}
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"
+1 -1
View File
@@ -1,7 +1,7 @@
# 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-t2}
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