STRA-338 size2 cd5: sampler, session state, stream_all and verify functions cut to the lawbook limits
This commit is contained in:
+11
-13
@@ -73,13 +73,7 @@ impl<'ctx> OriginalGpuStream<'ctx> {
|
||||
side: Option<SideStreams>,
|
||||
body: impl FnOnce(&mut OriginalCapture<'_, 'ctx>, &mut R) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
let guard = match self.inner.context.enter() {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
poison(self.inner.context);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
let guard = self.inner.context.enter().inspect_err(|_| poison(self.inner.context))?;
|
||||
// Body errors are primary, but EndCapture is always attempted before retirement.
|
||||
let mut token = OriginalCapture { stream: &self.inner, side, target: Cell::new(None) };
|
||||
let body_result = Self::run_body(g, &mut token, self.inner.context, body);
|
||||
@@ -184,18 +178,22 @@ fn instantiate_exec<R: OriginalGraphResources>(
|
||||
match exec {
|
||||
Ok(exec) => g.exec = Some(exec),
|
||||
Err(primary) => {
|
||||
capture_timing::add(1, captured.elapsed().as_secs_f64() * 1e3);
|
||||
if is_graph_out_of_memory(&primary) {
|
||||
eprintln!(
|
||||
"leleka-serve graph instantiate out of memory ({policy:?}); the context stays usable, the graph is dropped"
|
||||
);
|
||||
}
|
||||
report_instantiate_failure(&primary, policy, captured);
|
||||
return Err(primary);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn report_instantiate_failure(primary: &Error, policy: OriginalCapturePolicy, captured: Instant) {
|
||||
capture_timing::add(1, captured.elapsed().as_secs_f64() * 1e3);
|
||||
if is_graph_out_of_memory(primary) {
|
||||
eprintln!(
|
||||
"leleka-serve graph instantiate out of memory ({policy:?}); the context stays usable, the graph is dropped"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn warm_upload(a: &abi::Api, exec: usize, h: usize, policy: OriginalCapturePolicy) -> Result<()> {
|
||||
let upload = a.upload(exec, h);
|
||||
// The upload only warms the graph up (the first launch would do it): running out of memory there costs the warm-up,
|
||||
|
||||
@@ -171,7 +171,6 @@ impl<'ctx> Context<'ctx> {
|
||||
let tensors = self.upload_dense(&index, &blob)?;
|
||||
// Original frees the host blob at the end of its dense block.
|
||||
drop(blob);
|
||||
|
||||
let experts = self.stream_expert_bank(directory, n_expert)?;
|
||||
// Original checks the nine names only after both banks exist.
|
||||
index.check_required(REQUIRED_Q8_NAMES)?;
|
||||
|
||||
@@ -6,6 +6,9 @@ use crate::original_expert_cache::OriginalCachePrefix;
|
||||
use crate::original_prefill_layout::{OriginalPrefillLayout, PrefillLayoutOptions, PrefillPhase};
|
||||
use crate::{Context, DeviceBuffer, Error, Result, ffi};
|
||||
|
||||
mod ple_extent;
|
||||
use ple_extent::ple_extent;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) enum OriginalPromptSpan {
|
||||
R,
|
||||
@@ -378,28 +381,3 @@ impl Drop for OriginalPromptRows<'_, '_, '_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const PLE_SHAPES: [(OriginalPleSpan, usize, usize); 7] = [
|
||||
(OriginalPleSpan::Key, 10240, 4),
|
||||
(OriginalPleSpan::Qn, 10240, 4),
|
||||
(OriginalPleSpan::Gated, 10240, 4),
|
||||
(OriginalPleSpan::Value, 2560, 4),
|
||||
(OriginalPleSpan::Gate, 4, 4),
|
||||
(OriginalPleSpan::PackedEmbedding, 2560, 2),
|
||||
(OriginalPleSpan::PackedEmbeddingLow, 2560, 2),
|
||||
];
|
||||
|
||||
/// `(offset, bytes)` of the `role` span for `rows` rows in the carve that starts at `start`.
|
||||
fn ple_extent(role: OriginalPleSpan, rows: usize, start: usize) -> Result<(usize, usize)> {
|
||||
let mut offset = start;
|
||||
for (candidate, columns, width) in PLE_SHAPES {
|
||||
let bytes = rows.checked_mul(columns).and_then(|n| n.checked_mul(width)).ok_or(Error::InvalidSize)?;
|
||||
if std::mem::discriminant(&candidate) == std::mem::discriminant(&role) {
|
||||
return Ok((offset, bytes));
|
||||
}
|
||||
// Original local carve_f adds only255, unlike global Alloc::take.
|
||||
offset =
|
||||
offset.checked_add(bytes.checked_add(255).ok_or(Error::InvalidSize)? & !255).ok_or(Error::InvalidSize)?;
|
||||
}
|
||||
Err(Error::InvalidQwenShape)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
//! The PLE span carve of the prompt arena, split out by STRA-338 size pass 2.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
const PLE_SHAPES: [(OriginalPleSpan, usize, usize); 7] = [
|
||||
(OriginalPleSpan::Key, 10240, 4),
|
||||
(OriginalPleSpan::Qn, 10240, 4),
|
||||
(OriginalPleSpan::Gated, 10240, 4),
|
||||
(OriginalPleSpan::Value, 2560, 4),
|
||||
(OriginalPleSpan::Gate, 4, 4),
|
||||
(OriginalPleSpan::PackedEmbedding, 2560, 2),
|
||||
(OriginalPleSpan::PackedEmbeddingLow, 2560, 2),
|
||||
];
|
||||
|
||||
/// `(offset, bytes)` of the `role` span for `rows` rows in the carve that starts at `start`.
|
||||
pub(super) fn ple_extent(role: OriginalPleSpan, rows: usize, start: usize) -> Result<(usize, usize)> {
|
||||
let mut offset = start;
|
||||
for (candidate, columns, width) in PLE_SHAPES {
|
||||
let bytes = rows.checked_mul(columns).and_then(|n| n.checked_mul(width)).ok_or(Error::InvalidSize)?;
|
||||
if std::mem::discriminant(&candidate) == std::mem::discriminant(&role) {
|
||||
return Ok((offset, bytes));
|
||||
}
|
||||
// Original local carve_f adds only255, unlike global Alloc::take.
|
||||
offset =
|
||||
offset.checked_add(bytes.checked_add(255).ok_or(Error::InvalidSize)? & !255).ok_or(Error::InvalidSize)?;
|
||||
}
|
||||
Err(Error::InvalidQwenShape)
|
||||
}
|
||||
@@ -18,6 +18,9 @@ const GEMM_WS: usize = 32 << 20;
|
||||
const MMQ_GROUP: usize = 16;
|
||||
const MMQ_TAIL: usize = 4096;
|
||||
|
||||
mod carve_parts;
|
||||
use carve_parts::{merge_spans, take_kv_int8, take_kv_q4, take_ple};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PrefillPhase {
|
||||
Common,
|
||||
@@ -200,31 +203,6 @@ fn take_kv(a: &mut Alloc, stage: PrefillKvStage) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn take_kv_q4(a: &mut Alloc, rows: usize, head_dim: usize) -> Result<()> {
|
||||
if head_dim == 0 || !head_dim.is_multiple_of(32) {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
let per_head = mul(head_dim / 32, 18)?;
|
||||
a.rows("kv_k_q4", rows, per_head, 1)?;
|
||||
a.rows("kv_v_q4", rows, per_head, 1)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn take_kv_int8(a: &mut Alloc, rows: usize, head_dim: usize, without_key: bool) -> Result<()> {
|
||||
if head_dim == 0 || !head_dim.is_multiple_of(64) {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
if !without_key {
|
||||
a.rows("kv_k_q", rows, head_dim, 1)?;
|
||||
}
|
||||
a.rows("kv_v_q", rows, head_dim, 1)?;
|
||||
if !without_key {
|
||||
a.rows("kv_k_scale", rows, head_dim / 64, 2)?;
|
||||
}
|
||||
a.rows("kv_v_scale", rows, head_dim / 64, 2)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl PrefillLayoutOptions {
|
||||
pub fn original_ring_slots(&self) -> Result<usize> {
|
||||
if !self.pinned_share.is_finite() || !(0.0..=1.0).contains(&self.pinned_share) {
|
||||
@@ -381,22 +359,6 @@ impl PrefillLayoutOptions {
|
||||
}
|
||||
}
|
||||
|
||||
fn take_ple(a: &mut Alloc, t: usize) -> Result<()> {
|
||||
a.rows("ple_emb", t, N, 4)?;
|
||||
a.take("ple_norm", D, 4)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Moves the spans of one shared-region half behind the region's offset into the parent carve.
|
||||
fn merge_spans(a: &mut Alloc, layout: &mut Alloc, region_offset: usize) -> Result<()> {
|
||||
for span in &mut layout.spans {
|
||||
span.offset = add(span.offset, region_offset)?;
|
||||
}
|
||||
a.spans.try_reserve(layout.spans.len()).map_err(|_| Error::HostAllocation)?;
|
||||
a.spans.append(&mut layout.spans);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl OriginalPrefillLayout {
|
||||
/// The only overlapping spans are mutually exclusive attention/MoE halves
|
||||
/// and the explicit common parent region. A caller must drain before switching.
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
//! Carve helpers of the prefill layout, split out by STRA-338 size pass 2.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
pub(super) fn take_kv_q4(a: &mut Alloc, rows: usize, head_dim: usize) -> Result<()> {
|
||||
if head_dim == 0 || !head_dim.is_multiple_of(32) {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
let per_head = mul(head_dim / 32, 18)?;
|
||||
a.rows("kv_k_q4", rows, per_head, 1)?;
|
||||
a.rows("kv_v_q4", rows, per_head, 1)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn take_kv_int8(a: &mut Alloc, rows: usize, head_dim: usize, without_key: bool) -> Result<()> {
|
||||
if head_dim == 0 || !head_dim.is_multiple_of(64) {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
if !without_key {
|
||||
a.rows("kv_k_q", rows, head_dim, 1)?;
|
||||
}
|
||||
a.rows("kv_v_q", rows, head_dim, 1)?;
|
||||
if !without_key {
|
||||
a.rows("kv_k_scale", rows, head_dim / 64, 2)?;
|
||||
}
|
||||
a.rows("kv_v_scale", rows, head_dim / 64, 2)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn take_ple(a: &mut Alloc, t: usize) -> Result<()> {
|
||||
a.rows("ple_emb", t, N, 4)?;
|
||||
a.take("ple_norm", D, 4)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Moves the spans of one shared-region half behind the region's offset into the parent carve.
|
||||
pub(super) fn merge_spans(a: &mut Alloc, layout: &mut Alloc, region_offset: usize) -> Result<()> {
|
||||
for span in &mut layout.spans {
|
||||
span.offset = add(span.offset, region_offset)?;
|
||||
}
|
||||
a.spans.try_reserve(layout.spans.len()).map_err(|_| Error::HostAllocation)?;
|
||||
a.spans.append(&mut layout.spans);
|
||||
Ok(())
|
||||
}
|
||||
+64
-50
@@ -15,14 +15,15 @@ impl<'ctx> OriginalSampler<'ctx> {
|
||||
}
|
||||
let ptx = asset().ok_or(Error::UnsupportedQwenOperation)?;
|
||||
let sizes = [0, rows * history.max(1) * 4, rows * 4, 64, (HIST + DRAFTS) * 4, 4, 4, vocab * 4, vocab * 4];
|
||||
let charge = sizes.iter().try_fold(0usize, |a, b| a.checked_add(*b)).ok_or(Error::InvalidSize)?;
|
||||
let required = charge.checked_add(RESERVE).ok_or(Error::InvalidSize)?;
|
||||
if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget)
|
||||
|| context.memory_info()?.0 < required
|
||||
{
|
||||
return Err(Error::BudgetExceeded);
|
||||
Self::check_budget(context, &sizes)?;
|
||||
let mut owner = Self::unloaded(context, rows, vocab, history);
|
||||
if let Err(primary) = owner.allocate_and_load(ptx, sizes) {
|
||||
return combine(Err(primary), owner.close());
|
||||
}
|
||||
let mut owner = Self {
|
||||
Ok(owner)
|
||||
}
|
||||
fn unloaded(context: &'ctx Context<'ctx>, rows: usize, vocab: usize, history: usize) -> Self {
|
||||
Self {
|
||||
context,
|
||||
module: None,
|
||||
mapped: None,
|
||||
@@ -36,33 +37,40 @@ impl<'ctx> OriginalSampler<'ctx> {
|
||||
scratch_entries: 0,
|
||||
scratch_failed: 0,
|
||||
retired: Vec::new(),
|
||||
};
|
||||
let operation = (|| {
|
||||
for (slot, bytes) in owner.buffers.iter_mut().zip(sizes) {
|
||||
if bytes > 0 {
|
||||
*slot = Some(context.allocate(bytes)?);
|
||||
}
|
||||
}
|
||||
let guard = context.enter()?;
|
||||
let load: Result<()> = (|| {
|
||||
owner.module = Some(KernelModule::load(ptx, ENTRIES)?);
|
||||
owner.mapped = Some(MappedAllocation::new()?);
|
||||
Ok(())
|
||||
})();
|
||||
let pop = guard.finish();
|
||||
if load.is_err() || pop.is_err() {
|
||||
context.poisoned.set(true);
|
||||
}
|
||||
combine(load, pop)?;
|
||||
if context.memory_info()?.0 < RESERVE {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
}
|
||||
fn check_budget(context: &Context<'_>, sizes: &[usize; 9]) -> Result<()> {
|
||||
let charge = sizes.iter().try_fold(0usize, |a, b| a.checked_add(*b)).ok_or(Error::InvalidSize)?;
|
||||
let required = charge.checked_add(RESERVE).ok_or(Error::InvalidSize)?;
|
||||
if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget)
|
||||
|| context.memory_info()?.0 < required
|
||||
{
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn allocate_and_load(&mut self, ptx: &'static [u8], sizes: [usize; 9]) -> Result<()> {
|
||||
let context = self.context;
|
||||
for (slot, bytes) in self.buffers.iter_mut().zip(sizes) {
|
||||
if bytes > 0 {
|
||||
*slot = Some(context.allocate(bytes)?);
|
||||
}
|
||||
}
|
||||
let guard = context.enter()?;
|
||||
let load: Result<()> = (|| {
|
||||
self.module = Some(KernelModule::load(ptx, ENTRIES)?);
|
||||
self.mapped = Some(MappedAllocation::new()?);
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(primary) = operation {
|
||||
return combine(Err(primary), owner.close());
|
||||
let pop = guard.finish();
|
||||
if load.is_err() || pop.is_err() {
|
||||
context.poisoned.set(true);
|
||||
}
|
||||
Ok(owner)
|
||||
combine(load, pop)?;
|
||||
if context.memory_info()?.0 < RESERVE {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn allocated_bytes(&self) -> usize {
|
||||
self.buffers.iter().flatten().chain(self.retired.iter()).map(DeviceBuffer::len).sum()
|
||||
@@ -123,31 +131,37 @@ impl<'ctx> OriginalSampler<'ctx> {
|
||||
self.retired.try_reserve(1).map_err(|_| Error::HostAllocation)?;
|
||||
let want = (self.scratch_entries * 2).min(CAP).max(entries);
|
||||
for n in [want, entries] {
|
||||
let bytes = n * 8;
|
||||
let required = bytes + RESERVE;
|
||||
if self.context.allocated_bytes().checked_add(required).is_none_or(|v| v > self.context.budget)
|
||||
|| self.context.memory_info()?.0 < required
|
||||
{
|
||||
continue;
|
||||
}
|
||||
match self.context.allocate(bytes) {
|
||||
Ok(buffer) => {
|
||||
if let Some(old) = self.buffers[0].replace(buffer) {
|
||||
self.retired.push(old);
|
||||
}
|
||||
self.scratch_entries = n;
|
||||
return Ok(true);
|
||||
}
|
||||
Err(Error::BudgetExceeded) | Err(Error::Driver { operation: "cuMemAlloc_v2", code: 2 }) => {}
|
||||
Err(error) => {
|
||||
self.failed = true;
|
||||
return Err(error);
|
||||
}
|
||||
if self.grow_scratch(n)? {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
self.scratch_failed = entries;
|
||||
Ok(false)
|
||||
}
|
||||
/// Installs a scratch buffer of `n` entries; `false` when it does not fit or the device refuses it.
|
||||
fn grow_scratch(&mut self, n: usize) -> Result<bool> {
|
||||
let bytes = n * 8;
|
||||
let required = bytes + RESERVE;
|
||||
if self.context.allocated_bytes().checked_add(required).is_none_or(|v| v > self.context.budget)
|
||||
|| self.context.memory_info()?.0 < required
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
match self.context.allocate(bytes) {
|
||||
Ok(buffer) => {
|
||||
if let Some(old) = self.buffers[0].replace(buffer) {
|
||||
self.retired.push(old);
|
||||
}
|
||||
self.scratch_entries = n;
|
||||
Ok(true)
|
||||
}
|
||||
Err(Error::BudgetExceeded) | Err(Error::Driver { operation: "cuMemAlloc_v2", code: 2 }) => Ok(false),
|
||||
Err(error) => {
|
||||
self.failed = true;
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(in super::super) fn upload(&mut self, i: usize, bytes: &[u8]) -> Result<()> {
|
||||
let r = self.buffers[i].as_mut().ok_or(Error::ContextPoisoned)?.copy_from(bytes);
|
||||
if r.is_err() {
|
||||
|
||||
+209
-111
@@ -11,17 +11,28 @@ impl<'ctx> OriginalSampler<'ctx> {
|
||||
prob: bool,
|
||||
) -> Result<(Vec<u8>, [u8; 4])> {
|
||||
self.validate_context(self.context)?;
|
||||
let mut ids = Vec::new();
|
||||
if read_ids {
|
||||
ids.try_reserve_exact(self.rows * 4).map_err(|_| Error::HostAllocation)?;
|
||||
ids.resize(self.rows * 4, 0);
|
||||
}
|
||||
let mut probability = Vec::new();
|
||||
if prob {
|
||||
probability.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?;
|
||||
probability.resize(4, 0);
|
||||
}
|
||||
let mut ids = zeroed(self.rows * 4, read_ids)?;
|
||||
let mut probability = zeroed(4, prob)?;
|
||||
let settled = self.issue_guarded(commands, (read_ids, prob), (&mut ids, &mut probability))?;
|
||||
self.settle(settled, (&mut ids, &mut probability))?;
|
||||
Ok((ids, if prob { probability.try_into().expect("four bytes") } else { [0; 4] }))
|
||||
}
|
||||
/// Launches, reads the requested outputs back and drains inside one entered context;
|
||||
/// returns the `(operation, sync, pop)` results.
|
||||
fn issue_guarded(
|
||||
&self,
|
||||
commands: &mut [Launch],
|
||||
(read_ids, prob): (bool, bool),
|
||||
(ids, probability): (&mut [u8], &mut [u8]),
|
||||
) -> Result<(Result<()>, Result<()>, Result<()>)> {
|
||||
let guard = self.context.enter()?;
|
||||
let operation = self.launch_all(commands)?;
|
||||
let operation = self.read_outputs(operation, (read_ids, prob), (ids, probability))?;
|
||||
let sync = self.context.driver.api.synchronize();
|
||||
let pop = guard.finish();
|
||||
Ok((operation, sync, pop))
|
||||
}
|
||||
fn launch_all(&self, commands: &mut [Launch]) -> Result<Result<()>> {
|
||||
let mut operation = Ok(());
|
||||
for command in commands {
|
||||
if operation.is_ok() {
|
||||
@@ -34,29 +45,40 @@ impl<'ctx> OriginalSampler<'ctx> {
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(operation)
|
||||
}
|
||||
fn read_outputs(
|
||||
&self,
|
||||
mut operation: Result<()>,
|
||||
(read_ids, prob): (bool, bool),
|
||||
(ids, probability): (&mut [u8], &mut [u8]),
|
||||
) -> Result<Result<()>> {
|
||||
if operation.is_ok() && read_ids {
|
||||
operation =
|
||||
self.context.driver.api.copy_to(self.buffer(2)?.handle.ok_or(Error::ContextPoisoned)?, &mut ids);
|
||||
operation = self.copy_buffer_out(2, ids)?;
|
||||
}
|
||||
if operation.is_ok() && prob {
|
||||
operation = self
|
||||
.context
|
||||
.driver
|
||||
.api
|
||||
.copy_to(self.buffer(5)?.handle.ok_or(Error::ContextPoisoned)?, &mut probability);
|
||||
operation = self.copy_buffer_out(5, probability)?;
|
||||
}
|
||||
let sync = self.context.driver.api.synchronize();
|
||||
let pop = guard.finish();
|
||||
Ok(operation)
|
||||
}
|
||||
fn copy_buffer_out(&self, slot: usize, bytes: &mut [u8]) -> Result<Result<()>> {
|
||||
let handle = self.buffer(slot)?.handle.ok_or(Error::ContextPoisoned)?;
|
||||
Ok(self.context.driver.api.copy_to(handle, bytes))
|
||||
}
|
||||
/// A failed drain or pop retains the host buffers (the device may still write them) and reports the combined error.
|
||||
fn settle(
|
||||
&mut self,
|
||||
(operation, sync, pop): (Result<()>, Result<()>, Result<()>),
|
||||
(ids, probability): (&mut Vec<u8>, &mut Vec<u8>),
|
||||
) -> Result<()> {
|
||||
if operation.is_err() || sync.is_err() || pop.is_err() {
|
||||
self.failed = true;
|
||||
self.context.poisoned.set(true);
|
||||
}
|
||||
if sync.is_err() || pop.is_err() {
|
||||
std::mem::forget((ids, probability));
|
||||
return combine(combine(operation, sync), pop).map(|()| (Vec::new(), [0; 4]));
|
||||
std::mem::forget((std::mem::take(ids), std::mem::take(probability)));
|
||||
}
|
||||
combine(combine(operation, sync), pop)?;
|
||||
Ok((ids, if prob { probability.try_into().expect("four bytes") } else { [0; 4] }))
|
||||
combine(combine(operation, sync), pop)
|
||||
}
|
||||
/// One actual verify window. Histories are actual row-specific IDs from the
|
||||
/// caller's consumed tail/window, not a capability or inferred accepted prefix.
|
||||
@@ -70,6 +92,19 @@ impl<'ctx> OriginalSampler<'ctx> {
|
||||
captured: bool,
|
||||
) -> Result<Box<[i32]>> {
|
||||
params.validate()?;
|
||||
self.check_sample_request(rows, histories, ¶ms)?;
|
||||
self.admit(logits, rows * self.vocab * 4)?;
|
||||
let split = self.wants_split(rows, ¶ms, path, captured)?;
|
||||
self.upload_histories(histories)?;
|
||||
let mut commands = self.sample_commands(logits, rows, params, path, split)?;
|
||||
let result = self.run(&mut commands, true, false);
|
||||
if self.context.is_poisoned() {
|
||||
std::mem::forget(commands);
|
||||
}
|
||||
let (bytes, _) = result?;
|
||||
self.decode_ids(&bytes, rows)
|
||||
}
|
||||
fn check_sample_request(&self, rows: usize, histories: &[i32], params: &SamplerParams) -> Result<()> {
|
||||
if rows == 0
|
||||
|| rows > self.rows
|
||||
|| histories.len() != rows * self.history
|
||||
@@ -80,114 +115,62 @@ impl<'ctx> OriginalSampler<'ctx> {
|
||||
if params.penalty_last_n > 0 && self.history == 0 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
self.admit(logits, rows * self.vocab * 4)?;
|
||||
let split = path == SamplerPath::Split
|
||||
Ok(())
|
||||
}
|
||||
fn wants_split(&mut self, rows: usize, params: &SamplerParams, path: SamplerPath, captured: bool) -> Result<bool> {
|
||||
Ok(path == SamplerPath::Split
|
||||
&& !captured
|
||||
&& !params.greedy
|
||||
&& params.temperature > 0.0
|
||||
&& self.split_scratch(rows.max(16) * self.vocab.div_ceil(4096) * 64)?;
|
||||
&& self.split_scratch(rows.max(16) * self.vocab.div_ceil(4096) * 64)?)
|
||||
}
|
||||
/// The row histories, little endian and `-1` padded, into the history buffer.
|
||||
fn upload_histories(&mut self, histories: &[i32]) -> Result<()> {
|
||||
let mut h = Vec::new();
|
||||
h.try_reserve_exact(self.rows * self.history.max(1) * 4).map_err(|_| Error::HostAllocation)?;
|
||||
for id in histories {
|
||||
h.extend_from_slice(&id.to_le_bytes());
|
||||
}
|
||||
h.resize(self.rows * self.history.max(1) * 4, 0xff);
|
||||
self.upload(1, &h)?;
|
||||
self.upload(1, &h)
|
||||
}
|
||||
fn sample_commands(
|
||||
&self,
|
||||
logits: &DeviceBuffer<'_>,
|
||||
rows: usize,
|
||||
params: SamplerParams,
|
||||
path: SamplerPath,
|
||||
split: bool,
|
||||
) -> Result<Vec<Launch>> {
|
||||
let source = logits.handle.ok_or(Error::ContextPoisoned)?.qwen_address();
|
||||
let history = if self.history > 0 { Arg::Address(self.address(1)?) } else { Arg::NullAddress };
|
||||
let output = self.address(2)?;
|
||||
let nv = self.vocab as i32;
|
||||
let nt = rows as i32;
|
||||
let shared = if params.penalty_last_n > 0 { self.vocab.div_ceil(32) as u32 * 4 } else { 0 };
|
||||
let mut commands = Vec::new();
|
||||
commands.try_reserve_exact(2).map_err(|_| Error::HostAllocation)?;
|
||||
let a = SampleArgs { source, history, output, shared, rows, nv: self.vocab as i32, hist: self.history as i32 };
|
||||
if params.greedy || params.temperature <= 0.0 {
|
||||
commands.push(Launch::new(
|
||||
0,
|
||||
[rows as u32, 1],
|
||||
1024,
|
||||
shared,
|
||||
vec![
|
||||
Arg::Address(source),
|
||||
Arg::I32(nv),
|
||||
history,
|
||||
Arg::I32(self.history as i32),
|
||||
Arg::Params(params),
|
||||
Arg::I32(params.penalty_last_n),
|
||||
Arg::I32(params.penalty_last_n),
|
||||
Arg::Address(output),
|
||||
],
|
||||
));
|
||||
commands.push(a.greedy(params));
|
||||
} else if path == SamplerPath::Old {
|
||||
commands.push(Launch::new(
|
||||
1,
|
||||
[rows as u32, 1],
|
||||
1024,
|
||||
shared,
|
||||
vec![
|
||||
Arg::Address(source),
|
||||
Arg::I32(nv),
|
||||
Arg::I32(nt),
|
||||
history,
|
||||
Arg::I32(self.history as i32),
|
||||
Arg::Params(params),
|
||||
Arg::Address(output),
|
||||
],
|
||||
));
|
||||
commands.push(a.old(params));
|
||||
} else if split {
|
||||
let k = (if params.top_k > 0 && params.top_k < 64 { params.top_k } else { 64 }).min(nv);
|
||||
let blocks = self.vocab.div_ceil(4096) as i32;
|
||||
commands.push(Launch::new(
|
||||
3,
|
||||
[blocks as u32, rows as u32],
|
||||
128,
|
||||
0,
|
||||
vec![
|
||||
Arg::Address(source),
|
||||
Arg::I32(nv),
|
||||
history,
|
||||
Arg::I32(self.history as i32),
|
||||
Arg::Params(params),
|
||||
Arg::I32(k),
|
||||
Arg::I32(blocks),
|
||||
Arg::Address(self.address(0)?),
|
||||
],
|
||||
));
|
||||
commands.push(Launch::new(
|
||||
4,
|
||||
[rows as u32, 1],
|
||||
32,
|
||||
0,
|
||||
vec![
|
||||
Arg::Address(self.address(0)?),
|
||||
Arg::I32(blocks),
|
||||
Arg::I32(nv),
|
||||
Arg::Params(params),
|
||||
Arg::I32(k),
|
||||
Arg::Address(output),
|
||||
],
|
||||
));
|
||||
self.push_split(&mut commands, a, params)?;
|
||||
} else {
|
||||
commands.push(Launch::new(
|
||||
2,
|
||||
[rows as u32, 1],
|
||||
1024,
|
||||
shared,
|
||||
vec![
|
||||
Arg::Address(source),
|
||||
Arg::I32(nv),
|
||||
history,
|
||||
Arg::I32(self.history as i32),
|
||||
Arg::Params(params),
|
||||
Arg::Address(output),
|
||||
],
|
||||
));
|
||||
commands.push(a.fused(params));
|
||||
}
|
||||
let result = self.run(&mut commands, true, false);
|
||||
if self.context.is_poisoned() {
|
||||
std::mem::forget(commands);
|
||||
}
|
||||
let (bytes, _) = result?;
|
||||
Ok(commands)
|
||||
}
|
||||
fn push_split(&self, commands: &mut Vec<Launch>, a: SampleArgs, params: SamplerParams) -> Result<()> {
|
||||
let k = (if params.top_k > 0 && params.top_k < 64 { params.top_k } else { 64 }).min(a.nv);
|
||||
let blocks = self.vocab.div_ceil(4096) as i32;
|
||||
let (rows, nv, output) = (a.rows, a.nv, a.output);
|
||||
commands.push(a.split_partial(params, (k, blocks), self.address(0)?));
|
||||
commands.push(split_merge((rows, nv, output), params, (k, blocks), self.address(0)?));
|
||||
Ok(())
|
||||
}
|
||||
/// The sampled token ids of the rows; an id outside the vocabulary fails the sampler.
|
||||
fn decode_ids(&mut self, bytes: &[u8], rows: usize) -> Result<Box<[i32]>> {
|
||||
let nv = self.vocab as i32;
|
||||
let mut ids = Vec::new();
|
||||
ids.try_reserve_exact(rows).map_err(|_| Error::HostAllocation)?;
|
||||
for b in bytes[..rows * 4].chunks_exact(4) {
|
||||
@@ -201,3 +184,118 @@ impl<'ctx> OriginalSampler<'ctx> {
|
||||
Ok(ids.into_boxed_slice())
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` zeroed bytes when `wanted`, else nothing.
|
||||
fn zeroed(n: usize, wanted: bool) -> Result<Vec<u8>> {
|
||||
let mut v = Vec::new();
|
||||
if wanted {
|
||||
v.try_reserve_exact(n).map_err(|_| Error::HostAllocation)?;
|
||||
v.resize(n, 0);
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// The values every launch of one verify window shares.
|
||||
struct SampleArgs {
|
||||
source: u64,
|
||||
history: Arg,
|
||||
output: u64,
|
||||
shared: u32,
|
||||
rows: usize,
|
||||
nv: i32,
|
||||
hist: i32,
|
||||
}
|
||||
|
||||
fn split_merge(
|
||||
(rows, nv, output): (usize, i32, u64),
|
||||
params: SamplerParams,
|
||||
(k, blocks): (i32, i32),
|
||||
scratch: u64,
|
||||
) -> Launch {
|
||||
Launch::new(
|
||||
4,
|
||||
[rows as u32, 1],
|
||||
32,
|
||||
0,
|
||||
vec![
|
||||
Arg::Address(scratch),
|
||||
Arg::I32(blocks),
|
||||
Arg::I32(nv),
|
||||
Arg::Params(params),
|
||||
Arg::I32(k),
|
||||
Arg::Address(output),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
impl SampleArgs {
|
||||
fn split_partial(self, params: SamplerParams, (k, blocks): (i32, i32), scratch: u64) -> Launch {
|
||||
Launch::new(
|
||||
3,
|
||||
[blocks as u32, self.rows as u32],
|
||||
128,
|
||||
0,
|
||||
vec![
|
||||
Arg::Address(self.source),
|
||||
Arg::I32(self.nv),
|
||||
self.history,
|
||||
Arg::I32(self.hist),
|
||||
Arg::Params(params),
|
||||
Arg::I32(k),
|
||||
Arg::I32(blocks),
|
||||
Arg::Address(scratch),
|
||||
],
|
||||
)
|
||||
}
|
||||
fn greedy(self, params: SamplerParams) -> Launch {
|
||||
Launch::new(
|
||||
0,
|
||||
[self.rows as u32, 1],
|
||||
1024,
|
||||
self.shared,
|
||||
vec![
|
||||
Arg::Address(self.source),
|
||||
Arg::I32(self.nv),
|
||||
self.history,
|
||||
Arg::I32(self.hist),
|
||||
Arg::Params(params),
|
||||
Arg::I32(params.penalty_last_n),
|
||||
Arg::I32(params.penalty_last_n),
|
||||
Arg::Address(self.output),
|
||||
],
|
||||
)
|
||||
}
|
||||
fn old(self, params: SamplerParams) -> Launch {
|
||||
Launch::new(
|
||||
1,
|
||||
[self.rows as u32, 1],
|
||||
1024,
|
||||
self.shared,
|
||||
vec![
|
||||
Arg::Address(self.source),
|
||||
Arg::I32(self.nv),
|
||||
Arg::I32(self.rows as i32),
|
||||
self.history,
|
||||
Arg::I32(self.hist),
|
||||
Arg::Params(params),
|
||||
Arg::Address(self.output),
|
||||
],
|
||||
)
|
||||
}
|
||||
fn fused(self, params: SamplerParams) -> Launch {
|
||||
Launch::new(
|
||||
2,
|
||||
[self.rows as u32, 1],
|
||||
1024,
|
||||
self.shared,
|
||||
vec![
|
||||
Arg::Address(self.source),
|
||||
Arg::I32(self.nv),
|
||||
self.history,
|
||||
Arg::I32(self.hist),
|
||||
Arg::Params(params),
|
||||
Arg::Address(self.output),
|
||||
],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
+90
-61
@@ -40,11 +40,17 @@ impl<'ctx> OriginalSampler<'ctx> {
|
||||
for v in base {
|
||||
bytes.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
self.write_round_staging(params, &bytes)?;
|
||||
self.launch_stage()?;
|
||||
self.next_draft = Some(0);
|
||||
Ok(())
|
||||
}
|
||||
fn write_round_staging(&mut self, params: SamplerParams, bytes: &[u8]) -> Result<()> {
|
||||
let guard = self.context.enter()?;
|
||||
let mapped = self.mapped.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let operation = (|| {
|
||||
mapped.write(0, ¶ms.bytes())?;
|
||||
mapped.write(64, &bytes)?;
|
||||
mapped.write(64, bytes)?;
|
||||
Ok(())
|
||||
})();
|
||||
let pop = guard.finish();
|
||||
@@ -52,7 +58,9 @@ impl<'ctx> OriginalSampler<'ctx> {
|
||||
self.failed = true;
|
||||
self.context.poisoned.set(true);
|
||||
}
|
||||
combine(operation, pop)?;
|
||||
combine(operation, pop)
|
||||
}
|
||||
fn launch_stage(&mut self) -> Result<()> {
|
||||
let mapped = self.mapped.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let mut commands = [Launch::new(
|
||||
5,
|
||||
@@ -72,7 +80,6 @@ impl<'ctx> OriginalSampler<'ctx> {
|
||||
std::mem::forget(commands);
|
||||
}
|
||||
result?;
|
||||
self.next_draft = Some(0);
|
||||
Ok(())
|
||||
}
|
||||
/// Actual single draft logits, genuine caller's cell, successive j in one round.
|
||||
@@ -88,70 +95,92 @@ impl<'ctx> OriginalSampler<'ctx> {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
self.upload(6, &cell.to_le_bytes())?;
|
||||
let blocks = nv.div_ceil(4096) as i32;
|
||||
let kpart = nv.min(64) as i32;
|
||||
let sub = if self.subset.is_some() { Arg::Address(self.address(7)?) } else { Arg::NullAddress };
|
||||
let inverse = if self.subset.is_some() { Arg::Address(self.address(8)?) } else { Arg::NullAddress };
|
||||
let subset_args = self.coupled_subset_args()?;
|
||||
let l = logits.handle.ok_or(Error::ContextPoisoned)?.qwen_address();
|
||||
let mut commands = [
|
||||
Launch::new(
|
||||
6,
|
||||
[1, 1],
|
||||
1024,
|
||||
nv.div_ceil(32) as u32 * 4,
|
||||
vec![
|
||||
Arg::Address(l),
|
||||
Arg::I32(nv as i32),
|
||||
inverse,
|
||||
Arg::I32(self.vocab as i32),
|
||||
Arg::Address(self.address(3)?),
|
||||
Arg::Address(self.address(4)?),
|
||||
Arg::I32(HIST as i32),
|
||||
Arg::I32(j as i32),
|
||||
],
|
||||
),
|
||||
Launch::new(
|
||||
3,
|
||||
[blocks as u32, 1],
|
||||
128,
|
||||
0,
|
||||
vec![
|
||||
Arg::Address(l),
|
||||
Arg::I32(nv as i32),
|
||||
Arg::NullAddress,
|
||||
Arg::I32(0),
|
||||
Arg::Params(SamplerParams::default()),
|
||||
Arg::I32(kpart),
|
||||
Arg::I32(blocks),
|
||||
Arg::Address(self.address(0)?),
|
||||
],
|
||||
),
|
||||
Launch::new(
|
||||
7,
|
||||
[1, 1],
|
||||
32,
|
||||
0,
|
||||
vec![
|
||||
Arg::Address(self.address(0)?),
|
||||
Arg::I32(blocks),
|
||||
Arg::I32(nv as i32),
|
||||
Arg::I32(kpart),
|
||||
Arg::Address(self.address(3)?),
|
||||
Arg::Address(self.address(6)?),
|
||||
sub,
|
||||
Arg::Address(self.address(4)?),
|
||||
Arg::I32(HIST as i32),
|
||||
Arg::I32(j as i32),
|
||||
Arg::Address(self.address(2)?),
|
||||
Arg::Address(self.address(5)?),
|
||||
],
|
||||
),
|
||||
];
|
||||
let mut commands = self.coupled_launches(l, nv, j, subset_args)?;
|
||||
let result = self.run(&mut commands, true, true);
|
||||
if self.context.is_poisoned() {
|
||||
std::mem::forget(commands);
|
||||
}
|
||||
let (ids, p) = result?;
|
||||
self.accept_coupled(&ids, p, j)
|
||||
}
|
||||
/// The subset id map and its inverse as launch arguments (null for the whole vocabulary).
|
||||
fn coupled_subset_args(&self) -> Result<(Arg, Arg)> {
|
||||
let sub = if self.subset.is_some() { Arg::Address(self.address(7)?) } else { Arg::NullAddress };
|
||||
let inverse = if self.subset.is_some() { Arg::Address(self.address(8)?) } else { Arg::NullAddress };
|
||||
Ok((sub, inverse))
|
||||
}
|
||||
/// Literal penalties -> widest split -> coupled merge.
|
||||
fn coupled_launches(&self, l: u64, nv: usize, j: usize, (sub, inverse): (Arg, Arg)) -> Result<[Launch; 3]> {
|
||||
let blocks = nv.div_ceil(4096) as i32;
|
||||
let kpart = nv.min(64) as i32;
|
||||
Ok([
|
||||
self.coupled_penalty_launch(l, nv, j, inverse)?,
|
||||
self.coupled_partial_launch(l, nv, (blocks, kpart))?,
|
||||
self.coupled_merge_launch(nv, j, (blocks, kpart), sub)?,
|
||||
])
|
||||
}
|
||||
fn coupled_penalty_launch(&self, l: u64, nv: usize, j: usize, inverse: Arg) -> Result<Launch> {
|
||||
Ok(Launch::new(
|
||||
6,
|
||||
[1, 1],
|
||||
1024,
|
||||
nv.div_ceil(32) as u32 * 4,
|
||||
vec![
|
||||
Arg::Address(l),
|
||||
Arg::I32(nv as i32),
|
||||
inverse,
|
||||
Arg::I32(self.vocab as i32),
|
||||
Arg::Address(self.address(3)?),
|
||||
Arg::Address(self.address(4)?),
|
||||
Arg::I32(HIST as i32),
|
||||
Arg::I32(j as i32),
|
||||
],
|
||||
))
|
||||
}
|
||||
fn coupled_partial_launch(&self, l: u64, nv: usize, (blocks, kpart): (i32, i32)) -> Result<Launch> {
|
||||
Ok(Launch::new(
|
||||
3,
|
||||
[blocks as u32, 1],
|
||||
128,
|
||||
0,
|
||||
vec![
|
||||
Arg::Address(l),
|
||||
Arg::I32(nv as i32),
|
||||
Arg::NullAddress,
|
||||
Arg::I32(0),
|
||||
Arg::Params(SamplerParams::default()),
|
||||
Arg::I32(kpart),
|
||||
Arg::I32(blocks),
|
||||
Arg::Address(self.address(0)?),
|
||||
],
|
||||
))
|
||||
}
|
||||
fn coupled_merge_launch(&self, nv: usize, j: usize, (blocks, kpart): (i32, i32), sub: Arg) -> Result<Launch> {
|
||||
Ok(Launch::new(
|
||||
7,
|
||||
[1, 1],
|
||||
32,
|
||||
0,
|
||||
vec![
|
||||
Arg::Address(self.address(0)?),
|
||||
Arg::I32(blocks),
|
||||
Arg::I32(nv as i32),
|
||||
Arg::I32(kpart),
|
||||
Arg::Address(self.address(3)?),
|
||||
Arg::Address(self.address(6)?),
|
||||
sub,
|
||||
Arg::Address(self.address(4)?),
|
||||
Arg::I32(HIST as i32),
|
||||
Arg::I32(j as i32),
|
||||
Arg::Address(self.address(2)?),
|
||||
Arg::Address(self.address(5)?),
|
||||
],
|
||||
))
|
||||
}
|
||||
/// The coupled pick of the round's `j`-th draft; an id or probability out of range fails the sampler.
|
||||
fn accept_coupled(&mut self, ids: &[u8], p: [u8; 4], j: usize) -> Result<(i32, f32)> {
|
||||
let id = i32::from_le_bytes(ids[..4].try_into().expect("word"));
|
||||
let probability = f32::from_le_bytes(p);
|
||||
if id < 0 || id as usize >= self.vocab || !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
|
||||
|
||||
+37
-37
@@ -5,60 +5,38 @@ use super::*;
|
||||
|
||||
impl<'ctx> OriginalSampler<'ctx> {
|
||||
pub(in super::super) fn close_inner(&mut self) -> Result<()> {
|
||||
if self.module.is_none()
|
||||
&& self.mapped.is_none()
|
||||
&& self.buffers.iter().all(Option::is_none)
|
||||
&& self.retired.is_empty()
|
||||
{
|
||||
if self.is_released() {
|
||||
return Ok(());
|
||||
}
|
||||
self.failed = true;
|
||||
self.next_draft = None;
|
||||
let mut result = Ok(());
|
||||
for buffer in self.retired.drain(..) {
|
||||
let r = if self.context.is_poisoned() {
|
||||
std::mem::forget(buffer);
|
||||
Err(Error::ContextPoisoned)
|
||||
} else {
|
||||
buffer.release()
|
||||
};
|
||||
if r.is_err() {
|
||||
self.context.poisoned.set(true);
|
||||
}
|
||||
result = combine(result, r);
|
||||
result = combine(result, release_buffer(self.context, buffer));
|
||||
}
|
||||
for slot in &mut self.buffers {
|
||||
if let Some(buffer) = slot.take() {
|
||||
let r = if self.context.is_poisoned() {
|
||||
std::mem::forget(buffer);
|
||||
Err(Error::ContextPoisoned)
|
||||
} else {
|
||||
buffer.release()
|
||||
};
|
||||
if r.is_err() {
|
||||
self.context.poisoned.set(true);
|
||||
}
|
||||
result = combine(result, r);
|
||||
result = combine(result, release_buffer(self.context, buffer));
|
||||
}
|
||||
}
|
||||
self.close_module_and_mapped(result)
|
||||
}
|
||||
fn is_released(&self) -> bool {
|
||||
self.module.is_none()
|
||||
&& self.mapped.is_none()
|
||||
&& self.buffers.iter().all(Option::is_none)
|
||||
&& self.retired.is_empty()
|
||||
}
|
||||
/// The kernel module and the mapped staging go back inside an entered context; on a poisoned one they are retained.
|
||||
fn close_module_and_mapped(&mut self, result: Result<()>) -> Result<()> {
|
||||
if self.context.is_poisoned() {
|
||||
if let Some(module) = self.module.take() {
|
||||
std::mem::forget(module);
|
||||
}
|
||||
if let Some(mapped) = self.mapped.take() {
|
||||
std::mem::forget(mapped);
|
||||
}
|
||||
self.retain_module_and_mapped();
|
||||
return combine(result, Err(Error::ContextPoisoned));
|
||||
}
|
||||
let guard = match self.context.enter() {
|
||||
Ok(g) => g,
|
||||
Err(e) => {
|
||||
if let Some(m) = self.module.take() {
|
||||
std::mem::forget(m);
|
||||
}
|
||||
if let Some(m) = self.mapped.take() {
|
||||
std::mem::forget(m);
|
||||
}
|
||||
self.retain_module_and_mapped();
|
||||
return combine(result, Err(e));
|
||||
}
|
||||
};
|
||||
@@ -70,4 +48,26 @@ impl<'ctx> OriginalSampler<'ctx> {
|
||||
}
|
||||
combine(combine(combine(result, module), mapped), pop)
|
||||
}
|
||||
fn retain_module_and_mapped(&mut self) {
|
||||
if let Some(module) = self.module.take() {
|
||||
std::mem::forget(module);
|
||||
}
|
||||
if let Some(mapped) = self.mapped.take() {
|
||||
std::mem::forget(mapped);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Releases one buffer, or retains it on a poisoned context; a failure poisons the context.
|
||||
fn release_buffer(context: &Context<'_>, buffer: DeviceBuffer<'_>) -> Result<()> {
|
||||
let r = if context.is_poisoned() {
|
||||
std::mem::forget(buffer);
|
||||
Err(Error::ContextPoisoned)
|
||||
} else {
|
||||
buffer.release()
|
||||
};
|
||||
if r.is_err() {
|
||||
context.poisoned.set(true);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
@@ -68,6 +68,34 @@ mod enabled {
|
||||
fn check(op: &'static str, c: c_int) -> Result<()> {
|
||||
if c == 0 { Ok(()) } else { Err(Error::Driver { operation: op, code: c }) }
|
||||
}
|
||||
fn check_launch_shape(grid: [u32; 2], block: u32, shared: u32) -> Result<()> {
|
||||
if grid[0] == 0 || grid[1] == 0 || !matches!(block, 32 | 128 | 256 | 1024) || shared > 32768 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Rebuilds the parameter pointer array of `args` (and the uint64 parameter slots it points to).
|
||||
fn bind_arguments(args: &mut Command) -> Result<()> {
|
||||
args.pointers.clear();
|
||||
args.pointers.try_reserve_exact(args.values.len()).map_err(|_| Error::HostAllocation)?;
|
||||
args.addresses.clear();
|
||||
args.addresses.try_reserve_exact(args.values.len()).map_err(|_| Error::HostAllocation)?;
|
||||
args.addresses.resize(args.values.len(), 0);
|
||||
for (index, arg) in args.values.iter_mut().enumerate() {
|
||||
args.pointers.push(match arg {
|
||||
Arg::Address(x) => {
|
||||
// CUDA consumes an actual uint64_t parameter, never
|
||||
// the unspecified Rust representation of BufferHandle.
|
||||
args.addresses[index] = *x;
|
||||
(&mut args.addresses[index] as *mut u64).cast()
|
||||
}
|
||||
Arg::NullAddress => (&mut args.null as *mut u64).cast(),
|
||||
Arg::I32(x) => (x as *mut i32).cast(),
|
||||
Arg::Params(x) => (x as *mut SamplerParams).cast(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) struct KernelModule {
|
||||
_library: Option<Library>,
|
||||
module: Option<usize>,
|
||||
@@ -91,28 +119,34 @@ mod enabled {
|
||||
functions: Vec::new(),
|
||||
};
|
||||
owner.functions.try_reserve_exact(entries.len()).map_err(|_| Error::HostAllocation)?;
|
||||
let result = (|| {
|
||||
let mut m = std::ptr::null_mut(); // SAFETY: actual immutable pinned NUL PTX.
|
||||
check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?;
|
||||
if m.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuModuleLoadData"));
|
||||
}
|
||||
owner.module = Some(m as usize);
|
||||
for entry in entries {
|
||||
let mut f = std::ptr::null_mut(); // SAFETY: real module, static declared symbol.
|
||||
check("cuModuleGetFunction", unsafe { function(&mut f, m, entry.as_ptr()) })?;
|
||||
if f.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuModuleGetFunction"));
|
||||
}
|
||||
owner.functions.push(f as usize);
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(e) = result {
|
||||
if let Err(e) = owner.load_functions(load, function, ptx, entries) {
|
||||
return combine(Err(e), owner.close());
|
||||
}
|
||||
Ok(owner)
|
||||
}
|
||||
fn load_functions(
|
||||
&mut self,
|
||||
load: ModuleLoad,
|
||||
function: ModuleFunction,
|
||||
ptx: &'static [u8],
|
||||
entries: &'static [&'static CStr],
|
||||
) -> Result<()> {
|
||||
let mut m = std::ptr::null_mut(); // SAFETY: actual immutable pinned NUL PTX.
|
||||
check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?;
|
||||
if m.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuModuleLoadData"));
|
||||
}
|
||||
self.module = Some(m as usize);
|
||||
for entry in entries {
|
||||
let mut f = std::ptr::null_mut(); // SAFETY: real module, static declared symbol.
|
||||
check("cuModuleGetFunction", unsafe { function(&mut f, m, entry.as_ptr()) })?;
|
||||
if f.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuModuleGetFunction"));
|
||||
}
|
||||
self.functions.push(f as usize);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn launch(
|
||||
&self,
|
||||
index: usize,
|
||||
@@ -121,28 +155,9 @@ mod enabled {
|
||||
shared: u32,
|
||||
args: &mut Command,
|
||||
) -> Result<()> {
|
||||
if grid[0] == 0 || grid[1] == 0 || !matches!(block, 32 | 128 | 256 | 1024) || shared > 32768 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
check_launch_shape(grid, block, shared)?;
|
||||
let function = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?;
|
||||
args.pointers.clear();
|
||||
args.pointers.try_reserve_exact(args.values.len()).map_err(|_| Error::HostAllocation)?;
|
||||
args.addresses.clear();
|
||||
args.addresses.try_reserve_exact(args.values.len()).map_err(|_| Error::HostAllocation)?;
|
||||
args.addresses.resize(args.values.len(), 0);
|
||||
for (index, arg) in args.values.iter_mut().enumerate() {
|
||||
args.pointers.push(match arg {
|
||||
Arg::Address(x) => {
|
||||
// CUDA consumes an actual uint64_t parameter, never
|
||||
// the unspecified Rust representation of BufferHandle.
|
||||
args.addresses[index] = *x;
|
||||
(&mut args.addresses[index] as *mut u64).cast()
|
||||
}
|
||||
Arg::NullAddress => (&mut args.null as *mut u64).cast(),
|
||||
Arg::I32(x) => (x as *mut i32).cast(),
|
||||
Arg::Params(x) => (x as *mut SamplerParams).cast(),
|
||||
});
|
||||
}
|
||||
bind_arguments(args)?;
|
||||
// SAFETY: owned boxed command fields and exact producer-declared
|
||||
// ABI persist until drain; Driver copies the parameter pointer array
|
||||
// during this call. No pointer/entry escapes to public callers.
|
||||
|
||||
@@ -41,8 +41,9 @@ mod enabled {
|
||||
free: Free,
|
||||
}
|
||||
impl MappedAllocation {
|
||||
pub(crate) fn new() -> Result<Self> {
|
||||
// SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next.
|
||||
fn open_driver() -> Result<(Library, Alloc, Address, Free)> {
|
||||
// SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and
|
||||
// null-checked next.
|
||||
let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) });
|
||||
if library.0.is_null() {
|
||||
return Err(Error::LibraryUnavailable);
|
||||
@@ -50,9 +51,14 @@ mod enabled {
|
||||
let alloc = sym!(library, c"cuMemHostAlloc", Alloc);
|
||||
let address = sym!(library, c"cuMemHostGetDevicePointer_v2", Address);
|
||||
let free = sym!(library, c"cuMemFreeHost", Free);
|
||||
Ok((library, alloc, address, free))
|
||||
}
|
||||
pub(crate) fn new() -> Result<Self> {
|
||||
let (library, alloc, address, free) = Self::open_driver()?;
|
||||
let mut ptr = std::ptr::null_mut();
|
||||
// SAFETY: valid out-pointer, nonzero size, flags 3 = PORTABLE|DEVICEMAP; the pointer is null-checked below. The block is
|
||||
// owned by this type and released only by an explicit close() (Drop deliberately leaks instead of freeing).
|
||||
// SAFETY: valid out-pointer, nonzero size, flags 3 = PORTABLE|DEVICEMAP; the pointer is null-checked below.
|
||||
// The block is owned by this type and released only by an explicit close() (Drop deliberately leaks instead
|
||||
// of freeing).
|
||||
check("cuMemHostAlloc", unsafe { alloc(&mut ptr, BYTES, 3) })?;
|
||||
if ptr.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuMemHostAlloc"));
|
||||
@@ -68,8 +74,8 @@ mod enabled {
|
||||
let _ = owner.close();
|
||||
return Err(Error::InvalidDriverValue("mapped-host-alignment"));
|
||||
}
|
||||
// SAFETY: `ptr` is the whole freshly allocated block of `bytes` bytes and no GPU work references it yet; zeroing makes
|
||||
// the block fully initialized before the first CPU read.
|
||||
// SAFETY: `ptr` is the whole freshly allocated block of `bytes` bytes and no GPU work references it yet;
|
||||
// zeroing makes the block fully initialized before the first CPU read.
|
||||
unsafe {
|
||||
std::ptr::write_bytes(ptr.cast::<u8>(), 0, BYTES);
|
||||
} // initialized final whole owner; never resized.
|
||||
|
||||
@@ -81,6 +81,41 @@ fn zero_spans(layout: &OriginalSessionQsaLayout) -> Result<Vec<OriginalSessionSp
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Exactly two mandatory mapped allocations, then initialized host_step[kStepCount]=0; the authoritative KV block
|
||||
/// only for the resident and streamed modes.
|
||||
fn mapped_hosts<B: OriginalQsaInitBackend>(
|
||||
backend: &mut B,
|
||||
layout: &OriginalSessionQsaLayout,
|
||||
) -> Result<(B::MappedHost, B::MappedHost, Option<B::MappedHost>)> {
|
||||
let mut host_step = backend.mapped_host(layout.host_step_bytes)?;
|
||||
let host_pos = backend.mapped_host(layout.host_position_bytes)?;
|
||||
backend.mapped_write_i32(&mut host_step, 4, 0)?;
|
||||
let host_kv = if layout.mode != 0 { Some(backend.mapped_host(layout.host_kv_bytes)?) } else { None };
|
||||
Ok((host_step, host_pos, host_kv))
|
||||
}
|
||||
|
||||
/// The page table (or stream map) of the state's KV mode.
|
||||
fn init_page_table<B: OriginalQsaInitBackend>(backend: &mut B, layout: &OriginalSessionQsaLayout) -> Result<()> {
|
||||
match layout.mode {
|
||||
0 => upload_identity_page_table(backend, layout),
|
||||
1 => backend.reset_stream_map(layout),
|
||||
2 => backend.install_ring_table(layout.span("page_table")?, layout.pages, layout.slots),
|
||||
_ => Err(Error::InvalidQwenShape),
|
||||
}
|
||||
}
|
||||
|
||||
fn upload_identity_page_table<B: OriginalQsaInitBackend>(
|
||||
backend: &mut B,
|
||||
layout: &OriginalSessionQsaLayout,
|
||||
) -> Result<()> {
|
||||
let mut identity = Vec::new();
|
||||
identity.try_reserve_exact(layout.pages).map_err(|_| Error::HostAllocation)?;
|
||||
for page in 0..layout.pages {
|
||||
identity.push(i32::try_from(page).map_err(|_| Error::InvalidSize)?);
|
||||
}
|
||||
backend.upload(layout.span("page_table")?, &bytes_i32(&identity))
|
||||
}
|
||||
|
||||
impl<'ctx> OriginalSessionState<'ctx> {
|
||||
/// Initializes one pre-carved QSA state, preserving source order. `primary`
|
||||
/// has `owns_rope`; all later states share its exact two device spans.
|
||||
@@ -93,6 +128,15 @@ impl<'ctx> OriginalSessionState<'ctx> {
|
||||
scaling: OriginalRopeScaling,
|
||||
) -> Result<OriginalQsaInitResources<B::MappedHost>> {
|
||||
self.validate_context(self.context)?;
|
||||
let layout = self.checked_qsa_layout(ordinal, n_rot)?;
|
||||
let (host_step, host_pos, host_kv) = mapped_hosts(backend, &layout)?;
|
||||
self.init_rope(backend, ordinal, &layout, n_rot, scaling)?;
|
||||
init_page_table(backend, &layout)?;
|
||||
backend.synchronize()?;
|
||||
Ok(OriginalQsaInitResources { host_step, host_pos, host_kv })
|
||||
}
|
||||
|
||||
fn checked_qsa_layout(&self, ordinal: usize, n_rot: usize) -> Result<OriginalSessionQsaLayout> {
|
||||
let primary_ordinal = self.layout.qsa_ord0;
|
||||
let layout = self.layout.qsa.get(ordinal).and_then(Option::as_ref).ok_or(Error::InvalidQwenShape)?.clone();
|
||||
if ordinal < primary_ordinal
|
||||
@@ -106,21 +150,20 @@ impl<'ctx> OriginalSessionState<'ctx> {
|
||||
if layout.kv_hybrid && layout.mode == 1 {
|
||||
return Err(Error::UnsupportedQwenOperation);
|
||||
}
|
||||
Ok(layout)
|
||||
}
|
||||
|
||||
// Exactly two mandatory mapped allocations, then initialized host_step[kStepCount]=0.
|
||||
let mut host_step = backend.mapped_host(layout.host_step_bytes)?;
|
||||
let host_pos = backend.mapped_host(layout.host_position_bytes)?;
|
||||
backend.mapped_write_i32(&mut host_step, 4, 0)?;
|
||||
let host_kv = if layout.mode != 0 { Some(backend.mapped_host(layout.host_kv_bytes)?) } else { None };
|
||||
|
||||
if ordinal == primary_ordinal {
|
||||
let table = OriginalRopeTable::build(n_rot, self.layout.max_cells, scaling)?;
|
||||
let upload = table.upload_plan(layout.cos, layout.sin)?;
|
||||
backend.upload(upload.cos, &bytes_f32(&table.cos))?;
|
||||
backend.upload(upload.sin, &bytes_f32(&table.sin))?;
|
||||
if upload.registry_required {
|
||||
backend.register_native_rope(upload.cos, upload.sin, self.layout.max_cells, scaling)?;
|
||||
}
|
||||
/// The primary state builds and uploads the RoPE tables; every later state shares its exact two device spans.
|
||||
fn init_rope<B: OriginalQsaInitBackend>(
|
||||
&mut self,
|
||||
backend: &mut B,
|
||||
ordinal: usize,
|
||||
layout: &OriginalSessionQsaLayout,
|
||||
n_rot: usize,
|
||||
scaling: OriginalRopeScaling,
|
||||
) -> Result<()> {
|
||||
if ordinal == self.layout.qsa_ord0 {
|
||||
self.upload_rope(backend, layout, n_rot, scaling)?;
|
||||
self.layout.qsa[ordinal].as_mut().ok_or(Error::InvalidQwenShape)?.owns_rope = true;
|
||||
} else {
|
||||
let primary = self.layout.qsa_primary()?;
|
||||
@@ -128,22 +171,24 @@ impl<'ctx> OriginalSessionState<'ctx> {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
match layout.mode {
|
||||
0 => {
|
||||
let mut identity = Vec::new();
|
||||
identity.try_reserve_exact(layout.pages).map_err(|_| Error::HostAllocation)?;
|
||||
for page in 0..layout.pages {
|
||||
identity.push(i32::try_from(page).map_err(|_| Error::InvalidSize)?);
|
||||
}
|
||||
backend.upload(layout.span("page_table")?, &bytes_i32(&identity))?;
|
||||
}
|
||||
1 => backend.reset_stream_map(&layout)?,
|
||||
2 => backend.install_ring_table(layout.span("page_table")?, layout.pages, layout.slots)?,
|
||||
_ => return Err(Error::InvalidQwenShape),
|
||||
fn upload_rope<B: OriginalQsaInitBackend>(
|
||||
&self,
|
||||
backend: &mut B,
|
||||
layout: &OriginalSessionQsaLayout,
|
||||
n_rot: usize,
|
||||
scaling: OriginalRopeScaling,
|
||||
) -> Result<()> {
|
||||
let table = OriginalRopeTable::build(n_rot, self.layout.max_cells, scaling)?;
|
||||
let upload = table.upload_plan(layout.cos, layout.sin)?;
|
||||
backend.upload(upload.cos, &bytes_f32(&table.cos))?;
|
||||
backend.upload(upload.sin, &bytes_f32(&table.sin))?;
|
||||
if upload.registry_required {
|
||||
backend.register_native_rope(upload.cos, upload.sin, self.layout.max_cells, scaling)?;
|
||||
}
|
||||
backend.synchronize()?;
|
||||
Ok(OriginalQsaInitResources { host_step, host_pos, host_kv })
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Literal QSA part of `session_zero`: K/V pools and the three indexer
|
||||
|
||||
@@ -118,6 +118,44 @@ fn yarn_ramp(low: f32, high: f32, pair: usize) -> f32 {
|
||||
1.0 - (((pair as f32 - low) / denom).clamp(0.0, 1.0))
|
||||
}
|
||||
|
||||
/// `build_rope_table(int,double,...)`, statement order preserved. `shape` is `(n_rot, max_positions)`.
|
||||
fn fill_plain(cos: &mut [f32], sin: &mut [f32], shape: (usize, usize), scaling: &OriginalRopeScaling) {
|
||||
let (n_rot, max_positions) = shape;
|
||||
let half = n_rot / 2;
|
||||
for p in 0..max_positions {
|
||||
for i in 0..half {
|
||||
let inv = scaling.freq_base.powf(-2.0 * i as f64 / n_rot as f64);
|
||||
let ang = p as f64 * inv;
|
||||
cos[p * half + i] = ang.cos() as f32;
|
||||
sin[p * half + i] = ang.sin() as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The scaled (YaRN) form of the table.
|
||||
fn fill_scaled(cos: &mut [f32], sin: &mut [f32], shape: (usize, usize), scaling: &OriginalRopeScaling) {
|
||||
let (n_rot, max_positions) = shape;
|
||||
let half = n_rot / 2;
|
||||
let fs = scaling.freq_scale();
|
||||
let ms = scaling.mscale();
|
||||
let (low, high) = scaling.corr_dims(n_rot);
|
||||
let correct = scaling.ext_factor != 0.0;
|
||||
for p in 0..max_positions {
|
||||
for i in 0..half {
|
||||
let inv = scaling.freq_base.powf(-2.0 * i as f64 / n_rot as f64);
|
||||
let extrap = p as f64 * inv;
|
||||
let interp = fs * extrap;
|
||||
let mut ang = interp;
|
||||
if correct {
|
||||
let ramp = yarn_ramp(low as f32, high as f32, i) as f64 * scaling.ext_factor;
|
||||
ang = interp * (1.0 - ramp) + extrap * ramp;
|
||||
}
|
||||
cos[p * half + i] = (ang.cos() * ms) as f32;
|
||||
sin[p * half + i] = (ang.sin() * ms) as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The two independently-owned host tables that source creates before H2D.
|
||||
pub(crate) struct OriginalRopeTable {
|
||||
pub(crate) n_rot: usize,
|
||||
@@ -143,34 +181,9 @@ impl OriginalRopeTable {
|
||||
sin.resize(len, 0.0);
|
||||
|
||||
if scaling.kind == OriginalRopeScalingType::None {
|
||||
// `build_rope_table(int,double,...)`, statement order preserved.
|
||||
for p in 0..max_positions {
|
||||
for i in 0..half {
|
||||
let inv = scaling.freq_base.powf(-2.0 * i as f64 / n_rot as f64);
|
||||
let ang = p as f64 * inv;
|
||||
cos[p * half + i] = ang.cos() as f32;
|
||||
sin[p * half + i] = ang.sin() as f32;
|
||||
}
|
||||
}
|
||||
fill_plain(&mut cos, &mut sin, (n_rot, max_positions), &scaling);
|
||||
} else {
|
||||
let fs = scaling.freq_scale();
|
||||
let ms = scaling.mscale();
|
||||
let (low, high) = scaling.corr_dims(n_rot);
|
||||
let correct = scaling.ext_factor != 0.0;
|
||||
for p in 0..max_positions {
|
||||
for i in 0..half {
|
||||
let inv = scaling.freq_base.powf(-2.0 * i as f64 / n_rot as f64);
|
||||
let extrap = p as f64 * inv;
|
||||
let interp = fs * extrap;
|
||||
let mut ang = interp;
|
||||
if correct {
|
||||
let ramp = yarn_ramp(low as f32, high as f32, i) as f64 * scaling.ext_factor;
|
||||
ang = interp * (1.0 - ramp) + extrap * ramp;
|
||||
}
|
||||
cos[p * half + i] = (ang.cos() * ms) as f32;
|
||||
sin[p * half + i] = (ang.sin() * ms) as f32;
|
||||
}
|
||||
}
|
||||
fill_scaled(&mut cos, &mut sin, (n_rot, max_positions), &scaling);
|
||||
}
|
||||
Ok(Self { n_rot, max_positions, scaling, cos, sin })
|
||||
}
|
||||
|
||||
@@ -46,8 +46,8 @@ impl OriginalSessionGeometry {
|
||||
n_ff: 640,
|
||||
}
|
||||
}
|
||||
pub(super) fn validate(self) -> Result<()> {
|
||||
if [
|
||||
fn dimensions(self) -> [usize; 17] {
|
||||
[
|
||||
self.n_embd,
|
||||
self.n_layers,
|
||||
self.qsa_interval,
|
||||
@@ -66,9 +66,9 @@ impl OriginalSessionGeometry {
|
||||
self.experts,
|
||||
self.n_ff,
|
||||
]
|
||||
.contains(&0)
|
||||
|| self.conv_width < 1
|
||||
{
|
||||
}
|
||||
pub(super) fn validate(self) -> Result<()> {
|
||||
if self.dimensions().contains(&0) || self.conv_width < 1 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
// The actual linked split-K scratch kernel has HD=256, CHUNK=64.
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
mod new_phases;
|
||||
use new_phases::Request;
|
||||
|
||||
impl OriginalSessionLayout {
|
||||
pub(crate) fn new(
|
||||
g: OriginalSessionGeometry,
|
||||
@@ -12,88 +15,13 @@ impl OriginalSessionLayout {
|
||||
hi: i64,
|
||||
p: OriginalSessionKvPolicy,
|
||||
) -> Result<Self> {
|
||||
g.validate()?;
|
||||
if cells == 0 || cells > i32::MAX as usize || k == 0 || k > 64 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let layer_lo = usize::try_from(lo.max(0)).map_err(|_| Error::InvalidSize)?;
|
||||
let layer_hi = if hi < 0 || hi as u64 > g.n_layers as u64 { g.n_layers } else { hi as usize };
|
||||
if layer_lo >= layer_hi || layer_hi > g.n_layers {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let i = g.qsa_interval.max(1);
|
||||
let all_q = g.n_layers / g.qsa_interval;
|
||||
let qsa_ord0 = layer_lo / i;
|
||||
let qr = layer_hi / i - qsa_ord0;
|
||||
let qsa_alloc = qr.max(usize::from(all_q > 0));
|
||||
let gdn_ord0 = layer_lo - layer_lo / i;
|
||||
let gdn_alloc = (layer_hi - layer_lo).saturating_sub(qr);
|
||||
if add(qsa_ord0, qsa_alloc)? > all_q {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let gp = g.gdn_parts()?;
|
||||
let gdn_bytes = sum16(&gp)?;
|
||||
let state = mul(gdn_alloc, g.state_bytes()?)?;
|
||||
let first = qsa_price(g, cells, p, true)?;
|
||||
let rest = qsa_price(g, cells, p, false)?;
|
||||
let qsa_bytes = if all_q > 0 { add(first.charge, mul(qsa_alloc - 1, rest.charge)?)? } else { 0 };
|
||||
let qb = g.qsa_scratch_charge(cells)?;
|
||||
let mp = g.moe_parts(k)?;
|
||||
let mb = sum16(&mp)?;
|
||||
let bb = g.block_charge()?;
|
||||
let hist = product(&[PLE_HIST, PLE_DIM, 4])?;
|
||||
let session_bytes = session_bytes(g, cells, k, lo, hi, p)?;
|
||||
let mut c = Cursor { base: 0, used: 0 };
|
||||
let ga = c.take(gdn_bytes, ALIGN)?;
|
||||
let gdn_state = c.take(state, ALIGN)?;
|
||||
let qsa_state_arena = c.take(qsa_bytes, ALIGN)?;
|
||||
let qa = c.take(qb, ALIGN)?;
|
||||
let mut qsa: Vec<Option<OriginalSessionQsaLayout>> = Vec::new();
|
||||
qsa.try_reserve_exact(all_q).map_err(|_| Error::HostAllocation)?;
|
||||
qsa.resize_with(all_q, || None);
|
||||
for j in 0..qsa_alloc {
|
||||
let offset = if j == 0 { 0 } else { add(first.charge, mul(j - 1, rest.charge)?)? };
|
||||
let price = if j == 0 { &first } else { &rest };
|
||||
let share = if j == 0 {
|
||||
None
|
||||
} else {
|
||||
let primary = qsa[qsa_ord0].as_ref().ok_or(Error::InvalidQwenShape)?;
|
||||
Some((primary.cos, primary.sin))
|
||||
};
|
||||
qsa[qsa_ord0 + j] =
|
||||
Some(qsa_carve(g, cells, p, qsa_ord0 + j, qsa_state_arena.at(offset, price.charge)?, price, share)?);
|
||||
}
|
||||
let ma = c.take(mb, ALIGN)?;
|
||||
let ba = c.take(bb, ALIGN)?;
|
||||
let ple_hist = c.take(hist, ALIGN)?;
|
||||
if c.used > session_bytes {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
let block = parts(ba, g.block_parts()?)?;
|
||||
let gr = parts(block[7], g.gr_parts()?)?;
|
||||
Ok(Self {
|
||||
geometry: g,
|
||||
policy: p,
|
||||
max_cells: cells,
|
||||
k,
|
||||
layer_lo,
|
||||
layer_hi,
|
||||
qsa_ord0,
|
||||
qsa_alloc,
|
||||
gdn_ord0,
|
||||
gdn_alloc,
|
||||
session_bytes,
|
||||
init_used: c.used,
|
||||
gdn: parts(ga, gp)?,
|
||||
gdn_state,
|
||||
qsa_state_arena,
|
||||
qsa,
|
||||
qsa_buffers: parts(qa, g.qsa_scratch_parts(cells)?)?,
|
||||
moe: parts(ma, mp)?,
|
||||
block,
|
||||
gr,
|
||||
ple_hist,
|
||||
})
|
||||
let r = Request { g, cells, k, bounds: (lo, hi), p };
|
||||
r.check()?;
|
||||
let layers = r.layer_range()?;
|
||||
let split = r.split(layers)?;
|
||||
let sizes = r.sizes(&split)?;
|
||||
let carved = r.carve(&split, &sizes)?;
|
||||
r.assemble((layers, &split, &sizes), carved)
|
||||
}
|
||||
pub(crate) fn gdn_point_at(&self, layer: usize) -> Result<Option<(OriginalSessionSpan, OriginalSessionSpan)>> {
|
||||
if layer < self.layer_lo || layer >= self.layer_hi {
|
||||
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
//! Phases of `OriginalSessionLayout::new`, split out by STRA-338 size pass 2.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The inputs of one layout request.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Request {
|
||||
pub g: OriginalSessionGeometry,
|
||||
pub cells: usize,
|
||||
pub k: usize,
|
||||
pub bounds: (i64, i64),
|
||||
pub p: OriginalSessionKvPolicy,
|
||||
}
|
||||
|
||||
/// How the requested layers divide into QSA and GDN states.
|
||||
pub(super) struct Split {
|
||||
pub all_q: usize,
|
||||
pub qsa_ord0: usize,
|
||||
pub qsa_alloc: usize,
|
||||
pub gdn_ord0: usize,
|
||||
pub gdn_alloc: usize,
|
||||
}
|
||||
|
||||
/// Every byte size the carve needs.
|
||||
pub(super) struct Sizes {
|
||||
gp: [usize; 16],
|
||||
mp: [usize; 9],
|
||||
gdn_bytes: usize,
|
||||
state: usize,
|
||||
first: QsaPrice,
|
||||
rest: QsaPrice,
|
||||
qsa_bytes: usize,
|
||||
qb: usize,
|
||||
mb: usize,
|
||||
bb: usize,
|
||||
hist: usize,
|
||||
session_bytes: usize,
|
||||
}
|
||||
|
||||
/// The carved arena regions and the bytes the initialization uses.
|
||||
pub(super) struct Carved {
|
||||
ga: OriginalSessionSpan,
|
||||
gdn_state: OriginalSessionSpan,
|
||||
qsa_state_arena: OriginalSessionSpan,
|
||||
qa: OriginalSessionSpan,
|
||||
qsa: Vec<Option<OriginalSessionQsaLayout>>,
|
||||
ma: OriginalSessionSpan,
|
||||
ba: OriginalSessionSpan,
|
||||
ple_hist: OriginalSessionSpan,
|
||||
used: usize,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
pub fn check(&self) -> Result<()> {
|
||||
self.g.validate()?;
|
||||
if self.cells == 0 || self.cells > i32::MAX as usize || self.k == 0 || self.k > 64 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `(layer_lo, layer_hi)` after clamping to the model's layers.
|
||||
pub fn layer_range(&self) -> Result<(usize, usize)> {
|
||||
let (lo, hi) = self.bounds;
|
||||
let layer_lo = usize::try_from(lo.max(0)).map_err(|_| Error::InvalidSize)?;
|
||||
let layer_hi = if hi < 0 || hi as u64 > self.g.n_layers as u64 { self.g.n_layers } else { hi as usize };
|
||||
if layer_lo >= layer_hi || layer_hi > self.g.n_layers {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok((layer_lo, layer_hi))
|
||||
}
|
||||
|
||||
pub fn split(&self, (layer_lo, layer_hi): (usize, usize)) -> Result<Split> {
|
||||
let g = self.g;
|
||||
let i = g.qsa_interval.max(1);
|
||||
let all_q = g.n_layers / g.qsa_interval;
|
||||
let qsa_ord0 = layer_lo / i;
|
||||
let qr = layer_hi / i - qsa_ord0;
|
||||
let qsa_alloc = qr.max(usize::from(all_q > 0));
|
||||
let gdn_ord0 = layer_lo - layer_lo / i;
|
||||
let gdn_alloc = (layer_hi - layer_lo).saturating_sub(qr);
|
||||
if add(qsa_ord0, qsa_alloc)? > all_q {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok(Split { all_q, qsa_ord0, qsa_alloc, gdn_ord0, gdn_alloc })
|
||||
}
|
||||
|
||||
pub fn sizes(&self, split: &Split) -> Result<Sizes> {
|
||||
let (g, cells, p) = (self.g, self.cells, self.p);
|
||||
let gp = g.gdn_parts()?;
|
||||
let gdn_bytes = sum16(&gp)?;
|
||||
let state = mul(split.gdn_alloc, g.state_bytes()?)?;
|
||||
let first = qsa_price(g, cells, p, true)?;
|
||||
let rest = qsa_price(g, cells, p, false)?;
|
||||
let qsa_bytes = if split.all_q > 0 { add(first.charge, mul(split.qsa_alloc - 1, rest.charge)?)? } else { 0 };
|
||||
let qb = g.qsa_scratch_charge(cells)?;
|
||||
let mp = g.moe_parts(self.k)?;
|
||||
let mb = sum16(&mp)?;
|
||||
let bb = g.block_charge()?;
|
||||
let hist = product(&[PLE_HIST, PLE_DIM, 4])?;
|
||||
let (lo, hi) = self.bounds;
|
||||
let session_bytes = session_bytes(g, cells, self.k, lo, hi, p)?;
|
||||
Ok(Sizes { gp, mp, gdn_bytes, state, first, rest, qsa_bytes, qb, mb, bb, hist, session_bytes })
|
||||
}
|
||||
|
||||
pub fn carve(&self, split: &Split, s: &Sizes) -> Result<Carved> {
|
||||
let mut c = Cursor { base: 0, used: 0 };
|
||||
let ga = c.take(s.gdn_bytes, ALIGN)?;
|
||||
let gdn_state = c.take(s.state, ALIGN)?;
|
||||
let qsa_state_arena = c.take(s.qsa_bytes, ALIGN)?;
|
||||
let qa = c.take(s.qb, ALIGN)?;
|
||||
let qsa = self.carve_qsa_states(split, s, qsa_state_arena)?;
|
||||
let ma = c.take(s.mb, ALIGN)?;
|
||||
let ba = c.take(s.bb, ALIGN)?;
|
||||
let ple_hist = c.take(s.hist, ALIGN)?;
|
||||
if c.used > s.session_bytes {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
Ok(Carved { ga, gdn_state, qsa_state_arena, qa, qsa, ma, ba, ple_hist, used: c.used })
|
||||
}
|
||||
|
||||
fn carve_qsa_states(
|
||||
&self,
|
||||
split: &Split,
|
||||
s: &Sizes,
|
||||
arena: OriginalSessionSpan,
|
||||
) -> Result<Vec<Option<OriginalSessionQsaLayout>>> {
|
||||
let mut qsa: Vec<Option<OriginalSessionQsaLayout>> = Vec::new();
|
||||
qsa.try_reserve_exact(split.all_q).map_err(|_| Error::HostAllocation)?;
|
||||
qsa.resize_with(split.all_q, || None);
|
||||
for j in 0..split.qsa_alloc {
|
||||
let offset = if j == 0 { 0 } else { add(s.first.charge, mul(j - 1, s.rest.charge)?)? };
|
||||
let price = if j == 0 { &s.first } else { &s.rest };
|
||||
let share = rope_share(&qsa, split.qsa_ord0, j)?;
|
||||
let at = split.qsa_ord0 + j;
|
||||
qsa[at] = Some(qsa_carve(self.g, self.cells, self.p, at, arena.at(offset, price.charge)?, price, share)?);
|
||||
}
|
||||
Ok(qsa)
|
||||
}
|
||||
|
||||
pub fn assemble(
|
||||
&self,
|
||||
(layers, split, sizes): ((usize, usize), &Split, &Sizes),
|
||||
carved: Carved,
|
||||
) -> Result<OriginalSessionLayout> {
|
||||
let arrays = self.span_arrays(sizes, &carved)?;
|
||||
Ok(OriginalSessionLayout {
|
||||
geometry: self.g,
|
||||
policy: self.p,
|
||||
max_cells: self.cells,
|
||||
k: self.k,
|
||||
layer_lo: layers.0,
|
||||
layer_hi: layers.1,
|
||||
qsa_ord0: split.qsa_ord0,
|
||||
qsa_alloc: split.qsa_alloc,
|
||||
gdn_ord0: split.gdn_ord0,
|
||||
gdn_alloc: split.gdn_alloc,
|
||||
session_bytes: sizes.session_bytes,
|
||||
init_used: carved.used,
|
||||
gdn: arrays.gdn,
|
||||
gdn_state: carved.gdn_state,
|
||||
qsa_state_arena: carved.qsa_state_arena,
|
||||
qsa: carved.qsa,
|
||||
qsa_buffers: arrays.qsa_buffers,
|
||||
moe: arrays.moe,
|
||||
block: arrays.block,
|
||||
gr: arrays.gr,
|
||||
ple_hist: carved.ple_hist,
|
||||
})
|
||||
}
|
||||
/// The per-role span arrays inside the carved regions (block and gr first, as the Original resolves them).
|
||||
fn span_arrays(&self, sizes: &Sizes, carved: &Carved) -> Result<SpanArrays> {
|
||||
let g = self.g;
|
||||
let block = parts(carved.ba, g.block_parts()?)?;
|
||||
let gr = parts(block[7], g.gr_parts()?)?;
|
||||
Ok(SpanArrays {
|
||||
gdn: parts(carved.ga, sizes.gp)?,
|
||||
qsa_buffers: parts(carved.qa, g.qsa_scratch_parts(self.cells)?)?,
|
||||
moe: parts(carved.ma, sizes.mp)?,
|
||||
block,
|
||||
gr,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The five per-role span arrays of a layout.
|
||||
struct SpanArrays {
|
||||
gdn: [OriginalSessionSpan; 16],
|
||||
qsa_buffers: [OriginalSessionSpan; 18],
|
||||
moe: [OriginalSessionSpan; 9],
|
||||
block: [OriginalSessionSpan; 8],
|
||||
gr: [OriginalSessionSpan; 5],
|
||||
}
|
||||
|
||||
/// The primary state's RoPE spans for every later state (`None` for the primary itself).
|
||||
fn rope_share(
|
||||
qsa: &[Option<OriginalSessionQsaLayout>],
|
||||
qsa_ord0: usize,
|
||||
j: usize,
|
||||
) -> Result<Option<(OriginalSessionSpan, OriginalSessionSpan)>> {
|
||||
if j == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let primary = qsa[qsa_ord0].as_ref().ok_or(Error::InvalidQwenShape)?;
|
||||
Ok(Some((primary.cos, primary.sin)))
|
||||
}
|
||||
@@ -9,59 +9,228 @@ pub(super) fn qsa_price(
|
||||
p: OriginalSessionKvPolicy,
|
||||
rope: bool,
|
||||
) -> Result<QsaPrice> {
|
||||
// Literal layer.cpp498..519 kv_plan: negative ring_cells forces full
|
||||
// residence, positive chooses the drafter ring (mode2), zero chooses the
|
||||
// main clock-resident tier (mode1). OFF decisions are startup snapshots.
|
||||
let pages = cells.div_ceil(4);
|
||||
let mut slots = pages;
|
||||
let mut mode = 0;
|
||||
let mut pooled_rows = add(cells / 4, 2)?;
|
||||
if p.resident_cells > 0 && p.ring_cells >= 0 && !(if p.ring_cells > 0 { p.ring_off } else { p.main_off }) {
|
||||
if p.ring_cells > 0 {
|
||||
let ring = (p.ring_cells as usize).div_ceil(4);
|
||||
if ring < pages {
|
||||
slots = ring;
|
||||
mode = 2;
|
||||
pooled_rows = 2;
|
||||
}
|
||||
let (slots, mode, pooled_rows) = kv_placement(cells, p, pages)?;
|
||||
let pool = PoolSizes::new(g, slots)?.select(p)?;
|
||||
let n = base_state_bytes(pool, (pages, slots, mode))?;
|
||||
let n = tables_and_tail(g, (cells, rope), pooled_rows, n)?;
|
||||
Ok(QsaPrice { mode, pages, slots, pooled_rows, charge: add(align(n, 16)?, 256)? })
|
||||
}
|
||||
|
||||
/// `(slots, mode, pooled_rows)`. Literal layer.cpp498..519 kv_plan: negative ring_cells forces full
|
||||
/// residence, positive chooses the drafter ring (mode2), zero chooses the
|
||||
/// main clock-resident tier (mode1). OFF decisions are startup snapshots.
|
||||
fn kv_placement(cells: usize, p: OriginalSessionKvPolicy, pages: usize) -> Result<(usize, u8, usize)> {
|
||||
let full = (pages, 0, add(cells / 4, 2)?);
|
||||
if p.resident_cells > 0 && p.ring_cells >= 0 && !tier_off(p) {
|
||||
return Ok(smaller_tier(p, pages, full.2).unwrap_or(full));
|
||||
}
|
||||
Ok(full)
|
||||
}
|
||||
|
||||
fn tier_off(p: OriginalSessionKvPolicy) -> bool {
|
||||
if p.ring_cells > 0 { p.ring_off } else { p.main_off }
|
||||
}
|
||||
|
||||
/// The drafter ring or the clock-resident tier when it needs fewer slots than the pages.
|
||||
fn smaller_tier(p: OriginalSessionKvPolicy, pages: usize, pooled_rows: usize) -> Option<(usize, u8, usize)> {
|
||||
if p.ring_cells > 0 {
|
||||
let ring = (p.ring_cells as usize).div_ceil(4);
|
||||
(ring < pages).then_some((ring, 2, 2))
|
||||
} else {
|
||||
let resident = p.resident_cells.max(20480).div_ceil(4);
|
||||
(resident < pages).then_some((resident, 1, pooled_rows))
|
||||
}
|
||||
}
|
||||
|
||||
/// The byte sizes the K/V pool formulas share.
|
||||
struct PoolSizes {
|
||||
slots: usize,
|
||||
kv_heads: usize,
|
||||
head_dim: usize,
|
||||
rows: usize,
|
||||
q4: usize,
|
||||
q8cell: usize,
|
||||
}
|
||||
|
||||
impl PoolSizes {
|
||||
fn new(g: OriginalSessionGeometry, slots: usize) -> Result<Self> {
|
||||
let rows = product(&[slots, 4, g.kv_heads])?;
|
||||
let q4 = mul(g.head_dim / 32, 18)?;
|
||||
let q8cell = mul(g.kv_heads, add(mul(g.head_dim, 2)?, mul(g.head_dim / 64, 4)?)?)?;
|
||||
Ok(Self { slots, kv_heads: g.kv_heads, head_dim: g.head_dim, rows, q4, q8cell })
|
||||
}
|
||||
/// Preserve kv_pool_bytes decision priority, including without_key before
|
||||
/// hybrid/Q4. Unsupported combinations remain an init dependency, not recast.
|
||||
fn select(&self, p: OriginalSessionKvPolicy) -> Result<usize> {
|
||||
if p.without_key {
|
||||
self.without_key()
|
||||
} else if p.hybrid && p.ring_cells <= 0 {
|
||||
self.hybrid()
|
||||
} else if p.q4 {
|
||||
add(product(&[self.slots, 4, self.kv_heads, self.q4, 2])?, 64)
|
||||
} else if p.int8 || p.hybrid {
|
||||
add(product(&[self.slots, 4, self.q8cell])?, 64)
|
||||
} else {
|
||||
let resident = p.resident_cells.max(20480).div_ceil(4);
|
||||
if resident < pages {
|
||||
slots = resident;
|
||||
mode = 1;
|
||||
}
|
||||
product(&[self.slots, self.kv_heads, 4, self.head_dim, 4])
|
||||
}
|
||||
}
|
||||
let rows = product(&[slots, 4, g.kv_heads])?;
|
||||
let q4 = mul(g.head_dim / 32, 18)?;
|
||||
let q8cell = mul(g.kv_heads, add(mul(g.head_dim, 2)?, mul(g.head_dim / 64, 4)?)?)?;
|
||||
// Preserve kv_pool_bytes decision priority, including without_key before
|
||||
// hybrid/Q4. Unsupported combinations remain an init dependency, not recast.
|
||||
let pool = if p.without_key {
|
||||
add(mul(mul(slots, 4)?, q8cell)? / 2, 64)?
|
||||
} else if p.hybrid && p.ring_cells <= 0 {
|
||||
add(sum(&[mul(rows, g.head_dim)?, product(&[rows, g.head_dim / 64, 2])?, mul(rows, q4)?])?, 64)?
|
||||
} else if p.q4 {
|
||||
add(product(&[slots, 4, g.kv_heads, q4, 2])?, 64)?
|
||||
} else if p.int8 || p.hybrid {
|
||||
add(product(&[slots, 4, q8cell])?, 64)?
|
||||
} else {
|
||||
product(&[slots, g.kv_heads, 4, g.head_dim, 4])?
|
||||
};
|
||||
fn without_key(&self) -> Result<usize> {
|
||||
add(mul(mul(self.slots, 4)?, self.q8cell)? / 2, 64)
|
||||
}
|
||||
fn hybrid(&self) -> Result<usize> {
|
||||
let codes = mul(self.rows, self.head_dim)?;
|
||||
let scales = product(&[self.rows, self.head_dim / 64, 2])?;
|
||||
add(sum(&[codes, scales, mul(self.rows, self.q4)?])?, 64)
|
||||
}
|
||||
}
|
||||
|
||||
/// The pool, the page table and (mode 1) the streaming map. `shape` is `(pages, slots, mode)`.
|
||||
fn base_state_bytes(pool: usize, shape: (usize, usize, u8)) -> Result<usize> {
|
||||
let (pages, slots, mode) = shape;
|
||||
let mut n = add(pool, 64)?;
|
||||
n = add(n, mul(pages, 4)?)?;
|
||||
if mode == 1 {
|
||||
n = add(n, add(add(mul(slots, 20)?, 64)?, 96)?)?;
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// The indexer regions, the optional RoPE tables and the step / status / position tail on top of `n`.
|
||||
fn tables_and_tail(
|
||||
g: OriginalSessionGeometry,
|
||||
(cells, rope): (usize, bool),
|
||||
pooled_rows: usize,
|
||||
n: usize,
|
||||
) -> Result<usize> {
|
||||
let mut n = n;
|
||||
for b in [product(&[3, g.index_dim, 4])?, mul(g.index_dim, 4)?, product(&[pooled_rows, g.index_dim, 4])?, 16] {
|
||||
n = add(n, b)?;
|
||||
}
|
||||
if rope {
|
||||
n = add(n, product(&[cells, 32, 4, 2])?)?;
|
||||
}
|
||||
n = sum(&[n, 16, 16, mul(g.heads, 4)?])?;
|
||||
Ok(QsaPrice { mode, pages, slots, pooled_rows, charge: add(align(n, 16)?, 256)? })
|
||||
sum(&[n, 16, 16, mul(g.heads, 4)?])
|
||||
}
|
||||
|
||||
/// The regions of one QSA state in carve order, in an arena that starts at `arena.offset`.
|
||||
struct Carver {
|
||||
c: Cursor,
|
||||
regions: Vec<(&'static str, OriginalSessionSpan)>,
|
||||
}
|
||||
|
||||
/// Which K/V representation the policy selects for a state.
|
||||
#[derive(Clone, Copy)]
|
||||
struct KvFlags {
|
||||
hybrid: bool,
|
||||
int8: bool,
|
||||
q4_mode: bool,
|
||||
}
|
||||
|
||||
/// Element counts of the K/V regions of a state.
|
||||
struct KvSizes {
|
||||
codes: usize,
|
||||
scales: usize,
|
||||
q4: usize,
|
||||
}
|
||||
|
||||
impl KvSizes {
|
||||
fn new(slots: usize, g: OriginalSessionGeometry) -> Result<Self> {
|
||||
let rows = product(&[slots, g.kv_heads, 4])?;
|
||||
let codes = mul(rows, g.head_dim)?;
|
||||
let scales = product(&[rows, g.head_dim / 64, 2])?;
|
||||
let q4 = product(&[rows, g.head_dim / 32, 18])?;
|
||||
Ok(Self { codes, scales, q4 })
|
||||
}
|
||||
}
|
||||
|
||||
impl Carver {
|
||||
fn new(base: usize) -> Result<Self> {
|
||||
let mut regions = Vec::new();
|
||||
regions.try_reserve_exact(28).map_err(|_| Error::HostAllocation)?;
|
||||
Ok(Self { c: Cursor { base, used: 0 }, regions })
|
||||
}
|
||||
fn take(&mut self, name: &'static str, n: usize) -> Result<OriginalSessionSpan> {
|
||||
let s = self.c.take(n, 16)?;
|
||||
self.regions.push((name, s));
|
||||
Ok(s)
|
||||
}
|
||||
fn take_kv(&mut self, g: OriginalSessionGeometry, price: &QsaPrice, p: OriginalSessionKvPolicy) -> Result<KvFlags> {
|
||||
let sizes = KvSizes::new(price.slots, g)?;
|
||||
let hybrid = p.hybrid && p.ring_cells <= 0;
|
||||
let flags = KvFlags { hybrid, int8: p.int8 && !p.q4 && !hybrid, q4_mode: p.q4 && !hybrid };
|
||||
if flags.hybrid {
|
||||
self.take_hybrid(&sizes)?;
|
||||
} else if flags.q4_mode {
|
||||
self.take_q4(&sizes)?;
|
||||
} else if flags.int8 {
|
||||
self.take_int8(&sizes, p.without_key)?;
|
||||
} else {
|
||||
self.take_fp16(&sizes)?;
|
||||
}
|
||||
Ok(flags)
|
||||
}
|
||||
fn take_hybrid(&mut self, sizes: &KvSizes) -> Result<()> {
|
||||
self.take("k_q", sizes.codes)?;
|
||||
self.take("k_scale", sizes.scales)?;
|
||||
self.take("v_q4", sizes.q4)?;
|
||||
Ok(())
|
||||
}
|
||||
fn take_q4(&mut self, sizes: &KvSizes) -> Result<()> {
|
||||
self.take("k_q4", sizes.q4)?;
|
||||
self.take("v_q4", sizes.q4)?;
|
||||
Ok(())
|
||||
}
|
||||
fn take_int8(&mut self, sizes: &KvSizes, without_key: bool) -> Result<()> {
|
||||
if !without_key {
|
||||
self.take("k_q", sizes.codes)?;
|
||||
}
|
||||
self.take("v_q", sizes.codes)?;
|
||||
if !without_key {
|
||||
self.take("k_scale", sizes.scales)?;
|
||||
}
|
||||
self.take("v_scale", sizes.scales)?;
|
||||
Ok(())
|
||||
}
|
||||
fn take_fp16(&mut self, sizes: &KvSizes) -> Result<()> {
|
||||
self.take("k_pool", mul(sizes.codes, 2)?)?;
|
||||
self.take("v_pool", mul(sizes.codes, 2)?)?;
|
||||
Ok(())
|
||||
}
|
||||
/// The page table, the streaming map (mode 1) and the indexer regions.
|
||||
fn take_tables(&mut self, g: OriginalSessionGeometry, price: &QsaPrice) -> Result<()> {
|
||||
self.take("page_table", mul(price.pages, 4)?)?;
|
||||
if price.mode == 1 {
|
||||
for n in ["slot_block", "slot_stamp", "slot_ref", "miss_block", "miss_slot"] {
|
||||
self.take(n, mul(price.slots, 4)?)?;
|
||||
}
|
||||
self.take("ctl", 64)?;
|
||||
}
|
||||
self.take("idx_tail", product(&[3, g.index_dim, 4])?)?;
|
||||
self.take("idx_dead", mul(g.index_dim, 4)?)?;
|
||||
self.take("idx_pooled", product(&[price.pooled_rows, g.index_dim, 4])?)?;
|
||||
self.take("idx_block_pos", 4)?;
|
||||
Ok(())
|
||||
}
|
||||
/// The RoPE tables, or the primary state's two spans when they are shared.
|
||||
fn take_rope(
|
||||
&mut self,
|
||||
cells: usize,
|
||||
share: Option<(OriginalSessionSpan, OriginalSessionSpan)>,
|
||||
) -> Result<(OriginalSessionSpan, OriginalSessionSpan)> {
|
||||
if let Some(s) = share {
|
||||
return Ok(s);
|
||||
}
|
||||
Ok((self.take("cos", product(&[cells, 32, 4])?)?, self.take("sin", product(&[cells, 32, 4])?)?))
|
||||
}
|
||||
fn take_tail(&mut self, g: OriginalSessionGeometry) -> Result<()> {
|
||||
self.take("step", 16)?;
|
||||
self.take("attention_status", 4)?;
|
||||
self.take("pos_dev", mul(g.heads, 4)?)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn qsa_carve(
|
||||
g: OriginalSessionGeometry,
|
||||
cells: usize,
|
||||
@@ -71,76 +240,42 @@ pub(super) fn qsa_carve(
|
||||
price: &QsaPrice,
|
||||
share: Option<(OriginalSessionSpan, OriginalSessionSpan)>,
|
||||
) -> Result<OriginalSessionQsaLayout> {
|
||||
let mut c = Cursor { base: arena.offset, used: 0 };
|
||||
let mut regions = Vec::new();
|
||||
regions.try_reserve_exact(28).map_err(|_| Error::HostAllocation)?;
|
||||
let mut take = |name, n| -> Result<OriginalSessionSpan> {
|
||||
let s = c.take(n, 16)?;
|
||||
regions.push((name, s));
|
||||
Ok(s)
|
||||
};
|
||||
let rows = product(&[price.slots, g.kv_heads, 4])?;
|
||||
let codes = mul(rows, g.head_dim)?;
|
||||
let scales = product(&[rows, g.head_dim / 64, 2])?;
|
||||
let q4 = product(&[rows, g.head_dim / 32, 18])?;
|
||||
let hybrid = p.hybrid && p.ring_cells <= 0;
|
||||
let int8 = p.int8 && !p.q4 && !hybrid;
|
||||
let q4_mode = p.q4 && !hybrid;
|
||||
if hybrid {
|
||||
take("k_q", codes)?;
|
||||
take("k_scale", scales)?;
|
||||
take("v_q4", q4)?;
|
||||
} else if q4_mode {
|
||||
take("k_q4", q4)?;
|
||||
take("v_q4", q4)?;
|
||||
} else if int8 {
|
||||
if !p.without_key {
|
||||
take("k_q", codes)?;
|
||||
}
|
||||
take("v_q", codes)?;
|
||||
if !p.without_key {
|
||||
take("k_scale", scales)?;
|
||||
}
|
||||
take("v_scale", scales)?;
|
||||
} else {
|
||||
take("k_pool", mul(codes, 2)?)?;
|
||||
take("v_pool", mul(codes, 2)?)?;
|
||||
}
|
||||
take("page_table", mul(price.pages, 4)?)?;
|
||||
if price.mode == 1 {
|
||||
for n in ["slot_block", "slot_stamp", "slot_ref", "miss_block", "miss_slot"] {
|
||||
take(n, mul(price.slots, 4)?)?;
|
||||
}
|
||||
take("ctl", 64)?;
|
||||
}
|
||||
take("idx_tail", product(&[3, g.index_dim, 4])?)?;
|
||||
take("idx_dead", mul(g.index_dim, 4)?)?;
|
||||
take("idx_pooled", product(&[price.pooled_rows, g.index_dim, 4])?)?;
|
||||
take("idx_block_pos", 4)?;
|
||||
let (cos, sin) = if let Some(s) = share {
|
||||
s
|
||||
} else {
|
||||
(take("cos", product(&[cells, 32, 4])?)?, take("sin", product(&[cells, 32, 4])?)?)
|
||||
};
|
||||
take("step", 16)?;
|
||||
take("attention_status", 4)?;
|
||||
take("pos_dev", mul(g.heads, 4)?)?;
|
||||
drop(take);
|
||||
if c.used > arena.bytes {
|
||||
let mut carver = Carver::new(arena.offset)?;
|
||||
let flags = carver.take_kv(g, price, p)?;
|
||||
carver.take_tables(g, price)?;
|
||||
let (cos, sin) = carver.take_rope(cells, share)?;
|
||||
carver.take_tail(g)?;
|
||||
if carver.c.used > arena.bytes {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
let host_kv_bytes = if price.mode == 0 {
|
||||
0
|
||||
qsa_layout(g, p, flags, (ordinal, arena), (price, carver.regions, cos, sin))
|
||||
}
|
||||
|
||||
fn host_kv_bytes(g: OriginalSessionGeometry, price: &QsaPrice, flags: KvFlags) -> Result<usize> {
|
||||
if price.mode == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
let block = if flags.q4_mode {
|
||||
product(&[4, g.kv_heads, g.head_dim / 32, 18, 2])?
|
||||
} else if flags.int8 {
|
||||
product(&[4, g.kv_heads, add(mul(g.head_dim, 2)?, mul(g.head_dim / 64, 4)?)?])?
|
||||
} else {
|
||||
let block = if q4_mode {
|
||||
product(&[4, g.kv_heads, g.head_dim / 32, 18, 2])?
|
||||
} else if int8 {
|
||||
product(&[4, g.kv_heads, add(mul(g.head_dim, 2)?, mul(g.head_dim / 64, 4)?)?])?
|
||||
} else {
|
||||
product(&[4, g.kv_heads, g.head_dim, 4])?
|
||||
};
|
||||
add(mul(price.pages, block)?, 1024)?
|
||||
product(&[4, g.kv_heads, g.head_dim, 4])?
|
||||
};
|
||||
add(mul(price.pages, block)?, 1024)
|
||||
}
|
||||
|
||||
/// The price, the carved regions and the two RoPE spans of a state.
|
||||
type CarvedRegions<'a> =
|
||||
(&'a QsaPrice, Vec<(&'static str, OriginalSessionSpan)>, OriginalSessionSpan, OriginalSessionSpan);
|
||||
|
||||
fn qsa_layout(
|
||||
g: OriginalSessionGeometry,
|
||||
p: OriginalSessionKvPolicy,
|
||||
flags: KvFlags,
|
||||
(ordinal, arena): (usize, OriginalSessionSpan),
|
||||
(price, regions, cos, sin): CarvedRegions<'_>,
|
||||
) -> Result<OriginalSessionQsaLayout> {
|
||||
Ok(OriginalSessionQsaLayout {
|
||||
ordinal,
|
||||
arena,
|
||||
@@ -153,11 +288,11 @@ pub(super) fn qsa_carve(
|
||||
sin,
|
||||
host_step_bytes: 20,
|
||||
host_position_bytes: mul(g.heads, 4)?,
|
||||
host_kv_bytes,
|
||||
kv_int8: int8,
|
||||
kv_q4: q4_mode,
|
||||
kv_hybrid: hybrid,
|
||||
kv_rotate: q4_mode || (int8 && p.int8_rotate),
|
||||
host_kv_bytes: host_kv_bytes(g, price, flags)?,
|
||||
kv_int8: flags.int8,
|
||||
kv_q4: flags.q4_mode,
|
||||
kv_hybrid: flags.hybrid,
|
||||
kv_rotate: flags.q4_mode || (flags.int8 && p.int8_rotate),
|
||||
owns_rope: false,
|
||||
})
|
||||
}
|
||||
@@ -191,6 +326,10 @@ pub(crate) fn session_bytes(
|
||||
} else {
|
||||
add(qsa_price(g, cells, p, true)?.charge, mul(qn - 1, qsa_price(g, cells, p, false)?.charge)?)?
|
||||
};
|
||||
session_total(g, (cells, k), gn, qbytes)
|
||||
}
|
||||
|
||||
fn session_total(g: OriginalSessionGeometry, (cells, k): (usize, usize), gn: usize, qbytes: usize) -> Result<usize> {
|
||||
add(
|
||||
align(
|
||||
sum(&[
|
||||
|
||||
@@ -29,24 +29,23 @@ impl<'ctx> OriginalExpertStager<'ctx> {
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
let count = usize::from(end - first).checked_mul(512).ok_or(Error::BudgetExceeded)?;
|
||||
let extra = count
|
||||
.checked_mul(size_of::<Option<(BufferHandle, usize)>>())
|
||||
.and_then(|n| n.checked_add(size_of::<OriginalStreamAllForward<'_, '_, '_, '_, '_>>()))
|
||||
.and_then(|n| n.checked_add(crate::OriginalPromptLeaseIdentity::metadata_bytes()))
|
||||
.ok_or(Error::BudgetExceeded)?;
|
||||
// Add to the original run's conservative MAX_JOBS metadata before any job
|
||||
// publication or issuer activity; physical/source caps remain shared.
|
||||
let original = MAX_JOBS
|
||||
.checked_mul(size_of::<Entry>())
|
||||
.and_then(|n| {
|
||||
n.checked_add(
|
||||
GPU_RING_MAX * size_of::<BufferHandle>()
|
||||
+ size_of::<Issuer>()
|
||||
+ size_of::<OriginalStreamAll<'_, '_, '_, '_>>()
|
||||
+ size_of::<JoinHandle<()>>(),
|
||||
)
|
||||
})
|
||||
.ok_or(Error::BudgetExceeded)?;
|
||||
let (extra, original) = forward_costs(count)?;
|
||||
let remaining = self.admit_forward(extra, original, host_allowance, options)?;
|
||||
let resident = resident_spans(&rows, (first, end), count)?;
|
||||
let lease = rows.lease_identity();
|
||||
let row_count = rows.rows();
|
||||
self.run_stream_all(rows, copy, compute, first, end, options, remaining, move |scope| {
|
||||
run_forward_consumer(scope, (lease, row_count, resident), consumer)
|
||||
})
|
||||
}
|
||||
/// The host metadata and the shared source and memory caps admit a forward over `extra` bytes of its own.
|
||||
fn admit_forward(
|
||||
&self,
|
||||
extra: usize,
|
||||
original: usize,
|
||||
host_allowance: usize,
|
||||
options: OriginalStreamAllOptions,
|
||||
) -> Result<usize> {
|
||||
if self.metadata_bytes.checked_add(original).and_then(|n| n.checked_add(extra)).is_none_or(|n| n > META_CAP) {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
@@ -67,48 +66,96 @@ impl<'ctx> OriginalExpertStager<'ctx> {
|
||||
{
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
let mut resident = Vec::new();
|
||||
resident.try_reserve_exact(count).map_err(|_| Error::HostAllocation)?;
|
||||
if resident.capacity() > count {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
for layer in first..end {
|
||||
for expert in 0..512 {
|
||||
resident.push(rows.cache_expert_span(usize::from(layer), expert)?);
|
||||
}
|
||||
}
|
||||
let lease = rows.lease_identity();
|
||||
let row_count = rows.rows();
|
||||
self.run_stream_all(rows, copy, compute, first, end, options, remaining, move |scope| {
|
||||
let actual = scope.rows.take().ok_or(Error::ContextPoisoned)?;
|
||||
let mut forward = OriginalStreamAllForward { scope, lease, rows: row_count, resident };
|
||||
let invoked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| consumer(&mut forward, actual)));
|
||||
let (result, returned) = match invoked {
|
||||
Ok(value) => value,
|
||||
Err(panic) => {
|
||||
forward.scope.stager.context.poison();
|
||||
forward.scope.stager.context.retain_driver();
|
||||
// Original outer scope catches this unwind and unconditionally joins and
|
||||
// drains before resuming; no successful physical lease escapes.
|
||||
std::panic::resume_unwind(panic)
|
||||
}
|
||||
};
|
||||
match returned {
|
||||
Some(mut actual) => {
|
||||
let valid = forward.validate_rows(&actual);
|
||||
if valid.is_err() {
|
||||
actual.mark_failed();
|
||||
}
|
||||
forward.scope.rows = Some(actual);
|
||||
combine(result, valid)
|
||||
}
|
||||
None => {
|
||||
forward.scope.stager.context.poison();
|
||||
forward.scope.stager.context.retain_driver();
|
||||
combine(result, Err(Error::ContextPoisoned))
|
||||
}
|
||||
}
|
||||
Ok(remaining)
|
||||
}
|
||||
}
|
||||
|
||||
/// `(extra, original)` host metadata bytes: the forward's own, and the original run's conservative MAX_JOBS figure.
|
||||
fn forward_costs(count: usize) -> Result<(usize, usize)> {
|
||||
let extra = count
|
||||
.checked_mul(size_of::<Option<(BufferHandle, usize)>>())
|
||||
.and_then(|n| n.checked_add(size_of::<OriginalStreamAllForward<'_, '_, '_, '_, '_>>()))
|
||||
.and_then(|n| n.checked_add(crate::OriginalPromptLeaseIdentity::metadata_bytes()))
|
||||
.ok_or(Error::BudgetExceeded)?;
|
||||
// Add to the original run's conservative MAX_JOBS metadata before any job
|
||||
// publication or issuer activity; physical/source caps remain shared.
|
||||
let original = MAX_JOBS
|
||||
.checked_mul(size_of::<Entry>())
|
||||
.and_then(|n| {
|
||||
n.checked_add(
|
||||
GPU_RING_MAX * size_of::<BufferHandle>()
|
||||
+ size_of::<Issuer>()
|
||||
+ size_of::<OriginalStreamAll<'_, '_, '_, '_>>()
|
||||
+ size_of::<JoinHandle<()>>(),
|
||||
)
|
||||
})
|
||||
.ok_or(Error::BudgetExceeded)?;
|
||||
Ok((extra, original))
|
||||
}
|
||||
|
||||
/// The cache span of every expert of the layers `first..end`, in layer then expert order.
|
||||
fn resident_spans(
|
||||
rows: &OriginalPromptRows<'_, '_, '_>,
|
||||
(first, end): (u8, u8),
|
||||
count: usize,
|
||||
) -> Result<Vec<Option<(BufferHandle, usize)>>> {
|
||||
let mut resident = Vec::new();
|
||||
resident.try_reserve_exact(count).map_err(|_| Error::HostAllocation)?;
|
||||
if resident.capacity() > count {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
for layer in first..end {
|
||||
for expert in 0..512 {
|
||||
resident.push(rows.cache_expert_span(usize::from(layer), expert)?);
|
||||
}
|
||||
}
|
||||
Ok(resident)
|
||||
}
|
||||
|
||||
/// The scope callback of `run_stream_all_forward`: runs the consumer with the lease it was given, and settles the
|
||||
/// returned rows.
|
||||
fn run_forward_consumer<'arena, 'loan, 'ctx, T>(
|
||||
scope: &mut OriginalStreamAll<'_, 'arena, 'loan, 'ctx>,
|
||||
(lease, rows, resident): (crate::OriginalPromptLeaseIdentity, usize, Vec<Option<(BufferHandle, usize)>>),
|
||||
consumer: impl FnOnce(
|
||||
&mut OriginalStreamAllForward<'_, '_, 'arena, 'loan, 'ctx>,
|
||||
OriginalPromptRows<'arena, 'loan, 'ctx>,
|
||||
) -> (Result<T>, Option<OriginalPromptRows<'arena, 'loan, 'ctx>>),
|
||||
) -> Result<T> {
|
||||
let actual = scope.rows.take().ok_or(Error::ContextPoisoned)?;
|
||||
let mut forward = OriginalStreamAllForward { scope, lease, rows, resident };
|
||||
let invoked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| consumer(&mut forward, actual)));
|
||||
let (result, returned) = match invoked {
|
||||
Ok(value) => value,
|
||||
Err(panic) => {
|
||||
forward.scope.stager.context.poison();
|
||||
forward.scope.stager.context.retain_driver();
|
||||
// Original outer scope catches this unwind and unconditionally joins and
|
||||
// drains before resuming; no successful physical lease escapes.
|
||||
std::panic::resume_unwind(panic)
|
||||
}
|
||||
};
|
||||
forward.settle(result, returned)
|
||||
}
|
||||
|
||||
impl<'arena, 'loan, 'ctx> OriginalStreamAllForward<'_, '_, 'arena, 'loan, 'ctx> {
|
||||
/// The consumer's result against the rows it returned: valid rows go back to the scope, no rows poison it.
|
||||
fn settle<T>(&mut self, result: Result<T>, returned: Option<OriginalPromptRows<'arena, 'loan, 'ctx>>) -> Result<T> {
|
||||
match returned {
|
||||
Some(mut actual) => {
|
||||
let valid = self.validate_rows(&actual);
|
||||
if valid.is_err() {
|
||||
actual.mark_failed();
|
||||
}
|
||||
self.scope.rows = Some(actual);
|
||||
combine(result, valid)
|
||||
}
|
||||
None => {
|
||||
self.scope.stager.context.poison();
|
||||
self.scope.stager.context.retain_driver();
|
||||
combine(result, Err(Error::ContextPoisoned))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl OriginalStreamAllForward<'_, '_, '_, '_, '_> {
|
||||
@@ -144,51 +191,14 @@ impl OriginalStreamAllForward<'_, '_, '_, '_, '_> {
|
||||
rows: &OriginalPromptRows<'_, '_, '_>,
|
||||
layer: u8,
|
||||
experts: &[u32],
|
||||
mut producer: impl FnMut(u32, BufferHandle, usize, &mut OriginalGpuStream<'_>) -> Result<()>,
|
||||
producer: impl FnMut(u32, BufferHandle, usize, &mut OriginalGpuStream<'_>) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
self.validate_rows(rows)?;
|
||||
let scope = &mut self.scope;
|
||||
if layer != scope.next_layer
|
||||
|| layer < scope.first
|
||||
|| layer >= scope.end
|
||||
|| experts.len() > 512
|
||||
|| experts.windows(2).any(|p| p[0] >= p[1])
|
||||
|| experts.iter().any(|e| *e >= 512)
|
||||
{
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let layer_end = scope.layer_start[layer as usize + 1];
|
||||
for &e in experts {
|
||||
scope.release_unused(e, layer_end)?;
|
||||
scope.healthy()?;
|
||||
if scope.cursor < layer_end && scope.issuer.entries[scope.cursor].expert == e {
|
||||
let k = scope.cursor;
|
||||
let entry = scope.issuer.entries[k];
|
||||
if entry.layer != layer {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
while scope.issuer.issued.load(Ordering::Acquire) <= k {
|
||||
scope.healthy()?;
|
||||
thread::yield_now();
|
||||
}
|
||||
let sl = k % scope.issuer.ring;
|
||||
let api = &scope.stager.api;
|
||||
let copied = scope.issuer.events.copied[sl];
|
||||
let compute = scope.compute.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
compute.with_enqueue(|s| api.wait(s, copied))?;
|
||||
producer(e, scope.issuer.targets[sl], entry.bytes, compute)?;
|
||||
compute.with_enqueue(|s| api.record(scope.issuer.events.used[sl], s))?;
|
||||
scope.cursor += 1;
|
||||
scope.give_back()?;
|
||||
} else {
|
||||
let index = usize::from(layer - scope.first) * 512 + e as usize;
|
||||
let (h, n) = self.resident.get(index).copied().flatten().ok_or(Error::InvalidQwenShape)?;
|
||||
producer(e, h, n, scope.compute.as_mut().ok_or(Error::ContextPoisoned)?)?;
|
||||
}
|
||||
}
|
||||
scope.release_unused(512, layer_end)?;
|
||||
scope.next_layer += 1;
|
||||
Ok(())
|
||||
self.scope.check_layer(layer, experts)?;
|
||||
self.scope.walk_layer(layer, experts, producer, |scope, layer, e| {
|
||||
let index = usize::from(layer - scope.first) * 512 + e as usize;
|
||||
self.resident.get(index).copied().flatten().ok_or(Error::InvalidQwenShape)
|
||||
})
|
||||
}
|
||||
}
|
||||
impl<'member, 'ctx> OriginalStreamAllMember<'member, 'ctx> {
|
||||
@@ -224,92 +234,11 @@ impl<'f, 's, 'arena, 'loan, 'ctx> OriginalStreamAllForward<'f, 's, 'arena, 'loan
|
||||
producer: &mut P,
|
||||
) -> Result<()> {
|
||||
self.validate_rows(rows)?;
|
||||
let scope = &mut self.scope;
|
||||
if layer != scope.next_layer
|
||||
|| layer < scope.first
|
||||
|| layer >= scope.end
|
||||
|| experts.len() > 512
|
||||
|| experts.windows(2).any(|p| p[0] >= p[1])
|
||||
|| experts.iter().any(|e| *e >= 512)
|
||||
{
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
producer.validate(scope.stager.context, rows, layer)?;
|
||||
let layer_end = scope.layer_start[layer as usize + 1];
|
||||
let mut group_ids = [0u32; ORIGINAL_MMQ_GROUP];
|
||||
for (j, &expert) in experts.iter().enumerate() {
|
||||
scope.release_unused(expert, layer_end)?;
|
||||
scope.healthy()?;
|
||||
let group_slot = j % ORIGINAL_MMQ_GROUP;
|
||||
group_ids[group_slot] = expert;
|
||||
let last = group_slot + 1 == ORIGINAL_MMQ_GROUP || j + 1 == experts.len();
|
||||
if scope.cursor < layer_end && scope.issuer.entries[scope.cursor].expert == expert {
|
||||
let k = scope.cursor;
|
||||
let entry = scope.issuer.entries[k];
|
||||
if entry.layer != layer {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
while scope.issuer.issued.load(Ordering::Acquire) <= k {
|
||||
scope.healthy()?;
|
||||
thread::yield_now();
|
||||
}
|
||||
let slot = k % scope.issuer.ring;
|
||||
let api = &scope.stager.api;
|
||||
let compute = scope.compute.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
compute.with_enqueue(|s| api.wait(s, scope.issuer.events.copied[slot]))?;
|
||||
{
|
||||
let member = OriginalStreamAllMember {
|
||||
context: scope.stager.context,
|
||||
expert,
|
||||
blob: scope.issuer.targets[slot],
|
||||
bytes: entry.bytes,
|
||||
_borrow: std::marker::PhantomData,
|
||||
};
|
||||
producer.gather(&member, group_slot, compute)?;
|
||||
}
|
||||
// Exact Original used mark AFTER actual gather's last source read, BEFORE
|
||||
// the grouped math for the last member. No new host/device synchronization.
|
||||
compute.with_enqueue(|s| api.record(scope.issuer.events.used[slot], s))?;
|
||||
if last {
|
||||
producer.project(
|
||||
&OriginalStreamAllGatheredGroup {
|
||||
first: j - group_slot,
|
||||
experts: &group_ids[..group_slot + 1],
|
||||
},
|
||||
compute,
|
||||
)?;
|
||||
}
|
||||
// Original gives back this chronological slot after its compute callback
|
||||
// (including final-member group launches) returns.
|
||||
scope.cursor += 1;
|
||||
scope.give_back()?;
|
||||
} else {
|
||||
let index = usize::from(layer - scope.first) * 512 + expert as usize;
|
||||
let (blob, bytes) = self.resident.get(index).copied().flatten().ok_or(Error::InvalidQwenShape)?;
|
||||
let compute = scope.compute.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
{
|
||||
let member = OriginalStreamAllMember {
|
||||
context: scope.stager.context,
|
||||
expert,
|
||||
blob,
|
||||
bytes,
|
||||
_borrow: std::marker::PhantomData,
|
||||
};
|
||||
producer.gather(&member, group_slot, compute)?;
|
||||
}
|
||||
if last {
|
||||
producer.project(
|
||||
&OriginalStreamAllGatheredGroup {
|
||||
first: j - group_slot,
|
||||
experts: &group_ids[..group_slot + 1],
|
||||
},
|
||||
compute,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
scope.release_unused(512, layer_end)?;
|
||||
scope.next_layer += 1;
|
||||
Ok(())
|
||||
self.scope.check_layer(layer, experts)?;
|
||||
producer.validate(self.scope.stager.context, rows, layer)?;
|
||||
self.scope.walk_grouped(layer, experts, producer, |scope, layer, expert| {
|
||||
let index = usize::from(layer - scope.first) * 512 + expert as usize;
|
||||
self.resident.get(index).copied().flatten().ok_or(Error::InvalidQwenShape)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+51
-72
@@ -3,6 +3,9 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
#[path = "impl_originalstreamall/walk.rs"]
|
||||
mod walk;
|
||||
|
||||
impl OriginalStreamAll<'_, '_, '_, '_> {
|
||||
pub(in super::super) fn issue_inline(&mut self, limit: usize) -> Result<()> {
|
||||
while self.issuer.issued.load(Ordering::Acquire) < limit.min(self.issuer.entries.len()) {
|
||||
@@ -52,75 +55,30 @@ impl OriginalStreamAll<'_, '_, '_, '_> {
|
||||
&mut self,
|
||||
layer: u8,
|
||||
experts: &[u32],
|
||||
mut producer: impl FnMut(u32, BufferHandle, usize, &mut OriginalGpuStream<'_>) -> Result<()>,
|
||||
producer: impl FnMut(u32, BufferHandle, usize, &mut OriginalGpuStream<'_>) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
self.healthy()?;
|
||||
if layer != self.next_layer
|
||||
|| layer < self.first
|
||||
|| layer >= self.end
|
||||
|| experts.len() > 512
|
||||
|| experts.windows(2).any(|p| p[0] >= p[1])
|
||||
|| experts.iter().any(|e| *e >= 512)
|
||||
{
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let layer_end = self.layer_start[layer as usize + 1];
|
||||
for &e in experts {
|
||||
self.release_unused(e, layer_end)?;
|
||||
self.healthy()?;
|
||||
if self.cursor < layer_end && self.issuer.entries[self.cursor].expert == e {
|
||||
let k = self.cursor;
|
||||
let entry = self.issuer.entries[k];
|
||||
if entry.layer != layer {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
while self.issuer.issued.load(Ordering::Acquire) <= k {
|
||||
self.healthy()?;
|
||||
thread::yield_now();
|
||||
}
|
||||
let sl = k % self.issuer.ring;
|
||||
let api = &self.stager.api;
|
||||
let copied = self.issuer.events.copied[sl];
|
||||
let compute = self.compute.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
compute.with_enqueue(|s| api.wait(s, copied))?;
|
||||
producer(e, self.issuer.targets[sl], entry.bytes, compute)?;
|
||||
compute.with_enqueue(|s| api.record(self.issuer.events.used[sl], s))?;
|
||||
self.cursor += 1;
|
||||
self.give_back()?;
|
||||
} else {
|
||||
let (h, n) = self
|
||||
.rows
|
||||
.as_ref()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.cache_expert_span(layer as usize, e as usize)?
|
||||
.ok_or(Error::InvalidQwenShape)?;
|
||||
producer(e, h, n, self.compute.as_mut().ok_or(Error::ContextPoisoned)?)?;
|
||||
}
|
||||
}
|
||||
self.release_unused(512, layer_end)?;
|
||||
self.next_layer += 1;
|
||||
Ok(())
|
||||
self.check_layer(layer, experts)?;
|
||||
self.walk_layer(layer, experts, producer, |scope, layer, e| {
|
||||
scope
|
||||
.rows
|
||||
.as_ref()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.cache_expert_span(layer as usize, e as usize)?
|
||||
.ok_or(Error::InvalidQwenShape)
|
||||
})
|
||||
}
|
||||
pub(in super::super) fn cleanup(&mut self) -> Result<()> {
|
||||
if self.finished {
|
||||
return Ok(());
|
||||
}
|
||||
self.issuer.stop.store(true, Ordering::Release);
|
||||
let mut result = Ok(());
|
||||
if let Some(t) = self.thread.take() {
|
||||
if t.join().is_err() {
|
||||
result = Err(Error::InvalidDriverValue("Original issuer join"));
|
||||
}
|
||||
}
|
||||
let mut result = self.join_issuer();
|
||||
if self.issuer.failed.load(Ordering::Acquire) {
|
||||
result = combine(result, Err(self.issuer.error()));
|
||||
}
|
||||
self.stager.shared.stop(self.stager.generation);
|
||||
if let Some(source) = self.stager.source.as_ref() {
|
||||
if let Some(file) = &source.file {
|
||||
result = combine(result, file.lease.validate_current().map_err(|_| Error::InvalidSize));
|
||||
}
|
||||
}
|
||||
result = combine(result, self.source_lease_current());
|
||||
if self.stager.shared.failed.load(Ordering::Acquire) {
|
||||
result = combine(result, Err(self.stager.shared.error()));
|
||||
}
|
||||
@@ -129,26 +87,47 @@ impl OriginalStreamAll<'_, '_, '_, '_> {
|
||||
result =
|
||||
combine(result, self.compute.as_ref().map_or(Err(Error::ContextPoisoned), OriginalGpuStream::synchronize));
|
||||
if result.is_err() || self.stager.context.is_poisoned() {
|
||||
self.stager.shared.failed.store(true, Ordering::Release);
|
||||
self.stager.context.poison();
|
||||
self.stager.context.retain_driver();
|
||||
if let Some(mut rows) = self.rows.take() {
|
||||
rows.mark_failed();
|
||||
std::mem::forget(rows);
|
||||
}
|
||||
if let Some(s) = self.copy.take() {
|
||||
std::mem::forget(s);
|
||||
}
|
||||
if let Some(s) = self.compute.take() {
|
||||
std::mem::forget(s);
|
||||
}
|
||||
std::mem::forget(self.issuer.clone());
|
||||
std::mem::forget(self.stager.api.clone());
|
||||
self.retain_after_failure();
|
||||
}
|
||||
self.stager.external = false;
|
||||
self.finished = true;
|
||||
result
|
||||
}
|
||||
fn join_issuer(&mut self) -> Result<()> {
|
||||
let mut result = Ok(());
|
||||
if let Some(t) = self.thread.take() {
|
||||
if t.join().is_err() {
|
||||
result = Err(Error::InvalidDriverValue("Original issuer join"));
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
fn source_lease_current(&self) -> Result<()> {
|
||||
if let Some(source) = self.stager.source.as_ref() {
|
||||
if let Some(file) = &source.file {
|
||||
return file.lease.validate_current().map_err(|_| Error::InvalidSize);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// A failed or uncertain scope poisons the context and retains every owner a device operation may still touch.
|
||||
fn retain_after_failure(&mut self) {
|
||||
self.stager.shared.failed.store(true, Ordering::Release);
|
||||
self.stager.context.poison();
|
||||
self.stager.context.retain_driver();
|
||||
if let Some(mut rows) = self.rows.take() {
|
||||
rows.mark_failed();
|
||||
std::mem::forget(rows);
|
||||
}
|
||||
if let Some(s) = self.copy.take() {
|
||||
std::mem::forget(s);
|
||||
}
|
||||
if let Some(s) = self.compute.take() {
|
||||
std::mem::forget(s);
|
||||
}
|
||||
std::mem::forget(self.issuer.clone());
|
||||
std::mem::forget(self.stager.api.clone());
|
||||
}
|
||||
}
|
||||
impl Drop for OriginalStreamAll<'_, '_, '_, '_> {
|
||||
fn drop(&mut self) {
|
||||
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
//! The shared walk of the global expert stream (`consume_layer` and its grouped form), split out by STRA-338 size pass 2.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// What a streamed expert's callback gets: the issued entry, its ring slot, its target blob and the used event.
|
||||
pub(crate) struct Streamed<'a> {
|
||||
api: &'a abi::Api,
|
||||
entry: Entry,
|
||||
target: BufferHandle,
|
||||
used: usize,
|
||||
}
|
||||
|
||||
impl Streamed<'_> {
|
||||
/// Exact Original used mark, after the producer's last read of the blob.
|
||||
fn record_used(&self, compute: &mut OriginalGpuStream<'_>) -> Result<()> {
|
||||
compute.with_enqueue(|s| self.api.record(self.used, s))
|
||||
}
|
||||
}
|
||||
|
||||
/// One expert of a sorted layer list and its place in the 16-wide gather groups.
|
||||
pub(crate) struct GroupStep<'a> {
|
||||
expert: u32,
|
||||
ids: &'a [u32],
|
||||
j: usize,
|
||||
slot: usize,
|
||||
last: bool,
|
||||
}
|
||||
|
||||
impl GroupStep<'_> {
|
||||
fn gather<'ctx, P: OriginalStreamAllGroupProducer<'ctx>>(
|
||||
&self,
|
||||
producer: &mut P,
|
||||
(context, blob, bytes): (&'ctx crate::Context<'ctx>, BufferHandle, usize),
|
||||
compute: &mut OriginalGpuStream<'ctx>,
|
||||
) -> Result<()> {
|
||||
let member =
|
||||
OriginalStreamAllMember { context, expert: self.expert, blob, bytes, _borrow: std::marker::PhantomData };
|
||||
producer.gather(&member, self.slot, compute)
|
||||
}
|
||||
fn project_if_last<'ctx, P: OriginalStreamAllGroupProducer<'ctx>>(
|
||||
&self,
|
||||
producer: &mut P,
|
||||
compute: &mut OriginalGpuStream<'ctx>,
|
||||
) -> Result<()> {
|
||||
if !self.last {
|
||||
return Ok(());
|
||||
}
|
||||
producer.project(&OriginalStreamAllGatheredGroup { first: self.j - self.slot, experts: self.ids }, compute)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s, 'arena, 'loan, 'ctx> OriginalStreamAll<'s, 'arena, 'loan, 'ctx> {
|
||||
/// The layer is the next one, inside the scope, and the experts are strictly ascending ids.
|
||||
pub(crate) fn check_layer(&self, layer: u8, experts: &[u32]) -> Result<()> {
|
||||
if layer != self.next_layer
|
||||
|| layer < self.first
|
||||
|| layer >= self.end
|
||||
|| experts.len() > 512
|
||||
|| experts.windows(2).any(|p| p[0] >= p[1])
|
||||
|| experts.iter().any(|e| *e >= 512)
|
||||
{
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn streams_next(&self, expert: u32, layer_end: usize) -> bool {
|
||||
self.cursor < layer_end && self.issuer.entries[self.cursor].expert == expert
|
||||
}
|
||||
/// The streamed expert under the cursor: wait for its issued copy, let `produce` read the blob on the compute stream,
|
||||
/// then give the ring slot back.
|
||||
fn consume_streamed(
|
||||
&mut self,
|
||||
layer: u8,
|
||||
produce: impl FnOnce(&Streamed<'_>, &mut OriginalGpuStream<'ctx>) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
let k = self.cursor;
|
||||
let entry = self.issuer.entries[k];
|
||||
if entry.layer != layer {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
while self.issuer.issued.load(Ordering::Acquire) <= k {
|
||||
self.healthy()?;
|
||||
thread::yield_now();
|
||||
}
|
||||
let slot = k % self.issuer.ring;
|
||||
let api = &self.stager.api;
|
||||
let copied = self.issuer.events.copied[slot];
|
||||
let compute = self.compute.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
compute.with_enqueue(|s| api.wait(s, copied))?;
|
||||
let streamed = Streamed { api, entry, target: self.issuer.targets[slot], used: self.issuer.events.used[slot] };
|
||||
produce(&streamed, compute)?;
|
||||
self.cursor += 1;
|
||||
self.give_back()
|
||||
}
|
||||
/// Ascending global stream walk of one layer; `resident` finds the blob of an expert the stream does not carry.
|
||||
pub(crate) fn walk_layer(
|
||||
&mut self,
|
||||
layer: u8,
|
||||
experts: &[u32],
|
||||
mut producer: impl FnMut(u32, BufferHandle, usize, &mut OriginalGpuStream<'ctx>) -> Result<()>,
|
||||
mut resident: impl FnMut(&Self, u8, u32) -> Result<(BufferHandle, usize)>,
|
||||
) -> Result<()> {
|
||||
let layer_end = self.layer_start[layer as usize + 1];
|
||||
for &e in experts {
|
||||
self.walk_expert(layer, layer_end, e, &mut producer, &mut resident)?;
|
||||
}
|
||||
self.release_unused(512, layer_end)?;
|
||||
self.next_layer += 1;
|
||||
Ok(())
|
||||
}
|
||||
fn walk_expert(
|
||||
&mut self,
|
||||
layer: u8,
|
||||
layer_end: usize,
|
||||
e: u32,
|
||||
producer: &mut impl FnMut(u32, BufferHandle, usize, &mut OriginalGpuStream<'ctx>) -> Result<()>,
|
||||
resident: &mut impl FnMut(&Self, u8, u32) -> Result<(BufferHandle, usize)>,
|
||||
) -> Result<()> {
|
||||
self.release_unused(e, layer_end)?;
|
||||
self.healthy()?;
|
||||
if self.streams_next(e, layer_end) {
|
||||
return self.consume_streamed(layer, |st, compute| {
|
||||
producer(e, st.target, st.entry.bytes, compute)?;
|
||||
st.record_used(compute)
|
||||
});
|
||||
}
|
||||
let (h, n) = resident(self, layer, e)?;
|
||||
producer(e, h, n, self.compute.as_mut().ok_or(Error::ContextPoisoned)?)
|
||||
}
|
||||
/// Literal ascending global stream walk with default16/actual lastpartial.
|
||||
pub(crate) fn walk_grouped<P: OriginalStreamAllGroupProducer<'ctx>>(
|
||||
&mut self,
|
||||
layer: u8,
|
||||
experts: &[u32],
|
||||
producer: &mut P,
|
||||
mut resident: impl FnMut(&Self, u8, u32) -> Result<(BufferHandle, usize)>,
|
||||
) -> Result<()> {
|
||||
let layer_end = self.layer_start[layer as usize + 1];
|
||||
let mut group_ids = [0u32; ORIGINAL_MMQ_GROUP];
|
||||
for (j, &expert) in experts.iter().enumerate() {
|
||||
self.release_unused(expert, layer_end)?;
|
||||
self.healthy()?;
|
||||
let slot = j % ORIGINAL_MMQ_GROUP;
|
||||
group_ids[slot] = expert;
|
||||
let last = slot + 1 == ORIGINAL_MMQ_GROUP || j + 1 == experts.len();
|
||||
let step = GroupStep { expert, ids: &group_ids[..slot + 1], j, slot, last };
|
||||
self.group_step(layer, layer_end, &step, producer, &mut resident)?;
|
||||
}
|
||||
self.release_unused(512, layer_end)?;
|
||||
self.next_layer += 1;
|
||||
Ok(())
|
||||
}
|
||||
fn group_step<P: OriginalStreamAllGroupProducer<'ctx>>(
|
||||
&mut self,
|
||||
layer: u8,
|
||||
layer_end: usize,
|
||||
step: &GroupStep<'_>,
|
||||
producer: &mut P,
|
||||
resident: &mut impl FnMut(&Self, u8, u32) -> Result<(BufferHandle, usize)>,
|
||||
) -> Result<()> {
|
||||
let context = self.stager.context;
|
||||
if self.streams_next(step.expert, layer_end) {
|
||||
return self.consume_streamed(layer, |st, compute| {
|
||||
step.gather(producer, (context, st.target, st.entry.bytes), compute)?;
|
||||
// Exact Original used mark AFTER actual gather's last source read, BEFORE
|
||||
// the grouped math for the last member. No new host/device synchronization.
|
||||
st.record_used(compute)?;
|
||||
step.project_if_last(producer, compute)
|
||||
});
|
||||
}
|
||||
let (blob, bytes) = resident(self, layer, step.expert)?;
|
||||
let compute = self.compute.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
step.gather(producer, (context, blob, bytes), compute)?;
|
||||
step.project_if_last(producer, compute)
|
||||
}
|
||||
}
|
||||
+17
-15
@@ -100,21 +100,7 @@ pub(in super::super) fn issuer_thread(
|
||||
shared.fail(e);
|
||||
return;
|
||||
}
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
for k in 0..shared.entries.len() {
|
||||
while k >= shared.consumed.load(Ordering::Acquire).saturating_add(shared.ring) {
|
||||
if shared.stop.load(Ordering::Acquire) {
|
||||
return Ok(());
|
||||
}
|
||||
thread::yield_now();
|
||||
}
|
||||
if shared.stop.load(Ordering::Acquire) {
|
||||
return Ok(());
|
||||
}
|
||||
shared.issue_one(&api, &stager, copy, k)?;
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| issue_all(&api, &shared, &stager, copy)));
|
||||
match result {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(e)) => shared.fail(e),
|
||||
@@ -124,6 +110,22 @@ pub(in super::super) fn issuer_thread(
|
||||
shared.fail(e);
|
||||
}
|
||||
}
|
||||
/// Issues every entry in chronological order, never more than a ring ahead of the consumer; a stop request ends it quietly.
|
||||
fn issue_all(api: &abi::Api, shared: &Issuer, stager: &Shared, copy: usize) -> Result<()> {
|
||||
for k in 0..shared.entries.len() {
|
||||
while k >= shared.consumed.load(Ordering::Acquire).saturating_add(shared.ring) {
|
||||
if shared.stop.load(Ordering::Acquire) {
|
||||
return Ok(());
|
||||
}
|
||||
thread::yield_now();
|
||||
}
|
||||
if shared.stop.load(Ordering::Acquire) {
|
||||
return Ok(());
|
||||
}
|
||||
shared.issue_one(api, stager, copy, k)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
impl<'arena, 'loan, 'ctx> OriginalStreamAllCompleted<'arena, 'loan, 'ctx> {
|
||||
pub fn streamed_experts(&self) -> usize {
|
||||
self.streamed
|
||||
|
||||
+115
-107
@@ -12,45 +12,42 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
|
||||
capture.validate_context(self.physical.context)?;
|
||||
let stream = capture.stream_handle(self.physical.context)?;
|
||||
let module = self.physical.module.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
for c in &commands {
|
||||
module.admit(c)?
|
||||
}
|
||||
let mut retained = self.commands.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
|
||||
retained.try_reserve_exact(commands.len()).map_err(|_| Error::HostAllocation)?;
|
||||
let first = retained.len();
|
||||
retained.extend(commands);
|
||||
check_commands(&retained)?;
|
||||
for c in &mut retained[first..] {
|
||||
if let Err(e) = module.launch(stream, c) {
|
||||
if transport(&e) {
|
||||
self.physical.failed.set(true);
|
||||
poison(self.physical.context)
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
self.submit_with(module, stream, commands)
|
||||
}
|
||||
pub(crate) fn submit_qsa(&self, capture: &mut OriginalCapture<'_, 'ctx>, commands: Vec<Command>) -> Result<()> {
|
||||
capture.validate_context(self.physical.context)?;
|
||||
let stream = capture.stream_handle(self.physical.context)?;
|
||||
let module = self.physical.qsa_module.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
self.submit_with(module, stream, commands)
|
||||
}
|
||||
/// Admits the commands against `module`, retains them (the graph keeps their ABI alive) and launches them in order.
|
||||
fn submit_with(&self, module: &Module, stream: usize, commands: Vec<Command>) -> Result<()> {
|
||||
for c in &commands {
|
||||
module.admit(c)?;
|
||||
}
|
||||
let (mut retained, first) = self.retain_commands(commands)?;
|
||||
for c in &mut retained[first..] {
|
||||
self.launch_checked(module, stream, c)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Appends `commands` to the retained list; returns it with the index of the first new command.
|
||||
fn retain_commands(&self, commands: Vec<Command>) -> Result<(std::cell::RefMut<'_, Vec<Command>>, usize)> {
|
||||
let mut retained = self.commands.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
|
||||
retained.try_reserve_exact(commands.len()).map_err(|_| Error::HostAllocation)?;
|
||||
let first = retained.len();
|
||||
retained.extend(commands);
|
||||
check_commands(&retained)?;
|
||||
for c in &mut retained[first..] {
|
||||
if let Err(error) = module.launch(stream, c) {
|
||||
if transport(&error) {
|
||||
self.physical.failed.set(true);
|
||||
poison(self.physical.context)
|
||||
}
|
||||
return Err(error);
|
||||
Ok((retained, first))
|
||||
}
|
||||
/// A transport failure of a launch poisons the context.
|
||||
fn launch_checked(&self, module: &Module, stream: usize, command: &mut Command) -> Result<()> {
|
||||
if let Err(e) = module.launch(stream, command) {
|
||||
if transport(&e) {
|
||||
self.physical.failed.set(true);
|
||||
poison(self.physical.context)
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -75,36 +72,14 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
|
||||
) -> Result<()> {
|
||||
capture.validate_context(self.physical.context)?;
|
||||
let stream = capture.stream_handle(self.physical.context)?;
|
||||
let mut commands = Vec::new();
|
||||
commands.try_reserve_exact(launches.len()).map_err(|_| Error::HostAllocation)?;
|
||||
for l in &launches {
|
||||
commands.push(l.command()?)
|
||||
}
|
||||
let commands = launch_commands(&launches)?;
|
||||
let modules = self.physical.window.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
for (l, c) in launches.iter().zip(&commands) {
|
||||
let m = modules
|
||||
.iter()
|
||||
.find(|(n, _, _)| *n == l.asset.key())
|
||||
.ok_or(Error::InvalidDriverValue(l.asset.unsealed))?;
|
||||
m.1.admit(c)?
|
||||
window_module(&modules, l)?.admit(c)?
|
||||
}
|
||||
let mut retained = self.commands.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
|
||||
retained.try_reserve_exact(commands.len()).map_err(|_| Error::HostAllocation)?;
|
||||
let first = retained.len();
|
||||
retained.extend(commands);
|
||||
check_commands(&retained)?;
|
||||
for (i, c) in retained[first..].iter_mut().enumerate() {
|
||||
let m = modules
|
||||
.iter()
|
||||
.find(|(n, _, _)| *n == launches[i].asset.key())
|
||||
.ok_or(Error::InvalidDriverValue(launches[i].asset.unsealed))?;
|
||||
if let Err(e) = m.1.launch(stream, c) {
|
||||
if transport(&e) {
|
||||
self.physical.failed.set(true);
|
||||
poison(self.physical.context)
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
let (mut retained, first) = self.retain_commands(commands)?;
|
||||
for (l, c) in launches.iter().zip(retained[first..].iter_mut()) {
|
||||
self.launch_checked(window_module(&modules, l)?, stream, c)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -120,6 +95,14 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
|
||||
if !(1..=g.max_t).contains(&t) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let mut commands = self.mapped_input_copies(t)?;
|
||||
if self.ple.is_some() {
|
||||
commands.push(self.ple_input_copy(t)?);
|
||||
}
|
||||
self.submit(capture, commands)
|
||||
}
|
||||
fn mapped_input_copies(&self, t: usize) -> Result<Vec<Command>> {
|
||||
let g = self.geometry();
|
||||
let mut commands = Vec::new();
|
||||
commands.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?;
|
||||
for (name, slot, count) in
|
||||
@@ -136,20 +119,20 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
|
||||
],
|
||||
)?);
|
||||
}
|
||||
if self.ple.is_some() {
|
||||
let words = t * g.n;
|
||||
commands.push(command(
|
||||
"verify_copy_from_mapped_kernel",
|
||||
[(words / 4).div_ceil(256).min(64) as u32, 1, 1],
|
||||
[256, 1, 1],
|
||||
vec![
|
||||
Arg::Address(self.physical.span("ple", 0, words * 4)?),
|
||||
Arg::Address(self.physical.mapped_address(4, 0, words * 4)?),
|
||||
Arg::I64((words / 4) as i64),
|
||||
],
|
||||
)?);
|
||||
}
|
||||
self.submit(capture, commands)
|
||||
Ok(commands)
|
||||
}
|
||||
fn ple_input_copy(&self, t: usize) -> Result<Command> {
|
||||
let words = t * self.geometry().n;
|
||||
command(
|
||||
"verify_copy_from_mapped_kernel",
|
||||
[(words / 4).div_ceil(256).min(64) as u32, 1, 1],
|
||||
[256, 1, 1],
|
||||
vec![
|
||||
Arg::Address(self.physical.span("ple", 0, words * 4)?),
|
||||
Arg::Address(self.physical.mapped_address(4, 0, words * 4)?),
|
||||
Arg::I64((words / 4) as i64),
|
||||
],
|
||||
)
|
||||
}
|
||||
/// Literal `gpu_stamp(prof_, l*33+i, cs)` of `STRATA_VERIFY_PROFILE`; recorded for group 0 only
|
||||
/// and a no-op when the profile is off, so the captured graph is Original's either way.
|
||||
@@ -176,49 +159,74 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
|
||||
if begin >= end || end > g.max_t {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let n = end - begin;
|
||||
if chain::flags().glue {
|
||||
let a = |name: &str, off: usize, bytes: usize| self.physical.span(name, off, bytes);
|
||||
return self.submit_launches(
|
||||
capture,
|
||||
vec![kernels::Launch::new(
|
||||
&chain::CHAIN,
|
||||
chain::E_DOORBELL,
|
||||
[1, 1, 1],
|
||||
[1024, 1, 1],
|
||||
0,
|
||||
vec![
|
||||
kernels::A::P(a("mixed", begin * g.n * 4, n * g.n * 4)?),
|
||||
kernels::A::P(a("ids", begin * g.k * 4, n * g.k * 4)?),
|
||||
kernels::A::P(a("w", begin * g.k * 4, n * g.k * 4)?),
|
||||
kernels::A::I32((n * g.n) as i32),
|
||||
kernels::A::I32((n * g.k) as i32),
|
||||
kernels::A::P(self.physical.mapped_address(6, begin * g.n * 4, n * g.n * 4)?),
|
||||
kernels::A::P(self.physical.mapped_address(7, begin * g.k * 4, n * g.k * 4)?),
|
||||
kernels::A::P(self.physical.mapped_address(8, begin * g.k * 4, n * g.k * 4)?),
|
||||
kernels::A::P(self.physical.mapped_address(9, 0, 4)?),
|
||||
],
|
||||
)?],
|
||||
);
|
||||
return self.submit_launches(capture, vec![self.doorbell_glue_launch(begin, end)?]);
|
||||
}
|
||||
self.submit(
|
||||
capture,
|
||||
vec![command(
|
||||
"verify_doorbell_publish_kernel",
|
||||
[1, 1, 1],
|
||||
[1024, 1, 1],
|
||||
vec![
|
||||
Arg::Address(self.physical.span("mixed", begin * g.n * 4, n * g.n * 4)?),
|
||||
Arg::Address(self.physical.span("ids", begin * g.k * 4, n * g.k * 4)?),
|
||||
Arg::Address(self.physical.span("w", begin * g.k * 4, n * g.k * 4)?),
|
||||
Arg::I32((n * g.n) as i32),
|
||||
Arg::I32((n * g.k) as i32),
|
||||
Arg::Address(self.physical.mapped_address(6, begin * g.n * 4, n * g.n * 4)?),
|
||||
Arg::Address(self.physical.mapped_address(7, begin * g.k * 4, n * g.k * 4)?),
|
||||
Arg::Address(self.physical.mapped_address(8, begin * g.k * 4, n * g.k * 4)?),
|
||||
Arg::Address(self.physical.mapped_address(9, 0, 4)?),
|
||||
],
|
||||
)?],
|
||||
self.submit(capture, vec![self.doorbell_command(begin, end)?])
|
||||
}
|
||||
fn doorbell_glue_launch(&self, begin: usize, end: usize) -> Result<kernels::Launch> {
|
||||
let g = self.geometry();
|
||||
let n = end - begin;
|
||||
let a = |name: &str, off: usize, bytes: usize| self.physical.span(name, off, bytes);
|
||||
kernels::Launch::new(
|
||||
&chain::CHAIN,
|
||||
chain::E_DOORBELL,
|
||||
[1, 1, 1],
|
||||
[1024, 1, 1],
|
||||
0,
|
||||
vec![
|
||||
kernels::A::P(a("mixed", begin * g.n * 4, n * g.n * 4)?),
|
||||
kernels::A::P(a("ids", begin * g.k * 4, n * g.k * 4)?),
|
||||
kernels::A::P(a("w", begin * g.k * 4, n * g.k * 4)?),
|
||||
kernels::A::I32((n * g.n) as i32),
|
||||
kernels::A::I32((n * g.k) as i32),
|
||||
kernels::A::P(self.physical.mapped_address(6, begin * g.n * 4, n * g.n * 4)?),
|
||||
kernels::A::P(self.physical.mapped_address(7, begin * g.k * 4, n * g.k * 4)?),
|
||||
kernels::A::P(self.physical.mapped_address(8, begin * g.k * 4, n * g.k * 4)?),
|
||||
kernels::A::P(self.physical.mapped_address(9, 0, 4)?),
|
||||
],
|
||||
)
|
||||
}
|
||||
fn doorbell_command(&self, begin: usize, end: usize) -> Result<Command> {
|
||||
let g = self.geometry();
|
||||
let n = end - begin;
|
||||
command(
|
||||
"verify_doorbell_publish_kernel",
|
||||
[1, 1, 1],
|
||||
[1024, 1, 1],
|
||||
vec![
|
||||
Arg::Address(self.physical.span("mixed", begin * g.n * 4, n * g.n * 4)?),
|
||||
Arg::Address(self.physical.span("ids", begin * g.k * 4, n * g.k * 4)?),
|
||||
Arg::Address(self.physical.span("w", begin * g.k * 4, n * g.k * 4)?),
|
||||
Arg::I32((n * g.n) as i32),
|
||||
Arg::I32((n * g.k) as i32),
|
||||
Arg::Address(self.physical.mapped_address(6, begin * g.n * 4, n * g.n * 4)?),
|
||||
Arg::Address(self.physical.mapped_address(7, begin * g.k * 4, n * g.k * 4)?),
|
||||
Arg::Address(self.physical.mapped_address(8, begin * g.k * 4, n * g.k * 4)?),
|
||||
Arg::Address(self.physical.mapped_address(9, 0, 4)?),
|
||||
],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The commands of window launches, in order.
|
||||
fn launch_commands(launches: &[kernels::Launch]) -> Result<Vec<Command>> {
|
||||
let mut commands = Vec::new();
|
||||
commands.try_reserve_exact(launches.len()).map_err(|_| Error::HostAllocation)?;
|
||||
for l in launches {
|
||||
commands.push(l.command()?)
|
||||
}
|
||||
Ok(commands)
|
||||
}
|
||||
|
||||
/// The loaded window module of a launch's asset.
|
||||
fn window_module<'a>(
|
||||
modules: &'a [(&'static str, Rc<Module>, Vec<&'static str>)],
|
||||
launch: &kernels::Launch,
|
||||
) -> Result<&'a Module> {
|
||||
modules
|
||||
.iter()
|
||||
.find(|(n, _, _)| *n == launch.asset.key())
|
||||
.map(|m| &*m.1)
|
||||
.ok_or(Error::InvalidDriverValue(launch.asset.unsealed))
|
||||
}
|
||||
|
||||
+193
-119
@@ -15,101 +15,120 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
|
||||
end: usize,
|
||||
) -> Result<()> {
|
||||
self.validate_context(self.physical.context)?;
|
||||
let op = self.stage_operands(layer, begin, end)?;
|
||||
let mut commands = self.stage_commands(&op)?;
|
||||
if chain::flags().ab && matches!(stage, OriginalVerifyGdnStage::AlphaBeta) {
|
||||
return self.submit_launches(capture, vec![self.stage_ab_launch(&op)?]);
|
||||
}
|
||||
self.submit(capture, single_command(commands.swap_remove(stage as usize))?)
|
||||
}
|
||||
/// The range check and the arena spans one layer stage works on.
|
||||
fn stage_operands(&self, layer: usize, begin: usize, end: usize) -> Result<StageOperands> {
|
||||
let g = self.physical.layout.geometry;
|
||||
if layer >= 36 || begin >= end || end > g.max_t {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let n = end - begin;
|
||||
let w = &self.weights[layer];
|
||||
let c = self.physical.context;
|
||||
let qkv = self.physical.span("qkv_L", layer * g.max_t * g.channels * 4, g.max_t * g.channels * 4)?;
|
||||
let h = self.physical.span("h_L", layer * g.max_t * g.channels * 4, g.max_t * g.channels * 4)?;
|
||||
let gate = self.physical.span("gate_L", layer * g.max_t * g.value_heads * 4, g.max_t * g.value_heads * 4)?;
|
||||
let beta = self.physical.span("beta_L", layer * g.max_t * g.value_heads * 4, g.max_t * g.value_heads * 4)?;
|
||||
Ok(StageOperands { layer, begin, end, qkv, h, gate, beta })
|
||||
}
|
||||
fn stage_commands(&self, op: &StageOperands) -> Result<Vec<Command>> {
|
||||
let mut commands = Vec::new();
|
||||
commands.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?;
|
||||
commands.push(command(
|
||||
commands.push(self.stage_conv_command(op)?);
|
||||
commands.push(self.stage_ab_command(op)?);
|
||||
commands.push(self.stage_step_norm_command(op)?);
|
||||
Ok(commands)
|
||||
}
|
||||
fn stage_conv_command(&self, op: &StageOperands) -> Result<Command> {
|
||||
let w = &self.weights[op.layer];
|
||||
command(
|
||||
"verify_gdn_conv_l2_multi_kernel",
|
||||
[80, n as u32, 1],
|
||||
[80, (op.end - op.begin) as u32, 1],
|
||||
[128, 1, 1],
|
||||
vec![
|
||||
Arg::Address(self.canonical.span(layer, true)?),
|
||||
Arg::Address(qkv),
|
||||
Arg::Address(admit(c, w.conv, 10240 * 4 * 4)?),
|
||||
Arg::Address(h),
|
||||
Arg::Address(self.canonical.span(op.layer, true)?),
|
||||
Arg::Address(op.qkv),
|
||||
Arg::Address(admit(self.physical.context, w.conv, 10240 * 4 * 4)?),
|
||||
Arg::Address(op.h),
|
||||
Arg::I32(10240),
|
||||
Arg::I32(32),
|
||||
Arg::F32(EPS),
|
||||
Arg::I32(begin as i32),
|
||||
Arg::I32(op.begin as i32),
|
||||
],
|
||||
)?);
|
||||
commands.push(command(
|
||||
)
|
||||
}
|
||||
fn stage_ab_command(&self, op: &StageOperands) -> Result<Command> {
|
||||
let (g, c, w) = (self.physical.layout.geometry, self.physical.context, &self.weights[op.layer]);
|
||||
let n = op.end - op.begin;
|
||||
command(
|
||||
"verify_gdn_ab_multi_kernel",
|
||||
[12, 1, 1],
|
||||
[256, 1, 1],
|
||||
vec![
|
||||
Arg::Address(self.physical.span("mixed", begin * g.n * 4, n * g.n * 4)?),
|
||||
Arg::Address(self.physical.span("mixed", op.begin * g.n * 4, n * g.n * 4)?),
|
||||
Arg::Address(admit(c, w.alpha, 48 * 2560 * 2)?),
|
||||
Arg::Address(admit(c, w.beta, 48 * 2560 * 2)?),
|
||||
Arg::Address(admit(c, w.dt, 48 * 4)?),
|
||||
Arg::Address(admit(c, w.a, 48 * 4)?),
|
||||
Arg::Address(gate + (begin * 48 * 4) as u64),
|
||||
Arg::Address(beta + (begin * 48 * 4) as u64),
|
||||
Arg::Address(op.gate + (op.begin * 48 * 4) as u64),
|
||||
Arg::Address(op.beta + (op.begin * 48 * 4) as u64),
|
||||
Arg::I32(2560),
|
||||
Arg::I32(48),
|
||||
Arg::I32(n as i32),
|
||||
],
|
||||
)?);
|
||||
commands.push(command(
|
||||
)
|
||||
}
|
||||
fn stage_step_norm_command(&self, op: &StageOperands) -> Result<Command> {
|
||||
let (g, w) = (self.physical.layout.geometry, &self.weights[op.layer]);
|
||||
command(
|
||||
"verify_gdn_step_norm_multi_kernel",
|
||||
[48, 1, 1],
|
||||
[128, 4, 1],
|
||||
vec![
|
||||
Arg::Address(self.canonical.span(layer, false)?),
|
||||
Arg::Address(h),
|
||||
Arg::Address(self.canonical.span(op.layer, false)?),
|
||||
Arg::Address(op.h),
|
||||
Arg::I32(10240),
|
||||
Arg::Address(gate),
|
||||
Arg::Address(beta),
|
||||
Arg::Address(op.gate),
|
||||
Arg::Address(op.beta),
|
||||
Arg::Address(self.physical.span("z", 0, g.max_t * 6144 * 4)?),
|
||||
Arg::Address(admit(c, w.norm, 128 * 4)?),
|
||||
Arg::Address(admit(self.physical.context, w.norm, 128 * 4)?),
|
||||
Arg::F32(EPS),
|
||||
Arg::Address(self.physical.span("y", 0, g.max_t * 6144 * 4)?),
|
||||
Arg::I32(16),
|
||||
Arg::I32(48),
|
||||
Arg::I32(end as i32),
|
||||
Arg::I32(op.end as i32),
|
||||
Arg::Address(0),
|
||||
Arg::I32(begin as i32),
|
||||
Arg::I32(op.begin as i32),
|
||||
],
|
||||
)?);
|
||||
if chain::flags().ab && matches!(stage, OriginalVerifyGdnStage::AlphaBeta) {
|
||||
let x = self.physical.span("mixed", begin * g.n * 4, n * g.n * 4)?;
|
||||
return self.submit_launches(
|
||||
capture,
|
||||
vec![kernels::Launch::new(
|
||||
&chain::CHAIN,
|
||||
chain::E_GDN_AB,
|
||||
[96, 1, 1],
|
||||
[32, 1, 1],
|
||||
0,
|
||||
vec![
|
||||
kernels::A::P(x),
|
||||
kernels::A::P(admit(c, w.alpha, 48 * 2560 * 2)?),
|
||||
kernels::A::P(admit(c, w.beta, 48 * 2560 * 2)?),
|
||||
kernels::A::P(admit(c, w.dt, 48 * 4)?),
|
||||
kernels::A::P(admit(c, w.a, 48 * 4)?),
|
||||
kernels::A::P(gate + (begin * 48 * 4) as u64),
|
||||
kernels::A::P(beta + (begin * 48 * 4) as u64),
|
||||
kernels::A::I32(2560),
|
||||
kernels::A::I32(48),
|
||||
kernels::A::I32(n as i32),
|
||||
],
|
||||
)?],
|
||||
);
|
||||
}
|
||||
let mut selected = Vec::new();
|
||||
selected.try_reserve_exact(1).map_err(|_| Error::HostAllocation)?;
|
||||
selected.push(commands.swap_remove(stage as usize));
|
||||
self.submit(capture, selected)
|
||||
)
|
||||
}
|
||||
/// The fused chain-kernel form of the alpha/beta stage.
|
||||
fn stage_ab_launch(&self, op: &StageOperands) -> Result<kernels::Launch> {
|
||||
let (g, c, w) = (self.physical.layout.geometry, self.physical.context, &self.weights[op.layer]);
|
||||
let n = op.end - op.begin;
|
||||
let x = self.physical.span("mixed", op.begin * g.n * 4, n * g.n * 4)?;
|
||||
kernels::Launch::new(
|
||||
&chain::CHAIN,
|
||||
chain::E_GDN_AB,
|
||||
[96, 1, 1],
|
||||
[32, 1, 1],
|
||||
0,
|
||||
vec![
|
||||
kernels::A::P(x),
|
||||
kernels::A::P(admit(c, w.alpha, 48 * 2560 * 2)?),
|
||||
kernels::A::P(admit(c, w.beta, 48 * 2560 * 2)?),
|
||||
kernels::A::P(admit(c, w.dt, 48 * 4)?),
|
||||
kernels::A::P(admit(c, w.a, 48 * 4)?),
|
||||
kernels::A::P(op.gate + (op.begin * 48 * 4) as u64),
|
||||
kernels::A::P(op.beta + (op.begin * 48 * 4) as u64),
|
||||
kernels::A::I32(2560),
|
||||
kernels::A::I32(48),
|
||||
kernels::A::I32(n as i32),
|
||||
],
|
||||
)
|
||||
}
|
||||
/// First node of the literal commit graph: accepted count/row/positions.
|
||||
pub fn capture_commit_begin(&self, capture: &mut OriginalCapture<'_, 'ctx>) -> Result<()> {
|
||||
@@ -142,41 +161,43 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
|
||||
let h = self.physical.span("h_L", i * g.max_t * 10240 * 4, g.max_t * 10240 * 4)?;
|
||||
let gate = self.physical.span("gate_L", i * g.max_t * 48 * 4, g.max_t * 48 * 4)?;
|
||||
let beta = self.physical.span("beta_L", i * g.max_t * 48 * 4, g.max_t * 48 * 4)?;
|
||||
self.submit(
|
||||
capture,
|
||||
let op = StageOperands { layer: i, begin: 0, end: g.max_t, qkv, h, gate, beta };
|
||||
self.submit(capture, vec![self.commit_conv_command(&op, commit)?, self.commit_step_command(&op, commit)?])
|
||||
}
|
||||
fn commit_conv_command(&self, op: &StageOperands, commit: u64) -> Result<Command> {
|
||||
command(
|
||||
"verify_gdn_conv_commit_kernel",
|
||||
[40, 1, 1],
|
||||
[256, 1, 1],
|
||||
vec![
|
||||
command(
|
||||
"verify_gdn_conv_commit_kernel",
|
||||
[40, 1, 1],
|
||||
[256, 1, 1],
|
||||
vec![
|
||||
Arg::Address(self.canonical.span(i, true)?),
|
||||
Arg::Address(qkv),
|
||||
Arg::I32(10240),
|
||||
Arg::Address(commit),
|
||||
],
|
||||
)?,
|
||||
command(
|
||||
"verify_gdn_step_norm_multi_kernel",
|
||||
[48, 1, 1],
|
||||
[128, 4, 1],
|
||||
vec![
|
||||
Arg::Address(self.canonical.span(i, false)?),
|
||||
Arg::Address(h),
|
||||
Arg::I32(10240),
|
||||
Arg::Address(gate),
|
||||
Arg::Address(beta),
|
||||
Arg::Address(self.physical.span("z", 0, g.max_t * 6144 * 4)?),
|
||||
Arg::Address(admit(self.physical.context, self.weights[i].norm, 128 * 4)?),
|
||||
Arg::F32(EPS),
|
||||
Arg::Address(self.physical.span("y_dummy", 0, g.max_t * 6144 * 4)?),
|
||||
Arg::I32(16),
|
||||
Arg::I32(48),
|
||||
Arg::I32(g.max_t as i32),
|
||||
Arg::Address(commit),
|
||||
Arg::I32(0),
|
||||
],
|
||||
)?,
|
||||
Arg::Address(self.canonical.span(op.layer, true)?),
|
||||
Arg::Address(op.qkv),
|
||||
Arg::I32(10240),
|
||||
Arg::Address(commit),
|
||||
],
|
||||
)
|
||||
}
|
||||
fn commit_step_command(&self, op: &StageOperands, commit: u64) -> Result<Command> {
|
||||
let g = self.physical.layout.geometry;
|
||||
command(
|
||||
"verify_gdn_step_norm_multi_kernel",
|
||||
[48, 1, 1],
|
||||
[128, 4, 1],
|
||||
vec![
|
||||
Arg::Address(self.canonical.span(op.layer, false)?),
|
||||
Arg::Address(op.h),
|
||||
Arg::I32(10240),
|
||||
Arg::Address(op.gate),
|
||||
Arg::Address(op.beta),
|
||||
Arg::Address(self.physical.span("z", 0, g.max_t * 6144 * 4)?),
|
||||
Arg::Address(admit(self.physical.context, self.weights[op.layer].norm, 128 * 4)?),
|
||||
Arg::F32(EPS),
|
||||
Arg::Address(self.physical.span("y_dummy", 0, g.max_t * 6144 * 4)?),
|
||||
Arg::I32(16),
|
||||
Arg::I32(48),
|
||||
Arg::I32(g.max_t as i32),
|
||||
Arg::Address(commit),
|
||||
Arg::I32(0),
|
||||
],
|
||||
)
|
||||
}
|
||||
@@ -188,8 +209,11 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
|
||||
/// (`draft_commit_gdn_layers`: grid (48 heads + 20 conv blocks, 36 layers)). The per-layer operands are affine in the layer (checked against the per-layer spans below).
|
||||
pub(crate) fn capture_commit_gdn_fused(&self, capture: &mut OriginalCapture<'_, 'ctx>) -> Result<()> {
|
||||
self.validate_context(self.physical.context)?;
|
||||
let g = self.physical.layout.geometry;
|
||||
let t = g.max_t;
|
||||
let spans = self.fused_spans(self.physical.layout.geometry.max_t)?;
|
||||
self.check_fused_affine(&spans)?;
|
||||
self.submit_launches(capture, vec![spans.launch()?])
|
||||
}
|
||||
fn fused_spans(&self, t: usize) -> Result<FusedSpans> {
|
||||
let commit = self.physical.span("commit", 0, (t + 2) * 4)?;
|
||||
let state0 = self.canonical.span(0, false)?;
|
||||
let hist0 = self.canonical.span(0, true)?;
|
||||
@@ -199,41 +223,91 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
|
||||
let h = self.physical.span("h_L", 0, rows)?;
|
||||
let gate = self.physical.span("gate_L", 0, small)?;
|
||||
let beta = self.physical.span("beta_L", 0, small)?;
|
||||
// affine layout: layer i of every operand is base + i * stride (the per-layer spans `capture_commit_layer` binds)
|
||||
Ok(FusedSpans { t, commit, state0, hist0, qkv, h, gate, beta, rows, small })
|
||||
}
|
||||
/// Layer i of every operand is base + i * stride (the per-layer spans `capture_commit_layer` binds).
|
||||
fn check_fused_affine(&self, spans: &FusedSpans) -> Result<()> {
|
||||
for i in [1usize, 17, 35] {
|
||||
if self.canonical.span(i, false)? != state0 + (i * LAYER_BYTES) as u64
|
||||
|| self.canonical.span(i, true)? != hist0 + (i * LAYER_BYTES) as u64
|
||||
|| self.physical.span("qkv_L", i * rows, rows)? != qkv + (i * rows) as u64
|
||||
|| self.physical.span("h_L", i * rows, rows)? != h + (i * rows) as u64
|
||||
|| self.physical.span("gate_L", i * small, small)? != gate + (i * small) as u64
|
||||
|| self.physical.span("beta_L", i * small, small)? != beta + (i * small) as u64
|
||||
{
|
||||
if !self.layer_is_affine(i, spans)? {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
}
|
||||
if hist0 < state0 || (hist0 - state0) as usize != STATE_WORDS * 4 {
|
||||
if spans.hist0 < spans.state0 || (spans.hist0 - spans.state0) as usize != STATE_WORDS * 4 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
self.submit_launches(
|
||||
capture,
|
||||
vec![kernels::Launch::new(
|
||||
&draft::DRAFT_COMMIT,
|
||||
draft::E_GDN,
|
||||
[48 + 20, 36, 1],
|
||||
[128, 4, 1],
|
||||
0,
|
||||
vec![kernels::A::Words(vec![
|
||||
state0,
|
||||
LAYER_BYTES as u64,
|
||||
(STATE_WORDS * 4) as u64,
|
||||
qkv,
|
||||
h,
|
||||
gate,
|
||||
beta,
|
||||
commit,
|
||||
t as u64,
|
||||
])],
|
||||
)?],
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl FusedSpans {
|
||||
fn launch(&self) -> Result<kernels::Launch> {
|
||||
kernels::Launch::new(
|
||||
&draft::DRAFT_COMMIT,
|
||||
draft::E_GDN,
|
||||
[48 + 20, 36, 1],
|
||||
[128, 4, 1],
|
||||
0,
|
||||
vec![kernels::A::Words(vec![
|
||||
self.state0,
|
||||
LAYER_BYTES as u64,
|
||||
(STATE_WORDS * 4) as u64,
|
||||
self.qkv,
|
||||
self.h,
|
||||
self.gate,
|
||||
self.beta,
|
||||
self.commit,
|
||||
self.t as u64,
|
||||
])],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The arena spans and range of one GDN layer stage.
|
||||
struct StageOperands {
|
||||
layer: usize,
|
||||
begin: usize,
|
||||
end: usize,
|
||||
qkv: u64,
|
||||
h: u64,
|
||||
gate: u64,
|
||||
beta: u64,
|
||||
}
|
||||
|
||||
/// The base spans of the fused commit: layer `i` of every operand is `base + i * stride`.
|
||||
struct FusedSpans {
|
||||
t: usize,
|
||||
commit: u64,
|
||||
state0: u64,
|
||||
hist0: u64,
|
||||
qkv: u64,
|
||||
h: u64,
|
||||
gate: u64,
|
||||
beta: u64,
|
||||
rows: usize,
|
||||
small: usize,
|
||||
}
|
||||
|
||||
impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
|
||||
/// Whether layer `i`'s per-layer spans are affine in the layer, as the fused commit assumes.
|
||||
fn layer_is_affine(&self, i: usize, sp: &FusedSpans) -> Result<bool> {
|
||||
Ok(self.canonical_affine(i, sp)? && self.window_affine(i, sp)?)
|
||||
}
|
||||
fn canonical_affine(&self, i: usize, sp: &FusedSpans) -> Result<bool> {
|
||||
let stride = (i * LAYER_BYTES) as u64;
|
||||
Ok(self.canonical.span(i, false)? == sp.state0 + stride && self.canonical.span(i, true)? == sp.hist0 + stride)
|
||||
}
|
||||
fn window_affine(&self, i: usize, sp: &FusedSpans) -> Result<bool> {
|
||||
Ok(self.physical.span("qkv_L", i * sp.rows, sp.rows)? == sp.qkv + (i * sp.rows) as u64
|
||||
&& self.physical.span("h_L", i * sp.rows, sp.rows)? == sp.h + (i * sp.rows) as u64
|
||||
&& self.physical.span("gate_L", i * sp.small, sp.small)? == sp.gate + (i * sp.small) as u64
|
||||
&& self.physical.span("beta_L", i * sp.small, sp.small)? == sp.beta + (i * sp.small) as u64)
|
||||
}
|
||||
}
|
||||
|
||||
/// One command in a fresh vector (allocation failure is an error, not an abort).
|
||||
fn single_command(command: Command) -> Result<Vec<Command>> {
|
||||
let mut selected = Vec::new();
|
||||
selected.try_reserve_exact(1).map_err(|_| Error::HostAllocation)?;
|
||||
selected.push(command);
|
||||
Ok(selected)
|
||||
}
|
||||
|
||||
+19
-3
@@ -72,6 +72,16 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
|
||||
let _span_validate = crate::host_profile::span("head.validate_logits");
|
||||
self.validate_context(self.physical.context)?;
|
||||
stream.validate_context(self.physical.context)?;
|
||||
let (commands, status) = self.logits_scan_commands(logits, rows)?;
|
||||
self.run_logits_scan(stream, commands)?;
|
||||
self.check_scan_status(status)
|
||||
}
|
||||
/// The clear and scan commands over the whole head output, and the four byte status they write.
|
||||
fn logits_scan_commands(
|
||||
&self,
|
||||
logits: &DeviceBuffer<'ctx>,
|
||||
rows: usize,
|
||||
) -> Result<(Vec<Command>, crate::ffi::BufferHandle)> {
|
||||
let g = self.physical.layout.geometry;
|
||||
if !(1..=g.max_t).contains(&rows) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
@@ -83,7 +93,7 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
|
||||
return Err(Error::OutputAliasesInput);
|
||||
}
|
||||
let status = self.span("hit_count", 0, 4)?;
|
||||
let mut commands = vec![
|
||||
let commands = vec![
|
||||
command("verify_clear_status", [1, 1, 1], [32, 1, 1], vec![Arg::Address(status.qwen_address())])?,
|
||||
command(
|
||||
"verify_scan_logits",
|
||||
@@ -92,6 +102,10 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
|
||||
vec![Arg::Address(src), Arg::U64(words as u64), Arg::Address(status.qwen_address())],
|
||||
)?,
|
||||
];
|
||||
Ok((commands, status))
|
||||
}
|
||||
/// Admits and launches the scan on `stream` and drains it; a failed drain poisons the context and retains the commands.
|
||||
fn run_logits_scan(&self, stream: &mut crate::OriginalGpuStream<'ctx>, mut commands: Vec<Command>) -> Result<()> {
|
||||
let module = self.physical.module.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
for c in &commands {
|
||||
module.admit(c)?;
|
||||
@@ -109,9 +123,11 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
|
||||
self.physical.failed.set(true);
|
||||
poison(self.physical.context);
|
||||
std::mem::forget(commands);
|
||||
return combine(launched, sync);
|
||||
}
|
||||
combine(launched, sync)?;
|
||||
combine(launched, sync)
|
||||
}
|
||||
/// Reads the status word back; any nonzero value is a non-finite logit.
|
||||
fn check_scan_status(&self, status: crate::ffi::BufferHandle) -> Result<()> {
|
||||
let span_vc = crate::host_profile::span("head.validate_ctx_copy");
|
||||
let mut bytes = zero(4)?;
|
||||
let guard = self.physical.context.enter()?;
|
||||
|
||||
+51
-92
@@ -9,54 +9,8 @@ impl<'ctx> OriginalVerifyBank<'ctx> {
|
||||
let asset = sealed_asset(ASSET, ASSET_SHA)?;
|
||||
let qsa_asset = sealed_asset(QSA_ASSET, QSA_ASSET_SHA)?;
|
||||
admission(context, layout.bytes)?;
|
||||
let mut owner = Physical {
|
||||
context,
|
||||
layout,
|
||||
arena: None,
|
||||
prof: None,
|
||||
mapped: std::array::from_fn(|_| RefCell::new(None)),
|
||||
module: None,
|
||||
qsa_module: None,
|
||||
window: RefCell::new(Vec::new()),
|
||||
generation: Cell::new(0),
|
||||
failed: Cell::new(false),
|
||||
};
|
||||
let operation = (|| {
|
||||
let guard = context.enter()?;
|
||||
let loaded = (|| {
|
||||
owner.module = Some(Module::load(asset, ENTRIES)?);
|
||||
owner.qsa_module = Some(Module::load(qsa_asset, QSA_ENTRIES)?);
|
||||
// Original mapped staging is retained and memset before the arena carve.
|
||||
for (i, n) in owner.layout.mapped_bytes.into_iter().enumerate() {
|
||||
*owner.mapped[i].get_mut() = Some(MappedAllocation::new(n)?);
|
||||
owner.mapped[i].get_mut().as_mut().ok_or(Error::ContextPoisoned)?.initialize_zero()?;
|
||||
}
|
||||
admission(context, owner.layout.bytes)?;
|
||||
owner.arena = Some(context.allocate(owner.layout.bytes)?);
|
||||
let arena = owner.arena.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
context.driver.api.zero(handle(arena)?.qwen_address(), arena.len())?;
|
||||
// STRATA_VERIFY_PROFILE: the device stamp words (Verifier::init `prof_`); a failed allocation just turns the profile off.
|
||||
if std::env::var_os("STRATA_VERIFY_PROFILE").is_some() {
|
||||
let bytes = profile::profile_stamp_words(48) * 8;
|
||||
if let Ok(b) = context.allocate(bytes) {
|
||||
let zeroed = handle(&b).and_then(|h| context.driver.api.zero(h.qwen_address(), bytes));
|
||||
if zeroed.is_ok() {
|
||||
owner.prof = Some(b)
|
||||
} else {
|
||||
let _ = b.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
let sync = context.driver.api.synchronize();
|
||||
let pop = guard.finish();
|
||||
if loaded.as_ref().err().is_some_and(transport) || sync.is_err() || pop.is_err() {
|
||||
poison(context)
|
||||
}
|
||||
combine(combine(loaded, sync), pop)
|
||||
})();
|
||||
if let Err(primary) = operation {
|
||||
let mut owner = Physical::empty(context, layout);
|
||||
if let Err(primary) = owner.initialize(asset, qsa_asset) {
|
||||
return combine(Err(primary), owner.close());
|
||||
}
|
||||
Ok(Self {
|
||||
@@ -116,6 +70,25 @@ impl<'ctx> OriginalVerifyBank<'ctx> {
|
||||
/// mutable borrow is held by the actor, not copied into an unrelated certificate.
|
||||
pub(crate) fn stage(&mut self, tokens: &[i32], position: usize) -> Result<u64> {
|
||||
self.validate_context(self.physical.context)?;
|
||||
self.check_stage(tokens, position)?;
|
||||
let generation = self.generation.checked_add(1).ok_or(Error::InvalidSize)?;
|
||||
// Invalidate every escaped completed row/window BEFORE the first mapped write.
|
||||
// A failed partial staging cannot retain old generation authority.
|
||||
self.generation = generation;
|
||||
self.physical.generation.set(generation);
|
||||
self.last_t = 0;
|
||||
self.last_keep = 0;
|
||||
self.write_staged_rows(tokens, position)?;
|
||||
std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst);
|
||||
self.last_t = tokens.len();
|
||||
self.last_position = position;
|
||||
self.last_tokens[..tokens.len()].copy_from_slice(tokens);
|
||||
self.generation = generation;
|
||||
self.physical.generation.set(generation);
|
||||
self.last_keep = 0;
|
||||
Ok(generation)
|
||||
}
|
||||
fn check_stage(&self, tokens: &[i32], position: usize) -> Result<()> {
|
||||
let g = self.geometry();
|
||||
let t = tokens.len();
|
||||
if self.released
|
||||
@@ -125,59 +98,45 @@ impl<'ctx> OriginalVerifyBank<'ctx> {
|
||||
{
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let generation = self.generation.checked_add(1).ok_or(Error::InvalidSize)?;
|
||||
// Invalidate every escaped completed row/window BEFORE the first mapped write.
|
||||
// A failed partial staging cannot retain old generation authority.
|
||||
self.generation = generation;
|
||||
self.physical.generation.set(generation);
|
||||
self.last_t = 0;
|
||||
self.last_keep = 0;
|
||||
let mapped = &self.physical.mapped;
|
||||
Ok(())
|
||||
}
|
||||
/// The token, step and position words of every row, then the cleared doorbell flags.
|
||||
fn write_staged_rows(&self, tokens: &[i32], position: usize) -> Result<()> {
|
||||
for (i, &token) in tokens.iter().enumerate() {
|
||||
let p = position + i;
|
||||
mapped[0]
|
||||
.try_borrow_mut()
|
||||
.map_err(|_| Error::InvalidQwenShape)?
|
||||
.as_mut()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.write(i * 4, &token.to_le_bytes())?;
|
||||
for (j, v) in [p, p + 1, (p + 1) / 4, (p + 1).min(g.selection)].into_iter().enumerate() {
|
||||
mapped[1]
|
||||
.try_borrow_mut()
|
||||
.map_err(|_| Error::InvalidQwenShape)?
|
||||
.as_mut()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.write((i * 4 + j) * 4, &(v as i32).to_le_bytes())?
|
||||
}
|
||||
for (offset, heads) in
|
||||
[(0, g.heads), (g.max_t * g.heads, g.kv_heads), (g.max_t * (g.heads + g.kv_heads), g.index_heads)]
|
||||
{
|
||||
for h in 0..heads {
|
||||
mapped[2]
|
||||
.try_borrow_mut()
|
||||
.map_err(|_| Error::InvalidQwenShape)?
|
||||
.as_mut()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.write((offset + i * heads + h) * 4, &(p as i32).to_le_bytes())?
|
||||
}
|
||||
}
|
||||
self.write_row(i, token, position + i)?;
|
||||
}
|
||||
for flag in 9..=12 {
|
||||
mapped[flag]
|
||||
self.physical.mapped[flag]
|
||||
.try_borrow_mut()
|
||||
.map_err(|_| Error::InvalidQwenShape)?
|
||||
.as_mut()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.publish_u32(0, 0)?
|
||||
}
|
||||
std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst);
|
||||
self.last_t = t;
|
||||
self.last_position = position;
|
||||
self.last_tokens[..t].copy_from_slice(tokens);
|
||||
self.generation = generation;
|
||||
self.physical.generation.set(generation);
|
||||
self.last_keep = 0;
|
||||
Ok(generation)
|
||||
Ok(())
|
||||
}
|
||||
fn write_row(&self, i: usize, token: i32, p: usize) -> Result<()> {
|
||||
let g = self.geometry();
|
||||
self.mapped_write(0, i * 4, &token.to_le_bytes())?;
|
||||
for (j, v) in [p, p + 1, (p + 1) / 4, (p + 1).min(g.selection)].into_iter().enumerate() {
|
||||
self.mapped_write(1, (i * 4 + j) * 4, &(v as i32).to_le_bytes())?
|
||||
}
|
||||
for (offset, heads) in
|
||||
[(0, g.heads), (g.max_t * g.heads, g.kv_heads), (g.max_t * (g.heads + g.kv_heads), g.index_heads)]
|
||||
{
|
||||
for h in 0..heads {
|
||||
self.mapped_write(2, (offset + i * heads + h) * 4, &(p as i32).to_le_bytes())?
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn mapped_write(&self, slot: usize, offset: usize, bytes: &[u8]) -> Result<()> {
|
||||
self.physical.mapped[slot]
|
||||
.try_borrow_mut()
|
||||
.map_err(|_| Error::InvalidQwenShape)?
|
||||
.as_mut()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.write(offset, bytes)
|
||||
}
|
||||
pub(crate) fn stage_ple(&mut self, values: &[f32]) -> Result<()> {
|
||||
self.validate_context(self.physical.context)?;
|
||||
|
||||
+34
-15
@@ -90,7 +90,26 @@ impl<'ctx> OriginalVerifyBank<'ctx> {
|
||||
if handle(owned)?.overlaps(owned.len(), handle(arena)?, arena.len()) {
|
||||
return Err(Error::OutputAliasesInput);
|
||||
}
|
||||
for w in &weights {
|
||||
self.check_journal_weights(&weights, owned, arena)?;
|
||||
if let Some(history) = ple {
|
||||
self.check_journal_ple(history, owned, arena)?;
|
||||
}
|
||||
Ok(OriginalVerifyGdnJournal {
|
||||
physical: self.physical.clone(),
|
||||
canonical: canonical.inner.clone(),
|
||||
weights,
|
||||
ple,
|
||||
commands: RefCell::new(Vec::new()),
|
||||
})
|
||||
}
|
||||
/// Every layer operand fits its size and overlaps neither the canonical buffer nor the arena.
|
||||
fn check_journal_weights(
|
||||
&self,
|
||||
weights: &[OriginalVerifyGdnWeights<'_, 'ctx>; 36],
|
||||
owned: &DeviceBuffer<'ctx>,
|
||||
arena: &DeviceBuffer<'ctx>,
|
||||
) -> Result<()> {
|
||||
for w in weights {
|
||||
for (b, n) in [
|
||||
(w.conv, 10240 * 4 * 4),
|
||||
(w.alpha, 48 * 2560 * 2),
|
||||
@@ -107,21 +126,21 @@ impl<'ctx> OriginalVerifyBank<'ctx> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(history) = ple {
|
||||
admit(self.physical.context, history, 9 * 10240 * 4)?;
|
||||
if handle(history)?.overlaps(history.len(), handle(arena)?, arena.len())
|
||||
|| handle(history)?.overlaps(history.len(), handle(owned)?, owned.len())
|
||||
{
|
||||
return Err(Error::OutputAliasesInput);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn check_journal_ple(
|
||||
&self,
|
||||
history: &DeviceBuffer<'ctx>,
|
||||
owned: &DeviceBuffer<'ctx>,
|
||||
arena: &DeviceBuffer<'ctx>,
|
||||
) -> Result<()> {
|
||||
admit(self.physical.context, history, 9 * 10240 * 4)?;
|
||||
if handle(history)?.overlaps(history.len(), handle(arena)?, arena.len())
|
||||
|| handle(history)?.overlaps(history.len(), handle(owned)?, owned.len())
|
||||
{
|
||||
return Err(Error::OutputAliasesInput);
|
||||
}
|
||||
Ok(OriginalVerifyGdnJournal {
|
||||
physical: self.physical.clone(),
|
||||
canonical: canonical.inner.clone(),
|
||||
weights,
|
||||
ple,
|
||||
commands: RefCell::new(Vec::new()),
|
||||
})
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl<'ctx> OriginalVerifyRow<'ctx> {
|
||||
|
||||
@@ -28,86 +28,44 @@ impl Physical<'_> {
|
||||
pub(in super::super) fn ensure_window_assets(&self, specs: &[&'static kernels::AssetSpec]) -> Result<()> {
|
||||
self.validate(self.context)?;
|
||||
let started = std::time::Instant::now();
|
||||
let mut groups: Vec<(&'static str, &'static kernels::AssetSpec, Vec<&'static str>)> = Vec::new();
|
||||
for s in specs {
|
||||
match groups.iter_mut().find(|g| g.0 == s.key()) {
|
||||
Some(g) => {
|
||||
for e in s.entries {
|
||||
if !g.2.contains(e) {
|
||||
g.2.push(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
None => groups.push((s.key(), s, s.entries.to_vec())),
|
||||
}
|
||||
}
|
||||
let mut ready = Vec::new();
|
||||
let mut unsealed: Result<()> = Ok(());
|
||||
{
|
||||
let mut loaded = self.window.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let cache = self.context.window_modules.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
for (key, spec, entries) in groups {
|
||||
if let Some((_, _, have)) = loaded.iter().find(|(n, _, _)| *n == key) {
|
||||
if entries.iter().all(|e| have.contains(e)) {
|
||||
continue;
|
||||
}
|
||||
return Err(Error::InvalidDriverValue(
|
||||
"Original verifier window module is already loaded without an entry a later graph needs",
|
||||
));
|
||||
}
|
||||
// A module an earlier bank of this context loaded (sealed and admitted then) is shared, not loaded again:
|
||||
// the same sealed image, the same entries, unloaded with the context.
|
||||
if let Some((_, m, have)) = cache.iter().find(|(n, _, have)| {
|
||||
share_window_modules() && *n == key && entries.iter().all(|e| have.contains(e))
|
||||
}) {
|
||||
loaded.try_reserve(1).map_err(|_| Error::HostAllocation)?;
|
||||
loaded.push((key, Rc::clone(m), have.clone()));
|
||||
continue;
|
||||
}
|
||||
match spec.sealed() {
|
||||
Ok(ptx) => ready.push((key, ptx, entries)),
|
||||
Err(error) => {
|
||||
if unsealed.is_ok() {
|
||||
unsealed = Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let (ready, unsealed) = self.select_ready(group_specs(specs))?;
|
||||
if ready.is_empty() {
|
||||
crate::original_gpu_schedule::capture_timing::add(2, started.elapsed().as_secs_f64() * 1e3);
|
||||
return unsealed;
|
||||
}
|
||||
let loaded = self.load_ready(ready)?;
|
||||
crate::original_gpu_schedule::capture_timing::add(2, started.elapsed().as_secs_f64() * 1e3);
|
||||
combine(loaded, unsealed)
|
||||
}
|
||||
/// The groups still to load; the first unsealed module fails closed (after the others), by name.
|
||||
fn select_ready(&self, groups: Vec<WindowGroup>) -> Result<(Vec<ReadyModule>, Result<()>)> {
|
||||
let mut ready = Vec::new();
|
||||
let mut unsealed: Result<()> = Ok(());
|
||||
let mut loaded = self.window.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let cache = self.context.window_modules.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
for (key, spec, entries) in groups {
|
||||
if reuse_loaded(&mut loaded, &cache, key, &entries)? {
|
||||
continue;
|
||||
}
|
||||
match spec.sealed() {
|
||||
Ok(ptx) => ready.push((key, ptx, entries)),
|
||||
Err(error) => {
|
||||
if unsealed.is_ok() {
|
||||
unsealed = Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((ready, unsealed))
|
||||
}
|
||||
/// Loads the modules inside an entered context; the outer error is a failed enter.
|
||||
fn load_ready(&self, ready: Vec<ReadyModule>) -> Result<Result<()>> {
|
||||
let guard = self.context.enter()?;
|
||||
let mut result = Ok(());
|
||||
for (key, ptx, entries) in ready {
|
||||
match Module::load(ptx, &entries) {
|
||||
Ok(m) => {
|
||||
let m = Rc::new(m);
|
||||
match self.context.window_modules.try_borrow_mut() {
|
||||
Ok(mut c) => {
|
||||
c.retain(|(n, _, _)| *n != key);
|
||||
if c.try_reserve(1).is_ok() {
|
||||
c.push((key, Rc::clone(&m), entries.clone()))
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
result = combine(result, Err(Error::InvalidQwenShape));
|
||||
break;
|
||||
}
|
||||
}
|
||||
match self.window.try_borrow_mut() {
|
||||
Ok(mut w) => w.push((key, m, entries)),
|
||||
Err(_) => {
|
||||
result = combine(result, Err(Error::InvalidQwenShape));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
result = combine(result, Err(error));
|
||||
break;
|
||||
}
|
||||
if let Err(error) = self.load_module(key, ptx, entries) {
|
||||
result = combine(result, Err(error));
|
||||
break;
|
||||
}
|
||||
}
|
||||
let pop = guard.finish();
|
||||
@@ -115,8 +73,20 @@ impl Physical<'_> {
|
||||
self.failed.set(true);
|
||||
poison(self.context)
|
||||
}
|
||||
crate::original_gpu_schedule::capture_timing::add(2, started.elapsed().as_secs_f64() * 1e3);
|
||||
combine(combine(result, pop), unsealed)
|
||||
Ok(combine(result, pop))
|
||||
}
|
||||
/// Loads one module and records it in the context cache (shared with later banks) and in this bank.
|
||||
fn load_module(&self, key: &'static str, ptx: &'static [u8], entries: Vec<&'static str>) -> Result<()> {
|
||||
let m = Rc::new(Module::load(ptx, &entries)?);
|
||||
{
|
||||
let mut c = self.context.window_modules.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
|
||||
c.retain(|(n, _, _)| *n != key);
|
||||
if c.try_reserve(1).is_ok() {
|
||||
c.push((key, Rc::clone(&m), entries.clone()))
|
||||
}
|
||||
}
|
||||
self.window.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?.push((key, m, entries));
|
||||
Ok(())
|
||||
}
|
||||
/// `cuFuncSetAttribute(MAX_DYNAMIC_SHARED_SIZE)` of loaded window entries, once, before any capture
|
||||
/// (what Original does for the fused GR down kernels).
|
||||
@@ -174,34 +144,12 @@ impl Physical<'_> {
|
||||
.address(offset, bytes)
|
||||
}
|
||||
pub(in super::super) fn close(&mut self) -> Result<()> {
|
||||
if self.arena.is_none()
|
||||
&& self.prof.is_none()
|
||||
&& self.module.is_none()
|
||||
&& self.qsa_module.is_none()
|
||||
&& self.window.get_mut().is_empty()
|
||||
{
|
||||
if self.is_released() {
|
||||
return Ok(());
|
||||
}
|
||||
self.failed.set(true);
|
||||
if self.context.is_poisoned() {
|
||||
if let Some(b) = self.arena.take() {
|
||||
std::mem::forget(b)
|
||||
}
|
||||
if let Some(b) = self.prof.take() {
|
||||
std::mem::forget(b)
|
||||
}
|
||||
if let Some(m) = self.module.take() {
|
||||
std::mem::forget(m)
|
||||
}
|
||||
if let Some(m) = self.qsa_module.take() {
|
||||
std::mem::forget(m)
|
||||
}
|
||||
for (_, m, _) in self.window.get_mut().drain(..) {
|
||||
std::mem::forget(m)
|
||||
}
|
||||
for m in self.mapped.iter_mut().filter_map(|m| m.get_mut().take()) {
|
||||
std::mem::forget(m)
|
||||
}
|
||||
self.retain_poisoned();
|
||||
return Err(Error::ContextPoisoned);
|
||||
}
|
||||
let sync = self.context.synchronize();
|
||||
@@ -209,13 +157,45 @@ impl Physical<'_> {
|
||||
poison(self.context);
|
||||
return combine(sync, self.close());
|
||||
}
|
||||
let mut result = combine(
|
||||
let result = combine(
|
||||
self.arena.take().map_or(Ok(()), DeviceBuffer::release),
|
||||
self.prof.take().map_or(Ok(()), DeviceBuffer::release),
|
||||
);
|
||||
if self.context.is_poisoned() {
|
||||
return combine(result, self.close());
|
||||
}
|
||||
self.close_in_context(result)
|
||||
}
|
||||
fn is_released(&mut self) -> bool {
|
||||
self.arena.is_none()
|
||||
&& self.prof.is_none()
|
||||
&& self.module.is_none()
|
||||
&& self.qsa_module.is_none()
|
||||
&& self.window.get_mut().is_empty()
|
||||
}
|
||||
/// A poisoned context: nothing may be released, every owner is retained.
|
||||
fn retain_poisoned(&mut self) {
|
||||
if let Some(b) = self.arena.take() {
|
||||
std::mem::forget(b)
|
||||
}
|
||||
if let Some(b) = self.prof.take() {
|
||||
std::mem::forget(b)
|
||||
}
|
||||
if let Some(m) = self.module.take() {
|
||||
std::mem::forget(m)
|
||||
}
|
||||
if let Some(m) = self.qsa_module.take() {
|
||||
std::mem::forget(m)
|
||||
}
|
||||
for (_, m, _) in self.window.get_mut().drain(..) {
|
||||
std::mem::forget(m)
|
||||
}
|
||||
for m in self.mapped.iter_mut().filter_map(|m| m.get_mut().take()) {
|
||||
std::mem::forget(m)
|
||||
}
|
||||
}
|
||||
/// The mapped staging and the modules go back inside an entered context.
|
||||
fn close_in_context(&mut self, mut result: Result<()>) -> Result<()> {
|
||||
let guard = match self.context.enter() {
|
||||
Ok(g) => g,
|
||||
Err(e) => return combine(combine(result, Err(e)), self.close()),
|
||||
@@ -242,6 +222,118 @@ impl Physical<'_> {
|
||||
combine(combine(result, unload), pop)
|
||||
}
|
||||
}
|
||||
impl<'ctx> Physical<'ctx> {
|
||||
/// A bank that owns nothing yet.
|
||||
pub(in super::super) fn empty(context: &'ctx Context<'ctx>, layout: OriginalVerifyLayout) -> Self {
|
||||
Self {
|
||||
context,
|
||||
layout,
|
||||
arena: None,
|
||||
prof: None,
|
||||
mapped: std::array::from_fn(|_| RefCell::new(None)),
|
||||
module: None,
|
||||
qsa_module: None,
|
||||
window: RefCell::new(Vec::new()),
|
||||
generation: Cell::new(0),
|
||||
failed: Cell::new(false),
|
||||
}
|
||||
}
|
||||
/// Loads the two modules, the mapped staging and the arena inside an entered context.
|
||||
pub(in super::super) fn initialize(&mut self, asset: &'static [u8], qsa_asset: &'static [u8]) -> Result<()> {
|
||||
let context = self.context;
|
||||
let guard = context.enter()?;
|
||||
let loaded = self.load_banks(asset, qsa_asset);
|
||||
let sync = context.driver.api.synchronize();
|
||||
let pop = guard.finish();
|
||||
if loaded.as_ref().err().is_some_and(transport) || sync.is_err() || pop.is_err() {
|
||||
poison(context)
|
||||
}
|
||||
combine(combine(loaded, sync), pop)
|
||||
}
|
||||
fn load_banks(&mut self, asset: &'static [u8], qsa_asset: &'static [u8]) -> Result<()> {
|
||||
self.module = Some(Module::load(asset, ENTRIES)?);
|
||||
self.qsa_module = Some(Module::load(qsa_asset, QSA_ENTRIES)?);
|
||||
// Original mapped staging is retained and memset before the arena carve.
|
||||
for (i, n) in self.layout.mapped_bytes.into_iter().enumerate() {
|
||||
*self.mapped[i].get_mut() = Some(MappedAllocation::new(n)?);
|
||||
self.mapped[i].get_mut().as_mut().ok_or(Error::ContextPoisoned)?.initialize_zero()?;
|
||||
}
|
||||
admission(self.context, self.layout.bytes)?;
|
||||
self.arena = Some(self.context.allocate(self.layout.bytes)?);
|
||||
let arena = self.arena.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
self.context.driver.api.zero(handle(arena)?.qwen_address(), arena.len())?;
|
||||
self.allocate_profile();
|
||||
Ok(())
|
||||
}
|
||||
/// STRATA_VERIFY_PROFILE: the device stamp words (Verifier::init `prof_`); a failed allocation just turns the
|
||||
/// profile off.
|
||||
fn allocate_profile(&mut self) {
|
||||
if std::env::var_os("STRATA_VERIFY_PROFILE").is_none() {
|
||||
return;
|
||||
}
|
||||
let context = self.context;
|
||||
let bytes = profile::profile_stamp_words(48) * 8;
|
||||
if let Ok(b) = context.allocate(bytes) {
|
||||
let zeroed = handle(&b).and_then(|h| context.driver.api.zero(h.qwen_address(), bytes));
|
||||
if zeroed.is_ok() {
|
||||
self.prof = Some(b)
|
||||
} else {
|
||||
let _ = b.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The window assets of the requested specs, one group per PTX file with its entries unioned.
|
||||
type WindowGroup = (&'static str, &'static kernels::AssetSpec, Vec<&'static str>);
|
||||
/// A sealed module still to load: key, PTX and entries.
|
||||
type ReadyModule = (&'static str, &'static [u8], Vec<&'static str>);
|
||||
|
||||
fn group_specs(specs: &[&'static kernels::AssetSpec]) -> Vec<WindowGroup> {
|
||||
let mut groups: Vec<WindowGroup> = Vec::new();
|
||||
for s in specs {
|
||||
match groups.iter_mut().find(|g| g.0 == s.key()) {
|
||||
Some(g) => {
|
||||
for e in s.entries {
|
||||
if !g.2.contains(e) {
|
||||
g.2.push(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
None => groups.push((s.key(), s, s.entries.to_vec())),
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
/// Whether the group's module is already available: loaded into this bank (it must then have every entry the group
|
||||
/// needs), or shared from the context cache (sealed and admitted by an earlier bank of this context).
|
||||
fn reuse_loaded(
|
||||
loaded: &mut Vec<(&'static str, Rc<Module>, Vec<&'static str>)>,
|
||||
cache: &[(&'static str, Rc<Module>, Vec<&'static str>)],
|
||||
key: &'static str,
|
||||
entries: &[&'static str],
|
||||
) -> Result<bool> {
|
||||
if let Some((_, _, have)) = loaded.iter().find(|(n, _, _)| *n == key) {
|
||||
if entries.iter().all(|e| have.contains(e)) {
|
||||
return Ok(true);
|
||||
}
|
||||
return Err(Error::InvalidDriverValue(
|
||||
"Original verifier window module is already loaded without an entry a later graph needs",
|
||||
));
|
||||
}
|
||||
// A module an earlier bank of this context loaded (sealed and admitted then) is shared, not loaded again:
|
||||
// the same sealed image, the same entries, unloaded with the context.
|
||||
if let Some((_, m, have)) = cache
|
||||
.iter()
|
||||
.find(|(n, _, have)| share_window_modules() && *n == key && entries.iter().all(|e| have.contains(e)))
|
||||
{
|
||||
loaded.try_reserve(1).map_err(|_| Error::HostAllocation)?;
|
||||
loaded.push((key, Rc::clone(m), have.clone()));
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
impl Drop for Physical<'_> {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.close();
|
||||
|
||||
+39
-28
@@ -89,37 +89,11 @@ impl<'ctx> Context<'ctx> {
|
||||
histories: [&[f32]; 36],
|
||||
) -> Result<OriginalVerifyCanonicalGdn<'ctx>> {
|
||||
let _span_canonical = crate::host_profile::span("drv.canonical_gdn");
|
||||
for i in 0..36 {
|
||||
if states[i].len() != STATE_WORDS || histories[i].len() != HISTORY_WORDS {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
}
|
||||
check_canonical_lengths(&states, &histories)?;
|
||||
admission(self, CANONICAL_BYTES)?;
|
||||
let mut owner =
|
||||
Canonical { context: self, buffer: Some(self.allocate(CANONICAL_BYTES)?), failed: Cell::new(false) };
|
||||
// One pass per layer converts to little-endian bytes and checks every word finite (two plain slice loops, not a chained
|
||||
// iterator: they compile to wide copies); a non-finite word refuses the intake before the layer is uploaded.
|
||||
let operation = (|| {
|
||||
let mut bytes = zero(LAYER_BYTES)?;
|
||||
for i in 0..36 {
|
||||
let (head, tail) = bytes.split_at_mut(STATE_WORDS * 4);
|
||||
let mut finite = true;
|
||||
for (x, b) in states[i].iter().zip(head.chunks_exact_mut(4)) {
|
||||
finite &= x.is_finite();
|
||||
b.copy_from_slice(&x.to_le_bytes())
|
||||
}
|
||||
for (x, b) in histories[i].iter().zip(tail.chunks_exact_mut(4)) {
|
||||
finite &= x.is_finite();
|
||||
b.copy_from_slice(&x.to_le_bytes())
|
||||
}
|
||||
if !finite {
|
||||
return Err(Error::NonFiniteMmqOutput("Original canonical GDN intake"));
|
||||
}
|
||||
owner.buffer.as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(i * LAYER_BYTES, &bytes)?;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(primary) = operation {
|
||||
if let Err(primary) = owner.upload_layers(&states, &histories) {
|
||||
return combine(Err(primary), owner.close_inner());
|
||||
}
|
||||
Ok(OriginalVerifyCanonicalGdn { inner: Rc::new(owner) })
|
||||
@@ -128,7 +102,44 @@ impl<'ctx> Context<'ctx> {
|
||||
OriginalVerifyBank::new(self, geometry)
|
||||
}
|
||||
}
|
||||
fn check_canonical_lengths(states: &[&[f32]; 36], histories: &[&[f32]; 36]) -> Result<()> {
|
||||
for i in 0..36 {
|
||||
if states[i].len() != STATE_WORDS || histories[i].len() != HISTORY_WORDS {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Little-endian bytes of one layer's state then history; whether every word is finite. Two plain slice loops, not a
|
||||
/// chained iterator: they compile to wide copies.
|
||||
fn encode_layer(bytes: &mut [u8], state: &[f32], history: &[f32]) -> bool {
|
||||
let (head, tail) = bytes.split_at_mut(STATE_WORDS * 4);
|
||||
let mut finite = true;
|
||||
for (x, b) in state.iter().zip(head.chunks_exact_mut(4)) {
|
||||
finite &= x.is_finite();
|
||||
b.copy_from_slice(&x.to_le_bytes())
|
||||
}
|
||||
for (x, b) in history.iter().zip(tail.chunks_exact_mut(4)) {
|
||||
finite &= x.is_finite();
|
||||
b.copy_from_slice(&x.to_le_bytes())
|
||||
}
|
||||
finite
|
||||
}
|
||||
|
||||
impl Canonical<'_> {
|
||||
/// One pass per layer converts to little-endian bytes and checks every word finite; a non-finite word refuses the
|
||||
/// intake before the layer is uploaded.
|
||||
fn upload_layers(&mut self, states: &[&[f32]; 36], histories: &[&[f32]; 36]) -> Result<()> {
|
||||
let mut bytes = zero(LAYER_BYTES)?;
|
||||
for i in 0..36 {
|
||||
if !encode_layer(&mut bytes, states[i], histories[i]) {
|
||||
return Err(Error::NonFiniteMmqOutput("Original canonical GDN intake"));
|
||||
}
|
||||
self.buffer.as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(i * LAYER_BYTES, &bytes)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn allocated_bytes(&self) -> usize {
|
||||
self.buffer.as_ref().map_or(0, DeviceBuffer::len)
|
||||
}
|
||||
|
||||
@@ -166,19 +166,31 @@ pub fn original_verify_live_count() -> usize {
|
||||
/// true when no window remained in flight. Needs no driver call, so it is safe
|
||||
/// from the serve watchdog thread while the owner thread is blocked in a sync.
|
||||
pub fn original_verify_release_live(timeout: Duration, note: Option<&mut dyn Write>) -> bool {
|
||||
let live: Vec<Arc<Shared>> = {
|
||||
let guard = registry();
|
||||
for s in guard.iter() {
|
||||
s.released.store(true, Ordering::SeqCst);
|
||||
for a in [s.words.served, s.words.plan, s.words.copies] {
|
||||
raise_to_max(a);
|
||||
}
|
||||
}
|
||||
guard.iter().cloned().collect()
|
||||
};
|
||||
let live = raise_all_released();
|
||||
let start = Instant::now();
|
||||
let drained = wait_drained(&live, start, timeout);
|
||||
if let Some(f) = note {
|
||||
note_released(f, drained, start, timeout);
|
||||
}
|
||||
drained
|
||||
}
|
||||
|
||||
/// Marks every live verifier released and raises the flags its spin kernels wait on; returns them.
|
||||
fn raise_all_released() -> Vec<Arc<Shared>> {
|
||||
let guard = registry();
|
||||
for s in guard.iter() {
|
||||
s.released.store(true, Ordering::SeqCst);
|
||||
for a in [s.words.served, s.words.plan, s.words.copies] {
|
||||
raise_to_max(a);
|
||||
}
|
||||
}
|
||||
guard.iter().cloned().collect()
|
||||
}
|
||||
|
||||
/// Waits up to `timeout` for every window to leave the GPU; whether none remained in flight.
|
||||
fn wait_drained(live: &[Arc<Shared>], start: Instant, timeout: Duration) -> bool {
|
||||
let mut drained = true;
|
||||
for s in &live {
|
||||
for s in live {
|
||||
while s.active.load(Ordering::SeqCst) {
|
||||
if start.elapsed() > timeout {
|
||||
drained = false;
|
||||
@@ -187,25 +199,26 @@ pub fn original_verify_release_live(timeout: Duration, note: Option<&mut dyn Wri
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
if let Some(f) = note {
|
||||
let _ = if drained {
|
||||
writeln!(
|
||||
f,
|
||||
"strata: released the verify window's GPU waits (#267): the GPU finished in {} ms",
|
||||
start.elapsed().as_millis()
|
||||
)
|
||||
} else {
|
||||
writeln!(
|
||||
f,
|
||||
"strata: released the verify window's GPU waits (#267): the GPU did not finish within {} s",
|
||||
timeout.as_secs()
|
||||
)
|
||||
};
|
||||
let _ = f.flush();
|
||||
}
|
||||
drained
|
||||
}
|
||||
|
||||
fn note_released(f: &mut dyn Write, drained: bool, start: Instant, timeout: Duration) {
|
||||
let _ = if drained {
|
||||
writeln!(
|
||||
f,
|
||||
"strata: released the verify window's GPU waits (#267): the GPU finished in {} ms",
|
||||
start.elapsed().as_millis()
|
||||
)
|
||||
} else {
|
||||
writeln!(
|
||||
f,
|
||||
"strata: released the verify window's GPU waits (#267): the GPU did not finish within {} s",
|
||||
timeout.as_secs()
|
||||
)
|
||||
};
|
||||
let _ = f.flush();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -101,6 +101,11 @@ impl<'ctx> OriginalExpertTierProbe<'ctx> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn bank_and_copy(&mut self) -> Result<(&mut OriginalVerifyBank<'ctx>, &mut OriginalGpuStream<'ctx>)> {
|
||||
let bank = self.bank.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let copy = self.copy.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
Ok((bank, copy))
|
||||
}
|
||||
fn launch_bank(&mut self, mut commands: Vec<Command>) -> Result<()> {
|
||||
let physical = self.bank()?.physical.clone();
|
||||
let module = physical.module.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
@@ -145,144 +150,143 @@ impl<'ctx> OriginalExpertTierProbe<'ctx> {
|
||||
) -> Result<()>,
|
||||
) -> Result<Vec<f32>> {
|
||||
let g = self.bank()?.geometry();
|
||||
let (n, k) = (g.n, g.k);
|
||||
let rows = ids.len() / k;
|
||||
if rows == 0 || rows > g.max_t || ids.len() != rows * k || activation.len() != rows * n || layer >= 48 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let rows = check_group_request(&g, layer, activation, ids)?;
|
||||
let context = self.bank()?.physical.context;
|
||||
let ring = 1u32;
|
||||
let group = Rows { begin: 0, end: rows, group: 0 };
|
||||
// the doorbell's publication and the device FFN input
|
||||
self.stage_group(context, rows, activation, ids)?;
|
||||
// compute side, in the recorded order of `post`
|
||||
let plans = self.group_plans(&g, layer, Rows { begin: 0, end: rows, group: 0 })?;
|
||||
let physical = self.bank()?.physical.clone();
|
||||
let commands = group_commands(&physical, &g, rows)?;
|
||||
let enqueued = self.enqueue_group(&physical, plans, commands, ring);
|
||||
// host side: the pool callback, then the run loop's empty plan and M
|
||||
let served = enqueued.and_then(|()| self.serve_pool(&physical, (layer, rows, ring), pool));
|
||||
let finished = served.and_then(|()| self.finish_group(&physical, context, rows, ring));
|
||||
if finished.is_err() {
|
||||
self.abort_group();
|
||||
}
|
||||
finished
|
||||
}
|
||||
/// The doorbell's publication and the device FFN input, then known `parts` / `hit_out` contents.
|
||||
fn stage_group(&self, context: &Context<'_>, rows: usize, activation: &[f32], ids: &[i32]) -> Result<()> {
|
||||
let k = self.bank()?.geometry().k;
|
||||
for flag in 9..=12 {
|
||||
self.flag(flag, 0)?;
|
||||
}
|
||||
let as_bytes = |v: &[f32]| v.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>();
|
||||
self.write_mapped(6, 0, &as_bytes(activation))?;
|
||||
self.write_mapped(6, 0, &f32_bytes(activation))?;
|
||||
self.write_mapped(7, 0, &ids.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>())?;
|
||||
self.write_mapped(8, 0, &as_bytes(&vec![1.0 / k as f32; rows * k]))?;
|
||||
{
|
||||
let mixed = self.arena_handle("mixed", 0, rows * n * 4)?;
|
||||
self.write_mapped(8, 0, &f32_bytes(&vec![1.0 / k as f32; rows * k]))?;
|
||||
self.seed_group_buffers(context, rows, activation)
|
||||
}
|
||||
fn seed_group_buffers(&self, context: &Context<'_>, rows: usize, activation: &[f32]) -> Result<()> {
|
||||
let g = self.bank()?.geometry();
|
||||
let mixed = self.arena_handle("mixed", 0, rows * g.n * 4)?;
|
||||
let guard = context.enter()?;
|
||||
let copy = context.driver.api.copy_from(mixed, &f32_bytes(activation));
|
||||
combine(copy, guard.finish())?;
|
||||
// parts / hit_out start from a known state, as a reused window would not guarantee
|
||||
for name in ["parts", "hit_out"] {
|
||||
let h = self.arena_handle(name, 0, rows * g.k * g.n * 4)?;
|
||||
let guard = context.enter()?;
|
||||
let copy = context.driver.api.copy_from(mixed, &as_bytes(activation));
|
||||
combine(copy, guard.finish())?;
|
||||
// parts / hit_out start from a known state, as a reused window would not guarantee
|
||||
let zero = (|| {
|
||||
for name in ["parts", "hit_out"] {
|
||||
let h = self.arena_handle(name, 0, rows * k * n * 4)?;
|
||||
let guard = context.enter()?;
|
||||
let z = context.driver.api.zero(h.qwen_address(), rows * k * n * 4);
|
||||
combine(z, guard.finish())?;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
zero?;
|
||||
let z = context.driver.api.zero(h.qwen_address(), rows * g.k * g.n * 4);
|
||||
combine(z, guard.finish())?;
|
||||
}
|
||||
// compute side, in the recorded order of `post`
|
||||
Ok(())
|
||||
}
|
||||
fn group_plans(&self, g: &OriginalVerifyGeometry, layer: usize, group: Rows) -> Result<GroupPlans> {
|
||||
let knobs = MoeKnobs::mode17();
|
||||
let layout = PlanLayout::new(g.max_t * k);
|
||||
let (quantize, vram, pcie, hit_add) = {
|
||||
let arena = ProbeArena(&self.bank()?.physical);
|
||||
(
|
||||
moe::plan_quantize_expert_input(&arena, &g, &knobs, group)?,
|
||||
moe::plan_expert_groups(&arena, &g, &knobs, &self.formats, layer, group, ExpertTier::Vram)?,
|
||||
moe::plan_expert_groups(&arena, &g, &knobs, &self.formats, layer, group, ExpertTier::Pcie)?,
|
||||
moe::plan_hit_add(&arena, &g, group)?,
|
||||
)
|
||||
};
|
||||
let physical = self.bank()?.physical.clone();
|
||||
let wait = |index: usize| -> Result<Command> {
|
||||
command(
|
||||
"verify_wait_flag_ge_kernel",
|
||||
[1, 1, 1],
|
||||
[1, 1, 1],
|
||||
vec![Arg::Address(physical.mapped_address(index, 0, 4)?), Arg::I32(ring as i32)],
|
||||
)
|
||||
};
|
||||
let plan_copy = command(
|
||||
"verify_copy_i32_from_mapped_kernel",
|
||||
[1, 1, 1],
|
||||
[128, 1, 1],
|
||||
vec![
|
||||
Arg::Address(physical.span("plan", 0, layout.words * 4)?),
|
||||
Arg::Address(physical.mapped_address(14, 0, layout.words * 4)?),
|
||||
Arg::I32(layout.words as i32),
|
||||
],
|
||||
)?;
|
||||
let plan_word = |word: usize| physical.span("plan", word * 4, 4);
|
||||
let copy_rows = command(
|
||||
"verify_copy_rows_from_mapped_kernel",
|
||||
[(rows * k) as u32, 1, 1],
|
||||
[128, 1, 1],
|
||||
vec![
|
||||
Arg::Address(physical.span("parts", 0, rows * k * n * 4)?),
|
||||
Arg::Address(physical.mapped_address(13, 0, rows * k * n * 4)?),
|
||||
Arg::I64((n / 4) as i64),
|
||||
Arg::Address(plan_word(layout.dst)?),
|
||||
Arg::Address(plan_word(layout.counts + 1)?),
|
||||
],
|
||||
)?;
|
||||
let enqueued = (|| {
|
||||
self.launch_window(quantize)?;
|
||||
self.launch_bank(vec![wait(11)?, plan_copy])?;
|
||||
self.launch_window(vram)?;
|
||||
self.launch_bank(vec![wait(12)?])?;
|
||||
self.launch_window(pcie)?;
|
||||
self.launch_bank(vec![wait(10)?, copy_rows])?;
|
||||
self.launch_window(hit_add)
|
||||
})();
|
||||
// host side: the pool callback, then the run loop's empty plan and M
|
||||
let served = enqueued.and_then(|()| {
|
||||
let bank = self.bank.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let copy = self.copy.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let x = physical.mapped[6].try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let ids_m = physical.mapped[7].try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let w = physical.mapped[8].try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
MappedAllocation::with_cpu_rows(
|
||||
x.as_ref().ok_or(Error::ContextPoisoned)?,
|
||||
ids_m.as_ref().ok_or(Error::ContextPoisoned)?,
|
||||
w.as_ref().ok_or(Error::ContextPoisoned)?,
|
||||
0,
|
||||
rows,
|
||||
n,
|
||||
k,
|
||||
|activation, ids, route_weights| {
|
||||
pool(
|
||||
OriginalVerifyCpuRows { layer, group: 0, first_row: 0, activation, ids, route_weights },
|
||||
&mut OriginalVerifyCpuSink { bank, first: 0, rows, layer, group: 0, groups: 1, ring },
|
||||
copy,
|
||||
)
|
||||
},
|
||||
)
|
||||
});
|
||||
let finished = served.and_then(|()| {
|
||||
let a = physical.mapped[11]
|
||||
.try_borrow()
|
||||
.map_err(|_| Error::InvalidQwenShape)?
|
||||
.as_ref()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.read_u32(0)?;
|
||||
if a != ring {
|
||||
self.bank.as_mut().ok_or(Error::ContextPoisoned)?.publish_empty_plan(0, ring)?;
|
||||
}
|
||||
self.flag(10, ring)?;
|
||||
self.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?;
|
||||
self.copy.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?;
|
||||
self.bank.as_mut().ok_or(Error::ContextPoisoned)?.release_pcie_sources();
|
||||
let parts = self.arena_handle("parts", 0, rows * k * n * 4)?;
|
||||
let mut bytes = vec![0u8; rows * k * n * 4];
|
||||
let guard = context.enter()?;
|
||||
let read = context.driver.api.copy_to(parts, &mut bytes);
|
||||
combine(read, guard.finish())?;
|
||||
Ok(bytes.chunks_exact(4).map(|c| f32::from_le_bytes(c.try_into().unwrap_or([0; 4]))).collect())
|
||||
});
|
||||
if finished.is_err() {
|
||||
// no spin kernel may outlive a failed probe: raise every flag and drain both streams
|
||||
let _ = self.bank.as_mut().map(OriginalVerifyBank::release_gpu_waits);
|
||||
let _ = self.compute.as_ref().map(OriginalGpuStream::synchronize);
|
||||
let _ = self.copy.as_ref().map(OriginalGpuStream::synchronize);
|
||||
let arena = ProbeArena(&self.bank()?.physical);
|
||||
Ok(GroupPlans {
|
||||
quantize: moe::plan_quantize_expert_input(&arena, g, &knobs, group)?,
|
||||
vram: moe::plan_expert_groups(&arena, g, &knobs, &self.formats, layer, group, ExpertTier::Vram)?,
|
||||
pcie: moe::plan_expert_groups(&arena, g, &knobs, &self.formats, layer, group, ExpertTier::Pcie)?,
|
||||
hit_add: moe::plan_hit_add(&arena, g, group)?,
|
||||
})
|
||||
}
|
||||
/// quantize_expert_input | wait A | plan copy | VRAM groups | wait B | PCIe groups | wait M | copy cpu rows | hit add
|
||||
fn enqueue_group(
|
||||
&mut self,
|
||||
physical: &Physical<'ctx>,
|
||||
plans: GroupPlans,
|
||||
(plan_copy, copy_rows): (Command, Command),
|
||||
ring: u32,
|
||||
) -> Result<()> {
|
||||
self.launch_window(plans.quantize)?;
|
||||
self.launch_bank(vec![wait_command(physical, 11, ring)?, plan_copy])?;
|
||||
self.launch_window(plans.vram)?;
|
||||
self.launch_bank(vec![wait_command(physical, 12, ring)?])?;
|
||||
self.launch_window(plans.pcie)?;
|
||||
self.launch_bank(vec![wait_command(physical, 10, ring)?, copy_rows])?;
|
||||
self.launch_window(plans.hit_add)
|
||||
}
|
||||
/// The pool callback over the group's mapped rows, with the sink and the copy stream.
|
||||
fn serve_pool(
|
||||
&mut self,
|
||||
physical: &Physical<'ctx>,
|
||||
(layer, rows, ring): (usize, usize, u32),
|
||||
pool: impl FnOnce(
|
||||
OriginalVerifyCpuRows<'_>,
|
||||
&mut OriginalVerifyCpuSink<'_, 'ctx>,
|
||||
&mut OriginalGpuStream<'ctx>,
|
||||
) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
let g = &physical.layout.geometry;
|
||||
let (bank, copy) = self.bank_and_copy()?;
|
||||
let (x, ids_m, w) = mapped_rows(physical)?;
|
||||
MappedAllocation::with_cpu_rows(
|
||||
x.as_ref().ok_or(Error::ContextPoisoned)?,
|
||||
ids_m.as_ref().ok_or(Error::ContextPoisoned)?,
|
||||
w.as_ref().ok_or(Error::ContextPoisoned)?,
|
||||
0,
|
||||
rows,
|
||||
g.n,
|
||||
g.k,
|
||||
|activation, ids, route_weights| {
|
||||
pool(
|
||||
OriginalVerifyCpuRows { layer, group: 0, first_row: 0, activation, ids, route_weights },
|
||||
&mut OriginalVerifyCpuSink { bank, first: 0, rows, layer, group: 0, groups: 1, ring },
|
||||
copy,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
/// The run loop's empty plan unless published, M, the drains, then the group's `parts` rows.
|
||||
fn finish_group(
|
||||
&mut self,
|
||||
physical: &Physical<'ctx>,
|
||||
context: &Context<'_>,
|
||||
rows: usize,
|
||||
ring: u32,
|
||||
) -> Result<Vec<f32>> {
|
||||
let a = physical.mapped[11]
|
||||
.try_borrow()
|
||||
.map_err(|_| Error::InvalidQwenShape)?
|
||||
.as_ref()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.read_u32(0)?;
|
||||
if a != ring {
|
||||
self.bank.as_mut().ok_or(Error::ContextPoisoned)?.publish_empty_plan(0, ring)?;
|
||||
}
|
||||
finished
|
||||
self.flag(10, ring)?;
|
||||
self.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?;
|
||||
self.copy.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?;
|
||||
self.bank.as_mut().ok_or(Error::ContextPoisoned)?.release_pcie_sources();
|
||||
self.read_parts(context, rows)
|
||||
}
|
||||
fn read_parts(&self, context: &Context<'_>, rows: usize) -> Result<Vec<f32>> {
|
||||
let g = self.bank()?.geometry();
|
||||
let parts = self.arena_handle("parts", 0, rows * g.k * g.n * 4)?;
|
||||
let mut bytes = vec![0u8; rows * g.k * g.n * 4];
|
||||
let guard = context.enter()?;
|
||||
let read = context.driver.api.copy_to(parts, &mut bytes);
|
||||
combine(read, guard.finish())?;
|
||||
Ok(bytes.chunks_exact(4).map(|c| f32::from_le_bytes(c.try_into().unwrap_or([0; 4]))).collect())
|
||||
}
|
||||
/// No spin kernel may outlive a failed probe: raise every flag and drain both streams.
|
||||
fn abort_group(&mut self) {
|
||||
let _ = self.bank.as_mut().map(OriginalVerifyBank::release_gpu_waits);
|
||||
let _ = self.compute.as_ref().map(OriginalGpuStream::synchronize);
|
||||
let _ = self.copy.as_ref().map(OriginalGpuStream::synchronize);
|
||||
}
|
||||
fn close_inner(&mut self) -> Result<()> {
|
||||
let mut result = Ok(());
|
||||
@@ -303,3 +307,74 @@ impl Drop for OriginalExpertTierProbe<'_> {
|
||||
let _ = self.close_inner();
|
||||
}
|
||||
}
|
||||
|
||||
/// The group's row count after the shape checks.
|
||||
fn check_group_request(g: &OriginalVerifyGeometry, layer: usize, activation: &[f32], ids: &[i32]) -> Result<usize> {
|
||||
let (n, k) = (g.n, g.k);
|
||||
let rows = ids.len() / k;
|
||||
if rows == 0 || rows > g.max_t || ids.len() != rows * k || activation.len() != rows * n || layer >= 48 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
type MappedRef<'a> = std::cell::Ref<'a, Option<MappedAllocation>>;
|
||||
|
||||
/// The mapped activation, route id and route weight rows of a group, borrowed for the pool callback.
|
||||
fn mapped_rows<'a>(physical: &'a Physical<'_>) -> Result<(MappedRef<'a>, MappedRef<'a>, MappedRef<'a>)> {
|
||||
let x = physical.mapped[6].try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let ids = physical.mapped[7].try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
let w = physical.mapped[8].try_borrow().map_err(|_| Error::InvalidQwenShape)?;
|
||||
Ok((x, ids, w))
|
||||
}
|
||||
|
||||
fn f32_bytes(v: &[f32]) -> Vec<u8> {
|
||||
v.iter().flat_map(|x| x.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
/// The launches of the four phases of one group.
|
||||
struct GroupPlans {
|
||||
quantize: Vec<kernels::Launch>,
|
||||
vram: Vec<kernels::Launch>,
|
||||
pcie: Vec<kernels::Launch>,
|
||||
hit_add: Vec<kernels::Launch>,
|
||||
}
|
||||
|
||||
fn wait_command(physical: &Physical<'_>, index: usize, ring: u32) -> Result<Command> {
|
||||
command(
|
||||
"verify_wait_flag_ge_kernel",
|
||||
[1, 1, 1],
|
||||
[1, 1, 1],
|
||||
vec![Arg::Address(physical.mapped_address(index, 0, 4)?), Arg::I32(ring as i32)],
|
||||
)
|
||||
}
|
||||
|
||||
/// The plan copy and the CPU rows copy of a group of `rows` rows.
|
||||
fn group_commands(physical: &Physical<'_>, g: &OriginalVerifyGeometry, rows: usize) -> Result<(Command, Command)> {
|
||||
let (n, k) = (g.n, g.k);
|
||||
let layout = PlanLayout::new(g.max_t * k);
|
||||
let plan_copy = command(
|
||||
"verify_copy_i32_from_mapped_kernel",
|
||||
[1, 1, 1],
|
||||
[128, 1, 1],
|
||||
vec![
|
||||
Arg::Address(physical.span("plan", 0, layout.words * 4)?),
|
||||
Arg::Address(physical.mapped_address(14, 0, layout.words * 4)?),
|
||||
Arg::I32(layout.words as i32),
|
||||
],
|
||||
)?;
|
||||
let plan_word = |word: usize| physical.span("plan", word * 4, 4);
|
||||
let copy_rows = command(
|
||||
"verify_copy_rows_from_mapped_kernel",
|
||||
[(rows * k) as u32, 1, 1],
|
||||
[128, 1, 1],
|
||||
vec![
|
||||
Arg::Address(physical.span("parts", 0, rows * k * n * 4)?),
|
||||
Arg::Address(physical.mapped_address(13, 0, rows * k * n * 4)?),
|
||||
Arg::I64((n / 4) as i64),
|
||||
Arg::Address(plan_word(layout.dst)?),
|
||||
Arg::Address(plan_word(layout.counts + 1)?),
|
||||
],
|
||||
)?;
|
||||
Ok((plan_copy, copy_rows))
|
||||
}
|
||||
|
||||
@@ -99,6 +99,15 @@ impl Module {
|
||||
if library.0.is_null() {
|
||||
return Err(Error::LibraryUnavailable);
|
||||
}
|
||||
let (load, function, mut owner) = Self::bind(library)?;
|
||||
owner.functions.try_reserve_exact(entries.len()).map_err(|_| Error::HostAllocation)?;
|
||||
if let Err(primary) = owner.load_functions(load, function, ptx, entries) {
|
||||
return combine(Err(primary), owner.close());
|
||||
}
|
||||
Ok(owner)
|
||||
}
|
||||
/// Resolves every driver symbol of the module ABI; returns the two load entry points and the empty module owner.
|
||||
fn bind(library: Library) -> Result<(Load, Function, Self)> {
|
||||
fn sym(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("OriginalVerify ABI"))) } else { Ok(p) }
|
||||
@@ -113,7 +122,7 @@ impl Module {
|
||||
let launch_ex = sym(&library, c"cuLaunchKernelEx")
|
||||
.ok()
|
||||
.map(|p| unsafe { std::mem::transmute::<Handle, crate::launch_ex::LaunchEx>(p) });
|
||||
let mut owner = Self {
|
||||
let owner = Self {
|
||||
launch: symbol!(c"cuLaunchKernel", Launch),
|
||||
launch_ex,
|
||||
unload: symbol!(c"cuModuleUnload", Destroy),
|
||||
@@ -124,29 +133,31 @@ impl Module {
|
||||
handle: None,
|
||||
functions: Vec::new(),
|
||||
};
|
||||
owner.functions.try_reserve_exact(entries.len()).map_err(|_| Error::HostAllocation)?;
|
||||
let operation = (|| {
|
||||
let mut h = std::ptr::null_mut();
|
||||
check("cuModuleLoadData", unsafe { load(&mut h, crate::arch_ptx::image(ptx).as_ptr().cast()) })?;
|
||||
if h.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuModuleLoadData"));
|
||||
}
|
||||
owner.handle = Some(h as usize);
|
||||
for &name in entries {
|
||||
let c = std::ffi::CString::new(name).map_err(|_| Error::InvalidSize)?;
|
||||
let mut f = std::ptr::null_mut();
|
||||
check("cuModuleGetFunction", unsafe { function(&mut f, h, c.as_ptr()) })?;
|
||||
if f.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuModuleGetFunction"));
|
||||
}
|
||||
owner.functions.push((name, f as usize));
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(primary) = operation {
|
||||
return combine(Err(primary), owner.close());
|
||||
Ok((load, function, owner))
|
||||
}
|
||||
fn load_functions(
|
||||
&mut self,
|
||||
load: Load,
|
||||
function: Function,
|
||||
ptx: &'static [u8],
|
||||
entries: &[&'static str],
|
||||
) -> Result<()> {
|
||||
let mut h = std::ptr::null_mut();
|
||||
check("cuModuleLoadData", unsafe { load(&mut h, crate::arch_ptx::image(ptx).as_ptr().cast()) })?;
|
||||
if h.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuModuleLoadData"));
|
||||
}
|
||||
Ok(owner)
|
||||
self.handle = Some(h as usize);
|
||||
for &name in entries {
|
||||
let c = std::ffi::CString::new(name).map_err(|_| Error::InvalidSize)?;
|
||||
let mut f = std::ptr::null_mut();
|
||||
check("cuModuleGetFunction", unsafe { function(&mut f, h, c.as_ptr()) })?;
|
||||
if f.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuModuleGetFunction"));
|
||||
}
|
||||
self.functions.push((name, f as usize));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn admit(&self, c: &Command) -> Result<()> {
|
||||
if self.handle.is_none()
|
||||
@@ -166,22 +177,7 @@ impl Module {
|
||||
c.pointers.push(arg.pointer());
|
||||
}
|
||||
if c.cluster > 0 {
|
||||
let launch_ex = self.launch_ex.ok_or(Error::MissingSymbol("cuLaunchKernelEx"))?;
|
||||
if c.grid[0] % c.cluster != 0 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let mut attribute = crate::launch_ex::LaunchAttribute::cluster_x(c.cluster);
|
||||
let config = crate::launch_ex::LaunchConfig {
|
||||
grid: c.grid,
|
||||
block: c.block,
|
||||
smem: c.shared,
|
||||
stream: stream as Handle,
|
||||
attrs: &mut attribute,
|
||||
num_attrs: 1,
|
||||
};
|
||||
return check("cuLaunchKernelEx", unsafe {
|
||||
launch_ex(&config, f as Handle, c.pointers.as_mut_ptr(), std::ptr::null_mut())
|
||||
});
|
||||
return self.launch_cluster(f, stream, c);
|
||||
}
|
||||
check("cuLaunchKernel", unsafe {
|
||||
(self.launch)(
|
||||
@@ -199,6 +195,24 @@ impl Module {
|
||||
)
|
||||
})
|
||||
}
|
||||
fn launch_cluster(&self, f: usize, stream: usize, c: &mut Command) -> Result<()> {
|
||||
let launch_ex = self.launch_ex.ok_or(Error::MissingSymbol("cuLaunchKernelEx"))?;
|
||||
if c.grid[0] % c.cluster != 0 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let mut attribute = crate::launch_ex::LaunchAttribute::cluster_x(c.cluster);
|
||||
let config = crate::launch_ex::LaunchConfig {
|
||||
grid: c.grid,
|
||||
block: c.block,
|
||||
smem: c.shared,
|
||||
stream: stream as Handle,
|
||||
attrs: &mut attribute,
|
||||
num_attrs: 1,
|
||||
};
|
||||
check("cuLaunchKernelEx", unsafe {
|
||||
launch_ex(&config, f as Handle, c.pointers.as_mut_ptr(), std::ptr::null_mut())
|
||||
})
|
||||
}
|
||||
/// `cuFuncSetAttribute(CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES)` of one loaded entry (Original sets it once
|
||||
/// before any launch/capture for kernels that stage more than 48 KiB).
|
||||
pub(crate) fn set_max_dynamic_shared(&self, name: &str, bytes: usize) -> Result<()> {
|
||||
|
||||
@@ -47,7 +47,13 @@ fn align(n: usize, a: usize) -> Result<usize> {
|
||||
}
|
||||
impl OriginalVerifyGeometry {
|
||||
pub fn validate(self) -> Result<()> {
|
||||
if !(2..=8).contains(&self.max_t)
|
||||
if self.bad_model_shape() || self.bad_attention_shape() || self.bad_cells() || self.bad_expert_blob() {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn bad_model_shape(&self) -> bool {
|
||||
!(2..=8).contains(&self.max_t)
|
||||
|| self.n != 2560
|
||||
|| self.hc != 4
|
||||
|| self.lr != 320
|
||||
@@ -55,7 +61,9 @@ impl OriginalVerifyGeometry {
|
||||
|| self.experts != 512
|
||||
|| self.k != 10
|
||||
|| self.channels != 10240
|
||||
|| self.value_heads != 48
|
||||
}
|
||||
fn bad_attention_shape(&self) -> bool {
|
||||
self.value_heads != 48
|
||||
|| self.key_heads != 16
|
||||
|| self.heads != 24
|
||||
|| self.kv_heads != 2
|
||||
@@ -64,25 +72,49 @@ impl OriginalVerifyGeometry {
|
||||
|| self.index_dim != 128
|
||||
|| self.index_block != 4
|
||||
|| self.selection != 2051
|
||||
|| self.max_cells < self.max_t
|
||||
}
|
||||
fn bad_cells(&self) -> bool {
|
||||
self.max_cells < self.max_t
|
||||
|| self.max_cells > crate::MAX_CONTEXT_CELLS
|
||||
|| self.max_cells % 4 != 0
|
||||
|| self.vocabulary == 0
|
||||
|| self.vocabulary > i32::MAX as usize
|
||||
|| self.max_expert_blob == 0
|
||||
|| self.max_expert_blob > 8 * 1024 * 1024
|
||||
|| self.max_expert_blob % 16 != 0
|
||||
{
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn bad_expert_blob(&self) -> bool {
|
||||
self.max_expert_blob == 0 || self.max_expert_blob > 8 * 1024 * 1024 || self.max_expert_blob % 16 != 0
|
||||
}
|
||||
}
|
||||
impl OriginalVerifyLayout {
|
||||
pub fn new(g: OriginalVerifyGeometry) -> Result<Self> {
|
||||
g.validate()?;
|
||||
let t = g.max_t;
|
||||
let cap = t * g.k;
|
||||
let derived = Derived::of(&g)?;
|
||||
let mut builder = SpanBuilder::new()?;
|
||||
builder.take_tables(&g, &derived)?;
|
||||
if std::env::var_os("LELEKA_TRACE_LADDER").is_some() {
|
||||
builder.take("dbg_ladder", 96 * g.max_t * g.hc * g.n, 4)?;
|
||||
}
|
||||
let mapped_bytes = mapped_bytes(&g, derived.plan_i32);
|
||||
let bytes = align(builder.used, 256)?;
|
||||
Ok(Self { geometry: g, spans: builder.spans, bytes, plan_i32: derived.plan_i32, mapped_bytes })
|
||||
}
|
||||
pub fn span(&self, name: &str) -> Result<OriginalVerifySpan> {
|
||||
self.spans.iter().copied().find(|s| s.name == name).ok_or(Error::InvalidQwenShape)
|
||||
}
|
||||
}
|
||||
|
||||
/// The sizes the span table is derived from.
|
||||
struct Derived {
|
||||
plan_i32: usize,
|
||||
max_in: usize,
|
||||
scratch_floats: usize,
|
||||
max_blocks: usize,
|
||||
s2: usize,
|
||||
native: usize,
|
||||
}
|
||||
|
||||
impl Derived {
|
||||
fn of(g: &OriginalVerifyGeometry) -> Result<Self> {
|
||||
let cap = g.max_t * g.k;
|
||||
let ptr_off = align(4 + (cap + 1) + cap + cap, 2)?;
|
||||
let plan_i32 = add(add(ptr_off, 4 * cap)?, cap + 2)?;
|
||||
let max_in = g.n.max(g.value_heads * 128).max(g.heads * g.head_dim);
|
||||
@@ -93,101 +125,151 @@ impl OriginalVerifyLayout {
|
||||
add(2 * align(cap * (g.ff / 32) * 4, 16)?, align(g.n / 32 * 4, 16)?)?,
|
||||
)?;
|
||||
let native = add(3 * align(cap * g.ff * 4, 256)?, align(cap * (g.ff / 32) * 36, 256)?)?;
|
||||
let mut spans = Vec::new();
|
||||
spans.try_reserve_exact(64).map_err(|_| Error::HostAllocation)?;
|
||||
let mut used = 0usize;
|
||||
let mut take = |name, count, width| -> Result<()> {
|
||||
let bytes = mul(count, width)?;
|
||||
let offset = align(used, 256)?;
|
||||
used = add(offset, bytes)?;
|
||||
spans.push(OriginalVerifySpan { name, offset, bytes });
|
||||
Ok(())
|
||||
};
|
||||
for (name, count, width) in [
|
||||
("tok", t, 4),
|
||||
("step", t * 4, 4),
|
||||
("pos", t * (g.heads + g.kv_heads + g.index_heads), 4),
|
||||
("commit", 2 + t, 4),
|
||||
("ple", t * g.n, 4),
|
||||
("emb", t * g.n, 4),
|
||||
("R", t * g.hc * g.n, 4),
|
||||
("mixed", t * g.n, 4),
|
||||
("bo", t * g.n, 4),
|
||||
("inj", t * g.hc, 4),
|
||||
("inj2", t * g.hc, 4),
|
||||
("lo", t * g.lr, 4),
|
||||
("rs", t * g.hc, 4),
|
||||
("xn", t * g.hc * g.n, 4),
|
||||
("xq", t * (max_in / 32) * 36, 1),
|
||||
("qkv_L", 36 * t * g.channels, 4),
|
||||
("h_L", 36 * t * g.channels, 4),
|
||||
("gate_L", 36 * t * g.value_heads, 4),
|
||||
("beta_L", 36 * t * g.value_heads, 4),
|
||||
("z", t * g.value_heads * 128, 4),
|
||||
("y", t * g.value_heads * 128, 4),
|
||||
("y_dummy", t * g.value_heads * 128, 4),
|
||||
("qfull", t * g.heads * 2 * g.head_dim, 4),
|
||||
("qcur", t * g.heads * g.head_dim, 4),
|
||||
("kcur", t * g.kv_heads * g.head_dim, 4),
|
||||
("vcur", t * g.kv_heads * g.head_dim, 4),
|
||||
("idx_raw_L", 12 * t * g.index_dim, 4),
|
||||
("qidx", t * g.index_heads * g.index_dim, 4),
|
||||
("scores", t * max_blocks, 4),
|
||||
("sel", t * g.selection, 4),
|
||||
("attn", t * g.heads * g.head_dim, 4),
|
||||
("attn32", t * g.heads * g.head_dim, 4),
|
||||
("attn_scratch", t * scratch_floats, 4),
|
||||
("tail_snap", 12 * (g.index_block - 1) * g.index_dim, 4),
|
||||
("logits", t * g.experts, 4),
|
||||
("w", t * g.k, 4),
|
||||
("ids", t * g.k, 4),
|
||||
("shared", t * g.n, 4),
|
||||
("parts", t * g.k * g.n, 4),
|
||||
("hit_out", t * g.k * g.n, 4),
|
||||
("hit_slot", t * g.k, 4),
|
||||
("hit_dst", t * g.k, 4),
|
||||
("hit_count", 4, 4),
|
||||
("plan", 2 * (plan_i32 + 16), 4),
|
||||
("staging", 16 * g.max_expert_blob, 1),
|
||||
("hit_xq", t * (g.n / 32) * 34, 1),
|
||||
("hit_xs", t * (g.n / 32), 4),
|
||||
("nat_xq", t * (g.n / 32) * 36, 1),
|
||||
("hit_scratch", s2.max(native), 1),
|
||||
("head_mixed", t * g.n, 4),
|
||||
("head_inj", g.hc, 4),
|
||||
("sh_bf16", t * g.n, 2),
|
||||
("sh_gate", t * g.ff, 4),
|
||||
("sh_up", t * g.ff, 4),
|
||||
("sh_g", t + 4, 4),
|
||||
("head_logits", t * g.vocabulary, 4),
|
||||
("hist_snap", t * 9 * g.hc * g.n, 4),
|
||||
] {
|
||||
take(name, count, width)?;
|
||||
}
|
||||
if std::env::var_os("LELEKA_TRACE_LADDER").is_some() {
|
||||
take("dbg_ladder", 96 * t * g.hc * g.n, 4)?;
|
||||
}
|
||||
drop(take);
|
||||
let mapped_bytes = [
|
||||
t * 4,
|
||||
t * 4 * 4,
|
||||
t * (g.heads + g.kv_heads + g.index_heads) * 4,
|
||||
(2 + t) * 4 + 16,
|
||||
t * g.n * 4,
|
||||
t * 4 + 16,
|
||||
t * g.n * 4,
|
||||
t * g.k * 4,
|
||||
t * g.k * 4,
|
||||
64,
|
||||
64,
|
||||
64,
|
||||
64,
|
||||
t * g.k * g.n * 4,
|
||||
plan_i32 * 4 * 2 + 64,
|
||||
];
|
||||
Ok(Self { geometry: g, spans, bytes: align(used, 256)?, plan_i32, mapped_bytes })
|
||||
}
|
||||
pub fn span(&self, name: &str) -> Result<OriginalVerifySpan> {
|
||||
self.spans.iter().copied().find(|s| s.name == name).ok_or(Error::InvalidQwenShape)
|
||||
Ok(Self { plan_i32, max_in, scratch_floats, max_blocks, s2, native })
|
||||
}
|
||||
}
|
||||
|
||||
/// Spans laid out one after the other, each 256-byte aligned.
|
||||
struct SpanBuilder {
|
||||
spans: Vec<OriginalVerifySpan>,
|
||||
used: usize,
|
||||
}
|
||||
|
||||
type SpanRow = (&'static str, usize, usize);
|
||||
|
||||
impl SpanBuilder {
|
||||
fn new() -> Result<Self> {
|
||||
let mut spans = Vec::new();
|
||||
spans.try_reserve_exact(64).map_err(|_| Error::HostAllocation)?;
|
||||
Ok(Self { spans, used: 0 })
|
||||
}
|
||||
fn take(&mut self, name: &'static str, count: usize, width: usize) -> Result<()> {
|
||||
let bytes = mul(count, width)?;
|
||||
let offset = align(self.used, 256)?;
|
||||
self.used = add(offset, bytes)?;
|
||||
self.spans.push(OriginalVerifySpan { name, offset, bytes });
|
||||
Ok(())
|
||||
}
|
||||
fn take_rows(&mut self, rows: &[SpanRow]) -> Result<()> {
|
||||
for &(name, count, width) in rows {
|
||||
self.take(name, count, width)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn take_tables(&mut self, g: &OriginalVerifyGeometry, d: &Derived) -> Result<()> {
|
||||
self.take_rows(&input_rows(g))?;
|
||||
self.take_rows(&gdn_rows(g))?;
|
||||
self.take_rows(&attention_rows(g, d))?;
|
||||
self.take_rows(&moe_rows(g, d))?;
|
||||
self.take_rows(&head_rows(g))
|
||||
}
|
||||
}
|
||||
|
||||
fn input_rows(g: &OriginalVerifyGeometry) -> [SpanRow; 15] {
|
||||
let t = g.max_t;
|
||||
let max_in = g.n.max(g.value_heads * 128).max(g.heads * g.head_dim);
|
||||
[
|
||||
("tok", t, 4),
|
||||
("step", t * 4, 4),
|
||||
("pos", t * (g.heads + g.kv_heads + g.index_heads), 4),
|
||||
("commit", 2 + t, 4),
|
||||
("ple", t * g.n, 4),
|
||||
("emb", t * g.n, 4),
|
||||
("R", t * g.hc * g.n, 4),
|
||||
("mixed", t * g.n, 4),
|
||||
("bo", t * g.n, 4),
|
||||
("inj", t * g.hc, 4),
|
||||
("inj2", t * g.hc, 4),
|
||||
("lo", t * g.lr, 4),
|
||||
("rs", t * g.hc, 4),
|
||||
("xn", t * g.hc * g.n, 4),
|
||||
("xq", t * (max_in / 32) * 36, 1),
|
||||
]
|
||||
}
|
||||
|
||||
fn gdn_rows(g: &OriginalVerifyGeometry) -> [SpanRow; 7] {
|
||||
let t = g.max_t;
|
||||
[
|
||||
("qkv_L", 36 * t * g.channels, 4),
|
||||
("h_L", 36 * t * g.channels, 4),
|
||||
("gate_L", 36 * t * g.value_heads, 4),
|
||||
("beta_L", 36 * t * g.value_heads, 4),
|
||||
("z", t * g.value_heads * 128, 4),
|
||||
("y", t * g.value_heads * 128, 4),
|
||||
("y_dummy", t * g.value_heads * 128, 4),
|
||||
]
|
||||
}
|
||||
|
||||
fn attention_rows(g: &OriginalVerifyGeometry, d: &Derived) -> [SpanRow; 12] {
|
||||
let t = g.max_t;
|
||||
[
|
||||
("qfull", t * g.heads * 2 * g.head_dim, 4),
|
||||
("qcur", t * g.heads * g.head_dim, 4),
|
||||
("kcur", t * g.kv_heads * g.head_dim, 4),
|
||||
("vcur", t * g.kv_heads * g.head_dim, 4),
|
||||
("idx_raw_L", 12 * t * g.index_dim, 4),
|
||||
("qidx", t * g.index_heads * g.index_dim, 4),
|
||||
("scores", t * d.max_blocks, 4),
|
||||
("sel", t * g.selection, 4),
|
||||
("attn", t * g.heads * g.head_dim, 4),
|
||||
("attn32", t * g.heads * g.head_dim, 4),
|
||||
("attn_scratch", t * d.scratch_floats, 4),
|
||||
("tail_snap", 12 * (g.index_block - 1) * g.index_dim, 4),
|
||||
]
|
||||
}
|
||||
|
||||
fn moe_rows(g: &OriginalVerifyGeometry, d: &Derived) -> [SpanRow; 15] {
|
||||
let t = g.max_t;
|
||||
[
|
||||
("logits", t * g.experts, 4),
|
||||
("w", t * g.k, 4),
|
||||
("ids", t * g.k, 4),
|
||||
("shared", t * g.n, 4),
|
||||
("parts", t * g.k * g.n, 4),
|
||||
("hit_out", t * g.k * g.n, 4),
|
||||
("hit_slot", t * g.k, 4),
|
||||
("hit_dst", t * g.k, 4),
|
||||
("hit_count", 4, 4),
|
||||
("plan", 2 * (d.plan_i32 + 16), 4),
|
||||
("staging", 16 * g.max_expert_blob, 1),
|
||||
("hit_xq", t * (g.n / 32) * 34, 1),
|
||||
("hit_xs", t * (g.n / 32), 4),
|
||||
("nat_xq", t * (g.n / 32) * 36, 1),
|
||||
("hit_scratch", d.s2.max(d.native), 1),
|
||||
]
|
||||
}
|
||||
|
||||
fn head_rows(g: &OriginalVerifyGeometry) -> [SpanRow; 8] {
|
||||
let t = g.max_t;
|
||||
[
|
||||
("head_mixed", t * g.n, 4),
|
||||
("head_inj", g.hc, 4),
|
||||
("sh_bf16", t * g.n, 2),
|
||||
("sh_gate", t * g.ff, 4),
|
||||
("sh_up", t * g.ff, 4),
|
||||
("sh_g", t + 4, 4),
|
||||
("head_logits", t * g.vocabulary, 4),
|
||||
("hist_snap", t * 9 * g.hc * g.n, 4),
|
||||
]
|
||||
}
|
||||
|
||||
fn mapped_bytes(g: &OriginalVerifyGeometry, plan_i32: usize) -> [usize; 15] {
|
||||
let t = g.max_t;
|
||||
[
|
||||
t * 4,
|
||||
t * 4 * 4,
|
||||
t * (g.heads + g.kv_heads + g.index_heads) * 4,
|
||||
(2 + t) * 4 + 16,
|
||||
t * g.n * 4,
|
||||
t * 4 + 16,
|
||||
t * g.n * 4,
|
||||
t * g.k * 4,
|
||||
t * g.k * 4,
|
||||
64,
|
||||
64,
|
||||
64,
|
||||
64,
|
||||
t * g.k * g.n * 4,
|
||||
plan_i32 * 4 * 2 + 64,
|
||||
]
|
||||
}
|
||||
|
||||
@@ -48,21 +48,19 @@ pub struct RowLogprob {
|
||||
pub target_without_extra: f64,
|
||||
}
|
||||
|
||||
/// Analyse one logit row exactly like `Verifier::window_logprobs`.
|
||||
/// `None` when the target is outside the vocabulary (the row is skipped).
|
||||
pub fn analyse_row(row: &[f32], position: i64, target: i32, extra_id: i32) -> Option<RowLogprob> {
|
||||
let n = row.len();
|
||||
if target < 0 || target as usize >= n {
|
||||
return None;
|
||||
}
|
||||
/// The first index of the row's maximum.
|
||||
fn argmax_first(row: &[f32]) -> usize {
|
||||
let mut top = 0usize;
|
||||
for v in 1..n {
|
||||
for v in 1..row.len() {
|
||||
if row[v] > row[top] {
|
||||
top = v;
|
||||
}
|
||||
}
|
||||
let maxv = f64::from(row[top]);
|
||||
let has_extra = extra_id >= 0 && (extra_id as usize) < n;
|
||||
top
|
||||
}
|
||||
|
||||
/// `(sum, sum_without)` of `exp(x - maxv)` over the row, the second without the `extra_id` entry.
|
||||
fn exp_sums(row: &[f32], maxv: f64, extra_id: i32) -> (f64, f64) {
|
||||
let (mut sum, mut sum_without) = (0.0f64, 0.0f64);
|
||||
for (v, &x) in row.iter().enumerate() {
|
||||
let e = (f64::from(x) - maxv).exp();
|
||||
@@ -71,6 +69,20 @@ pub fn analyse_row(row: &[f32], position: i64, target: i32, extra_id: i32) -> Op
|
||||
sum_without += e;
|
||||
}
|
||||
}
|
||||
(sum, sum_without)
|
||||
}
|
||||
|
||||
/// Analyse one logit row exactly like `Verifier::window_logprobs`.
|
||||
/// `None` when the target is outside the vocabulary (the row is skipped).
|
||||
pub fn analyse_row(row: &[f32], position: i64, target: i32, extra_id: i32) -> Option<RowLogprob> {
|
||||
let n = row.len();
|
||||
if target < 0 || target as usize >= n {
|
||||
return None;
|
||||
}
|
||||
let top = argmax_first(row);
|
||||
let maxv = f64::from(row[top]);
|
||||
let has_extra = extra_id >= 0 && (extra_id as usize) < n;
|
||||
let (sum, sum_without) = exp_sums(row, maxv, extra_id);
|
||||
let lse = maxv + sum.ln();
|
||||
let extra = if has_extra { f64::from(row[extra_id as usize]) - lse } else { f64::NAN };
|
||||
let without = if has_extra && target != extra_id && sum_without > 0.0 {
|
||||
|
||||
@@ -52,7 +52,17 @@ mod enabled {
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn all_finite_is_the_is_finite_predicate() {
|
||||
let specials = [
|
||||
for len in [0usize, 1, 7, 255, 256, 257, 1000] {
|
||||
for at in [0usize, len / 2, len.saturating_sub(1)] {
|
||||
for s in finite_specials() {
|
||||
check_all_finite(len, at, s);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
fn finite_specials() -> [f32; 13] {
|
||||
[
|
||||
0.0f32,
|
||||
-0.0,
|
||||
1.0,
|
||||
@@ -66,23 +76,15 @@ mod enabled {
|
||||
-f32::NAN,
|
||||
f32::from_bits(0x7f80_0001),
|
||||
f32::from_bits(0xffc0_0000),
|
||||
];
|
||||
for len in [0usize, 1, 7, 255, 256, 257, 1000] {
|
||||
for at in [0usize, len / 2, len.saturating_sub(1)] {
|
||||
for &s in &specials {
|
||||
let mut v = vec![0.5f32; len];
|
||||
if len > 0 {
|
||||
v[at] = s;
|
||||
}
|
||||
assert_eq!(
|
||||
all_finite(&v),
|
||||
!v.iter().any(|x| !x.is_finite()),
|
||||
"len {len} at {at} value {:#x}",
|
||||
s.to_bits()
|
||||
);
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
#[cfg(test)]
|
||||
fn check_all_finite(len: usize, at: usize, s: f32) {
|
||||
let mut v = vec![0.5f32; len];
|
||||
if len > 0 {
|
||||
v[at] = s;
|
||||
}
|
||||
assert_eq!(all_finite(&v), !v.iter().any(|x| !x.is_finite()), "len {len} at {at} value {:#x}", s.to_bits());
|
||||
}
|
||||
pub(crate) struct MappedAllocation {
|
||||
library: Option<Library>,
|
||||
@@ -187,18 +189,9 @@ mod enabled {
|
||||
k: usize,
|
||||
consume: impl FnOnce(&[f32], &[i32], &[f32]) -> Result<R>,
|
||||
) -> Result<R> {
|
||||
let x = activation.range(
|
||||
first.checked_mul(n).and_then(|x| x.checked_mul(4)).ok_or(Error::InvalidSize)?,
|
||||
rows.checked_mul(n).and_then(|x| x.checked_mul(4)).ok_or(Error::InvalidSize)?,
|
||||
)?;
|
||||
let i = ids.range(
|
||||
first.checked_mul(k).and_then(|x| x.checked_mul(4)).ok_or(Error::InvalidSize)?,
|
||||
rows.checked_mul(k).and_then(|x| x.checked_mul(4)).ok_or(Error::InvalidSize)?,
|
||||
)?;
|
||||
let w = weights.range(
|
||||
first.checked_mul(k).and_then(|x| x.checked_mul(4)).ok_or(Error::InvalidSize)?,
|
||||
rows.checked_mul(k).and_then(|x| x.checked_mul(4)).ok_or(Error::InvalidSize)?,
|
||||
)?;
|
||||
let x = activation.rows_range(first, rows, n)?;
|
||||
let i = ids.rows_range(first, rows, k)?;
|
||||
let w = weights.rows_range(first, rows, k)?;
|
||||
if x % 4 != 0 || i % 4 != 0 || w % 4 != 0 {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
@@ -211,6 +204,13 @@ mod enabled {
|
||||
unsafe { std::slice::from_raw_parts(w as *const f32, rows * k) },
|
||||
)
|
||||
}
|
||||
/// The address of `rows` rows of `width` f32 words starting at row `first`, bounds checked.
|
||||
fn rows_range(&self, first: usize, rows: usize, width: usize) -> Result<usize> {
|
||||
self.range(
|
||||
first.checked_mul(width).and_then(|x| x.checked_mul(4)).ok_or(Error::InvalidSize)?,
|
||||
rows.checked_mul(width).and_then(|x| x.checked_mul(4)).ok_or(Error::InvalidSize)?,
|
||||
)
|
||||
}
|
||||
pub(crate) fn with_cpu_output<R>(
|
||||
&mut self,
|
||||
offset: usize,
|
||||
|
||||
@@ -80,33 +80,36 @@ impl OriginalVerifyProfile {
|
||||
}
|
||||
let at = |l: usize, i: usize| stamps[profile_stamp_slot(l, i)];
|
||||
for l in 0..layers {
|
||||
let kind = usize::from(qsa(l));
|
||||
let mut prev = at(l, 0);
|
||||
for i in 1..=24 {
|
||||
let x = at(l, i);
|
||||
if x == 0 || x < prev {
|
||||
continue;
|
||||
}
|
||||
self.sum[kind][i] += (x - prev) as f64;
|
||||
prev = x;
|
||||
}
|
||||
if l + 1 < layers {
|
||||
self.sum[kind][25] += gap(at(l + 1, 0), at(l, 24));
|
||||
}
|
||||
let dn = gap(at(l, 27), at(l, 0));
|
||||
let dd = gap(at(l, 28), at(l, 27));
|
||||
let du = gap(at(l, 1), at(l, 28));
|
||||
if dn > 0.0 && dd > 0.0 && du > 0.0 {
|
||||
// the split exists: show it split, not twice
|
||||
self.sum[kind][27] += dn;
|
||||
self.sum[kind][28] += dd;
|
||||
self.sum[kind][29] += du;
|
||||
self.sum[kind][1] -= gap(at(l, 1), at(l, 0));
|
||||
}
|
||||
self.add_layer(&at, (l, layers), usize::from(qsa(l)));
|
||||
}
|
||||
self.sum[0][26] += gap(at(layers, 1), at(layers, 0));
|
||||
self.windows += 1;
|
||||
}
|
||||
/// Folds layer `l` of `layers` (of the given `kind`) into the sums.
|
||||
fn add_layer(&mut self, at: &impl Fn(usize, usize) -> u64, (l, layers): (usize, usize), kind: usize) {
|
||||
let mut prev = at(l, 0);
|
||||
for i in 1..=24 {
|
||||
let x = at(l, i);
|
||||
if x == 0 || x < prev {
|
||||
continue;
|
||||
}
|
||||
self.sum[kind][i] += (x - prev) as f64;
|
||||
prev = x;
|
||||
}
|
||||
if l + 1 < layers {
|
||||
self.sum[kind][25] += gap(at(l + 1, 0), at(l, 24));
|
||||
}
|
||||
let dn = gap(at(l, 27), at(l, 0));
|
||||
let dd = gap(at(l, 28), at(l, 27));
|
||||
let du = gap(at(l, 1), at(l, 28));
|
||||
if dn > 0.0 && dd > 0.0 && du > 0.0 {
|
||||
// the split exists: show it split, not twice
|
||||
self.sum[kind][27] += dn;
|
||||
self.sum[kind][28] += dd;
|
||||
self.sum[kind][29] += du;
|
||||
self.sum[kind][1] -= gap(at(l, 1), at(l, 0));
|
||||
}
|
||||
}
|
||||
/// One line; empty when nothing was accumulated. Resets, like Original.
|
||||
pub fn report(&mut self) -> String {
|
||||
if self.windows == 0 {
|
||||
|
||||
@@ -21,7 +21,26 @@ impl OriginalVerifyCpuSink<'_, '_> {
|
||||
}
|
||||
impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>> OriginalVerifier<'ctx, R> {
|
||||
pub fn new(context: &'ctx Context<'ctx>, geometry: OriginalVerifyGeometry) -> Result<Self> {
|
||||
let mut owner = Self {
|
||||
let mut owner = Self::unopened();
|
||||
if let Err(primary) = owner.open(context, geometry) {
|
||||
return combine(Err(primary), owner.close_inner());
|
||||
}
|
||||
Ok(owner)
|
||||
}
|
||||
fn open(&mut self, context: &'ctx Context<'ctx>, geometry: OriginalVerifyGeometry) -> Result<()> {
|
||||
self.bank = Some(context.original_verify_bank(geometry)?);
|
||||
// #267 test hook, off unless set: withhold the last layer's flag in the N-th window (1-based).
|
||||
self.test_stall =
|
||||
std::env::var("STRATA_TEST_VERIFY_STALL").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(0);
|
||||
self.registration =
|
||||
Some(diag::Registration::new(self.bank.as_ref().ok_or(Error::ContextPoisoned)?.host_words()?));
|
||||
self.copy = Some(context.original_gpu_stream(OriginalStreamKind::NonBlocking)?);
|
||||
self.compute = Some(context.original_gpu_stream(OriginalStreamKind::NonBlocking)?);
|
||||
self.event = Some(context.original_gpu_event(OriginalEventKind::Completion)?);
|
||||
Ok(())
|
||||
}
|
||||
fn unopened() -> Self {
|
||||
Self {
|
||||
bank: None,
|
||||
compute: None,
|
||||
copy: None,
|
||||
@@ -43,23 +62,7 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
|
||||
released: false,
|
||||
profile: OriginalVerifyProfile::default(),
|
||||
test_stall: 0,
|
||||
};
|
||||
let operation = (|| {
|
||||
owner.bank = Some(context.original_verify_bank(geometry)?);
|
||||
// #267 test hook, off unless set: withhold the last layer's flag in the N-th window (1-based).
|
||||
owner.test_stall =
|
||||
std::env::var("STRATA_TEST_VERIFY_STALL").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(0);
|
||||
owner.registration =
|
||||
Some(diag::Registration::new(owner.bank.as_ref().ok_or(Error::ContextPoisoned)?.host_words()?));
|
||||
owner.copy = Some(context.original_gpu_stream(OriginalStreamKind::NonBlocking)?);
|
||||
owner.compute = Some(context.original_gpu_stream(OriginalStreamKind::NonBlocking)?);
|
||||
owner.event = Some(context.original_gpu_event(OriginalEventKind::Completion)?);
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(primary) = operation {
|
||||
return combine(Err(primary), owner.close_inner());
|
||||
}
|
||||
Ok(owner)
|
||||
}
|
||||
pub fn bank(&self) -> Result<&OriginalVerifyBank<'ctx>> {
|
||||
self.bank.as_ref().ok_or(Error::ContextPoisoned)
|
||||
@@ -105,19 +108,9 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
|
||||
resources: R,
|
||||
record: impl FnOnce(&mut OriginalCapture<'_, 'ctx>, &mut R, usize) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
if self.failed
|
||||
|| self.active
|
||||
|| !(1..=self.bank()?.geometry().max_t).contains(&t)
|
||||
|| self.window[t - 1].is_some()
|
||||
{
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
self.check_window_request(t)?;
|
||||
self.record_keys(&resources)?;
|
||||
if resources.native_head_rows()?.rows() != t
|
||||
|| resources.native_head_rows()?.completed_logits()?.len() != t * self.bank()?.geometry().vocabulary * 4
|
||||
{
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
self.check_native_rows(&resources, t)?;
|
||||
let groups = window_plan::window_groups(t, self.split);
|
||||
let stream = self.compute.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let graph = stream.capture_owned(OriginalCapturePolicy::VerifierWindow, resources, |capture, r| {
|
||||
@@ -131,6 +124,24 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
|
||||
self.groups[t - 1] = groups;
|
||||
Ok(())
|
||||
}
|
||||
fn check_window_request(&self, t: usize) -> Result<()> {
|
||||
if self.failed
|
||||
|| self.active
|
||||
|| !(1..=self.bank()?.geometry().max_t).contains(&t)
|
||||
|| self.window[t - 1].is_some()
|
||||
{
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn check_native_rows(&self, resources: &R, t: usize) -> Result<()> {
|
||||
if resources.native_head_rows()?.rows() != t
|
||||
|| resources.native_head_rows()?.completed_logits()?.len() != t * self.bank()?.geometry().vocabulary * 4
|
||||
{
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn record_commit(
|
||||
&mut self,
|
||||
resources: R,
|
||||
@@ -140,58 +151,13 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
self.record_keys(&resources)?;
|
||||
// sm_120 only: the fused kernels have no sm_86 companion (ptx-sm86/MANIFEST.json), another card keeps the Original's commit graph
|
||||
let fused_commit = crate::original_verify::draft::fused_commit()
|
||||
&& resources
|
||||
.verifier_journal()
|
||||
.window_device_attribute(crate::original_verify::gr::ATTR_COMPUTE_CAPABILITY_MAJOR)?
|
||||
== 12;
|
||||
let fused_commit = fused_commit_enabled(&resources)?;
|
||||
if fused_commit {
|
||||
resources.verifier_journal().load_draft_commit_asset()?;
|
||||
}
|
||||
let stream = self.compute.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
self.commit = Some(stream.capture_owned(OriginalCapturePolicy::VerifierCommit, resources, |capture, r| {
|
||||
r.verifier_journal().capture_commit_begin(capture)?;
|
||||
let mut gi = 0;
|
||||
let mut qi = 0;
|
||||
// draft-round: the layers are independent; one launch per kind (GDN, QSA) instead of 182 nodes. A QSA with retained angle tables keeps its per-layer commit.
|
||||
if fused_commit {
|
||||
r.verifier_journal().capture_commit_gdn_fused(capture)?;
|
||||
if r.verifier_qsa().capture_commit_fused(r.verifier_journal(), capture)? {
|
||||
for layer in (3..48).step_by(4) {
|
||||
record_extra(capture, r, layer)?;
|
||||
}
|
||||
if r.verifier_journal().ple.is_some() {
|
||||
r.verifier_journal().capture_ple_commit(capture)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
for layer in 0..48 {
|
||||
if layer % 4 == 3 {
|
||||
r.verifier_qsa().capture_commit_layer(r.verifier_journal(), capture, qi)?;
|
||||
record_extra(capture, r, layer)?;
|
||||
qi += 1
|
||||
}
|
||||
}
|
||||
if r.verifier_journal().ple.is_some() {
|
||||
r.verifier_journal().capture_ple_commit(capture)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
for layer in 0..48 {
|
||||
if layer % 4 == 3 {
|
||||
r.verifier_qsa().capture_commit_layer(r.verifier_journal(), capture, qi)?;
|
||||
record_extra(capture, r, layer)?;
|
||||
qi += 1
|
||||
} else {
|
||||
r.verifier_journal().capture_commit_layer(capture, gi)?;
|
||||
gi += 1
|
||||
}
|
||||
}
|
||||
if r.verifier_journal().ple.is_some() {
|
||||
r.verifier_journal().capture_ple_commit(capture)?;
|
||||
}
|
||||
Ok(())
|
||||
capture_commit_all(capture, r, fused_commit, &mut record_extra)
|
||||
})?);
|
||||
if crate::host_profile::enabled() {
|
||||
eprintln!("DBG graph commit nodes={:?}", self.commit.as_ref().and_then(|g| g.nodes()));
|
||||
@@ -199,3 +165,76 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// sm_120 only: the fused kernels have no sm_86 companion (ptx-sm86/MANIFEST.json), another card keeps the Original's
|
||||
/// commit graph.
|
||||
fn fused_commit_enabled<'ctx, R: OriginalVerifyGraphResources<'ctx>>(resources: &R) -> Result<bool> {
|
||||
Ok(crate::original_verify::draft::fused_commit()
|
||||
&& resources
|
||||
.verifier_journal()
|
||||
.window_device_attribute(crate::original_verify::gr::ATTR_COMPUTE_CAPABILITY_MAJOR)?
|
||||
== 12)
|
||||
}
|
||||
|
||||
/// The commit graph: begin, the GDN and QSA layers (fused or in the Original's order), then the PLE history commit.
|
||||
fn capture_commit_all<'ctx, R: OriginalVerifyGraphResources<'ctx>>(
|
||||
capture: &mut OriginalCapture<'_, 'ctx>,
|
||||
r: &mut R,
|
||||
fused_commit: bool,
|
||||
record_extra: &mut impl FnMut(&mut OriginalCapture<'_, 'ctx>, &mut R, usize) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
r.verifier_journal().capture_commit_begin(capture)?;
|
||||
if fused_commit {
|
||||
capture_fused_layers(capture, r, record_extra)?;
|
||||
} else {
|
||||
capture_plain_layers(capture, r, record_extra)?;
|
||||
}
|
||||
if r.verifier_journal().ple.is_some() {
|
||||
r.verifier_journal().capture_ple_commit(capture)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// draft-round: the layers are independent; one launch per kind (GDN, QSA) instead of 182 nodes. A QSA with retained
|
||||
/// angle tables keeps its per-layer commit.
|
||||
fn capture_fused_layers<'ctx, R: OriginalVerifyGraphResources<'ctx>>(
|
||||
capture: &mut OriginalCapture<'_, 'ctx>,
|
||||
r: &mut R,
|
||||
record_extra: &mut impl FnMut(&mut OriginalCapture<'_, 'ctx>, &mut R, usize) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
r.verifier_journal().capture_commit_gdn_fused(capture)?;
|
||||
if r.verifier_qsa().capture_commit_fused(r.verifier_journal(), capture)? {
|
||||
for layer in (3..48).step_by(4) {
|
||||
record_extra(capture, r, layer)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let mut qi = 0;
|
||||
for layer in 0..48 {
|
||||
if layer % 4 == 3 {
|
||||
r.verifier_qsa().capture_commit_layer(r.verifier_journal(), capture, qi)?;
|
||||
record_extra(capture, r, layer)?;
|
||||
qi += 1
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn capture_plain_layers<'ctx, R: OriginalVerifyGraphResources<'ctx>>(
|
||||
capture: &mut OriginalCapture<'_, 'ctx>,
|
||||
r: &mut R,
|
||||
record_extra: &mut impl FnMut(&mut OriginalCapture<'_, 'ctx>, &mut R, usize) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
let (mut gi, mut qi) = (0, 0);
|
||||
for layer in 0..48 {
|
||||
if layer % 4 == 3 {
|
||||
r.verifier_qsa().capture_commit_layer(r.verifier_journal(), capture, qi)?;
|
||||
record_extra(capture, r, layer)?;
|
||||
qi += 1
|
||||
} else {
|
||||
r.verifier_journal().capture_commit_layer(capture, gi)?;
|
||||
gi += 1
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user