Merge branch 'main' into claude/speed-vs-strata-08143a
This commit is contained in:
@@ -8,7 +8,7 @@
|
||||
"source": {
|
||||
"dyn-trait:leleka-backend-api": 1,
|
||||
"dyn-trait:leleka-cpu-worker": 4,
|
||||
"dyn-trait:leleka-cuda-driver": 46,
|
||||
"dyn-trait:leleka-cuda-driver": 45,
|
||||
"dyn-trait:leleka-cuda-model": 3,
|
||||
"dyn-trait:leleka-deploy": 17,
|
||||
"dyn-trait:leleka-engine-core": 18,
|
||||
|
||||
@@ -2727,6 +2727,13 @@
|
||||
"not built for sm_86 by design (claude/draft-round): LELEKA_DRAFT_FUSED_COMMIT is opt-in and original_verify_schedule.rs::record_commit fuses only on a compute capability 12 card, so an sm_86 build never loads this module"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "gdn_prefill_tc.ptx",
|
||||
"sm120_path": "crates/cuda-driver/src/gdn_prefill_tc.ptx",
|
||||
"problems": [
|
||||
"not built for sm_86 by design (claude/prefill-gdn-tensor-core): LELEKA_PREFILL_GDN_TC is opt-in and experimental and gdn_prefill_tc.rs::plan refuses every device below compute capability 12, so an sm_86 build never loads this module (the kernels use only sm_80 features and would retarget; the 3080 plan needs its own parity and quality run first)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "original_verify_window_qsa_kv_rows.ptx",
|
||||
"sm120_path": "crates/cuda-driver/src/original_verify_window_qsa_kv_rows.ptx",
|
||||
|
||||
@@ -54,6 +54,15 @@ impl AsyncApi {
|
||||
let _ = stream.0;
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn can_batch(&self) -> bool {
|
||||
false
|
||||
}
|
||||
pub(crate) fn copy_batch(&self, _: &mut crate::refill_batch_copy::BatchCall, _: Stream) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn wait_event(&self, _: Stream, _: Event) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
}
|
||||
#[cfg(not(all(
|
||||
feature = "cuda-driver",
|
||||
|
||||
@@ -33,7 +33,10 @@ pub(crate) struct AsyncApi {
|
||||
unregister: Unregister,
|
||||
stream_wait: Query,
|
||||
zero: Zero,
|
||||
/// `cuMemcpyBatchAsync_v2` and `cuStreamWaitEvent`, resolved optionally (`None`: the per-copy path only).
|
||||
batch: Option<batch_copy::BatchCopyApi>,
|
||||
}
|
||||
mod batch_copy;
|
||||
fn check(operation: &'static str, code: c_int) -> Result<()> {
|
||||
if code == 0 { Ok(()) } else { Err(Error::Driver { operation, code }) }
|
||||
}
|
||||
@@ -70,6 +73,7 @@ impl AsyncApi {
|
||||
unregister: symbol!(library, c"cuMemHostUnregister", Unregister),
|
||||
stream_wait: symbol!(library, c"cuStreamSynchronize", Query),
|
||||
zero: symbol!(library, c"cuMemsetD8_v2", Zero),
|
||||
batch: batch_copy::BatchCopyApi::resolve(&library),
|
||||
_library: library,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
//! The optional batch-copy entry of `AsyncApi` (the lent-slot refill's `LELEKA_REFILL_BATCH`): resolved only when the
|
||||
//! driver exports both symbols; a missing one leaves the per-copy path.
|
||||
use super::*;
|
||||
use crate::refill_batch_copy::BatchCall;
|
||||
|
||||
/// `cuMemcpyBatchAsync_v2` (CUDA 12.8+/13, the form without `failIdx`): dsts, srcs, sizes, count, attrs, attrsIdxs,
|
||||
/// numAttrs, stream. The same prototype as `original_gpu_schedule_ffi::platform::CopyBatch`.
|
||||
type CopyBatch = unsafe extern "C" fn(
|
||||
*mut u64,
|
||||
*mut u64,
|
||||
*mut usize,
|
||||
usize,
|
||||
*mut BatchAttributes,
|
||||
*mut usize,
|
||||
usize,
|
||||
*mut c_void,
|
||||
) -> c_int;
|
||||
/// `cuStreamWaitEvent`: stream, event, flags.
|
||||
type WaitEvent = unsafe extern "C" fn(*mut c_void, *mut c_void, c_uint) -> c_int;
|
||||
|
||||
/// `CUmemcpyAttributes`: srcAccessOrder, srcLocHint {type, id}, dstLocHint {type, id}, flags (24 bytes).
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
struct BatchAttributes {
|
||||
src_access_order: u32,
|
||||
src_loc: [i32; 2],
|
||||
dst_loc: [i32; 2],
|
||||
flags: u32,
|
||||
}
|
||||
const _: () = assert!(std::mem::size_of::<BatchAttributes>() == 24);
|
||||
/// `CU_MEMCPY_SRC_ACCESS_ORDER_STREAM`: the source is read in stream order (the bank stays retained to the fence).
|
||||
const SRC_ACCESS_ORDER_STREAM: u32 = 1;
|
||||
|
||||
pub(crate) struct BatchCopyApi {
|
||||
copy: CopyBatch,
|
||||
wait_event: WaitEvent,
|
||||
}
|
||||
|
||||
impl BatchCopyApi {
|
||||
pub(super) fn resolve(library: &Library) -> Option<Self> {
|
||||
// SAFETY: fixed C names and a live dlopen owner; a null address maps to `None`.
|
||||
let copy = unsafe { libc::dlsym(library.0, c"cuMemcpyBatchAsync_v2".as_ptr()) };
|
||||
// SAFETY: as above.
|
||||
let wait = unsafe { libc::dlsym(library.0, c"cuStreamWaitEvent".as_ptr()) };
|
||||
if copy.is_null() || wait.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: non-null addresses of the named symbols; `CopyBatch` and `WaitEvent` are their exact C signatures.
|
||||
Some(unsafe {
|
||||
Self {
|
||||
copy: std::mem::transmute::<*mut c_void, CopyBatch>(copy),
|
||||
wait_event: std::mem::transmute::<*mut c_void, WaitEvent>(wait),
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncApi {
|
||||
/// Whether the driver exports the batch-copy entry (and `cuStreamWaitEvent`).
|
||||
pub(crate) fn can_batch(&self) -> bool {
|
||||
self.batch.is_some()
|
||||
}
|
||||
/// One `cuMemcpyBatchAsync_v2` of `call` on `stream` (never the legacy default stream: the caller passes a
|
||||
/// created stream). The descriptor arrays are consumed during the call; the sources and destinations must stay
|
||||
/// alive until the stream's fence.
|
||||
pub(crate) fn copy_batch(&self, call: &mut BatchCall, stream: Stream) -> Result<()> {
|
||||
let batch = self.batch.as_ref().ok_or(Error::MissingSymbol("cuMemcpyBatchAsync_v2"))?;
|
||||
let count = call.sizes.len();
|
||||
if count == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
if call.destinations.len() != count || call.sources.len() != count || stream.0 == 0 {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
let mut attributes =
|
||||
BatchAttributes { src_access_order: SRC_ACCESS_ORDER_STREAM, src_loc: [0, 0], dst_loc: [0, 0], flags: 0 };
|
||||
let mut index = 0usize;
|
||||
// SAFETY: the three arrays hold `count` entries each (checked above) and, with `attributes`/`index`, live
|
||||
// across the call; the driver copies the descriptors during it. Every source is a slice of a bank the caller
|
||||
// retains until the stream's fence (srcAccessOrder STREAM); every destination is a validated slot subspan.
|
||||
check("cuMemcpyBatchAsync_v2", unsafe {
|
||||
(batch.copy)(
|
||||
call.destinations.as_mut_ptr(),
|
||||
call.sources.as_mut_ptr(),
|
||||
call.sizes.as_mut_ptr(),
|
||||
count,
|
||||
&mut attributes,
|
||||
&mut index,
|
||||
1,
|
||||
stream.0 as *mut c_void,
|
||||
)
|
||||
})
|
||||
}
|
||||
/// `cuStreamWaitEvent(stream, event, 0)`: later work of `stream` waits for the event's recorded work.
|
||||
pub(crate) fn wait_event(&self, stream: Stream, event: Event) -> Result<()> {
|
||||
let batch = self.batch.as_ref().ok_or(Error::MissingSymbol("cuStreamWaitEvent"))?;
|
||||
// SAFETY: live owned handles in their actual current Context; no host memory is passed.
|
||||
check("cuStreamWaitEvent", unsafe { (batch.wait_event)(stream.0 as *mut c_void, event.0 as *mut c_void, 0) })
|
||||
}
|
||||
}
|
||||
@@ -79,24 +79,33 @@ impl DeviceBuffer<'_> {
|
||||
/// synchronization with the same poisoning/leak rule as whole-buffer reads;
|
||||
/// a failed synchronization never returns its bytes.
|
||||
pub fn copy_to_range(&self, offset: usize, output: &mut [u8]) -> Result<()> {
|
||||
let staging = self.copy_range_staged(offset, output.len())?;
|
||||
output.copy_from_slice(&staging);
|
||||
Ok(())
|
||||
}
|
||||
/// `copy_to_range` that hands the completed staging over instead of copying it into a second buffer: the same
|
||||
/// transfer, synchronization and poisoning/leak rule, the same bytes, one allocation and one copy fewer.
|
||||
pub fn copy_to_range_owned(&self, offset: usize, bytes: usize) -> Result<Vec<u8>> {
|
||||
self.copy_range_staged(offset, bytes)
|
||||
}
|
||||
fn copy_range_staged(&self, offset: usize, bytes: usize) -> Result<Vec<u8>> {
|
||||
if self.context.poisoned.get() {
|
||||
return Err(Error::ContextPoisoned);
|
||||
}
|
||||
let handle = self.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(self.bytes, offset, output.len())?;
|
||||
let handle = self.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(self.bytes, offset, bytes)?;
|
||||
let mut staging = Vec::new();
|
||||
staging.try_reserve_exact(output.len()).map_err(|_| Error::HostAllocation)?;
|
||||
staging.resize(output.len(), 0);
|
||||
staging.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?;
|
||||
staging.resize(bytes, 0);
|
||||
let guard = self.context.enter()?;
|
||||
let copy = self.context.driver.api.copy_to(handle, &mut staging);
|
||||
let sync = self.context.driver.api.synchronize();
|
||||
if sync.is_err() {
|
||||
self.context.poisoned.set(true);
|
||||
std::mem::forget(staging);
|
||||
return combine(combine(copy, sync), guard.finish());
|
||||
return combine(combine(copy, sync), guard.finish()).map(|()| Vec::new());
|
||||
}
|
||||
combine(copy, guard.finish())?;
|
||||
output.copy_from_slice(&staging);
|
||||
Ok(())
|
||||
Ok(staging)
|
||||
}
|
||||
pub fn copy_to(&self, output: &mut [u8]) -> Result<()> {
|
||||
let staging = self.staging(output.len())?;
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
//! A byte vector of a size known up front, filled by a copy without first being filled with zeros.
|
||||
//!
|
||||
//! The prefix-cache export (`OriginalQsaMappedJournal::export_pages_fast`) writes every byte of a fresh buffer. The
|
||||
//! usual `resize(n, 0)` then touches the whole buffer once for nothing (a memset and the page faults of a fresh
|
||||
//! allocation) before the copy touches it again.
|
||||
use crate::{Error, Result};
|
||||
use std::mem::MaybeUninit;
|
||||
|
||||
/// `out` becomes exactly `total` bytes written by `fill` into its spare capacity, with no zero fill first.
|
||||
///
|
||||
/// `fill` gets `total` writable bytes and returns how many leading bytes it initialised. Anything but `total`, or an
|
||||
/// error, leaves `out` empty: a half-written buffer is never exposed. A reused `out` keeps its capacity.
|
||||
pub(crate) fn fill_exact(
|
||||
out: &mut Vec<u8>,
|
||||
total: usize,
|
||||
fill: impl FnOnce(&mut [MaybeUninit<u8>]) -> Result<usize>,
|
||||
) -> Result<()> {
|
||||
out.clear();
|
||||
out.try_reserve_exact(total).map_err(|_| Error::HostAllocation)?;
|
||||
let written = fill(&mut out.spare_capacity_mut()[..total])?;
|
||||
if written != total {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
// SAFETY: `fill` reported that it initialised the first `total` bytes of the spare capacity, `total` bytes were
|
||||
// reserved above, and `u8` has no invalid bit pattern.
|
||||
unsafe { out.set_len(total) };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A source split in pieces like the K/V page image: the pieces of the pattern in order.
|
||||
fn pattern(len: usize) -> Vec<u8> {
|
||||
(0..len).map(|i| (i.wrapping_mul(31) ^ (i >> 7)) as u8).collect()
|
||||
}
|
||||
|
||||
/// Copies `pieces` consecutive runs of `source` into `dst` the way the export copies its four runs.
|
||||
fn copy_runs(source: &[u8], runs: &[usize], dst: &mut [MaybeUninit<u8>]) -> Result<usize> {
|
||||
let (mut at, mut rest) = (0, dst);
|
||||
for &n in runs {
|
||||
let (piece, tail) = rest.split_at_mut(n);
|
||||
for (d, s) in piece.iter_mut().zip(&source[at..at + n]) {
|
||||
d.write(*s);
|
||||
}
|
||||
(at, rest) = (at + n, tail);
|
||||
}
|
||||
Ok(at)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_unzeroed_fill_gives_the_bytes_of_the_zero_filled_copy() {
|
||||
let source = pattern(4 * 1056 * 3);
|
||||
let runs = [3 * 2048, 3 * 2048, 3 * 64, 3 * 64];
|
||||
let mut zeroed = vec![0u8; source.len()];
|
||||
zeroed.copy_from_slice(&source);
|
||||
let mut fast = Vec::new();
|
||||
fill_exact(&mut fast, source.len(), |dst| copy_runs(&source, &runs, dst)).unwrap();
|
||||
assert_eq!(fast, zeroed);
|
||||
assert_eq!(fast.len(), 4 * 1056 * 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reused_buffer_is_replaced_whatever_it_held_and_keeps_its_capacity() {
|
||||
let source = pattern(512);
|
||||
let mut out = vec![0xAAu8; 4096];
|
||||
let capacity = out.capacity();
|
||||
fill_exact(&mut out, 512, |dst| copy_runs(&source, &[256, 256], dst)).unwrap();
|
||||
assert_eq!(out, source);
|
||||
assert_eq!(out.capacity(), capacity, "no new allocation for a smaller export");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_or_failed_fill_leaves_the_buffer_empty() {
|
||||
let source = pattern(64);
|
||||
let mut out = vec![1u8; 8];
|
||||
let short = fill_exact(&mut out, 64, |dst| copy_runs(&source, &[32], dst));
|
||||
assert!(matches!(short, Err(Error::InvalidSize)));
|
||||
assert!(out.is_empty());
|
||||
let failed = fill_exact(&mut out, 64, |_| Err(Error::ContextPoisoned));
|
||||
assert!(matches!(failed, Err(Error::ContextPoisoned)));
|
||||
assert!(out.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_size_that_cannot_be_reserved_is_a_host_allocation_error() {
|
||||
let mut out = Vec::new();
|
||||
let refused = fill_exact(&mut out, usize::MAX, |_| Ok(0));
|
||||
assert!(matches!(refused, Err(Error::HostAllocation)));
|
||||
assert!(out.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -342,7 +342,7 @@ mod gpu;
|
||||
// Original physical prompt arena producer: old whole-owner API remains exact.
|
||||
#[path = "gdn_prompt_device.rs"]
|
||||
mod prompt_device;
|
||||
pub use prompt_device::{OriginalGdnPromptDevice, OriginalGdnPromptState, OriginalGdnPromptWeights};
|
||||
pub use prompt_device::{GdnPromptOptions, OriginalGdnPromptDevice, OriginalGdnPromptState, OriginalGdnPromptWeights};
|
||||
|
||||
#[path = "gdn_native_batch/pinned.rs"]
|
||||
mod pinned;
|
||||
|
||||
@@ -0,0 +1,549 @@
|
||||
// Offline compilation source; not a runtime/toolkit dependency.
|
||||
// EXPERIMENTAL, LOSSY (LELEKA_PREFILL_GDN_TC, off by default): the prompt GDN recurrence as a chunked scan on the tensor cores.
|
||||
//
|
||||
// Port of Strata upstream `src/prefill/gdn_tc.cuh` (strata-upstream/main 504b1433, history 8c2a84694 -> 06f212aef (the 99-KB
|
||||
// split plan for sm_86 / sm_89 / sm_120) -> ee0511484 -> 51567de1a (two value tiles a head on cards with >= 96 SMs)), restricted
|
||||
// to the plan the RTX 5090 (sm_120, 99 KB of shared memory a block, 170 SMs) runs: SPLIT shared-memory plan, three f16 passes a
|
||||
// product (NP = 3), output norm NOT fused (our separate leleka_prefill_gdn_out_norm* kernel runs after the recurrence as before),
|
||||
// one value tile (leleka_gdn_tc_scan_t1, 48 blocks) or two (leleka_gdn_tc_scan_t2, 96 blocks of 128 threads). The fused norm, the
|
||||
// one-pass and 124-KB plans, and the NP experiments are not ported.
|
||||
//
|
||||
// What it replaces: leleka_prefill_gdn_rec / leleka_prefill_gdn_rec_kh (prefill_stage.cu), the token-serial recurrence of the
|
||||
// Original. Same interface and layout: state_in -> state_out ([128 rows][48 heads][128 cols] f32), h = the convolved and L2-normalised
|
||||
// qkv rows ([T][10240]: q | k | v), gate (log decay) and beta ([T][48]), the readout `oc_out` ([T][48][128], already x rsqrt(128))
|
||||
// and the state witness (bit 0 of *witness raised when the FINAL state holds a non-finite value, as leleka_prefill_gdn_rec_kh).
|
||||
//
|
||||
// NOT BITWISE EQUAL to those kernels, by design: the recurrence is re-associated into the chunked WY form of
|
||||
// gdn_chunk_scan_kernel and every product runs on f16 mma.sync with f16x3 splits (x = hi + lo, hi.hi + hi.lo + lo.hi, lo.lo dropped,
|
||||
// operands scaled by powers of two so that lo stays normal): within 3 x 2^-22 |a||b| of each exact product, 1e-4 of the sequential
|
||||
// kernel in the upstream harness. Upstream's end-to-end first-token KL against the sequential path: mean 0.0019, max 0.0125. The gate
|
||||
// that decides is docs/quality-gate.md (first-token KL / q_tail_gate / logprob envelope), not an identity probe.
|
||||
//
|
||||
// Three kernels, a prompt chunk of T tokens runs in super-blocks of nch chunks (32 tokens each) held in a scratch the host provides:
|
||||
// leleka_gdn_tc_prep grid nch * 16 (block b: chunk b / 16, key head b % 16), 256 threads, 43,264 B dynamic shared memory:
|
||||
// A, T = (I + A)^-1 and P of the chunk, the k / q f16 hi / lo images, the token scalars, into the scratch
|
||||
// leleka_gdn_tc_scan_t1 grid 48 (a block per value head), 256 threads, 97,808 B
|
||||
// leleka_gdn_tc_scan_t2 grid 96 (value head x 2 column tiles), 128 threads, 97,808 B
|
||||
// The scan launches of one prompt run in order and the second one on reads the state the first wrote (state_in == state_out is
|
||||
// supported: a block reads and writes only its own columns).
|
||||
//
|
||||
// Scratch (bytes, a chunk of the super-block): T images 196,608 + T scales 192 + token scalars 24,576 + k / q images 524,288 + P images
|
||||
// 196,608 = 942,272 B; 64 chunks (2048 tokens, upstream's GSB) are 60,305,408 B. Every sub-buffer starts on a 16-B boundary (cp.async).
|
||||
//
|
||||
// Intended offline compile (the recipe of the other precise assets): pinned NVCC 13.2.86, -std=c++17 -O3 -ptx -arch=sm_120
|
||||
// --ftz=false --prec-div=true --prec-sqrt=true --fmad=true.
|
||||
#include <cuda_fp16.h>
|
||||
#include <stdint.h>
|
||||
|
||||
namespace {
|
||||
constexpr int S = 128, HK = 16, HV = 48, C = 10240; // head size, key heads, value heads, qkv row width
|
||||
constexpr int VPK = HV / HK; // value heads a key head
|
||||
constexpr int GCH = 32; // tokens a chunk (the prep's solve is a lane per token)
|
||||
constexpr int GTP = GCH + 1; // padded T / P rows of the prep
|
||||
static_assert(GCH == 32, "a lane per token of the chunk");
|
||||
static_assert(C == 2 * HK * S + HV * S, "qkv row: q | k | v");
|
||||
|
||||
__device__ __forceinline__ void gdn_cp4(float* smem, const float* gmem) {
|
||||
asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem));
|
||||
}
|
||||
__device__ __forceinline__ void gdn_cp16(float* smem, const float* gmem) {
|
||||
asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem));
|
||||
}
|
||||
__device__ __forceinline__ void gdn_cp_commit() { asm volatile("cp.async.commit_group;\n" ::); }
|
||||
__device__ __forceinline__ void gdn_cp_wait_all() { asm volatile("cp.async.wait_all;\n" ::); }
|
||||
|
||||
constexpr int GTC_KP = S + 8; // f16 k / q rows: a 272-B stride puts the 8 rows of a ldmatrix 8x8 on 8 distinct 16-B lanes
|
||||
constexpr int GTC_VP = S + 4; // f32 v rows: lane (gid, tig) reads word 264 tig + gid, 32 distinct banks
|
||||
constexpr int GTC_PP = GCH + 8; // f16 T / P rows: an 80-B stride, 8 rows on distinct 16-B lanes
|
||||
constexpr int GTC_CW = S / 16; // consumer warps a block: 16 value columns each
|
||||
// The SPLIT shared-memory plan (the 99-KB cards): only k / q hi / lo and the token scalars stay double-buffered; v, T and P (one
|
||||
// buffer) are staged for the next chunk after this chunk's last read of them, so that load overlaps the state update.
|
||||
constexpr size_t kTcScanSmemSplit = 2 * (4 * GCH * GTC_KP * 2 + GCH * 16) + GCH * GTC_VP * 4 + 4 * GCH * GTC_PP * 2 + 16;
|
||||
static_assert(kTcScanSmemSplit == 97808, "the split shared-memory plan");
|
||||
constexpr size_t kTcPrepSmem = (size_t) 4 * GCH * GTC_KP * 2 + 2 * GCH * GTP * 4; // the images, then k_t.k_i and q_t.k_i
|
||||
static_assert(kTcPrepSmem == 43264, "the prep shared-memory plan");
|
||||
static_assert(VPK * GCH * GTP * 4 <= 4 * GCH * GTC_KP * 2, "gdn_tc_prep: A fits where the images were");
|
||||
|
||||
// the warp's largest of non-negative floats: their bits order as unsigned integers, so one redux.sync. Under the full mask (the
|
||||
// first call of the scan follows a lane-divergent branch, so __activemask() would not do).
|
||||
__device__ __forceinline__ float gtc_warp_max(float v) {
|
||||
return __uint_as_float(__reduce_max_sync(0xffffffffu, __float_as_uint(v)));
|
||||
}
|
||||
__device__ __forceinline__ float gtc_pow2(int e) { return __int_as_float((e + 127) << 23); } // 2^e, |e| < 127
|
||||
// the power of two that puts m = max |x| >= 0 in [2^14, 2^15): f16 hi never overflows (65504) and the low part of every entry within
|
||||
// 2^-17 of the max stays normal; clamped so that the compensating powers stay far from f32's range
|
||||
__device__ __forceinline__ int gtc_scale_exp(float m) {
|
||||
if (m == 0.0f) return 0;
|
||||
const int e = 14 - ((__float_as_int(m) >> 23) - 127);
|
||||
return e < -40 ? -40 : (e > 40 ? 40 : e);
|
||||
}
|
||||
|
||||
// ---- the tensor-core wrappers (PTX ISA "Matrix Fragments": lane = 4 gid + tig)
|
||||
// m16n8k16 f16: A a0 = (row gid, cols 2tig, 2tig+1) a1 = (gid+8, ..) a2 = (gid, 2tig+8..) a3 = (gid+8, 2tig+8..);
|
||||
// B b0 = (k 2tig, 2tig+1; n gid) b1 = (k 2tig+8..; n gid); C/D c0 = (gid, 2tig) c1 = (gid, 2tig+1)
|
||||
// c2 = (gid+8, 2tig) c3 = (gid+8, 2tig+1) - so two adjacent C tiles ARE the next product's A fragment
|
||||
// ldmatrix m8n8.x4.b16: lanes 8m..8m+7 give the row addresses of matrix m; a lane gets (row gid, cols 2tig, 2tig+1)
|
||||
// of each matrix (the lower column in the low half), or with .trans (rows 2tig, 2tig+1; col gid)
|
||||
__device__ __forceinline__ void gtc_ldsm_x4(uint32_t (&r)[4], const void* smem) {
|
||||
asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];"
|
||||
: "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3])
|
||||
: "r"((unsigned) __cvta_generic_to_shared(smem)));
|
||||
}
|
||||
__device__ __forceinline__ void gtc_ldsm_x4_trans(uint32_t (&r)[4], const void* smem) {
|
||||
asm volatile("ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {%0,%1,%2,%3}, [%4];"
|
||||
: "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3])
|
||||
: "r"((unsigned) __cvta_generic_to_shared(smem)));
|
||||
}
|
||||
__device__ __forceinline__ void gtc_mma_f16(float (&c)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t b1) {
|
||||
asm("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};"
|
||||
: "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
|
||||
: "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1));
|
||||
}
|
||||
// the three passes of a split product, small terms first: lo.hi, hi.lo, hi.hi
|
||||
__device__ __forceinline__ void gtc_mma3_f16(float (&c)[4], const uint32_t (&ah)[4], const uint32_t (&al)[4], uint32_t bh0,
|
||||
uint32_t bh1, uint32_t bl0, uint32_t bl1) {
|
||||
gtc_mma_f16(c, al, bh0, bh1);
|
||||
gtc_mma_f16(c, ah, bl0, bl1);
|
||||
gtc_mma_f16(c, ah, bh0, bh1);
|
||||
}
|
||||
// x0, x1 -> packed f16 hi (x0 in the low half) and lo = f16(x - hi): x - hi is exact in f32 (hi carries x's exponent)
|
||||
__device__ __forceinline__ void gtc_split_f16x2(float x0, float x1, uint32_t& hi, uint32_t& lo) {
|
||||
union { __half2 h; uint32_t u; } cv;
|
||||
cv.h = __floats2half2_rn(x0, x1);
|
||||
hi = cv.u;
|
||||
const float2 r = __half22float2(cv.h);
|
||||
cv.h = __floats2half2_rn(x0 - r.x, x1 - r.y);
|
||||
lo = cv.u;
|
||||
}
|
||||
// four consecutive elements of an f16 hi / lo row from a float4 x scale (an 8-byte store each)
|
||||
__device__ __forceinline__ void gtc_split_store4(uint16_t* hi, uint16_t* lo, float4 v, float scale) {
|
||||
uint32_t h0, l0, h1, l1;
|
||||
gtc_split_f16x2(v.x * scale, v.y * scale, h0, l0);
|
||||
gtc_split_f16x2(v.z * scale, v.w * scale, h1, l1);
|
||||
*reinterpret_cast<uint2*>(hi) = make_uint2(h0, h1);
|
||||
*reinterpret_cast<uint2*>(lo) = make_uint2(l0, l1);
|
||||
}
|
||||
// a float4 from shared memory the compiler does not keep: the per-token scalars are read in three phases of a chunk, a component
|
||||
// each, and kept across them they cost 24 registers a thread
|
||||
__device__ __forceinline__ float4 gtc_lds128(const float4* p) {
|
||||
float4 v;
|
||||
asm volatile("ld.shared.v4.f32 {%0,%1,%2,%3}, [%4];"
|
||||
: "=f"(v.x), "=f"(v.y), "=f"(v.z), "=f"(v.w)
|
||||
: "r"((unsigned) __cvta_generic_to_shared(p)));
|
||||
return v;
|
||||
}
|
||||
|
||||
// ---- the products of a chunk, a warp each
|
||||
// X^T = S^T K^T and QS^T = S^T Q^T: A = the state fragments x sA (= 2^es) split in f16 hi / lo just in time per k16-step (tiles 2kk and
|
||||
// 2kk + 1 of S^T are that step's A fragment), B = the f16 hi / lo images of k and q ([GCH][GTC_KP] in shared memory, rows = tokens) by
|
||||
// ldmatrix: matrices (n-tile 2hf + (lane >> 4), k-half (lane >> 3) & 1), a lane's row is token 8 n-tile + (lane & 7). The accumulators
|
||||
// come out as 2^(8 + es) times the products. 2 x 96 mma.
|
||||
__device__ __forceinline__ void gtc_prod_state(const float (&s)[16][4], float sA, const uint16_t* kh, const uint16_t* kl,
|
||||
const uint16_t* qh, const uint16_t* ql, float (&xt)[4][4], float (&qs)[4][4]) {
|
||||
const int lane = threadIdx.x & 31;
|
||||
const int off = (8 * (lane >> 4) + (lane & 7)) * GTC_KP + 8 * ((lane >> 3) & 1);
|
||||
#pragma unroll
|
||||
for (int kk = 0; kk < S / 16; ++kk) {
|
||||
uint32_t ah[4], al[4];
|
||||
gtc_split_f16x2(s[2 * kk][0] * sA, s[2 * kk][1] * sA, ah[0], al[0]);
|
||||
gtc_split_f16x2(s[2 * kk][2] * sA, s[2 * kk][3] * sA, ah[1], al[1]);
|
||||
gtc_split_f16x2(s[2 * kk + 1][0] * sA, s[2 * kk + 1][1] * sA, ah[2], al[2]);
|
||||
gtc_split_f16x2(s[2 * kk + 1][2] * sA, s[2 * kk + 1][3] * sA, ah[3], al[3]);
|
||||
#pragma unroll
|
||||
for (int hf = 0; hf < 2; ++hf) {
|
||||
const int o = off + 16 * hf * GTC_KP + 16 * kk;
|
||||
uint32_t bh[4], bl[4];
|
||||
gtc_ldsm_x4(bh, kh + o);
|
||||
gtc_ldsm_x4(bl, kl + o);
|
||||
gtc_mma3_f16(xt[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]);
|
||||
gtc_mma3_f16(xt[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]);
|
||||
gtc_ldsm_x4(bh, qh + o);
|
||||
gtc_ldsm_x4(bl, ql + o);
|
||||
gtc_mma3_f16(qs[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]);
|
||||
gtc_mma3_f16(qs[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// o^T += (sD D^T) (2^8 P^T) on f16x3: A = the D^T tiles x sD (= 2^ed) split per k16-step, B = the f16 hi / lo images of P x 2^8
|
||||
// ([GCH][GTC_PP], rows = tokens t) by ldmatrix as in gtc_prod_state. The tiles above P's diagonal are left out: tokens t < 16 (n-tiles
|
||||
// 0, 1) see no i >= 16 (k-step 1). 18 mma. D^T += (sY Y^T) (2^et T^T) is the same product on the T images (T is zero above its
|
||||
// diagonal too), the accumulator x 2^(ey + et).
|
||||
__device__ __forceinline__ void gtc_prod_dt(const float (&dt)[4][4], float sD, const uint16_t* ph, const uint16_t* pl,
|
||||
float (&ot)[4][4]) {
|
||||
const int lane = threadIdx.x & 31;
|
||||
const int off = (8 * (lane >> 4) + (lane & 7)) * GTC_PP + 8 * ((lane >> 3) & 1);
|
||||
#pragma unroll
|
||||
for (int ks = 0; ks < GCH / 16; ++ks) {
|
||||
uint32_t ah[4], al[4];
|
||||
gtc_split_f16x2(dt[2 * ks][0] * sD, dt[2 * ks][1] * sD, ah[0], al[0]);
|
||||
gtc_split_f16x2(dt[2 * ks][2] * sD, dt[2 * ks][3] * sD, ah[1], al[1]);
|
||||
gtc_split_f16x2(dt[2 * ks + 1][0] * sD, dt[2 * ks + 1][1] * sD, ah[2], al[2]);
|
||||
gtc_split_f16x2(dt[2 * ks + 1][2] * sD, dt[2 * ks + 1][3] * sD, ah[3], al[3]);
|
||||
#pragma unroll
|
||||
for (int hf = 0; hf < 2; ++hf) {
|
||||
if (ks == 1 && hf == 0) continue;
|
||||
const int o = off + 16 * hf * GTC_PP + 16 * ks;
|
||||
uint32_t bh[4], bl[4];
|
||||
gtc_ldsm_x4(bh, ph + o);
|
||||
gtc_ldsm_x4(bl, pl + o);
|
||||
gtc_mma3_f16(ot[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]);
|
||||
gtc_mma3_f16(ot[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// S^T += Dd^T (2^8 K) on f16x3: A = the (already scaled) Dd^T tiles split per k16-step, B = the same k images read the other way by
|
||||
// ldmatrix.trans: matrices (n-tile 2hf + (lane >> 4), k-half (lane >> 3) & 1), a lane's row is token 16 ks + 8 k-half + (lane & 7), its
|
||||
// 16-B piece state rows 8 n-tile.. 96 mma.
|
||||
__device__ __forceinline__ void gtc_update_state(float (&s)[16][4], const float (&dd)[4][4], const uint16_t* kh,
|
||||
const uint16_t* kl) {
|
||||
const int lane = threadIdx.x & 31;
|
||||
const int off = (8 * ((lane >> 3) & 1) + (lane & 7)) * GTC_KP + 8 * (lane >> 4);
|
||||
#pragma unroll
|
||||
for (int ks = 0; ks < GCH / 16; ++ks) {
|
||||
uint32_t ah[4], al[4];
|
||||
gtc_split_f16x2(dd[2 * ks][0], dd[2 * ks][1], ah[0], al[0]);
|
||||
gtc_split_f16x2(dd[2 * ks][2], dd[2 * ks][3], ah[1], al[1]);
|
||||
gtc_split_f16x2(dd[2 * ks + 1][0], dd[2 * ks + 1][1], ah[2], al[2]);
|
||||
gtc_split_f16x2(dd[2 * ks + 1][2], dd[2 * ks + 1][3], ah[3], al[3]);
|
||||
#pragma unroll
|
||||
for (int hf = 0; hf < S / 16; ++hf) {
|
||||
const int o = off + 16 * ks * GTC_KP + 16 * hf;
|
||||
uint32_t bh[4], bl[4];
|
||||
gtc_ldsm_x4_trans(bh, kh + o);
|
||||
gtc_ldsm_x4_trans(bl, kl + o);
|
||||
gtc_mma3_f16(s[2 * hf], ah, al, bh[0], bh[1], bl[0], bl[1]);
|
||||
gtc_mma3_f16(s[2 * hf + 1], ah, al, bh[2], bh[3], bl[2], bl[3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the scan of one super-block: a block per value head (or per head and column tile), warps of 16 value columns each walking
|
||||
// every chunk with their state slice in registers, the prep's scratch staged by cp.async. NTL value tiles a head (a launch of HV x NTL
|
||||
// blocks of GTC_CW / NTL warps): block (vh, tile) owns the state columns [tile S / NTL, (tile + 1) S / NTL). The k / q / T / P images
|
||||
// are staged by every tile of the head, v only for its columns.
|
||||
extern __shared__ __align__(16) unsigned char gtc_sm[]; // the scan's dynamic shared memory (97,808 B)
|
||||
|
||||
template <int NTL>
|
||||
__device__ __forceinline__ void gtc_scan_body(const float* state_in, float* state_out, const float* __restrict__ h,
|
||||
const uint16_t* __restrict__ tig_, const float* __restrict__ teg,
|
||||
const float4* __restrict__ scg, const uint16_t* __restrict__ kqg,
|
||||
const uint16_t* __restrict__ pig, float* __restrict__ oc_out, int64_t t0,
|
||||
int nch, int64_t T, unsigned* witness) {
|
||||
static_assert(GTC_CW % NTL == 0, "tiles of whole warps");
|
||||
constexpr int NT = (GTC_CW / NTL) * 32;
|
||||
uint16_t* kh = reinterpret_cast<uint16_t*>(gtc_sm); // [2][GCH][GTC_KP] f16 of k x 2^8 (hi)
|
||||
uint16_t* kl = kh + 2 * GCH * GTC_KP; // [2][GCH][GTC_KP] what hi left out (lo)
|
||||
uint16_t* qh = kl + 2 * GCH * GTC_KP; // q likewise
|
||||
uint16_t* ql = qh + 2 * GCH * GTC_KP;
|
||||
float* sv = reinterpret_cast<float*>(ql + 2 * GCH * GTC_KP); // [GCH][GTC_VP] v (one buffer)
|
||||
uint16_t* th = reinterpret_cast<uint16_t*>(sv + GCH * GTC_VP); // [GCH][GTC_PP] T x 2^et hi / lo
|
||||
uint16_t* tl = th + GCH * GTC_PP;
|
||||
uint16_t* ph = tl + GCH * GTC_PP; // [GCH][GTC_PP] P x 2^8 hi / lo
|
||||
uint16_t* pl = ph + GCH * GTC_PP;
|
||||
float4* sc = reinterpret_cast<float4*>(pl + GCH * GTC_PP); // [2][GCH] (beta, exp(gamma), exp(gL - gamma), gamma)
|
||||
float* ste = reinterpret_cast<float*>(sc + 2 * GCH); // [2] 2^-et
|
||||
const int vh = blockIdx.x / NTL, qhd = vh % HK, cb = (blockIdx.x % NTL) * (S / NTL); // the tile's first column
|
||||
const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31, gid = lane >> 2, tig = lane & 3;
|
||||
const size_t rs = (size_t) HV * S;
|
||||
// chunk ch into buffer b, this thread's 16-B pieces (one cp.async group): the four k / q images (4 x GCH rows of 16 pieces: 8 a
|
||||
// thread), v (4 a thread), the two T images (1), the two P images (1), the scalars (threads < GCH), T's scale (thread 0, 4 B)
|
||||
// parts: bit 0 = the k / q images, the scalars and T's scale (buffer b); bit 1 = v, T and P (the one buffer)
|
||||
auto stage = [&](int ch, int b, int parts) {
|
||||
const int64_t c_t0 = t0 + (int64_t) ch * GCH;
|
||||
const int n = (int) min((int64_t) GCH, T - c_t0);
|
||||
if (parts & 1) {
|
||||
const uint16_t* img = kqg + ((size_t) ch * HK + qhd) * 4 * GCH * S;
|
||||
#pragma unroll
|
||||
for (int m = 0; m < 4 * GCH * S / 8 / NT; ++m) {
|
||||
const int pc = tid + NT * m, im = pc / (GCH * S / 8), t = (pc % (GCH * S / 8)) / (S / 8), r = (pc % (S / 8)) * 8;
|
||||
uint16_t* dst = (im == 0 ? kh : im == 1 ? kl : im == 2 ? qh : ql) + (b * GCH + t) * GTC_KP + r;
|
||||
gdn_cp16(reinterpret_cast<float*>(dst), reinterpret_cast<const float*>(img + (im * GCH + t) * S + r));
|
||||
}
|
||||
if (tid < GCH) gdn_cp16(reinterpret_cast<float*>(sc + b * GCH + tid), reinterpret_cast<const float*>(scg + ((int64_t) ch * HV + vh) * GCH + tid));
|
||||
if (tid == 0) gdn_cp4(ste + b, teg + (int64_t) ch * HV + vh);
|
||||
}
|
||||
if (parts & 2) {
|
||||
#pragma unroll
|
||||
for (int m = 0; m < GCH * (S / NTL) / 4 / NT; ++m) {
|
||||
const int p = tid + NT * m, t = p / (S / NTL / 4), r = (p % (S / NTL / 4)) * 4;
|
||||
float* dst = sv + t * GTC_VP + r;
|
||||
if (t < n) gdn_cp16(dst, h + (c_t0 + t) * C + 2 * HK * S + vh * S + cb + r);
|
||||
else *reinterpret_cast<float4*>(dst) = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int m = 0; m < 2 * GCH * GCH / 8 / NT; ++m) {
|
||||
const int pc = tid + NT * m, im = pc / (GCH * GCH / 8), t = (pc % (GCH * GCH / 8)) / (GCH / 8), i = (pc % (GCH / 8)) * 8;
|
||||
const int64_t src = ((((int64_t) ch * HV + vh) * 2 + im) * GCH + t) * GCH + i;
|
||||
const int dst = t * GTC_PP + i;
|
||||
gdn_cp16(reinterpret_cast<float*>((im ? tl : th) + dst), reinterpret_cast<const float*>(tig_ + src));
|
||||
gdn_cp16(reinterpret_cast<float*>((im ? pl : ph) + dst), reinterpret_cast<const float*>(pig + src));
|
||||
}
|
||||
}
|
||||
gdn_cp_commit();
|
||||
};
|
||||
const int c0 = 16 * warp; // the warp's value columns c0 + gid and c0 + gid + 8 of the tile (v in shared memory)
|
||||
const int ca = cb + c0; // the same in the head (state, output)
|
||||
// the state slice as S^T fragments: tile j = rows 8j..8j+7; s[j][0] = S[8j + 2tig][c0 + gid], [1] the row after, [2] column + 8, [3]
|
||||
// both (64 scalar loads a lane, 32-B runs, once a launch)
|
||||
float s[16][4];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 16; ++j) {
|
||||
const float* p = state_in + (size_t) (8 * j + 2 * tig) * rs + (size_t) vh * S + ca + gid;
|
||||
s[j][0] = p[0]; s[j][1] = p[rs]; s[j][2] = p[8]; s[j][3] = p[rs + 8];
|
||||
}
|
||||
stage(0, 0, 3);
|
||||
const float out_scale = rsqrtf((float) S);
|
||||
for (int ch = 0; ch < nch; ++ch) {
|
||||
const int b = ch & 1;
|
||||
const int64_t c_t0 = t0 + (int64_t) ch * GCH;
|
||||
const int n = (int) min((int64_t) GCH, T - c_t0);
|
||||
gdn_cp_wait_all(); // this thread's pieces of chunk ch
|
||||
__syncthreads(); // every thread's: chunk ch's buffer complete; every read of the other one done
|
||||
if (ch + 1 < nch) stage(ch + 1, b ^ 1, 1);
|
||||
const uint16_t* bkh = kh + b * GCH * GTC_KP;
|
||||
const uint16_t* bkl = kl + b * GCH * GTC_KP;
|
||||
const uint16_t* bqh = qh + b * GCH * GTC_KP;
|
||||
const uint16_t* bql = ql + b * GCH * GTC_KP;
|
||||
const float4* bsc = sc + b * GCH;
|
||||
// (a) X^T = S0^T K^T and QS^T = S0^T Q^T, the state x 2^es (its largest entry in [2^14, 2^15)). The lane's maximum over eight
|
||||
// chains (nvcc keeps the order written: one chain was 64 dependent FMNMX before the first mma)
|
||||
float m8[8] = {};
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 16; ++j)
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) m8[(2 * j + (q >> 1)) & 7] = fmaxf(m8[(2 * j + (q >> 1)) & 7], fabsf(s[j][q]));
|
||||
const float m = fmaxf(fmaxf(fmaxf(m8[0], m8[1]), fmaxf(m8[2], m8[3])), fmaxf(fmaxf(m8[4], m8[5]), fmaxf(m8[6], m8[7])));
|
||||
const int es = gtc_scale_exp(gtc_warp_max(m));
|
||||
float xt[4][4] = {}, qs[4][4] = {};
|
||||
gtc_prod_state(s, gtc_pow2(es), bkh, bkl, bqh, bql, xt, qs);
|
||||
// (b) Y^T = beta_i (V^T - e'_i X^T), e'_i = exp(gamma_i) 2^-(8 + es): lane (gid, tig) holds tokens 8nt + 2tig and + 1, columns
|
||||
// c0 + gid and + 8
|
||||
const float eS = gtc_pow2(-(8 + es));
|
||||
float yt[4][4];
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < 4; ++nt) {
|
||||
const float4 s0 = gtc_lds128(bsc + 8 * nt + 2 * tig), s1 = gtc_lds128(bsc + 8 * nt + 2 * tig + 1);
|
||||
const float* v = sv + (8 * nt + 2 * tig) * GTC_VP + c0 + gid;
|
||||
const float e0 = s0.y * eS, e1 = s1.y * eS;
|
||||
yt[nt][0] = s0.x * fmaf(-e0, xt[nt][0], v[0]);
|
||||
yt[nt][1] = s1.x * fmaf(-e1, xt[nt][1], v[GTC_VP]);
|
||||
yt[nt][2] = s0.x * fmaf(-e0, xt[nt][2], v[8]);
|
||||
yt[nt][3] = s1.x * fmaf(-e1, xt[nt][3], v[GTC_VP + 8]);
|
||||
}
|
||||
// (c) D^T = Y^T T^T on f16x3: Y^T x 2^ey (its largest entry in [2^14, 2^15)), T's images x 2^et from the prep; the accumulator
|
||||
// comes out x 2^(ey + et) (T above its diagonal skipped)
|
||||
float my4[4] = {};
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < 4; ++nt)
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) my4[q] = fmaxf(my4[q], fabsf(yt[nt][q]));
|
||||
const int ey = gtc_scale_exp(gtc_warp_max(fmaxf(fmaxf(my4[0], my4[1]), fmaxf(my4[2], my4[3]))));
|
||||
float dt[4][4] = {};
|
||||
gtc_prod_dt(yt, gtc_pow2(ey), th, tl, dt);
|
||||
const float sYT = gtc_pow2(-ey) * ste[b];
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < 4; ++nt)
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) dt[nt][q] *= sYT;
|
||||
// (d) o^T = e_t QS^T + D^T P^T: the accumulator starts as 2^(ed + 8) e_t QS^T (QS^T came out x 2^(8 + es)), D^T goes in x 2^ed, P
|
||||
// x 2^8; the output is the accumulator x 2^-(ed + 8), then rsqrt(S)
|
||||
float md4[4] = {};
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < 4; ++nt)
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) md4[q] = fmaxf(md4[q], fabsf(dt[nt][q]));
|
||||
const int ed = gtc_scale_exp(gtc_warp_max(fmaxf(fmaxf(md4[0], md4[1]), fmaxf(md4[2], md4[3]))));
|
||||
const float sD = gtc_pow2(ed), sO = gtc_pow2(ed + 8), sOi = gtc_pow2(-(ed + 8)), eO = gtc_pow2(ed - es);
|
||||
float ot[4][4];
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < 4; ++nt) {
|
||||
const float e0 = gtc_lds128(bsc + 8 * nt + 2 * tig).y * eO, e1 = gtc_lds128(bsc + 8 * nt + 2 * tig + 1).y * eO;
|
||||
ot[nt][0] = qs[nt][0] * e0; ot[nt][1] = qs[nt][1] * e1; ot[nt][2] = qs[nt][2] * e0; ot[nt][3] = qs[nt][3] * e1;
|
||||
}
|
||||
gtc_prod_dt(dt, sD, ph, pl, ot);
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < 4; ++nt)
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
const int t = 8 * nt + 2 * tig + (q & 1);
|
||||
if (t < n) oc_out[(c_t0 + t) * rs + (size_t) vh * S + ca + gid + 8 * (q >> 1)] = (ot[nt][q] * sOi) * out_scale;
|
||||
}
|
||||
// v, T and P of this chunk are dead: every warp is past (d); the next chunk's land during (e)
|
||||
__syncthreads();
|
||||
if (ch + 1 < nch) stage(ch + 1, 0, 2);
|
||||
// (e) S^T = eL S0^T + Dd^T K, Dd^T = f_i D^T: the accumulator x (eL 2^(ed + 8)) before (one rounding), Dd^T in x 2^ed, K x 2^8,
|
||||
// the accumulator x 2^-(ed + 8) after
|
||||
const float sPre = gtc_lds128(bsc + GCH - 1).y * sO; // exp(gL)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 16; ++j)
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) s[j][q] *= sPre;
|
||||
float dd[4][4];
|
||||
#pragma unroll
|
||||
for (int nt = 0; nt < 4; ++nt) {
|
||||
const float f0 = gtc_lds128(bsc + 8 * nt + 2 * tig).z * sD, f1 = gtc_lds128(bsc + 8 * nt + 2 * tig + 1).z * sD;
|
||||
dd[nt][0] = dt[nt][0] * f0; dd[nt][1] = dt[nt][1] * f1; dd[nt][2] = dt[nt][2] * f0; dd[nt][3] = dt[nt][3] * f1;
|
||||
}
|
||||
gtc_update_state(s, dd, bkh, bkl);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 16; ++j)
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) s[j][q] *= sOi;
|
||||
}
|
||||
// the final state and its witness (a non-finite state value never becomes finite again, so the final state is enough)
|
||||
unsigned bad = 0;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 16; ++j) {
|
||||
float* p = state_out + (size_t) (8 * j + 2 * tig) * rs + (size_t) vh * S + ca + gid;
|
||||
p[0] = s[j][0]; p[rs] = s[j][1]; p[8] = s[j][2]; p[rs + 8] = s[j][3];
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) bad |= (__float_as_uint(s[j][q]) & 0x7f800000u) == 0x7f800000u;
|
||||
}
|
||||
if (bad) atomicOr(witness, 1u);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// ---- the prep, a block per (chunk, key head): the same A, solve, T and P as the chunk algebra, but the Gram products k_t.k_i and
|
||||
// q_t.k_i on the tensor cores (f16x3 from the k and q hi / lo images x 2^8, which the block builds first in shared memory straight from
|
||||
// the float4 registers the rows arrive in, rows past the chunk's end zero), and it writes what the scan stages by cp.async with no
|
||||
// conversion of its own: the same k / q images, P as f16 hi / lo images x 2^8 and the token scalars (beta, exp(gamma), exp(gL - gamma),
|
||||
// gamma) as a float4 a token, T as f16 hi / lo images x 2^et, et from the warp's largest |T| (2^-et beside them in te). The Gram
|
||||
// entries are within 3 x 2^-22 of exact, so T and P differ from the sequential algebra's by that.
|
||||
// Grid: nch * HK blocks, block b = chunk b / HK of the super-block, key head b % HK (a 1-D grid: KernelModule's contract).
|
||||
extern "C" __global__ void __launch_bounds__(256) leleka_gdn_tc_prep(
|
||||
const float* __restrict__ h, const float* __restrict__ gate, const float* __restrict__ beta, uint16_t* __restrict__ ti,
|
||||
float* __restrict__ te, float4* __restrict__ sc, uint16_t* __restrict__ kq, uint16_t* __restrict__ pi, int64_t t0,
|
||||
int64_t T) {
|
||||
extern __shared__ __align__(16) float gsm[];
|
||||
uint16_t* im = reinterpret_cast<uint16_t*>(gsm); // [4][GCH][GTC_KP] k hi, k lo, q hi, q lo (x 2^8)
|
||||
float* skk = gsm + 4 * GCH * GTC_KP / 2; // [GCH][GTP] k_t.k_i
|
||||
float* sqk = skk + GCH * GTP; // [GCH][GTP] q_t.k_i
|
||||
float* sa = gsm; // [VPK][GCH][GTP] A, then T below the diagonal (over the images: read by then)
|
||||
const int qh = blockIdx.x % HK, ch = blockIdx.x / HK, tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
|
||||
const int64_t tb = t0 + (int64_t) ch * GCH;
|
||||
const int n = (int) min((int64_t) GCH, T - tb);
|
||||
// after the Gram: warps j and VPK + j take value head j (lane i: token i), the first A, the solve and T, the second P and the token
|
||||
// scalars; their beta and gate (past the end: gate 0, beta 0, no effect on S) are loaded now so that they are in by then
|
||||
const int j = warp % VPK, vh = qh + j * HK, i = lane;
|
||||
const bool pv = warp < 2 * VPK && i < n;
|
||||
const float b = pv ? beta[(tb + i) * HV + vh] : 0.0f;
|
||||
float gam = pv ? gate[(tb + i) * HV + vh] : 0.0f;
|
||||
{ // k and q as float4, every load issued before the first store; the images to shared and to global
|
||||
constexpr int NP = GCH * S / 4 / 256; // float4 a thread, each of k and q
|
||||
float4 kv[NP], qv[NP];
|
||||
#pragma unroll
|
||||
for (int m = 0; m < NP; ++m) {
|
||||
const int p = tid + 256 * m, t = p / (S / 4), r = (p % (S / 4)) * 4;
|
||||
kv[m] = t < n ? *reinterpret_cast<const float4*>(h + (tb + t) * C + HK * S + qh * S + r) : make_float4(0.f, 0.f, 0.f, 0.f);
|
||||
qv[m] = t < n ? *reinterpret_cast<const float4*>(h + (tb + t) * C + qh * S + r) : make_float4(0.f, 0.f, 0.f, 0.f);
|
||||
}
|
||||
uint16_t* img = kq + ((size_t) ch * HK + qh) * 4 * GCH * S;
|
||||
#pragma unroll
|
||||
for (int m = 0; m < NP; ++m) {
|
||||
const int p = tid + 256 * m, t = p / (S / 4), r = (p % (S / 4)) * 4;
|
||||
const int o = t * GTC_KP + r;
|
||||
gtc_split_store4(im + o, im + GCH * GTC_KP + o, kv[m], 256.0f);
|
||||
gtc_split_store4(im + 2 * GCH * GTC_KP + o, im + 3 * GCH * GTC_KP + o, qv[m], 256.0f);
|
||||
gtc_split_store4(img + t * S + r, img + GCH * S + t * S + r, kv[m], 256.0f);
|
||||
gtc_split_store4(img + 2 * GCH * S + t * S + r, img + 3 * GCH * S + t * S + r, qv[m], 256.0f);
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
{ // the Gram products: warp w takes product w >> 2 (k_t.k_i, q_t.k_i), rows 16 ((w >> 1) & 1).. (the A tile, by ldmatrix as a
|
||||
// row-major [t][r] 16 x 16), columns 16 (w & 1).. (two n-tiles: B = k^T, stored [n][k] = the k rows, by ldmatrix as the scan's
|
||||
// gtc_prod_state); the accumulators come out x 2^16
|
||||
const int pr = warp >> 2, mt = (warp >> 1) & 1, np = warp & 1;
|
||||
const uint16_t* ah_ = im + 2 * pr * GCH * GTC_KP + (16 * mt + (lane & 7) + 8 * ((lane >> 3) & 1)) * GTC_KP + 8 * (lane >> 4);
|
||||
const uint16_t* bh_ = im + (16 * np + 8 * (lane >> 4) + (lane & 7)) * GTC_KP + 8 * ((lane >> 3) & 1);
|
||||
float c[2][4] = {};
|
||||
#pragma unroll
|
||||
for (int kk = 0; kk < S / 16; ++kk) {
|
||||
uint32_t ah[4], al[4], bh[4], bl[4];
|
||||
gtc_ldsm_x4(ah, ah_ + 16 * kk);
|
||||
gtc_ldsm_x4(al, ah_ + GCH * GTC_KP + 16 * kk);
|
||||
gtc_ldsm_x4(bh, bh_ + 16 * kk);
|
||||
gtc_ldsm_x4(bl, bh_ + GCH * GTC_KP + 16 * kk);
|
||||
gtc_mma3_f16(c[0], ah, al, bh[0], bh[1], bl[0], bl[1]);
|
||||
gtc_mma3_f16(c[1], ah, al, bh[2], bh[3], bl[2], bl[3]);
|
||||
}
|
||||
float* g = pr ? sqk : skk;
|
||||
const int gid = lane >> 2, tig = lane & 3;
|
||||
#pragma unroll
|
||||
for (int jj = 0; jj < 2; ++jj)
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
const int t = 16 * mt + gid + 8 * (q >> 1), ii = 16 * np + 8 * jj + 2 * tig + (q & 1);
|
||||
g[t * GTP + ii] = ii <= t ? c[jj][q] * gtc_pow2(-16) : 0.0f;
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if (warp >= 2 * VPK) return;
|
||||
#pragma unroll
|
||||
for (int o = 1; o < 32; o <<= 1) {
|
||||
const float u = __shfl_up_sync(0xffffffffu, gam, o);
|
||||
if (lane >= o) gam += u;
|
||||
}
|
||||
if (warp >= VPK) { // P = exp(gamma_t - gamma_i) q_t.k_i (i <= t) x 2^8 as f16 hi / lo; the scalars
|
||||
uint16_t* Ph = pi + ((int64_t) ch * HV + vh) * 2 * GCH * GCH;
|
||||
uint16_t* Pl = Ph + GCH * GCH;
|
||||
#pragma unroll
|
||||
for (int t = 0; t < GCH; ++t) {
|
||||
const float gt = __shfl_sync(0xffffffffu, gam, t);
|
||||
const float p = (i <= t ? expf(gt - gam) * sqk[t * GTP + i] : 0.0f) * 256.0f;
|
||||
const __half hi = __float2half_rn(p);
|
||||
Ph[t * GCH + i] = __half_as_ushort(hi);
|
||||
Pl[t * GCH + i] = __half_as_ushort(__float2half_rn(p - __half2float(hi)));
|
||||
}
|
||||
const float gL = __shfl_sync(0xffffffffu, gam, GCH - 1);
|
||||
sc[((int64_t) ch * HV + vh) * GCH + i] = make_float4(b, expf(gam), expf(gL - gam), gam);
|
||||
return;
|
||||
}
|
||||
float* a = sa + j * GCH * GTP;
|
||||
#pragma unroll
|
||||
for (int t = 0; t < GCH; ++t) {
|
||||
const float gt = __shfl_sync(0xffffffffu, gam, t), bt = __shfl_sync(0xffffffffu, b, t);
|
||||
a[t * GTP + i] = i < t ? bt * expf(gt - gam) * skk[t * GTP + i] : (i == t ? 1.0f : 0.0f);
|
||||
}
|
||||
__syncwarp();
|
||||
// T = (I + A)^-1 by forward substitution, row by row: T[t][i] = -sum_{k < t} A[t][k] T[k][i] over the finished rows (diagonal 1,
|
||||
// zeros above it: the terms k < i add an exact 0, so the same bits as summing from k = i). Lane i keeps its column T[.][i] in
|
||||
// registers, so a row needs only A's row t (a broadcast load a term) and A is never written: no store and no __syncwarp a row
|
||||
float tv[GCH];
|
||||
tv[0] = i == 0 ? 1.0f : 0.0f;
|
||||
#pragma unroll
|
||||
for (int t = 1; t < GCH; ++t) {
|
||||
float v = 0.0f;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < t; ++k) v = fmaf(-a[t * GTP + k], tv[k], v);
|
||||
tv[t] = i < t ? v : (i == t ? 1.0f : 0.0f);
|
||||
}
|
||||
// T's images x 2^et (its largest entry in [2^14, 2^15), as the scan scales its own operands)
|
||||
float mt4[4] = {};
|
||||
#pragma unroll
|
||||
for (int t = 0; t < GCH; ++t) mt4[t & 3] = fmaxf(mt4[t & 3], fabsf(tv[t]));
|
||||
const int et = gtc_scale_exp(gtc_warp_max(fmaxf(fmaxf(mt4[0], mt4[1]), fmaxf(mt4[2], mt4[3]))));
|
||||
const float sT = gtc_pow2(et);
|
||||
uint16_t* Th = ti + ((int64_t) ch * HV + vh) * 2 * GCH * GCH;
|
||||
uint16_t* Tl = Th + GCH * GCH;
|
||||
#pragma unroll
|
||||
for (int t = 0; t < GCH; ++t) {
|
||||
const float x = tv[t] * sT;
|
||||
const __half hi = __float2half_rn(x);
|
||||
Th[t * GCH + i] = __half_as_ushort(hi);
|
||||
Tl[t * GCH + i] = __half_as_ushort(__float2half_rn(x - __half2float(hi)));
|
||||
}
|
||||
if (i == 0) te[(int64_t) ch * HV + vh] = gtc_pow2(-et);
|
||||
}
|
||||
|
||||
// ---- the two scan entries. Arguments: state_in, state_out, h, ti, te, sc, kq, pi, oc_out, t0 (first token of the super-block), nch (its
|
||||
// chunks), T (tokens of the whole prompt chunk), witness.
|
||||
extern "C" __global__ void __launch_bounds__(GTC_CW * 32, 1) leleka_gdn_tc_scan_t1(
|
||||
const float* state_in, float* state_out, const float* h, const uint16_t* ti, const float* te, const float4* sc,
|
||||
const uint16_t* kq, const uint16_t* pi, float* oc_out, int64_t t0, int nch, int64_t T, unsigned* witness) {
|
||||
gtc_scan_body<1>(state_in, state_out, h, ti, te, sc, kq, pi, oc_out, t0, nch, T, witness);
|
||||
}
|
||||
extern "C" __global__ void __launch_bounds__(GTC_CW * 32, 1) leleka_gdn_tc_scan_t2(
|
||||
const float* state_in, float* state_out, const float* h, const uint16_t* ti, const float* te, const float4* sc,
|
||||
const uint16_t* kq, const uint16_t* pi, float* oc_out, int64_t t0, int nch, int64_t T, unsigned* witness) {
|
||||
gtc_scan_body<2>(state_in, state_out, h, ti, te, sc, kq, pi, oc_out, t0, nch, T, witness);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,299 @@
|
||||
//! Fixed asset `gdn_prefill_tc.cu` (EXPERIMENTAL, LOSSY, off by default): the prompt GDN recurrence as a chunked
|
||||
//! scan on the tensor cores, a port of Strata upstream `src/prefill/gdn_tc.cuh` (step-ledger row U1).
|
||||
//!
|
||||
//! This module is the host side that needs no device: the sealed PTX with its pin, the launch geometry, the scratch
|
||||
//! layout, the decision table "may this run take the tensor-core scan?" and the launch list of one prompt chunk. The
|
||||
//! device owner (`gdn_prompt_device`) loads the module, reads the device and executes the list.
|
||||
//!
|
||||
//! The scan is NOT bitwise equal to `leleka_prefill_gdn_rec_kh` (the reduction order changes; every product is an f16x3
|
||||
//! split on `mma.sync`). Whether it may ever be a default is decided by the lossy gate of docs/quality-gate.md.
|
||||
use crate::kar_decode_levels::{KarDecodeError, PtxPin, admit_ptx};
|
||||
use crate::ple_batch_ffi::{BatchArg, DeviceGeometry};
|
||||
use crate::{Error, Result, ffi::BufferHandle};
|
||||
use std::ffi::CStr;
|
||||
|
||||
/// The PTX plus the single ABI NUL, like every other fixed asset.
|
||||
pub(crate) static PTX: &[u8] = concat!(include_str!("gdn_prefill_tc.ptx"), "\0").as_bytes();
|
||||
/// Module entry order: the index passed to `KernelModule::launch_dynamic`.
|
||||
pub(crate) const ENTRIES: &[&CStr] = &[c"leleka_gdn_tc_prep", c"leleka_gdn_tc_scan_t1", c"leleka_gdn_tc_scan_t2"];
|
||||
const PREP: usize = 0;
|
||||
const SCAN_ONE_TILE: usize = 1;
|
||||
const SCAN_TWO_TILES: usize = 2;
|
||||
|
||||
/// Frozen by `scripts/gpu-bringup/reseal_own.py` after `compile_assets.py` (extra-seal-plan.json, group
|
||||
/// gdn-prefill-tc).
|
||||
pub(crate) const PIN: PtxPin = PtxPin {
|
||||
source_sha256: [
|
||||
140, 121, 176, 81, 97, 167, 229, 92, 123, 79, 111, 249, 182, 76, 245, 54, 123, 180, 179, 251, 37, 236, 33, 38,
|
||||
136, 203, 250, 118, 228, 111, 207, 65,
|
||||
],
|
||||
ptx_sha256: [
|
||||
84, 91, 216, 169, 217, 214, 20, 131, 163, 13, 60, 51, 198, 226, 196, 128, 60, 146, 243, 71, 219, 96, 55, 223,
|
||||
64, 7, 233, 68, 123, 153, 107, 33,
|
||||
],
|
||||
};
|
||||
pub(crate) fn admit() -> std::result::Result<(), KarDecodeError> {
|
||||
admit_ptx(PTX, &PIN)
|
||||
}
|
||||
|
||||
/// Tokens a chunk of the scan (the prep solves a lane per token).
|
||||
pub(crate) const CHUNK_TOKENS: usize = 32;
|
||||
/// Upstream `kGdnTcMin`: the prep and scan launches cost about 20 us, below this the sequential kernel wins.
|
||||
pub(crate) const MIN_TOKENS: usize = 128;
|
||||
const KEY_HEADS: usize = 16;
|
||||
const VALUE_HEADS: usize = 48;
|
||||
/// Dynamic shared memory of one scan block (`kTcScanSmemSplit`, the 99-KB plan) and of one prep block.
|
||||
pub(crate) const SCAN_SMEM: u32 = 97_808;
|
||||
pub(crate) const PREP_SMEM: u32 = 43_264;
|
||||
const PREP_THREADS: u32 = 256;
|
||||
/// Upstream `GSB / GCH`: chunks of one super-block at the frozen scratch of 60,305,408 bytes.
|
||||
pub(crate) const UPSTREAM_CHUNKS: usize = 64;
|
||||
/// Scratch bytes a chunk, in the order the kernels take them: T images, T scales, token scalars, k/q images, P images.
|
||||
const SCRATCH_PARTS: [usize; 5] = [
|
||||
VALUE_HEADS * 2 * CHUNK_TOKENS * CHUNK_TOKENS * 2,
|
||||
VALUE_HEADS * 4,
|
||||
VALUE_HEADS * CHUNK_TOKENS * 16,
|
||||
KEY_HEADS * 4 * CHUNK_TOKENS * 128 * 2,
|
||||
VALUE_HEADS * 2 * CHUNK_TOKENS * CHUNK_TOKENS * 2,
|
||||
];
|
||||
/// Scratch bytes a chunk (942,272).
|
||||
pub(crate) const SCRATCH_PER_CHUNK: usize =
|
||||
SCRATCH_PARTS[0] + SCRATCH_PARTS[1] + SCRATCH_PARTS[2] + SCRATCH_PARTS[3] + SCRATCH_PARTS[4];
|
||||
|
||||
/// Chunks of one super-block that a scratch of `bytes` holds, at most upstream's 64.
|
||||
pub(crate) fn chunks_fitting(bytes: usize) -> usize {
|
||||
(bytes / SCRATCH_PER_CHUNK).min(UPSTREAM_CHUNKS)
|
||||
}
|
||||
|
||||
/// Why a run does not take the scan; the device owner prints it once.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Refusal {
|
||||
NotRequested,
|
||||
/// The sealed image is sm_120: the compute capability major of the device is below 12.
|
||||
ComputeCapability(u32),
|
||||
/// Fewer multiprocessors than value heads: the scan would run in several waves.
|
||||
Multiprocessors(u32),
|
||||
/// The opt-in shared memory a block is below the plan's 97,808 bytes.
|
||||
SharedMemory(u32),
|
||||
/// The scratch holds no chunk.
|
||||
Scratch,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Refusal {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::NotRequested => write!(f, "not requested"),
|
||||
Self::ComputeCapability(major) => write!(f, "compute capability {major}.x, the sealed image is sm_120"),
|
||||
Self::Multiprocessors(n) => write!(f, "{n} multiprocessors, fewer than the {VALUE_HEADS} value heads"),
|
||||
Self::SharedMemory(n) => write!(f, "{n} bytes of shared memory a block, the plan needs {SCAN_SMEM}"),
|
||||
Self::Scratch => write!(f, "the scratch holds no chunk"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a device owner decided once: value tiles a head and chunks of a super-block.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct ScanPlan {
|
||||
tiles: u32,
|
||||
chunks: usize,
|
||||
}
|
||||
|
||||
/// The decision table. Upstream's runtime gate (compute capability >= 8, one multiprocessor per value head, shared
|
||||
/// memory) plus this repository's: the image is sealed for sm_120. Two value tiles a head on cards with at least
|
||||
/// twice as many multiprocessors as value heads (upstream 51567de1a: one wave of 96 blocks; an RTX A6000 with 84 SMs
|
||||
/// was 1.25x slower with two tiles, a card with 110 SMs 1.47x faster).
|
||||
pub(crate) fn plan(
|
||||
requested: bool,
|
||||
device: DeviceGeometry,
|
||||
scratch_bytes: usize,
|
||||
) -> std::result::Result<ScanPlan, Refusal> {
|
||||
if !requested {
|
||||
return Err(Refusal::NotRequested);
|
||||
}
|
||||
if device.cc_major < 12 {
|
||||
return Err(Refusal::ComputeCapability(device.cc_major));
|
||||
}
|
||||
if (device.multiprocessors as usize) < VALUE_HEADS {
|
||||
return Err(Refusal::Multiprocessors(device.multiprocessors));
|
||||
}
|
||||
if device.shared_optin < SCAN_SMEM {
|
||||
return Err(Refusal::SharedMemory(device.shared_optin));
|
||||
}
|
||||
let chunks = chunks_fitting(scratch_bytes);
|
||||
if chunks == 0 {
|
||||
return Err(Refusal::Scratch);
|
||||
}
|
||||
let tiles = if device.multiprocessors as usize >= 2 * VALUE_HEADS { 2 } else { 1 };
|
||||
Ok(ScanPlan { tiles, chunks })
|
||||
}
|
||||
|
||||
impl ScanPlan {
|
||||
/// Value tiles a head (1: 48 blocks of 256 threads, 2: 96 blocks of 128 threads).
|
||||
pub(crate) fn tiles(&self) -> u32 {
|
||||
self.tiles
|
||||
}
|
||||
/// Chunks of one super-block (the scratch holds this many).
|
||||
pub(crate) fn chunks(&self) -> usize {
|
||||
self.chunks
|
||||
}
|
||||
/// Per-run dispatch: a prompt chunk of `tokens` takes the scan from `MIN_TOKENS` on.
|
||||
pub(crate) fn takes(&self, tokens: usize) -> bool {
|
||||
tokens >= MIN_TOKENS
|
||||
}
|
||||
/// `(first token, chunks)` of every super-block of a run of `tokens`.
|
||||
pub(crate) fn super_blocks(&self, tokens: usize) -> Vec<(usize, usize)> {
|
||||
let span = self.chunks * CHUNK_TOKENS;
|
||||
(0..tokens.div_ceil(span)).map(|i| (i * span, (tokens - i * span).min(span).div_ceil(CHUNK_TOKENS))).collect()
|
||||
}
|
||||
/// Tests only: the same plan with `tiles` value tiles a head (1 or 2).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_tiles(self, tiles: u32) -> Self {
|
||||
Self { tiles, ..self }
|
||||
}
|
||||
/// Tests only: the same plan with super-blocks of `chunks` chunks (small values chain the state through many
|
||||
/// launches).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_chunks(self, chunks: usize) -> Self {
|
||||
Self { chunks, ..self }
|
||||
}
|
||||
fn scan_entry(&self) -> usize {
|
||||
if self.tiles == 2 { SCAN_TWO_TILES } else { SCAN_ONE_TILE }
|
||||
}
|
||||
/// `(grid, block)` of the scan launch.
|
||||
pub(crate) fn scan_shape(&self) -> (u32, u32) {
|
||||
let heads = VALUE_HEADS as u32;
|
||||
if self.tiles == 2 { (heads * 2, 128) } else { (heads, 256) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The buffers of one run: the recurrence's own interface (as `leleka_prefill_gdn_rec_kh`) and the scratch.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct RecurrenceIo {
|
||||
pub(crate) state_in: BufferHandle,
|
||||
pub(crate) state_out: BufferHandle,
|
||||
pub(crate) h: BufferHandle,
|
||||
pub(crate) gate: BufferHandle,
|
||||
pub(crate) beta: BufferHandle,
|
||||
pub(crate) y: BufferHandle,
|
||||
pub(crate) witness: BufferHandle,
|
||||
pub(crate) scratch: BufferHandle,
|
||||
}
|
||||
|
||||
/// One kernel launch of the list: module entry, grid and block (1-D), dynamic shared memory and arguments.
|
||||
pub(crate) struct TcLaunch {
|
||||
pub(crate) entry: usize,
|
||||
pub(crate) grid: u32,
|
||||
pub(crate) block: u32,
|
||||
pub(crate) smem: u32,
|
||||
pub(crate) args: Vec<BatchArg>,
|
||||
}
|
||||
|
||||
/// The five sub-buffers of the scratch, `chunks` chunks each.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Scratch {
|
||||
ti: BufferHandle,
|
||||
te: BufferHandle,
|
||||
sc: BufferHandle,
|
||||
kq: BufferHandle,
|
||||
pi: BufferHandle,
|
||||
}
|
||||
|
||||
impl Scratch {
|
||||
/// Carves a scratch allocation of `len` bytes starting at `base`.
|
||||
fn carve(base: BufferHandle, len: usize, chunks: usize) -> Result<Self> {
|
||||
let mut offset = 0;
|
||||
let mut parts = [base; 5];
|
||||
for (part, bytes) in parts.iter_mut().zip(SCRATCH_PARTS) {
|
||||
let bytes = bytes * chunks;
|
||||
*part = base.checked_subspan(len, offset, bytes)?;
|
||||
offset += bytes;
|
||||
}
|
||||
let [ti, te, sc, kq, pi] = parts;
|
||||
Ok(Self { ti, te, sc, kq, pi })
|
||||
}
|
||||
}
|
||||
|
||||
/// One super-block: first token, chunks, and the tokens of the whole run.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Block {
|
||||
t0: i64,
|
||||
chunks: i32,
|
||||
tokens: i64,
|
||||
}
|
||||
|
||||
fn prep_launch(io: &RecurrenceIo, s: &Scratch, b: Block) -> TcLaunch {
|
||||
let a = BatchArg::Address;
|
||||
TcLaunch {
|
||||
entry: PREP,
|
||||
grid: b.chunks as u32 * KEY_HEADS as u32,
|
||||
block: PREP_THREADS,
|
||||
smem: PREP_SMEM,
|
||||
args: vec![
|
||||
a(io.h),
|
||||
a(io.gate),
|
||||
a(io.beta),
|
||||
a(s.ti),
|
||||
a(s.te),
|
||||
a(s.sc),
|
||||
a(s.kq),
|
||||
a(s.pi),
|
||||
BatchArg::I64(b.t0),
|
||||
BatchArg::I64(b.tokens),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
fn scan_launch(plan: &ScanPlan, (io, s): (&RecurrenceIo, &Scratch), (state_in, b): (BufferHandle, Block)) -> TcLaunch {
|
||||
let a = BatchArg::Address;
|
||||
let (grid, block) = plan.scan_shape();
|
||||
TcLaunch {
|
||||
entry: plan.scan_entry(),
|
||||
grid,
|
||||
block,
|
||||
smem: SCAN_SMEM,
|
||||
args: vec![
|
||||
a(state_in),
|
||||
a(io.state_out),
|
||||
a(io.h),
|
||||
a(s.ti),
|
||||
a(s.te),
|
||||
a(s.sc),
|
||||
a(s.kq),
|
||||
a(s.pi),
|
||||
a(io.y),
|
||||
BatchArg::I64(b.t0),
|
||||
BatchArg::I32(b.chunks),
|
||||
BatchArg::I64(b.tokens),
|
||||
a(io.witness),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/// The launches of one prompt chunk of `tokens` tokens (the caller asks `ScanPlan::takes` first; the kernels
|
||||
/// themselves run any `tokens >= 1`, which the parity test uses): per super-block the prep and the scan, in stream
|
||||
/// order. The first scan reads `state_in`, the later ones the `state_out` the scan before wrote (in place: a block
|
||||
/// reads and writes only its own columns). The witness word is raised by every scan whose final state is not finite.
|
||||
pub(crate) fn launches(
|
||||
plan: &ScanPlan,
|
||||
io: &RecurrenceIo,
|
||||
(scratch_len, tokens): (usize, usize),
|
||||
) -> Result<Vec<TcLaunch>> {
|
||||
if tokens == 0 || scratch_len < SCRATCH_PER_CHUNK * plan.chunks {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let scratch = Scratch::carve(io.scratch, scratch_len, plan.chunks)?;
|
||||
let blocks = plan.super_blocks(tokens);
|
||||
let mut list = Vec::new();
|
||||
list.try_reserve_exact(2 * blocks.len()).map_err(|_| Error::HostAllocation)?;
|
||||
for (index, (t0, chunks)) in blocks.into_iter().enumerate() {
|
||||
let b = Block { t0: t0 as i64, chunks: chunks as i32, tokens: tokens as i64 };
|
||||
list.push(prep_launch(io, &scratch, b));
|
||||
let from = if index == 0 { io.state_in } else { io.state_out };
|
||||
list.push(scan_launch(plan, (io, &scratch), (from, b)));
|
||||
}
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "gdn_prefill_tc_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,201 @@
|
||||
//! Host tests of `gdn_prefill_tc`: layout, launch parameters, the dispatch decision table and the launch list.
|
||||
//! No device.
|
||||
use super::*;
|
||||
|
||||
fn device(cc_major: u32, multiprocessors: u32, shared_optin: u32) -> DeviceGeometry {
|
||||
DeviceGeometry { cc_major, multiprocessors, shared_optin }
|
||||
}
|
||||
/// The RTX 5090: compute capability 12.0, 170 SMs, 101,376 bytes of opt-in shared memory a block.
|
||||
const RTX_5090: DeviceGeometry = DeviceGeometry { cc_major: 12, multiprocessors: 170, shared_optin: 101_376 };
|
||||
/// The prompt device's dequantization scratch the scan runs in.
|
||||
const SCRATCH: usize = 52_428_800;
|
||||
|
||||
fn handle(address: u64) -> BufferHandle {
|
||||
BufferHandle::synthetic(address)
|
||||
}
|
||||
fn io() -> RecurrenceIo {
|
||||
let [state_in, state_out, h, gate, beta, y, witness, scratch] =
|
||||
[0x1000u64, 0x2000, 0x3000, 0x4000, 0x5000, 0x6000, 0x7000, 0x1_0000_0000].map(handle);
|
||||
RecurrenceIo { state_in, state_out, h, gate, beta, y, witness, scratch }
|
||||
}
|
||||
fn address(arg: &BatchArg) -> u64 {
|
||||
match arg {
|
||||
BatchArg::Address(h) => h.qwen_address(),
|
||||
_ => panic!("not an address"),
|
||||
}
|
||||
}
|
||||
fn int(arg: &BatchArg) -> i64 {
|
||||
match arg {
|
||||
BatchArg::I64(x) => *x,
|
||||
BatchArg::I32(x) => i64::from(*x),
|
||||
_ => panic!("not an integer"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_shared_memory_and_scratch_plans_are_the_frozen_ones() {
|
||||
// kTcScanSmemSplit: 2 (4 GCH KP 2 + GCH 16) + GCH VP 4 + 4 GCH PP 2 + 16,
|
||||
// with KP = 136, VP = 132, PP = 40, GCH = 32
|
||||
assert_eq!(2 * (4 * 32 * 136 * 2 + 32 * 16) + 32 * 132 * 4 + 4 * 32 * 40 * 2 + 16, SCAN_SMEM as usize);
|
||||
assert_eq!(4 * 32 * 136 * 2 + 2 * 32 * 33 * 4, PREP_SMEM as usize);
|
||||
// the 99-KB opt-in of sm_86 / sm_89 / sm_120 holds the scan
|
||||
const { assert!(SCAN_SMEM <= 101_376 && PREP_SMEM <= 48 * 1024) };
|
||||
assert_eq!(SCRATCH_PER_CHUNK, 942_272);
|
||||
assert_eq!(SCRATCH_PER_CHUNK * UPSTREAM_CHUNKS, 60_305_408, "upstream's frozen scratch for HV 48 / HK 16");
|
||||
// cp.async copies 16-byte pieces: every part starts on a 16-byte boundary for any chunk count (the 4-byte scales
|
||||
// are 192 bytes a chunk)
|
||||
for chunks in 1..=UPSTREAM_CHUNKS {
|
||||
let mut offset = 0;
|
||||
for (i, bytes) in SCRATCH_PARTS.iter().enumerate() {
|
||||
assert_eq!(offset % 16, 0, "part {i} at {offset} with {chunks} chunks");
|
||||
offset += bytes * chunks;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_source_names_the_same_plans() {
|
||||
let source = include_str!("gdn_prefill_tc.cu");
|
||||
for needle in
|
||||
["kTcScanSmemSplit == 97808", "kTcPrepSmem == 43264", "constexpr int S = 128, HK = 16, HV = 48, C = 10240"]
|
||||
{
|
||||
assert!(source.contains(needle), "gdn_prefill_tc.cu lacks {needle:?}");
|
||||
}
|
||||
for entry in ENTRIES {
|
||||
let name = entry.to_str().expect("ascii");
|
||||
assert!(source.contains(name), "gdn_prefill_tc.cu lacks the entry {name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_dequantization_scratch_holds_55_chunks_so_the_scan_costs_no_extra_memory() {
|
||||
assert_eq!(chunks_fitting(SCRATCH), 55);
|
||||
assert_eq!(chunks_fitting(60_305_408), UPSTREAM_CHUNKS);
|
||||
assert_eq!(chunks_fitting(2 * 60_305_408), UPSTREAM_CHUNKS);
|
||||
assert_eq!(chunks_fitting(SCRATCH_PER_CHUNK - 1), 0);
|
||||
const { assert!(55 * SCRATCH_PER_CHUNK <= SCRATCH && 56 * SCRATCH_PER_CHUNK > SCRATCH) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_decision_table_refuses_every_card_the_plan_does_not_fit() {
|
||||
let plan_of = |d, bytes| plan(true, d, bytes);
|
||||
assert_eq!(plan(false, RTX_5090, SCRATCH), Err(Refusal::NotRequested), "off unless asked");
|
||||
assert_eq!(
|
||||
plan_of(device(8, 170, 101_376), SCRATCH),
|
||||
Err(Refusal::ComputeCapability(8)),
|
||||
"sm_86 has no companion image"
|
||||
);
|
||||
assert_eq!(plan_of(device(11, 170, 101_376), SCRATCH), Err(Refusal::ComputeCapability(11)));
|
||||
assert_eq!(
|
||||
plan_of(device(12, 47, 101_376), SCRATCH),
|
||||
Err(Refusal::Multiprocessors(47)),
|
||||
"fewer SMs than value heads"
|
||||
);
|
||||
assert_eq!(plan_of(device(12, 170, SCAN_SMEM - 1), SCRATCH), Err(Refusal::SharedMemory(SCAN_SMEM - 1)));
|
||||
assert_eq!(plan_of(device(12, 170, 48 * 1024), SCRATCH), Err(Refusal::SharedMemory(48 * 1024)), "no opt-in");
|
||||
assert_eq!(plan_of(RTX_5090, SCRATCH_PER_CHUNK - 1), Err(Refusal::Scratch));
|
||||
assert!(plan_of(device(12, 48, SCAN_SMEM), SCRATCH).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_value_tiles_a_head_from_96_multiprocessors() {
|
||||
let tiles = |sms| plan(true, device(12, sms, 101_376), SCRATCH).expect("plan").tiles();
|
||||
assert_eq!([tiles(48), tiles(84), tiles(95), tiles(96), tiles(110), tiles(170)], [1, 1, 1, 2, 2, 2]);
|
||||
let five_thousand_ninety = plan(true, RTX_5090, SCRATCH).expect("plan");
|
||||
assert_eq!((five_thousand_ninety.tiles(), five_thousand_ninety.chunks()), (2, 55));
|
||||
assert_eq!(five_thousand_ninety.scan_shape(), (96, 128), "96 blocks of 4 warps, one wave on 170 SMs");
|
||||
assert_eq!(plan(true, device(12, 84, 101_376), SCRATCH).expect("plan").scan_shape(), (48, 256));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_takes_the_scan_from_128_tokens_and_walks_super_blocks_of_the_scratch() {
|
||||
let p = plan(true, RTX_5090, SCRATCH).expect("plan");
|
||||
assert!(!p.takes(1) && !p.takes(127) && p.takes(128) && p.takes(8192));
|
||||
assert_eq!(p.super_blocks(128), [(0, 4)]);
|
||||
assert_eq!(p.super_blocks(129), [(0, 5)], "a partial chunk is a chunk");
|
||||
assert_eq!(p.super_blocks(1760), [(0, 55)]);
|
||||
assert_eq!(p.super_blocks(1761), [(0, 55), (1760, 1)]);
|
||||
let all = p.super_blocks(8192);
|
||||
assert_eq!(all.len(), 5);
|
||||
assert_eq!(all.iter().map(|b| b.1).sum::<usize>(), 256, "8192 tokens are 256 chunks");
|
||||
assert_eq!(all[4], (7040, 36));
|
||||
for t in [128usize, 200, 1759, 1760, 1761, 3520, 3521, 4099, 8191, 8192] {
|
||||
let blocks = p.super_blocks(t);
|
||||
assert_eq!(blocks[0].0, 0);
|
||||
for pair in blocks.windows(2) {
|
||||
assert_eq!(pair[1].0, pair[0].0 + pair[0].1 * CHUNK_TOKENS, "t={t}: contiguous");
|
||||
}
|
||||
let (last_t0, last) = *blocks.last().unwrap();
|
||||
assert!(last_t0 < t && last_t0 + last * CHUNK_TOKENS >= t && last_t0 + (last - 1) * CHUNK_TOKENS < t, "t={t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launch_list_orders_prep_and_scan_and_chains_the_state() {
|
||||
let p = plan(true, RTX_5090, SCRATCH).expect("plan");
|
||||
let io = io();
|
||||
let list = launches(&p, &io, (SCRATCH, 8192)).expect("launches");
|
||||
assert_eq!(list.len(), 10, "a prep and a scan for each of the 5 super-blocks");
|
||||
for (i, pair) in list.chunks(2).enumerate() {
|
||||
let (prep, scan) = (&pair[0], &pair[1]);
|
||||
assert_eq!((prep.entry, prep.block, prep.smem, prep.args.len()), (0, 256, PREP_SMEM, 10));
|
||||
assert_eq!(prep.grid as usize, [55, 55, 55, 55, 36][i] * 16, "a block a (chunk, key head)");
|
||||
assert_eq!((scan.entry, scan.grid, scan.block, scan.smem, scan.args.len()), (2, 96, 128, SCAN_SMEM, 13));
|
||||
// state: the first scan reads the prior state, the others what the scan before wrote; all write state_out
|
||||
assert_eq!(address(&scan.args[0]), if i == 0 { 0x1000 } else { 0x2000 });
|
||||
assert_eq!(address(&scan.args[1]), 0x2000);
|
||||
assert_eq!(int(&scan.args[9]), (i * 1760) as i64, "first token of the super-block");
|
||||
assert_eq!(int(&scan.args[10]), [55, 55, 55, 55, 36][i]);
|
||||
assert_eq!(int(&scan.args[11]), 8192, "tokens of the whole run");
|
||||
assert_eq!(address(&scan.args[12]), 0x7000, "the state witness word");
|
||||
assert_eq!(address(&scan.args[8]), 0x6000, "the readout buffer");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launch_list_stays_inside_the_scratch_and_refuses_what_does_not_fit() {
|
||||
let p = plan(true, RTX_5090, SCRATCH).expect("plan");
|
||||
let io = io();
|
||||
let list = launches(&p, &io, (SCRATCH, 4096)).expect("launches");
|
||||
let base = 0x1_0000_0000u64;
|
||||
let mut parts: Vec<(u64, usize)> = list[0].args[3..8].iter().map(address).map(|a| (a, 0)).collect();
|
||||
parts.iter_mut().zip(SCRATCH_PARTS).for_each(|(p, bytes)| p.1 = bytes * 55);
|
||||
assert_eq!(parts[0].0, base, "T images first");
|
||||
for pair in parts.windows(2) {
|
||||
assert_eq!(pair[1].0, pair[0].0 + pair[0].1 as u64, "parts follow each other");
|
||||
}
|
||||
let end = parts[4].0 + parts[4].1 as u64;
|
||||
assert!(end - base <= SCRATCH as u64, "the five parts end at {} of {SCRATCH}", end - base);
|
||||
assert!(launches(&p, &io, (SCRATCH, 0)).is_err(), "an empty run launches nothing");
|
||||
assert_eq!(
|
||||
launches(&p, &io, (SCRATCH, 1)).expect("one token").len(),
|
||||
2,
|
||||
"the kernels run any length; takes() is the dispatch"
|
||||
);
|
||||
assert!(launches(&p, &io, (SCRATCH - 1_000_000, 4096)).is_err(), "a scratch shorter than the plan's chunks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sealed_image_is_pinned_and_exports_the_three_entries() {
|
||||
assert!(admit().is_ok(), "gdn_prefill_tc.ptx must match PIN (scripts/gpu-bringup/reseal_own.py)");
|
||||
let ptx = std::str::from_utf8(&PTX[..PTX.len() - 1]).expect("ascii");
|
||||
assert!(ptx.lines().any(|l| l == ".target sm_120") && ptx.lines().any(|l| l == ".address_size 64"));
|
||||
for entry in ENTRIES {
|
||||
let name = entry.to_str().expect("ascii");
|
||||
assert!(ptx.contains(&format!(".visible .entry {name}(")), "{name}");
|
||||
}
|
||||
assert_eq!(ptx.matches(".entry ").count(), ENTRIES.len(), "no other kernel in the asset");
|
||||
assert!(!ptx.contains("UNSEALED"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_super_blocks_chain_the_state_through_state_out() {
|
||||
let p = plan(true, RTX_5090, SCRATCH).expect("plan").with_chunks(3).with_tiles(1);
|
||||
assert_eq!(p.super_blocks(200), [(0, 3), (96, 3), (192, 1)]);
|
||||
let list = launches(&p, &io(), (SCRATCH, 200)).expect("launches");
|
||||
let scans: Vec<_> = list.iter().filter(|l| l.entry == 1).collect();
|
||||
assert_eq!(scans.len(), 3);
|
||||
assert_eq!(scans.iter().map(|l| (l.grid, l.block)).collect::<Vec<_>>(), [(48, 256); 3]);
|
||||
assert_eq!(scans.iter().map(|l| address(&l.args[0])).collect::<Vec<_>>(), [0x1000, 0x2000, 0x2000]);
|
||||
assert!(scans.iter().all(|l| address(&l.args[1]) == 0x2000), "every scan writes state_out");
|
||||
}
|
||||
@@ -18,8 +18,21 @@ pub struct OriginalGdnPromptDevice<'ctx> {
|
||||
history: [Option<DeviceBuffer<'ctx>>; 2],
|
||||
/// `prefill_stage.cu`: element-parallel weight dequantization and the kernels with their guards folded in.
|
||||
stage: Option<KernelModule>,
|
||||
options: GdnPromptOptions,
|
||||
/// The EXPERIMENTAL tensor-core scan of the recurrence (`gdn_prefill_tc.cu`): off unless `options` ask, decided
|
||||
/// once.
|
||||
tensor_core: TensorCoreState,
|
||||
failed: bool,
|
||||
}
|
||||
/// What the operator chose for the prompt GDN device. Every field is off by default.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct GdnPromptOptions {
|
||||
/// `LELEKA_PREFILL_GDN_TC` (EXPERIMENTAL, LOSSY): runs of 128 tokens and more take the chunked tensor-core scan
|
||||
/// of the recurrence when the device fits it (sm_120, 48 or more SMs, 97,808 bytes of shared memory a block);
|
||||
/// anything else keeps the sequential kernel. Not bitwise equal to it; the lossy gate of docs/quality-gate.md
|
||||
/// decides.
|
||||
pub tensor_core_scan: bool,
|
||||
}
|
||||
/// Actual complete role owners; source/row/current prior are authenticated by runtime.
|
||||
pub struct OriginalGdnPromptWeights<'w, 'ctx> {
|
||||
pub matrices: [&'w DeviceBuffer<'ctx>; 5], // QKV,Z,Out,Alpha,Beta
|
||||
@@ -57,6 +70,14 @@ enum DeviceCommand {
|
||||
block: u32,
|
||||
args: KernelArguments,
|
||||
},
|
||||
/// A kernel of the experimental tensor-core scan module (1-D grid, dynamic shared memory).
|
||||
TensorCore {
|
||||
entry: usize,
|
||||
grid: u32,
|
||||
block: u32,
|
||||
smem: u32,
|
||||
args: KernelArguments,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -67,5 +88,6 @@ mod stage_gpu_tests;
|
||||
mod context;
|
||||
#[path = "gdn_prompt_device/original_gdn_prompt_device.rs"]
|
||||
mod original_gdn_prompt_device;
|
||||
use original_gdn_prompt_device::TensorCoreState;
|
||||
#[path = "gdn_prompt_device/original_gdn_prompt_device_drop.rs"]
|
||||
mod original_gdn_prompt_device_drop;
|
||||
|
||||
@@ -9,6 +9,15 @@ impl<'ctx> Context<'ctx> {
|
||||
capacity: usize,
|
||||
profile: crate::GrNativeProfile,
|
||||
) -> Result<OriginalGdnPromptDevice<'ctx>> {
|
||||
OriginalGdnPromptDevice::new(self, capacity, profile)
|
||||
self.original_gdn_prompt_device_with(capacity, profile, GdnPromptOptions::default())
|
||||
}
|
||||
/// `original_gdn_prompt_device` with the operator's options (all off by default).
|
||||
pub fn original_gdn_prompt_device_with(
|
||||
&'ctx self,
|
||||
capacity: usize,
|
||||
profile: crate::GrNativeProfile,
|
||||
options: GdnPromptOptions,
|
||||
) -> Result<OriginalGdnPromptDevice<'ctx>> {
|
||||
OriginalGdnPromptDevice::new(self, (capacity, profile), options)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,5 +15,8 @@ mod original_gdn_prompt_device_drain;
|
||||
mod prompt_block_produce;
|
||||
#[path = "original_gdn_prompt_device/prompt_command_list.rs"]
|
||||
mod prompt_command_list;
|
||||
#[path = "original_gdn_prompt_device/prompt_tensor_core_scan.rs"]
|
||||
mod prompt_tensor_core_scan;
|
||||
#[allow(unused_imports)]
|
||||
use gdn_prompt_run_buffer_binder::{Binder, Carve, Carved, Handles, Phase};
|
||||
pub(super) use prompt_tensor_core_scan::TensorCoreState;
|
||||
|
||||
+4
-2
@@ -12,8 +12,8 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
}
|
||||
pub(in super::super) fn new(
|
||||
context: &'ctx Context<'ctx>,
|
||||
capacity: usize,
|
||||
profile: crate::GrNativeProfile,
|
||||
(capacity, profile): (usize, crate::GrNativeProfile),
|
||||
options: GdnPromptOptions,
|
||||
) -> Result<Self> {
|
||||
Self::admit_budget(context, capacity)?;
|
||||
let mut owner = Self {
|
||||
@@ -24,6 +24,8 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
scratch: None,
|
||||
history: [None, None],
|
||||
stage: None,
|
||||
options,
|
||||
tensor_core: TensorCoreState::new(options.tensor_core_scan),
|
||||
failed: false,
|
||||
};
|
||||
let operation = owner.open();
|
||||
|
||||
+2
-1
@@ -26,6 +26,7 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
if let Some(m) = self.stage.take() {
|
||||
result = combine(result, self.release_stage(m));
|
||||
}
|
||||
result = combine(result, self.release_tensor_core());
|
||||
if let Some(b) = self.batch.take() {
|
||||
result = combine(result, self.release_batch(b));
|
||||
}
|
||||
@@ -35,7 +36,7 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
}
|
||||
result
|
||||
}
|
||||
fn release_stage(&self, m: KernelModule) -> Result<()> {
|
||||
pub(super) fn release_stage(&self, m: KernelModule) -> Result<()> {
|
||||
if self.context.is_poisoned() {
|
||||
std::mem::forget(m);
|
||||
return Err(Error::ContextPoisoned);
|
||||
|
||||
+5
-1
@@ -40,6 +40,7 @@ fn command_label(cmd: &DeviceCommand) -> &'static str {
|
||||
DeviceCommand::Kernel { .. } => "kernel",
|
||||
DeviceCommand::Gemm { .. } => "gemm",
|
||||
DeviceCommand::Stage { .. } => "stage",
|
||||
DeviceCommand::TensorCore { .. } => "tensor-core",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +57,7 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
let host = self.execute(workspace, (commands, host), run)?;
|
||||
self.decode_run(host)
|
||||
}
|
||||
fn fail_context(&mut self) {
|
||||
pub(super) fn fail_context(&mut self) {
|
||||
self.failed = true;
|
||||
self.context.poison();
|
||||
self.context.retain_driver();
|
||||
@@ -172,6 +173,9 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
Some(module) => module.launch(*index, LinearLaunch::new(*grid, *block, blas.stream()), args),
|
||||
None => Err(Error::ContextPoisoned),
|
||||
},
|
||||
DeviceCommand::TensorCore { entry, grid, block, smem, args } => {
|
||||
self.launch_tensor_core(blas, (*entry, *grid, *block, *smem), args)
|
||||
}
|
||||
}
|
||||
}
|
||||
fn read_back(&self, hd: &Handles, host: &mut Host) -> Result<()> {
|
||||
|
||||
+1
@@ -19,6 +19,7 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
let t = read.rows();
|
||||
self.admit(&read, workspace, history)?;
|
||||
let handles = self.admit_handles(read.lease(), (workspace, t), &weights, (state, next_state))?;
|
||||
self.prepare_tensor_core()?;
|
||||
let commands = self.build_commands(&handles, weights.formats, t)?;
|
||||
let values = self.drain(workspace, commands, history, (&handles, t))?;
|
||||
Ok((read.from_completed_block(), values))
|
||||
|
||||
+47
-7
@@ -3,6 +3,7 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::gdn_prefill_tc as tc;
|
||||
|
||||
/// The commands of one run under construction.
|
||||
struct Cmds<'f, 'ctx> {
|
||||
@@ -14,6 +15,8 @@ struct Cmds<'f, 'ctx> {
|
||||
/// its FP16 image ride on the kernels that read or write those tensors (same status words).
|
||||
fused: bool,
|
||||
fast_dequant: bool,
|
||||
/// The experimental tensor-core scan of the recurrence, when the device owner admitted it.
|
||||
tensor_core: Option<tc::ScanPlan>,
|
||||
list: Vec<DeviceCommand>,
|
||||
}
|
||||
|
||||
@@ -44,10 +47,11 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
t: usize,
|
||||
) -> Result<Vec<DeviceCommand>> {
|
||||
let mut list = Vec::new();
|
||||
list.try_reserve_exact(48).map_err(|_| Error::HostAllocation)?;
|
||||
list.try_reserve_exact(64).map_err(|_| Error::HostAllocation)?;
|
||||
let funcs = self.batch.as_ref().ok_or(Error::ContextPoisoned)?.functions.as_ref();
|
||||
let funcs = funcs.ok_or(Error::ContextPoisoned)?;
|
||||
let mut c = Cmds::new(funcs, self.context, (*hd, t), list);
|
||||
c.tensor_core = self.tensor_core.plan();
|
||||
c.begin()?;
|
||||
c.projections(formats)?;
|
||||
c.gates()?;
|
||||
@@ -67,7 +71,8 @@ impl<'f, 'ctx> Cmds<'f, 'ctx> {
|
||||
) -> Self {
|
||||
let (hd, t) = run;
|
||||
let fused = crate::prefill_stage::fused_scans() && t > 64;
|
||||
Self { funcs, context, hd, t, fused, fast_dequant: crate::prefill_stage::fast_dequant(), list }
|
||||
let fast_dequant = crate::prefill_stage::fast_dequant();
|
||||
Self { funcs, context, hd, t, fused, fast_dequant, tensor_core: None, list }
|
||||
}
|
||||
fn kernel(&mut self, kernel: Kernel, geometry: ([u32; 3], [u32; 3]), args: &[ffi::KernelArg]) -> Result<()> {
|
||||
self.list.push(DeviceCommand::Kernel {
|
||||
@@ -260,16 +265,51 @@ impl<'f, 'ctx> Cmds<'f, 'ctx> {
|
||||
self.kernel(Kernel::L2, ([32, t as u32, 1], [128, 1, 1]), &args)?;
|
||||
self.scan(GdnBatchStage::Qk, h)
|
||||
}
|
||||
/// The state recurrence: the staged kernel when requested or usable, the original pipe kernel otherwise.
|
||||
/// The state recurrence: the experimental tensor-core scan when the device admitted it and the run is long
|
||||
/// enough, else the sequential kernels.
|
||||
fn recurrence(&mut self) -> Result<()> {
|
||||
let witness = self.word(GdnBatchStage::StateSteps)?;
|
||||
if crate::prefill_stage::fast_rec() || crate::prefill_stage::gdn_kh_usable(self.context) {
|
||||
self.recurrence_staged(witness);
|
||||
} else {
|
||||
self.recurrence_pipe(witness)?;
|
||||
if !self.recurrence_tensor_core(witness)? {
|
||||
self.recurrence_sequential(witness)?;
|
||||
}
|
||||
self.scan(GdnBatchStage::NextState, self.hd.sout)
|
||||
}
|
||||
/// The token-serial recurrence: the staged kernel when requested or usable, the original pipe kernel otherwise.
|
||||
fn recurrence_sequential(&mut self, witness: ffi::BufferHandle) -> Result<()> {
|
||||
if crate::prefill_stage::fast_rec() || crate::prefill_stage::gdn_kh_usable(self.context) {
|
||||
self.recurrence_staged(witness);
|
||||
Ok(())
|
||||
} else {
|
||||
self.recurrence_pipe(witness)
|
||||
}
|
||||
}
|
||||
/// `LELEKA_PREFILL_GDN_TC` (EXPERIMENTAL, LOSSY): the prep and scan launches of every super-block of the run, same
|
||||
/// interface as the kernels they replace (state in/out, readout `y`, the state witness). False: not taken.
|
||||
fn recurrence_tensor_core(&mut self, witness: ffi::BufferHandle) -> Result<bool> {
|
||||
let Some(plan) = self.tensor_core.filter(|p| p.takes(self.t)) else { return Ok(false) };
|
||||
let (hd, p) = (self.hd, self.hd.c.p);
|
||||
let io = tc::RecurrenceIo {
|
||||
state_in: hd.sin,
|
||||
state_out: hd.sout,
|
||||
h: p.h,
|
||||
gate: p.gate,
|
||||
beta: p.beta,
|
||||
y: p.y,
|
||||
witness,
|
||||
scratch: hd.scratch,
|
||||
};
|
||||
for l in tc::launches(&plan, &io, (SCRATCH, self.t))? {
|
||||
let args = KernelArguments::new(l.args);
|
||||
self.list.push(DeviceCommand::TensorCore {
|
||||
entry: l.entry,
|
||||
grid: l.grid,
|
||||
block: l.block,
|
||||
smem: l.smem,
|
||||
args,
|
||||
});
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
fn recurrence_staged(&mut self, witness: ffi::BufferHandle) {
|
||||
let kh = !crate::prefill_stage::fast_rec();
|
||||
let index = if kh { crate::prefill_stage::GDN_REC_KH } else { crate::prefill_stage::GDN_REC };
|
||||
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
//! The EXPERIMENTAL tensor-core scan of the prompt GDN recurrence, device-owner side (`LELEKA_PREFILL_GDN_TC`, off
|
||||
//! by default; kernels and launch list: `gdn_prefill_tc.rs` / `gdn_prefill_tc.cu`, ledger row U1). It loads the
|
||||
//! sealed module once, reads the device, and decides once whether this device takes the scan. Nothing here
|
||||
//! allocates: the scan runs in the dequantization scratch the owner already holds, which is idle during the
|
||||
//! recurrence (every command of a run is on one stream; the projections' dequantization wrote it before and the
|
||||
//! output projection's rewrites it after), so it costs no device memory and the prefill budget is unchanged.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::gdn_prefill_tc as tc;
|
||||
use crate::ple_batch_ffi::LinearLaunch;
|
||||
|
||||
/// The loaded module and the plan the device admitted.
|
||||
pub(in super::super) struct TensorCoreScan {
|
||||
pub(super) module: KernelModule,
|
||||
pub(super) plan: tc::ScanPlan,
|
||||
}
|
||||
|
||||
/// `Off` until asked for; `Pending` until the first run decides; then `Ready` or `Refused` for good.
|
||||
pub(in super::super) enum TensorCoreState {
|
||||
Off,
|
||||
Pending,
|
||||
Ready(TensorCoreScan),
|
||||
Refused,
|
||||
}
|
||||
|
||||
impl TensorCoreState {
|
||||
pub(in super::super) fn new(requested: bool) -> Self {
|
||||
if requested { Self::Pending } else { Self::Off }
|
||||
}
|
||||
/// The plan of the scan when this device runs it.
|
||||
pub(super) fn plan(&self) -> Option<tc::ScanPlan> {
|
||||
match self {
|
||||
Self::Ready(scan) => Some(scan.plan),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
/// Decides once, before the first command list of the device is recorded. A device that does not fit the scan
|
||||
/// (or a module that does not load) keeps the sequential kernel and says so once on stderr; only a context
|
||||
/// failure is an error.
|
||||
pub(in super::super) fn prepare_tensor_core(&mut self) -> Result<()> {
|
||||
if !matches!(self.tensor_core, TensorCoreState::Pending) {
|
||||
return Ok(());
|
||||
}
|
||||
let guard = self.context.enter()?;
|
||||
let probed = combine(Self::probe_tensor_core(), guard.finish());
|
||||
if probed.is_err() {
|
||||
self.fail_context();
|
||||
}
|
||||
self.tensor_core = match probed? {
|
||||
Ok(scan) => {
|
||||
Self::say_tensor_core_taken(&scan.plan);
|
||||
TensorCoreState::Ready(scan)
|
||||
}
|
||||
Err(why) => {
|
||||
eprintln!("leleka: LELEKA_PREFILL_GDN_TC=1 requested, the sequential GDN recurrence stays: {why}");
|
||||
TensorCoreState::Refused
|
||||
}
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
fn say_tensor_core_taken(plan: &tc::ScanPlan) {
|
||||
eprintln!(
|
||||
"leleka: LELEKA_PREFILL_GDN_TC=1 (EXPERIMENTAL, LOSSY): the prompt GDN recurrence of runs of {} tokens \
|
||||
and more runs on the tensor cores ({} value tile(s) a head, {} chunks of {} tokens a super-block)",
|
||||
tc::MIN_TOKENS,
|
||||
plan.tiles(),
|
||||
plan.chunks(),
|
||||
tc::CHUNK_TOKENS
|
||||
);
|
||||
}
|
||||
/// Loads the module and reads the device (the context is current). `Err(reason)` inside is a refusal, not a
|
||||
/// failure.
|
||||
fn probe_tensor_core() -> Result<std::result::Result<TensorCoreScan, String>> {
|
||||
if let Err(e) = tc::admit() {
|
||||
return Ok(Err(format!("the sealed PTX does not match its pin ({e:?})")));
|
||||
}
|
||||
let module = match KernelModule::load(tc::PTX, tc::ENTRIES) {
|
||||
Ok(m) => m,
|
||||
Err(e) => return Ok(Err(format!("the module does not load on this device ({e:?})"))),
|
||||
};
|
||||
let geometry = module.device_geometry()?;
|
||||
Ok(match tc::plan(true, geometry, SCRATCH) {
|
||||
Ok(plan) => Ok(TensorCoreScan { module, plan }),
|
||||
Err(refusal) => {
|
||||
module.close()?;
|
||||
Err(refusal.to_string())
|
||||
}
|
||||
})
|
||||
}
|
||||
/// Closes the scan's module (the owner's `close_inner`).
|
||||
pub(in super::super) fn release_tensor_core(&mut self) -> Result<()> {
|
||||
match std::mem::replace(&mut self.tensor_core, TensorCoreState::Refused) {
|
||||
TensorCoreState::Ready(scan) => self.release_stage(scan.module),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
/// One command of the scan on the batch stream: `(entry, grid, block, dynamic shared bytes)`.
|
||||
pub(in super::super) fn launch_tensor_core(
|
||||
&self,
|
||||
blas: &crate::ple_batch_ffi::Blas,
|
||||
(entry, grid, block, smem): (usize, u32, u32, u32),
|
||||
args: &mut KernelArguments,
|
||||
) -> Result<()> {
|
||||
let TensorCoreState::Ready(scan) = &self.tensor_core else { return Err(Error::ContextPoisoned) };
|
||||
scan.module.launch_dynamic(entry, LinearLaunch::new(grid, block, blas.stream()), smem, args)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_scan_is_off_unless_the_options_ask_for_it() {
|
||||
assert!(!GdnPromptOptions::default().tensor_core_scan);
|
||||
assert!(matches!(TensorCoreState::new(false), TensorCoreState::Off));
|
||||
assert!(matches!(TensorCoreState::new(true), TensorCoreState::Pending));
|
||||
for state in [TensorCoreState::Off, TensorCoreState::Pending, TensorCoreState::Refused] {
|
||||
assert!(state.plan().is_none(), "only a Ready scan has a plan");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ use std::{
|
||||
pub(crate) use leleka_cuda_model::bringup_trace_enabled;
|
||||
pub use leleka_cuda_model::{
|
||||
command_profile, device_arena, host_profile, mmq_original_prefill_misc, native_flash_attn,
|
||||
original_prefill_schedule, qsa_prompt_attention_select, s_gemv_legacy,
|
||||
original_prefill_schedule, qsa_prompt_attention_select, ring_prefetch, s_gemv_legacy,
|
||||
};
|
||||
use leleka_cuda_model::{original_expert_slots, original_mtp_loader, serving_context};
|
||||
|
||||
@@ -59,6 +59,8 @@ mod original_gpu_schedule;
|
||||
mod original_moe_prompt_device;
|
||||
mod original_prefill_arena;
|
||||
mod original_prefill_layout;
|
||||
#[cfg_attr(not(feature = "cuda-driver"), allow(dead_code))]
|
||||
mod owner_loan;
|
||||
mod routed_group_workspace;
|
||||
mod routed_stage_finite_guard;
|
||||
pub mod vram_ledger;
|
||||
@@ -157,6 +159,12 @@ mod grouped_down_columns_gpu;
|
||||
#[allow(unsafe_code)]
|
||||
mod api;
|
||||
mod async_owned_copy;
|
||||
// The lent-slot refill's batched copies (`LELEKA_REFILL_BATCH`): the call plan (pure) and its issue.
|
||||
mod refill_batch_copy;
|
||||
pub use refill_batch_copy::RefillBatchReport;
|
||||
#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
|
||||
#[path = "refill_batch_copy_gpu.rs"]
|
||||
mod refill_batch_copy_gpu;
|
||||
|
||||
// Explicit experimental resident pipeline; original entry bodies remain unchanged.
|
||||
mod routed_resident_queue;
|
||||
@@ -183,6 +191,9 @@ mod qsa_index_ffi;
|
||||
mod qsa_prompt_index;
|
||||
|
||||
// Genuine page4 INT8 owners and literal Original prompt/decode programs.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
#[allow(unsafe_code)]
|
||||
mod exact_fill;
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
mod kv_stream_gpu;
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
@@ -216,6 +227,7 @@ mod sealed_ptx;
|
||||
#[cfg(feature = "sm86")]
|
||||
mod sm86_table;
|
||||
|
||||
mod gdn_prefill_tc;
|
||||
mod launch_ex;
|
||||
mod native_prompt_device;
|
||||
mod prefill_stage;
|
||||
|
||||
@@ -124,7 +124,7 @@ pub struct OriginalMmqOutput<'lease, 'layer, 'ctx> {
|
||||
mod copy_ring;
|
||||
use copy_ring::GatherDest;
|
||||
pub(crate) use copy_ring::prefetch_point;
|
||||
pub use copy_ring::{OriginalMmqCopySchedule, RingExperts};
|
||||
pub use copy_ring::{OriginalMmqCopySchedule, PrefetchSource, PrefetchTarget, RingExperts};
|
||||
|
||||
// Closed global issuer consumer. Old per-layer/synchronous producers unchanged.
|
||||
#[path = "mmq_original_stream_all.rs"]
|
||||
|
||||
@@ -14,11 +14,18 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
|
||||
experts: RingExperts<'_, 'ctx>,
|
||||
) -> Result<()> {
|
||||
let (formats, sources) = (experts.formats, experts.sources);
|
||||
self.copy_ring_preflight(read, sources.len())?;
|
||||
if let Err(e) = self.copy_ring_preflight(read, sources.len()) {
|
||||
schedule.trace_refusal(experts.layer, "layer.preflight", (sources.len(), (0, 0, 0, self.counts.len())), &e);
|
||||
return Err(e);
|
||||
}
|
||||
let groups = self.counts.len().div_ceil(16);
|
||||
let init_span = crate::host_profile::span("ring.init");
|
||||
let mut ring = copy_ring::Ring::new(self.workspace.context, read, schedule, experts, groups)?;
|
||||
drop(init_span);
|
||||
let operation = self.stream_through_ring(&mut ring, read, formats, sources.len());
|
||||
let close_span = crate::host_profile::span("ring.close");
|
||||
let close = ring.close();
|
||||
drop(close_span);
|
||||
if operation.is_err() || close.is_err() {
|
||||
// A failed layer cannot masquerade as a completed output or resume midway.
|
||||
// Numeric refusal does not poison Context; caller must discard this lease.
|
||||
@@ -69,23 +76,33 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
|
||||
let lookahead = stages - 1;
|
||||
let mut staged = 0usize;
|
||||
for j in 0..sources {
|
||||
let stage_span = crate::host_profile::span("ring.stage");
|
||||
Self::ring_stage_ahead(ring, formats, (&mut staged, j + lookahead, sources))?;
|
||||
drop(stage_span);
|
||||
let gather_span = crate::host_profile::span("ring.gather");
|
||||
self.ring_gather(ring, j, formats)?;
|
||||
drop(gather_span);
|
||||
if self.staged < 16 && j + 1 < sources {
|
||||
continue;
|
||||
}
|
||||
let enqueue_span = crate::host_profile::span("ring.enqueue");
|
||||
self.ring_enqueue_group(ring, formats)?;
|
||||
drop(enqueue_span);
|
||||
}
|
||||
Self::check_ring_statuses(ring.finish_statuses()?)
|
||||
let statuses_span = crate::host_profile::span("ring.finish_statuses");
|
||||
let statuses = ring.finish_statuses()?;
|
||||
drop(statuses_span);
|
||||
Self::check_ring_statuses(statuses)
|
||||
}
|
||||
|
||||
/// Stages experts up to `limit` (the literal STAGE-1 lookahead) that are not yet staged.
|
||||
/// Stages experts up to `limit` (the literal STAGE-1 lookahead) that are not yet staged. With prefetched slots
|
||||
/// reserved in the ring (`LELEKA_PREFILL_RING_PREFETCH`) a copy that has no free slot yet waits for a later gather.
|
||||
fn ring_stage_ahead(
|
||||
ring: &mut copy_ring::Ring<'_, 'ctx>,
|
||||
formats: [MmqFormat; 3],
|
||||
(staged, limit, sources): (&mut usize, usize, usize),
|
||||
) -> Result<()> {
|
||||
while *staged < sources && *staged <= limit {
|
||||
while *staged < sources && *staged <= limit && ring.stage_room(*staged) {
|
||||
ring.stage_one(*staged, formats)?;
|
||||
*staged += 1;
|
||||
}
|
||||
|
||||
@@ -45,8 +45,8 @@ trait RingArena: GroupArena {
|
||||
struct Slot {
|
||||
span: ffi::BufferHandle,
|
||||
bytes: usize,
|
||||
live: bool,
|
||||
gathered: bool,
|
||||
/// filled / read / held for a prefetched source until its gather (`LELEKA_PREFILL_RING_PREFETCH`)
|
||||
state: crate::ring_prefetch::SlotState,
|
||||
}
|
||||
struct Events<'ctx> {
|
||||
copied: Option<OriginalGpuEvent<'ctx>>,
|
||||
@@ -89,6 +89,9 @@ pub struct OriginalMmqCopySchedule<'ctx> {
|
||||
/// The per-layer status words, kept between layers: a cuMemFree per layer would synchronize the whole device
|
||||
/// (the copy stream included) and wait for every queued expert copy. `(bytes, buffer)`.
|
||||
status_pool: Option<(usize, DeviceBuffer<'ctx>)>,
|
||||
/// EXPERIMENTAL ring prefetch (`LELEKA_PREFILL_RING_PREFETCH`, off by default): the policy, the per-layer miss
|
||||
/// history and the experts copied ahead for the next layer's ring.
|
||||
prefetch: RingPrefetch<'ctx>,
|
||||
}
|
||||
struct Source<'read> {
|
||||
spans: &'read [ResidentExpertBankSpan; 3],
|
||||
@@ -101,6 +104,8 @@ struct Source<'read> {
|
||||
/// slot offsets of gate, up and down after a page-aligned copy (claude/ledger); `None`: the literal blob layout 0,
|
||||
/// gu, 2*gu
|
||||
dest: Option<[usize; 3]>,
|
||||
/// the expert was prefetched into `slot` before the router ran: no stage copy
|
||||
prefetched: bool,
|
||||
}
|
||||
/// Private owner: no external pointer/ready event can manufacture a stage.
|
||||
/// The actual source Rc prevents unregister/free during H2D or gathered use.
|
||||
@@ -121,6 +126,8 @@ pub(super) struct Ring<'read, 'ctx> {
|
||||
streamed: bool,
|
||||
layer: u8,
|
||||
stage_done: usize,
|
||||
/// slots still reserved for a prefetched expert (0 without the prefetch: the literal ring)
|
||||
reserved: usize,
|
||||
submitted: bool,
|
||||
drained: bool,
|
||||
closed: bool,
|
||||
@@ -147,3 +154,7 @@ mod original_mmq_copy_schedule_drop;
|
||||
mod ring;
|
||||
#[path = "mmq_original_ring/ring_drop.rs"]
|
||||
mod ring_drop;
|
||||
#[path = "mmq_original_ring/ring_prefetch_issue.rs"]
|
||||
mod ring_prefetch_issue;
|
||||
use ring_prefetch_issue::RingPrefetch;
|
||||
pub use ring_prefetch_issue::{PrefetchSource, PrefetchTarget};
|
||||
|
||||
@@ -65,6 +65,8 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
|
||||
bytes_per_second: f64,
|
||||
) -> Result<()> {
|
||||
use crate::ffi::original_stager::Api as StagerApi;
|
||||
// the stream owns the stage slots from here: a ring prefetch no ring took is drained and dropped
|
||||
self.cancel_ring_prefetch()?;
|
||||
self.stream_admit(read, bank, first)?;
|
||||
let lease = read.lease();
|
||||
let ring = lease.copy_ring_slots()?;
|
||||
@@ -80,9 +82,15 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
|
||||
self.stream_launch(api, bank, StreamPlan { first, ring, entries, targets }, events)
|
||||
}
|
||||
/// End the chunk's expert stream: stop and join the issuer, drain the copy and compute streams, release the
|
||||
/// raw events. Idempotent; a failure poisons the schedule.
|
||||
/// raw events. Idempotent; a failure poisons the schedule. A ring prefetch no ring took is dropped first (its
|
||||
/// copies drained), so no copy outlives the chunk's row lease.
|
||||
pub fn end_prompt_stream(&mut self) -> Result<()> {
|
||||
let Some(mut stream) = self.stream.take() else { return Ok(()) };
|
||||
let cancelled = self.cancel_ring_prefetch();
|
||||
let Some(stream) = self.stream.take() else { return cancelled };
|
||||
combine(cancelled, self.end_stream(stream))
|
||||
}
|
||||
|
||||
fn end_stream(&mut self, mut stream: ChunkStream) -> Result<()> {
|
||||
let stopped = stream.stop();
|
||||
let copy = self.copy.as_ref().map_or(Ok(()), OriginalGpuStream::synchronize);
|
||||
let compute = self.compute.as_ref().map_or(Ok(()), OriginalGpuStream::synchronize);
|
||||
|
||||
@@ -8,6 +8,9 @@ mod ring_construction;
|
||||
#[path = "ring/ring_gather_and_finish.rs"]
|
||||
mod ring_gather_and_finish;
|
||||
mod ring_init;
|
||||
#[path = "ring/ring_prefetch.rs"]
|
||||
mod ring_prefetch;
|
||||
pub(super) use ring_prefetch::profile_prefetch;
|
||||
#[path = "ring/ring_stage_expert_copies.rs"]
|
||||
mod ring_stage_expert_copies;
|
||||
use ring_init::RingPlan;
|
||||
pub(super) use ring_init::RingPlan;
|
||||
|
||||
@@ -3,6 +3,31 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Whether a schedule that owns `schedule_slots` slot events serves an arena ring of `arena_slots` slots. The
|
||||
/// schedule is opened once with the full prompt layout's ring (384 slots). A smaller arena of the prompt loan ladder
|
||||
/// (the 512-row rung carves the literal 8-slot ring below `stream_all_min`) uses the first `arena_slots` events: slot
|
||||
/// `i` is `i % arena_slots`, so the surplus events stay idle. A schedule with fewer events than the ring needs is
|
||||
/// refused.
|
||||
fn schedule_serves_ring(schedule_slots: usize, arena_slots: usize) -> bool {
|
||||
arena_slots <= schedule_slots
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod schedule_tests {
|
||||
use super::schedule_serves_ring;
|
||||
|
||||
#[test]
|
||||
fn a_smaller_ring_uses_the_first_events_of_a_larger_schedule() {
|
||||
assert!(schedule_serves_ring(384, 384));
|
||||
assert!(schedule_serves_ring(384, 8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_schedule_with_fewer_events_than_the_ring_is_refused() {
|
||||
assert!(!schedule_serves_ring(8, 384));
|
||||
}
|
||||
}
|
||||
|
||||
impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
pub(in super::super::super) fn new(
|
||||
context: &'ctx Context<'ctx>,
|
||||
@@ -12,14 +37,13 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
groups: usize,
|
||||
) -> Result<Self> {
|
||||
let RingExperts { layer, bank, formats, sources: spans } = experts;
|
||||
Self::validate_new(context, read, &bank, (layer, groups, spans.len()), &formats)?;
|
||||
let (gu, down, blob) = Self::blob_geometry(&formats)?;
|
||||
let admitted: &dyn RingArena = read;
|
||||
let count = admitted.stage_slots()?;
|
||||
schedule.validate_context(context)?;
|
||||
if schedule.ring_slots() != count {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
let shape = (layer, groups, spans.len());
|
||||
if let Err(e) = Self::validate_new(context, read, &bank, shape, &formats) {
|
||||
schedule.trace_refusal(layer, "new.validate", (spans.len(), (0, 0, 0, spans.len())), &e);
|
||||
return Err(e);
|
||||
}
|
||||
let (gu, down, blob) = Self::blob_geometry(&formats)?;
|
||||
let count = Self::admitted_slots(context, read, schedule, layer)?;
|
||||
let mut owner = Self::empty(context, read, bank, schedule, layer);
|
||||
let plan = RingPlan { layer, groups, formats, gu, down, blob, count };
|
||||
if let Err(primary) = owner.init(spans, &plan) {
|
||||
@@ -27,4 +51,22 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
}
|
||||
Ok(owner)
|
||||
}
|
||||
|
||||
/// The arena's stage slot count, refused when the schedule has fewer slot events.
|
||||
fn admitted_slots(
|
||||
context: &'ctx Context<'ctx>,
|
||||
read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>,
|
||||
schedule: &OriginalMmqCopySchedule<'ctx>,
|
||||
layer: usize,
|
||||
) -> Result<usize> {
|
||||
let admitted: &dyn RingArena = read;
|
||||
let count = admitted.stage_slots()?;
|
||||
schedule.validate_context(context)?;
|
||||
if !schedule_serves_ring(schedule.ring_slots(), count) {
|
||||
let e = Error::InvalidProjectionShape;
|
||||
schedule.trace_refusal(layer, "new.schedule_slots", (schedule.ring_slots(), (0, 0, count, 0)), &e);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(count)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::ring_prefetch::RingRefusal;
|
||||
|
||||
impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
pub(in super::super::super) fn gather(
|
||||
@@ -12,7 +13,10 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
dest: GatherDest,
|
||||
) -> Result<()> {
|
||||
let GatherDest { gate_up, down_out } = dest;
|
||||
let source = self.sources.get(index).ok_or(Error::InvalidProjectionShape)?;
|
||||
let source = self
|
||||
.sources
|
||||
.get(index)
|
||||
.ok_or_else(|| self.traced("gather.no_source", index, Error::InvalidProjectionShape))?;
|
||||
let gu = formats[0].layout(1)?.raw_weight;
|
||||
let down = formats[2].layout(1)?.raw_weight;
|
||||
let (sl, entry, dest, resident) = (source.slot, source.entry, source.dest, source.resident);
|
||||
@@ -21,7 +25,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
} else if let Some(k) = entry {
|
||||
self.gather_streamed(k, (gu, down))?
|
||||
} else {
|
||||
self.gather_slot(sl, dest, (gu, down))?
|
||||
self.gather_slot(sl, dest, (gu, down)).map_err(|e| self.traced("gather.slot", index, e))?
|
||||
};
|
||||
Self::check_gather_destination(raw, (gate_up, down_out), (gu, down))?;
|
||||
self.enqueue(Command::Gather(
|
||||
@@ -51,12 +55,12 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
dest: Option<[usize; 3]>,
|
||||
(gu, down): (usize, usize),
|
||||
) -> Result<[ffi::BufferHandle; 3]> {
|
||||
let sl = sl.ok_or(Error::InvalidProjectionShape)?;
|
||||
let slot = &mut self.slots[sl];
|
||||
let events = &mut self.schedule.events[sl];
|
||||
if !slot.live || slot.gathered {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
let sl = sl.ok_or_else(|| self.refuse(RingRefusal::GatherNoSlot, usize::MAX))?;
|
||||
if let Err(refusal) = self.slots[sl].state.check_gather() {
|
||||
return Err(self.refuse(refusal, sl));
|
||||
}
|
||||
let slot = &self.slots[sl];
|
||||
let events = &mut self.schedule.events[sl];
|
||||
events
|
||||
.copied
|
||||
.as_mut()
|
||||
@@ -104,7 +108,9 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
.as_mut()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.record(self.schedule.compute.as_ref().ok_or(Error::ContextPoisoned)?)?;
|
||||
slot.gathered = true;
|
||||
if slot.state.gathered() {
|
||||
self.reserved -= 1;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
//! The copy ring's side of the EXPERIMENTAL prefetch (`LELEKA_PREFILL_RING_PREFETCH`,
|
||||
//! docs/experiments/ring-prefetch.md): one prefetch copy into a stage slot, the miss history a ring feeds, and the
|
||||
//! adoption of the prefetched set when the router result is known. A prefetched expert is read by the same gather from
|
||||
//! the same bytes; only the time of its copy changes.
|
||||
|
||||
use super::super::ring_prefetch_issue::{PendingPrefetch, PrefetchEntry};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::ring_prefetch::{self, ExpertMask, RingRefusal, SlotState, mask_set, match_prefetch};
|
||||
|
||||
/// `(address, length)` of the gate, up and down host ranges: the identity of the bytes a copy moved.
|
||||
pub(in super::super) type Pieces = [(usize, usize); 3];
|
||||
|
||||
impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
/// The host ranges of an expert as addresses, compared between the prefetch and the routed source.
|
||||
pub(in super::super) fn piece_ids(
|
||||
bank: &crate::MappedExpertBank<'ctx>,
|
||||
spans: &[ResidentExpertBankSpan; 3],
|
||||
) -> Result<Pieces> {
|
||||
Ok(Self::source_pieces(bank, spans)?.map(|p| (p.as_ptr() as usize, p.len())))
|
||||
}
|
||||
|
||||
/// Copies one expert into stage slot `slot` (span `span`) on the schedule's copy stream exactly as `stage_one` does
|
||||
/// and records the slot's `copied` event. The spans are checked like a routed source's first.
|
||||
pub(in super::super) fn prefetch_into_slot(
|
||||
schedule: &mut OriginalMmqCopySchedule<'ctx>,
|
||||
bank: &crate::MappedExpertBank<'ctx>,
|
||||
spans: &[ResidentExpertBankSpan; 3],
|
||||
(slot, span): (usize, (ffi::BufferHandle, usize)),
|
||||
plan: &RingPlan,
|
||||
) -> Result<PrefetchEntry> {
|
||||
Self::check_source_spans(bank, spans, true, plan)?;
|
||||
let target = Slot { span: span.0, bytes: span.1, state: Default::default() };
|
||||
if target.bytes < plan.blob {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
let dest = Self::prefetch_copy(schedule, bank, spans, &target, plan)?;
|
||||
let copy = schedule.copy.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let events = schedule.events.get_mut(slot).ok_or(Error::InvalidProjectionShape)?;
|
||||
events.copied.as_mut().ok_or(Error::ContextPoisoned)?.record(copy)?;
|
||||
let expert = spans[0].expert();
|
||||
Ok(PrefetchEntry { expert, slot, span, pieces: Self::piece_ids(bank, spans)?, dest })
|
||||
}
|
||||
|
||||
/// The page-aligned supersets side by side when they fit, else the exact pieces (`stage_copy_pieces`).
|
||||
fn prefetch_copy(
|
||||
schedule: &mut OriginalMmqCopySchedule<'ctx>,
|
||||
bank: &crate::MappedExpertBank<'ctx>,
|
||||
spans: &[ResidentExpertBankSpan; 3],
|
||||
slot: &Slot,
|
||||
plan: &RingPlan,
|
||||
) -> Result<Option<[usize; 3]>> {
|
||||
let api = schedule.api.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let copy = schedule.copy.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
if let Some(parts) = Self::aligned_parts(bank, spans, slot.bytes)? {
|
||||
Self::copy_aligned(copy, api, slot, &parts)?;
|
||||
return Ok(Some([parts[0].2 + parts[0].1, parts[1].2 + parts[1].1, parts[2].2 + parts[2].1]));
|
||||
}
|
||||
let operands = Self::exact_operands(bank, slot, spans, (plan.gu, plan.down))?;
|
||||
Self::copy_exact(copy, api, bank, operands)?;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// With the prefetch on, this layer's missed set (routed and not resident) joins the layer's history.
|
||||
pub(super) fn record_ring_misses(&mut self, plan: &RingPlan) {
|
||||
let Some(history) = self.schedule.prefetch.history.as_mut() else { return };
|
||||
let mut missed: ExpertMask = [0; 8];
|
||||
for source in self.sources.iter().filter(|s| s.resident.is_none()) {
|
||||
mask_set(&mut missed, source.spans[0].expert() as usize);
|
||||
}
|
||||
history.record(plan.layer, missed);
|
||||
}
|
||||
|
||||
/// Takes the schedule's prefetched set: a routed, non-resident source whose bytes a prefetch copied is read from
|
||||
/// that slot (reserved until its gather); every other prefetched slot stays free. A set issued for another layer,
|
||||
/// bank or arena is dropped once its copies are drained.
|
||||
pub(super) fn adopt_prefetch(&mut self, plan: &RingPlan) -> Result<()> {
|
||||
let Some(pending) = self.schedule.take_ring_prefetch() else { return Ok(()) };
|
||||
// the ring's drain also covers the prefetch copies, whatever happens below
|
||||
self.submitted = true;
|
||||
self.drained = false;
|
||||
if !self.prefetch_usable(&pending, plan) {
|
||||
let (layer, n) = (pending.layer, pending.entries.len());
|
||||
self.schedule.trace_prefetch(format_args!("layer={} dropped={n} issued_for={layer}", plan.layer));
|
||||
profile_prefetch("ring.prefetch_wasted", pending.entries.len(), plan.blob);
|
||||
return self.schedule.drain_dropped_prefetch(pending);
|
||||
}
|
||||
let experts: Vec<u32> = pending.entries.iter().map(|e| e.expert).collect();
|
||||
let needs: Vec<Option<u32>> = self
|
||||
.sources
|
||||
.iter()
|
||||
.map(|s| (s.resident.is_none() && s.job.is_none()).then(|| s.spans[0].expert()))
|
||||
.collect();
|
||||
let matched = match_prefetch(&experts, &needs);
|
||||
let mut hits = 0;
|
||||
for (source, entry) in matched.hits {
|
||||
hits += usize::from(self.consume_prefetched(source, &pending.entries[entry])?);
|
||||
}
|
||||
let wasted = pending.entries.len() - hits;
|
||||
self.schedule.trace_prefetch(format_args!("layer={} hits={hits} wasted={wasted}", plan.layer));
|
||||
profile_prefetch("ring.prefetch_hit", hits, plan.blob);
|
||||
profile_prefetch("ring.prefetch_wasted", wasted, plan.blob);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the set was issued for this layer, from this ring's bank, into this arena's slots, with no chunk stream.
|
||||
fn prefetch_usable(&self, pending: &PendingPrefetch<'ctx>, plan: &RingPlan) -> bool {
|
||||
let same_bank = self.bank.as_ref().is_some_and(|b| Rc::ptr_eq(b, &pending.bank));
|
||||
let same_slots = pending.entries.iter().all(|e| {
|
||||
self.slots.get(e.slot).is_some_and(|s| (s.span, s.bytes) == e.span && s.state == SlotState::default())
|
||||
});
|
||||
pending.layer == plan.layer
|
||||
&& pending.blob == plan.blob
|
||||
&& same_bank
|
||||
&& same_slots
|
||||
&& self.schedule.stream.is_none()
|
||||
}
|
||||
|
||||
/// Source `source` reads the prefetched slot when the copied bytes are its own; returns whether it does.
|
||||
fn consume_prefetched(&mut self, source: usize, entry: &PrefetchEntry) -> Result<bool> {
|
||||
let bank = self.bank.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
if Self::piece_ids(bank, self.sources[source].spans)? != entry.pieces {
|
||||
return Ok(false);
|
||||
}
|
||||
let slot = &mut self.slots[entry.slot];
|
||||
slot.state = SlotState::PREFETCHED;
|
||||
self.reserved += 1;
|
||||
let source = &mut self.sources[source];
|
||||
(source.slot, source.dest, source.prefetched) = (Some(entry.slot), entry.dest, true);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Whether `stage_one` copies source `index` (`Ok(false)`: resident, a chunk-stream entry or prefetched).
|
||||
pub(super) fn stage_needed(&self, index: usize) -> std::result::Result<bool, RingRefusal> {
|
||||
let source = &self.sources[index];
|
||||
let no_copy = source.resident.is_some() || source.entry.is_some();
|
||||
ring_prefetch::stage_needed(no_copy, source.prefetched, source.slot.is_some())
|
||||
}
|
||||
|
||||
/// The slot `stage_one` copies into: the next one in ring order no prefetched source holds (`stage_next` itself
|
||||
/// without a prefetch), refused when it still holds an unread copy.
|
||||
pub(super) fn stage_target(&self) -> std::result::Result<usize, RingRefusal> {
|
||||
ring_prefetch::stage_target(self.slots.len(), self.stage_next, |s| self.slots[s].state)
|
||||
}
|
||||
|
||||
/// Whether source `index` can be staged now: it needs no copy, or some unreserved slot is free. Always true for the
|
||||
/// literal ring (no prefetch adopted); after a prefetch, a copy waits for a gather when every unreserved slot still
|
||||
/// holds an unread copy (also once every hit was gathered: the slot order no longer follows the gather order).
|
||||
pub(in super::super::super) fn stage_room(&self, index: usize) -> bool {
|
||||
if index >= self.sources.len() {
|
||||
return true;
|
||||
}
|
||||
!matches!(self.stage_needed(index), Ok(true)) || self.stage_target().is_ok()
|
||||
}
|
||||
|
||||
/// The error of a refused ring check (`InvalidProjectionShape`); with the driver error trace on, a `RING-REFUSE`
|
||||
/// line names the check, the layer, the source and the slot bookkeeping.
|
||||
pub(in super::super::super) fn refuse(&self, refusal: RingRefusal, index: usize) -> Error {
|
||||
self.traced(refusal.check(), index, Error::InvalidProjectionShape)
|
||||
}
|
||||
|
||||
/// `error`, traced under the check name `check` when the driver error trace is on.
|
||||
pub(in super::super::super) fn traced(&self, check: &'static str, index: usize, error: Error) -> Error {
|
||||
let state = (self.stage_next, self.reserved, self.slots.len(), self.sources.len());
|
||||
self.schedule.trace_refusal(usize::from(self.layer), check, (index, state), &error);
|
||||
error
|
||||
}
|
||||
}
|
||||
/// `LELEKA_SERVE_PROFILE`: one call of `name` per expert, its MB as the value.
|
||||
pub(in super::super) fn profile_prefetch(name: &'static str, experts: usize, blob: usize) {
|
||||
for _ in 0..experts {
|
||||
crate::host_profile::add(name, blob as f64 / 1e6);
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,11 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
}
|
||||
pub(in super::super::super) fn enqueue(&mut self, command: Command) -> Result<()> {
|
||||
if self.closed || self.commands.len() == COMMAND_CAP || !self.read.matches_context(self.context) {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
return Err(self.traced(
|
||||
"enqueue.closed_full_or_context",
|
||||
self.commands.len(),
|
||||
Error::InvalidProjectionShape,
|
||||
));
|
||||
}
|
||||
self.commands.push(command);
|
||||
self.submitted = true;
|
||||
@@ -45,31 +49,29 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
)
|
||||
}
|
||||
pub(in super::super::super) fn stage_one(&mut self, index: usize, formats: [MmqFormat; 3]) -> Result<()> {
|
||||
let source = self.sources.get(index).ok_or(Error::InvalidProjectionShape)?;
|
||||
if source.resident.is_some() || source.entry.is_some() {
|
||||
if index >= self.sources.len() {
|
||||
return Err(self.traced("stage.no_source", index, Error::InvalidProjectionShape));
|
||||
}
|
||||
if !self.stage_needed(index).map_err(|r| self.refuse(r, index))? {
|
||||
return Ok(());
|
||||
}
|
||||
if source.slot.is_some() {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
let sl = self.stage_next;
|
||||
let sl = self.stage_target().map_err(|r| self.refuse(r, index))?;
|
||||
let next = (sl + 1) % self.slots.len();
|
||||
self.stage_wait_slot(sl)?;
|
||||
let new_dest = self.stage_copy(index, sl, formats)?;
|
||||
profile_copied(formats)?;
|
||||
self.stage_record(index, sl, new_dest)?;
|
||||
self.stage_next = next;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A live slot is reused only after its gather; the copy stream waits the previous gather.
|
||||
/// A live slot is reused only after its gather (`stage_target` refused an ungathered one); the copy stream waits
|
||||
/// the previous gather.
|
||||
fn stage_wait_slot(&mut self, sl: usize) -> Result<()> {
|
||||
let slot = &self.slots[sl];
|
||||
let events = &mut self.schedule.events[sl];
|
||||
let copy = self.schedule.copy.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
if slot.live {
|
||||
if !slot.gathered {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
if slot.state.live {
|
||||
// Re-recorded copied and used events have the same real source
|
||||
// streams; the copy stream waits the previous gather before reuse.
|
||||
events.used.as_mut().ok_or(Error::ContextPoisoned)?.wait_on(copy)?;
|
||||
@@ -149,7 +151,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
|
||||
/// `(superset, lead, offset)` of the three pieces side by side at page offsets, when they fit `slot_bytes`.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn aligned_parts<'b>(
|
||||
pub(super) fn aligned_parts<'b>(
|
||||
bank: &'b crate::MappedExpertBank<'ctx>,
|
||||
spans: &[ResidentExpertBankSpan; 3],
|
||||
slot_bytes: usize,
|
||||
@@ -167,7 +169,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
Ok((off <= slot_bytes).then_some(parts))
|
||||
}
|
||||
|
||||
fn copy_aligned(
|
||||
pub(super) fn copy_aligned(
|
||||
copy: &mut OriginalGpuStream<'ctx>,
|
||||
api: &Api,
|
||||
slot: &Slot,
|
||||
@@ -183,7 +185,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
|
||||
/// The exact gate, up and down host ranges and their destinations back to back in the slot.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn exact_operands<'b>(
|
||||
pub(super) fn exact_operands<'b>(
|
||||
bank: &'b crate::MappedExpertBank<'ctx>,
|
||||
slot: &Slot,
|
||||
spans: &[ResidentExpertBankSpan; 3],
|
||||
@@ -198,7 +200,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
Ok((sources, destinations))
|
||||
}
|
||||
|
||||
fn copy_exact(
|
||||
pub(super) fn copy_exact(
|
||||
copy: &mut OriginalGpuStream<'ctx>,
|
||||
api: &Api,
|
||||
bank: &crate::MappedExpertBank<'ctx>,
|
||||
@@ -229,10 +231,18 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
if serialize_ring(Drain::Copies) {
|
||||
copy.synchronize()?;
|
||||
}
|
||||
self.slots[sl].live = true;
|
||||
self.slots[sl].gathered = false;
|
||||
self.slots[sl].state.staged();
|
||||
self.sources[index].slot = Some(sl);
|
||||
self.sources[index].dest = new_dest;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// `LELEKA_SERVE_PROFILE`: the count of experts copied over PCIe (the call count of `ring.copied_mb`) and their MB.
|
||||
fn profile_copied(formats: [MmqFormat; 3]) -> Result<()> {
|
||||
if crate::host_profile::enabled() {
|
||||
let blob = formats[0].layout(1)?.raw_weight * 2 + formats[2].layout(1)?.raw_weight;
|
||||
crate::host_profile::add("ring.copied_mb", blob as f64 / 1e6);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -5,18 +5,18 @@
|
||||
use super::*;
|
||||
|
||||
/// Layer-wide numbers every construction phase needs.
|
||||
pub(super) struct RingPlan {
|
||||
pub(super) layer: usize,
|
||||
pub(super) groups: usize,
|
||||
pub(super) formats: [MmqFormat; 3],
|
||||
pub(in super::super) struct RingPlan {
|
||||
pub(in super::super) layer: usize,
|
||||
pub(in super::super) groups: usize,
|
||||
pub(in super::super) formats: [MmqFormat; 3],
|
||||
/// raw bytes of one gate or up matrix
|
||||
pub(super) gu: usize,
|
||||
pub(in super::super) gu: usize,
|
||||
/// raw bytes of one down matrix
|
||||
pub(super) down: usize,
|
||||
pub(in super::super) down: usize,
|
||||
/// bytes of one expert blob (gate + up + down)
|
||||
pub(super) blob: usize,
|
||||
pub(in super::super) blob: usize,
|
||||
/// number of stage slots of the arena
|
||||
pub(super) count: usize,
|
||||
pub(in super::super) count: usize,
|
||||
}
|
||||
|
||||
impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
@@ -44,7 +44,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
}
|
||||
|
||||
/// `(gate/up bytes, down bytes, blob bytes)` of one expert.
|
||||
pub(super) fn blob_geometry(formats: &[MmqFormat; 3]) -> Result<(usize, usize, usize)> {
|
||||
pub(in super::super) fn blob_geometry(formats: &[MmqFormat; 3]) -> Result<(usize, usize, usize)> {
|
||||
let gu = formats[0].layout(1)?.raw_weight;
|
||||
let down = formats[2].layout(1)?.raw_weight;
|
||||
let blob = gu.checked_mul(2).and_then(|n| n.checked_add(down)).ok_or(Error::InvalidSize)?;
|
||||
@@ -74,6 +74,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
streamed: false,
|
||||
layer: layer as u8,
|
||||
stage_done: 0,
|
||||
reserved: 0,
|
||||
submitted: false,
|
||||
drained: false,
|
||||
closed: false,
|
||||
@@ -86,6 +87,8 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
self.check_metadata_budget()?;
|
||||
self.admit_slots(plan)?;
|
||||
self.admit_sources(spans, plan)?;
|
||||
self.record_ring_misses(plan);
|
||||
self.adopt_prefetch(plan)?;
|
||||
self.attach_stream(plan)?;
|
||||
let jobs = self.plan_host_jobs(plan)?;
|
||||
self.admit_status(plan)?;
|
||||
@@ -95,7 +98,9 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
fn start_jobs(&mut self, jobs: Vec<Job>, plan: &RingPlan) -> Result<()> {
|
||||
// The old input quantization/metadata upload used default stream.
|
||||
// Admit that dependency once before starting nonblocking producers.
|
||||
let sync_span = crate::host_profile::span("ring.init_sync");
|
||||
self.context.synchronize()?;
|
||||
drop(sync_span);
|
||||
if !jobs.is_empty() {
|
||||
self.start_host_stage(jobs, plan)?;
|
||||
}
|
||||
@@ -145,7 +150,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
return Err(Error::OutputAliasesInput);
|
||||
}
|
||||
}
|
||||
self.slots.push(Slot { span: h, bytes: n, live: false, gathered: false });
|
||||
self.slots.push(Slot { span: h, bytes: n, state: Default::default() });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -154,14 +159,15 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
let bank = self.bank.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
for (i, spans) in spans.iter().enumerate() {
|
||||
let ordered = i == 0 || spans[0].expert() > self.sources[i - 1].spans[0].expert();
|
||||
Self::check_source_spans(bank, spans, ordered, plan)?;
|
||||
Self::check_source_spans(bank, spans, ordered, plan).map_err(|e| self.traced("sources.spans", i, e))?;
|
||||
let resident = self.resident_blob(spans[0].expert() as usize, plan)?;
|
||||
self.sources.push(Source { spans, resident, slot: None, job: None, entry: None, dest: None });
|
||||
let source = Source { spans, resident, slot: None, job: None, entry: None, dest: None, prefetched: false };
|
||||
self.sources.push(source);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_source_spans(
|
||||
pub(super) fn check_source_spans(
|
||||
bank: &crate::MappedExpertBank<'ctx>,
|
||||
spans: &[ResidentExpertBankSpan; 3],
|
||||
ordered: bool,
|
||||
@@ -202,30 +208,39 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
|
||||
/// With an active chunk stream for this layer, every non-resident expert is the stream's entry.
|
||||
fn attach_stream(&mut self, plan: &RingPlan) -> Result<()> {
|
||||
let bank = self.bank.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
if let Some(stream) = self.schedule.stream.as_ref() {
|
||||
if !stream.next_layer_is(plan.layer as u8) {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
for source in &mut self.sources {
|
||||
if source.resident.is_some() {
|
||||
continue;
|
||||
}
|
||||
let entry =
|
||||
stream.entry(plan.layer as u8, source.spans[0].expert()).ok_or(Error::InvalidProjectionShape)?;
|
||||
// the stream copies exactly the bytes this span names
|
||||
if !stream.entry_matches(entry, Self::source_pieces(bank, source.spans)?) {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
source.entry = Some(entry);
|
||||
}
|
||||
self.streamed = true;
|
||||
let Some(stream) = self.schedule.stream.as_ref() else { return Ok(()) };
|
||||
if !stream.next_layer_is(plan.layer as u8) {
|
||||
return Err(self.traced("stream.layer", 0, Error::InvalidProjectionShape));
|
||||
}
|
||||
for index in 0..self.sources.len() {
|
||||
let entry = self.stream_entry(index, plan).map_err(|(check, e)| self.traced(check, index, e))?;
|
||||
self.sources[index].entry = entry;
|
||||
}
|
||||
self.streamed = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The chunk stream's entry of a non-resident source (`None` for a resident one), or the refused check.
|
||||
fn stream_entry(&self, index: usize, plan: &RingPlan) -> std::result::Result<Option<usize>, (&'static str, Error)> {
|
||||
let source = &self.sources[index];
|
||||
if source.resident.is_some() {
|
||||
return Ok(None);
|
||||
}
|
||||
let poisoned = || ("stream.bank", Error::ContextPoisoned);
|
||||
let bank = self.bank.as_ref().ok_or_else(poisoned)?;
|
||||
let stream = self.schedule.stream.as_ref().ok_or_else(poisoned)?;
|
||||
let refused = |check| (check, Error::InvalidProjectionShape);
|
||||
let entry = stream.entry(plan.layer as u8, source.spans[0].expert()).ok_or(refused("stream.no_entry"))?;
|
||||
// the stream copies exactly the bytes this span names
|
||||
let pieces = Self::source_pieces(bank, source.spans).map_err(|e| ("stream.pieces", e))?;
|
||||
if !stream.entry_matches(entry, pieces) {
|
||||
return Err(refused("stream.entry_bytes"));
|
||||
}
|
||||
Ok(Some(entry))
|
||||
}
|
||||
|
||||
/// The gate, up and down host ranges of one expert.
|
||||
fn source_pieces<'b>(
|
||||
pub(super) fn source_pieces<'b>(
|
||||
bank: &'b crate::MappedExpertBank<'ctx>,
|
||||
spans: &[ResidentExpertBankSpan; 3],
|
||||
) -> Result<[&'b [u8]; 3]> {
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
//! EXPERIMENTAL prompt copy-ring prefetch (`LELEKA_PREFILL_RING_PREFETCH`, off by default;
|
||||
//! docs/experiments/ring-prefetch.md): the schedule's half. After a layer's ring has drained, the experts the NEXT
|
||||
//! layer missed most often in its recent chunks are copied into the next ring's stage slots on the copy stream while
|
||||
//! the layer's combine and the next mixer run. The next `Ring::new` takes the set (`adopt_prefetch`). The policy comes
|
||||
//! from the engine's settings; nothing here reads the environment.
|
||||
|
||||
use super::ring::{RingPlan, profile_prefetch};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::ring_prefetch::{MissHistory, RingPrefetchPolicy};
|
||||
|
||||
/// One expert copied ahead into a stage slot.
|
||||
pub(super) struct PrefetchEntry {
|
||||
pub(super) expert: u32,
|
||||
pub(super) slot: usize,
|
||||
/// the stage slot's `(span, bytes)` at the copy: the adopting ring must see the same arena slot
|
||||
pub(super) span: (ffi::BufferHandle, usize),
|
||||
/// `(address, length)` of the copied gate, up and down host ranges
|
||||
pub(super) pieces: [(usize, usize); 3],
|
||||
/// the page-aligned lead offsets, as `stage_record` keeps them
|
||||
pub(super) dest: Option<[usize; 3]>,
|
||||
}
|
||||
|
||||
/// The experts copied for the next ring of `layer`, with the bank the copies read (held while they may run).
|
||||
pub(super) struct PendingPrefetch<'ctx> {
|
||||
pub(super) layer: usize,
|
||||
pub(super) bank: Rc<crate::MappedExpertBank<'ctx>>,
|
||||
pub(super) blob: usize,
|
||||
pub(super) entries: Vec<PrefetchEntry>,
|
||||
}
|
||||
|
||||
/// The policy (none: off), the per-layer miss history and the copied set waiting for its ring.
|
||||
#[derive(Default)]
|
||||
pub(super) struct RingPrefetch<'ctx> {
|
||||
pub(super) policy: Option<RingPrefetchPolicy>,
|
||||
pub(super) history: Option<MissHistory>,
|
||||
pub(super) pending: Option<PendingPrefetch<'ctx>>,
|
||||
/// the engine's driver error trace (`LELEKA_TRACE_DRIVER_ERRORS` / `LELEKA_BRINGUP_TRACE`): name every refused ring
|
||||
/// check and every prefetch decision on stderr
|
||||
pub(super) trace_errors: bool,
|
||||
}
|
||||
|
||||
/// The bank spans and matrix formats of one predicted expert, as the caller resolved them; `None` skips it.
|
||||
pub type PrefetchSource = Option<([ResidentExpertBankSpan; 3], [MmqFormat; 3])>;
|
||||
|
||||
/// The ring the prefetch fills: the row lease's read, the registered bank and the layer about to run.
|
||||
pub struct PrefetchTarget<'a, 'arena, 'loan, 'ctx> {
|
||||
pub read: &'a crate::OriginalDeviceGrRead<'arena, 'loan, 'ctx>,
|
||||
pub bank: &'a Rc<crate::MappedExpertBank<'ctx>>,
|
||||
pub layer: usize,
|
||||
}
|
||||
|
||||
impl<'ctx> OriginalMmqCopySchedule<'ctx> {
|
||||
/// Switches the prefetch on (with its policy) or off; the miss history starts empty.
|
||||
pub fn set_ring_prefetch(&mut self, policy: Option<RingPrefetchPolicy>) {
|
||||
self.prefetch.history = policy.map(|p| MissHistory::new(p.window));
|
||||
self.prefetch.policy = policy;
|
||||
}
|
||||
|
||||
/// The engine's driver error trace: a refused copy-ring check prints a `RING-REFUSE` line naming it, and the
|
||||
/// prefetch prints its decisions (`RING-PREFETCH`). No environment is read here.
|
||||
pub fn set_ring_error_trace(&mut self, on: bool) {
|
||||
self.prefetch.trace_errors = on;
|
||||
}
|
||||
|
||||
/// With the trace on: `RING-REFUSE layer check source stage_next reserved slots sources error`.
|
||||
pub(crate) fn trace_refusal(
|
||||
&self,
|
||||
layer: usize,
|
||||
check: &str,
|
||||
(index, state): (usize, (usize, usize, usize, usize)),
|
||||
error: &Error,
|
||||
) {
|
||||
if self.prefetch.trace_errors {
|
||||
let (next, reserved, slots, sources) = state;
|
||||
let ring = format!("stage_next={next} reserved={reserved} slots={slots} sources={sources}");
|
||||
eprintln!("RING-REFUSE layer={layer} check={check} source={index} {ring} error={error:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With the trace on: one `RING-PREFETCH` line per decision.
|
||||
pub(super) fn trace_prefetch(&self, what: std::fmt::Arguments<'_>) {
|
||||
if self.prefetch.trace_errors {
|
||||
eprintln!("RING-PREFETCH {what}");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ring_prefetch(&self) -> Option<RingPrefetchPolicy> {
|
||||
self.prefetch.policy
|
||||
}
|
||||
|
||||
/// Copies the predicted missing experts of `target.layer` into its ring's stage slots; returns how many. Never
|
||||
/// fails the caller: a refused or failed prefetch copies less (or nothing) and the ring copies the rest as usual.
|
||||
pub fn prefetch_ring_layer(
|
||||
&mut self,
|
||||
target: PrefetchTarget<'_, '_, '_, 'ctx>,
|
||||
mut sources: impl FnMut(u32) -> PrefetchSource,
|
||||
) -> usize {
|
||||
if self.prefetch.policy.is_none() || self.cancel_ring_prefetch().is_err() || !self.prefetch_allowed(&target) {
|
||||
return 0;
|
||||
}
|
||||
let _span = crate::host_profile::span("ring.prefetch_issue");
|
||||
let issued = self.issue_prefetch(&target, &mut sources);
|
||||
if let Err(error) = &issued {
|
||||
// a copy may have been queued for the failed expert: let it land before anything is dropped
|
||||
crate::host_profile::add("ring.prefetch_failed", 1.0);
|
||||
self.trace_prefetch(format_args!("layer={} issue failed: {error:?}", target.layer));
|
||||
let _ = self.copy.as_ref().map(OriginalGpuStream::synchronize);
|
||||
}
|
||||
let count = self.prefetch.pending.as_ref().map_or(0, |p| p.entries.len());
|
||||
self.trace_prefetch(format_args!("layer={} issued={count}", target.layer));
|
||||
if count == 0 {
|
||||
self.prefetch.pending = None;
|
||||
} else {
|
||||
self.detach_drains();
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
/// `detach_drains` only (EXPERIMENTAL): the mixer's drains stop waiting for the prefetch copies; the next ring's
|
||||
/// `take_ring_prefetch` restores them.
|
||||
fn detach_drains(&mut self) {
|
||||
if !self.prefetch.policy.is_some_and(|p| p.detach_drains) {
|
||||
return;
|
||||
}
|
||||
if let Some(Ok(copy)) = self.copy.as_mut().map(|c| c.with_enqueue(Ok)) {
|
||||
crate::compute_drain::set_background(copy);
|
||||
}
|
||||
}
|
||||
|
||||
/// No chunk stream, a registered (page-locked) bank, a healthy schedule and a layer that exists.
|
||||
fn prefetch_allowed(&self, target: &PrefetchTarget<'_, '_, '_, 'ctx>) -> bool {
|
||||
self.stream.is_none()
|
||||
&& !self.is_failed()
|
||||
&& target.layer < 48
|
||||
&& !target.bank.pageable()
|
||||
&& target.bank.cache_context_matches(self.context)
|
||||
&& target.read.context_matches(self.context)
|
||||
&& !skip_expert_dma()
|
||||
&& crate::compute_drain::background() == 0
|
||||
}
|
||||
|
||||
/// Predicts, then copies expert after expert into slots 0, 1, ...; the set is kept as it grows.
|
||||
fn issue_prefetch(
|
||||
&mut self,
|
||||
target: &PrefetchTarget<'_, '_, '_, 'ctx>,
|
||||
sources: &mut impl FnMut(u32) -> PrefetchSource,
|
||||
) -> Result<()> {
|
||||
let lease = target.read.lease();
|
||||
let slots = lease.copy_ring_slots()?.min(self.events.len());
|
||||
let policy = self.prefetch.policy.ok_or(Error::ContextPoisoned)?;
|
||||
let history = self.prefetch.history.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let resident = |e: u32| lease.cache_expert_span(target.layer, e as usize).map_or(true, |s| s.is_some());
|
||||
let experts = history.predict(target.layer, policy.budget(slots), resident);
|
||||
for expert in experts {
|
||||
let Some((spans, formats)) = sources(expert) else { continue };
|
||||
self.prefetch_one(target, &spans, formats)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Copies one expert into the next free prefetch slot; an expert of another format than the set is skipped.
|
||||
fn prefetch_one(
|
||||
&mut self,
|
||||
target: &PrefetchTarget<'_, '_, '_, 'ctx>,
|
||||
spans: &[ResidentExpertBankSpan; 3],
|
||||
formats: [MmqFormat; 3],
|
||||
) -> Result<()> {
|
||||
let plan = Self::prefetch_plan(target.layer, formats)?;
|
||||
let pending = self.prefetch.pending.get_or_insert_with(|| PendingPrefetch {
|
||||
layer: target.layer,
|
||||
bank: Rc::clone(target.bank),
|
||||
blob: plan.blob,
|
||||
entries: Vec::new(),
|
||||
});
|
||||
if pending.blob != plan.blob {
|
||||
return Ok(());
|
||||
}
|
||||
let slot = pending.entries.len();
|
||||
let span = target.read.lease().copy_ring_span(slot)?;
|
||||
Self::check_prefetch_slot(target.read, span, plan.blob)?;
|
||||
let entry = Ring::prefetch_into_slot(self, target.bank, spans, (slot, span), &plan)?;
|
||||
self.prefetch.pending.as_mut().ok_or(Error::ContextPoisoned)?.entries.push(entry);
|
||||
profile_prefetch("ring.prefetch_issued", 1, plan.blob);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The ring plan of one expert of `layer` in `formats` (the same checks as `Ring::new`).
|
||||
fn prefetch_plan(layer: usize, formats: [MmqFormat; 3]) -> Result<RingPlan> {
|
||||
if formats[0] != formats[1] || !FORMATS[..5].contains(&formats[0]) || !FORMATS[5..].contains(&formats[2]) {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
let (gu, down, blob) = Ring::blob_geometry(&formats)?;
|
||||
Ok(RingPlan { layer, groups: 0, formats, gu, down, blob, count: 0 })
|
||||
}
|
||||
|
||||
/// A stage slot holds the blob and overlaps no temporary role of the arena (`Ring::admit_slots`).
|
||||
fn check_prefetch_slot(
|
||||
read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>,
|
||||
(h, n): (ffi::BufferHandle, usize),
|
||||
blob: usize,
|
||||
) -> Result<()> {
|
||||
if n < blob {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
h.validate_projection_extent(n, 256)?;
|
||||
for role in 0..TMP {
|
||||
let (a, m) = GroupArena::span(read, role)?;
|
||||
if h.overlaps(blob, a, m) {
|
||||
return Err(Error::OutputAliasesInput);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The copied set for the ring being built (the drains wait for the copy stream again from here on).
|
||||
pub(super) fn take_ring_prefetch(&mut self) -> Option<PendingPrefetch<'ctx>> {
|
||||
let pending = self.prefetch.pending.take()?;
|
||||
self.restore_drains();
|
||||
Some(pending)
|
||||
}
|
||||
|
||||
/// Drops a set no ring consumes: its copies finish before the bank reference goes.
|
||||
pub(super) fn drain_dropped_prefetch(&mut self, pending: PendingPrefetch<'ctx>) -> Result<()> {
|
||||
let drained = self.copy.as_ref().map_or(Ok(()), OriginalGpuStream::synchronize);
|
||||
if drained.is_err() {
|
||||
self.failed = true;
|
||||
std::mem::forget(pending);
|
||||
return drained;
|
||||
}
|
||||
drop(pending);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drops a set no ring took (a failed chunk, a chunk stream starting, the forward's exit). Idempotent.
|
||||
pub fn cancel_ring_prefetch(&mut self) -> Result<()> {
|
||||
let Some(pending) = self.take_ring_prefetch() else { return Ok(()) };
|
||||
self.trace_prefetch(format_args!("layer={} cancelled={}", pending.layer, pending.entries.len()));
|
||||
profile_prefetch("ring.prefetch_wasted", pending.entries.len(), pending.blob);
|
||||
self.drain_dropped_prefetch(pending)
|
||||
}
|
||||
|
||||
/// Drains wait for the copy stream again; buffers freed meanwhile are released now.
|
||||
fn restore_drains(&mut self) {
|
||||
if crate::compute_drain::background() != 0 && self.stream.is_none() {
|
||||
crate::compute_drain::set_background(0);
|
||||
if self.context.flush_deferred_frees().is_err() {
|
||||
self.failed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -127,6 +127,7 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
|
||||
stream_events: Vec::new(),
|
||||
stream_started: None,
|
||||
status_pool: None,
|
||||
prefetch: RingPrefetch::default(),
|
||||
}
|
||||
}
|
||||
/// Create the copy and compute streams and the copied/used events of `slots` ring slots.
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
// Batched numerical guard of the MTP draft step (LELEKA_DRAFT_CHECK_MERGE, off by default).
|
||||
//
|
||||
// One launch runs the guards of a run of ADJACENT check launches of the step program: grid.y selects the entry, and
|
||||
// every entry is checked by exactly the loop and the predicate of the single-check kernels
|
||||
// `mtp_original_finite` and `mtp_original_q8_guard` (mtp_original_tail.cu / mtp_original_full_checks.cu), and sets
|
||||
// the same status word of its own with the same `atomicOr(status, 1)`. Nothing is read from device memory but the
|
||||
// checked buffer, nothing is written but the entry's status word; the status words are therefore bit-identical to the
|
||||
// ones the separate launches leave.
|
||||
//
|
||||
// The descriptor is ONE by-value parameter of 114 u64 words (the shape of the GrMulti parameter, so the host side
|
||||
// reuses its argument type):
|
||||
// w[0] number of entries (1..=28)
|
||||
// w[1 + 4*e] address of the checked buffer of entry e
|
||||
// w[2 + 4*e] low 32 bits: element count n (floats, or Q8_1 blocks); high 32 bits: kind (0 = f32 words, 1 = Q8_1
|
||||
// block scales)
|
||||
// w[3 + 4*e] address of the entry's status word
|
||||
// w[4 + 4*e] reserved, zero
|
||||
// Launch: grid (ceil(max n / 256), entries, 1), block (256, 1, 1). The grid-stride loop covers every element for any
|
||||
// grid.x, so an entry shorter than the longest one simply has idle blocks.
|
||||
#include <cuda_fp16.h>
|
||||
#include <cuda_runtime.h>
|
||||
#include <cstdint>
|
||||
namespace strata::kernels {
|
||||
struct Q81Block { half2 ds; int8_t qs[32]; };
|
||||
static_assert(sizeof(Q81Block) == 36, "Q8_1 block layout");
|
||||
struct CheckBatch { unsigned long long w[114]; };
|
||||
static_assert(sizeof(CheckBatch) == 912, "the descriptor is the 912-byte by-value parameter of GrMulti");
|
||||
extern "C" __global__ void mtp_original_check_batch(CheckBatch b) {
|
||||
const unsigned entry = blockIdx.y;
|
||||
if (entry >= static_cast<unsigned>(b.w[0])) return;
|
||||
const unsigned long long data = b.w[1 + 4 * entry];
|
||||
const unsigned long long meta = b.w[2 + 4 * entry];
|
||||
int* status = reinterpret_cast<int*>(b.w[3 + 4 * entry]);
|
||||
const int n = static_cast<int>(meta & 0xffffffffull);
|
||||
const int q8 = static_cast<int>(meta >> 32) == 1;
|
||||
for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x) {
|
||||
if (!q8) {
|
||||
if (!isfinite(reinterpret_cast<const float*>(data)[i])) atomicOr(status, 1);
|
||||
} else {
|
||||
float2 ds = __half22float2(reinterpret_cast<const Q81Block*>(data)[i].ds);
|
||||
if (!isfinite(ds.x) || !isfinite(ds.y)) atomicOr(status, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace strata::kernels
|
||||
Binary file not shown.
@@ -0,0 +1,155 @@
|
||||
//! `LELEKA_DRAFT_CHECK_MERGE` (off by default): the adjacent finite and Q8_1 scale guards of a draft step program are
|
||||
//! launched as one `mtp_original_check_batch` (docs/experiments/step-ledger.md, row O8). The grouping and the
|
||||
//! descriptor are the pure `leleka_cuda_model::draft_check_batch`; this module classifies the commands of the two
|
||||
//! command lists (the scalar prefix and the tail), builds the batched commands, owns the batch module and launches it.
|
||||
//!
|
||||
//! Only checks that are neighbours in the list are grouped, so no check moves across another command.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use leleka_cuda_model::draft_check_batch::{self as batch, Check, CheckKind, THREADS};
|
||||
|
||||
/// Placeholder asset of a batched check in both command lists (the real module tables are far shorter).
|
||||
const BATCH_ASSET: usize = usize::MAX;
|
||||
/// Module of the single-check kernels in the tail command list, and their entries (finite, Q8_1 scales).
|
||||
const TAIL_CHECKS: usize = 18;
|
||||
const TAIL_CHECK_ENTRIES: (usize, usize) = (0, 1);
|
||||
/// The same in the scalar prefix command list.
|
||||
const PREFIX_CHECKS: usize = 2;
|
||||
const PREFIX_CHECK_ENTRIES: (usize, usize) = (11, 12);
|
||||
/// The first prefix commands are the status reset and the embedding lookup; the native embedding is captured by their
|
||||
/// index, so they stay where they are.
|
||||
const PREFIX_KEEP: usize = 2;
|
||||
|
||||
/// The sealed batch module, loaded once for each of the two launch interfaces of the program.
|
||||
pub(super) struct CheckBatchModules {
|
||||
tail: Rc<FM>,
|
||||
prefix: Rc<Module>,
|
||||
}
|
||||
|
||||
impl CheckBatchModules {
|
||||
/// Loads the sealed `mtp_original_check_batch.ptx` into `context`.
|
||||
pub(super) fn load(context: &Context<'_>) -> Result<Self> {
|
||||
let g = context.enter().inspect_err(|_| {
|
||||
context.poison();
|
||||
context.retain_driver();
|
||||
})?;
|
||||
let loaded = Self::load_current();
|
||||
let pop = g.finish();
|
||||
if pop.is_err() {
|
||||
context.poison();
|
||||
context.retain_driver();
|
||||
}
|
||||
combine(loaded, pop)
|
||||
}
|
||||
|
||||
fn load_current() -> Result<Self> {
|
||||
let (ptx, entries) = (symbols::CHECK_BATCH.0, symbols::CHECK_BATCH.1);
|
||||
let sealed = crate::sealed_ptx::pinned(ptx, Some(symbols::CHECK_BATCH_PIN));
|
||||
let ptx = sealed.ok_or(Error::UnsupportedQwenOperation)?;
|
||||
Ok(Self { tail: Rc::new(FM::load(ptx, entries)?), prefix: Rc::new(Module::load(ptx, entries)?) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `shape` the launch shape of the separate check of `check`?
|
||||
fn is_single_launch(shape: &LaunchShape, check: &Check) -> bool {
|
||||
shape.dims.grid == [check.single_grid(), 1, 1] && shape.dims.block == [THREADS, 1, 1] && shape.shared == 0
|
||||
}
|
||||
|
||||
fn check_of(kind: CheckKind, words: (u64, i32, u64), shape: &LaunchShape) -> Option<Check> {
|
||||
let (data, count, flag) = words;
|
||||
let check = Check { kind, data, count: u32::try_from(count).ok()?, flag };
|
||||
is_single_launch(shape, &check).then_some(check)
|
||||
}
|
||||
|
||||
/// Which single-check kernel `(asset, index)` is, given the module and the entries of the list.
|
||||
fn kind_of((asset, index): (usize, usize), module: usize, entries: (usize, usize)) -> Option<CheckKind> {
|
||||
if asset != module {
|
||||
None
|
||||
} else if index == entries.0 {
|
||||
Some(CheckKind::Finite)
|
||||
} else if index == entries.1 {
|
||||
Some(CheckKind::Q8Scale)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The check a tail command is, if it is exactly one separate check launch.
|
||||
fn tail_check(command: &FullCommand) -> Option<Check> {
|
||||
let kind = kind_of((command.asset, command.index), TAIL_CHECKS, TAIL_CHECK_ENTRIES)?;
|
||||
check_of(kind, command.args.check_words()?, &command.shape)
|
||||
}
|
||||
|
||||
/// The check a scalar prefix command is, if it is exactly one separate check launch.
|
||||
fn prefix_check(command: &ScalarCommand) -> Option<Check> {
|
||||
let ScalarCommand::Kernel { asset, index, shape, args } = command else { return None };
|
||||
let kind = kind_of((*asset, *index), PREFIX_CHECKS, PREFIX_CHECK_ENTRIES)?;
|
||||
check_of(kind, args.check_words()?, shape)
|
||||
}
|
||||
|
||||
fn batch_shape(launch: &batch::BatchLaunch) -> LaunchShape {
|
||||
LaunchShape::new(launch.grid, [THREADS, 1, 1], 0)
|
||||
}
|
||||
|
||||
fn tail_batch(checks: &[Check]) -> Result<FullCommand> {
|
||||
let launch = batch::encode(checks)?;
|
||||
let shape = batch_shape(&launch);
|
||||
Ok(FullCommand { asset: BATCH_ASSET, index: 0, shape, args: FA::new(vec![F::GrMulti(launch.words)])? })
|
||||
}
|
||||
|
||||
fn prefix_batch(checks: &[Check]) -> Result<ScalarCommand> {
|
||||
let launch = batch::encode(checks)?;
|
||||
let shape = batch_shape(&launch);
|
||||
Ok(ScalarCommand::Kernel {
|
||||
asset: BATCH_ASSET,
|
||||
index: 0,
|
||||
shape,
|
||||
args: Arguments::new(vec![Arg::GrMulti(launch.words)])?,
|
||||
})
|
||||
}
|
||||
|
||||
/// The tail commands with every run of adjacent checks launched as one batch.
|
||||
pub(super) fn merge_tail(commands: Vec<FullCommand>) -> Result<Vec<FullCommand>> {
|
||||
batch::merge_adjacent(commands, 0, tail_check, tail_batch)
|
||||
}
|
||||
|
||||
/// The scalar prefix commands with every run of adjacent checks launched as one batch.
|
||||
pub(super) fn merge_prefix(commands: Vec<ScalarCommand>) -> Result<Vec<ScalarCommand>> {
|
||||
batch::merge_adjacent(commands, PREFIX_KEEP, prefix_check, prefix_batch)
|
||||
}
|
||||
|
||||
/// Launch one command of a scalar prefix list (the catch-up and the step prefix).
|
||||
pub(super) fn launch_prefix_command(
|
||||
modules: &[Rc<Module>; 6],
|
||||
batch: Option<&CheckBatchModules>,
|
||||
stream: usize,
|
||||
command: &mut ScalarCommand,
|
||||
) -> Result<()> {
|
||||
let ScalarCommand::Kernel { asset, index, shape, args } = command else {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
};
|
||||
if *asset == BATCH_ASSET {
|
||||
return batch.ok_or(Error::ContextPoisoned)?.prefix.launch(*index, *shape, stream, args);
|
||||
}
|
||||
modules.get(*asset).ok_or(Error::InvalidQwenShape)?.launch(*index, *shape, stream, args)
|
||||
}
|
||||
|
||||
/// Launch a batched tail command.
|
||||
pub(super) fn launch_tail_batch(
|
||||
batch: Option<&CheckBatchModules>,
|
||||
stream: usize,
|
||||
command: &mut FullCommand,
|
||||
) -> Result<()> {
|
||||
batch.ok_or(Error::ContextPoisoned)?.tail.launch(command.index, command.shape, stream, &mut command.args)
|
||||
}
|
||||
|
||||
/// Does the tail command launch a batch?
|
||||
pub(super) fn is_tail_batch(command: &FullCommand) -> bool {
|
||||
command.asset == BATCH_ASSET
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod gpu_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,186 @@
|
||||
//! Model-free GPU proof of `mtp_original_check_batch`: for a finite buffer set and for a NaN or Inf placed at the
|
||||
//! edges and in the middle of every checked buffer (floats and Q8_1 scale pairs), the status words of one batched
|
||||
//! launch, through the tail interface and through the scalar prefix interface, equal the ones of the separate
|
||||
//! launches of `mtp_original_finite` and `mtp_original_q8_guard`.
|
||||
//! Run: `cargo test -p leleka-cuda-driver --features cuda-driver --lib check_batch_program_gpu -- --ignored`.
|
||||
use super::*;
|
||||
use crate::{DeviceBuffer, Driver};
|
||||
use leleka_cuda_model::draft_check_batch::encode;
|
||||
|
||||
const FLOATS: [usize; 3] = [12288, 640, 4];
|
||||
const BLOCKS: usize = 80;
|
||||
const WORDS: usize = 16;
|
||||
|
||||
fn floats_bytes(n: usize, at: Option<(usize, f32)>) -> Vec<u8> {
|
||||
let mut v = vec![1.0f32; n];
|
||||
if let Some((i, x)) = at {
|
||||
v[i] = x;
|
||||
}
|
||||
v.iter().flat_map(|x| x.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
/// `BLOCKS` Q8_1 blocks of 36 bytes: a finite scale pair, one half replaced by a non-finite code at (block, half).
|
||||
fn blocks_bytes(at: Option<(usize, usize, u16)>) -> Vec<u8> {
|
||||
let mut b = vec![0u8; BLOCKS * 36];
|
||||
for i in 0..BLOCKS {
|
||||
b[i * 36..i * 36 + 4].copy_from_slice(&[0x00, 0x38, 0x00, 0x40]);
|
||||
}
|
||||
if let Some((block, half, code)) = at {
|
||||
let o = block * 36 + 2 * half;
|
||||
b[o..o + 2].copy_from_slice(&code.to_le_bytes());
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
struct Fault {
|
||||
floats: [Option<(usize, f32)>; 3],
|
||||
scale: Option<(usize, usize, u16)>,
|
||||
}
|
||||
|
||||
fn faults() -> Vec<Fault> {
|
||||
let none = || Fault { floats: [None; 3], scale: None };
|
||||
let mut all = vec![none()];
|
||||
for (buffer, n) in FLOATS.into_iter().enumerate() {
|
||||
for i in [0, 1, 255, 256, n / 2, n - 1] {
|
||||
for x in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
let mut f = none();
|
||||
f.floats[buffer] = Some((i.min(n - 1), x));
|
||||
all.push(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
for block in [0, 1, 79] {
|
||||
for half in [0, 1] {
|
||||
for code in [0x7e00u16, 0x7c00, 0xfc00] {
|
||||
all.push(Fault { floats: [None; 3], scale: Some((block, half, code)) });
|
||||
}
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
fn address(buffer: &DeviceBuffer<'_>) -> u64 {
|
||||
buffer.handle.expect("handle").qwen_address()
|
||||
}
|
||||
|
||||
fn read_status(status: &DeviceBuffer<'_>) -> Vec<u32> {
|
||||
let bytes = status.copy_to_owned(WORDS * 4).expect("read");
|
||||
bytes.chunks_exact(4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).collect()
|
||||
}
|
||||
|
||||
/// The device buffers, the checks over them and the two ways to launch them.
|
||||
struct Rig<'a> {
|
||||
context: &'a Context<'a>,
|
||||
stream: usize,
|
||||
data: Vec<DeviceBuffer<'a>>,
|
||||
blocks: DeviceBuffer<'a>,
|
||||
status: DeviceBuffer<'a>,
|
||||
checks: Vec<Check>,
|
||||
batch: CheckBatchModules,
|
||||
singles: FM,
|
||||
}
|
||||
|
||||
impl<'a> Rig<'a> {
|
||||
fn new(context: &'a Context<'a>, stream: usize) -> Self {
|
||||
let data: Vec<DeviceBuffer<'a>> = FLOATS.iter().map(|n| context.allocate(n * 4).expect("alloc")).collect();
|
||||
let blocks = context.allocate(BLOCKS * 36).expect("alloc");
|
||||
let status = context.allocate(WORDS * 4).expect("alloc");
|
||||
let bases = [(CheckKind::Finite, &data[0], FLOATS[0]), (CheckKind::Finite, &data[1], FLOATS[1])];
|
||||
let bases = bases.into_iter().chain([(CheckKind::Finite, &data[2], FLOATS[2])]);
|
||||
let bases = bases.chain([(CheckKind::Q8Scale, &blocks, BLOCKS)]);
|
||||
let flag = address(&status);
|
||||
let checks = bases
|
||||
.enumerate()
|
||||
.map(|(i, (kind, b, count))| Check {
|
||||
kind,
|
||||
data: address(b),
|
||||
count: count as u32,
|
||||
flag: flag + 4 * i as u64,
|
||||
})
|
||||
.collect();
|
||||
let batch = CheckBatchModules::load(context).expect("sealed batch asset");
|
||||
Self { context, stream, data, blocks, status, checks, batch, singles: Self::load_singles(context) }
|
||||
}
|
||||
|
||||
/// The separate guard kernels; loading a module needs the context current, as `CheckBatchModules::load` does.
|
||||
fn load_singles(context: &Context<'_>) -> FM {
|
||||
let (ptx, entries) = symbols::ASSETS[TAIL_CHECKS];
|
||||
let guard = context.enter().expect("enter");
|
||||
let singles = FM::load(ptx, entries).expect("single checks");
|
||||
guard.finish().expect("pop");
|
||||
singles
|
||||
}
|
||||
|
||||
fn upload(&mut self, fault: &Fault) {
|
||||
for (i, buffer) in self.data.iter_mut().enumerate() {
|
||||
buffer.copy_from(&floats_bytes(FLOATS[i], fault.floats[i])).expect("upload");
|
||||
}
|
||||
self.blocks.copy_from(&blocks_bytes(fault.scale)).expect("upload");
|
||||
}
|
||||
|
||||
fn run(&mut self, launch: impl FnOnce(&Self)) -> Vec<u32> {
|
||||
self.status.copy_from(&[0u8; WORDS * 4]).expect("zero");
|
||||
launch(self);
|
||||
self.context.synchronize().expect("sync");
|
||||
read_status(&self.status)
|
||||
}
|
||||
|
||||
fn separate(&self) {
|
||||
for c in &self.checks {
|
||||
let index = usize::from(c.kind == CheckKind::Q8Scale);
|
||||
let mut args = FA::new(vec![F::U64(c.data), F::I32(c.count as i32), F::U64(c.flag)]).unwrap();
|
||||
let shape = single_shape(c.single_grid());
|
||||
self.singles.launch(index, shape, self.stream, &mut args).expect("single");
|
||||
}
|
||||
}
|
||||
|
||||
fn tail(&self) {
|
||||
let launch = encode(&self.checks).unwrap();
|
||||
let mut args = FA::new(vec![F::GrMulti(launch.words.clone())]).unwrap();
|
||||
self.batch.tail.launch(0, batch_shape(&launch), self.stream, &mut args).expect("batch");
|
||||
}
|
||||
|
||||
fn prefix(&self) {
|
||||
let launch = encode(&self.checks).unwrap();
|
||||
let mut args = Arguments::new(vec![Arg::GrMulti(launch.words.clone())]).unwrap();
|
||||
self.batch.prefix.launch(0, batch_shape(&launch), self.stream, &mut args).expect("batch");
|
||||
}
|
||||
}
|
||||
|
||||
/// A readable name of a case for the verdict line.
|
||||
fn describe(fault: &Fault) -> String {
|
||||
let floats = fault.floats.iter().enumerate().find_map(|(i, f)| f.map(|(at, x)| format!("floats[{i}][{at}]={x}")));
|
||||
let scale = fault.scale.map(|(block, half, code)| format!("scale block {block} half {half} code {code:#06x}"));
|
||||
floats.or(scale).unwrap_or_else(|| "clean".to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Root-only: needs a CUDA device"]
|
||||
fn the_batched_guard_leaves_the_status_words_of_the_separate_launches() {
|
||||
let driver = Driver::load().expect("driver");
|
||||
let context = driver.device(0).expect("device").create_context(1usize << 30).expect("context");
|
||||
// the workspace owns the stream: it must outlive every launch
|
||||
let workspace = context.native_batch_workspace().expect("workspace");
|
||||
let stream = workspace.blas().expect("blas").stream();
|
||||
let mut rig = Rig::new(&context, stream);
|
||||
let guard = context.enter().expect("enter");
|
||||
let (mut total, mut caught, mut differ) = (0, 0, 0);
|
||||
for fault in faults() {
|
||||
rig.upload(&fault);
|
||||
let separate = rig.run(Rig::separate);
|
||||
let (tail, prefix) = (rig.run(Rig::tail), rig.run(Rig::prefix));
|
||||
let verdict = if tail == separate && prefix == separate { "equal" } else { "DIFFER" };
|
||||
println!("CHECK-BATCH case {} status words {verdict} (separate {separate:?})", describe(&fault));
|
||||
total += 1;
|
||||
caught += usize::from(separate.iter().any(|w| *w != 0));
|
||||
differ += usize::from(verdict == "DIFFER");
|
||||
}
|
||||
guard.finish().expect("pop");
|
||||
println!("CHECK-BATCH summary: {total} cases, {caught} raise a flag, {differ} differ");
|
||||
assert_eq!(differ, 0, "the batched guard must leave the separate launches' status words");
|
||||
assert_eq!(total - caught, 1, "exactly the clean case raises nothing");
|
||||
}
|
||||
|
||||
fn single_shape(grid: u32) -> LaunchShape {
|
||||
LaunchShape::new([grid, 1, 1], [THREADS, 1, 1], 0)
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
//! The command lists of a draft step with merged checks: the adapters recognise exactly the separate check launches,
|
||||
//! the merged lists stand for the separate ones, and the sealed batch asset is the one the kernel source builds.
|
||||
use super::*;
|
||||
use crate::sealed_ptx::test_support::{assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted};
|
||||
use leleka_cuda_model::draft_check_batch::{BATCH_WORDS, ENTRY_WORDS};
|
||||
|
||||
/// What a command is, for comparing a list before and after merging.
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum Item {
|
||||
Check(Check),
|
||||
Other(usize, usize),
|
||||
}
|
||||
|
||||
fn single_shape(count: u32) -> LaunchShape {
|
||||
LaunchShape::new([count.div_ceil(THREADS), 1, 1], [THREADS, 1, 1], 0)
|
||||
}
|
||||
|
||||
fn tail_check_command(index: usize, buffer: u64, count: i32, slot: u64) -> FullCommand {
|
||||
let args = vec![F::U64(buffer), F::I32(count), F::U64(0x9000 + 4 * slot)];
|
||||
FullCommand { asset: TAIL_CHECKS, index, shape: single_shape(count as u32), args: FA::new(args).unwrap() }
|
||||
}
|
||||
|
||||
fn tail_other(asset: usize, index: usize) -> FullCommand {
|
||||
let shape = LaunchShape::new([1, 1, 1], [32, 1, 1], 0);
|
||||
FullCommand { asset, index, shape, args: FA::new(vec![F::U64(8)]).unwrap() }
|
||||
}
|
||||
|
||||
fn prefix_check_command(index: usize, buffer: u64, count: i32, slot: u64) -> ScalarCommand {
|
||||
let args = Arguments::new(vec![Arg::U64(buffer), Arg::I32(count), Arg::U64(0x9000 + 4 * slot)]).unwrap();
|
||||
ScalarCommand::Kernel { asset: PREFIX_CHECKS, index, shape: single_shape(count as u32), args }
|
||||
}
|
||||
|
||||
fn prefix_other(asset: usize, index: usize) -> ScalarCommand {
|
||||
let shape = LaunchShape::new([1, 1, 1], [32, 1, 1], 0);
|
||||
ScalarCommand::Kernel { asset, index, shape, args: Arguments::new(vec![Arg::U64(8)]).unwrap() }
|
||||
}
|
||||
|
||||
/// Decodes a batched command's descriptor back into the checks it stands for.
|
||||
fn decode(words: &[u64; BATCH_WORDS], shape: &LaunchShape) -> Vec<Check> {
|
||||
let entries = words[0] as usize;
|
||||
assert!(entries >= 2, "a batch of one is never built");
|
||||
assert_eq!(shape.dims.grid[1] as usize, entries);
|
||||
assert_eq!((shape.dims.block, shape.shared), ([THREADS, 1, 1], 0));
|
||||
(0..entries)
|
||||
.map(|e| {
|
||||
let meta = words[2 + ENTRY_WORDS * e];
|
||||
let kind = if meta >> 32 == 1 { CheckKind::Q8Scale } else { CheckKind::Finite };
|
||||
Check { kind, data: words[1 + ENTRY_WORDS * e], count: meta as u32, flag: words[3 + ENTRY_WORDS * e] }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn tail_items(commands: &[FullCommand]) -> Vec<Item> {
|
||||
let mut items = Vec::new();
|
||||
for c in commands {
|
||||
if c.asset == BATCH_ASSET {
|
||||
items.extend(decode(c.args.gr_words().unwrap(), &c.shape).into_iter().map(Item::Check));
|
||||
} else {
|
||||
items.push(tail_check(c).map_or(Item::Other(c.asset, c.index), Item::Check));
|
||||
}
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
fn prefix_items(commands: &[ScalarCommand]) -> Vec<Item> {
|
||||
let mut items = Vec::new();
|
||||
for c in commands {
|
||||
let ScalarCommand::Kernel { asset, index, shape, args } = c else { panic!("copy") };
|
||||
if *asset == BATCH_ASSET {
|
||||
items.extend(decode(args.gr_words().unwrap(), shape).into_iter().map(Item::Check));
|
||||
} else {
|
||||
items.push(prefix_check(c).map_or(Item::Other(*asset, *index), Item::Check));
|
||||
}
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
fn tail_list() -> Vec<FullCommand> {
|
||||
vec![
|
||||
tail_other(13, 5),
|
||||
tail_check_command(0, 0x1000, 12288, 0),
|
||||
tail_other(16, 0),
|
||||
tail_check_command(0, 0x2000, 6144, 1),
|
||||
tail_check_command(0, 0x3000, 10240, 7),
|
||||
tail_check_command(1, 0x4000, 192, 5),
|
||||
tail_check_command(0, 0x5000, 4, 10),
|
||||
tail_other(13, 6),
|
||||
tail_check_command(0, 0x6000, 2560, 11),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tail_list_loses_the_adjacent_check_launches_and_nothing_else() {
|
||||
let list = tail_list();
|
||||
let before = tail_items(&list);
|
||||
let merged = merge_tail(list).unwrap();
|
||||
assert_eq!(tail_items(&merged), before);
|
||||
// 9 commands: kernel, check, kernel, 4 adjacent checks (one batch), kernel, check
|
||||
assert_eq!(merged.len(), 6);
|
||||
assert_eq!(merged.iter().filter(|c| c.asset == BATCH_ASSET).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_prefix_list_keeps_its_first_commands_and_merges_the_rest() {
|
||||
let list = vec![
|
||||
prefix_other(0, 11),
|
||||
prefix_check_command(11, 0x1000, 2560, 0),
|
||||
prefix_check_command(11, 0x2000, 2560, 1),
|
||||
prefix_other(3, 0),
|
||||
prefix_check_command(11, 0x3000, 2560, 6),
|
||||
prefix_check_command(12, 0x4000, 80, 6),
|
||||
prefix_check_command(11, 0x5000, 10240, 7),
|
||||
];
|
||||
let before = prefix_items(&list);
|
||||
let merged = prefix_items(&merge_prefix(list).unwrap());
|
||||
assert_eq!(merged, before);
|
||||
let list = vec![
|
||||
prefix_other(0, 11),
|
||||
prefix_check_command(11, 0x1000, 2560, 0),
|
||||
prefix_check_command(11, 0x2000, 2560, 1),
|
||||
prefix_check_command(11, 0x3000, 2560, 2),
|
||||
];
|
||||
// index 1 is not merged (the native embedding is captured by command index), 2 and 3 are
|
||||
let merged = merge_prefix(list).unwrap();
|
||||
assert_eq!(merged.len(), 3);
|
||||
assert!(matches!(&merged[2], ScalarCommand::Kernel { asset, .. } if *asset == BATCH_ASSET));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_exact_separate_check_launches_are_recognised() {
|
||||
let good = tail_check_command(0, 0x1000, 600, 3);
|
||||
assert_eq!(tail_check(&good), Some(Check { kind: CheckKind::Finite, data: 0x1000, count: 600, flag: 0x900c }));
|
||||
// another kernel of the module, another module, a different grid, other arguments, a negative count
|
||||
let mut other_entry = tail_check_command(0, 0x1000, 600, 3);
|
||||
other_entry.index = 2;
|
||||
let mut other_module = tail_check_command(0, 0x1000, 600, 3);
|
||||
other_module.asset = 17;
|
||||
let mut other_grid = tail_check_command(0, 0x1000, 600, 3);
|
||||
other_grid.shape = LaunchShape::new([4, 1, 1], [THREADS, 1, 1], 0);
|
||||
let mut shared = tail_check_command(0, 0x1000, 600, 3);
|
||||
shared.shape = LaunchShape::new([3, 1, 1], [THREADS, 1, 1], 16);
|
||||
let mut extra_arg = tail_check_command(0, 0x1000, 600, 3);
|
||||
extra_arg.args = FA::new(vec![F::U64(0x1000), F::I32(600), F::U64(0x900c), F::I32(1)]).unwrap();
|
||||
let negative = tail_check_command(0, 0x1000, -1, 3);
|
||||
for command in [&other_entry, &other_module, &other_grid, &shared, &extra_arg, &negative] {
|
||||
assert!(tail_check(command).is_none());
|
||||
}
|
||||
assert_eq!(tail_check(&tail_check_command(1, 0x2000, 20, 5)).unwrap().kind, CheckKind::Q8Scale);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_that_is_not_a_check_is_never_swallowed() {
|
||||
let mut seed = 0x9e37_79b9_7f4a_7c15u64;
|
||||
let mut next = move || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
seed
|
||||
};
|
||||
for _ in 0..100 {
|
||||
let list: Vec<FullCommand> = (0..40)
|
||||
.map(|i| match next() % 4 {
|
||||
0 => tail_other(13, (next() % 5) as usize),
|
||||
1 => tail_check_command(1, 0x1000 * (i + 1), 20 + (next() % 500) as i32, i % 30),
|
||||
_ => tail_check_command(0, 0x1000 * (i + 1), 1 + (next() % 12000) as i32, i % 30),
|
||||
})
|
||||
.collect();
|
||||
let before = tail_items(&list);
|
||||
assert_eq!(tail_items(&merge_tail(list).unwrap()), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_check_kernels_are_the_entries_the_lists_name() {
|
||||
let (_, tail) = symbols::ASSETS[TAIL_CHECKS];
|
||||
assert_eq!(tail[TAIL_CHECK_ENTRIES.0], c"mtp_original_finite");
|
||||
assert_eq!(tail[TAIL_CHECK_ENTRIES.1], c"mtp_original_q8_guard");
|
||||
assert_eq!(TAIL_ENTRIES[PREFIX_CHECK_ENTRIES.0], c"mtp_original_finite");
|
||||
assert_eq!(TAIL_ENTRIES[PREFIX_CHECK_ENTRIES.1], c"mtp_original_q8_guard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_batch_asset_is_the_sealed_ptx_of_its_source() {
|
||||
let (ptx, entries) = symbols::CHECK_BATCH;
|
||||
assert_eq!(entries, [c"mtp_original_check_batch"]);
|
||||
assert!(crate::sealed_ptx::pinned(ptx, Some(symbols::CHECK_BATCH_PIN)).is_some());
|
||||
assert!(crate::sealed_ptx::pinned(one_byte_corrupted(ptx), Some(symbols::CHECK_BATCH_PIN)).is_none());
|
||||
assert_real_sm120_ptx("check batch", ptx, ["mtp_original_check_batch"]);
|
||||
assert_nvcc_13_2_86("check batch", ptx);
|
||||
let text = std::str::from_utf8(&ptx[..ptx.len() - 1]).unwrap();
|
||||
assert!(text.contains("mtp_original_check_batch_param_0[912]"), "one 114-word by-value parameter");
|
||||
assert_eq!(text.matches(".entry").count(), 1);
|
||||
assert_eq!(text.matches("atom.global.or.b32").count(), 2, "one atomicOr per kind, as the single kernels");
|
||||
}
|
||||
@@ -3,8 +3,12 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
#[path = "original_mtp_drafter/original_mtp_drafter_chain_gate.rs"]
|
||||
mod original_mtp_drafter_chain_gate;
|
||||
#[path = "original_mtp_drafter/original_mtp_drafter_finish_chain.rs"]
|
||||
mod original_mtp_drafter_finish_chain;
|
||||
#[path = "original_mtp_drafter/original_mtp_drafter_keep_bank.rs"]
|
||||
mod original_mtp_drafter_keep_bank;
|
||||
#[path = "original_mtp_drafter/original_mtp_drafter_launch_rounds.rs"]
|
||||
mod original_mtp_drafter_launch_rounds;
|
||||
#[path = "original_mtp_drafter/original_mtp_drafter_new_draft.rs"]
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
//! The profile label of the pipelined-chain gate (split out of the finish-chain file to keep it under its line limit).
|
||||
|
||||
/// Which condition of the pipelined chain decided this draft (profile counters `mtp.chain_gate.*`, one per draft).
|
||||
pub(super) fn chain_gate(switch_on: bool, (coupled, min_p, limit): (bool, f32, i32)) -> &'static str {
|
||||
if !switch_on {
|
||||
"mtp.chain_gate.switch_off"
|
||||
} else if coupled {
|
||||
"mtp.chain_gate.coupled"
|
||||
} else if min_p > 0.0 {
|
||||
"mtp.chain_gate.min_p"
|
||||
} else if limit <= 2 {
|
||||
"mtp.chain_gate.short"
|
||||
} else {
|
||||
"mtp.chain_gate.pipelined"
|
||||
}
|
||||
}
|
||||
+161
-3
@@ -42,19 +42,170 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
|
||||
) -> Result<([i32; 8], [f32; 8], usize)> {
|
||||
let mut ids = [0i32; 8];
|
||||
let mut probabilities = [0f32; 8];
|
||||
let output = self.finish_first_step(key)?;
|
||||
ids[0] = output.token;
|
||||
probabilities[0] = output.probability;
|
||||
// draft j writes the cell first + a + j, and the ring ends at MTP_ORIGINAL_MAX_CELLS (upstream `max_steps`)
|
||||
let limit = crate::original_mtp_actor::chain_end_within_cells(
|
||||
(self.max_t as i32 - 1).min(max_drafts),
|
||||
first.saturating_add(a),
|
||||
MTP_ORIGINAL_MAX_CELLS,
|
||||
);
|
||||
let gate = super::original_mtp_drafter_chain_gate::chain_gate(policy.chain_pipeline, (cp, min_p, limit));
|
||||
crate::host_profile::add(gate, 0.0);
|
||||
if policy.chain_pipeline && !cp && min_p <= 0.0 && limit > 2 {
|
||||
let count = self.finish_chain_pipelined(ring, policy, (key, limit), (&mut ids, &mut probabilities))?;
|
||||
return Ok((ids, probabilities, count));
|
||||
}
|
||||
let output = self.finish_first_step(key)?;
|
||||
ids[0] = output.token;
|
||||
probabilities[0] = output.probability;
|
||||
let count = self.finish_chain_steps(ring, policy, (cp, limit, min_p), (&mut ids, &mut probabilities))?;
|
||||
Ok((ids, probabilities, count))
|
||||
}
|
||||
|
||||
/// Chain steps 1..limit enqueued back to back behind the round graph (greedy drafts with `min_p` 0: the depth is
|
||||
/// known up front, every step's cell record is static and its token comes from the device), one stream drain, then
|
||||
/// every step's output is read and the shared numerical flags are checked once. The kernels and their order are
|
||||
/// those of the sequential path; only the host round trip between two steps (stream sync, flag read-back, record
|
||||
/// write, launch) is gone. The step graphs of this path are recorded without the flag resets, so a fault of any
|
||||
/// step stays set until the single read. While a graph is missing it is recorded first, on the idle stream.
|
||||
fn finish_chain_pipelined(
|
||||
&mut self,
|
||||
ring: &mut MtpOriginalInt8<'ctx>,
|
||||
policy: &OriginalMtpFullPolicy,
|
||||
(key, limit): (OriginalGraphKey, i32),
|
||||
(ids, probabilities): (&mut [i32; 8], &mut [f32; 8]),
|
||||
) -> Result<usize> {
|
||||
let steps = 1..limit as usize;
|
||||
let first = if self.chain_graphs_recorded(steps.clone())? {
|
||||
None
|
||||
} else {
|
||||
let first = self.finish_first_step(key)?;
|
||||
self.record_chain_graphs(ring, policy, steps.clone())?;
|
||||
Some(first)
|
||||
};
|
||||
let _span = crate::host_profile::span("mtp.chain_pipelined");
|
||||
let stream = self.stream.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let graphs = self.graphs.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let outputs = Self::run_chain(self.context, (graphs, stream), (key, steps), first);
|
||||
let outputs = outputs.inspect_err(|_| self.fail_if_poisoned())?;
|
||||
for (j, output) in outputs.into_iter().enumerate() {
|
||||
ids[j] = output.token;
|
||||
probabilities[j] = output.probability;
|
||||
}
|
||||
Ok(limit as usize)
|
||||
}
|
||||
|
||||
/// Enqueues the steps back to back, drains the stream once and reads every output.
|
||||
fn run_chain(
|
||||
context: &'ctx Context<'ctx>,
|
||||
(graphs, stream): (&mut ChainGraphs<'ctx>, &mut OriginalGpuStream<'ctx>),
|
||||
(key, steps): (OriginalGraphKey, std::ops::Range<usize>),
|
||||
first: Option<OriginalMtpStepOutput>,
|
||||
) -> Result<Vec<OriginalMtpStepOutput>> {
|
||||
// LELEKA_SERVE_PROFILE: the GPU time of the whole run (events around the enqueues), next to its wall time
|
||||
let mut timing = Self::timing_events(context);
|
||||
if let Some((a, _)) = timing.as_mut() {
|
||||
let _ = a.record(stream);
|
||||
}
|
||||
Self::enqueue_chain(graphs, stream, steps.clone())?;
|
||||
if let Some((_, b)) = timing.as_mut() {
|
||||
let _ = b.record(stream);
|
||||
}
|
||||
let done = stream.synchronize_with_receipt()?;
|
||||
if let Some(ms) = timing.as_ref().and_then(|(a, b)| a.elapsed_ms(b).ok()) {
|
||||
crate::host_profile::add("gpu.mtp_chain_pipelined", f64::from(ms));
|
||||
}
|
||||
Self::chain_outputs(graphs, key, steps, &done, first)
|
||||
}
|
||||
|
||||
fn enqueue_chain(
|
||||
graphs: &mut ChainGraphs<'ctx>,
|
||||
stream: &mut OriginalGpuStream<'ctx>,
|
||||
steps: std::ops::Range<usize>,
|
||||
) -> Result<()> {
|
||||
for j in steps {
|
||||
let graph = graphs.find_mut(chain_key(j))?.ok_or(Error::InvalidQwenShape)?;
|
||||
graph.mtp_stage_chain_ahead()?;
|
||||
graph.enqueue(stream)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The outputs of the round graph (when its read was deferred) and of every step, after the one drain; the flag
|
||||
/// words are checked with the last step.
|
||||
fn chain_outputs(
|
||||
graphs: &mut ChainGraphs<'ctx>,
|
||||
key: OriginalGraphKey,
|
||||
steps: std::ops::Range<usize>,
|
||||
done: &crate::OriginalStreamDrained<'ctx>,
|
||||
first: Option<OriginalMtpStepOutput>,
|
||||
) -> Result<Vec<OriginalMtpStepOutput>> {
|
||||
let mut outputs = Vec::with_capacity(steps.len() + 1);
|
||||
outputs.push(match first {
|
||||
Some(output) => output,
|
||||
None => graphs.find_mut(key)?.ok_or(Error::InvalidQwenShape)?.mtp_finish_drained(done, false)?,
|
||||
});
|
||||
let last = steps.end - 1;
|
||||
for j in steps {
|
||||
let graph = graphs.find_mut(chain_key(j))?.ok_or(Error::InvalidQwenShape)?;
|
||||
outputs.push(graph.mtp_finish_drained(done, j == last)?);
|
||||
}
|
||||
Ok(outputs)
|
||||
}
|
||||
|
||||
fn chain_graphs_recorded(&mut self, steps: std::ops::Range<usize>) -> Result<bool> {
|
||||
let graphs = self.graphs.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
for j in steps {
|
||||
if graphs.find_mut(chain_key(j))?.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Records the missing no-reset step graphs; the stream must be idle (the round graph was read back).
|
||||
fn record_chain_graphs(
|
||||
&mut self,
|
||||
ring: &mut MtpOriginalInt8<'ctx>,
|
||||
policy: &OriginalMtpFullPolicy,
|
||||
steps: std::ops::Range<usize>,
|
||||
) -> Result<()> {
|
||||
for j in steps {
|
||||
self.record_chain_graph(ring, policy, j)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn record_chain_graph(
|
||||
&mut self,
|
||||
ring: &mut MtpOriginalInt8<'ctx>,
|
||||
policy: &OriginalMtpFullPolicy,
|
||||
j: usize,
|
||||
) -> Result<()> {
|
||||
let full = self.full.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let scalar = self.scalar.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let graphs = self.graphs.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let stream = self.stream.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let captures = graphs.captures();
|
||||
let pol = policy.for_capture(j, false);
|
||||
let graph = graphs.record(
|
||||
chain_key(j),
|
||||
stream,
|
||||
|| full.prepare_chain_step(scalar, ring, j, &pol),
|
||||
|c, r| r.capture(c),
|
||||
)?;
|
||||
let metadata = graph.mtp_resource_metadata()?;
|
||||
if graphs.captures() != captures {
|
||||
self.graph_metadata = self.graph_metadata.checked_add(metadata).ok_or(Error::BudgetExceeded)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn fail_if_poisoned(&mut self) {
|
||||
if self.context.is_poisoned() {
|
||||
self.failed = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_first_step(&mut self, key: OriginalGraphKey) -> Result<OriginalMtpStepOutput> {
|
||||
let graphs = self.graphs.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let stream = self.stream.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
@@ -240,3 +391,10 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
|
||||
combine(combine(combine(graphs, scalar), stream), full)
|
||||
}
|
||||
}
|
||||
|
||||
type ChainGraphs<'ctx> = OriginalGraphRegistry<'ctx, OriginalMtpDraftProgram<'ctx>>;
|
||||
|
||||
/// The graph key of the no-reset chain step `j`.
|
||||
fn chain_key(j: usize) -> OriginalGraphKey {
|
||||
OriginalGraphKey::MtpChain { step: j as u8 }
|
||||
}
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
//! The drafter's side of a kept verifier bank (`LELEKA_DECODE_GRAPH_REUSE`, docs/experiments/decode-graph-reuse.md).
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
impl<'ctx> OriginalMtpDrafter<'ctx> {
|
||||
/// End of a request over a verifier bank that STAYS (`LELEKA_DECODE_GRAPH_REUSE`,
|
||||
/// docs/experiments/decode-graph-reuse.md): the state keyed on the request goes, the programs bound to the bank do
|
||||
/// not. Drain the draft stream, forget a draft that was launched and never finished (its ring mutation stays open,
|
||||
/// as in `release_verifier_bindings`) and drop the verifier window the last round staged (the tail owner keeps it
|
||||
/// until the next stage, and after the bank's re-arm it is a window of an older generation). The cached round
|
||||
/// programs, the direct mode, the ring owner and the policy key stay: they name the bank's final-R span and the
|
||||
/// draft ring, both unchanged for the same bank, and `stage_round` refuses a window at another address.
|
||||
pub fn end_request_keep_bank(&mut self) -> Result<()> {
|
||||
self.validate_context(self.context)?;
|
||||
self.stream.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?;
|
||||
self.in_flight = None;
|
||||
let source = self.full.as_ref().ok_or(Error::ContextPoisoned)?.release_staged_source();
|
||||
if source.is_err() {
|
||||
self.failed = true;
|
||||
}
|
||||
source
|
||||
}
|
||||
}
|
||||
+1
-8
@@ -13,14 +13,6 @@ impl OriginalMtpFullPolicy {
|
||||
pub(super) fn for_capture(&self, j: usize, coupled: bool) -> Self {
|
||||
let k = &self.kv;
|
||||
Self {
|
||||
native_router: self.native_router,
|
||||
legacy_router_mode: self.legacy_router_mode,
|
||||
native_shared_scalar: self.native_shared_scalar,
|
||||
native_combine: self.native_combine,
|
||||
old_grouped_s2: self.old_grouped_s2,
|
||||
native_final_gr: self.native_final_gr,
|
||||
fp32_final_gr: self.fp32_final_gr,
|
||||
gr: self.gr,
|
||||
kv: DraftKvPolicy {
|
||||
disabled: k.disabled,
|
||||
hybrid: k.hybrid,
|
||||
@@ -38,6 +30,7 @@ impl OriginalMtpFullPolicy {
|
||||
mscale: k.mscale,
|
||||
},
|
||||
coupled_j: if coupled { Some(j as u8) } else { None },
|
||||
..*self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,22 @@ impl Arguments {
|
||||
+ self.values.iter().map(|a| if matches!(a, Arg::GrMulti(_)) { 114 * 8 } else { 0 }).sum::<usize>()
|
||||
}
|
||||
|
||||
/// The three words of a check launch (buffer, count, status word), when the arguments are exactly those.
|
||||
pub(crate) fn check_words(&self) -> Option<(u64, i32, u64)> {
|
||||
match &*self.values {
|
||||
[Arg::U64(data), Arg::I32(count), Arg::U64(flag)] => Some((*data, *count, *flag)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn gr_words(&self) -> Option<&[u64; 114]> {
|
||||
match &*self.values {
|
||||
[Arg::GrMulti(words)] => Some(words),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new(values: Vec<Arg>) -> Result<Self> {
|
||||
let mut pointers = Vec::new();
|
||||
pointers.try_reserve_exact(values.len()).map_err(|_| Error::HostAllocation)?;
|
||||
|
||||
@@ -74,6 +74,12 @@ pub struct OriginalMtpFullPolicy {
|
||||
pub gr: OriginalMtpGrVariant,
|
||||
pub kv: DraftKvPolicy,
|
||||
pub coupled_j: Option<u8>,
|
||||
/// Enqueue the chain steps of a greedy draft with `min_p` 0 back to back and read them after one stream drain
|
||||
/// (`LELEKA_DRAFT_CHAIN_PIPELINE`; the kernels and their order are the sequential path's).
|
||||
pub chain_pipeline: bool,
|
||||
/// Launch the adjacent finite and Q8_1 scale guards of a step as one batched guard
|
||||
/// (`LELEKA_DRAFT_CHECK_MERGE`; the same checks of the same buffers at the same positions, fewer launches).
|
||||
pub check_merge: bool,
|
||||
}
|
||||
struct TailLayout {
|
||||
sizes: [usize; 36],
|
||||
@@ -147,6 +153,12 @@ pub struct OriginalMtpForwardProgram<'ctx> {
|
||||
native_embedding: Option<OriginalMtpNativeGather<'ctx>>,
|
||||
coupled_stage: Option<FA>,
|
||||
addrs: ScalarAddrs,
|
||||
/// Captured without the tail flag reset (the prefix plan drops its status reset too): the numerical flags of
|
||||
/// a chain step OR into the words the draft round's own resets cleared, so the host reads them once for a run
|
||||
/// of steps enqueued back to back.
|
||||
accumulate_flags: bool,
|
||||
/// The batched guard module, loaded when the policy asks for merged checks.
|
||||
check_batch: Option<mtp_original_check_batch_program::CheckBatchModules>,
|
||||
}
|
||||
|
||||
/// The scalar prefix's modules and the buffers its commands run on.
|
||||
@@ -306,6 +318,7 @@ mod role_map_tests {
|
||||
mod context;
|
||||
#[path = "mtp_original_full_forward/full_owned.rs"]
|
||||
mod full_owned;
|
||||
mod mtp_original_check_batch_program;
|
||||
mod mtp_original_full_init;
|
||||
#[path = "mtp_original_full_forward/original_mtp_full_forward.rs"]
|
||||
mod original_mtp_full_forward;
|
||||
|
||||
+20
-1
@@ -1,5 +1,6 @@
|
||||
//! Moved out of the parent module by STRA-338: impl OriginalMtpFullForward (2).
|
||||
|
||||
use super::super::mtp_original_check_batch_program::{CheckBatchModules, merge_prefix, merge_tail};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
@@ -16,7 +17,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
|
||||
let ScalarPrefixPlan { commands: prefix, native_embedding, step_row } = plan;
|
||||
self.program_reject_aliases(scalar, ring)?;
|
||||
let p = self.program_prefix(scalar, ring, step_row)?;
|
||||
let commands = self.plan(&p, policy)?;
|
||||
let (prefix, commands, check_batch) = self.program_commands(scalar.context, &p, (prefix, policy))?;
|
||||
let window = self.program_window(&p, ring)?;
|
||||
let coupled_stage = self.program_coupled_stage(policy)?;
|
||||
Ok(OriginalMtpForwardProgram {
|
||||
@@ -30,9 +31,27 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
|
||||
native_embedding,
|
||||
coupled_stage,
|
||||
addrs: Self::program_addrs(scalar)?,
|
||||
accumulate_flags: false,
|
||||
check_batch,
|
||||
})
|
||||
}
|
||||
|
||||
/// The tail commands of the step, and with `LELEKA_DRAFT_CHECK_MERGE` the adjacent checks of the scalar prefix and
|
||||
/// of the tail launched as batches, with the module that launches them. Without it the lists are as planned.
|
||||
fn program_commands(
|
||||
&self,
|
||||
context: &'ctx Context<'ctx>,
|
||||
p: &ForwardPrefix<'_, 'ctx>,
|
||||
(prefix, policy): (Vec<ScalarCommand>, &OriginalMtpFullPolicy),
|
||||
) -> Result<(Vec<ScalarCommand>, Vec<FullCommand>, Option<CheckBatchModules>)> {
|
||||
let tail = self.plan(p, policy)?;
|
||||
if !policy.check_merge {
|
||||
return Ok((prefix, tail, None));
|
||||
}
|
||||
let batch = CheckBatchModules::load(context)?;
|
||||
Ok((merge_prefix(prefix)?, merge_tail(tail)?, Some(batch)))
|
||||
}
|
||||
|
||||
fn program_addrs(scalar: &OriginalMtpScalarPrefill<'ctx>) -> Result<ScalarAddrs> {
|
||||
Ok(ScalarAddrs {
|
||||
residual_offset: scalar.layout.offsets[1],
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
//! Moved out of the parent module by STRA-338: impl OriginalMtpForwardProgram, impl OriginalMtpForwardProgram, impl
|
||||
//! OriginalMtpForwardProgram.
|
||||
|
||||
use super::mtp_original_check_batch_program::{
|
||||
CheckBatchModules, is_tail_batch, launch_prefix_command, launch_tail_batch,
|
||||
};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use abi::LaunchShape;
|
||||
@@ -20,7 +23,7 @@ impl OriginalMtpForwardProgram<'_> {
|
||||
(&self.tail, &self.ring),
|
||||
(&self.args.split, &mut self.args.window),
|
||||
stream,
|
||||
command,
|
||||
(self.check_batch.as_ref(), command),
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -29,35 +32,47 @@ impl OriginalMtpForwardProgram<'_> {
|
||||
/// The coupled sampler stage, the tail flag reset and the scalar prefix commands (the native embedding is
|
||||
/// captured before the second one).
|
||||
fn capture_prefix(&mut self, capture: &mut OriginalCapture<'_, '_>, stream: usize) -> Result<()> {
|
||||
if let Some(stage) = &mut self.coupled_stage {
|
||||
self.tail.modules[20].launch(1, LaunchShape::new([1, 1, 1], [256, 1, 1], 0), stream, stage)?;
|
||||
}
|
||||
self.owners.modules[0].launch(11, LaunchShape::new([1, 1, 1], [256, 1, 1], 0), stream, &mut self.args.reset)?;
|
||||
self.capture_coupled_stage(stream)?;
|
||||
self.capture_flag_reset(stream)?;
|
||||
for (i, command) in self.prefix.iter_mut().enumerate() {
|
||||
if i == 1
|
||||
&& let Some(e) = &mut self.native_embedding
|
||||
{
|
||||
e.capture(capture)?;
|
||||
}
|
||||
Self::launch_scalar(&self.owners.modules, stream, command)?;
|
||||
if !(i == 0 && self.accumulate_flags) {
|
||||
launch_prefix_command(&self.owners.modules, self.check_batch.as_ref(), stream, command)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn launch_scalar(modules: &[Rc<Module>; 6], stream: usize, command: &mut ScalarCommand) -> Result<()> {
|
||||
match command {
|
||||
ScalarCommand::Kernel { asset, index, shape, args } => modules[*asset].launch(*index, *shape, stream, args),
|
||||
ScalarCommand::Copy { .. } => Err(Error::InvalidQwenShape),
|
||||
fn capture_coupled_stage(&mut self, stream: usize) -> Result<()> {
|
||||
match &mut self.coupled_stage {
|
||||
Some(stage) => self.tail.modules[20].launch(1, LaunchShape::new([1, 1, 1], [256, 1, 1], 0), stream, stage),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The tail flag reset, unless this program accumulates its flags with the steps around it.
|
||||
fn capture_flag_reset(&mut self, stream: usize) -> Result<()> {
|
||||
if self.accumulate_flags {
|
||||
return Ok(());
|
||||
}
|
||||
let shape = LaunchShape::new([1, 1, 1], [256, 1, 1], 0);
|
||||
self.owners.modules[0].launch(11, shape, stream, &mut self.args.reset)
|
||||
}
|
||||
|
||||
/// One tail command, preceded by the Q split copy or the window-ids transport where Original puts them.
|
||||
fn launch_tail_command(
|
||||
(tail, ring): (&FullOwned<'_>, &MtpOriginalRingResources<'_>),
|
||||
(split, window): (&full_abi::Copy2D, &mut abi::Arguments),
|
||||
stream: usize,
|
||||
command: &mut FullCommand,
|
||||
(batch, command): (Option<&CheckBatchModules>, &mut FullCommand),
|
||||
) -> Result<()> {
|
||||
if is_tail_batch(command) {
|
||||
return launch_tail_batch(batch, stream, command);
|
||||
}
|
||||
if command.asset == 16 && command.index == 0 {
|
||||
tail.modules[13].copy2d(split, stream)?;
|
||||
}
|
||||
@@ -88,6 +103,16 @@ impl OriginalMtpForwardProgram<'_> {
|
||||
}
|
||||
}
|
||||
impl OriginalMtpForwardProgram<'_> {
|
||||
/// Capture this program without the tail flag reset and without the prefix plan's leading status reset (the plan
|
||||
/// keeps the command: the native embedding is captured by command index).
|
||||
pub(crate) fn accumulate_flags(&mut self) -> Result<()> {
|
||||
if !matches!(self.prefix.first(), Some(ScalarCommand::Kernel { asset: 0, index: 11, .. })) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
self.accumulate_flags = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_flags_after_actual_drain(&self) -> Result<()> {
|
||||
self.validate_context(self.context)?;
|
||||
let h = self.tail.handle(27)?;
|
||||
|
||||
@@ -68,6 +68,27 @@ impl<'ctx> OriginalGpuGraph<'ctx, OriginalMtpDraftProgram<'ctx>> {
|
||||
}
|
||||
self.resources.as_ref().ok_or(Error::ContextPoisoned)?.stage_chain()
|
||||
}
|
||||
/// `mtp_stage_chain` for a step enqueued behind a step that is still in flight on the same stream.
|
||||
pub(crate) fn mtp_stage_chain_ahead(&mut self) -> Result<()> {
|
||||
self.validate()?;
|
||||
if self.launched {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
self.resources.as_ref().ok_or(Error::ContextPoisoned)?.stage_chain_ahead()
|
||||
}
|
||||
/// The output of a step that is already drained: `done` is the receipt of ONE stream drain after the last step
|
||||
/// of a run enqueued back to back. `check_flags` reads the shared numerical flag words (last step of the run).
|
||||
pub(crate) fn mtp_finish_drained(
|
||||
&mut self,
|
||||
done: &crate::OriginalStreamDrained<'ctx>,
|
||||
check_flags: bool,
|
||||
) -> Result<OriginalMtpStepOutput> {
|
||||
self.validate()?;
|
||||
if !self.launched {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
self.resources_after_stream_drain(done)?.finish_after_drain_flags(check_flags)
|
||||
}
|
||||
pub(crate) fn mtp_stage_sampling(&mut self, params: crate::SamplerParams, history: &[i32; 4096]) -> Result<()> {
|
||||
self.validate()?;
|
||||
if self.launched {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Moved out of the parent module by STRA-338: impl OriginalMtpDraftProgram.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::super::mtp_original_check_batch_program::launch_prefix_command;
|
||||
use super::*;
|
||||
|
||||
impl<'ctx> OriginalMtpDraftProgram<'ctx> {
|
||||
@@ -52,12 +53,8 @@ impl<'ctx> OriginalMtpDraftProgram<'ctx> {
|
||||
{
|
||||
e.capture(c)?;
|
||||
}
|
||||
match cmd {
|
||||
ScalarCommand::Kernel { asset, index, shape, args } => {
|
||||
self.program.owners.modules[*asset].launch(*index, *shape, stream, args)?
|
||||
}
|
||||
ScalarCommand::Copy { .. } => return Err(Error::InvalidQwenShape),
|
||||
}
|
||||
let (modules, batch) = (&self.program.owners.modules, self.program.check_batch.as_ref());
|
||||
launch_prefix_command(modules, batch, stream, cmd)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -253,14 +250,41 @@ impl<'ctx> OriginalMtpDraftProgram<'ctx> {
|
||||
std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
/// Stages the cell record of chain step `j` while step `j - 1` is still in flight on the same stream (a run of
|
||||
/// steps enqueued back to back): the sequential path moves `next_j` on only after reading the previous step's
|
||||
/// output, here stream order guarantees the previous step finishes first, so the position is advanced now.
|
||||
pub(crate) fn stage_chain_ahead(&self) -> Result<()> {
|
||||
if self.j == 0 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
{
|
||||
let mut source = self.program.tail.source.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let s = source.as_mut().ok_or(Error::InvalidQwenShape)?;
|
||||
if s.next_j + 1 != self.j && s.next_j != self.j {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
s.next_j = self.j;
|
||||
}
|
||||
self.stage_chain()
|
||||
}
|
||||
|
||||
pub(crate) fn finish_after_drain(&self) -> Result<OriginalMtpStepOutput> {
|
||||
self.program.tail.validate_staged(self.j)?;
|
||||
self.program.validate_flags_after_actual_drain()?;
|
||||
self.finish_after_drain_flags(true)
|
||||
}
|
||||
|
||||
/// The step's output after the stream drained; `check_flags` reads the numerical flag words too (the steps of a
|
||||
/// run enqueued back to back share them, so only the last step's read covers the whole run).
|
||||
pub(crate) fn finish_after_drain_flags(&self, check_flags: bool) -> Result<OriginalMtpStepOutput> {
|
||||
self.program.tail.validate_staged_ahead(self.j)?;
|
||||
if check_flags {
|
||||
self.program.validate_flags_after_actual_drain()?;
|
||||
}
|
||||
let (token, probability) = self.read_step_output()?;
|
||||
let mut b = self.program.tail.source.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let s = b.as_mut().ok_or(Error::InvalidQwenShape)?;
|
||||
s.validate(self.program.context)?;
|
||||
s.next_j = self.j + 1;
|
||||
s.next_j = s.next_j.max(self.j + 1);
|
||||
Ok(OriginalMtpStepOutput { token, probability })
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! crate_original_gpu_schedule_resources, impl OriginalGraphResources_for_OriginalMtpDraftProgram, impl
|
||||
//! OriginalMtpFullForward, fn mapped_i32 ....
|
||||
|
||||
use super::super::mtp_original_check_batch_program::merge_prefix;
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
@@ -38,6 +39,17 @@ impl FullOwned<'_> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// As `validate_staged` for a step of a run enqueued back to back: later steps may already be staged.
|
||||
pub(super) fn validate_staged_ahead(&self, j: usize) -> Result<()> {
|
||||
self.validate(self.context)?;
|
||||
let source = self.source.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let source = source.as_ref().ok_or(Error::InvalidQwenShape)?;
|
||||
source.validate(self.context)?;
|
||||
if !source.ready || source.next_j < j {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl crate::original_gpu_schedule::resources::Sealed for OriginalMtpDraftProgram<'_> {}
|
||||
impl OriginalGraphResources for OriginalMtpDraftProgram<'_> {
|
||||
@@ -84,6 +96,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
|
||||
let ra = 2 * self.inner.max_t - 1;
|
||||
let prefix = self.round_prefix(scalar, ring, policy, ra)?;
|
||||
let mut program = self.program(scalar, ring, prefix, policy)?;
|
||||
let catchup_commands = Self::catchup_commands(&program, catchup.commands)?;
|
||||
let coupled_stage = program.coupled_stage.take();
|
||||
let before = self.round_before(scalar, rows)?;
|
||||
let after = self.round_after(scalar, rows, ra)?;
|
||||
@@ -95,12 +108,19 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
|
||||
before,
|
||||
after,
|
||||
post,
|
||||
catchup: catchup.commands,
|
||||
catchup: catchup_commands,
|
||||
catchup_embed: catchup.native_embedding,
|
||||
coupled_stage,
|
||||
direct_window: None,
|
||||
})
|
||||
}
|
||||
/// The catch-up commands, with their adjacent checks batched when the program's are.
|
||||
fn catchup_commands(
|
||||
program: &OriginalMtpForwardProgram<'ctx>,
|
||||
commands: Vec<ScalarCommand>,
|
||||
) -> Result<Vec<ScalarCommand>> {
|
||||
if program.check_batch.is_some() { merge_prefix(commands) } else { Ok(commands) }
|
||||
}
|
||||
fn check_round_rows(
|
||||
&self,
|
||||
scalar: &OriginalMtpScalarPrefill<'ctx>,
|
||||
@@ -215,11 +235,45 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
|
||||
ring: &MtpOriginalInt8<'ctx>,
|
||||
j: usize,
|
||||
policy: &OriginalMtpFullPolicy,
|
||||
) -> Result<OriginalMtpDraftProgram<'ctx>> {
|
||||
self.step_program(scalar, ring, (j, false), policy)
|
||||
}
|
||||
|
||||
/// The chain step `j` for a run of steps enqueued back to back (`LELEKA_DRAFT_CHAIN_PIPELINE`): the same
|
||||
/// kernels as `prepare_step` without the two flag resets (tail flags, prefix status words), so a fault of any
|
||||
/// step stays set until the host reads the words once after the last step.
|
||||
pub fn prepare_chain_step(
|
||||
&self,
|
||||
scalar: &OriginalMtpScalarPrefill<'ctx>,
|
||||
ring: &MtpOriginalInt8<'ctx>,
|
||||
j: usize,
|
||||
policy: &OriginalMtpFullPolicy,
|
||||
) -> Result<OriginalMtpDraftProgram<'ctx>> {
|
||||
self.step_program(scalar, ring, (j, true), policy)
|
||||
}
|
||||
|
||||
fn step_program(
|
||||
&self,
|
||||
scalar: &OriginalMtpScalarPrefill<'ctx>,
|
||||
ring: &MtpOriginalInt8<'ctx>,
|
||||
(j, accumulate): (usize, bool),
|
||||
policy: &OriginalMtpFullPolicy,
|
||||
) -> Result<OriginalMtpDraftProgram<'ctx>> {
|
||||
self.check_step_index(scalar, j, policy)?;
|
||||
let row = self.inner.max_t + j - 1;
|
||||
let prefix = self.prefix_commands(scalar, ring, policy, PrefixRows { rows: 1, step_row: row })?;
|
||||
let program = self.program(scalar, ring, prefix, policy)?;
|
||||
let mut program = self.program(scalar, ring, prefix, policy)?;
|
||||
if accumulate {
|
||||
program.accumulate_flags()?;
|
||||
}
|
||||
self.step_draft(program, (row, j))
|
||||
}
|
||||
|
||||
fn step_draft(
|
||||
&self,
|
||||
program: OriginalMtpForwardProgram<'ctx>,
|
||||
(row, j): (usize, usize),
|
||||
) -> Result<OriginalMtpDraftProgram<'ctx>> {
|
||||
let mut before = Vec::new();
|
||||
self.push_row_records(&mut before, row)?;
|
||||
let post = post_select(&program, j)?;
|
||||
|
||||
@@ -22,3 +22,20 @@ pub(super) use chain_asset_types::DAILY_ASSET;
|
||||
pub(super) use chain_asset_types::DAILY_CHUNK;
|
||||
#[allow(unused_imports)]
|
||||
pub(super) use chain_asset_types::DAILY_MERGE_V2;
|
||||
|
||||
/// The sealed batched numerical guard (`LELEKA_DRAFT_CHECK_MERGE`); loaded only when the switch is on, so it is not a
|
||||
/// slot of `ASSETS` and moves no index.
|
||||
#[allow(unused_imports)]
|
||||
pub(super) static CHECK_BATCH: (&[u8], &[&std::ffi::CStr]) =
|
||||
(include_bytes!("mtp_original_check_batch.ptx"), &[c"mtp_original_check_batch"]);
|
||||
|
||||
/// Length (with the terminal NUL) and sha256 of the body of `mtp_original_check_batch.ptx`, compiled from
|
||||
/// `mtp_original_check_batch.cu` by `scripts/gpu-bringup/compile_assets.py` (nvcc 13.2.86, the plan entry of
|
||||
/// `extra-seal-plan.json`) and installed by `seal_pins.py`.
|
||||
pub(super) const CHECK_BATCH_PIN: (usize, [u8; 32]) = (
|
||||
2050,
|
||||
[
|
||||
0x89, 0x7d, 0xf5, 0x42, 0x89, 0x1f, 0x07, 0x6f, 0xdc, 0x3e, 0x9c, 0x12, 0x80, 0xfb, 0xd0, 0x94, 0x82, 0x5a,
|
||||
0x19, 0x79, 0xfc, 0x74, 0xac, 0x15, 0x12, 0x4f, 0xce, 0x82, 0x34, 0x70, 0x6a, 0x66,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -23,6 +23,22 @@ impl Arguments {
|
||||
+ self.values.iter().map(|a| if matches!(a, Arg::GrMulti(_)) { 114 * 8 } else { 0 }).sum::<usize>()
|
||||
}
|
||||
|
||||
/// The three words of a check launch (buffer, count, status word), when the arguments are exactly those.
|
||||
pub(crate) fn check_words(&self) -> Option<(u64, i32, u64)> {
|
||||
match &*self.values {
|
||||
[Arg::U64(data), Arg::I32(count), Arg::U64(flag)] => Some((*data, *count, *flag)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn gr_words(&self) -> Option<&[u64; 114]> {
|
||||
match &*self.values {
|
||||
[Arg::GrMulti(words)] => Some(words),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new(values: Vec<Arg>) -> Result<Self> {
|
||||
let mut pointers = Vec::new();
|
||||
pointers.try_reserve_exact(values.len()).map_err(|_| Error::HostAllocation)?;
|
||||
|
||||
@@ -45,6 +45,11 @@ pub struct OriginalExpertCache<'ctx> {
|
||||
/// Non-blocking stream of `fill_slot_queued_async` (the lent-slot refill): its copies do not order the legacy
|
||||
/// default stream's other users behind them; `sync_queued` waits for it as well.
|
||||
fill_stream: Option<api::Stream>,
|
||||
/// Batched refill from the default stream: recorded there and waited for by `fill_stream`, so the batch (which
|
||||
/// the legacy default stream does not take) runs after everything queued before it, as the per-copy path does.
|
||||
fill_event: Option<api::Event>,
|
||||
/// Set when the driver refused a batch call once: later refills of this cache are issued per copy.
|
||||
batch_refused: bool,
|
||||
swap_event: Option<api::Event>,
|
||||
/// Slots whose swap copy is queued on `swap_stream`, with the retained sources they read.
|
||||
swapping: Vec<usize>,
|
||||
@@ -56,3 +61,4 @@ pub struct OriginalExpertCache<'ctx> {
|
||||
mod original_cache_prefix;
|
||||
mod original_expert_cache_drop;
|
||||
mod original_expert_cache_methods;
|
||||
pub use original_expert_cache_methods::RefillBatchOptions;
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
use super::*;
|
||||
|
||||
mod original_expert_cache_adaptive_swaps;
|
||||
mod original_expert_cache_batched_refill;
|
||||
pub use original_expert_cache_batched_refill::RefillBatchOptions;
|
||||
mod original_expert_cache_file_slot_fill;
|
||||
mod original_expert_cache_open_and_slots;
|
||||
mod original_expert_cache_verify_and_lend;
|
||||
|
||||
+4
-4
@@ -183,10 +183,10 @@ impl<'ctx> OriginalExpertCache<'ctx> {
|
||||
self.fills = next_fills;
|
||||
Ok(())
|
||||
}
|
||||
fn check_fill(
|
||||
pub(in super::super) fn check_fill(
|
||||
&self,
|
||||
slot: usize,
|
||||
bank: &Rc<MappedExpertBank<'ctx>>,
|
||||
bank: &MappedExpertBank<'ctx>,
|
||||
spans: &[ResidentExpertBankSpan; 3],
|
||||
) -> Result<(ffi::BufferHandle, usize)> {
|
||||
self.ensure_live()?;
|
||||
@@ -201,7 +201,7 @@ impl<'ctx> OriginalExpertCache<'ctx> {
|
||||
check_total(bank, spans, capacity)?;
|
||||
Ok((handle, capacity))
|
||||
}
|
||||
fn fill_layer(&self, bank: &Rc<MappedExpertBank<'ctx>>, spans: &[ResidentExpertBankSpan; 3]) -> Result<usize> {
|
||||
fn fill_layer(&self, bank: &MappedExpertBank<'ctx>, spans: &[ResidentExpertBankSpan; 3]) -> Result<usize> {
|
||||
if self.file_source_digest.is_some() {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
@@ -235,7 +235,7 @@ impl<'ctx> OriginalExpertCache<'ctx> {
|
||||
Ok(())
|
||||
}
|
||||
/// The default stream, or the cache's own non-blocking fill stream (created on first use).
|
||||
fn fill_stream_for(
|
||||
pub(in super::super) fn fill_stream_for(
|
||||
api: Option<&api::AsyncApi>,
|
||||
fill_stream: &mut Option<api::Stream>,
|
||||
own_stream: bool,
|
||||
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
//! The lent-slot refill with batched copies (`LELEKA_REFILL_BATCH`, EXPERIMENTAL, off by default): the same pieces as
|
||||
//! `fill_slot_queued_on`, slot by slot and role by role, handed to `cuMemcpyBatchAsync_v2` in calls of a few hundred
|
||||
//! copies inside one context entry. The bytes, destinations and source order are those of the per-copy path.
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::RefillBatchReport;
|
||||
use crate::refill_batch_copy::{HostCopy, issue_copies, per_copy};
|
||||
|
||||
/// How one batched refill is issued.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct RefillBatchOptions {
|
||||
/// The copies belong on the cache's own non-blocking fill stream (`fill_slot_queued_async`); otherwise they are
|
||||
/// ordered after the legacy default stream's earlier work (`fill_slot_queued`).
|
||||
pub own_stream: bool,
|
||||
/// Copies per `cuMemcpyBatchAsync_v2` call (1 to 4096).
|
||||
pub max_copies_per_call: usize,
|
||||
}
|
||||
|
||||
impl<'ctx> OriginalExpertCache<'ctx> {
|
||||
/// `fill_slot_queued`/`_async` of every `(slot, spans)` in order, with the copies batched. All slots are checked
|
||||
/// and their sources retained before anything is queued; a check failure queues nothing. A driver failure poisons
|
||||
/// the cache as the per-copy path does; a refused batch call is reported once and the rest goes per copy.
|
||||
/// `sync_queued` is the fence, as for the per-copy fills.
|
||||
pub fn fill_slots_queued_batched(
|
||||
&mut self,
|
||||
bank: &Rc<MappedExpertBank<'ctx>>,
|
||||
fills: Vec<(usize, [ResidentExpertBankSpan; 3])>,
|
||||
options: RefillBatchOptions,
|
||||
) -> Result<RefillBatchReport> {
|
||||
if fills.is_empty() {
|
||||
return self.ensure_live().map(|()| RefillBatchReport::default());
|
||||
}
|
||||
let copies = self.refill_copies(bank, &fills)?;
|
||||
let next_fills = self.fills.checked_add(fills.len() as u64).ok_or(Error::InvalidSize)?;
|
||||
let slots = self.retain_refill(bank, fills)?;
|
||||
let guard = self.context.enter()?;
|
||||
let issued = self.issue_refill(&copies, options, !bank.pageable());
|
||||
let mut report = match combine(issued, guard.finish()) {
|
||||
Ok(report) => report,
|
||||
Err(error) => {
|
||||
self.poison();
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
for &slot in &slots {
|
||||
self.states[slot] = State::Queued;
|
||||
}
|
||||
self.fills = next_fills;
|
||||
report.slots = slots.len();
|
||||
count_refill(&report);
|
||||
Ok(report)
|
||||
}
|
||||
/// Every piece of every slot, in the per-copy path's order; checks each slot like `fill_slot_queued_on`.
|
||||
fn refill_copies<'b>(
|
||||
&self,
|
||||
bank: &'b MappedExpertBank<'ctx>,
|
||||
fills: &[(usize, [ResidentExpertBankSpan; 3])],
|
||||
) -> Result<Vec<HostCopy<'b>>> {
|
||||
let mut seen = vec![false; self.states.len()];
|
||||
let mut copies = Vec::new();
|
||||
copies.try_reserve(fills.len() * 3).map_err(|_| Error::HostAllocation)?;
|
||||
for (slot, spans) in fills {
|
||||
if std::mem::replace(seen.get_mut(*slot).ok_or(Error::InvalidSize)?, true) {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
self.slot_copies(bank, (*slot, spans), &mut copies)?;
|
||||
}
|
||||
Ok(copies)
|
||||
}
|
||||
fn slot_copies<'b>(
|
||||
&self,
|
||||
bank: &'b MappedExpertBank<'ctx>,
|
||||
(slot, spans): (usize, &[ResidentExpertBankSpan; 3]),
|
||||
copies: &mut Vec<HostCopy<'b>>,
|
||||
) -> Result<()> {
|
||||
let (handle, capacity) = self.check_fill(slot, bank, spans)?;
|
||||
let mut offset = 0usize;
|
||||
for span in spans {
|
||||
let source = bank.cache_source(span)?;
|
||||
for (at, bytes) in bank.copy_pieces(source) {
|
||||
let destination = handle.checked_subspan(capacity, offset + at, bytes)?.qwen_address();
|
||||
copies.push(HostCopy { destination, source: &source[at..at + bytes] });
|
||||
}
|
||||
offset += source.len();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The real registered sources retained BEFORE any enqueue; returns the slots in order.
|
||||
fn retain_refill(
|
||||
&mut self,
|
||||
bank: &Rc<MappedExpertBank<'ctx>>,
|
||||
fills: Vec<(usize, [ResidentExpertBankSpan; 3])>,
|
||||
) -> Result<Vec<usize>> {
|
||||
self.pending.try_reserve(fills.len()).map_err(|_| Error::HostAllocation)?;
|
||||
let mut slots = Vec::new();
|
||||
slots.try_reserve_exact(fills.len()).map_err(|_| Error::HostAllocation)?;
|
||||
for (slot, spans) in fills {
|
||||
self.pending.push(RetainedFill::Mapped { bank: Rc::clone(bank), spans });
|
||||
slots.push(slot);
|
||||
}
|
||||
Ok(slots)
|
||||
}
|
||||
/// Inside the entered context: batched on the fill stream, or per copy on the per-copy path's stream when the
|
||||
/// driver has no batch entry, refused one before, or the bank is pageable (the batch is used for registered
|
||||
/// sources only).
|
||||
fn issue_refill(
|
||||
&mut self,
|
||||
copies: &[HostCopy<'_>],
|
||||
options: RefillBatchOptions,
|
||||
registered: bool,
|
||||
) -> Result<RefillBatchReport> {
|
||||
self.attempted = true;
|
||||
let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
if self.batch_refused || !registered || !api.can_batch() {
|
||||
let stream = Self::fill_stream_for(Some(api), &mut self.fill_stream, options.own_stream)?;
|
||||
per_copy(api, copies, stream)?;
|
||||
return Ok(RefillBatchReport {
|
||||
copies: copies.len(),
|
||||
per_copy: copies.len(),
|
||||
..RefillBatchReport::default()
|
||||
});
|
||||
}
|
||||
let stream = Self::batch_stream(api, (&mut self.fill_stream, &mut self.fill_event), options.own_stream)?;
|
||||
let (report, refused) = issue_copies(api, copies, stream, options.max_copies_per_call)?;
|
||||
if let Some(error) = refused {
|
||||
self.batch_refused = true;
|
||||
eprintln!(
|
||||
"leleka-serve: WARNING: the driver refused a batched expert refill ({error:?}); the rest of it and \
|
||||
every later refill of this cache are issued one copy at a time (LELEKA_REFILL_BATCH)"
|
||||
);
|
||||
}
|
||||
Ok(report)
|
||||
}
|
||||
/// The fill stream; for a default-stream refill it first waits for an event recorded on the legacy default
|
||||
/// stream, so the batch runs after everything queued there before it (`cuMemcpyBatchAsync_v2` does not take the
|
||||
/// legacy default stream itself).
|
||||
fn batch_stream(
|
||||
api: &api::AsyncApi,
|
||||
(stream, event): (&mut Option<api::Stream>, &mut Option<api::Event>),
|
||||
own_stream: bool,
|
||||
) -> Result<api::Stream> {
|
||||
let fill = Self::fill_stream_for(Some(api), stream, true)?;
|
||||
if !own_stream {
|
||||
if event.is_none() {
|
||||
*event = Some(api.create_event()?);
|
||||
}
|
||||
let after = event.ok_or(Error::ContextPoisoned)?;
|
||||
api.record(after, api::Stream(0))?;
|
||||
api.wait_event(fill, after)?;
|
||||
}
|
||||
Ok(fill)
|
||||
}
|
||||
}
|
||||
|
||||
/// The refill's profile counters (`LELEKA_SERVE_PROFILE`): batch calls, copies they carried, copies issued singly.
|
||||
fn count_refill(report: &RefillBatchReport) {
|
||||
crate::host_profile::add("refill.batch_calls", report.batch_calls as f64);
|
||||
crate::host_profile::add("refill.batch_copies", (report.copies - report.per_copy) as f64);
|
||||
crate::host_profile::add("refill.per_copy", report.per_copy as f64);
|
||||
}
|
||||
+2
@@ -75,6 +75,8 @@ impl<'ctx> OriginalExpertCache<'ctx> {
|
||||
failed: false,
|
||||
swap_stream: None,
|
||||
fill_stream: None,
|
||||
fill_event: None,
|
||||
batch_refused: false,
|
||||
swap_event: None,
|
||||
swapping: Vec::new(),
|
||||
swap_sources: Vec::new(),
|
||||
|
||||
+4
-3
@@ -151,13 +151,14 @@ impl<'ctx> OriginalExpertCache<'ctx> {
|
||||
std::mem::forget(api);
|
||||
}
|
||||
}
|
||||
/// Destroys the adaptive and fill streams and the swap event; the outer error is a failed context entry.
|
||||
/// Destroys the adaptive and fill streams and the swap and fill events; the outer error is a failed context entry.
|
||||
fn release_streams(&mut self) -> Result<Result<()>> {
|
||||
let mut released = Ok(());
|
||||
if self.swap_event.is_some() || self.swap_stream.is_some() || self.fill_stream.is_some() {
|
||||
let events = self.swap_event.is_some() || self.fill_event.is_some();
|
||||
if events || self.swap_stream.is_some() || self.fill_stream.is_some() {
|
||||
let guard = self.context.enter()?;
|
||||
if let Some(api) = self.api.as_ref() {
|
||||
if let Some(event) = self.swap_event.take() {
|
||||
for event in [self.swap_event.take(), self.fill_event.take()].into_iter().flatten() {
|
||||
released = combine(released, api.destroy_event(event));
|
||||
}
|
||||
if let Some(stream) = self.fill_stream.take() {
|
||||
|
||||
@@ -120,7 +120,8 @@ pub struct OriginalGraphFlight<'g, 'ctx, R: OriginalGraphResources> {
|
||||
active: bool,
|
||||
}
|
||||
|
||||
/// Literal graph identities, with Original layer/token/window/coupled separation.
|
||||
/// Literal graph identities, with Original layer/token/window/coupled separation. `MtpChain` is a chain step
|
||||
/// recorded without the flag resets (`LELEKA_DRAFT_CHAIN_PIPELINE`, greedy drafts only).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum OriginalGraphKey {
|
||||
LayerPre(u8),
|
||||
@@ -134,6 +135,7 @@ pub enum OriginalGraphKey {
|
||||
MtpPrefill { rows: u8, device_inputs: bool },
|
||||
MtpRound { rows: u8, coupled: bool },
|
||||
MtpStep { step: u8, coupled: bool },
|
||||
MtpChain { step: u8 },
|
||||
Registry { qsa: bool, tokens: u32 },
|
||||
}
|
||||
/// Fixed upfront capacity, capture-once/replay-many: a hit never calls either
|
||||
|
||||
@@ -12,7 +12,7 @@ impl OriginalGraphKey {
|
||||
Self::Token | Self::VerifyCommit => true,
|
||||
Self::VerifyWindow(t) => (1..=8).contains(&t),
|
||||
Self::MtpPrefill { rows, .. } | Self::MtpRound { rows, .. } => (1..=8).contains(&rows),
|
||||
Self::MtpStep { step, .. } => (1..=6).contains(&step),
|
||||
Self::MtpStep { step, .. } | Self::MtpChain { step } => (1..=6).contains(&step),
|
||||
Self::Registry { tokens, .. } => tokens > 0,
|
||||
};
|
||||
if valid { Ok(()) } else { Err(Error::InvalidQwenShape) }
|
||||
@@ -21,7 +21,9 @@ impl OriginalGraphKey {
|
||||
match self {
|
||||
Self::VerifyWindow(_) => OriginalCapturePolicy::VerifierWindow,
|
||||
Self::VerifyCommit => OriginalCapturePolicy::VerifierCommit,
|
||||
Self::MtpPrefill { .. } | Self::MtpRound { .. } | Self::MtpStep { .. } => OriginalCapturePolicy::Mtp,
|
||||
Self::MtpPrefill { .. } | Self::MtpRound { .. } | Self::MtpStep { .. } | Self::MtpChain { .. } => {
|
||||
OriginalCapturePolicy::Mtp
|
||||
}
|
||||
Self::Registry { .. } => OriginalCapturePolicy::Registry,
|
||||
_ => OriginalCapturePolicy::Session,
|
||||
}
|
||||
|
||||
@@ -49,6 +49,18 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo
|
||||
self.completed_experts = self.order.len();
|
||||
Ok(())
|
||||
}
|
||||
/// EXPERIMENTAL (`LELEKA_PREFILL_RING_PREFETCH`, docs/experiments/ring-prefetch.md): after this layer's copy ring
|
||||
/// drained, copy the experts `layer` (the next one) is predicted to miss into its ring's stage slots, through this
|
||||
/// layer's row lease. Returns how many were copied; never fails (the next ring copies whatever is missing).
|
||||
pub fn prefetch_ring_layer(
|
||||
&self,
|
||||
schedule: &mut crate::OriginalMmqCopySchedule<'ctx>,
|
||||
bank: &std::rc::Rc<MappedExpertBank<'ctx>>,
|
||||
layer: usize,
|
||||
sources: impl FnMut(u32) -> crate::PrefetchSource,
|
||||
) -> usize {
|
||||
schedule.prefetch_ring_layer(crate::PrefetchTarget { read: &self.read, bank, layer }, sources)
|
||||
}
|
||||
pub fn execute_mmq(
|
||||
&mut self,
|
||||
workspace: &mut MmqWorkspace<'ctx>,
|
||||
|
||||
+5
@@ -216,6 +216,11 @@ impl<'ctx> OriginalMtpActor<'ctx> {
|
||||
self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.release_verifier_bindings()
|
||||
}
|
||||
|
||||
/// The end of a request over a verifier bank that stays (see `OriginalMtpDrafter::end_request_keep_bank`).
|
||||
pub fn end_request_keep_bank(&mut self) -> Result<()> {
|
||||
self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.end_request_keep_bank()
|
||||
}
|
||||
|
||||
/// `kv_restore(upto)`: refill the draft ring's window for a sequence that
|
||||
/// continues at `upto` from the host pages `prior` authenticates. A no-op
|
||||
/// when the ring is fully resident, exactly as in Original.
|
||||
|
||||
@@ -19,7 +19,9 @@ const MMQ_GROUP: usize = 16;
|
||||
const MMQ_TAIL: usize = 4096;
|
||||
|
||||
mod carve_parts;
|
||||
mod mmq_identity;
|
||||
use carve_parts::{merge_spans, take_kv_int8, take_kv_q4, take_ple};
|
||||
use mmq_identity::mmq_identity_words;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PrefillPhase {
|
||||
@@ -327,7 +329,7 @@ impl PrefillLayoutOptions {
|
||||
|
||||
fn take_mmq_groups(&self, a: &mut Alloc, t: usize) -> Result<()> {
|
||||
if self.mmq_any {
|
||||
a.rows("ids_identity", t, K, 4)?;
|
||||
a.take("ids_identity", mmq_identity_words(t)?, 4)?;
|
||||
let bounds = self.mmq_bounds_words()?;
|
||||
a.take("bounds_dev", bounds, 4)?;
|
||||
for (name, max) in [("grp_gu", self.mmq_gu_max), ("grp_d", self.mmq_down_max)] {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
//! Size of the identity row table of the prompt MMQ launches (ledger row U3).
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Widest column tile of the grouped MMQ launches (ggml `mul_mat_q_switch_J`: J = 8 .. 128 in steps of 8).
|
||||
const MMQ_TILE_COLS_MAX: usize = 128;
|
||||
|
||||
/// Entries of the identity row table of the prompt MMQ launches: the `t * K` routed rows plus the margin that the
|
||||
/// stream-k fixup (`mul_mat_q_stream_k_fixup`) reads past them. It loads `ids_dst[col_low + jt * J + j]` for a whole
|
||||
/// J-column tile before it compares the tile with the expert's rows, and a tile runs to `ceil(max_rows / J) * J` with
|
||||
/// `max_rows <= t` (an expert takes at most one row per token), so the table needs `roundup(t, J) + J` more entries
|
||||
/// for the widest J (upstream Strata `f225844d1`). The values past `t * K` are never routed to: results are unchanged.
|
||||
pub(super) fn mmq_identity_words(t: usize) -> Result<usize> {
|
||||
let tile_rounded = add(t, MMQ_TILE_COLS_MAX - 1)? / MMQ_TILE_COLS_MAX * MMQ_TILE_COLS_MAX;
|
||||
add(add(mul(t, K)?, tile_rounded)?, MMQ_TILE_COLS_MAX)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod mmq_identity_margin_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_identity_table_covers_every_index_the_stream_k_fixup_can_read() {
|
||||
for t in [1usize, 7, 127, 128, 129, 1000, 8192] {
|
||||
let words = mmq_identity_words(t).unwrap();
|
||||
// the last column tile of the widest J starts below t and ends at roundup(t, J); the table index adds the
|
||||
// experts' column offset, which is at most t * K - 1
|
||||
let last_read = t * K - 1 + t.div_ceil(MMQ_TILE_COLS_MAX) * MMQ_TILE_COLS_MAX;
|
||||
assert!(last_read < words, "t {t}: reads index {last_read}, table has {words} entries");
|
||||
assert!(words > t * K, "t {t}: no margin");
|
||||
}
|
||||
assert!(mmq_identity_words(usize::MAX / 4).is_err(), "a size that does not fit must fail, not wrap");
|
||||
}
|
||||
}
|
||||
@@ -62,6 +62,8 @@ pub(crate) use original_verify_gpu_plan_methods::{PlanEntryShape, encode_plan_bl
|
||||
mod cpu_sink_publish_gpu_plan;
|
||||
#[path = "original_verify_gpu_plan/plan_phases.rs"]
|
||||
mod plan_phases;
|
||||
#[path = "original_verify_gpu_plan/plan_tier_tally.rs"]
|
||||
mod plan_tier_tally;
|
||||
#[allow(unused_imports)]
|
||||
pub(crate) use cpu_sink_publish_gpu_plan::dma_options;
|
||||
#[path = "original_verify_gpu_plan/dma_options_for.rs"]
|
||||
|
||||
@@ -44,6 +44,7 @@ impl<'ctx> schedule::OriginalVerifyCpuSink<'_, 'ctx> {
|
||||
copy: &mut OriginalGpuStream<'ctx>,
|
||||
) -> Result<()> {
|
||||
let (layout, cap, ids) = self.plan_preflight(cache, copy)?;
|
||||
super::plan_tier_tally::tally(self.layer, plan, &ids);
|
||||
let vram = self.plan_vram(plan, cache, &ids)?;
|
||||
let stride = self.check_pcie(plan, pcie.as_ref(), &ids)?;
|
||||
let staging = self.staging_base(plan)?;
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
//! Profile-only tally of the tier legs of every verify layer group (`LELEKA_SERVE_PROFILE=1`): per layer, how many
|
||||
//! distinct routed experts the window used and how they split between the VRAM tier, the PCIe share and the CPU
|
||||
//! pool. The value of `tier.lNN.vram|pcie|cpu` is an expert count (the profile prints `value/windows`); nothing
|
||||
//! here changes what the plan does. Ledger V5/V7: which layers carry the CPU/PCIe legs.
|
||||
use super::OriginalVerifyGpuPlan;
|
||||
use crate::host_profile;
|
||||
|
||||
const VRAM: [&str; 48] = [
|
||||
"tier.l00.vram",
|
||||
"tier.l01.vram",
|
||||
"tier.l02.vram",
|
||||
"tier.l03.vram",
|
||||
"tier.l04.vram",
|
||||
"tier.l05.vram",
|
||||
"tier.l06.vram",
|
||||
"tier.l07.vram",
|
||||
"tier.l08.vram",
|
||||
"tier.l09.vram",
|
||||
"tier.l10.vram",
|
||||
"tier.l11.vram",
|
||||
"tier.l12.vram",
|
||||
"tier.l13.vram",
|
||||
"tier.l14.vram",
|
||||
"tier.l15.vram",
|
||||
"tier.l16.vram",
|
||||
"tier.l17.vram",
|
||||
"tier.l18.vram",
|
||||
"tier.l19.vram",
|
||||
"tier.l20.vram",
|
||||
"tier.l21.vram",
|
||||
"tier.l22.vram",
|
||||
"tier.l23.vram",
|
||||
"tier.l24.vram",
|
||||
"tier.l25.vram",
|
||||
"tier.l26.vram",
|
||||
"tier.l27.vram",
|
||||
"tier.l28.vram",
|
||||
"tier.l29.vram",
|
||||
"tier.l30.vram",
|
||||
"tier.l31.vram",
|
||||
"tier.l32.vram",
|
||||
"tier.l33.vram",
|
||||
"tier.l34.vram",
|
||||
"tier.l35.vram",
|
||||
"tier.l36.vram",
|
||||
"tier.l37.vram",
|
||||
"tier.l38.vram",
|
||||
"tier.l39.vram",
|
||||
"tier.l40.vram",
|
||||
"tier.l41.vram",
|
||||
"tier.l42.vram",
|
||||
"tier.l43.vram",
|
||||
"tier.l44.vram",
|
||||
"tier.l45.vram",
|
||||
"tier.l46.vram",
|
||||
"tier.l47.vram",
|
||||
];
|
||||
const PCIE: [&str; 48] = [
|
||||
"tier.l00.pcie",
|
||||
"tier.l01.pcie",
|
||||
"tier.l02.pcie",
|
||||
"tier.l03.pcie",
|
||||
"tier.l04.pcie",
|
||||
"tier.l05.pcie",
|
||||
"tier.l06.pcie",
|
||||
"tier.l07.pcie",
|
||||
"tier.l08.pcie",
|
||||
"tier.l09.pcie",
|
||||
"tier.l10.pcie",
|
||||
"tier.l11.pcie",
|
||||
"tier.l12.pcie",
|
||||
"tier.l13.pcie",
|
||||
"tier.l14.pcie",
|
||||
"tier.l15.pcie",
|
||||
"tier.l16.pcie",
|
||||
"tier.l17.pcie",
|
||||
"tier.l18.pcie",
|
||||
"tier.l19.pcie",
|
||||
"tier.l20.pcie",
|
||||
"tier.l21.pcie",
|
||||
"tier.l22.pcie",
|
||||
"tier.l23.pcie",
|
||||
"tier.l24.pcie",
|
||||
"tier.l25.pcie",
|
||||
"tier.l26.pcie",
|
||||
"tier.l27.pcie",
|
||||
"tier.l28.pcie",
|
||||
"tier.l29.pcie",
|
||||
"tier.l30.pcie",
|
||||
"tier.l31.pcie",
|
||||
"tier.l32.pcie",
|
||||
"tier.l33.pcie",
|
||||
"tier.l34.pcie",
|
||||
"tier.l35.pcie",
|
||||
"tier.l36.pcie",
|
||||
"tier.l37.pcie",
|
||||
"tier.l38.pcie",
|
||||
"tier.l39.pcie",
|
||||
"tier.l40.pcie",
|
||||
"tier.l41.pcie",
|
||||
"tier.l42.pcie",
|
||||
"tier.l43.pcie",
|
||||
"tier.l44.pcie",
|
||||
"tier.l45.pcie",
|
||||
"tier.l46.pcie",
|
||||
"tier.l47.pcie",
|
||||
];
|
||||
const CPU: [&str; 48] = [
|
||||
"tier.l00.cpu",
|
||||
"tier.l01.cpu",
|
||||
"tier.l02.cpu",
|
||||
"tier.l03.cpu",
|
||||
"tier.l04.cpu",
|
||||
"tier.l05.cpu",
|
||||
"tier.l06.cpu",
|
||||
"tier.l07.cpu",
|
||||
"tier.l08.cpu",
|
||||
"tier.l09.cpu",
|
||||
"tier.l10.cpu",
|
||||
"tier.l11.cpu",
|
||||
"tier.l12.cpu",
|
||||
"tier.l13.cpu",
|
||||
"tier.l14.cpu",
|
||||
"tier.l15.cpu",
|
||||
"tier.l16.cpu",
|
||||
"tier.l17.cpu",
|
||||
"tier.l18.cpu",
|
||||
"tier.l19.cpu",
|
||||
"tier.l20.cpu",
|
||||
"tier.l21.cpu",
|
||||
"tier.l22.cpu",
|
||||
"tier.l23.cpu",
|
||||
"tier.l24.cpu",
|
||||
"tier.l25.cpu",
|
||||
"tier.l26.cpu",
|
||||
"tier.l27.cpu",
|
||||
"tier.l28.cpu",
|
||||
"tier.l29.cpu",
|
||||
"tier.l30.cpu",
|
||||
"tier.l31.cpu",
|
||||
"tier.l32.cpu",
|
||||
"tier.l33.cpu",
|
||||
"tier.l34.cpu",
|
||||
"tier.l35.cpu",
|
||||
"tier.l36.cpu",
|
||||
"tier.l37.cpu",
|
||||
"tier.l38.cpu",
|
||||
"tier.l39.cpu",
|
||||
"tier.l40.cpu",
|
||||
"tier.l41.cpu",
|
||||
"tier.l42.cpu",
|
||||
"tier.l43.cpu",
|
||||
"tier.l44.cpu",
|
||||
"tier.l45.cpu",
|
||||
"tier.l46.cpu",
|
||||
"tier.l47.cpu",
|
||||
];
|
||||
|
||||
/// Adds the expert counts of one layer group; a no-op unless the profile is on.
|
||||
pub(super) fn tally(layer: usize, plan: &OriginalVerifyGpuPlan, ids: &[i32]) {
|
||||
if !host_profile::enabled() || layer >= VRAM.len() {
|
||||
return;
|
||||
}
|
||||
let mut distinct = ids.to_vec();
|
||||
distinct.sort_unstable();
|
||||
distinct.dedup();
|
||||
let (vram, pcie) = (plan.vram.len(), plan.pcie.len());
|
||||
host_profile::add(VRAM[layer], vram as f64);
|
||||
host_profile::add(PCIE[layer], pcie as f64);
|
||||
host_profile::add(CPU[layer], distinct.len().saturating_sub(vram + pcie) as f64);
|
||||
}
|
||||
@@ -29,8 +29,8 @@ use super::planner::{Planner, WindowWeights};
|
||||
use super::proj::{self, GdnProjectionAddrs, OriginalVerifyProjBinding, QsaProjectionAddrs};
|
||||
use super::qsa::{self, OriginalVerifyQsaBinding, OriginalVerifyQsaKvBinding, QsaLayerAddrs, QsaRope};
|
||||
use super::sm120;
|
||||
use super::window_plan::{gdn_index, qsa_layer};
|
||||
use super::window_plan::{PlanLayout, WINDOW_LAYERS, staging_blobs_per_group};
|
||||
use super::window_plan::{gdn_index, qsa_layer};
|
||||
use super::window_record::{ExpertTier, HcHalf, Projection, QuantSource, Rows, WindowOps, WindowPolicy, record_window};
|
||||
use super::*;
|
||||
use crate::{OriginalNativeEmbedRows, OriginalNativeHeadGraphResources};
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Bookkeeping of the loan of the twelve resident QSA owners (`OriginalVerifyQsaJournal::lend` / `take_back`).
|
||||
//!
|
||||
//! A captured window graph holds the device and mapped-host addresses of the owners' buffers. The journal that the
|
||||
//! graphs retain may hand the owners back to the prompt executor between two requests, without dropping the graphs, but
|
||||
//! only on one condition: what returns is the same set of buffers at the same addresses. The loan records a fingerprint
|
||||
//! of those addresses when it lends and compares it when the owners come back. Any difference - or any later use of a
|
||||
//! failed loan - is final: the journal is failed and the graph set that retains it must be retired, never replayed.
|
||||
//! This module is the pure state machine; the journal supplies the fingerprints.
|
||||
|
||||
/// Why a loan step was refused.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum LoanError {
|
||||
/// The owners are already out.
|
||||
AlreadyLent,
|
||||
/// The owners are home: nothing to take back.
|
||||
NotLent,
|
||||
/// The returned owners are not the lent ones (an address changed, or the fingerprint could not be taken).
|
||||
Changed,
|
||||
/// An earlier step failed the loan for good.
|
||||
Failed,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum State<F> {
|
||||
Home,
|
||||
Lent(F),
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// Home, lent with the fingerprint of the owners that left, or failed.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct OwnerLoan<F> {
|
||||
state: State<F>,
|
||||
}
|
||||
|
||||
impl<F: PartialEq> OwnerLoan<F> {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self { state: State::Home }
|
||||
}
|
||||
|
||||
pub(crate) fn is_lent(&self) -> bool {
|
||||
matches!(self.state, State::Lent(_))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn is_failed(&self) -> bool {
|
||||
matches!(self.state, State::Failed)
|
||||
}
|
||||
|
||||
/// The owners leave with `fingerprint`.
|
||||
pub(crate) fn lend(&mut self, fingerprint: F) -> Result<(), LoanError> {
|
||||
match self.state {
|
||||
State::Home => {
|
||||
self.state = State::Lent(fingerprint);
|
||||
Ok(())
|
||||
}
|
||||
State::Lent(_) => Err(LoanError::AlreadyLent),
|
||||
State::Failed => Err(LoanError::Failed),
|
||||
}
|
||||
}
|
||||
|
||||
/// The owners are about to return; `now` is the fingerprint of the ones that come back (`None`: it could not be
|
||||
/// taken). Equal: the loan ends. Anything else fails it for good.
|
||||
pub(crate) fn take_back(&mut self, now: Option<F>) -> Result<(), LoanError> {
|
||||
match &self.state {
|
||||
State::Home => Err(LoanError::NotLent),
|
||||
State::Failed => Err(LoanError::Failed),
|
||||
State::Lent(lent) if now.as_ref() == Some(lent) => {
|
||||
self.state = State::Home;
|
||||
Ok(())
|
||||
}
|
||||
State::Lent(_) => {
|
||||
self.state = State::Failed;
|
||||
Err(LoanError::Changed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fail the loan (the journal itself failed).
|
||||
pub(crate) fn fail(&mut self) {
|
||||
self.state = State::Failed;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn owners_that_come_back_at_the_same_addresses_end_the_loan() {
|
||||
let mut loan = OwnerLoan::new();
|
||||
assert!(!loan.is_lent());
|
||||
loan.lend([1u64, 2, 3]).unwrap();
|
||||
assert!(loan.is_lent());
|
||||
loan.take_back(Some([1, 2, 3])).unwrap();
|
||||
assert!(!loan.is_lent() && !loan.is_failed());
|
||||
loan.lend([1, 2, 3]).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_address_or_a_missing_fingerprint_fails_the_loan_for_good() {
|
||||
for now in [Some([1u64, 2, 4]), None] {
|
||||
let mut loan = OwnerLoan::new();
|
||||
loan.lend([1u64, 2, 3]).unwrap();
|
||||
assert_eq!(loan.take_back(now), Err(LoanError::Changed));
|
||||
assert!(loan.is_failed());
|
||||
assert_eq!(loan.lend([1, 2, 3]), Err(LoanError::Failed));
|
||||
assert_eq!(loan.take_back(Some([1, 2, 3])), Err(LoanError::Failed));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_steps_out_of_order_are_refused_and_change_nothing() {
|
||||
let mut loan = OwnerLoan::new();
|
||||
assert_eq!(loan.take_back(Some(7u32)), Err(LoanError::NotLent));
|
||||
loan.lend(7).unwrap();
|
||||
assert_eq!(loan.lend(7), Err(LoanError::AlreadyLent));
|
||||
assert!(loan.is_lent() && !loan.is_failed());
|
||||
loan.take_back(Some(7)).unwrap();
|
||||
loan.fail();
|
||||
assert!(loan.is_failed());
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,14 @@ impl LinearLaunch {
|
||||
Self { grid, block, stream }
|
||||
}
|
||||
}
|
||||
/// What a kernel module's host code needs to know about the current device: compute capability major, multiprocessor
|
||||
/// count and the opt-in limit of dynamic shared memory a block.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct DeviceGeometry {
|
||||
pub(crate) cc_major: u32,
|
||||
pub(crate) multiprocessors: u32,
|
||||
pub(crate) shared_optin: u32,
|
||||
}
|
||||
/// The grid `[x, y]`, `block` threads, cluster width and dynamic shared memory of one cluster launch.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct ClusterShape {
|
||||
|
||||
@@ -79,18 +79,63 @@ impl KernelModule {
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn launch(&self, index: usize, launch: LinearLaunch, args: &mut KernelArguments) -> Result<()> {
|
||||
self.launch_dynamic(index, launch, 0, args)
|
||||
}
|
||||
/// `launch` with `smem` bytes of dynamic shared memory. Above the 48 KiB default the function is first opted in
|
||||
/// with `cuFuncSetAttribute(MAX_DYNAMIC_SHARED_SIZE_BYTES)` (the device's opt-in limit is the caller's check).
|
||||
pub(crate) fn launch_dynamic(
|
||||
&self,
|
||||
index: usize,
|
||||
launch: LinearLaunch,
|
||||
smem: u32,
|
||||
args: &mut KernelArguments,
|
||||
) -> Result<()> {
|
||||
let LinearLaunch { grid, block, stream } = launch;
|
||||
if grid == 0 || !matches!(block, 128 | 256 | 512 | 1024) || stream == 0 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let function = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?;
|
||||
if smem > 48 * 1024 {
|
||||
self.allow_dynamic_shared(function, smem)?;
|
||||
}
|
||||
args.pack()?;
|
||||
// SAFETY: owned boxed command fields and exact producer-declared
|
||||
// ABI persist until drain; Driver copies the parameter pointer array
|
||||
// during this call. No pointer/entry escapes to public callers.
|
||||
let (function, stream, pointers) = (function as *mut c_void, stream as *mut c_void, args.pointers.as_mut_ptr());
|
||||
check("cuLaunchKernel", unsafe {
|
||||
(self.launch)(function, grid, 1, 1, block, 1, 1, 0, stream, pointers, std::ptr::null_mut())
|
||||
(self.launch)(function, grid, 1, 1, block, 1, 1, smem, stream, pointers, std::ptr::null_mut())
|
||||
})
|
||||
}
|
||||
/// `cuFuncSetAttribute(MAX_DYNAMIC_SHARED_SIZE_BYTES, smem)` of one function of this module.
|
||||
fn allow_dynamic_shared(&self, function: usize, smem: u32) -> Result<()> {
|
||||
let library = self._library.as_ref().ok_or(Error::LibraryUnavailable)?;
|
||||
let set_attribute = symbol!(library, c"cuFuncSetAttribute", FuncSetAttribute);
|
||||
let attribute = crate::launch_ex::FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED;
|
||||
// SAFETY: the function belongs to this live module and the context is current (the launch contract).
|
||||
check("cuFuncSetAttribute", unsafe { set_attribute(function as *mut c_void, attribute, smem as c_int) })
|
||||
}
|
||||
/// Compute capability, multiprocessor count and opt-in shared memory of the device that is current (the caller runs
|
||||
/// inside `Context::enter`).
|
||||
pub(crate) fn device_geometry(&self) -> Result<crate::ple_batch_ffi::DeviceGeometry> {
|
||||
type CtxGetDevice = unsafe extern "C" fn(*mut c_int) -> c_int;
|
||||
type DeviceAttribute = unsafe extern "C" fn(*mut c_int, c_int, c_int) -> c_int;
|
||||
let library = self._library.as_ref().ok_or(Error::LibraryUnavailable)?;
|
||||
let device = symbol!(library, c"cuCtxGetDevice", CtxGetDevice);
|
||||
let attribute = symbol!(library, c"cuDeviceGetAttribute", DeviceAttribute);
|
||||
let mut d: c_int = 0;
|
||||
// SAFETY: a valid out-pointer to a live local; a current context is the caller's precondition.
|
||||
check("cuCtxGetDevice", unsafe { device(&mut d) })?;
|
||||
let read = |id: c_int, what: &'static str| -> Result<u32> {
|
||||
let mut value: c_int = 0;
|
||||
// SAFETY: valid out-pointer to a live local and the device just returned by the driver.
|
||||
check(what, unsafe { attribute(&mut value, id, d) })?;
|
||||
u32::try_from(value).map_err(|_| Error::InvalidDriverValue(what))
|
||||
};
|
||||
Ok(crate::ple_batch_ffi::DeviceGeometry {
|
||||
cc_major: read(75, "cuDeviceGetAttribute(compute capability major)")?,
|
||||
multiprocessors: read(16, "cuDeviceGetAttribute(multiprocessors)")?,
|
||||
shared_optin: read(97, "cuDeviceGetAttribute(shared memory opt-in)")?,
|
||||
})
|
||||
}
|
||||
/// `cuLaunchKernelEx` with a thread-block cluster (sm_90+): grid `[x, y, 1]`, `block` threads, cluster `[cx, 1,
|
||||
|
||||
@@ -55,6 +55,12 @@ impl KernelModule {
|
||||
pub(crate) fn launch_cluster(&self, _: usize, _: ClusterShape, _: usize, _: &mut KernelArguments) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn launch_dynamic(&self, _: usize, _: LinearLaunch, _: u32, _: &mut KernelArguments) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn device_geometry(&self) -> Result<DeviceGeometry> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn close(self) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -32,3 +32,5 @@ use enable_types::Rng;
|
||||
mod gdn_recurrence_equals_the_original;
|
||||
#[path = "prefill_stage_gdn_gpu/gdn_stage_kernels_equal.rs"]
|
||||
mod gdn_stage_kernels_equal;
|
||||
#[path = "prefill_stage_gdn_gpu/gdn_tensor_core_scan_parity.rs"]
|
||||
mod gdn_tensor_core_scan_parity;
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
//! GPU parity of the EXPERIMENTAL tensor-core scan of the prompt GDN recurrence (`gdn_prefill_tc.cu`, ledger row U1)
|
||||
//! against the sequential `leleka_prefill_gdn_rec` kernel (bit-identical to the Original's recurrence). The scan is
|
||||
//! LOSSY by design: this test is the upstream harness's gate (1e-4 absolute / relative, `gdn_rec_parity`), not an
|
||||
//! identity probe, and the quality gate of docs/quality-gate.md decides whether it may ever be used. Needs a CUDA
|
||||
//! device with compute capability 12 and no model:
|
||||
//! LELEKA_PREFILL_STAGE_GPU=yes cargo test -p leleka-cuda-driver --features cuda-driver --release --lib \
|
||||
//! gdn_tensor_core_scan -- --ignored --nocapture
|
||||
//! Every case is run and printed before the verdict, so one run shows all failures (`PREFILL-GDN-TC` lines).
|
||||
|
||||
use super::gdn_recurrence_equals_the_original::{Rig, with_rig};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::gdn_prefill_tc as tc;
|
||||
use crate::ple_batch_ffi::LinearLaunch;
|
||||
|
||||
const STATE_LEN: usize = 128 * 48 * 128;
|
||||
/// The prompt device's dequantization scratch the scan runs in.
|
||||
const SCRATCH: usize = 52_428_800;
|
||||
/// Upstream's gate: |scan - sequential| <= 1e-4 max(1, |sequential|), element by element.
|
||||
const TOLERANCE: f32 = 1e-4;
|
||||
/// Ill-conditioned inputs (identical keys, no decay): T = (I + A)^-1 grows; reported, with a looser bound.
|
||||
const STRESS_TOLERANCE: f32 = 1e-3;
|
||||
|
||||
/// What a case feeds the recurrence.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Inputs {
|
||||
/// Unit q/k, decay exp(-0.02..-0.7), beta 0.05..1, v and state O(1): the shape of a real prompt.
|
||||
Typical,
|
||||
/// Almost no decay and beta near 1: the state keeps everything it was given.
|
||||
NoDecay,
|
||||
/// v 8x and the state 4x larger than typical (the per-chunk power-of-two scales move).
|
||||
Large,
|
||||
/// Every token of a key head has (almost) the same k, beta 1, no decay: T = (I + A)^-1 spans 2^30.
|
||||
CollinearKeys,
|
||||
/// One infinite value in the prior state: both kernels must raise the witness.
|
||||
InfiniteState,
|
||||
}
|
||||
|
||||
impl Inputs {
|
||||
fn stress(self) -> bool {
|
||||
matches!(self, Self::CollinearKeys | Self::NoDecay)
|
||||
}
|
||||
}
|
||||
|
||||
/// A unit vector of `n` values from the generator (the L2 norm of the real chain).
|
||||
fn unit(rng: &mut Rng, out: &mut [f32]) {
|
||||
out.iter_mut().for_each(|x| *x = rng.f(1.0));
|
||||
let norm = out.iter().map(|x| x * x).sum::<f32>().sqrt().max(1e-6);
|
||||
out.iter_mut().for_each(|x| *x /= norm);
|
||||
}
|
||||
|
||||
/// One run's inputs on the host: state [128][48][128], h [t][10240] (q | k | v), gate and beta [t][48].
|
||||
struct Host {
|
||||
state: Vec<f32>,
|
||||
h: Vec<f32>,
|
||||
gate: Vec<f32>,
|
||||
beta: Vec<f32>,
|
||||
}
|
||||
|
||||
fn generate(rng: &mut Rng, t: usize, kind: Inputs) -> Host {
|
||||
let (state_scale, v_scale) = if kind == Inputs::Large { (4.0, 8.0) } else { (0.5, 1.0) };
|
||||
let mut state: Vec<f32> = (0..STATE_LEN).map(|_| rng.f(state_scale)).collect();
|
||||
if kind == Inputs::InfiniteState {
|
||||
state[1234] = f32::INFINITY;
|
||||
}
|
||||
let mut h = vec![0.0f32; t * 10240];
|
||||
let first_k: Vec<f32> = (0..16 * 128).map(|_| rng.f(1.0)).collect();
|
||||
for row in h.chunks_mut(10240) {
|
||||
for head in 0..16 {
|
||||
unit(rng, &mut row[head * 128..(head + 1) * 128]);
|
||||
let k = &mut row[2048 + head * 128..2048 + (head + 1) * 128];
|
||||
unit(rng, k);
|
||||
if kind == Inputs::CollinearKeys {
|
||||
k.iter_mut().zip(&first_k[head * 128..]).for_each(|(x, f)| *x = f + 1e-3 * *x);
|
||||
let norm = k.iter().map(|x| x * x).sum::<f32>().sqrt();
|
||||
k.iter_mut().for_each(|x| *x /= norm);
|
||||
}
|
||||
}
|
||||
row[4096..].iter_mut().for_each(|x| *x = rng.f(v_scale));
|
||||
}
|
||||
let (gate, beta) = match kind {
|
||||
Inputs::NoDecay | Inputs::CollinearKeys => (vec![-1e-3; t * 48], vec![0.95; t * 48]),
|
||||
_ => (
|
||||
(0..t * 48).map(|_| -0.02 - rng.f(0.34).abs() * 2.0).collect(),
|
||||
(0..t * 48).map(|_| 0.05 + (rng.f(0.5) + 0.5).abs() * 0.95).collect(),
|
||||
),
|
||||
};
|
||||
Host { state, h, gate, beta }
|
||||
}
|
||||
|
||||
/// The device side of one case; `_s` the sequential kernel's outputs, `_t` the scan's.
|
||||
struct Device<'c> {
|
||||
sin: DeviceBuffer<'c>,
|
||||
h: DeviceBuffer<'c>,
|
||||
gate: DeviceBuffer<'c>,
|
||||
beta: DeviceBuffer<'c>,
|
||||
sout_s: DeviceBuffer<'c>,
|
||||
sout_t: DeviceBuffer<'c>,
|
||||
y_s: DeviceBuffer<'c>,
|
||||
y_t: DeviceBuffer<'c>,
|
||||
w_s: DeviceBuffer<'c>,
|
||||
w_t: DeviceBuffer<'c>,
|
||||
scratch: DeviceBuffer<'c>,
|
||||
}
|
||||
|
||||
impl<'c> Device<'c> {
|
||||
fn new(context: &'c Context<'c>, host: &Host, t: usize) -> Self {
|
||||
let zero = |bytes: usize| upload(context, &vec![0u8; bytes]);
|
||||
Self {
|
||||
sin: upload(context, &f32_bytes(&host.state)),
|
||||
h: upload(context, &f32_bytes(&host.h)),
|
||||
gate: upload(context, &f32_bytes(&host.gate)),
|
||||
beta: upload(context, &f32_bytes(&host.beta)),
|
||||
sout_s: zero(STATE_LEN * 4),
|
||||
sout_t: zero(STATE_LEN * 4),
|
||||
y_s: zero(t * 6144 * 4),
|
||||
y_t: zero(t * 6144 * 4),
|
||||
w_s: zero(16),
|
||||
w_t: zero(16),
|
||||
scratch: context.allocate(SCRATCH).expect("scratch"),
|
||||
}
|
||||
}
|
||||
fn io(&self) -> tc::RecurrenceIo {
|
||||
tc::RecurrenceIo {
|
||||
state_in: hd(&self.sin),
|
||||
state_out: hd(&self.sout_t),
|
||||
h: hd(&self.h),
|
||||
gate: hd(&self.gate),
|
||||
beta: hd(&self.beta),
|
||||
y: hd(&self.y_t),
|
||||
witness: hd(&self.w_t),
|
||||
scratch: hd(&self.scratch),
|
||||
}
|
||||
}
|
||||
/// A sequential kernel (`entry` of the stage module, `grid` blocks of 128 threads) into the `_s` buffers.
|
||||
fn run_sequential(&self, rig: &Rig<'_>, t: usize, (entry, grid): (usize, u32)) {
|
||||
let mut args = KernelArguments::new(vec![
|
||||
A::Address(hd(&self.sin)),
|
||||
A::Address(hd(&self.sout_s)),
|
||||
A::Address(hd(&self.h)),
|
||||
A::Address(hd(&self.gate)),
|
||||
A::Address(hd(&self.beta)),
|
||||
A::Address(hd(&self.y_s)),
|
||||
A::I64(t as i64),
|
||||
A::Address(hd(&self.w_s)),
|
||||
]);
|
||||
let guard = rig.context.enter().expect("enter");
|
||||
let launch = LinearLaunch::new(grid, 128, rig.stream);
|
||||
rig.stage.launch(entry, launch, &mut args).expect("launch sequential");
|
||||
rig.context.driver.api.synchronize().expect("sync");
|
||||
guard.finish().expect("finish");
|
||||
}
|
||||
/// The prep and scan launches of the plan into the `_t` buffers, `reps` times (the state is re-read from `sin`).
|
||||
fn run_scan(&self, (rig, module): (&Rig<'_>, &KernelModule), plan: &tc::ScanPlan, (t, reps): (usize, usize)) {
|
||||
let guard = rig.context.enter().expect("enter");
|
||||
let mut keep = Vec::new();
|
||||
for _ in 0..reps {
|
||||
for l in tc::launches(plan, &self.io(), (SCRATCH, t)).expect("launches") {
|
||||
let mut args = KernelArguments::new(l.args);
|
||||
let launch = LinearLaunch::new(l.grid, l.block, rig.stream);
|
||||
module.launch_dynamic(l.entry, launch, l.smem, &mut args).expect("launch scan");
|
||||
keep.push(args);
|
||||
}
|
||||
}
|
||||
rig.context.driver.api.synchronize().expect("sync");
|
||||
guard.finish().expect("finish");
|
||||
}
|
||||
}
|
||||
|
||||
/// Worst element of one tensor against the gate `|a - b| <= tolerance max(1, |b|)`.
|
||||
#[derive(Default, Clone, Copy)]
|
||||
struct Worst {
|
||||
/// the largest |a - b| / max(1, |b|)
|
||||
scaled: f32,
|
||||
/// the largest |b|
|
||||
reference: f32,
|
||||
non_finite: usize,
|
||||
}
|
||||
|
||||
fn compare(scan: &[u8], reference: &[u8]) -> Worst {
|
||||
let to_f32 = |b: &[u8]| -> Vec<f32> { b.chunks(4).map(|c| f32::from_le_bytes(c.try_into().unwrap())).collect() };
|
||||
let (a, b) = (to_f32(scan), to_f32(reference));
|
||||
let mut worst = Worst::default();
|
||||
for (x, y) in a.iter().zip(&b) {
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
worst.non_finite += usize::from(x.is_finite() != y.is_finite());
|
||||
continue;
|
||||
}
|
||||
worst.scaled = worst.scaled.max((x - y).abs() / y.abs().max(1.0));
|
||||
worst.reference = worst.reference.max(y.abs());
|
||||
}
|
||||
worst
|
||||
}
|
||||
|
||||
/// One row of the table.
|
||||
struct Row {
|
||||
label: String,
|
||||
readout: Worst,
|
||||
state: Worst,
|
||||
witness: (u32, u32),
|
||||
tolerance: f32,
|
||||
}
|
||||
|
||||
impl Row {
|
||||
fn failure(&self, kind: Inputs) -> Option<String> {
|
||||
let (w_scan, w_ref) = self.witness;
|
||||
let expect_bad = kind == Inputs::InfiniteState;
|
||||
if (w_ref != 0) != expect_bad || (w_scan != 0) != expect_bad {
|
||||
return Some(format!("witness scan {w_scan} sequential {w_ref} (expected {})", u32::from(expect_bad)));
|
||||
}
|
||||
if expect_bad {
|
||||
return None;
|
||||
}
|
||||
let bad = |w: &Worst| w.scaled > self.tolerance || w.non_finite > 0;
|
||||
(bad(&self.readout) || bad(&self.state)).then(|| "beyond the gate".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// One token count, one input kind, one plan: the sequential kernel, then the scan, then the comparison.
|
||||
fn case(rig: &Rig<'_>, module: &KernelModule, host_of: (&Host, Inputs), (t, plan): (usize, &tc::ScanPlan)) -> Row {
|
||||
let (host, kind) = host_of;
|
||||
let device = Device::new(rig.context, host, t);
|
||||
device.run_sequential(rig, t, (crate::prefill_stage::GDN_REC, 192));
|
||||
device.run_scan((rig, module), plan, (t, 1));
|
||||
let readout = compare(&download(&device.y_t, t * 6144 * 4), &download(&device.y_s, t * 6144 * 4));
|
||||
let state = compare(&download(&device.sout_t, STATE_LEN * 4), &download(&device.sout_s, STATE_LEN * 4));
|
||||
Row {
|
||||
label: format!("t={t} {kind:?} tiles={} chunks/block={}", plan.tiles(), plan.chunks()),
|
||||
readout,
|
||||
state,
|
||||
witness: (words(&device.w_t, 1)[0], words(&device.w_s, 1)[0]),
|
||||
tolerance: if kind.stress() { STRESS_TOLERANCE } else { TOLERANCE },
|
||||
}
|
||||
}
|
||||
|
||||
fn print(row: &Row) {
|
||||
let w = |w: &Worst| format!("{:.2e} (max|ref| {:.3}, {} non-finite)", w.scaled, w.reference, w.non_finite);
|
||||
eprintln!(
|
||||
"PREFILL-GDN-TC {}: readout {} state {} witness scan {} seq {} gate {:.0e}",
|
||||
row.label,
|
||||
w(&row.readout),
|
||||
w(&row.state),
|
||||
row.witness.0,
|
||||
row.witness.1,
|
||||
row.tolerance
|
||||
);
|
||||
}
|
||||
|
||||
/// The device's plan, or None (with the reason printed) when this card cannot run the asset.
|
||||
fn device_plan(module: &KernelModule, rig: &Rig<'_>) -> Option<tc::ScanPlan> {
|
||||
let guard = rig.context.enter().expect("enter");
|
||||
let geometry = module.device_geometry().expect("device geometry");
|
||||
guard.finish().expect("finish");
|
||||
match tc::plan(true, geometry, SCRATCH) {
|
||||
Ok(plan) => Some(plan),
|
||||
Err(refusal) => {
|
||||
eprintln!("PREFILL-GDN-TC skipped: {refusal} ({geometry:?})");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_module(rig: &Rig<'_>) -> KernelModule {
|
||||
tc::admit().expect("gdn_prefill_tc.ptx must match its pin");
|
||||
let guard = rig.context.enter().expect("enter");
|
||||
let module = KernelModule::load(tc::PTX, tc::ENTRIES).expect("tensor-core scan module");
|
||||
guard.finish().expect("finish");
|
||||
module
|
||||
}
|
||||
|
||||
/// Token counts of the gate: every chunk edge near 32, 128 (the dispatch minimum), the super-block edge of the
|
||||
/// scratch (1,760) and of upstream's 2,048, the harness's 4,099 and a full 8,192-token prompt chunk, then eight
|
||||
/// pseudo-random lengths up to 4,099.
|
||||
fn token_counts(rng: &mut Rng) -> Vec<usize> {
|
||||
let mut counts = vec![
|
||||
1, 2, 31, 32, 33, 63, 64, 65, 127, 128, 129, 200, 255, 256, 257, 1000, 1759, 1760, 1761, 2047, 2048, 2049,
|
||||
3520, 3521, 4096, 4097, 4099, 8192,
|
||||
];
|
||||
counts.extend((0..8).map(|_| 1 + (rng.next() % 4099) as usize));
|
||||
counts
|
||||
}
|
||||
|
||||
/// The cases run so far, and what they run on.
|
||||
struct Gate<'a> {
|
||||
rig: &'a Rig<'a>,
|
||||
module: KernelModule,
|
||||
rng: Rng,
|
||||
table: Vec<(Row, Inputs)>,
|
||||
}
|
||||
|
||||
impl Gate<'_> {
|
||||
fn run(&mut self, t: usize, kind: Inputs, plan: &tc::ScanPlan) {
|
||||
let host = generate(&mut self.rng, t, kind);
|
||||
let row = case(self.rig, &self.module, (&host, kind), (t, plan));
|
||||
print(&row);
|
||||
self.table.push((row, kind));
|
||||
}
|
||||
/// Typical inputs, every length, both value-tile plans of the 99-KB card.
|
||||
fn typical_lengths(&mut self, plan: &tc::ScanPlan) {
|
||||
for t in token_counts(&mut self.rng) {
|
||||
for tiles in [1, 2] {
|
||||
self.run(t, Inputs::Typical, &plan.with_tiles(tiles));
|
||||
}
|
||||
}
|
||||
// small super-blocks chain the state through many launches (in place, as the product does)
|
||||
for t in [200, 1000, 4099] {
|
||||
self.run(t, Inputs::Typical, &plan.with_chunks(3));
|
||||
}
|
||||
}
|
||||
fn stress(&mut self, plan: &tc::ScanPlan) {
|
||||
for kind in [Inputs::NoDecay, Inputs::Large, Inputs::CollinearKeys, Inputs::InfiniteState] {
|
||||
for t in [128, 129, 1000, 2049, 8192] {
|
||||
self.run(t, kind, plan);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn verdict(&self) {
|
||||
let fails = |(r, k): &(Row, Inputs)| r.failure(*k).map(|why| format!("{}: {why}", r.label));
|
||||
let failures: Vec<String> = self.table.iter().filter_map(fails).collect();
|
||||
let (n, list) = (self.table.len(), failures.join("\n"));
|
||||
assert!(failures.is_empty(), "{} of {n} cases fail:\n{list}", failures.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Root-only: needs a CUDA device with compute capability 12"]
|
||||
fn gdn_tensor_core_scan_stays_within_the_gate_of_the_sequential_recurrence() {
|
||||
with_rig(6usize << 30, 2048, |rig| {
|
||||
let module = load_module(rig);
|
||||
let Some(plan) = device_plan(&module, rig) else { return };
|
||||
let mut gate = Gate { rig, module, rng: Rng(0x7e57_0c0d_e5ca_17ed), table: Vec::new() };
|
||||
gate.typical_lengths(&plan);
|
||||
gate.stress(&plan);
|
||||
gate.verdict();
|
||||
});
|
||||
}
|
||||
|
||||
/// Timing on warm data, a SYNTHETIC kernel number (not an end-to-end prefill gain): 20 runs of the scan's prep + scan
|
||||
/// against 20 of the kh recurrence (64 blocks, the product's sequential kernel), for the lengths of a prompt chunk.
|
||||
/// The span to compare in a real run is the `gdn` stage of the prefill profile.
|
||||
#[test]
|
||||
#[ignore = "Root-only: needs a CUDA device with compute capability 12"]
|
||||
fn gdn_tensor_core_scan_timing_against_the_kh_recurrence() {
|
||||
with_rig(6usize << 30, 2048, |rig| {
|
||||
let module = load_module(rig);
|
||||
let Some(plan) = device_plan(&module, rig) else { return };
|
||||
let mut rng = Rng(0x71_3e_71_3e_71_3e);
|
||||
for t in [512usize, 2048, 8192] {
|
||||
let device = Device::new(rig.context, &generate(&mut rng, t, Inputs::Typical), t);
|
||||
let reps = 20;
|
||||
let started = std::time::Instant::now();
|
||||
for _ in 0..reps {
|
||||
device.run_sequential(rig, t, (crate::prefill_stage::GDN_REC_KH, 64));
|
||||
}
|
||||
let sequential = started.elapsed().as_secs_f64() * 1e3 / reps as f64;
|
||||
let started = std::time::Instant::now();
|
||||
device.run_scan((rig, &module), &plan, (t, reps));
|
||||
let scan = started.elapsed().as_secs_f64() * 1e3 / reps as f64;
|
||||
eprintln!(
|
||||
"PREFILL-GDN-TC timing t={t} tiles={}: kh recurrence {sequential:.3} ms (one sync each), \
|
||||
tensor-core prep+scan {scan:.3} ms (mean of {reps}, warm; synthetic)",
|
||||
plan.tiles()
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -136,6 +136,14 @@ mod parked_tests {
|
||||
assert_eq!(*out, sub_span(kv, pages, 100, 150));
|
||||
// beyond the reachable end is refused
|
||||
assert!(journal.export_pages(500, 13, out).is_err());
|
||||
// the fast export (drained context, no zero fill) returns the same bytes and refuses the same spans
|
||||
let mut fast = vec![7u8; 3];
|
||||
journal.export_pages_fast(0, pages, &mut fast).unwrap();
|
||||
assert_eq!(fast, kv, "the fast export is byte for byte the export");
|
||||
journal.export_pages_fast(100, 50, &mut fast).unwrap();
|
||||
assert_eq!(fast, sub_span(kv, pages, 100, 150));
|
||||
assert!(journal.export_pages_fast(500, 13, &mut fast).is_err());
|
||||
assert!(journal.export_pages_fast(0, 0, &mut fast).is_err());
|
||||
}
|
||||
|
||||
/// Rolled back, the image is written back in two pieces, and malformed spans are refused.
|
||||
@@ -165,6 +173,16 @@ mod parked_tests {
|
||||
assert_eq!(out, kv);
|
||||
}
|
||||
|
||||
/// The fast export of the index image returns the rows of the export and refuses the same spans.
|
||||
fn fast_rows_match(index: &OriginalQsaResidentIndex<'_>, rows: &[u8]) {
|
||||
let (row, mut fast) = (OriginalQsaResidentIndex::ROW_BYTES, vec![7u8; 3]);
|
||||
index.export_rows_fast(0, rows.len() / row, &mut fast).unwrap();
|
||||
assert_eq!(fast, rows, "the fast export is byte for byte the export");
|
||||
index.export_rows_fast(10, 20, &mut fast).unwrap();
|
||||
assert_eq!(fast, rows[10 * row..30 * row]);
|
||||
assert!(index.export_rows_fast(rows.len() / row, 1, &mut fast).is_err(), "rows beyond end / 4 are refused");
|
||||
}
|
||||
|
||||
/// The index: pooled rows below end/4 plus a 2564-byte tail, written back whole and then in part.
|
||||
fn index_round_trip<'c>(
|
||||
index: &mut OriginalQsaResidentIndex<'c>,
|
||||
@@ -181,6 +199,7 @@ mod parked_tests {
|
||||
index.validate_checkpoint(&checkpoint).unwrap();
|
||||
index.export_rows(0, cells / 4, out).unwrap();
|
||||
assert_eq!(*out, rows, "the pooled rows come back");
|
||||
fast_rows_match(index, &rows);
|
||||
assert_eq!(index.export_tail(&checkpoint).unwrap(), tail_bytes, "the tail round-trips through the image");
|
||||
// partial write-back: only the second half of the rows, on top of an image that already holds the first
|
||||
let second = rows[(cells / 8) * OriginalQsaResidentIndex::ROW_BYTES..].to_vec();
|
||||
|
||||
@@ -189,17 +189,20 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
|
||||
pub const HOST_PAGE_BYTES: usize = QSA_PROMPT_HOST_PAGE_BYTES;
|
||||
/// Copy the pages `first_page..first_page + pages` of the reachable prefix out of the host image.
|
||||
pub fn export_pages(&self, first_page: usize, pages: usize, out: &mut Vec<u8>) -> Result<()> {
|
||||
self.validate_context(self.owner.context)?;
|
||||
// whole pages up to the one holding the last reachable cell (a request-end checkpoint ends inside a page)
|
||||
if pages == 0 || first_page.checked_add(pages).is_none_or(|e| e > self.end.div_ceil(4)) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
self.check_export(first_page, pages)?;
|
||||
// the GPU wrote these cells through the mapped alias; every public writer drains, this keeps the read ordered
|
||||
// after it
|
||||
self.owner.context.synchronize()?;
|
||||
{
|
||||
let _p = crate::host_profile::span("export.sync");
|
||||
self.owner.context.synchronize()?;
|
||||
}
|
||||
out.clear();
|
||||
out.try_reserve_exact(pages * Self::HOST_PAGE_BYTES).map_err(|_| Error::HostAllocation)?;
|
||||
out.resize(pages * Self::HOST_PAGE_BYTES, 0);
|
||||
{
|
||||
let _p = crate::host_profile::span("export.alloc");
|
||||
out.try_reserve_exact(pages * Self::HOST_PAGE_BYTES).map_err(|_| Error::HostAllocation)?;
|
||||
out.resize(pages * Self::HOST_PAGE_BYTES, 0);
|
||||
}
|
||||
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 mut at = 0;
|
||||
@@ -210,6 +213,35 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The journal is this context's and the pages lie in the reachable prefix: whole pages up to the one holding the
|
||||
/// last reachable cell (a request-end checkpoint ends inside a page).
|
||||
fn check_export(&self, first_page: usize, pages: usize) -> Result<()> {
|
||||
self.validate_context(self.owner.context)?;
|
||||
if pages == 0 || first_page.checked_add(pages).is_none_or(|e| e > self.end.div_ceil(4)) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// `export_pages` for a caller that has drained the context since the last enqueue (one
|
||||
/// `Context::synchronize` for all the layers of a park, not one per layer) and for a buffer that is only ever
|
||||
/// written by the copy: the bytes are the same as `export_pages`, with no synchronize and no zero fill first.
|
||||
/// With an undrained context the cells the GPU wrote last may not have landed: the caller owns that ordering.
|
||||
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 _p = crate::host_profile::span("export.copy_fast");
|
||||
crate::exact_fill::fill_exact(out, pages * Self::HOST_PAGE_BYTES, |dst| {
|
||||
let mut rest = dst;
|
||||
let mut written = 0;
|
||||
for (i, &page) in super::super::PAGE.iter().enumerate() {
|
||||
let (run, tail) = rest.split_at_mut(pages * page);
|
||||
m.read_uninit(offsets[i] + first_page * page, run)?;
|
||||
(written, rest) = (written + run.len(), tail);
|
||||
}
|
||||
Ok(written)
|
||||
})
|
||||
}
|
||||
/// Put parked spans `(first_page, bytes)` back into the host image and make the journal's reachable prefix end at
|
||||
/// `end` cells: the cells below `end` that no span names must already hold the prefix (the caller's live-prefix
|
||||
/// bookkeeping). Any written cell may have a stale copy in the VRAM resident window, so the resolver is reset
|
||||
|
||||
@@ -126,6 +126,17 @@ mod enabled {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// `read` into bytes that are not initialised yet (the prefix-cache export fills a fresh buffer without
|
||||
/// zeroing it first); every byte of `out` is written.
|
||||
pub(crate) fn read_uninit(&self, o: usize, out: &mut [std::mem::MaybeUninit<u8>]) -> Result<()> {
|
||||
let p = self.range(o, out.len())?;
|
||||
// SAFETY: as `read`: `range` proved `[p, p + out.len())` lies inside the live allocation and `out` is a
|
||||
// caller slice that cannot overlap it; the copy writes all `out.len()` bytes of `out`.
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(p as *const u8, out.as_mut_ptr().cast::<u8>(), out.len());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn close(&mut self) -> Result<()> {
|
||||
if let Some(p) = self.host {
|
||||
// SAFETY: `p` is the base returned by cuMemHostAlloc and not yet freed (`host` is cleared only after a
|
||||
@@ -174,6 +185,9 @@ impl MappedAllocation {
|
||||
pub(crate) fn read(&self, _: usize, _: &mut [u8]) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn read_uninit(&self, _: usize, _: &mut [std::mem::MaybeUninit<u8>]) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn write(&mut self, _: usize, _: &[u8]) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ mod resident_scalar_index;
|
||||
pub use resident_scalar_index::{OriginalQsaResidentScalarIndex, OriginalQsaResidentScalarSelection, ScalarStepRows};
|
||||
|
||||
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
|
||||
pub use resident_index::verification_commit::{OriginalVerifyQsaJournal, OriginalVerifyRope};
|
||||
pub use resident_index::verification_commit::{OriginalQsaOwners, OriginalVerifyQsaJournal, OriginalVerifyRope};
|
||||
|
||||
mod max_blocks;
|
||||
#[allow(unused_imports)]
|
||||
|
||||
@@ -193,6 +193,18 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> {
|
||||
pub const TAIL_BYTES: usize = CHECKPOINT_BYTES;
|
||||
/// Copy the pooled key rows `first_row..first_row + rows` (all below the current end / 4) to the host.
|
||||
pub fn export_rows(&self, first_row: usize, rows: usize, out: &mut Vec<u8>) -> Result<()> {
|
||||
self.check_export(first_row, rows)?;
|
||||
out.clear();
|
||||
{
|
||||
let _p = crate::host_profile::span("export.index_alloc");
|
||||
out.try_reserve_exact(rows * Self::ROW_BYTES).map_err(|_| Error::HostAllocation)?;
|
||||
out.resize(rows * Self::ROW_BYTES, 0);
|
||||
}
|
||||
let _p = crate::host_profile::span("export.index_copy");
|
||||
self.image[0].as_ref().ok_or(Error::ContextPoisoned)?.copy_to_range(first_row * Self::ROW_BYTES, out)
|
||||
}
|
||||
/// The image is settled and the rows lie below the current end / 4.
|
||||
fn check_export(&self, first_row: usize, rows: usize) -> Result<()> {
|
||||
self.validate()?;
|
||||
if self.in_flight || self.unpublished {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
@@ -200,10 +212,18 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> {
|
||||
if rows == 0 || first_row.checked_add(rows).is_none_or(|e| e > self.end / 4) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
out.clear();
|
||||
out.try_reserve_exact(rows * Self::ROW_BYTES).map_err(|_| Error::HostAllocation)?;
|
||||
out.resize(rows * Self::ROW_BYTES, 0);
|
||||
self.image[0].as_ref().ok_or(Error::ContextPoisoned)?.copy_to_range(first_row * Self::ROW_BYTES, out)
|
||||
Ok(())
|
||||
}
|
||||
/// `export_rows` that takes the device read's own staging as the result instead of zero filling `out` and copying
|
||||
/// the staging into it: the same bytes, one allocation, one zero fill and one copy fewer. `out` is replaced.
|
||||
pub fn export_rows_fast(&self, first_row: usize, rows: usize, out: &mut Vec<u8>) -> Result<()> {
|
||||
self.check_export(first_row, rows)?;
|
||||
let _p = crate::host_profile::span("export.index_copy_fast");
|
||||
*out = self.image[0]
|
||||
.as_ref()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.copy_to_range_owned(first_row * Self::ROW_BYTES, rows * Self::ROW_BYTES)?;
|
||||
Ok(())
|
||||
}
|
||||
/// The bytes of a checkpoint of this lineage: everything `import` needs besides the rows below its end.
|
||||
pub fn export_tail(&self, s: &OriginalQsaIndexCheckpoint<'ctx>) -> Result<Vec<u8>> {
|
||||
|
||||
@@ -5,6 +5,7 @@ use super::*;
|
||||
use crate::OriginalCapture;
|
||||
use crate::original_verify::abi::{Arg, Command};
|
||||
use crate::original_verify::{OriginalVerifyBank, OriginalVerifyGdnJournal};
|
||||
use crate::owner_loan::OwnerLoan;
|
||||
use std::cell::RefCell;
|
||||
/// Resolved Original analytic constants, and actual optional retained device
|
||||
/// tables. Process policy is fixed before capture by the genuine model adapter.
|
||||
@@ -20,6 +21,7 @@ pub struct OriginalVerifyRope<'ctx> {
|
||||
pub angles: Option<(DeviceRef<'ctx>, DeviceRef<'ctx>, usize)>,
|
||||
}
|
||||
/// Addresses of one QSA layer's fixed owners (see `OriginalVerifyQsaJournal::window_addresses`).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) struct OriginalVerifyQsaWindowAddresses {
|
||||
pub resident: [u64; 4],
|
||||
pub table: u64,
|
||||
@@ -44,8 +46,10 @@ struct Live {
|
||||
/// before the indexer and resolves attention from that same K/V prefix.
|
||||
pub struct OriginalVerifyQsaJournal<'ctx> {
|
||||
context: &'ctx Context<'ctx>,
|
||||
indices: [RefCell<OriginalQsaResidentIndex<'ctx>>; 12],
|
||||
mapped: [RefCell<OriginalQsaMappedJournal<'ctx>>; 12],
|
||||
/// The owners; `None` while they are out on loan (`lend` / `take_back`).
|
||||
indices: [RefCell<Option<OriginalQsaResidentIndex<'ctx>>>; 12],
|
||||
mapped: [RefCell<Option<OriginalQsaMappedJournal<'ctx>>>; 12],
|
||||
loan: RefCell<OwnerLoan<[verify_qsa_journal_loan::OwnerPrint; 12]>>,
|
||||
gamma: [DeviceRef<'ctx>; 12],
|
||||
rope: OriginalVerifyRope<'ctx>,
|
||||
live: RefCell<Live>,
|
||||
@@ -65,6 +69,9 @@ use original_verify_rope::overlaps;
|
||||
use original_verify_rope::whole;
|
||||
#[path = "qsa_verification_commit/original_verify_qsa_journal.rs"]
|
||||
mod original_verify_qsa_journal;
|
||||
#[path = "qsa_verification_commit/verify_qsa_journal_loan.rs"]
|
||||
mod verify_qsa_journal_loan;
|
||||
pub use verify_qsa_journal_loan::OriginalQsaOwners;
|
||||
#[path = "qsa_verification_commit/verify_qsa_journal_capture_commit.rs"]
|
||||
mod verify_qsa_journal_capture_commit;
|
||||
#[path = "qsa_verification_commit/verify_qsa_journal_index_image.rs"]
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Moved out of the parent module by STRA-338: impl OriginalVerifyQsaJournal.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::verify_qsa_journal_loan::print_of;
|
||||
use super::*;
|
||||
|
||||
type Indices<'ctx> = [OriginalQsaResidentIndex<'ctx>; 12];
|
||||
@@ -69,7 +70,7 @@ fn check_rope_clear(rope: &OriginalVerifyRope<'_>, indices: &Indices<'_>) -> Res
|
||||
Ok(())
|
||||
}
|
||||
/// Every index and journal belongs to `context`, is idle and stands at `end`.
|
||||
fn check_aligned<'ctx>(
|
||||
pub(super) fn check_aligned<'ctx>(
|
||||
context: &'ctx Context<'ctx>,
|
||||
indices: &Indices<'ctx>,
|
||||
mapped: &[OriginalQsaMappedJournal<'ctx>; 12],
|
||||
@@ -99,8 +100,9 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
check_rope_clear(&rope, &indices)?;
|
||||
Ok(Rc::new(Self {
|
||||
context,
|
||||
indices: indices.map(RefCell::new),
|
||||
mapped: mapped.map(RefCell::new),
|
||||
indices: indices.map(|i| RefCell::new(Some(i))),
|
||||
mapped: mapped.map(|m| RefCell::new(Some(m))),
|
||||
loan: RefCell::new(OwnerLoan::new()),
|
||||
gamma,
|
||||
rope,
|
||||
live: RefCell::new(Live { generation: 0, position: end, rows: 0, armed: false }),
|
||||
@@ -117,9 +119,8 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
if self.failed.get() || c.is_poisoned() {
|
||||
return Err(Error::ContextPoisoned);
|
||||
}
|
||||
for (i, m) in self.indices.iter().zip(self.mapped.iter()) {
|
||||
let i = i.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let m = m.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
for layer in 0..12 {
|
||||
let (i, m) = (self.index(layer)?, self.kv(layer)?);
|
||||
i.validate_context(c)?;
|
||||
m.validate_context(c)?;
|
||||
if i.next_position() != m.next_position() {
|
||||
@@ -142,7 +143,7 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
if layer >= 12 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let i = self.indices[layer].try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let i = self.index(layer)?;
|
||||
consume(
|
||||
[
|
||||
i.image[0].as_ref().ok_or(Error::ContextPoisoned)?,
|
||||
@@ -162,7 +163,7 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
if layer >= 12 || self.live.try_borrow().map_err(|_| Error::InvalidQwenShape)?.armed {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let mut i = self.indices[layer].try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let mut i = self.index_mut(layer)?;
|
||||
if i.in_flight || i.unpublished {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
@@ -180,8 +181,8 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
}
|
||||
let mut held = Vec::new();
|
||||
held.try_reserve_exact(12).map_err(|_| Error::HostAllocation)?;
|
||||
for i in &self.indices {
|
||||
held.push(i.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?)
|
||||
for layer in 0..12 {
|
||||
held.push(self.index_mut(layer)?)
|
||||
}
|
||||
let mut refs: Vec<&mut OriginalQsaResidentIndex<'ctx>> = held.iter_mut().map(|i| &mut **i).collect();
|
||||
let saved = OriginalQsaResidentIndex::checkpoint_fenced_all(&mut refs, ws)?;
|
||||
@@ -198,7 +199,7 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
if layer >= 12 || self.live.try_borrow().map_err(|_| Error::InvalidQwenShape)?.armed {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let mut m = self.mapped[layer].try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let mut m = self.kv_mut(layer)?;
|
||||
consume(&mut m)
|
||||
}
|
||||
/// The resolved Original RoPE constants and optional retained tables (read only).
|
||||
@@ -213,39 +214,17 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
if layer >= 12 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let (resident, table, host, resolver, slots) =
|
||||
self.mapped[layer].try_borrow().map_err(|_| Error::InvalidQwenShape)?.window_kv_addresses()?;
|
||||
let ((pooled, pooled_bytes), (dead, dead_bytes)) = self.index_spans(layer)?;
|
||||
Ok(OriginalVerifyQsaWindowAddresses {
|
||||
resident,
|
||||
table,
|
||||
host,
|
||||
resolver,
|
||||
slots,
|
||||
pooled,
|
||||
pooled_bytes,
|
||||
dead,
|
||||
dead_bytes,
|
||||
})
|
||||
}
|
||||
/// The device address and byte length of the index image's pooled keys and of its spare key, as `(pooled, dead)`.
|
||||
fn index_spans(&self, layer: usize) -> Result<((u64, usize), (u64, usize))> {
|
||||
let i = self.indices[layer].try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let pooled = i.image[0].as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let dead = i.image[2].as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let address =
|
||||
|b: &DeviceBuffer<'ctx>| -> Result<u64> { Ok(b.handle.ok_or(Error::ContextPoisoned)?.qwen_address()) };
|
||||
Ok(((address(pooled)?, pooled.len()), (address(dead)?, dead.len())))
|
||||
let (index, kv) = (self.index(layer)?, self.kv(layer)?);
|
||||
Ok(print_of(&index, &kv)?.window)
|
||||
}
|
||||
pub fn allocated_bytes(&self) -> usize {
|
||||
self.indices.iter().map(|i| i.borrow().allocated_bytes()).sum::<usize>()
|
||||
+ self.mapped.iter().map(|m| m.borrow().allocated_bytes()).sum::<usize>()
|
||||
self.indices.iter().filter_map(|i| i.borrow().as_ref().map(|i| i.allocated_bytes())).sum::<usize>()
|
||||
+ self.mapped.iter().filter_map(|m| m.borrow().as_ref().map(|m| m.allocated_bytes())).sum::<usize>()
|
||||
}
|
||||
/// Every index and journal is idle and stands at `position`.
|
||||
pub(super) fn check_idle_at(&self, position: usize) -> Result<()> {
|
||||
for (i, m) in self.indices.iter().zip(self.mapped.iter()) {
|
||||
let i = i.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let m = m.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
for layer in 0..12 {
|
||||
let (i, m) = (self.index(layer)?, self.kv(layer)?);
|
||||
if i.in_flight || i.unpublished || i.end != position || m.next_position() != position {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
@@ -263,8 +242,8 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
snapshot.clear();
|
||||
snapshot.try_reserve_exact(12 * n).map_err(|_| Error::HostAllocation)?;
|
||||
snapshot.resize(12 * n, 0);
|
||||
for (layer, i) in self.indices.iter().enumerate() {
|
||||
let i = i.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
for layer in 0..12 {
|
||||
let i = self.index(layer)?;
|
||||
i.read_window_state(&mut snapshot[layer * n..(layer + 1) * n])?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -281,8 +260,8 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
self.snapshot_window_state()?;
|
||||
// All immutable borrows above are gone. This single-thread-affine owner
|
||||
// has no escaping RefMut; the fixed pass performs no fallible allocation.
|
||||
for i in &self.indices {
|
||||
let mut i = i.borrow_mut();
|
||||
for layer in 0..12 {
|
||||
let mut i = self.index_mut(layer)?;
|
||||
i.in_flight = true;
|
||||
i.unpublished = true;
|
||||
}
|
||||
@@ -301,7 +280,7 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
if layer >= 12 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let i = self.indices[layer].try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let i = self.index(layer)?;
|
||||
journal.submit(
|
||||
capture,
|
||||
vec![Command::new(
|
||||
|
||||
@@ -17,7 +17,7 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
if layer >= 12 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let i = self.indices[layer].try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let i = self.index(layer)?;
|
||||
let t = journal.geometry().max_t;
|
||||
journal.submit(
|
||||
capture,
|
||||
@@ -71,7 +71,7 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
fn fused_layers(&self) -> Result<[[u64; 12]; 5]> {
|
||||
let mut layers = [[0u64; 12]; 5];
|
||||
for layer in 0..12 {
|
||||
let i = self.indices[layer].try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let i = self.index(layer)?;
|
||||
let [tail, dead, pooled, block_pos] = image_addresses(&i)?;
|
||||
layers[0][layer] = tail;
|
||||
layers[1][layer] = dead;
|
||||
@@ -135,7 +135,7 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
if layer >= 12 || begin >= end || end > t {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let i = self.indices[layer].try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let i = self.index(layer)?;
|
||||
let gamma = whole(self.context, &self.gamma[layer], 512)?;
|
||||
let commands = self.append_commands(journal, &i, (layer * t, begin..end), (commit, gamma))?;
|
||||
journal.submit_qsa(capture, commands)
|
||||
@@ -225,8 +225,8 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
self.validate_context(self.context)?;
|
||||
workspace.validate_context(self.context)?;
|
||||
let keep = self.check_appended(bank, &appended)?;
|
||||
for (m, a) in self.mapped.iter().zip(appended) {
|
||||
let result = m.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?.accept_prefix(workspace, &a, keep);
|
||||
for (layer, a) in appended.into_iter().enumerate() {
|
||||
let result = self.kv_mut(layer)?.accept_prefix(workspace, &a, keep);
|
||||
if let Err(e) = result {
|
||||
self.failed.set(true);
|
||||
return Err(e);
|
||||
@@ -245,18 +245,17 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
let staged = bank.staged_window()?;
|
||||
let keep = bank.staged_keep()?;
|
||||
check_armed_window(&live, staged, keep)?;
|
||||
for (m, a) in self.mapped.iter().zip(appended.iter()) {
|
||||
Self::check_receipt(m, a, (staged.1, staged.2))?;
|
||||
for (layer, a) in appended.iter().enumerate() {
|
||||
Self::check_receipt(&*self.kv(layer)?, a, (staged.1, staged.2))?;
|
||||
}
|
||||
Ok(keep)
|
||||
}
|
||||
/// A receipt covers exactly the staged window, and its journal accepts the final prefix.
|
||||
fn check_receipt(
|
||||
m: &RefCell<OriginalQsaMappedJournal<'ctx>>,
|
||||
m: &OriginalQsaMappedJournal<'ctx>,
|
||||
a: &OriginalQsaMappedAppend,
|
||||
(position, rows): (usize, usize),
|
||||
) -> Result<()> {
|
||||
let m = m.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
if a.first_position() != position
|
||||
|| a.rows() != rows
|
||||
|| a.final_prefix().next_position() != position.checked_add(rows).ok_or(Error::InvalidSize)?
|
||||
|
||||
@@ -20,7 +20,7 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
if self.rope.angles.is_some() {
|
||||
return Ok(None);
|
||||
}
|
||||
let i = self.indices[layer].try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let i = self.index(layer)?;
|
||||
let [tail, dead, pooled, block_pos] = image_addresses(&i)?;
|
||||
let gamma = whole(self.context, &self.gamma[layer], 512)?;
|
||||
let positions = self
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
//! The owner loan of `OriginalVerifyQsaJournal` (ledger row Q7, docs/experiments/decode-graph-reuse.md).
|
||||
//!
|
||||
//! The captured window graphs retain this journal and bind the addresses of the twelve index images and mapped K/V
|
||||
//! journals it owns. The prompt executor needs those owners again for the next request. `lend` hands them out without
|
||||
//! dropping the journal (and so the graphs), `take_back` receives them, and the journal accepts them only if every
|
||||
//! address the graphs bound is unchanged. While the owners are out every use of the journal is refused (the accessors
|
||||
//! find nothing); a mismatch fails the journal for good, so the graph set that retains it is retired and never
|
||||
//! replayed.
|
||||
|
||||
use super::original_verify_qsa_journal::{check_aligned, image_addresses};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::owner_loan::LoanError;
|
||||
use std::cell::{Ref, RefMut};
|
||||
|
||||
/// The twelve index images and mapped journals of a loan.
|
||||
pub type OriginalQsaOwners<'ctx> = ([OriginalQsaResidentIndex<'ctx>; 12], [OriginalQsaMappedJournal<'ctx>; 12]);
|
||||
|
||||
/// Every address one layer's captured kernels bind: the window addresses plus the image's tail and block position.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) struct OwnerPrint {
|
||||
pub(super) window: OriginalVerifyQsaWindowAddresses,
|
||||
image: [u64; 4],
|
||||
}
|
||||
|
||||
/// The addresses the window graphs bind for one layer's owners.
|
||||
pub(super) fn print_of(index: &OriginalQsaResidentIndex<'_>, kv: &OriginalQsaMappedJournal<'_>) -> Result<OwnerPrint> {
|
||||
let (resident, table, host, resolver, slots) = kv.window_kv_addresses()?;
|
||||
let address = |b: &DeviceBuffer<'_>| -> Result<u64> { Ok(b.handle.ok_or(Error::ContextPoisoned)?.qwen_address()) };
|
||||
let pooled = index.image[0].as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let dead = index.image[2].as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let window = OriginalVerifyQsaWindowAddresses {
|
||||
resident,
|
||||
table,
|
||||
host,
|
||||
resolver,
|
||||
slots,
|
||||
pooled: address(pooled)?,
|
||||
pooled_bytes: pooled.len(),
|
||||
dead: address(dead)?,
|
||||
dead_bytes: dead.len(),
|
||||
};
|
||||
Ok(OwnerPrint { window, image: image_addresses(index)? })
|
||||
}
|
||||
|
||||
/// The accessors every use of the owners goes through: an error while the owners are out.
|
||||
impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
pub(super) fn index(&self, layer: usize) -> Result<Ref<'_, OriginalQsaResidentIndex<'ctx>>> {
|
||||
let cell = self.indices.get(layer).ok_or(Error::InvalidQwenShape)?;
|
||||
let held = cell.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
Ref::filter_map(held, Option::as_ref).map_err(|_| Error::InvalidQwenShape)
|
||||
}
|
||||
|
||||
pub(super) fn index_mut(&self, layer: usize) -> Result<RefMut<'_, OriginalQsaResidentIndex<'ctx>>> {
|
||||
let cell = self.indices.get(layer).ok_or(Error::InvalidQwenShape)?;
|
||||
let held = cell.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
|
||||
RefMut::filter_map(held, Option::as_mut).map_err(|_| Error::InvalidQwenShape)
|
||||
}
|
||||
|
||||
pub(super) fn kv(&self, layer: usize) -> Result<Ref<'_, OriginalQsaMappedJournal<'ctx>>> {
|
||||
let cell = self.mapped.get(layer).ok_or(Error::InvalidQwenShape)?;
|
||||
let held = cell.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
Ref::filter_map(held, Option::as_ref).map_err(|_| Error::InvalidQwenShape)
|
||||
}
|
||||
|
||||
pub(super) fn kv_mut(&self, layer: usize) -> Result<RefMut<'_, OriginalQsaMappedJournal<'ctx>>> {
|
||||
let cell = self.mapped.get(layer).ok_or(Error::InvalidQwenShape)?;
|
||||
let held = cell.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
|
||||
RefMut::filter_map(held, Option::as_mut).map_err(|_| Error::InvalidQwenShape)
|
||||
}
|
||||
|
||||
/// The addresses of the twelve layers' owners, as the graphs bound them.
|
||||
fn prints(&self) -> Result<[OwnerPrint; 12]> {
|
||||
let mut prints = Vec::new();
|
||||
prints.try_reserve_exact(12).map_err(|_| Error::HostAllocation)?;
|
||||
for layer in 0..12 {
|
||||
let (index, kv) = (self.index(layer)?, self.kv(layer)?);
|
||||
prints.push(print_of(&index, &kv)?);
|
||||
}
|
||||
prints.try_into().map_err(|_| Error::InvalidQwenShape)
|
||||
}
|
||||
|
||||
/// Whether the owners are out on loan.
|
||||
pub fn owners_lent(&self) -> bool {
|
||||
self.loan.try_borrow().map(|loan| loan.is_lent()).unwrap_or(true)
|
||||
}
|
||||
|
||||
/// Hand the twelve owners out (to the prompt executor) and keep the journal, and so the graphs that retain it.
|
||||
/// Needs the journal idle: no window armed, every index published and standing where its journal does. The
|
||||
/// fingerprint of the owners' addresses is kept for `take_back`. Any use of the journal fails until then.
|
||||
pub fn lend(&self) -> Result<OriginalQsaOwners<'ctx>> {
|
||||
self.require_idle()?;
|
||||
let prints = self.prints()?;
|
||||
let mut loan = self.loan.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
|
||||
loan.lend(prints).map_err(|_| Error::InvalidQwenShape)?;
|
||||
let (indices, mapped) = (self.take_all(&self.indices)?, self.take_all(&self.mapped)?);
|
||||
Ok((indices, mapped))
|
||||
}
|
||||
|
||||
/// Move the twelve values out of their cells: all twelve are borrowed and found full before the first moves.
|
||||
pub(super) fn take_all<T>(&self, cells: &[RefCell<Option<T>>; 12]) -> Result<[T; 12]> {
|
||||
let mut held = Vec::new();
|
||||
held.try_reserve_exact(12).map_err(|_| Error::HostAllocation)?;
|
||||
for cell in cells {
|
||||
held.push(cell.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?);
|
||||
}
|
||||
if held.iter().any(|value| value.is_none()) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let taken: Vec<T> = held.iter_mut().filter_map(|value| value.take()).collect();
|
||||
taken.try_into().map_err(|_| Error::InvalidQwenShape)
|
||||
}
|
||||
|
||||
/// Receive the owners back. They must be the lent ones: every address the graphs bound unchanged, all twelve idle
|
||||
/// and standing at one position. Otherwise the journal is failed for good (the graph set must be retired) and the
|
||||
/// owners come back to the caller with the error, so that none is lost.
|
||||
pub fn take_back(
|
||||
&self,
|
||||
owners: OriginalQsaOwners<'ctx>,
|
||||
) -> std::result::Result<(), (Error, OriginalQsaOwners<'ctx>)> {
|
||||
let now = self.print_owners(&owners);
|
||||
let end = owners.0[0].next_position();
|
||||
let aligned = check_aligned(self.context, &owners.0, &owners.1, end);
|
||||
let outcome = match (aligned, self.loan.try_borrow_mut()) {
|
||||
(Ok(()), Ok(mut loan)) => loan.take_back(now.ok()),
|
||||
(_, Ok(mut loan)) => {
|
||||
loan.fail();
|
||||
Err(LoanError::Changed)
|
||||
}
|
||||
(_, Err(_)) => Err(LoanError::Failed),
|
||||
};
|
||||
match outcome {
|
||||
Ok(()) => Ok(self.receive(owners, end)),
|
||||
Err(_) => {
|
||||
self.failed.set(true);
|
||||
Err((Error::InvalidQwenShape, owners))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn print_owners(&self, owners: &OriginalQsaOwners<'ctx>) -> Result<[OwnerPrint; 12]> {
|
||||
let mut prints = Vec::new();
|
||||
prints.try_reserve_exact(12).map_err(|_| Error::HostAllocation)?;
|
||||
for (index, kv) in owners.0.iter().zip(owners.1.iter()) {
|
||||
prints.push(print_of(index, kv)?);
|
||||
}
|
||||
prints.try_into().map_err(|_| Error::InvalidQwenShape)
|
||||
}
|
||||
|
||||
/// Put the accepted owners in their cells and stand the journal at their position, disarmed.
|
||||
fn receive(&self, owners: OriginalQsaOwners<'ctx>, end: usize) {
|
||||
let (indices, mapped) = owners;
|
||||
for (cell, index) in self.indices.iter().zip(indices) {
|
||||
*cell.borrow_mut() = Some(index);
|
||||
}
|
||||
for (cell, kv) in self.mapped.iter().zip(mapped) {
|
||||
*cell.borrow_mut() = Some(kv);
|
||||
}
|
||||
let mut live = self.live.borrow_mut();
|
||||
*live = Live { generation: live.generation, position: end, rows: 0, armed: false };
|
||||
}
|
||||
}
|
||||
+18
-20
@@ -22,8 +22,8 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
}
|
||||
/// Every index is still in flight and unpublished.
|
||||
fn check_all_in_flight(&self) -> Result<()> {
|
||||
for i in &self.indices {
|
||||
let i = i.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
for layer in 0..12 {
|
||||
let i = self.index(layer)?;
|
||||
if !i.in_flight || !i.unpublished {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
@@ -32,8 +32,8 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
}
|
||||
/// Advance every index to `end` and publish it.
|
||||
fn publish_window_indices(&self, position: usize, end: usize) {
|
||||
for i in &self.indices {
|
||||
let mut i = i.borrow_mut();
|
||||
for layer in 0..12 {
|
||||
let Ok(mut i) = self.index_mut(layer) else { continue };
|
||||
i.coverage.end.set(i.coverage.end.get().min(position));
|
||||
i.coverage = Rc::new(Coverage { end: Cell::new(end) });
|
||||
i.end = end;
|
||||
@@ -45,13 +45,13 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
/// visible; publish that K/V half on the host here, after the commit drain, and only then the index half. Do not
|
||||
/// publish an index-only verifier state: every journal must stand at `position` and every one is advanced together.
|
||||
fn publish_window_kv(&self, position: usize, keep: usize) -> Result<()> {
|
||||
for m in &self.mapped {
|
||||
if m.try_borrow().map_err(|_| Error::InvalidQwenShape)?.next_position() != position {
|
||||
for layer in 0..12 {
|
||||
if self.kv(layer)?.next_position() != position {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
}
|
||||
for m in &self.mapped {
|
||||
m.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?.publish_window_rows(position, keep)?;
|
||||
for layer in 0..12 {
|
||||
self.kv_mut(layer)?.publish_window_rows(position, keep)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -113,10 +113,8 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
/// Write the snapshots back: each index image, then the PLE history.
|
||||
fn restore_window_state(&self, snapshot: &[u8], ple: Option<(&DeviceBuffer<'ctx>, &[u8])>) -> Result<()> {
|
||||
let n = OriginalQsaResidentIndex::WINDOW_STATE_BYTES;
|
||||
for (layer, i) in self.indices.iter().enumerate() {
|
||||
i.try_borrow_mut()
|
||||
.map_err(|_| Error::InvalidQwenShape)?
|
||||
.write_window_state(&snapshot[layer * n..(layer + 1) * n])?;
|
||||
for layer in 0..12 {
|
||||
self.index_mut(layer)?.write_window_state(&snapshot[layer * n..(layer + 1) * n])?;
|
||||
}
|
||||
if let Some((ple, bytes)) = ple {
|
||||
ple.copy_from_range_shared(0, bytes)?;
|
||||
@@ -139,9 +137,8 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
self.check_in_flight_at(position)
|
||||
}
|
||||
fn check_in_flight_at(&self, position: usize) -> Result<()> {
|
||||
for (i, m) in self.indices.iter().zip(self.mapped.iter()) {
|
||||
let i = i.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let m = m.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
for layer in 0..12 {
|
||||
let (i, m) = (self.index(layer)?, self.kv(layer)?);
|
||||
if !i.in_flight || !i.unpublished || i.end != position || m.next_position() != position {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
@@ -151,8 +148,8 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
/// Publish every index at its restored position and disarm the journal.
|
||||
fn release_window(&self) -> Result<()> {
|
||||
let mut live = self.live.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
|
||||
for i in &self.indices {
|
||||
let mut i = i.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
|
||||
for layer in 0..12 {
|
||||
let mut i = self.index_mut(layer)?;
|
||||
i.in_flight = false;
|
||||
i.unpublished = false;
|
||||
}
|
||||
@@ -161,8 +158,8 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
}
|
||||
pub(crate) fn abandon_after_drain(&self) {
|
||||
self.failed.set(true);
|
||||
for i in &self.indices {
|
||||
if let Ok(mut i) = i.try_borrow_mut() {
|
||||
for layer in 0..12 {
|
||||
if let Ok(mut i) = self.index_mut(layer) {
|
||||
i.in_flight = false;
|
||||
i.unpublished = true;
|
||||
}
|
||||
@@ -178,7 +175,8 @@ impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
|
||||
if s.live.borrow().armed && !s.failed.get() {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok((s.indices.map(RefCell::into_inner), s.mapped.map(RefCell::into_inner)))
|
||||
let taken = (s.take_all(&s.indices)?, s.take_all(&s.mapped)?);
|
||||
Ok(taken)
|
||||
}
|
||||
Err(_) => Err(Error::InvalidQwenShape),
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ impl OriginalVerifyQsaJournal<'_> {
|
||||
if self.live.try_borrow().map_err(|_| Error::InvalidQwenShape)?.armed {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let end = self.indices[0].try_borrow().map_err(|_| Error::InvalidQwenShape)?.next_position();
|
||||
let end = self.index(0)?.next_position();
|
||||
self.check_idle_at(end)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
//! Batched host-to-device copies of the lent-slot refill (`LELEKA_REFILL_BATCH`, EXPERIMENTAL, off by default).
|
||||
//!
|
||||
//! The per-copy refill issues one `cuMemcpyHtoDAsync_v2` per piece (three or more per slot). This path hands the same
|
||||
//! pieces, in the same order, with the same sources, destinations and sizes, to `cuMemcpyBatchAsync_v2` in calls of
|
||||
//! at most `max_per_call` copies, so only the host's issue cost changes. A call the driver refuses is reported once
|
||||
//! and the refused call and every later one are issued per copy on the same stream (a copy the refused call may have
|
||||
//! queued is copied again with the same bytes, so the slot bytes stay identical).
|
||||
use crate::api::{AsyncApi, Stream};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Upper bound of copies in one batch call (the descriptor arrays are built on the host for each call).
|
||||
pub(crate) const MAX_COPIES_PER_CALL: usize = 4096;
|
||||
|
||||
/// One host-to-device piece: a device address and the host bytes copied there.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct HostCopy<'a> {
|
||||
pub(crate) destination: u64,
|
||||
pub(crate) source: &'a [u8],
|
||||
}
|
||||
|
||||
/// The descriptor arrays of one `cuMemcpyBatchAsync_v2` call; `range` is the slice of the copy list it covers.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) struct BatchCall {
|
||||
pub(crate) range: std::ops::Range<usize>,
|
||||
pub(crate) destinations: Vec<u64>,
|
||||
pub(crate) sources: Vec<u64>,
|
||||
pub(crate) sizes: Vec<usize>,
|
||||
}
|
||||
|
||||
/// What one batched issue did.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct RefillBatchReport {
|
||||
/// Slots whose copies were queued.
|
||||
pub slots: usize,
|
||||
/// Copies queued (batched or per copy).
|
||||
pub copies: usize,
|
||||
/// `cuMemcpyBatchAsync_v2` calls the driver accepted.
|
||||
pub batch_calls: usize,
|
||||
/// Copies issued one call each (no batch entry, a refused call, or a pageable bank).
|
||||
pub per_copy: usize,
|
||||
}
|
||||
|
||||
/// The batch calls of `copies` in order: consecutive runs of at most `max_per_call` non-empty copies. An empty copy
|
||||
/// moves no byte, so it is left out (`cuMemcpyBatchAsync_v2` refuses a zero size).
|
||||
pub(crate) fn plan_batch_calls(copies: &[HostCopy<'_>], max_per_call: usize) -> Result<Vec<BatchCall>> {
|
||||
if max_per_call == 0 || max_per_call > MAX_COPIES_PER_CALL {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
let mut calls = Vec::new();
|
||||
let mut start = 0;
|
||||
while start < copies.len() {
|
||||
let end = (start + max_per_call).min(copies.len());
|
||||
calls.push(batch_call(copies, start..end));
|
||||
start = end;
|
||||
}
|
||||
Ok(calls)
|
||||
}
|
||||
|
||||
fn batch_call(copies: &[HostCopy<'_>], range: std::ops::Range<usize>) -> BatchCall {
|
||||
let kept = || copies[range.clone()].iter().filter(|c| !c.source.is_empty());
|
||||
BatchCall {
|
||||
destinations: kept().map(|c| c.destination).collect(),
|
||||
sources: kept().map(|c| c.source.as_ptr() as u64).collect(),
|
||||
sizes: kept().map(|c| c.source.len()).collect(),
|
||||
range,
|
||||
}
|
||||
}
|
||||
|
||||
/// Issue `copies` on `stream`: batched when the driver has the entry, per copy otherwise or from the first refused
|
||||
/// call on. Returns the report and the refusal (the caller decides whether to stop batching); an error of a per-copy
|
||||
/// call is returned as the per-copy path returns it.
|
||||
pub(crate) fn issue_copies(
|
||||
api: &AsyncApi,
|
||||
copies: &[HostCopy<'_>],
|
||||
stream: Stream,
|
||||
max_per_call: usize,
|
||||
) -> Result<(RefillBatchReport, Option<Error>)> {
|
||||
let mut report = RefillBatchReport { copies: copies.len(), ..RefillBatchReport::default() };
|
||||
if !api.can_batch() {
|
||||
per_copy(api, copies, stream)?;
|
||||
report.per_copy = copies.len();
|
||||
return Ok((report, None));
|
||||
}
|
||||
for mut call in plan_batch_calls(copies, max_per_call)? {
|
||||
if let Err(refused) = api.copy_batch(&mut call, stream) {
|
||||
let rest = &copies[call.range.start..];
|
||||
per_copy(api, rest, stream)?;
|
||||
report.per_copy = rest.len();
|
||||
return Ok((report, Some(refused)));
|
||||
}
|
||||
report.batch_calls += 1;
|
||||
}
|
||||
Ok((report, None))
|
||||
}
|
||||
|
||||
/// One `cuMemcpyHtoDAsync_v2` per copy, in order (the per-copy refill).
|
||||
pub(crate) fn per_copy(api: &AsyncApi, copies: &[HostCopy<'_>], stream: Stream) -> Result<()> {
|
||||
copies.iter().try_for_each(|c| api.copy(c.destination, c.source, stream))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn copies<'a>(bytes: &'a [u8], lens: &[usize]) -> Vec<HostCopy<'a>> {
|
||||
let mut at = 0;
|
||||
lens.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &n)| {
|
||||
let c = HostCopy { destination: 0x1000_0000 + 0x1_0000 * i as u64, source: &bytes[at..at + n] };
|
||||
at += n;
|
||||
c
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copies_split_into_ordered_calls_of_at_most_the_cap() {
|
||||
let bytes = vec![7u8; 4096];
|
||||
let list = copies(&bytes, &[16; 7]);
|
||||
let calls = plan_batch_calls(&list, 3).unwrap();
|
||||
assert_eq!(calls.iter().map(|c| c.range.clone()).collect::<Vec<_>>(), vec![0..3, 3..6, 6..7]);
|
||||
let flat: Vec<u64> = calls.iter().flat_map(|c| c.destinations.clone()).collect();
|
||||
assert_eq!(flat, list.iter().map(|c| c.destination).collect::<Vec<_>>(), "same order, same destinations");
|
||||
let sources: Vec<u64> = calls.iter().flat_map(|c| c.sources.clone()).collect();
|
||||
assert_eq!(sources, list.iter().map(|c| c.source.as_ptr() as u64).collect::<Vec<_>>());
|
||||
assert!(calls.iter().all(|c| c.sizes.iter().all(|&n| n == 16)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_list_within_the_cap_is_one_call_and_an_empty_list_none() {
|
||||
let bytes = vec![1u8; 1 << 20];
|
||||
let list = copies(&bytes, &[1000, 300_000, 5, 64]);
|
||||
let calls = plan_batch_calls(&list, 512).unwrap();
|
||||
assert_eq!(calls.len(), 1);
|
||||
assert_eq!(calls[0].sizes, vec![1000, 300_000, 5, 64]);
|
||||
assert!(plan_batch_calls(&[], 512).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refill_of_2226_slots_takes_fourteen_calls_of_512() {
|
||||
let bytes = vec![0u8; 3 * 2226];
|
||||
let list = copies(&bytes, &vec![1; 3 * 2226]);
|
||||
let calls = plan_batch_calls(&list, 512).unwrap();
|
||||
assert_eq!(calls.len(), 14);
|
||||
assert_eq!(calls.iter().map(|c| c.sizes.len()).sum::<usize>(), 3 * 2226);
|
||||
assert_eq!(calls.last().unwrap().range.end, 3 * 2226);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_copies_are_left_out_but_keep_their_place_in_the_ranges() {
|
||||
let bytes = vec![3u8; 64];
|
||||
let list = copies(&bytes, &[8, 0, 8, 0]);
|
||||
let calls = plan_batch_calls(&list, 2).unwrap();
|
||||
assert_eq!(calls[0].range, 0..2);
|
||||
assert_eq!(calls[0].sizes, vec![8]);
|
||||
assert_eq!(calls[1].destinations, vec![list[2].destination]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cap_outside_one_to_the_maximum_is_refused() {
|
||||
let bytes = vec![0u8; 8];
|
||||
let list = copies(&bytes, &[8]);
|
||||
assert!(plan_batch_calls(&list, 0).is_err());
|
||||
assert!(plan_batch_calls(&list, MAX_COPIES_PER_CALL + 1).is_err());
|
||||
assert!(plan_batch_calls(&list, MAX_COPIES_PER_CALL).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! Model-free GPU check of the batched lent-slot refill (`LELEKA_REFILL_BATCH`): `N` slots are filled from one
|
||||
//! registered host buffer twice, once one `cuMemcpyHtoDAsync_v2` per piece (the per-copy refill) and once through
|
||||
//! `issue_copies` (`cuMemcpyBatchAsync_v2` in calls of 512), with three pieces per slot taken role-major from three
|
||||
//! regions of the buffer (gate, up, down) like `MappedExpertBank::copy_pieces` does. Every slot byte must be equal in
|
||||
//! both destinations and equal to the host bytes, and the bytes between the pieces must keep their fill pattern.
|
||||
//!
|
||||
//! Run (one process; a fault poisons the context):
|
||||
//! cargo test --release -p leleka-cuda-driver --features cuda-driver,sm120 --lib -- --ignored --nocapture \
|
||||
//! refill_batch_copy_gpu
|
||||
use crate::api::{AsyncApi, Stream};
|
||||
use crate::refill_batch_copy::{HostCopy, issue_copies, per_copy};
|
||||
use crate::{Context, DeviceBuffer, Driver};
|
||||
|
||||
const SLOTS: usize = 1024;
|
||||
const SLOT: usize = 64 << 10;
|
||||
const PIECE_MAX: usize = 20 << 10;
|
||||
const REGION: usize = SLOTS * PIECE_MAX;
|
||||
const UNTOUCHED: u8 = 0xA5;
|
||||
|
||||
/// The three role pieces of a slot: (source offset in the host buffer, destination offset in the slot, bytes).
|
||||
fn pieces(slot: usize) -> [(usize, usize, usize); 3] {
|
||||
let len = |role: usize| 16 * (1 + (slot * 7 + role * 13) % (PIECE_MAX / 16 - 1));
|
||||
let (g, u, d) = (len(0), len(1), len(2));
|
||||
[(slot * PIECE_MAX, 0, g), (REGION + slot * PIECE_MAX, g, u), (2 * REGION + slot * PIECE_MAX, g + u, d)]
|
||||
}
|
||||
|
||||
fn host_bytes() -> Vec<u8> {
|
||||
let mut x = 0x9E37_79B9_7F4A_7C15u64;
|
||||
(0..3 * REGION)
|
||||
.map(|_| {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 7;
|
||||
x ^= x << 17;
|
||||
(x >> 24) as u8
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn slot_copies<'a>(host: &'a [u8], destination: u64) -> Vec<HostCopy<'a>> {
|
||||
(0..SLOTS)
|
||||
.flat_map(|slot| pieces(slot).map(move |p| (slot, p)))
|
||||
.map(|(slot, (from, at, n))| HostCopy {
|
||||
destination: destination + (slot * SLOT + at) as u64,
|
||||
source: &host[from..from + n],
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn expected(host: &[u8]) -> Vec<u8> {
|
||||
let mut out = vec![UNTOUCHED; SLOTS * SLOT];
|
||||
for slot in 0..SLOTS {
|
||||
for (from, at, n) in pieces(slot) {
|
||||
out[slot * SLOT + at..slot * SLOT + at + n].copy_from_slice(&host[from..from + n]);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Fill `dest` from `host` on `stream`, batched or per copy, and read it back.
|
||||
fn fill(api: &AsyncApi, (host, dest): (&[u8], &mut DeviceBuffer<'_>), stream: Stream, batched: bool) -> Vec<u8> {
|
||||
dest.copy_from(&vec![UNTOUCHED; SLOTS * SLOT]).unwrap();
|
||||
let copies = slot_copies(host, dest.handle.expect("live buffer").qwen_address());
|
||||
eprintln!("fill batched={batched}: {} copies issued next", copies.len());
|
||||
if batched {
|
||||
let (report, refused) = issue_copies(api, &copies, stream, 512).unwrap();
|
||||
assert!(refused.is_none(), "the driver refused the batch: {refused:?}");
|
||||
assert_eq!((report.batch_calls, report.per_copy), ((3 * SLOTS).div_ceil(512), 0));
|
||||
} else {
|
||||
per_copy(api, &copies, stream).unwrap();
|
||||
}
|
||||
eprintln!("fill batched={batched}: issued, synchronising");
|
||||
api.synchronize_stream(stream).unwrap_or_else(|e| panic!("batched={batched}: synchronise failed: {e:?}"));
|
||||
dest.copy_to_owned(SLOTS * SLOT).unwrap()
|
||||
}
|
||||
|
||||
fn compare(ctx: &Context<'_>, api: &AsyncApi, host: &[u8]) {
|
||||
let (mut one, mut batch) = (ctx.allocate(SLOTS * SLOT).unwrap(), ctx.allocate(SLOTS * SLOT).unwrap());
|
||||
let guard = ctx.enter().unwrap();
|
||||
let stream = api.create_stream().unwrap();
|
||||
guard.finish().unwrap();
|
||||
let per_copy_bytes = fill(api, (host, &mut one), stream, false);
|
||||
let batched_bytes = fill(api, (host, &mut batch), stream, true);
|
||||
let want = expected(host);
|
||||
let first_difference = (0..want.len()).find(|&i| batched_bytes[i] != per_copy_bytes[i]);
|
||||
assert_eq!(
|
||||
first_difference,
|
||||
None,
|
||||
"batched and per-copy slots differ (slot {:?})",
|
||||
first_difference.map(|i| i / SLOT)
|
||||
);
|
||||
assert!(per_copy_bytes == want, "the per-copy slots are not the host bytes");
|
||||
let guard = ctx.enter().unwrap();
|
||||
api.destroy_stream(stream).unwrap();
|
||||
guard.finish().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs a CUDA GPU"]
|
||||
fn refill_batch_copy_gpu_slots_equal_per_copy() {
|
||||
let driver = Driver::load().unwrap();
|
||||
let ctx = driver.device(0).unwrap().create_context(256 << 20).unwrap();
|
||||
let mut host = host_bytes();
|
||||
let api = AsyncApi::load().unwrap();
|
||||
assert!(api.can_batch(), "the driver does not export cuMemcpyBatchAsync_v2");
|
||||
let guard = ctx.enter().unwrap();
|
||||
api.register(&mut host).unwrap();
|
||||
guard.finish().unwrap();
|
||||
compare(&ctx, &api, &host);
|
||||
let guard = ctx.enter().unwrap();
|
||||
api.unregister(&mut host).unwrap();
|
||||
guard.finish().unwrap();
|
||||
println!("refill batch copy: {SLOTS} slots x 3 pieces, batched == per copy == host bytes");
|
||||
drop(api);
|
||||
ctx.close().unwrap();
|
||||
}
|
||||
@@ -8,8 +8,8 @@ pub use device_slab::{DeviceSlice, SlabAllocator, SlabPolicy, SlabStats};
|
||||
pub use gdn_state_finite_guard::GdnStateFiniteGuard;
|
||||
pub use head_greedy::{HEAD_GREEDY_WORKSPACE_BYTES, HeadGreedySelection, HeadGreedyWorkspace};
|
||||
pub use mmq::resident::original_group::{
|
||||
OriginalMmqCopySchedule, OriginalMmqLayer, OriginalMmqOutput, OriginalStreamAllLayer, RingExperts,
|
||||
original_mmq_group_bank_bytes,
|
||||
OriginalMmqCopySchedule, OriginalMmqLayer, OriginalMmqOutput, OriginalStreamAllLayer, PrefetchSource,
|
||||
PrefetchTarget, RingExperts, original_mmq_group_bank_bytes,
|
||||
};
|
||||
pub use mmq::resident::{FiniteMmqOutput, MmqChunkActivation, MmqGroupActivation, MmqHidden, MmqWorkspace};
|
||||
pub use mmq::{MmqExperiment, MmqFormat, MmqProfile, MmqRequest, MmqWeights};
|
||||
@@ -19,7 +19,7 @@ pub use mtp_dense_kv::{
|
||||
CompletedMtpAttention, CompletedMtpKvReplay, MtpInt8OwnerId, MtpInt8Snapshot, MtpOriginalInt8, MtpOriginalMixed,
|
||||
MtpOriginalQuery,
|
||||
};
|
||||
pub use original_expert_cache::OriginalExpertCache;
|
||||
pub use original_expert_cache::{OriginalExpertCache, RefillBatchOptions};
|
||||
pub use original_gpu_schedule::{
|
||||
OriginalCapture, OriginalCapturePolicy, OriginalEventKind, OriginalGpuEvent, OriginalGpuGraph, OriginalGpuStream,
|
||||
OriginalGraphFlight, OriginalGraphKey, OriginalGraphRegistry, OriginalGraphResources, OriginalStreamKind,
|
||||
@@ -87,8 +87,8 @@ pub(crate) use qwen_dispatch::gdn_native_batch::GdnGeometry;
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))]
|
||||
pub use qwen_dispatch::gdn_native_batch::{
|
||||
GDN_BATCH_EPSILON, GDN_BATCH_MAX_TOKENS, GdnBatchCompletion, GdnBatchPrefix, GdnBatchStage, GdnGemm,
|
||||
GdnNativeFormat, GdnPrefillBatch, GdnStream, GemmShape, OriginalGdnPromptDevice, OriginalGdnPromptState,
|
||||
OriginalGdnPromptWeights,
|
||||
GdnNativeFormat, GdnPrefillBatch, GdnPromptOptions, GdnStream, GemmShape, OriginalGdnPromptDevice,
|
||||
OriginalGdnPromptState, OriginalGdnPromptWeights,
|
||||
};
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))]
|
||||
pub use qwen_dispatch::moe_prefill_batch::{
|
||||
@@ -314,4 +314,4 @@ pub use prompt_sync_trace_types::RoutedGateUpQ8;
|
||||
#[allow(unused_imports)]
|
||||
pub use q5_kshape_types::DeviceBuffer;
|
||||
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
|
||||
pub use qsa_prompt_index::{OriginalVerifyQsaJournal, OriginalVerifyRope};
|
||||
pub use qsa_prompt_index::{OriginalQsaOwners, OriginalVerifyQsaJournal, OriginalVerifyRope};
|
||||
|
||||
@@ -57,6 +57,8 @@ fn full_policy() -> OriginalMtpFullPolicy {
|
||||
gr: OriginalMtpGrVariant::Plain,
|
||||
kv: DraftKvPolicy::original_int8(1e7f32.powf(-2.0 / 64.0)),
|
||||
coupled_j: None,
|
||||
chain_pipeline: false,
|
||||
check_merge: false,
|
||||
}
|
||||
}
|
||||
impl<'ctx> Replay<'ctx> {
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
//! The batched numerical guard of the MTP draft step (`LELEKA_DRAFT_CHECK_MERGE`, off by default): the host half.
|
||||
//!
|
||||
//! A draft step launches a finite check (`mtp_original_finite`, floats) or a Q8_1 scale check (`mtp_original_q8_guard`,
|
||||
//! blocks) after almost every kernel, one launch per buffer. Where several of those launches are ADJACENT in the
|
||||
//! program (no other kernel or copy between them) the buffers cannot change between the first and the last of them, so
|
||||
//! the run can be checked by one launch of `mtp_original_check_batch` at the position of the run, each entry setting
|
||||
//! the status word its own launch set. Nothing is moved across another command: the checked (buffer, moment) pairs and
|
||||
//! the status words are the ones of the separate launches.
|
||||
//!
|
||||
//! This module holds the pure parts: the descriptor the kernel reads (`encode`, the layout of
|
||||
//! `mtp_original_check_batch.cu`), the grouping of adjacent checks (`merge_adjacent`), and, in the tests, a reference
|
||||
//! of the kernel and the proof that a merged schedule leaves the same status words as the separate one for a
|
||||
//! non-finite value placed anywhere.
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// By-value words of the kernel parameter (the shape of the GrMulti parameter).
|
||||
pub const BATCH_WORDS: usize = 114;
|
||||
/// Words of one entry: buffer address, count and kind, status address, reserved.
|
||||
pub const ENTRY_WORDS: usize = 4;
|
||||
/// Entries one launch holds: word 0 is the count.
|
||||
pub const MAX_ENTRIES: usize = (BATCH_WORDS - 1) / ENTRY_WORDS;
|
||||
/// Threads per block of every check launch, single or batched.
|
||||
pub const THREADS: u32 = 256;
|
||||
|
||||
/// What a check reads: f32 words, or the `half2` scale pair at the head of each 36-byte Q8_1 block.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CheckKind {
|
||||
Finite,
|
||||
Q8Scale,
|
||||
}
|
||||
|
||||
/// One check launch: `count` floats or blocks at `data`, a non-finite one sets bit 0 of the word at `flag`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Check {
|
||||
pub kind: CheckKind,
|
||||
pub data: u64,
|
||||
pub count: u32,
|
||||
pub flag: u64,
|
||||
}
|
||||
|
||||
impl Check {
|
||||
/// The grid of the separate launch of this check (block `THREADS`).
|
||||
pub fn single_grid(&self) -> u32 {
|
||||
self.count.div_ceil(THREADS)
|
||||
}
|
||||
}
|
||||
|
||||
/// The descriptor words and the grid of one batched launch.
|
||||
pub struct BatchLaunch {
|
||||
pub words: Box<[u64; BATCH_WORDS]>,
|
||||
pub grid: [u32; 3],
|
||||
}
|
||||
|
||||
/// The launch that checks `checks` (1 to `MAX_ENTRIES`): grid.y is the entry, grid.x covers the longest one.
|
||||
pub fn encode(checks: &[Check]) -> Result<BatchLaunch> {
|
||||
if checks.is_empty() || checks.len() > MAX_ENTRIES {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
let mut words = Box::new([0u64; BATCH_WORDS]);
|
||||
words[0] = checks.len() as u64;
|
||||
for (e, check) in checks.iter().enumerate() {
|
||||
if check.count == 0 || check.count > i32::MAX as u32 || check.flag % 4 != 0 || check.data == 0 {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
let kind = u64::from(check.kind == CheckKind::Q8Scale);
|
||||
words[1 + ENTRY_WORDS * e] = check.data;
|
||||
words[2 + ENTRY_WORDS * e] = u64::from(check.count) | kind << 32;
|
||||
words[3 + ENTRY_WORDS * e] = check.flag;
|
||||
}
|
||||
let x = checks.iter().map(Check::single_grid).max().unwrap_or(1);
|
||||
Ok(BatchLaunch { words, grid: [x, checks.len() as u32, 1] })
|
||||
}
|
||||
|
||||
/// Replaces every maximal run of adjacent checks (as `view` sees them) by batches of at most `MAX_ENTRIES`; a run or
|
||||
/// a chunk of one check, and every item before `keep`, stay as they are. Order and every other item are untouched.
|
||||
pub fn merge_adjacent<T>(
|
||||
items: Vec<T>,
|
||||
keep: usize,
|
||||
view: impl Fn(&T) -> Option<Check>,
|
||||
mut batch: impl FnMut(&[Check]) -> Result<T>,
|
||||
) -> Result<Vec<T>> {
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(items.len()).map_err(|_| Error::HostAllocation)?;
|
||||
let mut run: Vec<(T, Check)> = Vec::new();
|
||||
for (i, item) in items.into_iter().enumerate() {
|
||||
match view(&item).filter(|_| i >= keep) {
|
||||
Some(check) => run.push((item, check)),
|
||||
None => {
|
||||
flush_run(&mut run, &mut out, &mut batch)?;
|
||||
out.push(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
flush_run(&mut run, &mut out, &mut batch)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn flush_run<T>(
|
||||
run: &mut Vec<(T, Check)>,
|
||||
out: &mut Vec<T>,
|
||||
batch: &mut impl FnMut(&[Check]) -> Result<T>,
|
||||
) -> Result<()> {
|
||||
let mut rest = std::mem::take(run);
|
||||
while !rest.is_empty() {
|
||||
let tail = rest.split_off(rest.len().min(MAX_ENTRIES));
|
||||
if rest.len() == 1 {
|
||||
out.extend(rest.drain(..).map(|(item, _)| item));
|
||||
} else {
|
||||
let checks: Vec<Check> = rest.iter().map(|(_, check)| *check).collect();
|
||||
out.push(batch(&checks)?);
|
||||
}
|
||||
rest = tail;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod model;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,249 @@
|
||||
//! The model of the device and of the draft step the tests run: memory, the single and batched kernels, schedules, and
|
||||
//! the checks of one step in program order.
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
const BLOCK: u32 = THREADS;
|
||||
|
||||
// ------------------------------------------------------------------------------------- memory and kernels
|
||||
|
||||
/// Device memory of the model: f32 buffers, Q8_1 scale pairs, and the status words by address.
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct Memory {
|
||||
pub(super) floats: BTreeMap<u64, Vec<f32>>,
|
||||
pub(super) scales: BTreeMap<u64, Vec<[f32; 2]>>,
|
||||
pub(super) flags: BTreeMap<u64, u32>,
|
||||
}
|
||||
|
||||
impl Memory {
|
||||
/// `atomicOr(status, 1)` of the thread that found a non-finite value.
|
||||
fn raise(&mut self, flag: u64) {
|
||||
*self.flags.entry(flag).or_insert(0) |= 1;
|
||||
}
|
||||
fn bad(&self, kind: CheckKind, data: u64, i: usize) -> bool {
|
||||
match kind {
|
||||
CheckKind::Finite => !self.floats[&data][i].is_finite(),
|
||||
CheckKind::Q8Scale => self.scales[&data][i].iter().any(|v| !v.is_finite()),
|
||||
}
|
||||
}
|
||||
/// The grid-stride loop of one entry, for every (block, thread) of grid `x`; the body of both kernels.
|
||||
fn entry(&mut self, (kind, data, count, flag): (CheckKind, u64, u32, u64), x: u32) {
|
||||
for block in 0..x {
|
||||
for thread in 0..BLOCK {
|
||||
let mut i = block * BLOCK + thread;
|
||||
while i < count {
|
||||
if self.bad(kind, data, i as usize) {
|
||||
self.raise(flag);
|
||||
}
|
||||
i += x * BLOCK;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The separate launch: `mtp_original_finite` or `mtp_original_q8_guard`.
|
||||
pub(super) fn single(&mut self, c: &Check) {
|
||||
self.entry((c.kind, c.data, c.count, c.flag), c.single_grid());
|
||||
}
|
||||
/// `mtp_original_check_batch`, decoded from the descriptor words only, as the kernel does.
|
||||
pub(super) fn batch(&mut self, launch: &BatchLaunch) {
|
||||
let w = &launch.words;
|
||||
for e in 0..launch.grid[1] as usize {
|
||||
assert!(e < w[0] as usize, "a block row past the entry count returns");
|
||||
let meta = w[2 + ENTRY_WORDS * e];
|
||||
let kind = if meta >> 32 == 1 { CheckKind::Q8Scale } else { CheckKind::Finite };
|
||||
self.entry((kind, w[1 + ENTRY_WORDS * e], meta as u32, w[3 + ENTRY_WORDS * e]), launch.grid[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- schedules
|
||||
|
||||
/// A kernel that (re)writes buffers, a separate check, or a batch of checks.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(super) enum Op {
|
||||
Kernel(usize, Vec<u64>),
|
||||
Check(Check),
|
||||
Batch(Vec<Check>),
|
||||
}
|
||||
|
||||
pub(super) fn view(op: &Op) -> Option<Check> {
|
||||
match op {
|
||||
Op::Check(c) => Some(*c),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn merge(ops: Vec<Op>, keep: usize) -> Vec<Op> {
|
||||
merge_adjacent(ops, keep, view, |checks| Ok(Op::Batch(checks.to_vec()))).unwrap()
|
||||
}
|
||||
|
||||
/// The separate schedule a merged one stands for.
|
||||
pub(super) fn expand(ops: &[Op]) -> Vec<Op> {
|
||||
ops.iter()
|
||||
.flat_map(|op| match op {
|
||||
Op::Batch(checks) => checks.iter().copied().map(Op::Check).collect(),
|
||||
other => vec![other.clone()],
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A non-finite value placed in `buffer[element]` right after kernel `after` wrote it.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Fault {
|
||||
pub(super) after: usize,
|
||||
pub(super) buffer: u64,
|
||||
pub(super) element: usize,
|
||||
pub(super) value: f32,
|
||||
}
|
||||
|
||||
pub(super) fn write(memory: &mut Memory, buffer: u64, fault: Option<Fault>, kernel: usize) {
|
||||
if let Some(v) = memory.floats.get_mut(&buffer) {
|
||||
v.fill(1.0);
|
||||
}
|
||||
if let Some(v) = memory.scales.get_mut(&buffer) {
|
||||
v.fill([0.5, 2.0]);
|
||||
}
|
||||
let Some(f) = fault.filter(|f| f.after == kernel && f.buffer == buffer) else { return };
|
||||
if let Some(v) = memory.floats.get_mut(&buffer) {
|
||||
let len = v.len();
|
||||
v[f.element % len] = f.value;
|
||||
}
|
||||
if let Some(v) = memory.scales.get_mut(&buffer) {
|
||||
let len = v.len();
|
||||
v[f.element / 2 % len][f.element % 2] = f.value;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn run(ops: &[Op], blank: &Memory, fault: Option<Fault>) -> BTreeMap<u64, u32> {
|
||||
let mut memory = blank.clone();
|
||||
for op in ops {
|
||||
match op {
|
||||
Op::Kernel(id, buffers) => buffers.iter().for_each(|b| write(&mut memory, *b, fault, *id)),
|
||||
Op::Check(c) => memory.single(c),
|
||||
Op::Batch(checks) => memory.batch(&encode(checks).unwrap()),
|
||||
}
|
||||
}
|
||||
memory.flags
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------- the draft step
|
||||
|
||||
pub(super) const FLAGS: u64 = 0x9000_0000;
|
||||
pub(super) const SCRATCH: u64 = 0x1000_0000;
|
||||
|
||||
pub(super) fn flag(slot: u64) -> u64 {
|
||||
FLAGS + 4 * slot
|
||||
}
|
||||
pub(super) fn buf(i: u64) -> u64 {
|
||||
SCRATCH + 0x10_0000 * i
|
||||
}
|
||||
pub(super) fn finite(i: u64, count: u32, slot: u64) -> Op {
|
||||
Op::Check(Check { kind: CheckKind::Finite, data: buf(i), count, flag: flag(slot) })
|
||||
}
|
||||
pub(super) fn q8(i: u64, count: u32, slot: u64) -> Op {
|
||||
Op::Check(Check { kind: CheckKind::Q8Scale, data: buf(i), count, flag: flag(slot) })
|
||||
}
|
||||
pub(super) fn kernel(id: usize, writes: &[u64]) -> Op {
|
||||
Op::Kernel(id, writes.iter().map(|i| buf(*i)).collect())
|
||||
}
|
||||
|
||||
/// The checked buffers with their sizes: floats, or Q8_1 blocks for the ones in `Q8`.
|
||||
pub(super) const SIZES: [(u64, usize); 13] = [
|
||||
(0, 12288),
|
||||
(1, 6144),
|
||||
(2, 6144),
|
||||
(3, 6144),
|
||||
(4, 2560),
|
||||
(5, 10240),
|
||||
(6, 10240),
|
||||
(7, 320),
|
||||
(8, 4),
|
||||
(9, 2560),
|
||||
(10, 640),
|
||||
(11, 640),
|
||||
(12, 1),
|
||||
];
|
||||
pub(super) const Q8: [(u64, usize); 2] = [(20, 192), (21, 20)];
|
||||
|
||||
pub(super) fn blank() -> Memory {
|
||||
let mut m = Memory::default();
|
||||
for (i, n) in SIZES {
|
||||
m.floats.insert(buf(i), vec![1.0; n]);
|
||||
}
|
||||
for (i, n) in Q8 {
|
||||
m.scales.insert(buf(i), vec![[0.5, 2.0]; n]);
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// The checks of one draft step in the order of the program: the prefix (with its run of five guards after the GR
|
||||
/// block) and the tail (with its runs of five after the MLP GR and of two after the shared gate and up), the kernels
|
||||
/// between written as buffer writers. Buffers 1, 5, 6, 7 and 8 are written more than once, like `qcur`, `r`, `xn` and
|
||||
/// `lo`.
|
||||
pub(super) fn draft_step() -> Vec<Op> {
|
||||
[prefix_part(), tail_part()].concat()
|
||||
}
|
||||
|
||||
/// The scalar prefix: its guards, with the run of five after the GR block.
|
||||
pub(super) fn prefix_part() -> Vec<Op> {
|
||||
vec![
|
||||
kernel(0, &[9]),
|
||||
finite(9, 2560, 0),
|
||||
kernel(1, &[5]),
|
||||
finite(5, 10240, 1),
|
||||
kernel(2, &[20]),
|
||||
q8(20, 192, 2),
|
||||
kernel(3, &[6]),
|
||||
finite(6, 10240, 3),
|
||||
kernel(4, &[6, 7, 8, 9, 12]),
|
||||
finite(8, 4, 6),
|
||||
finite(6, 10240, 6),
|
||||
finite(7, 320, 7),
|
||||
finite(12, 1, 7),
|
||||
finite(9, 2560, 8),
|
||||
kernel(5, &[10]),
|
||||
finite(10, 640, 10),
|
||||
kernel(6, &[11]),
|
||||
finite(11, 640, 11),
|
||||
]
|
||||
}
|
||||
|
||||
/// The tail: attention and gate, the MLP GR with its run of five, the router and experts, the shared expert with its
|
||||
/// run of two, the combine.
|
||||
pub(super) fn tail_part() -> Vec<Op> {
|
||||
vec![
|
||||
kernel(7, &[0]),
|
||||
finite(0, 12288, 0),
|
||||
kernel(8, &[1]),
|
||||
finite(1, 6144, 1),
|
||||
kernel(9, &[1]),
|
||||
finite(1, 6144, 2),
|
||||
kernel(10, &[2, 3]),
|
||||
finite(2, 6144, 3),
|
||||
kernel(11, &[4]),
|
||||
finite(3, 6144, 4),
|
||||
kernel(17, &[21]),
|
||||
q8(21, 20, 5),
|
||||
kernel(12, &[4]),
|
||||
finite(4, 2560, 6),
|
||||
kernel(13, &[5, 6, 7, 8, 12]),
|
||||
finite(5, 10240, 7),
|
||||
finite(6, 10240, 8),
|
||||
finite(7, 320, 9),
|
||||
finite(8, 4, 10),
|
||||
finite(9, 2560, 11),
|
||||
kernel(14, &[10]),
|
||||
finite(10, 640, 12),
|
||||
kernel(15, &[11]),
|
||||
finite(11, 640, 13),
|
||||
finite(12, 1, 13),
|
||||
]
|
||||
}
|
||||
|
||||
pub(super) fn checks_in(ops: &[Op]) -> usize {
|
||||
ops.iter().map(|op| expand(std::slice::from_ref(op)).iter().filter(|o| view(o).is_some()).count()).sum()
|
||||
}
|
||||
|
||||
pub(super) fn launches_in(ops: &[Op]) -> usize {
|
||||
ops.len()
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
//! The batched guard leaves the status words of the separate launches, for a non-finite value anywhere.
|
||||
use super::model::*;
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ tests
|
||||
|
||||
#[test]
|
||||
fn the_step_loses_exactly_the_adjacent_check_launches() {
|
||||
let step = draft_step();
|
||||
let merged = merge(step.clone(), 0);
|
||||
assert_eq!(checks_in(&merged), checks_in(&step));
|
||||
// runs of five (prefix guards), five (MLP GR outputs) and two (shared gate and up): 12 launches become 3
|
||||
assert_eq!(launches_in(&step) - launches_in(&merged), 9);
|
||||
assert_eq!(merged.iter().filter(|op| matches!(op, Op::Batch(_))).count(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_merged_schedule_expands_to_the_separate_one() {
|
||||
let step = draft_step();
|
||||
assert_eq!(expand(&merge(step.clone(), 0)), step);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_finite_value_anywhere_leaves_the_same_status_words() {
|
||||
let step = draft_step();
|
||||
let merged = merge(step.clone(), 0);
|
||||
let memory = blank();
|
||||
assert_eq!(run(&step, &memory, None), run(&merged, &memory, None));
|
||||
let (mut caught, mut missed) = (0, 0);
|
||||
for fault in faults(&step, &memory) {
|
||||
let separate = run(&step, &memory, Some(fault));
|
||||
let together = run(&merged, &memory, Some(fault));
|
||||
assert_eq!(separate, together, "fault {:?} after kernel {}", fault.value, fault.after);
|
||||
if separate.is_empty() { missed += 1 } else { caught += 1 }
|
||||
}
|
||||
// the model is not vacuous: most faults are caught, and the ones that are not (a buffer overwritten before its
|
||||
// check) are missed by both
|
||||
assert!(caught > 400 && missed > 0, "caught {caught}, missed {missed}");
|
||||
}
|
||||
|
||||
/// Every kernel output, at the first, the last, the block edges and a middle element, with NaN, +Inf and -Inf.
|
||||
fn faults(ops: &[Op], memory: &Memory) -> Vec<Fault> {
|
||||
let mut all = Vec::new();
|
||||
for op in ops {
|
||||
let Op::Kernel(after, buffers) = op else { continue };
|
||||
for &buffer in buffers {
|
||||
let len = memory.floats.get(&buffer).map_or_else(|| memory.scales[&buffer].len() * 2, Vec::len);
|
||||
let spots = [0, 1, 255, 256, 257, len / 2, len - 1].map(|e| e.min(len - 1));
|
||||
for element in spots {
|
||||
for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
all.push(Fault { after: *after, buffer, element, value });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_status_word_stays_the_one_of_its_own_check() {
|
||||
let step = draft_step();
|
||||
let merged = merge(step.clone(), 0);
|
||||
let memory = blank();
|
||||
// a fault in a buffer raises the words of exactly the checks of that buffer after its last write, in both
|
||||
let fault = Fault { after: 13, buffer: buf(6), element: 9000, value: f32::NAN };
|
||||
let words = run(&merged, &memory, Some(fault));
|
||||
assert_eq!(words.keys().copied().collect::<Vec<_>>(), vec![flag(8)]);
|
||||
assert_eq!(words, run(&step, &memory, Some(fault)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_longer_than_a_launch_are_chunked_and_still_expand_to_the_original() {
|
||||
for n in [1usize, 2, 27, 28, 29, 56, 57, 70] {
|
||||
let ops: Vec<Op> = (0..n).map(|i| finite(i as u64 % 13, 4, i as u64)).collect();
|
||||
let merged = merge(ops.clone(), 0);
|
||||
assert_eq!(expand(&merged), ops, "run of {n}");
|
||||
let expected = n / MAX_ENTRIES + usize::from(n % MAX_ENTRIES != 0);
|
||||
assert_eq!(merged.len(), expected, "launches of a run of {n}");
|
||||
assert!(merged.iter().all(|op| !matches!(op, Op::Batch(c) if c.len() < 2 || c.len() > MAX_ENTRIES)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_adjacent_checks_are_merged_and_everything_else_is_untouched() {
|
||||
let mut seed = 0x2545_f491_4f6c_dd1du64;
|
||||
let mut next = move || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
seed
|
||||
};
|
||||
for _ in 0..200 {
|
||||
let ops: Vec<Op> = (0..60)
|
||||
.map(|i| if next() % 3 == 0 { kernel(i, &[next() % 13]) } else { finite(next() % 13, 8, i as u64) })
|
||||
.collect();
|
||||
let keep = (next() % 10) as usize;
|
||||
let merged = merge(ops.clone(), keep);
|
||||
assert_eq!(expand(&merged), ops);
|
||||
assert_eq!(&merged[..keep.min(merged.len())], &ops[..keep.min(merged.len())].to_vec()[..], "items before keep");
|
||||
// between two batches or checks of the result there is a kernel: no two adjacent check launches remain unless
|
||||
// they are on both sides of the protected prefix
|
||||
for pair in merged.windows(2).skip(keep) {
|
||||
let is_check = |op: &Op| matches!(op, Op::Check(_) | Op::Batch(_));
|
||||
assert!(!(is_check(&pair[0]) && is_check(&pair[1])));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_protected_prefix_is_never_merged() {
|
||||
let ops = vec![finite(0, 4, 0), finite(1, 4, 1), finite(2, 4, 2), finite(3, 4, 3)];
|
||||
let merged = merge(ops.clone(), 2);
|
||||
assert_eq!(merged.len(), 3);
|
||||
assert_eq!(&merged[..2], &ops[..2]);
|
||||
assert!(matches!(&merged[2], Op::Batch(c) if c.len() == 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_descriptor_is_the_layout_the_kernel_reads() {
|
||||
let checks = [
|
||||
Check { kind: CheckKind::Finite, data: 0x1000, count: 10240, flag: 0x2004 },
|
||||
Check { kind: CheckKind::Q8Scale, data: 0x3000, count: 80, flag: 0x2008 },
|
||||
];
|
||||
let launch = encode(&checks).unwrap();
|
||||
assert_eq!(launch.grid, [40, 2, 1]);
|
||||
assert_eq!(launch.words[..9], [2, 0x1000, 10240, 0x2004, 0, 0x3000, 80 | 1 << 32, 0x2008, 0]);
|
||||
assert!(launch.words[9..].iter().all(|w| *w == 0));
|
||||
let source = driver_source!("src/mtp_original_check_batch.cu");
|
||||
for needle in [
|
||||
"unsigned long long w[114]",
|
||||
"sizeof(CheckBatch) == 912",
|
||||
"b.w[1 + 4 * entry]",
|
||||
"b.w[2 + 4 * entry]",
|
||||
"b.w[3 + 4 * entry]",
|
||||
"meta & 0xffffffffull",
|
||||
"meta >> 32",
|
||||
"blockIdx.y",
|
||||
"!isfinite(reinterpret_cast<const float*>(data)[i])",
|
||||
"!isfinite(ds.x) || !isfinite(ds.y)",
|
||||
"atomicOr(status, 1)",
|
||||
] {
|
||||
assert!(source.contains(needle), "kernel source lost `{needle}`");
|
||||
}
|
||||
assert_eq!(MAX_ENTRIES, 28);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_descriptor_that_the_kernel_could_misread_is_refused() {
|
||||
let ok = Check { kind: CheckKind::Finite, data: 0x1000, count: 4, flag: 0x2000 };
|
||||
assert!(encode(&[ok]).is_ok());
|
||||
assert!(encode(&[]).is_err());
|
||||
assert!(encode(&vec![ok; MAX_ENTRIES + 1]).is_err());
|
||||
assert!(encode(&[Check { count: 0, ..ok }]).is_err());
|
||||
assert!(encode(&[Check { count: i32::MAX as u32 + 1, ..ok }]).is_err());
|
||||
assert!(encode(&[Check { flag: 0x2001, ..ok }]).is_err());
|
||||
assert!(encode(&[Check { data: 0, ..ok }]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_single_launch_grid_is_the_one_the_old_programs_used() {
|
||||
let c = |count| Check { kind: CheckKind::Finite, data: 8, count, flag: 4 };
|
||||
assert_eq!([c(1).single_grid(), c(256).single_grid(), c(257).single_grid(), c(12288).single_grid()], [1, 1, 2, 48]);
|
||||
}
|
||||
@@ -18,6 +18,7 @@ macro_rules! driver_source {
|
||||
mod bringup_trace;
|
||||
pub mod command_profile;
|
||||
pub mod device_arena;
|
||||
pub mod draft_check_batch;
|
||||
mod error;
|
||||
mod error_display;
|
||||
pub mod host_profile;
|
||||
@@ -28,6 +29,7 @@ pub mod original_mtp_loader;
|
||||
pub mod original_prefill_schedule;
|
||||
mod projection;
|
||||
pub mod qsa_prompt_attention_select;
|
||||
pub mod ring_prefetch;
|
||||
pub mod s_gemv_legacy;
|
||||
pub mod serving_context;
|
||||
mod shapes;
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
//! Pure host-side half of the EXPERIMENTAL prompt copy-ring prefetch (`LELEKA_PREFILL_RING_PREFETCH`, off by
|
||||
//! default; docs/experiments/ring-prefetch.md).
|
||||
//!
|
||||
//! The per-layer copy ring of a prompt chunk below the expert stream's row minimum copies every routed expert the
|
||||
//! arena cache does not hold, but only after the layer's router ran. The PCIe link is idle during the layer's mixer
|
||||
//! (GDN / QSA). The prefetch copies, while the previous layer's tail and this layer's mixer run, the experts this layer
|
||||
//! MISSED most often in its recent chunks into the ring's own stage slots. When the router result arrives a
|
||||
//! prefetched expert that is routed and still not resident is consumed from its slot (no second copy); every other
|
||||
//! prefetched slot is dropped. The same experts reach the same kernels in the same group order: only the time and the
|
||||
//! order of the copies change.
|
||||
//!
|
||||
//! This module holds what needs no GPU: the policy and its slot budget, the per-layer miss history and its ranking,
|
||||
//! the matching of the prefetched set against the routed one, and the stage-slot search that skips reserved slots.
|
||||
use std::collections::VecDeque;
|
||||
|
||||
/// Experts per layer.
|
||||
pub const EXPERTS: usize = 512;
|
||||
/// Layers of the model.
|
||||
pub const LAYERS: usize = 48;
|
||||
/// A 512-bit set of experts of one layer.
|
||||
pub type ExpertMask = [u64; EXPERTS / 64];
|
||||
/// A ring smaller than this (the literal 8-slot ring of the 512-row rung) is never prefetched into.
|
||||
pub const MIN_RING_SLOTS: usize = 32;
|
||||
|
||||
/// The prefetch switch: how many experts per layer at most, and over how many recent chunks the misses are counted.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct RingPrefetchPolicy {
|
||||
/// at most this many experts per layer (also bounded by half of the ring, see [`RingPrefetchPolicy::budget`])
|
||||
pub top_k: usize,
|
||||
/// the misses of the last `window` chunks of a layer are counted
|
||||
pub window: usize,
|
||||
/// EXPERIMENTAL on top of the prefetch: while the copies are pending, the copy stream is the `compute_drain`
|
||||
/// background stream (the mixer's drains stop waiting for it; all-zero uploads become memsets; frees are deferred),
|
||||
/// as under the chunk expert stream. Off: the drains stay context-wide and wait for the prefetch copies.
|
||||
pub detach_drains: bool,
|
||||
}
|
||||
|
||||
impl RingPrefetchPolicy {
|
||||
/// The offline study's operating point (57 % precision, 43 % of the need at K = 150 over N = 3..16 chunks).
|
||||
pub const DEFAULT_TOP_K: usize = 150;
|
||||
pub const DEFAULT_WINDOW: usize = 8;
|
||||
pub const MAX_WINDOW: usize = 64;
|
||||
|
||||
/// `top_k` and `window` clamped to what the ring and the history can hold; the drains stay context-wide.
|
||||
pub fn new(top_k: usize, window: usize) -> Self {
|
||||
Self { top_k: top_k.min(EXPERTS), window: window.clamp(1, Self::MAX_WINDOW), detach_drains: false }
|
||||
}
|
||||
|
||||
/// The same policy with [`RingPrefetchPolicy::detach_drains`] set to `on`.
|
||||
pub fn with_detached_drains(self, on: bool) -> Self {
|
||||
Self { detach_drains: on, ..self }
|
||||
}
|
||||
|
||||
/// The experts one layer may prefetch into a ring of `ring_slots` slots: none below [`MIN_RING_SLOTS`], else at
|
||||
/// most half the ring, so the ring's own lookahead always keeps free slots for the mandatory copies.
|
||||
pub fn budget(&self, ring_slots: usize) -> usize {
|
||||
if ring_slots < MIN_RING_SLOTS {
|
||||
return 0;
|
||||
}
|
||||
self.top_k.min(ring_slots / 2)
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets bit `expert` of `mask` (out-of-range experts are ignored).
|
||||
pub fn mask_set(mask: &mut ExpertMask, expert: usize) {
|
||||
if expert < EXPERTS {
|
||||
mask[expert / 64] |= 1 << (expert % 64);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether bit `expert` of `mask` is set.
|
||||
pub fn mask_has(mask: &ExpertMask, expert: usize) -> bool {
|
||||
expert < EXPERTS && mask[expert / 64] >> (expert % 64) & 1 == 1
|
||||
}
|
||||
|
||||
/// The missed (routed and not resident) experts of the last `window` chunks, per layer, newest last.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MissHistory {
|
||||
window: usize,
|
||||
layers: Vec<VecDeque<ExpertMask>>,
|
||||
}
|
||||
|
||||
impl MissHistory {
|
||||
pub fn new(window: usize) -> Self {
|
||||
let window = window.max(1);
|
||||
Self { window, layers: (0..LAYERS).map(|_| VecDeque::with_capacity(window)).collect() }
|
||||
}
|
||||
|
||||
/// Appends one chunk's missed set of `layer`, forgetting the oldest beyond the window.
|
||||
pub fn record(&mut self, layer: usize, missed: ExpertMask) {
|
||||
let Some(chunks) = self.layers.get_mut(layer) else { return };
|
||||
if chunks.len() == self.window {
|
||||
chunks.pop_front();
|
||||
}
|
||||
chunks.push_back(missed);
|
||||
}
|
||||
|
||||
/// Chunks recorded for `layer` (at most the window).
|
||||
pub fn depth(&self, layer: usize) -> usize {
|
||||
self.layers.get(layer).map_or(0, VecDeque::len)
|
||||
}
|
||||
|
||||
/// At most `k` experts of `layer` ranked by how many of the recorded chunks missed them, then by the most recent
|
||||
/// chunk that missed them, then by id; experts for which `skip` holds (resident now) are left out.
|
||||
pub fn predict(&self, layer: usize, k: usize, skip: impl Fn(u32) -> bool) -> Vec<u32> {
|
||||
let Some(chunks) = self.layers.get(layer) else { return Vec::new() };
|
||||
let mut ranked: Vec<(u32, usize, usize)> = Vec::new();
|
||||
for expert in 0..EXPERTS {
|
||||
let (count, last) = Self::count_and_last(chunks, expert);
|
||||
if count > 0 && !skip(expert as u32) {
|
||||
ranked.push((expert as u32, count, last));
|
||||
}
|
||||
}
|
||||
ranked.sort_by(|a, b| b.1.cmp(&a.1).then(b.2.cmp(&a.2)).then(a.0.cmp(&b.0)));
|
||||
ranked.into_iter().take(k).map(|(expert, _, _)| expert).collect()
|
||||
}
|
||||
|
||||
/// `(chunks that missed expert, 1 + index of the newest one)`; `(0, 0)` when none did.
|
||||
fn count_and_last(chunks: &VecDeque<ExpertMask>, expert: usize) -> (usize, usize) {
|
||||
let mut count = 0;
|
||||
let mut last = 0;
|
||||
for (index, mask) in chunks.iter().enumerate() {
|
||||
if mask_has(mask, expert) {
|
||||
count += 1;
|
||||
last = index + 1;
|
||||
}
|
||||
}
|
||||
(count, last)
|
||||
}
|
||||
}
|
||||
|
||||
/// How the routed sources of a layer met the prefetched set.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct PrefetchMatch {
|
||||
/// `(source index, prefetch entry index)`: the source is consumed from the entry's slot
|
||||
pub hits: Vec<(usize, usize)>,
|
||||
/// prefetch entries no source consumed: their slots are returned unused
|
||||
pub wasted: Vec<usize>,
|
||||
}
|
||||
|
||||
/// Matches the prefetched experts (`prefetched[i]` is entry `i`) against the sources that need a copy:
|
||||
/// `needs_copy[s]` is `Some(expert)` for a routed source that is not resident (and not staged otherwise), `None`
|
||||
/// otherwise. Every entry is consumed at most once and by at most one source; an entry whose expert is not among the
|
||||
/// needing sources is wasted.
|
||||
pub fn match_prefetch(prefetched: &[u32], needs_copy: &[Option<u32>]) -> PrefetchMatch {
|
||||
let mut used = vec![false; prefetched.len()];
|
||||
let mut out = PrefetchMatch::default();
|
||||
for (source, expert) in needs_copy.iter().enumerate() {
|
||||
let Some(expert) = expert else { continue };
|
||||
let found = prefetched.iter().enumerate().position(|(i, e)| e == expert && !used[i]);
|
||||
if let Some(entry) = found {
|
||||
used[entry] = true;
|
||||
out.hits.push((source, entry));
|
||||
}
|
||||
}
|
||||
out.wasted = (0..prefetched.len()).filter(|i| !used[*i]).collect();
|
||||
out
|
||||
}
|
||||
|
||||
/// The first slot from `start` (wrapping over `slots`) that `reserved` does not hold, or `None` when every slot is
|
||||
/// reserved. With no reservation this is `start` itself, the literal ring order.
|
||||
pub fn next_unreserved_slot(start: usize, slots: usize, reserved: impl Fn(usize) -> bool) -> Option<usize> {
|
||||
(0..slots).map(|step| (start + step) % slots).find(|slot| !reserved(*slot))
|
||||
}
|
||||
|
||||
/// The copy-ring check that refused: the driver error stays `InvalidProjectionShape`, the trace names the check.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RingRefusal {
|
||||
/// `stage_one` of a source that already holds a slot and was not prefetched
|
||||
SourceAlreadyStaged,
|
||||
/// `stage_one` found every slot reserved by prefetched sources
|
||||
AllSlotsReserved,
|
||||
/// `stage_one`'s slot still holds a copy no gather read yet
|
||||
SlotNotGathered,
|
||||
/// `gather` of a source that needs a slot and has none
|
||||
GatherNoSlot,
|
||||
/// `gather` of a slot no copy filled
|
||||
GatherSlotNotLive,
|
||||
/// `gather` of a slot an earlier gather already read
|
||||
GatherSlotGathered,
|
||||
}
|
||||
|
||||
impl RingRefusal {
|
||||
/// The check's name in the `RING-REFUSE` trace line.
|
||||
pub fn check(self) -> &'static str {
|
||||
match self {
|
||||
Self::SourceAlreadyStaged => "stage.source_already_staged",
|
||||
Self::AllSlotsReserved => "stage.all_slots_reserved",
|
||||
Self::SlotNotGathered => "stage.slot_not_gathered",
|
||||
Self::GatherNoSlot => "gather.no_slot",
|
||||
Self::GatherSlotNotLive => "gather.slot_not_live",
|
||||
Self::GatherSlotGathered => "gather.slot_already_gathered",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One stage slot of the copy ring: a copy filled it (`live`), a gather read it (`gathered`), a prefetched source
|
||||
/// holds it until its gather (`reserved`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct SlotState {
|
||||
pub live: bool,
|
||||
pub gathered: bool,
|
||||
pub reserved: bool,
|
||||
}
|
||||
|
||||
impl SlotState {
|
||||
/// A slot a prefetch copy filled for a routed source.
|
||||
pub const PREFETCHED: Self = Self { live: true, gathered: false, reserved: true };
|
||||
|
||||
/// After a stage copy into it.
|
||||
pub fn staged(&mut self) {
|
||||
*self = Self { live: true, gathered: false, reserved: false };
|
||||
}
|
||||
|
||||
/// A gather may read it: a copy filled it and no gather read it yet.
|
||||
pub fn check_gather(self) -> Result<(), RingRefusal> {
|
||||
match (self.live, self.gathered) {
|
||||
(false, _) => Err(RingRefusal::GatherSlotNotLive),
|
||||
(true, true) => Err(RingRefusal::GatherSlotGathered),
|
||||
(true, false) => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// After its gather: the slot is free for the next copy; returns whether it was reserved.
|
||||
pub fn gathered(&mut self) -> bool {
|
||||
self.gathered = true;
|
||||
std::mem::take(&mut self.reserved)
|
||||
}
|
||||
}
|
||||
|
||||
/// What `stage_one` does with a source: `Ok(true)` copy it, `Ok(false)` nothing (resident, a chunk-stream entry or
|
||||
/// prefetched); a source that already holds a slot without being prefetched is refused.
|
||||
pub fn stage_needed(no_copy: bool, prefetched: bool, has_slot: bool) -> Result<bool, RingRefusal> {
|
||||
if no_copy || prefetched {
|
||||
return Ok(false);
|
||||
}
|
||||
if has_slot { Err(RingRefusal::SourceAlreadyStaged) } else { Ok(true) }
|
||||
}
|
||||
|
||||
/// The slot `stage_one` copies into: the first one from `start` (in ring order, wrapping) that no prefetched source
|
||||
/// holds and that is free (never filled, or its copy already gathered). Refused when every slot is reserved, or when
|
||||
/// every unreserved slot still holds a copy no gather read; the stage-ahead walk then waits for a gather
|
||||
/// (`Ring::stage_room`).
|
||||
///
|
||||
/// The literal ring always finds `start` itself: its copies and gathers run in the same order and its lookahead is one
|
||||
/// slot short of the ring, so the next slot in order holds the oldest copy, already gathered. With prefetched sources
|
||||
/// the copies skip the hits, the slot order is no longer the gather order, and the next slot in order can hold a copy
|
||||
/// of an earlier source of the same layer that is not gathered yet (PET.1: layers 46/47, 410-460 sources on 384 slots,
|
||||
/// `stage.slot_not_gathered` with no slot reserved); the search skips it.
|
||||
pub fn stage_target(slots: usize, start: usize, state: impl Fn(usize) -> SlotState) -> Result<usize, RingRefusal> {
|
||||
next_unreserved_slot(start, slots, |s| state(s).reserved).ok_or(RingRefusal::AllSlotsReserved)?;
|
||||
let free = |s: usize| {
|
||||
let target = state(s);
|
||||
!target.reserved && (!target.live || target.gathered)
|
||||
};
|
||||
(0..slots).map(|step| (start + step) % slots).find(|s| free(*s)).ok_or(RingRefusal::SlotNotGathered)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "ring_prefetch/tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,327 @@
|
||||
//! The ring prefetch's pure halves: the budget, the miss ranking, the consume-once matching and the slot search, plus
|
||||
//! a host model of the copy ring's stage-ahead walk with reserved (prefetched) slots.
|
||||
use super::*;
|
||||
|
||||
fn mask(experts: &[usize]) -> ExpertMask {
|
||||
let mut m = [0u64; EXPERTS / 64];
|
||||
for &e in experts {
|
||||
mask_set(&mut m, e);
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_budget_is_bounded_by_half_the_ring_and_zero_on_the_small_ring() {
|
||||
let policy = RingPrefetchPolicy::new(150, 8);
|
||||
assert_eq!(policy.budget(8), 0, "the literal 8-slot ring of the 512-row rung is never prefetched into");
|
||||
assert_eq!(policy.budget(31), 0);
|
||||
assert_eq!(policy.budget(32), 16);
|
||||
assert_eq!(policy.budget(96), 48);
|
||||
assert_eq!(policy.budget(384), 150);
|
||||
assert_eq!(RingPrefetchPolicy::new(10_000, 0), RingPrefetchPolicy { top_k: 512, window: 1, detach_drains: false });
|
||||
assert_eq!(RingPrefetchPolicy::new(1, 1_000).window, RingPrefetchPolicy::MAX_WINDOW);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn masks_hold_exactly_the_experts_set() {
|
||||
let m = mask(&[0, 63, 64, 511, 512]);
|
||||
assert!(mask_has(&m, 0) && mask_has(&m, 63) && mask_has(&m, 64) && mask_has(&m, 511));
|
||||
assert!(!mask_has(&m, 1) && !mask_has(&m, 512), "out of range is never set");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ranking_is_frequency_then_recency_then_id() {
|
||||
let mut history = MissHistory::new(4);
|
||||
history.record(3, mask(&[10, 20, 30]));
|
||||
history.record(3, mask(&[10, 40]));
|
||||
history.record(3, mask(&[10, 20, 50]));
|
||||
// 10: 3 chunks; 20: 2 (newest 3); 50: 1 (newest 3); 40: 1 (newest 2); 30: 1 (newest 1)
|
||||
assert_eq!(history.predict(3, 10, |_| false), [10, 20, 50, 40, 30]);
|
||||
assert_eq!(history.predict(3, 2, |_| false), [10, 20], "bounded by k");
|
||||
assert!(history.predict(4, 10, |_| false).is_empty(), "history is per layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resident_experts_are_skipped_and_ties_break_by_id() {
|
||||
let mut history = MissHistory::new(2);
|
||||
history.record(0, mask(&[7, 5, 9]));
|
||||
assert_eq!(history.predict(0, 10, |_| false), [5, 7, 9]);
|
||||
assert_eq!(history.predict(0, 10, |e| e == 7), [5, 9], "an expert resident now is not prefetched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_forgets_the_oldest_chunk() {
|
||||
let mut history = MissHistory::new(2);
|
||||
history.record(1, mask(&[1]));
|
||||
history.record(1, mask(&[2]));
|
||||
history.record(1, mask(&[3]));
|
||||
assert_eq!(history.depth(1), 2);
|
||||
assert_eq!(history.predict(1, 10, |_| false), [3, 2], "expert 1 left the window");
|
||||
history.record(LAYERS, mask(&[1]));
|
||||
assert!(history.predict(LAYERS, 10, |_| false).is_empty(), "an out-of-range layer is ignored");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_prefetched_entry_is_consumed_at_most_once_and_misses_are_dropped() {
|
||||
let prefetched = [40, 10, 20, 99];
|
||||
// sources: 10 (copy), 15 (copy), 20 (resident -> None), 40 (copy), 40 again (impossible routing, consumed once)
|
||||
let needs = [Some(10), Some(15), None, Some(40), Some(40)];
|
||||
let m = match_prefetch(&prefetched, &needs);
|
||||
assert_eq!(m.hits, [(0, 1), (3, 0)]);
|
||||
assert_eq!(m.wasted, [2, 3], "20 became resident, 99 was not routed");
|
||||
let consumed: Vec<usize> = m.hits.iter().map(|h| h.1).chain(m.wasted.iter().copied()).collect();
|
||||
let mut sorted = consumed.clone();
|
||||
sorted.sort_unstable();
|
||||
assert_eq!(sorted, [0, 1, 2, 3], "every entry is either consumed or dropped, exactly once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_slot_search_is_the_literal_order_without_reservations() {
|
||||
assert_eq!(next_unreserved_slot(5, 8, |_| false), Some(5));
|
||||
assert_eq!(next_unreserved_slot(7, 8, |s| s == 7 || s == 0), Some(1), "wraps past reserved slots");
|
||||
assert_eq!(next_unreserved_slot(0, 4, |_| true), None);
|
||||
}
|
||||
|
||||
/// One source of the ring model: resident, a prefetch hit holding a reserved slot, or a mandatory copy.
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
enum Kind {
|
||||
Resident,
|
||||
Hit(usize),
|
||||
Copy,
|
||||
}
|
||||
|
||||
/// The copy ring's slot bookkeeping driven by the same functions the driver's `Ring` calls (`stage_needed`,
|
||||
/// `stage_target`, `SlotState`): the slots, the slot each source reads and the next slot of the rotation.
|
||||
struct RingModel {
|
||||
ring: Vec<SlotState>,
|
||||
kinds: Vec<Kind>,
|
||||
at: Vec<Option<usize>>,
|
||||
next: usize,
|
||||
}
|
||||
|
||||
impl RingModel {
|
||||
/// The ring after `adopt_prefetch`: every hit's slot is reserved for its source.
|
||||
fn new(slots: usize, kinds: &[Kind]) -> Self {
|
||||
let mut model = Self {
|
||||
ring: vec![SlotState::default(); slots],
|
||||
kinds: kinds.to_vec(),
|
||||
at: vec![None; kinds.len()],
|
||||
next: 0,
|
||||
};
|
||||
for (i, kind) in kinds.iter().enumerate() {
|
||||
if let Kind::Hit(slot) = kind {
|
||||
model.ring[*slot] = SlotState::PREFETCHED;
|
||||
model.at[i] = Some(*slot);
|
||||
}
|
||||
}
|
||||
model
|
||||
}
|
||||
|
||||
/// `Ring::stage_room`: always true without reserved slots (the literal ring).
|
||||
fn room(&self, index: usize) -> bool {
|
||||
let found = stage_target(self.ring.len(), self.next, |s| self.ring[s]).is_ok();
|
||||
let free = self.ring.iter().any(|s| !s.reserved && (!s.live || s.gathered));
|
||||
assert_eq!(found, free, "stage_target refuses only when no unreserved slot is free (PET.1)");
|
||||
self.kinds[index] != Kind::Copy || found
|
||||
}
|
||||
|
||||
/// `Ring::stage_one`.
|
||||
fn stage(&mut self, index: usize) -> Result<(), RingRefusal> {
|
||||
let kind = self.kinds[index];
|
||||
let prefetched = matches!(kind, Kind::Hit(_));
|
||||
if !stage_needed(kind == Kind::Resident, prefetched, self.at[index].is_some())? {
|
||||
return Ok(());
|
||||
}
|
||||
let sl = stage_target(self.ring.len(), self.next, |s| self.ring[s])?;
|
||||
let target = self.ring[sl];
|
||||
assert!(!target.reserved && !(target.live && !target.gathered), "source {index} overwrites slot {sl}");
|
||||
self.ring[sl].staged();
|
||||
self.at[index] = Some(sl);
|
||||
self.next = (sl + 1) % self.ring.len();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `Ring::gather` / `after_gather`.
|
||||
fn gather(&mut self, j: usize) -> Result<(), RingRefusal> {
|
||||
if self.kinds[j] == Kind::Resident {
|
||||
return Ok(());
|
||||
}
|
||||
let sl = self.at[j].ok_or(RingRefusal::GatherNoSlot)?;
|
||||
self.ring[sl].check_gather()?;
|
||||
self.ring[sl].gathered();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The driver's stage-ahead walk (`stream_through_ring`); returns the slot each source was read from.
|
||||
fn walk(slots: usize, kinds: &[Kind]) -> Vec<Option<usize>> {
|
||||
let mut model = RingModel::new(slots, kinds);
|
||||
let mut staged = 0usize;
|
||||
for j in 0..kinds.len() {
|
||||
while staged < kinds.len() && staged < j + slots && model.room(staged) {
|
||||
model.stage(staged).expect("stage_one refused");
|
||||
staged += 1;
|
||||
}
|
||||
assert!(staged > j, "source {j} is staged before its gather");
|
||||
model.gather(j).expect("gather refused");
|
||||
}
|
||||
model.at
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserved_slots_are_never_overwritten_before_their_gather() {
|
||||
let slots = 32;
|
||||
let budget = RingPrefetchPolicy::new(150, 8).budget(slots);
|
||||
let kinds: Vec<Kind> = (0..120)
|
||||
.map(|i| match i % 5 {
|
||||
0 if i / 5 < budget => Kind::Hit(i / 5),
|
||||
1 => Kind::Resident,
|
||||
_ => Kind::Copy,
|
||||
})
|
||||
.collect();
|
||||
let at = walk(slots, &kinds);
|
||||
for (i, kind) in kinds.iter().enumerate() {
|
||||
match kind {
|
||||
Kind::Resident => assert_eq!(at[i], None),
|
||||
Kind::Hit(slot) => assert_eq!(at[i], Some(*slot), "a hit is consumed from its prefetched slot"),
|
||||
Kind::Copy => assert!(at[i].is_some()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_prefetch_the_walk_is_the_literal_rotation() {
|
||||
let at = walk(8, &[Kind::Copy; 20]);
|
||||
let want: Vec<Option<usize>> = (0..20).map(|i| Some(i % 8)).collect();
|
||||
assert_eq!(at, want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ring_half_reserved_still_stages_every_copy() {
|
||||
let mut kinds: Vec<Kind> = (0..16).map(Kind::Hit).collect();
|
||||
kinds.extend([Kind::Copy; 100]);
|
||||
kinds.rotate_left(8); // copies before and after the hits
|
||||
assert!(walk(32, &kinds).iter().all(Option::is_some));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prefetched_source_is_never_staged_again() {
|
||||
let mut model = RingModel::new(8, &[Kind::Hit(3), Kind::Copy]);
|
||||
model.stage(0).expect("a prefetched source needs no stage copy");
|
||||
assert_eq!((model.at[0], model.ring[3]), (Some(3), SlotState::PREFETCHED), "its slot and state are untouched");
|
||||
model.stage(1).unwrap();
|
||||
assert_eq!(model.at[1], Some(0), "the next copy skips nothing but the reserved slot 3");
|
||||
assert_eq!(stage_needed(false, false, true), Err(RingRefusal::SourceAlreadyStaged));
|
||||
assert_eq!(stage_needed(false, true, true), Ok(false));
|
||||
assert_eq!(stage_needed(true, false, false), Ok(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reserved_slot_is_skipped_until_its_gather_then_reused() {
|
||||
let mut ring = [SlotState::PREFETCHED, SlotState::default(), SlotState::default()];
|
||||
assert_eq!(stage_target(3, 0, |s| ring[s]), Ok(1), "slot 0 is reserved");
|
||||
ring[1].staged();
|
||||
ring[2].staged();
|
||||
assert_eq!(stage_target(3, 1, |s| ring[s]), Err(RingRefusal::SlotNotGathered), "1 holds an unread copy");
|
||||
assert!(ring[0].gathered(), "the gather releases the reservation");
|
||||
assert_eq!(stage_target(3, 0, |s| ring[s]), Ok(0), "a gathered slot takes the next copy");
|
||||
let all = [SlotState::PREFETCHED; 2];
|
||||
assert_eq!(stage_target(2, 0, |s| all[s]), Err(RingRefusal::AllSlotsReserved));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gather_reads_a_slot_exactly_once() {
|
||||
let mut slot = SlotState::default();
|
||||
assert_eq!(slot.check_gather(), Err(RingRefusal::GatherSlotNotLive));
|
||||
slot.staged();
|
||||
assert_eq!(slot.check_gather(), Ok(()));
|
||||
assert!(!slot.gathered(), "a staged slot was not reserved");
|
||||
assert_eq!(slot.check_gather(), Err(RingRefusal::GatherSlotGathered));
|
||||
let mut model = RingModel::new(4, &[Kind::Copy]);
|
||||
assert_eq!(model.gather(0), Err(RingRefusal::GatherNoSlot), "a gather before the stage copy is refused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_refusal_has_its_own_trace_name() {
|
||||
use RingRefusal::*;
|
||||
let all =
|
||||
[SourceAlreadyStaged, AllSlotsReserved, SlotNotGathered, GatherNoSlot, GatherSlotNotLive, GatherSlotGathered];
|
||||
let mut names: Vec<&str> = all.iter().map(|r| r.check()).collect();
|
||||
names.sort_unstable();
|
||||
names.dedup();
|
||||
assert_eq!(names.len(), all.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_drains_stay_context_wide_unless_detached() {
|
||||
let policy = RingPrefetchPolicy::new(150, 8);
|
||||
assert!(!policy.detach_drains);
|
||||
assert!(policy.with_detached_drains(true).detach_drains);
|
||||
}
|
||||
|
||||
/// A small deterministic generator for the randomized ring walks.
|
||||
struct Lcg(u64);
|
||||
|
||||
impl Lcg {
|
||||
fn below(&mut self, n: usize) -> usize {
|
||||
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
((self.0 >> 33) as usize) % n
|
||||
}
|
||||
}
|
||||
|
||||
/// `sources` routed experts on `slots` stage slots: about a tenth resident, and the prefetch's `budget` entries in
|
||||
/// slots `0..budget`, each consumed (a hit) with probability ~55 % by a random copy source among the first ones.
|
||||
fn prefetched_layer(seed: u64, sources: usize, slots: usize) -> Vec<Kind> {
|
||||
let mut rng = Lcg(seed);
|
||||
let mut kinds: Vec<Kind> =
|
||||
(0..sources).map(|_| if rng.below(10) == 0 { Kind::Resident } else { Kind::Copy }).collect();
|
||||
let budget = RingPrefetchPolicy::new(150, 8).budget(slots);
|
||||
for slot in 0..budget {
|
||||
if rng.below(100) < 55 {
|
||||
let source = rng.below(sources.min(300));
|
||||
if kinds[source] == Kind::Copy {
|
||||
kinds[source] = Kind::Hit(slot);
|
||||
}
|
||||
}
|
||||
}
|
||||
kinds
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn more_sources_than_slots_with_prefetch_hits_never_stage_onto_an_unread_slot() {
|
||||
// PET.1: layers 46/47 route 410-460 experts on the 384-slot ring; the stage order wraps past the hits
|
||||
for seed in 0..200 {
|
||||
let kinds = prefetched_layer(seed, 460, 384);
|
||||
let at = walk(384, &kinds);
|
||||
for (i, kind) in kinds.iter().enumerate() {
|
||||
match kind {
|
||||
Kind::Resident => assert_eq!(at[i], None),
|
||||
Kind::Hit(slot) => assert_eq!(at[i], Some(*slot), "seed {seed}: hit {i} reads its prefetched slot"),
|
||||
Kind::Copy => assert!(at[i].is_some(), "seed {seed}: copy {i} was staged"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_next_slot_in_order_may_be_unread_after_hits_and_the_search_skips_it() {
|
||||
// slot 1 holds an unread copy (an earlier source), slot 2 is free: the literal "next in order" would be refused
|
||||
let mut ring = [SlotState::default(); 4];
|
||||
ring[0].staged();
|
||||
ring[0].gathered();
|
||||
ring[1].staged();
|
||||
assert_eq!(stage_target(4, 1, |s| ring[s]), Ok(2));
|
||||
ring[2].staged();
|
||||
ring[3].staged();
|
||||
assert_eq!(stage_target(4, 1, |s| ring[s]), Ok(0), "wraps to the gathered slot");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_size_and_seed_keeps_the_ring_sound() {
|
||||
for (sources, slots) in [(40, 32), (100, 32), (200, 96), (460, 384), (512, 384), (300, 384)] {
|
||||
for seed in 0..50 {
|
||||
let kinds = prefetched_layer(seed, sources, slots);
|
||||
assert!(walk(slots, &kinds).iter().zip(&kinds).all(|(at, k)| at.is_some() == (*k != Kind::Resident)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -259,6 +259,47 @@ fn tokens_are_printable_distinct_and_long_enough() {
|
||||
assert!((32..=4096).contains(&a.len()) && a.bytes().all(|c| (0x21..=0x7e).contains(&c)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_prompt_loan_ladder_is_on_for_the_5090_profiles_and_not_for_the_laptop() {
|
||||
let key = "LELEKA_PREFILL_LOAN_TIERS";
|
||||
for name in ["rtx5090-32g", "rtx5090-32g-file", "rtx5090-32g-gguf-ple"] {
|
||||
assert_eq!(
|
||||
config(name)
|
||||
.engine_environment()
|
||||
.get(key)
|
||||
.map(String::as_str),
|
||||
Some("1"),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
assert!(!config("rtx3080-16g").engine_environment().contains_key(key));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_switches_that_passed_the_bitwise_gate_are_on_for_the_5090_profiles_only() {
|
||||
// teacher-forced identity: 2057 rows, 1036 draft lines, A/A floor (step ledger, rows O8, B3, Q7)
|
||||
for key in [
|
||||
"LELEKA_DRAFT_CHECK_MERGE",
|
||||
"LELEKA_PREFIX_PARK_FAST",
|
||||
"LELEKA_DECODE_GRAPH_REUSE",
|
||||
] {
|
||||
for name in ["rtx5090-32g", "rtx5090-32g-file", "rtx5090-32g-gguf-ple"] {
|
||||
assert_eq!(
|
||||
config(name)
|
||||
.engine_environment()
|
||||
.get(key)
|
||||
.map(String::as_str),
|
||||
Some("1"),
|
||||
"{name} {key}"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
!config("rtx3080-16g").engine_environment().contains_key(key),
|
||||
"{key}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_server_profile_switches_reach_the_engine_environment_through_the_saved_config() {
|
||||
// `up` saves the RunConfig (profile.engine_env inside) as leleka.json; `run` loads it and `start_engine` hands
|
||||
@@ -308,3 +349,23 @@ fn expert_environment_wins_over_the_profile() {
|
||||
assert_eq!(env["LELEKA_ORIGINAL_SERVE_PCIE_FRAC"], "0.2");
|
||||
assert_eq!(env["LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS"], "auto");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_expert_stream_starts_at_1536_rows_for_the_5090_profiles_only() {
|
||||
// chunk residual hashes equal, prefill.read -180 ms at tails of 1.5-4k tokens (step ledger, row Q5)
|
||||
for name in ["rtx5090-32g", "rtx5090-32g-file", "rtx5090-32g-gguf-ple"] {
|
||||
assert_eq!(
|
||||
config(name)
|
||||
.engine_environment()
|
||||
.get("STRATA_PREFILL_STREAM_MIN")
|
||||
.map(String::as_str),
|
||||
Some("1536"),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
!config("rtx3080-16g")
|
||||
.engine_environment()
|
||||
.contains_key("STRATA_PREFILL_STREAM_MIN")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -111,8 +111,7 @@ impl Profile {
|
||||
for (key, value) in &self.engine_env {
|
||||
if !engine_env_key_ok(key) {
|
||||
return Err(format!(
|
||||
"engine_env key {key} must be an upper-case LELEKA_ORIGINAL_SERVE_*, LELEKA_SM120_*, \
|
||||
LELEKA_DRAFT_* or LELEKA_PLE_* name (or LELEKA_CHAIN)"
|
||||
"engine_env key {key} must be an upper-case name starting with one of {ENGINE_ENV_PREFIXES:?}"
|
||||
));
|
||||
}
|
||||
if value.is_empty() || value.len() > 1024 || value.chars().any(char::is_control) {
|
||||
@@ -127,14 +126,27 @@ impl Profile {
|
||||
|
||||
/// LELEKA_CHAIN selects the chain-kernel group (docs/chain-kernels.md), LELEKA_SM120_* the compute-capability-12
|
||||
/// kernel switches, LELEKA_DRAFT_* the draft-round ones (docs/experiments/draft-round-5090.md), LELEKA_PLE_* the
|
||||
/// GGUF PLE row reader
|
||||
/// (`kar_source: none`); every other switch is a serve-stack one.
|
||||
/// GGUF PLE row reader (`kar_source: none`), LELEKA_PREFILL_* the prompt-prefill switches (the loan ladder,
|
||||
/// docs/prefill-throughput.md), LELEKA_PREFIX_* the prefix-cache parking and LELEKA_DECODE_* the decode graph reuse
|
||||
/// (docs/experiments/step-ledger.md rows B3, Q7), STRATA_PREFILL_STREAM_MIN the chunk size from which the prompt
|
||||
/// streams every non-resident expert (row Q5); every other switch is a serve-stack one.
|
||||
/// The name prefixes a profile `engine_env` key may start with.
|
||||
const ENGINE_ENV_PREFIXES: [&str; 9] = [
|
||||
"LELEKA_ORIGINAL_SERVE_",
|
||||
"LELEKA_SM120_",
|
||||
"LELEKA_DRAFT_",
|
||||
"LELEKA_PLE_",
|
||||
"LELEKA_PREFILL_",
|
||||
"LELEKA_PREFIX_",
|
||||
"LELEKA_DECODE_",
|
||||
"LELEKA_CHAIN",
|
||||
"STRATA_PREFILL_STREAM_",
|
||||
];
|
||||
|
||||
fn engine_env_key_ok(key: &str) -> bool {
|
||||
let known = key.starts_with("LELEKA_ORIGINAL_SERVE_")
|
||||
|| key.starts_with("LELEKA_SM120_")
|
||||
|| key.starts_with("LELEKA_DRAFT_")
|
||||
|| key.starts_with("LELEKA_PLE_")
|
||||
|| key == "LELEKA_CHAIN";
|
||||
let known = ENGINE_ENV_PREFIXES
|
||||
.iter()
|
||||
.any(|prefix| key.starts_with(prefix));
|
||||
known
|
||||
&& key
|
||||
.bytes()
|
||||
|
||||
@@ -30,6 +30,9 @@ mod tests;
|
||||
mod exec_arguments;
|
||||
pub use exec_arguments::{archive_serve_extents, parse_seal_exec, substitute};
|
||||
|
||||
mod single_copy;
|
||||
pub use single_copy::{ALLOW_FULL_MEMFD_ENV, SINGLE_COPY_SLACK_BYTES, single_copy_verdict};
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
mod unsupported_host;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user