perf(prefill): deferred guard status for the prompt producer's run (LELEKA_PREFILL_DEFER_GUARDS=1, experimental, default off): stream-ordered zero + DtoH into a pinned ring, cross-stream event ordering instead of the context drain, evaluated in order before results leave the device
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
cb843dd7b7
commit
242d54a503
@@ -35,6 +35,13 @@ pub(crate) fn set_background(stream: usize) {
|
||||
pub(crate) fn background() -> usize {
|
||||
BACKGROUND.load(Ordering::SeqCst)
|
||||
}
|
||||
/// Every registered stream except `except` and the chunk's background copy stream, plus the legacy default stream (0): the
|
||||
/// streams whose later work must be ordered after a stream's deferred-guard run (deferred_status.rs).
|
||||
pub(crate) fn streams_except(except: usize) -> Vec<usize> {
|
||||
let all = STREAMS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let background = background();
|
||||
std::iter::once(0usize).chain(all.iter().copied().filter(|&s| s != except && s != background)).collect()
|
||||
}
|
||||
/// Drain the legacy default stream and every registered stream but the background one.
|
||||
pub(crate) fn drain(sync: impl FnMut(usize) -> crate::Result<()>) -> crate::Result<()> {
|
||||
let all = STREAMS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
//! `LELEKA_PREFILL_DEFER_GUARDS=1` (EXPERIMENTAL, claude/schedule): deferred guard status for the prompt producer's `run`.
|
||||
//!
|
||||
//! Today every `OriginalPromptDevice::run` (the hyper-connection reads and injections: about 560 per 8192-token chunk) zeroes its status
|
||||
//! words with a synchronous upload, runs its kernels, drains the whole context, reads the words back and refuses on the first set one:
|
||||
//! three host synchronizations and two transfers per call, each one a hole in the GPU queue and a latecomer in the H2D copy FIFO.
|
||||
//! Deferred mode keeps the same words, the same kernels and the same refusal, but moves the *host's look* at them:
|
||||
//! 1. the words are zeroed by a stream-ordered memset (no upload, no wait);
|
||||
//! 2. after the kernels the words are copied by a stream-ordered DtoH into a pinned slot and an event is recorded behind the copy;
|
||||
//! 3. every other stream (and the legacy default stream) is ordered after that event on the device, which replaces the context
|
||||
//! drain that used to order the next producer after this one (the host does not wait);
|
||||
//! 4. the slot is evaluated by `resolve`, in order, with the unchanged evaluation (`evaluate`): when the ring of 64 slots is full, and
|
||||
//! at the points where results leave the device (final-row reads, preview/finish of the phase, row-lease teardown).
|
||||
//! A failing slot poisons the context exactly like the immediate check does (every later driver call refuses with `ContextPoisoned`) and
|
||||
//! returns the same error class and label as the immediate path would have, only later: work enqueued after the failing run has executed
|
||||
//! on its output, but nothing of it is observable (no row is read back, no phase is sealed, no session state is published) before `resolve`.
|
||||
use crate::Error;
|
||||
use crate::Result;
|
||||
|
||||
/// The evaluation of one status readback, shared by the immediate and the deferred path: any word above 1 is an unknown status; then
|
||||
/// the first set word in the producer's order (`stride == 10`: PLE, row first then stage order; otherwise GR, stage first over all rows).
|
||||
pub(crate) fn evaluate(readback: &[u8], stride: usize, order: &[usize], labels: &[&'static str]) -> Result<()> {
|
||||
for word in readback.as_chunks::<4>().0 {
|
||||
if u32::from_le_bytes(*word) > 1 {
|
||||
return Err(Error::InvalidDriverValue("Original prompt status"));
|
||||
}
|
||||
}
|
||||
let word_at = |row: &[u8], stage: usize| -> Result<u32> {
|
||||
Ok(u32::from_le_bytes(row[stage * 4..stage * 4 + 4].try_into().map_err(|_| Error::InvalidQwenShape)?))
|
||||
};
|
||||
if stride == 10 {
|
||||
for row in readback.chunks_exact(stride * 4) {
|
||||
for &stage in order {
|
||||
if word_at(row, stage)? != 0 {
|
||||
return Err(Error::NonFiniteMmqOutput(labels[stage]));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for &stage in order {
|
||||
for row in readback.chunks_exact(stride * 4) {
|
||||
if word_at(row, stage)? != 0 {
|
||||
return Err(Error::NonFiniteMmqOutput(labels[stage]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read once: the switch. Off by default (experimental mode).
|
||||
pub(crate) fn enabled() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var("LELEKA_PREFILL_DEFER_GUARDS").is_ok_and(|v| v == "1"))
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))]
|
||||
mod device {
|
||||
use super::evaluate;
|
||||
use crate::ffi::{BufferHandle, deferred_status::{Api, HostBuffer}};
|
||||
use crate::{Context, Error, Result};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
const SLOTS: usize = 64;
|
||||
|
||||
struct Check {
|
||||
slot: usize,
|
||||
bytes: usize,
|
||||
stride: usize,
|
||||
order: Vec<usize>,
|
||||
labels: Vec<&'static str>,
|
||||
}
|
||||
struct Slot {
|
||||
host: HostBuffer,
|
||||
event: usize,
|
||||
}
|
||||
struct State {
|
||||
api: Api,
|
||||
context: usize,
|
||||
slots: Vec<Slot>,
|
||||
live: VecDeque<Check>,
|
||||
head: usize,
|
||||
}
|
||||
thread_local! {
|
||||
// The contexts are single-thread owners (Rc), so one state per thread, bound to the context that created it.
|
||||
static STATE: RefCell<Option<State>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
fn open(context: &Context<'_>, slot_bytes: usize) -> Result<State> {
|
||||
let api = Api::load()?;
|
||||
let mut slots = Vec::with_capacity(SLOTS);
|
||||
for _ in 0..SLOTS {
|
||||
slots.push(Slot { host: api.host_buffer(slot_bytes)?, event: api.event()? });
|
||||
}
|
||||
Ok(State { api, context: std::ptr::from_ref(context) as usize, slots, live: VecDeque::new(), head: 0 })
|
||||
}
|
||||
|
||||
/// Wait for the oldest live check and evaluate it. The first failure poisons the context; every other live copy is still waited for.
|
||||
fn resolve_oldest(context: &Context<'_>, st: &mut State) -> Result<()> {
|
||||
let Some(check) = st.live.pop_front() else { return Ok(()) };
|
||||
let slot = &st.slots[check.slot];
|
||||
st.api.wait_host(slot.event)?;
|
||||
let verdict = slot.host.view(check.bytes).and_then(|b| evaluate(b, check.stride, &check.order, &check.labels));
|
||||
if verdict.is_err() {
|
||||
context.poisoned.set(true);
|
||||
while let Some(rest) = st.live.pop_front() {
|
||||
let _ = st.api.wait_host(st.slots[rest.slot].event);
|
||||
}
|
||||
}
|
||||
verdict
|
||||
}
|
||||
|
||||
/// Step 1 of a deferred run: zero the status words, stream ordered.
|
||||
pub(crate) fn begin(context: &Context<'_>, status: BufferHandle, bytes: usize, stream: usize, slot_bytes: usize) -> Result<()> {
|
||||
STATE.with(|cell| {
|
||||
let mut guard = cell.borrow_mut();
|
||||
if guard.as_ref().is_some_and(|s| s.context != std::ptr::from_ref(context) as usize || s.slots[0].host.bytes() < bytes) {
|
||||
if guard.as_ref().is_some_and(|s| !s.live.is_empty()) {
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
*guard = None;
|
||||
}
|
||||
if guard.is_none() {
|
||||
*guard = Some(open(context, slot_bytes.max(bytes))?);
|
||||
}
|
||||
let st = guard.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
st.api.zero_async(status, bytes, stream)
|
||||
})
|
||||
}
|
||||
|
||||
/// Steps 2-3: copy the words out behind the kernels, record the event, order every other stream after it, remember the check.
|
||||
pub(crate) fn finish(
|
||||
context: &Context<'_>,
|
||||
status: BufferHandle,
|
||||
bytes: usize,
|
||||
stream: usize,
|
||||
stride: usize,
|
||||
order: &[usize],
|
||||
labels: &[&'static str],
|
||||
) -> Result<()> {
|
||||
STATE.with(|cell| {
|
||||
let mut guard = cell.borrow_mut();
|
||||
let st = guard.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
if st.live.len() == SLOTS {
|
||||
resolve_oldest(context, st)?;
|
||||
}
|
||||
let slot_index = st.head % SLOTS;
|
||||
st.head += 1;
|
||||
let slot = &st.slots[slot_index];
|
||||
st.api.read_async(&slot.host, status, bytes, stream)?;
|
||||
st.api.record(slot.event, stream)?;
|
||||
for other in crate::compute_drain::streams_except(stream) {
|
||||
st.api.wait_stream(other, slot.event)?;
|
||||
}
|
||||
st.live.push_back(Check { slot: slot_index, bytes, stride, order: order.to_vec(), labels: labels.to_vec() });
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Evaluate everything outstanding, in order. Enters the context itself.
|
||||
pub(crate) fn resolve(context: &Context<'_>) -> Result<()> {
|
||||
STATE.with(|cell| {
|
||||
let mut guard = cell.borrow_mut();
|
||||
let Some(st) = guard.as_mut() else { return Ok(()) };
|
||||
if st.live.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if st.context != std::ptr::from_ref(context) as usize {
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
let entered = context.enter()?;
|
||||
let mut result = Ok(());
|
||||
while !st.live.is_empty() {
|
||||
let r = resolve_oldest(context, st);
|
||||
if result.is_ok() {
|
||||
result = r;
|
||||
}
|
||||
}
|
||||
let popped = entered.finish();
|
||||
result.and(popped.map(|_| ()))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn pending() -> usize {
|
||||
STATE.with(|cell| cell.borrow().as_ref().map_or(0, |s| s.live.len()))
|
||||
}
|
||||
}
|
||||
#[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))]
|
||||
#[allow(unused_imports)]
|
||||
pub(crate) use device::{begin, finish, pending, resolve};
|
||||
|
||||
#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))]
|
||||
mod unsupported {
|
||||
use crate::ffi::BufferHandle;
|
||||
use crate::{Context, Error, Result};
|
||||
pub(crate) fn begin(_: &Context<'_>, _: BufferHandle, _: usize, _: usize, _: usize) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn finish(_: &Context<'_>, _: BufferHandle, _: usize, _: usize, _: usize, _: &[usize], _: &[&'static str]) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn resolve(_: &Context<'_>) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn pending() -> usize {
|
||||
0
|
||||
}
|
||||
}
|
||||
#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))]
|
||||
pub(crate) use unsupported::{begin, finish, pending, resolve};
|
||||
|
||||
#[cfg(all(test, feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))]
|
||||
#[path = "deferred_status_gpu.rs"]
|
||||
mod gpu_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn words(rows: &[&[u32]]) -> Vec<u8> {
|
||||
rows.iter().flat_map(|r| r.iter().flat_map(|w| w.to_le_bytes())).collect()
|
||||
}
|
||||
#[test]
|
||||
fn evaluate_reports_the_first_set_stage_in_the_producers_order() {
|
||||
let labels = ["a", "b", "c", "d"];
|
||||
// GR (stride 4): stage first over all rows; order [2, 0, 1, 3]; row 1 sets stage 0 and row 2 sets stage 2
|
||||
let b = words(&[&[0, 0, 0, 0], &[1, 0, 0, 0], &[0, 0, 1, 0]]);
|
||||
assert!(matches!(evaluate(&b, 4, &[2, 0, 1, 3], &labels), Err(Error::NonFiniteMmqOutput("c"))));
|
||||
assert!(matches!(evaluate(&b, 4, &[0, 1, 2, 3], &labels), Err(Error::NonFiniteMmqOutput("a"))));
|
||||
assert!(evaluate(&words(&[&[0; 4], &[0; 4]]), 4, &[0, 1, 2, 3], &labels).is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn evaluate_orders_ple_rows_before_stages_and_refuses_unknown_words() {
|
||||
let labels = ["s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9"];
|
||||
let mut r0 = [0u32; 10];
|
||||
let mut r1 = [0u32; 10];
|
||||
r0[5] = 1;
|
||||
r1[2] = 1;
|
||||
let b = words(&[&r0, &r1]);
|
||||
// PLE: row 0 is examined before row 1 whatever the stage order
|
||||
assert!(matches!(evaluate(&b, 10, &[2, 5], &labels), Err(Error::NonFiniteMmqOutput("s5"))));
|
||||
// an unknown status (2) beats a set flag that comes earlier
|
||||
r0[0] = 2;
|
||||
let b = words(&[&r0, &r1]);
|
||||
assert!(matches!(evaluate(&b, 10, &[2, 5], &labels), Err(Error::InvalidDriverValue(_))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//! Audited child of ffi (claude/schedule): the few asynchronous driver calls the deferred guard status block needs
|
||||
//! (`LELEKA_PREFILL_DEFER_GUARDS`, see deferred_status.rs): a device memset and a device-to-host copy on a stream, pinned host
|
||||
//! buffers, and events with cross-stream waits. Nothing here owns a device allocation or a stream; the host buffers are owned
|
||||
//! by `HostBuffer` and freed by `Api::free_host`. Callers keep the context current (their `enter()` guard) and keep every
|
||||
//! device allocation alive until the event of the copy that reads it has been waited for.
|
||||
use super::BufferHandle;
|
||||
use crate::{Error, Result};
|
||||
use std::ffi::{CStr, c_void};
|
||||
type Handle = *mut c_void;
|
||||
type HostAlloc = unsafe extern "C" fn(*mut Handle, usize, u32) -> i32;
|
||||
type HandleCall = unsafe extern "C" fn(Handle) -> i32;
|
||||
type EventCreate = unsafe extern "C" fn(*mut Handle, u32) -> i32;
|
||||
type EventRecord = unsafe extern "C" fn(Handle, Handle) -> i32;
|
||||
type StreamWait = unsafe extern "C" fn(Handle, Handle, u32) -> i32;
|
||||
type DtoHAsync = unsafe extern "C" fn(*mut c_void, u64, usize, Handle) -> i32;
|
||||
type MemsetAsync = unsafe extern "C" fn(u64, u8, usize, Handle) -> i32;
|
||||
fn check(name: &'static str, code: i32) -> Result<()> {
|
||||
if code == 0 { Ok(()) } else { Err(Error::Driver { operation: name, code }) }
|
||||
}
|
||||
pub(crate) struct HostBuffer {
|
||||
address: usize,
|
||||
bytes: usize,
|
||||
}
|
||||
impl HostBuffer {
|
||||
pub(crate) fn bytes(&self) -> usize {
|
||||
self.bytes
|
||||
}
|
||||
/// The first `len` bytes. SAFETY contract (checked by the caller's protocol, not here): the event of the last copy
|
||||
/// into this buffer has completed, and no copy into it is in flight.
|
||||
pub(crate) fn view(&self, len: usize) -> Result<&[u8]> {
|
||||
if len > self.bytes {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
// SAFETY: `address` is a live pinned allocation of `bytes` bytes owned by `self`; `len <= bytes`; the protocol above
|
||||
// guarantees no concurrent writer.
|
||||
Ok(unsafe { std::slice::from_raw_parts(self.address as *const u8, len) })
|
||||
}
|
||||
}
|
||||
// usize is the real dlopen handle; the table holds only immutable C ABI function pointers.
|
||||
pub(crate) struct Api {
|
||||
library: usize,
|
||||
host_alloc: HostAlloc,
|
||||
host_free: HandleCall,
|
||||
event_create: EventCreate,
|
||||
event_destroy: HandleCall,
|
||||
event_sync: HandleCall,
|
||||
event_record: EventRecord,
|
||||
stream_wait: StreamWait,
|
||||
dtoh: DtoHAsync,
|
||||
memset: MemsetAsync,
|
||||
}
|
||||
impl Drop for Api {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the handle returned by dlopen in `load`, closed once.
|
||||
unsafe {
|
||||
libc::dlclose(self.library as Handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Api {
|
||||
pub(crate) fn load() -> Result<Self> {
|
||||
// SAFETY: NUL-terminated literal name.
|
||||
let l = unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) };
|
||||
if l.is_null() {
|
||||
return Err(Error::LibraryUnavailable);
|
||||
}
|
||||
struct Opening(Handle);
|
||||
impl Drop for Opening {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: dlopen handle not yet transferred to `Api`.
|
||||
unsafe {
|
||||
libc::dlclose(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
let opening = Opening(l);
|
||||
fn symbol(l: Handle, n: &'static CStr) -> Result<Handle> {
|
||||
// SAFETY: valid dlopen handle and NUL-terminated name.
|
||||
let p = unsafe { libc::dlsym(l, n.as_ptr()) };
|
||||
if p.is_null() { Err(Error::MissingSymbol(n.to_str().unwrap_or("deferred status symbol"))) } else { Ok(p) }
|
||||
}
|
||||
macro_rules! sym {
|
||||
($n:literal,$t:ty) => {
|
||||
// SAFETY: the CUDA driver ABI of this symbol is exactly the declared function type.
|
||||
unsafe { std::mem::transmute::<Handle, $t>(symbol(l, $n)?) }
|
||||
};
|
||||
}
|
||||
let result = Self {
|
||||
library: l as usize,
|
||||
host_alloc: sym!(c"cuMemHostAlloc", HostAlloc),
|
||||
host_free: sym!(c"cuMemFreeHost", HandleCall),
|
||||
event_create: sym!(c"cuEventCreate", EventCreate),
|
||||
event_destroy: sym!(c"cuEventDestroy_v2", HandleCall),
|
||||
event_sync: sym!(c"cuEventSynchronize", HandleCall),
|
||||
event_record: sym!(c"cuEventRecord", EventRecord),
|
||||
stream_wait: sym!(c"cuStreamWaitEvent", StreamWait),
|
||||
dtoh: sym!(c"cuMemcpyDtoHAsync_v2", DtoHAsync),
|
||||
memset: sym!(c"cuMemsetD8Async", MemsetAsync),
|
||||
};
|
||||
std::mem::forget(opening);
|
||||
Ok(result)
|
||||
}
|
||||
pub(crate) fn host_buffer(&self, bytes: usize) -> Result<HostBuffer> {
|
||||
if bytes == 0 {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
let mut p = std::ptr::null_mut();
|
||||
// SAFETY: valid out pointer, nonzero size, flags 0 (plain page-locked memory).
|
||||
check("cuMemHostAlloc", unsafe { (self.host_alloc)(&mut p, bytes, 0) })?;
|
||||
if p.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuMemHostAlloc"));
|
||||
}
|
||||
Ok(HostBuffer { address: p as usize, bytes })
|
||||
}
|
||||
pub(crate) fn free_host(&self, buffer: HostBuffer) -> Result<()> {
|
||||
// SAFETY: the address came from `host_buffer`; the caller has waited for every copy into it.
|
||||
check("cuMemFreeHost", unsafe { (self.host_free)(buffer.address as Handle) })
|
||||
}
|
||||
pub(crate) fn event(&self) -> Result<usize> {
|
||||
let mut e = std::ptr::null_mut();
|
||||
// SAFETY: valid out pointer; flags 2 = CU_EVENT_DISABLE_TIMING.
|
||||
check("cuEventCreate", unsafe { (self.event_create)(&mut e, 2) })?;
|
||||
Ok(e as usize)
|
||||
}
|
||||
pub(crate) fn destroy_event(&self, event: usize) -> Result<()> {
|
||||
// SAFETY: event created by `event`, no pending waits the caller still needs.
|
||||
check("cuEventDestroy_v2", unsafe { (self.event_destroy)(event as Handle) })
|
||||
}
|
||||
pub(crate) fn record(&self, event: usize, stream: usize) -> Result<()> {
|
||||
// SAFETY: live event and stream handles of the current context.
|
||||
check("cuEventRecord", unsafe { (self.event_record)(event as Handle, stream as Handle) })
|
||||
}
|
||||
/// Block the host until the event has completed (a spin wait is the driver default).
|
||||
pub(crate) fn wait_host(&self, event: usize) -> Result<()> {
|
||||
// SAFETY: live event of the current context.
|
||||
check("cuEventSynchronize", unsafe { (self.event_sync)(event as Handle) })
|
||||
}
|
||||
/// Order `stream` (0 = the legacy default stream) after the work recorded in `event`, device side.
|
||||
pub(crate) fn wait_stream(&self, stream: usize, event: usize) -> Result<()> {
|
||||
// SAFETY: live event and stream (or the null stream) of the current context.
|
||||
check("cuStreamWaitEvent", unsafe { (self.stream_wait)(stream as Handle, event as Handle, 0) })
|
||||
}
|
||||
pub(crate) fn zero_async(&self, buffer: BufferHandle, bytes: usize, stream: usize) -> Result<()> {
|
||||
if bytes == 0 {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
buffer.validate_extent(bytes)?;
|
||||
// SAFETY: validated extent of a live allocation of the current context; stream handle of the same context.
|
||||
check("cuMemsetD8Async", unsafe { (self.memset)(buffer.0, 0, bytes, stream as Handle) })
|
||||
}
|
||||
pub(crate) fn read_async(&self, host: &HostBuffer, source: BufferHandle, bytes: usize, stream: usize) -> Result<()> {
|
||||
if bytes == 0 || bytes > host.bytes {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
source.validate_extent(bytes)?;
|
||||
// SAFETY: pinned destination of at least `bytes`, validated device extent, same-context stream; the caller keeps both
|
||||
// alive and does not read or reuse the host buffer before the event recorded after this copy has completed.
|
||||
check("cuMemcpyDtoHAsync_v2", unsafe { (self.dtoh)(host.address as *mut c_void, source.0, bytes, stream as Handle) })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Model-free GPU proof of the deferred guard status machinery (deferred_status.rs): the stream-ordered zero, the DtoH into the pinned
|
||||
//! ring, the ordering events, the ring wrap and the poisoning, against the immediate evaluation. Enable with
|
||||
//! `LELEKA_PREFILL_STAGE_GPU=yes` (`cargo test -p leleka-cuda-driver --features cuda-driver deferred -- --ignored`).
|
||||
use super::*;
|
||||
use crate::{Context, DeviceBuffer, Driver};
|
||||
|
||||
fn status_bytes(words: &[u32]) -> Vec<u8> {
|
||||
words.iter().flat_map(|w| w.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Root-only: needs a CUDA device"]
|
||||
fn deferred_status_equals_the_immediate_evaluation_and_poisons() {
|
||||
assert_eq!(std::env::var("LELEKA_PREFILL_STAGE_GPU").ok().as_deref(), Some("yes"));
|
||||
let driver = Driver::load().expect("driver");
|
||||
let device = driver.device(0).expect("device");
|
||||
let context = device.create_context(1usize << 30).expect("context");
|
||||
let workspace = context.native_batch_workspace().expect("workspace");
|
||||
let blas = workspace.blas().expect("blas");
|
||||
let stride = 4usize;
|
||||
let rows = 8usize;
|
||||
let bytes = rows * stride * 4;
|
||||
let order = [0usize, 1, 2, 3];
|
||||
let labels = ["n", "d", "s", "u"];
|
||||
let mut status: DeviceBuffer<'_> = context.allocate(4096).expect("alloc");
|
||||
let handle = status.handle.expect("handle");
|
||||
let put = |status: &mut DeviceBuffer<'_>, words: &[u32]| {
|
||||
let mut b = status_bytes(words);
|
||||
b.resize(4096, 0);
|
||||
status.copy_from(&b).expect("upload");
|
||||
};
|
||||
let run = |status: &mut DeviceBuffer<'_>, words: &[u32]| {
|
||||
let guard = context.enter().expect("enter");
|
||||
begin(&context, handle, bytes, blas.stream(), 4096).expect("begin");
|
||||
blas.synchronize().expect("sync");
|
||||
put(status, words); // stands in for the kernels' flag writes
|
||||
finish(&context, handle, bytes, blas.stream(), stride, &order, &labels).expect("finish");
|
||||
guard.finish().expect("pop");
|
||||
};
|
||||
// clean run, the zeroing must have cleared the previous words
|
||||
run(&mut status, &vec![0; rows * stride]);
|
||||
run(&mut status, &vec![0; rows * stride]);
|
||||
assert_eq!(pending(), 2);
|
||||
resolve(&context).expect("clean runs");
|
||||
assert_eq!(pending(), 0);
|
||||
// more runs than slots: the ring wraps and resolves its oldest entries by itself
|
||||
for _ in 0..150 {
|
||||
run(&mut status, &vec![0; rows * stride]);
|
||||
}
|
||||
assert!(pending() <= 64);
|
||||
resolve(&context).expect("wrapped ring");
|
||||
// a set flag: same label as the immediate evaluation
|
||||
let mut words = vec![0u32; rows * stride];
|
||||
words[3 * stride + 2] = 1;
|
||||
run(&mut status, &words);
|
||||
let expected = evaluate(&status_bytes(&words), stride, &order, &labels).unwrap_err();
|
||||
let got = resolve(&context).unwrap_err();
|
||||
assert_eq!(format!("{got:?}"), format!("{expected:?}"));
|
||||
assert!(context.is_poisoned());
|
||||
assert!(matches!(context.enter(), Err(Error::ContextPoisoned)));
|
||||
}
|
||||
@@ -2768,3 +2768,11 @@ pub(crate) mod original_stager;
|
||||
))]
|
||||
#[path = "original_file_expert_source_ffi.rs"]
|
||||
pub(crate) mod original_file_source;
|
||||
|
||||
#[cfg(all(
|
||||
feature = "cuda-driver",
|
||||
target_os = "linux",
|
||||
target_pointer_width = "64"
|
||||
))]
|
||||
#[path = "deferred_status_ffi.rs"]
|
||||
pub(crate) mod deferred_status;
|
||||
|
||||
@@ -30,6 +30,7 @@ use std::{cell::{Cell, RefCell}, fmt, marker::PhantomData, rc::Rc};
|
||||
#[allow(unsafe_code)]
|
||||
mod ffi;
|
||||
pub mod compute_drain;
|
||||
mod deferred_status;
|
||||
#[allow(unsafe_code)]
|
||||
mod original_gpu_schedule;
|
||||
pub use original_gpu_schedule::{
|
||||
|
||||
@@ -158,6 +158,11 @@ impl<'arena, 'loan, 'ctx> OriginalDeviceResidual<'arena, 'loan, 'ctx> {
|
||||
}
|
||||
/// Consume the actual retained lease only after Root validated the genuine
|
||||
/// preview identity and draft receipt. No second host row read occurs.
|
||||
/// Look at every deferred guard status now (LELEKA_PREFILL_DEFER_GUARDS; a no-op when nothing is deferred). The runtime calls it
|
||||
/// before it seals a phase whose rows stay on the device.
|
||||
pub fn resolve_guards(&self) -> Result<()> {
|
||||
crate::deferred_status::resolve(self.lease.context())
|
||||
}
|
||||
pub fn finish_after_preview(mut self) -> Result<()> {
|
||||
if self.lease.is_failed() {
|
||||
return Err(Error::ContextPoisoned);
|
||||
@@ -790,8 +795,16 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
let mut op = self.context.driver.api.copy_from(status, &zero);
|
||||
if op.is_ok() {
|
||||
// LELEKA_PREFILL_DEFER_GUARDS (experimental, deferred_status.rs): the status words are zeroed and read back on the stream and
|
||||
// looked at later (ring full, or before results leave the device); PLE (stride 10) and the profiling mode stay immediate.
|
||||
let defer = crate::deferred_status::enabled() && stride != 10 && !crate::command_profile::enabled();
|
||||
let status_bytes = t * stride * 4;
|
||||
let mut op = if defer {
|
||||
crate::deferred_status::begin(self.context, status, status_bytes, blas.stream(), self.capacity * 40)
|
||||
} else {
|
||||
self.context.driver.api.copy_from(status, &zero)
|
||||
};
|
||||
if op.is_ok() && !defer {
|
||||
op = self.context.driver.api.synchronize()
|
||||
}
|
||||
// LELEKA_PREFILL_PROFILE_SYNC: each command drained on its own and charged to (tag, position)
|
||||
@@ -843,6 +856,28 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
|
||||
crate::command_profile::add(self.profile_tag, position + 1, label, started.elapsed());
|
||||
}
|
||||
}
|
||||
if defer {
|
||||
// no host wait: the words and the cross-stream ordering are queued on the stream (deferred_status.rs)
|
||||
let queued = if op.is_ok() {
|
||||
crate::deferred_status::finish(self.context, status, status_bytes, blas.stream(), stride, order, labels)
|
||||
} else {
|
||||
op
|
||||
};
|
||||
let pop = guard.finish();
|
||||
if queued.is_err() || pop.is_err() {
|
||||
self.failed = true;
|
||||
lease.mark_failed();
|
||||
workspace.mark_failed();
|
||||
std::mem::forget((commands, zero, readback));
|
||||
self.context.retain_driver();
|
||||
return combine(queued, pop);
|
||||
}
|
||||
// cuLaunchKernel copies its parameter values at the call and cuBLAS (host pointer mode) reads alpha/beta at the
|
||||
// call, so the argument vectors need not outlive the enqueue (the immediate path keeps them until its drain
|
||||
// as a conservative audit rule; the failure path above still leaks them)
|
||||
drop(commands);
|
||||
return Ok(());
|
||||
}
|
||||
let sync = blas.synchronize();
|
||||
if op.is_ok() && sync.is_ok() {
|
||||
op = self.context.driver.api.copy_to(status, &mut readback)
|
||||
@@ -860,44 +895,15 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
|
||||
return combine(combine(combine(op, sync), all), pop);
|
||||
}
|
||||
combine(combine(combine(op, sync), all), pop)?;
|
||||
// Unknown status is never a usable finite product, including a later
|
||||
// word after an earlier numerical flag. All actual kernels write0/1.
|
||||
for word in readback.as_chunks::<4>().0 {
|
||||
if u32::from_le_bytes(*word) > 1 {
|
||||
// Unknown status is never a usable finite product, including a later word after an earlier numerical flag. All actual
|
||||
// kernels write 0/1. The evaluation is shared with the deferred path (deferred_status::evaluate).
|
||||
if let Err(e) = crate::deferred_status::evaluate(&readback, stride, order, labels) {
|
||||
if matches!(e, Error::InvalidDriverValue(_)) {
|
||||
self.failed = true;
|
||||
lease.mark_failed();
|
||||
self.context.retain_driver();
|
||||
return Err(Error::InvalidDriverValue("Original prompt status"));
|
||||
}
|
||||
}
|
||||
if stride == 10 {
|
||||
// PLE preserves chronological row THEN original ten-stage order.
|
||||
for row in readback.chunks_exact(stride * 4) {
|
||||
for &stage in order {
|
||||
if u32::from_le_bytes(
|
||||
row[stage * 4..stage * 4 + 4]
|
||||
.try_into()
|
||||
.map_err(|_| Error::InvalidQwenShape)?,
|
||||
) != 0
|
||||
{
|
||||
return Err(Error::NonFiniteMmqOutput(labels[stage]));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// GR preserves the original stage-first whole-output validation.
|
||||
for &stage in order {
|
||||
for row in readback.chunks_exact(stride * 4) {
|
||||
if u32::from_le_bytes(
|
||||
row[stage * 4..stage * 4 + 4]
|
||||
.try_into()
|
||||
.map_err(|_| Error::InvalidQwenShape)?,
|
||||
) != 0
|
||||
{
|
||||
return Err(Error::NonFiniteMmqOutput(labels[stage]));
|
||||
}
|
||||
}
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -252,6 +252,11 @@ impl<'arena, 'loan, 'ctx> OriginalPromptRows<'arena, 'loan, 'ctx> {
|
||||
/// required for source-equivalent stream ordering at the caller seam.
|
||||
pub(crate) fn drain(&mut self) -> Result<()> {
|
||||
if self.drained { return Ok(()); }
|
||||
// deferred guard words (LELEKA_PREFILL_DEFER_GUARDS) are looked at before anything leaves the device
|
||||
if let Err(e) = crate::deferred_status::resolve(self.arena.context) {
|
||||
self.arena.failed = true;
|
||||
return Err(e);
|
||||
}
|
||||
let result = self.arena.context.synchronize();
|
||||
if result.is_err() { self.arena.failed = true; }
|
||||
self.drained = result.is_ok();
|
||||
|
||||
@@ -126,6 +126,7 @@ impl<'source,'arena,'loan,'ctx> PromptDeviceRows<'source,'arena,'loan,'ctx>{
|
||||
if last.input.position().get().checked_add(1)!=Some(txn.end_position()){return Err(Error::IdentityMismatch)}
|
||||
let known_next=txn.known_prompt_next()?.ok_or(Error::IdentityMismatch)?;
|
||||
let lease_identity=self.device.lease_identity();
|
||||
self.device.resolve_guards().map_err(micro_driver_error)?;
|
||||
phase.seal_final()?;
|
||||
Ok(PromptDeviceFinal{binding:binding.identity(),phase,token:last.input.token(),position:last.input.position(),
|
||||
product:FinalProduct::DeviceConditioning{known_next},lease_identity})
|
||||
|
||||
Reference in New Issue
Block a user