STRA-338 size2 cd4: original_file_expert_source/ffi, gpu schedule bridges, moe prompt device, mtp loader/rt/draft vocab split into helpers and comments wrapped
This commit is contained in:
+18
-9
@@ -23,15 +23,24 @@ fn fill_worker(per_layer: &[Vec<abi::Copy>], next: &AtomicUsize, first: &Mutex<O
|
||||
if first.lock().is_ok_and(|e| e.is_some()) {
|
||||
break;
|
||||
}
|
||||
for j in &per_layer[l] {
|
||||
if let Err(e) = j.run() {
|
||||
if let Ok(mut f) = first.lock() {
|
||||
if f.is_none() {
|
||||
*f = Some(e);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
run_layer(&per_layer[l], first);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs one layer's copies in order; the first failure is recorded and ends the layer.
|
||||
fn run_layer(jobs: &[abi::Copy], first: &Mutex<Option<Error>>) {
|
||||
for j in jobs {
|
||||
if let Err(e) = j.run() {
|
||||
record_first(first, e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn record_first(first: &Mutex<Option<Error>>, e: Error) {
|
||||
if let Ok(mut f) = first.lock() {
|
||||
if f.is_none() {
|
||||
*f = Some(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+39
-15
@@ -117,27 +117,47 @@ impl<'ctx> OriginalFileExpertSource<'ctx> {
|
||||
let off = self.offsets.get(k).copied().unwrap_or(NONE);
|
||||
let n = self.layer_bytes[l];
|
||||
let (bytes, alias) = if off != NONE {
|
||||
let a = self.arena.as_ref().ok_or(Error::InvalidSize)?;
|
||||
(a.part(off, n)?, a.alias(off, n)?)
|
||||
} else if let Some(q) = self.overrides.get(k).copied().filter(|q| *q != NONE) {
|
||||
(self.exchange.as_ref().ok_or(Error::InvalidSize)?.part(q * self.maximum, n)?, None)
|
||||
self.arena_blob(off, n)?
|
||||
} else if let Some(q) = self.override_slot(k) {
|
||||
(self.exchange_part(q, n)?, None)
|
||||
} else {
|
||||
let v = *self.stage_of.get(&k).ok_or(Error::InvalidSize)?;
|
||||
let s = &self.stage[v];
|
||||
if s.busy || s.key != k {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
(&s.data[..n], None)
|
||||
(self.staged_part(k, n)?, None)
|
||||
};
|
||||
self.count_blob_read(k, off);
|
||||
Ok(OriginalFileSourceBlob { source: self, layer: l, expert: e, bytes, alias })
|
||||
}
|
||||
/// The exchange slot that holds expert key `k`, if any.
|
||||
fn override_slot(&self, k: usize) -> Option<usize> {
|
||||
self.overrides.get(k).copied().filter(|q| *q != NONE)
|
||||
}
|
||||
fn arena_blob(&self, off: usize, n: usize) -> Result<(&[u8], Option<u64>)> {
|
||||
let a = self.arena.as_ref().ok_or(Error::InvalidSize)?;
|
||||
Ok((a.part(off, n)?, a.alias(off, n)?))
|
||||
}
|
||||
fn arena_part(&self, off: usize, n: usize) -> Result<&[u8]> {
|
||||
self.arena.as_ref().ok_or(Error::InvalidSize)?.part(off, n)
|
||||
}
|
||||
fn exchange_part(&self, q: usize, n: usize) -> Result<&[u8]> {
|
||||
self.exchange.as_ref().ok_or(Error::InvalidSize)?.part(q * self.maximum, n)
|
||||
}
|
||||
/// The staged bytes of key `k`; an idle or re-keyed stage is an error.
|
||||
fn staged_part(&self, k: usize, n: usize) -> Result<&[u8]> {
|
||||
let v = *self.stage_of.get(&k).ok_or(Error::InvalidSize)?;
|
||||
let s = &self.stage[v];
|
||||
if s.busy || s.key != k {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
Ok(&s.data[..n])
|
||||
}
|
||||
fn count_blob_read(&self, k: usize, off: usize) {
|
||||
let mut c = self.counts.get();
|
||||
if off != NONE {
|
||||
c.ram_reads = c.ram_reads.wrapping_add(1);
|
||||
} else if self.ready && self.overrides.get(k).copied().unwrap_or(NONE) == NONE {
|
||||
} else if self.ready && self.override_slot(k).is_none() {
|
||||
c.file_reads = c.file_reads.wrapping_add(1);
|
||||
}
|
||||
c.reads = c.reads.wrapping_add(1);
|
||||
self.counts.set(c);
|
||||
Ok(OriginalFileSourceBlob { source: self, layer: l, expert: e, bytes, alias })
|
||||
}
|
||||
pub fn copy_blob(&self, l: usize, e: usize, out: &mut [u8]) -> Result<()> {
|
||||
self.live()?;
|
||||
@@ -148,13 +168,17 @@ impl<'ctx> OriginalFileExpertSource<'ctx> {
|
||||
}
|
||||
let off = self.offsets.get(k).copied().unwrap_or(NONE);
|
||||
if off != NONE {
|
||||
out.copy_from_slice(self.arena.as_ref().ok_or(Error::InvalidSize)?.part(off, n)?);
|
||||
out.copy_from_slice(self.arena_part(off, n)?);
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(q) = self.overrides.get(k).copied().filter(|q| *q != NONE) {
|
||||
out.copy_from_slice(self.exchange.as_ref().ok_or(Error::InvalidSize)?.part(q * self.maximum, n)?);
|
||||
if let Some(q) = self.override_slot(k) {
|
||||
out.copy_from_slice(self.exchange_part(q, n)?);
|
||||
return Ok(());
|
||||
}
|
||||
self.copy_blob_from_file(l, e, out)
|
||||
}
|
||||
fn copy_blob_from_file(&self, l: usize, e: usize, out: &mut [u8]) -> Result<()> {
|
||||
let n = self.layer_bytes[l];
|
||||
let t = Instant::now();
|
||||
let result = abi::Copy::into_slice(self.parts(l, e)?, out)?.run();
|
||||
let mut c = self.counts.get();
|
||||
|
||||
@@ -30,7 +30,8 @@ macro_rules! sym {
|
||||
}
|
||||
impl Drop for Api {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: `library` is the single dlopen reference taken by `load`; the table is shared as `Arc<Api>`, so this runs after its last user.
|
||||
// SAFETY: `library` is the single dlopen reference taken by `load`; the table is shared as `Arc<Api>`,
|
||||
// so this runs after its last user.
|
||||
unsafe {
|
||||
libc::dlclose(self.library as P);
|
||||
}
|
||||
@@ -134,9 +135,10 @@ impl Api {
|
||||
if bytes == 0 || offset.checked_add(bytes).is_none_or(|n| n > arena.bytes) || arena.address == 0 {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
// SAFETY: `offset + bytes <= arena.bytes` (checked above), so the destination is inside the live arena; `source` extent validated.
|
||||
// A pinned (`full_pin`) arena is written asynchronously: `stage_swaps` synchronizes the stream before any `part` read and before `close`;
|
||||
// a `malloc` arena is pageable, so the driver completes the copy before returning.
|
||||
// SAFETY: `offset + bytes <= arena.bytes` (checked above), so the destination is inside the live arena;
|
||||
// `source` extent validated. A pinned (`full_pin`) arena is written asynchronously: `stage_swaps`
|
||||
// synchronizes the stream before any `part` read and before `close`; a `malloc` arena is pageable, so
|
||||
// the driver completes the copy before returning.
|
||||
check("cuMemcpyDtoHAsync_v2", unsafe {
|
||||
(self.dtoh)((arena.address + offset) as P, source.qwen_address(), bytes, stream as P)
|
||||
})
|
||||
@@ -145,7 +147,8 @@ impl Api {
|
||||
if arena.full_pin || arena.partial != 0 || bytes == 0 || bytes > arena.bytes {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
// SAFETY: `arena.address..+bytes` (`bytes <= arena.bytes`) is the live `malloc` block, not resized or freed until `close` unregisters it first.
|
||||
// SAFETY: `arena.address..+bytes` (`bytes <= arena.bytes`) is the live `malloc` block, not resized or
|
||||
// freed until `close` unregisters it first.
|
||||
if unsafe { (self.register)(arena.address as P, bytes, 3) } != 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -167,11 +170,13 @@ impl Api {
|
||||
return Ok(());
|
||||
}
|
||||
if arena.full_pin {
|
||||
// SAFETY: base returned by `cuMemHostAlloc` for this `full_pin` arena; `close` frees it once (address zeroed) after `context.synchronize()`.
|
||||
// SAFETY: base returned by `cuMemHostAlloc` for this `full_pin` arena; `close` frees it once (address
|
||||
// zeroed) after `context.synchronize()`.
|
||||
check("cuMemFreeHost", unsafe { (self.free)(arena.address as P) })?;
|
||||
} else {
|
||||
if arena.partial > 0 {
|
||||
// SAFETY: identical base that `register_prefix` registered (`partial > 0`); unregistered once, before the block is freed.
|
||||
// SAFETY: identical base that `register_prefix` registered (`partial > 0`); unregistered once,
|
||||
// before the block is freed.
|
||||
check("cuMemHostUnregister", unsafe { (self.unregister)(arena.address as P) })?;
|
||||
arena.partial = 0;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Moved out of the parent module by STRA-338: impl Arena, impl Copy, fn warm, fn copy_parts_record, fn copy_parts_to, fn worker_stack_bytes ....
|
||||
//! Moved out of the parent module by STRA-338: impl Arena, impl Copy, fn warm, fn copy_parts_record, fn copy_parts_to,
|
||||
//! fn worker_stack_bytes ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -96,7 +97,9 @@ impl Copy {
|
||||
if p == 0 || n == 0 || p.checked_add(n).is_none_or(|e| p < d + n && d < e) {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
// SAFETY: `run` checked each source/destination pair for overlap and overflow; the destination is inside the arena/stage (checked by `write`/`into_slice`), sources are retained mapped file bytes. Callers run it before the owners are released.
|
||||
// SAFETY: `run` checked each source/destination pair for overlap and overflow; the destination is
|
||||
// inside the arena/stage (checked by `write`/`into_slice`), sources are retained mapped file bytes.
|
||||
// Callers run it before the owners are released.
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(p as *const u8, d as *mut u8, n);
|
||||
}
|
||||
|
||||
@@ -18,23 +18,31 @@ impl<'ctx, R: OriginalNativeHeadGraphResources<'ctx>> OriginalGpuGraph<'ctx, R>
|
||||
stream: &mut OriginalGpuStream<'ctx>,
|
||||
sampling: NativeHeadSampling<'_, 'ctx>,
|
||||
) -> Result<NativeHeadSelection> {
|
||||
self.check_head_launched_on(stream)?;
|
||||
self.drain_head_stream(stream)?;
|
||||
self.resources
|
||||
.as_mut()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.native_head_rows_mut()?
|
||||
.finish_same_stream(stream, sampling)
|
||||
}
|
||||
fn check_head_launched_on(&self, stream: &OriginalGpuStream<'ctx>) -> Result<()> {
|
||||
self.validate()?;
|
||||
stream.validate_context(self.context)?;
|
||||
// A captured but never replayed graph does not contain completed logits.
|
||||
if !self.launched || !self.last.as_ref().is_some_and(|s| Rc::ptr_eq(s, &stream.inner)) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn drain_head_stream(&mut self, stream: &mut OriginalGpuStream<'ctx>) -> Result<()> {
|
||||
let receipt = stream.synchronize_with_receipt()?;
|
||||
if !Rc::ptr_eq(&receipt.stream, &stream.inner) || receipt.sequence < self.last_sequence {
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
// Same validated graph retirement rules as the shared schedule receipt.
|
||||
self.resources_after_stream_drain(&receipt)?;
|
||||
self.resources
|
||||
.as_mut()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.native_head_rows_mut()?
|
||||
.finish_same_stream(stream, sampling)
|
||||
Ok(())
|
||||
}
|
||||
/// Diagnostic full logits only after an actual current head result. Callback
|
||||
/// borrows the real whole buffer until return; it cannot mutate graph resources.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Moved out of the parent module by STRA-338: impl OriginalGpuGraph, impl Drop_for_OriginalGpuGraph, impl OriginalGraphFlight, impl Drop_for_OriginalGraphFlight.
|
||||
//! Moved out of the parent module by STRA-338: impl OriginalGpuGraph, impl Drop_for_OriginalGpuGraph, impl
|
||||
//! OriginalGraphFlight, impl Drop_for_OriginalGraphFlight.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -24,13 +25,7 @@ impl<'ctx, R: OriginalGraphResources> OriginalGpuGraph<'ctx, R> {
|
||||
/// Enqueue without a host wait, matching Original pre/post/token replay loops.
|
||||
/// Same-executable overlapping launches are ordered on its same actual stream.
|
||||
pub fn enqueue(&mut self, s: &OriginalGpuStream<'ctx>) -> Result<()> {
|
||||
s.validate_context(self.context)?;
|
||||
if s.inner.capture.get() {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
if self.launched && self.last.as_ref().is_some_and(|old| !Rc::ptr_eq(old, &s.inner)) {
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
self.check_enqueue_stream(s)?;
|
||||
let ex = self.validate()?;
|
||||
self.resources.as_ref().ok_or(Error::ContextPoisoned)?.validate_replay_context(self.context)?;
|
||||
let st = s.inner.validate()?;
|
||||
@@ -38,6 +33,19 @@ impl<'ctx, R: OriginalGraphResources> OriginalGpuGraph<'ctx, R> {
|
||||
self.last = Some(s.inner.clone());
|
||||
self.launched = true;
|
||||
self.last_sequence = sequence;
|
||||
self.launch_exec(ex, st)
|
||||
}
|
||||
fn check_enqueue_stream(&self, s: &OriginalGpuStream<'ctx>) -> Result<()> {
|
||||
s.validate_context(self.context)?;
|
||||
if s.inner.capture.get() {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
if self.launched && self.last.as_ref().is_some_and(|old| !Rc::ptr_eq(old, &s.inner)) {
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn launch_exec(&self, ex: usize, st: usize) -> Result<()> {
|
||||
call(self.context, &self.api, |a| {
|
||||
a.launch(ex, st)?;
|
||||
if let Some(e) = self.done {
|
||||
|
||||
@@ -8,18 +8,20 @@ fn symbol(l: &Library, n: &'static CStr) -> Result<Handle> {
|
||||
let p = unsafe { libc::dlsym(l.0, n.as_ptr()) };
|
||||
if p.is_null() { Err(Error::MissingSymbol(n.to_str().unwrap_or("Original schedule symbol"))) } else { Ok(p) }
|
||||
}
|
||||
/// `Api::bind`: every required symbol of the table in declaration order (the first missing one is reported), then the two
|
||||
/// optional symbols, which only ever map to `None`.
|
||||
/// `Api::bind`: every required symbol of the table in declaration order (the first missing one is reported), then the
|
||||
/// two optional symbols, which only ever map to `None`.
|
||||
macro_rules! api_table {
|
||||
($($field:ident: $name:literal as $ty:ty,)*) => {
|
||||
fn bind(l: Library) -> Result<Self> {
|
||||
Ok(Self {
|
||||
// SAFETY: non-null address of the named CUDA Driver symbol; every `$ty` is that symbol's exact Linux64 C signature.
|
||||
// SAFETY: non-null address of the named CUDA Driver symbol; every `$ty` is that symbol's exact Linux64
|
||||
// C signature.
|
||||
$($field: unsafe { std::mem::transmute::<Handle, $ty>(symbol(&l, $name)?) },)*
|
||||
copy_batch: {
|
||||
// SAFETY: optional symbol; a null address is mapped to `None` below.
|
||||
let p = unsafe { libc::dlsym(l.0, c"cuMemcpyBatchAsync_v2".as_ptr()) };
|
||||
// SAFETY: non-null `cuMemcpyBatchAsync_v2` (CUDA 13 signature without `failIdx`); `CopyBatch` is that exact C signature.
|
||||
// SAFETY: non-null `cuMemcpyBatchAsync_v2` (CUDA 13 signature without `failIdx`); `CopyBatch` is
|
||||
// that exact C signature.
|
||||
(!p.is_null()).then(|| unsafe { std::mem::transmute::<Handle, CopyBatch>(p) })
|
||||
},
|
||||
write_value: {
|
||||
@@ -80,25 +82,28 @@ impl Api {
|
||||
self.warm_callback_thread(s);
|
||||
Ok(s as usize)
|
||||
}
|
||||
/// Linux: the driver creates the thread that runs host functions lazily, at the first `cuLaunchHostFunc` of the process, and the
|
||||
/// new thread inherits the CPU mask of the thread that made the call. The CPU expert pool later pins the host thread to one
|
||||
/// core (`rust_platform::pin`); a callback thread created after that would share the core with the host's spin-wait (upstream
|
||||
/// measured 985 us instead of 4 us per callback, `0e20d9ae`/`c08fd902`, `STRATA_ADAPT_CALLBACK_WARMUP`). One no-op host function and a
|
||||
/// stream synchronize at the first stream's creation start the thread while the host thread is still unpinned. Windows CPU
|
||||
/// sets are per thread and not inherited, so nothing is done there. A failure is ignored: the first real callback creates the thread.
|
||||
/// Linux: the driver creates the thread that runs host functions lazily, at the first `cuLaunchHostFunc` of the
|
||||
/// process, and the new thread inherits the CPU mask of the thread that made the call. The CPU expert pool later
|
||||
/// pins the host thread to one core (`rust_platform::pin`); a callback thread created after that would share the
|
||||
/// core with the host's spin-wait (upstream measured 985 us instead of 4 us per callback, `0e20d9ae`/`c08fd902`,
|
||||
/// `STRATA_ADAPT_CALLBACK_WARMUP`). One no-op host function and a stream synchronize at the first stream's creation
|
||||
/// start the thread while the host thread is still unpinned. Windows CPU sets are per thread and not inherited, so
|
||||
/// nothing is done there. A failure is ignored: the first real callback creates the thread.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(super) fn warm_callback_thread(&self, s: Handle) {
|
||||
static WARMED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
if !callback_warmup_enabled() || WARMED.swap(true, std::sync::atomic::Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
// SAFETY: `s` is the stream just created through this Api in the entered Context; the host function ignores its argument.
|
||||
// SAFETY: `s` is the stream just created through this Api in the entered Context; the host function ignores its
|
||||
// argument.
|
||||
let launched = unsafe { (self.host_fn)(s, noop_host_fn, std::ptr::null_mut()) };
|
||||
// SAFETY: C ABI call on the live handle; no host memory is passed.
|
||||
let synced = if launched == 0 { unsafe { (self.sync)(s) } } else { launched };
|
||||
if synced == 0 {
|
||||
eprintln!(
|
||||
"leleka-serve: GPU host-callback thread started before host-core pinning (LELEKA_CB_WARMUP=off skips it)"
|
||||
"leleka-serve: GPU host-callback thread started before host-core pinning \
|
||||
(LELEKA_CB_WARMUP=off skips it)"
|
||||
);
|
||||
} else {
|
||||
eprintln!(
|
||||
@@ -110,15 +115,18 @@ impl Api {
|
||||
pub(super) fn warm_callback_thread(&self, _: Handle) {}
|
||||
pub(crate) fn stream_destroy(&self, s: usize) -> Result<()> {
|
||||
crate::compute_drain::unregister(s);
|
||||
// SAFETY: stream created through this Api; `Stream::close` destroys it once, after `stream_sync` succeeded (host functions included).
|
||||
// SAFETY: stream created through this Api; `Stream::close` destroys it once, after `stream_sync` succeeded
|
||||
// (host functions included).
|
||||
check("cuStreamDestroy_v2", unsafe { (self.destroy)(s as Handle) })
|
||||
}
|
||||
pub(crate) fn stream_sync(&self, s: usize) -> Result<()> {
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed.
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is
|
||||
// passed.
|
||||
crate::compute_drain::timed(7, || check("cuStreamSynchronize", unsafe { (self.sync)(s as Handle) }))
|
||||
}
|
||||
pub(crate) fn stream_query(&self, s: usize) -> Result<bool> {
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed.
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is
|
||||
// passed.
|
||||
let q = unsafe { (self.query)(s as Handle) };
|
||||
if q == 600 { Ok(false) } else { check("cuStreamQuery", q).map(|()| true) }
|
||||
}
|
||||
@@ -129,7 +137,8 @@ impl Api {
|
||||
Ok(p)
|
||||
}
|
||||
pub(crate) fn stream_wait(&self, s: usize, e: usize) -> Result<()> {
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed.
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is
|
||||
// passed.
|
||||
check("cuStreamWaitEvent", unsafe { (self.wait)(s as Handle, e as Handle, 0) })
|
||||
}
|
||||
pub(crate) fn event_create(&self, timing: bool) -> Result<usize> {
|
||||
@@ -142,20 +151,24 @@ impl Api {
|
||||
Ok(e as usize)
|
||||
}
|
||||
pub(crate) fn event_destroy(&self, e: usize) -> Result<()> {
|
||||
// SAFETY: event created through this Api; destroyed once by `OriginalGpuEvent::close_inner` after it (and its waiter streams) were synchronized.
|
||||
// SAFETY: event created through this Api; destroyed once by `OriginalGpuEvent::close_inner` after it (and its
|
||||
// waiter streams) were synchronized.
|
||||
check("cuEventDestroy_v2", unsafe { (self.event_destroy)(e as Handle) })
|
||||
}
|
||||
pub(crate) fn event_record(&self, e: usize, s: usize) -> Result<()> {
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed.
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is
|
||||
// passed.
|
||||
check("cuEventRecord", unsafe { (self.event_record)(e as Handle, s as Handle) })
|
||||
}
|
||||
pub(crate) fn event_query(&self, e: usize) -> Result<bool> {
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed.
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is
|
||||
// passed.
|
||||
let q = unsafe { (self.event_query)(e as Handle) };
|
||||
if q == 600 { Ok(false) } else { check("cuEventQuery", q).map(|()| true) }
|
||||
}
|
||||
pub(crate) fn event_sync(&self, e: usize) -> Result<()> {
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed.
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is
|
||||
// passed.
|
||||
crate::compute_drain::timed(7, || check("cuEventSynchronize", unsafe { (self.event_sync)(e as Handle) }))
|
||||
}
|
||||
pub(crate) fn elapsed(&self, a: usize, b: usize) -> Result<f32> {
|
||||
@@ -168,7 +181,8 @@ impl Api {
|
||||
Ok(ms)
|
||||
}
|
||||
pub(crate) fn begin(&self, s: usize) -> Result<()> {
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed.
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is
|
||||
// passed.
|
||||
check("cuStreamBeginCapture_v2", unsafe { (self.begin)(s as Handle, 1) })
|
||||
} // ThreadLocal
|
||||
pub(crate) fn end(&self, s: usize) -> Result<usize> {
|
||||
@@ -196,19 +210,23 @@ impl Api {
|
||||
Ok(e as usize)
|
||||
}
|
||||
pub(crate) fn graph_destroy(&self, g: usize) -> Result<()> {
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed.
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is
|
||||
// passed.
|
||||
check("cuGraphDestroy", unsafe { (self.graph_destroy)(g as Handle) })
|
||||
}
|
||||
pub(crate) fn exec_destroy(&self, e: usize) -> Result<()> {
|
||||
// SAFETY: executable created through this Api; destroyed once by `OriginalGpuGraph::close_inner` after its stream was drained.
|
||||
// SAFETY: executable created through this Api; destroyed once by `OriginalGpuGraph::close_inner` after its
|
||||
// stream was drained.
|
||||
check("cuGraphExecDestroy", unsafe { (self.exec_destroy)(e as Handle) })
|
||||
}
|
||||
pub(crate) fn upload(&self, e: usize, s: usize) -> Result<()> {
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed.
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is
|
||||
// passed.
|
||||
check("cuGraphUpload", unsafe { (self.upload)(e as Handle, s as Handle) })
|
||||
}
|
||||
pub(crate) fn launch(&self, e: usize, s: usize) -> Result<()> {
|
||||
// SAFETY: live executable and stream; the graph's resources (`R`: device/mapped owners) are retained by `OriginalGpuGraph` until drained.
|
||||
// SAFETY: live executable and stream; the graph's resources (`R`: device/mapped owners) are retained by
|
||||
// `OriginalGpuGraph` until drained.
|
||||
check("cuGraphLaunch", unsafe { (self.launch)(e as Handle, s as Handle) })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,8 +7,8 @@ impl Api {
|
||||
/// `cudaMemcpyAsync(H2D)` of `fetch_dma`. The caller keeps `src` (a registered bank) and `dst` alive
|
||||
/// until the stream's fence.
|
||||
pub(crate) fn copy_h2d(&self, dst: u64, src: &[u8], s: usize) -> Result<()> {
|
||||
// SAFETY: `dst` is a validated device range; `src` is a registered bank slice the caller keeps alive and registered
|
||||
// until this stream's next fence (documented contract of `enqueue_copy_h2d`).
|
||||
// SAFETY: `dst` is a validated device range; `src` is a registered bank slice the caller keeps alive and
|
||||
// registered until this stream's next fence (documented contract of `enqueue_copy_h2d`).
|
||||
check("cuMemcpyHtoDAsync_v2", unsafe { (self.copy_h2d)(dst, src.as_ptr().cast(), src.len(), s as Handle) })
|
||||
}
|
||||
/// Every `(destination, source)` piece of a group in stream order: one `cuMemcpyBatchAsync` when `batch` and the
|
||||
@@ -38,8 +38,9 @@ impl Api {
|
||||
// srcAccessOrder STREAM (1): the registered bank stays valid until the stream's fence
|
||||
let mut attr = BatchAttributes { src_access_order: 1, src_loc: [0, 0], dst_loc: [0, 0], flags: 0 };
|
||||
let mut index = 0usize;
|
||||
// SAFETY: `dsts/srcs/sizes/attr/index` are locals alive across the call and consumed by the driver during it (CUDA copies the
|
||||
// descriptor arrays); `count`/`numAttrs` match; the source bytes stay retained by the caller until the stream fence (srcAccessOrder STREAM).
|
||||
// SAFETY: `dsts/srcs/sizes/attr/index` are locals alive across the call and consumed by the driver during it
|
||||
// (CUDA copies the descriptor arrays); `count`/`numAttrs` match; the source bytes stay retained by the caller
|
||||
// until the stream fence (srcAccessOrder STREAM).
|
||||
let code = unsafe {
|
||||
f(
|
||||
dsts.as_mut_ptr(),
|
||||
@@ -61,7 +62,8 @@ impl Api {
|
||||
/// (no host callback thread). `MissingSymbol` when the driver lacks the call.
|
||||
pub(crate) fn write_u32_after(&self, s: usize, device_address: u64, value: u32) -> Result<()> {
|
||||
let f = self.write_value.ok_or(Error::MissingSymbol("cuStreamWriteValue32_v2"))?;
|
||||
// SAFETY: `device_address` is the device alias of a live 4-byte mapped host word the caller keeps allocated past this stream's fence.
|
||||
// SAFETY: `device_address` is the device alias of a live 4-byte mapped host word the caller keeps allocated
|
||||
// past this stream's fence.
|
||||
check("cuStreamWriteValue32_v2", unsafe { f(s as Handle, device_address, value, 0) })
|
||||
}
|
||||
/// Flag B after the copies: a stream write of the device alias when the driver takes it, else (or after one
|
||||
@@ -86,7 +88,8 @@ impl Api {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
let data = Box::into_raw(Box::new(Raise { word, value }));
|
||||
// SAFETY: `data` is a leaked `Box<Raise>` owned by the callback from here on (reclaimed there, or below if the launch is refused);
|
||||
// SAFETY: `data` is a leaked `Box<Raise>` owned by the callback from here on (reclaimed there, or below if the
|
||||
// launch is refused);
|
||||
// `word` is a live 4-byte-aligned mapped host word whose owner synchronizes the Context before freeing it.
|
||||
let launched =
|
||||
check("cuLaunchHostFunc", unsafe { (self.host_fn)(s as Handle, raise_after_copies, data.cast()) });
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Moved out of the parent module by STRA-338: impl Drop_for_Library, fn check, fn raise_after_copies, fn noop_host_fn, fn callback_warmup_enabled.
|
||||
//! Moved out of the parent module by STRA-338: impl Drop_for_Library, fn check, fn raise_after_copies, fn noop_host_fn,
|
||||
//! fn callback_warmup_enabled.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -6,7 +7,8 @@ use super::*;
|
||||
impl Drop for Library {
|
||||
fn drop(&mut self) {
|
||||
if !self.0.is_null() {
|
||||
// SAFETY: `self.0` is the live, non-null dlopen handle; closed once when the table (or a failed `load`) drops.
|
||||
// SAFETY: `self.0` is the live, non-null dlopen handle; closed once when the table (or a failed `load`)
|
||||
// drops.
|
||||
unsafe {
|
||||
libc::dlclose(self.0);
|
||||
}
|
||||
@@ -28,7 +30,8 @@ pub(super) unsafe extern "C" fn raise_after_copies(data: *mut c_void) {
|
||||
/// The no-op host function of the callback-thread warm-up.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(super) unsafe extern "C" fn noop_host_fn(_: *mut c_void) {}
|
||||
/// `LELEKA_CB_WARMUP=off|0|no` skips the warm-up of [`Api::warm_callback_thread`] (A/B arm; docs/upstream-port-plan.md row 0.6).
|
||||
/// `LELEKA_CB_WARMUP=off|0|no` skips the warm-up of [`Api::warm_callback_thread`] (A/B arm; docs/upstream-port-plan.md
|
||||
/// row 0.6).
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(super) fn callback_warmup_enabled() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
|
||||
@@ -10,6 +10,20 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
|
||||
done: &OriginalStreamDrained<'ctx>,
|
||||
sampling: NativeHeadSampling<'_, 'ctx>,
|
||||
) -> Result<NativeHeadSelection> {
|
||||
self.check_verifier_drained(stream, done)?;
|
||||
self.resources_after_stream_drain(done)?;
|
||||
self.validate_verifier_logits(stream)?;
|
||||
self.resources
|
||||
.as_mut()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.native_head_rows_mut()?
|
||||
.finish_same_stream(stream, sampling)
|
||||
}
|
||||
fn check_verifier_drained(
|
||||
&self,
|
||||
stream: &OriginalGpuStream<'ctx>,
|
||||
done: &OriginalStreamDrained<'ctx>,
|
||||
) -> Result<()> {
|
||||
self.validate()?;
|
||||
stream.validate_context(self.context)?;
|
||||
if !self.launched
|
||||
@@ -19,19 +33,16 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
|
||||
{
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
self.resources_after_stream_drain(done)?;
|
||||
Ok(())
|
||||
}
|
||||
fn validate_verifier_logits(&self, stream: &mut OriginalGpuStream<'ctx>) -> Result<()> {
|
||||
let r = self.resources.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let rows = r.native_head_rows()?.completed_logits()?;
|
||||
let geometry = r.verifier_journal().geometry();
|
||||
if rows.len() != r.native_head_rows()?.rows() * geometry.vocabulary * 4 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
r.verifier_journal().validate_completed_logits(stream, rows, rows.len() / (geometry.vocabulary * 4))?;
|
||||
self.resources
|
||||
.as_mut()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.native_head_rows_mut()?
|
||||
.finish_same_stream(stream, sampling)
|
||||
r.verifier_journal().validate_completed_logits(stream, rows, rows.len() / (geometry.vocabulary * 4))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,8 +59,9 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
|
||||
let r = self.resources.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
r.verifier_journal().validate_bank(bank)?;
|
||||
r.verifier_qsa().begin_window(bank)?;
|
||||
// the window advances the PLE history row by row and only the commit graph sets it from the kept row's snapshot: the NaN guard's
|
||||
// undo (`OriginalVerifyQsaJournal::discard_window`) needs it as it stood before the window (no-op unless the snapshots are on)
|
||||
// the window advances the PLE history row by row and only the commit graph sets it from the kept row's
|
||||
// snapshot: the NaN guard's undo (`OriginalVerifyQsaJournal::discard_window`) needs it as it stood before the
|
||||
// window (no-op unless the snapshots are on)
|
||||
if let Some(ple) = r.verifier_journal().ple_buffer() {
|
||||
r.verifier_qsa().snapshot_ple(ple)?;
|
||||
}
|
||||
|
||||
+13
-6
@@ -1,4 +1,5 @@
|
||||
//! Moved out of the parent module by STRA-338: impl Drop_for_OriginalMoePromptDevice, impl OriginalMoePromptLayer, impl OriginalMoePromptLayer.
|
||||
//! Moved out of the parent module by STRA-338: impl Drop_for_OriginalMoePromptDevice, impl OriginalMoePromptLayer, impl
|
||||
//! OriginalMoePromptLayer.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -65,7 +66,8 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo
|
||||
self.completed_experts = self.order.len();
|
||||
Ok(())
|
||||
}
|
||||
/// Nothing was executed yet, one source triple per routed expert, in order, all resident in `bank` and of this `layer`.
|
||||
/// Nothing was executed yet, one source triple per routed expert, in order, all resident in `bank` and of this
|
||||
/// `layer`.
|
||||
fn check_sources(
|
||||
&self,
|
||||
bank: &MappedExpertBank<'ctx>,
|
||||
@@ -76,10 +78,7 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
for (source, expert) in sources.iter().zip(&self.order) {
|
||||
if !bank.eligible(source)
|
||||
|| source[0].expert() != *expert
|
||||
|| !matches!(source[0].role(), leleka_model_format::qwen4exp::TensorRole::Layer { layer: l, .. } if usize::from(l) == layer)
|
||||
{
|
||||
if !bank.eligible(source) || source[0].expert() != *expert || !source_in_layer(source, layer) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
}
|
||||
@@ -194,3 +193,11 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the first span of an expert triple is a tensor of `layer`.
|
||||
fn source_in_layer(source: &[ResidentExpertBankSpan; 3], layer: usize) -> bool {
|
||||
matches!(
|
||||
source[0].role(),
|
||||
leleka_model_format::qwen4exp::TensorRole::Layer { layer: l, .. } if usize::from(l) == layer
|
||||
)
|
||||
}
|
||||
|
||||
+11
-7
@@ -131,8 +131,9 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> {
|
||||
outcome?;
|
||||
self.check_status(&got, labels)
|
||||
}
|
||||
/// The device part of `run`: zero the status words, issue the commands, drain, read the status back. Returns the combined
|
||||
/// result and whether the driver must be retained (an unconfirmed drain leaves the host buffers referenced).
|
||||
/// The device part of `run`: zero the status words, issue the commands, drain, read the status back. Returns the
|
||||
/// combined result and whether the driver must be retained (an unconfirmed drain leaves the host buffers
|
||||
/// referenced).
|
||||
fn run_device(
|
||||
&mut self,
|
||||
workspace: &mut NativeBatchWorkspace<'ctx>,
|
||||
@@ -150,14 +151,17 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> {
|
||||
}
|
||||
let all = self.context.driver.api.synchronize();
|
||||
let pop = guard.finish();
|
||||
if operation.is_err() || wait.is_err() || all.is_err() || pop.is_err() {
|
||||
self.failed = true;
|
||||
self.context.poison();
|
||||
workspace.mark_failed();
|
||||
}
|
||||
let retain = wait.is_err() || all.is_err() || pop.is_err();
|
||||
if operation.is_err() || retain {
|
||||
self.fail_device(workspace);
|
||||
}
|
||||
Ok((combine(combine(combine(operation, wait), all), pop), retain))
|
||||
}
|
||||
fn fail_device(&mut self, workspace: &mut NativeBatchWorkspace<'ctx>) {
|
||||
self.failed = true;
|
||||
self.context.poison();
|
||||
workspace.mark_failed();
|
||||
}
|
||||
fn issue(
|
||||
&self,
|
||||
blas: &crate::ple_batch_ffi::Blas,
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
//! Opt-in choice of the MTP draft head's token subset: `LELEKA_DRAFT_VOCAB`.
|
||||
//!
|
||||
//! The Original drafts over the rows of the main native head listed in `rt/draft_vocab.bin` (int32 token ids, 106,299 of
|
||||
//! the 248,320 rows, English, code and every CJK token). Upstream Strata ships three smaller or different subsets built
|
||||
//! with the same tool (`engine/strata/tools/draft_vocab.py`) and selects one with `--draft-vocab en|cyrillic|fr` or
|
||||
//! `--mtp-draft-vocab FILE`. The English subset (`draft_vocab_en.bin`, 40,525 ids) drops 65,774 head rows from the draft:
|
||||
//! about 110 MiB less VRAM and a shorter draft LM-head GEMV, at the price that a token outside the subset can never be
|
||||
//! proposed (CJK, most Cyrillic).
|
||||
//! The Original drafts over the rows of the main native head listed in `rt/draft_vocab.bin` (int32 token ids, 106,299
|
||||
//! of the 248,320 rows, English, code and every CJK token). Upstream Strata ships three smaller or different subsets
|
||||
//! built with the same tool (`engine/strata/tools/draft_vocab.py`) and selects one with `--draft-vocab en|cyrillic|fr`
|
||||
//! or
|
||||
//! `--mtp-draft-vocab FILE`. The English subset (`draft_vocab_en.bin`, 40,525 ids) drops 65,774 head rows from the
|
||||
//! draft: about 110 MiB less VRAM and a shorter draft LM-head GEMV, at the price that a token outside the subset can
|
||||
//! never be proposed (CJK, most Cyrillic).
|
||||
//!
|
||||
//! The draft only proposes; the verifier decides every token. The output therefore does not depend on the subset in
|
||||
//! principle. In practice a different subset changes which tokens are accepted, so the verifier windows have other
|
||||
@@ -116,7 +117,8 @@ fn refuse(path: &Path, why: &str) -> RtError {
|
||||
RtError::DraftVocabSelection(format!("{ENV}: {} {why}", path.display()))
|
||||
}
|
||||
|
||||
/// Reads and checks the file the setting names against the recorded subsets. Pure over the filesystem: no environment, no log.
|
||||
/// Reads and checks the file the setting names against the recorded subsets. Pure over the filesystem: no environment,
|
||||
/// no log.
|
||||
pub(crate) fn select(directory: &Path, setting: &Setting) -> Result<Selection, RtError> {
|
||||
select_in(directory, setting, &KNOWN)
|
||||
}
|
||||
@@ -138,6 +140,22 @@ pub(crate) fn select_in(directory: &Path, setting: &Setting, table: &[KnownSubse
|
||||
|
||||
/// The bytes of the selected file, or `None` when it does not exist: a regular file of whole int32 ids, read once.
|
||||
fn read_subset_file(path: &Path) -> Result<Option<Vec<u8>>, RtError> {
|
||||
let Some(length) = subset_file_length(path)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut bytes = Vec::new();
|
||||
bytes.try_reserve_exact(length as usize).map_err(|_| RtError::Host)?;
|
||||
let mut file = fs::File::open(path).map_err(|_| refuse(path, "cannot be opened"))?;
|
||||
// one bounded read: a file that grew since the lstat is cut at `length + 1` and refused below
|
||||
file.by_ref().take(length + 1).read_to_end(&mut bytes).map_err(|_| refuse(path, "cannot be read"))?;
|
||||
if bytes.len() as u64 != length {
|
||||
return Err(refuse(path, "changed while it was read"));
|
||||
}
|
||||
Ok(Some(bytes))
|
||||
}
|
||||
|
||||
/// The byte length of the selected file, or `None` when it does not exist: a regular file of whole int32 ids.
|
||||
fn subset_file_length(path: &Path) -> Result<Option<u64>, RtError> {
|
||||
let metadata = match fs::symlink_metadata(path) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => {
|
||||
@@ -157,15 +175,7 @@ fn read_subset_file(path: &Path) -> Result<Option<Vec<u8>>, RtError> {
|
||||
if length / 4 > DRAFT_VOCAB_MAX_IDS {
|
||||
return Err(RtError::DraftVocabTooLarge);
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
bytes.try_reserve_exact(length as usize).map_err(|_| RtError::Host)?;
|
||||
let mut file = fs::File::open(path).map_err(|_| refuse(path, "cannot be opened"))?;
|
||||
// one bounded read: a file that grew since the lstat is cut at `length + 1` and refused below
|
||||
file.by_ref().take(length + 1).read_to_end(&mut bytes).map_err(|_| refuse(path, "cannot be read"))?;
|
||||
if bytes.len() as u64 != length {
|
||||
return Err(refuse(path, "changed while it was read"));
|
||||
}
|
||||
Ok(Some(bytes))
|
||||
Ok(Some(length))
|
||||
}
|
||||
|
||||
/// The recorded subset whose digest the bytes have (the requested one when the setting named a row).
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Moved out of the parent module by STRA-338: impl LoaderError, fn add, fn mul, fn ceil, fn aligned, impl WeightBankPlan ....
|
||||
//! Moved out of the parent module by STRA-338: impl LoaderError, fn add, fn mul, fn ceil, fn aligned, impl
|
||||
//! WeightBankPlan ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -167,7 +168,10 @@ impl KvInputs {
|
||||
if place.mode == KvMode::Streamed {
|
||||
device = add(device, add(add(mul(place.slots, 20)?, 64)?, 6 * 16)?)?;
|
||||
}
|
||||
device = self.add_index_tables(device, place.pooled_rows)?;
|
||||
self.state_device_tail(device, place.pooled_rows)
|
||||
}
|
||||
fn state_device_tail(&self, device: u64, pooled_rows: u64) -> PlanResult<u64> {
|
||||
let mut device = self.add_index_tables(device, pooled_rows)?;
|
||||
device = add(device, 16)?;
|
||||
device = add(device, 16 + 16)?; // four step ints + attention status/alignment
|
||||
device = add(device, mul(self.heads, 4)?)?;
|
||||
@@ -205,14 +209,12 @@ pub(crate) fn mapped_staging(max_t: u64, heads: u64) -> PlanResult<[u64; 6]> {
|
||||
if !(1..=8).contains(&max_t) || heads == 0 {
|
||||
return Err(LoaderError::Geometry);
|
||||
}
|
||||
Ok([
|
||||
add(mul(max_t, 4)?, 64)?,
|
||||
add(mul(max_t, 32)?, 64)?,
|
||||
add(mul(mul(max_t, heads)?, 8)?, 64)?,
|
||||
64,
|
||||
add(mul(max_t, 4)?, 64)?,
|
||||
add(mul(max_t, 4)?, 64)?,
|
||||
])
|
||||
let word = padded(max_t, 4)?;
|
||||
Ok([word, padded(max_t, 32)?, padded(mul(max_t, heads)?, 8)?, 64, word, word])
|
||||
}
|
||||
/// `count * unit` plus the 64 bytes of padding of one mapped staging allocation.
|
||||
fn padded(count: u64, unit: u64) -> PlanResult<u64> {
|
||||
add(mul(count, unit)?, 64)
|
||||
}
|
||||
pub(crate) fn coupled_plan(
|
||||
enabled: bool,
|
||||
@@ -230,9 +232,17 @@ pub(crate) fn coupled_plan(
|
||||
if sampled == 0 || ceil(sampled, 4096)? > 64 {
|
||||
return Ok(CoupledPlan::ArgmaxVocabularyTooWide);
|
||||
}
|
||||
let inverse_map = subset_vocabulary.map(|_| vocabulary);
|
||||
coupled_sized(max_t, sampled, inverse_map)
|
||||
}
|
||||
/// The `Allocate` plan: `inverse_map` is the full vocabulary when a subset is drafted over.
|
||||
fn coupled_sized(max_t: u64, sampled: u64, inverse_map: Option<u64>) -> PlanResult<CoupledPlan> {
|
||||
let ring = mul(add(COUPLED_HISTORY, max_t)?, 4)?;
|
||||
let scratch = mul(ceil(sampled, 4096)?, 64 * 8)?;
|
||||
let inverse_map = if subset_vocabulary.is_some() { mul(vocabulary, 4)? } else { 0 };
|
||||
let inverse_map = if let Some(vocabulary) = inverse_map { mul(vocabulary, 4)? } else { 0 };
|
||||
coupled_allocation(ring, scratch, inverse_map)
|
||||
}
|
||||
fn coupled_allocation(ring: u64, scratch: u64, inverse_map: u64) -> PlanResult<CoupledPlan> {
|
||||
Ok(CoupledPlan::Allocate {
|
||||
params: 64,
|
||||
ring,
|
||||
@@ -244,31 +254,34 @@ pub(crate) fn coupled_plan(
|
||||
})
|
||||
}
|
||||
pub(crate) fn bind_bytes(input: BindInputs) -> PlanResult<u64> {
|
||||
let BindInputs {
|
||||
max_t,
|
||||
vocabulary,
|
||||
head_row_bytes,
|
||||
logits_already_owned,
|
||||
subset_already_owned,
|
||||
observed_subset_file_bytes,
|
||||
coupled_enabled,
|
||||
coupled_params_already_owned,
|
||||
} = input;
|
||||
if !(1..=8).contains(&max_t) {
|
||||
if !(1..=8).contains(&input.max_t) {
|
||||
return Err(LoaderError::Geometry);
|
||||
}
|
||||
let mut bytes = if logits_already_owned { 0 } else { mul(mul(max_t, vocabulary)?, 4)? };
|
||||
if !subset_already_owned
|
||||
&& let Some(size) = observed_subset_file_bytes
|
||||
let mut bytes = logits_bind_bytes(&input)?;
|
||||
bytes = add(bytes, subset_bind_bytes(&input)?)?;
|
||||
if input.coupled_enabled && !input.coupled_params_already_owned {
|
||||
bytes = add(bytes, coupled_bind_bytes(input.vocabulary, input.max_t)?)?;
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
/// The logits charge of `bind_bytes`: zero when the actor already owns them.
|
||||
fn logits_bind_bytes(input: &BindInputs) -> PlanResult<u64> {
|
||||
if input.logits_already_owned { Ok(0) } else { mul(mul(input.max_t, input.vocabulary)?, 4) }
|
||||
}
|
||||
/// The draft-vocabulary charge of `bind_bytes`: zero unless a new, whole-id subset file was observed.
|
||||
fn subset_bind_bytes(input: &BindInputs) -> PlanResult<u64> {
|
||||
if !input.subset_already_owned
|
||||
&& let Some(size) = input.observed_subset_file_bytes
|
||||
&& size >= 4
|
||||
&& size % 4 == 0
|
||||
{
|
||||
bytes = add(bytes, add(mul(size / 4, head_row_bytes)?, size)?)?;
|
||||
return add(mul(size / 4, input.head_row_bytes)?, size);
|
||||
}
|
||||
if coupled_enabled && !coupled_params_already_owned {
|
||||
bytes = add(bytes, add(add(mul(vocabulary, 4)?, mul(add(COUPLED_HISTORY, max_t)?, 4)?)?, 64 * 64 * 8 + 4096)?)?;
|
||||
}
|
||||
Ok(bytes)
|
||||
Ok(0)
|
||||
}
|
||||
/// The coupled-sampler parameter charge of `bind_bytes`: inverse map, ring and the fixed scratch.
|
||||
fn coupled_bind_bytes(vocabulary: u64, max_t: u64) -> PlanResult<u64> {
|
||||
add(add(mul(vocabulary, 4)?, mul(add(COUPLED_HISTORY, max_t)?, 4)?)?, 64 * 64 * 8 + 4096)
|
||||
}
|
||||
|
||||
impl OriginalMtpKvStartup {
|
||||
|
||||
@@ -68,18 +68,29 @@ impl<'ctx> OriginalMtpDrafter<'ctx> {
|
||||
tokens: &[i32],
|
||||
cell0: usize,
|
||||
) -> Result<()> {
|
||||
self.check_prefill_ring(ring, prior)?;
|
||||
if cell0.checked_add(tokens.len()).is_none_or(|e| e > MTP_ORIGINAL_MAX_CELLS) {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
self.check_prefill_residual(residual, tokens.len())
|
||||
}
|
||||
fn check_prefill_ring(&self, ring: &MtpOriginalInt8<'ctx>, prior: &MtpInt8Snapshot) -> Result<()> {
|
||||
self.validate_context(self.context)?;
|
||||
ring.validate_context(self.context)?;
|
||||
ring.validate_snapshot(prior)?;
|
||||
if ring.max_t != self.max_t {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
if cell0.checked_add(tokens.len()).is_none_or(|e| e > MTP_ORIGINAL_MAX_CELLS) {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn check_prefill_residual(
|
||||
&self,
|
||||
residual: Option<&OriginalDeviceResidual<'_, '_, 'ctx>>,
|
||||
token_count: usize,
|
||||
) -> Result<()> {
|
||||
match residual {
|
||||
Some(r) if r.context_matches(self.context) && r.rows() == tokens.len() => {}
|
||||
None if tokens.is_empty() => {}
|
||||
Some(r) if r.context_matches(self.context) && r.rows() == token_count => {}
|
||||
None if token_count == 0 => {}
|
||||
Some(r) if !r.context_matches(self.context) => return Err(Error::ContextMismatch),
|
||||
_ => return Err(Error::InvalidProjectionShape),
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Moved out of the parent module by STRA-338: impl RtError, impl OriginalMtpTensorKind, fn digits, impl DenseIndex, fn open_regular, fn zeroed.
|
||||
//! Moved out of the parent module by STRA-338: impl RtError, impl OriginalMtpTensorKind, fn digits, impl DenseIndex, fn
|
||||
//! open_regular, fn zeroed.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -7,30 +8,69 @@ impl RtError {
|
||||
/// Original error text where `mtp.cpp` has one, otherwise an `mtp:` text in
|
||||
/// the same style. Never contains file contents beyond the offending line.
|
||||
pub(crate) fn message(&self) -> String {
|
||||
match self {
|
||||
Self::CannotOpenIndex { .. }
|
||||
| Self::IndexTooLarge
|
||||
| Self::IndexNotAscii
|
||||
| Self::MalformedLine(_)
|
||||
| Self::TooManyTensors
|
||||
| Self::InvalidName(_)
|
||||
| Self::DuplicateTensor(_)
|
||||
| Self::UnknownKind(_) => self.index_message(),
|
||||
Self::Geometry(_)
|
||||
| Self::OutOfRange(_)
|
||||
| Self::NonFinite(_)
|
||||
| Self::CannotReadDense
|
||||
| Self::DenseTooLarge
|
||||
| Self::CannotOpenExperts
|
||||
| Self::ExpertsTruncated
|
||||
| Self::MissingRequired(_) => self.pack_message(),
|
||||
Self::ExpertSizeOverflow
|
||||
| Self::DraftVocabTooLarge
|
||||
| Self::DraftVocabOutOfRange
|
||||
| Self::DraftVocabSelection(_)
|
||||
| Self::Host => self.limit_message(),
|
||||
}
|
||||
}
|
||||
/// The errors of `dense.txt` itself (`message` routes only these here).
|
||||
fn index_message(&self) -> String {
|
||||
match self {
|
||||
Self::CannotOpenIndex { directory } => {
|
||||
format!("mtp: cannot open {directory}/dense.txt (run tools/mtp_rt.py)")
|
||||
}
|
||||
Self::MalformedLine(line) => format!("mtp: malformed dense.txt line: {line}"),
|
||||
Self::CannotReadDense => "mtp: cannot read dense.bin".into(),
|
||||
Self::CannotOpenExperts => "mtp: cannot open experts.bin".into(),
|
||||
Self::ExpertsTruncated => "mtp: experts.bin is truncated".into(),
|
||||
Self::MissingRequired(name) => format!("mtp: {name} is missing (q8_0)"),
|
||||
Self::IndexTooLarge => "mtp: dense.txt exceeds 64 KiB".into(),
|
||||
Self::IndexNotAscii => "mtp: dense.txt must be ASCII".into(),
|
||||
Self::TooManyTensors => "mtp: dense.txt lists more than 128 tensors".into(),
|
||||
Self::InvalidName(name) => format!("mtp: invalid tensor name in dense.txt: {name}"),
|
||||
Self::DuplicateTensor(name) => format!("mtp: duplicate tensor in dense.txt: {name}"),
|
||||
Self::UnknownKind(name) => format!("mtp: unsupported kind for tensor {name}"),
|
||||
_ => unreachable!("RtError::message routes only dense.txt errors here"),
|
||||
}
|
||||
}
|
||||
/// The errors of the tensor payloads in `dense.bin` and `experts.bin` (`message` routes only these here).
|
||||
fn pack_message(&self) -> String {
|
||||
match self {
|
||||
Self::CannotReadDense => "mtp: cannot read dense.bin".into(),
|
||||
Self::CannotOpenExperts => "mtp: cannot open experts.bin".into(),
|
||||
Self::ExpertsTruncated => "mtp: experts.bin is truncated".into(),
|
||||
Self::MissingRequired(name) => format!("mtp: {name} is missing (q8_0)"),
|
||||
Self::Geometry(name) => format!("mtp: inconsistent geometry for tensor {name}"),
|
||||
Self::OutOfRange(name) => format!("mtp: tensor {name} extends beyond dense.bin"),
|
||||
Self::NonFinite(name) => format!("mtp: non-finite values in {name}"),
|
||||
Self::DenseTooLarge => "mtp: dense.bin is too large".into(),
|
||||
_ => unreachable!("RtError::message routes only pack errors here"),
|
||||
}
|
||||
}
|
||||
/// Size, draft-vocabulary and host errors (`message` routes only these here).
|
||||
fn limit_message(&self) -> String {
|
||||
match self {
|
||||
Self::ExpertSizeOverflow => "mtp: the expert bank size overflows".into(),
|
||||
Self::DraftVocabTooLarge => "mtp: draft_vocab.bin is too large".into(),
|
||||
Self::DraftVocabOutOfRange => "mtp: draft_vocab.bin holds an id outside the vocabulary".into(),
|
||||
Self::DraftVocabSelection(text) => format!("mtp: {text}"),
|
||||
Self::Host => "mtp: host allocation failed".into(),
|
||||
_ => unreachable!("RtError::message routes only limit errors here"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user