merge: claude/pool-zero-copy (direct CPU expert pool: borrowed expert bytes, one dispatch per group, one-time admission, mmap page prefetch)
5090 decode mean 18.4 -> 56.5 tok/s on 6 prompts (verify window 169.5 -> 54.5 ms); laptop RTX 3080 mean 2.74 -> 8.10 tok/s (Original 8.15). Real-model crosscheck: 4320 groups / 57556 expert rows, 0 differing floats. LELEKA_CPU_POOL=legacy keeps the old path for A/B, =crosscheck runs both. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -211,6 +211,8 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() {
|
||||
Ok(outcome) => {
|
||||
if pass == 0 {
|
||||
eprintln!("DBG corpus {index} output ({} tokens, rounds {}): {}", out.len(), outcome.rounds, out.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(" "));
|
||||
} else {
|
||||
eprintln!("DBG corpus {index} output pass={pass} ({} tokens, rounds {}): {}", out.len(), outcome.rounds, out.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(" "));
|
||||
}
|
||||
let ttft = first.unwrap_or(total);
|
||||
let decode_s = (total - ttft).as_secs_f64();
|
||||
|
||||
@@ -118,7 +118,7 @@ fn native_error(error:leleka_native_cpu_expert::Error)->CpuMissError {
|
||||
E::Allocation|E::BudgetExceeded=>CpuMissError::Allocation,E::NonFinite=>CpuMissError::NonFinite,
|
||||
E::NativeFailure|E::Closed=>CpuMissError::NativeFailure }
|
||||
}
|
||||
fn validate_triplet([gate,up,down]:[MoeWeightDescriptor;3])->Result<(GateUpFormat,DownFormat)> {
|
||||
pub(crate) fn validate_triplet([gate,up,down]:[MoeWeightDescriptor;3])->Result<(GateUpFormat,DownFormat)> {
|
||||
if gate.expert.is_none() || gate.expert!=up.expert || gate.expert!=down.expert || gate.layer!=up.layer || gate.layer!=down.layer ||
|
||||
gate.role!=0 || up.role!=1 || down.role!=2 || gate.columns!=H || up.columns!=H || gate.rows!=FF || up.rows!=FF ||
|
||||
down.columns!=FF || down.rows!=H || gate.raw_kind!=up.raw_kind || gate.bytes!=up.bytes { return Err(CpuMissError::Shape); }
|
||||
|
||||
@@ -274,6 +274,8 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> {
|
||||
where
|
||||
R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>,
|
||||
{
|
||||
let window_clock = super::original_serve_pool::window_trace::now();
|
||||
let _ = super::original_serve_pool::window_trace::take();
|
||||
let session_position = self.position()?;
|
||||
self.ledger.begin_window(position, inputs, consumed, session_position)?;
|
||||
let first = usize::try_from(position).map_err(|_| Error::InvalidPosition)?;
|
||||
@@ -284,6 +286,8 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let ple_ms = window_clock.map(|c| c.elapsed().as_secs_f64() * 1e3);
|
||||
let mut verifier_ms = 0.0f64;
|
||||
let (params, path, enabled) = (self.sampling.params, self.sampling.path, self.sampling.enabled());
|
||||
let mut pool_error: Option<Error> = None;
|
||||
let mut driver_failure: Option<ServeFailure> = None;
|
||||
@@ -300,13 +304,23 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> {
|
||||
enabled,
|
||||
|| if committed == consumed { Ok(()) } else { Err(Error::IdentityMismatch) },
|
||||
|sampling| {
|
||||
verifier
|
||||
let verifier_clock = super::original_serve_pool::window_trace::now();
|
||||
let ran = verifier
|
||||
.run(inputs, first, ple.as_deref(), sampling, |rows, sink, copy| {
|
||||
pool.run_group(rows, sink, copy).map_err(|error| {
|
||||
let group_clock = super::original_serve_pool::window_trace::now();
|
||||
let ran = pool.run_group(rows, sink, copy).map_err(|error| {
|
||||
pool_error = Some(error);
|
||||
leleka_cuda_driver::Error::InvalidDriverValue("Original serve expert pool refused a layer group")
|
||||
})
|
||||
})
|
||||
});
|
||||
if let Some(c) = group_clock {
|
||||
super::original_serve_pool::window_trace::add(super::original_serve_pool::window_trace::POOL, c.elapsed().as_secs_f64() * 1e3);
|
||||
}
|
||||
ran
|
||||
});
|
||||
if let Some(c) = verifier_clock {
|
||||
verifier_ms = c.elapsed().as_secs_f64() * 1e3;
|
||||
}
|
||||
ran
|
||||
.map_err(|error| {
|
||||
let failure = ServeFailure::from(error);
|
||||
let class = failure.error;
|
||||
@@ -315,6 +329,22 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> {
|
||||
})
|
||||
},
|
||||
);
|
||||
if let (Some(c), Some(ple_ms)) = (window_clock, ple_ms) {
|
||||
let total = c.elapsed().as_secs_f64() * 1e3;
|
||||
let sums = super::original_serve_pool::window_trace::take();
|
||||
let parts: Vec<String> = super::original_serve_pool::window_trace::NAMES
|
||||
.iter()
|
||||
.zip(sums)
|
||||
.map(|(name, v)| format!("{name}={v:.2}"))
|
||||
.collect();
|
||||
eprintln!(
|
||||
"DBG window rows={} total={total:.2} ple={ple_ms:.2} sampling_setup={:.2} verifier={verifier_ms:.2} gpu_wait_and_head={:.2} {}",
|
||||
inputs.len(),
|
||||
total - ple_ms - verifier_ms,
|
||||
verifier_ms - sums[super::original_serve_pool::window_trace::POOL],
|
||||
parts.join(" ")
|
||||
);
|
||||
}
|
||||
match result {
|
||||
Ok(window) => {
|
||||
self.window_origin = Some(origin);
|
||||
|
||||
@@ -14,11 +14,13 @@
|
||||
//! (`original_serve_residency::GpuExpertPool`), which hands this pool only the entries it must compute.
|
||||
use super::{
|
||||
contract::{Error, Result},
|
||||
cpu_expert_miss::{runtime_error, CpuMissWorkspace},
|
||||
cpu_expert_miss::{runtime_error, validate_triplet, CpuMissWorkspace},
|
||||
input::binding_error,
|
||||
};
|
||||
use crate::model_binding::qwen4exp_input::{ModelBinding, MoeMatrixRole};
|
||||
use crate::model_binding::qwen4exp_input::{ModelBinding, MoeExpertWeights, MoeMatrixRole};
|
||||
use leleka_cuda_driver::{OriginalGpuStream, OriginalVerifyCpuRows, OriginalVerifyCpuSink};
|
||||
use leleka_model_format::qwen4exp::ResidentExpertBankSpan;
|
||||
use leleka_native_cpu_expert::{BorrowedExpert, BorrowedGroup, DirectCpuPool, DownFormat, GateUpFormat};
|
||||
|
||||
const HIDDEN: usize = 2560;
|
||||
const TOP_K: usize = 10;
|
||||
@@ -28,6 +30,53 @@ const EXPERTS: i32 = 512;
|
||||
const JOBS_PER_BATCH: usize = 12;
|
||||
const BATCH_ALLOWANCE: usize = 48 << 20;
|
||||
|
||||
/// Bring-up timing of the window's host work (`LELEKA_BRINGUP_TRACE` only): per-window sums in ms, printed
|
||||
/// and reset by the host after each window. Remove together with the other DBG lines.
|
||||
pub(in crate::qwen_forward) mod window_trace {
|
||||
use std::cell::Cell;
|
||||
use std::time::Instant;
|
||||
pub(in crate::qwen_forward) const NAMES: [&str; 13] =
|
||||
["pool", "gpu_split", "plan", "prepare", "start", "join", "validate", "scatter", "experts", "entries", "fetch", "pcie_spans", "pcie_experts"];
|
||||
pub(in crate::qwen_forward) const POOL: usize = 0;
|
||||
pub(in crate::qwen_forward) const GPU_SPLIT: usize = 1;
|
||||
pub(in crate::qwen_forward) const PLAN: usize = 2;
|
||||
pub(in crate::qwen_forward) const PREPARE: usize = 3;
|
||||
pub(in crate::qwen_forward) const START: usize = 4;
|
||||
pub(in crate::qwen_forward) const JOIN: usize = 5;
|
||||
pub(in crate::qwen_forward) const VALIDATE: usize = 6;
|
||||
pub(in crate::qwen_forward) const SCATTER: usize = 7;
|
||||
pub(in crate::qwen_forward) const EXPERTS: usize = 8;
|
||||
pub(in crate::qwen_forward) const ENTRIES: usize = 9;
|
||||
pub(in crate::qwen_forward) const FETCH: usize = 10;
|
||||
pub(in crate::qwen_forward) const PCIE_SPANS: usize = 11;
|
||||
pub(in crate::qwen_forward) const PCIE_EXPERTS: usize = 12;
|
||||
thread_local! { static SUMS: Cell<[f64; 13]> = const { Cell::new([0.0; 13]) }; }
|
||||
/// A clock only when tracing.
|
||||
pub(in crate::qwen_forward) fn now() -> Option<Instant> {
|
||||
crate::bringup_trace_enabled().then(Instant::now)
|
||||
}
|
||||
/// Add the time since `from` to `slot` and restart the clock.
|
||||
pub(in crate::qwen_forward) fn lap(slot: usize, from: &mut Option<Instant>) {
|
||||
if let Some(at) = from {
|
||||
let next = Instant::now();
|
||||
add(slot, (next - *at).as_secs_f64() * 1e3);
|
||||
*at = next;
|
||||
}
|
||||
}
|
||||
pub(in crate::qwen_forward) fn add(slot: usize, value: f64) {
|
||||
if crate::bringup_trace_enabled() {
|
||||
SUMS.with(|s| {
|
||||
let mut v = s.get();
|
||||
v[slot] += value;
|
||||
s.set(v);
|
||||
});
|
||||
}
|
||||
}
|
||||
pub(in crate::qwen_forward) fn take() -> [f64; 13] {
|
||||
SUMS.with(|s| s.replace([0.0; 13]))
|
||||
}
|
||||
}
|
||||
|
||||
/// The expert tier of a window group.
|
||||
pub(in crate::qwen_forward) trait OriginalServePool<'ctx> {
|
||||
/// Complete every routed `(row, slot)` of this group into `sink` before returning; an error leaves
|
||||
@@ -117,17 +166,84 @@ pub(in crate::qwen_forward) fn scatter(out: &mut [f32], job: &ExpertJob, values:
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How the CPU tier runs a group (`LELEKA_CPU_POOL`, read once when the pool opens).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(in crate::qwen_forward) enum PoolPath {
|
||||
/// Default: every routed expert of the group computed straight from the resident expert bank in one
|
||||
/// dispatch over the worker pool, written in place into the mapped destination (no expert copy).
|
||||
Direct,
|
||||
/// `LELEKA_CPU_POOL=legacy` (A/B arm): owned copies of every expert, batches of 12, re-validation, scatter.
|
||||
Legacy,
|
||||
/// `LELEKA_CPU_POOL=crosscheck` (diagnostic): the direct path, then the legacy path on the same group,
|
||||
/// every computed float compared bit for bit; a difference fails the group.
|
||||
Crosscheck,
|
||||
}
|
||||
impl PoolPath {
|
||||
pub(in crate::qwen_forward) fn from_env() -> Self {
|
||||
match std::env::var("LELEKA_CPU_POOL").as_deref() {
|
||||
Ok("legacy") => Self::Legacy,
|
||||
Ok("crosscheck") => Self::Crosscheck,
|
||||
_ => Self::Direct,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The direct path's state: the synchronous worker pool and the admitted experts. An expert's three
|
||||
/// encoded matrices are admitted (every block's FP16 scale finite: the guard `PreparedJob::new` applied to
|
||||
/// each copy) the first time it is routed to the CPU; the admitted spans are retained, so their bank memory
|
||||
/// stays alive and a later span of the same expert at the same address is the same immutable bytes.
|
||||
struct DirectTier {
|
||||
pool: DirectCpuPool,
|
||||
admitted: Vec<Admission>,
|
||||
}
|
||||
|
||||
/// One routed expert's retained state: its admitted spans and the route bound to it (a top-10 that selects
|
||||
/// it in slot 0). The route is immutable bound metadata; every use still opens a source scope that checks
|
||||
/// it against the binding and the actual descriptors.
|
||||
#[derive(Default)]
|
||||
pub(in crate::qwen_forward) struct Admission {
|
||||
spans: Option<[ResidentExpertBankSpan; 3]>,
|
||||
route: Option<MoeExpertWeights>,
|
||||
}
|
||||
|
||||
/// The all-CPU expert tier over the pinned model's mapped routed weights.
|
||||
pub(in crate::qwen_forward) struct CpuExpertPool<'a> {
|
||||
binding: &'a ModelBinding,
|
||||
cpu: CpuMissWorkspace,
|
||||
direct: Option<DirectTier>,
|
||||
legacy: Option<CpuMissWorkspace>,
|
||||
crosscheck: CrosscheckCounts,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct CrosscheckCounts {
|
||||
groups: u64,
|
||||
rows: u64,
|
||||
}
|
||||
impl<'a> CpuExpertPool<'a> {
|
||||
pub(in crate::qwen_forward) fn new(binding: &'a ModelBinding, workers: i32) -> Result<Self> {
|
||||
Self::with_path(binding, workers, PoolPath::from_env())
|
||||
}
|
||||
pub(in crate::qwen_forward) fn with_path(binding: &'a ModelBinding, workers: i32, path: PoolPath) -> Result<Self> {
|
||||
if binding.expert_count() != EXPERTS as u32 || binding.expert_used_count() != TOP_K as u32 {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
Ok(Self { binding, cpu: CpuMissWorkspace::new(binding, workers).map_err(runtime_error)? })
|
||||
let direct = match path {
|
||||
PoolPath::Legacy => None,
|
||||
PoolPath::Direct | PoolPath::Crosscheck => {
|
||||
let pool = DirectCpuPool::new(workers).map_err(|e| runtime_error(native_cpu_error(e)))?;
|
||||
let mut admitted = Vec::new();
|
||||
admitted.try_reserve_exact(48 * EXPERTS as usize).map_err(|_| Error::InputAllocation)?;
|
||||
admitted.resize_with(48 * EXPERTS as usize, Admission::default);
|
||||
Some(DirectTier { pool, admitted })
|
||||
}
|
||||
};
|
||||
let legacy = match path {
|
||||
PoolPath::Direct => None,
|
||||
PoolPath::Legacy | PoolPath::Crosscheck => Some(CpuMissWorkspace::new(binding, workers).map_err(runtime_error)?),
|
||||
};
|
||||
if path != PoolPath::Direct {
|
||||
eprintln!("leleka-serve cpu expert pool: {path:?} path (LELEKA_CPU_POOL)");
|
||||
}
|
||||
Ok(Self { binding, direct, legacy, crosscheck: CrosscheckCounts::default() })
|
||||
}
|
||||
}
|
||||
impl<'ctx> OriginalServePool<'ctx> for CpuExpertPool<'_> {
|
||||
@@ -158,9 +274,145 @@ impl CpuExpertPool<'_> {
|
||||
{
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let mut clock = window_trace::now();
|
||||
let plan = plan_experts_where(rows.ids, count, include)?;
|
||||
window_trace::lap(window_trace::PLAN, &mut clock);
|
||||
window_trace::add(window_trace::EXPERTS, plan.len() as f64);
|
||||
window_trace::add(window_trace::ENTRIES, plan.iter().map(|j| j.pairs.len()).sum::<usize>() as f64);
|
||||
if self.direct.is_some() {
|
||||
self.run_direct(&rows, sink, include, &plan, &mut clock)?;
|
||||
if self.legacy.is_some() {
|
||||
let results = self.legacy_results(&rows, &plan, &mut clock)?;
|
||||
return self.compare(sink, &plan, &results);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let results = self.legacy_results(&rows, &plan, &mut clock)?;
|
||||
let mut failure = None;
|
||||
let written = sink.with_output(|out| {
|
||||
if out.len() != count * TOP_K * HIDDEN {
|
||||
failure = Some(Error::InvalidDimension);
|
||||
return Err(leleka_cuda_driver::Error::InvalidQwenShape);
|
||||
}
|
||||
if let Some(mask) = include {
|
||||
for (entry, _) in mask.iter().enumerate().filter(|(_, computed)| !**computed) {
|
||||
out[entry * HIDDEN..(entry + 1) * HIDDEN].fill(0.0);
|
||||
}
|
||||
}
|
||||
for (job_index, values) in &results {
|
||||
if let Err(error) = scatter(out, &plan[*job_index], values) {
|
||||
failure = Some(error);
|
||||
return Err(leleka_cuda_driver::Error::InvalidQwenShape);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
window_trace::lap(window_trace::SCATTER, &mut clock);
|
||||
sink_result(written, failure)
|
||||
}
|
||||
|
||||
/// The direct path: per expert one source scope (`admitted_expert`), then the whole group in one
|
||||
/// synchronous dispatch writing every computed row in place.
|
||||
fn run_direct(
|
||||
&mut self,
|
||||
rows: &OriginalVerifyCpuRows<'_>,
|
||||
sink: &mut OriginalVerifyCpuSink<'_, '_>,
|
||||
include: Option<&[bool]>,
|
||||
plan: &[ExpertJob],
|
||||
clock: &mut Option<std::time::Instant>,
|
||||
) -> Result<()> {
|
||||
let binding = self.binding;
|
||||
let layer = rows.layer as u32;
|
||||
let plan = plan_experts_where(rows.ids, count, include)?;
|
||||
let count = rows.ids.len() / TOP_K;
|
||||
let tier = self.direct.as_mut().ok_or(Error::IdentityMismatch)?;
|
||||
let mut sources: Vec<[ResidentExpertBankSpan; 3]> = Vec::new();
|
||||
sources.try_reserve_exact(plan.len()).map_err(|_| Error::InputAllocation)?;
|
||||
let mut formats = None;
|
||||
let mut ready: Vec<bool> = Vec::new();
|
||||
ready.try_reserve_exact(plan.len()).map_err(|_| Error::InputAllocation)?;
|
||||
let mut mapped = false;
|
||||
for job in plan {
|
||||
let expert = u32::try_from(job.expert).map_err(|_| Error::InvalidExpert)?;
|
||||
let admitted = tier.admitted.get_mut(layer as usize * EXPERTS as usize + expert as usize).ok_or(Error::InvalidExpert)?;
|
||||
let (spans, format, admitted_now) = open_expert(binding, layer, expert, admitted, false)?;
|
||||
if *formats.get_or_insert(format) != format {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
ready.push(admitted_now);
|
||||
mapped |= spans.iter().any(ResidentExpertBankSpan::file_mapped);
|
||||
sources.push(spans);
|
||||
}
|
||||
let mut experts: Vec<BorrowedExpert<'_>> = Vec::new();
|
||||
experts.try_reserve_exact(plan.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for (job, spans) in plan.iter().zip(&sources) {
|
||||
experts.push(BorrowedExpert { gate: spans[0].bytes(), up: spans[1].bytes(), down: spans[2].bytes(), pairs: &job.pairs });
|
||||
}
|
||||
window_trace::lap(window_trace::PREPARE, clock);
|
||||
if let (true, Some((gu, down))) = (mapped, formats) {
|
||||
// The file-mapped source (the Original's --mmap-experts): every page of the group's experts is
|
||||
// advised and faulted in on all workers at once, before the admission scans and the compute.
|
||||
for chunk in experts.chunks(leleka_native_cpu_expert::MAX_JOBS) {
|
||||
tier.pool.prefetch(gu, down, chunk).map_err(|e| runtime_error(native_cpu_error(e)))?;
|
||||
}
|
||||
}
|
||||
window_trace::lap(window_trace::FETCH, clock);
|
||||
// First use: admit every row of the experts not yet admitted (their pages are now resident).
|
||||
for ((job, spans), _) in plan.iter().zip(&sources).zip(&ready).filter(|(_, ready)| !**ready) {
|
||||
let expert = job.expert as u32;
|
||||
let admitted = tier.admitted.get_mut(layer as usize * EXPERTS as usize + expert as usize).ok_or(Error::InvalidExpert)?;
|
||||
let (again, _, _) = open_expert(binding, layer, expert, admitted, true)?;
|
||||
if again.iter().zip(spans).any(|(a, b)| a.bytes().as_ptr() != b.bytes().as_ptr() || a.bytes().len() != b.bytes().len()) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
}
|
||||
window_trace::lap(window_trace::PREPARE, clock);
|
||||
let mut failure = None;
|
||||
let written = sink.with_output(|out| {
|
||||
if out.len() != count * TOP_K * HIDDEN {
|
||||
failure = Some(Error::InvalidDimension);
|
||||
return Err(leleka_cuda_driver::Error::InvalidQwenShape);
|
||||
}
|
||||
if let Some(mask) = include {
|
||||
for (entry, _) in mask.iter().enumerate().filter(|(_, computed)| !**computed) {
|
||||
out[entry * HIDDEN..(entry + 1) * HIDDEN].fill(0.0);
|
||||
}
|
||||
}
|
||||
if let Some((gu, down)) = formats {
|
||||
// At most 80 distinct experts per group, so one dispatch (MAX_JOBS is 96).
|
||||
for chunk in experts.chunks(leleka_native_cpu_expert::MAX_JOBS) {
|
||||
let group = BorrowedGroup { tokens: rows.activation, experts: chunk, stride: TOP_K };
|
||||
if let Err(e) = tier.pool.compute_group(gu, down, &group, out) {
|
||||
failure = Some(runtime_error(native_cpu_error(e)));
|
||||
return Err(leleka_cuda_driver::Error::InvalidQwenShape);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
window_trace::lap(window_trace::JOIN, clock);
|
||||
sink_result(written, failure)
|
||||
}
|
||||
|
||||
/// The PCIe tier's source spans of `expert`, through the same per-call validation and one-time row
|
||||
/// admission as the CPU's own experts; `None` on the legacy path (the caller keeps its full scan).
|
||||
pub(in crate::qwen_forward) fn admitted_spans(&mut self, layer: u32, expert: u32) -> Option<Result<[ResidentExpertBankSpan; 3]>> {
|
||||
let binding = self.binding;
|
||||
let tier = self.direct.as_mut()?;
|
||||
let admitted = tier.admitted.get_mut(layer as usize * EXPERTS as usize + expert as usize)?;
|
||||
Some(admitted_expert(binding, layer, expert, admitted).map(|(spans, _)| spans))
|
||||
}
|
||||
|
||||
/// The legacy path's results: owned copies, batches of `JOBS_PER_BATCH` joined in turn, every result
|
||||
/// re-validated against a re-opened source. `(plan index, rows)` for the caller to scatter.
|
||||
fn legacy_results(
|
||||
&mut self,
|
||||
rows: &OriginalVerifyCpuRows<'_>,
|
||||
plan: &[ExpertJob],
|
||||
clock: &mut Option<std::time::Instant>,
|
||||
) -> Result<Vec<(usize, Box<[f32]>)>> {
|
||||
let binding = self.binding;
|
||||
let layer = rows.layer as u32;
|
||||
let cpu = self.legacy.as_mut().ok_or(Error::IdentityMismatch)?;
|
||||
// Every batch is prepared, run and joined before the next; results are held until the whole
|
||||
// group is complete so the mapped destination is written in one bounded pass.
|
||||
let mut results: Vec<(usize, Box<[f32]>)> = Vec::new();
|
||||
@@ -179,14 +431,17 @@ impl CpuExpertPool<'_> {
|
||||
inputs.push(&rows.activation[row * HIDDEN..(row + 1) * HIDDEN]);
|
||||
}
|
||||
let prepared = binding.with_moe_routed_source(&members, binding_error, |source| {
|
||||
let prepared = self.cpu.prepare_scoped(binding, source, 0, &inputs).map_err(runtime_error)?;
|
||||
let prepared = cpu.prepare_scoped(binding, source, 0, &inputs).map_err(runtime_error)?;
|
||||
source.finish().map_err(binding_error)?;
|
||||
Ok(prepared)
|
||||
})?;
|
||||
jobs.push(prepared);
|
||||
}
|
||||
let pending = self.cpu.start(jobs, BATCH_ALLOWANCE).map_err(runtime_error)?;
|
||||
window_trace::lap(window_trace::PREPARE, clock);
|
||||
let pending = cpu.start(jobs, BATCH_ALLOWANCE).map_err(runtime_error)?;
|
||||
window_trace::lap(window_trace::START, clock);
|
||||
let completed = pending.join().map_err(runtime_error)?;
|
||||
window_trace::lap(window_trace::JOIN, clock);
|
||||
if completed.len() != batch.len() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
@@ -210,31 +465,143 @@ impl CpuExpertPool<'_> {
|
||||
})?;
|
||||
results.push((batch_index * JOBS_PER_BATCH + k, done.into_values()));
|
||||
}
|
||||
window_trace::lap(window_trace::VALIDATE, clock);
|
||||
}
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
/// Crosscheck: the direct rows already in the destination against the legacy rows, bit for bit.
|
||||
fn compare(&mut self, sink: &mut OriginalVerifyCpuSink<'_, '_>, plan: &[ExpertJob], results: &[(usize, Box<[f32]>)]) -> Result<()> {
|
||||
let mut differing = 0usize;
|
||||
let mut compared = 0usize;
|
||||
let mut failure = None;
|
||||
let written = sink.with_output(|out| {
|
||||
if out.len() != count * TOP_K * HIDDEN {
|
||||
failure = Some(Error::InvalidDimension);
|
||||
return Err(leleka_cuda_driver::Error::InvalidQwenShape);
|
||||
}
|
||||
if let Some(mask) = include {
|
||||
for (entry, _) in mask.iter().enumerate().filter(|(_, computed)| !**computed) {
|
||||
out[entry * HIDDEN..(entry + 1) * HIDDEN].fill(0.0);
|
||||
}
|
||||
}
|
||||
for (job_index, values) in &results {
|
||||
if let Err(error) = scatter(out, &plan[*job_index], values) {
|
||||
failure = Some(error);
|
||||
let read = sink.with_output(|out| {
|
||||
for (job_index, values) in results {
|
||||
let job = &plan[*job_index];
|
||||
if values.len() != job.pairs.len() * HIDDEN {
|
||||
failure = Some(Error::InvalidDimension);
|
||||
return Err(leleka_cuda_driver::Error::InvalidQwenShape);
|
||||
}
|
||||
for (i, &(row, slot)) in job.pairs.iter().enumerate() {
|
||||
let at = output_offset(row, slot);
|
||||
let direct = out.get(at..at + HIDDEN).ok_or(leleka_cuda_driver::Error::InvalidQwenShape)?;
|
||||
differing += direct.iter().zip(&values[i * HIDDEN..(i + 1) * HIDDEN]).filter(|(a, b)| a.to_bits() != b.to_bits()).count();
|
||||
compared += 1;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
match (written, failure) {
|
||||
(Ok(()), None) => Ok(()),
|
||||
(_, Some(error)) => Err(error),
|
||||
(Err(_), None) => Err(Error::CudaExecution),
|
||||
sink_result(read, failure)?;
|
||||
self.crosscheck.groups += 1;
|
||||
self.crosscheck.rows += compared as u64;
|
||||
if differing != 0 {
|
||||
eprintln!("CROSSCHECK cpu pool: {differing} floats differ in a group of {} experts", plan.len());
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if self.crosscheck.groups % 48 == 0 {
|
||||
eprintln!("CROSSCHECK cpu pool: {} groups, {} expert rows bit-identical (direct vs legacy)", self.crosscheck.groups, self.crosscheck.rows);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// One routed expert's resident source, opened and validated on every call (binding, the actual
|
||||
/// gate/up/down descriptors of exactly this layer and expert, their formats, the bank spans) while its
|
||||
/// encoded rows are admitted only on first use: `admitted` retains the checked spans, so the bank bytes
|
||||
/// they address stay alive and immutable, and a later span at the same address needs no new scan.
|
||||
pub(in crate::qwen_forward) fn admitted_expert(
|
||||
binding: &ModelBinding,
|
||||
layer: u32,
|
||||
expert: u32,
|
||||
admitted: &mut Admission,
|
||||
) -> Result<([ResidentExpertBankSpan; 3], (GateUpFormat, DownFormat))> {
|
||||
let (spans, format, _) = open_expert(binding, layer, expert, admitted, true)?;
|
||||
Ok((spans, format))
|
||||
}
|
||||
|
||||
/// `admitted_expert` that, with `admit` false, leaves a not yet admitted expert unscanned and says so
|
||||
/// (third value false): the caller prefetches it and admits it before any consumer reads it.
|
||||
fn open_expert(
|
||||
binding: &ModelBinding,
|
||||
layer: u32,
|
||||
expert: u32,
|
||||
admission: &mut Admission,
|
||||
admit: bool,
|
||||
) -> Result<([ResidentExpertBankSpan; 3], (GateUpFormat, DownFormat), bool)> {
|
||||
if layer >= 48 || expert >= EXPERTS as u32 {
|
||||
return Err(Error::InvalidExpert);
|
||||
}
|
||||
if admission.route.is_none() {
|
||||
// A route that selects `expert` in slot 0 (cache_original_prompt.rs `original_expert_spans`).
|
||||
let selected = std::array::from_fn(|i| (expert + i as u32) % EXPERTS as u32);
|
||||
admission.route = Some(binding.moe_expert_weights(layer, selected).map_err(binding_error)?);
|
||||
}
|
||||
let Admission { spans: admitted, route } = admission;
|
||||
let bound = route.as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
let members = [(bound, 0)];
|
||||
binding.with_moe_routed_source(&members, binding_error, |source| {
|
||||
let operation = (|| {
|
||||
source.validate_binding(binding).map_err(binding_error)?;
|
||||
let keys = [
|
||||
source.descriptor(0, MoeMatrixRole::Gate).map_err(binding_error)?,
|
||||
source.descriptor(0, MoeMatrixRole::Up).map_err(binding_error)?,
|
||||
source.descriptor(0, MoeMatrixRole::Down).map_err(binding_error)?,
|
||||
];
|
||||
if keys.iter().any(|k| k.layer != layer || k.expert != Some(expert)) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let format = validate_triplet(keys).map_err(runtime_error)?;
|
||||
let spans = [
|
||||
source.bank_span(0, MoeMatrixRole::Gate).map_err(binding_error)?,
|
||||
source.bank_span(0, MoeMatrixRole::Up).map_err(binding_error)?,
|
||||
source.bank_span(0, MoeMatrixRole::Down).map_err(binding_error)?,
|
||||
];
|
||||
let same = |held: &[ResidentExpertBankSpan; 3]| {
|
||||
held.iter().zip(&spans).all(|(a, b)| a.bytes().as_ptr() == b.bytes().as_ptr() && a.bytes().len() == b.bytes().len())
|
||||
};
|
||||
if !admitted.as_ref().is_some_and(same) {
|
||||
*admitted = None;
|
||||
if !admit {
|
||||
return Ok((spans, format, false));
|
||||
}
|
||||
// First use (or a different span): admit every row of the actual matrices.
|
||||
let checked = [
|
||||
source.mapped_span(0, MoeMatrixRole::Gate).map_err(binding_error)?,
|
||||
source.mapped_span(0, MoeMatrixRole::Up).map_err(binding_error)?,
|
||||
source.mapped_span(0, MoeMatrixRole::Down).map_err(binding_error)?,
|
||||
];
|
||||
if !same(&checked) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
*admitted = Some(checked);
|
||||
}
|
||||
Ok((spans, format, true))
|
||||
})();
|
||||
let finish = source.finish().map_err(binding_error);
|
||||
match operation {
|
||||
Err(e) => Err(e),
|
||||
Ok(v) => finish.map(|()| v),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn sink_result(written: leleka_cuda_driver::Result<()>, failure: Option<Error>) -> Result<()> {
|
||||
match (written, failure) {
|
||||
(Ok(()), None) => Ok(()),
|
||||
(_, Some(error)) => Err(error),
|
||||
(Err(_), None) => Err(Error::CudaExecution),
|
||||
}
|
||||
}
|
||||
|
||||
fn native_cpu_error(error: leleka_native_cpu_expert::Error) -> super::cpu_expert_miss::CpuMissError {
|
||||
use super::cpu_expert_miss::CpuMissError as C;
|
||||
use leleka_native_cpu_expert::Error as E;
|
||||
match error {
|
||||
E::Shape => C::Shape,
|
||||
E::Unsupported => C::Unsupported,
|
||||
E::Allocation | E::BudgetExceeded => C::Allocation,
|
||||
E::NonFinite => C::NonFinite,
|
||||
E::NativeFailure | E::Closed => C::NativeFailure,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -342,6 +342,7 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> {
|
||||
if layer >= LAYERS || rows.ids.is_empty() || rows.ids.len() % TOP_K != 0 {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let mut clock = super::original_serve_pool::window_trace::now();
|
||||
if !self.state.usage.is_empty() {
|
||||
for &e in rows.ids {
|
||||
if (0..EXPERTS as i32).contains(&e) {
|
||||
@@ -358,11 +359,24 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> {
|
||||
self.pcie_num,
|
||||
sink.staging_capacity(),
|
||||
)?;
|
||||
super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::GPU_SPLIT, &mut clock);
|
||||
let mut spans = Vec::new();
|
||||
spans.try_reserve_exact(split.pcie_experts.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for &e in &split.pcie_experts {
|
||||
spans.push(self.moe.original_expert_spans(self.binding, layer as u32, e)?);
|
||||
// The direct CPU tier's admission (rows scanned once per expert) serves the PCIe sources too.
|
||||
match self.cpu.admitted_spans(layer as u32, e) {
|
||||
Some(admitted) => {
|
||||
let admitted = admitted?;
|
||||
if !self.bank.eligible(&admitted) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
spans.push(admitted);
|
||||
}
|
||||
None => spans.push(self.moe.original_expert_spans(self.binding, layer as u32, e)?),
|
||||
}
|
||||
}
|
||||
super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::PCIE_SPANS, &mut clock);
|
||||
super::original_serve_pool::window_trace::add(super::original_serve_pool::window_trace::PCIE_EXPERTS, split.pcie_experts.len() as f64);
|
||||
let pcie = (self.pcie_num > 0).then_some(OriginalVerifyPcieSource { bank: &self.bank, spans: &spans });
|
||||
sink.publish_gpu_plan(&split.plan, cache, pcie, copy).map_err(|e| driver_error(&e))?;
|
||||
let include: Vec<bool> = split.kinds.iter().map(|&k| k < 0).collect();
|
||||
@@ -375,6 +389,7 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> {
|
||||
_ => stats.cpu_entries += 1,
|
||||
}
|
||||
}
|
||||
super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::GPU_SPLIT, &mut clock);
|
||||
self.cpu.run_entries(rows, sink, Some(&include))
|
||||
}
|
||||
fn apply_pending(&mut self) -> Result<()> {
|
||||
@@ -392,7 +407,16 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> {
|
||||
let swaps = choose_swaps(&self.state.usage, |l, e| cache.resident_slot(l, e).is_some(), self.adapt_swaps);
|
||||
for swap in &swaps {
|
||||
let slot = self.cache.resident_slot(swap.layer, swap.outgoing).ok_or(Error::IdentityMismatch)?;
|
||||
let spans = self.moe.original_expert_spans(self.binding, swap.layer as u32, swap.incoming as u32)?;
|
||||
let spans = match self.cpu.admitted_spans(swap.layer as u32, swap.incoming as u32) {
|
||||
Some(admitted) => {
|
||||
let admitted = admitted?;
|
||||
if !self.bank.eligible(&admitted) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
admitted
|
||||
}
|
||||
None => self.moe.original_expert_spans(self.binding, swap.layer as u32, swap.incoming as u32)?,
|
||||
};
|
||||
self.cache.swap_slot_queued(slot, Rc::clone(&self.bank), spans).map_err(|e| driver_error(&e))?;
|
||||
}
|
||||
self.cache.arm_swaps().map_err(|e| driver_error(&e))?;
|
||||
|
||||
@@ -579,6 +579,11 @@ impl ResidentExpertBankSpan {
|
||||
pub fn raw_kind(&self) -> u32 {
|
||||
self.member.raw_kind()
|
||||
}
|
||||
/// The bytes are a read-only shared mapping of the verified shard (the low-RAM source), so a read
|
||||
/// may fault the page in from the file.
|
||||
pub fn file_mapped(&self) -> bool {
|
||||
self.member.file_mapped()
|
||||
}
|
||||
pub fn belongs_to(&self, member: &ResidentExpertBankMember) -> bool {
|
||||
self.member.descriptor == member.descriptor
|
||||
&& Rc::ptr_eq(&self.member.tensor, &member.tensor)
|
||||
|
||||
@@ -5,6 +5,22 @@ pub(super) struct NativePool {pool:Option<super::rust_pool::NativePool>}
|
||||
impl NativePool {
|
||||
pub(super) fn new(workers:i32)->Result<Self>{Ok(Self{pool:Some(super::rust_pool::NativePool::new(workers)?)})}
|
||||
pub(super) fn workers(&self)->Result<usize>{self.pool.as_ref().ok_or(Error::Closed)?.workers()}
|
||||
/// A caught panic drops (stops and joins) the native pool before returning, so no worker can still
|
||||
/// touch the borrowed group afterwards; the pool is then closed.
|
||||
pub(super) fn compute_borrowed(&mut self,gu:i32,down:i32,group:&super::BorrowedGroup<'_>,out:&mut [f32])->Result<()> {
|
||||
let pool=self.pool.as_mut().ok_or(Error::Closed)?;
|
||||
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(||pool.compute_borrowed(gu,down,group,out))) {
|
||||
Ok(result)=>result,
|
||||
Err(_)=>{drop(self.pool.take());Err(Error::NativeFailure)}
|
||||
}
|
||||
}
|
||||
pub(super) fn prefetch_borrowed(&mut self,gu:i32,down:i32,experts:&[super::BorrowedExpert<'_>])->Result<()> {
|
||||
let pool=self.pool.as_mut().ok_or(Error::Closed)?;
|
||||
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(||pool.prefetch_borrowed(gu,down,experts))) {
|
||||
Ok(result)=>result,
|
||||
Err(_)=>{drop(self.pool.take());Err(Error::NativeFailure)}
|
||||
}
|
||||
}
|
||||
pub(super) fn compute_batch(&mut self,jobs:&mut [PreparedJob])->Result<()> {
|
||||
let pool=self.pool.as_mut().ok_or(Error::Closed)?;
|
||||
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(||pool.compute_batch(jobs))) {
|
||||
|
||||
@@ -106,6 +106,47 @@ impl PreparedJob {
|
||||
.ok_or(Error::BudgetExceeded)
|
||||
}
|
||||
}
|
||||
/// One routed expert of a borrowed group: its three encoded matrices in place (no copy) and the
|
||||
/// `(token, slot)` pairs that selected it, in the order its rows are computed.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct BorrowedExpert<'a> { pub gate: &'a [u8], pub up: &'a [u8], pub down: &'a [u8], pub pairs: &'a [(usize, usize)] }
|
||||
/// A whole layer group: `tokens` are its activation rows (`rows * 2560` floats), each pair's result goes
|
||||
/// to output row `token * stride + slot`.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct BorrowedGroup<'a> { pub tokens: &'a [f32], pub experts: &'a [BorrowedExpert<'a>], pub stride: usize }
|
||||
/// Output rows a borrowed group may address (8 rows x top-10 is 80).
|
||||
pub const MAX_OUT_ROWS: usize = 128;
|
||||
|
||||
/// Actor-owned synchronous pool for borrowed groups: the calling thread publishes the group and drains
|
||||
/// beside the workers (pool.cpp `host_works_`), so nothing crosses a thread boundary by value and every
|
||||
/// borrow ends when `compute_group` returns. The encoded bytes are the caller's admitted matrices: this
|
||||
/// crate checks extents, pair bounds, disjoint destinations and finite inputs/outputs, never the source.
|
||||
pub struct DirectCpuPool { native: ffi::NativePool, workers: usize, failed: bool, _actor: PhantomData<Rc<()>> }
|
||||
impl DirectCpuPool {
|
||||
pub fn new(workers: i32) -> Result<Self> {
|
||||
let native = ffi::NativePool::new(workers)?;
|
||||
let workers = native.workers()?;
|
||||
Ok(Self { native, workers, failed: false, _actor: PhantomData })
|
||||
}
|
||||
pub fn workers(&self) -> usize { self.workers }
|
||||
/// Compute every expert of `group` into `out` in one two-phase dispatch (at most `MAX_JOBS` experts,
|
||||
/// all of the same gate/up and down formats). Only the pairs' rows of `out` are written.
|
||||
pub fn compute_group(&mut self, gu: GateUpFormat, down: DownFormat, group: &BorrowedGroup<'_>, out: &mut [f32]) -> Result<()> {
|
||||
if self.failed { return Err(Error::Closed); }
|
||||
let result = self.native.compute_borrowed(gu.kind(), down.kind(), group, out);
|
||||
if matches!(result, Err(Error::NativeFailure | Error::Closed)) { self.failed = true; }
|
||||
result
|
||||
}
|
||||
/// Read every page of the experts' matrices on all workers after `MADV_WILLNEED` on all of them (for a
|
||||
/// file-mapped source; the pairs are ignored). Nothing is computed or written.
|
||||
pub fn prefetch(&mut self, gu: GateUpFormat, down: DownFormat, experts: &[BorrowedExpert<'_>]) -> Result<()> {
|
||||
if self.failed { return Err(Error::Closed); }
|
||||
let result = self.native.prefetch_borrowed(gu.kind(), down.kind(), experts);
|
||||
if matches!(result, Err(Error::NativeFailure | Error::Closed)) { self.failed = true; }
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CompletedJob { values: Box<[f32]> }
|
||||
impl CompletedJob { pub fn into_values(self) -> Box<[f32]> { self.values } }
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ unsafe extern "C" {
|
||||
fn pthread_self()->usize;
|
||||
fn pthread_setaffinity_np(thread:usize,bytes:usize,set:*const usize)->i32;
|
||||
fn sysconf(name:i32)->i64;
|
||||
fn madvise(addr:*mut u8,len:usize,advice:i32)->i32;
|
||||
}
|
||||
pub(super) fn stack_size()->Result<usize> {
|
||||
#[cfg(not(target_env="gnu"))] {return Err(Error::Unsupported);}
|
||||
@@ -30,6 +31,15 @@ pub(super) fn cores(skip_first:bool)->Vec<i32> {
|
||||
let mut seen=Vec::new();let mut physical=Vec::new();for cpu in allowed {let key=(read_cpu(cpu,"physical_package_id"),read_cpu(cpu,"core_id"));if key.0>=0&&key.1>=0 {if seen.contains(&key){continue;}seen.push(key);}physical.push(cpu);}
|
||||
if skip_first&&!physical.is_empty(){physical.remove(0);}physical
|
||||
}
|
||||
/// `madvise(MADV_WILLNEED)` over the pages of `bytes`: the kernel starts reading a file-mapped range in the
|
||||
/// background (expert_source.cpp `warm`). Advice only; a failure changes nothing.
|
||||
pub(super) fn will_need(bytes:&[u8]) {
|
||||
if bytes.is_empty(){return;}
|
||||
let page=4096usize;let start=bytes.as_ptr() as usize&!(page-1);let end=bytes.as_ptr() as usize+bytes.len();
|
||||
// SAFETY: advice over pages that contain the caller's live borrowed range; MADV_WILLNEED (3) never
|
||||
// changes the contents or the mapping.
|
||||
unsafe {let _=madvise(start as *mut u8,end-start,3);}
|
||||
}
|
||||
pub(super) fn pin(core:i32) {
|
||||
if core<0{return;}let mut set=[0usize;16];if core as usize>=1024{return;}set[core as usize/64]|=1usize<<(core as usize%64);
|
||||
// Original intentionally ignores OS affinity refusal; it does not change math.
|
||||
|
||||
@@ -10,11 +10,11 @@ impl Default for NativeAct{fn default()->Self{Self{q:[Q8K::default();10],padding
|
||||
#[repr(C,align(64))]struct Scratch{a1:ActQ,a2:ActQ,ff:[f32;FF]}
|
||||
impl Default for Scratch{fn default()->Self{Self{a1:ActQ::default(),a2:ActQ::default(),ff:[0.0;FF]}}}
|
||||
#[repr(C)]
|
||||
#[derive(Clone,Copy)]struct Job{blob:*const u8,rows:i32,act:[*const ActQ;MAX_ROWS],output:[*mut f32;MAX_ROWS],nact:[*const u8;MAX_ROWS]}
|
||||
impl Default for Job{fn default()->Self{Self{blob:std::ptr::null(),rows:0,act:[std::ptr::null();MAX_ROWS],output:[std::ptr::null_mut();MAX_ROWS],nact:[std::ptr::null();MAX_ROWS]}}}
|
||||
#[derive(Clone,Copy)]struct Job{gate:*const u8,up:*const u8,down:*const u8,rows:i32,act:[*const ActQ;MAX_ROWS],output:[*mut f32;MAX_ROWS],nact:[*const u8;MAX_ROWS]}
|
||||
impl Default for Job{fn default()->Self{Self{gate:std::ptr::null(),up:std::ptr::null(),down:std::ptr::null(),rows:0,act:[std::ptr::null();MAX_ROWS],output:[std::ptr::null_mut();MAX_ROWS],nact:[std::ptr::null();MAX_ROWS]}}}
|
||||
#[repr(C,align(64))]struct SingleSplit{ff:[f32;FF],a2:ActQ}
|
||||
impl Default for SingleSplit{fn default()->Self{Self{ff:[0.0;FF],a2:ActQ::default()}}}
|
||||
const _: ()=assert!(std::mem::size_of::<Job>()==208);
|
||||
const _: ()=assert!(std::mem::size_of::<Job>()==224);
|
||||
const _: ()=assert!(std::mem::size_of::<Scratch>()==9728);
|
||||
const _: ()=assert!(std::mem::size_of::<SingleSplit>()==6144);
|
||||
struct Batch{jobs:[Job;MAX_JOBS],format:NativeFmt,count:usize,mode:u32,rows:usize,tasks:usize}
|
||||
@@ -22,6 +22,8 @@ struct Shared {
|
||||
head:Line<AtomicU64>,done:Line<AtomicU32>,parked:Line<AtomicU32>,epoch:Line<AtomicU32>,stop:Line<AtomicBool>,sleepers:Line<AtomicU32>,
|
||||
sleep_mu:Mutex<()>,sleep_cv:Condvar,spin:Duration,n:usize,
|
||||
batch:UnsafeCell<Batch>,act:Vec<UnsafeCell<[ActQ;MAX_ROWS]>>,nact:Vec<UnsafeCell<[NativeAct;MAX_ROWS]>>,split:Vec<UnsafeCell<SplitBuf>>,
|
||||
// Borrowed groups quantize every token once (expert_source.cpp act_multi/nact_multi), not once per job row.
|
||||
tok_act:Vec<UnsafeCell<[ActQ;MAX_ROWS]>>,tok_nact:Vec<UnsafeCell<[NativeAct;MAX_ROWS]>>,
|
||||
// Keep the original per-worker scratch reservation even though native phases
|
||||
// require only split storage; it remains owned until all worker joins complete.
|
||||
_scratch:Vec<Scratch>,_single_split:Vec<SingleSplit>,
|
||||
@@ -42,17 +44,21 @@ impl Shared {
|
||||
unsafe {self.execute(i);}self.done.0.fetch_add(1,Ordering::Release);
|
||||
}}
|
||||
unsafe fn execute(&self,i:usize){unsafe {
|
||||
let b=&*self.batch.get();let per=if b.mode==5{FF}else{H};let mut at=b.rows*i/b.tasks;let end=b.rows*(i+1)/b.tasks;
|
||||
while at<end{let e=at/per;debug_assert!(e<b.count);let r0=at%per;let r1=per.min(r0+end-at);let j=b.jobs[e];let nr=j.rows as usize;let f=b.format;let blob=std::slice::from_raw_parts(j.blob,f.bytes);
|
||||
let b=&*self.batch.get();let per=match b.mode{5=>FF,6=>H,_=>2*FF+H};let mut at=b.rows*i/b.tasks;let end=b.rows*(i+1)/b.tasks;
|
||||
while at<end{let e=at/per;debug_assert!(e<b.count);let r0=at%per;let r1=per.min(r0+end-at);let j=b.jobs[e];let nr=j.rows as usize;let f=b.format;let gate=std::slice::from_raw_parts(j.gate,f.up_off);let up=std::slice::from_raw_parts(j.up,f.up_off);let down=std::slice::from_raw_parts(j.down,f.bytes-f.down_off);
|
||||
let slot=self.split[e].get();let mut g=[0.0f32;MAX_ROWS];let mut u=[0.0f32;MAX_ROWS];
|
||||
if b.mode==5 {
|
||||
for r in r0..r1 {let gr=&blob[r*f.gu_row..(r+1)*f.gu_row];let ur=&blob[f.up_off+r*f.gu_row..f.up_off+(r+1)*f.gu_row];
|
||||
if b.mode==7 {
|
||||
// Prefault: read the first and the last byte of every encoded row (rows are contiguous, so every page).
|
||||
for r in r0..r1 {let row=if r<FF{&gate[r*f.gu_row..(r+1)*f.gu_row]}else if r<2*FF{&up[(r-FF)*f.gu_row..(r-FF+1)*f.gu_row]}else{&down[(r-2*FF)*f.down_row..(r-2*FF+1)*f.down_row]};
|
||||
std::ptr::read_volatile(row.as_ptr());std::ptr::read_volatile(row.as_ptr().add(row.len()-1));}
|
||||
} else if b.mode==5 {
|
||||
for r in r0..r1 {let gr=&gate[r*f.gu_row..(r+1)*f.gu_row];let ur=&up[r*f.gu_row..(r+1)*f.gu_row];
|
||||
if f.gu==42{let mut aa=[&*j.act[0];MAX_ROWS];for t in 0..nr{aa[t]=&*j.act[t];}if dispatch().avx512{super::rust_q2::dot512(gr,&aa[..nr],&mut g[..nr]);super::rust_q2::dot512(ur,&aa[..nr],&mut u[..nr]);}else{super::rust_q2::dot256(gr,&aa[..nr],&mut g[..nr]);super::rust_q2::dot256(ur,&aa[..nr],&mut u[..nr]);}}
|
||||
else {let mut yy=[(&*j.nact[0].cast::<NativeAct>()).q.as_slice();MAX_ROWS];for t in 0..nr{yy[t]=(&*j.nact[t].cast::<NativeAct>()).q.as_slice();}let d=dispatch();if (nr as i32)>=d.mt_min&&matches!(f.gu,16|17|18|21|22)&&d.iq512{super::rust_iq::dot_multi512(f.gu,gr,&yy[..nr],&mut g[..nr]);super::rust_iq::dot_multi512(f.gu,ur,&yy[..nr],&mut u[..nr]);}else if (nr as i32)>=d.mt_min&&matches!(f.gu,16|17|18|21|22)&&d.iq256{super::rust_iq::dot_multi256(f.gu,gr,&yy[..nr],&mut g[..nr]);super::rust_iq::dot_multi256(f.gu,ur,&yy[..nr],&mut u[..nr]);}else{for t in 0..nr{g[t]=super::rust_iq::dot_single(f.gu,gr,yy[t]);u[t]=super::rust_iq::dot_single(f.gu,ur,yy[t]);}}}
|
||||
let dst=std::ptr::addr_of_mut!((*slot).ff).cast::<f32>();for t in 0..nr{dst.add(t*FF+r).write(silu(g[t],u[t]));}
|
||||
}
|
||||
} else {
|
||||
for r in r0..r1{let row=&blob[f.down_off+r*f.down_row..f.down_off+(r+1)*f.down_row];
|
||||
for r in r0..r1{let row=&down[r*f.down_row..(r+1)*f.down_row];
|
||||
if f.down==42{let base=std::ptr::addr_of!((*slot).a2).cast::<ActQ>();let mut aa=[&*base;MAX_ROWS];for t in 0..nr{aa[t]=&*base.add(t);}if dispatch().avx512{super::rust_q2::dot512(row,&aa[..nr],&mut g[..nr]);}else{super::rust_q2::dot256(row,&aa[..nr],&mut g[..nr]);}}
|
||||
else{let base=std::ptr::addr_of!((*slot).hq).cast::<super::rust_types::NativeHidden>();let empty:&[super::rust_types::Q8Zero]=&[];let mut yy=[empty;MAX_ROWS];for t in 0..nr{yy[t]=&(*base.add(t)).q;}let d=dispatch();let single=(nr as i32)<d.mt_min||!d.iq4nl;super::rust_iq::iq4nl(row,&yy[..nr],&mut g[..nr],single);}
|
||||
for t in 0..nr{j.output[t].add(r).write(g[t]);}
|
||||
@@ -74,7 +80,7 @@ pub(super) struct NativePool{shared:Arc<Shared>,workers:Vec<thread::JoinHandle<(
|
||||
impl NativePool {
|
||||
pub fn new(workers:i32)->Result<Self>{if !(0..=15).contains(&workers){return Err(Error::Shape);}let stack=super::rust_platform::stack_size()?;if !super::rust_simd::avx2_ok()||super::rust_simd::avx512_ok()&&!super::rust_simd::dq_ok(){return Err(Error::Unsupported);}let cores=super::rust_platform::cores(true);if workers==0&&cores.len()>15{return Err(Error::Unsupported);}let n=if workers>0{workers as usize}else{cores.len().max(1)};
|
||||
let spin=std::env::var("STRATA_POOL_SPIN_US").map(|s|Duration::from_micros(super::rust_simd::atoi(&s).max(0)as u64)).unwrap_or(Duration::from_millis(20));
|
||||
let shared=Arc::new(Shared{head:Line(AtomicU64::new(0)),done:Line(AtomicU32::new(0)),parked:Line(AtomicU32::new(0)),epoch:Line(AtomicU32::new(0)),stop:Line(AtomicBool::new(false)),sleepers:Line(AtomicU32::new(0)),sleep_mu:Mutex::new(()),sleep_cv:Condvar::new(),spin,n,batch:UnsafeCell::new(Batch{jobs:[Job::default();MAX_JOBS],format:NativeFmt::new(18,42)?,count:0,mode:0,rows:0,tasks:1}),act:allocated(MAX_JOBS)?,nact:allocated(MAX_JOBS)?,split:allocated(MAX_JOBS)?,_scratch:allocated(n+1)?,_single_split:allocated(16)?});
|
||||
let shared=Arc::new(Shared{head:Line(AtomicU64::new(0)),done:Line(AtomicU32::new(0)),parked:Line(AtomicU32::new(0)),epoch:Line(AtomicU32::new(0)),stop:Line(AtomicBool::new(false)),sleepers:Line(AtomicU32::new(0)),sleep_mu:Mutex::new(()),sleep_cv:Condvar::new(),spin,n,batch:UnsafeCell::new(Batch{jobs:[Job::default();MAX_JOBS],format:NativeFmt::new(18,42)?,count:0,mode:0,rows:0,tasks:1}),act:allocated(MAX_JOBS)?,nact:allocated(MAX_JOBS)?,split:allocated(MAX_JOBS)?,tok_act:allocated(1)?,tok_nact:allocated(1)?,_scratch:allocated(n+1)?,_single_split:allocated(16)?});
|
||||
let mut out=Self{shared,workers:Vec::new()};out.workers.try_reserve_exact(n).map_err(|_|Error::Allocation)?;for i in 0..n{let shared=Arc::clone(&out.shared);let core=cores.get(i).copied().unwrap_or(-1);out.workers.push(thread::Builder::new().name(format!("strata-expert-{i}")).stack_size(stack).spawn(move||shared.worker(core)).map_err(|_|Error::Allocation)?);}Ok(out)
|
||||
}
|
||||
pub fn workers(&self)->Result<usize>{Ok(self.workers.len())}
|
||||
@@ -86,11 +92,68 @@ impl NativePool {
|
||||
self.shared.wait_parked();
|
||||
// SAFETY: all workers parked; jobs remain exclusively borrowed until both
|
||||
// phases finish and workers park again. NativePool::Drop joins before owners.
|
||||
unsafe {let b=&mut*self.shared.batch.get();b.format=f;b.count=jobs.len();for (e,j) in jobs.iter_mut().enumerate(){b.jobs[e]=Job{blob:j.blob.as_ptr(),rows:j.rows as i32,..Job::default()};for t in 0..j.rows{let x=&j.input[t*H..(t+1)*H];b.jobs[e].output[t]=j.output.as_mut_ptr().add(t*H);b.jobs[e].act[t]=(*self.shared.act[e].get()).as_ptr().add(t);b.jobs[e].nact[t]=(*self.shared.nact[e].get()).as_ptr().add(t).cast();let ptr=(*self.shared.act[e].get()).as_mut_ptr().add(t);if f.gu==42{if dispatch().avx512{super::rust_quant::q8_one_avx512(x,&mut*ptr);}else{super::rust_quant::q8_one_avx2(x,&mut*ptr);}}else{let ptr=(*self.shared.nact[e].get()).as_mut_ptr().add(t);super::rust_quant::q8_k(x,&mut(*ptr).q);}}}}
|
||||
self.phase(5,jobs.len()*FF);
|
||||
unsafe {for (e,j) in jobs.iter().enumerate(){let s=&mut*self.shared.split[e].get();for t in 0..j.rows{if f.down==42{if dispatch().avx512{super::rust_quant::q8_one_avx512(&s.ff[t],&mut s.a2[t]);}else{super::rust_quant::q8_one_avx2(&s.ff[t],&mut s.a2[t]);}}else{super::rust_quant::q8_zero(&s.ff[t],&mut s.hq[t].q);}}}}
|
||||
self.phase(6,jobs.len()*H);
|
||||
unsafe {let b=&mut*self.shared.batch.get();b.format=f;b.count=jobs.len();for (e,j) in jobs.iter_mut().enumerate(){let p=j.blob.as_ptr();b.jobs[e]=Job{gate:p,up:p.add(f.up_off),down:p.add(f.down_off),rows:j.rows as i32,..Job::default()};for t in 0..j.rows{let x=&j.input[t*H..(t+1)*H];b.jobs[e].output[t]=j.output.as_mut_ptr().add(t*H);b.jobs[e].act[t]=(*self.shared.act[e].get()).as_ptr().add(t);b.jobs[e].nact[t]=(*self.shared.nact[e].get()).as_ptr().add(t).cast();let ptr=(*self.shared.act[e].get()).as_mut_ptr().add(t);if f.gu==42{if dispatch().avx512{super::rust_quant::q8_one_avx512(x,&mut*ptr);}else{super::rust_quant::q8_one_avx2(x,&mut*ptr);}}else{let ptr=(*self.shared.nact[e].get()).as_mut_ptr().add(t);super::rust_quant::q8_k(x,&mut(*ptr).q);}}}}
|
||||
self.run_published(f,jobs.len());
|
||||
if jobs.iter().any(|j|j.output.iter().any(|v|!v.is_finite())){Err(Error::NonFinite)}else{Ok(())}
|
||||
}
|
||||
/// Gate/up phase, the host requantization of every job's hidden rows, then the down phase, over the
|
||||
/// `count` jobs already described in the batch (workers parked).
|
||||
fn run_published(&mut self,f:NativeFmt,count:usize){
|
||||
self.phase(5,count*FF);
|
||||
// SAFETY: all workers parked after phase 5; job rows were admitted before publication.
|
||||
unsafe {let b=&*self.shared.batch.get();for e in 0..count{let rows=b.jobs[e].rows as usize;let s=&mut*self.shared.split[e].get();for t in 0..rows{if f.down==42{if dispatch().avx512{super::rust_quant::q8_one_avx512(&s.ff[t],&mut s.a2[t]);}else{super::rust_quant::q8_one_avx2(&s.ff[t],&mut s.a2[t]);}}else{super::rust_quant::q8_zero(&s.ff[t],&mut s.hq[t].q);}}}}
|
||||
self.phase(6,count*H);
|
||||
}
|
||||
/// Fault the borrowed matrices in on every worker (and the caller) after `MADV_WILLNEED` on all of
|
||||
/// them: a file-mapped source's misses become many outstanding reads instead of one serial stream
|
||||
/// (expert_source.cpp `prefetch` on its fetch threads). Reads only; nothing is computed or written.
|
||||
pub fn prefetch_borrowed(&mut self,gu:i32,down:i32,experts:&[super::BorrowedExpert<'_>])->Result<()> {
|
||||
let f=NativeFmt::new(gu,down)?;
|
||||
if !(1..=MAX_JOBS).contains(&experts.len()){return Err(Error::Shape);}
|
||||
for x in experts{if x.gate.len()!=f.up_off||x.up.len()!=f.up_off||x.down.len()!=f.bytes-f.down_off{return Err(Error::Shape);}}
|
||||
for x in experts{for m in [x.gate,x.up,x.down]{super::rust_platform::will_need(m);}}
|
||||
self.shared.wait_parked();
|
||||
// SAFETY: all workers parked; the borrowed matrices outlive this call, which returns only after the
|
||||
// phase finished and the workers parked again. The phase only reads them.
|
||||
unsafe {let b=&mut*self.shared.batch.get();b.format=f;b.count=experts.len();for (e,x) in experts.iter().enumerate(){b.jobs[e]=Job{gate:x.gate.as_ptr(),up:x.up.as_ptr(),down:x.down.as_ptr(),..Job::default()};}}
|
||||
self.phase(7,experts.len()*(2*FF+H));
|
||||
Ok(())
|
||||
}
|
||||
/// One whole group straight from borrowed encoded matrices into the caller's output rows: a single
|
||||
/// two-phase dispatch, no copy of expert bytes or activations. Every borrow ends before this returns;
|
||||
/// the caller holds `group` and `out` exclusively for the call. `out` row `token * stride + slot` of
|
||||
/// each pair receives that expert's row; the pairs of all experts must name distinct rows.
|
||||
pub fn compute_borrowed(&mut self,gu:i32,down:i32,group:&super::BorrowedGroup<'_>,out:&mut [f32])->Result<()> {
|
||||
let f=NativeFmt::new(gu,down)?;let experts=group.experts;let tokens=group.tokens;let stride=group.stride;
|
||||
if !(1..=MAX_JOBS).contains(&experts.len())||tokens.len()%H!=0||!(1..=MAX_ROWS).contains(&(tokens.len()/H))||stride==0||out.len()%H!=0{return Err(Error::Shape);}
|
||||
let ntok=tokens.len()/H;let out_rows=out.len()/H;if out_rows>super::MAX_OUT_ROWS{return Err(Error::Shape);}
|
||||
// Validate the ENTIRE group (extents, pair bounds, disjoint destinations, finite inputs) first.
|
||||
let mut written=[0u64;super::MAX_OUT_ROWS/64];let mut used=[false;MAX_ROWS];
|
||||
for x in experts{
|
||||
if x.gate.len()!=f.up_off||x.up.len()!=f.up_off||x.down.len()!=f.bytes-f.down_off||!(1..=MAX_ROWS).contains(&x.pairs.len()){return Err(Error::Shape);}
|
||||
for &(token,slot) in x.pairs{
|
||||
if token>=ntok||slot>=stride{return Err(Error::Shape);}
|
||||
let row=token.checked_mul(stride).and_then(|r|r.checked_add(slot)).ok_or(Error::Shape)?;
|
||||
if row>=out_rows||written[row/64]>>(row%64)&1!=0{return Err(Error::Shape);}
|
||||
written[row/64]|=1<<(row%64);used[token]=true;
|
||||
}
|
||||
}
|
||||
if tokens.iter().any(|x|!x.is_finite()){return Err(Error::NonFinite);}
|
||||
self.shared.wait_parked();
|
||||
// SAFETY: all workers parked; the borrowed matrices, tokens and `out` outlive this call, which returns
|
||||
// only after both phases finished and the workers parked again. Destinations are pairwise disjoint rows.
|
||||
unsafe {
|
||||
let ta=&mut*self.shared.tok_act[0].get();let tn=&mut*self.shared.tok_nact[0].get();
|
||||
for t in (0..ntok).filter(|&t|used[t]){let x=&tokens[t*H..(t+1)*H];if f.gu==42{if dispatch().avx512{super::rust_quant::q8_one_avx512(x,&mut ta[t]);}else{super::rust_quant::q8_one_avx2(x,&mut ta[t]);}}else{super::rust_quant::q8_k(x,&mut tn[t].q);}}
|
||||
let b=&mut*self.shared.batch.get();b.format=f;b.count=experts.len();let base=out.as_mut_ptr();
|
||||
for (e,x) in experts.iter().enumerate(){
|
||||
b.jobs[e]=Job{gate:x.gate.as_ptr(),up:x.up.as_ptr(),down:x.down.as_ptr(),rows:x.pairs.len() as i32,..Job::default()};
|
||||
for (t,&(token,slot)) in x.pairs.iter().enumerate(){b.jobs[e].act[t]=ta.as_ptr().add(token);b.jobs[e].nact[t]=tn.as_ptr().add(token).cast();b.jobs[e].output[t]=base.add((token*stride+slot)*H);}
|
||||
}
|
||||
}
|
||||
self.run_published(f,experts.len());
|
||||
for x in experts{for &(token,slot) in x.pairs{let at=(token*stride+slot)*H;if out[at..at+H].iter().any(|v|!v.is_finite()){return Err(Error::NonFinite);}}}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Drop for NativePool{fn drop(&mut self){self.shared.stop.0.store(true,Ordering::Release);self.shared.publish();for t in self.workers.drain(..){let _=t.join();}}}
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
//! The borrowed single-dispatch group path (`DirectCpuPool::compute_group`) against the owned path the
|
||||
//! serve pool used before (`PreparedJob` copies, batches of 12 through `CpuPool::start`/`join`, scatter):
|
||||
//! every output bit must be identical, on every gate/up x down format pair, for groups of 1..=8 rows whose
|
||||
//! experts are shared between rows. Synthetic encoded blobs: random codes, random finite FP16 block scales.
|
||||
//!
|
||||
//! cargo test --release -p leleka-native-cpu-expert --test borrowed_group_parity
|
||||
//! (the ignored `group_path_cost` prints the model-free cost of both paths)
|
||||
use leleka_native_cpu_expert::{BorrowedExpert, BorrowedGroup, CpuPool, DirectCpuPool, DownFormat, GateUpFormat, PreparedJob};
|
||||
use std::time::Instant;
|
||||
|
||||
const H: usize = 2560;
|
||||
const FF: usize = 640;
|
||||
const TOP_K: usize = 10;
|
||||
const OLD_BATCH: usize = 12;
|
||||
|
||||
struct Rng(u64);
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
fn below(&mut self, n: usize) -> usize {
|
||||
(self.next() % n as u64) as usize
|
||||
}
|
||||
fn unit(&mut self) -> f32 {
|
||||
(self.next() >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0
|
||||
}
|
||||
}
|
||||
|
||||
fn gate_up_block(f: GateUpFormat) -> (usize, usize) {
|
||||
match f {
|
||||
GateUpFormat::Iq3Xxs => (256, 98),
|
||||
GateUpFormat::Iq3S => (256, 110),
|
||||
GateUpFormat::Iq2S => (256, 82),
|
||||
GateUpFormat::Iq4Xs => (256, 136),
|
||||
GateUpFormat::Q2_0 => (64, 18),
|
||||
}
|
||||
}
|
||||
fn down_block(f: DownFormat) -> (usize, usize) {
|
||||
match f {
|
||||
DownFormat::Iq4Nl => (32, 18),
|
||||
DownFormat::Q2_0 => (64, 18),
|
||||
}
|
||||
}
|
||||
|
||||
/// Random codes; every block starts with a finite FP16 scale in [2^-10, 2^-5).
|
||||
fn matrix(rng: &mut Rng, bytes: usize, block: usize) -> Vec<u8> {
|
||||
let mut out: Vec<u8> = (0..bytes).map(|_| rng.next() as u8).collect();
|
||||
for at in (0..bytes).step_by(block) {
|
||||
let exponent = 5 + rng.below(5) as u16;
|
||||
let half = (rng.below(2) as u16) << 15 | exponent << 10 | (rng.next() as u16 & 0x3ff);
|
||||
out[at..at + 2].copy_from_slice(&half.to_le_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
struct Expert {
|
||||
gate: Vec<u8>,
|
||||
up: Vec<u8>,
|
||||
down: Vec<u8>,
|
||||
}
|
||||
fn bank(rng: &mut Rng, gu: GateUpFormat, down: DownFormat, count: usize) -> Vec<Expert> {
|
||||
let (gq, gb) = gate_up_block(gu);
|
||||
let (dq, db) = down_block(down);
|
||||
(0..count)
|
||||
.map(|_| Expert {
|
||||
gate: matrix(rng, H / gq * gb * FF, gb),
|
||||
up: matrix(rng, H / gq * gb * FF, gb),
|
||||
down: matrix(rng, FF / dq * db * H, db),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A router output: `rows` rows of 10 distinct experts out of `experts`, plus the CPU mask.
|
||||
fn route(rng: &mut Rng, rows: usize, experts: usize, cpu_share: usize) -> (Vec<usize>, Vec<bool>) {
|
||||
let mut ids = Vec::new();
|
||||
for _ in 0..rows {
|
||||
let mut row: Vec<usize> = Vec::new();
|
||||
while row.len() < TOP_K {
|
||||
let e = rng.below(experts);
|
||||
if !row.contains(&e) {
|
||||
row.push(e);
|
||||
}
|
||||
}
|
||||
ids.extend(row);
|
||||
}
|
||||
let include = (0..ids.len()).map(|_| rng.below(100) < cpu_share).collect();
|
||||
(ids, include)
|
||||
}
|
||||
|
||||
/// Experts in first-use order with their ascending `(row, slot)` pairs (original_serve_pool::plan_experts_where).
|
||||
fn plan(ids: &[usize], include: &[bool]) -> Vec<(usize, Vec<(usize, usize)>)> {
|
||||
let mut jobs: Vec<(usize, Vec<(usize, usize)>)> = Vec::new();
|
||||
for (i, &e) in ids.iter().enumerate() {
|
||||
if !include[i] {
|
||||
continue;
|
||||
}
|
||||
let pair = (i / TOP_K, i % TOP_K);
|
||||
match jobs.iter_mut().find(|(x, _)| *x == e) {
|
||||
Some((_, pairs)) => pairs.push(pair),
|
||||
None => jobs.push((e, vec![pair])),
|
||||
}
|
||||
}
|
||||
jobs
|
||||
}
|
||||
|
||||
/// The previous serve path: copy every role into owned boxes, build owned inputs, run batches of 12 with
|
||||
/// a join between them, scatter every expert's rows into the output.
|
||||
fn owned_path(pool: &mut CpuPool, gu: GateUpFormat, down: DownFormat, bank: &[Expert], tokens: &[f32], jobs: &[(usize, Vec<(usize, usize)>)], out: &mut [f32]) {
|
||||
for batch in jobs.chunks(OLD_BATCH) {
|
||||
let mut prepared = Vec::with_capacity(batch.len());
|
||||
for (e, pairs) in batch {
|
||||
let x = &bank[*e];
|
||||
let mut input = Vec::with_capacity(pairs.len() * H);
|
||||
for &(row, _) in pairs {
|
||||
input.extend_from_slice(&tokens[row * H..(row + 1) * H]);
|
||||
}
|
||||
prepared.push(
|
||||
PreparedJob::new(gu, down, x.gate.clone().into_boxed_slice(), x.up.clone().into_boxed_slice(), x.down.clone().into_boxed_slice(), input.into_boxed_slice(), pairs.len())
|
||||
.expect("owned job"),
|
||||
);
|
||||
}
|
||||
let done = pool.start(prepared, 48 << 20).expect("start").join().expect("join");
|
||||
for (job, (_, pairs)) in done.into_iter().zip(batch) {
|
||||
let values = job.into_values();
|
||||
for (i, &(row, slot)) in pairs.iter().enumerate() {
|
||||
let at = (row * TOP_K + slot) * H;
|
||||
out[at..at + H].copy_from_slice(&values[i * H..(i + 1) * H]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn borrowed_path(pool: &mut DirectCpuPool, gu: GateUpFormat, down: DownFormat, bank: &[Expert], tokens: &[f32], jobs: &[(usize, Vec<(usize, usize)>)], out: &mut [f32]) {
|
||||
let experts: Vec<BorrowedExpert<'_>> =
|
||||
jobs.iter().map(|(e, pairs)| BorrowedExpert { gate: &bank[*e].gate, up: &bank[*e].up, down: &bank[*e].down, pairs }).collect();
|
||||
pool.compute_group(gu, down, &BorrowedGroup { tokens, experts: &experts, stride: TOP_K }, out).expect("borrowed group");
|
||||
}
|
||||
|
||||
const PAIRS: [(GateUpFormat, DownFormat); 10] = [
|
||||
(GateUpFormat::Iq3Xxs, DownFormat::Iq4Nl),
|
||||
(GateUpFormat::Iq3S, DownFormat::Iq4Nl),
|
||||
(GateUpFormat::Iq2S, DownFormat::Iq4Nl),
|
||||
(GateUpFormat::Iq4Xs, DownFormat::Iq4Nl),
|
||||
(GateUpFormat::Q2_0, DownFormat::Iq4Nl),
|
||||
(GateUpFormat::Iq3Xxs, DownFormat::Q2_0),
|
||||
(GateUpFormat::Iq3S, DownFormat::Q2_0),
|
||||
(GateUpFormat::Iq2S, DownFormat::Q2_0),
|
||||
(GateUpFormat::Iq4Xs, DownFormat::Q2_0),
|
||||
(GateUpFormat::Q2_0, DownFormat::Q2_0),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn borrowed_group_is_bit_identical_to_the_owned_batches() {
|
||||
let workers = std::env::var("PARITY_WORKERS").ok().and_then(|v| v.parse().ok()).unwrap_or(4);
|
||||
let mut owned = CpuPool::new(workers).expect("owned pool");
|
||||
let mut direct = DirectCpuPool::new(workers).expect("direct pool");
|
||||
let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
|
||||
let mut groups = 0;
|
||||
for (gu, down) in PAIRS {
|
||||
// a small bank so rows share experts and batches of 12 are crossed
|
||||
let bank = bank(&mut rng, gu, down, 40);
|
||||
for rows in [1usize, 2, 3, 4, 6, 8] {
|
||||
for share in [100usize, 50] {
|
||||
let (ids, include) = route(&mut rng, rows, bank.len(), share);
|
||||
let jobs = plan(&ids, &include);
|
||||
if jobs.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let tokens: Vec<f32> = (0..rows * H).map(|_| rng.unit()).collect();
|
||||
// different sentinels: rows the plan leaves out must stay untouched by both paths
|
||||
let mut a = vec![f32::from_bits(0x7fc0_0001); rows * TOP_K * H];
|
||||
let mut b = vec![f32::from_bits(0x7fc0_0001); rows * TOP_K * H];
|
||||
owned_path(&mut owned, gu, down, &bank, &tokens, &jobs, &mut a);
|
||||
if share != 100 {
|
||||
// the file-mapped source's prefetch phase reads only: the group computes the same bits
|
||||
let refs: Vec<BorrowedExpert<'_>> =
|
||||
jobs.iter().map(|(e, pairs)| BorrowedExpert { gate: &bank[*e].gate, up: &bank[*e].up, down: &bank[*e].down, pairs }).collect();
|
||||
direct.prefetch(gu, down, &refs).expect("prefetch");
|
||||
}
|
||||
borrowed_path(&mut direct, gu, down, &bank, &tokens, &jobs, &mut b);
|
||||
let differing = a.iter().zip(&b).filter(|(x, y)| x.to_bits() != y.to_bits()).count();
|
||||
assert_eq!(differing, 0, "{gu:?} x {down:?} rows={rows} share={share}: {differing} floats differ");
|
||||
let computed: usize = jobs.iter().map(|(_, p)| p.len()).sum();
|
||||
assert!(b.iter().filter(|v| v.is_finite()).count() == computed * H, "{gu:?} x {down:?}: only planned rows written, all finite");
|
||||
groups += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!("bit-identical groups: {groups}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn borrowed_group_refuses_bad_shapes_without_touching_out() {
|
||||
let mut direct = DirectCpuPool::new(2).expect("direct pool");
|
||||
let mut rng = Rng(7);
|
||||
let (gu, down) = (GateUpFormat::Iq3S, DownFormat::Iq4Nl);
|
||||
let bank = bank(&mut rng, gu, down, 2);
|
||||
let tokens = vec![0.25f32; 2 * H];
|
||||
let mut out = vec![-3.0f32; 2 * TOP_K * H];
|
||||
let pairs_a = [(0usize, 1usize)];
|
||||
let duplicate = [(0usize, 1usize)];
|
||||
let out_of_rows = [(2usize, 0usize)];
|
||||
let wide_slot = [(0usize, TOP_K)];
|
||||
let x = |pairs| BorrowedExpert { gate: &bank[0].gate, up: &bank[0].up, down: &bank[0].down, pairs };
|
||||
let y = |pairs| BorrowedExpert { gate: &bank[1].gate, up: &bank[1].up, down: &bank[1].down, pairs };
|
||||
for experts in [vec![x(&pairs_a), y(&duplicate)], vec![x(&out_of_rows)], vec![x(&wide_slot)], vec![]] {
|
||||
let group = BorrowedGroup { tokens: &tokens, experts: &experts, stride: TOP_K };
|
||||
assert!(direct.compute_group(gu, down, &group, &mut out).is_err());
|
||||
}
|
||||
let short = BorrowedExpert { gate: &bank[0].gate[1..], up: &bank[0].up, down: &bank[0].down, pairs: &pairs_a };
|
||||
assert!(direct.compute_group(gu, down, &BorrowedGroup { tokens: &tokens, experts: &[short], stride: TOP_K }, &mut out).is_err());
|
||||
let wrong_format = [x(&pairs_a)];
|
||||
assert!(direct.compute_group(GateUpFormat::Iq3Xxs, down, &BorrowedGroup { tokens: &tokens, experts: &wrong_format, stride: TOP_K }, &mut out).is_err());
|
||||
let mut nan = tokens.clone();
|
||||
nan[5] = f32::NAN;
|
||||
assert!(direct.compute_group(gu, down, &BorrowedGroup { tokens: &nan, experts: &wrong_format, stride: TOP_K }, &mut out).is_err());
|
||||
assert!(out.iter().all(|&v| v == -3.0), "a refused group writes nothing");
|
||||
// and the pool still serves a good group afterwards
|
||||
let good = [x(&pairs_a)];
|
||||
direct.compute_group(gu, down, &BorrowedGroup { tokens: &tokens, experts: &good, stride: TOP_K }, &mut out).expect("good group");
|
||||
assert!(out[H..2 * H].iter().all(|v| v.is_finite()));
|
||||
}
|
||||
|
||||
/// The previous runtime prepare step per expert also copied each role out of the source (`block`) and
|
||||
/// scanned every block header (`encoded_finite`) before `PreparedJob::new` copied them again.
|
||||
fn owned_path_with_source_copy(pool: &mut CpuPool, gu: GateUpFormat, down: DownFormat, bank: &[Expert], tokens: &[f32], jobs: &[(usize, Vec<(usize, usize)>)], out: &mut [f32]) {
|
||||
let (_, gb) = gate_up_block(gu);
|
||||
let (_, db) = down_block(down);
|
||||
let scan = |bytes: &[u8], block: usize| bytes.chunks_exact(block).all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7c00 != 0x7c00);
|
||||
for batch in jobs.chunks(OLD_BATCH) {
|
||||
let mut prepared = Vec::with_capacity(batch.len());
|
||||
for (e, pairs) in batch {
|
||||
let x = &bank[*e];
|
||||
let (g, u, d) = (x.gate.clone().into_boxed_slice(), x.up.clone().into_boxed_slice(), x.down.clone().into_boxed_slice());
|
||||
assert!(scan(&g, gb) && scan(&u, gb) && scan(&d, db));
|
||||
let mut input = Vec::with_capacity(pairs.len() * H);
|
||||
for &(row, _) in pairs {
|
||||
input.extend_from_slice(&tokens[row * H..(row + 1) * H]);
|
||||
}
|
||||
prepared.push(PreparedJob::new(gu, down, g, u, d, input.into_boxed_slice(), pairs.len()).expect("owned job"));
|
||||
}
|
||||
let done = pool.start(prepared, 48 << 20).expect("start").join().expect("join");
|
||||
for (job, (_, pairs)) in done.into_iter().zip(batch) {
|
||||
let values = job.into_values();
|
||||
for (i, &(row, slot)) in pairs.iter().enumerate() {
|
||||
let at = (row * TOP_K + slot) * H;
|
||||
out[at..at + H].copy_from_slice(&values[i * H..(i + 1) * H]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Model-free cost of one decode round's CPU share: 48 groups of `GROUP_ROWS` rows, `GROUP_SHARE`% of the
|
||||
/// entries on the CPU, experts drawn from a bank larger than the LLC. Same workers for both paths.
|
||||
#[test]
|
||||
#[ignore = "benchmark; prints the cost of both group paths"]
|
||||
fn group_path_cost() {
|
||||
let env = |name: &str, default: usize| std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(default);
|
||||
let workers = env("BENCH_WORKERS", 15) as i32;
|
||||
let rows = env("GROUP_ROWS", 4);
|
||||
let share = env("GROUP_SHARE", 50);
|
||||
let rounds = env("ROUNDS", 5);
|
||||
let (gu, down) = (GateUpFormat::Iq3S, DownFormat::Iq4Nl);
|
||||
let mut rng = Rng(42);
|
||||
let bank = bank(&mut rng, gu, down, env("BANK_EXPERTS", 256));
|
||||
let mut owned = CpuPool::new(workers).expect("owned pool");
|
||||
let mut direct = DirectCpuPool::new(workers).expect("direct pool");
|
||||
let groups: Vec<(Vec<f32>, Vec<(usize, Vec<(usize, usize)>)>)> = (0..48 * rounds)
|
||||
.map(|_| {
|
||||
let (ids, include) = route(&mut rng, rows, bank.len(), share);
|
||||
((0..rows * H).map(|_| rng.unit()).collect(), plan(&ids, &include))
|
||||
})
|
||||
.collect();
|
||||
let experts: usize = groups.iter().map(|(_, j)| j.len()).sum();
|
||||
let mut out = vec![0.0f32; rows * TOP_K * H];
|
||||
for arm in ["owned+source-copy", "owned", "borrowed", "owned+source-copy", "owned", "borrowed"] {
|
||||
let started = Instant::now();
|
||||
for (tokens, jobs) in &groups {
|
||||
match arm {
|
||||
"borrowed" => borrowed_path(&mut direct, gu, down, &bank, tokens, jobs, &mut out),
|
||||
"owned" => owned_path(&mut owned, gu, down, &bank, tokens, jobs, &mut out),
|
||||
_ => owned_path_with_source_copy(&mut owned, gu, down, &bank, tokens, jobs, &mut out),
|
||||
}
|
||||
}
|
||||
let ms = started.elapsed().as_secs_f64() * 1e3;
|
||||
let gb = experts as f64 * (bank[0].gate.len() * 2 + bank[0].down.len()) as f64 / 1e9;
|
||||
eprintln!(
|
||||
"BENCH {arm:>18}: workers={workers} rows={rows} share={share}% {:.2} experts/group, {:.2} ms/round (48 groups), {:.1} GB/s of expert bytes",
|
||||
experts as f64 / groups.len() as f64,
|
||||
ms / rounds as f64,
|
||||
gb / (ms / 1e3)
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user