chain: hyper-connection down projection tiled over rows and tokens (8 rows x 2 tokens per block): 16.6 -> 9.7 us at 4 rows, bit-identical; probe diagnostics; sealed chain_window.ptx

This commit is contained in:
Pavlo Ratushnyi
2026-10-25 13:34:33 +01:00
parent acc228e427
commit c9ccd81856
10 changed files with 6244 additions and 1552 deletions
+52 -65
View File
@@ -598,101 +598,88 @@ CHAIN_GR_DOWN(4, 3)
CHAIN_GR_DOWN(8, 2) CHAIN_GR_DOWN(8, 3) CHAIN_GR_DOWN(8, 4)
// ------------------------------------------------------------------------------------------------------------------
// hyper-connection DOWN projection with R rows per warp (R x W rows per block): the activation tile of a block is read from
// shared memory once per warp for R rows instead of once per row, and the weights are streamed tile by tile through registers
// (the next tile's R x 5 uint4 are loaded while the current tile is multiplied) instead of being held whole. Per row and token
// the arithmetic is the one above: lane l accumulates chunks h * 160 + l + 32 q ascending with dot8 (starting from 0.0f), then
// the xor warp reduction, so every output is bit-identical.
// hyper-connection DOWN projection tiled over rows AND tokens: a block handles W rows (one per warp) and TPB tokens (grid.y = ceil(T / TPB)),
// so the 324 rows x T tokens spread over every SM instead of 41 (the per-block cost is the instruction stream of 8 rows x all tokens plus
// the staging of every token's activations). Per (row, token) the arithmetic is the one above (bit-identical).
// ------------------------------------------------------------------------------------------------------------------
namespace {
template <int R, int W, int NB>
__device__ __forceinline__ void gr_down_rr_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 row0 = (blockIdx.x * W + warp) * R;
const uint4* w4[R];
bool act[R];
#pragma unroll
for (int r = 0; r < R; ++r) {
const int row = row0 + r;
const bool inject = row >= LR;
act[r] = 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) (act[r] ? (inject ? row - LR : row) : 0) * D;
w4[r] = reinterpret_cast<const uint4*>(wrow);
template <int W>
__device__ __forceinline__ void stage_tile_tp(const GrMulti& m, int k0, int Tn, int h, float4* buf, int t) {
for (int i = t; i < Tn * (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) (k0 + 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);
}
const size_t buf_f4 = (size_t) T * (H_TILE / 4);
float acc[R][kFusedGrMaxT];
}
template <int W, int NB, int TPB>
__device__ __forceinline__ void gr_down_tp_body(const GrMulti& m) {
extern __shared__ __align__(16) float4 hbuf[]; // NB x [Tn][2][160] float4
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const int k0 = blockIdx.y * TPB;
const int Tn = min(TPB, m.T - k0);
const int row = blockIdx.x * W + warp;
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) Tn * (H_TILE / 4);
float acc[TPB];
#pragma unroll
for (int r = 0; r < R; ++r)
for (int k = 0; k < TPB; ++k) acc[k] = 0.0f;
uint4 wv[N_HTILES][HQ];
if (active) {
#pragma unroll
for (int k = 0; k < kFusedGrMaxT; ++k) acc[r][k] = 0.0f;
uint4 wc[R][HQ], wn[R][HQ];
for (int h = 0; h < N_HTILES; ++h)
#pragma unroll
for (int r = 0; r < R; ++r)
#pragma unroll
for (int q = 0; q < HQ; ++q) wc[r][q] = __ldg(w4[r] + lane + 32 * q);
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);
stage_tile_tp<W>(m, k0, Tn, b, hbuf + b * buf_f4, t);
cp_async_commit();
}
#pragma unroll
for (int h = 0; h < N_HTILES; ++h) {
if (h + 1 < N_HTILES) {
#pragma unroll
for (int r = 0; r < R; ++r)
#pragma unroll
for (int q = 0; q < HQ; ++q) wn[r][q] = __ldg(w4[r] + (h + 1) * (H_TILE / 8) + lane + 32 * q);
}
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;
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);
const float4 x0 = pk[j], x1 = pk[H_TILE / 8 + j];
#pragma unroll
for (int r = 0; r < R; ++r) acc[r][k] += dot8v(wc[r][q], x0, x1);
for (int k = 0; k < TPB; ++k) {
if (k < Tn) {
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);
if (h + NB - 1 < N_HTILES) stage_tile_tp<W>(m, k0, Tn, h + NB - 1, hbuf + ((h + NB - 1) % NB) * buf_f4, t);
cp_async_commit();
if (h + 1 < N_HTILES) {
#pragma unroll
for (int r = 0; r < R; ++r)
#pragma unroll
for (int q = 0; q < HQ; ++q) wc[r][q] = wn[r][q];
}
}
if (!active) return;
float s[TPB];
#pragma unroll
for (int r = 0; r < R; ++r) {
if (!act[r]) continue;
const int row = row0 + r;
const bool inject = row >= LR;
for (int k = 0; k < TPB; ++k) s[k] = k < Tn ? warp_sum(acc[k]) : 0.0f;
#pragma unroll
for (int k = 0; k < kFusedGrMaxT; ++k) {
const float s = k < T ? warp_sum(acc[r][k]) : 0.0f;
if (k >= T || lane != k) continue;
if (inject) {
m.a[k].inject_out[row - LR] = s;
} else {
const float x = s / (float) HC;
m.a[k].lo[row] = x / (1.0f + __expf(-x));
}
for (int k = 0; k < TPB; ++k) {
if (k >= Tn || lane != k) continue;
if (inject) {
m.a[k0 + k].inject_out[row - LR] = s[k];
} else {
const float x = s[k] / (float) HC;
m.a[k0 + k].lo[row] = x / (1.0f + __expf(-x));
}
}
}
} // namespace
#define CHAIN_GR_DOWN_RR(R, W, NB) extern "C" __global__ void __launch_bounds__((W) * 32) chain_gr_down_r##R##w##W##_nb##NB(GrMulti m) { gr_down_rr_body<R, W, NB>(m); }
CHAIN_GR_DOWN_RR(2, 4, 3) CHAIN_GR_DOWN_RR(2, 2, 3) CHAIN_GR_DOWN_RR(4, 2, 3) CHAIN_GR_DOWN_RR(4, 1, 3) CHAIN_GR_DOWN_RR(4, 2, 2) CHAIN_GR_DOWN_RR(2, 4, 2)
extern "C" __global__ void __launch_bounds__(256) chain_gr_down_t2w8_nb4(GrMulti m) { gr_down_tp_body<8, 4, 2>(m); }
// ------------------------------------------------------------------------------------------------------------------
// small fusions (group `tiny`)
File diff suppressed because it is too large Load Diff
@@ -26,6 +26,7 @@ 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_GR_DOWN_T2W8: &str = "chain_gr_down_t2w8_nb4";
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";
@@ -37,8 +38,8 @@ pub(crate) const E_QSA_MERGE_N: &str = "chain_qsa_decode_merge_n";
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],
sha: [98, 66, 53, 57, 75, 116, 84, 181, 100, 146, 39, 173, 15, 112, 76, 250, 17, 11, 0, 115, 118, 181, 227, 180, 208, 172, 34, 90, 225, 142, 74, 135],
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_GR_DOWN_T2W8, 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)",
};
@@ -113,6 +114,14 @@ pub(crate) fn up8() -> bool {
*ON.get_or_init(|| std::env::var("LELEKA_CHAIN_UP8").map_or(true, |v| v != "0"))
}
/// The hyper-connection down projection tiled over rows AND tokens (8 rows x 2 tokens per block, `ceil(T / 2)` x 41 blocks, four tile buffers of
/// two tokens): 9.7 / 11.3 / 15.0 us at 4 / 6 / 8 rows against 16.6 / 19.7 / 29.9 us for the 8-row x all-tokens shape (job p33); same arithmetic
/// per (row, token), so bit-identical. `LELEKA_CHAIN_DOWN=w8` selects the previous shape (the A arm of the paired A/B).
pub(crate) fn down_tiled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("LELEKA_CHAIN_DOWN").map_or(true, |v| v != "w8"))
}
/// 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() }
@@ -130,7 +139,7 @@ mod tests {
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);
assert_eq!(CHAIN.entries.len(), 17);
}
#[test]
@@ -509,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 && super::chain::down_tiled() {
// same arithmetic as the staged kernel; blocks of 8 rows x 2 tokens (grid.y = ceil(ct / 2)) spread the work over the SMs, the whole weight row
// in registers, four tile buffers of two tokens in flight
let shared = 4 * ct.min(2) as u32 * (STAGED_TILE * 4);
if shared > cfg.usable_shared {
return Err(Error::InvalidProjectionShape);
}
down.push(Launch::new(
&super::chain::CHAIN,
super::chain::E_GR_DOWN_T2W8,
[DOWN_BLOCKS, ct.div_ceil(2) as u32, 1],
[THREADS, 1, 1],
shared,
vec![A::Words(chunk_words(&full, n, c0, ct))],
)?);
c0 += ct;
continue;
}
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) };
@@ -522,7 +522,7 @@ mod tests {
// 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_eq!(on.iter().filter(|s| s.starts_with("chain_gr_down_t2w8_nb") || 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);
+12
View File
@@ -0,0 +1,12 @@
# claude/perf3 task 2: bit identity of the prompt loan ladder. The first 24 requests of the live CRM session 9e3 (teacher forced), chunk 8192 / grid 8192, on a stack whose chunks all borrow the full loan
# (N = !notiers) and on one with the ladder (T): LELEKA_TRACE_PREFILL_R=1 prints the FNV-1a hash of every row of every chunk's final residual R (compare the two PREFILL-R sequences in
# ~/work/leleka-ttft-runs/loan-tiers-id.full; the hash trace slows every chunk, the timings of this job are not comparable).
export BIN=$HOME/work/leleka-perf3/bin/rt-a4
export LELEKA_BRINGUP_TRACE=1
source ~/work/ttft-jobs/ttft-common.sh
export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto
run_ttft loan-tiers-id original_serve_replay::original_serve_replay_smoke LELEKA_REPLAY_DIR=$CAP/9e3-crm-tail-reply LELEKA_REPLAY_COUNT=24 LELEKA_REPLAY_PREFIX_MIB=20000 \
LELEKA_PREFIX_TRACE=1 LELEKA_TRACE_PREFILL_R=1 LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 LELEKA_ORIGINAL_SERVE_SEED=off \
LELEKA_REPLAY_ARMS=N=reply@8192!notiers,T=reply@8192 LELEKA_REPLAY_FORCE=1
grep -E "PREFILL-R|REPLAY-ARM" $HOME/work/leleka-ttft-runs/loan-tiers-id.full | cut -c1-160
date -u +%FT%TZ
+10
View File
@@ -0,0 +1,10 @@
# claude/perf3 task 2: the prompt loan ladder against the full-capacity loan, same chunk 8192 / grid 8192, the live CRM session 9e3 (first 30 requests, teacher forced), arms T N N T inside one
# process (T = ladder, N = `!notiers`: every chunk borrows the full 1.9 GB loan and refills it). Tier = the live one (auto-sized per-layer cache, adaptation and seed at their defaults).
export BIN=$HOME/work/leleka-perf3/bin/rt-a4
export LELEKA_BRINGUP_TRACE=1
source ~/work/ttft-jobs/ttft-common.sh
export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto
run_ttft loan-tiers-ab original_serve_replay::original_serve_replay_smoke LELEKA_REPLAY_DIR=$CAP/9e3-crm-tail-reply LELEKA_REPLAY_COUNT=${COUNT:-30} LELEKA_REPLAY_PREFIX_MIB=20000 \
LELEKA_PREFIX_TRACE=1 \
LELEKA_REPLAY_ARMS=T1=reply@8192,N1=reply@8192!notiers,N2=reply@8192!notiers,T2=reply@8192 LELEKA_REPLAY_FORCE=1
date -u +%FT%TZ
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python3
"""Sum of the serve-profile spans (`DBG profile request: name=ms/count ...`) per replay arm.
usage: parse_spans.py FULL_LOG [span ...] (FULL_LOG: the raw output of a replay job, ~/work/leleka-ttft-runs/<label>.full)
Arms are split by `REPLAY-ARM start label=` lines; every `DBG profile request:` line belongs to one request. Prints, per arm, the total ms and the
call count of each span over all requests (default: the spans that differ between prefill shapes and the decode-phase totals).
"""
import re
import sys
log = sys.argv[1]
wanted = sys.argv[2:] or [
"prefill.read", "prefill.refill", "refill.queue", "refill.sync", "prefill.seed", "prefix.export_kv", "prefix.export_index", "prefix.park_tail",
"prefix.after_prefill", "prefix.park_state", "prefix.import_session", "decode.assemble", "decode.seed_ple", "round.run_window", "round.verify_commit",
"round.apply_pending", "window.ple", "pool.cpu", "round.adapt", "commit.wait", "window.verifier", "round.T", "round.acc",
]
arms = []
cur = None
for line in open(log, errors="replace"):
m = re.search(r"REPLAY-ARM start label=(\S+)", line)
if m:
cur = {"label": m[1], "n": 0, "ms": {}, "cnt": {}}
arms.append(cur)
continue
if cur is None or "DBG profile request:" not in line:
continue
cur["n"] += 1
for name, ms, cnt in re.findall(r"([\w.]+)=([\d.]+)/(\d+)", line.split("DBG profile request:", 1)[1]):
cur["ms"][name] = cur["ms"].get(name, 0.0) + float(ms)
cur["cnt"][name] = cur["cnt"].get(name, 0) + int(cnt)
print(f"{'span':<26}" + "".join(f"{a['label']:>22}" for a in arms))
print(f"{'requests':<26}" + "".join(f"{a['n']:>22}" for a in arms))
for w in wanted:
print(f"{w:<26}" + "".join(f"{a['ms'].get(w, 0.0):>13.0f} ms /{a['cnt'].get(w, 0):>6}" for a in arms))
+40 -8
View File
@@ -278,15 +278,17 @@ static void test_gr() {
}
// ---- the new down projection shapes: exactness against the Original's staged kernel, then timing
struct DV { const char* name; int W, NB, R; CUfunction f; };
std::vector<DV> dvs = {{"w4_nb3", 4, 3, 1, 0}, {"w8_nb2", 8, 2, 1, 0}, {"w8_nb3", 8, 3, 1, 0}, {"w8_nb4", 8, 4, 1, 0},
{"r2w4_nb3", 4, 3, 2, 0}, {"r2w2_nb3", 2, 3, 2, 0}, {"r4w2_nb3", 2, 3, 4, 0}, {"r4w1_nb3", 1, 3, 4, 0}, {"r4w2_nb2", 2, 2, 4, 0}, {"r2w4_nb2", 4, 2, 2, 0}};
struct DV { const char* name; int W, NB, R; CUfunction f; int TP = 0; };
std::vector<DV> dvs = {{"w8_nb3", 8, 3, 1, 0},
{"t2w8_nb3", 8, 3, 1, 0, 2}, {"t2w8_nb4", 8, 4, 1, 0, 2}, {"t2w8_nb5", 8, 5, 1, 0, 2}, {"t2w8_nb6", 8, 6, 1, 0, 2},
{"t3w8_nb4", 8, 4, 1, 0, 3}, {"t3w8_nb5", 8, 5, 1, 0, 3}, {"t4w8_nb4", 8, 4, 1, 0, 4}};
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); };
auto dshared = [](int T, int NB, int TP = 0) { return (unsigned)(NB * (TP ? std::min(TP, T) : T) * 5120); };
auto dgy = [](int T, int TP) { return (unsigned)(TP ? (T + TP - 1) / TP : 1); };
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);
@@ -297,11 +299,11 @@ static void test_gr() {
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;
if (dshared(T, v.NB, v.TP) > 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 * v.R - 1) / (v.W * v.R), 1, v.W * 32, dshared(T, v.NB), pd);
launch(v.f, (324 + v.W * v.R - 1) / (v.W * v.R), dgy(T, v.TP), v.W * 32, dshared(T, v.NB, v.TP), 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);
@@ -318,8 +320,8 @@ static void test_gr() {
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 * v.R - 1) / (v.W * v.R), 1, v.W * 32, dshared(T, v.NB), p); }, 96);
if (dshared(T, v.NB, v.TP) > 99 * 1024) continue;
double t = time_graph([&](int i) { void* p[] = {ws[i % NS].data()}; launch(v.f, (324 + v.W * v.R - 1) / (v.W * v.R), dgy(T, v.TP), v.W * 32, dshared(T, v.NB, v.TP), p); }, 96);
printf("RESULT gr_down_time T=%d %s us=%.3f\n", T, v.name, t);
}
}
@@ -577,6 +579,35 @@ static void test_grprof(const std::string& dir) {
}
}
static void test_grdiag(const std::string& dir) {
CUmodule m = load_module(dir + "/gr_prof.ptx");
const int NS = 12;
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 : {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);
const char* names[] = {"m0_full", "m1_no_weight_loads", "m2_no_activations", "m3_neither"};
for (int d = 0; d < 4; ++d) {
char nm[32]; snprintf(nm, sizeof nm, "gr_diag_m%d", d);
CUfunction f = get_fn(m, nm);
CU(cuFuncSetAttribute(f, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, 99 * 1024));
double t = time_graph([&](int i) { void* p[] = {ws[i % NS].data()}; launch(f, 41, 1, 256, 3 * T * 5120, p); }, 96);
printf("RESULT gr_diag T=%d %s us=%.3f\n", T, names[d], t);
}
}
}
int main(int argc, char** argv) {
if (argc < 2) { fprintf(stderr, "usage: chain_probe PTXDIR [tests...]\n"); return 2; }
std::string dir = argv[1];
@@ -607,6 +638,7 @@ int main(int argc, char** argv) {
else if (t == "sampler") test_sampler();
else if (t == "qsaprof") test_qsaprof(dir);
else if (t == "grprof") test_grprof(dir);
else if (t == "grdiag") test_grdiag(dir);
else fprintf(stderr, "unknown test %s\n", t.c_str());
}
printf("RESULT summary failures=%d\n", g_fail);
+76
View File
@@ -164,7 +164,83 @@ __device__ __forceinline__ void gr_down_body(const GrMulti& m, unsigned long lon
}
}
}
// ---- diagnostics: the same kernel with the weight loads (MODE & 1) and/or the activation staging + shared reads (MODE & 2) removed
template <int W, int NB, int MODE>
__device__ __forceinline__ void gr_down_diag(const GrMulti& m) {
extern __shared__ __align__(16) float4 hbuf[];
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const int T = m.T;
const int row = blockIdx.x * W + warp;
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) {
if (MODE & 1) wv[h][q] = make_uint4(0x3f803f80u + h, 0x3f803f80u + q, 0x3f803f80u + lane, 0x3f803f80u);
else wv[h][q] = __ldg(w4 + h * (H_TILE / 8) + lane + 32 * q);
}
}
if (!(MODE & 2)) {
#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) {
if (!(MODE & 2)) {
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) {
float4 x0, x1;
if (MODE & 2) { x0 = make_float4(1.0f + j, 2.0f + k, 3.0f, 4.0f + h); x1 = make_float4(0.5f, 0.25f + j, 0.125f, 1.5f + k); }
else { const float4* pk = cur + (size_t) k * (H_TILE / 4); x0 = pk[j]; x1 = pk[H_TILE / 8 + j]; }
acc[k] += dot8v(wv[h][q], x0, x1);
}
}
}
}
if (!(MODE & 2)) {
__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
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); }
extern "C" __global__ void __launch_bounds__(256) gr_diag_m0(GrMulti m) { gr_down_diag<8, 3, 0>(m); }
extern "C" __global__ void __launch_bounds__(256) gr_diag_m1(GrMulti m) { gr_down_diag<8, 3, 1>(m); }
extern "C" __global__ void __launch_bounds__(256) gr_diag_m2(GrMulti m) { gr_down_diag<8, 3, 2>(m); }
extern "C" __global__ void __launch_bounds__(256) gr_diag_m3(GrMulti m) { gr_down_diag<8, 3, 3>(m); }