Merge claude/debt-final-ctx2: positions, the resident KV window and the serving geometry belong to the model binding and the Context, not to the process (STRA-338)

This commit is contained in:
Pavlo Ratushnyi
2026-11-23 23:14:40 +01:00
89 changed files with 388 additions and 294 deletions
+1 -1
View File
@@ -53,7 +53,7 @@
"exceptions": [
{"crate": "leleka-cuda-model", "file": "src/env_switch.rs", "ratchet": "env-read", "reason": "EnvSwitch is the one reader of the operator environment in this crate: it reads one named variable on the first get() and applies a typed rule"},
{"crate": "leleka-cuda-model", "file": "src/env_switch.rs", "ratchet": "process-global", "reason": "the OnceLock inside EnvSwitch caches the switch position for the process life (an immutable operator setting; a hot path pays one atomic load)"},
{"crate": "leleka-cuda-model", "file": "src/serving_context.rs", "ratchet": "process-global", "reason": "the serving context and the resident KV window are fixed once at engine start (configure_*) and read by every kernel geometry; injecting them through every owner is the settings follow-up of S13"},
{"crate": "leleka-cuda-model", "file": "src/serving_context.rs", "ratchet": "process-global", "reason": "the serving context is fixed once at engine start (configure_serving_context); the driver copies it into each Context when the Context is created and every kernel geometry reads it from the Context, so this cell is read at one place (create_context). The engine composition still reads it for the bind-time cell count; handing the value down from the config is the follow-up of S13. The resident KV window is not here: it belongs to the driver Context"},
{"crate": "leleka-cpu-worker", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"},
{"crate": "leleka-tokenizer", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"},
{"crate": "leleka-gptoss-npu", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"},
@@ -4,6 +4,7 @@
use super::{
Cell, Context, Device, Driver, Error, PoisonCell, PromptSyncTrace, Rc, Result, RoutedGateUpQ8, ffi, qwen_dispatch,
};
use leleka_cuda_model::serving_context::ServingContext;
impl PromptSyncTrace {
pub fn enter() -> Self {
@@ -50,7 +51,12 @@ impl Driver {
}
}
impl<'driver> Device<'driver> {
/// A context for the serving context the process configured (the trained default when none was).
pub fn create_context(&self, byte_budget: usize) -> Result<Context<'driver>> {
self.create_context_serving(byte_budget, crate::serving_context::serving_context())
}
/// A context whose buffers are sized and whose rotating kernels are parameterized for `serving`.
pub fn create_context_serving(&self, byte_budget: usize, serving: ServingContext) -> Result<Context<'driver>> {
valid_size(byte_budget)?;
let api = &self.driver.api;
let handle = api.create(self.handle)?;
@@ -64,7 +70,9 @@ impl<'driver> Device<'driver> {
}
return combine(Err(error), cleanup);
}
Ok(Context::fresh(self.driver, handle, self.ordinal, byte_budget))
let mut context = Context::fresh(self.driver, handle, self.ordinal, byte_budget);
context.retained.serving = serving;
Ok(context)
}
}
impl<'driver> Context<'driver> {
@@ -95,7 +103,7 @@ impl<'driver> Context<'driver> {
qwen_kernels: qwen_dispatch::Cache::new(),
kar_levels: Cell::new(None),
experimental: std::array::from_fn(|_| Cell::new(None)),
retained: crate::prompt_sync_trace_types::Retained::default(),
retained: crate::prompt_sync_trace_types::Retained::new(ServingContext::trained()),
}
}
}
+40
View File
@@ -0,0 +1,40 @@
//! The serving context of a Context: the cell count its buffers are sized from and the RoPE constants of its rotating
//! kernels (fixed when the context is created), and the resident KV window its streamed QSA owners keep in VRAM
//! (`--kv-resident N`, the Original's `qsa_set_kv_resident`). Both belong to the Context, not to the process: every
//! owner sizes its pool from the value when it is created, so an owner created before the window is set keeps the
//! default window consistently.
use super::{Context, Error, Result};
use crate::serving_context::{KV_RESIDENT_DEFAULT_CELLS, ServingContext};
use leleka_context::geometry::QsaGeometry;
impl Context<'_> {
/// The serving context this context was created for.
pub fn serving(&self) -> &ServingContext {
&self.retained.serving
}
/// The geometry every context-linear size of this context is derived from.
pub fn serving_geometry(&self) -> QsaGeometry {
self.retained.serving.geometry
}
/// Fix the resident KV window of this context. The first call wins; a later call must request the same count.
pub fn configure_kv_resident(&self, cells: usize) -> Result<()> {
self.serving().resident_pages_for(cells)?;
match self.retained.kv_resident.get() {
Some(set) if set != cells => {
Err(Error::InvalidDriverValue("resident KV window already configured differently"))
}
_ => {
self.retained.kv_resident.set(Some(cells));
Ok(())
}
}
}
/// Resident pages (VRAM slots) a new streamed QSA owner of this context allocates.
pub(crate) fn kv_resident_pages(&self) -> Result<usize> {
self.serving().resident_pages_for(self.retained.kv_resident.get().unwrap_or(KV_RESIDENT_DEFAULT_CELLS))
}
}
@@ -27,11 +27,11 @@ fn synthetic_image(rng: &mut Rng) -> [Vec<u8>; 4] {
/// The real mapped host copy holding `image` and the device addresses of its four runs.
fn map_host(c: &Context<'_>, image: &[Vec<u8>; 4]) -> (MappedAllocation, [u64; 4]) {
let geometry = crate::serving_context::geometry();
let geometry = c.serving_geometry();
let offsets = geometry.stage_offsets().unwrap();
let mut mapped = {
let g = c.enter().unwrap();
let m = MappedAllocation::new();
let m = MappedAllocation::new(geometry);
g.finish().unwrap();
m.expect("pinned mapped host copy")
};
@@ -61,7 +61,7 @@ impl<'c> Pools<'c> {
let identity = upload(c, &i32s(&(0..N_BLOCKS as i32).collect::<Vec<_>>())).unwrap();
let stage = PAGE.iter().map(|n| c.allocate(n * N_BLOCKS).unwrap()).collect();
let resident = PAGE.iter().map(|n| c.allocate(n * slots).unwrap()).collect();
let table = c.allocate(crate::serving_context::geometry().page_table_bytes()).unwrap();
let table = c.allocate(c.serving_geometry().page_table_bytes()).unwrap();
Self { reference, identity, stage, resident, table }
}
@@ -205,7 +205,7 @@ impl<'c> Stream<'c> {
fn new(c: &'c Context<'c>) -> Self {
let mut w = c.native_batch_workspace().expect("workspace");
let mut rng = Rng(0x2545_f491_4f6c_dd1d);
let slots = crate::serving_context::geometry().resident_pages_for(20_480).unwrap();
let slots = c.serving_geometry().resident_pages_for(20_480).unwrap();
assert_eq!(slots, 5120);
let image = synthetic_image(&mut rng);
let (mapped, host) = map_host(c, &image);
@@ -257,7 +257,7 @@ impl<'c> Stream<'c> {
/// Every block the call named is resident and holds the host bytes; nothing overflowed.
fn check_resident(&mut self, call: usize, named: &BTreeSet<usize>) {
let bytes = crate::serving_context::geometry().page_table_bytes();
let bytes = self.pools.table.context.serving_geometry().page_table_bytes();
let map = self.pools.table.copy_to_owned(bytes).unwrap();
let map: Vec<i32> = map.chunks_exact(4).map(|b| i32::from_le_bytes(b.try_into().unwrap())).collect();
let slots = self.slots;
+1
View File
@@ -273,6 +273,7 @@ use q6_k_shape::q6_k_shape;
use q6_k_shape::vector_shape;
mod context;
mod context_gate_up_projection_admission;
mod context_serving;
mod context_matvec_k_quant_projections;
mod context_projection_kernel_slots;
mod context_routed_gate_up_projection;
@@ -1,16 +1,33 @@
//! The host-side lists a `Context` keeps for the verify-window modules and the deferred buffer frees.
//! What a `Context` keeps for itself: the verify-window modules, the deferred buffer frees and the resident KV window
//! its streamed QSA owners are sized from.
use super::{Rc, RefCell, ffi};
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
use super::original_verify;
use super::{Cell, Rc, RefCell, ffi};
use leleka_cuda_model::serving_context::ServingContext;
/// Lists that live and die with the context: both start empty.
#[derive(Default)]
/// State that lives and dies with the context: its serving context, the lists (empty at the start) and the KV window
/// (unset at the start).
pub(crate) struct Retained {
/// The serving context this context was created for: the cell count every context-linear buffer is sized
/// from and the RoPE constants of the rotating kernels. Fixed for the life of the context.
pub(crate) serving: ServingContext,
/// Sealed verify-window modules loaded under this context, shared by every verifier bank created later
/// (the serve path assembles one per request) and unloaded with the context.
pub(crate) window_modules: RefCell<Vec<(&'static str, Rc<original_verify::abi::Module>, Vec<&'static str>)>>,
/// Buffers released while a prompt chunk's expert copies are in flight (cuMemFree synchronizes the whole
/// device and would wait for every queued copy): freed by `flush_deferred_frees`. They stay charged.
pub(crate) deferred_frees: RefCell<Vec<(ffi::BufferHandle, usize)>>,
/// The resident KV window of this context's streamed QSA owners, in cells; `None` keeps the default window.
pub(crate) kv_resident: Cell<Option<usize>>,
}
impl Retained {
pub(crate) fn new(serving: ServingContext) -> Self {
Self {
serving,
window_modules: RefCell::default(),
deferred_frees: RefCell::default(),
kv_resident: Cell::new(None),
}
}
}
+12 -6
View File
@@ -1,5 +1,6 @@
//! Private fixed Original QSA entries. No stream/Blas ownership or public grid API.
use crate::{Error, Result, combine, ffi::BufferHandle};
use leleka_cuda_model::serving_context::ServingContext;
use std::ffi::CStr;
pub(crate) enum Arg {
Address(BufferHandle),
@@ -21,9 +22,9 @@ pub(crate) struct Arguments {
}
impl Arguments {
/// The arguments of `shape` followed, where its kernel takes them, by the serving context's RoPE constants.
pub(crate) fn for_launch(shape: Launch, mut values: Vec<Arg>) -> Result<Self> {
pub(crate) fn for_launch(serving: &ServingContext, shape: Launch, mut values: Vec<Arg>) -> Result<Self> {
shape.check_reach(serving)?;
if shape.carries_rope() {
let serving = crate::serving_context::serving_context();
values.extend(rope_tail(rope_abi()?, serving.rope_is_scaled(), serving.rope_args)?);
}
Self::new(values)
@@ -186,14 +187,19 @@ impl Launch {
fn carries_rope(self) -> bool {
matches!(self, Self::First | Self::Blocks(_) | Self::Rope(_) | Self::DecodeAppend | Self::DecodeRope(_))
}
/// Refuses a ScoreTC reach past the score row of the serving context (checked where the arguments are built, which
/// is where the serving context is known).
fn check_reach(self, serving: &ServingContext) -> Result<()> {
match self {
Self::Tc { reach, .. } if reach as usize > serving.geometry.max_blocks() => Err(Error::InvalidQwenShape),
_ => Ok(()),
}
}
/// Refuses the launches whose extents the Original fixes: the ScoreTC window and the decode norm/rope widths.
fn check_extents(self) -> Result<()> {
match self {
Self::Tc { t, reach } => {
if !(1..=256).contains(&t)
|| reach == 0
|| reach as usize > crate::serving_context::geometry().max_blocks()
{
if !(1..=256).contains(&t) || reach == 0 {
return Err(Error::InvalidQwenShape);
}
}
@@ -31,7 +31,7 @@ pub(super) fn with_gpu(body: impl FnOnce(&Context<'_>, usize, usize)) {
let context = device.create_context(6usize << 30).expect("context");
let workspace = context.native_batch_workspace().expect("workspace");
let stream = workspace.blas().expect("blas").stream();
let max_blocks = crate::serving_context::geometry().max_blocks();
let max_blocks = context.serving_geometry().max_blocks();
body(&context, stream, max_blocks);
}
@@ -1,9 +1,10 @@
//! Private fixed mapped-host allocation. Caller holds actual Context and drains before CPU access/free.
use crate::{Error, Result};
/// Original payload + four 256 B cursor alignment allowances, for the configured serving context
use leleka_context::geometry::QsaGeometry;
/// Original payload + four 256 B cursor alignment allowances, for the serving context of `geometry`
/// (`276_825_088` at the trained 262144 cells).
fn configured_bytes() -> Result<usize> {
crate::serving_context::geometry().mapped_host_bytes().map_err(|_| Error::InvalidSize)
fn configured_bytes(geometry: QsaGeometry) -> Result<usize> {
geometry.mapped_host_bytes().map_err(|_| Error::InvalidSize)
}
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
mod enabled {
@@ -55,12 +56,12 @@ mod enabled {
free: Free,
}
impl MappedAllocation {
pub(crate) fn new() -> Result<Self> {
pub(crate) fn new(geometry: QsaGeometry) -> Result<Self> {
let library = open_library()?;
let alloc = sym!(library, c"cuMemHostAlloc", Alloc);
let address = sym!(library, c"cuMemHostGetDevicePointer_v2", Address);
let free = sym!(library, c"cuMemFreeHost", Free);
let bytes = configured_bytes()?;
let bytes = configured_bytes(geometry)?;
let mut ptr = std::ptr::null_mut();
// SAFETY: valid out pointer; flags 3 = PORTABLE|DEVICEMAP; a context is current (the caller holds the
// Context). On success the allocation is `bytes` long, page-aligned, and owned by `MappedAllocation`
@@ -173,11 +174,11 @@ pub(crate) struct MappedAllocation;
target_pointer_width = "64"
)))]
impl MappedAllocation {
pub(crate) fn new() -> Result<Self> {
pub(crate) fn new(_: QsaGeometry) -> Result<Self> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn bytes(&self) -> usize {
configured_bytes().unwrap_or(0)
0
}
pub(crate) fn address(&self, _: usize, _: usize) -> Result<u64> {
Err(Error::UnsupportedPlatform)
@@ -37,9 +37,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
Ok(())
}
fn select_bounds_ok(&self, p: usize, n: usize) -> bool {
n != 0
&& n <= self.capacity
&& p.checked_add(n).is_some_and(|e| e <= crate::serving_context::geometry().cells())
n != 0 && n <= self.capacity && p.checked_add(n).is_some_and(|e| e <= self.context.serving_geometry().cells())
}
/// Budget check, exact-size allocation and alias admission of the five outputs; releases them on failure.
fn admit_outputs(
@@ -2,14 +2,14 @@
//! buffer sizes), the f32 little-endian encoder for uploads and the Context constructors.
use super::{Context, Error, QsaPromptIndexWorkspace, Result};
use leleka_context::geometry::QsaGeometry;
/// Score row stride (blocks plus tail and spare) of the configured serving context: `65538` at 262144 cells.
pub(super) fn max_blocks() -> usize {
crate::serving_context::geometry().max_blocks()
/// Score row stride (blocks plus tail and spare) of the serving context `g`: `65538` at 262144 cells.
pub(super) fn max_blocks(g: QsaGeometry) -> usize {
g.max_blocks()
}
// pooled,tail,dead,block_position,raw,K,V,Qfull,IndexQ,scores,status.
pub(super) fn sizes() -> [usize; 11] {
let g = crate::serving_context::geometry();
pub(super) fn sizes(g: QsaGeometry) -> [usize; 11] {
[
g.pooled_rows() * 128 * 4,
384 * 4,
@@ -7,6 +7,7 @@ use super::{
QsaPromptIndexWorkspace, RESERVE, Result, S, SCRATCH, SELECT, arena_span, combine, common, ffi, max_blocks,
native_block, sizes,
};
use leleka_context::geometry::QsaGeometry;
type Spans = Vec<(ffi::BufferHandle, usize)>;
@@ -30,11 +31,12 @@ pub(super) fn index_for<'ctx>(
context: &'ctx Context<'ctx>,
capacity: usize,
) -> ([usize; 11], QsaPromptIndexWorkspace<'ctx>) {
let mut sizes = sizes();
let geometry = context.serving_geometry();
let mut sizes = sizes(geometry);
for i in [4, 5, 6, 7, 8] {
sizes[i] = 4
}
sizes[9] = capacity.min(256) * max_blocks() * 4;
sizes[9] = capacity.min(256) * max_blocks(geometry) * 4;
let index = QsaPromptIndexWorkspace {
capacity,
sizes,
@@ -250,9 +252,9 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
}
/// The prior image must have the lengths of a prompt starting at `p` and be finite.
pub(super) fn check_prior(t: usize, p: usize, prior: [&[f32]; 3]) -> Result<()> {
pub(super) fn check_prior(geometry: QsaGeometry, t: usize, p: usize, prior: [&[f32]; 3]) -> Result<()> {
let [pooled, tail, dead] = prior;
if p.checked_add(t).is_none_or(|end| end > crate::serving_context::geometry().cells())
if p.checked_add(t).is_none_or(|end| end > geometry.cells())
|| pooled.len() != p / 4 * 128
|| tail.len() != 384
|| dead.len() != 128
@@ -40,7 +40,7 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
let QsaChunkPrior { first_position: p0, image } = prior;
let QsaIndexPrior { pooled, tail, dead } = image;
let (t, p) = (read.rows(), p0 as usize);
Self::check_prior(t, p, [pooled, tail, dead])?;
Self::check_prior(self.context.serving_geometry(), t, p, [pooled, tail, dead])?;
let (w, gamma) = self.admit(&read, &weights, ws)?;
self.project_prior(&read, ws, &weights.kinds, w)?;
let (out, [raw, qfull, iq]) = self.index_spans(&read, t)?;
@@ -7,9 +7,10 @@ use super::{
OriginalQsaPromptWeights, QsaNativePacking, QsaPromptIndexWorkspace, RESERVE, Result, SCRATCH, ffi, max_blocks,
sizes,
};
use leleka_context::geometry::QsaGeometry;
impl<'ctx> OriginalQsaPromptDevice<'ctx> {
pub fn device_bytes(capacity: usize) -> Result<usize> {
pub fn device_bytes(geometry: QsaGeometry, capacity: usize) -> Result<usize> {
if !(1..=8192).contains(&capacity) {
return Err(Error::InvalidQwenShape);
}
@@ -17,17 +18,19 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
// projection/normalized/IDs/attn/Out payloads are actual arena spans.
(SCRATCH
+ {
let z = sizes();
let z = sizes(geometry);
z[0] + z[1] + z[2] + z[3]
}
+ 5 * 4
+ 64)
.checked_add(capacity.min(256) * max_blocks() * 4)
.checked_add(capacity.min(256) * max_blocks(geometry) * 4)
.and_then(|x| x.checked_add(capacity * 16))
.ok_or(Error::BudgetExceeded)
}
pub(super) fn new(context: &'ctx Context<'ctx>, capacity: usize, packing: QsaNativePacking) -> Result<Self> {
let required = Self::device_bytes(capacity)?.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?;
let required = Self::device_bytes(context.serving_geometry(), capacity)?
.checked_add(RESERVE)
.ok_or(Error::BudgetExceeded)?;
check_assets()?;
if context.is_poisoned() {
return Err(Error::ContextPoisoned);
@@ -7,6 +7,7 @@ use super::{
OriginalQsaResidentIndex, OriginalQsaResidentSelection, PrefillPhase, ProjectionSpans, ProjectionWeight,
QsaPromptIndexWorkspace, RESERVE, ResidentContinuation, Result, S, arena_span, combine, common, ffi,
};
use leleka_context::geometry::QsaGeometry;
/// The spans the resident index program reads and writes for one chunk.
struct ResidentSpans {
@@ -96,7 +97,7 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
if t == 0 || t > self.capacity {
return Err(Error::InvalidQwenShape);
}
if p.checked_add(t).is_none_or(|end| end > crate::serving_context::geometry().cells()) {
if p.checked_add(t).is_none_or(|end| end > self.context.serving_geometry().cells()) {
return Err(Error::InvalidQwenShape);
}
self.admit_budget(t)?;
@@ -253,19 +254,20 @@ impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>
}
pub(crate) fn kv_stage_spans(&self, c: &Context<'_>) -> Result<[ffi::BufferHandle; 4]> {
self.validate(c)?;
kv_stage_spans_of(&self.read, self.rows())
kv_stage_spans_of(c.serving_geometry(), &self.read, self.rows())
}
}
/// The four KV stage spans of a read lease for `rows` rows (the arena's `kv_k_q`, `kv_v_q`, `kv_k_scale`,
/// `kv_v_scale`), each checked against the layer's working spans. The stage is the same four arena spans for every QSA
/// layer of a chunk, so they are known before the layer's indexer runs.
pub(crate) fn kv_stage_spans_of(
geometry: QsaGeometry,
read: &OriginalDeviceGrRead<'_, '_, '_>,
rows: usize,
) -> Result<[ffi::BufferHandle; 4]> {
let mut spans = Vec::new();
spans.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?;
let runs = crate::serving_context::geometry().stage_runs().map_err(|_| Error::InvalidSize)?;
let runs = geometry.stage_runs().map_err(|_| Error::InvalidSize)?;
for (name, bytes) in [("kv_k_q", runs[0]), ("kv_v_q", runs[1]), ("kv_k_scale", runs[2]), ("kv_v_scale", runs[3])] {
let (h, n) = read.lease().span(PrefillPhase::Common, name)?;
if n != bytes {
@@ -6,6 +6,7 @@ use super::{
OriginalQsaResidentPromptDevice, POSTOPS, QsaNativePacking, QsaPromptIndexWorkspace, RESERVE, Result, SCRATCH,
SELECT, combine, max_blocks, sizes,
};
use leleka_context::geometry::QsaGeometry;
/// The sealed kernels must be the pinned ones.
fn check_sealed() -> Result<()> {
@@ -22,15 +23,15 @@ fn check_sealed() -> Result<()> {
Ok(())
}
/// The index image holds four 4-byte placeholders instead of the canonical image.
fn resident_sizes(capacity: usize) -> [usize; 11] {
let mut sizes = sizes();
fn resident_sizes(geometry: QsaGeometry, capacity: usize) -> [usize; 11] {
let mut sizes = sizes(geometry);
for n in &mut sizes[..4] {
*n = 4;
}
for i in [4, 5, 6, 7, 8] {
sizes[i] = 4
}
sizes[9] = capacity.min(256) * max_blocks() * 4;
sizes[9] = capacity.min(256) * max_blocks(geometry) * 4;
sizes
}
impl<'ctx> OriginalQsaPromptDevice<'ctx> {
@@ -39,7 +40,7 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
capacity: usize,
packing: QsaNativePacking,
) -> Result<Self> {
let required = OriginalQsaResidentPromptDevice::device_bytes(capacity)?
let required = OriginalQsaResidentPromptDevice::device_bytes(context.serving_geometry(), capacity)?
.checked_add(RESERVE)
.ok_or(Error::BudgetExceeded)?;
check_sealed()?;
@@ -51,7 +52,7 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
{
return Err(Error::BudgetExceeded);
}
let sizes = resident_sizes(capacity);
let sizes = resident_sizes(context.serving_geometry(), capacity);
let mut owner = Self::unloaded(context, capacity, packing, sizes);
if let Err(e) = owner.init_resident(sizes) {
let _ = owner.close();
@@ -11,6 +11,7 @@ use super::{
};
use crate::ple_batch_ffi::LinearLaunch;
use crate::qsa_prompt_attention::OriginalQsaAttendedKv;
use leleka_context::geometry::QsaGeometry;
impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>
OriginalQsaResidentSelection<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>
@@ -172,10 +173,10 @@ impl<'ctx> Context<'ctx> {
}
}
impl<'ctx> OriginalQsaResidentPromptDevice<'ctx> {
pub fn device_bytes(capacity: usize) -> Result<usize> {
OriginalQsaPromptDevice::device_bytes(capacity)?
pub fn device_bytes(geometry: QsaGeometry, capacity: usize) -> Result<usize> {
OriginalQsaPromptDevice::device_bytes(geometry, capacity)?
.checked_sub({
let z = sizes();
let z = sizes(geometry);
z[0] + z[1] + z[2] + z[3]
})
.and_then(|n| n.checked_add(16))
@@ -6,6 +6,7 @@ use super::{
QsaIndexPrior, QsaPromptIndexWorkspace, QsaPromptSelection, RESERVE, Result, SELECT, SelectRequest, encode, ffi,
max_blocks, sizes,
};
use leleka_context::geometry::QsaGeometry;
impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
pub(super) fn new(context: &'ctx Context<'ctx>) -> Result<Self> {
@@ -15,7 +16,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
if !(1..=8192).contains(&capacity) {
return Err(Error::InvalidQwenShape);
}
let sizes = capacity_sizes(capacity)?;
let sizes = capacity_sizes(context.serving_geometry(), capacity)?;
let output_bytes = capacity * (512 * 2 + 6144 + CAP + 4) * 4;
check_assets_sealed()?;
if context.is_poisoned() {
@@ -55,11 +56,11 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
}
Ok(())
}
pub fn prompt_device_bytes(capacity: usize) -> Result<usize> {
pub fn prompt_device_bytes(geometry: QsaGeometry, capacity: usize) -> Result<usize> {
if !(1..=8192).contains(&capacity) {
return Err(Error::InvalidQwenShape);
}
let s = sizes();
let s = sizes(geometry);
Ok(s[0]
+ s[1]
+ s[2]
@@ -67,7 +68,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
+ 8
+ 64
+ capacity * (128 + 12288 + 512) * 4
+ capacity.min(256) * max_blocks() * 4)
+ capacity.min(256) * max_blocks(geometry) * 4)
}
pub fn prompt_output_bytes(capacity: usize) -> Result<usize> {
if !(1..=8192).contains(&capacity) {
@@ -170,12 +171,12 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
}
/// Buffer sizes for a workspace of `capacity` rows.
fn capacity_sizes(capacity: usize) -> Result<[usize; 11]> {
let mut sizes = sizes();
fn capacity_sizes(geometry: QsaGeometry, capacity: usize) -> Result<[usize; 11]> {
let mut sizes = sizes(geometry);
for i in [4, 7, 8] {
sizes[i] = (sizes[i] / 64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?;
}
sizes[9] = capacity.min(256) * max_blocks() * 4;
sizes[9] = capacity.min(256) * max_blocks(geometry) * 4;
Ok(sizes)
}
@@ -5,9 +5,10 @@ use super::{
CHECKPOINT_BYTES, Context, DeviceBuffer, Error, OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex, POOLED,
Result, Saved, sizes,
};
use leleka_context::geometry::QsaGeometry;
pub(super) fn image_bytes() -> usize {
sizes()[0] + 1536 + 512 + 4
pub(super) fn image_bytes(geometry: QsaGeometry) -> usize {
sizes(geometry)[0] + 1536 + 512 + 4
}
impl Drop for Saved<'_> {
fn drop(&mut self) {
@@ -44,7 +45,7 @@ impl OriginalQsaIndexCheckpoint<'_> {
if self.0.bytes.context.is_poisoned() {
return Err(Error::ContextPoisoned);
}
if self.0.end > crate::serving_context::geometry().cells()
if self.0.end > context.serving_geometry().cells()
|| self.0.end > self.0.coverage.end.get()
|| self.0.bytes.len() != CHECKPOINT_BYTES
{
@@ -6,13 +6,14 @@ use super::{
OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex, RESERVE, Rc, RefCell, Result, Saved, Transfer, combine, ffi,
image_bytes, sizes,
};
use leleka_context::geometry::QsaGeometry;
impl<'ctx> OriginalQsaResidentIndex<'ctx> {
pub fn device_bytes() -> usize {
image_bytes()
pub fn device_bytes(geometry: QsaGeometry) -> usize {
image_bytes(geometry)
}
pub(super) fn new(context: &'ctx Context<'ctx>) -> Result<Self> {
let n = image_bytes().checked_add(RESERVE).ok_or(Error::BudgetExceeded)?;
let n = image_bytes(context.serving_geometry()).checked_add(RESERVE).ok_or(Error::BudgetExceeded)?;
if context.is_poisoned() {
return Err(Error::ContextPoisoned);
}
@@ -48,7 +49,7 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> {
// One-time bounded initialization, never a whole host index image. Each
// upload owns its actual staging until completion; no 33MiB host allocation.
let zero = [0u8; 65536];
for (i, n) in [sizes()[0], 1536, 512, 4].into_iter().enumerate() {
for (i, n) in [sizes(context.serving_geometry())[0], 1536, 512, 4].into_iter().enumerate() {
self.image[i] = Some(context.allocate(n)?);
let b = self.image[i].as_mut().ok_or(Error::ContextPoisoned)?;
for offset in (0..n).step_by(zero.len()) {
@@ -80,7 +81,7 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> {
if self.is_failed() || self.copy.is_none() {
return Err(Error::ContextPoisoned);
}
for (i, n) in [sizes()[0], 1536, 512, 4].into_iter().enumerate() {
for (i, n) in [sizes(self.context.serving_geometry())[0], 1536, 512, 4].into_iter().enumerate() {
let b = self.image[i].as_ref().ok_or(Error::ContextPoisoned)?;
if !std::ptr::eq(b.context, self.context) || b.len() != n {
return Err(Error::InvalidQwenShape);
@@ -94,7 +95,7 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> {
if !Rc::ptr_eq(&self.origin, &s.0.origin)
|| self.epoch != s.0.epoch
|| s.0.end > s.0.coverage.end.get()
|| s.0.end > crate::serving_context::geometry().cells()
|| s.0.end > self.context.serving_geometry().cells()
|| !std::ptr::eq(self.context, s.0.bytes.context)
|| s.0.bytes.len() != CHECKPOINT_BYTES
{
@@ -62,7 +62,7 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> {
if !std::ptr::eq(self.context, w.context) {
return Err(Error::ContextMismatch);
}
let image_sizes = [sizes()[0], 1536, 512, 4];
let image_sizes = [sizes(self.context.serving_geometry())[0], 1536, 512, 4];
let sizes = std::array::from_fn(|i| w.sizes[i]);
for i in 0..4 {
std::mem::swap(&mut self.image[i], &mut w.buffers[i]);
@@ -267,7 +267,7 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> {
if self.in_flight {
return Err(Error::InvalidQwenShape);
}
if tail.len() != CHECKPOINT_BYTES || end > crate::serving_context::geometry().cells() {
if tail.len() != CHECKPOINT_BYTES || end > self.context.serving_geometry().cells() {
return Err(Error::InvalidQwenShape);
}
for (first, bytes) in spans {
@@ -101,7 +101,7 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
let end = indices[0].next_position();
check_aligned(context, &indices, &mapped, end)?;
check_gamma(context, &gamma, &indices)?;
rope.validate(context, crate::serving_context::geometry().cells())?;
rope.validate(context, context.serving_geometry().cells())?;
check_rope_clear(&rope, &indices)?;
Ok(Rc::new(Self {
context,
@@ -109,7 +109,7 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
.rope
.positions
.as_ref()
.map(|b| whole(self.context, b, crate::serving_context::geometry().cells() * 12))
.map(|b| whole(self.context, b, self.context.serving_geometry().cells() * 12))
.transpose()?
.unwrap_or(0))
}
@@ -26,7 +26,7 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
.rope
.positions
.as_ref()
.map(|b| whole(self.context, b, crate::serving_context::geometry().cells() * 12))
.map(|b| whole(self.context, b, self.context.serving_geometry().cells() * 12))
.transpose()?
.unwrap_or(0);
Ok(Some(IndexImage { tail, dead, pooled, block_pos, gamma, positions, rope: index_rope(&self.rope) }))
@@ -2,6 +2,7 @@
//! function; the submission and the checks stay in `qsa_prompt_index_workspace.rs`.
use super::{A, Arguments, CAP, Error, Launch, QsaPromptIndexWorkspace, Result, ffi, max_blocks};
use leleka_cuda_model::serving_context::ServingContext;
/// A launch of `qsa_late.cu`: (position in `commands` it runs before, grid, entry, block, arguments).
pub(super) type LateLaunch = (usize, u32, usize, u32, crate::ple_batch_ffi::KernelArguments);
@@ -56,6 +57,8 @@ pub(super) struct ArenaPlan {
pub(super) commands: Vec<(Launch, Arguments)>,
pub(super) late: Vec<LateLaunch>,
pushed: usize,
/// The serving context of the Context the program is planned for (launch geometry and RoPE constants).
serving: ServingContext,
}
/// One 256-row tile of the score selection.
@@ -70,13 +73,13 @@ struct Tile {
}
impl ArenaPlan {
pub(super) fn new(n: usize) -> Result<Self> {
pub(super) fn new(n: usize, serving: ServingContext) -> Result<Self> {
let mut commands = Vec::new();
commands.try_reserve_exact(32 + 4 * n.div_ceil(256)).map_err(|_| Error::HostAllocation)?;
Ok(Self { commands, late: Vec::new(), pushed: 0 })
Ok(Self { commands, late: Vec::new(), pushed: 0, serving })
}
fn push(&mut self, shape: Launch, args: Vec<A>) -> Result<()> {
self.commands.push((shape, Arguments::for_launch(shape, args)?));
self.commands.push((shape, Arguments::for_launch(&self.serving, shape, args)?));
self.pushed += 1;
Ok(())
}
@@ -215,7 +218,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
A::Address(io.dead),
A::Address(io.pooled),
A::Address(self.handle(3, 4)?),
A::I32(crate::serving_context::geometry().cells() as i32),
A::I32(plan.serving.geometry.cells() as i32),
A::F32(io.theta),
],
)
@@ -262,7 +265,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
fn plan_tiles(&self, plan: &mut ArenaPlan, io: &ArenaIo, fast_select: bool) -> Result<()> {
let n = io.t as usize;
let tile_rows = if io.decode { 1 } else { n.min(256) };
let scores = self.handle(9, tile_rows * max_blocks() * 4)?;
let scores = self.handle(9, tile_rows * max_blocks(plan.serving.geometry) * 4)?;
for first_row in (0..n).step_by(256) {
let tile = Tile::new(io, scores, first_row)?;
self.plan_scores(plan, io, &tile)?;
@@ -275,7 +278,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
Ok(())
}
fn plan_scores(&self, plan: &mut ArenaPlan, io: &ArenaIo, tile: &Tile) -> Result<()> {
let mb = max_blocks() as i64;
let mb = max_blocks(plan.serving.geometry) as i64;
let (pooled, dead, iq, steps, scores) = (io.pooled, io.dead, tile.iq, tile.steps, tile.scores);
let (pooled, dead, iq, steps, scores) =
(A::Address(pooled), A::Address(dead), A::Address(iq), A::Address(steps), A::Address(scores));
@@ -291,7 +294,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
/// qsa_late.cu: the same flag over the blocks the tile can hold, and the same ids from coalesced reads.
fn plan_late_select(plan: &mut ArenaPlan, io: &ArenaIo, tile: &Tile) {
use crate::ple_batch_ffi::{BatchArg as B, KernelArguments as Args};
let mb = max_blocks() as i64;
let mb = max_blocks(plan.serving.geometry) as i64;
let (scores, steps) = (B::Address(tile.scores), B::Address(tile.steps));
plan.defer(
(tile.count * tile.reach).div_ceil(256) as u32,
@@ -313,10 +316,10 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
plan.defer(tile.ct, topk_entry, topk_block, args);
}
fn plan_scan_select(plan: &mut ArenaPlan, io: &ArenaIo, tile: &Tile) -> Result<()> {
let mb = max_blocks() as i64;
let mb = max_blocks(plan.serving.geometry) as i64;
let (scores, steps) = (A::Address(tile.scores), A::Address(tile.steps));
plan.push(
Launch::ScoreScan((tile.count * max_blocks()) as u32),
Launch::ScoreScan((tile.count * max_blocks(plan.serving.geometry)) as u32),
vec![scores, steps, A::I32(tile.count as i32), A::I64(mb), A::Address(io.status), A::U32(4)],
)?;
let (scores, steps) = (A::Address(tile.scores), A::Address(tile.steps));
@@ -4,6 +4,7 @@
use super::{
A, Arguments, CAP, DeviceBuffer, Error, Launch, NativeBatchWorkspace, QsaPromptIndexWorkspace, Result, combine, ffi,
};
use leleka_cuda_model::serving_context::ServingContext;
/// The device spans one accepted-prefix replay reads and writes.
struct ReplayIo {
@@ -15,6 +16,7 @@ struct ReplayIo {
tail: ffi::BufferHandle,
dead: ffi::BufferHandle,
bp: ffi::BufferHandle,
serving: ServingContext,
}
/// The launches of a replay and the step rows they read.
type ReplayWork<'ctx> = (Vec<(Launch, Arguments)>, DeviceBuffer<'ctx>);
@@ -54,6 +56,7 @@ fn replay_commands(p0: usize, t: usize, io: &ReplayIo) -> Result<Vec<(Launch, Ar
}
fn replay_append(io: &ReplayIo, key: ffi::BufferHandle, pos: ffi::BufferHandle, theta: f32) -> Result<Arguments> {
Arguments::for_launch(
&io.serving,
Launch::DecodeAppend,
vec![
A::Address(key),
@@ -65,7 +68,7 @@ fn replay_append(io: &ReplayIo, key: ffi::BufferHandle, pos: ffi::BufferHandle,
A::Address(io.dead),
A::Address(io.pooled),
A::Address(io.bp),
A::I32(crate::serving_context::geometry().cells() as i32),
A::I32(io.serving.geometry.cells() as i32),
A::F32(theta),
],
)
@@ -90,7 +93,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
let [status, pooled, tail, dead, bp] = self.replay_handles()?;
let step = self.upload_steps(p0, t)?;
let sh = step.handle.ok_or(Error::ContextPoisoned)?;
let io = ReplayIo { raw, gamma, step: sh, status, pooled, tail, dead, bp };
let io = ReplayIo { raw, gamma, step: sh, status, pooled, tail, dead, bp, serving: *self.context.serving() };
let commands = replay_commands(p0, t, &io)?;
let mut flags = [0u8; 64];
self.run_replay(ws, status, (commands, step), &mut flags)?;
@@ -118,8 +121,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
(raw, gamma): (ffi::BufferHandle, ffi::BufferHandle),
ws: &NativeBatchWorkspace<'ctx>,
) -> Result<()> {
if !(1..=8192).contains(&t) || p0.checked_add(t).is_none_or(|x| x > crate::serving_context::geometry().cells())
{
if !(1..=8192).contains(&t) || p0.checked_add(t).is_none_or(|x| x > self.context.serving_geometry().cells()) {
return Err(Error::InvalidQwenShape);
}
ws.validate_context(self.context)?;
@@ -32,7 +32,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
let n = call.t as usize;
let steps = Self::arena_steps(call.p0 as usize, n)?;
let status = self.handle(10, 64)?;
let mut plan = ArenaPlan::new(n)?;
let mut plan = ArenaPlan::new(n, *self.context.serving())?;
let fast_select = !call.decode && crate::qsa_late::usable(self.context);
let (io, decode_positions) = self.arena_io(call, status)?;
self.plan_arena(&mut plan, &io, fast_select)?;
@@ -5,20 +5,21 @@ use super::{
NativeBatchWorkspace, OriginalQsaIndexBatch, OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex, POSTOPS,
QsaPromptIndexWorkspace, RESERVE, ResidentContinuation, Result, SELECT, combine, encode, ffi, max_blocks, sizes,
};
use leleka_context::geometry::QsaGeometry;
type Outputs<'ctx> = [Option<DeviceBuffer<'ctx>>; 5];
pub struct OriginalQsaResidentScalarIndex<'ctx> {
workspace: QsaPromptIndexWorkspace<'ctx>,
}
/// The index buffers of a scalar index: the image is four 4-byte placeholders.
fn scalar_index_sizes() -> [usize; 11] {
let mut sizes = sizes();
fn scalar_index_sizes(geometry: QsaGeometry) -> [usize; 11] {
let mut sizes = sizes(geometry);
for n in &mut sizes[..4] {
*n = 4;
}
sizes[4] = 608;
sizes[7] = 49152;
sizes[8] = 2048;
sizes[9] = max_blocks() * 4;
sizes[9] = max_blocks(geometry) * 4;
sizes
}
/// The sizes of the five outputs: K, V, the query, the selected ids and the finite flags.
@@ -33,7 +34,7 @@ impl<'ctx> Context<'ctx> {
if [INDEX, SELECT, POSTOPS, DECODE_POSTOPS].iter().any(|x| x.starts_with(b"// UNSEALED")) {
return Err(Error::UnsupportedQwenOperation);
}
let sizes = scalar_index_sizes();
let sizes = scalar_index_sizes(self.serving_geometry());
self.admit_scalar_index(&sizes)?;
let mut workspace = QsaPromptIndexWorkspace {
capacity: 1,
@@ -209,7 +210,7 @@ impl<'ctx> OriginalQsaResidentScalarIndex<'ctx> {
if resident.in_flight
|| resident.unpublished
|| resident.next_position() != p
|| p >= crate::serving_context::geometry().cells()
|| p >= context.serving_geometry().cells()
|| !std::ptr::eq(resident.context, context)
{
return Err(Error::InvalidQwenShape);
@@ -20,6 +20,7 @@ pub(super) fn push_scan(
) -> Result<()> {
push_launch(
commands,
&plan.serving,
Launch::Scan(count as u32),
vec![A::Address(buf), A::I64(count as i64), A::Address(plan.status), A::U32(which)],
)
@@ -45,7 +46,7 @@ fn push_decode_norm_rope(
(heads, dim, _): (u32, i32, i64),
) -> Result<()> {
let rms = vec![A::Address(buf), A::Address(gamma), A::Address(buf), A::I32(dim), A::F32(1e-6)];
push_launch(commands, Launch::DecodeRms(heads), rms)?;
push_launch(commands, &plan.serving, Launch::DecodeRms(heads), rms)?;
let rope = vec![
A::Address(buf),
A::Address(buf),
@@ -54,7 +55,7 @@ fn push_decode_norm_rope(
A::F32(plan.theta),
A::Address(positions),
];
push_launch(commands, Launch::DecodeRope(heads), rope)
push_launch(commands, &plan.serving, Launch::DecodeRope(heads), rope)
}
fn push_prompt_norm_rope(
@@ -64,7 +65,7 @@ fn push_prompt_norm_rope(
(heads, dim, stride): (u32, i32, i64),
) -> Result<()> {
let rms = vec![A::Address(buf), A::Address(gamma), A::I64(dim as i64), A::I64(dim as i64), A::F32(1e-6)];
push_launch(commands, Launch::Rms(plan.t * heads), rms)?;
push_launch(commands, &plan.serving, Launch::Rms(plan.t * heads), rms)?;
let rope = vec![
A::Address(buf),
A::I64(heads as i64),
@@ -73,7 +74,7 @@ fn push_prompt_norm_rope(
A::I64(plan.p0 as i64),
A::F32(plan.theta),
];
push_launch(commands, Launch::Rope(plan.t * heads), rope)
push_launch(commands, &plan.serving, Launch::Rope(plan.t * heads), rope)
}
impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
@@ -113,10 +114,10 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
A::Address(plan.dead),
A::Address(plan.pooled),
A::Address(self.handle(3, 4)?),
A::I32(crate::serving_context::geometry().cells() as i32),
A::I32(plan.serving.geometry.cells() as i32),
A::F32(plan.theta),
];
push_launch(commands, Launch::DecodeAppend, args)
push_launch(commands, &plan.serving, Launch::DecodeAppend, args)
}
fn push_pool_prompt(&self, commands: &mut Commands, plan: &RunPlan, gamma: ffi::BufferHandle) -> Result<()> {
@@ -132,7 +133,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
self.push_pool_blocks(commands, plan, gamma, (first, hi))?;
}
let tail = vec![A::Address(plan.raw), A::I64(t as i64), A::I64(p0 as i64), A::Address(plan.tail)];
push_launch(commands, Launch::Tail, tail)
push_launch(commands, &plan.serving, Launch::Tail, tail)
}
fn push_pool_blocks(
@@ -157,7 +158,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
A::I64(hi as i64),
A::F32(plan.theta),
];
push_launch(commands, Launch::Blocks((hi - first + 1) as u32), args)
push_launch(commands, &plan.serving, Launch::Blocks((hi - first + 1) as u32), args)
}
pub(super) fn push_scores(
@@ -170,7 +171,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
// Original prompt selection reuses one 256-row score tile. Every
// offset is checked against the actual whole producer allocation.
let tile_rows = if plan.decode { 1 } else { n.min(256) };
let scores = self.handle(9, tile_rows * max_blocks() * 4)?;
let scores = self.handle(9, tile_rows * max_blocks(plan.serving.geometry) * 4)?;
for first_row in (0..n).step_by(256) {
let count = (n - first_row).min(256);
let tile = ScoreTile {
@@ -195,7 +196,7 @@ fn push_pool_first(commands: &mut Commands, plan: &RunPlan, gamma: ffi::BufferHa
A::Address(plan.pooled),
A::F32(plan.theta),
];
push_launch(commands, Launch::First, args)
push_launch(commands, &plan.serving, Launch::First, args)
}
fn push_tile_scores(
@@ -211,20 +212,20 @@ fn push_tile_scores(
A::Address(tile.iq),
A::Address(tile.steps),
A::I32(1),
A::I64(max_blocks() as i64),
A::I64(max_blocks(plan.serving.geometry) as i64),
A::Address(scores),
];
return push_launch(commands, Launch::DecodeScores, args);
return push_launch(commands, &plan.serving, Launch::DecodeScores, args);
}
push_tile_tc(commands, plan, scores, tile)?;
let tail = vec![
A::Address(plan.dead),
A::Address(tile.iq),
A::Address(tile.steps),
A::I64(max_blocks() as i64),
A::I64(max_blocks(plan.serving.geometry) as i64),
A::Address(scores),
];
push_launch(commands, Launch::ScoreTail(tile.count as u32), tail)
push_launch(commands, &plan.serving, Launch::ScoreTail(tile.count as u32), tail)
}
fn push_tile_tc(commands: &mut Commands, plan: &RunPlan, scores: ffi::BufferHandle, tile: &ScoreTile) -> Result<()> {
@@ -233,11 +234,11 @@ fn push_tile_tc(commands: &mut Commands, plan: &RunPlan, scores: ffi::BufferHand
A::Address(tile.iq),
A::Address(tile.steps),
A::I64(tile.count as i64),
A::I64(max_blocks() as i64),
A::I64(max_blocks(plan.serving.geometry) as i64),
A::I64(tile.reach as i64),
A::Address(scores),
];
push_launch(commands, Launch::Tc { t: tile.count as u32, reach: tile.reach as u32 }, tc)
push_launch(commands, &plan.serving, Launch::Tc { t: tile.count as u32, reach: tile.reach as u32 }, tc)
}
fn push_tile_select(
@@ -250,17 +251,22 @@ fn push_tile_select(
A::Address(scores),
A::Address(tile.steps),
A::I32(tile.count as i32),
A::I64(max_blocks() as i64),
A::I64(max_blocks(plan.serving.geometry) as i64),
A::Address(plan.status),
A::U32(4),
];
push_launch(commands, Launch::ScoreScan((tile.count * max_blocks()) as u32), scan)?;
push_launch(
commands,
&plan.serving,
Launch::ScoreScan((tile.count * max_blocks(plan.serving.geometry)) as u32),
scan,
)?;
let topk = vec![
A::Address(scores),
A::Address(tile.steps),
A::I64(max_blocks() as i64),
A::I64(max_blocks(plan.serving.geometry) as i64),
A::I64(CAP as i64),
A::Address(tile.ids),
];
push_launch(commands, Launch::Topk(tile.count as u32), topk)
push_launch(commands, &plan.serving, Launch::Topk(tile.count as u32), topk)
}
@@ -6,6 +6,7 @@ use super::{
QsaPromptIndexWorkspace, Result, encode, ffi,
};
use crate::ple_batch_ffi::Blas;
use leleka_cuda_model::serving_context::ServingContext;
pub(super) type Commands = Vec<(Launch, Arguments)>;
@@ -23,6 +24,8 @@ pub(super) struct RunPlan {
pub(super) status: ffi::BufferHandle,
pub(super) positions: Option<ffi::BufferHandle>,
pub(super) theta: f32,
/// The serving context of the Context the run is built for (launch geometry and RoPE constants).
pub(super) serving: ServingContext,
}
#[derive(Default)]
@@ -52,8 +55,13 @@ impl HostStaging {
}
}
pub(super) fn push_launch(commands: &mut Commands, shape: Launch, args: Vec<A>) -> Result<()> {
commands.push((shape, Arguments::for_launch(shape, args)?));
pub(super) fn push_launch(
commands: &mut Commands,
serving: &ServingContext,
shape: Launch,
args: Vec<A>,
) -> Result<()> {
commands.push((shape, Arguments::for_launch(serving, shape, args)?));
Ok(())
}
@@ -181,6 +189,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
status,
positions,
theta,
serving: *self.context.serving(),
})
}
@@ -200,7 +209,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
None => self.handle(7, n * 12288 * 4)?,
};
let split = vec![A::Address(qfull), A::Address(out[2]), A::I64(plan.t as i64)];
push_launch(commands, Launch::Split((n * 6144) as u32), split)?;
push_launch(commands, &plan.serving, Launch::Split((n * 6144) as u32), split)?;
push_norm_rope(commands, plan, (out[2], gamma[0]), (24, 256, 6144))?;
push_scan(commands, plan, out[2], n * 6144, 1)?;
push_norm_rope(commands, plan, (plan.iq, gamma[2]), (4, 128, 512))?;
@@ -218,7 +227,12 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
let n = plan.t as usize;
self.push_pool(commands, plan, gamma, out[4])?;
self.push_scores(commands, plan, out)?;
push_launch(commands, Launch::Round((n * 128) as u32), vec![A::Address(plan.raw), A::I64((n * 128) as i64)])?;
push_launch(
commands,
&plan.serving,
Launch::Round((n * 128) as u32),
vec![A::Address(plan.raw), A::I64((n * 128) as i64)],
)?;
push_scan(commands, plan, plan.raw, n * 128, 5)
}
+2 -3
View File
@@ -3,12 +3,11 @@
use crate::qsa_prompt_attention_ffi::{Arg, Arguments, LaunchGeometry, Module};
use crate::qsa_prompt_host_ffi::MappedAllocation;
use crate::qsa_prompt_resolver::{PoolAddresses, Resolver, SelectedRows};
use crate::serving_context::geometry;
use crate::{Context, DeviceBuffer, Error, NativeBatchWorkspace, Result, combine};
use std::rc::Rc;
// The `pub const` sizes below are the frozen TRAINED-context (262144 cells) values and are kept for the
// 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`).
// public API; every internal use derives the size of the serving context of its Context from
// `Context::serving_geometry()`, which equals these at the default (asserted in `leleka-context`).
pub const QSA_PROMPT_MAX_CELLS: usize = 262144;
/// 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).
@@ -15,7 +15,7 @@ impl<'ctx> QsaPromptKv<'ctx> {
self.validate_snapshot(prior)?;
stage.validate(self.context)?;
workspace.validate_context(self.context)?;
Self::check_rows(prior, t, 8192)?;
self.check_rows(prior, t, 8192)?;
let (kh, vh) = inputs.kv_spans(self.context)?;
self.reject_original_spans((workspace, stage), (kh, vh), t * 512 * 4)?;
let addresses = (kh.qwen_address(), vh.qwen_address(), t);
@@ -6,6 +6,7 @@ use super::{
OriginalQsaMappedJournal, OriginalQsaMappedPrefix, OriginalQsaResidentTransport, QSA_PROMPT_HOST_PAGE_BYTES, Rc,
Result, checked,
};
use leleka_context::geometry::QsaGeometry;
impl<'ctx> OriginalQsaMappedJournal<'ctx> {
pub fn append_resident_decode(
@@ -58,7 +59,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
stage.validate(self.owner.context)?;
workspace.validate_context(self.owner.context)?;
if !(1..=8192).contains(&t)
|| prior.end.checked_add(t).is_none_or(|n| n > crate::serving_context::geometry().cells())
|| prior.end.checked_add(t).is_none_or(|n| n > self.owner.context.serving_geometry().cells())
{
return Err(Error::InvalidQwenShape);
}
@@ -208,7 +209,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
}
let _p = crate::host_profile::span("export.copy");
let m = self.owner.mapped.as_ref().ok_or(Error::ContextPoisoned)?;
let offsets = super::super::offsets()?;
let offsets = super::super::offsets(self.owner.context.serving_geometry())?;
let mut at = 0;
for (i, &page) in super::super::PAGE.iter().enumerate() {
let n = pages * page;
@@ -233,7 +234,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
pub fn export_pages_fast(&self, first_page: usize, pages: usize, out: &mut Vec<u8>) -> Result<()> {
self.check_export(first_page, pages)?;
let m = self.owner.mapped.as_ref().ok_or(Error::ContextPoisoned)?;
let offsets = super::super::offsets()?;
let offsets = super::super::offsets(self.owner.context.serving_geometry())?;
let _p = crate::host_profile::span("export.copy_fast");
crate::exact_fill::fill_exact(out, pages * Self::HOST_PAGE_BYTES, |dst| {
let mut rest = dst;
@@ -252,8 +253,8 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
/// (as `QsaPromptKv::restore` does); with no span nothing is written and nothing is reset. The epoch does not
/// change: prefixes minted before are fenced by the new coverage, exactly as after `rollback`.
/// Every span is whole pages inside the serving context and below the new end.
fn check_import_spans(spans: &[(usize, &[u8])], end: usize) -> Result<()> {
let page_limit = crate::serving_context::geometry().pages();
fn check_import_spans(geometry: QsaGeometry, spans: &[(usize, &[u8])], end: usize) -> Result<()> {
let page_limit = geometry.pages();
for (first, bytes) in spans {
if bytes.is_empty()
|| bytes.len() % Self::HOST_PAGE_BYTES != 0
@@ -267,7 +268,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
}
/// Writes the spans into the host image and resets the resolver; any failure marks the journal failed.
fn write_import_spans(&mut self, w: &mut NativeBatchWorkspace<'ctx>, spans: &[(usize, &[u8])]) -> Result<()> {
let offsets = super::super::offsets()?;
let offsets = super::super::offsets(self.owner.context.serving_geometry())?;
let m = self.owner.mapped.as_mut().ok_or(Error::ContextPoisoned)?;
for (first, bytes) in spans {
let pages = bytes.len() / Self::HOST_PAGE_BYTES;
@@ -297,10 +298,11 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
) -> Result<OriginalQsaMappedPrefix> {
self.validate_context(self.owner.context)?;
w.validate_context(self.owner.context)?;
if end > crate::serving_context::geometry().cells() {
let geometry = self.owner.context.serving_geometry();
if end > geometry.cells() {
return Err(Error::InvalidQwenShape);
}
Self::check_import_spans(spans, end)?;
Self::check_import_spans(geometry, spans, end)?;
// no CPU host write may race a stream use of the old cells
self.owner.context.synchronize().map_err(|e| {
self.failed = true;
@@ -72,7 +72,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
prior_end: usize,
) -> Result<()> {
for (i, h) in stage_spans.iter().enumerate() {
self.owner.reject_original_span(*h, stage_runs()?[i])?;
self.owner.reject_original_span(*h, stage_runs(self.owner.context.serving_geometry())?[i])?;
}
let timed = crate::command_profile::enabled();
let started = std::time::Instant::now();
@@ -14,8 +14,8 @@ impl OriginalQsaMappedPrefix {
pub fn owner_id(&self) -> QsaKvOwnerId {
self.origin.clone()
}
pub fn validate_retained(&self) -> Result<()> {
if self.end > crate::serving_context::geometry().cells() || self.end > self.coverage.end.get() {
pub fn validate_retained(&self, context: &Context<'_>) -> Result<()> {
if self.end > context.serving_geometry().cells() || self.end > self.coverage.end.get() {
return Err(Error::InvalidQwenShape);
}
Ok(())
@@ -112,7 +112,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
|| p.epoch != self.epoch
|| p.end > p.coverage.end.get()
|| p.end > self.end
|| p.end > crate::serving_context::geometry().cells()
|| p.end > self.owner.context.serving_geometry().cells()
{
return Err(Error::InvalidQwenShape);
}
@@ -170,7 +170,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
pub(crate) fn publish_window_rows(&mut self, position: usize, keep: usize) -> Result<()> {
self.validate_context(self.owner.context)?;
let end = position.checked_add(keep).ok_or(Error::InvalidSize)?;
if keep == 0 || self.end != position || end > crate::serving_context::geometry().cells() {
if keep == 0 || self.end != position || end > self.owner.context.serving_geometry().cells() {
return Err(Error::InvalidQwenShape);
}
self.end = end;
@@ -214,9 +214,10 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
return Ok(());
}
self.check_prefetch(workspace, stage, prior, read)?;
let stage_spans = crate::qsa_prompt_index::kv_stage_spans_of(read, read.rows())?;
let geometry = self.owner.context.serving_geometry();
let stage_spans = crate::qsa_prompt_index::kv_stage_spans_of(geometry, read, read.rows())?;
for (i, h) in stage_spans.iter().enumerate() {
self.owner.reject_original_span(*h, stage_runs()?[i])?;
self.owner.reject_original_span(*h, stage_runs(geometry)?[i])?;
}
let hp = self.owner.host_addresses()?;
stage.begin_prefix(workspace, hp, stage_spans, prior.end.div_ceil(4))
+11 -10
View File
@@ -3,16 +3,17 @@
use super::{
CompletedQsaKvAppend, Context, DeviceBuffer, Error, Origin, Page, Pools, QSA_PROMPT_HOST_PAGE_BYTES, QsaKvInputs,
QsaKvOwnerId, QsaKvSnapshot, QsaPromptKv, QsaPromptStage, RESERVE, Rc, Result, Snapshot, combine, geometry,
QsaKvOwnerId, QsaKvSnapshot, QsaPromptKv, QsaPromptStage, RESERVE, Rc, Result, Snapshot, combine,
};
use leleka_context::geometry::QsaGeometry;
/// Run offsets inside the mapped allocation for the configured context.
pub(super) fn offsets() -> Result<[usize; 4]> {
geometry().stage_offsets().map_err(|_| Error::InvalidSize)
/// Run offsets inside the mapped allocation for the serving context of `geometry`.
pub(super) fn offsets(geometry: QsaGeometry) -> Result<[usize; 4]> {
geometry.stage_offsets().map_err(|_| Error::InvalidSize)
}
/// Run lengths of the full staging pool for the configured context.
pub(super) fn stage_runs() -> Result<[usize; 4]> {
geometry().stage_runs().map_err(|_| Error::InvalidSize)
/// Run lengths of the full staging pool for the serving context of `geometry`.
pub(super) fn stage_runs(geometry: QsaGeometry) -> Result<[usize; 4]> {
geometry.stage_runs().map_err(|_| Error::InvalidSize)
}
/// The four resident runs of `slots` resident pages (`[16777216, 16777216, 524288, 524288]` at 8192).
pub(super) fn resident_runs(slots: usize) -> Result<[usize; 4]> {
@@ -55,7 +56,7 @@ impl QsaKvSnapshot {
/// Diagnostic comparison of actual encoded logical cells. Completed batch
/// snapshots may retain future backing; it is excluded from causal equality.
pub fn logical_payload_eq(&self, other: &Self) -> bool {
if self.0.end != other.0.end || self.0.end > geometry().cells() {
if self.0.end != other.0.end {
return false;
}
let pages = self.0.end.div_ceil(4);
@@ -109,7 +110,7 @@ impl<'ctx> Pools<'ctx> {
for (i, n) in sizes.into_iter().enumerate() {
self.buffers[i] = Some(c.allocate(n)?);
}
self.table = Some(c.allocate(geometry().page_table_bytes())?);
self.table = Some(c.allocate(c.serving_geometry().page_table_bytes())?);
Ok(())
}
pub(super) fn addresses(&self) -> Result<[u64; 4]> {
@@ -126,7 +127,7 @@ impl<'ctx> Pools<'ctx> {
for (b, n) in self.buffers.iter().zip(sizes) {
checked(c, b.as_ref().ok_or(Error::ContextPoisoned)?, n)?;
}
checked(c, self.table.as_ref().ok_or(Error::ContextPoisoned)?, geometry().page_table_bytes())?;
checked(c, self.table.as_ref().ok_or(Error::ContextPoisoned)?, c.serving_geometry().page_table_bytes())?;
Ok(())
}
pub(super) fn close(&mut self) -> Result<()> {
@@ -3,8 +3,7 @@
use super::{
Arguments, Context, DeviceBuffer, Error, LaunchGeometry, NativeBatchWorkspace, PAGE, Pools, QsaKvSnapshot,
QsaPromptKv, QsaPromptStage, RESERVE, Rc, Result, Snapshot, admit, bytes_i32, checked, combine, geometry,
stage_runs,
QsaPromptKv, QsaPromptStage, RESERVE, Rc, Result, Snapshot, admit, bytes_i32, checked, combine, stage_runs,
};
impl Drop for QsaPromptKv<'_> {
@@ -14,7 +13,7 @@ impl Drop for QsaPromptKv<'_> {
}
impl<'ctx> QsaPromptStage<'ctx> {
pub(super) fn new(c: &'ctx Context<'ctx>) -> Result<Self> {
admit(c, geometry().stage_bytes().map_err(|_| Error::BudgetExceeded)?)?;
admit(c, c.serving_geometry().stage_bytes().map_err(|_| Error::BudgetExceeded)?)?;
let ptx = include_bytes!("../qsa_prompt_kv.ptx");
let entries = &[c"leleka_qsa_kv_guard", c"leleka_qsa_kv_append", c"leleka_qsa_kv_scale_guard"];
let module = crate::qsa_prompt_attention_ffi::load_in_context(c, ptx, entries)?;
@@ -34,13 +33,13 @@ impl<'ctx> QsaPromptStage<'ctx> {
/// The pools, the status word and the identity page table; the reserve of device memory must stay free.
fn allocate_all(&mut self) -> Result<()> {
let c = self.context;
self.pools.allocate(c, stage_runs()?)?;
self.pools.allocate(c, stage_runs(c.serving_geometry())?)?;
self.status = Some(c.allocate(4)?);
self.pools
.table
.as_mut()
.ok_or(Error::ContextPoisoned)?
.copy_from(&bytes_i32((0..geometry().pages()).map(|x| x as i32))?)?;
.copy_from(&bytes_i32((0..c.serving_geometry().pages()).map(|x| x as i32))?)?;
if c.memory_info()?.0 < RESERVE {
return Err(Error::BudgetExceeded);
}
@@ -59,7 +58,7 @@ impl<'ctx> QsaPromptStage<'ctx> {
if self.is_failed() || self.module.is_none() {
return Err(Error::ContextPoisoned);
}
self.pools.validate(c, stage_runs()?)?;
self.pools.validate(c, stage_runs(c.serving_geometry())?)?;
checked(c, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?;
Ok(())
}
@@ -78,8 +77,8 @@ impl<'ctx> QsaPromptStage<'ctx> {
self.validate(self.context)?;
owner.validate_context(self.context)?;
owner.validate_snapshot(s)?;
if s.0.end > geometry().cells() || s.0.pages.len() < s.0.end.div_ceil(4) || s.0.pages.len() > geometry().pages()
{
let geometry = self.context.serving_geometry();
if s.0.end > geometry.cells() || s.0.pages.len() < s.0.end.div_ceil(4) || s.0.pages.len() > geometry.pages() {
return Err(Error::InvalidQwenShape);
}
Ok(())
@@ -4,6 +4,7 @@ use super::{
Arguments, Context, DeviceBuffer, Error, LaunchGeometry, Module, NativeBatchWorkspace, RESERVE, Result, admit,
bytes_i32, checked, combine,
};
use leleka_context::geometry::QsaGeometry;
pub struct OriginalQsaResidentTransport<'ctx> {
context: &'ctx Context<'ctx>,
table: Option<DeviceBuffer<'ctx>>,
@@ -19,11 +20,11 @@ impl<'ctx> Context<'ctx> {
}
}
impl<'ctx> OriginalQsaResidentTransport<'ctx> {
pub fn device_bytes() -> usize {
crate::serving_context::geometry().page_table_bytes() + 4
pub fn device_bytes(geometry: QsaGeometry) -> usize {
geometry.page_table_bytes() + 4
}
fn new(context: &'ctx Context<'ctx>) -> Result<Self> {
admit(context, Self::device_bytes())?;
admit(context, Self::device_bytes(context.serving_geometry()))?;
let mut s =
Self { context, table: None, status: None, module: None, transfer: None, failed: false, prefix: None };
if let Err(e) = s.init() {
@@ -57,8 +58,9 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> {
Ok(())
}
fn init_table(&mut self) -> Result<()> {
let mut table = self.context.allocate(crate::serving_context::geometry().page_table_bytes())?;
table.copy_from(&bytes_i32((0..crate::serving_context::geometry().pages()).map(|p| p as i32))?)?;
let geometry = self.context.serving_geometry();
let mut table = self.context.allocate(geometry.page_table_bytes())?;
table.copy_from(&bytes_i32((0..geometry.pages()).map(|p| p as i32))?)?;
self.table = Some(table);
self.status = Some(self.context.allocate(4)?);
Ok(())
@@ -76,11 +78,7 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> {
if self.is_failed() || self.module.is_none() {
return Err(Error::ContextPoisoned);
}
checked(
c,
self.table.as_ref().ok_or(Error::ContextPoisoned)?,
crate::serving_context::geometry().page_table_bytes(),
)?;
checked(c, self.table.as_ref().ok_or(Error::ContextPoisoned)?, c.serving_geometry().page_table_bytes())?;
checked(c, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?;
Ok(())
}
@@ -88,7 +86,7 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> {
checked(
self.context,
self.table.as_ref().ok_or(Error::ContextPoisoned)?,
crate::serving_context::geometry().page_table_bytes(),
self.context.serving_geometry().page_table_bytes(),
)
}
pub(crate) fn status(&mut self) -> Result<&mut DeviceBuffer<'ctx>> {
@@ -186,7 +184,7 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> {
pages: usize,
) -> Result<()> {
self.validate(self.context)?;
if pages > crate::serving_context::geometry().pages() {
if pages > self.context.serving_geometry().pages() {
return Err(Error::InvalidQwenShape);
}
self.cancel_pending()?;
@@ -226,7 +224,7 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> {
pages: usize,
) -> Result<()> {
self.validate(self.context)?;
if pages > crate::serving_context::geometry().pages() {
if pages > self.context.serving_geometry().pages() {
return Err(Error::InvalidQwenShape);
}
if pages == 0 {
@@ -5,7 +5,7 @@ use super::{
Arg, Arguments, CompletedQsaKvAppend, Context, DeviceBuffer, Error, LaunchGeometry, MappedAllocation,
NativeBatchWorkspace, Origin, PAGE, Page, PoolAddresses, Pools, QsaKvInputs, QsaKvOwnerId, QsaKvSnapshot,
QsaPromptKv, QsaPromptStage, RESERVE, Rc, Resolver, Result, SelectedRows, Snapshot, admit, checked, combine,
geometry, offsets, read_range, resident_runs, stage_runs,
offsets, read_range, resident_runs, stage_runs,
};
/// The stage one bounded append runs on and the snapshot it extends.
@@ -2,7 +2,7 @@
use super::{
Arg, Arguments, CompletedQsaKvAppend, DeviceBuffer, Error, LaunchGeometry, NativeBatchWorkspace, PAGE, Page,
QsaKvSnapshot, QsaPromptKv, QsaPromptStage, Rc, Result, Snapshot, checked, geometry, read_range,
QsaKvSnapshot, QsaPromptKv, QsaPromptStage, Rc, Result, Snapshot, checked, read_range,
};
type Completed = Vec<Vec<Vec<u8>>>;
@@ -83,8 +83,9 @@ fn install_pages(pages: &mut Vec<Rc<Page>>, completed: Completed, first: usize,
impl<'ctx> QsaPromptKv<'ctx> {
/// 1..=limit rows, ending within the context's cell count.
pub(in crate::qsa_prompt_kv) fn check_rows(prior: &QsaKvSnapshot, t: usize, limit: usize) -> Result<()> {
if !(1..=limit).contains(&t) || prior.0.end.checked_add(t).is_none_or(|n| n > geometry().cells()) {
pub(in crate::qsa_prompt_kv) fn check_rows(&self, prior: &QsaKvSnapshot, t: usize, limit: usize) -> Result<()> {
let cells = self.context.serving_geometry().cells();
if !(1..=limit).contains(&t) || prior.0.end.checked_add(t).is_none_or(|n| n > cells) {
return Err(Error::InvalidQwenShape);
}
Ok(())
@@ -98,7 +99,7 @@ impl<'ctx> QsaPromptKv<'ctx> {
(keys, values, t): (&DeviceBuffer<'_>, &DeviceBuffer<'_>, usize),
limit: usize,
) -> Result<(u64, u64)> {
Self::check_rows(prior, t, limit)?;
self.check_rows(prior, t, limit)?;
let k = checked(self.context, keys, t * 512 * 4)?;
let v = checked(self.context, values, t * 512 * 4)?;
let (kh, vh) = (keys.handle.ok_or(Error::ContextPoisoned)?, values.handle.ok_or(Error::ContextPoisoned)?);
@@ -4,16 +4,18 @@
use super::{
CompletedQsaKvAppend, Context, DeviceBuffer, Error, MappedAllocation, NativeBatchWorkspace, Origin, PAGE,
PoolAddresses, Pools, QsaKvInputs, QsaKvOwnerId, QsaKvSnapshot, QsaPromptKv, QsaPromptStage, RESERVE, Rc, Resolver,
Result, SelectedRows, Snapshot, StagedAppend, admit, checked, combine, geometry, offsets, resident_runs,
stage_runs,
Result, SelectedRows, Snapshot, StagedAppend, admit, checked, combine, offsets, resident_runs, stage_runs,
};
use leleka_context::geometry::QsaGeometry;
impl<'ctx> QsaPromptKv<'ctx> {
pub(in super::super) fn new(c: &'ctx Context<'ctx>) -> Result<Self> {
let slots = crate::serving_context::kv_resident_pages()?;
let slots = c.kv_resident_pages()?;
admit(
c,
geometry().resident_bytes_with(slots, Resolver::map_bytes(slots)?).map_err(|_| Error::BudgetExceeded)?,
c.serving_geometry()
.resident_bytes_with(slots, Resolver::map_bytes(slots)?)
.map_err(|_| Error::BudgetExceeded)?,
)?;
let mut o = Self {
context: c,
@@ -36,7 +38,7 @@ impl<'ctx> QsaPromptKv<'ctx> {
fn init_resources(&mut self, slots: usize) -> Result<()> {
let c = self.context;
self.resolver = Some(Resolver::new(c, slots)?);
check_host_memory()?;
check_host_memory(c.serving_geometry())?;
self.map_host()?;
self.pools.allocate(c, resident_runs(slots)?)?;
if c.memory_info()?.0 < RESERVE {
@@ -48,7 +50,7 @@ impl<'ctx> QsaPromptKv<'ctx> {
fn map_host(&mut self) -> Result<()> {
let c = self.context;
let g = c.enter()?;
let mapped = MappedAllocation::new();
let mapped = MappedAllocation::new(c.serving_geometry());
let pop = g.finish();
match mapped {
Ok(m) => {
@@ -106,10 +108,11 @@ impl<'ctx> QsaPromptKv<'ctx> {
}
pub fn validate_snapshot(&self, s: &QsaKvSnapshot) -> Result<()> {
self.validate()?;
let geometry = self.context.serving_geometry();
if !Rc::ptr_eq(&s.0.origin, &self.origin)
|| s.0.end > geometry().cells()
|| s.0.end > geometry.cells()
|| s.0.pages.len() < s.0.end.div_ceil(4)
|| s.0.pages.len() > geometry().pages()
|| s.0.pages.len() > geometry.pages()
{
return Err(Error::InvalidQwenShape);
}
@@ -124,7 +127,8 @@ impl<'ctx> QsaPromptKv<'ctx> {
}
pub(in super::super) fn host_addresses(&self) -> Result<[u64; 4]> {
let m = self.mapped.as_ref().ok_or(Error::ContextPoisoned)?;
let (offsets, runs) = (offsets()?, stage_runs()?);
let geometry = self.context.serving_geometry();
let (offsets, runs) = (offsets(geometry)?, stage_runs(geometry)?);
Ok([
m.address(offsets[0], runs[0])?,
m.address(offsets[1], runs[1])?,
@@ -135,7 +139,7 @@ impl<'ctx> QsaPromptKv<'ctx> {
/// Writes the pages of `s` that `previous` (the snapshot last written) does not already hold into the mapped host.
fn write_pages(&mut self, previous: Option<&Rc<Snapshot>>, s: &QsaKvSnapshot) -> Result<()> {
let m = self.mapped.as_mut().ok_or(Error::ContextPoisoned)?;
let offsets = offsets()?;
let offsets = offsets(self.context.serving_geometry())?;
for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() {
if previous.is_some_and(|old| {
Rc::ptr_eq(&old.origin, &s.0.origin)
@@ -240,7 +244,7 @@ impl<'ctx> QsaPromptKv<'ctx> {
}
/// The mapped host area plus 8 GiB of headroom must fit the available system memory.
fn check_host_memory() -> Result<()> {
fn check_host_memory(geometry: QsaGeometry) -> Result<()> {
#[cfg(windows)]
let available = libc::physical_memory()
.and_then(|(_, available)| usize::try_from(available).ok())
@@ -253,7 +257,7 @@ fn check_host_memory() -> Result<()> {
.find_map(|line| line.strip_prefix("MemAvailable:")?.split_whitespace().next()?.parse::<usize>().ok())
.and_then(|n| n.checked_mul(1024))
.ok_or(Error::HostAllocation)?;
let mapped_host = geometry().mapped_host_bytes().map_err(|_| Error::HostAllocation)?;
let mapped_host = geometry.mapped_host_bytes().map_err(|_| Error::HostAllocation)?;
if available < mapped_host + 8 * 1024 * 1024 * 1024 {
return Err(Error::HostAllocation);
}
@@ -188,7 +188,7 @@ impl<'ctx> Resolver<'ctx> {
}
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();
let pages = self.context.serving_geometry().pages();
values.push(Arg::I64(pages as i64));
values.push(Arg::I64(self.n_slots as i64));
let a = Arguments::new(values)?;
@@ -58,7 +58,7 @@ impl Context<'_> {
if matches!(
operation,
Operation::QsaRopeQ | Operation::QsaRopeK | Operation::QsaRopeIndexQ | Operation::QsaIndexAppend
) && crate::serving_context::serving_context().rope_is_scaled()
) && self.serving().rope_is_scaled()
{
return Err(Error::UnsupportedQwenOperation);
}
+1 -1
View File
@@ -63,7 +63,7 @@ pub use leleka_cuda_model::original_mtp_loader::{
};
pub use leleka_cuda_model::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,
configure_serving_context, serving_context,
};
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))]
+8 -32
View File
@@ -67,44 +67,20 @@ pub fn serving_context() -> ServingContext {
SERVING.get().copied().unwrap_or_else(ServingContext::trained)
}
/// The geometry every context-linear size is derived from.
#[inline]
pub 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"))
impl ServingContext {
/// Resident pages (VRAM slots) a streamed QSA owner allocates for a window of `cells` (`--kv-resident N`, the
/// Original's `qsa_set_kv_resident`). `0` keeps the whole context resident; a positive count is raised to
/// `qsa_kv_resident_min()` (20480) and rounded up to whole pages.
pub fn resident_pages_for(&self, cells: usize) -> Result<usize> {
self.geometry.resident_pages_for(cells).map_err(|_| Error::InvalidDriverValue("resident KV window"))
}
}
/// The configured resident KV window in cells (the default 32768 when none was configured).
#[inline]
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 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::*;
@@ -120,8 +96,8 @@ mod tests {
#[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());
assert!(ServingContext::trained().geometry.resident_pages_for(KV_RESIDENT_DEFAULT_CELLS) == Ok(8192));
assert!(ServingContext::trained().resident_pages_for(MAX_CONTEXT_CELLS + 4).is_err());
}
/// Wherever the Original streams a layer (`kv_plan` mode 1, golden-tested in `leleka-experimental-ref`)
@@ -6,6 +6,7 @@ use super::{
BindingIdentity, BindingSeal, BoundLayer, BoundLayerKind, InputBindingError, InputConstants, InputResult, PLE_ROWS,
Qwen4ExpArtifact, Rc, fmt,
};
use crate::qwen_forward::contract::Dimension;
impl fmt::Display for InputBindingError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
@@ -24,6 +25,12 @@ impl BindingIdentity {
pub(crate) fn bound_cells(&self) -> u64 {
self.0.serving_cells
}
/// The `Position` dimension of the serving context the model was bound under: every `Position` built for this
/// binding shares it.
pub(crate) fn position_dimension(&self) -> Dimension {
// The cell count was validated when the binding was made (positive, at most the charter ceiling).
Dimension::new(self.0.serving_cells).expect("serving cells are a validated positive i32")
}
}
impl BoundLayer {
pub(crate) fn index(&self) -> u32 {
@@ -183,6 +183,10 @@ impl ModelBinding {
pub(crate) fn identity(&self) -> BindingIdentity {
self.identity.clone()
}
/// The `Position` dimension of the serving context this model was bound under.
pub(crate) fn position_dimension(&self) -> crate::qwen_forward::contract::Dimension {
self.identity.position_dimension()
}
pub(crate) fn input_constants(&self) -> &InputConstants {
&self.constants
}
@@ -92,10 +92,11 @@ pub(crate) fn serving_cells() -> u64 {
leleka_cuda_driver::serving_context().geometry.cells() as u64
}
/// The `Position` dimension of the current serving context; every `Position` of a run shares it.
pub(crate) fn position_dimension() -> Dimension {
// The driver validated the cell count (positive, at most the charter ceiling) when it was configured.
Dimension::new(serving_cells()).expect("serving cells are a validated positive i32")
/// The `Position` dimension of the trained serving context (262144 cells), for tests that build positions without
/// a model binding. Production positions take their dimension from the binding they belong to.
#[cfg(test)]
pub(crate) fn trained_dimension() -> Dimension {
Dimension::new(262_144).expect("262144 is a positive i32")
}
// Retain the checked domain bound in each ID: equal numeric IDs from different
@@ -27,7 +27,7 @@ struct Ids {
impl Ids {
fn new() -> Self {
let vocab = Dimension::new(248320).expect("vocabulary refused");
let bounds = crate::qwen_forward::contract::position_dimension();
let bounds = crate::qwen_forward::contract::trained_dimension();
let fixed = |n| TokenId::new(n, vocab).expect("fixed token refused");
let ids: Vec<_> = [0, 1, 0, 1].into_iter().map(fixed).collect();
let next = TokenId::new(0, vocab).expect("known next refused");
@@ -39,7 +39,7 @@ pub(in crate::qwen_forward) fn check_mmq_on_loaded(owners: LoadedTargetOwners<'_
}
pub(super) fn pos(n: u64) -> Position {
Position::new(n, crate::qwen_forward::contract::position_dimension()).unwrap()
Position::new(n, crate::qwen_forward::contract::trained_dimension()).unwrap()
}
/// The loaded model, caches and fixed four-token chunk that every phase of the observation shares.
@@ -119,7 +119,7 @@ impl<'a, 'driver, 'k, 'o, 'p, 'd> Proof<'a, 'driver, 'k, 'o, 'p, 'd> {
devices: ProofDevices<'a, 'o, 'p, 'k, 'driver, 'd>,
) -> Result<Self> {
let vocab = Dimension::new(248320)?;
let bounds = crate::qwen_forward::contract::position_dimension();
let bounds = binding.position_dimension();
let ids = tokens(4, vocab)?;
let (next, follow) = (TokenId::new(0, vocab)?, TokenId::new(1, vocab)?);
if !session.test_reset_replay_snapshot(binding)?.has_prefix(0, [-1, -1]) {
@@ -139,7 +139,7 @@ fn pinned_artifact_refuses_missing_output_before_layers_without_state_commit() {
let mut session = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context));
let token = TokenId::new(0, Dimension::new(248_320).unwrap()).unwrap();
let position = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap();
let position = Position::new(0, crate::qwen_forward::contract::trained_dimension()).unwrap();
assert_eq!(QwenForward::step(&binding, token, position, &mut session), Err(Error::Unsupported(Stage::Output)));
let state_probe = pinned::probe_fresh_state(&mut session, &binding, token, position);
@@ -162,7 +162,7 @@ fn pinned_artifact_two_tokens_finish_all_layers_and_commit_state() {
let output = OutputStage::load(&binding, context.as_ref()).expect("output head load failed");
let mut session = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context));
let vocabulary = Dimension::new(248_320).unwrap();
let context_length = crate::qwen_forward::contract::position_dimension();
let context_length = crate::qwen_forward::contract::trained_dimension();
// Synthetic public token IDs, never a captured user request. A finite
// bounded result proves composition only, not independent model parity.
@@ -64,7 +64,7 @@ mod tests {
fn identity() -> TokenLayer {
TokenLayer::new(
TokenId::new(0, Dimension::new(248_320).unwrap()).unwrap(),
Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap(),
Position::new(0, crate::qwen_forward::contract::trained_dimension()).unwrap(),
LayerId::new(0, Dimension::new(48).unwrap()).unwrap(),
)
}
@@ -64,7 +64,7 @@ fn pair_projection<'ctx>(
fn identity(layer: u64, position: u64) -> TokenLayer {
TokenLayer::new(
TokenId::new(0, Dimension::new(248320).unwrap()).unwrap(),
Position::new(position, crate::qwen_forward::contract::position_dimension()).unwrap(),
Position::new(position, crate::qwen_forward::contract::trained_dimension()).unwrap(),
LayerId::new(layer, Dimension::new(48).unwrap()).unwrap(),
)
}
@@ -48,7 +48,7 @@ fn original_projection(ctx: &Context<'_>, weights: &DeviceBuffer<'_>, input: &[f
fn identity(layer: u64, position: u64) -> TokenLayer {
TokenLayer::new(
TokenId::new(0, Dimension::new(248320).unwrap()).unwrap(),
Position::new(position, crate::qwen_forward::contract::position_dimension()).unwrap(),
Position::new(position, crate::qwen_forward::contract::trained_dimension()).unwrap(),
LayerId::new(layer, Dimension::new(48).unwrap()).unwrap(),
)
}
@@ -158,7 +158,7 @@ impl Fixture {
)?;
let position = super::super::super::super::contract::Position::new(
65,
crate::qwen_forward::contract::position_dimension(),
crate::qwen_forward::contract::trained_dimension(),
)?;
canonical.validate(&self.binding, &self.gdn_owner, self.layer, position)?;
counts.differences += difference(canonical.values(), &self.expected.state65)?
@@ -210,7 +210,7 @@ fn foreign_prior<'ctx>(
let mut foreign_prior = None;
let refused = foreign.transact_completion(
id,
Position::new(0, crate::qwen_forward::contract::position_dimension())?,
Position::new(0, crate::qwen_forward::contract::trained_dimension())?,
&binding.identity(),
|txn| {
foreign_prior = Some(txn.gdn_prior(layer)?);
@@ -72,7 +72,7 @@ fn pair<'ctx>(
fn identity(prior: &GdnPrior, seed: usize) -> TokenLayer {
TokenLayer::new(
TokenId::new(seed as u64, Dimension::new(248320).unwrap()).unwrap(),
Position::new(prior.next_position(), crate::qwen_forward::contract::position_dimension()).unwrap(),
Position::new(prior.next_position(), crate::qwen_forward::contract::trained_dimension()).unwrap(),
prior.layer(),
)
}
@@ -136,7 +136,7 @@ impl<'c> Run<'c> {
assert_eq!((self.mirror.hits, self.mirror.misses), (3, 3));
let wrong_identity = TokenLayer::new(
TokenId::new(5, Dimension::new(248320).unwrap()).unwrap(),
Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap(),
Position::new(1, crate::qwen_forward::contract::trained_dimension()).unwrap(),
self.layer,
);
assert_eq!(
@@ -245,7 +245,7 @@ mod tests {
let binding = BindingIdentity::test_identity();
let owner = GdnOwner::new();
let layer = LayerId::new(0, Dimension::new(48).unwrap()).unwrap();
let pos = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap();
let pos = Position::new(0, crate::qwen_forward::contract::trained_dimension()).unwrap();
let identity = TokenLayer::new(TokenId::new(0, Dimension::new(248320).unwrap()).unwrap(), pos, layer);
let prior = GdnPrior::zero(binding.clone(), &owner, layer).unwrap();
assert_prior_bound_to_owner(&prior, &binding, &owner, layer, pos);
@@ -33,7 +33,7 @@ fn identity() -> TokenLayer {
use super::super::contract::{Position, TokenId};
TokenLayer::new(
TokenId::new(0, Dimension::new(248_320).unwrap()).unwrap(),
Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap(),
Position::new(0, crate::qwen_forward::contract::trained_dimension()).unwrap(),
LayerId::new(0, Dimension::new(48).unwrap()).unwrap(),
)
}
@@ -105,7 +105,7 @@ mod tests {
fn validated_ids_cannot_substitute_another_vocabulary_or_context() {
let constants = InputConstants::test_fixture();
let vocabulary = Dimension::new(248320).unwrap();
let context = crate::qwen_forward::contract::position_dimension();
let context = crate::qwen_forward::contract::trained_dimension();
let token = TokenId::new(0, vocabulary).unwrap();
let pos = Position::new(0, context).unwrap();
assert_eq!(validate_ids(&constants, token, pos), Ok(()));
@@ -194,7 +194,7 @@ mod ple_tests {
let binding = BindingIdentity::test_identity();
let owner = PleOwner::new();
let prior = PlePrior::zero(binding.clone(), &owner).unwrap();
let position = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap();
let position = Position::new(0, crate::qwen_forward::contract::trained_dimension()).unwrap();
assert_eq!(prior.validate(&binding, &owner, position), Ok(()));
assert_eq!(prior.validate(&binding, &PleOwner::new(), position), Err(Error::IdentityMismatch));
let token = TokenId::new(0, Dimension::new(248320).unwrap()).unwrap();
@@ -18,7 +18,7 @@ fn token(value: u64) -> TokenId {
}
fn position(value: u64) -> Position {
Position::new(value, crate::qwen_forward::contract::position_dimension()).unwrap()
Position::new(value, crate::qwen_forward::contract::trained_dimension()).unwrap()
}
fn layer(value: u64) -> LayerId {
@@ -59,7 +59,7 @@ impl MtpInput {
previous.frame.validate(binding, session)?;
let position = Position::new(
previous.frame.position.get().checked_add(1).ok_or(Error::Overflow)?,
crate::qwen_forward::contract::position_dimension(),
binding.position_dimension(),
)?;
let mut frame = draft.frame(binding, position, previous.predicted, previous.frame.origin.clone())?;
frame.depth = previous.frame.depth.checked_add(1).ok_or(Error::Overflow)?;
@@ -73,7 +73,7 @@ mod tests {
draft.stage_chunk_bound(
&target,
foreign_anchor,
Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap()
Position::new(0, crate::qwen_forward::contract::trained_dimension()).unwrap()
),
Err(Error::IdentityMismatch)
));
@@ -87,7 +87,7 @@ mod tests {
MtpFrame {
binding: stage.candidate.binding.clone(),
token: TokenId::new(1, Dimension::new(248320).unwrap()).unwrap(),
position: Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap(),
position: Position::new(0, crate::qwen_forward::contract::trained_dimension()).unwrap(),
origin: anchor,
epoch: Rc::clone(&stage.candidate.epoch),
generation: 0,
@@ -124,7 +124,7 @@ mod tests {
let retained = draft.retained.get();
let anchor = target.target_origin().unwrap();
{
let position = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap();
let position = Position::new(0, crate::qwen_forward::contract::trained_dimension()).unwrap();
let mut stage = draft.stage_chunk_bound(&target, anchor.clone(), position).unwrap();
let frame = probe_frame(&stage, anchor);
commit_private_branch(&mut stage, &frame);
@@ -152,7 +152,7 @@ mod tests {
draft.stage_chunk_bound(
&target,
anchor.clone(),
Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap()
Position::new(1, crate::qwen_forward::contract::trained_dimension()).unwrap()
),
Err(Error::IdentityMismatch)
));
@@ -162,7 +162,7 @@ mod tests {
draft.stage_chunk_bound(
&target,
anchor,
Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap()
Position::new(0, crate::qwen_forward::contract::trained_dimension()).unwrap()
),
Err(Error::IdentityMismatch)
));
@@ -209,7 +209,7 @@ mod branch_refusal {
draft.stage_chunk_bound(
&target,
current,
Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap()
Position::new(0, crate::qwen_forward::contract::trained_dimension()).unwrap()
),
Err(Error::IdentityMismatch)
));
@@ -51,7 +51,7 @@ impl MtpSession {
) -> Result<MtpChunkStage<'a>> {
let bound = ValidatedWarmEnd::from_txn(txn, binding.input_constants().bound_cells())?;
let target = txn.original_session()?;
let start = Position::new(txn.start_position(), crate::qwen_forward::contract::position_dimension())?;
let start = Position::new(txn.start_position(), binding.position_dimension())?;
binding
.mtp_weights()
.map_err(super::super::super::binding_error)?
@@ -14,7 +14,7 @@ fn draft() -> (MtpSession, MtpFrame) {
let frame = MtpFrame {
binding: binding.clone(),
token: TokenId::new(1, Dimension::new(248320).unwrap()).unwrap(),
position: Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap(),
position: Position::new(0, crate::qwen_forward::contract::trained_dimension()).unwrap(),
origin: target.target_origin().unwrap(),
epoch: Rc::clone(&epoch),
generation: 0,
@@ -56,7 +56,7 @@ fn arrange_first_seed(extra_prediction: bool) -> SeedRestore {
let seed_residual = Rc::clone(seed.residual.as_ref().unwrap());
if extra_prediction {
let mut next = frame.clone();
next.position = Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap();
next.position = Position::new(1, crate::qwen_forward::contract::trained_dimension()).unwrap();
next.depth = 1;
let tail = pending(&draft, &next);
draft.commit(&next, tail, vec![2.0; 10240].into_boxed_slice()).unwrap();
@@ -237,7 +237,7 @@ fn ring_requires_exact_parent_epoch_and_branch() {
assert!(first.ring_same(&first.clone(), &frame).unwrap());
draft.commit(&frame, first.clone(), vec![0.0; 10240].into_boxed_slice()).unwrap();
let mut next_frame = frame.clone();
next_frame.position = Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap();
next_frame.position = Position::new(1, crate::qwen_forward::contract::trained_dimension()).unwrap();
let next = pending(&draft, &next_frame);
assert!(next.ring_append(&first, &next_frame).unwrap());
let branch = pending(&draft, &next_frame);
@@ -258,7 +258,7 @@ fn ring_restore_requires_reload_for_old_numerical_mirror() {
draft.commit(&frame, first.clone(), vec![0.0; 10240].into_boxed_slice()).unwrap();
let checkpoint = draft.checkpoint().unwrap();
let mut next_frame = frame.clone();
next_frame.position = Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap();
next_frame.position = Position::new(1, crate::qwen_forward::contract::trained_dimension()).unwrap();
let second = pending(&draft, &next_frame);
draft.commit(&next_frame, second, vec![0.0; 10240].into_boxed_slice()).unwrap();
draft.restore(&checkpoint).unwrap();
@@ -10,7 +10,7 @@ use crate::qwen_forward::executor::{StepCaches, StepRequest};
use crate::qwen_forward::mtp_decode::{MtpWindowRequest, WindowOwners};
pub(super) fn position_at(position: u64) -> Position {
Position::new(position, crate::qwen_forward::contract::position_dimension()).unwrap()
Position::new(position, crate::qwen_forward::contract::trained_dimension()).unwrap()
}
/// Ten complete snapshots + transaction peak and draft copies stay below
/// this explicit host cap; production transaction remains exactly512MiB.
@@ -238,7 +238,7 @@ impl MtpDecoder {
let binding = cx.binding;
let position = cx.next_position(st.tokens.len())?;
self.scalar_warm(binding, owners, cancelled, st)?;
let position = Position::new(position, crate::qwen_forward::contract::position_dimension())?;
let position = Position::new(position, binding.position_dimension())?;
let request = StepRequest { binding, token: st.expected, position };
let kar = owners.kar_cache.as_deref_mut();
let caches = StepCaches { kar, moe: Some(&mut *owners.cache), dense: Some(cx.dense_cache) };
@@ -30,7 +30,7 @@ pub(super) struct Weights<'ctx> {
pub(super) moe: MoeWeightCache<'ctx>,
}
/// The refusals that precede any allocation: the config, the process-wide KV window, the context identity, the model
/// The refusals that precede any allocation: the config, the context's KV window, the context identity, the model
/// shape.
pub(super) fn check_open<'ctx>(
binding: &ModelBinding,
@@ -41,7 +41,7 @@ pub(super) fn check_open<'ctx>(
crate::bringup_trace!("DBG[{:.0}s] OriginalServeStack::open begin", dbg_el());
config.validate(binding.input_constants().bound_cells()).map_err(at("config.validate"))?;
// generate.cpp: qsa_set_kv_resident before any QSA state exists (every streamed owner sizes from it)
leleka_cuda_driver::configure_kv_resident(config.kv_resident).map_err(|_| ServeFailure {
context.configure_kv_resident(config.kv_resident).map_err(|_| ServeFailure {
error: Error::InvalidDimension,
detail: Some(format!(
"--kv-resident {}: the process already serves another resident KV window",
@@ -94,7 +94,7 @@ mod tests {
fn identity(pos: u64) -> TokenLayer {
TokenLayer::new(
TokenId::new(7, Dimension::new(248320).unwrap()).unwrap(),
Position::new(pos, crate::qwen_forward::contract::position_dimension()).unwrap(),
Position::new(pos, crate::qwen_forward::contract::trained_dimension()).unwrap(),
layer(),
)
}
@@ -40,7 +40,7 @@ mod tests {
index[512..].fill(p as f32 + 0.5);
let identity = TokenLayer::new(
TokenId::new(0, Dimension::new(1).unwrap()).unwrap(),
Position::new(p, crate::qwen_forward::contract::position_dimension()).unwrap(),
Position::new(p, crate::qwen_forward::contract::trained_dimension()).unwrap(),
prior.layer(),
);
QsaPending::new(prior, identity, &[0; KV * 2], &[0; KV * 2], &index).unwrap().into_prior()
@@ -123,7 +123,7 @@ mod late_cpu {
index[512..].fill(2.0);
let identity = TokenLayer::new(
TokenId::new(0, Dimension::new(1).unwrap()).unwrap(),
Position::new(190003, crate::qwen_forward::contract::position_dimension()).unwrap(),
Position::new(190003, crate::qwen_forward::contract::trained_dimension()).unwrap(),
prior.layer(),
);
let next = QsaPending::new(&prior, identity, &[0; KV * 2], &[0; KV * 2], &index).unwrap().into_prior();
@@ -169,7 +169,7 @@ mod gpu {
index[512..].fill(2.0);
let identity = TokenLayer::new(
TokenId::new(0, Dimension::new(1).unwrap()).unwrap(),
Position::new(p, crate::qwen_forward::contract::position_dimension()).unwrap(),
Position::new(p, crate::qwen_forward::contract::trained_dimension()).unwrap(),
prior.layer(),
);
let next = QsaPending::new(&prior, identity, &[0; KV * 2], &[0; KV * 2], &index).unwrap().into_prior();
@@ -50,7 +50,7 @@ impl ResidentQsaPrior<'_> {
let context = session.mtp_context()?;
self.check_lineage(identity, layer, end)?;
self.0.index.validate_retained(context).map_err(device_error)?;
self.0.kv.validate_retained().map_err(device_error)?;
self.0.kv.validate_retained(context).map_err(device_error)?;
if context.is_poisoned() {
return Err(Error::CudaExecution);
}
@@ -10,7 +10,7 @@ use crate::qwen_forward::contract::{Dimension, TokenId};
fn append(prior: &QsaPrior, word: u16) -> Result<QsaPrior> {
let identity = TokenLayer::new(
TokenId::new(7, Dimension::new(248320)?)?,
Position::new(prior.next_position(), crate::qwen_forward::contract::position_dimension())?,
Position::new(prior.next_position(), crate::qwen_forward::contract::trained_dimension())?,
prior.layer(),
);
let mut index = [0.0; 640];
@@ -187,7 +187,7 @@ mod refusal_tests {
fn fixture<'a>(session: &'a mut QwenSession<'static>) -> QwenChunkTxn<'a, 'static> {
session.layer_count = 48;
let origin = session.target_origin().unwrap();
let position = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap();
let position = Position::new(0, crate::qwen_forward::contract::trained_dimension()).unwrap();
let row = Row { token: token(3), position, predecessors: [-1, -1], input: None, completed: 0 };
let init = PromptInit { origin, rows: vec![row], witnesses: Vec::new() };
let mut txn = QwenChunkTxn::fresh(session, init, (Some(token(4)), 1, false));
@@ -163,7 +163,7 @@ impl GdnChunkStart {
chunk: owner,
prior: prior.clone(),
layer,
first: Position::new(txn.start_position(), crate::qwen_forward::contract::position_dimension())?,
first: Position::new(txn.start_position(), txn.original_session().binding.position_dimension())?,
end: txn.end_position(),
count: txn.len(),
}));
@@ -154,7 +154,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
for witness in &self.witnesses {
self.validate_row(witness)?;
}
let end_position = Position::new(self.end, crate::qwen_forward::contract::position_dimension())?;
let end_position = Position::new(self.end, self.session.binding.position_dimension())?;
self.validate_publish_ple(end_position)?;
for slot in 0..STATE_CAPACITY {
self.validate_gdn_slot(slot, end_position)?;
@@ -200,7 +200,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
self.check_first_layer(residuals)?;
let layer = LayerId::new(0, Dimension::new(48)?)?;
let words = self.first_layer_words(residuals, layer)?;
let end = Position::new(self.end, crate::qwen_forward::contract::position_dimension())?;
let end = Position::new(self.end, self.session.binding.position_dimension())?;
self.validate_first_layer_prior(layer, end)?;
self.micro.test_partial_words = words;
Ok(())
@@ -196,7 +196,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
owner.finish_verification(seal, binding, cache).map(|()| None)
} else {
owner.finish(seal, binding, cache).and_then(|prior| {
let end = Position::new(self.end, crate::qwen_forward::contract::position_dimension())?;
let end = Position::new(self.end, self.session.binding.position_dimension())?;
prior.validate(&self.session.binding, &self.session.gdn_owner, layer, end)?;
Ok(Some(prior))
})
@@ -12,7 +12,7 @@ use super::{
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
impl TestGdnComponentRows {
pub(in crate::qwen_forward) fn new(prior: GdnPrior, binding: BindingIdentity) -> Result<Self> {
let first = Position::new(prior.next_position(), crate::qwen_forward::contract::position_dimension())?;
let first = Position::new(prior.next_position(), crate::qwen_forward::contract::trained_dimension())?;
let end = first.get().checked_add(65).ok_or(Error::Overflow)?;
let start = GdnChunkStart(Rc::new(GdnChunkAnchor {
binding,
@@ -40,7 +40,7 @@ impl TestGdnComponentRows {
TokenId::new(index as u64, Dimension::new(248320)?)?,
Position::new(
self.start.0.first.get().checked_add(index as u64).ok_or(Error::Overflow)?,
crate::qwen_forward::contract::position_dimension(),
crate::qwen_forward::contract::trained_dimension(),
)?,
self.start.0.layer,
),
@@ -211,7 +211,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
/// The replayed prior stands at the end of the first `count` rows.
fn validate_replayed_prior(&self, prior: &GdnPrior, layer: LayerId, count: usize) -> Result<()> {
let end = self.start_position().checked_add(count as u64).ok_or(Error::Overflow)?;
let end = Position::new(end, crate::qwen_forward::contract::position_dimension())?;
let end = Position::new(end, self.session.binding.position_dimension())?;
prior.validate(&self.session.binding, &self.session.gdn_owner, layer, end)
}
/// Replay every GDN layer's device proofs; the other slots stay empty.
@@ -301,10 +301,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
if row.position != position || self.gdn_chunk.is_some() {
return Err(Error::IdentityMismatch);
}
Position::new(
position.get().checked_add(1).ok_or(Error::Overflow)?,
crate::qwen_forward::contract::position_dimension(),
)
Position::new(position.get().checked_add(1).ok_or(Error::Overflow)?, self.session.binding.position_dimension())
}
/// The chunk is the layer-one GDN chunk of this transaction, with the same extent and first row.
fn ple_chunk_extent(&self, start: &GdnChunkAnchor) -> bool {
@@ -364,10 +361,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
return Err(Error::IdentityMismatch);
}
start.prior.validate(&self.session.binding, &self.session.gdn_owner, start.layer, start.first)?;
Position::new(
position.get().checked_add(1).ok_or(Error::Overflow)?,
crate::qwen_forward::contract::position_dimension(),
)
Position::new(position.get().checked_add(1).ok_or(Error::Overflow)?, self.session.binding.position_dimension())
}
pub(in super::super::super) fn record_verification_ple(&mut self, index: usize, position: Position) -> Result<()> {
if self.verification.is_none() {
@@ -126,7 +126,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
}
let end = Position::new(
row.position.get().checked_add(1).ok_or(Error::Overflow)?,
crate::qwen_forward::contract::position_dimension(),
self.session.binding.position_dimension(),
)?;
let state = journal_state(&self.verification, index)?;
self.validate_state_ple(state, end)?;
@@ -73,7 +73,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
if !leased {
return Ok(());
}
let end_position = Position::new(end, crate::qwen_forward::contract::position_dimension())?;
let end_position = Position::new(end, self.session.binding.position_dimension())?;
for slot in 0..STATE_CAPACITY {
if self.session.gdn_layers[slot] {
state.gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))?.validate(
@@ -51,7 +51,7 @@ fn ple_gdn_fixture<'a>(session: &'a mut QwenSession<'static>) -> QwenChunkTxn<'a
session.gdn_layers[1] = true;
let binding = session.binding.clone();
let origin = session.target_origin().unwrap();
let position = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap();
let position = Position::new(0, crate::qwen_forward::contract::trained_dimension()).unwrap();
let input = crate::qwen_forward::input::InputReady::test_fixture(token(3), position, binding);
let row = Row { token: token(3), position, predecessors: [-1, -1], input: Some(Rc::new(input)), completed: 1 };
let init = PromptInit { origin, rows: vec![row], witnesses: Vec::new() };
@@ -81,7 +81,7 @@ fn layer_of(index: u64) -> LayerId {
}
fn row_position() -> Position {
Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap()
Position::new(0, crate::qwen_forward::contract::trained_dimension()).unwrap()
}
/// Stages the next PLE prior of `layer` as the transaction's own and returns it.
@@ -137,7 +137,7 @@ fn break_authority(txn: &mut Txn<'_>, refusal: u32, layer: LayerId, position: Po
use crate::qwen_forward::input::{PleOwner, PlePending};
match refusal {
8 => txn.gdn_chunk.as_mut().unwrap().accepted = 1,
9 => txn.rows[0].position = Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap(),
9 => txn.rows[0].position = Position::new(1, crate::qwen_forward::contract::trained_dimension()).unwrap(),
10 => {
let foreign = PlePrior::zero(txn.session.binding.clone(), &PleOwner::new()).unwrap();
txn.next_ple = Some(
@@ -155,8 +155,7 @@ impl<'session, 'driver> OriginalPromptTxn<'session, 'driver> {
}
let index = self.inputs.len();
let token = self.tokens[index];
let position =
Position::new(self.phase.first + index as u64, crate::qwen_forward::contract::position_dimension())?;
let position = Position::new(self.phase.first + index as u64, self.session.binding.position_dimension())?;
let mut view = self.input_view(position);
let operation = (|| {
let mut step = view.begin(token, position)?;
@@ -156,7 +156,7 @@ impl<'session, 'driver> OriginalPromptTxn<'session, 'driver> {
let PromptPublication { completed, draft_kv, sample } = publication;
self.validate_publish_inputs(binding, completed, draft_kv, sample)?;
let draft_permit = draft.prepare_publication(binding, self, draft_kv.completed())?;
let end = Position::new(self.phase.end, crate::qwen_forward::contract::position_dimension())?;
let end = Position::new(self.phase.end, self.session.binding.position_dimension())?;
let ple = self.next_ple.get_mut().clone();
let gdn = self.next_gdn.get_mut().clone();
let mut qsa = std::mem::replace(self.next_qsa.get_mut(), std::array::from_fn(|_| None));
@@ -21,7 +21,7 @@ impl<'session, 'driver> OriginalPromptTxn<'session, 'driver> {
&self.session.binding,
&self.session.gdn_owner,
layer,
Position::new(self.phase.first, crate::qwen_forward::contract::position_dimension())?,
Position::new(self.phase.first, self.session.binding.position_dimension())?,
)?;
Ok(prior)
}
@@ -48,7 +48,7 @@ impl<'session, 'driver> OriginalPromptTxn<'session, 'driver> {
&self.session.binding,
&self.session.gdn_owner,
layer,
Position::new(self.phase.end, crate::qwen_forward::contract::position_dimension())?,
Position::new(self.phase.end, self.session.binding.position_dimension())?,
)?;
self.next_gdn.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?[layer.get() as usize] = Some(next);
self.gdn_completed.set(self.gdn_completed.get() | (1 << layer.get()));
@@ -59,7 +59,7 @@ impl<'session, 'driver> OriginalPromptTxn<'session, 'driver> {
prior.validate(
&self.session.binding,
&self.session.ple_owner,
Position::new(at, crate::qwen_forward::contract::position_dimension())?,
Position::new(at, self.session.binding.position_dimension())?,
)
}
/// The rolling PLE state at the window start: the session's prior, or the zero state at position 0.
@@ -176,7 +176,7 @@ impl<'driver> QwenSession<'driver> {
if end > limit {
return Err(Error::InvalidPosition);
}
Ok((end, Position::new(end, super::super::contract::position_dimension())?))
Ok((end, Position::new(end, self.binding.position_dimension())?))
}
fn check_qsa(&self, qsa: &[Option<ResidentQsaPrior<'driver>>; STATE_CAPACITY], end: u64) -> Result<()> {
for slot in 0..STATE_CAPACITY {
@@ -270,7 +270,7 @@ impl<'driver> QwenSession<'driver> {
if self.layer_count != 48 || self.state_lag.is_none() {
return Err(Error::IdentityMismatch);
}
let at = Position::new(self.next_position, super::super::contract::position_dimension())?;
let at = Position::new(self.next_position, self.binding.position_dimension())?;
self.check_state(&gdn, &ple, at)?;
self.complete_cuda()?;
self.ple_state = ple;
@@ -13,7 +13,7 @@ fn token(value: u64) -> TokenId {
}
fn position(value: u64) -> Position {
Position::new(value, crate::qwen_forward::contract::position_dimension()).unwrap()
Position::new(value, crate::qwen_forward::contract::trained_dimension()).unwrap()
}
mod gdn_session_commit_advances_all;
-1
View File
@@ -109,7 +109,6 @@ mod tests {
assert_eq!(admit_context_tokens(262_144, 1), Ok(()));
assert_eq!(admit_context_tokens(1, 1), Ok(()));
assert_eq!(crate::qwen_forward::contract::serving_cells(), 262_144);
assert_eq!(crate::qwen_forward::contract::position_dimension().get(), 262_144);
}
#[test]