Merge branch 'claude/port-gpu-bringup' into claude/round-overhead
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
//! `LELEKA_BRINGUP_TRACE` + `LELEKA_PREFILL_PROFILE_SYNC`: per-command wall time of the batched prompt
|
||||
//! producers (each command drained on its own; attribution only, the drains slow the run). The runtime's
|
||||
//! `PREFILL-PROFILE` takes and prints the totals once per chunk.
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
static TOTALS: Mutex<Vec<(&'static str, usize, &'static str, Duration, u32)>> = Mutex::new(Vec::new());
|
||||
|
||||
/// Whether per-command timing is on (both switches set).
|
||||
pub fn enabled() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| {
|
||||
crate::bringup_trace_enabled() && std::env::var_os("LELEKA_PREFILL_PROFILE_SYNC").is_some()
|
||||
})
|
||||
}
|
||||
pub(crate) fn add(producer: &'static str, index: usize, label: &'static str, elapsed: Duration) {
|
||||
if let Ok(mut totals) = TOTALS.lock() {
|
||||
match totals.iter_mut().find(|e| e.0 == producer && e.1 == index) {
|
||||
Some(entry) => {
|
||||
entry.3 += elapsed;
|
||||
entry.4 += 1;
|
||||
}
|
||||
None => totals.push((producer, index, label, elapsed, 1)),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The accumulated totals as `producer#index:label=ms(xcount)` and reset.
|
||||
pub fn take_report() -> String {
|
||||
let Ok(mut totals) = TOTALS.lock() else { return String::new() };
|
||||
let mut entries = std::mem::take(&mut *totals);
|
||||
entries.sort_by_key(|e| (e.0, e.1));
|
||||
entries
|
||||
.iter()
|
||||
.map(|(p, i, l, d, n)| format!("{p}#{i}:{l}={:.1}(x{n})", d.as_secs_f64() * 1e3))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
@@ -507,15 +507,26 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
let timed = crate::command_profile::enabled();
|
||||
let started = std::time::Instant::now();
|
||||
let mut operation = context
|
||||
.driver
|
||||
.api
|
||||
.copy_from(hin, &history_bytes)
|
||||
.and_then(|()| context.driver.api.synchronize());
|
||||
for cmd in &mut commands {
|
||||
// the batch below runs without a drain until its end: next-MoE expert copies can run under it
|
||||
if operation.is_ok() {
|
||||
crate::prefetch_point();
|
||||
}
|
||||
if timed {
|
||||
crate::command_profile::add("gdn", 0, "history upload", started.elapsed());
|
||||
}
|
||||
for (index, cmd) in commands.iter_mut().enumerate() {
|
||||
if operation.is_err() {
|
||||
break;
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
let label = match cmd { DeviceCommand::Kernel { .. } => "kernel", DeviceCommand::Gemm { .. } => "gemm" };
|
||||
operation = match cmd {
|
||||
DeviceCommand::Kernel {
|
||||
function,
|
||||
@@ -540,8 +551,13 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
offset,
|
||||
beta,
|
||||
} => blas.gemm_gdn(*bf16, *x, *w, *y, t as i32, *n, *k, *ldy, *offset, beta),
|
||||
};
|
||||
if timed && operation.is_ok() {
|
||||
operation = blas.synchronize();
|
||||
crate::command_profile::add("gdn", index + 1, label, started.elapsed());
|
||||
}
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
let sync = blas.synchronize();
|
||||
if operation.is_ok() && sync.is_ok() {
|
||||
operation = context
|
||||
@@ -551,6 +567,10 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
.and_then(|()| context.driver.api.copy_to(hout, &mut final_history))
|
||||
}
|
||||
let all = context.driver.api.synchronize();
|
||||
crate::prefetch_window_end();
|
||||
if timed {
|
||||
crate::command_profile::add("gdn", 999, "drain+readback", started.elapsed());
|
||||
}
|
||||
let pop = guard.finish();
|
||||
let result = combine(combine(combine(operation, sync), all), pop);
|
||||
if result.is_err() {
|
||||
|
||||
@@ -68,6 +68,11 @@ impl<'ctx> GdnStateFiniteGuard<'ctx> {
|
||||
Ok(owner)
|
||||
}
|
||||
|
||||
/// Whether this guard refused or lost its owners (a failed guard is never reused).
|
||||
pub fn is_failed(&self) -> bool {
|
||||
self.failed || self.context.is_poisoned()
|
||||
}
|
||||
|
||||
/// Actual private status allocation; no state buffer is allocated here.
|
||||
pub fn allocated_bytes(&self) -> usize {
|
||||
self.status.as_ref().map_or(0, |status| status.bytes)
|
||||
|
||||
@@ -64,6 +64,7 @@ mod mmq_native;
|
||||
pub use mmq::resident::original_group::{
|
||||
OriginalMmqCopySchedule, OriginalMmqLayer, OriginalMmqOutput, original_mmq_group_bank_bytes,
|
||||
};
|
||||
pub(crate) use mmq::resident::original_group::{prefetch_point, prefetch_window_end};
|
||||
pub use mmq::resident::{
|
||||
FiniteMmqOutput, MmqChunkActivation, MmqGroupActivation, MmqHidden, MmqWorkspace,
|
||||
};
|
||||
@@ -132,6 +133,8 @@ pub use qsa_selected_kv::{QsaSelectedKvProducts, QsaSelectedKvWorkspace};
|
||||
mod qwen_ffi;
|
||||
|
||||
pub mod experimental;
|
||||
/// Per-command timing of the batched prompt producers (bring-up profiling only).
|
||||
pub mod command_profile;
|
||||
#[cfg(all(
|
||||
feature = "cuda-driver",
|
||||
target_os = "linux",
|
||||
|
||||
@@ -208,6 +208,26 @@ impl<'ctx> MappedExpertBank<'ctx> {
|
||||
+ 2 * size_of::<usize>()
|
||||
+ self.banks.capacity() * size_of::<RegisteredBank>()
|
||||
}
|
||||
/// The gate/up/down host ranges (address, length) of `expert` of `layer`: the members hold 512 equal
|
||||
/// per-expert extents in id order (the same extents `cache_source` returns for that expert's spans).
|
||||
pub(crate) fn expert_pieces(&self, layer: u8, expert: u32) -> Result<[(usize, usize); 3]> {
|
||||
if self.closed || self.context.is_poisoned() {
|
||||
return Err(Error::ContextPoisoned);
|
||||
}
|
||||
if layer >= 48 || expert >= 512 {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
let mut pieces = [(0usize, 0usize); 3];
|
||||
for (role, piece) in pieces.iter_mut().enumerate() {
|
||||
let bytes = self.banks[usize::from(layer) * 3 + role].member.bytes();
|
||||
if !bytes.len().is_multiple_of(512) {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
let each = bytes.len() / 512;
|
||||
*piece = (bytes.as_ptr() as usize + expert as usize * each, each);
|
||||
}
|
||||
Ok(pieces)
|
||||
}
|
||||
/// True for the low-RAM source: pageable file-mapped banks, no device aliases (see the field).
|
||||
pub fn pageable(&self) -> bool {
|
||||
self.pageable
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
//! prefill.cpp's `stream_all` (1159-1286) order for a page-locked (registered) expert bank: every expert of every
|
||||
//! layer of the chunk that the arena cache does not hold is copied, layer by layer in id order, into the copy ring
|
||||
//! (entry k lands in slot k % ring), whether or not the routing uses it.
|
||||
//!
|
||||
//! The port's compute path drains with context-wide synchronizations (cuCtxSynchronize) after every stage, and
|
||||
//! such a drain also waits for every copy queued on the copy stream: copies queued ahead of a mixer would be waited
|
||||
//! for at its first drain. (A free-running issuer thread, the Original's D-5, made every mixer drain wait for the
|
||||
//! issuer to fill the ring: measured slower, job 707.) So the copies are enqueued on the calling thread, at two
|
||||
//! kinds of points:
|
||||
//! * the layer's MoE: entries up to the ring's capacity, within the current layer only (as the per-layer ring);
|
||||
//! * `prefetch_point` (called by a long mixer producer right after its last drain before a sync-free batch of
|
||||
//! kernels, the GDN prompt producer): as many entries of the next MoE layer as its measured batch time covers,
|
||||
//! so those copies run under the mixer's kernels and are complete by its closing drain.
|
||||
//! The consumer (the per-layer copy ring) waits for entry k's `copied` event on the compute stream before
|
||||
//! gathering it and records `used` after; entries a layer does not route are released in order. Same bytes into
|
||||
//! the same kind of slot, gathered by the same kernels: the layer's products do not change.
|
||||
use crate::ffi::BufferHandle;
|
||||
use crate::ffi::original_stager::Api;
|
||||
use crate::{Error, Result};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Entry {
|
||||
pub(super) layer: u8,
|
||||
pub(super) expert: u32,
|
||||
/// gate/up/down host ranges (page-locked bank), copied back to back into the slot
|
||||
pub(super) pieces: [(usize, usize); 3],
|
||||
}
|
||||
struct Core {
|
||||
api: Api,
|
||||
entries: Vec<Entry>,
|
||||
targets: Vec<(BufferHandle, usize)>,
|
||||
copied: Vec<usize>,
|
||||
used: Vec<usize>,
|
||||
/// first entry of every layer (49 bounds)
|
||||
layer_start: [usize; 49],
|
||||
copy: usize,
|
||||
issued: Cell<usize>,
|
||||
consumed: Cell<usize>,
|
||||
next_layer: Cell<u8>,
|
||||
failed: Cell<bool>,
|
||||
/// measured length of the last prefetch window (point to closing drain) and the bytes/s estimate
|
||||
window: Cell<Duration>,
|
||||
window_start: Cell<Option<Instant>>,
|
||||
bytes_per_second: f64,
|
||||
}
|
||||
impl Core {
|
||||
fn ring(&self) -> usize {
|
||||
self.targets.len()
|
||||
}
|
||||
fn layer_end(&self, layer: u8) -> usize {
|
||||
self.layer_start[usize::from(layer) + 1]
|
||||
}
|
||||
/// Enqueue entries until `limit` (never past the ring: entry k - ring must be consumed first).
|
||||
fn issue_until(&self, limit: usize) -> Result<()> {
|
||||
if self.failed.get() {
|
||||
return Err(Error::ContextPoisoned);
|
||||
}
|
||||
let limit = limit.min(self.entries.len()).min(self.consumed.get() + self.ring());
|
||||
while self.issued.get() < limit {
|
||||
let k = self.issued.get();
|
||||
let result = self.issue(k);
|
||||
if result.is_err() {
|
||||
self.failed.set(true);
|
||||
return result;
|
||||
}
|
||||
self.issued.set(k + 1);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn issue(&self, k: usize) -> Result<()> {
|
||||
let entry = self.entries[k];
|
||||
let slot = k % self.ring();
|
||||
if k >= self.ring() {
|
||||
// the slot's previous entry was gathered (or released) on the compute stream
|
||||
self.api.wait(self.copy, self.used[slot])?;
|
||||
}
|
||||
let (target, capacity) = self.targets[slot];
|
||||
let mut offset = 0usize;
|
||||
for (address, length) in entry.pieces {
|
||||
let end = offset.checked_add(length).ok_or(Error::InvalidSize)?;
|
||||
if end > capacity {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
self.api.copy_raw(target.checked_subspan(capacity, offset, length)?, address, length, self.copy)?;
|
||||
offset = end;
|
||||
}
|
||||
self.api.record(self.copied[slot], self.copy)
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The active chunk stream of this thread, for `prefetch_point` (the producers have no schedule handle).
|
||||
static ACTIVE: RefCell<Option<Rc<Core>>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Called by a long mixer producer right after its last drain and before its sync-free kernel batch: enqueue as
|
||||
/// many next-MoE entries as the previous window covered. The caller must call `prefetch_window_end` after its
|
||||
/// closing drain. No-op without an active stream. The caller's Context must be current.
|
||||
pub(crate) fn prefetch_point() {
|
||||
ACTIVE.with(|active| {
|
||||
let Some(core) = active.borrow().clone() else { return };
|
||||
core.window_start.set(Some(Instant::now()));
|
||||
let window = core.window.get();
|
||||
if window.is_zero() {
|
||||
return;
|
||||
}
|
||||
let layer = core.next_layer.get();
|
||||
if layer >= 48 {
|
||||
return;
|
||||
}
|
||||
let blob: usize = core
|
||||
.entries
|
||||
.get(core.issued.get())
|
||||
.map_or(0, |e| e.pieces.iter().map(|p| p.1).sum());
|
||||
if blob == 0 {
|
||||
return;
|
||||
}
|
||||
// 90% of the window: the copies must be done by the window's closing drain
|
||||
let budget = (window.as_secs_f64() * 0.9 * core.bytes_per_second / blob as f64) as usize;
|
||||
let limit = (core.issued.get() + budget).min(core.layer_end(layer));
|
||||
let _ = core.issue_until(limit);
|
||||
});
|
||||
}
|
||||
/// The producer's closing drain returned: record the window length for the next `prefetch_point`.
|
||||
pub(crate) fn prefetch_window_end() {
|
||||
ACTIVE.with(|active| {
|
||||
if let Some(core) = active.borrow().as_ref()
|
||||
&& let Some(start) = core.window_start.take()
|
||||
{
|
||||
core.window.set(start.elapsed());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// One chunk's stream and the consumer's cursor (the caller's thread only).
|
||||
pub(super) struct ChunkStream {
|
||||
core: Rc<Core>,
|
||||
}
|
||||
impl ChunkStream {
|
||||
/// `entries` in stream order (layers ascending, experts ascending within a layer, from `first` to 48);
|
||||
/// `targets` the ring slots; `copied`/`used` one raw event per slot (created by the caller on this Context).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn start(
|
||||
api: Api,
|
||||
copy: usize,
|
||||
first: u8,
|
||||
entries: Vec<Entry>,
|
||||
targets: Vec<(BufferHandle, usize)>,
|
||||
copied: Vec<usize>,
|
||||
used: Vec<usize>,
|
||||
bytes_per_second: f64,
|
||||
) -> Result<Self> {
|
||||
if targets.is_empty() || copied.len() != targets.len() || used.len() != targets.len() || first >= 48 {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
if entries.windows(2).any(|w| (w[0].layer, w[0].expert) >= (w[1].layer, w[1].expert))
|
||||
|| entries.iter().any(|e| e.layer < first || e.layer >= 48 || e.expert >= 512)
|
||||
{
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
let mut layer_start = [0usize; 49];
|
||||
let mut k = 0usize;
|
||||
for (layer, start) in layer_start.iter_mut().enumerate() {
|
||||
while k < entries.len() && usize::from(entries[k].layer) < layer {
|
||||
k += 1;
|
||||
}
|
||||
*start = k;
|
||||
}
|
||||
let core = Rc::new(Core {
|
||||
api,
|
||||
entries,
|
||||
targets,
|
||||
copied,
|
||||
used,
|
||||
layer_start,
|
||||
copy,
|
||||
issued: Cell::new(layer_start[usize::from(first)]),
|
||||
consumed: Cell::new(layer_start[usize::from(first)]),
|
||||
next_layer: Cell::new(first),
|
||||
failed: Cell::new(false),
|
||||
window: Cell::new(Duration::ZERO),
|
||||
window_start: Cell::new(None),
|
||||
bytes_per_second: bytes_per_second.max(1e9),
|
||||
});
|
||||
ACTIVE.with(|active| *active.borrow_mut() = Some(Rc::clone(&core)));
|
||||
Ok(Self { core })
|
||||
}
|
||||
pub(super) fn next_layer_is(&self, layer: u8) -> bool {
|
||||
self.core.next_layer.get() == layer
|
||||
}
|
||||
/// Whether entry `k` copies exactly these gate/up/down byte ranges.
|
||||
pub(super) fn entry_matches(&self, k: usize, parts: [&[u8]; 3]) -> bool {
|
||||
self.core.entries.get(k).is_some_and(|e| {
|
||||
e.pieces.iter().zip(parts).all(|(&(a, n), p)| a == p.as_ptr() as usize && n == p.len())
|
||||
})
|
||||
}
|
||||
/// Entry index of `expert` in `layer`, if the stream carries it (not arena-resident).
|
||||
pub(super) fn entry(&self, layer: u8, expert: u32) -> Option<usize> {
|
||||
let (a, b) = (self.core.layer_start[usize::from(layer)], self.core.layer_start[usize::from(layer) + 1]);
|
||||
self.core.entries[a..b].binary_search_by_key(&expert, |e| e.expert).ok().map(|i| a + i)
|
||||
}
|
||||
/// Release (record `used`, consume) every entry before `upto` in order on `compute`.
|
||||
fn release_until(&mut self, upto: usize, compute: usize) -> Result<()> {
|
||||
let core = &self.core;
|
||||
while core.consumed.get() < upto {
|
||||
let k = core.consumed.get();
|
||||
// its copy is queued before its release is ordered after it
|
||||
core.issue_until(k + 1)?;
|
||||
let slot = k % core.ring();
|
||||
core.api.wait(compute, core.copied[slot])?;
|
||||
core.api.record(core.used[slot], compute)?;
|
||||
core.consumed.set(k + 1);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The ring's look-ahead for the cursor's layer: queue entries up to the ring's capacity, within the layer.
|
||||
pub(super) fn stage_ahead(&mut self, k: usize) -> Result<()> {
|
||||
let layer = self.core.entries.get(k).ok_or(Error::InvalidProjectionShape)?.layer;
|
||||
let end = self.core.layer_end(layer);
|
||||
self.core.issue_until(end)
|
||||
}
|
||||
/// Make entry `k` ready on `compute`: its slot and the slot's byte capacity.
|
||||
pub(super) fn acquire(&mut self, k: usize, compute: usize) -> Result<(BufferHandle, usize)> {
|
||||
self.release_until(k, compute)?;
|
||||
if self.core.consumed.get() != k {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
self.stage_ahead(k)?;
|
||||
let slot = k % self.core.ring();
|
||||
self.core.api.wait(compute, self.core.copied[slot])?;
|
||||
Ok(self.core.targets[slot])
|
||||
}
|
||||
/// The gather of entry `k` (the cursor) is enqueued on `compute`: mark its slot used.
|
||||
pub(super) fn consumed(&mut self, k: usize, compute: usize) -> Result<()> {
|
||||
if self.core.consumed.get() != k || self.core.issued.get() <= k {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
let slot = k % self.core.ring();
|
||||
self.core.api.record(self.core.used[slot], compute)?;
|
||||
self.core.consumed.set(k + 1);
|
||||
Ok(())
|
||||
}
|
||||
/// The layer's last routed expert was gathered: release its remaining entries and move to the next layer.
|
||||
pub(super) fn finish_layer(&mut self, layer: u8, compute: usize) -> Result<()> {
|
||||
if !self.next_layer_is(layer) {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
let end = self.core.layer_end(layer);
|
||||
self.release_until(end, compute)?;
|
||||
self.core.next_layer.set(layer + 1);
|
||||
Ok(())
|
||||
}
|
||||
/// Deactivate: no producer prefetches into these slots after this. The caller drains the copy stream.
|
||||
pub(super) fn stop(&mut self) -> Result<()> {
|
||||
ACTIVE.with(|active| {
|
||||
let mut active = active.borrow_mut();
|
||||
if active.as_ref().is_some_and(|a| Rc::ptr_eq(a, &self.core)) {
|
||||
*active = None;
|
||||
}
|
||||
});
|
||||
if self.core.failed.get() { Err(Error::ContextPoisoned) } else { Ok(()) }
|
||||
}
|
||||
pub(super) fn api(&self) -> &Api {
|
||||
&self.core.api
|
||||
}
|
||||
}
|
||||
impl Drop for ChunkStream {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.stop();
|
||||
}
|
||||
}
|
||||
@@ -1435,6 +1435,7 @@ impl OriginalMmqOutput<'_, '_, '_> {
|
||||
#[path = "mmq_original_ring.rs"]
|
||||
mod copy_ring;
|
||||
pub use copy_ring::OriginalMmqCopySchedule;
|
||||
pub(crate) use copy_ring::{prefetch_point, prefetch_window_end};
|
||||
impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
|
||||
/// Execute the actual ascending expert layer through Original's copy ring.
|
||||
/// The actual read/arena and registered bank remain retained until BOTH stream
|
||||
|
||||
@@ -9,7 +9,50 @@ use leleka_model_format::qwen4exp::{ResidentExpertBankSpan, TensorRole};
|
||||
use std::rc::Rc;
|
||||
#[path = "mmq_original_host_stage.rs"]
|
||||
mod host_stage;
|
||||
/// `LELEKA_PREFILL_DIAG_SKIP_EXPERT_DMA=1` (EXPERIMENTAL, diagnostic, wrong outputs): the copy ring issues no
|
||||
/// expert copies, so a profile shows the ring's compute alone. Never set in serving.
|
||||
fn skip_expert_dma() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("LELEKA_PREFILL_DIAG_SKIP_EXPERT_DMA").is_some_and(|v| v == "1"))
|
||||
}
|
||||
use host_stage::{HostStage, Job};
|
||||
#[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))]
|
||||
#[path = "mmq_original_chunk_stream.rs"]
|
||||
mod chunk_stream;
|
||||
#[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))]
|
||||
use chunk_stream::{ChunkStream, Entry as StreamEntry};
|
||||
#[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))]
|
||||
pub(crate) use chunk_stream::{prefetch_point, prefetch_window_end};
|
||||
#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))]
|
||||
pub(crate) fn prefetch_point() {}
|
||||
#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))]
|
||||
pub(crate) fn prefetch_window_end() {}
|
||||
#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))]
|
||||
struct ChunkStream;
|
||||
#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))]
|
||||
impl ChunkStream {
|
||||
fn entry(&self, _: u8, _: u32) -> Option<usize> {
|
||||
None
|
||||
}
|
||||
fn next_layer_is(&self, _: u8) -> bool {
|
||||
false
|
||||
}
|
||||
fn entry_matches(&self, _: usize, _: [&[u8]; 3]) -> bool {
|
||||
false
|
||||
}
|
||||
fn acquire(&mut self, _: usize, _: usize) -> Result<(ffi::BufferHandle, usize)> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
fn consumed(&mut self, _: usize, _: usize) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
fn finish_layer(&mut self, _: u8, _: usize) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
fn stop(&mut self) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
const COMMAND_CAP: usize = 2048;
|
||||
trait RingArena: GroupArena {
|
||||
fn stage_slots(&self) -> Result<usize>;
|
||||
@@ -58,6 +101,11 @@ pub struct OriginalMmqCopySchedule<'ctx> {
|
||||
/// first use, with one completion event per page-locked buffer.
|
||||
host: Option<HostStage>,
|
||||
host_events: Vec<OriginalGpuEvent<'ctx>>,
|
||||
/// prefill.cpp's `stream_all` issuer for the current prompt chunk (`begin_prompt_stream`), its bank and
|
||||
/// raw per-slot events.
|
||||
stream: Option<ChunkStream>,
|
||||
stream_bank: Option<Rc<crate::MappedExpertBank<'ctx>>>,
|
||||
stream_events: Vec<usize>,
|
||||
}
|
||||
impl Context<'_> {
|
||||
pub fn original_mmq_copy_schedule(&self, slots: usize) -> Result<OriginalMmqCopySchedule<'_>> {
|
||||
@@ -78,6 +126,9 @@ impl Context<'_> {
|
||||
host_metadata_outside: 0,
|
||||
host: None,
|
||||
host_events: Vec::new(),
|
||||
stream: None,
|
||||
stream_bank: None,
|
||||
stream_events: Vec::new(),
|
||||
};
|
||||
let result = (|| {
|
||||
owner
|
||||
@@ -117,7 +168,7 @@ impl Context<'_> {
|
||||
Ok(owner)
|
||||
}
|
||||
}
|
||||
impl OriginalMmqCopySchedule<'_> {
|
||||
impl<'ctx> OriginalMmqCopySchedule<'ctx> {
|
||||
/// Byte accounting only: the real caller computes retained bank, source
|
||||
/// vector and current router-layer capacities before this exclusive loan.
|
||||
pub fn retain_host_metadata_charge(&mut self, bytes: usize) -> Result<()> {
|
||||
@@ -137,6 +188,150 @@ impl OriginalMmqCopySchedule<'_> {
|
||||
pub fn ring_slots(&self) -> usize {
|
||||
self.events.len()
|
||||
}
|
||||
/// Whether a prompt-chunk expert stream is active.
|
||||
pub fn prompt_stream_active(&self) -> bool {
|
||||
self.stream.is_some()
|
||||
}
|
||||
/// prefill.cpp `stream_all` for the rest of this prompt chunk, from `first` (a layer about to run its
|
||||
/// MoE) to the last layer: an issuer thread copies every expert the arena cache does not hold, layer by
|
||||
/// layer in id order, from the page-locked `bank` into this arena's copy ring, at most `inflight` copies
|
||||
/// queued at a time. Only for a registered bank (a pageable one is staged by the ring's `HostStage`).
|
||||
/// The caller ends the stream (`end_prompt_stream`) before the row lease or the bank go, on every path.
|
||||
pub fn begin_prompt_stream(
|
||||
&mut self,
|
||||
read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>,
|
||||
bank: &Rc<crate::MappedExpertBank<'ctx>>,
|
||||
first: u8,
|
||||
bytes_per_second: f64,
|
||||
) -> Result<()> {
|
||||
self.begin_stream_inner(read, bank, first, bytes_per_second)
|
||||
}
|
||||
#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))]
|
||||
fn begin_stream_inner(
|
||||
&mut self,
|
||||
_: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>,
|
||||
_: &Rc<crate::MappedExpertBank<'ctx>>,
|
||||
_: u8,
|
||||
_: f64,
|
||||
) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
#[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))]
|
||||
fn begin_stream_inner(
|
||||
&mut self,
|
||||
read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>,
|
||||
bank: &Rc<crate::MappedExpertBank<'ctx>>,
|
||||
first: u8,
|
||||
bytes_per_second: f64,
|
||||
) -> Result<()> {
|
||||
use crate::ffi::original_stager::Api as StagerApi;
|
||||
self.validate_context(self.context)?;
|
||||
if self.stream.is_some() || bank.pageable() || !bank.cache_context_matches(self.context) || first >= 48
|
||||
|| !read.context_matches(self.context)
|
||||
{
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
let lease = read.lease();
|
||||
let ring = lease.copy_ring_slots()?;
|
||||
let mut targets = Vec::new();
|
||||
targets.try_reserve_exact(ring).map_err(|_| Error::HostAllocation)?;
|
||||
for index in 0..ring {
|
||||
targets.push(lease.copy_ring_span(index)?);
|
||||
}
|
||||
let mut entries = Vec::new();
|
||||
entries
|
||||
.try_reserve_exact((48 - usize::from(first)) * 512)
|
||||
.map_err(|_| Error::HostAllocation)?;
|
||||
for layer in first..48 {
|
||||
for expert in 0..512u32 {
|
||||
if lease.cache_expert_span(usize::from(layer), expert as usize)?.is_some() {
|
||||
continue;
|
||||
}
|
||||
let pieces = bank.expert_pieces(layer, expert)?;
|
||||
let bytes: usize = pieces.iter().map(|p| p.1).sum();
|
||||
if targets.iter().any(|t| t.1 < bytes) {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
entries.push(StreamEntry { layer, expert, pieces });
|
||||
}
|
||||
}
|
||||
let api = StagerApi::load()?;
|
||||
let guard = self.context.enter()?;
|
||||
let mut events = Vec::new();
|
||||
let created = (|| -> Result<()> {
|
||||
events.try_reserve_exact(2 * ring).map_err(|_| Error::HostAllocation)?;
|
||||
for _ in 0..2 * ring {
|
||||
events.push(api.event_create()?);
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
let pop = guard.finish();
|
||||
if let Err(primary) = combine(created, pop) {
|
||||
let guard = self.context.enter()?;
|
||||
for e in &events {
|
||||
let _ = api.event_destroy(*e);
|
||||
}
|
||||
let _ = guard.finish();
|
||||
return Err(primary);
|
||||
}
|
||||
let (copied, used) = (events[..ring].to_vec(), events[ring..].to_vec());
|
||||
let copy = self.copy.as_mut().ok_or(Error::ContextPoisoned)?.with_enqueue(Ok)?;
|
||||
// the copies must follow everything the compute path queued so far on its own streams
|
||||
self.context.synchronize()?;
|
||||
match ChunkStream::start(api, copy, first, entries, targets, copied, used, bytes_per_second) {
|
||||
Ok(stream) => {
|
||||
self.stream = Some(stream);
|
||||
self.stream_bank = Some(Rc::clone(bank));
|
||||
self.stream_events = events;
|
||||
Ok(())
|
||||
}
|
||||
Err(primary) => {
|
||||
let guard = self.context.enter()?;
|
||||
let loaded = StagerApi::load();
|
||||
if let Ok(api) = loaded {
|
||||
for e in &events {
|
||||
let _ = api.event_destroy(*e);
|
||||
}
|
||||
}
|
||||
let _ = guard.finish();
|
||||
Err(primary)
|
||||
}
|
||||
}
|
||||
}
|
||||
/// 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.
|
||||
pub fn end_prompt_stream(&mut self) -> Result<()> {
|
||||
let Some(mut stream) = self.stream.take() else { return Ok(()) };
|
||||
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);
|
||||
drop(stream);
|
||||
let drained = combine(copy, compute);
|
||||
let mut result = combine(stopped, drained);
|
||||
let events = std::mem::take(&mut self.stream_events);
|
||||
if result.is_ok() {
|
||||
result = self.destroy_stream_events(&events);
|
||||
} else {
|
||||
self.failed = true;
|
||||
std::mem::forget(events);
|
||||
}
|
||||
self.stream_bank.take();
|
||||
result
|
||||
}
|
||||
#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))]
|
||||
fn destroy_stream_events(&self, _: &[usize]) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))]
|
||||
fn destroy_stream_events(&self, events: &[usize]) -> Result<()> {
|
||||
let api = crate::ffi::original_stager::Api::load()?;
|
||||
let guard = self.context.enter()?;
|
||||
let mut result = Ok(());
|
||||
for e in events {
|
||||
result = combine(result, api.event_destroy(*e));
|
||||
}
|
||||
combine(result, guard.finish())
|
||||
}
|
||||
/// Bounded Rust metadata includes conservative actual private event/API/Rc
|
||||
/// storage. CUDA's opaque residency remains actual physical room, not zero.
|
||||
pub fn metadata_bytes(&self) -> Result<usize> {
|
||||
@@ -172,6 +367,7 @@ impl OriginalMmqCopySchedule<'_> {
|
||||
if self.closed {
|
||||
return Ok(());
|
||||
}
|
||||
let ended = self.end_prompt_stream();
|
||||
self.closed = true;
|
||||
let copy = self
|
||||
.copy
|
||||
@@ -181,7 +377,7 @@ impl OriginalMmqCopySchedule<'_> {
|
||||
.compute
|
||||
.as_ref()
|
||||
.map_or(Ok(()), OriginalGpuStream::synchronize);
|
||||
let mut result = combine(copy, compute);
|
||||
let mut result = combine(ended, combine(copy, compute));
|
||||
if let Some(mut host) = self.host.take() {
|
||||
if result.is_ok() {
|
||||
result = combine(result, host.close());
|
||||
@@ -227,6 +423,8 @@ struct Source<'read> {
|
||||
slot: Option<usize>,
|
||||
/// the host staging job of an expert copied through `HostStage`
|
||||
job: Option<usize>,
|
||||
/// the chunk stream entry of an expert the issuer copies (`begin_prompt_stream`)
|
||||
entry: Option<usize>,
|
||||
}
|
||||
/// Private owner: no external pointer/ready event can manufacture a stage.
|
||||
/// The actual source Rc prevents unregister/free during H2D or gathered use.
|
||||
@@ -243,6 +441,9 @@ pub(super) struct Ring<'read, 'ctx> {
|
||||
stage_next: usize,
|
||||
/// host staging started for this layer; DMAs of staged jobs known complete (in order)
|
||||
staging: bool,
|
||||
/// this layer's experts come from the chunk stream
|
||||
streamed: bool,
|
||||
layer: u8,
|
||||
stage_done: usize,
|
||||
submitted: bool,
|
||||
drained: bool,
|
||||
@@ -295,6 +496,8 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
flags: Vec::new(),
|
||||
stage_next: 0,
|
||||
staging: false,
|
||||
streamed: false,
|
||||
layer: layer as u8,
|
||||
stage_done: 0,
|
||||
submitted: false,
|
||||
drained: false,
|
||||
@@ -386,13 +589,39 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
resident,
|
||||
slot: None,
|
||||
job: None,
|
||||
entry: None,
|
||||
});
|
||||
}
|
||||
// With an active chunk stream for this layer, every non-resident expert is the stream's entry.
|
||||
if let Some(stream) = owner.schedule.stream.as_ref() {
|
||||
if stream.next_layer_is(layer as u8) {
|
||||
for source in &mut owner.sources {
|
||||
if source.resident.is_some() {
|
||||
continue;
|
||||
}
|
||||
let entry = stream
|
||||
.entry(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, [
|
||||
bank.cache_source(&source.spans[0])?,
|
||||
bank.cache_source(&source.spans[1])?,
|
||||
bank.cache_source(&source.spans[2])?,
|
||||
]) {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
source.entry = Some(entry);
|
||||
}
|
||||
owner.streamed = true;
|
||||
} else {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
}
|
||||
// Experts not page-locked (a pageable bank) are copied by the host stager's helpers into page-locked
|
||||
// buffers, in launch order, ahead of their DMAs.
|
||||
let mut jobs = Vec::new();
|
||||
for source in &mut owner.sources {
|
||||
if source.resident.is_none() && bank.host_staged(source.spans) {
|
||||
if source.resident.is_none() && source.entry.is_none() && bank.host_staged(source.spans) {
|
||||
let mut pieces = [(0usize, 0usize, 0u32); 3];
|
||||
for (role, span) in source.spans.iter().enumerate() {
|
||||
let bytes = bank.cache_source(span)?;
|
||||
@@ -500,7 +729,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
.sources
|
||||
.get(index)
|
||||
.ok_or(Error::InvalidProjectionShape)?;
|
||||
if source.resident.is_some() {
|
||||
if source.resident.is_some() || source.entry.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
if source.slot.is_some() {
|
||||
@@ -527,7 +756,10 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
let api = self.schedule.api.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let gu = formats[0].layout(1)?.raw_weight;
|
||||
let down = formats[2].layout(1)?.raw_weight;
|
||||
if let Some(j) = source.job {
|
||||
if skip_expert_dma() {
|
||||
// EXPERIMENTAL diagnostic only (wrong outputs): no expert bytes move; the slot keeps whatever blob it
|
||||
// held, so the ring's compute runs alone. Measures the grouped MMQ cost without the PCIe stream.
|
||||
} else if let Some(j) = source.job {
|
||||
// prefill.cpp stage_one, unpinned: the stager's page-locked copy (waits only if it is behind), then DMA
|
||||
let blob = gu * 2 + down;
|
||||
let host = self.schedule.host.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
@@ -602,8 +834,23 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
let gu = formats[0].layout(1)?.raw_weight;
|
||||
let down = formats[2].layout(1)?.raw_weight;
|
||||
let sl = source.slot;
|
||||
let entry = source.entry;
|
||||
let raw = if let Some(raw) = source.resident {
|
||||
raw
|
||||
} else if let Some(k) = entry {
|
||||
// the chunk stream's copy of entry k (the compute stream waits for it)
|
||||
let schedule = &mut *self.schedule;
|
||||
let stream = schedule.stream.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let (span, bytes) = schedule
|
||||
.compute
|
||||
.as_mut()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.with_enqueue(|s| stream.acquire(k, s))?;
|
||||
[
|
||||
span.checked_subspan(bytes, 0, gu)?,
|
||||
span.checked_subspan(bytes, gu, gu)?,
|
||||
span.checked_subspan(bytes, gu * 2, down)?,
|
||||
]
|
||||
} else {
|
||||
let sl = sl.ok_or(Error::InvalidProjectionShape)?;
|
||||
let slot = &mut self.slots[sl];
|
||||
@@ -645,6 +892,15 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
((gu * 2 + down) / 16) as u32,
|
||||
ffi::MmqOriginalGatherArguments::new(raw, gate_up, down_out, gu, down),
|
||||
))?;
|
||||
if let Some(k) = entry {
|
||||
let schedule = &mut *self.schedule;
|
||||
let stream = schedule.stream.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
schedule
|
||||
.compute
|
||||
.as_mut()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.with_enqueue(|s| stream.consumed(k, s))?;
|
||||
}
|
||||
if let Some(sl) = sl {
|
||||
let slot = &mut self.slots[sl];
|
||||
let events = &mut self.schedule.events[sl];
|
||||
@@ -661,6 +917,18 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
/// Every status is copied only after BOTH real streams drain. Numeric
|
||||
/// refusal remains stage/group ordered; later transport failure is primary.
|
||||
pub(super) fn finish_statuses(&mut self) -> Result<&[u8]> {
|
||||
if self.streamed {
|
||||
// release the layer's unrouted stream entries (in order) and hand the stream to the next layer
|
||||
let layer = self.layer;
|
||||
let schedule = &mut *self.schedule;
|
||||
let stream = schedule.stream.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
schedule
|
||||
.compute
|
||||
.as_mut()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.with_enqueue(|s| stream.finish_layer(layer, s))?;
|
||||
self.streamed = false;
|
||||
}
|
||||
self.drain()?;
|
||||
let status = self.status.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let guard = self.context.enter()?;
|
||||
@@ -707,6 +975,13 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
return Ok(());
|
||||
}
|
||||
self.closed = true;
|
||||
if self.streamed {
|
||||
// a layer that did not finish leaves the stream unusable: stop its issuer now (the owner ends it)
|
||||
if let Some(stream) = self.schedule.stream.as_mut() {
|
||||
let _ = stream.stop();
|
||||
}
|
||||
self.streamed = false;
|
||||
}
|
||||
// no stager helper reads the bank after this
|
||||
if self.staging {
|
||||
if let Some(host) = self.schedule.host.as_mut() {
|
||||
|
||||
@@ -658,7 +658,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
|
||||
/// Initial authentic prompt staging only. Later phases never download R.
|
||||
pub fn initialize<'arena, 'loan>(
|
||||
&mut self,
|
||||
mut lease: OriginalPromptRows<'arena, 'loan, 'ctx>,
|
||||
lease: OriginalPromptRows<'arena, 'loan, 'ctx>,
|
||||
workspace: &mut NativeBatchWorkspace<'ctx>,
|
||||
streams: &[f32],
|
||||
embedding: &[f32],
|
||||
@@ -673,6 +673,49 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
|
||||
}
|
||||
let s = encode(streams)?;
|
||||
let e = encode(embedding)?;
|
||||
self.upload_initial(lease, workspace, s, e)
|
||||
}
|
||||
/// `initialize` over the rows in place: each row's 10240 residual-stream values and 2560 PLE embedding
|
||||
/// values, in row order. The same finite refusal and the same device bytes, staged in one pass per buffer
|
||||
/// instead of a caller concatenation, a finite scan and a byte conversion.
|
||||
pub fn initialize_rows<'arena, 'loan>(
|
||||
&mut self,
|
||||
lease: OriginalPromptRows<'arena, 'loan, 'ctx>,
|
||||
workspace: &mut NativeBatchWorkspace<'ctx>,
|
||||
rows: &[(&[f32], &[f32])],
|
||||
) -> Result<OriginalDeviceResidual<'arena, 'loan, 'ctx>> {
|
||||
self.validate(&lease, workspace)?;
|
||||
let t = lease.rows();
|
||||
if rows.len() != t || rows.iter().any(|(s, e)| s.len() != 10240 || e.len() != 2560) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let mut s = Vec::new();
|
||||
s.try_reserve_exact(t * 10240 * 4).map_err(|_| Error::HostAllocation)?;
|
||||
let mut e = Vec::new();
|
||||
e.try_reserve_exact(t * 2560 * 4).map_err(|_| Error::HostAllocation)?;
|
||||
let mut finite = true;
|
||||
for (streams, embedding) in rows {
|
||||
for x in streams.iter() {
|
||||
finite &= x.is_finite();
|
||||
s.extend_from_slice(&x.to_le_bytes());
|
||||
}
|
||||
for x in embedding.iter() {
|
||||
finite &= x.is_finite();
|
||||
e.extend_from_slice(&x.to_le_bytes());
|
||||
}
|
||||
}
|
||||
if !finite {
|
||||
return Err(Error::NonFiniteMmqOutput("Original prompt input"));
|
||||
}
|
||||
self.upload_initial(lease, workspace, s, e)
|
||||
}
|
||||
fn upload_initial<'arena, 'loan>(
|
||||
&mut self,
|
||||
mut lease: OriginalPromptRows<'arena, 'loan, 'ctx>,
|
||||
workspace: &mut NativeBatchWorkspace<'ctx>,
|
||||
s: Vec<u8>,
|
||||
e: Vec<u8>,
|
||||
) -> Result<OriginalDeviceResidual<'arena, 'loan, 'ctx>> {
|
||||
let rh = Self::span(&lease, S::R, 40960)?;
|
||||
let eh = Self::span(&lease, S::PleEmbedding, 10240)?;
|
||||
let guard = match self.context.enter() {
|
||||
|
||||
@@ -31,6 +31,7 @@ pub(crate) struct Api {
|
||||
event_create: EventCreate,
|
||||
event_destroy: HandleCall,
|
||||
event_sync: HandleCall,
|
||||
event_query: HandleCall,
|
||||
event_record: EventRecord,
|
||||
stream_wait: StreamWait,
|
||||
copy: Copy,
|
||||
@@ -111,6 +112,7 @@ impl Api {
|
||||
event_create: sym!(c"cuEventCreate", EventCreate),
|
||||
event_destroy: sym!(c"cuEventDestroy_v2", HandleCall),
|
||||
event_sync: sym!(c"cuEventSynchronize", HandleCall),
|
||||
event_query: sym!(c"cuEventQuery", HandleCall),
|
||||
event_record: sym!(c"cuEventRecord", EventRecord),
|
||||
stream_wait: sym!(c"cuStreamWaitEvent", StreamWait),
|
||||
copy: sym!(c"cuMemcpyHtoDAsync_v2", Copy),
|
||||
@@ -183,6 +185,31 @@ impl Api {
|
||||
(self.event_sync)(event as Handle)
|
||||
})
|
||||
}
|
||||
/// `cuEventQuery`: `Ok(true)` once complete, `Ok(false)` while pending (CUDA_ERROR_NOT_READY = 600).
|
||||
pub(crate) fn event_query(&self, event: usize) -> Result<bool> {
|
||||
match unsafe { (self.event_query)(event as Handle) } {
|
||||
0 => Ok(true),
|
||||
600 => Ok(false),
|
||||
code => Err(Error::Driver { operation: "cuEventQuery", code }),
|
||||
}
|
||||
}
|
||||
/// One H2D copy of `bytes` from a host address the caller retains (a page-locked bank range) into
|
||||
/// `destination` on `stream`.
|
||||
pub(crate) fn copy_raw(
|
||||
&self,
|
||||
destination: BufferHandle,
|
||||
source: usize,
|
||||
bytes: usize,
|
||||
stream: usize,
|
||||
) -> Result<()> {
|
||||
destination.validate_extent(bytes)?;
|
||||
if bytes == 0 || source == 0 {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
check("cuMemcpyHtoDAsync_v2", unsafe {
|
||||
(self.copy)(destination.0, source as *const c_void, bytes, stream as Handle)
|
||||
})
|
||||
}
|
||||
pub(crate) fn context_token(handle: ContextHandle) -> usize {
|
||||
handle.0
|
||||
}
|
||||
|
||||
@@ -104,6 +104,10 @@ fn original_serve_laptop_bench() {
|
||||
config.kv_resident = v.parse().expect("LELEKA_ORIGINAL_SERVE_KV_RESIDENT must be a count");
|
||||
}
|
||||
config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from);
|
||||
// LELEKA_LAPTOP_PROMPT_CACHE=0 reads every request from the empty prompt (the stack default is --prompt-cache 6)
|
||||
if env::var("LELEKA_LAPTOP_PROMPT_CACHE").is_ok_and(|v| v == "0") {
|
||||
config.conversation = None;
|
||||
}
|
||||
config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment()
|
||||
.expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting");
|
||||
eprintln!("LAPTOP config: capacity {} cpu_workers {} max_context {} kv_resident {} budget {budget_gib} GiB tier {:?}",
|
||||
|
||||
@@ -348,6 +348,11 @@ fn original_serve_long_context_streamed_kv_smoke() {
|
||||
config.capacity = number("LELEKA_ORIGINAL_SERVE_CAPACITY", 2048);
|
||||
config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from);
|
||||
config.kv_resident = resident;
|
||||
// A prefill measurement: every request is read from the empty prompt unless
|
||||
// LELEKA_ORIGINAL_SERVE_LONG_CONVERSATION=yes keeps the stack's conversation cache.
|
||||
if !env::var("LELEKA_ORIGINAL_SERVE_LONG_CONVERSATION").is_ok_and(|v| v == "yes") {
|
||||
config.conversation = None;
|
||||
}
|
||||
config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment()
|
||||
.expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting");
|
||||
eprintln!("long-smoke capacity={} expert tier {:?}", config.capacity, config.expert_tier);
|
||||
@@ -359,6 +364,14 @@ fn original_serve_long_context_streamed_kv_smoke() {
|
||||
for prompt in &prompts {
|
||||
let prompt = prompt.as_slice();
|
||||
eprintln!("long-smoke prompt tokens={} kv-resident={resident} max-context={max_context}", prompt.len());
|
||||
// LELEKA_ORIGINAL_SERVE_LONG_IDS_DIR: write the prompt as `prompt<N>.ids` (comma-separated) for the Original's
|
||||
// `--tokens-file`, so both engines read the identical token sequence
|
||||
if let Some(dir) = env::var_os("LELEKA_ORIGINAL_SERVE_LONG_IDS_DIR") {
|
||||
let path = PathBuf::from(dir).join(format!("prompt{}.ids", prompt.len()));
|
||||
let text = prompt.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(",");
|
||||
std::fs::write(&path, text).unwrap_or_else(|e| panic!("cannot write {}: {e}", path.display()));
|
||||
eprintln!("long-smoke prompt ids -> {}", path.display());
|
||||
}
|
||||
for pass in 0..repeat {
|
||||
let started = std::time::Instant::now();
|
||||
let mut tokens = Vec::new();
|
||||
|
||||
@@ -926,6 +926,100 @@ impl ModelBinding {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
|
||||
impl<'group> MoeRoutedSourceScope<'_, 'group> {
|
||||
/// Inside a group scope (`with_moe_routed_group_source`): make `members` (one job's route, all
|
||||
/// selecting one expert of this layer) the scope's members, with exactly the member checks a new
|
||||
/// `with_moe_routed_source` scope applies, without a new source observation. Every descriptor,
|
||||
/// span and admission request afterwards is validated as in a per-expert scope.
|
||||
pub(crate) fn retarget(&mut self, members: &'group [(&'group MoeExpertWeights, usize)]) -> InputResult<()> {
|
||||
let (first, first_slot) = *members.first().ok_or(E::Range)?;
|
||||
if members.len() > 64 || !first.matches(&self.binding.identity(), self.layer) {
|
||||
return Err(E::Metadata);
|
||||
}
|
||||
let expert = *first.selected.get(first_slot).ok_or(E::Range)?;
|
||||
if expert >= EXPERTS as u32 {
|
||||
return Err(E::Range);
|
||||
}
|
||||
for (weights, slot) in members {
|
||||
if !weights.matches(&self.binding.identity(), self.layer) {
|
||||
return Err(E::Metadata);
|
||||
}
|
||||
if weights.selected.get(*slot) != Some(&expert) {
|
||||
return Err(E::Metadata);
|
||||
}
|
||||
}
|
||||
let source = self.source.as_mut().ok_or(E::Read)?;
|
||||
// Preserve the first Gate geometry check of a fresh scope.
|
||||
let tensor = source.tensor(routed_source_role(MoeMatrixRole::Gate)).map_err(|_| E::Geometry)?;
|
||||
routed_source_descriptor(&self.binding.identity(), first, first_slot, MoeMatrixRole::Gate, tensor)?;
|
||||
source.retarget(expert).map_err(|_| E::Range)?;
|
||||
self.members = members;
|
||||
self.expert = expert;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
|
||||
impl ModelBinding {
|
||||
/// One source fence for a whole layer group (generate.cpp reads a group's experts under one
|
||||
/// source): `jobs` holds one route per job, all of one layer. The callback starts on `jobs[0]`
|
||||
/// and moves to every other job with `retarget`, which applies the same member checks; every
|
||||
/// descriptor/span request is validated per job exactly as in `with_moe_routed_source`. Same
|
||||
/// finish discipline: the callback must finish, and a callback error still observes the source.
|
||||
pub(crate) fn with_moe_routed_group_source<'g, T, F>(
|
||||
&'g self,
|
||||
jobs: &'g [[(&'g MoeExpertWeights, usize); 1]],
|
||||
map_source_error: impl Fn(E) -> F,
|
||||
execute: impl FnOnce(&mut MoeRoutedSourceScope<'_, 'g>) -> std::result::Result<T, F>,
|
||||
) -> std::result::Result<T, F> {
|
||||
let members: &'g [(&'g MoeExpertWeights, usize)] = jobs.first().ok_or(E::Range).map_err(&map_source_error)?;
|
||||
let (first, first_slot) = members[0];
|
||||
if !first.matches(&self.identity(), first.layer) {
|
||||
return Err(map_source_error(E::Metadata));
|
||||
}
|
||||
if jobs.iter().any(|job| !job[0].0.matches(&self.identity(), first.layer)) {
|
||||
return Err(map_source_error(E::Metadata));
|
||||
}
|
||||
let expert = *first.selected.get(first_slot).ok_or(E::Range).map_err(&map_source_error)?;
|
||||
if expert >= EXPERTS as u32 {
|
||||
return Err(map_source_error(E::Range));
|
||||
}
|
||||
let mut artifact = self.artifact.try_borrow_mut().map_err(|_| map_source_error(E::Busy))?;
|
||||
let first_role = first
|
||||
.matrix(MoeExpertSelection::Routed { slot: first_slot }, MoeMatrixRole::Gate)
|
||||
.map_err(&map_source_error)?
|
||||
.role;
|
||||
routed_source_descriptor(
|
||||
&self.identity(),
|
||||
first,
|
||||
first_slot,
|
||||
MoeMatrixRole::Gate,
|
||||
artifact.tensor(first_role).map_err(|_| map_source_error(E::Geometry))?,
|
||||
)
|
||||
.map_err(&map_source_error)?;
|
||||
let source = artifact.begin_routed_moe_source(first.layer, expert).map_err(|_| map_source_error(E::Read))?;
|
||||
let mut scope = MoeRoutedSourceScope { binding: self, members, expert, layer: first.layer, source: Some(source), finished: false };
|
||||
let result = execute(&mut scope);
|
||||
let explicitly_finished = scope.finished;
|
||||
let cleanup = if scope.source.is_some() {
|
||||
scope.finish()
|
||||
} else if scope.finished {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(E::Read)
|
||||
};
|
||||
match result {
|
||||
Err(primary) => Err(primary),
|
||||
Ok(value) if explicitly_finished => cleanup.map(|()| value).map_err(&map_source_error),
|
||||
Ok(_) => {
|
||||
cleanup.map_err(&map_source_error)?;
|
||||
Err(map_source_error(E::Read))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Direct bound shared descriptors. No selected route is created for preload.
|
||||
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
|
||||
impl ModelBinding {
|
||||
|
||||
@@ -9,6 +9,22 @@ use leleka_cuda_driver::{GdnNativeFormat, NativeBatchWorkspace,
|
||||
use leleka_model_format::qwen4exp::ResidentExpertBankSpan;
|
||||
use crate::qwen_forward::prefill_profile::{self as prof, Stage as PStage};
|
||||
|
||||
/// prefill.cpp `stream_all` order (`begin_prompt_stream`): on for chunks of at least `STRATA_PREFILL_STREAM_MIN`
|
||||
/// rows (1024) over a registered bank; `LELEKA_PREFILL_STREAM=0` keeps the per-layer copy ring.
|
||||
/// `LELEKA_PREFILL_PCIE_GBPS` (default 45) sizes the copies queued under a GDN layer's kernels.
|
||||
fn prompt_stream_settings() -> Option<(usize, f64)> {
|
||||
static SETTINGS: std::sync::OnceLock<Option<(usize, f64)>> = std::sync::OnceLock::new();
|
||||
*SETTINGS.get_or_init(|| {
|
||||
if std::env::var("LELEKA_PREFILL_STREAM").is_ok_and(|v| v == "0") {
|
||||
return None;
|
||||
}
|
||||
let number = |name: &str, default: usize| std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default);
|
||||
let gbps = std::env::var("LELEKA_PREFILL_PCIE_GBPS").ok().and_then(|v| v.trim().parse::<f64>().ok())
|
||||
.filter(|g| g.is_finite() && *g > 1.0).unwrap_or(45.0);
|
||||
Some((number("STRATA_PREFILL_STREAM_MIN", 1024), gbps * 1e9))
|
||||
})
|
||||
}
|
||||
|
||||
fn native_format(key: MoeWeightDescriptor) -> Result<GdnNativeFormat> {
|
||||
match key.raw_kind {
|
||||
8 => Ok(GdnNativeFormat::Q8_0), 12 => Ok(GdnNativeFormat::Q4K),
|
||||
@@ -66,6 +82,14 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
Ok(cache)
|
||||
}
|
||||
|
||||
/// End the prompt chunk's expert stream, if any (idempotent; every forward exit calls it).
|
||||
pub(in crate::qwen_forward) fn end_prompt_stream(&mut self) -> Result<()> {
|
||||
match self.original_copy_schedule.as_mut() {
|
||||
Some(schedule) => schedule.end_prompt_stream().map_err(driver_error),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The registered retained model bank the prompt path streams from: also the source of the VRAM expert
|
||||
/// tier's fills, lent-slot refills, adaptive swaps and PCIe copies.
|
||||
pub(crate) fn original_expert_bank(&self) -> Option<Rc<leleka_cuda_driver::MappedExpertBank<'ctx>>> {
|
||||
@@ -161,7 +185,16 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
schedule.validate_context(self.context).map_err(driver_error)?;
|
||||
let context = self.context;
|
||||
let drain = Some(context as &dyn prof::Drain);
|
||||
let last_layer = layer.get() + 1 == binding.layer_count();
|
||||
let result = (|| {
|
||||
if layer.get() == 0 && !schedule.prompt_stream_active()
|
||||
&& let Some((minimum, bytes_per_second)) = prompt_stream_settings()
|
||||
&& read.rows() >= minimum && !bank.pageable()
|
||||
{
|
||||
// the whole chunk's expert stream starts with the first MoE layer
|
||||
schedule.begin_prompt_stream(&read, &bank, 0, bytes_per_second).map_err(driver_error)?;
|
||||
crate::bringup_trace!("DBG prefill stream: begin rows={}", read.rows());
|
||||
}
|
||||
// High-only is the selected literal Original mixed BF16 policy.
|
||||
let prepare_span = prof::span(PStage::MoePrepare, drain);
|
||||
let mut layer_program = program.prepare(read, shared, weights, formats, false)
|
||||
@@ -228,8 +261,16 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
routed_formats.ok_or(Error::IdentityMismatch)?, &sources).map_err(driver_error)?;
|
||||
drop(ring_span);
|
||||
let _span = prof::span(PStage::MoeFinish, drain);
|
||||
layer_program.finish(shared).map_err(driver_error)
|
||||
let block = layer_program.finish(shared).map_err(driver_error)?;
|
||||
if last_layer && schedule.prompt_stream_active() {
|
||||
schedule.end_prompt_stream().map_err(driver_error)?;
|
||||
}
|
||||
Ok(block)
|
||||
})();
|
||||
if result.is_err() {
|
||||
// the stream never outlives a failed layer
|
||||
let _ = schedule.end_prompt_stream();
|
||||
}
|
||||
if self.context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { self.failed.set(true); }
|
||||
result
|
||||
}
|
||||
|
||||
@@ -77,6 +77,9 @@ pub(crate) struct DenseWeightCache<'ctx> {
|
||||
gdn_qk_workspace: Option<Rc<QkScratch<'ctx>>>,
|
||||
qsa_attention_workspace: Option<RefCell<QsaAttentionScratch<'ctx>>>,
|
||||
gdn_verification: Option<Rc<RefCell<super::gdn::verification::Workspace<'ctx>>>>,
|
||||
/// Idle GDN next-state finite guards (each owns a loaded module and a status word): a prompt chunk's GDN
|
||||
/// layer borrows one and gives it back, instead of loading the module once per layer and chunk.
|
||||
gdn_guards: RefCell<Vec<leleka_cuda_driver::GdnStateFiniteGuard<'ctx>>>,
|
||||
gr_scratch: Option<RefCell<GrScratch<'ctx>>>,
|
||||
qsa_input: Option<RefCell<QsaInputScratch<'ctx>>>,
|
||||
qsa_keys: Option<RefCell<QsaIndexKeyCache<'ctx>>>,
|
||||
@@ -377,6 +380,39 @@ impl<'ctx> DenseWeightCache<'ctx> {
|
||||
let qsa=leleka_cuda_driver::QsaPromptIndexWorkspace::prompt_output_bytes(capacity).map_err(driver_error)?;
|
||||
gr.checked_add(qsa).ok_or(Error::Overflow)
|
||||
}
|
||||
/// An idle GDN next-state finite guard of this cache's Context, or a new one.
|
||||
pub(in crate::qwen_forward) fn take_gdn_guard(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
context: &Context<'_>,
|
||||
) -> Result<leleka_cuda_driver::GdnStateFiniteGuard<'ctx>> {
|
||||
let context = self.retained_context(binding, context)?;
|
||||
let idle = self.gdn_guards.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.pop();
|
||||
match idle {
|
||||
Some(guard) if !guard.is_failed() => Ok(guard),
|
||||
Some(guard) => {
|
||||
let _ = guard.close();
|
||||
context.gdn_state_finite_guard().map_err(driver_error)
|
||||
}
|
||||
None => context.gdn_state_finite_guard().map_err(driver_error),
|
||||
}
|
||||
}
|
||||
/// Give a guard back after a clean use; a failed one is closed instead.
|
||||
pub(in crate::qwen_forward) fn return_gdn_guard(
|
||||
&self,
|
||||
guard: leleka_cuda_driver::GdnStateFiniteGuard<'ctx>,
|
||||
) -> Result<()> {
|
||||
if guard.is_failed() {
|
||||
return guard.close().map_err(driver_error);
|
||||
}
|
||||
let mut idle = self.gdn_guards.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
|
||||
if idle.len() >= 4 {
|
||||
drop(idle);
|
||||
return guard.close().map_err(driver_error);
|
||||
}
|
||||
idle.push(guard);
|
||||
Ok(())
|
||||
}
|
||||
pub(in crate::qwen_forward) fn has_gdn_verification_workspace(&self) -> bool {
|
||||
self.gdn_verification.is_some()
|
||||
}
|
||||
@@ -414,6 +450,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
|
||||
gdn_qk_workspace: None,
|
||||
qsa_attention_workspace: None,
|
||||
gdn_verification: None,
|
||||
gdn_guards: RefCell::new(Vec::new()),
|
||||
gr_scratch: None,
|
||||
qsa_input: None,
|
||||
qsa_keys: None,
|
||||
@@ -1385,6 +1422,11 @@ impl<'ctx> DenseWeightCache<'ctx> {
|
||||
}
|
||||
pub(crate) fn close(self) -> Result<()> {
|
||||
let mut error = self.mirror_failed.get().then_some(Error::CudaExecution);
|
||||
for guard in self.gdn_guards.take() {
|
||||
if let Err(e) = guard.close() {
|
||||
error.get_or_insert(driver_error(e));
|
||||
}
|
||||
}
|
||||
if let Some(modules) = self.modules
|
||||
&& let Err(e) = modules.close()
|
||||
{
|
||||
|
||||
@@ -274,10 +274,13 @@ impl<'ctx> OriginalPromptExecutor<'ctx>{
|
||||
drop(input_span);
|
||||
let init_span=prof::span(PStage::Initialize,drain);
|
||||
let mut sources=Vec::new();sources.try_reserve_exact(tokens.len()).map_err(|_|Error::InputAllocation)?;
|
||||
let sources_span=prof::span(PStage::InitSources,None);
|
||||
for local in 0..tokens.len(){sources.push(PromptDeviceSource::from_original(binding,self.context,&txn,local)?);}
|
||||
drop(sources_span);
|
||||
let upload_span=prof::span(PStage::InitUpload,drain);
|
||||
let prompt=self.prompt.as_mut().ok_or(Error::IdentityMismatch)?;
|
||||
let rows=PromptDeviceRows::initialize(binding,dense,self.context,prompt,arena.begin_rows(tokens.len()).map_err(driver_error)?,sources)?;
|
||||
drop(init_span);
|
||||
drop(upload_span);drop(init_span);
|
||||
let mut carrier=Carrier::Plain(rows);
|
||||
for layer in binding.ordered_layers(){
|
||||
let index=layer.index();let role=super::super::gr::GrRole::Attention(index);
|
||||
@@ -345,6 +348,8 @@ impl<'ctx> OriginalPromptExecutor<'ctx>{
|
||||
crate::bringup_trace!("DBG[{:.0}s] L{index} moe ok",crate::qwen_forward::original_serve_stack::dbg_el());
|
||||
}
|
||||
let Carrier::Plain(mut rows)=carrier else{return Err(Error::IdentityMismatch);};
|
||||
// the chunk's expert stream (if any) ended with the last MoE layer; never carried past the layers
|
||||
moe.end_prompt_stream()?;
|
||||
let final_span=prof::span(PStage::Final,drain);
|
||||
crate::bringup_trace!("DBG[{:.0}s] forward: all layers ok, final row",crate::qwen_forward::original_serve_stack::dbg_el());
|
||||
let final_row=rows.preview_conditioning(binding,dense,&txn).map_err(|e|{crate::bringup_trace!("DBG[{:.0}s] preview_conditioning err {e:?}",crate::qwen_forward::original_serve_stack::dbg_el());e})?;
|
||||
@@ -390,6 +395,8 @@ impl<'ctx> OriginalPromptExecutor<'ctx>{
|
||||
match operation{
|
||||
Err(primary)=>{
|
||||
crate::bringup_trace!("DBG[{:.0}s] forward operation failed: {primary:?}",crate::qwen_forward::original_serve_stack::dbg_el());
|
||||
// stop the chunk's expert stream before the transaction rolls back
|
||||
if moe.end_prompt_stream().is_err(){self.failed=true;}
|
||||
let cleanup=txn.abort_with_draft(binding,dense,&mut self.layers,&checkpoint,draft,&draft_checkpoint);
|
||||
if cleanup.is_err()||self.context.is_poisoned(){self.failed=true;}
|
||||
Err(primary)
|
||||
|
||||
@@ -147,7 +147,7 @@ impl<'ctx> GdnChunkDevice<'ctx> {
|
||||
// No position-only key or intermediate host state is manufactured.
|
||||
owner.state = Some(upload(context, owner.start.prior().values())?);
|
||||
owner.next = Some(allocate(context, STATE_ELEMENTS)?);
|
||||
owner.guard = Some(context.gdn_state_finite_guard().map_err(driver_error)?);
|
||||
owner.guard = Some(cache.take_gdn_guard(binding, context)?);
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(primary) = operation {
|
||||
@@ -563,10 +563,7 @@ impl<'ctx> GdnChunkDevice<'ctx> {
|
||||
})?;
|
||||
}
|
||||
if let Some(guard) = self.guard.take() {
|
||||
guard.close().map_err(|e| {
|
||||
self.failed.set(true);
|
||||
driver_error(e)
|
||||
})?;
|
||||
cache.return_gdn_guard(guard).inspect_err(|_| self.failed.set(true))?;
|
||||
}
|
||||
let mut mirror = cache.gdn_mirror(binding, prior.layer().get(), self.context)?;
|
||||
let buffer = self.state.take().ok_or(Error::IdentityMismatch)?;
|
||||
|
||||
@@ -115,8 +115,11 @@ impl InputStage {
|
||||
txn.input_predecessors()?,
|
||||
binding.input_constants(),
|
||||
)?;
|
||||
let embedding_span = super::prefill_profile::span(super::prefill_profile::Stage::InputEmbedding, None);
|
||||
let embedding = binding.embedding_row(token.get()).map_err(binding_error)?;
|
||||
let streams = ResidualStreams::broadcast(&embedding)?;
|
||||
drop(embedding_span);
|
||||
let _ple_span = super::prefill_profile::span(super::prefill_profile::Stage::InputPle, None);
|
||||
let ple = cache.gather(kar, &rows)?;
|
||||
Ok(InputReady {
|
||||
binding: binding.identity(),
|
||||
|
||||
@@ -95,6 +95,8 @@ mod original_serve_native;
|
||||
// The routed-expert tier of the Original verifier window (all-CPU pool over the pinned mapped weights).
|
||||
#[cfg(all(target_os="linux",target_arch="x86_64"))]
|
||||
pub(crate) mod original_serve_pool;
|
||||
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
|
||||
pub(crate) mod original_serve_lookahead;
|
||||
// The VRAM expert tier of that window (R4 residency, PCIe share, adaptive swaps, prompt-path slot loan).
|
||||
#[cfg(all(target_os="linux",target_arch="x86_64"))]
|
||||
pub(crate) mod original_serve_residency;
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
//! expert_source.cpp `RouterLookahead` for the file-mapped expert source (the Original's `--mmap-experts`):
|
||||
//! when the CPU tier starts layer `l`, a background thread applies layer `l + 1`'s router (BF16 host copy) to
|
||||
//! layer `l`'s MoE input (the residual stream changes little from one layer to the next), takes each row's
|
||||
//! top-10, drops the experts the VRAM tier holds and advises the kernel to read the rest's pages
|
||||
//! (`MADV_WILLNEED`), so they are on the way while layer `l` computes. A prediction only warms pages: it
|
||||
//! never changes which experts are computed or how. `submit` never waits: a prediction still running for an
|
||||
//! earlier layer makes this one skip.
|
||||
use std::sync::{Arc, Condvar, Mutex, atomic::{AtomicU64, Ordering}};
|
||||
use std::thread::JoinHandle;
|
||||
|
||||
const HIDDEN: usize = 2560;
|
||||
const EXPERTS: usize = 512;
|
||||
const TOP_K: usize = 10;
|
||||
const MAX_ROWS: usize = 8;
|
||||
|
||||
/// Where layer `l`'s routed experts live in the mapped bank: per role (gate, up, down) the address of
|
||||
/// expert 0 and the bytes of one expert (experts are contiguous and uniform, `checked_descriptor`).
|
||||
pub(in crate::qwen_forward) type LayerLayout = [(usize, usize); 3];
|
||||
|
||||
#[derive(Default)]
|
||||
struct Mail {
|
||||
pending: bool,
|
||||
busy: bool,
|
||||
quit: bool,
|
||||
layer: usize,
|
||||
rows: usize,
|
||||
x: Vec<f32>,
|
||||
resident: Vec<bool>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(in crate::qwen_forward) struct LookaheadStats {
|
||||
pub(in crate::qwen_forward) submitted: AtomicU64,
|
||||
pub(in crate::qwen_forward) skipped: AtomicU64,
|
||||
pub(in crate::qwen_forward) predicted: AtomicU64,
|
||||
pub(in crate::qwen_forward) busy_us: AtomicU64,
|
||||
}
|
||||
|
||||
pub(in crate::qwen_forward) struct RouterLookahead {
|
||||
shared: Arc<(Mutex<Mail>, Condvar)>,
|
||||
stats: Arc<LookaheadStats>,
|
||||
thread: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl RouterLookahead {
|
||||
/// `routers[l]`: layer l's `ffn_gate_inp` as BF16 bits, 512 rows of 2560; `layouts[l]`: its bank layout.
|
||||
pub(in crate::qwen_forward) fn start(routers: Vec<Box<[u16]>>, layouts: Vec<LayerLayout>) -> Option<Self> {
|
||||
if routers.len() != layouts.len() || routers.iter().any(|r| r.len() != EXPERTS * HIDDEN) {
|
||||
return None;
|
||||
}
|
||||
let mut mail = Mail::default();
|
||||
mail.x.try_reserve_exact(MAX_ROWS * HIDDEN).ok()?;
|
||||
mail.resident.try_reserve_exact(EXPERTS).ok()?;
|
||||
let shared = Arc::new((Mutex::new(mail), Condvar::new()));
|
||||
let stats = Arc::new(LookaheadStats::default());
|
||||
let (worker_shared, worker_stats) = (Arc::clone(&shared), Arc::clone(&stats));
|
||||
let thread = std::thread::Builder::new()
|
||||
.name("leleka-lookahead".into())
|
||||
.spawn(move || run(&worker_shared, &worker_stats, &routers, &layouts))
|
||||
.ok()?;
|
||||
Some(Self { shared, stats, thread: Some(thread) })
|
||||
}
|
||||
|
||||
/// Layer `layer`'s MoE input (`rows` x 2560): predict and warm layer `layer + 1`, leaving out the experts
|
||||
/// `resident` (of layer `layer + 1`) says the VRAM tier holds.
|
||||
pub(in crate::qwen_forward) fn submit(&self, layer: usize, x: &[f32], resident: impl Fn(usize) -> bool) {
|
||||
let rows = (x.len() / HIDDEN).min(MAX_ROWS);
|
||||
if rows == 0 {
|
||||
return;
|
||||
}
|
||||
let (lock, wake) = &*self.shared;
|
||||
let Ok(mut mail) = lock.try_lock() else {
|
||||
self.stats.skipped.fetch_add(1, Ordering::Relaxed);
|
||||
return;
|
||||
};
|
||||
if mail.busy || mail.pending || mail.quit {
|
||||
self.stats.skipped.fetch_add(1, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
mail.x.clear();
|
||||
mail.x.extend_from_slice(&x[..rows * HIDDEN]);
|
||||
mail.resident.clear();
|
||||
mail.resident.extend((0..EXPERTS).map(&resident));
|
||||
mail.layer = layer + 1;
|
||||
mail.rows = rows;
|
||||
mail.pending = true;
|
||||
drop(mail);
|
||||
self.stats.submitted.fetch_add(1, Ordering::Relaxed);
|
||||
wake.notify_one();
|
||||
}
|
||||
|
||||
pub(in crate::qwen_forward) fn stats(&self) -> &LookaheadStats {
|
||||
&self.stats
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RouterLookahead {
|
||||
fn drop(&mut self) {
|
||||
let (lock, wake) = &*self.shared;
|
||||
if let Ok(mut mail) = lock.lock() {
|
||||
mail.quit = true;
|
||||
}
|
||||
wake.notify_all();
|
||||
if let Some(thread) = self.thread.take() {
|
||||
let _ = thread.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run(shared: &(Mutex<Mail>, Condvar), stats: &LookaheadStats, routers: &[Box<[u16]>], layouts: &[LayerLayout]) {
|
||||
let (lock, wake) = shared;
|
||||
let mut x = vec![0.0f32; MAX_ROWS * HIDDEN];
|
||||
let mut resident = vec![false; EXPERTS];
|
||||
let mut logits = vec![0.0f32; MAX_ROWS * EXPERTS];
|
||||
let mut order: Vec<usize> = (0..EXPERTS).collect();
|
||||
let mut want: Vec<usize> = Vec::with_capacity(MAX_ROWS * TOP_K);
|
||||
loop {
|
||||
let (layer, rows) = {
|
||||
let Ok(mut mail) = lock.lock() else { return };
|
||||
while !mail.quit && !mail.pending {
|
||||
mail = match wake.wait(mail) {
|
||||
Ok(mail) => mail,
|
||||
Err(_) => return,
|
||||
};
|
||||
}
|
||||
if mail.quit {
|
||||
return;
|
||||
}
|
||||
mail.pending = false;
|
||||
mail.busy = true;
|
||||
let rows = mail.rows;
|
||||
x[..rows * HIDDEN].copy_from_slice(&mail.x[..rows * HIDDEN]);
|
||||
resident.copy_from_slice(&mail.resident);
|
||||
(mail.layer, rows)
|
||||
};
|
||||
let started = std::time::Instant::now();
|
||||
if let (Some(router), Some(layout)) = (routers.get(layer), layouts.get(layer)) {
|
||||
let out = &mut logits[..rows * EXPERTS];
|
||||
if leleka_native_cpu_expert::bf16_rows_multi(router, EXPERTS, HIDDEN, &x[..rows * HIDDEN], rows, out).is_ok() {
|
||||
want.clear();
|
||||
for t in 0..rows {
|
||||
let lt = &out[t * EXPERTS..(t + 1) * EXPERTS];
|
||||
order.iter_mut().enumerate().for_each(|(i, o)| *o = i);
|
||||
order.select_nth_unstable_by(TOP_K - 1, |&a, &b| lt[b].total_cmp(<[a]));
|
||||
for &e in &order[..TOP_K] {
|
||||
if !resident[e] && !want.contains(&e) {
|
||||
want.push(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
for &e in &want {
|
||||
for &(base, bytes) in layout {
|
||||
leleka_native_cpu_expert::advise_will_need(base + e * bytes, bytes);
|
||||
}
|
||||
}
|
||||
stats.predicted.fetch_add(want.len() as u64, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
stats.busy_us.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
|
||||
if let Ok(mut mail) = lock.lock() {
|
||||
mail.busy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,9 +17,10 @@ use super::{
|
||||
cpu_expert_miss::{runtime_error, validate_triplet, CpuMissWorkspace},
|
||||
input::binding_error,
|
||||
};
|
||||
use crate::model_binding::qwen4exp_input::{ModelBinding, MoeExpertWeights, MoeMatrixRole};
|
||||
use crate::model_binding::qwen4exp_input::{ModelBinding, MoeExpertWeights, MoeMatrixRole, MoeRoutedSourceScope};
|
||||
use leleka_cuda_driver::{OriginalGpuStream, OriginalVerifyCpuRows, OriginalVerifyCpuSink};
|
||||
use leleka_model_format::qwen4exp::ResidentExpertBankSpan;
|
||||
use super::original_serve_lookahead::{LayerLayout, RouterLookahead};
|
||||
use leleka_native_cpu_expert::{BorrowedExpert, BorrowedGroup, DirectCpuPool, DownFormat, GateUpFormat};
|
||||
|
||||
const HIDDEN: usize = 2560;
|
||||
@@ -188,22 +189,190 @@ impl PoolPath {
|
||||
}
|
||||
}
|
||||
|
||||
/// The direct path's state: the synchronous worker pool and the admitted experts. An expert's three
|
||||
/// encoded matrices are admitted (every block's FP16 scale finite: the guard `PreparedJob::new` applied to
|
||||
/// each copy) the first time it is routed to the CPU; the admitted spans are retained, so their bank memory
|
||||
/// stays alive and a later span of the same expert at the same address is the same immutable bytes.
|
||||
/// The direct path's state: the synchronous worker pool, the admitted experts and their bound routes. An
|
||||
/// expert's three encoded matrices are admitted (every block's FP16 scale finite: the guard
|
||||
/// `PreparedJob::new` applied to each copy) the first time it is routed to the CPU or PCIe; the admitted
|
||||
/// spans are retained, so their bank memory stays alive and a later span of the same expert at the same
|
||||
/// address is the same immutable bytes. The route (a top-10 selecting the expert in slot 0) is immutable
|
||||
/// bound metadata; every use still checks it against the binding inside a source scope.
|
||||
struct DirectTier {
|
||||
pool: DirectCpuPool,
|
||||
admitted: Vec<Admission>,
|
||||
held: Vec<Option<[ResidentExpertBankSpan; 3]>>,
|
||||
routes: Vec<Option<MoeExpertWeights>>,
|
||||
/// One source fence per layer group (default) or one per job (`LELEKA_CPU_POOL_FENCE=job`, A/B arm).
|
||||
group_fence: bool,
|
||||
/// The router lookahead over a file-mapped source (opt-in: `LELEKA_CPU_POOL_LOOKAHEAD=on`).
|
||||
lookahead_enabled: bool,
|
||||
lookahead: Option<RouterLookahead>,
|
||||
/// Which experts of the next layer the VRAM tier holds (set by the tier before each group).
|
||||
next_resident: Vec<bool>,
|
||||
}
|
||||
|
||||
/// One routed expert's retained state: its admitted spans and the route bound to it (a top-10 that selects
|
||||
/// it in slot 0). The route is immutable bound metadata; every use still opens a source scope that checks
|
||||
/// it against the binding and the actual descriptors.
|
||||
#[derive(Default)]
|
||||
pub(in crate::qwen_forward) struct Admission {
|
||||
spans: Option<[ResidentExpertBankSpan; 3]>,
|
||||
route: Option<MoeExpertWeights>,
|
||||
/// One opened expert of a group: its bank spans, formats and whether it was already admitted.
|
||||
type Opened = ([ResidentExpertBankSpan; 3], (GateUpFormat, DownFormat), bool);
|
||||
|
||||
/// The per-job checks inside a scope whose members are this job's route: binding, the actual gate/up/down
|
||||
/// descriptors of exactly this layer and expert, their formats and the bank spans; `held` says whether the
|
||||
/// same spans were admitted before.
|
||||
fn open_job(
|
||||
source: &mut MoeRoutedSourceScope<'_, '_>,
|
||||
binding: &ModelBinding,
|
||||
layer: u32,
|
||||
expert: u32,
|
||||
held: &Option<[ResidentExpertBankSpan; 3]>,
|
||||
) -> Result<Opened> {
|
||||
source.validate_binding(binding).map_err(binding_error)?;
|
||||
let keys = [
|
||||
source.descriptor(0, MoeMatrixRole::Gate).map_err(binding_error)?,
|
||||
source.descriptor(0, MoeMatrixRole::Up).map_err(binding_error)?,
|
||||
source.descriptor(0, MoeMatrixRole::Down).map_err(binding_error)?,
|
||||
];
|
||||
if keys.iter().any(|k| k.layer != layer || k.expert != Some(expert)) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let format = validate_triplet(keys).map_err(runtime_error)?;
|
||||
let spans = [
|
||||
source.bank_span(0, MoeMatrixRole::Gate).map_err(binding_error)?,
|
||||
source.bank_span(0, MoeMatrixRole::Up).map_err(binding_error)?,
|
||||
source.bank_span(0, MoeMatrixRole::Down).map_err(binding_error)?,
|
||||
];
|
||||
let ready = held.as_ref().is_some_and(|h| same_spans(h, &spans));
|
||||
Ok((spans, format, ready))
|
||||
}
|
||||
|
||||
/// First use (or a different span): admit every row of the job's actual matrices and retain them.
|
||||
fn admit_job(
|
||||
source: &mut MoeRoutedSourceScope<'_, '_>,
|
||||
held: &mut Option<[ResidentExpertBankSpan; 3]>,
|
||||
spans: &[ResidentExpertBankSpan; 3],
|
||||
) -> Result<()> {
|
||||
*held = None;
|
||||
let checked = [
|
||||
source.mapped_span(0, MoeMatrixRole::Gate).map_err(binding_error)?,
|
||||
source.mapped_span(0, MoeMatrixRole::Up).map_err(binding_error)?,
|
||||
source.mapped_span(0, MoeMatrixRole::Down).map_err(binding_error)?,
|
||||
];
|
||||
if !same_spans(&checked, spans) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
*held = Some(checked);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn same_spans(a: &[ResidentExpertBankSpan; 3], b: &[ResidentExpertBankSpan; 3]) -> bool {
|
||||
a.iter().zip(b).all(|(x, y)| x.bytes().as_ptr() == y.bytes().as_ptr() && x.bytes().len() == y.bytes().len())
|
||||
}
|
||||
|
||||
impl DirectTier {
|
||||
fn start_lookahead(&mut self, binding: &ModelBinding) -> Result<RouterLookahead> {
|
||||
let mut routers: Vec<Box<[u16]>> = Vec::new();
|
||||
let mut layouts: Vec<LayerLayout> = Vec::new();
|
||||
for layer in 0..48u32 {
|
||||
let weights = binding.moe_route_weights(layer).map_err(binding_error)?;
|
||||
let block = binding.moe_route_matrix_block(&weights, 0, EXPERTS as usize).map_err(binding_error)?;
|
||||
routers.push(block.bytes().chunks_exact(2).map(|b| u16::from_le_bytes([b[0], b[1]])).collect());
|
||||
let at = Self::index(layer, 0)?;
|
||||
if self.routes[at].is_none() {
|
||||
let selected = std::array::from_fn(|i| i as u32);
|
||||
self.routes[at] = Some(binding.moe_expert_weights(layer, selected).map_err(binding_error)?);
|
||||
}
|
||||
let members = [(self.routes[at].as_ref().ok_or(Error::IdentityMismatch)?, 0)];
|
||||
let layout = binding.with_moe_routed_source(&members, binding_error, |source| {
|
||||
let spans = [
|
||||
source.bank_span(0, MoeMatrixRole::Gate).map_err(binding_error),
|
||||
source.bank_span(0, MoeMatrixRole::Up).map_err(binding_error),
|
||||
source.bank_span(0, MoeMatrixRole::Down).map_err(binding_error),
|
||||
];
|
||||
let finish = source.finish().map_err(binding_error);
|
||||
let mut layout: LayerLayout = [(0, 0); 3];
|
||||
for (slot, span) in layout.iter_mut().zip(spans) {
|
||||
let span = span?;
|
||||
*slot = ((span.bytes().as_ptr() as usize).wrapping_sub(span.offset()), span.bytes().len());
|
||||
}
|
||||
finish.map(|()| layout)
|
||||
})?;
|
||||
layouts.push(layout);
|
||||
}
|
||||
RouterLookahead::start(routers, layouts).ok_or(Error::InputAllocation)
|
||||
}
|
||||
|
||||
fn index(layer: u32, expert: u32) -> Result<usize> {
|
||||
if layer >= 48 || expert >= EXPERTS as u32 {
|
||||
return Err(Error::InvalidExpert);
|
||||
}
|
||||
Ok(layer as usize * EXPERTS as usize + expert as usize)
|
||||
}
|
||||
|
||||
/// Open every expert of one layer group (under one source fence, or one per job), let `between`
|
||||
/// see the opened spans (the mapped source's prefetch), then admit the first-use experts. The
|
||||
/// result keeps the order of `experts`.
|
||||
fn open_group(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
layer: u32,
|
||||
experts: &[u32],
|
||||
between: impl FnOnce(&mut DirectCpuPool, &[Opened]) -> Result<()>,
|
||||
) -> Result<Vec<Opened>> {
|
||||
for &expert in experts {
|
||||
let at = Self::index(layer, expert)?;
|
||||
if self.routes[at].is_none() {
|
||||
// A route that selects `expert` in slot 0 (cache_original_prompt.rs `original_expert_spans`).
|
||||
let selected = std::array::from_fn(|i| (expert + i as u32) % EXPERTS as u32);
|
||||
self.routes[at] = Some(binding.moe_expert_weights(layer, selected).map_err(binding_error)?);
|
||||
}
|
||||
}
|
||||
let DirectTier { pool, held, routes, group_fence, .. } = self;
|
||||
let mut members: Vec<[(&MoeExpertWeights, usize); 1]> = Vec::new();
|
||||
members.try_reserve_exact(experts.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for &expert in experts {
|
||||
members.push([(routes[Self::index(layer, expert)?].as_ref().ok_or(Error::IdentityMismatch)?, 0)]);
|
||||
}
|
||||
let mut opened: Vec<Opened> = Vec::new();
|
||||
opened.try_reserve_exact(experts.len()).map_err(|_| Error::InputAllocation)?;
|
||||
if members.is_empty() {
|
||||
return Ok(opened);
|
||||
}
|
||||
if *group_fence {
|
||||
binding.with_moe_routed_group_source(&members, binding_error, |source| {
|
||||
for (i, &expert) in experts.iter().enumerate() {
|
||||
if i > 0 {
|
||||
source.retarget(&members[i][..]).map_err(binding_error)?;
|
||||
}
|
||||
opened.push(open_job(source, binding, layer, expert, &held[Self::index(layer, expert)?])?);
|
||||
}
|
||||
between(pool, &opened)?;
|
||||
for (i, &expert) in experts.iter().enumerate() {
|
||||
if !opened[i].2 {
|
||||
source.retarget(&members[i][..]).map_err(binding_error)?;
|
||||
admit_job(source, &mut held[Self::index(layer, expert)?], &opened[i].0)?;
|
||||
}
|
||||
}
|
||||
source.finish().map_err(binding_error)
|
||||
})?;
|
||||
} else {
|
||||
for (i, &expert) in experts.iter().enumerate() {
|
||||
let at = Self::index(layer, expert)?;
|
||||
let job = binding.with_moe_routed_source(&members[i], binding_error, |source| {
|
||||
let job = open_job(source, binding, layer, expert, &held[at]);
|
||||
let finish = source.finish().map_err(binding_error);
|
||||
job.and_then(|job| finish.map(|()| job))
|
||||
})?;
|
||||
opened.push(job);
|
||||
}
|
||||
between(pool, &opened)?;
|
||||
for (i, &expert) in experts.iter().enumerate() {
|
||||
if !opened[i].2 {
|
||||
let at = Self::index(layer, expert)?;
|
||||
binding.with_moe_routed_source(&members[i], binding_error, |source| {
|
||||
let admitted = admit_job(source, &mut held[at], &opened[i].0);
|
||||
let finish = source.finish().map_err(binding_error);
|
||||
admitted.and_then(|()| finish)
|
||||
})?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(opened)
|
||||
}
|
||||
}
|
||||
|
||||
/// The all-CPU expert tier over the pinned model's mapped routed weights.
|
||||
@@ -230,10 +399,21 @@ impl<'a> CpuExpertPool<'a> {
|
||||
PoolPath::Legacy => None,
|
||||
PoolPath::Direct | PoolPath::Crosscheck => {
|
||||
let pool = DirectCpuPool::new(workers).map_err(|e| runtime_error(native_cpu_error(e)))?;
|
||||
let mut admitted = Vec::new();
|
||||
admitted.try_reserve_exact(48 * EXPERTS as usize).map_err(|_| Error::InputAllocation)?;
|
||||
admitted.resize_with(48 * EXPERTS as usize, Admission::default);
|
||||
Some(DirectTier { pool, admitted })
|
||||
let table = 48 * EXPERTS as usize;
|
||||
let mut held = Vec::new();
|
||||
held.try_reserve_exact(table).map_err(|_| Error::InputAllocation)?;
|
||||
held.resize_with(table, || None);
|
||||
let mut routes = Vec::new();
|
||||
routes.try_reserve_exact(table).map_err(|_| Error::InputAllocation)?;
|
||||
routes.resize_with(table, || None);
|
||||
let group_fence = std::env::var("LELEKA_CPU_POOL_FENCE").as_deref() != Ok("job");
|
||||
if !group_fence {
|
||||
eprintln!("leleka-serve cpu expert pool: one source fence per job (LELEKA_CPU_POOL_FENCE=job)");
|
||||
}
|
||||
// Opt-in, like the Original's: on the 8-core laptop with a warm page cache it measured no gain, and
|
||||
// its router GEMVs (~0.7 ms per layer) compete with the workers for the cores.
|
||||
let lookahead_enabled = std::env::var("LELEKA_CPU_POOL_LOOKAHEAD").as_deref() == Ok("on");
|
||||
Some(DirectTier { pool, held, routes, group_fence, lookahead_enabled, lookahead: None, next_resident: vec![false; EXPERTS as usize] })
|
||||
}
|
||||
};
|
||||
let legacy = match path {
|
||||
@@ -325,47 +505,61 @@ impl CpuExpertPool<'_> {
|
||||
let layer = rows.layer as u32;
|
||||
let count = rows.ids.len() / TOP_K;
|
||||
let tier = self.direct.as_mut().ok_or(Error::IdentityMismatch)?;
|
||||
let mut sources: Vec<[ResidentExpertBankSpan; 3]> = Vec::new();
|
||||
sources.try_reserve_exact(plan.len()).map_err(|_| Error::InputAllocation)?;
|
||||
let mut formats = None;
|
||||
let mut ready: Vec<bool> = Vec::new();
|
||||
ready.try_reserve_exact(plan.len()).map_err(|_| Error::InputAllocation)?;
|
||||
let mut mapped = false;
|
||||
if let Some(lookahead) = &tier.lookahead {
|
||||
let resident = &tier.next_resident;
|
||||
lookahead.submit(rows.layer, rows.activation, |e| resident[e]);
|
||||
}
|
||||
tier.next_resident.fill(false);
|
||||
let mut ids: Vec<u32> = Vec::new();
|
||||
ids.try_reserve_exact(plan.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for job in plan {
|
||||
let expert = u32::try_from(job.expert).map_err(|_| Error::InvalidExpert)?;
|
||||
let admitted = tier.admitted.get_mut(layer as usize * EXPERTS as usize + expert as usize).ok_or(Error::InvalidExpert)?;
|
||||
let (spans, format, admitted_now) = open_expert(binding, layer, expert, admitted, false)?;
|
||||
if *formats.get_or_insert(format) != format {
|
||||
ids.push(u32::try_from(job.expert).map_err(|_| Error::InvalidExpert)?);
|
||||
}
|
||||
let mut fetch_ms = 0.0f64;
|
||||
let opened = tier.open_group(binding, layer, &ids, |pool, opened| {
|
||||
let mapped = opened.iter().any(|(spans, _, _)| spans.iter().any(ResidentExpertBankSpan::file_mapped));
|
||||
let Some(&(_, (gu, down), _)) = opened.first() else { return Ok(()) };
|
||||
if mapped {
|
||||
// The file-mapped source (the Original's --mmap-experts): every page of the group's experts is
|
||||
// advised and faulted in on all workers at once, before the admission scans and the compute.
|
||||
let started = window_trace::now();
|
||||
let mut refs: Vec<BorrowedExpert<'_>> = Vec::new();
|
||||
refs.try_reserve_exact(opened.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for (spans, _, _) in opened {
|
||||
refs.push(BorrowedExpert { gate: spans[0].bytes(), up: spans[1].bytes(), down: spans[2].bytes(), pairs: &[] });
|
||||
}
|
||||
for chunk in refs.chunks(leleka_native_cpu_expert::MAX_JOBS) {
|
||||
pool.prefetch(gu, down, chunk).map_err(|e| runtime_error(native_cpu_error(e)))?;
|
||||
}
|
||||
fetch_ms = started.map_or(0.0, |t| t.elapsed().as_secs_f64() * 1e3);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
if tier.lookahead_enabled && tier.lookahead.is_none() && opened.iter().any(|(s, _, _)| s.iter().any(ResidentExpertBankSpan::file_mapped)) {
|
||||
// Once: the routers' BF16 host copies and the bank layout of every layer, then the thread.
|
||||
tier.lookahead_enabled = false;
|
||||
match tier.start_lookahead(binding) {
|
||||
Ok(lookahead) => {
|
||||
eprintln!("leleka-serve cpu expert pool: router lookahead on (mapped experts, LELEKA_CPU_POOL_LOOKAHEAD=on)");
|
||||
tier.lookahead = Some(lookahead);
|
||||
}
|
||||
Err(e) => eprintln!("leleka-serve cpu expert pool: WARNING: router lookahead not started ({e:?})"),
|
||||
}
|
||||
}
|
||||
let mut formats = None;
|
||||
for (_, format, _) in &opened {
|
||||
if *formats.get_or_insert(*format) != *format {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
ready.push(admitted_now);
|
||||
mapped |= spans.iter().any(ResidentExpertBankSpan::file_mapped);
|
||||
sources.push(spans);
|
||||
}
|
||||
let mut experts: Vec<BorrowedExpert<'_>> = Vec::new();
|
||||
experts.try_reserve_exact(plan.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for (job, spans) in plan.iter().zip(&sources) {
|
||||
for (job, (spans, _, _)) in plan.iter().zip(&opened) {
|
||||
experts.push(BorrowedExpert { gate: spans[0].bytes(), up: spans[1].bytes(), down: spans[2].bytes(), pairs: &job.pairs });
|
||||
}
|
||||
window_trace::lap(window_trace::PREPARE, clock);
|
||||
if let (true, Some((gu, down))) = (mapped, formats) {
|
||||
// The file-mapped source (the Original's --mmap-experts): every page of the group's experts is
|
||||
// advised and faulted in on all workers at once, before the admission scans and the compute.
|
||||
for chunk in experts.chunks(leleka_native_cpu_expert::MAX_JOBS) {
|
||||
tier.pool.prefetch(gu, down, chunk).map_err(|e| runtime_error(native_cpu_error(e)))?;
|
||||
}
|
||||
}
|
||||
window_trace::lap(window_trace::FETCH, clock);
|
||||
// First use: admit every row of the experts not yet admitted (their pages are now resident).
|
||||
for ((job, spans), _) in plan.iter().zip(&sources).zip(&ready).filter(|(_, ready)| !**ready) {
|
||||
let expert = job.expert as u32;
|
||||
let admitted = tier.admitted.get_mut(layer as usize * EXPERTS as usize + expert as usize).ok_or(Error::InvalidExpert)?;
|
||||
let (again, _, _) = open_expert(binding, layer, expert, admitted, true)?;
|
||||
if again.iter().zip(spans).any(|(a, b)| a.bytes().as_ptr() != b.bytes().as_ptr() || a.bytes().len() != b.bytes().len()) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
window_trace::lap(window_trace::PREPARE, clock);
|
||||
window_trace::add(window_trace::PREPARE, -fetch_ms);
|
||||
window_trace::add(window_trace::FETCH, fetch_ms);
|
||||
let mut failure = None;
|
||||
let written = sink.with_output(|out| {
|
||||
if out.len() != count * TOP_K * HIDDEN {
|
||||
@@ -393,13 +587,25 @@ impl CpuExpertPool<'_> {
|
||||
sink_result(written, failure)
|
||||
}
|
||||
|
||||
/// The PCIe tier's source spans of `expert`, through the same per-call validation and one-time row
|
||||
/// admission as the CPU's own experts; `None` on the legacy path (the caller keeps its full scan).
|
||||
pub(in crate::qwen_forward) fn admitted_spans(&mut self, layer: u32, expert: u32) -> Option<Result<[ResidentExpertBankSpan; 3]>> {
|
||||
/// The VRAM tier tells the router lookahead which experts of `layer` it holds (before each group).
|
||||
pub(in crate::qwen_forward) fn set_next_resident(&mut self, resident: impl Fn(usize) -> bool) {
|
||||
if let Some(tier) = self.direct.as_mut().filter(|t| t.lookahead.is_some()) {
|
||||
for (e, slot) in tier.next_resident.iter_mut().enumerate() {
|
||||
*slot = resident(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(in crate::qwen_forward) fn lookahead_running(&self) -> bool {
|
||||
self.direct.as_ref().is_some_and(|t| t.lookahead.is_some())
|
||||
}
|
||||
|
||||
/// The PCIe tier's (or an adaptive swap's) source spans of `experts` of `layer`, through the same
|
||||
/// per-job validation and one-time row admission as the CPU's own experts, under one source fence;
|
||||
/// `None` on the legacy path (the caller keeps its per-expert full scan).
|
||||
pub(in crate::qwen_forward) fn admitted_spans(&mut self, layer: u32, experts: &[u32]) -> Option<Result<Vec<[ResidentExpertBankSpan; 3]>>> {
|
||||
let binding = self.binding;
|
||||
let tier = self.direct.as_mut()?;
|
||||
let admitted = tier.admitted.get_mut(layer as usize * EXPERTS as usize + expert as usize)?;
|
||||
Some(admitted_expert(binding, layer, expert, admitted).map(|(spans, _)| spans))
|
||||
Some(tier.open_group(binding, layer, experts, |_, _| Ok(())).map(|opened| opened.into_iter().map(|(spans, _, _)| spans).collect()))
|
||||
}
|
||||
|
||||
/// The legacy path's results: owned copies, batches of `JOBS_PER_BATCH` joined in turn, every result
|
||||
@@ -505,84 +711,17 @@ impl CpuExpertPool<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// One routed expert's resident source, opened and validated on every call (binding, the actual
|
||||
/// gate/up/down descriptors of exactly this layer and expert, their formats, the bank spans) while its
|
||||
/// encoded rows are admitted only on first use: `admitted` retains the checked spans, so the bank bytes
|
||||
/// they address stay alive and immutable, and a later span at the same address needs no new scan.
|
||||
pub(in crate::qwen_forward) fn admitted_expert(
|
||||
binding: &ModelBinding,
|
||||
layer: u32,
|
||||
expert: u32,
|
||||
admitted: &mut Admission,
|
||||
) -> Result<([ResidentExpertBankSpan; 3], (GateUpFormat, DownFormat))> {
|
||||
let (spans, format, _) = open_expert(binding, layer, expert, admitted, true)?;
|
||||
Ok((spans, format))
|
||||
}
|
||||
|
||||
/// `admitted_expert` that, with `admit` false, leaves a not yet admitted expert unscanned and says so
|
||||
/// (third value false): the caller prefetches it and admits it before any consumer reads it.
|
||||
fn open_expert(
|
||||
binding: &ModelBinding,
|
||||
layer: u32,
|
||||
expert: u32,
|
||||
admission: &mut Admission,
|
||||
admit: bool,
|
||||
) -> Result<([ResidentExpertBankSpan; 3], (GateUpFormat, DownFormat), bool)> {
|
||||
if layer >= 48 || expert >= EXPERTS as u32 {
|
||||
return Err(Error::InvalidExpert);
|
||||
}
|
||||
if admission.route.is_none() {
|
||||
// A route that selects `expert` in slot 0 (cache_original_prompt.rs `original_expert_spans`).
|
||||
let selected = std::array::from_fn(|i| (expert + i as u32) % EXPERTS as u32);
|
||||
admission.route = Some(binding.moe_expert_weights(layer, selected).map_err(binding_error)?);
|
||||
}
|
||||
let Admission { spans: admitted, route } = admission;
|
||||
let bound = route.as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
let members = [(bound, 0)];
|
||||
binding.with_moe_routed_source(&members, binding_error, |source| {
|
||||
let operation = (|| {
|
||||
source.validate_binding(binding).map_err(binding_error)?;
|
||||
let keys = [
|
||||
source.descriptor(0, MoeMatrixRole::Gate).map_err(binding_error)?,
|
||||
source.descriptor(0, MoeMatrixRole::Up).map_err(binding_error)?,
|
||||
source.descriptor(0, MoeMatrixRole::Down).map_err(binding_error)?,
|
||||
];
|
||||
if keys.iter().any(|k| k.layer != layer || k.expert != Some(expert)) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let format = validate_triplet(keys).map_err(runtime_error)?;
|
||||
let spans = [
|
||||
source.bank_span(0, MoeMatrixRole::Gate).map_err(binding_error)?,
|
||||
source.bank_span(0, MoeMatrixRole::Up).map_err(binding_error)?,
|
||||
source.bank_span(0, MoeMatrixRole::Down).map_err(binding_error)?,
|
||||
];
|
||||
let same = |held: &[ResidentExpertBankSpan; 3]| {
|
||||
held.iter().zip(&spans).all(|(a, b)| a.bytes().as_ptr() == b.bytes().as_ptr() && a.bytes().len() == b.bytes().len())
|
||||
};
|
||||
if !admitted.as_ref().is_some_and(same) {
|
||||
*admitted = None;
|
||||
if !admit {
|
||||
return Ok((spans, format, false));
|
||||
}
|
||||
// First use (or a different span): admit every row of the actual matrices.
|
||||
let checked = [
|
||||
source.mapped_span(0, MoeMatrixRole::Gate).map_err(binding_error)?,
|
||||
source.mapped_span(0, MoeMatrixRole::Up).map_err(binding_error)?,
|
||||
source.mapped_span(0, MoeMatrixRole::Down).map_err(binding_error)?,
|
||||
];
|
||||
if !same(&checked) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
*admitted = Some(checked);
|
||||
}
|
||||
Ok((spans, format, true))
|
||||
})();
|
||||
let finish = source.finish().map_err(binding_error);
|
||||
match operation {
|
||||
Err(e) => Err(e),
|
||||
Ok(v) => finish.map(|()| v),
|
||||
impl Drop for DirectTier {
|
||||
fn drop(&mut self) {
|
||||
if let Some(lookahead) = &self.lookahead {
|
||||
let s = lookahead.stats();
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
eprintln!(
|
||||
"leleka-serve router lookahead: {} layers submitted, {} skipped, {} experts warmed, {:.1} ms busy",
|
||||
s.submitted.load(Relaxed), s.skipped.load(Relaxed), s.predicted.load(Relaxed), s.busy_us.load(Relaxed) as f64 / 1e3
|
||||
);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn sink_result(written: leleka_cuda_driver::Result<()>, failure: Option<Error>) -> Result<()> {
|
||||
|
||||
@@ -397,17 +397,21 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> {
|
||||
let profile_spans = super::original_serve_profile::span("pool.spans");
|
||||
let mut spans = Vec::new();
|
||||
spans.try_reserve_exact(split.pcie_experts.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for &e in &split.pcie_experts {
|
||||
// The direct CPU tier's admission (rows scanned once per expert) serves the PCIe sources too.
|
||||
match self.cpu.admitted_spans(layer as u32, e) {
|
||||
Some(admitted) => {
|
||||
let admitted = admitted?;
|
||||
if !self.bank.eligible(&admitted) {
|
||||
// The direct CPU tier's admission (one fence per group, rows scanned once per expert) serves the
|
||||
// PCIe sources too; the legacy path keeps the per-expert full scan.
|
||||
match self.cpu.admitted_spans(layer as u32, &split.pcie_experts) {
|
||||
Some(admitted) => {
|
||||
for spans_of in admitted? {
|
||||
if !self.bank.eligible(&spans_of) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
spans.push(admitted);
|
||||
spans.push(spans_of);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
for &e in &split.pcie_experts {
|
||||
spans.push(self.moe.original_expert_spans(self.binding, layer as u32, e)?);
|
||||
}
|
||||
None => spans.push(self.moe.original_expert_spans(self.binding, layer as u32, e)?),
|
||||
}
|
||||
}
|
||||
super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::PCIE_SPANS, &mut clock);
|
||||
@@ -427,6 +431,10 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> {
|
||||
_ => stats.cpu_entries += 1,
|
||||
}
|
||||
}
|
||||
if self.cpu.lookahead_running() && layer + 1 < LAYERS {
|
||||
let next = layer + 1;
|
||||
self.cpu.set_next_resident(|e| cache.resident_slot(next, e).is_some());
|
||||
}
|
||||
super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::GPU_SPLIT, &mut clock);
|
||||
let _p = super::original_serve_profile::span("pool.cpu");
|
||||
self.cpu.run_entries(rows, sink, Some(&include))
|
||||
@@ -453,9 +461,9 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> {
|
||||
let swaps = choose_swaps(&self.state.usage, |l, e| cache.resident_slot(l, e).is_some(), self.adapt_swaps);
|
||||
for swap in &swaps {
|
||||
let slot = self.cache.resident_slot(swap.layer, swap.outgoing).ok_or(Error::IdentityMismatch)?;
|
||||
let spans = match self.cpu.admitted_spans(swap.layer as u32, swap.incoming as u32) {
|
||||
let spans = match self.cpu.admitted_spans(swap.layer as u32, &[swap.incoming as u32]) {
|
||||
Some(admitted) => {
|
||||
let admitted = admitted?;
|
||||
let admitted = admitted?.pop().ok_or(Error::IdentityMismatch)?;
|
||||
if !self.bank.eligible(&admitted) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
|
||||
@@ -13,8 +13,16 @@ use std::time::{Duration, Instant};
|
||||
pub(crate) enum Stage {
|
||||
/// Host input staging of every row (token embedding, KAR/PLE inputs).
|
||||
Input,
|
||||
/// Token embedding rows of the input staging (KAR path).
|
||||
InputEmbedding,
|
||||
/// PLE rows of the input staging (KAR gather, KAR path).
|
||||
InputPle,
|
||||
/// Row source keys and the initial R/PLE upload.
|
||||
Initialize,
|
||||
/// Row source keys and their finite checks.
|
||||
InitSources,
|
||||
/// Initial R/PLE staging and upload.
|
||||
InitUpload,
|
||||
/// Layer-one PLE application and its history.
|
||||
Ple,
|
||||
/// Chronological per-row session validation of every phase.
|
||||
@@ -23,6 +31,12 @@ pub(crate) enum Stage {
|
||||
AttnRead,
|
||||
/// GDN mixer (projections, conv, recurrence, out) incl. the following GR injection.
|
||||
Gdn,
|
||||
/// GDN layer state staging: the chunk owner's prior upload, scratch and finite guard.
|
||||
GdnStateIn,
|
||||
/// GDN projections, conv, recurrence and output of the chunk.
|
||||
GdnCompute,
|
||||
/// GDN end state download, mirror adoption and journal staging.
|
||||
GdnStateOut,
|
||||
/// QSA mixer (index, selection, attention, KV) incl. the following GR injection.
|
||||
Qsa,
|
||||
/// GR read before the FFN.
|
||||
@@ -50,8 +64,9 @@ pub(crate) enum Stage {
|
||||
/// Expert-cache slot loan for the chunk's arena (expert tier only).
|
||||
Lend,
|
||||
}
|
||||
const STAGES: [Stage; 19] = [
|
||||
Stage::Input, Stage::Initialize, Stage::Ple, Stage::Validate, Stage::AttnRead, Stage::Gdn, Stage::Qsa,
|
||||
const STAGES: [Stage; 26] = [
|
||||
Stage::Input, Stage::InputEmbedding, Stage::InputPle, Stage::Initialize, Stage::InitSources, Stage::InitUpload, Stage::Ple, Stage::Validate, Stage::AttnRead, Stage::Gdn, Stage::GdnStateIn,
|
||||
Stage::GdnCompute, Stage::GdnStateOut, Stage::Qsa,
|
||||
Stage::FfnRead, Stage::Moe, Stage::MoePrepare, Stage::MoeSpans, Stage::MoeRing, Stage::MoeFinish, Stage::Inject,
|
||||
Stage::Final, Stage::DraftKv, Stage::FinishPreview, Stage::Publish, Stage::Lend,
|
||||
];
|
||||
@@ -59,11 +74,18 @@ impl Stage {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Input => "input",
|
||||
Self::InputEmbedding => "input.embedding",
|
||||
Self::InputPle => "input.ple",
|
||||
Self::Initialize => "init",
|
||||
Self::InitSources => "init.sources",
|
||||
Self::InitUpload => "init.upload",
|
||||
Self::Ple => "ple",
|
||||
Self::Validate => "validate",
|
||||
Self::AttnRead => "attn_read",
|
||||
Self::Gdn => "gdn",
|
||||
Self::GdnStateIn => "gdn.state_in",
|
||||
Self::GdnCompute => "gdn.compute",
|
||||
Self::GdnStateOut => "gdn.state_out",
|
||||
Self::Qsa => "qsa",
|
||||
Self::FfnRead => "ffn_read",
|
||||
Self::Moe => "moe",
|
||||
@@ -170,6 +192,10 @@ pub(crate) fn end_chunk(first: u64, tokens: usize) {
|
||||
let covered: Duration = top.iter().map(|s| acc[s.index()]).sum();
|
||||
line.push_str(&format!(" other={:.1}", ms(total.saturating_sub(covered))));
|
||||
eprintln!("{line}");
|
||||
let commands = leleka_cuda_driver::command_profile::take_report();
|
||||
if !commands.is_empty() {
|
||||
eprintln!("PREFILL-COMMANDS first={first} {commands}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -193,11 +193,11 @@ impl<'source,'arena,'loan,'ctx> PromptDeviceRows<'source,'arena,'loan,'ctx>{
|
||||
let sources=Sources{binding:binding.identity(),context,rows,role:GrRole::Attention(0),validated:0};sources.validate(binding,cache)?;
|
||||
// Only initial real source staging: Original also uploads initial R
|
||||
// and PLE embeddings. Later layer phases retain this same device R.
|
||||
let mut streams=Vec::new();streams.try_reserve_exact(sources.rows.len()*10240).map_err(|_|Error::InputAllocation)?;
|
||||
let mut embedding=Vec::new();embedding.try_reserve_exact(sources.rows.len()*2560).map_err(|_|Error::InputAllocation)?;
|
||||
for s in &sources.rows{streams.extend_from_slice(s.input.streams().values());embedding.extend_from_slice(s.input.ple_embedding());}
|
||||
// The driver stages every row's streams and PLE embedding in place (one pass, same bytes and refusals).
|
||||
let mut slices=Vec::new();slices.try_reserve_exact(sources.rows.len()).map_err(|_|Error::InputAllocation)?;
|
||||
for s in &sources.rows{slices.push((s.input.streams().values(),s.input.ple_embedding()));}
|
||||
let result=(||{let mut workspace=cache.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?;
|
||||
producer.initialize(lease,&mut workspace,&streams,&embedding).map_err(micro_driver_error)})();
|
||||
producer.initialize_rows(lease,&mut workspace,&slices).map_err(micro_driver_error)})();
|
||||
if producer.is_failed(){cache.transport_failure_flag(binding,context)?.set(true)}
|
||||
let device=result?;sources.validate(binding,cache)?;
|
||||
if let Some(phase)=sources.original_phase()?{phase.initialize(sources.rows.len())?;}
|
||||
@@ -367,13 +367,20 @@ fn produce_original_gdn<'arena,'loan,'ctx>(binding:&ModelBinding,dense:&DenseWei
|
||||
txn:&OriginalPromptTxn<'_, '_>,context:&'ctx Context<'ctx>,layer:LayerId,
|
||||
read:OriginalDeviceGrRead<'arena,'loan,'ctx>,gdn:&mut leleka_cuda_driver::OriginalGdnPromptDevice<'ctx>,
|
||||
)->Result<OriginalDeviceBlock<'arena,'loan,'ctx>>{
|
||||
use super::prefill_profile::{span,Stage as P,Drain};
|
||||
let drain=Some(context as &dyn Drain);
|
||||
let state_in=span(P::GdnStateIn,drain);
|
||||
let prior=txn.gdn_prior(layer)?;
|
||||
let(start,rows)=super::session::chunk::GdnChunkStart::from_original_prompt(txn,layer,&prior)?;
|
||||
let mut owner=super::gdn::chunk_device::GdnChunkDevice::new(binding,context,dense,start.clone())?;
|
||||
drop(state_in);
|
||||
let compute=span(P::GdnCompute,drain);
|
||||
let mut workspace=dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?;
|
||||
let(block,edges)=super::gdn::GdnStage::produce_prompt_device(binding,layer,dense,context,
|
||||
&mut owner,rows,read,gdn,&mut workspace)?;
|
||||
drop(workspace);
|
||||
drop(compute);
|
||||
let _state_out=span(P::GdnStateOut,drain);
|
||||
let seal=super::session::chunk::GdnChunkSeal::from_original_prompt(txn,&start,edges)?;
|
||||
let next=owner.finish(seal,binding,dense)?;txn.stage_gdn(&prior,next)?;Ok(block)
|
||||
}
|
||||
|
||||
@@ -1846,9 +1846,20 @@ pub struct RoutedMoeSourceScope<'source> {
|
||||
roles: &'source BTreeMap<TensorRole, ResolvedTensor>,
|
||||
layer: u8,
|
||||
expert: u32,
|
||||
expert_count: u32,
|
||||
resident_experts: Option<&'source expert_source_bank::ResidentExpertBank>,
|
||||
}
|
||||
impl RoutedMoeSourceScope<'_> {
|
||||
/// Point the same loan at another expert of its layer: a group fence (one source observation at
|
||||
/// begin and one at finish) covering every expert of a layer group. Every request after this still
|
||||
/// rechecks its exact indexed tensor, as before.
|
||||
pub fn retarget(&mut self, expert: u32) -> Result<(), BindingError> {
|
||||
if expert >= self.expert_count {
|
||||
return Err(BindingError::Range("routed_moe_source"));
|
||||
}
|
||||
self.expert = expert;
|
||||
Ok(())
|
||||
}
|
||||
fn role(&self, role: LayerRole) -> Result<TensorRole, BindingError> {
|
||||
if !matches!(
|
||||
role,
|
||||
@@ -1990,6 +2001,7 @@ impl Qwen4ExpArtifact {
|
||||
roles: &self.roles,
|
||||
layer,
|
||||
expert,
|
||||
expert_count: self.topology.expert_count,
|
||||
resident_experts: self.resident_experts.as_ref(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -46,6 +46,7 @@ pub mod rust_bench;
|
||||
mod rust_quant_grids;
|
||||
#[allow(unsafe_code)] mod rust_weight_iq;
|
||||
pub use rust_kq::{bf16_rows,bf16_rows_multi};
|
||||
pub use rust_platform::advise_will_need;
|
||||
|
||||
const H: usize = 2560;
|
||||
const FF: usize = 640;
|
||||
@@ -121,18 +122,34 @@ pub const MAX_OUT_ROWS: usize = 128;
|
||||
/// beside the workers (pool.cpp `host_works_`), so nothing crosses a thread boundary by value and every
|
||||
/// borrow ends when `compute_group` returns. The encoded bytes are the caller's admitted matrices: this
|
||||
/// crate checks extents, pair bounds, disjoint destinations and finite inputs/outputs, never the source.
|
||||
pub struct DirectCpuPool { native: ffi::NativePool, workers: usize, failed: bool, _actor: PhantomData<Rc<()>> }
|
||||
pub struct DirectCpuPool {
|
||||
native: ffi::NativePool, workers: usize, failed: bool,
|
||||
/// session.cpp `SessionLoopScratch`: the caller (the host loop, which drains beside the workers) is pinned
|
||||
/// once to the first physical core, the one the workers leave free; its previous mask is restored on drop.
|
||||
pin_host: bool, host_mask: Option<[usize; 16]>,
|
||||
_actor: PhantomData<Rc<()>>,
|
||||
}
|
||||
impl DirectCpuPool {
|
||||
pub fn new(workers: i32) -> Result<Self> {
|
||||
let native = ffi::NativePool::new(workers)?;
|
||||
let workers = native.workers()?;
|
||||
Ok(Self { native, workers, failed: false, _actor: PhantomData })
|
||||
let pin_host = std::env::var("LELEKA_CPU_POOL_PIN_HOST").as_deref() != Ok("off");
|
||||
Ok(Self { native, workers, failed: false, pin_host, host_mask: None, _actor: PhantomData })
|
||||
}
|
||||
fn pin_caller(&mut self) {
|
||||
if self.pin_host && self.host_mask.is_none() {
|
||||
if let (Some(mask), Some(&core)) = (rust_platform::current_affinity(), rust_platform::cores(false).first()) {
|
||||
self.host_mask = Some(mask);
|
||||
rust_platform::pin(core);
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn workers(&self) -> usize { self.workers }
|
||||
/// Compute every expert of `group` into `out` in one two-phase dispatch (at most `MAX_JOBS` experts,
|
||||
/// all of the same gate/up and down formats). Only the pairs' rows of `out` are written.
|
||||
pub fn compute_group(&mut self, gu: GateUpFormat, down: DownFormat, group: &BorrowedGroup<'_>, out: &mut [f32]) -> Result<()> {
|
||||
if self.failed { return Err(Error::Closed); }
|
||||
self.pin_caller();
|
||||
let result = self.native.compute_borrowed(gu.kind(), down.kind(), group, out);
|
||||
if matches!(result, Err(Error::NativeFailure | Error::Closed)) { self.failed = true; }
|
||||
result
|
||||
@@ -147,6 +164,12 @@ impl DirectCpuPool {
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DirectCpuPool {
|
||||
fn drop(&mut self) {
|
||||
if let Some(mask) = self.host_mask.take() { rust_platform::restore_affinity(&mask); }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CompletedJob { values: Box<[f32]> }
|
||||
impl CompletedJob { pub fn into_values(self) -> Box<[f32]> { self.values } }
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ fn u32(b:&[u8],o:usize)->u32 {u32::from_le_bytes(b[o..o+4].try_into().unwrap())}
|
||||
pub(super) fn format_bytes(t:i32)->usize {match t{16=>66,17=>74,18=>98,21=>110,22=>82,23=>136,_=>unreachable!()}}
|
||||
fn factor(t:i32)->f32 {match t {16|17|22=>0.125,18=>0.25,21|23=>1.0,_=>unreachable!()}}
|
||||
// Whole 32-value half: magnitude bytes, literal signs and 16-value integer scales.
|
||||
#[inline(always)]
|
||||
fn decode(t:i32,b:&[u8],j:usize,h:usize)->([u8;32],u32,[i16;16]) {
|
||||
let mut g=[0u8;32];let mut signs=0u32;let (s0,s1);
|
||||
match t {
|
||||
@@ -35,18 +36,26 @@ pub(super) unsafe fn dot_multi256(t:i32,row:&[u8],ys:&[&[Q8K]],out:&mut [f32]) {
|
||||
}
|
||||
for (k,r) in out.iter_mut().enumerate(){*r=hsum_original(accf[k]);}
|
||||
}}
|
||||
/// The multi-token IQ kernel, specialised on the format and the token count (iq_avx512.cpp templates its
|
||||
/// `row_dot<TY, NT>` the same way): the same operations in the same order per token, so the same bits.
|
||||
#[target_feature(enable="avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
pub(super) unsafe fn dot_multi512(t:i32,row:&[u8],ys:&[&[Q8K]],out:&mut [f32]) {unsafe {
|
||||
assert!(ys.len()<=8&&ys.len()==out.len());let nb=ys[0].len();assert_eq!(row.len(),nb*format_bytes(t));let mut af=[_mm512_setzero_ps();8];let zero=_mm512_setzero_si512();
|
||||
macro_rules! by_n {($T:literal)=>{match ys.len(){1=>dot_multi512_tn::<$T,1>(row,ys,out),2=>dot_multi512_tn::<$T,2>(row,ys,out),3=>dot_multi512_tn::<$T,3>(row,ys,out),4=>dot_multi512_tn::<$T,4>(row,ys,out),5=>dot_multi512_tn::<$T,5>(row,ys,out),6=>dot_multi512_tn::<$T,6>(row,ys,out),7=>dot_multi512_tn::<$T,7>(row,ys,out),8=>dot_multi512_tn::<$T,8>(row,ys,out),_=>panic!("dot_multi512: 1..=8 tokens")}}}
|
||||
match t {16=>by_n!(16),17=>by_n!(17),18=>by_n!(18),21=>by_n!(21),22=>by_n!(22),_=>unreachable!()}
|
||||
}}
|
||||
#[target_feature(enable="avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
unsafe fn dot_multi512_tn<const T:i32,const N:usize>(row:&[u8],ys:&[&[Q8K]],out:&mut [f32]) {unsafe {
|
||||
let t=T;
|
||||
assert!(N<=8&&ys.len()==N&&out.len()==N);let nb=ys[0].len();assert_eq!(row.len(),nb*format_bytes(t));let mut af=[_mm512_setzero_ps();8];let zero=_mm512_setzero_si512();
|
||||
for i in 0..nb {let b=&row[i*format_bytes(t)..][..format_bytes(t)];prefetch(b.as_ptr());let mut ai=[_mm512_setzero_si512();8];
|
||||
for j in 0..4 {let (g0,s0,sc0)=decode(t,b,j,0);let (g1,s1,sc1)=decode(t,b,j,1);let mut g=[0u8;64];g[..32].copy_from_slice(&g0);g[32..].copy_from_slice(&g1);let mut sc=[0i16;32];sc[..16].copy_from_slice(&sc0);sc[16..].copy_from_slice(&sc1);
|
||||
let gv=if super::rust_simd::dispatch().gather&&(t==18||t==21){let q=&b[2+16*j..];let mut idx=_mm512_cvtepu8_epi32(_mm_loadu_si128(q.as_ptr().cast()));if t==21{let m=b[66+2*j]as u16|((b[67+2*j]as u16)<<8);idx=_mm512_mask_add_epi32(idx,m,idx,_mm512_set1_epi32(256));}_mm512_i32gather_epi32::<4>(idx,if t==18{IQ3XXS_GRID.as_ptr().cast()}else{IQ3S_GRID.as_ptr().cast()})}else{_mm512_loadu_si512(g.as_ptr().cast())};
|
||||
let sv=_mm512_loadu_si512(sc.as_ptr().cast());let m=s0 as u64|((s1 as u64)<<32);
|
||||
for (k,y) in ys.iter().enumerate(){let v=_mm512_loadu_si512(y[i].qs.as_ptr().add(64*j).cast());let sy=_mm512_mask_sub_epi8(v,m,zero,v);ai[k]=_mm512_add_epi32(ai[k],_mm512_madd_epi16(_mm512_maddubs_epi16(gv,sy),sv));}
|
||||
for k in 0..N {let y=ys[k];let v=_mm512_loadu_si512(y[i].qs.as_ptr().add(64*j).cast());let sy=_mm512_mask_sub_epi8(v,m,zero,v);ai[k]=_mm512_add_epi32(ai[k],_mm512_madd_epi16(_mm512_maddubs_epi16(gv,sy),sv));}
|
||||
}
|
||||
let dx=half(u16(b,0))*factor(t);for (k,y) in ys.iter().enumerate(){af[k]=_mm512_fmadd_ps(_mm512_set1_ps(dx*y[i].d),_mm512_cvtepi32_ps(ai[k]),af[k]);}
|
||||
let dx=half(u16(b,0))*factor(t);for k in 0..N {let y=ys[k];af[k]=_mm512_fmadd_ps(_mm512_set1_ps(dx*y[i].d),_mm512_cvtepi32_ps(ai[k]),af[k]);}
|
||||
}
|
||||
for (k,r) in out.iter_mut().enumerate(){*r=_mm512_reduce_add_ps(af[k]);}
|
||||
for k in 0..N {out[k]=_mm512_reduce_add_ps(af[k]);}
|
||||
}}
|
||||
// GGML AVX2 T1: two alternating exact integer accumulators, factor AFTER final reduction.
|
||||
#[target_feature(enable="avx2,fma,f16c")]
|
||||
@@ -62,10 +71,16 @@ unsafe fn iq4xs(row:&[u8],y:&[Q8K])->f32 {unsafe {
|
||||
af=_mm256_fmadd_ps(_mm256_set1_ps(half(u16(b,0))*y[i].d),_mm256_cvtepi32_ps(_mm256_add_epi32(sums[0],sums[1])),af);
|
||||
}hsum_ggml(af)
|
||||
}}
|
||||
/// IQ4_NL rows specialised on the token count; the same operations in the same order per token.
|
||||
#[target_feature(enable="avx2,fma,f16c")]
|
||||
pub(super) unsafe fn iq4nl(row:&[u8],ys:&[&[Q8Zero]],out:&mut [f32],single:bool) {unsafe {
|
||||
match ys.len(){1=>iq4nl_n::<1>(row,ys,out,single),2=>iq4nl_n::<2>(row,ys,out,single),3=>iq4nl_n::<3>(row,ys,out,single),4=>iq4nl_n::<4>(row,ys,out,single),5=>iq4nl_n::<5>(row,ys,out,single),6=>iq4nl_n::<6>(row,ys,out,single),7=>iq4nl_n::<7>(row,ys,out,single),8=>iq4nl_n::<8>(row,ys,out,single),_=>panic!("iq4nl: 1..=8 tokens")}
|
||||
}}
|
||||
#[target_feature(enable="avx2,fma,f16c")]
|
||||
unsafe fn iq4nl_n<const N:usize>(row:&[u8],ys:&[&[Q8Zero]],out:&mut [f32],single:bool) {unsafe {
|
||||
assert!(N<=8&&ys.len()==N&&out.len()==N);
|
||||
let values=_mm_loadu_si128(KVALUES_IQ4NL.as_ptr().cast());let m4=_mm_set1_epi8(15);let ones=_mm256_set1_epi16(1);let mut af=[[_mm256_setzero_ps();2];8];
|
||||
for (ib,b) in row.chunks_exact(18).enumerate(){prefetch(b.as_ptr());let bits=_mm_loadu_si128(b.as_ptr().add(2).cast());let q=_mm256_inserti128_si256::<1>(_mm256_castsi128_si256(_mm_shuffle_epi8(values,_mm_and_si128(bits,m4))),_mm_shuffle_epi8(values,_mm_and_si128(_mm_srli_epi16::<4>(bits),m4)));let aq=_mm256_sign_epi8(q,q);let dx=half(u16(b,0));
|
||||
for (t,y) in ys.iter().enumerate(){let b=&y[ib];let v=_mm256_loadu_si256(b.qs.as_ptr().cast());let p=_mm256_madd_epi16(_mm256_maddubs_epi16(aq,_mm256_sign_epi8(v,q)),ones);let lane=if single{ib&1}else{0};let d=if single{half(b.d)*dx}else{dx*half(b.d)};af[t][lane]=_mm256_fmadd_ps(_mm256_set1_ps(d),_mm256_cvtepi32_ps(p),af[t][lane]);}
|
||||
}for (t,r) in out.iter_mut().enumerate(){*r=if single{hsum_ggml(_mm256_add_ps(af[t][0],af[t][1]))}else{hsum_original(af[t][0])};}
|
||||
for t in 0..N {let y=ys[t];let b=&y[ib];let v=_mm256_loadu_si256(b.qs.as_ptr().cast());let p=_mm256_madd_epi16(_mm256_maddubs_epi16(aq,_mm256_sign_epi8(v,q)),ones);let lane=if single{ib&1}else{0};let d=if single{half(b.d)*dx}else{dx*half(b.d)};af[t][lane]=_mm256_fmadd_ps(_mm256_set1_ps(d),_mm256_cvtepi32_ps(p),af[t][lane]);}
|
||||
}for t in 0..N {out[t]=if single{hsum_ggml(_mm256_add_ps(af[t][0],af[t][1]))}else{hsum_original(af[t][0])};}
|
||||
}}
|
||||
|
||||
@@ -10,6 +10,7 @@ unsafe extern "C" {
|
||||
fn sched_getaffinity(pid:i32,bytes:usize,set:*mut usize)->i32;
|
||||
fn pthread_self()->usize;
|
||||
fn pthread_setaffinity_np(thread:usize,bytes:usize,set:*const usize)->i32;
|
||||
fn pthread_getaffinity_np(thread:usize,bytes:usize,set:*mut usize)->i32;
|
||||
fn sysconf(name:i32)->i64;
|
||||
fn madvise(addr:*mut u8,len:usize,advice:i32)->i32;
|
||||
}
|
||||
@@ -33,6 +34,14 @@ pub(super) fn cores(skip_first:bool)->Vec<i32> {
|
||||
}
|
||||
/// `madvise(MADV_WILLNEED)` over the pages of `bytes`: the kernel starts reading a file-mapped range in the
|
||||
/// background (expert_source.cpp `warm`). Advice only; a failure changes nothing.
|
||||
/// `madvise(MADV_WILLNEED)` over `[addr, addr+len)` rounded out to pages: advice only, it never reads or
|
||||
/// writes the range, so any address is memory-safe (an unmapped range just fails).
|
||||
pub fn advise_will_need(addr:usize,len:usize) {
|
||||
if len==0{return;}
|
||||
let page=4096usize;let start=addr&!(page-1);let Some(end)=addr.checked_add(len) else {return};
|
||||
// SAFETY: MADV_WILLNEED (3) only schedules readahead; it accesses no memory of this process.
|
||||
unsafe {let _=madvise(start as *mut u8,end-start,3);}
|
||||
}
|
||||
pub(super) fn will_need(bytes:&[u8]) {
|
||||
if bytes.is_empty(){return;}
|
||||
let page=4096usize;let start=bytes.as_ptr() as usize&!(page-1);let end=bytes.as_ptr() as usize+bytes.len();
|
||||
@@ -40,6 +49,16 @@ pub(super) fn will_need(bytes:&[u8]) {
|
||||
// changes the contents or the mapping.
|
||||
unsafe {let _=madvise(start as *mut u8,end-start,3);}
|
||||
}
|
||||
/// The calling thread's affinity mask (to restore after `pin`).
|
||||
pub(super) fn current_affinity()->Option<[usize;16]> {
|
||||
let mut set=[0usize;16];
|
||||
// SAFETY: initialized cpu_set_t-sized mask of the calling thread, no pointer retention.
|
||||
(unsafe {pthread_getaffinity_np(pthread_self(),std::mem::size_of_val(&set),set.as_mut_ptr())}==0).then_some(set)
|
||||
}
|
||||
pub(super) fn restore_affinity(set:&[usize;16]) {
|
||||
// SAFETY: as `pin`; a refusal leaves the thread where it is.
|
||||
unsafe {let _=pthread_setaffinity_np(pthread_self(),std::mem::size_of_val(set),set.as_ptr());}
|
||||
}
|
||||
pub(super) fn pin(core:i32) {
|
||||
if core<0{return;}let mut set=[0usize;16];if core as usize>=1024{return;}set[core as usize/64]|=1usize<<(core as usize%64);
|
||||
// Original intentionally ignores OS affinity refusal; it does not change math.
|
||||
|
||||
@@ -15,13 +15,19 @@ pub(super) unsafe fn dot256(row:&[u8],a:&[&ActQ],r:&mut [f32]) {unsafe {
|
||||
acc[t]=_mm256_fmadd_ps(_mm256_set1_ps(d*a.scale[2*b]),_mm256_cvtepi32_ps(s0),acc[t]);acc[t]=_mm256_fmadd_ps(_mm256_set1_ps(d*a.scale[2*b+1]),_mm256_cvtepi32_ps(s1),acc[t]);corr[t]+=d*(a.hx[2*b]+a.hx[2*b+1]);}}
|
||||
for (t,r) in r.iter_mut().enumerate(){let h=_mm_add_ps(_mm256_castps256_ps128(acc[t]),_mm256_extractf128_ps::<1>(acc[t]));let s=_mm_add_ps(h,_mm_movehl_ps(h,h));*r=_mm_cvtss_f32(_mm_add_ss(s,_mm_movehdup_ps(s)))-corr[t];}
|
||||
}}
|
||||
/// The Q2_0 rows specialised on the token count; the same operations in the same order per token.
|
||||
#[target_feature(enable="avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
pub(super) unsafe fn dot512(row:&[u8],a:&[&ActQ],r:&mut [f32]) {unsafe {
|
||||
match a.len(){1=>dot512_n::<1>(row,a,r),2=>dot512_n::<2>(row,a,r),3=>dot512_n::<3>(row,a,r),4=>dot512_n::<4>(row,a,r),5=>dot512_n::<5>(row,a,r),6=>dot512_n::<6>(row,a,r),7=>dot512_n::<7>(row,a,r),8=>dot512_n::<8>(row,a,r),_=>panic!("dot512: 1..=8 tokens")}
|
||||
}}
|
||||
#[target_feature(enable="avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")]
|
||||
unsafe fn dot512_n<const N:usize>(row:&[u8],a:&[&ActQ],r:&mut [f32]) {unsafe {
|
||||
assert!(N<=8&&a.len()==N&&r.len()==N);
|
||||
let mut acc=[_mm512_setzero_ps();8];let mut corr=[_mm512_setzero_ps();8];let base=_mm512_setr_epi32(0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1);let dup=_mm512_setr_epi32(0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7);let nb=row.len()/18;
|
||||
for b0 in (0..nb).step_by(8){let n=(nb-b0).min(8);let mask=if n==8{0xffff}else{((1u32<<(2*n))-1)as u16};let mut sc=[0u16;8];for i in 0..n{sc[i]=u16::from_le_bytes([row[(b0+i)*18],row[(b0+i)*18+1]]);}
|
||||
let d8=_mm512_castps256_ps512(_mm256_cvtph_ps(_mm_loadu_si128(sc.as_ptr().cast())));let dd=_mm512_maskz_mov_ps(mask,_mm512_permutexvar_ps(dup,d8));let mut p=[_mm512_setzero_ps();8];
|
||||
for (t,a) in a.iter().enumerate(){p[t]=_mm512_mul_ps(dd,_mm512_maskz_loadu_ps(mask,a.scale.as_ptr().add(2*b0)));corr[t]=_mm512_fmadd_ps(dd,_mm512_maskz_loadu_ps(mask,a.hx.as_ptr().add(2*b0)),corr[t]);}
|
||||
for i in 0..n{let b=b0+i;let packed=_mm_loadu_si128(row.as_ptr().add(b*18+2).cast());let lanes=_mm512_cvtepu16_epi64(packed);let ctrl=_mm512_set1_epi64(0x0e0c0a0806040200);let w=_mm512_and_si512(_mm512_multishift_epi64_epi8(ctrl,lanes),_mm512_set1_epi8(3));let idx=_mm512_add_epi32(base,_mm512_set1_epi32(2*i as i32));for (t,a) in a.iter().enumerate(){let dot=_mm512_dpbusd_epi32(_mm512_setzero_si512(),w,_mm512_loadu_si512(a.q.as_ptr().add(b*64).cast()));acc[t]=_mm512_fmadd_ps(_mm512_permutexvar_ps(idx,p[t]),_mm512_cvtepi32_ps(dot),acc[t]);}}
|
||||
for t in 0..N {let a=a[t];p[t]=_mm512_mul_ps(dd,_mm512_maskz_loadu_ps(mask,a.scale.as_ptr().add(2*b0)));corr[t]=_mm512_fmadd_ps(dd,_mm512_maskz_loadu_ps(mask,a.hx.as_ptr().add(2*b0)),corr[t]);}
|
||||
for i in 0..n{let b=b0+i;let packed=_mm_loadu_si128(row.as_ptr().add(b*18+2).cast());let lanes=_mm512_cvtepu16_epi64(packed);let ctrl=_mm512_set1_epi64(0x0e0c0a0806040200);let w=_mm512_and_si512(_mm512_multishift_epi64_epi8(ctrl,lanes),_mm512_set1_epi8(3));let idx=_mm512_add_epi32(base,_mm512_set1_epi32(2*i as i32));for t in 0..N {let a=a[t];let dot=_mm512_dpbusd_epi32(_mm512_setzero_si512(),w,_mm512_loadu_si512(a.q.as_ptr().add(b*64).cast()));acc[t]=_mm512_fmadd_ps(_mm512_permutexvar_ps(idx,p[t]),_mm512_cvtepi32_ps(dot),acc[t]);}}
|
||||
}
|
||||
for (t,r) in r.iter_mut().enumerate(){*r=_mm512_reduce_add_ps(acc[t])-_mm512_reduce_add_ps(corr[t]);}
|
||||
for t in 0..N {r[t]=_mm512_reduce_add_ps(acc[t])-_mm512_reduce_add_ps(corr[t]);}
|
||||
}}
|
||||
|
||||
@@ -183,6 +183,9 @@ fn borrowed_group_is_bit_identical_to_the_owned_batches() {
|
||||
borrowed_path(&mut direct, gu, down, &bank, &tokens, &jobs, &mut b);
|
||||
let differing = a.iter().zip(&b).filter(|(x, y)| x.to_bits() != y.to_bits()).count();
|
||||
assert_eq!(differing, 0, "{gu:?} x {down:?} rows={rows} share={share}: {differing} floats differ");
|
||||
// A digest of every output bit: compared across builds to prove a kernel change bit-exact.
|
||||
let digest = b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, v| (h ^ u64::from(v.to_bits())).wrapping_mul(0x100_0000_01b3));
|
||||
eprintln!("DIGEST {gu:?} {down:?} rows={rows} share={share} {digest:016x}");
|
||||
let computed: usize = jobs.iter().map(|(_, p)| p.len()).sum();
|
||||
assert!(b.iter().filter(|v| v.is_finite()).count() == computed * H, "{gu:?} x {down:?}: only planned rows written, all finite");
|
||||
groups += 1;
|
||||
|
||||
Reference in New Issue
Block a user