feat(kv): per-owner resident KV window for the streamed QSA layers (kv_stream n_slots)

The resolver PTX baked 8192 resident pages (--kv-resident 32768). Port the
Original's KvStreamMap::n_slots: leleka_qsa_resolve and leleka_qsa_stream_reset
take n_slots (resealed with nvcc 13.2.86, sm_120, precise flags; digests in the
window asset, the window seal plan and the ptx_abi test). Every streamed owner
sizes its resident runs and resolver state from the process-wide window
(configure_kv_resident, default 32768 cells = the previous behaviour) and
launches with its own slot count; the verify window carries it in its KV
binding. leleka-context: resident_pages_for (layer.cpp kv_plan rule),
resident_runs, stream_map_bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-16 10:34:33 +02:00
co-authored by Claude Opus 5.5
parent 64f117f84b
commit 0103ee90aa
15 changed files with 795 additions and 607 deletions
+94 -2
View File
@@ -30,6 +30,9 @@ pub const MAPPED_ALIGNMENT_BYTES: usize = 1024;
pub enum GeometryError {
/// `cells` must be a positive multiple of [`PAGE_CELLS`] no larger than [`MAX_CELLS`].
Cells(usize),
/// A `--kv-resident` cell count that gives fewer resident pages than the resolve block
/// ([`RESOLVE_BLOCK`]) or more cells than [`MAX_CELLS`].
Resident(usize),
Overflow,
}
@@ -40,6 +43,10 @@ impl fmt::Display for GeometryError {
f,
"context of {n} cells must be a positive multiple of {PAGE_CELLS} and at most {MAX_CELLS}"
),
Self::Resident(n) => write!(
f,
"a resident KV window of {n} cells is not servable: it must give at least {RESOLVE_BLOCK} pages and at most {MAX_CELLS} cells (0 keeps the whole context resident)"
),
Self::Overflow => f.write_str("geometry arithmetic overflowed"),
}
}
@@ -135,6 +142,34 @@ impl QsaGeometry {
map_bytes,
)
}
/// Resident pages (VRAM slots) of one streamed QSA layer for `--kv-resident resident_cells`
/// (`layer.cpp::kv_plan`, `mode == 1`): `ceil(max(resident_cells, 20480) / 4)`. `0` keeps every page of
/// the context resident (the Original's `mode == 0`; here the streaming machinery stays on and simply
/// never evicts). Unlike the Original a window at least as large as the context is not clamped to it:
/// the slots past the context stay unused (the default 32768 cells at a small context).
pub fn resident_pages_for(self, resident_cells: usize) -> R<usize> {
if resident_cells > MAX_CELLS {
return Err(GeometryError::Resident(resident_cells));
}
let pages = if resident_cells == 0 {
self.pages()
} else {
resident_cells.max(KV_RESIDENT_MIN_CELLS).div_ceil(PAGE_CELLS)
};
if pages < RESOLVE_BLOCK {
return Err(GeometryError::Resident(resident_cells));
}
Ok(pages)
}
/// Device bytes of one layer's resident pool with `slots` resident pages: the four resident runs, the
/// context page table and `map_bytes` of resolver state.
pub fn resident_bytes_with(self, slots: usize, map_bytes: usize) -> R<usize> {
let runs = resident_runs(slots)?;
add(
add(add(add(runs[0], runs[1])?, add(runs[2], runs[3])?)?, self.page_table_bytes())?,
map_bytes,
)
}
/// Canonical host metadata bound of one layer (`NativeQsaResources::CANONICAL_METADATA`).
pub fn canonical_metadata_bytes(self) -> R<usize> {
add(mul(self.pages(), 160)?, 4096)
@@ -153,9 +188,30 @@ impl QsaGeometry {
}
}
/// The resident device runs hold `RESIDENT_PAGES` pages regardless of the context (the "actual 32K resident
/// pool"): `[16777216, 16777216, 524288, 524288]` bytes.
/// The default resident device runs hold `RESIDENT_PAGES` pages regardless of the context (the "actual 32K
/// resident pool", `--kv-resident 32768`): `[16777216, 16777216, 524288, 524288]` bytes.
pub const RESIDENT_PAGES: usize = 8192;
/// `qsa_kv_resident_min()`: the smallest resident window the Original streams with (one verify window's
/// selections must fit at once).
pub const KV_RESIDENT_MIN_CELLS: usize = 20_480;
/// The resident window of the default configuration (and of the production profile `--kv-resident 32768`).
pub const KV_RESIDENT_DEFAULT_CELLS: usize = RESIDENT_PAGES * PAGE_CELLS;
/// Threads of `kv_stream.cu`'s resolve block: with fewer slots one clock-sweep step could take a slot twice.
pub const RESOLVE_BLOCK: usize = 1024;
/// `kKvCtlInts` of `kv_stream.hpp`.
pub const KV_CTL_INTS: usize = 16;
/// The four resident runs (K codes, V codes, K scales, V scales) of `slots` resident pages.
pub fn resident_runs(slots: usize) -> R<[usize; 4]> {
let page = |run: usize| mul(slots, mul(RUN_CELL_BYTES[run], PAGE_CELLS)?);
Ok([page(0)?, page(1)?, page(2)?, page(3)?])
}
/// `kv_stream_map_bytes(n_slots)`: five per-slot `i32` arrays (slot block, stamp, reference bit, miss block,
/// miss slot) and the control block (`163_904` at 8192 slots).
pub fn stream_map_bytes(slots: usize) -> R<usize> {
add(mul(mul(slots, 4)?, 5)?, KV_CTL_INTS * 4)
}
pub const RESIDENT_RUNS: [usize; 4] = [16_777_216, 16_777_216, 524_288, 524_288];
pub const RESIDENT_RUNS_BYTES: usize = 34_603_008;
@@ -191,6 +247,42 @@ mod tests {
assert_eq!(g.rope_table_bytes(64), Ok(67_108_864));
}
#[test]
fn resident_window_follows_kv_plan_and_reproduces_the_frozen_pool_at_the_default() {
let g = QsaGeometry::TRAINED;
assert_eq!(g.resident_pages_for(KV_RESIDENT_DEFAULT_CELLS), Ok(RESIDENT_PAGES));
assert_eq!(resident_runs(RESIDENT_PAGES), Ok(RESIDENT_RUNS));
assert_eq!(stream_map_bytes(RESIDENT_PAGES), Ok(163_904));
assert_eq!(
g.resident_bytes_with(RESIDENT_PAGES, 163_904),
g.resident_bytes(163_904)
);
// max(resident, qsa_kv_resident_min()) rounded up to whole pages
assert_eq!(g.resident_pages_for(1), Ok(5120));
assert_eq!(g.resident_pages_for(20_480), Ok(5120));
assert_eq!(g.resident_pages_for(20_481), Ok(5121));
// 0: the whole context resident
assert_eq!(g.resident_pages_for(0), Ok(65_536));
assert_eq!(
QsaGeometry::new(MAX_CELLS).unwrap().resident_pages_for(0),
Ok(131_072)
);
// a tiny context cannot be fully resident with fewer slots than the resolve block
assert_eq!(
QsaGeometry::new(1024).unwrap().resident_pages_for(0),
Err(GeometryError::Resident(0))
);
assert_eq!(
g.resident_pages_for(MAX_CELLS + 4),
Err(GeometryError::Resident(MAX_CELLS + 4))
);
// production profile: 12 layers x (32768 cells x 1056 B) of VRAM KV
assert_eq!(
resident_runs(RESIDENT_PAGES).unwrap().iter().sum::<usize>(),
32_768 * KV_CELL_BYTES
);
}
#[test]
fn run_cell_bytes_are_the_original_kv_cell() {
assert_eq!(RUN_CELL_BYTES.iter().sum::<usize>(), KV_CELL_BYTES);
+3 -1
View File
@@ -105,7 +105,9 @@ mod tests {
("qsa_prompt_indexer.ptx", "qsa_decode_append", 11, 5),
("qsa_prompt_postops.ptx", "qsa_rope_rows", 6, 5),
("qsa_decode_postops.ptx", "qsa_decode_rope", 6, 5),
("qsa_prompt_resolver.ptx", "leleka_qsa_stream_reset", 7, 1),
// `n_blocks` (context pages) and `n_slots` (the `--kv-resident` page count)
("qsa_prompt_resolver.ptx", "leleka_qsa_stream_reset", 7, 2),
("qsa_prompt_resolver.ptx", "leleka_qsa_resolve", 10, 1),
] {
let text = committed(file);
let state = abi_state(&text, entry, frozen, extra);
+2 -1
View File
@@ -117,7 +117,8 @@ pub use qwen_dispatch::gr_batch_read::{GrMicroValues, GrMicrobatchRead};
mod qsa_selected_kv;
mod serving_context;
pub use serving_context::{
MAX_CONTEXT_CELLS, ServingContext, TRAINED_CONTEXT_CELLS, configure_serving_context,
KV_RESIDENT_DEFAULT_CELLS, KV_RESIDENT_MIN_CELLS, MAX_CONTEXT_CELLS, ServingContext, TRAINED_CONTEXT_CELLS,
configure_kv_resident, configure_serving_context, kv_resident_cells,
serving_context,
};
pub use mtp_dense_kv::MtpDenseKvRing;
@@ -224,6 +224,7 @@ mod tests {
table: b + 0x1300_0000,
host: [b + 0x2000_0000, b + 0x2100_0000, b + 0x2200_0000, b + 0x2210_0000],
resolver: [b + 0x1300_0000, b + 0x1310_0000, b + 0x1320_0000, b + 0x1330_0000, b + 0x1340_0000, b + 0x1350_0000, b + 0x1360_0000],
slots: 8192,
pooled: b + 0x1400_0000,
pooled_bytes: 1026 * 512,
dead: b + 0x1410_0000,
@@ -33,8 +33,6 @@ use crate::{Context, DeviceBuffer, Error, Result};
const EPS: f32 = 1e-6;
/// `QsaShapes::page_size` of the real artifact: one page = one indexer block.
const PAGE_SIZE: i32 = 4;
/// The streamed pool of the Rust target holds this many pages (baked in the sealed resolver).
const RESIDENT_PAGES: usize = 8192;
/// Original `MQ`: queries at most for the multi-query block score kernel.
const SCORE_MAX_QUERIES: usize = 8;
const ATTN_CHUNK: usize = 64;
@@ -98,8 +96,8 @@ pub(crate) static RESOLVER: AssetSpec = AssetSpec {
name: "qsa_prompt_resolver.ptx",
ptx: include_bytes!("qsa_prompt_resolver.ptx"),
sha: [
116, 138, 46, 13, 95, 205, 18, 169, 212, 154, 32, 250, 21, 86, 25, 11, 34, 176, 99, 6, 128,
199, 164, 239, 57, 141, 144, 31, 71, 244, 113, 179,
141, 62, 203, 174, 203, 242, 132, 69, 186, 100, 72, 91, 223, 243, 217, 26, 33, 216, 123, 133, 213, 147, 154,
1, 82, 239, 47, 36, 20, 72, 14, 34,
],
entries: RESOLVER_ENTRIES,
unsealed: "Original verifier asset unsealed: qsa_prompt_resolver.ptx (KV streaming resolve)",
@@ -259,6 +257,8 @@ pub struct OriginalVerifyQsaKvBinding {
pub host: [u64; 4],
/// `st.map`: `[table, slot_block, slot_stamp, slot_ref, ctl, miss_block, miss_slot]`.
pub resolver: [u64; 7],
/// `st.map.n_slots`: the resident pages of the streamed pool (`--kv-resident` / 4).
pub slots: usize,
/// `st.idx_pooled` and its byte length.
pub pooled: u64,
pub pooled_bytes: usize,
@@ -275,6 +275,7 @@ impl OriginalVerifyQsaKvBinding {
table: a.table,
host: a.host,
resolver: a.resolver,
slots: a.slots,
pooled: a.pooled,
pooled_bytes: a.pooled_bytes,
dead: a.dead,
@@ -287,7 +288,7 @@ impl OriginalVerifyQsaKvBinding {
if all.clone().any(|&a| a == 0 || a % 16 != 0) {
return Err(Error::InvalidQwenShape);
}
if self.table != self.resolver[0] {
if self.table != self.resolver[0] || self.slots < leleka_context::geometry::RESOLVE_BLOCK || self.slots > i32::MAX as usize / 4 {
return Err(Error::InvalidQwenShape);
}
// pairwise distinct owners (the page table is the resolver's first word)
@@ -672,14 +673,14 @@ impl<'a> QsaWindow<'a> {
let g = &self.g;
w.kv.validate(g)?;
// each query selects whole 4-cell blocks plus a partial one; all of them must fit the miss arrays
if s.n * (g.selection.div_ceil(PAGE_SIZE as usize) + 1) > RESIDENT_PAGES {
if s.n * (g.selection.div_ceil(PAGE_SIZE as usize) + 1) > w.kv.slots {
return Err(refuse!("the window's selections can miss more blocks than the resolver has slots"));
}
let ids = self.span("sel", s.tb * g.selection * 4, s.n * g.selection * 4)?;
let steps = self.span("step", s.tb * 16, s.n * 16)?;
let r = &w.kv.resolver;
let mut resolve: Vec<A> = r.iter().map(|&a| A::P(a)).collect();
resolve.extend([A::P(ids), A::P(steps), A::I32(s.n as i32)]);
resolve.extend([A::P(ids), A::P(steps), A::I32(s.n as i32), A::I64(w.kv.slots as i64)]);
let mut copy = vec![A::P(r[4]), A::P(r[5]), A::P(r[6])];
copy.extend(w.kv.host.iter().chain(&w.kv.resident).map(|&a| A::P(a)));
Ok(vec![
@@ -780,6 +781,7 @@ mod tests {
table: 0x1_3000_0000,
host: [0x2_0000_0000, 0x2_1000_0000, 0x2_2000_0000, 0x2_2100_0000],
resolver: [0x1_3000_0000, 0x1_3100_0000, 0x1_3200_0000, 0x1_3300_0000, 0x1_3400_0000, 0x1_3500_0000, 0x1_3600_0000],
slots: 8192,
pooled: 0x1_4000_0000,
pooled_bytes: 1026 * 512,
dead: 0x1_4100_0000,
@@ -1215,7 +1217,7 @@ mod tests {
assert_eq!(l.len(), 2);
assert_eq!((l[0].entry, l[0].grid, l[0].block), ("leleka_qsa_resolve", [1, 1, 1], [1024, 1, 1]));
let mut want: Vec<A> = KV.resolver.iter().map(|&a| A::P(a)).collect();
want.extend([A::P(at(&m, "sel", 0)), A::P(at(&m, "step", 0)), A::I32(n as i32)]);
want.extend([A::P(at(&m, "sel", 0)), A::P(at(&m, "step", 0)), A::I32(n as i32), A::I64(8192)]);
assert_eq!(l[0].args, want);
assert_eq!((l[1].entry, l[1].grid, l[1].block), ("leleka_qsa_miss_copy", [96, 1, 1], [128, 1, 1]));
let mut copy = vec![A::P(KV.resolver[4]), A::P(KV.resolver[5]), A::P(KV.resolver[6])];
@@ -1227,6 +1229,25 @@ mod tests {
assert_eq!(l[0].args[7], A::P(at(&m, "sel", 3 * 2051 * 4)));
assert_eq!(l[0].args[8], A::P(at(&m, "step", 3 * 16)));
assert_eq!(l[0].args[9], A::I32(3));
assert_eq!(l[0].args[10], A::I64(8192));
}
#[test]
fn resolve_launches_with_the_owners_resident_window_and_refuses_one_too_small() {
let (m, g) = setup();
let w = window(&m, g);
// --kv-resident 20480: 5120 slots hold the selections of a whole 8-row window
let mut l = layer();
l.kv.slots = 5120;
let launches = w.kv_resolve(0, &l, rows(0, 8)).unwrap();
assert_eq!(launches[0].args[10], A::I64(5120));
launches.iter().for_each(assert_abi);
// fewer slots than the resolve block, or than one call can miss, is refused before any launch
l.kv.slots = 1023;
assert!(w.kv_resolve(0, &l, rows(0, 1)).is_err());
l.kv.slots = 1024;
assert!(w.kv_resolve(0, &l, rows(0, 1)).is_ok());
assert!(w.kv_resolve(0, &l, rows(0, 2)).is_err());
}
#[test]
+4 -4
View File
@@ -155,16 +155,16 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx>{
impl<'ctx> OriginalQsaMappedJournal<'ctx>{
/// Fixed device addresses the captured verifier window binds for this layer's streamed INT8 KV:
/// (resident pools `[k_q, v_q, k_scale, v_scale]`, page table, host copy `[k_q, v_q, k_scale, v_scale]`,
/// resolver `[table, slot_block, slot_stamp, slot_ref, ctl, miss_block, miss_slot]`).
/// resolver `[table, slot_block, slot_stamp, slot_ref, ctl, miss_block, miss_slot]`, resident page count).
/// Read only: no coverage, epoch or resolver state changes.
pub(crate) fn window_kv_addresses(&self)->Result<([u64;4],u64,[u64;4],[u64;7])>{
pub(crate) fn window_kv_addresses(&self)->Result<([u64;4],u64,[u64;4],[u64;7],usize)>{
self.validate_context(self.owner.context)?;
// The captured window launches the resolver against these slots: it must have been reset (zeroed
// page table / slot stamps) by an owner call first, exactly like the prompt paths do lazily.
if !self.resolver_ready{return Err(Error::InvalidDriverValue("Original verifier producer unavailable: qsa_resolve: the streamed KV resolver was not initialised (reset) before the window capture"))}
let table=self.owner.pools.table()?;
let resolver=self.owner.resolver.as_ref().ok_or(Error::ContextPoisoned)?.window_addresses(table)?;
Ok((self.owner.pools.addresses()?,table,self.owner.host_addresses()?,resolver))
let r=self.owner.resolver.as_ref().ok_or(Error::ContextPoisoned)?;let resolver=r.window_addresses(table)?;
Ok((self.owner.pools.addresses()?,table,self.owner.host_addresses()?,resolver,r.n_slots()))
}
pub(crate) fn resolved_addresses(&mut self,w:&mut NativeBatchWorkspace<'ctx>,prefix:&OriginalQsaMappedPrefix,ids:&DeviceBuffer<'_>,steps:&DeviceBuffer<'_>,t:usize)->Result<([u64;4],u64,usize)>{
self.validate_prefix(prefix)?;w.validate_context(self.owner.context)?;if !(1..=3).contains(&t){return Err(Error::InvalidQwenShape)}
+20 -7
View File
@@ -2,7 +2,7 @@
//! Immutable snapshots are completed byte ownership, never a runtime causal certificate.
use crate::qsa_prompt_attention_ffi::{Arg, Arguments, Module};
use crate::qsa_prompt_host_ffi::MappedAllocation;
use crate::qsa_prompt_resolver::{MAP_BYTES, Resolver};
use crate::qsa_prompt_resolver::Resolver;
use crate::{Context, DeviceBuffer, Error, NativeBatchWorkspace, Result, combine};
use crate::serving_context::geometry;
use std::rc::Rc;
@@ -10,7 +10,9 @@ use std::rc::Rc;
// public API; every internal use derives the size of the configured serving context from
// `serving_context::geometry()`, which equals these at the default (asserted in `leleka-context`).
pub const QSA_PROMPT_MAX_CELLS: usize = 262144;
pub const QSA_PROMPT_RESIDENT_BYTES: usize = 34_865_152 + MAP_BYTES;
/// Device bytes of one layer at the DEFAULT resident window (32768 cells); a configured `--kv-resident`
/// window changes it (`QsaPromptKv::allocated_bytes` reports the actual owner).
pub const QSA_PROMPT_RESIDENT_BYTES: usize = 34_865_152 + 163_904;
pub const QSA_PROMPT_STAGE_BYTES: usize = 277_086_212; // four pools, identity table,4B status
pub const QSA_PROMPT_HOST_PAGE_BYTES: usize = 4224;
pub const QSA_PROMPT_MAX_SNAPSHOT_PAYLOAD_BYTES: usize = 276_824_064;
@@ -36,7 +38,10 @@ fn offsets() -> Result<[usize; 4]> {
fn stage_runs() -> Result<[usize; 4]> {
geometry().stage_runs().map_err(|_| Error::InvalidSize)
}
const RESIDENT: [usize; 4] = [16777216, 16777216, 524288, 524288];
/// The four resident runs of `slots` resident pages (`[16777216, 16777216, 524288, 524288]` at 8192).
fn resident_runs(slots: usize) -> Result<[usize; 4]> {
leleka_context::geometry::resident_runs(slots).map_err(|_| Error::InvalidSize)
}
/// A real borrowed normalized/RoPE K and raw V pair. Shape is not readiness.
pub struct QsaKvInputs<'loan, 'buffers> {
keys: &'loan DeviceBuffer<'buffers>,
@@ -266,6 +271,8 @@ pub struct QsaPromptKv<'ctx> {
mapped_current: Option<Rc<Snapshot>>,
mapped: Option<MappedAllocation>,
resolver: Option<Resolver<'ctx>>,
/// Resident pages (VRAM slots) of this owner, fixed at construction (`--kv-resident` / 4).
slots: usize,
failed: bool,
}
/// ONE model-owned full-context staging pool; shared serially among QSA layers.
@@ -287,10 +294,11 @@ impl Context<'_> {
}
impl<'ctx> QsaPromptKv<'ctx> {
fn new(c: &'ctx Context<'ctx>) -> Result<Self> {
let slots = crate::serving_context::kv_resident_pages()?;
admit(
c,
geometry()
.resident_bytes(MAP_BYTES)
.resident_bytes_with(slots, Resolver::map_bytes(slots)?)
.map_err(|_| Error::BudgetExceeded)?,
)?;
let mut o = Self {
@@ -301,12 +309,13 @@ impl<'ctx> QsaPromptKv<'ctx> {
mapped_current: None,
mapped: None,
resolver: None,
slots,
failed: false,
};
let r = (|| {
// Asset fails closed before host allocation. Root charges mapped AND immutable
// snapshot payload as separate actual host owners, never transient-cap credit.
o.resolver = Some(Resolver::new(c)?);
o.resolver = Some(Resolver::new(c, slots)?);
let text =
std::fs::read_to_string("/proc/meminfo").map_err(|_| Error::HostAllocation)?;
let available = text
@@ -344,7 +353,7 @@ impl<'ctx> QsaPromptKv<'ctx> {
return combine(Err(e), pop);
}
}
o.pools.allocate(c, RESIDENT)?;
o.pools.allocate(c, resident_runs(slots)?)?;
if c.memory_info()?.0 < RESERVE {
return Err(Error::BudgetExceeded);
}
@@ -375,6 +384,10 @@ impl<'ctx> QsaPromptKv<'ctx> {
pub fn allocated_bytes(&self) -> usize {
self.pools.bytes() + self.resolver.as_ref().map_or(0, Resolver::bytes)
}
/// Resident pages (VRAM slots) of this owner.
pub fn resident_pages(&self) -> usize {
self.slots
}
pub fn pinned_host_bytes(&self) -> usize {
self.mapped.as_ref().map_or(0, MappedAllocation::bytes)
}
@@ -385,7 +398,7 @@ impl<'ctx> QsaPromptKv<'ctx> {
if self.is_failed() {
return Err(Error::ContextPoisoned);
}
self.pools.validate(self.context, RESIDENT)?;
self.pools.validate(self.context, resident_runs(self.slots)?)?;
self.resolver
.as_ref()
.ok_or(Error::ContextPoisoned)?
@@ -29,8 +29,11 @@ __device__ int block_scan(int v, int* warp_sums, int& total) {
return excl;
}
extern "C" __global__ void __launch_bounds__(RT) leleka_qsa_resolve(int32_t*table,int32_t*block,int32_t*stamp,int32_t*ref,int32_t*ctl,int32_t*miss_block,int32_t*miss_slot,const int32_t*ids,const int32_t*steps,int n_q) {
const KvStreamMap m{table,block,stamp,ref,ctl,miss_block,miss_slot,65536,8192}; const int cap=2051,page_size=4;
// `n_slots` is the resident page count of the streamed layer (`--kv-resident` / 4; the old kernel baked 8192, i.e.
// 32768 cells). The host side guarantees n_slots >= RT (kv_stream_resolve's guard) and that one call's distinct
// blocks fit (n_q x (cap / page_size + 2) <= n_slots). `n_blocks` is not read by the resolve phases.
extern "C" __global__ void __launch_bounds__(RT) leleka_qsa_resolve(int32_t*table,int32_t*block,int32_t*stamp,int32_t*ref,int32_t*ctl,int32_t*miss_block,int32_t*miss_slot,const int32_t*ids,const int32_t*steps,int n_q,int64_t n_slots) {
const KvStreamMap m{table,block,stamp,ref,ctl,miss_block,miss_slot,0,n_slots}; const int cap=2051,page_size=4;
__shared__ int s_nmiss, s_lookups, s_cut;
__shared__ int warp_sums[32];
const int epoch = m.ctl[0] + 1;
@@ -109,7 +112,7 @@ extern "C" __global__ void __launch_bounds__(RT) leleka_qsa_resolve(int32_t*tabl
// One block per missed block (grid-stride): copy its runs from the host copy into its slot, 16 B per thread.
extern "C" __global__ void leleka_qsa_miss_copy(int32_t*ctl,int32_t*miss_block,int32_t*miss_slot,const uint8_t*sk,const uint8_t*sv,const uint8_t*sks,const uint8_t*svs,uint8_t*dk,uint8_t*dv,uint8_t*dks,uint8_t*dvs) {
const KvStreamMap m{nullptr,nullptr,nullptr,nullptr,ctl,miss_block,miss_slot,65536,8192}; const Runs r{{sk,sv,sks,svs},{dk,dv,dks,dvs},{2048,2048,64,64},4};
const KvStreamMap m{nullptr,nullptr,nullptr,nullptr,ctl,miss_block,miss_slot,0,0}; const Runs r{{sk,sv,sks,svs},{dk,dv,dks,dvs},{2048,2048,64,64},4};
const int need = m.ctl[2];
for (int k = blockIdx.x; k < need; k += gridDim.x) {
const long long b = m.miss_block[k], sl = m.miss_slot[k];
@@ -122,9 +125,9 @@ extern "C" __global__ void leleka_qsa_miss_copy(int32_t*ctl,int32_t*miss_block,i
}
// `n_blocks` is the page count of the serving context (cells / 4; 65536 at the trained 262144): the old kernel baked
// 65536, which would leave every page-table entry past it uninitialised at a larger context.
extern "C" __global__ void leleka_qsa_stream_reset(int32_t*table,int32_t*block,int32_t*stamp,int32_t*ref,int32_t*ctl,int32_t*miss_block,int32_t*miss_slot,int64_t n_blocks) {
const KvStreamMap m{table,block,stamp,ref,ctl,miss_block,miss_slot,n_blocks,8192};
// 65536, which would leave every page-table entry past it uninitialised at a larger context. `n_slots` as above.
extern "C" __global__ void leleka_qsa_stream_reset(int32_t*table,int32_t*block,int32_t*stamp,int32_t*ref,int32_t*ctl,int32_t*miss_block,int32_t*miss_slot,int64_t n_blocks,int64_t n_slots) {
const KvStreamMap m{table,block,stamp,ref,ctl,miss_block,miss_slot,n_blocks,n_slots};
const long long i0 = (long long) blockIdx.x * blockDim.x + threadIdx.x, st = (long long) gridDim.x * blockDim.x;
for (long long i = i0; i < m.n_blocks; i += st) m.page_table[i] = -1;
for (long long i = i0; i < m.n_slots; i += st) {
File diff suppressed because it is too large Load Diff
+52 -48
View File
@@ -1,32 +1,24 @@
//! Literal Original clock state and mapped-host miss copy. No selectable policy or public address.
//! The resident page count (`n_slots`, `--kv-resident` / 4) is fixed per owner at construction.
use crate::qsa_prompt_attention_ffi::{Arg, Arguments, Module};
use crate::qsa_prompt_kv::checked;
use crate::{Context, DeviceBuffer, Error, NativeBatchWorkspace, Result, combine};
pub(crate) const MAP_BYTES: usize = 163904; // five8192*i32 owners +16i32 ctl
/// Page-table entries `leleka_qsa_stream_reset` clears in the committed PTX (`262144 / 4`).
const FROZEN_RESET_BLOCKS: usize = 65536;
use leleka_context::geometry::{RESOLVE_BLOCK, stream_map_bytes};
const CTL_BYTES: usize = 64;
const RESOLVER_PTX: &str = include_str!("qsa_prompt_resolver.ptx");
/// Blocks one query's selection can name: `2051 / 4` whole blocks plus the partial and the spare one.
pub(crate) const BLOCKS_PER_QUERY: usize = 2051 / 4 + 2;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ResetAbi {
/// Seven parameters, the page count baked in the kernel.
Frozen,
/// Regenerated PTX: an eighth `n_blocks` parameter.
Extended,
}
/// Inspect the embedded PTX once; anything but the frozen or the extended list is refused.
fn reset_abi() -> Result<ResetAbi> {
use leleka_context::ptx_abi::{AbiState, abi_state};
static ABI: std::sync::OnceLock<Result<ResetAbi>> = std::sync::OnceLock::new();
ABI.get_or_init(
|| match abi_state(RESOLVER_PTX, "leleka_qsa_stream_reset", 7, 1) {
AbiState::Frozen => Ok(ResetAbi::Frozen),
AbiState::Extended => Ok(ResetAbi::Extended),
AbiState::Unknown => Err(Error::UnsupportedQwenOperation),
},
)
.clone()
/// The committed PTX must take `n_blocks, n_slots` in the reset and `n_slots` in the resolve.
fn check_abi() -> Result<()> {
use leleka_context::ptx_abi::entry_param_count;
static ABI: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let ok = *ABI.get_or_init(|| {
entry_param_count(RESOLVER_PTX, "leleka_qsa_stream_reset") == Some(9)
&& entry_param_count(RESOLVER_PTX, "leleka_qsa_resolve") == Some(11)
&& entry_param_count(RESOLVER_PTX, "leleka_qsa_miss_copy") == Some(11)
});
if ok { Ok(()) } else { Err(Error::UnsupportedQwenOperation) }
}
pub(crate) struct Resolver<'ctx> {
context: &'ctx Context<'ctx>,
@@ -34,10 +26,21 @@ pub(crate) struct Resolver<'ctx> {
ctl: Option<DeviceBuffer<'ctx>>,
module: Option<Module>,
epoch: i32,
/// Resident pages of the owner (the clock's slot count).
n_slots: usize,
failed: bool,
}
impl<'ctx> Resolver<'ctx> {
pub(crate) fn new(c: &'ctx Context<'ctx>) -> Result<Self> {
/// Resolver state of `n_slots` resident pages (`kv_stream_map_bytes`).
pub(crate) fn map_bytes(n_slots: usize) -> Result<usize> {
stream_map_bytes(n_slots).map_err(|_| Error::InvalidSize)
}
pub(crate) fn new(c: &'ctx Context<'ctx>, n_slots: usize) -> Result<Self> {
check_abi()?;
// kv_stream_resolve's guard: one sweep step looks at RT consecutive slots
if n_slots < RESOLVE_BLOCK || n_slots > i32::MAX as usize / 4 {
return Err(Error::InvalidQwenShape);
}
let g = c.enter()?;
let load = Module::load(
include_bytes!("qsa_prompt_resolver.ptx"),
@@ -65,13 +68,14 @@ impl<'ctx> Resolver<'ctx> {
ctl: None,
module: Some(module),
epoch: 0,
n_slots,
failed: false,
};
let r = (|| {
for b in &mut o.slots {
*b = Some(c.allocate(32768)?);
*b = Some(c.allocate(n_slots * 4)?);
}
o.ctl = Some(c.allocate(64)?);
o.ctl = Some(c.allocate(CTL_BYTES)?);
Ok(())
})();
if let Err(e) = r {
@@ -95,13 +99,13 @@ impl<'ctx> Resolver<'ctx> {
checked(
self.context,
b.as_ref().ok_or(Error::ContextPoisoned)?,
32768,
self.n_slots * 4,
)?;
}
checked(
self.context,
self.ctl.as_ref().ok_or(Error::ContextPoisoned)?,
64,
CTL_BYTES,
)?;
Ok(())
}
@@ -110,8 +114,8 @@ impl<'ctx> Resolver<'ctx> {
/// captured verifier window; the miss copy kernel takes entries 4..7.
pub(crate) fn window_addresses(&self, table: u64) -> Result<[u64; 7]> {
self.validate()?;
let slot = |i: usize| checked(self.context, self.slots[i].as_ref().ok_or(Error::ContextPoisoned)?, 32768);
let ctl = checked(self.context, self.ctl.as_ref().ok_or(Error::ContextPoisoned)?, 64)?;
let slot = |i: usize| checked(self.context, self.slots[i].as_ref().ok_or(Error::ContextPoisoned)?, self.n_slots * 4);
let ctl = checked(self.context, self.ctl.as_ref().ok_or(Error::ContextPoisoned)?, CTL_BYTES)?;
Ok([table, slot(0)?, slot(1)?, slot(2)?, ctl, slot(3)?, slot(4)?])
}
fn addresses(&self, table: u64) -> Result<Vec<Arg>> {
@@ -123,19 +127,19 @@ impl<'ctx> Resolver<'ctx> {
v.push(Arg::U64(checked(
self.context,
self.slots[i].as_ref().ok_or(Error::ContextPoisoned)?,
32768,
self.n_slots * 4,
)?));
}
v.push(Arg::U64(checked(
self.context,
self.ctl.as_ref().ok_or(Error::ContextPoisoned)?,
64,
CTL_BYTES,
)?));
for i in 3..5 {
v.push(Arg::U64(checked(
self.context,
self.slots[i].as_ref().ok_or(Error::ContextPoisoned)?,
32768,
self.n_slots * 4,
)?));
}
Ok(v)
@@ -173,24 +177,24 @@ impl<'ctx> Resolver<'ctx> {
}
combine(combine(op, sync), pop)
}
/// The owner's resident page count.
pub(crate) fn n_slots(&self) -> usize {
self.n_slots
}
pub(crate) fn reset(&mut self, w: &mut NativeBatchWorkspace<'ctx>, table: u64) -> Result<()> {
let mut values = self.addresses(table)?;
let pages = crate::serving_context::geometry().pages();
match reset_abi()? {
// The committed PTX bakes 65536 page-table entries (the trained 262144 cells).
ResetAbi::Frozen if pages > FROZEN_RESET_BLOCKS => {
return Err(Error::UnsupportedQwenOperation);
}
ResetAbi::Frozen => {}
ResetAbi::Extended => values.push(Arg::I64(pages as i64)),
}
values.push(Arg::I64(pages as i64));
values.push(Arg::I64(self.n_slots as i64));
let a = Arguments::new(values)?;
self.run(w, 0, [128, 1, 1], 256, a)?;
self.epoch = 0;
Ok(())
}
/// Guarded Q/IDs/steps must already be completed and shape-checked. T<=3 bounds
/// distinct miss count by3*2051 (<8192), even without exploiting sorted page overlap.
/// Guarded Q/IDs/steps must already be completed and shape-checked. The selections name whole
/// 4-cell blocks plus the partial one, so one query touches at most `BLOCKS_PER_QUERY` blocks and
/// T<=3 queries at most 1542 (`kv_stream_resolve`'s `n_q x (cap / page_size + 2)` bound), below the
/// smallest window (5120 slots).
pub(crate) fn resolve(
&mut self,
w: &mut NativeBatchWorkspace<'ctx>,
@@ -201,26 +205,26 @@ impl<'ctx> Resolver<'ctx> {
host: [u64; 4],
resident: [u64; 4],
) -> Result<()> {
if !(1..=3).contains(&t) {
if !(1..=3).contains(&t) || t * BLOCKS_PER_QUERY > self.n_slots {
return Err(Error::InvalidQwenShape);
}
let epoch = self.epoch.checked_add(1).ok_or(Error::InvalidQwenShape)?;
let mut a = self.addresses(table)?;
a.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?;
a.extend([Arg::U64(ids), Arg::U64(steps), Arg::I32(t as i32)]);
a.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?;
a.extend([Arg::U64(ids), Arg::U64(steps), Arg::I32(t as i32), Arg::I64(self.n_slots as i64)]);
let mut copy = Vec::new();
copy.try_reserve_exact(11)
.map_err(|_| Error::HostAllocation)?;
copy.push(Arg::U64(checked(
self.context,
self.ctl.as_ref().ok_or(Error::ContextPoisoned)?,
64,
CTL_BYTES,
)?));
for i in 3..5 {
copy.push(Arg::U64(checked(
self.context,
self.slots[i].as_ref().ok_or(Error::ContextPoisoned)?,
32768,
self.n_slots * 4,
)?));
}
for x in host.into_iter().chain(resident) {
@@ -17,7 +17,7 @@ impl OriginalVerifyRope<'_, '_>{fn validate(&self,c:&Context<'_>,capacity:usize)
fn whole(c:&Context<'_>,b:&DeviceBuffer<'_>,bytes:usize)->Result<u64>{if !std::ptr::eq(c,b.context){return Err(Error::ContextMismatch)}if b.len()!=bytes{return Err(Error::ShapeMismatch{expected:bytes,actual:b.len()})}let h=b.handle.ok_or(Error::ContextPoisoned)?;h.validate_projection_extent(bytes,4)?;Ok(h.qwen_address())}
fn overlaps(a:&DeviceBuffer<'_>,b:&DeviceBuffer<'_>)->Result<bool>{Ok(a.handle.ok_or(Error::ContextPoisoned)?.overlaps(a.len(),b.handle.ok_or(Error::ContextPoisoned)?,b.len()))}
/// Addresses of one QSA layer's fixed owners (see `OriginalVerifyQsaJournal::window_addresses`).
pub(crate) struct OriginalVerifyQsaWindowAddresses{pub resident:[u64;4],pub table:u64,pub host:[u64;4],pub resolver:[u64;7],pub pooled:u64,pub pooled_bytes:usize,pub dead:u64,pub dead_bytes:usize}
pub(crate) struct OriginalVerifyQsaWindowAddresses{pub resident:[u64;4],pub table:u64,pub host:[u64;4],pub resolver:[u64;7],pub slots:usize,pub pooled:u64,pub pooled_bytes:usize,pub dead:u64,pub dead_bytes:usize}
struct Live{generation:u64,position:usize,rows:usize,armed:bool}
/// Actual source gamma references, table owners and index images stay alive
/// through ALL graph captures/replays and accepted-prefix commits.
@@ -49,11 +49,11 @@ impl<'a,'ctx> OriginalVerifyQsaJournal<'a,'ctx>{
/// Read only; the window recorder may call it while a window is armed because no state changes.
pub(crate) fn window_addresses(&self,layer:usize)->Result<OriginalVerifyQsaWindowAddresses>{
self.validate_context(self.context)?;if layer>=12{return Err(Error::InvalidQwenShape)}
let (resident,table,host,resolver)=self.mapped[layer].try_borrow().map_err(|_|Error::InvalidQwenShape)?.window_kv_addresses()?;
let (resident,table,host,resolver,slots)=self.mapped[layer].try_borrow().map_err(|_|Error::InvalidQwenShape)?.window_kv_addresses()?;
let i=self.indices[layer].try_borrow().map_err(|_|Error::InvalidQwenShape)?;
let pooled=i.image[0].as_ref().ok_or(Error::ContextPoisoned)?;let dead=i.image[2].as_ref().ok_or(Error::ContextPoisoned)?;
let address=|b:&DeviceBuffer<'ctx>|->Result<u64>{Ok(b.handle.ok_or(Error::ContextPoisoned)?.qwen_address())};
Ok(OriginalVerifyQsaWindowAddresses{resident,table,host,resolver,pooled:address(pooled)?,pooled_bytes:pooled.len(),dead:address(dead)?,dead_bytes:dead.len()})
Ok(OriginalVerifyQsaWindowAddresses{resident,table,host,resolver,slots,pooled:address(pooled)?,pooled_bytes:pooled.len(),dead:address(dead)?,dead_bytes:dead.len()})
}
pub fn allocated_bytes(&self)->usize{self.indices.iter().map(|i|i.borrow().allocated_bytes()).sum::<usize>()+self.mapped.iter().map(|m|m.borrow().allocated_bytes()).sum::<usize>()}
pub(crate) fn begin_window(&self,bank:&OriginalVerifyBank<'ctx>)->Result<()>{
+47
View File
@@ -88,6 +88,46 @@ pub(crate) fn geometry() -> QsaGeometry {
serving_context().geometry
}
/// The resident KV window (cells per QSA layer kept in VRAM, `--kv-resident`) of the default configuration.
pub const KV_RESIDENT_DEFAULT_CELLS: usize = leleka_context::geometry::KV_RESIDENT_DEFAULT_CELLS;
/// `qsa_kv_resident_min()`.
pub const KV_RESIDENT_MIN_CELLS: usize = leleka_context::geometry::KV_RESIDENT_MIN_CELLS;
static KV_RESIDENT: OnceLock<usize> = OnceLock::new();
/// Fix the resident KV window of the streamed QSA layers for this process (`--kv-resident N`, the Original's
/// `qsa_set_kv_resident` before any state exists). `0` keeps the whole context resident; a positive count is
/// raised to `qsa_kv_resident_min()` (20480) and rounded up to whole pages. The first call wins; a later call
/// must request the same count. Every owner sizes its pool from the value when it is created and launches
/// with its own slot count, so an owner created before this call keeps the default window consistently.
pub fn configure_kv_resident(cells: usize) -> Result<()> {
geometry()
.resident_pages_for(cells)
.map_err(|_| Error::InvalidDriverValue("resident KV window"))?;
if *KV_RESIDENT.get_or_init(|| cells) == cells {
Ok(())
} else {
Err(Error::InvalidDriverValue(
"resident KV window already configured differently",
))
}
}
/// The configured resident KV window in cells (the default 32768 when none was configured).
pub fn kv_resident_cells() -> usize {
KV_RESIDENT
.get()
.copied()
.unwrap_or(KV_RESIDENT_DEFAULT_CELLS)
}
/// Resident pages (VRAM slots) a new streamed QSA owner allocates.
pub(crate) fn kv_resident_pages() -> Result<usize> {
geometry()
.resident_pages_for(kv_resident_cells())
.map_err(|_| Error::InvalidDriverValue("resident KV window"))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -100,6 +140,13 @@ mod tests {
assert!(!c.rope_is_scaled());
}
#[test]
fn the_default_resident_window_is_the_frozen_8192_page_pool() {
assert_eq!(KV_RESIDENT_DEFAULT_CELLS, 32_768);
assert!(geometry().resident_pages_for(KV_RESIDENT_DEFAULT_CELLS) == Ok(8192));
assert!(configure_kv_resident(MAX_CONTEXT_CELLS + 4).is_err());
}
#[test]
fn refuses_past_trained_without_scaling_and_bad_counts() {
assert!(configure_serving_context(524_288, &RopeScaling::default()).is_err());
+1 -1
View File
@@ -136,7 +136,7 @@
},
{
"ptx": "crates/cuda-driver/src/qsa_prompt_resolver.ptx",
"sha256": "748a2e0d5fcd12a9d49a20fa1556190b22b0630680c7a4ef398d901f47f471b3"
"sha256": "8d3ecbaecbf28445ba64485bdff3d91a21d87b85d5939a0152ef2f2414480e22"
},
{
"ptx": "crates/cuda-driver/src/qsa_prompt_select.ptx",
+3 -3
View File
@@ -49,11 +49,11 @@ Grep of all non-vendored `.cu`/`.ptx` for 262144 / 65536 / 65537 / 65538: the on
| `qsa_prompt_indexer.cu` | `qsa_append_first`, `qsa_append_blocks`, `qsa_decode_append` | 5 trailing floats `freq_scale, corr_low, corr_high, ext_factor, mscale` replace the baked identity |
| `qsa_prompt_postops.cu` | `qsa_rope_rows` | same 5 floats |
| `qsa_decode_postops.cu` | `qsa_decode_rope` | same 5 floats |
| `qsa_prompt_resolver.cu` | `leleka_qsa_stream_reset` | trailing `int64_t n_blocks` replaces the baked 65536 (`leleka_qsa_resolve` / `leleka_qsa_miss_copy` do not use `n_blocks`) |
| `qsa_prompt_resolver.cu` | `leleka_qsa_stream_reset`, `leleka_qsa_resolve` | trailing `int64_t n_blocks` replaces the baked 65536 in the reset; a trailing `int64_t n_slots` (the `--kv-resident` page count, see `docs/kv-streaming.md`) replaces the baked 8192 in both (`leleka_qsa_miss_copy` reads neither) |
Frozen parameter counts of the committed PTX (asserted by `ptx_abi::tests::committed_ptx_has_the_frozen_argument_lists`): first 6, blocks 13, decode_append 11, rope_rows 6, decode_rope 6 (each +5 after regeneration), stream_reset 7 (+1).
Frozen parameter counts of the committed PTX (asserted by `ptx_abi::tests::committed_ptx_has_the_frozen_argument_lists`): first 6, blocks 13, decode_append 11, rope_rows 6, decode_rope 6 (each +5 after regeneration), stream_reset 7 (+2), resolve 10 (+1).
The Rust launch side is ABI-gated so a mismatch cannot be silent: `qsa_index_ffi.rs` (`rope_abi()`, `Arguments::for_launch`) appends the 5 floats only when the PTX is extended; scaled RoPE against frozen PTX is refused. `qsa_prompt_resolver.rs` (`reset_abi()`) appends `n_blocks` for the extended PTX and refuses more than 65536 pages against the frozen one. The default configuration therefore runs on the committed PTX unchanged, and the `Tc` reach limit is `max_blocks()`.
The Rust launch side is ABI-gated so a mismatch cannot be silent: `qsa_index_ffi.rs` (`rope_abi()`, `Arguments::for_launch`) appends the 5 floats only when the PTX is extended; scaled RoPE against frozen PTX is refused. `qsa_prompt_resolver.rs` requires the regenerated resolver (reset 9 and resolve 11 parameters) and refuses any other PTX. The default configuration therefore runs on the committed PTX unchanged, and the `Tc` reach limit is `max_blocks()`.
### Regeneration (Linux host, pinned toolkit 13.0.88)
@@ -87,7 +87,7 @@ class PlanParsing(unittest.TestCase):
self.assertEqual(flags, ["--ptx", "-std=c++17", "-O3", "-arch=sm_120", "--fmad=true", "--ftz=false"])
self.assertEqual(incs, L.STANDARD_INCLUDES)
abi = L.parse_abi_tuples((REPO / L.ABI_SOURCE).read_text())
self.assertEqual(abi["qsa_prompt_resolver.ptx"], {"leleka_qsa_stream_reset": (7, 1)})
self.assertEqual(abi["qsa_prompt_resolver.ptx"], {"leleka_qsa_stream_reset": (7, 2), "leleka_qsa_resolve": (10, 1)})
self.assertEqual(abi["qsa_prompt_indexer.ptx"]["qsa_append_blocks"], (13, 5))
def test_rope_variants_differ_only_for_the_two_fast_math_sources(self):