Merge claude/speed-vs-strata-08143a: PcieAuto (off), tail fusion HEAD_CHAIN_BATCH (off), D1/D2 default on, hit-share-gap analysis
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -2789,6 +2789,13 @@
|
||||
"problems": [
|
||||
"not built for sm_86 by design (claude/u5a-gr-down-fused): LELEKA_SM120_GR_DOWN_FUSED is a compute capability 12.0 decode switch; original_verify_window_sm120.rs enables it only on a 12.x card, so an sm_86 build never loads this module"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "sm120_head_chain.ptx",
|
||||
"sm120_path": "crates/cuda-driver/src/sm120_head_chain.ptx",
|
||||
"problems": [
|
||||
"not built for sm_86 by design (claude/tail-fusion): LELEKA_SM120_HEAD_CHAIN_BATCH is an opt-in compute capability 12.0 decode switch; original_verify_window_sm120.rs enables it only on a 12.x card, so an sm_86 build never loads this module"
|
||||
]
|
||||
}
|
||||
],
|
||||
"portable_no_companion_needed": [
|
||||
|
||||
@@ -166,6 +166,9 @@ pub(crate) struct GrConfig {
|
||||
/// `LELEKA_SM120_GR_DOWN_FUSED`, resolved by `fused_down::resolve` (off in `from_device`): the split and the tiled
|
||||
/// chain down kernel of the staged read as one launch.
|
||||
pub down_fused: bool,
|
||||
/// `LELEKA_SM120_HEAD_CHAIN_BATCH`, resolved by `head_chain::resolve` (off in `from_device`): the residual write
|
||||
/// and the head mix of all window rows in a handful of launches instead of `6 T`.
|
||||
pub head_chain_batch: bool,
|
||||
}
|
||||
|
||||
/// What every gated-residual (GR) planner reads: the arena the spans come from, the window geometry and the
|
||||
@@ -349,6 +352,8 @@ pub(crate) use assets::shared_attributes;
|
||||
pub(crate) use assets::tiled_down_geometry;
|
||||
#[path = "original_verify_window_gr/fused_down.rs"]
|
||||
pub(crate) mod fused_down;
|
||||
#[path = "original_verify_window_gr/head_chain.rs"]
|
||||
pub(crate) mod head_chain;
|
||||
#[path = "original_verify_window_gr/plan_hc_read.rs"]
|
||||
mod plan_hc_read;
|
||||
pub(crate) use fused_down::plan_hc_read_launches;
|
||||
|
||||
@@ -51,6 +51,7 @@ impl GrConfig {
|
||||
attr_down: (cc_major >= 7 && optin > 0).then_some(want),
|
||||
attr_staged: (cc_major >= 7 && optin > 0).then_some(want_staged),
|
||||
down_fused: false,
|
||||
head_chain_batch: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
//! `LELEKA_SM120_HEAD_CHAIN_BATCH` (design note `docs/experiments/verify-tail-and-gaps.md`): the graph tail after the
|
||||
//! last layer, for all window rows at once. The literal tail launches, per row `t`, the residual write of the last
|
||||
//! layer (`mtp_full_native_write`) and the five kernels of `lm_head_mix` (norm, down gemv, down-silu, up gemv,
|
||||
//! pre-final): `6 T` dependent launches, each a latency-bound kernel of a few microseconds. With the switch:
|
||||
//!
|
||||
//! * the residual write of a group is ONE launch (`leleka_verify_final_write_rows`, grid.y = row);
|
||||
//! * the head mix is FIVE launches whatever `T`: `leleka_verify_head_norm_rows`, the sealed multi-column
|
||||
//! `bf16_f32_mmvf_multi_kernel` (down), `mtp_full_down_silu` over the contiguous `lo` slots of the rows,
|
||||
//! `bf16_f32_mmvf_multi_kernel` (up), `leleka_verify_head_pre_final_rows`.
|
||||
//!
|
||||
//! Bitwise by construction, not by a tolerance: the three new kernels are the bodies of the kernels they batch with the
|
||||
//! row as `blockIdx.y` (`sm120_head_chain.cu`), and the multi-column gemv runs the per-column fma chain and warp tree
|
||||
//! of `mtp_full_mmvf256|160` (the same chain the multi-token projections of the layers already rely on). Nothing here
|
||||
//! touches the arithmetic of the hyper-connection read of the head: `LELEKA_SM120_HEAD_MIX_MULTI` changed it (another
|
||||
//! summation order, 25 of 2057 top-16 rows moved) and stays a separate, lossy-class switch; when both are on the
|
||||
//! planner takes `plan_head_mix_multi` and only the residual write is batched. A window of one row keeps the literal
|
||||
//! launches.
|
||||
//!
|
||||
//! The switch is resolved before capture (`resolve`, like `fused_down`) and carried in `GrConfig::head_chain_batch`;
|
||||
//! the asset is sm_120 only (`Sm120Switches`: a card below 12.x never takes it) and loaded only when it is on.
|
||||
use super::super::sm120::Sm120Switches;
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
pub(crate) const E_FINAL_WRITE_ROWS: &str = "leleka_verify_final_write_rows";
|
||||
pub(crate) const E_HEAD_NORM_ROWS: &str = "leleka_verify_head_norm_rows";
|
||||
pub(crate) const E_HEAD_PRE_FINAL_ROWS: &str = "leleka_verify_head_pre_final_rows";
|
||||
/// Threads of the norm kernel (`mtp_full_gr_norm`); the element-wise kernels use `THREADS`.
|
||||
const NORM_THREADS: u32 = 1024;
|
||||
|
||||
/// `sm120_head_chain.cu` (nvcc 13.2.86, `--fmad=true --use_fast_math`, the flags `mtp_original_full_gr_norm` and
|
||||
/// `mtp_original_full_gr_post` were sealed with); plan entry in `scripts/gpu-bringup/extra-seal-plan.json` (group
|
||||
/// `sm120-decode`).
|
||||
pub(crate) static HEAD_CHAIN: AssetSpec = AssetSpec {
|
||||
name: "sm120_head_chain.ptx",
|
||||
ptx: concat!(include_str!("../sm120_head_chain.ptx"), "\0").as_bytes(),
|
||||
sha: [
|
||||
108, 159, 128, 249, 97, 125, 144, 237, 99, 113, 100, 98, 16, 147, 170, 163, 30, 214, 120, 146, 251, 203, 3, 73,
|
||||
31, 110, 176, 118, 251, 64, 94, 168,
|
||||
],
|
||||
entries: &[E_FINAL_WRITE_ROWS, E_HEAD_NORM_ROWS, E_HEAD_PRE_FINAL_ROWS],
|
||||
unsealed: "Original verifier asset unsealed: sm120_head_chain.ptx (HEAD_CHAIN_BATCH tail kernels)",
|
||||
};
|
||||
|
||||
/// Resolves the switch for the card and the environment, before the assets are loaded. Said once per process.
|
||||
pub(crate) fn resolve(journal: &OriginalVerifyGdnJournal<'_>, cfg: &GrConfig) -> Result<bool> {
|
||||
let major = journal.window_device_attribute(ATTR_COMPUTE_CAPABILITY_MAJOR)?;
|
||||
let minor = journal.window_device_attribute(ATTR_COMPUTE_CAPABILITY_MINOR)?;
|
||||
let on = Sm120Switches::from_env(major, minor).head_chain_batch && cfg.native_mmvf;
|
||||
if on {
|
||||
static SAID: std::sync::Once = std::sync::Once::new();
|
||||
SAID.call_once(|| eprintln!("leleka-serve head chain batch: on (compute capability {major}.{minor})"));
|
||||
}
|
||||
Ok(on)
|
||||
}
|
||||
|
||||
/// The asset the window preloads before capture (none when the switch is off).
|
||||
pub(crate) fn assets(on: bool) -> Vec<&'static AssetSpec> {
|
||||
if on { vec![&HEAD_CHAIN] } else { Vec::new() }
|
||||
}
|
||||
|
||||
impl GrConfig {
|
||||
/// This configuration with the switch resolved by `resolve`.
|
||||
pub(crate) fn with_head_chain_batch(self, on: bool) -> Self {
|
||||
Self { head_chain_batch: on, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
/// The residual write of the rows `rows` as one launch: `mtp_full_native_write` of every row in place, the row as
|
||||
/// grid.y. The caller checked the rows and `cfg.native_mmvf`.
|
||||
pub(super) fn final_write_rows(arena: &(impl ArenaMap + ?Sized), rows: Rows) -> Result<Launch> {
|
||||
let n = rows.len();
|
||||
let span = |name: &str, row_bytes: usize| arena.span(name, rows.begin * row_bytes, n * row_bytes);
|
||||
let (r, bo, inject) = (span("R", D * 4)?, span("bo", N * 4)?, span("inj2", HC * 4)?);
|
||||
let grid = [(D as u32).div_ceil(THREADS), n as u32, 1];
|
||||
let args = [A::P(r), A::P(bo), A::P(inject), A::I32(N as i32), A::I32(HC as i32), A::F32(QUARTER)];
|
||||
let strides = [A::I64(D as i64), A::I64(N as i64), A::I64(HC as i64)];
|
||||
Launch::new(
|
||||
&HEAD_CHAIN,
|
||||
E_FINAL_WRITE_ROWS,
|
||||
LaunchExtent::new(grid, [THREADS, 1, 1], 0),
|
||||
args.into_iter().chain(strides).collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The first addresses of the per-row buffers of the head mix and the row stride of `parts`, in floats.
|
||||
struct HeadRows {
|
||||
r: u64,
|
||||
xn: u64,
|
||||
lo: u64,
|
||||
gated: u64,
|
||||
mixed: u64,
|
||||
gated_stride: usize,
|
||||
}
|
||||
|
||||
impl HeadRows {
|
||||
/// The spans of the first `rows` rows of the window; `gated` is the first `D` floats of each `parts` slot.
|
||||
fn of(arena: &(impl ArenaMap + ?Sized), geo: &OriginalVerifyGeometry, mixed: u64, rows: usize) -> Result<Self> {
|
||||
let gated_stride = geo.k * N;
|
||||
Ok(Self {
|
||||
r: arena.span("R", 0, rows * D * 4)?,
|
||||
xn: arena.span("xn", 0, rows * D * 4)?,
|
||||
lo: arena.span("lo", 0, rows * LR * 4)?,
|
||||
gated: arena.span("parts", 0, ((rows - 1) * gated_stride + D) * 4)?,
|
||||
mixed,
|
||||
gated_stride,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The five launches of the head mix over the first `rows >= 2` rows of the window, writing the mixed vector of row
|
||||
/// `t` at `mixed_base + t * N * 4`. The caller checked the rows, the geometry and `cfg.native_mmvf`.
|
||||
pub(super) fn head_mix_rows(
|
||||
arena: &(impl ArenaMap + ?Sized),
|
||||
geo: &OriginalVerifyGeometry,
|
||||
w: &HeadAddrs,
|
||||
(mixed_base, rows): (u64, usize),
|
||||
) -> Result<Vec<Launch>> {
|
||||
let h = HeadRows::of(arena, geo, mixed_base, rows)?;
|
||||
let (x_rows, lo_rows) = (StridedRows::new(h.xn, D), StridedRows::new(h.lo, LR));
|
||||
let down = plan_bf16_gemv(x_rows, w.down, lo_rows, Bf16GemvExtents::new(D, LR, rows))?;
|
||||
let gated_rows = StridedRows::new(h.gated, h.gated_stride);
|
||||
let up = plan_bf16_gemv(lo_rows, w.up, gated_rows, Bf16GemvExtents::new(LR, D, rows))?;
|
||||
Ok(vec![norm_rows(&h, w.norm, rows)?, down, down_silu_rows(&h, rows)?, up, pre_final_rows(&h, rows)?])
|
||||
}
|
||||
|
||||
/// `mtp_full_gr_norm` of every row as one launch: grid (hc, rows), the weight rows shared by the rows.
|
||||
fn norm_rows(h: &HeadRows, weight: u64, rows: usize) -> Result<Launch> {
|
||||
let args = [A::P(h.r), A::P(weight), A::P(h.xn), A::I32(N as i32), A::F32(EPS), A::I64(D as i64), A::I64(D as i64)];
|
||||
let extent = LaunchExtent::new([HC as u32, rows as u32, 1], [NORM_THREADS, 1, 1], 0);
|
||||
Launch::new(&HEAD_CHAIN, E_HEAD_NORM_ROWS, extent, args.to_vec())
|
||||
}
|
||||
|
||||
/// `mtp_full_down_silu` over the `rows * LR` contiguous floats of the `lo` slots of the rows: element-wise, so one
|
||||
/// launch of the sealed kernel computes every element as its own launch did.
|
||||
fn down_silu_rows(h: &HeadRows, rows: usize) -> Result<Launch> {
|
||||
let count = rows * LR;
|
||||
let extent = LaunchExtent::new([(count as u32).div_ceil(THREADS), 1, 1], [THREADS, 1, 1], 0);
|
||||
Launch::new(&GR_POST, "mtp_full_down_silu", extent, vec![A::P(h.lo), A::I32(count as i32), A::F32(QUARTER)])
|
||||
}
|
||||
|
||||
/// `mtp_full_pre_final` of every row as one launch.
|
||||
fn pre_final_rows(h: &HeadRows, rows: usize) -> Result<Launch> {
|
||||
let args = [A::P(h.xn), A::P(h.gated), A::P(h.mixed), A::I32(N as i32), A::I32(HC as i32), A::F32(QUARTER)];
|
||||
let strides = [A::I64(D as i64), A::I64(h.gated_stride as i64), A::I64(N as i64)];
|
||||
let extent = LaunchExtent::new([(N as u32).div_ceil(THREADS), rows as u32, 1], [THREADS, 1, 1], 0);
|
||||
Launch::new(&HEAD_CHAIN, E_HEAD_PRE_FINAL_ROWS, extent, args.into_iter().chain(strides).collect())
|
||||
}
|
||||
@@ -202,6 +202,9 @@ pub(crate) fn plan_final_write(
|
||||
rows: Rows,
|
||||
) -> Result<Vec<Launch>> {
|
||||
check_rows(geo, rows)?;
|
||||
if cfg.head_chain_batch && rows.len() > 1 && cfg.native_mmvf {
|
||||
return Ok(vec![super::head_chain::final_write_rows(arena, rows)?]);
|
||||
}
|
||||
(rows.begin..rows.end).map(|t| write_row(arena, cfg, t, "final_write")).collect()
|
||||
}
|
||||
|
||||
@@ -233,6 +236,9 @@ pub(crate) fn plan_head_mix(
|
||||
if !cfg.native_mmvf {
|
||||
return Err(refuse("head"));
|
||||
}
|
||||
if cfg.head_chain_batch && rows > 1 {
|
||||
return super::head_chain::head_mix_rows(arena, geo, w, (mixed_out_base, rows));
|
||||
}
|
||||
let mut out = Vec::with_capacity(rows * 5);
|
||||
for t in 0..rows {
|
||||
out.extend(head_mix_row(arena, geo, w, mixed_out_base, t)?);
|
||||
|
||||
@@ -60,6 +60,8 @@ fn ple_addrs(key: PleKey) -> PleAddrs {
|
||||
|
||||
#[path = "tests/fused_down_launches.rs"]
|
||||
mod fused_down_launches;
|
||||
#[path = "tests/head_chain_launches.rs"]
|
||||
mod head_chain_launches;
|
||||
#[path = "tests/head_mix_is_the_native.rs"]
|
||||
mod head_mix_is_the_native;
|
||||
#[path = "tests/head_mix_multi.rs"]
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
//! `LELEKA_SM120_HEAD_CHAIN_BATCH` (`head_chain.rs`, `sm120_head_chain.cu`): the plan, the decision, the asset and the
|
||||
//! arithmetic the batched kernels share with the kernels they replace.
|
||||
|
||||
use super::super::super::sm120::{DEFAULT_ON_HEAD_CHAIN_BATCH, Sm120Switches};
|
||||
use super::head_chain::{
|
||||
E_FINAL_WRITE_ROWS, E_HEAD_NORM_ROWS, E_HEAD_PRE_FINAL_ROWS, HEAD_CHAIN, assets as head_chain_assets,
|
||||
};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
const MIXED_BASE: u64 = 0x9999_0000;
|
||||
const HEAD: HeadAddrs = HeadAddrs { norm: 0xA000, down: 0xB000, up: 0xC000 };
|
||||
|
||||
fn batch_card() -> GrConfig {
|
||||
sm120(GrVariant::Staged).with_head_chain_batch(true)
|
||||
}
|
||||
fn write_launches(cfg: &GrConfig, r: Rows) -> Vec<Launch> {
|
||||
let (m, g) = (arena(), test_geometry());
|
||||
plan_final_write(&m, &g, cfg, r).unwrap()
|
||||
}
|
||||
fn mix_launches(cfg: &GrConfig, rows: usize) -> Vec<Launch> {
|
||||
let (m, g) = (arena(), test_geometry());
|
||||
plan_head_mix(window(&m, &g, cfg), &HEAD, MIXED_BASE, rows).unwrap()
|
||||
}
|
||||
fn entries(l: &[Launch]) -> Vec<&'static str> {
|
||||
l.iter().map(|x| x.entry).collect()
|
||||
}
|
||||
/// The address argument `k` of a launch.
|
||||
fn address(l: &Launch, k: usize) -> u64 {
|
||||
match l.args[k] {
|
||||
A::P(a) => a,
|
||||
ref other => panic!("argument {k} is {other:?}, not an address"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_switch_is_off_in_every_config_the_card_derives_and_loads_its_asset_only_when_on() {
|
||||
assert!(!sm120(GrVariant::Staged).head_chain_batch);
|
||||
assert!(!from_card(GrVariant::Staged, (8, 6), 101_376, 49_152).head_chain_batch);
|
||||
assert!(batch_card().head_chain_batch && !batch_card().with_head_chain_batch(false).head_chain_batch);
|
||||
assert!(head_chain_assets(false).is_empty());
|
||||
assert!(std::ptr::eq(head_chain_assets(true)[0], &HEAD_CHAIN));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_switch_is_off_by_default_follows_its_own_variable_and_no_other_switch_follows_it() {
|
||||
const VAR: &str = "LELEKA_SM120_HEAD_CHAIN_BATCH";
|
||||
let resolve = |major, minor, pairs: &'static [(&'static str, &'static str)]| {
|
||||
Sm120Switches::resolve(major, minor, move |k| pairs.iter().find(|(n, _)| *n == k).map(|(_, v)| v.to_string()))
|
||||
};
|
||||
assert!(!DEFAULT_ON_HEAD_CHAIN_BATCH && !resolve(12, 0, &[]).head_chain_batch);
|
||||
assert!(resolve(12, 0, &[(VAR, "1")]).head_chain_batch);
|
||||
assert!(!resolve(12, 0, &[(VAR, "0")]).head_chain_batch);
|
||||
assert!(!resolve(8, 6, &[(VAR, "1")]).head_chain_batch, "below 12.x the sm_120 PTX is never taken");
|
||||
assert!(resolve(12, 0, &[("LELEKA_SM120_PERF", "0"), (VAR, "1")]).head_chain_batch);
|
||||
let only = Sm120Switches { head_chain_batch: true, ..Sm120Switches::default() };
|
||||
assert_eq!(resolve(12, 0, &[(VAR, "1")]), only);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_asset_is_sealed_and_exports_the_three_kernels() {
|
||||
HEAD_CHAIN.assert_sealed_and_fail_closed();
|
||||
assert_eq!(HEAD_CHAIN.entries, &[E_FINAL_WRITE_ROWS, E_HEAD_NORM_ROWS, E_HEAD_PRE_FINAL_ROWS]);
|
||||
let ptx = std::str::from_utf8(HEAD_CHAIN.ptx).unwrap();
|
||||
assert!(HEAD_CHAIN.entries.iter().all(|e| entry_declared(ptx, e)));
|
||||
assert!(ptx.contains(".target sm_120"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switch_off_is_the_literal_tail_six_launches_a_row() {
|
||||
for rows in 1..=8usize {
|
||||
let write = write_launches(&sm120(GrVariant::Staged), rows_of(0, rows));
|
||||
assert_eq!(entries(&write), vec!["mtp_full_native_write"; rows]);
|
||||
let mix = mix_launches(&sm120(GrVariant::Staged), rows);
|
||||
assert_eq!(mix.len(), 5 * rows);
|
||||
assert!(mix.iter().all(|l| !std::ptr::eq(l.asset, &HEAD_CHAIN)), "rows {rows}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_row_keeps_the_literal_launches_with_the_switch_on() {
|
||||
let off = (write_launches(&sm120(GrVariant::Staged), rows_of(0, 1)), mix_launches(&sm120(GrVariant::Staged), 1));
|
||||
let on = (write_launches(&batch_card(), rows_of(0, 1)), mix_launches(&batch_card(), 1));
|
||||
assert_eq!(off, on);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_residual_write_of_a_group_is_one_launch_with_the_row_as_grid_y() {
|
||||
for (begin, end) in [(0, 2), (0, 8), (3, 5), (1, 8)] {
|
||||
let l = write_launches(&batch_card(), rows_of(begin, end));
|
||||
assert_eq!(l.len(), 1);
|
||||
let n = end - begin;
|
||||
assert_eq!((l[0].entry, l[0].grid, l[0].block), (E_FINAL_WRITE_ROWS, [40, n as u32, 1], [256, 1, 1]));
|
||||
assert!(std::ptr::eq(l[0].asset, &HEAD_CHAIN));
|
||||
// the literal launches of the same rows, per row, against the batched base plus the row stride
|
||||
let literal = write_launches(&sm120(GrVariant::Staged), rows_of(begin, end));
|
||||
for (t, row) in literal.iter().enumerate() {
|
||||
for (k, stride) in [(0usize, 40_960u64), (1, 10_240), (2, 16)] {
|
||||
assert_eq!(address(row, k), address(&l[0], k) + t as u64 * stride, "rows {begin}..{end} t {t} arg {k}");
|
||||
}
|
||||
assert_eq!(address(row, 3), address(row, 0), "the literal write is in place");
|
||||
}
|
||||
let tail = [A::I32(2560), A::I32(4), A::F32(0.25), A::I64(10_240), A::I64(2560), A::I64(4)];
|
||||
assert_eq!(l[0].args[3..], tail);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_head_mix_is_five_launches_whatever_the_window_width() {
|
||||
for rows in 2..=8usize {
|
||||
let l = mix_launches(&batch_card(), rows);
|
||||
let nt = if rows <= 4 { "ELi4EE" } else { "ELi8EE" };
|
||||
assert_eq!(l.len(), 5, "rows {rows}");
|
||||
assert_eq!((l[0].entry, l[0].grid, l[0].block), (E_HEAD_NORM_ROWS, [4, rows as u32, 1], [1024, 1, 1]));
|
||||
assert!(l[1].entry.contains("mmvf_multi_kernelILi256") && l[1].entry.contains(nt), "{}", l[1].entry);
|
||||
assert_eq!((l[1].grid, l[1].block), ([320, 1, 1], [256, 1, 1]));
|
||||
let silu_grid = [(rows as u32 * 320).div_ceil(256), 1, 1];
|
||||
assert_eq!((l[2].entry, l[2].grid, l[2].block), ("mtp_full_down_silu", silu_grid, [256, 1, 1]));
|
||||
assert!(l[3].entry.contains("mmvf_multi_kernelILi160") && l[3].entry.contains(nt), "{}", l[3].entry);
|
||||
assert_eq!((l[3].grid, l[3].block), ([10_240, 1, 1], [160, 1, 1]));
|
||||
assert_eq!((l[4].entry, l[4].grid, l[4].block), (E_HEAD_PRE_FINAL_ROWS, [10, rows as u32, 1], [256, 1, 1]));
|
||||
}
|
||||
}
|
||||
|
||||
/// The addresses of the literal launches of row `t` equal the batched base plus `t` strides, stage by stage.
|
||||
fn assert_row_addresses(k: &[Launch], batch: &[Launch], t: usize) {
|
||||
let step = |stride_bytes: u64| t as u64 * stride_bytes;
|
||||
// norm: R -> xn, gamma shared
|
||||
assert_eq!(address(&k[0], 0), address(&batch[0], 0) + step(40_960));
|
||||
assert_eq!(address(&k[0], 1), address(&batch[0], 1));
|
||||
assert_eq!(address(&k[0], 2), address(&batch[0], 2) + step(40_960));
|
||||
// down gemv: xn -> lo (multi kernel args: x, ldx, w, y, ldy, n_in, n_tok)
|
||||
assert_eq!(address(&k[1], 0), address(&batch[1], 0) + step(40_960));
|
||||
assert_eq!(address(&k[1], 1), address(&batch[1], 2));
|
||||
assert_eq!(address(&k[1], 2), address(&batch[1], 3) + step(1280));
|
||||
// down-silu over lo
|
||||
assert_eq!(address(&k[2], 0), address(&batch[2], 0) + step(1280));
|
||||
// up gemv: lo -> gated (a slot of `parts` each)
|
||||
assert_eq!(address(&k[3], 0), address(&batch[3], 0) + step(1280));
|
||||
assert_eq!(address(&k[3], 2), address(&batch[3], 3) + step(102_400));
|
||||
// pre-final: xn, gated -> mixed
|
||||
assert_eq!(address(&k[4], 0), address(&batch[4], 0) + step(40_960));
|
||||
assert_eq!(address(&k[4], 1), address(&batch[4], 1) + step(102_400));
|
||||
assert_eq!(address(&k[4], 2), address(&batch[4], 2) + step(10_240));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_row_has_the_addresses_the_literal_chain_gave_it() {
|
||||
for rows in 2..=8usize {
|
||||
let (literal, batch) = (mix_launches(&sm120(GrVariant::Staged), rows), mix_launches(&batch_card(), rows));
|
||||
for t in 0..rows {
|
||||
assert_row_addresses(&literal[t * 5..t * 5 + 5], &batch, t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_strides_and_extents_are_the_row_pitches_of_the_arena() {
|
||||
for rows in 2..=8usize {
|
||||
let batch = mix_launches(&batch_card(), rows);
|
||||
let n = rows as i32;
|
||||
let ints = |l: &Launch| (l.args[1].clone(), l.args[4].clone(), l.args[5].clone(), l.args[6].clone());
|
||||
assert_eq!(ints(&batch[1]), (A::I64(10_240), A::I64(320), A::I32(10_240), A::I32(n)));
|
||||
assert_eq!(ints(&batch[3]), (A::I64(320), A::I64(25_600), A::I32(320), A::I32(n)));
|
||||
assert_eq!(batch[2].args[1..], [A::I32(n * 320), A::F32(0.25)]);
|
||||
let pre = [A::I32(2560), A::I32(4), A::F32(0.25), A::I64(10_240), A::I64(25_600), A::I64(2560)];
|
||||
assert_eq!(batch[4].args[3..], pre);
|
||||
assert_eq!(batch[0].args[3..], [A::I32(2560), A::F32(1e-6), A::I64(10_240), A::I64(10_240)]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_head_chain_refuses_what_the_literal_chain_refuses() {
|
||||
let (m, g) = (arena(), test_geometry());
|
||||
let cfg = batch_card();
|
||||
assert!(plan_head_mix(window(&m, &g, &cfg), &HEAD, MIXED_BASE, 9).is_err());
|
||||
assert!(plan_head_mix(window(&m, &g, &cfg), &HEAD, MIXED_BASE, 0).is_err());
|
||||
let non_native = GrConfig { native_mmvf: false, ..batch_card() };
|
||||
assert!(plan_head_mix(window(&m, &g, &non_native), &HEAD, MIXED_BASE, 3).is_err());
|
||||
assert!(plan_final_write(&m, &g, &non_native, rows_of(0, 3)).is_err());
|
||||
assert!(plan_final_write(&m, &g, &cfg, rows_of(0, 9)).is_err());
|
||||
}
|
||||
|
||||
fn rows_of(begin: usize, end: usize) -> Rows {
|
||||
rows(begin, end, 0)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------ arithmetic
|
||||
/// The mnemonics of the floating point, shuffle, barrier and special-function instructions of one entry, in order.
|
||||
fn float_ops(ptx: &[u8], entry: &str) -> Vec<String> {
|
||||
let text = std::str::from_utf8(ptx).unwrap();
|
||||
let start = text.find(&format!(".visible .entry {entry}(")).unwrap_or_else(|| panic!("{entry} missing"));
|
||||
let body = &text[start..];
|
||||
let body = &body[..body.find("\n}\n").unwrap()];
|
||||
let kinds = [".f32", "shfl", "bar.sync", "ex2", "rcp", "rsqrt", "sqrt"];
|
||||
let is_float = |op: &str| kinds.iter().any(|k| op.contains(k));
|
||||
let mut ops = Vec::new();
|
||||
for line in body.lines().map(str::trim) {
|
||||
let mut words = line.split_whitespace();
|
||||
let mut op = words.next().unwrap_or("");
|
||||
if op.starts_with('@') {
|
||||
op = words.next().unwrap_or("");
|
||||
}
|
||||
if !op.is_empty() && !op.starts_with(['.', '$', '/']) && is_float(op) {
|
||||
ops.push(op.to_string());
|
||||
}
|
||||
}
|
||||
ops
|
||||
}
|
||||
|
||||
/// The three kernels run the floating point instructions of the kernels they batch, in the same order (the norm and
|
||||
/// the residual write instruction for instruction; the pre-final mix per loop iteration, whose unrolling differs
|
||||
/// between two compilations of the same source).
|
||||
#[test]
|
||||
fn the_batched_kernels_use_the_arithmetic_of_the_kernels_they_batch() {
|
||||
let ops = |a: &AssetSpec, e: &str| float_ops(a.ptx, e);
|
||||
assert_eq!(ops(&HEAD_CHAIN, E_FINAL_WRITE_ROWS), ops(&GR_POST, "mtp_full_native_write"));
|
||||
assert_eq!(ops(&HEAD_CHAIN, E_HEAD_NORM_ROWS), ops(&GR_NORM, "mtp_full_gr_norm"));
|
||||
let (new, old) = (ops(&HEAD_CHAIN, E_HEAD_PRE_FINAL_ROWS), ops(&GR_POST, "mtp_full_pre_final"));
|
||||
let iteration = |v: &[String]| v[..v.iter().position(|o| o == "selp.f32").unwrap() + 1].to_vec();
|
||||
assert_eq!(iteration(&new), iteration(&old));
|
||||
assert_eq!(new.last(), old.last());
|
||||
let distinct = |v: &[String]| v.iter().cloned().collect::<std::collections::BTreeSet<_>>();
|
||||
assert_eq!(distinct(&new), distinct(&old));
|
||||
// the fast-math lowering of the originals, not the precise one
|
||||
for op in ["ex2.approx.ftz.f32", "rcp.approx.ftz.f32", "fma.rn.ftz.f32"] {
|
||||
assert!(new.iter().any(|o| o == op), "{op}");
|
||||
}
|
||||
assert!(ops(&HEAD_CHAIN, E_HEAD_NORM_ROWS).iter().any(|o| o.starts_with("rsqrt.approx")));
|
||||
}
|
||||
@@ -176,8 +176,11 @@ impl<'ctx> OriginalVerifyWindowResources<'ctx> {
|
||||
let cfg = GrConfig::query(&self.base.journal, policy.gr_variant, policy.native_mmvf)?;
|
||||
// claude/u5a-gr-down-fused: LELEKA_SM120_GR_DOWN_FUSED, decided before the assets are loaded
|
||||
let cfg = cfg.with_fused_down(gr::fused_down::resolve(&self.base.journal, &cfg)?);
|
||||
// claude/tail-fusion: LELEKA_SM120_HEAD_CHAIN_BATCH, decided before the assets are loaded
|
||||
let cfg = cfg.with_head_chain_batch(gr::head_chain::resolve(&self.base.journal, &cfg)?);
|
||||
let mut assets = self.required_assets(policy);
|
||||
assets.extend(gr::fused_down::assets(cfg.down_fused));
|
||||
assets.extend(gr::head_chain::assets(cfg.head_chain_batch));
|
||||
self.base.journal.ensure_window_assets(&assets)?;
|
||||
let mut attributes = Vec::new();
|
||||
if self.gr.is_some() {
|
||||
|
||||
@@ -347,3 +347,5 @@ mod every_window_size_and_group;
|
||||
mod fused_gr_down;
|
||||
#[path = "tests/fused_qsa_prelude.rs"]
|
||||
mod fused_qsa_prelude;
|
||||
#[path = "tests/head_chain_batch.rs"]
|
||||
mod head_chain_batch;
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
//! `LELEKA_SM120_HEAD_CHAIN_BATCH` through the recorder: with the switch off the window is the literal one; with it on
|
||||
//! only the residual write of the last layer and the head mix change, and the launch counts fall as the design note
|
||||
//! says (`docs/experiments/verify-tail-and-gaps.md`).
|
||||
|
||||
use super::super::super::combine_head::CombineHeadKernels;
|
||||
use super::super::super::gr::head_chain::{E_FINAL_WRITE_ROWS, E_HEAD_NORM_ROWS, E_HEAD_PRE_FINAL_ROWS};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
fn record_batched(cfg: GrConfig, t: usize, groups: usize, multi: bool) -> Vec<String> {
|
||||
let (m, fake) = geometry_and_fake(false);
|
||||
let policy = WindowPolicy::mode17();
|
||||
let kernels = CombineHeadKernels { combine_vec4: false, head_mix_multi: multi };
|
||||
let planner = Planner::new(&m, test_geometry(), policy, cfg, &fake).with_combine_head(kernels);
|
||||
let mut ops = PlanOps { planner, log: Vec::new(), t };
|
||||
record_window(&mut ops, &policy, t, groups, false).unwrap();
|
||||
ops.log
|
||||
}
|
||||
fn on(t: usize, groups: usize, multi: bool) -> Vec<String> {
|
||||
record_batched(sm120().with_head_chain_batch(true), t, groups, multi)
|
||||
}
|
||||
fn off(t: usize, groups: usize, multi: bool) -> Vec<String> {
|
||||
record_batched(sm120(), t, groups, multi)
|
||||
}
|
||||
/// The log without the sections the producers `names` planned (`<name` ... `name>`), and those sections apart.
|
||||
fn split_sections(log: &[String], names: &[&str]) -> (Vec<String>, Vec<Vec<String>>) {
|
||||
let (mut rest, mut cut, mut open): (Vec<String>, Vec<Vec<String>>, Option<usize>) = (Vec::new(), Vec::new(), None);
|
||||
for line in log {
|
||||
match open {
|
||||
None if names.iter().any(|n| *line == format!("<{n}")) => {
|
||||
open = Some(cut.len());
|
||||
cut.push(Vec::new());
|
||||
}
|
||||
Some(i) => {
|
||||
if names.iter().any(|n| *line == format!("{n}>")) {
|
||||
open = None;
|
||||
} else {
|
||||
cut[i].push(line.clone());
|
||||
}
|
||||
}
|
||||
None => rest.push(line.clone()),
|
||||
}
|
||||
}
|
||||
(rest, cut)
|
||||
}
|
||||
fn count_in(sections: &[Vec<String>], name: &str) -> usize {
|
||||
sections.iter().flatten().filter(|s| *s == name).count()
|
||||
}
|
||||
const TAIL: [&str; 2] = ["final_write", "head_mix"];
|
||||
|
||||
#[test]
|
||||
fn switch_off_is_the_literal_window() {
|
||||
for (t, groups) in [(1, 1), (3, 1), (8, 1), (6, 2)] {
|
||||
assert_eq!(off(t, groups, false), record(t, groups, false), "T {t} groups {groups}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_residual_write_and_the_head_mix_change_and_the_launches_fall_to_six() {
|
||||
for (t, groups) in [(2, 1), (3, 1), (5, 1), (8, 1), (6, 2), (4, 2), (3, 2)] {
|
||||
let (rest_off, tail_off) = split_sections(&off(t, groups, false), &TAIL);
|
||||
let (rest_on, tail_on) = split_sections(&on(t, groups, false), &TAIL);
|
||||
assert_eq!(rest_on, rest_off, "T {t} groups {groups}: nothing outside the tail changes");
|
||||
let first = t.div_ceil(2);
|
||||
let group_sizes = if groups == 2 { vec![first, t - first] } else { vec![t] };
|
||||
let batched_writes = group_sizes.iter().filter(|n| **n > 1).count();
|
||||
let single_writes = group_sizes.iter().filter(|n| **n == 1).count();
|
||||
assert_eq!(count_in(&tail_off, "mtp_full_native_write"), t);
|
||||
assert_eq!(count_in(&tail_on, E_FINAL_WRITE_ROWS), batched_writes, "T {t} groups {groups}");
|
||||
assert_eq!(count_in(&tail_on, "mtp_full_native_write"), single_writes, "T {t} groups {groups}");
|
||||
assert_eq!(count_in(&tail_off, "mtp_full_pre_final"), t);
|
||||
assert_eq!(count_in(&tail_on, "mtp_full_pre_final") + count_in(&tail_on, "mtp_full_gr_norm"), 0);
|
||||
assert_eq!(count_in(&tail_on, E_HEAD_NORM_ROWS) + count_in(&tail_on, E_HEAD_PRE_FINAL_ROWS), 2);
|
||||
let launches = |s: &[Vec<String>]| s.iter().map(Vec::len).sum::<usize>();
|
||||
assert_eq!(launches(&tail_off), 6 * t, "T {t}: a write and five kernels a row");
|
||||
assert_eq!(launches(&tail_on), 5 + batched_writes + single_writes, "T {t} groups {groups}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_of_one_row_is_unchanged() {
|
||||
assert_eq!(on(1, 1, false), off(1, 1, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_the_multi_head_mix_only_the_residual_write_is_batched() {
|
||||
for t in [2usize, 4, 7] {
|
||||
let (rest_off, tail_off) = split_sections(&off(t, 1, true), &TAIL);
|
||||
let (rest_on, tail_on) = split_sections(&on(t, 1, true), &TAIL);
|
||||
assert_eq!(rest_on, rest_off, "T {t}");
|
||||
assert_eq!(count_in(&tail_on, E_FINAL_WRITE_ROWS), 1);
|
||||
assert_eq!(count_in(&tail_on, E_HEAD_NORM_ROWS) + count_in(&tail_on, E_HEAD_PRE_FINAL_ROWS), 0);
|
||||
let launches = |s: &[Vec<String>]| s.iter().map(Vec::len).sum::<usize>();
|
||||
assert_eq!(launches(&tail_off) - launches(&tail_on), t - 1, "T {t}: the head mix launches are the multi read");
|
||||
}
|
||||
}
|
||||
@@ -95,6 +95,8 @@ pub(crate) const DEFAULT_ON_GR_DOWN_FUSED: bool = false;
|
||||
pub(crate) const DEFAULT_ON_DOWN_SUB16: bool = false;
|
||||
pub(crate) const DEFAULT_ON_HITS_IN_COMBINE: bool = false;
|
||||
pub(crate) const DEFAULT_ON_WAIT_M_ROWS: bool = false;
|
||||
// claude/tail-fusion (original_verify_window_gr/head_chain.rs): off until its identity run and a paired A/B
|
||||
pub(crate) const DEFAULT_ON_HEAD_CHAIN_BATCH: bool = false;
|
||||
|
||||
/// Which parts of the verify graph run on the two side streams: the GDN gates and gate projection, the QSA indexer and
|
||||
/// query chains (upstream `STRATA_SIDE_MIXER=2`), and the shared expert beside the routed experts (upstream's shared
|
||||
@@ -154,6 +156,9 @@ pub struct Sm120Switches {
|
||||
pub hits_in_combine: bool,
|
||||
/// `LELEKA_SM120_WAIT_M_ROWS`: the wait on flag M and the copy of the CPU rows as one launch.
|
||||
pub wait_m_rows: bool,
|
||||
// ---- claude/tail-fusion
|
||||
/// `LELEKA_SM120_HEAD_CHAIN_BATCH`: the residual write and the head mix of all window rows, 6 launches not `6 T`.
|
||||
pub head_chain_batch: bool,
|
||||
}
|
||||
|
||||
fn one(get: &impl Fn(&str) -> Option<String>, var: &str, default: bool) -> bool {
|
||||
@@ -206,6 +211,7 @@ impl Sm120Switches {
|
||||
down_sub16: switch("LELEKA_SM120_DOWN_SUB16", DEFAULT_ON_DOWN_SUB16),
|
||||
hits_in_combine: switch("LELEKA_SM120_HITS_IN_COMBINE", DEFAULT_ON_HITS_IN_COMBINE),
|
||||
wait_m_rows: switch("LELEKA_SM120_WAIT_M_ROWS", DEFAULT_ON_WAIT_M_ROWS),
|
||||
head_chain_batch: switch("LELEKA_SM120_HEAD_CHAIN_BATCH", DEFAULT_ON_HEAD_CHAIN_BATCH),
|
||||
}
|
||||
}
|
||||
/// The side-stream parts these switches ask for.
|
||||
@@ -230,6 +236,7 @@ impl Sm120Switches {
|
||||
down_sub16: s.down_sub16,
|
||||
hits_in_combine: s.hits_in_combine,
|
||||
wait_m_rows: s.wait_m_rows,
|
||||
head_chain_batch: s.head_chain_batch,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
// verify window, the graph tail after the last layer: the final residual write and the head's hyper-connection mix of
|
||||
// ALL window rows in a handful of launches (docs/experiments/verify-tail-and-gaps.md): LELEKA_SM120_HEAD_CHAIN_BATCH.
|
||||
//
|
||||
// The literal tail launches, per window row t, `mtp_full_native_write` (the last layer's residual write) and the five
|
||||
// kernels of `lm_head_mix`: `mtp_full_gr_norm`, `mtp_full_mmvf256`, `mtp_full_down_silu`, `mtp_full_mmvf160`,
|
||||
// `mtp_full_pre_final` = 6 T launches, one dependent chain per row. The three kernels below are those kernels with the
|
||||
// row as `blockIdx.y` and the per-row base offsets as launch arguments; the two gemv kernels and the silu are not
|
||||
// here: the existing sealed `bf16_f32_mmvf_multi_kernel<block, 4|8>` runs the per-column fma chain of
|
||||
// `mtp_full_mmvf256|160` (`acc[k] = fma(w, x, acc[k])` over the same pairs, the same warp tree) for 2..8 columns, and
|
||||
// `mtp_full_down_silu` is element-wise over the rows' contiguous `lo` slots.
|
||||
//
|
||||
// Same value of every output element, element by element: each body below is the body of the kernel it batches, token
|
||||
// by token, with `blockIdx.y` selecting the row and no other change. The row bases add `tk * stride` (in floats) to the
|
||||
// pointers; everything else, including the order of the sums of the norm and the helper functions, is the text of
|
||||
// mtp_original_full_gr_norm.cu / mtp_original_full_gr_post.cu (closed literal Original MTP exports). Compile with the
|
||||
// flags those two were sealed with (extra-seal-plan.json, group reseal-fastmath): --fmad=true --use_fast_math, so
|
||||
// `expf`, `rsqrtf` and the divisions lower to the same approximate PTX as the originals' (checked by the unit test
|
||||
// `the_batched_kernels_use_the_arithmetic_of_the_kernels_they_batch`).
|
||||
//
|
||||
// Compile: nvcc --ptx -O3 -arch=sm_120 -std=c++17 --fmad=true --use_fast_math
|
||||
#include <cuda_runtime.h>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace {
|
||||
__device__ __forceinline__ float norm_warp_sum(float value) {
|
||||
#pragma unroll
|
||||
for (int offset = 16; offset > 0; offset >>= 1) {
|
||||
value += __shfl_xor_sync(0xffffffffu, value, offset, 32);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
__device__ __forceinline__ float sigmoid(float x) { return 1.0f / (1.0f + expf(-x)); }
|
||||
// ggml SCALE uses scale*x+bias, including its +0 bias. Retain this operation explicitly so compile-time zero does not
|
||||
// change signed-zero behavior.
|
||||
__device__ __forceinline__ float scale_zero_bias(float x, float scale) {
|
||||
return __fmaf_rn(scale, x, 0.0f);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// mtp_full_native_write over `gridDim.y` rows: output = block_out * (2 * sigmoid(scale * inject[c])) + residual, in
|
||||
// place (residual and output are the same row). Strides in floats.
|
||||
extern "C" __global__ void leleka_verify_final_write_rows(float* residual_output, const float* __restrict__ block_out,
|
||||
const float* __restrict__ inject, int n_embd, int hc,
|
||||
float scale, int64_t residual_stride, int64_t block_stride,
|
||||
int64_t inject_stride) {
|
||||
const int64_t tk = blockIdx.y;
|
||||
const float* residual = residual_output + tk * residual_stride;
|
||||
float* output = residual_output + tk * residual_stride;
|
||||
block_out += tk * block_stride;
|
||||
inject += tk * inject_stride;
|
||||
const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x;
|
||||
if (i >= std::size_t(n_embd) * hc) return;
|
||||
const int c = int(i / n_embd), d = int(i % n_embd);
|
||||
const float weight = scale_zero_bias(sigmoid(scale_zero_bias(inject[c], scale)), 2.0f);
|
||||
// Exact residual/output alias is supported; no other thread reads residual[i].
|
||||
output[i] = __fmaf_rn(block_out[d], weight, residual[i]);
|
||||
}
|
||||
|
||||
// mtp_full_gr_norm over `gridDim.y` rows (grid.x = hc rows of the row's state): weighted RMS norm of block x of row
|
||||
// tk. `gamma` is the head's norm weight, the same for every row. 1024 threads.
|
||||
extern "C" __global__ void leleka_verify_head_norm_rows(const float* __restrict__ input,
|
||||
const float* __restrict__ gamma, float* __restrict__ output,
|
||||
int n_cols, float epsilon, int64_t input_stride,
|
||||
int64_t output_stride) {
|
||||
const int tid = threadIdx.x;
|
||||
const int64_t tk = blockIdx.y;
|
||||
const std::size_t row_offset = std::size_t(blockIdx.x) * n_cols;
|
||||
input += tk * input_stride + row_offset;
|
||||
gamma += row_offset;
|
||||
output += tk * output_stride + row_offset;
|
||||
float partial = 0.0f;
|
||||
for (int col = tid; col < n_cols; col += 1024) {
|
||||
const float value = input[col];
|
||||
partial += value * value;
|
||||
}
|
||||
|
||||
// Pinned block_reduce<SUM,1024>: every warp repeats the final XOR
|
||||
// reduction. There is no warp-0-only broadcast or downward-shuffle tree.
|
||||
__shared__ float sums[32];
|
||||
partial = norm_warp_sum(partial);
|
||||
const int lane = tid % 32;
|
||||
if (lane == 0) sums[tid / 32] = partial;
|
||||
__syncthreads();
|
||||
partial = 0.0f;
|
||||
if (lane < 1024 / 32) partial = sums[lane];
|
||||
partial = norm_warp_sum(partial);
|
||||
|
||||
const float mean = partial / n_cols;
|
||||
const float scale = rsqrtf(mean + epsilon);
|
||||
for (int col = tid; col < n_cols; col += 1024) {
|
||||
output[col] = scale * input[col] * gamma[col];
|
||||
}
|
||||
}
|
||||
|
||||
// mtp_full_pre_final over `gridDim.y` rows: gate = xn * sigmoid(gate) per channel, mixed = scale * (the channel sum),
|
||||
// as the final mixer (not the layer form). Strides in floats.
|
||||
extern "C" __global__ void leleka_verify_head_pre_final_rows(const float* __restrict__ xn, float* __restrict__ gate,
|
||||
float* __restrict__ mixed, int n_embd, int hc, float scale,
|
||||
int64_t xn_stride, int64_t gate_stride,
|
||||
int64_t mixed_stride) {
|
||||
const int64_t tk = blockIdx.y;
|
||||
xn += tk * xn_stride;
|
||||
gate += tk * gate_stride;
|
||||
mixed += tk * mixed_stride;
|
||||
const std::size_t d = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x;
|
||||
if (d >= std::size_t(n_embd)) return;
|
||||
float sum = 0.0f;
|
||||
for (int c = 0; c < hc; ++c) {
|
||||
const std::size_t i = std::size_t(c) * n_embd + d;
|
||||
const float x = xn[i], w = sigmoid(gate[i]);
|
||||
const float product = __fmul_rn(x, w);
|
||||
gate[i] = product;
|
||||
sum = c == 0 ? product : __fadd_rn(sum, product);
|
||||
}
|
||||
mixed[d] = scale_zero_bias(sum, scale);
|
||||
}
|
||||
@@ -0,0 +1,582 @@
|
||||
//
|
||||
// Generated by NVIDIA NVVM Compiler
|
||||
//
|
||||
// Compiler Build ID: UNKNOWN
|
||||
// Cuda compilation tools, release 13.2, V13.2.86
|
||||
// Based on NVVM 22.0.0
|
||||
//
|
||||
|
||||
.version 9.2
|
||||
.target sm_120
|
||||
.address_size 64
|
||||
|
||||
// .globl leleka_verify_final_write_rows
|
||||
// _ZZ28leleka_verify_head_norm_rowsE4sums has been demoted
|
||||
|
||||
.visible .entry leleka_verify_final_write_rows(
|
||||
.param .u64 .ptr .align 1 leleka_verify_final_write_rows_param_0,
|
||||
.param .u64 .ptr .align 1 leleka_verify_final_write_rows_param_1,
|
||||
.param .u64 .ptr .align 1 leleka_verify_final_write_rows_param_2,
|
||||
.param .u32 leleka_verify_final_write_rows_param_3,
|
||||
.param .u32 leleka_verify_final_write_rows_param_4,
|
||||
.param .f32 leleka_verify_final_write_rows_param_5,
|
||||
.param .u64 leleka_verify_final_write_rows_param_6,
|
||||
.param .u64 leleka_verify_final_write_rows_param_7,
|
||||
.param .u64 leleka_verify_final_write_rows_param_8
|
||||
)
|
||||
{
|
||||
.reg .pred %p<3>;
|
||||
.reg .b32 %r<23>;
|
||||
.reg .b64 %rd<32>;
|
||||
|
||||
ld.param.b64 %rd3, [leleka_verify_final_write_rows_param_0];
|
||||
ld.param.b64 %rd4, [leleka_verify_final_write_rows_param_1];
|
||||
ld.param.b64 %rd5, [leleka_verify_final_write_rows_param_2];
|
||||
ld.param.b32 %r2, [leleka_verify_final_write_rows_param_3];
|
||||
ld.param.b32 %r3, [leleka_verify_final_write_rows_param_4];
|
||||
ld.param.b32 %r1, [leleka_verify_final_write_rows_param_5];
|
||||
ld.param.b64 %rd6, [leleka_verify_final_write_rows_param_6];
|
||||
ld.param.b64 %rd7, [leleka_verify_final_write_rows_param_7];
|
||||
ld.param.b64 %rd8, [leleka_verify_final_write_rows_param_8];
|
||||
mov.u32 %r4, %ctaid.x;
|
||||
mov.u32 %r5, %ntid.x;
|
||||
mul.wide.u32 %rd9, %r4, %r5;
|
||||
mov.u32 %r6, %tid.x;
|
||||
cvt.u64.u32 %rd10, %r6;
|
||||
add.s64 %rd1, %rd9, %rd10;
|
||||
cvt.s64.s32 %rd2, %r2;
|
||||
mul.wide.s32 %rd11, %r3, %r2;
|
||||
setp.ge.u64 %p1, %rd1, %rd11;
|
||||
@%p1 bra $L__BB0_5;
|
||||
or.b64 %rd12, %rd1, %rd2;
|
||||
and.b64 %rd13, %rd12, -4294967296;
|
||||
setp.ne.b64 %p2, %rd13, 0;
|
||||
@%p2 bra $L__BB0_3;
|
||||
cvt.u32.u64 %r7, %rd2;
|
||||
cvt.u32.u64 %r8, %rd1;
|
||||
div.u32 %r9, %r8, %r7;
|
||||
mul.lo.s32 %r10, %r9, %r7;
|
||||
sub.s32 %r11, %r8, %r10;
|
||||
cvt.u64.u32 %rd30, %r9;
|
||||
cvt.u64.u32 %rd31, %r11;
|
||||
bra.uni $L__BB0_4;
|
||||
$L__BB0_3:
|
||||
div.u64 %rd30, %rd1, %rd2;
|
||||
mul.lo.s64 %rd14, %rd30, %rd2;
|
||||
sub.s64 %rd31, %rd1, %rd14;
|
||||
$L__BB0_4:
|
||||
mov.u32 %r12, %ctaid.y;
|
||||
cvt.u64.u32 %rd15, %r12;
|
||||
cvt.s64.s32 %rd16, %rd30;
|
||||
mad.lo.s64 %rd17, %rd8, %rd15, %rd16;
|
||||
cvta.to.global.u64 %rd18, %rd5;
|
||||
shl.b64 %rd19, %rd17, 2;
|
||||
add.s64 %rd20, %rd18, %rd19;
|
||||
ld.global.nc.b32 %r13, [%rd20];
|
||||
fma.rn.ftz.f32 %r14, %r1, %r13, 0f00000000;
|
||||
mul.ftz.f32 %r15, %r14, 0fBFB8AA3B;
|
||||
ex2.approx.ftz.f32 %r16, %r15;
|
||||
add.ftz.f32 %r17, %r16, 0f3F800000;
|
||||
rcp.approx.ftz.f32 %r18, %r17;
|
||||
fma.rn.ftz.f32 %r19, %r18, 0f40000000, 0f00000000;
|
||||
cvt.s64.s32 %rd21, %rd31;
|
||||
mad.lo.s64 %rd22, %rd7, %rd15, %rd21;
|
||||
cvta.to.global.u64 %rd23, %rd4;
|
||||
shl.b64 %rd24, %rd22, 2;
|
||||
add.s64 %rd25, %rd23, %rd24;
|
||||
ld.global.nc.b32 %r20, [%rd25];
|
||||
mad.lo.s64 %rd26, %rd6, %rd15, %rd1;
|
||||
cvta.to.global.u64 %rd27, %rd3;
|
||||
shl.b64 %rd28, %rd26, 2;
|
||||
add.s64 %rd29, %rd27, %rd28;
|
||||
ld.global.b32 %r21, [%rd29];
|
||||
fma.rn.ftz.f32 %r22, %r20, %r19, %r21;
|
||||
st.global.b32 [%rd29], %r22;
|
||||
$L__BB0_5:
|
||||
ret;
|
||||
|
||||
}
|
||||
// .globl leleka_verify_head_norm_rows
|
||||
.visible .entry leleka_verify_head_norm_rows(
|
||||
.param .u64 .ptr .align 1 leleka_verify_head_norm_rows_param_0,
|
||||
.param .u64 .ptr .align 1 leleka_verify_head_norm_rows_param_1,
|
||||
.param .u64 .ptr .align 1 leleka_verify_head_norm_rows_param_2,
|
||||
.param .u32 leleka_verify_head_norm_rows_param_3,
|
||||
.param .f32 leleka_verify_head_norm_rows_param_4,
|
||||
.param .u64 leleka_verify_head_norm_rows_param_5,
|
||||
.param .u64 leleka_verify_head_norm_rows_param_6
|
||||
)
|
||||
{
|
||||
.reg .pred %p<26>;
|
||||
.reg .b32 %r<133>;
|
||||
.reg .b64 %rd<54>;
|
||||
// demoted variable
|
||||
.shared .align 4 .b8 _ZZ28leleka_verify_head_norm_rowsE4sums[128];
|
||||
ld.param.b64 %rd8, [leleka_verify_head_norm_rows_param_0];
|
||||
ld.param.b64 %rd9, [leleka_verify_head_norm_rows_param_1];
|
||||
ld.param.b64 %rd10, [leleka_verify_head_norm_rows_param_2];
|
||||
ld.param.b32 %r9, [leleka_verify_head_norm_rows_param_3];
|
||||
ld.param.b32 %r10, [leleka_verify_head_norm_rows_param_4];
|
||||
ld.param.b64 %rd11, [leleka_verify_head_norm_rows_param_5];
|
||||
ld.param.b64 %rd12, [leleka_verify_head_norm_rows_param_6];
|
||||
cvta.to.global.u64 %rd1, %rd10;
|
||||
cvta.to.global.u64 %rd2, %rd9;
|
||||
cvta.to.global.u64 %rd3, %rd8;
|
||||
mov.u32 %r132, %tid.x;
|
||||
mov.u32 %r11, %ctaid.y;
|
||||
cvt.u64.u32 %rd13, %r11;
|
||||
mov.u32 %r12, %ctaid.x;
|
||||
cvt.u64.u32 %rd14, %r12;
|
||||
cvt.s64.s32 %rd15, %r9;
|
||||
mul.lo.s64 %rd4, %rd15, %rd14;
|
||||
mad.lo.s64 %rd5, %rd11, %rd13, %rd4;
|
||||
mul.lo.s64 %rd6, %rd12, %rd13;
|
||||
setp.ge.s32 %p1, %r132, %r9;
|
||||
mov.b32 %r128, 0f00000000;
|
||||
@%p1 bra $L__BB1_11;
|
||||
not.b32 %r13, %r132;
|
||||
add.s32 %r14, %r9, %r13;
|
||||
shr.u32 %r15, %r14, 10;
|
||||
add.s32 %r1, %r15, 1;
|
||||
and.b32 %r2, %r1, 15;
|
||||
setp.lt.u32 %p2, %r14, 15360;
|
||||
mov.b32 %r128, 0f00000000;
|
||||
mov.b32 %r127, %r132;
|
||||
@%p2 bra $L__BB1_5;
|
||||
and.b32 %r16, %r1, 8388592;
|
||||
neg.s32 %r130, %r16;
|
||||
shl.b64 %rd16, %rd5, 2;
|
||||
mul.wide.u32 %rd17, %r132, 4;
|
||||
add.s64 %rd18, %rd16, %rd17;
|
||||
add.s64 %rd19, %rd18, %rd3;
|
||||
add.s64 %rd47, %rd19, 32768;
|
||||
mov.b32 %r128, 0f00000000;
|
||||
mov.b32 %r127, %r132;
|
||||
$L__BB1_3:
|
||||
.pragma "nounroll";
|
||||
ld.global.nc.b32 %r17, [%rd47+-32768];
|
||||
fma.rn.ftz.f32 %r18, %r17, %r17, %r128;
|
||||
ld.global.nc.b32 %r19, [%rd47+-28672];
|
||||
fma.rn.ftz.f32 %r20, %r19, %r19, %r18;
|
||||
ld.global.nc.b32 %r21, [%rd47+-24576];
|
||||
fma.rn.ftz.f32 %r22, %r21, %r21, %r20;
|
||||
ld.global.nc.b32 %r23, [%rd47+-20480];
|
||||
fma.rn.ftz.f32 %r24, %r23, %r23, %r22;
|
||||
ld.global.nc.b32 %r25, [%rd47+-16384];
|
||||
fma.rn.ftz.f32 %r26, %r25, %r25, %r24;
|
||||
ld.global.nc.b32 %r27, [%rd47+-12288];
|
||||
fma.rn.ftz.f32 %r28, %r27, %r27, %r26;
|
||||
ld.global.nc.b32 %r29, [%rd47+-8192];
|
||||
fma.rn.ftz.f32 %r30, %r29, %r29, %r28;
|
||||
ld.global.nc.b32 %r31, [%rd47+-4096];
|
||||
fma.rn.ftz.f32 %r32, %r31, %r31, %r30;
|
||||
ld.global.nc.b32 %r33, [%rd47];
|
||||
fma.rn.ftz.f32 %r34, %r33, %r33, %r32;
|
||||
ld.global.nc.b32 %r35, [%rd47+4096];
|
||||
fma.rn.ftz.f32 %r36, %r35, %r35, %r34;
|
||||
ld.global.nc.b32 %r37, [%rd47+8192];
|
||||
fma.rn.ftz.f32 %r38, %r37, %r37, %r36;
|
||||
ld.global.nc.b32 %r39, [%rd47+12288];
|
||||
fma.rn.ftz.f32 %r40, %r39, %r39, %r38;
|
||||
ld.global.nc.b32 %r41, [%rd47+16384];
|
||||
fma.rn.ftz.f32 %r42, %r41, %r41, %r40;
|
||||
ld.global.nc.b32 %r43, [%rd47+20480];
|
||||
fma.rn.ftz.f32 %r44, %r43, %r43, %r42;
|
||||
ld.global.nc.b32 %r45, [%rd47+24576];
|
||||
fma.rn.ftz.f32 %r46, %r45, %r45, %r44;
|
||||
ld.global.nc.b32 %r47, [%rd47+28672];
|
||||
fma.rn.ftz.f32 %r128, %r47, %r47, %r46;
|
||||
add.s32 %r127, %r127, 16384;
|
||||
add.s32 %r130, %r130, 16;
|
||||
add.s64 %rd47, %rd47, 65536;
|
||||
setp.eq.b32 %p3, %r130, 0;
|
||||
@%p3 bra $L__BB1_4;
|
||||
bra.uni $L__BB1_3;
|
||||
$L__BB1_4:
|
||||
setp.eq.b32 %p4, %r2, 0;
|
||||
@%p4 bra $L__BB1_11;
|
||||
$L__BB1_5:
|
||||
shl.b64 %rd20, %rd5, 2;
|
||||
add.s64 %rd7, %rd3, %rd20;
|
||||
and.b32 %r3, %r1, 7;
|
||||
setp.lt.u32 %p5, %r2, 8;
|
||||
@%p5 bra $L__BB1_7;
|
||||
mul.wide.u32 %rd21, %r127, 4;
|
||||
add.s64 %rd22, %rd7, %rd21;
|
||||
ld.global.nc.b32 %r48, [%rd22];
|
||||
fma.rn.ftz.f32 %r49, %r48, %r48, %r128;
|
||||
ld.global.nc.b32 %r50, [%rd22+4096];
|
||||
fma.rn.ftz.f32 %r51, %r50, %r50, %r49;
|
||||
ld.global.nc.b32 %r52, [%rd22+8192];
|
||||
fma.rn.ftz.f32 %r53, %r52, %r52, %r51;
|
||||
ld.global.nc.b32 %r54, [%rd22+12288];
|
||||
fma.rn.ftz.f32 %r55, %r54, %r54, %r53;
|
||||
ld.global.nc.b32 %r56, [%rd22+16384];
|
||||
fma.rn.ftz.f32 %r57, %r56, %r56, %r55;
|
||||
ld.global.nc.b32 %r58, [%rd22+20480];
|
||||
fma.rn.ftz.f32 %r59, %r58, %r58, %r57;
|
||||
ld.global.nc.b32 %r60, [%rd22+24576];
|
||||
fma.rn.ftz.f32 %r61, %r60, %r60, %r59;
|
||||
ld.global.nc.b32 %r62, [%rd22+28672];
|
||||
fma.rn.ftz.f32 %r128, %r62, %r62, %r61;
|
||||
add.s32 %r127, %r127, 8192;
|
||||
setp.eq.b32 %p6, %r3, 0;
|
||||
@%p6 bra $L__BB1_11;
|
||||
$L__BB1_7:
|
||||
and.b32 %r4, %r1, 3;
|
||||
setp.lt.u32 %p7, %r3, 4;
|
||||
@%p7 bra $L__BB1_9;
|
||||
mul.wide.u32 %rd23, %r127, 4;
|
||||
add.s64 %rd24, %rd7, %rd23;
|
||||
ld.global.nc.b32 %r63, [%rd24];
|
||||
fma.rn.ftz.f32 %r64, %r63, %r63, %r128;
|
||||
ld.global.nc.b32 %r65, [%rd24+4096];
|
||||
fma.rn.ftz.f32 %r66, %r65, %r65, %r64;
|
||||
ld.global.nc.b32 %r67, [%rd24+8192];
|
||||
fma.rn.ftz.f32 %r68, %r67, %r67, %r66;
|
||||
ld.global.nc.b32 %r69, [%rd24+12288];
|
||||
fma.rn.ftz.f32 %r128, %r69, %r69, %r68;
|
||||
add.s32 %r127, %r127, 4096;
|
||||
setp.eq.b32 %p8, %r4, 0;
|
||||
@%p8 bra $L__BB1_11;
|
||||
$L__BB1_9:
|
||||
mul.wide.u32 %rd25, %r127, 4;
|
||||
add.s64 %rd26, %rd20, %rd25;
|
||||
add.s64 %rd46, %rd3, %rd26;
|
||||
neg.s32 %r129, %r4;
|
||||
$L__BB1_10:
|
||||
.pragma "nounroll";
|
||||
ld.global.nc.b32 %r70, [%rd46];
|
||||
fma.rn.ftz.f32 %r128, %r70, %r70, %r128;
|
||||
add.s64 %rd46, %rd46, 4096;
|
||||
add.s32 %r129, %r129, 1;
|
||||
setp.eq.b32 %p9, %r129, 0;
|
||||
@%p9 bra $L__BB1_11;
|
||||
bra.uni $L__BB1_10;
|
||||
$L__BB1_11:
|
||||
shfl.sync.bfly.b32 %r71|%p10, %r128, 16, 31, -1;
|
||||
add.ftz.f32 %r72, %r128, %r71;
|
||||
shfl.sync.bfly.b32 %r73|%p11, %r72, 8, 31, -1;
|
||||
add.ftz.f32 %r74, %r72, %r73;
|
||||
shfl.sync.bfly.b32 %r75|%p12, %r74, 4, 31, -1;
|
||||
add.ftz.f32 %r76, %r74, %r75;
|
||||
shfl.sync.bfly.b32 %r77|%p13, %r76, 2, 31, -1;
|
||||
add.ftz.f32 %r78, %r76, %r77;
|
||||
shfl.sync.bfly.b32 %r79|%p14, %r78, 1, 31, -1;
|
||||
add.ftz.f32 %r5, %r78, %r79;
|
||||
and.b32 %r6, %r132, 31;
|
||||
setp.ne.b32 %p15, %r6, 0;
|
||||
@%p15 bra $L__BB1_13;
|
||||
shr.u32 %r80, %r132, 3;
|
||||
mov.b32 %r81, _ZZ28leleka_verify_head_norm_rowsE4sums;
|
||||
add.s32 %r82, %r81, %r80;
|
||||
st.shared.b32 [%r82], %r5;
|
||||
$L__BB1_13:
|
||||
setp.ge.s32 %p16, %r132, %r9;
|
||||
bar.sync 0;
|
||||
shl.b32 %r83, %r6, 2;
|
||||
mov.b32 %r84, _ZZ28leleka_verify_head_norm_rowsE4sums;
|
||||
add.s32 %r85, %r84, %r83;
|
||||
ld.shared.b32 %r86, [%r85];
|
||||
shfl.sync.bfly.b32 %r87|%p17, %r86, 16, 31, -1;
|
||||
add.ftz.f32 %r88, %r86, %r87;
|
||||
shfl.sync.bfly.b32 %r89|%p18, %r88, 8, 31, -1;
|
||||
add.ftz.f32 %r90, %r88, %r89;
|
||||
shfl.sync.bfly.b32 %r91|%p19, %r90, 4, 31, -1;
|
||||
add.ftz.f32 %r92, %r90, %r91;
|
||||
shfl.sync.bfly.b32 %r93|%p20, %r92, 2, 31, -1;
|
||||
add.ftz.f32 %r94, %r92, %r93;
|
||||
shfl.sync.bfly.b32 %r95|%p21, %r94, 1, 31, -1;
|
||||
add.ftz.f32 %r96, %r94, %r95;
|
||||
cvt.rn.f32.s32 %r97, %r9;
|
||||
div.approx.ftz.f32 %r98, %r96, %r97;
|
||||
add.ftz.f32 %r99, %r10, %r98;
|
||||
rsqrt.approx.ftz.f32 %r7, %r99;
|
||||
@%p16 bra $L__BB1_20;
|
||||
not.b32 %r100, %r132;
|
||||
add.s32 %r8, %r9, %r100;
|
||||
and.b32 %r101, %r8, 3072;
|
||||
setp.eq.b32 %p22, %r101, 3072;
|
||||
@%p22 bra $L__BB1_17;
|
||||
shr.u32 %r102, %r8, 10;
|
||||
add.s32 %r103, %r102, 1;
|
||||
and.b32 %r104, %r103, 3;
|
||||
cvt.u64.u32 %rd27, %r132;
|
||||
add.s64 %rd28, %rd4, %rd27;
|
||||
add.s64 %rd29, %rd28, %rd6;
|
||||
shl.b64 %rd30, %rd29, 2;
|
||||
add.s64 %rd50, %rd1, %rd30;
|
||||
shl.b64 %rd31, %rd28, 2;
|
||||
add.s64 %rd49, %rd2, %rd31;
|
||||
shl.b64 %rd32, %rd5, 2;
|
||||
mul.wide.u32 %rd33, %r132, 4;
|
||||
add.s64 %rd34, %rd32, %rd33;
|
||||
add.s64 %rd48, %rd3, %rd34;
|
||||
neg.s32 %r131, %r104;
|
||||
shl.b32 %r105, %r103, 10;
|
||||
and.b32 %r106, %r105, 3072;
|
||||
or.b32 %r132, %r132, %r106;
|
||||
$L__BB1_16:
|
||||
.pragma "nounroll";
|
||||
ld.global.nc.b32 %r107, [%rd48];
|
||||
mul.ftz.f32 %r108, %r7, %r107;
|
||||
ld.global.nc.b32 %r109, [%rd49];
|
||||
mul.ftz.f32 %r110, %r108, %r109;
|
||||
st.global.b32 [%rd50], %r110;
|
||||
add.s64 %rd50, %rd50, 4096;
|
||||
add.s64 %rd49, %rd49, 4096;
|
||||
add.s64 %rd48, %rd48, 4096;
|
||||
add.s32 %r131, %r131, 1;
|
||||
setp.ne.b32 %p23, %r131, 0;
|
||||
@%p23 bra $L__BB1_16;
|
||||
$L__BB1_17:
|
||||
setp.lt.u32 %p24, %r8, 3072;
|
||||
@%p24 bra $L__BB1_20;
|
||||
shl.b64 %rd35, %rd5, 2;
|
||||
cvt.u64.u32 %rd36, %r132;
|
||||
mul.wide.u32 %rd37, %r132, 4;
|
||||
add.s64 %rd38, %rd35, %rd37;
|
||||
add.s64 %rd39, %rd38, %rd3;
|
||||
add.s64 %rd53, %rd39, 8192;
|
||||
add.s64 %rd40, %rd4, %rd36;
|
||||
shl.b64 %rd41, %rd40, 2;
|
||||
add.s64 %rd42, %rd41, %rd2;
|
||||
add.s64 %rd52, %rd42, 8192;
|
||||
add.s64 %rd43, %rd40, %rd6;
|
||||
shl.b64 %rd44, %rd43, 2;
|
||||
add.s64 %rd45, %rd44, %rd1;
|
||||
add.s64 %rd51, %rd45, 8192;
|
||||
$L__BB1_19:
|
||||
ld.global.nc.b32 %r111, [%rd53+-8192];
|
||||
mul.ftz.f32 %r112, %r7, %r111;
|
||||
ld.global.nc.b32 %r113, [%rd52+-8192];
|
||||
mul.ftz.f32 %r114, %r112, %r113;
|
||||
st.global.b32 [%rd51+-8192], %r114;
|
||||
ld.global.nc.b32 %r115, [%rd53+-4096];
|
||||
mul.ftz.f32 %r116, %r7, %r115;
|
||||
ld.global.nc.b32 %r117, [%rd52+-4096];
|
||||
mul.ftz.f32 %r118, %r116, %r117;
|
||||
st.global.b32 [%rd51+-4096], %r118;
|
||||
ld.global.nc.b32 %r119, [%rd53];
|
||||
mul.ftz.f32 %r120, %r7, %r119;
|
||||
ld.global.nc.b32 %r121, [%rd52];
|
||||
mul.ftz.f32 %r122, %r120, %r121;
|
||||
st.global.b32 [%rd51], %r122;
|
||||
ld.global.nc.b32 %r123, [%rd53+4096];
|
||||
mul.ftz.f32 %r124, %r7, %r123;
|
||||
ld.global.nc.b32 %r125, [%rd52+4096];
|
||||
mul.ftz.f32 %r126, %r124, %r125;
|
||||
st.global.b32 [%rd51+4096], %r126;
|
||||
add.s32 %r132, %r132, 4096;
|
||||
add.s64 %rd53, %rd53, 16384;
|
||||
add.s64 %rd52, %rd52, 16384;
|
||||
add.s64 %rd51, %rd51, 16384;
|
||||
setp.lt.s32 %p25, %r132, %r9;
|
||||
@%p25 bra $L__BB1_19;
|
||||
$L__BB1_20:
|
||||
ret;
|
||||
|
||||
}
|
||||
// .globl leleka_verify_head_pre_final_rows
|
||||
.visible .entry leleka_verify_head_pre_final_rows(
|
||||
.param .u64 .ptr .align 1 leleka_verify_head_pre_final_rows_param_0,
|
||||
.param .u64 .ptr .align 1 leleka_verify_head_pre_final_rows_param_1,
|
||||
.param .u64 .ptr .align 1 leleka_verify_head_pre_final_rows_param_2,
|
||||
.param .u32 leleka_verify_head_pre_final_rows_param_3,
|
||||
.param .u32 leleka_verify_head_pre_final_rows_param_4,
|
||||
.param .f32 leleka_verify_head_pre_final_rows_param_5,
|
||||
.param .u64 leleka_verify_head_pre_final_rows_param_6,
|
||||
.param .u64 leleka_verify_head_pre_final_rows_param_7,
|
||||
.param .u64 leleka_verify_head_pre_final_rows_param_8
|
||||
)
|
||||
{
|
||||
.reg .pred %p<12>;
|
||||
.reg .b32 %r<70>;
|
||||
.reg .b64 %rd<73>;
|
||||
|
||||
ld.param.b64 %rd16, [leleka_verify_head_pre_final_rows_param_0];
|
||||
ld.param.b64 %rd17, [leleka_verify_head_pre_final_rows_param_1];
|
||||
ld.param.s32 %rd9, [leleka_verify_head_pre_final_rows_param_3];
|
||||
ld.param.b32 %r2, [leleka_verify_head_pre_final_rows_param_4];
|
||||
ld.param.b32 %r3, [leleka_verify_head_pre_final_rows_param_5];
|
||||
ld.param.b64 %rd18, [leleka_verify_head_pre_final_rows_param_6];
|
||||
ld.param.b64 %rd19, [leleka_verify_head_pre_final_rows_param_7];
|
||||
ld.param.b64 %rd20, [leleka_verify_head_pre_final_rows_param_8];
|
||||
cvta.to.global.u64 %rd1, %rd17;
|
||||
cvta.to.global.u64 %rd2, %rd16;
|
||||
mov.u32 %r4, %ctaid.y;
|
||||
cvt.u64.u32 %rd21, %r4;
|
||||
mul.lo.s64 %rd3, %rd18, %rd21;
|
||||
mul.lo.s64 %rd4, %rd19, %rd21;
|
||||
mul.lo.s64 %rd5, %rd20, %rd21;
|
||||
mov.u32 %r5, %ctaid.x;
|
||||
mov.u32 %r6, %ntid.x;
|
||||
mul.wide.u32 %rd6, %r5, %r6;
|
||||
mov.u32 %r7, %tid.x;
|
||||
cvt.u64.u32 %rd7, %r7;
|
||||
add.s64 %rd8, %rd6, %rd7;
|
||||
setp.ge.u64 %p1, %rd8, %rd9;
|
||||
@%p1 bra $L__BB2_10;
|
||||
setp.lt.s32 %p2, %r2, 1;
|
||||
mov.b32 %r69, 0f00000000;
|
||||
@%p2 bra $L__BB2_9;
|
||||
and.b32 %r1, %r2, 3;
|
||||
setp.lt.u32 %p3, %r2, 4;
|
||||
mov.b32 %r69, 0f00000000;
|
||||
mov.b32 %r68, 0;
|
||||
@%p3 bra $L__BB2_6;
|
||||
shl.b64 %rd22, %rd4, 2;
|
||||
shl.b64 %rd23, %rd9, 2;
|
||||
add.s64 %rd24, %rd22, %rd23;
|
||||
add.s64 %rd10, %rd1, %rd24;
|
||||
shl.b64 %rd25, %rd6, 2;
|
||||
shl.b64 %rd26, %rd7, 2;
|
||||
add.s64 %rd72, %rd25, %rd26;
|
||||
shl.b64 %rd27, %rd9, 3;
|
||||
add.s64 %rd28, %rd22, %rd27;
|
||||
add.s64 %rd11, %rd1, %rd28;
|
||||
mul.lo.s64 %rd29, %rd9, 12;
|
||||
add.s64 %rd30, %rd22, %rd29;
|
||||
add.s64 %rd12, %rd1, %rd30;
|
||||
shl.b64 %rd31, %rd3, 2;
|
||||
add.s64 %rd32, %rd31, %rd23;
|
||||
add.s64 %rd13, %rd2, %rd32;
|
||||
add.s64 %rd33, %rd31, %rd27;
|
||||
add.s64 %rd14, %rd2, %rd33;
|
||||
add.s64 %rd34, %rd31, %rd29;
|
||||
add.s64 %rd15, %rd2, %rd34;
|
||||
and.b32 %r8, %r2, 2147483644;
|
||||
neg.s32 %r67, %r8;
|
||||
mov.b32 %r69, 0f00000000;
|
||||
mov.b32 %r68, 0;
|
||||
$L__BB2_4:
|
||||
.pragma "nounroll";
|
||||
shl.b64 %rd35, %rd3, 2;
|
||||
add.s64 %rd36, %rd2, %rd35;
|
||||
add.s64 %rd37, %rd36, %rd72;
|
||||
ld.global.nc.b32 %r9, [%rd37];
|
||||
shl.b64 %rd38, %rd4, 2;
|
||||
add.s64 %rd39, %rd1, %rd38;
|
||||
add.s64 %rd40, %rd39, %rd72;
|
||||
ld.global.b32 %r10, [%rd40];
|
||||
mul.ftz.f32 %r11, %r10, 0fBFB8AA3B;
|
||||
ex2.approx.ftz.f32 %r12, %r11;
|
||||
add.ftz.f32 %r13, %r12, 0f3F800000;
|
||||
rcp.approx.ftz.f32 %r14, %r13;
|
||||
mul.rn.ftz.f32 %r15, %r9, %r14;
|
||||
st.global.b32 [%rd40], %r15;
|
||||
setp.eq.b32 %p4, %r68, 0;
|
||||
add.rn.ftz.f32 %r16, %r69, %r15;
|
||||
selp.f32 %r17, %r15, %r16, %p4;
|
||||
add.s64 %rd41, %rd13, %rd72;
|
||||
ld.global.nc.b32 %r18, [%rd41];
|
||||
add.s64 %rd42, %rd10, %rd72;
|
||||
ld.global.b32 %r19, [%rd42];
|
||||
mul.ftz.f32 %r20, %r19, 0fBFB8AA3B;
|
||||
ex2.approx.ftz.f32 %r21, %r20;
|
||||
add.ftz.f32 %r22, %r21, 0f3F800000;
|
||||
rcp.approx.ftz.f32 %r23, %r22;
|
||||
mul.rn.ftz.f32 %r24, %r18, %r23;
|
||||
st.global.b32 [%rd42], %r24;
|
||||
add.rn.ftz.f32 %r25, %r17, %r24;
|
||||
add.s64 %rd43, %rd14, %rd72;
|
||||
ld.global.nc.b32 %r26, [%rd43];
|
||||
add.s64 %rd44, %rd11, %rd72;
|
||||
ld.global.b32 %r27, [%rd44];
|
||||
mul.ftz.f32 %r28, %r27, 0fBFB8AA3B;
|
||||
ex2.approx.ftz.f32 %r29, %r28;
|
||||
add.ftz.f32 %r30, %r29, 0f3F800000;
|
||||
rcp.approx.ftz.f32 %r31, %r30;
|
||||
mul.rn.ftz.f32 %r32, %r26, %r31;
|
||||
st.global.b32 [%rd44], %r32;
|
||||
add.rn.ftz.f32 %r33, %r25, %r32;
|
||||
add.s64 %rd45, %rd15, %rd72;
|
||||
ld.global.nc.b32 %r34, [%rd45];
|
||||
add.s64 %rd46, %rd12, %rd72;
|
||||
ld.global.b32 %r35, [%rd46];
|
||||
mul.ftz.f32 %r36, %r35, 0fBFB8AA3B;
|
||||
ex2.approx.ftz.f32 %r37, %r36;
|
||||
add.ftz.f32 %r38, %r37, 0f3F800000;
|
||||
rcp.approx.ftz.f32 %r39, %r38;
|
||||
mul.rn.ftz.f32 %r40, %r34, %r39;
|
||||
st.global.b32 [%rd46], %r40;
|
||||
add.rn.ftz.f32 %r69, %r33, %r40;
|
||||
add.s32 %r68, %r68, 4;
|
||||
shl.b64 %rd47, %rd9, 4;
|
||||
add.s64 %rd72, %rd72, %rd47;
|
||||
add.s32 %r67, %r67, 4;
|
||||
setp.ne.b32 %p5, %r67, 0;
|
||||
@%p5 bra $L__BB2_4;
|
||||
setp.eq.b32 %p6, %r1, 0;
|
||||
@%p6 bra $L__BB2_9;
|
||||
$L__BB2_6:
|
||||
setp.eq.b32 %p7, %r1, 1;
|
||||
@%p7 bra $L__BB2_8;
|
||||
cvt.u64.u32 %rd48, %r68;
|
||||
mad.lo.s64 %rd49, %rd48, %rd9, %rd8;
|
||||
add.s64 %rd50, %rd49, %rd3;
|
||||
shl.b64 %rd51, %rd50, 2;
|
||||
add.s64 %rd52, %rd2, %rd51;
|
||||
ld.global.nc.b32 %r41, [%rd52];
|
||||
add.s64 %rd53, %rd49, %rd4;
|
||||
shl.b64 %rd54, %rd53, 2;
|
||||
add.s64 %rd55, %rd1, %rd54;
|
||||
ld.global.b32 %r42, [%rd55];
|
||||
mul.ftz.f32 %r43, %r42, 0fBFB8AA3B;
|
||||
ex2.approx.ftz.f32 %r44, %r43;
|
||||
add.ftz.f32 %r45, %r44, 0f3F800000;
|
||||
rcp.approx.ftz.f32 %r46, %r45;
|
||||
mul.rn.ftz.f32 %r47, %r41, %r46;
|
||||
st.global.b32 [%rd55], %r47;
|
||||
setp.eq.b32 %p8, %r68, 0;
|
||||
add.rn.ftz.f32 %r48, %r69, %r47;
|
||||
selp.f32 %r49, %r47, %r48, %p8;
|
||||
shl.b64 %rd56, %rd9, 2;
|
||||
add.s64 %rd57, %rd52, %rd56;
|
||||
ld.global.nc.b32 %r50, [%rd57];
|
||||
add.s64 %rd58, %rd55, %rd56;
|
||||
ld.global.b32 %r51, [%rd58];
|
||||
mul.ftz.f32 %r52, %r51, 0fBFB8AA3B;
|
||||
ex2.approx.ftz.f32 %r53, %r52;
|
||||
add.ftz.f32 %r54, %r53, 0f3F800000;
|
||||
rcp.approx.ftz.f32 %r55, %r54;
|
||||
mul.rn.ftz.f32 %r56, %r50, %r55;
|
||||
st.global.b32 [%rd58], %r56;
|
||||
add.rn.ftz.f32 %r69, %r49, %r56;
|
||||
add.s32 %r68, %r68, 2;
|
||||
and.b32 %r57, %r2, 1;
|
||||
setp.ne.b32 %p9, %r57, 0;
|
||||
not.pred %p10, %p9;
|
||||
@%p10 bra $L__BB2_9;
|
||||
$L__BB2_8:
|
||||
cvt.u64.u32 %rd59, %r68;
|
||||
mad.lo.s64 %rd60, %rd59, %rd9, %rd8;
|
||||
add.s64 %rd61, %rd60, %rd3;
|
||||
shl.b64 %rd62, %rd61, 2;
|
||||
add.s64 %rd63, %rd2, %rd62;
|
||||
ld.global.nc.b32 %r58, [%rd63];
|
||||
add.s64 %rd64, %rd60, %rd4;
|
||||
shl.b64 %rd65, %rd64, 2;
|
||||
add.s64 %rd66, %rd1, %rd65;
|
||||
ld.global.b32 %r59, [%rd66];
|
||||
mul.ftz.f32 %r60, %r59, 0fBFB8AA3B;
|
||||
ex2.approx.ftz.f32 %r61, %r60;
|
||||
add.ftz.f32 %r62, %r61, 0f3F800000;
|
||||
rcp.approx.ftz.f32 %r63, %r62;
|
||||
mul.rn.ftz.f32 %r64, %r58, %r63;
|
||||
st.global.b32 [%rd66], %r64;
|
||||
setp.eq.b32 %p11, %r68, 0;
|
||||
add.rn.ftz.f32 %r65, %r69, %r64;
|
||||
selp.f32 %r69, %r64, %r65, %p11;
|
||||
$L__BB2_9:
|
||||
ld.param.b64 %rd71, [leleka_verify_head_pre_final_rows_param_2];
|
||||
fma.rn.ftz.f32 %r66, %r3, %r69, 0f00000000;
|
||||
add.s64 %rd67, %rd5, %rd8;
|
||||
cvta.to.global.u64 %rd68, %rd71;
|
||||
shl.b64 %rd69, %rd67, 2;
|
||||
add.s64 %rd70, %rd68, %rd69;
|
||||
st.global.b32 [%rd70], %r66;
|
||||
$L__BB2_10:
|
||||
ret;
|
||||
|
||||
}
|
||||
@@ -170,6 +170,14 @@ pub(in crate::qwen_forward) struct CpuExpertPool<'a> {
|
||||
direct: Option<DirectTier>,
|
||||
legacy: Option<CpuMissWorkspace>,
|
||||
crosscheck: CrosscheckCounts,
|
||||
/// What the last direct group spent in the worker pool (read by the PCIe share controller).
|
||||
last_group: ComputeSample,
|
||||
}
|
||||
/// The worker pool's wall time in one group and the distinct experts it computed (Strata's `ms_run` / `multi_misses`).
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub(in crate::qwen_forward) struct ComputeSample {
|
||||
pub(in crate::qwen_forward) elapsed: std::time::Duration,
|
||||
pub(in crate::qwen_forward) experts: usize,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct CrosscheckCounts {
|
||||
@@ -199,7 +207,7 @@ use prefetch_off_file_exists::same_spans;
|
||||
#[allow(unused_imports)]
|
||||
pub(in crate::qwen_forward) use prefetch_off_file_exists::scatter;
|
||||
mod direct_parts;
|
||||
use direct_parts::{borrow_experts, compute_into_sink, group_formats, plan_expert_ids, prefetch_group};
|
||||
use direct_parts::{GroupWork, borrow_experts, compute_into_sink, group_formats, plan_expert_ids, prefetch_group};
|
||||
mod cpu_expert_pool;
|
||||
mod direct_tier;
|
||||
mod direct_tier_drop;
|
||||
|
||||
@@ -81,7 +81,9 @@ impl CpuExpertPool<'_> {
|
||||
window_trace::add(window_trace::PREPARE, -group.fetch_ms);
|
||||
window_trace::add(window_trace::FETCH, group.fetch_ms);
|
||||
let sink_span = super::super::original_serve_profile::span("cpu.sink");
|
||||
let (written, failure) = compute_into_sink(&mut tier.pool, sink, rows, include, (&experts, formats));
|
||||
let work = GroupWork { experts: &experts, formats, opened_at: group.started };
|
||||
let (written, failure, pool_time) = compute_into_sink(&mut tier.pool, sink, rows, include, work);
|
||||
self.last_group = ComputeSample { elapsed: pool_time, experts: plan.len() };
|
||||
window_trace::lap(window_trace::JOIN, clock);
|
||||
drop(sink_span);
|
||||
let record = (group.any_mapped && failure.is_none() && !plan.is_empty()).then_some(group.use_pass);
|
||||
@@ -89,6 +91,11 @@ impl CpuExpertPool<'_> {
|
||||
sink_result(written, failure)
|
||||
}
|
||||
|
||||
/// The worker pool's time and expert count of the last direct group (zero before one ran).
|
||||
pub(in crate::qwen_forward) fn last_group_sample(&self) -> ComputeSample {
|
||||
self.last_group
|
||||
}
|
||||
|
||||
/// The VRAM tier tells the router lookahead which experts of `layer` it holds (before each group).
|
||||
pub(in crate::qwen_forward) fn set_next_resident(&mut self, resident: impl Fn(usize) -> bool) {
|
||||
if let Some(tier) = self.direct.as_mut().filter(|t| t.lookahead.is_some()) {
|
||||
|
||||
@@ -62,18 +62,26 @@ pub(super) fn borrow_experts<'p>(plan: &'p [ExpertJob], opened: &'p [Opened]) ->
|
||||
Ok(experts)
|
||||
}
|
||||
|
||||
/// Zero the entries the GPU tier owns and compute the rest of the group in place; the sink's result and the failure it
|
||||
/// saw.
|
||||
/// One group's work for the worker pool: its experts, their one format, and the instant the group was opened (the
|
||||
/// clock the pool's time is read from).
|
||||
pub(super) struct GroupWork<'e, 'b> {
|
||||
pub(super) experts: &'e [BorrowedExpert<'b>],
|
||||
pub(super) formats: Option<(GateUpFormat, DownFormat)>,
|
||||
pub(super) opened_at: std::time::Instant,
|
||||
}
|
||||
|
||||
/// Zero the entries the GPU tier owns and compute the rest of the group in place; the sink's result, the failure it
|
||||
/// saw and the wall time of the worker pool's dispatch (without the zeroing).
|
||||
pub(super) fn compute_into_sink(
|
||||
pool: &mut DirectCpuPool,
|
||||
sink: &mut OriginalVerifyCpuSink<'_, '_>,
|
||||
rows: &OriginalVerifyCpuRows<'_>,
|
||||
include: Option<&[bool]>,
|
||||
work: (&[BorrowedExpert<'_>], Option<(GateUpFormat, DownFormat)>),
|
||||
) -> (leleka_cuda_driver::Result<()>, Option<Error>) {
|
||||
let (experts, formats) = work;
|
||||
work: GroupWork<'_, '_>,
|
||||
) -> (leleka_cuda_driver::Result<()>, Option<Error>, std::time::Duration) {
|
||||
let count = rows.ids.len() / TOP_K;
|
||||
let mut failure = None;
|
||||
let mut pool_time = std::time::Duration::ZERO;
|
||||
let written = sink.with_output(|out| {
|
||||
if out.len() != count * TOP_K * HIDDEN {
|
||||
failure = Some(Error::InvalidDimension);
|
||||
@@ -83,15 +91,27 @@ pub(super) fn compute_into_sink(
|
||||
zero_unselected(out, include);
|
||||
drop(zero_span);
|
||||
let _compute_span = super::super::original_serve_profile::span("cpu.compute");
|
||||
if let Some(formats) = formats {
|
||||
if let Err(error) = compute_chunks(pool, (rows, experts), formats, out) {
|
||||
failure = Some(error);
|
||||
return Err(leleka_cuda_driver::Error::InvalidQwenShape);
|
||||
}
|
||||
let (computed, took) = compute_timed(pool, (rows, &work), out);
|
||||
pool_time = took;
|
||||
if let Err(error) = computed {
|
||||
failure = Some(error);
|
||||
return Err(leleka_cuda_driver::Error::InvalidQwenShape);
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
(written, failure)
|
||||
(written, failure, pool_time)
|
||||
}
|
||||
|
||||
/// `compute_chunks` over the group's experts and the wall time it took (zero when the group holds none).
|
||||
fn compute_timed(
|
||||
pool: &mut DirectCpuPool,
|
||||
(rows, work): (&OriginalVerifyCpuRows<'_>, &GroupWork<'_, '_>),
|
||||
out: &mut [f32],
|
||||
) -> (std::result::Result<(), Error>, std::time::Duration) {
|
||||
let Some(formats) = work.formats else { return (Ok(()), std::time::Duration::ZERO) };
|
||||
let before = work.opened_at.elapsed();
|
||||
let computed = compute_chunks(pool, (rows, work.experts), formats, out);
|
||||
(computed, work.opened_at.elapsed().saturating_sub(before))
|
||||
}
|
||||
|
||||
/// The entries the GPU tier owns (`include` false) read as zeros.
|
||||
|
||||
@@ -331,7 +331,8 @@ impl<'a> CpuExpertPool<'a> {
|
||||
if path != PoolPath::Direct {
|
||||
eprintln!("leleka-serve cpu expert pool: {path:?} path (LELEKA_CPU_POOL)");
|
||||
}
|
||||
Ok(Self { binding, direct, legacy, crosscheck: CrosscheckCounts::default() })
|
||||
let (crosscheck, last_group) = (CrosscheckCounts::default(), ComputeSample::default());
|
||||
Ok(Self { binding, direct, legacy, crosscheck, last_group })
|
||||
}
|
||||
}
|
||||
impl<'ctx> OriginalServePool<'ctx> for CpuExpertPool<'_> {
|
||||
|
||||
@@ -96,6 +96,11 @@ pub(crate) struct ExpertTierConfig {
|
||||
pub(crate) pcie_frac_set: bool,
|
||||
/// `--pcie-mode` (auto).
|
||||
pub(crate) pcie_mode: PcieMode,
|
||||
/// EXPERIMENTAL, opt-in (`LELEKA_ORIGINAL_SERVE_PCIE_AUTO=on`, default `None` = off; placement class): Strata's
|
||||
/// `PcieAuto` moves the PCIe share from the CPU pool's measured speed after the first decode windows, with
|
||||
/// `pcie_frac` as its start value. `Some(link GB/s)` (`_PCIE_LINK_GBPS`, default 47.5) is the host-to-device
|
||||
/// bandwidth it balances the pool against. See `strata_pcie_auto`.
|
||||
pub(crate) strata_pcie_auto: Option<f64>,
|
||||
/// `--adapt-every` (4) and `--adapt-swaps` (96); either 0 turns the adaptive tier off.
|
||||
pub(crate) adapt_every: u32,
|
||||
pub(crate) adapt_swaps: u32,
|
||||
@@ -237,6 +242,10 @@ pub(crate) struct ResidencyState {
|
||||
pub(crate) spans: SpanCache,
|
||||
pub(crate) pcie_auto: Option<PcieAuto>,
|
||||
pub(crate) pcie_lag: Option<PcieLag>,
|
||||
/// `LELEKA_ORIGINAL_SERVE_PCIE_AUTO`: the link bandwidth when the switch is on, and the controller started from it
|
||||
/// at the first round (`start_strata_pcie_auto`).
|
||||
strata_pcie_link_gbps: Option<f64>,
|
||||
pub(crate) strata_pcie_auto: Option<StrataPcieAuto>,
|
||||
pcie_auto_checked: bool,
|
||||
}
|
||||
|
||||
@@ -296,6 +305,11 @@ pub(in crate::qwen_forward) use split_group_pcie::{PcieSplitPolicy, RoutedGroup}
|
||||
mod cross_layer_potential;
|
||||
mod swap_tie_order;
|
||||
pub(in crate::qwen_forward) use swap_tie_order::TieOrder;
|
||||
mod strata_pcie_auto;
|
||||
use strata_pcie_auto::StrataPcieAuto;
|
||||
mod strata_pcie_auto_glue;
|
||||
#[cfg(test)]
|
||||
mod strata_pcie_auto_tests;
|
||||
mod span_cache_and_pcie_lag;
|
||||
#[allow(unused_imports)]
|
||||
use span_cache_and_pcie_lag::span_cache_enabled;
|
||||
|
||||
+11
-5
@@ -82,6 +82,7 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> {
|
||||
let ran = self.cpu.run_entries(rows, sink, Some(&include));
|
||||
if ran.is_ok() {
|
||||
self.measure_pcie_lag(sink, &split);
|
||||
self.note_cpu_pool_work();
|
||||
}
|
||||
ran
|
||||
}
|
||||
@@ -90,6 +91,7 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> {
|
||||
self.state.pcie_auto_checked = true;
|
||||
self.state.pcie_auto = PcieAuto::from_environment(self.pcie_num);
|
||||
self.state.pcie_lag = PcieLag::from_environment(self.pcie_num);
|
||||
self.start_strata_pcie_auto();
|
||||
}
|
||||
if let Some(auto) = self.state.pcie_auto.as_mut() {
|
||||
auto.round();
|
||||
@@ -97,6 +99,7 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> {
|
||||
if let Some(lag) = self.state.pcie_lag.as_mut() {
|
||||
lag.round();
|
||||
}
|
||||
self.end_strata_pcie_round();
|
||||
// The swaps issued beside the previous commit land before this window (`apply_pending(true)`): their copies
|
||||
// would otherwise read host memory while the CPU pool streams its experts (job 803: the overlap costs the CPU
|
||||
// share more than the wait), and the resident set no longer depends on when the copies finished.
|
||||
@@ -184,13 +187,16 @@ impl<'ctx> GpuExpertPool<'_, '_, 'ctx> {
|
||||
drop(profile_split);
|
||||
Ok(split)
|
||||
}
|
||||
/// The PCIe share in 256ths: the lag controller's, else the auto controller's, else the configured one.
|
||||
/// The PCIe share in 256ths: Strata's `PcieAuto` (`LELEKA_ORIGINAL_SERVE_PCIE_AUTO`), else the lag controller's,
|
||||
/// else the hill climber's, else the configured one.
|
||||
fn current_pcie_num(&self) -> u32 {
|
||||
self.state
|
||||
.pcie_lag
|
||||
let state = &*self.state;
|
||||
state
|
||||
.strata_pcie_auto
|
||||
.as_ref()
|
||||
.map(PcieLag::pcie_num)
|
||||
.or_else(|| self.state.pcie_auto.as_ref().map(PcieAuto::pcie_num))
|
||||
.map(StrataPcieAuto::pcie_num)
|
||||
.or_else(|| state.pcie_lag.as_ref().map(PcieLag::pcie_num))
|
||||
.or_else(|| state.pcie_auto.as_ref().map(PcieAuto::pcie_num))
|
||||
.unwrap_or(self.pcie_num)
|
||||
}
|
||||
fn fetch_pcie_spans(
|
||||
|
||||
+2
@@ -159,6 +159,8 @@ impl ResidencyState {
|
||||
routing,
|
||||
pcie_auto: None,
|
||||
pcie_lag: None,
|
||||
strata_pcie_link_gbps: config.strata_pcie_auto,
|
||||
strata_pcie_auto: None,
|
||||
pcie_auto_checked: false,
|
||||
marks: Vec::new(),
|
||||
mark_base: [0; 3],
|
||||
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
//! Strata's `PcieAuto` (generate.cpp `struct PcieAuto`, 0.2.6) as a pure policy: no clock, no device, no environment.
|
||||
//!
|
||||
//! What it decides: the PCIe share of a group's missed experts (the rest of the misses run on the CPU pool). The
|
||||
//! balance share is `link / (link + 1.85 x pool rate)`: `link` is the host-to-device bandwidth, the pool rate is the
|
||||
//! routed-expert bytes over the pool's wall time per CPU-computed expert. The policy reads that pool time over a
|
||||
//! window of decode rounds and moves the share to the balance, rounded to steps of 0.05 and kept inside 0.10..0.60.
|
||||
//! At most three updates are made (after 48, then 96 and 96 more rounds), then the share stays where it is; a
|
||||
//! reading of fewer than 300 CPU experts is not enough and the policy looks again (it gives up after 2000 rounds).
|
||||
//! A new share must differ from the current one by 0.025 or more to be taken.
|
||||
//!
|
||||
//! Opt-in `LELEKA_ORIGINAL_SERVE_PCIE_AUTO`. The share decides which misses a CPU computes and which a GPU computes,
|
||||
//! and the two round differently (docs/original-serve.md), so this is a placement-class change.
|
||||
|
||||
/// Strata's `PcieAuto::kPoolFactor`: how many times the CPU pool's byte rate the balance counts for.
|
||||
pub(crate) const POOL_FACTOR: f64 = 1.85;
|
||||
/// Rounds in the first window, and in each later one.
|
||||
pub(crate) const FIRST_WINDOW_ROUNDS: u32 = 48;
|
||||
pub(crate) const LATER_WINDOW_ROUNDS: u32 = 96;
|
||||
/// Fewest CPU-computed experts a window must hold for its pool time to be read.
|
||||
pub(crate) const MIN_WINDOW_EXPERTS: u64 = 300;
|
||||
/// A window that never holds enough experts stops the policy after this many rounds.
|
||||
pub(crate) const GIVE_UP_ROUNDS: u32 = 2000;
|
||||
/// Updates made at most.
|
||||
pub(crate) const MAX_UPDATES: u32 = 3;
|
||||
/// The share is kept inside these bounds and on steps of `1 / SHARE_STEPS_PER_UNIT`.
|
||||
pub(crate) const MIN_SHARE: f64 = 0.10;
|
||||
pub(crate) const MAX_SHARE: f64 = 0.60;
|
||||
const SHARE_STEPS_PER_UNIT: f64 = 20.0;
|
||||
/// A share closer than this to the current one is left alone.
|
||||
pub(crate) const DEAD_BAND: f64 = 0.025;
|
||||
/// Host-to-device bandwidth Strata's start-up probe read on the RTX 5090 server (parity-audit-5090.md, row 5).
|
||||
pub(crate) const DEFAULT_LINK_GBPS: f64 = 47.5;
|
||||
|
||||
/// What the policy needs to know about the machine, fixed for the life of the process.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct PcieAutoInputs {
|
||||
/// Host-to-device bandwidth in GB/s (Strata probes it at start-up; here it is configured).
|
||||
pub(crate) link_gbps: f64,
|
||||
/// Mean routed-expert blob size over the layers, in bytes.
|
||||
pub(crate) blob_bytes: f64,
|
||||
}
|
||||
|
||||
/// What the CPU pool did: wall microseconds spent computing, and the distinct experts it computed.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub(crate) struct PoolWork {
|
||||
pub(crate) micros: f64,
|
||||
pub(crate) experts: u64,
|
||||
}
|
||||
|
||||
impl PoolWork {
|
||||
fn add(&mut self, other: PoolWork) {
|
||||
self.micros += other.micros;
|
||||
self.experts += other.experts;
|
||||
}
|
||||
}
|
||||
|
||||
/// A new share and the reading it came from (for the operator line).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct ShareChange {
|
||||
pub(crate) pcie_num: u32,
|
||||
pub(crate) fraction: f64,
|
||||
pub(crate) micros_per_expert: f64,
|
||||
pub(crate) pool_gbps: f64,
|
||||
}
|
||||
|
||||
/// The controller: the current share in 256ths and the pool time read so far.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct StrataPcieAuto {
|
||||
inputs: PcieAutoInputs,
|
||||
pcie_num: u32,
|
||||
live: bool,
|
||||
round: Option<PoolWork>,
|
||||
window: PoolWork,
|
||||
rounds: u32,
|
||||
updates: u32,
|
||||
}
|
||||
|
||||
/// `pcie_num = clamp(round(share * 256), 0, 256)`, as `ExpertTierConfig::pcie_num`.
|
||||
fn num_of(share: f64) -> u32 {
|
||||
(share * 256.0 + 0.5).clamp(0.0, 256.0) as u32
|
||||
}
|
||||
|
||||
/// The balance share for a link and a pool rate, on the 0.05 grid inside the bounds.
|
||||
pub(crate) fn balanced_share(link_gbps: f64, pool_gbps: f64) -> f64 {
|
||||
let balance = link_gbps / (link_gbps + POOL_FACTOR * pool_gbps);
|
||||
((balance * SHARE_STEPS_PER_UNIT).round() / SHARE_STEPS_PER_UNIT).clamp(MIN_SHARE, MAX_SHARE)
|
||||
}
|
||||
|
||||
impl StrataPcieAuto {
|
||||
pub(crate) fn new(inputs: PcieAutoInputs, start_num: u32) -> Self {
|
||||
Self {
|
||||
inputs,
|
||||
pcie_num: start_num,
|
||||
live: true,
|
||||
round: None,
|
||||
window: PoolWork::default(),
|
||||
rounds: 0,
|
||||
updates: 0,
|
||||
}
|
||||
}
|
||||
/// The PCIe share in 256ths the next group is split with.
|
||||
pub(crate) fn pcie_num(&self) -> u32 {
|
||||
self.pcie_num
|
||||
}
|
||||
/// Whether the policy can still move the share.
|
||||
pub(crate) fn live(&self) -> bool {
|
||||
self.live
|
||||
}
|
||||
/// One group's CPU work (the pool's wall time and experts), added to the round that is running.
|
||||
pub(crate) fn note_group(&mut self, work: PoolWork) {
|
||||
if self.live {
|
||||
self.round.get_or_insert_with(PoolWork::default).add(work);
|
||||
}
|
||||
}
|
||||
/// A round boundary: the round that ended joins the window; at the window's size the share may move. A round in
|
||||
/// which the pool ran no group (the boundary before a request's first round) is not a round.
|
||||
pub(crate) fn end_round(&mut self) -> Option<ShareChange> {
|
||||
let work = self.round.take()?;
|
||||
self.window.add(work);
|
||||
self.rounds += 1;
|
||||
let needed = if self.updates == 0 { FIRST_WINDOW_ROUNDS } else { LATER_WINDOW_ROUNDS };
|
||||
if self.rounds < needed {
|
||||
return None;
|
||||
}
|
||||
if self.window.experts < MIN_WINDOW_EXPERTS {
|
||||
self.live = self.rounds < GIVE_UP_ROUNDS;
|
||||
return None;
|
||||
}
|
||||
let read = std::mem::take(&mut self.window);
|
||||
self.rounds = 0;
|
||||
self.updates += 1;
|
||||
self.live = self.updates < MAX_UPDATES;
|
||||
self.retarget(read)
|
||||
}
|
||||
fn retarget(&mut self, read: PoolWork) -> Option<ShareChange> {
|
||||
let PcieAutoInputs { link_gbps, blob_bytes } = self.inputs;
|
||||
let micros_per_expert = read.micros / read.experts as f64;
|
||||
let readable = micros_per_expert > 1.0 && blob_bytes > 0.0 && link_gbps > 0.0;
|
||||
if !readable {
|
||||
return None;
|
||||
}
|
||||
let pool_gbps = blob_bytes / (micros_per_expert * 1e-6) / 1e9;
|
||||
let fraction = balanced_share(link_gbps, pool_gbps);
|
||||
if (fraction - f64::from(self.pcie_num) / 256.0).abs() < DEAD_BAND {
|
||||
return None;
|
||||
}
|
||||
self.pcie_num = num_of(fraction);
|
||||
Some(ShareChange { pcie_num: self.pcie_num, fraction, micros_per_expert, pool_gbps })
|
||||
}
|
||||
}
|
||||
|
||||
impl ShareChange {
|
||||
/// The operator line of an update: what the pool took, what the link is, the share it was and the share it is.
|
||||
pub(crate) fn operator_line(&self, (was_num, link_gbps): (u32, f64), last: bool) -> String {
|
||||
format!(
|
||||
"leleka-serve PCIe share (LELEKA_ORIGINAL_SERVE_PCIE_AUTO): the CPU pool takes {:.0} us per computed \
|
||||
expert ({:.1} GB/s of expert bytes), the link {:.1} GB/s -> pcie_frac {:.2} (pcie_num {} -> {}, was \
|
||||
{:.2}){}",
|
||||
self.micros_per_expert,
|
||||
self.pool_gbps,
|
||||
link_gbps,
|
||||
self.fraction,
|
||||
was_num,
|
||||
self.pcie_num,
|
||||
f64::from(was_num) / 256.0,
|
||||
if last { "; last update" } else { "" },
|
||||
)
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
//! `StrataPcieAuto` on the window pool (`LELEKA_ORIGINAL_SERVE_PCIE_AUTO`): started at the first round, fed with the
|
||||
//! CPU pool's time after every group, moved at the round boundary. The policy is `strata_pcie_auto`; nothing here
|
||||
//! runs with the switch off.
|
||||
|
||||
use super::super::original_serve_config::ExpertBlobSizes;
|
||||
use super::strata_pcie_auto::{PcieAutoInputs, PoolWork};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The mean routed-expert blob size over the layers (Strata: the sum of `blob_bytes(l)` over `n_layers`); 0 when the
|
||||
/// layout cannot be read.
|
||||
fn mean_blob_bytes(binding: &ModelBinding) -> f64 {
|
||||
let Ok(blobs) = ExpertBlobSizes::from_binding(binding) else { return 0.0 };
|
||||
let total: usize = (0..LAYERS).filter_map(|layer| blobs.blob_bytes(layer)).sum();
|
||||
total as f64 / LAYERS as f64
|
||||
}
|
||||
|
||||
impl GpuExpertPool<'_, '_, '_> {
|
||||
/// Once, at the first round: the controller, when the switch is on and the tier stages anything over PCIe.
|
||||
pub(super) fn start_strata_pcie_auto(&mut self) {
|
||||
let Some(link_gbps) = self.state.strata_pcie_link_gbps else { return };
|
||||
if self.pcie_num == 0 {
|
||||
eprintln!("leleka-serve PCIe share: PCIE_AUTO is on but the tier stages nothing over PCIe (pcie_num 0)");
|
||||
return;
|
||||
}
|
||||
let inputs = PcieAutoInputs { link_gbps, blob_bytes: mean_blob_bytes(self.binding) };
|
||||
eprintln!(
|
||||
"leleka-serve PCIe share: LELEKA_ORIGINAL_SERVE_PCIE_AUTO on, start pcie_frac {:.2} (pcie_num {}), \
|
||||
link {:.1} GB/s, expert blob {:.0} bytes (mean); first update after {} decode rounds",
|
||||
f64::from(self.pcie_num) / 256.0,
|
||||
self.pcie_num,
|
||||
inputs.link_gbps,
|
||||
inputs.blob_bytes,
|
||||
strata_pcie_auto::FIRST_WINDOW_ROUNDS,
|
||||
);
|
||||
if self.state.pcie_lag.is_some() || self.state.pcie_auto.is_some() {
|
||||
eprintln!("leleka-serve PCIe share: LELEKA_PCIE_AUTO is shadowed by LELEKA_ORIGINAL_SERVE_PCIE_AUTO");
|
||||
}
|
||||
self.state.strata_pcie_auto = Some(StrataPcieAuto::new(inputs, self.pcie_num));
|
||||
}
|
||||
/// After a group the CPU pool computed: its dispatch time and expert count join the running round.
|
||||
pub(super) fn note_cpu_pool_work(&mut self) {
|
||||
let Some(auto) = self.state.strata_pcie_auto.as_mut() else { return };
|
||||
let sample = self.cpu.last_group_sample();
|
||||
auto.note_group(PoolWork { micros: sample.elapsed.as_secs_f64() * 1e6, experts: sample.experts as u64 });
|
||||
}
|
||||
/// A round boundary: the controller may move the share; the move is printed.
|
||||
pub(super) fn end_strata_pcie_round(&mut self) {
|
||||
let link_gbps = self.state.strata_pcie_link_gbps.unwrap_or_default();
|
||||
let Some(auto) = self.state.strata_pcie_auto.as_mut() else { return };
|
||||
let was = auto.pcie_num();
|
||||
if let Some(change) = auto.end_round() {
|
||||
eprintln!("{}", change.operator_line((was, link_gbps), !auto.live()));
|
||||
}
|
||||
}
|
||||
}
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
//! `StrataPcieAuto`: the policy's numbers against Strata's `PcieAuto` (generate.cpp:2196), no device.
|
||||
|
||||
use super::strata_pcie_auto::*;
|
||||
|
||||
/// An expert blob of 2.05 MB: with the 47.5 GB/s link, 43 us per expert is Strata's 0.35 on the RTX 5090 server
|
||||
/// (parity-audit-5090.md row 5), 53 us its 0.40.
|
||||
const BLOB: f64 = 2.05e6;
|
||||
const INPUTS: PcieAutoInputs = PcieAutoInputs { link_gbps: DEFAULT_LINK_GBPS, blob_bytes: BLOB };
|
||||
const START_055: u32 = 141;
|
||||
|
||||
fn controller() -> StrataPcieAuto {
|
||||
StrataPcieAuto::new(INPUTS, START_055)
|
||||
}
|
||||
|
||||
/// `rounds` rounds of one group each, `experts_per_round` experts at `micros_per_expert`; the last change, if any.
|
||||
fn run_rounds(
|
||||
auto: &mut StrataPcieAuto,
|
||||
rounds: u32,
|
||||
(experts_per_round, micros_per_expert): (u64, f64),
|
||||
) -> Option<ShareChange> {
|
||||
let mut last = None;
|
||||
for _ in 0..rounds {
|
||||
auto.note_group(PoolWork { micros: micros_per_expert * experts_per_round as f64, experts: experts_per_round });
|
||||
last = auto.end_round().or(last);
|
||||
}
|
||||
last
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_balance_share_is_link_over_link_plus_pool_on_the_005_grid() {
|
||||
let pool_43us = BLOB / 43e-6 / 1e9;
|
||||
let pool_53us = BLOB / 53e-6 / 1e9;
|
||||
assert_eq!(balanced_share(47.5, pool_43us), 0.35);
|
||||
assert_eq!(balanced_share(47.5, pool_53us), 0.40);
|
||||
// a link as fast as the pool takes 1 / 2.85 of the misses
|
||||
assert_eq!(balanced_share(40.0, 40.0), 0.35);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_share_stays_inside_the_bounds() {
|
||||
assert_eq!(balanced_share(47.5, 1000.0), MIN_SHARE);
|
||||
assert_eq!(balanced_share(47.5, 1.0), MAX_SHARE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_moves_before_the_first_window_of_48_rounds() {
|
||||
let mut auto = controller();
|
||||
assert_eq!(run_rounds(&mut auto, FIRST_WINDOW_ROUNDS - 1, (40, 43.0)), None);
|
||||
assert_eq!(auto.pcie_num(), START_055);
|
||||
let change = run_rounds(&mut auto, 1, (40, 43.0)).expect("48th round");
|
||||
assert_eq!((change.pcie_num, change.fraction), (90, 0.35));
|
||||
assert!((change.micros_per_expert - 43.0).abs() < 1e-9);
|
||||
assert!((change.pool_gbps - BLOB / 43e-6 / 1e9).abs() < 1e-6);
|
||||
assert_eq!(auto.pcie_num(), 90);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_share_follows_a_slower_pool_down_in_steps_like_the_vanilla_replay() {
|
||||
// Strata's replay went 0.55 -> 0.40 -> 0.35: 48 rounds, then 96 more, then 96 more
|
||||
let mut auto = controller();
|
||||
let first = run_rounds(&mut auto, FIRST_WINDOW_ROUNDS, (40, 53.0)).expect("first update");
|
||||
assert_eq!((first.pcie_num, first.fraction), (102, 0.40));
|
||||
assert_eq!(run_rounds(&mut auto, LATER_WINDOW_ROUNDS - 1, (40, 43.0)), None);
|
||||
let second = run_rounds(&mut auto, 1, (40, 43.0)).expect("second update");
|
||||
assert_eq!((second.pcie_num, second.fraction), (90, 0.35));
|
||||
assert!(auto.live(), "two updates made, the third is still to come");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reading_within_the_dead_band_changes_nothing_but_uses_the_update() {
|
||||
let mut auto = StrataPcieAuto::new(INPUTS, 90);
|
||||
assert_eq!(run_rounds(&mut auto, FIRST_WINDOW_ROUNDS, (40, 43.0)), None);
|
||||
assert_eq!(auto.pcie_num(), 90);
|
||||
// the next window is the 96-round one
|
||||
assert_eq!(run_rounds(&mut auto, LATER_WINDOW_ROUNDS - 1, (40, 53.0)), None);
|
||||
assert!(run_rounds(&mut auto, 1, (40, 53.0)).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_third_update_is_the_last_and_still_applies() {
|
||||
let mut auto = controller();
|
||||
run_rounds(&mut auto, FIRST_WINDOW_ROUNDS, (40, 53.0));
|
||||
run_rounds(&mut auto, LATER_WINDOW_ROUNDS, (40, 43.0));
|
||||
assert!(auto.live());
|
||||
let third = run_rounds(&mut auto, LATER_WINDOW_ROUNDS, (40, 120.0)).expect("third update");
|
||||
assert!(third.fraction > 0.40, "a slow pool takes fewer misses, so the PCIe share rises: {third:?}");
|
||||
assert!(!auto.live());
|
||||
let kept = auto.pcie_num();
|
||||
assert_eq!(run_rounds(&mut auto, 500, (40, 10.0)), None);
|
||||
assert_eq!(auto.pcie_num(), kept);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_with_too_few_cpu_experts_is_looked_at_again_and_then_given_up() {
|
||||
let mut auto = controller();
|
||||
// 48 rounds x 6 experts = 288 < 300: not enough, the window grows
|
||||
assert_eq!(run_rounds(&mut auto, FIRST_WINDOW_ROUNDS, (6, 43.0)), None);
|
||||
assert!(auto.live());
|
||||
assert_eq!(run_rounds(&mut auto, 1, (6, 43.0)), None, "49 rounds hold 294 experts");
|
||||
let change = run_rounds(&mut auto, 1, (6, 43.0)).expect("50 rounds hold 300 experts");
|
||||
assert_eq!(change.fraction, 0.35);
|
||||
let mut starved = controller();
|
||||
assert_eq!(run_rounds(&mut starved, GIVE_UP_ROUNDS - 1, (0, 0.0)), None);
|
||||
assert!(starved.live());
|
||||
assert_eq!(run_rounds(&mut starved, 1, (0, 0.0)), None);
|
||||
assert!(!starved.live());
|
||||
assert_eq!(starved.pcie_num(), START_055);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_boundary_without_a_group_is_not_a_round() {
|
||||
let mut auto = controller();
|
||||
for _ in 0..200 {
|
||||
assert_eq!(auto.end_round(), None);
|
||||
}
|
||||
assert_eq!(run_rounds(&mut auto, FIRST_WINDOW_ROUNDS - 1, (40, 43.0)), None);
|
||||
assert!(run_rounds(&mut auto, 1, (40, 43.0)).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reading_that_cannot_be_used_leaves_the_share() {
|
||||
// 1 us per expert or less is a clock artefact, not a pool speed
|
||||
let mut auto = controller();
|
||||
assert_eq!(run_rounds(&mut auto, FIRST_WINDOW_ROUNDS, (40, 0.5)), None);
|
||||
assert_eq!(auto.pcie_num(), START_055);
|
||||
let no_blob = PcieAutoInputs { blob_bytes: 0.0, ..INPUTS };
|
||||
let mut blind = StrataPcieAuto::new(no_blob, START_055);
|
||||
assert_eq!(run_rounds(&mut blind, FIRST_WINDOW_ROUNDS, (40, 43.0)), None);
|
||||
let no_link = PcieAutoInputs { link_gbps: 0.0, ..INPUTS };
|
||||
let mut unlinked = StrataPcieAuto::new(no_link, START_055);
|
||||
assert_eq!(run_rounds(&mut unlinked, FIRST_WINDOW_ROUNDS, (40, 43.0)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fast_pool_lowers_the_share_to_the_floor() {
|
||||
let mut auto = controller();
|
||||
let change = run_rounds(&mut auto, FIRST_WINDOW_ROUNDS, (40, 2.0)).expect("update");
|
||||
assert_eq!((change.fraction, change.pcie_num), (MIN_SHARE, 26));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_operator_line_names_the_reading_the_old_and_the_new_share() {
|
||||
let change = ShareChange { pcie_num: 90, fraction: 0.35, micros_per_expert: 43.2, pool_gbps: 47.4 };
|
||||
let line = change.operator_line((141, 47.5), false);
|
||||
for want in ["pcie_frac 0.35", "pcie_num 141 -> 90", "was 0.55", "43 us", "47.4 GB/s", "link 47.5 GB/s"] {
|
||||
assert!(line.contains(want), "{want:?} in {line:?}");
|
||||
}
|
||||
assert!(!line.contains("last update"));
|
||||
assert!(change.operator_line((141, 47.5), true).ends_with("last update"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_start_share_is_kept_until_the_first_window_and_the_inputs_are_read_back() {
|
||||
let auto = controller();
|
||||
assert_eq!((auto.pcie_num(), auto.live()), (START_055, true));
|
||||
}
|
||||
+20
-2
@@ -82,11 +82,11 @@ impl ExpertTierConfig {
|
||||
// (`LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB=130`) until its own arm measures it.
|
||||
decode_reserve_mib: 300,
|
||||
// the PCIe share that equalises the legs when the CPU pool and the DMA share the host's memory ceiling
|
||||
// (P/(P+C) = 0.45, job 987-b/909; 0.45 vs 0.55: +0.5 % / +4.7 % at the auto-sized cache, equal at
|
||||
// 2048 slots)
|
||||
// (P/(P+C) = 0.45, job 987-b/909; 0.45 vs 0.55: +0.5 % / +4.7 % at auto-sized cache, equal at 2048 slots)
|
||||
pcie_frac: 0.45,
|
||||
pcie_frac_set: false,
|
||||
pcie_mode: PcieMode::Auto,
|
||||
strata_pcie_auto: None,
|
||||
adapt_every: 4,
|
||||
adapt_swaps: 96,
|
||||
prefill_borrow: true,
|
||||
@@ -152,6 +152,7 @@ impl ExpertTierConfig {
|
||||
let mut config = Self::off();
|
||||
config.read_placement(env)?;
|
||||
config.read_pcie(env)?;
|
||||
config.read_strata_pcie_auto(env)?;
|
||||
config.read_adaptation(env)?;
|
||||
config.read_seed(env)?;
|
||||
config.read_seed_shape(env)?;
|
||||
@@ -184,6 +185,23 @@ impl ExpertTierConfig {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// `_PCIE_AUTO` (`on` | `off`, also `yes`/`1` and `no`/`0`; anything else is refused) with `_PCIE_LINK_GBPS`
|
||||
/// (a bandwidth above 0 and up to 1000, checked even while the switch is off).
|
||||
fn read_strata_pcie_auto(&mut self, env: &impl EnvSource) -> Result<()> {
|
||||
let link = match serve_var(env, "PCIE_LINK_GBPS") {
|
||||
Some(v) => v.parse::<f64>().map_err(|_| Error::InvalidDimension)?,
|
||||
None => strata_pcie_auto::DEFAULT_LINK_GBPS,
|
||||
};
|
||||
if !(link > 0.0 && link <= 1000.0) {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
self.strata_pcie_auto = match serve_var(env, "PCIE_AUTO").as_deref() {
|
||||
None | Some("off" | "no" | "0") => None,
|
||||
Some("on" | "yes" | "1") => Some(link),
|
||||
Some(_) => return Err(Error::InvalidDimension),
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
fn read_adaptation(&mut self, env: &impl EnvSource) -> Result<()> {
|
||||
if let Some(v) = serve_var(env, "ADAPT_EVERY") {
|
||||
self.adapt_every = v.parse().map_err(|_| Error::InvalidDimension)?;
|
||||
|
||||
@@ -111,3 +111,34 @@ fn the_profile_path_is_kept_as_set_without_a_check() {
|
||||
assert_eq!(read(&[("EXPERT_PROFILE", "/p/x.strp")]).unwrap().profile, Some(PathBuf::from("/p/x.strp")));
|
||||
assert_eq!(read(&[("EXPERT_PROFILE", "")]).unwrap().profile, Some(PathBuf::from("")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strata_pcie_auto_is_off_unless_asked_and_its_link_has_a_default() {
|
||||
assert_eq!(read(&[]).unwrap().strata_pcie_auto, None);
|
||||
let link = Some(super::strata_pcie_auto::DEFAULT_LINK_GBPS);
|
||||
for (value, want) in [("on", link), ("yes", link), ("1", link), ("off", None), ("no", None), ("0", None)] {
|
||||
assert_eq!(read(&[("PCIE_AUTO", value)]).map(|c| c.strata_pcie_auto), Ok(want), "{value:?}");
|
||||
}
|
||||
for value in ["", "ON", "true", "lag", "2"] {
|
||||
assert!(read(&[("PCIE_AUTO", value)]).is_err(), "{value:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pcie_link_is_a_positive_bandwidth_up_to_a_thousand() {
|
||||
assert_eq!(read(&[("PCIE_AUTO", "on"), ("PCIE_LINK_GBPS", "26.5")]).map(|c| c.strata_pcie_auto), Ok(Some(26.5)));
|
||||
assert_eq!(read(&[("PCIE_LINK_GBPS", "26.5")]).map(|c| c.strata_pcie_auto), Ok(None), "no switch, no controller");
|
||||
for value in ["0", "-1", "1000.5", "NaN", "inf", "x", ""] {
|
||||
assert!(read(&[("PCIE_LINK_GBPS", value)]).is_err(), "{value:?}");
|
||||
assert!(read(&[("PCIE_AUTO", "on"), ("PCIE_LINK_GBPS", value)]).is_err(), "{value:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_controller_exists_only_for_the_switch_and_the_fixed_share_is_untouched() {
|
||||
let off = ExpertTierConfig::off();
|
||||
assert!(ResidencyState::new(&off).strata_pcie_link_gbps.is_none());
|
||||
let on = ExpertTierConfig { strata_pcie_auto: Some(30.0), ..off.clone() };
|
||||
assert_eq!(ResidencyState::new(&on).strata_pcie_link_gbps, Some(30.0));
|
||||
assert_eq!(on.pcie_num(), off.pcie_num(), "the start share is the configured one");
|
||||
}
|
||||
|
||||
+3
-2
@@ -249,9 +249,10 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
fn pcie_num_for_report(&self) -> u32 {
|
||||
self.tier
|
||||
.residency
|
||||
.pcie_lag
|
||||
.strata_pcie_auto
|
||||
.as_ref()
|
||||
.map(|l| l.pcie_num())
|
||||
.map(|s| s.pcie_num())
|
||||
.or_else(|| self.tier.residency.pcie_lag.as_ref().map(|l| l.pcie_num()))
|
||||
.or_else(|| self.tier.residency.pcie_auto.as_ref().map(|a| a.pcie_num()))
|
||||
.unwrap_or(self.config.expert_tier.pcie_num())
|
||||
}
|
||||
|
||||
@@ -76,8 +76,8 @@ Structure first, then the layer steps in graph order: embed (R7), mixer half (V3
|
||||
| V9 | verify graph kernel time sum | 13.349 | 13.728 | -0.379 (VANL runs kernels concurrently: its span is shorter than its sum) | CUPTI | device | proved-equal (LEL ahead) |
|
||||
| V8 | launches per verify graph | 2061 | 2098 | -37 | CUPTI | device | proved-equal (LEL ahead) |
|
||||
| R5 | verify graph launch call (host) | 1.485 | 1.509 | -0.024 | CUPTI | device | proved-equal (LEL ahead) |
|
||||
| R6 | idle inside the verify graph (2052 gaps against 1193 per round, mean 0.1 us) | 0.213 | 0.119 | +0.094 | CUPTI | device | open |
|
||||
| R7 | first doorbell after graph start (embed, first layer mixer) | 0.132 | 0.117 | +0.015 | CUPTI | device | open |
|
||||
| R6 | idle inside the verify graph (2052 gaps against 1193 per round, mean 0.1 us) | 0.213 | 0.119 | +0.094 | CUPTI | device | proved-equal (2026-11-11 `docs/experiments/verify-tail-and-gaps.md`: the 2052/1193 are per verify graph; union gaps CL.2 2035 / 211.0 us, VANL 1194 / 119.3 us; with the side streams LEL has 1124 / 123.7 us (CP.1) and 1070 / 118.4 us (CY.1): residual +5.8 us a graph at LEL's T mix, closed by the side-stream switches) |
|
||||
| R7 | first doorbell after graph start (embed, first layer mixer) | 0.132 | 0.117 | +0.015 | CUPTI | device | proved-equal (2026-11-11 `docs/experiments/verify-tail-and-gaps.md`: 21-23 kernels precede the first doorbell in both; LEL 95.6 / 105.6 / 112.5 / 121.9 / 137.4 / 149.5 us at T 1..6, VANL 93.3 / 98.6 / 114.7 / 125.8 / - / 135.3: mixed signs, no gap) |
|
||||
| V3 | mixer phase (`add_hits` end to next doorbell) | 6.366 | 5.963 | +0.403 | CUPTI | device | fixing |
|
||||
| verify: side branch of the GDN mixer (V3a) | GDN gates and gate projection on side streams (`LELEKA_SM120_SIDE_MIXER=1`, existing, off) | mixer 5.913, round 17.508 (`CM.1`) | mixer 5.963 | section delta mixer -0.453, round -0.356; mixer phase now equal to VANL | CUPTI | device | fixed (identity `spd-sqid1` P2 PASS: 2057 top-16 rows bit-identical, 0 argmax flips, draft trace 518/518; A/B `ab-sm` n=10 decode +1.39 %, CI +0.46..+2.32 %; default ON in the 5090 profiles; closed 2026-11-09 by section delta + identity (owner method); set A/B `verify-side-branches-ab-mixer-only-vs-all-branches` (M mixer only against U all three side parts, n=10 pairs, 27 requests a block, 2026-11-10): decode tok/s 179.11 -> 182.90, +2.11 %, CI +1.18..+3.04 % (ms/token 5.583 -> 5.467); end-to-end 162.29 -> 164.70, +1.49 %, CI +0.17..+2.80 %; ms/round 20.06 -> 19.90, -0.80 %, CI -3.80..+2.21 % (not significant); tokens/round 3.59 -> 3.64, CI -2.01..+4.60 %; no regression; out_sha equal in 15 of 300 live requests, which is replay placement noise, the identity gate is the teacher-forced `spd-sqid1`) |
|
||||
| verify: side branches of the QSA indexer and query chains (V3b) | QSA indexer chain and query chain on side streams (`LELEKA_SM120_SIDE_QSA`, code `0c30105d4`, off) | in line | 0.509 ms of overlap with the main stream (main+qsa) | section delta (`CN.1` against `CL.1`, same replay window r29): mixer phase of a QSA layer 184.5 -> 169.7 us p50 (-14.8 us x 12 = -0.18 ms/round); `CT.1` (all three) 169.2 us. FFN phase rose in `CN.1` on GDN layers too (109 -> 131 us), which the branch does not touch, so the whole-graph time of that window (14.62 against 13.56 ms mean) is window drift, not the branch; the A/B decides | CUPTI (VANL) | device | fixed (A/B `ab-sqn` L against N, n=10: decode tok/s +0.35 %, CI -0.23..+0.93 % (not significant, no regression); ms/token 5.635 -> 5.616; ms/round +0.11, CI -2.99..+4.11 %; end-to-end +0.87 %, CI -0.16..+1.90 %; default ON in the 5090 profiles; closed 2026-11-09 by section delta + identity (owner method); set A/B `verify-side-branches-ab-mixer-only-vs-all-branches` (M mixer only against U all three side parts, n=10 pairs, 27 requests a block, 2026-11-10): decode tok/s 179.11 -> 182.90, +2.11 %, CI +1.18..+3.04 % (ms/token 5.583 -> 5.467); end-to-end 162.29 -> 164.70, +1.49 %, CI +0.17..+2.80 %; ms/round 20.06 -> 19.90, -0.80 %, CI -3.80..+2.21 % (not significant); tokens/round 3.59 -> 3.64, CI -2.01..+4.60 %; no regression; out_sha equal in 15 of 300 live requests, which is replay placement noise, the identity gate is the teacher-forced `spd-sqid1`) |
|
||||
@@ -108,7 +108,7 @@ Structure first, then the layer steps in graph order: embed (R7), mixer half (V3
|
||||
| S2 | `GU_SWIGLU` (routed expert gate/up + SwiGLU + q8_1) | on since lever 1 | on | as S1 | gap doc lever 1 | device | fixing (needs a CUPTI section delta) |
|
||||
| S7 | sub16 routed-expert kernels beyond `GU_SWIGLU` | warp-per-row | sub16 | estimate 0.20-0.35; the CUPTI pair K11 does not show LEL slower, so this must be re-measured by kernel before any work | upstream plan | device | fixed (closed 2026-11-11 by section delta + identity; enabled in the three 5090 profiles; windows `docs/experiments/ffn-d1-d2-d3-windows.md` WD-CP: F-layer FFN phase -3.9 / -7.7 / -10.0 / -12.9 / -18.7 us at T 1..5 = -0.214 ms a graph at CP's T mix (se 0.008), VRAM-pass down 19.3 -> 14.1 us and PCIe-pass down 5.5 -> 0.64 us at T 3; probe 64 cases byte-identical; identity P2/P5 2057/2057 rows, draft trace identical) (was: built, off: `LELEKA_SM120_DOWN_SUB16`, branch `claude/ffn-down-sub16` merged, sealed `sm120_down_sub16`; jobs `verify-ffn-d1-d2-d3-bitwise-probes` (`sm120_probe down`), `-identity` P2/P5, window WD/WZ queued 2026-11-11; look at `window_moe_down_20/_42` -> `sm120_moe_down_20/_42`; estimate refined to 0.17-0.23 ms a graph; `docs/experiments/ffn-phase-loss-design.md`) |
|
||||
| D2 | `add_hits` folded into the combine (`LELEKA_SM120_HITS_IN_COMBINE`, upstream `combine_k10_vec4_hits`) | `add_hits` 48 x 1.2-1.3 us a graph | folded | upper bound 0.06 ms a graph (T 2-4) | design `ffn-phase-loss-design.md` 4.1 | device | fixed (closed 2026-11-11 by section delta + identity; enabled in the three 5090 profiles; windows `docs/experiments/ffn-d1-d2-d3-windows.md` WH-CP: `add_hits` gone, tail after the CPU rows -0.86..-0.93 us a layer = -0.043 ms a graph (about -0.025 with COMBINE_VEC4 on); probe failures=0, identity P3/P5 2057/2057 rows) (was: built, off: `LELEKA_SM120_HITS_IN_COMBINE`, branch `claude/ffn-hits-combine` merged, sealed `sm120_combine_hits`; jobs `verify-ffn-d1-d2-d3-bitwise-probes`, `-identity` P3/P5, `-cupti-windows` WH/WZ queued 2026-11-11; look at `add_hits` (-48 launches a graph) and the combine entry) |
|
||||
| D3 | wait on flag M folded into the copy of the CPU rows (`LELEKA_SM120_WAIT_M_ROWS`) | 2 launches a layer | folded | 0.04-0.06 ms a graph; risk: upstream measured -1.5 % decode on Turing for the same fold | design `ffn-phase-loss-design.md` 4.1 | device | open (measured LOSS, `docs/experiments/ffn-d1-d2-d3-windows.md` WW-CP: the fused kernel costs 5.8 / 10.2 / 14.4 / 18.8 / 23.2 us at T 1..5 against 2.7 us for wait M + copy (1.44 us + 0.433 us per block: every block polls the flag over PCIe), F-layer FFN phase +3.3 / +7.7 / +12.6 / +17.3 / +21.8 us per layer; OFF, probe and identity PASS; retry only with a single-poller structure) (was: built, off: `LELEKA_SM120_WAIT_M_ROWS`, branch `claude/ffn-wait-m-rows` merged, sealed `sm120_wait_copy_rows`; thread 0 of each block polls, fence, barrier, then the copy; jobs as D2, window WW/WZ; look at the second `verify_wait_flag_ge` + `chain_copy_rows_from_mapped` -> `leleka_verify_wait_copy_rows`, and watch for a longer copy kernel) |
|
||||
| D3 | wait on flag M folded into the copy of the CPU rows (`LELEKA_SM120_WAIT_M_ROWS`) | 2 launches a layer | folded | 0.04-0.06 ms a graph; risk: upstream measured -1.5 % decode on Turing for the same fold | design `ffn-phase-loss-design.md` 4.1 | device | open (measured LOSS, `docs/experiments/ffn-d1-d2-d3-windows.md` WW-CP: the fused kernel costs 5.8 / 10.2 / 14.4 / 18.8 / 23.2 us at T 1..5 against 2.7 us for wait M + copy (1.44 us + 0.433 us per block: every block polls the flag over PCIe), F-layer FFN phase +3.3 / +7.7 / +12.6 / +17.3 / +21.8 us per layer; OFF, probe and identity PASS; retry key: ONE polling block for the whole grid (the other blocks wait on a device-side release word the poller writes, or the copy is split into a one-block wait kernel + the existing copy graph node), so the PCIe flag is read by one warp, not by T x 10 blocks; the floor to beat is 2.7 us for wait M + copy) (was: built, off: `LELEKA_SM120_WAIT_M_ROWS`, branch `claude/ffn-wait-m-rows` merged, sealed `sm120_wait_copy_rows`; thread 0 of each block polls, fence, barrier, then the copy; jobs as D2, window WW/WZ; look at the second `verify_wait_flag_ge` + `chain_copy_rows_from_mapped` -> `leleka_verify_wait_copy_rows`, and watch for a longer copy kernel) |
|
||||
| S11 | float4 combine | not ported | `combine_k10_vec4` 50.6 x 1.2 us | estimate 0.05-0.10 (the code has no launch saving, one launch a layer both ways: expect 0.01-0.02) | upstream plan | device | fixed (switch `LELEKA_SM120_COMBINE_VEC4` (off), sealed `sm120_combine_vec4`, branch `claude/s11-s9-combine-headmix` merged; jobs `verify-s11-s9-u5a-bitwise-probes`, `-identity` P2/P5, `-cupti-windows` CS/CZ queued; look at `mtp_full_combine` against `leleka_verify_combine_k10_vec4` per launch). Identity 2026-11-10 (`verify-s11-s9-u5a-identity` P2): top-16 rows 2057/2057 bit-identical, draft trace 1036/1036, A/A identical: PASS. Window (cumulative variants, CS-CP, `docs/experiments/verify-s11-s9-u5a-windows.md`): combine 1.50 -> 1.15 us per launch, -0.0164 ms a graph weighted over T (noise <= 0.0004), resolved at every T. Enabled by default in the three 5090 profiles 2026-11-11 (closed by section delta + identity)) |
|
||||
| K8 | hyper-connection down (`chain_gr_down_t2w8_nb4` 11.1 us against `gr_down_staged` 11.5 us) | 1.063 | 1.112 | -0.049 | CUPTI | device | proved-equal (LEL ahead) |
|
||||
| K9 | hyper-connection up (`chain_gr_up8` 8.5 us against `gr_up75` + `gr_up_multi` variants) | 0.817 | 0.877 | -0.060 | CUPTI | device | proved-equal (LEL ahead) |
|
||||
@@ -116,7 +116,7 @@ Structure first, then the layer steps in graph order: embed (R7), mixer half (V3
|
||||
| S4 | `GR_DOWN_TG` | 9.7 us (`chain_gr_down_t2w8_nb4`) | 18.4 us | -8.7 us | gap doc | device | proved-equal (LEL ahead) |
|
||||
| S5 | `GR_UP75` (hoisted row loads) | partial | on | estimate 0.05-0.10 | upstream plan | device | open |
|
||||
| K14 | small kernels (norms, PLE, copies, sampler) | 0.049 | 0.253 | -0.204 | CUPTI role table | device | proved-equal (LEL ahead) |
|
||||
| R8 | tail after the last layer's `add_hits` (final write, head, argmax) | 0.463 | 0.373 | +0.090 | CUPTI | device | open |
|
||||
| R8 | tail after the last layer's `add_hits` (final write, head, argmax) | 0.463 | 0.373 | +0.090 | CUPTI | device | fixing (2026-11-11 `docs/experiments/verify-tail-and-gaps.md`: LEL +86.5 us at its T mix = the ledger's +0.090; head hc chain +31.2 us (6T+4 launches against 10), head matmul at T>=3 +38.4 us, greedy pick + finite scan +18.0 us (`chain_sampler_greedy_kernel` 25 us against ~7). Switch `LELEKA_SM120_HEAD_CHAIN_BATCH` (off, branch `claude/tail-fusion` merged, sealed `sm120_head_chain`): batches the 6T tail launches into 6, bitwise by construction, expected 0.02-0.035 ms a graph; jobs `verify-tail-head-chain-bitwise-probe`, `-identity`, `-cupti-windows` (QP/QT) queued 2026-11-11, binary `bin-tail`. Not done: greedy pick fold (18 us, bitwise-safe, needs a scratch buffer in `OriginalNativeHeadRows`), head matmul T>=3 (38 us, try the sealed `head_n14_tN_small` dispatch, per-row arithmetic unverified)) |
|
||||
| S9 | `HEAD_MIX_MULTI` | not ported | on | estimate 0.06-0.10 | upstream plan | device | open (switch `LELEKA_SM120_HEAD_MIX_MULTI` (off), one multi-token hc read for the head, 3 launches a token instead of 5 (-(5T-3) a graph), branch `claude/s11-s9-combine-headmix` merged; bitwise rests on upstream's claim until `verify-s11-s9-u5a-bitwise-probes` and identity P3/P5 run; window CH/CZ queued). Identity 2026-11-10 (P3): NOT bitwise. 25 of 2057 top-16 rows differ against the reference (same 25 in both arms, A/A identical, so it is the switch, not noise), d_top1 max 0.0015, p99 0.0013, argmax flips 0, draft trace 1036/1036 identical. The multi-token head read changes the summation order of the head mix. A lossy-class change: OFF, and it needs its own quality gate and a delta before it can be considered (the window `CH`; expected gain is only the 5T-3 launches). Window CH-CS (`docs/experiments/verify-s11-s9-u5a-windows.md`): -(5T-3) kernels confirmed, head span -0.0004 .. -0.0605 ms a graph at T 1..6, weighted -0.023 ms (noise <= 0.0001): real but small, far below the 0.06-0.10 estimate; OFF because it is not bitwise |
|
||||
|
||||
## C2u. Upstream cc 12.0 defaults after 0.2.6 (owner 2026-11-09: +0.3 % and +0.5 % are tokens too)
|
||||
@@ -178,13 +178,13 @@ The tier adapts every 4 rounds and survives across requests.
|
||||
|
||||
| id | step | LEL | VANL | difference | source | owner | status |
|
||||
| --- | --- | ---: | ---: | ---: | --- | --- | --- |
|
||||
| H1 | VRAM hit share in the replay | 90.8 % | 92.8 % | -2.0 points; 28 % more misses | LOG | device | open |
|
||||
| H1 | VRAM hit share in the replay | 90.8 % | 92.8 % | -2.0 points; 28 % more misses | LOG | device | open (2026-11-11 `docs/experiments/vram-hit-share-gap.md`: the -2.0 does not reproduce, the two surviving VANL replays give 91.8 unweighted / 93.4 token-weighted; gap on the 30-request replay is -0.7..-1.3 points token-weighted, -1.0..-1.6 unweighted) |
|
||||
| H2 | VRAM hit share weighted by decode time in real sessions | nestng-crm 91.38 %, ttt 92.68 % | 92.41 %, 93.38 % | -1.03 and -0.70 points; at most 0.57 ms per round per point, so up to 0.59 and 0.40 ms per round | LOG | device | open |
|
||||
| H3 | short requests (< 600 tokens) hit share | 86.9 % | 89.9 % | -3.0 points (up to 7 in single requests) | LOG | device | open |
|
||||
| H4 | expert slots | 12,192 | 12,575 (+3 %) | -383 slots; variant H (reserves 130 / 500 MiB, about +190 slots): VRAM share +0.44 points, ms/round -0.44 (-2.19 %, CI -3.55..-0.83), tokens per round -1.69 %, decode +0.51 % (CI -0.19..+1.20), end-to-end +1.06 % (CI -0.38..+2.50) | A/B `ab-l3v2` | device | fixing (placement-class: needs the gate against the control placement) |
|
||||
| H4 | expert slots | 12,192 | 12,575 (+3 %) | -383 slots; variant H (reserves 130 / 500 MiB, about +190 slots): VRAM share +0.44 points, ms/round -0.44 (-2.19 %, CI -3.55..-0.83), tokens per round -1.69 %, decode +0.51 % (CI -0.19..+1.20), end-to-end +1.06 % (CI -0.38..+2.50) | A/B `ab-l3v2` | device | fixing (CORRECTION 2026-11-11 `docs/experiments/vram-hit-share-gap.md`: the earlier reading that variant H 'gained nothing' was an env leak; the clean paired A/B `ab-l3v2` (10 pairs, H 12,384 slots against A 12,192) is a real gain: hit share +0.44 points token-weighted (CI +0.24..+0.64), ms/round -2.10 % (CI -3.61..-0.59), decode tok/s +0.67 % (CI +0.02..+1.31); about 0.23 points per 100 slots, 383 missing slots are worth about 0.9 of the 1.3-point gap. Not enabled: the free VRAM at decode drops to about 355 MiB (vanilla 315), and the project rule is that real work is 256k: before any profile change a run on the 245k corpus (docs/quality-gate.md q245, `leleka/decode/`, sha in the manifest) with the memory profile, the minimum free VRAM along the run, no OOM or refusal and the memory governor without incident is required, and the memory owner (hex-finish, 2026-11-11) names the threshold: no stricter rule exists, vanilla's own minimum free VRAM of 315 MiB (`vram-footprint-5090.md`: 389 at request start, 315 after the windows are captured; `decode_headroom_mib()` = 700+130-514 = 316) is the proof of safety, so 355 MiB is inside it. Pass criteria: (1) minimum free VRAM by 100 ms sampling (`mon.csv`) over the WHOLE 245k corpus session >= 315 MiB, (2) 0 request failures / CudaExecution / OOM, (3) 3 repeats (the adaptive tier is not bitwise reproducible), (4) the cost confirmed: 12,384 slots. The VRAM floor is set by decode_reserve + usable_room (`original_cache_startup.rs`), not by the memory governor (host RAM). No current 256k stub with a memory profile exists in jobs/: nearest are `987-decode-vram` (dc-g2, `run_corpus` of dec-common.sh, prints the minimum free VRAM, old binary) and `q245-*`; the plan is `run_corpus` with the current binary and the two variables. Group A/B `decode-slots-and-adapt-every-group-ab-pg-vs-ps-pw` (PS = alias + reserve 130) queued; the per-layer-quota arm (EXPERT_PER_LAYER=no) is measured by hex-finish (`host-tier-global-rank-fill-vs-uniform-layer-quota-profile`)) |
|
||||
| H5 | adaptive tie order (equal-gain swaps share the cap across layers, `LELEKA_ADAPT_TIE_SPREAD`, `9d130fd38`) | low layer first | | run `memory-tier-tie-spread-ab-first-half/xb` queued | gap doc | device | fixing |
|
||||
| H6 | tier knobs: adapt every 2, 192 swaps, decay 0.85, margin 1.0 (`spd-w1..w5`) | 4, 96, 0.7, 1.5 | same policy | runs queued | gap doc | device | fixing |
|
||||
| H7 | first rounds of a request see an unadapted tier | | | not isolated | gap doc | device | open |
|
||||
| H6 | tier knobs: adapt every 2, 192 swaps, decay 0.85, margin 1.0 (`spd-w1..w5`) | 4, 96, 0.7, 1.5 | same policy | runs queued | gap doc | device | fixing (W1 adapt every 2: earlier n=5 +0.56 points hit, +1.31 % tok/s (CI +0.77..+1.85); in the group A/B above as PW against PG, then 10 pairs if it holds) |
|
||||
| H7 | first rounds of a request see an unadapted tier | | | not isolated | gap doc | device | open (isolated for ours 2026-11-11 `docs/experiments/vram-hit-share-gap.md`: hit share 79 % in the first 4 windows of a request, 85 % at windows 16-31, 90 % at 32-63, 93 % from 128; the first 64 windows carry 20 % of the misses, a ceiling of 0.71 points; vanilla has no per-window log; a request-start warm-up needs code in `original_serve_residency/source_spans.rs`, hex-finish) |
|
||||
| H8 | CPU expert compute per expert (2 MB) | 39 us (52 GB/s) | 44 us | -5 us | PROFILE | hex-finish | proved-equal (LEL ahead) |
|
||||
|
||||
## Counts
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
# Verify graph: the tail after the last layer and the idle gaps (ledger rows R6, R7, R8; switch HEAD_CHAIN_BATCH)
|
||||
|
||||
Branch `claude/tail-fusion`. Analysis first (CUPTI windows, read-only on `rnr5090`), then one opt-in switch,
|
||||
`LELEKA_SM120_HEAD_CHAIN_BATCH` (default off). Nothing was run on a GPU: every claim below is either read from the
|
||||
CUPTI traces (marked with the window) or from code, and the expected section delta is arithmetic, not a measurement.
|
||||
|
||||
## 0. Answer first
|
||||
|
||||
| ledger row | what the windows show | verdict |
|
||||
| --- | --- | --- |
|
||||
| R6 idle inside the verify graph, 2052 against 1193 gaps, +0.094 ms | The numbers are the **verify graph only**, counted as union gaps (no kernel of the graph runs), and they reproduce exactly: control `CL.2` (one stream) 2035 gaps / 211.0 us, VANL 1194 / 119.3 us. With the side streams of the profile set (`CP.1`, `CY.1`) LEL has **1124 / 123.7 us and 1070 / 118.4 us**, i.e. +5.8 us a graph at LEL's own T mix (+2.3 .. +13.1 us at equal T). Every gap is 0.10-0.11 us in both. The loss of R6 was the single stream; the side-stream switches (V1, V3a, V3b, V4a) removed it. | closed by the side streams; residual +0.006 ms, nothing to build |
|
||||
| R7 first doorbell after graph start, +0.015 ms | 21-23 kernels precede the first doorbell in both; LEL 95.6 / 105.6 / 112.5 / 121.9 / 137.4 / 149.5 us at T 1..6, VANL 93.3 / 98.6 / 114.7 / 125.8 / - / 135.3 us. | no gap to remove (-3.9 .. +14.2 us, mixed signs) |
|
||||
| R8 tail after the last `add_hits`, +0.090 ms | At LEL's T mix the tail is **86.5 us** longer than VANL's (table in 3.3): hyper-connection chain of the head **31.2 us**, language-model head matmul at T >= 3 **38.4 us**, greedy pick + finite scan **18.0 us**, one extra VANL kernel -1.0 us. | the chain is a launch-count loss and is removed bitwise by the switch; matmul and pick are not launch fusion (3.4) |
|
||||
| the 2052 / 1193 "per round" | not per round: per verify graph. The non-verify graphs of a round are separate: LEL 4.23 graphs, 426 kernels, 409 union gaps, 43.5 us idle; VANL 3.48 graphs, 148 kernels, 108 gaps, 11.6 us (`CP.1` and VANL windows; draft graph 113 kernels against 53, 2.2 a round). That is the draft/commit side (rows O1, O9), not the tail. | out of scope here |
|
||||
|
||||
## 1. Data and method
|
||||
|
||||
* LEL: `/data/leleka-e2e/spd-gap/runs/verify-ffn-d1-d2-d3-cupti-windows/CP.1/win-r29.lct` (profile set: side mixer / QSA /
|
||||
shared expert, fused QSA prelude; no COMBINE_VEC4, no D1/D2/D3, so the tail is the literal one). 785 verify graphs,
|
||||
T 1..8 (28 / 206 / 253 / 40 / 231 / 22 / 4 / 1). Control for R6: `verify-new-switches-cupti-windows/CL.2/win-r29.lct`
|
||||
(833 graphs, one stream) and `CY.1` (profile set + new switches, 894 graphs).
|
||||
* VANL: `/data/leleka-e2e/spd-gap/runs/cupti/VANL/win-r29.lct`, 893 verify graphs (T 1 / 2 / 3 / 4 / 6 = 127 / 94 / 92 /
|
||||
569 / 11; no T = 5, its row below is the mean of T = 4 and 6, marked).
|
||||
* Script `scripts/e2e/codex/speed/verify_tail_report.py` (`extract`, then `compare`; stdlib, reads `lct.py`). Verify graph =
|
||||
at least 900 kernels per correlation id, first and last two dropped; T = grid of the CPU-row copy kernel / 10; tail =
|
||||
every kernel that starts at or after the end of the last `add_hits`; the head matmul is the longest kernel of the tail.
|
||||
Every number is a p50 per T unless it says weighted. "Weighted" = the per-T difference summed over LEL's own T mix
|
||||
(780 graphs), the only mix both sides can be compared at.
|
||||
|
||||
## 2. The idle gaps (R6, R7)
|
||||
|
||||
Union gaps and idle time inside one verify graph (p50 per T):
|
||||
|
||||
| T | LEL `CP.1` gaps / idle us | VANL gaps / idle us | difference idle us |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | 1135 / 124.8 | 1203 / 122.0 | +2.8 |
|
||||
| 2 | 1069 / 118.2 | 1167 / 115.9 | +2.3 |
|
||||
| 3 | 1095 / 120.3 | 1166 / 115.7 | +4.6 |
|
||||
| 4 | 1156 / 126.6 | 1200 / 119.8 | +6.7 |
|
||||
| 5 | 1175 / 128.9 | - (mean of T 4, 6: 119.2) | +9.7 (interpolated) |
|
||||
| 6 | 1194 / 131.6 | 1198 / 118.6 | +13.1 |
|
||||
| all graphs (mean) | 1124 / 123.7 | 1194 / 119.3 | weighted +5.8 |
|
||||
| control `CL.2`, one stream | 2035 / 211.0 | | R6's LEL column |
|
||||
|
||||
The R6 cell (0.213 against 0.119 ms) is the single-stream control against VANL. The profile windows have three streams in
|
||||
the verify graph for LEL (`CP.1`, `CY.1`), like VANL, and the gap time of a graph is then the time the critical path waits
|
||||
for a dependent launch: about 0.10 us per serial edge. What is left (+0.006 ms weighted) grows with T, i.e. with the number
|
||||
of serial edges of the per-token head chain below; it is not a separate loss.
|
||||
|
||||
First doorbell (R7), kernels before it and its start from the graph start, p50: LEL 23 kernels and 95.6 / 105.6 / 112.5 /
|
||||
121.9 / 137.4 / 149.5 us at T 1..6; VANL 21-23 kernels and 93.3 / 98.6 / 114.7 / 125.8 / - / 135.3 us. The difference is
|
||||
inside the T-dependent embedding and mixer work of the first layer, with mixed signs: nothing to fuse.
|
||||
|
||||
## 3. The tail (R8)
|
||||
|
||||
### 3.1 Kernel sequence after the last `add_hits` (T = 3, p50 duration us, gap before us)
|
||||
|
||||
LEL (22 launches, 415.6 us) and VANL (10 launches, 352.9 us):
|
||||
|
||||
| LEL | dur | gap | VANL | dur | gap |
|
||||
| --- | ---: | ---: | --- | ---: | ---: |
|
||||
| `mtp_full_combine` | 1.44 | 0.48 | combine (vec4) | 1.12 | 0.48 |
|
||||
| `mtp_full_native_write` x 3 | 0.83 / 0.77 / 0.74 | 0.10 | `post` (all rows) | 0.90 | 0.10 |
|
||||
| `mtp_full_gr_norm`, `mmvf256`, `down_silu`, `mmvf160`, `pre_final` **x 3** | 17.5 + 13.3 + 13.3 | 0.10 each | hyper-connection split, down, up (three `GrMulti` kernels, one multi-token read) | 2.69 + 10.11 + 7.94 | 0.10 |
|
||||
| `head_quant` | 0.86 | 0.10 | quantize | 0.86 | 0.10 |
|
||||
| | | | an extra kernel (`Q81Block const*, int*, int*, float*`) | 0.96 | 0.10 |
|
||||
| `head_n14_t3_large` | 338.5 | 0.10 | head matmul `F::Block` | 319.9 | 0.10 |
|
||||
| `chain_sampler_greedy_kernel` (grid T, 1024 threads) | 25.9 | -0.10 | `sampler_greedy_cluster_kernel` (grid 8 x T) + `logits_nonfinite` | 4.5 + 2.8 | -0.10 |
|
||||
|
||||
Launches in the tail by T: LEL 10 / 16 / 22 / 28 / 34 / 40 at T 1..6 (6 T + 4), VANL 9 / 10 / 10 / 10 / - / 10. Gaps inside
|
||||
the tail are 0.10 us per launch: 1.3 .. 4.1 us in LEL, 1.1 .. 1.3 us in VANL. At T = 1 the hyper-connection chain and the matmul are the same (20.5 against 21.8 us, 310.2 against 310.5); the
|
||||
tail differs there only by the pick (24.5 against 6.8 us).
|
||||
|
||||
### 3.2 Why the LEL head chain is per token
|
||||
|
||||
`plan_head_mix` (`original_verify_window_gr/plan_hc_read.rs`) launches the native `lm_head_mix` once per row: `mtp_full_gr_norm`,
|
||||
`bf16_gemv` (down, `mtp_full_mmvf256`), `mtp_full_down_silu`, `bf16_gemv` (up, `mtp_full_mmvf160`), `mtp_full_pre_final`, and
|
||||
the last layer's `plan_final_write` adds one `mtp_full_native_write` a row: **6 T launches**, each 0.7 .. 7 us and latency
|
||||
bound. VANL does one multi-token hyper-connection read (`output_hc_*` read as three launches), which is what
|
||||
`LELEKA_SM120_HEAD_MIX_MULTI` ports; that switch changes the summation order and is not bitwise (25 of 2057 rows moved), so
|
||||
it stays off. The loss is therefore the launch count of a per-token chain, not the arithmetic.
|
||||
|
||||
### 3.3 Where the 86.5 us go (LEL minus VANL, p50 per T, weighted at LEL's T mix; `compare` output)
|
||||
|
||||
| section | T1 | T2 | T3 | T4 | T5 (VANL mean of 4, 6) | T6 | weighted |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
|
||||
| tail total | +16.2 | +23.4 | +62.7 | +88.8 | +162.0 | +246.2 | **86.5** |
|
||||
| hyper-connection chain (last `add_hits` to the head quantize) | -1.3 | +12.7 | +26.6 | +38.9 | +52.2 | +64.8 | **31.2** |
|
||||
| head matmul (`head_n14_tN_large` against VANL's kernel) | -0.3 | -6.6 | +18.6 | +32.5 | +93.8 | +165.8 | **38.4** |
|
||||
| greedy pick + finite scan | +17.7 | +18.2 | +18.6 | +18.3 | +17.3 | +16.2 | **18.0** |
|
||||
| the extra VANL kernel before the matmul | 0 | -0.9 | -1.0 | -1.0 | -1.2 | -1.3 | -1.0 |
|
||||
| head quantize | +0.1 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
|
||||
The sum of the sections reproduces R8's +0.090 ms (86.5 us). LEL's weighted tail is 453.9 us, VANL's at that mix 367.3 us.
|
||||
|
||||
### 3.4 What can be removed, and how
|
||||
|
||||
| part | weighted | bitwise route | done here |
|
||||
| --- | ---: | --- | --- |
|
||||
| hyper-connection chain, `6 T` launches | 31.2 us | yes: same per-row kernels, row as `blockIdx.y`; the multi-column gemv has the same per-column fma chain | **yes, the switch** |
|
||||
| greedy pick: `chain_sampler_greedy_kernel` is one block of 1024 threads a token (25 us, 1 MB read at ~40 GB/s); VANL splits a token over 8 blocks (4.2-6.6 us) | up to 20 us (25.3 -> ~5 plus a merge) | yes: argmax with lowest-index ties is independent of the split, NaN never wins (`s > bv`), penalties are not used in the verify graph (`Address(0)` history). Needs a small scratch for the partials in `OriginalNativeHeadRows` (native_head, outside this scope) | no |
|
||||
| head matmul at T >= 3: LEL uses the "exact" multi-column layout (1 row a block, 4 warps; `multi_exact`, Original mode17), so 248,320 blocks; VANL 15,520 .. 62,080 blocks | 38.4 us | the existing `_upstream` kernels are NOT bitwise (the cross-warp reduction groups the sums differently). The sealed `head_n14_tN_small` kernels (4 rows a block, the per-row program unchanged by the source comment of `native_head_native.cu`) are the cheap experiment: a dispatch change in `native_head/dispatch.rs` for kind 14, T >= 3; unmeasured | no |
|
||||
| 2.8 us finite scan | in the 18.0 | `LELEKA_SM120_ACCEPT_ON_DEVICE` already puts it in the graph (off; no sign in CA.1) | no |
|
||||
|
||||
## 4. The switch `LELEKA_SM120_HEAD_CHAIN_BATCH`
|
||||
|
||||
Resolved in `original_verify_window_sm120.rs` (`Sm120Switches::head_chain_batch`, `DEFAULT_ON_HEAD_CHAIN_BATCH = false`, below
|
||||
12.x never taken), carried to the planners in `GrConfig::head_chain_batch` (like U5a's `down_fused`; decided in
|
||||
`prepare` before the assets load, so a requested switch whose PTX is not sealed fails the recording by name).
|
||||
|
||||
* **Final residual write.** `plan_final_write` of a group with >= 2 rows is ONE launch of `leleka_verify_final_write_rows`
|
||||
(grid `[40, rows]`), in place, instead of `mtp_full_native_write` a row.
|
||||
* **Head mix.** `plan_head_mix` with >= 2 rows is FIVE launches, whatever T:
|
||||
`leleka_verify_head_norm_rows` (grid `[4, T]`, 1024 threads) -> sealed `bf16_f32_mmvf_multi_kernel<256, 4|8>` (down) ->
|
||||
existing `mtp_full_down_silu` over the T x 320 contiguous `lo` floats -> sealed `bf16_f32_mmvf_multi_kernel<160, 4|8>` (up)
|
||||
-> `leleka_verify_head_pre_final_rows` (grid `[10, T]`).
|
||||
* One row keeps the literal launches. With `HEAD_MIX_MULTI` also on, the planner takes `plan_head_mix_multi` and only the
|
||||
residual write is batched. `head_quant`, the head matmul and the pick are unchanged.
|
||||
* Launches a graph: `6 T` -> `6` (one group; with two groups the writes are 2): `-(6 T - 6)`, 12 / 18 / 24 / 30 at T = 3 / 4 /
|
||||
5 / 6, about 15 at the mean T = 3.6 of the replay.
|
||||
|
||||
**Why it is bitwise.** The three new kernels are the bodies of `mtp_full_native_write`, `mtp_full_gr_norm` and
|
||||
`mtp_full_pre_final` with `blockIdx.y` as the row and the per-row bases added as arguments; no instruction order changes. They
|
||||
are compiled with `--fmad=true --use_fast_math`, the flags the two originals were resealed with (extra-seal-plan group
|
||||
`reseal-fastmath`), so `expf`, `rsqrtf` and the divisions lower to the same approximate PTX. The unit test
|
||||
`the_batched_kernels_use_the_arithmetic_of_the_kernels_they_batch` compares the float instruction sequence of each new entry with
|
||||
the sealed original: identical for the write (7 instructions) and the norm (64), per loop iteration for the pre-final mix (the
|
||||
originals' loop is unrolled differently, the iteration `mul.ftz, ex2.approx.ftz, add.ftz, rcp.approx.ftz, mul.rn.ftz, add.rn.ftz,
|
||||
selp` is the same). The gemv is the existing multi-column kernel: `acc[k] = fma(w1, x1, fma(w0, x0, acc[k]))` over the same
|
||||
pairs, the same shared-memory reset and the same warp tree as the single-column kernel, for each column k < T. The silu is
|
||||
element-wise on contiguous slots. All of these are the facts the model-free probe checks on the GPU (section 6).
|
||||
|
||||
**Not touched.** The arithmetic of the head's hyper-connection read (the thing `HEAD_MIX_MULTI` changed), `head_quant`, the matmul,
|
||||
the argmax, `executor_prefill*`, the profile JSONs, `original_verify_window_gpu_plan*`.
|
||||
|
||||
### Files
|
||||
|
||||
New: `crates/cuda-driver/src/sm120_head_chain.{cu,ptx}` (nvcc 13.2.86 in WSL: `--ptx -O3 -arch=sm_120 -std=c++17 --fmad=true
|
||||
--use_fast_math`, sha256 `6c9f80f9617d90ed637164621093aaa31ed67892fbcb03491f6eb076fb405ea8`),
|
||||
`original_verify_window_gr/head_chain.rs` (asset, resolve, the two plans), `original_verify_window_gr/tests/head_chain_launches.rs`,
|
||||
`original_verify_window_planner/tests/head_chain_batch.rs`, `tools/decode-sm120/sm120_probe_head_chain.cpp` +
|
||||
`build_head_chain.sh`, `scripts/e2e/codex/speed/verify_tail_report.py`. Edited (a few lines each): `original_verify_window_sm120.rs` (switch, own
|
||||
block), `original_verify_window_gr.rs` (field, module), `.../gr/assets.rs`, `.../gr/plan_hc_read.rs` (two dispatch lines),
|
||||
`.../ops/all_window_assets.rs` (resolve + asset), `scripts/gpu-bringup/extra-seal-plan.json`, `ptx-sm86/MANIFEST.json` ("not built
|
||||
for sm_86 by design").
|
||||
|
||||
## 5. Expected section delta (arithmetic, not a claim)
|
||||
|
||||
Per extra row the literal chain pays (p50 of `CP.1`): write 0.8 + norm 1.9 + down gemv 3.7 + silu 0.7 + up gemv 5.8 + pre-final
|
||||
1.2 = 14.1 us of kernels and 6 x 0.10 us of gaps = **14.7 us**. The batched chain pays for the first row what T = 1 pays (20.5 us
|
||||
from the last `add_hits` to the head quantize) plus the wider kernels. Upper bound of the saving of the section "hyper-connection
|
||||
chain" is therefore 14.7 x (T - 1) = 14.7 / 29.4 / 44.1 / 58.8 / 73.5 us at T 2..6, **35 us weighted at LEL's T mix** (mean T - 1 =
|
||||
2.39); the lower bound is what the wider kernels give back (the up gemv has T x 10,240 block-rows of work and is throughput
|
||||
bound, so not all of its 5.8 us per row disappears). My expectation is 0.02 .. 0.035 ms a graph, which would close 22 .. 39 % of
|
||||
R8's 0.090 ms. VANL parity for this section would be 31.2 us weighted. The matmul (38.4) and pick (18.0) stay.
|
||||
|
||||
## 6. What the orchestrator should look at
|
||||
|
||||
* **Probe** (model-free, on the GPU; built in WSL, not run):
|
||||
`tools/decode-sm120/build_head_chain.sh [OUTDIR]` then `OUTDIR/sm120_probe_head_chain OUTDIR/ptx`. It runs the literal six
|
||||
kernels a row against the batched launches for T = 1..8, three seeds (small, large, special values: -0.0, denormals, inf,
|
||||
nan), the write also for groups starting at row 1..7; every byte of R, xn, lo, gated and mixed is compared (buffers start
|
||||
as 0xCD, so a stray write shows). Expected: `SUMMARY failures=0`.
|
||||
* **Identity**: set only `LELEKA_SM120_HEAD_CHAIN_BATCH=1` (alone, then with the profile set) and run the teacher-forced
|
||||
top-16 + draft trace job: rows must be bit-identical, A/A first.
|
||||
* **CUPTI window**, per T within one variant (the tail section of `verify_tail_report.py`): launches in the tail 6 T + 4 -> 10
|
||||
(one group); kernels `mtp_full_native_write`, `mtp_full_gr_norm`, `mtp_full_mmvf256`, `mtp_full_down_silu`, `mtp_full_mmvf160`,
|
||||
`mtp_full_pre_final` drop to 0 (they stay elsewhere: `mmvf256` / `down_silu` in the PLE and projection paths), and
|
||||
`leleka_verify_final_write_rows` 1, `leleka_verify_head_norm_rows` 1, `leleka_verify_head_pre_final_rows` 1,
|
||||
`bf16_f32_mmvf_multi_kernel<256, 4|8>` +1, `bf16_f32_mmvf_multi_kernel<160, 4|8>` +1 come. The section to compare is "last
|
||||
`add_hits` end to the start of `head_quant`" (`hc` in the report): 35.7 / 50.4 / 65.8 / 81.3 / 96.1 us at T 2..6 in `CP.1`,
|
||||
20.5 at T 1. Note the window of the control and of the variant must be separate sessions with their own T mix: compare per T.
|
||||
* The engine log prints `leleka-serve head chain batch: on` once when the switch resolved.
|
||||
|
||||
## 7. Not finished / next
|
||||
|
||||
* Greedy pick (18.0 us weighted, bitwise, needs a scratch buffer in `OriginalNativeHeadRows`) and the head matmul at T >= 3
|
||||
(38.4 us, first experiment: the `_small` 4-rows-a-block kernels of kind 14) are the larger remaining parts of R8 and
|
||||
are not launch-count fusion; both are outside the files of this step.
|
||||
* The probe and the identity run need the GPU; the PTX is built (nvcc 13.2.86 in WSL) and byte-pinned.
|
||||
* Ledger rows to update after the orchestrator's windows: R6 (closed by side streams, residual +0.006 ms), R7 (no gap), R8 (this
|
||||
decomposition; the switch as the fix for the 31.2 us part).
|
||||
@@ -0,0 +1,154 @@
|
||||
# VRAM hit share of the routed experts: why ours is below vanilla, and what to try (ledger C6, H1-H7)
|
||||
|
||||
Date 2026-11-11. Research only: no host code, no GPU, no server writes (read-only `ssh rnr5090`, `nice`, stdlib Python). Branch `claude/hit-share-gap`.
|
||||
Labels: M measured in the run or log named, E estimate or model, U unverified. Nothing here is a performance claim; the speed numbers quoted are from earlier paired A/B runs, recomputed from their logs.
|
||||
|
||||
## 0. Answer first
|
||||
|
||||
The hit share of the 30-request replay (`nestng-crm-r2`, token-weighted by output tokens) is **92.1 % for ours (adaptive window, 76 blocks) against 93.4 % for vanilla (two replays)**; unweighted per request 90.2 against 91.8. With vanilla's fixed window (B, one block) the gap is smaller: 92.7 against 93.4 (unweighted 90.8 against 91.8). The H1 figures (90.8 against 92.8, -2.0) are not reproducible from the surviving logs (section 1); the gap is **-0.7 to -1.3 points token-weighted, -1.0 to -1.6 unweighted**.
|
||||
|
||||
The tier policy is the same code as vanilla's and swaps at the same rate. What differs, in order of measured weight:
|
||||
|
||||
| rank | cause | evidence | share of the gap (token-weighted) |
|
||||
| ---: | --- | --- | ---: |
|
||||
| 1 | **Fewer VRAM slots**: 12,192 (254 in every layer) against 12,575 | clean paired A/B: +192 slots give +0.44 points (CI +0.24..+0.64), so 383 slots are worth about +0.9 (M, extrapolated) | about 0.9 of 1.3 |
|
||||
| 2 | **Wider speculation window**: ours adapts the window up to T=8, vanilla runs T<=6 at 2.95 tokens a round. Hit share per entry falls with T inside our own run: 96 % at T<=3, 94.8 % at T=4, 90.5 % at T=7-8 | B (fixed window 4) is 0.55 points above A (n=1 B, M); within-run curve (M, one run) | about 0.55 of 1.3 (absent when B is compared) |
|
||||
| 3 | **Global against per-layer slot allocation**: vanilla gives layers 173 to 372 slots from the global rank of the profile, ours 254 each | the layers vanilla favours show the excess misses in ours (r = 0.82 over 48 layers, M); the net hit share effect is second order, E +0.12..+0.16 points at equal slot count | about 0.15 (E) |
|
||||
| - | tier policy constants, swap volume, tie order, seed, prefix cache | identical constants; 15.6 against 13.1 swaps a round; tie order A/B +0.04 (CI -0.20..+0.29); seed off in both; nothing in the prefix path touches the tier | 0 within noise |
|
||||
| - | first rounds of a request (H7) | ours: 79 % in windows 0-3, 85 % in 16-31, 90 % in 32-63, 93 % from window 128 (M, one run); the first 64 windows carry 20 % of all misses; vanilla cannot be measured per window | a property of both engines; not a gap cause that can be shown |
|
||||
|
||||
The sum of 1-3 (1.5) is about the observed gap (1.3 token-weighted, 1.6 unweighted), so **no large unexplained policy or start-up effect is left**; the three do not separate cleanly (section 5).
|
||||
|
||||
Two things the same data say that matter more than the parity question: (1) the cap of 96 swaps binds in every short request in both engines (21-25 swaps a round = 96 / 4), and adapting every 2 rounds already gave **+0.56 points of hit share and +1.31 % decode (CI +0.77..+1.85, n=5 pairs)** (M); (2) the rounds at the start of a request hold 20 % of all misses (section 2, H7). Both are ways to go above vanilla, not to reach it.
|
||||
|
||||
## 1. Data and definitions
|
||||
|
||||
* Ours: the `engine.log` request line of every replay block (`tier_vram_pct` = VRAM entries / (VRAM + PCIe + CPU entries), entries per row of every window, rejected draft rows included; `crates/leleka-memory/src/telemetry/lock.rs`, `source_spans.rs` `tally_group`). Vanilla: `strata serve: decode expert cache hit rate ... of all N routed` (hits / all routed entries, `N` = rows x 480). Same quantity. Route tail skip is OFF in A, B, L, D, H, W*, X, so all of them are comparable; the E/T/K arms skip entries, are not in `all`, and show 93.6-95 %: **not comparable to vanilla**.
|
||||
* Replay: the 30 first requests of VANL `nestng-crm-r2`, the same recorded prompts through both engines. Ours: `runs/ab-l1`, `ab-l3`, `ab-l3v2`, `ab-l5v2`, `ab-l6`, `ab-l7`, `ab-sm`, `ab-sqe`, `ab-sqn`, `ab-w`, `memory-tier-tie-spread-ab`, `main/{A,B,P}` under `/data/leleka-e2e/spd-gap/runs/`. Vanilla: `main/VANL-noprof` and `main/VANLP` (the only two vanilla replay logs, engine 0.1.50 at pin `41cf05a0`, `--spec 4 --spec-min-p 0.5`, `--expert-cache auto`, profile sha256 `8f59b4aa...` = ours, `--expert-profile /home/para/work/vanilla-strata/control/data/expert-profile.bin`).
|
||||
* Script: `scripts/e2e/codex/speed/hit_share_gap.py` (`arms`, `pairs`, `requests`, `windows`, `swaps`; run on the server with `nice python3 -I - CMD < script`), `hit_share_layers.py` (local).
|
||||
|
||||
Hit share of the first 30 requests (M, `hit_share_gap.py arms`):
|
||||
|
||||
| source | blocks | token-weighted | unweighted | time-weighted | tokens/round |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: |
|
||||
| ours A (adaptive window): per experiment, A and L arms of nine experiments (76 A blocks pooled in the per-request table) | 5-10 each | 92.05-92.25 (sd 0.2-0.3 per block) | 90.2 | 92.1-92.3 | 3.9 |
|
||||
| ours B (fixed window 4, floor 0.5), `main/B` | 1 | 92.66 | 90.76 | 92.67 | 3.09 |
|
||||
| vanilla `VANL-noprof` | 1 | 93.32 | 91.84 | 93.40 | 2.95 (ledger Q9) |
|
||||
| vanilla `VANLP` | 1 | 93.49 | 91.75 | 93.59 | |
|
||||
|
||||
H1 (90.8 against 92.8): the ours side is close to B over the 59-request replay (both cells, unweighted 90.94); the 92.8 on the vanilla side I cannot reproduce from the two surviving replays of 30 requests (91.8 unweighted, 93.6 entry-weighted). Real sessions (H2, `session_hit.py` re-run, M): nestng-crm 91.38 against 92.41 (-1.03), ttt 92.68 against 93.38 (-0.70).
|
||||
|
||||
## 2. Cause by cause
|
||||
|
||||
### (a) Slots
|
||||
|
||||
* Ours: `expert cache 12192 slots (23.24 GiB, per layer)` = 254 x 48 (`runs/main/A/engine.log`); the prompt path lends its last 2,226. Vanilla: `expert cache 12575 slots, 23.87 GiB`, lends 2,089 (`main/VANL-noprof/engine.log`). `LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=8000` is only the identity-job setting (a static tier for bitwise comparisons); the product runs `auto`.
|
||||
* The 383 slots are 744 MiB: 647 MiB less free VRAM before the cache (24,717 against 25,364 MiB: second token table 324, PLE row cache 64, prompt stage and MoE arena, `vram-footprint-5090.md` section 2 and `vram-footprint2-5090.md`) and 97 MiB more reserve (ours 700 + 300 against vanilla 700 + 218 for its draft head). The planner grows in whole 48-slot quota steps (`vram-footprint3-5090.md`: reserve 130 freed 170 MiB and added 48 slots).
|
||||
* **Slope (M)**: `ab-l3v2`, 10 pairs, H (reserves 130 / 500 MiB, 12,384 slots) against A (12,192): hit share +0.44 points token-weighted (CI +0.24..+0.64), +0.41 unweighted; decode tok/s +0.67 % (CI +0.02..+1.31), ms/round -2.10 % (CI -3.61..-0.59), tokens/round -1.45 % (CI -3.20..+0.31). That is 0.23 points per 100 slots, so 383 slots = +0.88 points (CI 0.48..1.28 if linear).
|
||||
* Why "H gained nothing" earlier: the first attempt G (`--gpu-budget-gib 31`) opened the same 12,192 slots in both arms (the card binds, not the budget): a null experiment. The first H pairs ran with leaked variables (`spd_ab_job.sh` did not unset them, `ab-l3h-contaminated`, not evidence). The clean rerun above is a real, significant hit-share and ms/round gain; the end-to-end figure (+1.06 %, CI -0.38..+2.50) is just not significant. `vram-footprint3-5090.md` (3 pairs, `both` = alias + reserve 130, 12,384 slots, lowest free 355 MiB, +1.69 % tok/s) agrees in sign and is inside its noise. Free VRAM at decode: H cuts the reserves by 370 MiB; the 130 MiB decode reserve alone keeps 407 MiB (vanilla runs at 315-389); the 500 MiB VRAM reserve is what goes below vanilla's floor (E, not read in a log).
|
||||
|
||||
### (b) Initial placement, per-layer against global
|
||||
|
||||
* Same profile in both (sha256 `8f59b4aa8873...`, ours `ours-assets/data/expert-profile.bin`). **Vanilla's log says `PROFILE, ranked by routing frequency, no eviction` and `pre-filled 12575 of 12575 slots`**: global fill (no `--expert-cache-per-layer`), so the layer quotas are the counts of each layer in the first 12,575 ranks of the profile. Ours: `LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes` (profile `rtx5090-32g.json`), every layer 254. Quotas of the global fill (profile bytes, M): min 173 (layer 15), max 372 (layer 0), 31 layers above 254; 680 slots sit in a different layer than in ours at equal slot count (888 at 12,575). Swaps are paired inside a layer in both engines, so the quotas never change after the start.
|
||||
* **Per-layer evidence (M)**: CUPTI windows of request 29 (`cupti/VANL`, `cupti/CL.1`, `verify-new-switches-cupti-windows/CY.1`, `hit_share_layers.py`): share of layer-windows with a miss leg (class C or X of `ffn_phase_timeline.py`) per layer, ours minus vanilla, against the quota difference: Pearson **0.82** (0.78 at T 3-4 only). 16 layers where vanilla has 20 or more extra slots (avg +48): ours has **+0.196** more miss-leg layer-windows; 9 donor layers (avg -45): **-0.095**; the 23 neutral layers +0.028. OLS slope 0.0027-0.0031 of miss-leg share per slot. The quota is therefore visible per layer.
|
||||
* **Net effect (E)**: reallocating at equal slot count only exchanges pairs near the rank boundary, whose calibration frequencies are close. A power-law model f(rank) ~ rank^-alpha over the profile's global ranks gives +0.12 to +0.16 points for global against uniform fill at 12,192 slots (alpha 0.5-0.9), and +0.44..+1.10 for the 383 extra slots (0.79 at alpha 0.7 = 0.21 per 100 slots, close to the measured 0.23). So the quota is real but worth about one eighth of the gap. The October `o-global` arm (n=5, VRAM share 78-84 %) found "no difference", which is consistent with that size (noise 3 points there).
|
||||
* Static placement for reference (M, `id-l1`, FA arms, tier frozen, per-layer uniform): 62.3 % token-weighted. Vanilla has no frozen arm.
|
||||
|
||||
### (c) Adaptive swap policy
|
||||
|
||||
* Source, line for line: vanilla `generate.cpp:10431-10458` (per layer: candidates = non-resident with count >= 2.0, victims = resident, sorted, paired while `cand >= vict + 1.5`, all layers sorted by gain, first 96); ours `split_group_pcie.rs` `choose_swaps_by` (the same). Every 4 verify rounds, decay 0.7, usage counted per routed entry of every window row (vanilla `expert_source.cpp:4826`, ours `note_usage`). The warm-up interval `STRATA_SPEC_ADAPT_EVERY=2 / WARM=200` exists in vanilla only for sm_86 and opt-in (`nv_defaults.cpp`): not active on the 5090. One difference: equal-gain swaps compete for the cap in unspecified `std::sort` order in vanilla, low layer first in ours. A/B `memory-tier-tie-spread-ab` (`LELEKA_ADAPT_TIE_SPREAD=on`, 5 pairs): hit +0.04 (CI -0.20..+0.29), tok/s +0.10 % (CI -0.73..+0.94): neutral (M).
|
||||
* Swap volume (M, `hit_share_gap.py swaps`, 30 requests): ours 15.6 swaps a round (62 per adaptation), vanilla 13.1 a window. In short requests both sit at 21-25 a round = the cap (96 / 4): the cap binds in both. Knobs on ours (`ab-w`, 5 pairs each, A against variant):
|
||||
|
||||
| variant | hit share (token-w) | tok/s | ms/round | tokens/round |
|
||||
| --- | ---: | ---: | ---: | ---: |
|
||||
| W1 adapt every 2 | **+0.56** (CI +0.26..+0.86), unweighted +0.89 | **+1.31 %** (CI +0.77..+1.85) | -2.23 % (CI -4.46..+0.01) | -0.94 % (CI -2.99..+1.11) |
|
||||
| W2 192 swaps | +0.71 (CI +0.46..+0.96) | -1.07 % (CI -2.04..-0.09) | -1.28 % | -2.33 % (CI -4.43..-0.23) |
|
||||
| W3 decay 0.85 | +0.14 (CI -0.27..+0.54) | -0.08 % | -0.62 % | -0.67 % |
|
||||
| W4 margin 1.0 | +0.30 (CI -0.11..+0.71) | -1.07 % | -1.44 % | -2.54 % |
|
||||
|
||||
The tier lags behind the text in both engines; more swap capacity buys hits at both. These are placement-class changes (output differs slightly). n=5 pairs is below the 10-pair rule of the ledger.
|
||||
|
||||
### (d) Seed, warm start, prefix cache (H7)
|
||||
|
||||
* Seed: `LELEKA_ORIGINAL_SERVE_SEED=off` in the 5090 profile; vanilla has none. Usage counts live with the stack across requests in both; the prefix cache and the lent-slot refill do not touch them (ours refills the lent slots with their own previous experts; `LELEKA_REFILL_DEFER` A/B: hit 92.18 against 92.11).
|
||||
* **Request start (M, `prof-l5/Q.1`, one diagnostic profiled run (`LELEKA_BRINGUP_TRACE`, prefill sync drains; its hit share 91.66 is inside the A blocks' spread), per-window `DBG window` lines, requests 3-30; `hit_share_gap.py windows`)**:
|
||||
|
||||
| windows since request start | rows | hit share | share of all misses |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| 0-3 | 350 | 79.3 % | 1.7 % |
|
||||
| 4-7 | 408 | 82.9 % | 1.6 % |
|
||||
| 8-15 | 691 | 84.1 % | 2.5 % |
|
||||
| 16-31 | 1,725 | 85.5 % | 5.7 % |
|
||||
| 32-63 | 3,697 | 90.2 % | 8.3 % |
|
||||
| 64-127 | 7,038 | 91.3 % | 14.0 % |
|
||||
| 128-255 | 11,229 | 93.2 % | 17.4 % |
|
||||
| 256 and more | 30,067 | 92.6-93.1 % | 49 % |
|
||||
|
||||
The tier at the start of a request is the state of the previous request's last rounds (counts decayed by 0.7 every 4 rounds: a memory of about 12 rounds), not of the new content. The first 64 windows carry 20 % of all misses; against the steady 6.9 % miss rate they hold an excess worth **0.71 points of the overall hit share** (ceiling). The first two requests of a cold engine are the worst: ours 82.7 and 88.1 against vanilla 86.4 and 92.4 (-3.7, -4.3; profile placement only, about 11 adaptations, so slots + quota + the first swaps).
|
||||
* Vanilla's short-request deficit (H3, nestng-crm -3.0) is not a stable effect: in the paired replay the buckets by output length are (token-weighted / unweighted, ours minus vanilla) < 600 tokens -0.22 / -1.43, 600-2000 -1.37 / -1.92, >= 2000 -1.16 / -1.43; ttt shows +0.1 for < 600 tokens in the real sessions. The large single-request gaps (requests 12, 22, 15: -5.7, -5.1, -3.3) are requests where the two engines generated different lengths (vanilla 2,580 against 399 tokens ours in request 12), i.e. different text.
|
||||
|
||||
### (e) Window width
|
||||
|
||||
* Ours adapts the window (A: 3.9 tokens a round, T up to 8); vanilla `--spec 4` (windows up to 6 rows, 2.95). Entries count every row, so wide windows weigh heavily: 33 % of our rows are T=8 windows. Hit share by window rows inside our run (M, Q.1, windows >= 64, requests 3-30): T=1 95.95 %, T=2 96.34, T=3 96.04, T=4 94.80, T=5 93.23, T=6 91.83, T=7 90.54, T=8 90.52 (content confounded: wide windows come with repetitive text).
|
||||
* B (fixed window, tokens/round 3.09) against A in the same code: 92.66 against 92.13 token-weighted (+0.55), 90.76 against 90.2 unweighted (+0.55). D (adaptive window with floor 0.5) shows no change (92.10 against 92.15), so it is the width, not the floor. B is one block (A sd 0.2-0.3), so this is an indication.
|
||||
|
||||
## 3. Decomposition (token-weighted, first 30 requests; M unless marked)
|
||||
|
||||
| item | points |
|
||||
| --- | ---: |
|
||||
| ours A minus vanilla | -1.3 (-1.6 unweighted) |
|
||||
| slots, 383 x 0.23 / 100 | +0.88 (CI 0.48..1.28) |
|
||||
| window width (B minus A) | +0.55 (n=1 B) |
|
||||
| global allocation at equal slots (E) | +0.12..+0.16 |
|
||||
| sum of the three | 1.55..1.6 |
|
||||
| ours B minus vanilla (like for like in width) | -0.7 (-1.0 unweighted); slots + quota = 1.0 |
|
||||
|
||||
The effects are not additive in general and the vanilla side has two blocks, so the table says "consistent within the noise", not "proved".
|
||||
|
||||
## 4. What is NOT comparable
|
||||
|
||||
* Real sessions (H2, H3): the two engines run different agent trajectories, (the logs hold different numbers of requests), so request-length buckets mix different tasks; the short-request gap is one session (nestng-crm -3.0, ttt +0.1).
|
||||
* Replay requests differ in text after the first requests (the two engines generate different outputs; prompts +228 tokens of template in ours, 10,187 against 9,959): per-request differences above about 2 points are mostly different text. Only pooled and weighted figures are usable.
|
||||
* The E/T/K arms (tail skip on): entries skipped are not counted; 93.6-95 % there is not a hit share.
|
||||
* Weights: token-weighted (long requests: request 3 alone is 8,401 tokens, 97 %) against unweighted differ by 2 points in level and by 0.3 in gap; always state which.
|
||||
* Vanilla's per-window hit share is not logged (only the request total and the `decode timing` line), so H7 cannot be compared per window; the CUPTI class shares are one request (29), two ours windows against one vanilla window with a different T mix (vanilla T=4 in 64 % of layer-windows, ours T=2-3).
|
||||
* `LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=8000` is not a product setting; no hit-share figure of the identity jobs says anything about the tier.
|
||||
|
||||
## 5. What the data cannot separate
|
||||
|
||||
* The quota effect (b) from the slot effect (a) in the measured hit share: no run has vanilla's quotas at ours slot count (or the reverse). The per-layer data prove the quota matters per layer; the net is estimated by a model only.
|
||||
* The width effect (e) from the content: one B block.
|
||||
* Anything at window resolution for vanilla (H7), and the part of H7 that is "unadapted tier" against "new text is different".
|
||||
* Whether the early-request excess (0.71 ceiling) is recoverable: nothing has tried to pre-warm the tier on a warm engine at agent-turn size (the seed tests of `original-serve.md` reset the tier to the profile before every request; the 245k tests used huge prompts).
|
||||
|
||||
## 6. Ranked changes to try
|
||||
|
||||
| # | change | knob | expected gain | how to measure | owner |
|
||||
| ---: | --- | --- | --- | --- | --- |
|
||||
| 1 | **Close the slot gap** with the opt-ins that exist: alias + decode reserve 130 (`both` of footprint3: 12,384 slots, lowest free 355 MiB >= vanilla 315) and global fill (no 48-slot quota step, uneven quotas) | `LELEKA_PROMPT_EMBED_ALIAS=1 LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB=130`, then `+ LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=no` | hit +0.44 for the first (M: same 12,384 slots as H), +0.6..+0.9 with the quota step gone and vanilla's quotas (E); ms/round -2 % (M for H) | new `spd_ab_job.sh` variants (`SL`, `SLG`), 10 pairs each against A, `hit_share_gap.py pairs`; read `expert cache N slots` from each log; free VRAM at decode (`DBG vram decode after assemble`, profile run) must stay >= 315 MiB; placement-class gate against the control placement. Add `LELEKA_PROMPT_EMBED_ALIAS` and `LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER` to the unset list first (the leak that invalidated `ab-l3h`); the profile sets PER_LAYER=yes and `engine_launch.rs` lets the `up`-resolved environment win, so check that `leleka up` forwards the shell variable (the October `o-global` arm did) by the log line `expert cache N slots` losing its `per layer`; the A blocks must leave it unset | env only; uneven quotas in code: `original_cache_startup`, `cache_strata_adaptive/reserve.rs`: host/tier (hex-finish) |
|
||||
| 2 | **Faster tier in the cap-bound first rounds**: adapt every 2 (measured), then a request-start warm-up (interval 2 and/or cap 192 only for the first 64 windows of a request, vanilla's own `STRATA_SPEC_ADAPT_EVERY/WARM` mechanism, which vanilla enables only on sm_86) so steady-state swap cost does not rise | `LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=2` (variant W1 exists); warm-up needs code | W1: +0.56 hit, +1.31 % tok/s (n=5, M). Warm-up: bounded by the 0.71 early-excess ceiling, E +0.3..+0.5 | W1 with 10 pairs (`ab-w` variant, `SPD_VARIANTS` 10 blocks), then the warm-up variant; cost side: `adapt.queue` / `round.apply_pending` spans in a P run | env: nobody; warm-up code in `original_serve_residency/source_spans.rs` (`begin_adaptation`) and `split_group_pcie.rs` (`adapt_tuning`): host/tier (hex-finish) |
|
||||
| 3 | **Offline tier simulator on one routing dump**, so every policy question above is answered in seconds, not 1-hour A/Bs | one replay with `LELEKA_ORIGINAL_SERVE_DUMP_ROUTING=<path>` (variant A plus the variable, about 6 min, about 230 MB, ignored path) and a Python simulator (allowed for experiments) | decides global against uniform at equal slots, accepted-rows-only usage counting (rejected rows pollute the counts; hit falls with T), decay / margin / cap / interval grid, request-start carry-over, before any GPU A/B | calibrate first: simulated A must reproduce 92.1 / 90.2 and the start-of-request curve of section 2 within 0.3; the dump has per-row records only (layer resets mark windows), so the dump should also carry request id and accepted-row count: a few lines in `record_routing` | dump change: host/tier (hex-finish); simulator: any |
|
||||
| 4 | Warm the tier from the new prompt tail (lowest priority) | `LELEKA_ORIGINAL_SERVE_SEED=1 LELEKA_ORIGINAL_SERVE_SEED_USAGE=0.02 LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS=4096` (one swap, prompt counts added to the usage) | at most the same 0.71 ceiling; U | 10-pair A/B; all earlier seed tests started from a reset tier, none from a warm one | env only |
|
||||
|
||||
Not proposed: tie order (neutral), decay (+0.14, CI crosses 0), margin 1.0 (tok/s -1.07 %), cap 192 alone (tok/s -1.07 %, CI -2.04..-0.09; the cap is only worth it for the first rounds).
|
||||
|
||||
Host/tier files (hex-finish): `original_serve_residency.rs` and `original_serve_residency/*` (policy, swap choice, counts, `open_tier`, seed hook), `original_serve_seed.rs`, `original_cache_startup.rs`, `cache_strata_adaptive/*`, `settings/memory.rs`, `original_serve_pool.rs`, and the `spd_ab_job.sh` variants. Device code is not involved in any of the four.
|
||||
|
||||
## 7. Proposed ledger edits (not made)
|
||||
|
||||
* H1: restate as -0.7 (B) / -1.3 (A) points token-weighted and -1.0 / -1.6 unweighted over the 30-request replay (sources above); the 92.8 figure has no surviving log.
|
||||
* H4: add the slope 0.23 points per 100 slots (A/B `ab-l3v2`, M) and the composition of the 383 slots (744 MiB).
|
||||
* H5: neutral (`memory-tier-tie-spread-ab`, 5 pairs, +0.04, CI -0.20..+0.29): `proved-equal`.
|
||||
* H6: W1 +0.56 points / +1.31 % tok/s (n=5), W2 +0.71 / -1.07 %, W3 +0.14, W4 +0.30 (all M, 5 pairs).
|
||||
* H7: isolated for ours (section 2: 79 % to 93 % over the first 128 windows, 20 % of all misses in the first 64); vanilla not measurable.
|
||||
* New row: global against per-layer quotas, per-layer evidence r = 0.82, net E +0.12..+0.16.
|
||||
|
||||
## 8. Reproduction
|
||||
|
||||
```
|
||||
S=scripts/e2e/codex/speed/hit_share_gap.py
|
||||
for c in arms "pairs ab-l3v2 A H 10" "pairs ab-w A W1 5" requests windows swaps; do ssh rnr5090 "nice python3 -I - $c" < $S; done
|
||||
# per-layer (local; the json.gz come from ffn_phase_timeline.py extract, ffn-phase-loss-design.md section 6)
|
||||
python3 -I scripts/e2e/codex/speed/hit_share_layers.py crates/deploy/data/expert-profile.bin VANL.json.gz CL.1.json.gz CY.1.json.gz
|
||||
python3 -I - < scripts/e2e/codex/speed/session_hit.py # on the server: H2 / H3
|
||||
```
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
# Group A/B of the VANL PcieAuto share controller (LELEKA_ORIGINAL_SERVE_PCIE_AUTO=on, placement class, step of ledger V2/H) against the final profile set PG, n = 5 pairs, one binary bin-pcie-auto.
|
||||
# First 30 requests of VANL nestng-crm-r2, floor profile. Report: ab_report.py RUN_DIR PG PA, plus the controller's update lines (stderr "PCIe share") from each PA engine.log for the settled share.
|
||||
unset SPD_VARIANTS SPD_CELLS SPD_OUT SPD_MAX SPD_TUNES SPD_BIN
|
||||
export SPD_BIN=/data/leleka-e2e/spd-gap/bin-pcie-auto SPD_VARIANTS="PG.1 PA.1 PA.2 PG.2 PG.3 PA.3 PA.4 PG.4 PG.5 PA.5" SPD_MAX=30 SPD_CELLS=/data/leleka-e2e/codex-compare/runs/main/VANL/nestng-crm-r2 SPD_OUT=/data/leleka-e2e/spd-gap/runs/decode-pcie-auto-group-ab-pg-vs-pa
|
||||
exec bash /data/leleka-e2e/spd-gap/tools/spd_ab_job_x.sh
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
# Group A/B of two env-only tier levers against the final profile set PG (placement class, experiments 1 and 2 of docs/experiments/vram-hit-share-gap.md), n = 5 pairs each, one binary bin-pcie-auto (both switches off in it):
|
||||
# PS = PG + LELEKA_PROMPT_EMBED_ALIAS=1 + LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB=130 (12,384 slots against 12,192; free VRAM at decode must stay >= 315 MiB: read DBG vram lines / status), PW = PG + LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=2.
|
||||
# Report: ab_report.py RUN_DIR PG PS ; ab_report.py RUN_DIR PG PW ; plus `expert cache N slots` from each engine.log.
|
||||
unset SPD_VARIANTS SPD_CELLS SPD_OUT SPD_MAX SPD_TUNES SPD_BIN
|
||||
export SPD_BIN=/data/leleka-e2e/spd-gap/bin-pcie-auto SPD_VARIANTS="PG.1 PS.1 PW.1 PW.2 PS.2 PG.2 PG.3 PS.3 PW.3 PW.4 PS.4 PG.4 PG.5 PS.5 PW.5" SPD_MAX=30 SPD_CELLS=/data/leleka-e2e/codex-compare/runs/main/VANL/nestng-crm-r2 SPD_OUT=/data/leleka-e2e/spd-gap/runs/decode-slots-and-adapt-every-group-ab-pg-vs-ps-pw
|
||||
exec bash /data/leleka-e2e/spd-gap/tools/spd_ab_job_x.sh
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
# Group A/B at the end of the stage (owner rule 2026-11-10, n = 5 pairs): PB = the 5090 profile set before the QSA prelude, the fused commit and the combine vec4;
|
||||
# PG = the final profile set of the stage as the profiles carry it (+ prelude, fused commit, combine vec4, down sub16, hits in combine). Same binary bin-ffn-switches (the switches come from the variant, not from a profile file). Re-measures the decode step of R1 after the whole stage: how many ms/round of the +1.98 are closed.
|
||||
# First 30 requests of VANL nestng-crm-r2, floor profile, order ABBA-like to cancel drift. Report: ab_report.py RUN_DIR PB PG.
|
||||
unset SPD_VARIANTS SPD_CELLS SPD_OUT SPD_MAX SPD_TUNES SPD_BIN
|
||||
export SPD_BIN=/data/leleka-e2e/spd-gap/bin-ffn-switches SPD_VARIANTS="PB.1 PG.1 PG.2 PB.2 PB.3 PG.3 PG.4 PB.4 PB.5 PG.5" SPD_MAX=30 SPD_CELLS=/data/leleka-e2e/codex-compare/runs/main/VANL/nestng-crm-r2 SPD_OUT=/data/leleka-e2e/spd-gap/runs/decode-stage-group-ab-profile-set-pb-vs-pg
|
||||
exec bash /data/leleka-e2e/spd-gap/tools/spd_ab_job_x.sh
|
||||
@@ -0,0 +1,194 @@
|
||||
"""VRAM hit share of the routed experts, ours against vanilla (docs/experiments/vram-hit-share-gap.md).
|
||||
|
||||
Read-only, stdlib only, no GPU; run on the server with `nice python3 -I - SUBCOMMAND ... < hit_share_gap.py`.
|
||||
arms hit share per experiment and arm: token-weighted, unweighted, time-weighted, tok/round
|
||||
pairs EXP A B N paired A/B (blocks A.1..A.N against B.1..B.N): decode tok/s, ms/round, hit share
|
||||
requests per request of the 30-request replay: pooled A arms against the two vanilla replays
|
||||
windows hit share by window index since the request start and by window rows T (Q.1 trace)
|
||||
swaps adaptive swaps per round: ours (P run, DBG tier) against vanilla (VANLP timing lines)
|
||||
Definitions: the hit share is VRAM entries / all routed entries (every row of every window counts, rejected draft rows
|
||||
too), the same quantity as vanilla's "hits / all routed". Weights: otok = generated tokens of the request.
|
||||
"""
|
||||
import collections
|
||||
import glob
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import statistics as st
|
||||
import sys
|
||||
|
||||
R = "/data/leleka-e2e/spd-gap/runs"
|
||||
T95 = {2: 4.303, 3: 3.182, 4: 2.776, 9: 2.262}
|
||||
|
||||
|
||||
def lel(path):
|
||||
"""Per-request rows of an engine.log of ours (the engine's one structured line per request)."""
|
||||
rows = []
|
||||
for line in open(path + "/engine.log", errors="replace"):
|
||||
if line.startswith("{") and '"ev":"request"' in line and '"comp":"engine"' in line:
|
||||
j = json.loads(line)
|
||||
if "tier_vram_pct" in j:
|
||||
rows.append(dict(ptok=j["ptok"], otok=j["otok"], rounds=j["rounds"], tpr=j.get("tok_per_round"),
|
||||
dec_ms=j["dec_ms"], v=j["tier_vram_pct"], p=j["tier_pcie_pct"], c=j["tier_cpu_pct"]))
|
||||
return rows
|
||||
|
||||
|
||||
def van(path):
|
||||
"""Per-request rows of a vanilla engine.log: the `prompt ...` line, then its `hit rate` line."""
|
||||
rows, cur = [], {}
|
||||
pat_p = r"strata serve: prompt (\d+) tokens = (\d+) reused \+ (\d+) read in .*?(\d+) generated in ([\d.]+) ms"
|
||||
pat_h = r"hit rate: [\d.]+% \((\d+) hits / (\d+) lookups\); (\d+) more.*?of all (\d+) routed"
|
||||
for line in open(path + "/engine.log", errors="replace"):
|
||||
m = re.search(pat_p, line)
|
||||
if m:
|
||||
cur = dict(ptok=int(m[1]), otok=int(m[4]), dec_ms=float(m[5]))
|
||||
m = re.search(pat_h, line)
|
||||
if m and cur:
|
||||
routed = int(m[4])
|
||||
cur.update(v=100 * int(m[1]) / routed, p=100 * int(m[3]) / routed,
|
||||
c=100 * (int(m[2]) - int(m[1])) / routed, routed=routed)
|
||||
rows.append(cur)
|
||||
cur = {}
|
||||
return rows
|
||||
|
||||
|
||||
def wavg(rows, key="v", weight="otok"):
|
||||
return sum(r[key] * r[weight] for r in rows) / sum(r[weight] for r in rows)
|
||||
|
||||
|
||||
def metrics(path, n=30):
|
||||
rows = lel(path)[:n]
|
||||
ot, ms, rd = (sum(r[k] for r in rows) for k in ("otok", "dec_ms", "rounds"))
|
||||
return dict(tps=1000 * ot / ms, msr=ms / rd, tpr=ot / rd, v=wavg(rows), vu=st.mean(r["v"] for r in rows))
|
||||
|
||||
|
||||
def replay_dirs():
|
||||
"""Experiment dirs whose replay starts with the 10,187-token request of nestng-crm-r2 and has >= 30 requests."""
|
||||
for d in sorted(glob.glob(R + "/*/*")):
|
||||
if os.path.isfile(d + "/engine.log") and "contaminated" not in d:
|
||||
rows = lel(d)
|
||||
if len(rows) >= 30 and rows[0]["ptok"] == 10187:
|
||||
yield d, rows
|
||||
|
||||
|
||||
def cmd_arms():
|
||||
agg = collections.defaultdict(list)
|
||||
for d, rows in replay_dirs():
|
||||
exp, arm = d[len(R) + 1:].split("/")
|
||||
agg[(exp, arm.split(".")[0])].append((wavg(rows[:30]), st.mean(r["v"] for r in rows[:30]),
|
||||
wavg(rows[:30], weight="dec_ms"), st.mean(r["tpr"] for r in rows[:30])))
|
||||
for key, v in sorted(agg.items()):
|
||||
print("%-52s n=%2d token-w %.2f (sd %.2f) | unweighted %.2f | time-w %.2f | tok/round %.2f" % (
|
||||
key, len(v), st.mean(x[0] for x in v), st.pstdev(x[0] for x in v), st.mean(x[1] for x in v),
|
||||
st.mean(x[2] for x in v), st.mean(x[3] for x in v)))
|
||||
for name in ("VANL-noprof", "VANLP"):
|
||||
rows = van(R + "/main/" + name)[1:31]
|
||||
print("%-52s token-w %.2f | unweighted %.2f | time-w %.2f | entry-w %.2f" % (
|
||||
name, wavg(rows), st.mean(r["v"] for r in rows), wavg(rows, weight="dec_ms"),
|
||||
wavg(rows, weight="routed")))
|
||||
|
||||
|
||||
def cmd_pairs(exp, a, b, n):
|
||||
pairs = []
|
||||
for k in range(1, int(n) + 1):
|
||||
pa, pb = "%s/%s/%s.%d" % (R, exp, a, k), "%s/%s/%s.%d" % (R, exp, b, k)
|
||||
if os.path.isfile(pa + "/engine.log") and os.path.isfile(pb + "/engine.log"):
|
||||
pairs.append((metrics(pa), metrics(pb)))
|
||||
print("%s: %s against %s, %d pairs" % (exp, b, a, len(pairs)))
|
||||
for key, label, rel in (("tps", "decode tok/s %", 1), ("msr", "ms/round %", 1), ("tpr", "tok/round %", 1),
|
||||
("v", "hit share points (token-w)", 0), ("vu", "hit share points (unweighted)", 0)):
|
||||
d = [(q[key] / p[key] - 1) * 100 if rel else q[key] - p[key] for p, q in pairs]
|
||||
m, sd = st.mean(d), (st.stdev(d) if len(d) > 1 else 0.0)
|
||||
ci = T95.get(len(d) - 1, 2.3) * sd / math.sqrt(len(d))
|
||||
print(" %-32s %+.2f (CI %+.2f..%+.2f)" % (label, m, m - ci, m + ci))
|
||||
|
||||
|
||||
def cmd_requests():
|
||||
pool = collections.defaultdict(list)
|
||||
for d, rows in replay_dirs():
|
||||
if re.search(r"/A(\.\d+)?$", d):
|
||||
for i, r in enumerate(rows[:30]):
|
||||
pool[i].append(r)
|
||||
vs = [van(R + "/main/" + n)[1:31] for n in ("VANL-noprof", "VANLP")]
|
||||
print("idx ptok(V) otok(V) otok(A) | hit V hit A (pooled, sd) | A-V | cpu V/A pcie V/A")
|
||||
out = []
|
||||
for i in range(30):
|
||||
a, v = pool[i], [x[i] for x in vs]
|
||||
out.append((st.mean(x["otok"] for x in v), st.mean(r["otok"] for r in a), st.mean(x["v"] for x in v),
|
||||
st.mean(r["v"] for r in a)))
|
||||
print("%2d %6d %6d %6.0f | %.1f %.1f (%.2f) | %+.1f | %.1f/%.1f %.1f/%.1f" % (
|
||||
i + 1, v[0]["ptok"], out[-1][0], out[-1][1], out[-1][2], out[-1][3], st.pstdev([r["v"] for r in a]),
|
||||
out[-1][3] - out[-1][2], st.mean(x["c"] for x in v), st.mean(r["c"] for r in a),
|
||||
st.mean(x["p"] for x in v), st.mean(r["p"] for r in a)))
|
||||
for name, lo, hi in (("< 600 tokens", 0, 600), ("600-2000", 600, 2000), (">= 2000", 2000, 10 ** 9)):
|
||||
sel = [o for o in out if lo <= o[0] < hi]
|
||||
print("%-14s n=%2d token-w V %.2f A %.2f | unweighted V %.2f A %.2f" % (
|
||||
name, len(sel), sum(o[0] * o[2] for o in sel) / sum(o[0] for o in sel),
|
||||
sum(o[1] * o[3] for o in sel) / sum(o[1] for o in sel), st.mean(o[2] for o in sel),
|
||||
st.mean(o[3] for o in sel)))
|
||||
|
||||
|
||||
def windows_of(path):
|
||||
"""Per request: the `DBG window` rows (rows, cpu entries, pcie experts) in file order, split at the request line."""
|
||||
reqs, cur = [], []
|
||||
for line in open(path, errors="replace"):
|
||||
if line.startswith("DBG window"):
|
||||
m = dict(re.findall(r"(\w+)=([\d.]+)", line))
|
||||
cur.append((int(m["rows"]), float(m["entries"]), float(m["pcie_experts"])))
|
||||
elif line.startswith("{") and '"ev":"request"' in line and '"comp":"engine"' in line:
|
||||
if "tier_vram_pct" in json.loads(line):
|
||||
reqs.append(cur)
|
||||
cur = []
|
||||
return reqs
|
||||
|
||||
|
||||
def cmd_windows():
|
||||
reqs = windows_of(R + "/prof-l5/Q.1/engine.log")
|
||||
edges = [0, 4, 8, 16, 32, 64, 128, 256, 512, 10 ** 6]
|
||||
acc = collections.defaultdict(lambda: [0, 0.0])
|
||||
for w in reqs[2:]:
|
||||
for i, (rows, cpu, pcie) in enumerate(w):
|
||||
b = max(k for k in range(len(edges) - 1) if edges[k] <= i)
|
||||
acc[b][0] += rows * 480
|
||||
acc[b][1] += cpu + pcie
|
||||
print("hit share by window index since the request start (requests 3..30 of Q.1, row-weighted)")
|
||||
for b in sorted(acc):
|
||||
print(" windows %4d-%-6d rows %6d hit %.2f%% misses %.1f%% of all" % (
|
||||
edges[b], edges[b + 1] - 1, acc[b][0] / 480, 100 * (1 - acc[b][1] / acc[b][0]),
|
||||
100 * acc[b][1] / sum(a[1] for a in acc.values())))
|
||||
by_t = collections.defaultdict(lambda: [0, 0.0])
|
||||
for w in reqs[2:]:
|
||||
for i, (rows, cpu, pcie) in enumerate(w):
|
||||
if i >= 64:
|
||||
by_t[rows][0] += rows * 480
|
||||
by_t[rows][1] += cpu + pcie
|
||||
print("hit share by window rows T (windows >= 64 of requests 3..30)")
|
||||
for t in sorted(by_t):
|
||||
print(" T=%d rows share %.1f%% hit %.2f%%" % (t, 100 * by_t[t][0] / sum(a[0] for a in by_t.values()),
|
||||
100 * (1 - by_t[t][1] / by_t[t][0])))
|
||||
|
||||
|
||||
def cmd_swaps():
|
||||
tiers = []
|
||||
for line in open(R + "/main/P/engine.log", errors="replace"):
|
||||
m = re.search(r"DBG tier request: .*adaptations (\d+) swaps (\d+)", line)
|
||||
if m:
|
||||
tiers.append((int(m[1]), int(m[2])))
|
||||
rounds = sum(r["rounds"] for r in lel(R + "/main/P")[:30])
|
||||
print("ours: %d swaps in %d rounds = %.2f per round, %.1f per adaptation (cap 96)" % (
|
||||
sum(t[1] for t in tiers[:30]), rounds, sum(t[1] for t in tiers[:30]) / rounds,
|
||||
sum(t[1] for t in tiers[:30]) / sum(t[0] for t in tiers[:30])))
|
||||
vt = []
|
||||
for line in open(R + "/main/VANLP/engine.log", errors="replace"):
|
||||
m = re.search(r"decode timing: (\d+) windows, avg T ([\d.]+).*?([\d.]+) swaps/window", line)
|
||||
if m:
|
||||
vt.append((int(m[1]), float(m[2]), float(m[3])))
|
||||
w = sum(x[0] for x in vt)
|
||||
print("vanilla: %.2f swaps per window, avg T %.2f" % (sum(x[0] * x[2] for x in vt) / w,
|
||||
sum(x[0] * x[1] for x in vt) / w))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
cmds = dict(arms=cmd_arms, pairs=cmd_pairs, requests=cmd_requests, windows=cmd_windows, swaps=cmd_swaps)
|
||||
cmds[sys.argv[1]](*sys.argv[2:])
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Miss-leg frequency per layer, ours against vanilla, against the layer's slot quota (vram-hit-share-gap.md, cause b).
|
||||
|
||||
Local, stdlib only, no GPU. Input: the per-layer records of CUPTI windows written by `ffn_phase_timeline.py extract`
|
||||
(reproduction in ffn-phase-loss-design.md section 6):
|
||||
python3 hit_share_layers.py PROFILE.bin VANL.json.gz LEL.json.gz...
|
||||
A layer-window is "with a miss leg" when its class is C (CPU rows late) or X (PCIe leg); F has neither.
|
||||
Vanilla fills 12,575 slots by the global rank of the profile; ours gives every layer 254 (12,192 / 48).
|
||||
"""
|
||||
import os
|
||||
import statistics as st
|
||||
import struct
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.dont_write_bytecode = True
|
||||
import ffn_phase_timeline as F # noqa: E402
|
||||
|
||||
LAYERS, OURS_QUOTA, VANILLA_SLOTS = 48, 254, 12575
|
||||
|
||||
|
||||
def global_quota(profile_path):
|
||||
raw = open(profile_path, "rb").read()
|
||||
pairs = [struct.unpack("<HH", raw[24 + 4 * i:28 + 4 * i]) for i in range(LAYERS * 512)]
|
||||
return [sum(1 for layer, _ in pairs[:VANILLA_SLOTS] if layer == li) for li in range(LAYERS)]
|
||||
|
||||
|
||||
def share(cells, li, classes):
|
||||
sel = [c for c in cells if c["li"] == li]
|
||||
return sum(1 for c in sel if c["cls"] in classes) / len(sel)
|
||||
|
||||
|
||||
def pearson(xs, ys):
|
||||
mx, my = st.mean(xs), st.mean(ys)
|
||||
cov = sum((a - mx) * (b - my) for a, b in zip(xs, ys))
|
||||
return cov / (sum((a - mx) ** 2 for a in xs) ** 0.5 * sum((b - my) ** 2 for b in ys) ** 0.5)
|
||||
|
||||
|
||||
def report(vanl, lels, quota, classes, rows_t):
|
||||
pick = (lambda cs: cs) if rows_t is None else (lambda cs: [c for c in cs if c["T"] in rows_t])
|
||||
ours = [st.mean(share(pick(c), li, classes) for c in lels) for li in range(LAYERS)]
|
||||
theirs = [share(pick(vanl), li, classes) for li in range(LAYERS)]
|
||||
diff = [a - b for a, b in zip(ours, theirs)]
|
||||
dq = [q - OURS_QUOTA for q in quota]
|
||||
slope = sum((a - st.mean(dq)) * (b - st.mean(diff)) for a, b in zip(dq, diff)) / sum(
|
||||
(a - st.mean(dq)) ** 2 for a in dq)
|
||||
print("classes %s, window rows %s: mean share ours %.3f vanilla %.3f, pearson(quota - 254, ours - vanilla) %.2f, "
|
||||
"slope %.4f per slot" % ("|".join(classes), rows_t or "all", st.mean(ours), st.mean(theirs),
|
||||
pearson(dq, diff), slope))
|
||||
for name, sel in (("receivers (+20 slots or more)", [i for i in range(LAYERS) if dq[i] > 20]),
|
||||
("neutral", [i for i in range(LAYERS) if abs(dq[i]) <= 20]),
|
||||
("donors (-20 slots or fewer)", [i for i in range(LAYERS) if dq[i] < -20])):
|
||||
print(" %-30s %2d layers, %+4.0f slots each, ours - vanilla %+.3f" % (
|
||||
name, len(sel), st.mean(dq[i] for i in sel), st.mean(diff[i] for i in sel)))
|
||||
|
||||
|
||||
def uniform_ranks(pairs, per_layer):
|
||||
taken, ranks = [0] * LAYERS, []
|
||||
for rank, (layer, _) in enumerate(pairs):
|
||||
if taken[layer] < per_layer:
|
||||
taken[layer] += 1
|
||||
ranks.append(rank)
|
||||
return ranks
|
||||
|
||||
|
||||
def model_gain(profile_path):
|
||||
"""Static coverage of a power-law routing model f(rank) ~ rank^-alpha over the profile's global ranks (E)."""
|
||||
raw = open(profile_path, "rb").read()
|
||||
pairs = [struct.unpack("<HH", raw[24 + 4 * i:28 + 4 * i]) for i in range(LAYERS * 512)]
|
||||
for alpha in (0.5, 0.7, 0.9):
|
||||
total = sum((r + 1) ** -alpha for r in range(len(pairs)))
|
||||
cover = lambda ranks: 100 * sum((r + 1) ** -alpha for r in ranks) / total # noqa: E731
|
||||
uni, glob12192, glob12575 = cover(uniform_ranks(pairs, OURS_QUOTA)), cover(range(12192)), cover(range(12575))
|
||||
print("model alpha %.1f: global fill at equal slots %+.2f points, +383 slots (12,575 global) %+.2f points" % (
|
||||
alpha, glob12192 - uni, glob12575 - glob12192))
|
||||
|
||||
|
||||
def main(profile, vanl_path, *lel_paths):
|
||||
vanl = F.load(vanl_path)["cells"]
|
||||
lels = [F.load(p)["cells"] for p in lel_paths]
|
||||
quota = global_quota(profile)
|
||||
print("global quota per layer (min %d, max %d, layers above 254: %d, slots moved: %d)" % (
|
||||
min(quota), max(quota), sum(q > OURS_QUOTA for q in quota), sum(max(0, q - OURS_QUOTA) for q in quota)))
|
||||
for classes in (("C", "X"), ("X",)):
|
||||
for rows_t in (None, (3, 4)):
|
||||
report(vanl, lels, quota, classes, rows_t)
|
||||
model_gain(profile)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(*sys.argv[1:])
|
||||
@@ -69,7 +69,7 @@ COMMON="--assets $AS --state-dir $ST --prefix $PFX --bin-src $BIN --cublas-dir $
|
||||
for v in $VARS; do
|
||||
D=$RUN/$v; mkdir -p "$D"; vb=${v%%.*}
|
||||
[ -f "$D/replay.jsonl" ] && { log "variant $v already done: skipped"; continue; }
|
||||
unset CUDA_INJECTION64_PATH LELEKA_CUPTI_TRIGGER LCT_MAX_SECONDS LELEKA_ADAPT_TIE_SPREAD LELEKA_ADAPT_DECAY LELEKA_ADAPT_MARGIN LELEKA_ORIGINAL_SERVE_ADAPT_SWAPS LELEKA_REFILL_DEFER LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB LELEKA_ORIGINAL_SERVE_VRAM_RESERVE_MIB LELEKA_BRINGUP_TRACE LELEKA_PREFILL_PROFILE_SYNC LELEKA_ORIGINAL_SERVE_ADAPT_EVERY LELEKA_SM120_ATTN_DAILY LELEKA_SM120_GU_SWIGLU LELEKA_SM120_SIDE_MIXER LELEKA_SM120_SIDE_QSA LELEKA_SM120_SIDE_SHARED LELEKA_DRAFT_FUSED_COMMIT LELEKA_SM120_FUSED_QSA_PRELUDE LELEKA_SM120_FUSED_GDN LELEKA_SM120_GDN_AB_UNROLL LELEKA_SM120_ACCEPT_ON_DEVICE LELEKA_SM120_COMBINE_VEC4 LELEKA_SM120_HEAD_MIX_MULTI LELEKA_SM120_GR_DOWN_FUSED LELEKA_SM120_DOWN_SUB16 LELEKA_SM120_HITS_IN_COMBINE LELEKA_SM120_WAIT_M_ROWS LELEKA_ORIGINAL_SERVE_PCIE_FRAC LELEKA_SERVE_PROFILE STRATA_VERIFY_PROFILE LELEKA_ROUTE_TAIL_SKIP LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED LELEKA_SPEC LELEKA_SPEC_ADAPTIVE LELEKA_SPEC_FLOOR_CEILING LELEKA_SPEC_STATS
|
||||
unset CUDA_INJECTION64_PATH LELEKA_CUPTI_TRIGGER LCT_MAX_SECONDS LELEKA_ADAPT_TIE_SPREAD LELEKA_ADAPT_DECAY LELEKA_ADAPT_MARGIN LELEKA_ORIGINAL_SERVE_ADAPT_SWAPS LELEKA_REFILL_DEFER LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB LELEKA_ORIGINAL_SERVE_VRAM_RESERVE_MIB LELEKA_BRINGUP_TRACE LELEKA_PREFILL_PROFILE_SYNC LELEKA_ORIGINAL_SERVE_ADAPT_EVERY LELEKA_SM120_ATTN_DAILY LELEKA_SM120_GU_SWIGLU LELEKA_SM120_SIDE_MIXER LELEKA_SM120_SIDE_QSA LELEKA_SM120_SIDE_SHARED LELEKA_DRAFT_FUSED_COMMIT LELEKA_SM120_FUSED_QSA_PRELUDE LELEKA_SM120_FUSED_GDN LELEKA_SM120_GDN_AB_UNROLL LELEKA_SM120_ACCEPT_ON_DEVICE LELEKA_SM120_COMBINE_VEC4 LELEKA_SM120_HEAD_MIX_MULTI LELEKA_SM120_GR_DOWN_FUSED LELEKA_SM120_DOWN_SUB16 LELEKA_SM120_HITS_IN_COMBINE LELEKA_SM120_WAIT_M_ROWS LELEKA_SM120_HEAD_CHAIN_BATCH LELEKA_PROMPT_EMBED_ALIAS LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER LELEKA_ORIGINAL_SERVE_PCIE_FRAC LELEKA_ORIGINAL_SERVE_PCIE_AUTO LELEKA_ORIGINAL_SERVE_PCIE_LINK_GBPS LELEKA_SERVE_PROFILE STRATA_VERIFY_PROFILE LELEKA_ROUTE_TAIL_SKIP LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED LELEKA_SPEC LELEKA_SPEC_ADAPTIVE LELEKA_SPEC_FLOOR_CEILING LELEKA_SPEC_STATS
|
||||
FLOOR=""; UPX=""
|
||||
case $vb in
|
||||
A) ;;
|
||||
@@ -100,7 +100,11 @@ for v in $VARS; do
|
||||
PB) export LELEKA_SM120_ATTN_DAILY=1 LELEKA_SM120_GU_SWIGLU=1 LELEKA_SM120_SIDE_MIXER=1 LELEKA_SM120_SIDE_QSA=1 LELEKA_SM120_SIDE_SHARED=1;; # the 5090 profile set before the prelude, exactly as the profiles carry it (no fused commit): base of the QSA prelude A/B
|
||||
ZQ) export LELEKA_SM120_ATTN_DAILY=1 LELEKA_SM120_GU_SWIGLU=1 LELEKA_SM120_SIDE_MIXER=1 LELEKA_SM120_SIDE_QSA=1 LELEKA_SM120_SIDE_SHARED=1 LELEKA_SM120_FUSED_QSA_PRELUDE=1;; # PB + the QSA prelude: the set the 5090 profiles now carry (group A/B PB against ZQ)
|
||||
PN) export LELEKA_SM120_ATTN_DAILY=1 LELEKA_SM120_GU_SWIGLU=1 LELEKA_SM120_SIDE_MIXER=1 LELEKA_SM120_SIDE_QSA=1 LELEKA_SM120_SIDE_SHARED=1 LELEKA_SM120_FUSED_QSA_PRELUDE=1 LELEKA_DRAFT_FUSED_COMMIT=1 LELEKA_SM120_COMBINE_VEC4=1;; # the 5090 profiles as of 2026-11-11 (prelude, fused commit, combine vec4 on top of PB): the new side of the stage group A/B against PB
|
||||
PF) export LELEKA_SM120_ATTN_DAILY=1 LELEKA_SM120_GU_SWIGLU=1 LELEKA_SM120_SIDE_MIXER=1 LELEKA_SM120_SIDE_QSA=1 LELEKA_SM120_SIDE_SHARED=1 LELEKA_SM120_FUSED_QSA_PRELUDE=1 LELEKA_DRAFT_FUSED_COMMIT=1 LELEKA_SM120_COMBINE_VEC4=1 LELEKA_SM120_DOWN_SUB16=1 LELEKA_SM120_HITS_IN_COMBINE=1 LELEKA_SM120_WAIT_M_ROWS=1;; # PN + the FFN-phase switches D1-D3
|
||||
PG) export LELEKA_SM120_ATTN_DAILY=1 LELEKA_SM120_GU_SWIGLU=1 LELEKA_SM120_SIDE_MIXER=1 LELEKA_SM120_SIDE_QSA=1 LELEKA_SM120_SIDE_SHARED=1 LELEKA_SM120_FUSED_QSA_PRELUDE=1 LELEKA_DRAFT_FUSED_COMMIT=1 LELEKA_SM120_COMBINE_VEC4=1 LELEKA_SM120_DOWN_SUB16=1 LELEKA_SM120_HITS_IN_COMBINE=1;; # PN + D1 and D2: the 5090 profiles as of 2026-11-11 (final set of the stage), against PB
|
||||
PA) export LELEKA_SM120_ATTN_DAILY=1 LELEKA_SM120_GU_SWIGLU=1 LELEKA_SM120_SIDE_MIXER=1 LELEKA_SM120_SIDE_QSA=1 LELEKA_SM120_SIDE_SHARED=1 LELEKA_SM120_FUSED_QSA_PRELUDE=1 LELEKA_DRAFT_FUSED_COMMIT=1 LELEKA_SM120_COMBINE_VEC4=1 LELEKA_SM120_DOWN_SUB16=1 LELEKA_SM120_HITS_IN_COMBINE=1 LELEKA_ORIGINAL_SERVE_PCIE_AUTO=on;; # PG + the VANL PcieAuto share controller (placement class; needs a binary with the switch)
|
||||
QP|QT) export LELEKA_SM120_ATTN_DAILY=1 LELEKA_SM120_GU_SWIGLU=1 LELEKA_SM120_SIDE_MIXER=1 LELEKA_SM120_SIDE_QSA=1 LELEKA_SM120_SIDE_SHARED=1 LELEKA_SM120_FUSED_QSA_PRELUDE=1 LELEKA_DRAFT_FUSED_COMMIT=1 LELEKA_SM120_COMBINE_VEC4=1 LELEKA_SM120_DOWN_SUB16=1 LELEKA_SM120_HITS_IN_COMBINE=1; [ "$vb" = QT ] && export LELEKA_SM120_HEAD_CHAIN_BATCH=1; export CUDA_INJECTION64_PATH=$DRT/tools/libleleka_cupti_trace.so LELEKA_CUPTI_TRIGGER=$D/cupti.trigger LCT_MAX_SECONDS=60 LD_LIBRARY_PATH=$DRT/cupti/lib:$LD_LIBRARY_PATH;; # CUPTI windows of the final profile set (QP, control) and + the batched head chain (QT, R8)
|
||||
PS) export LELEKA_SM120_ATTN_DAILY=1 LELEKA_SM120_GU_SWIGLU=1 LELEKA_SM120_SIDE_MIXER=1 LELEKA_SM120_SIDE_QSA=1 LELEKA_SM120_SIDE_SHARED=1 LELEKA_SM120_FUSED_QSA_PRELUDE=1 LELEKA_DRAFT_FUSED_COMMIT=1 LELEKA_SM120_COMBINE_VEC4=1 LELEKA_SM120_DOWN_SUB16=1 LELEKA_SM120_HITS_IN_COMBINE=1 LELEKA_PROMPT_EMBED_ALIAS=1 LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB=130;; # PG + the embedding alias and a decode reserve of 130 MiB: 12,384 expert slots instead of 12,192 (docs/experiments/vram-hit-share-gap.md, experiment 1; placement class)
|
||||
PW) export LELEKA_SM120_ATTN_DAILY=1 LELEKA_SM120_GU_SWIGLU=1 LELEKA_SM120_SIDE_MIXER=1 LELEKA_SM120_SIDE_QSA=1 LELEKA_SM120_SIDE_SHARED=1 LELEKA_SM120_FUSED_QSA_PRELUDE=1 LELEKA_DRAFT_FUSED_COMMIT=1 LELEKA_SM120_COMBINE_VEC4=1 LELEKA_SM120_DOWN_SUB16=1 LELEKA_SM120_HITS_IN_COMBINE=1 LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=2;; # PG + a tier swap round every 2 verify rounds (vram-hit-share-gap.md, experiment 2; placement class)
|
||||
R) export LELEKA_REFILL_DEFER=on;; # lever 5: the lent-slot refill queued inside the decode phase's assembly (same copies, other time)
|
||||
S) export LELEKA_ROUTE_TAIL_SKIP=7 LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED=100;;
|
||||
T*) export LELEKA_ROUTE_TAIL_SKIP=7 LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED=100; p=${vb#T}; p=${p%[a-z]}; [ "$p" != 45 ] && export LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.$p;;
|
||||
@@ -133,11 +137,11 @@ for v in $VARS; do
|
||||
done
|
||||
touch "$D/replay.jsonl"
|
||||
else
|
||||
case $vb in C|CL|CM|CN|CE|CT|CF|CU|CQ|CG|CV|CA|CY|CP|CS|CH|CD|CZ|WD|WH|WW|WZ) cupti_arm=1;; *) cupti_arm=0;; esac
|
||||
case $vb in C|CL|CM|CN|CE|CT|CF|CU|CQ|CG|CV|CA|CY|CP|CS|CH|CD|CZ|WD|WH|WW|WZ|QP|QT) cupti_arm=1;; *) cupti_arm=0;; esac
|
||||
if [ $cupti_arm = 1 ]; then spd_watch "$D/replay.jsonl" "$D/cupti.trigger" "$D" "$TRIG_AT" & WATCH_PID=$!; fi
|
||||
python3 -I "$SPD/tools/replay_hash.py" "${args[@]}" --url http://127.0.0.1:8081 --model qwen-iq3 --key-file "$ST/api-key" --out "$D/replay.jsonl" --max-requests "$MAXR" >"$D/replay.out" 2>&1
|
||||
log "replay rc=$? $(wc -l <"$D/replay.jsonl") requests"
|
||||
case $vb in C|CL|CM|CN|CE|CT|CF|CU|CQ|CG|CV|CA|CY|CP|CS|CH|CD|CZ|WD|WH|WW|WZ) cupti_arm=1;; *) cupti_arm=0;; esac
|
||||
case $vb in C|CL|CM|CN|CE|CT|CF|CU|CQ|CG|CV|CA|CY|CP|CS|CH|CD|CZ|WD|WH|WW|WZ|QP|QT) cupti_arm=1;; *) cupti_arm=0;; esac
|
||||
if [ $cupti_arm = 1 ]; then for _ in $(seq 1 60); do [ -e "$D/cupti.trigger.done" ] && break; sleep 1; done; kill "$WATCH_PID" 2>/dev/null; fi
|
||||
fi
|
||||
cp "$ST/logs/engine.log" "$D/engine.log" 2>/dev/null; cp "$ST/logs/requests.log" "$D/requests.log" 2>/dev/null
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env bash
|
||||
# Bitwise probe of LELEKA_SM120_HEAD_CHAIN_BATCH (ledger R8) at kernel level: sm120_head_chain.ptx entries against the sealed per-row chain, T 1..8, 3 seeds incl. special values, group offsets; every byte of R, xn, lo, gated, mixed. Expected: SUMMARY failures=0.
|
||||
# Small GPU job (minutes, no model), takes /data/leleka-e2e/gpu.lock; inputs frozen (MANIFEST.sha256), the job runs copies with the executable bit.
|
||||
set -uo pipefail
|
||||
D=/data/leleka-e2e/spd-gap/probes/verify-tail-head-chain-bitwise-probe
|
||||
LOCK=/data/leleka-e2e/gpu.lock
|
||||
NAME=verify-tail-head-chain-bitwise-probe
|
||||
OUT=$D/../$NAME.result.txt
|
||||
export LD_LIBRARY_PATH=$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-}
|
||||
cd "$D" || { echo "no $D"; exit 2; }
|
||||
sha256sum --quiet -c MANIFEST.sha256 || { echo "MANIFEST.sha256 does not match the files in $D"; exit 5; }
|
||||
RUN=$D/../$NAME.exec
|
||||
rm -rf "$RUN"; mkdir -p "$RUN" && cp -r headchain "$RUN"/ && chmod -R u+rwx "$RUN" || { echo "cannot stage $RUN"; exit 6; }
|
||||
got=0
|
||||
for _ in $(seq 1 360); do
|
||||
if mkdir "$LOCK" 2>/dev/null; then echo "$NAME $(date -u +%FT%TZ)" >"$LOCK/owner"; got=1; break; fi
|
||||
sleep 5
|
||||
done
|
||||
[ $got = 1 ] || { echo "GPU lock held by: $(cat "$LOCK/owner" 2>/dev/null)"; exit 3; }
|
||||
release() { if grep -q "$NAME" "$LOCK/owner" 2>/dev/null; then rm -f "$LOCK/owner"; rmdir "$LOCK"; fi; }
|
||||
trap release EXIT
|
||||
{
|
||||
date -u +%FT%TZ; nvidia-smi --query-gpu=name,driver_version --format=csv,noheader
|
||||
echo "== sm120_probe_head_chain (R8)"; timeout 900 "$RUN"/headchain/sm120_probe_head_chain "$RUN"/headchain/ptx; echo "exit $?"
|
||||
} 2>&1 | tee "$OUT"
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
# CUPTI windows (request 29, 15 s) of the final 5090 profile set (QP, control) and + LELEKA_SM120_HEAD_CHAIN_BATCH (QT, ledger R8: the 6T tail launches batched to 6). Binary bin-tail.
|
||||
# Look at: tail launch count 6T+4 -> 10, mtp_full_gr_norm / mmvf256 / mmvf160 / pre_final -> 0 in the tail, new leleka_verify_final_write_rows / head_norm_rows / head_pre_final_rows; time from the last add_hits end to head_quant start per T.
|
||||
unset SPD_VARIANTS SPD_CELLS SPD_OUT SPD_MAX SPD_TUNES SPD_BIN
|
||||
export SPD_BIN=/data/leleka-e2e/spd-gap/bin-tail SPD_VARIANTS="QP.1 QT.1" SPD_MAX=30 SPD_CELLS=/data/leleka-e2e/codex-compare/runs/main/VANL/nestng-crm-r2 SPD_OUT=/data/leleka-e2e/spd-gap/runs/verify-tail-head-chain-cupti-windows SPD_TRIG_AT=28 SPD_WIN_S=15
|
||||
exec bash /data/leleka-e2e/spd-gap/tools/spd_ab_job_x.sh
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
# identity gate (teacher forced, test binary rt-tail) of LELEKA_SM120_HEAD_CHAIN_BATCH (ledger R8); reference = idP1.full of verify-new-switches-identity, SKIP_P1=1
|
||||
# P2 HEAD_CHAIN_BATCH alone, P3 the final 5090 profile set (SIDE_*, prelude, fused commit, combine vec4, down sub16, hits in combine) + HEAD_CHAIN_BATCH; each process has the A/A pair I1/I2
|
||||
export D=/data/leleka-e2e/spd-gap/dt ID_BIN=rt-tail ID_OUT=/data/leleka-e2e/spd-gap/runs/verify-tail-head-chain-identity MAX_NEW=240 ADAPT=4 SKIP_P1=1
|
||||
mkdir -p "$ID_OUT"; [ -f "$ID_OUT/idP1.full" ] || cp -p /data/leleka-e2e/spd-gap/runs/verify-s11-s9-u5a-identity/idP1.full "$ID_OUT/idP1.full"
|
||||
B="LELEKA_SM120_ATTN_DAILY_MTP=1 LELEKA_SM120_ATTN_DAILY=1 LELEKA_SM120_GU_SWIGLU=1"
|
||||
export P1_ENV="$B"
|
||||
export P2_ENV="$B LELEKA_SM120_HEAD_CHAIN_BATCH=1"
|
||||
export P3_ENV="$B LELEKA_SM120_SIDE_MIXER=1 LELEKA_SM120_SIDE_QSA=1 LELEKA_SM120_SIDE_SHARED=1 LELEKA_SM120_FUSED_QSA_PRELUDE=1 LELEKA_DRAFT_FUSED_COMMIT=1 LELEKA_SM120_COMBINE_VEC4=1 LELEKA_SM120_DOWN_SUB16=1 LELEKA_SM120_HITS_IN_COMBINE=1 LELEKA_SM120_HEAD_CHAIN_BATCH=1"
|
||||
exec bash /data/leleka-e2e/spd-gap/tools/verify-switches-identity.sh
|
||||
@@ -0,0 +1,157 @@
|
||||
"""The tail of the verify graph and the idle gaps inside it (ledger rows R6, R7, R8; docs/experiments/verify-tail-and-gaps.md).
|
||||
|
||||
Offline analysis of CUPTI trace directories (tools/cupti-trace, `lct.py`); host-side Python, stdlib only, no GPU.
|
||||
|
||||
extract TRACE_DIR LABEL [--lct DIR] (python3 -B; reads the trace, writes JSON on stdout)
|
||||
per window row count T (the grid of the CPU-row copy kernel / 10) of every verify graph (>= 900 kernels per
|
||||
correlation id, first and last two dropped): graphs, union gaps and idle, first doorbell, and the tail after the
|
||||
last `add_hits` end split into the hyper-connection part (to the head quantize), the quantize, what sits between it and the
|
||||
language-model head matmul (the longest kernel of the tail), the matmul and what follows it (greedy pick, finite scan); the kernel sequence
|
||||
of the tail (p50 duration and gap before each launch); the non-verify graphs per round.
|
||||
compare LEL.json VANL.json (markdown on stdout)
|
||||
per T the differences of the tail sections, and the sum over LEL's own T mix (VANL's T without graphs, here T=5, is
|
||||
the mean of its neighbours).
|
||||
|
||||
A union gap is an interval inside a graph where no kernel of the graph runs (first start to last end). `--lct` defaults
|
||||
to /data/leleka-e2e/decode/tools (read only).
|
||||
"""
|
||||
import argparse
|
||||
import collections
|
||||
import json
|
||||
import sys
|
||||
|
||||
SECTIONS = ("total", "hc", "quant", "misc", "matmul", "post")
|
||||
|
||||
|
||||
def p50(values):
|
||||
v = sorted(values)
|
||||
return v[len(v) // 2] if v else float("nan")
|
||||
|
||||
|
||||
def union_gaps(ks):
|
||||
cur, gaps = ks[0].end, []
|
||||
for k in ks[1:]:
|
||||
if k.start > cur:
|
||||
gaps.append(k.start - cur)
|
||||
cur = max(cur, k.end)
|
||||
return gaps
|
||||
|
||||
|
||||
def window_rows(ks, name):
|
||||
rows = collections.Counter(k.gx // 10 for k in ks if "copy_rows" in name(k))
|
||||
return rows.most_common(1)[0][0] if rows else -1
|
||||
|
||||
|
||||
def tail_of(ks, name):
|
||||
"""(anchor end, kernels from the last add_hits end on); with HITS_IN_COMBINE the anchor is the last combine."""
|
||||
hits = [k for k in ks if "add_hi" in name(k)]
|
||||
if hits:
|
||||
a = max(hits, key=lambda k: k.end).end
|
||||
else:
|
||||
a = max((k for k in ks if "combine" in name(k)), key=lambda k: k.start).start - 1
|
||||
return a, [k for k in ks if k.start >= a]
|
||||
|
||||
|
||||
def sections(ks, name):
|
||||
a, tail = tail_of(ks, name)
|
||||
end = max(k.end for k in ks)
|
||||
mm = max(range(len(tail)), key=lambda i: tail[i].end - tail[i].start)
|
||||
q = next((i for i in range(mm - 1, max(mm - 4, -1), -1) if "quant" in name(tail[i])), mm - 1)
|
||||
dur = lambda k: (k.end - k.start) / 1e3 # noqa: E731
|
||||
return {"total": (end - a) / 1e3, "hc": (tail[q].start - a) / 1e3, "quant": dur(tail[q]),
|
||||
"misc": (tail[mm].start - tail[q].end) / 1e3, "matmul": dur(tail[mm]), "post": (end - tail[mm].end) / 1e3}
|
||||
|
||||
|
||||
def sequence(graphs, name):
|
||||
"""The p50 duration and gap before each launch of the most common tail length."""
|
||||
tails = [tail_of(ks, name) for ks in graphs]
|
||||
length = collections.Counter(len(t) for _, t in tails).most_common(1)[0][0]
|
||||
good = [(a, t) for a, t in tails if len(t) == length]
|
||||
out = []
|
||||
for i in range(length):
|
||||
d = [(t[i].end - t[i].start) / 1e3 for _, t in good]
|
||||
g = [(t[i].start - (t[i - 1].end if i else a)) / 1e3 for a, t in good]
|
||||
out.append({"name": name(good[0][1][i])[-60:], "dur": p50(d), "gap": p50(g), "grid": [good[0][1][i].gx, good[0][1][i].gy]})
|
||||
return out
|
||||
|
||||
|
||||
def per_t(graphs, name):
|
||||
d = {"n": len(graphs), "kernels": p50([len(ks) for ks in graphs]), "streams": p50([len({k.stream for k in ks}) for ks in graphs])}
|
||||
gaps = [union_gaps(ks) for ks in graphs]
|
||||
d["union_gaps"] = p50([len(g) for g in gaps])
|
||||
d["idle_us"] = p50([sum(g) / 1e3 for g in gaps])
|
||||
doors = [(db[0].start - ks[0].start) / 1e3 for ks in graphs for db in [[k for k in ks if "doorbell" in name(k)]] if db]
|
||||
d["first_doorbell_us"] = p50(doors)
|
||||
secs = [sections(ks, name) for ks in graphs]
|
||||
d.update({s: round(p50([x[s] for x in secs]), 2) for s in SECTIONS})
|
||||
d["tail_launches"] = collections.Counter(len(tail_of(ks, name)[1]) for ks in graphs).most_common(1)[0][0]
|
||||
d["sequence"] = sequence(graphs, name)
|
||||
return d
|
||||
|
||||
|
||||
def extract(path, label, lct_dir):
|
||||
sys.path.insert(0, lct_dir)
|
||||
sys.dont_write_bytecode = True
|
||||
import lct
|
||||
t = lct.Trace(path)
|
||||
name = lambda k: t.names.get(k.name, "?") # noqa: E731
|
||||
by = collections.defaultdict(list)
|
||||
for k in t.kernels:
|
||||
by[k.corr].append(k)
|
||||
big = sorted((c for c, v in by.items() if len(v) >= 900), key=lambda c: min(k.start for k in by[c]))
|
||||
kept = [sorted(by[c], key=lambda k: k.start) for c in big[2:-2]]
|
||||
groups = collections.defaultdict(list)
|
||||
for ks in kept:
|
||||
groups[window_rows(ks, name)].append(ks)
|
||||
rest = [union_gaps(sorted(v, key=lambda k: k.start)) for c, v in by.items() if 2 <= len(v) < 900]
|
||||
return {"label": label, "graphs": len(kept), "T": {str(T): per_t(g, name) for T, g in sorted(groups.items())},
|
||||
"non_verify_per_round": {"graphs": len(rest) / len(kept), "union_gaps": sum(map(len, rest)) / len(kept),
|
||||
"idle_us": sum(sum(g) for g in rest) / 1e3 / len(kept)}}
|
||||
|
||||
|
||||
def filled(vanl):
|
||||
"""VANL per T with the missing Ts filled by the mean of the neighbours that exist."""
|
||||
have = sorted(int(t) for t in vanl["T"])
|
||||
out = {}
|
||||
for T in range(1, 9):
|
||||
if str(T) in vanl["T"]:
|
||||
out[T] = vanl["T"][str(T)]
|
||||
elif have[0] < T < have[-1]:
|
||||
lo, hi = max(t for t in have if t < T), min(t for t in have if t > T)
|
||||
a, b = vanl["T"][str(lo)], vanl["T"][str(hi)]
|
||||
out[T] = {s: (a[s] + b[s]) / 2 for s in SECTIONS + ("idle_us", "union_gaps")}
|
||||
return out
|
||||
|
||||
|
||||
def compare(lel, vanl):
|
||||
v = filled(vanl)
|
||||
mix = {int(T): d["n"] for T, d in lel["T"].items() if int(T) in v}
|
||||
total = sum(mix.values())
|
||||
print("| section (LEL - VANL, us) | " + " | ".join("T%d" % T for T in mix) + " | weighted at LEL's T mix |")
|
||||
print("| --- |" + " ---: |" * (len(mix) + 1))
|
||||
for s in SECTIONS + ("idle_us", "union_gaps"):
|
||||
diffs = {T: lel["T"][str(T)][s] - v[T][s] for T in mix}
|
||||
w = sum(mix[T] * diffs[T] for T in mix) / total
|
||||
print("| %s | %s | %.1f |" % (s, " | ".join("%+.1f" % diffs[T] for T in mix), w))
|
||||
print("graphs per T (LEL): %s" % mix)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
e = sub.add_parser("extract")
|
||||
e.add_argument("trace")
|
||||
e.add_argument("label")
|
||||
e.add_argument("--lct", default="/data/leleka-e2e/decode/tools")
|
||||
c = sub.add_parser("compare")
|
||||
c.add_argument("lel")
|
||||
c.add_argument("vanl")
|
||||
a = ap.parse_args()
|
||||
if a.cmd == "extract":
|
||||
json.dump(extract(a.trace, a.label, a.lct), sys.stdout, indent=1)
|
||||
else:
|
||||
compare(json.load(open(a.lel)), json.load(open(a.vanl)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1183,6 +1183,32 @@
|
||||
},
|
||||
"group": "sm120-decode",
|
||||
"optional": false
|
||||
},
|
||||
{
|
||||
"cu": "crates/cuda-driver/src/sm120_head_chain.cu",
|
||||
"ptx": "crates/cuda-driver/src/sm120_head_chain.ptx",
|
||||
"flags": [
|
||||
"--ptx",
|
||||
"-O3",
|
||||
"-arch=sm_120",
|
||||
"-std=c++17",
|
||||
"--fmad=true",
|
||||
"--use_fast_math"
|
||||
],
|
||||
"policy": "fast-math (--fmad=true --use_fast_math: the flags mtp_original_full_gr_norm.cu and mtp_original_full_gr_post.cu were resealed with, extra-seal-plan group reseal-fastmath, because the batched kernels are their bodies and expf, rsqrtf and the divisions must lower to the same approximate PTX; claude/tail-fusion: LELEKA_SM120_HEAD_CHAIN_BATCH, the residual write, the head norm and the pre-final mix of all window rows as grid.y = row). Self-contained: cuda_runtime.h only, so it takes no include profile",
|
||||
"entries": [
|
||||
"leleka_verify_final_write_rows",
|
||||
"leleka_verify_head_norm_rows",
|
||||
"leleka_verify_head_pre_final_rows"
|
||||
],
|
||||
"encoding": "concat_include_str",
|
||||
"rust_fields_to_fill": {
|
||||
"crates/cuda-driver/src/original_verify_window_gr/head_chain.rs": [
|
||||
"HEAD_CHAIN.sha"
|
||||
]
|
||||
},
|
||||
"group": "sm120-decode",
|
||||
"optional": false
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build the HEAD_CHAIN_BATCH probe in WSL (never on the server) and collect the PTX it compares.
|
||||
# tools/decode-sm120/build_head_chain.sh [OUTDIR] default OUTDIR=$HOME/sm120-head-chain-bin ; then: OUTDIR/sm120_probe_head_chain OUTDIR/ptx
|
||||
set -euo pipefail
|
||||
here="$(cd "$(dirname "$0")" && pwd)"
|
||||
root="$(cd "$here/../.." && pwd)"
|
||||
out="${1:-$HOME/sm120-head-chain-bin}"
|
||||
nvcc="${NVCC:-$HOME/cuda-toolkits/13.2.2/bin/nvcc}"
|
||||
mkdir -p "$out/ptx"
|
||||
"$nvcc" -O2 -std=c++17 "$here/sm120_probe_head_chain.cpp" -lcuda -o "$out/sm120_probe_head_chain"
|
||||
for f in mtp_original_full_gr_post mtp_original_full_gr_norm mtp_original_full_bf16 sm120_head_chain; do
|
||||
cp "$root/crates/cuda-driver/src/$f.ptx" "$out/ptx/$f.ptx"
|
||||
done
|
||||
sha256sum "$out"/sm120_probe_head_chain "$out"/ptx/* > "$out/SHA256SUMS"
|
||||
ls -la "$out" "$out/ptx"
|
||||
@@ -0,0 +1,198 @@
|
||||
// claude/tail-fusion: model-free probe of LELEKA_SM120_HEAD_CHAIN_BATCH (docs/experiments/verify-tail-and-gaps.md).
|
||||
// The literal tail of the verify graph, per window row t,
|
||||
// mtp_full_native_write R_t = bo_t * (2 sigmoid(inject)) + R_t (mtp_original_full_gr_post.ptx)
|
||||
// mtp_full_gr_norm xn_t = norm(R_t) * gamma (mtp_original_full_gr_norm.ptx)
|
||||
// mtp_full_mmvf256 lo_t = down . xn_t (mtp_original_full_bf16.ptx)
|
||||
// mtp_full_down_silu lo_t = silu(lo_t / 4) (mtp_original_full_gr_post.ptx)
|
||||
// mtp_full_mmvf160 gated_t = up . lo_t (mtp_original_full_bf16.ptx)
|
||||
// mtp_full_pre_final gated_t = xn_t * sigmoid(gated_t); mixed_t = sum / 4
|
||||
// is run against the batched launches of the switch (sm120_head_chain.ptx: leleka_verify_final_write_rows,
|
||||
// leleka_verify_head_norm_rows, leleka_verify_head_pre_final_rows; the sealed bf16_f32_mmvf_multi_kernel<256|160, 4|8>;
|
||||
// mtp_full_down_silu over the T * 320 contiguous floats) on real-size random inputs, for T = 1..8 rows, three seeds
|
||||
// (small, large and special values: -0.0, denormals, inf, nan in the residual, block output and weights), the write also
|
||||
// for a group that starts at row 1..7 of the arena. EVERY byte of R, xn, lo, gated (the parts slots) and mixed is
|
||||
// compared, so a stray write outside the rows shows too (buffers start as 0xCD). Prints "RESULT name key=value" lines;
|
||||
// exits 1 if any comparison differs. Never touches the model. Written without a GPU: compiled
|
||||
// (tools/decode-sm120/build_head_chain.sh), not run.
|
||||
// sm120_probe_head_chain PTXDIR PTXDIR holds mtp_original_full_gr_post.ptx, mtp_original_full_gr_norm.ptx,
|
||||
// mtp_original_full_bf16.ptx and sm120_head_chain.ptx (build_head_chain.sh [OUTDIR] collects them).
|
||||
#include <cuda.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#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 const int N = 2560, HC = 4, LR = 320, D = N * HC, K = 10, MAXT = 8;
|
||||
static const float QUARTER = 0.25f, EPS = 1e-6f;
|
||||
static const char* MULTI_FMT = "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi%dELi%dEEEvPKflPKtPflii";
|
||||
|
||||
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)); CU(cuMemsetD8(p, 0xCD, bytes)); }
|
||||
void put(const void* h, size_t bytes) { CU(cuMemcpyHtoD(p, h, bytes)); }
|
||||
std::vector<uint8_t> get() const { std::vector<uint8_t> v(n); CU(cuCtxSynchronize()); 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) {
|
||||
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 void launch(CUfunction f, unsigned gx, unsigned gy, unsigned bx, void** args) {
|
||||
CU(cuLaunchKernel(f, gx, gy, 1, bx, 1, 1, 0, nullptr, args, nullptr));
|
||||
}
|
||||
static float special(uint32_t pick) {
|
||||
switch (pick % 6) { case 0: return -0.0f; case 1: return 0.0f; case 2: return 1e-40f; case 3: return -1e-40f; case 4: return INFINITY; default: return NAN; }
|
||||
}
|
||||
|
||||
struct Fns {
|
||||
CUfunction write, norm, mmvf256, mmvf160, silu, pre_final; // the literal kernels
|
||||
CUfunction write_rows, norm_rows, pre_final_rows, multi256[2], multi160[2]; // the batched ones (multi: NT 4, 8)
|
||||
};
|
||||
|
||||
// One case: T rows, the write for rows [first, first + T) of an 8-row arena, the head chain for rows [0, T).
|
||||
static void run_case(const Fns& f, int seed, int tokens, int first) {
|
||||
const float mag = seed == 1 ? 1e3f : 1.0f;
|
||||
const bool specials = seed == 2;
|
||||
std::vector<float> r((size_t)MAXT * D), bo((size_t)MAXT * N), inj((size_t)MAXT * HC), gamma(D);
|
||||
std::vector<uint16_t> down((size_t)LR * D), up((size_t)D * LR);
|
||||
for (auto& v : r) v = rndf() * mag;
|
||||
for (auto& v : bo) v = rndf() * mag;
|
||||
for (auto& v : inj) v = rndf() * 4.0f;
|
||||
for (auto& v : gamma) v = rndf() * 2.0f;
|
||||
for (auto& v : down) v = (uint16_t)(((rnd() & 0x7f00) | (rnd() & 0xff)) | ((rnd() & 1) << 15)); // bf16, small exponents
|
||||
for (auto& v : up) v = (uint16_t)(((rnd() & 0x3f00) | (rnd() & 0xff)) | ((rnd() & 1) << 15));
|
||||
if (specials) {
|
||||
for (size_t i = 0; i < r.size(); i += 997) r[i] = special(rnd());
|
||||
for (size_t i = 0; i < bo.size(); i += 389) bo[i] = special(rnd());
|
||||
for (size_t i = 0; i < gamma.size(); i += 211) gamma[i] = special(rnd());
|
||||
for (size_t i = 0; i < inj.size(); i += 5) inj[i] = special(rnd()) * 3.0f;
|
||||
}
|
||||
Dev dr[2], dbo, dinj, dgamma, ddown, dup, dxn[2], dlo[2], dgate[2], dmix[2];
|
||||
for (int a = 0; a < 2; ++a) {
|
||||
dr[a].alloc(r.size() * 4); dxn[a].alloc((size_t)MAXT * D * 4); dlo[a].alloc((size_t)MAXT * LR * 4);
|
||||
dgate[a].alloc((size_t)MAXT * K * N * 4); dmix[a].alloc((size_t)MAXT * N * 4);
|
||||
dr[a].put(r.data(), r.size() * 4);
|
||||
}
|
||||
dbo.alloc(bo.size() * 4); dbo.put(bo.data(), bo.size() * 4);
|
||||
dinj.alloc(inj.size() * 4); dinj.put(inj.data(), inj.size() * 4);
|
||||
dgamma.alloc(gamma.size() * 4); dgamma.put(gamma.data(), gamma.size() * 4);
|
||||
ddown.alloc(down.size() * 2); ddown.put(down.data(), down.size() * 2);
|
||||
dup.alloc(up.size() * 2); dup.put(up.data(), up.size() * 2);
|
||||
int n = N, hc = HC, lr = LR, d = D, count = tokens * LR;
|
||||
float quarter = QUARTER, eps = EPS;
|
||||
|
||||
// literal arm: the write of the group's rows, then the five kernels per row from row 0
|
||||
for (int t = first; t < first + tokens; ++t) {
|
||||
CUdeviceptr R = dr[0].p + (size_t)t * D * 4, B = dbo.p + (size_t)t * N * 4, I = dinj.p + (size_t)t * HC * 4;
|
||||
void* a[] = {&R, &B, &I, &R, &n, &hc, &quarter};
|
||||
launch(f.write, (D + 255) / 256, 1, 256, a);
|
||||
}
|
||||
for (int t = 0; t < tokens; ++t) {
|
||||
CUdeviceptr R = dr[0].p + (size_t)t * D * 4, XN = dxn[0].p + (size_t)t * D * 4, LO = dlo[0].p + (size_t)t * LR * 4;
|
||||
CUdeviceptr G = dgate[0].p + (size_t)t * K * N * 4, M = dmix[0].p + (size_t)t * N * 4;
|
||||
void* a_norm[] = {&R, &dgamma.p, &XN, &n, &eps};
|
||||
launch(f.norm, HC, 1, 1024, a_norm);
|
||||
void* a_down[] = {&XN, &ddown.p, &LO, &d};
|
||||
launch(f.mmvf256, LR, 1, 256, a_down);
|
||||
void* a_silu[] = {&LO, &lr, &quarter};
|
||||
launch(f.silu, (LR + 255) / 256, 1, 256, a_silu);
|
||||
void* a_up[] = {&LO, &dup.p, &G, &lr};
|
||||
launch(f.mmvf160, D, 1, 160, a_up);
|
||||
void* a_pre[] = {&XN, &G, &M, &n, &hc, &quarter};
|
||||
launch(f.pre_final, (N + 255) / 256, 1, 256, a_pre);
|
||||
}
|
||||
|
||||
// batched arm
|
||||
{
|
||||
CUdeviceptr R = dr[1].p + (size_t)first * D * 4, B = dbo.p + (size_t)first * N * 4, I = dinj.p + (size_t)first * HC * 4;
|
||||
int64_t rs = D, bs = N, is = HC;
|
||||
void* a[] = {&R, &B, &I, &n, &hc, &quarter, &rs, &bs, &is};
|
||||
launch(f.write_rows, (D + 255) / 256, (unsigned)tokens, 256, a);
|
||||
}
|
||||
{
|
||||
CUdeviceptr R = dr[1].p, XN = dxn[1].p, LO = dlo[1].p, G = dgate[1].p, M = dmix[1].p;
|
||||
int64_t ds = D, ls = LR, gs = (int64_t)K * N, ms = N;
|
||||
int nt = tokens;
|
||||
const int slot = tokens <= 4 ? 0 : 1;
|
||||
void* a_norm[] = {&R, &dgamma.p, &XN, &n, &eps, &ds, &ds};
|
||||
launch(f.norm_rows, HC, (unsigned)tokens, 1024, a_norm);
|
||||
void* a_down[] = {&XN, &ds, &ddown.p, &LO, &ls, &d, &nt};
|
||||
launch(f.multi256[slot], LR, 1, 256, a_down);
|
||||
void* a_silu[] = {&LO, &count, &quarter};
|
||||
launch(f.silu, (unsigned)((count + 255) / 256), 1, 256, a_silu);
|
||||
void* a_up[] = {&LO, &ls, &dup.p, &G, &gs, &lr, &nt};
|
||||
launch(f.multi160[slot], D, 1, 160, a_up);
|
||||
void* a_pre[] = {&XN, &G, &M, &n, &hc, &quarter, &ds, &gs, &ms};
|
||||
launch(f.pre_final_rows, (N + 255) / 256, (unsigned)tokens, 256, a_pre);
|
||||
}
|
||||
const bool ok_r = same("R (residual write)", dr[0].get(), dr[1].get());
|
||||
const bool ok_xn = same("xn (head norm)", dxn[0].get(), dxn[1].get());
|
||||
const bool ok_lo = same("lo (down gemv + silu)", dlo[0].get(), dlo[1].get());
|
||||
const bool ok_g = same("gated (up gemv + pre-final gate)", dgate[0].get(), dgate[1].get());
|
||||
const bool ok_m = same("mixed", dmix[0].get(), dmix[1].get());
|
||||
printf("RESULT head_chain seed=%d T=%d first=%d identical_R=%d identical_xn=%d identical_lo=%d identical_gated=%d identical_mixed=%d\n", seed, tokens, first,
|
||||
ok_r, ok_xn, ok_lo, ok_g, ok_m);
|
||||
for (int a = 0; a < 2; ++a) for (Dev* x : {&dr[a], &dxn[a], &dlo[a], &dgate[a], &dmix[a]}) CU(cuMemFree(x->p));
|
||||
for (Dev* x : {&dbo, &dinj, &dgamma, &ddown, &dup}) CU(cuMemFree(x->p));
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc < 2) { fprintf(stderr, "usage: %s PTXDIR\n", argv[0]); return 2; }
|
||||
const std::string dir = argv[1];
|
||||
CU(cuInit(0)); CUdevice dev; CU(cuDeviceGet(&dev, 0)); CUcontext ctx; CU(cuDevicePrimaryCtxRetain(&ctx, dev)); CU(cuCtxSetCurrent(ctx));
|
||||
CUmodule post = load_module(dir + "/mtp_original_full_gr_post.ptx"), norm = load_module(dir + "/mtp_original_full_gr_norm.ptx");
|
||||
CUmodule bf16 = load_module(dir + "/mtp_original_full_bf16.ptx"), chain = load_module(dir + "/sm120_head_chain.ptx");
|
||||
Fns f;
|
||||
f.write = get_fn(post, "mtp_full_native_write"); f.silu = get_fn(post, "mtp_full_down_silu"); f.pre_final = get_fn(post, "mtp_full_pre_final");
|
||||
f.norm = get_fn(norm, "mtp_full_gr_norm");
|
||||
f.mmvf256 = get_fn(bf16, "mtp_full_mmvf256"); f.mmvf160 = get_fn(bf16, "mtp_full_mmvf160");
|
||||
f.write_rows = get_fn(chain, "leleka_verify_final_write_rows"); f.norm_rows = get_fn(chain, "leleka_verify_head_norm_rows");
|
||||
f.pre_final_rows = get_fn(chain, "leleka_verify_head_pre_final_rows");
|
||||
for (int s = 0; s < 2; ++s) {
|
||||
char name[256];
|
||||
snprintf(name, sizeof name, MULTI_FMT, 256, s ? 8 : 4); f.multi256[s] = get_fn(bf16, name);
|
||||
snprintf(name, sizeof name, MULTI_FMT, 160, s ? 8 : 4); f.multi160[s] = get_fn(bf16, name);
|
||||
}
|
||||
for (int seed = 0; seed < 3; ++seed)
|
||||
for (int tokens = 1; tokens <= MAXT; ++tokens) {
|
||||
run_case(f, seed, tokens, 0);
|
||||
if (tokens < MAXT) run_case(f, seed, tokens, MAXT - tokens);
|
||||
}
|
||||
printf("SUMMARY failures=%d\n", g_fail);
|
||||
return g_fail ? 1 : 0;
|
||||
}
|
||||
Reference in New Issue
Block a user