STRA-338 size: cuda-driver complexity census back to parity (helpers trimmed), limits baseline tightened (fn_lines 2099 -> 2095, nesting 139 -> 136)
This commit is contained in:
@@ -148,6 +148,12 @@ impl<'ctx> GrNativeBatch<'ctx> {
|
||||
A::I64(t),
|
||||
]));
|
||||
args.push(self.scan(4, 320, 1)?);
|
||||
self.push_product_args(args, flags)
|
||||
}
|
||||
|
||||
/// Arguments of the products conversion and its finite flag kernel.
|
||||
fn push_product_args(&self, args: &mut Vec<KernelArguments>, flags: ffi::BufferHandle) -> Result<()> {
|
||||
let t = self.tokens as i64;
|
||||
args.push(Self::args(vec![
|
||||
A::Address(self.handle(4)?),
|
||||
A::Address(self.handle(5)?),
|
||||
@@ -168,6 +174,17 @@ impl<'ctx> GrNativeBatch<'ctx> {
|
||||
let t = self.tokens as i64;
|
||||
args.push(self.scan(7, 10240, 3)?);
|
||||
args.push(self.scan(12, 4, 6)?);
|
||||
self.push_mix_kernel_args(args, w0, flags)
|
||||
}
|
||||
|
||||
/// Arguments of the mix kernel; the inject arguments follow.
|
||||
fn push_mix_kernel_args(
|
||||
&self,
|
||||
args: &mut Vec<KernelArguments>,
|
||||
w0: ffi::BufferHandle,
|
||||
flags: ffi::BufferHandle,
|
||||
) -> Result<()> {
|
||||
let t = self.tokens as i64;
|
||||
args.push(Self::args(vec![
|
||||
A::Address(self.handle(0)?),
|
||||
A::Address(self.handle(1)?),
|
||||
@@ -179,6 +196,17 @@ impl<'ctx> GrNativeBatch<'ctx> {
|
||||
A::Address(self.handle(11)?),
|
||||
self.low(10)?,
|
||||
]));
|
||||
self.push_inject_args(args, w0, flags)
|
||||
}
|
||||
|
||||
/// Arguments of the inject kernel and the scan of the mixed state.
|
||||
fn push_inject_args(
|
||||
&self,
|
||||
args: &mut Vec<KernelArguments>,
|
||||
w0: ffi::BufferHandle,
|
||||
flags: ffi::BufferHandle,
|
||||
) -> Result<()> {
|
||||
let t = self.tokens as i64;
|
||||
args.push(Self::args(vec![
|
||||
A::Address(self.handle(0)?),
|
||||
A::Address(self.handle(1)?),
|
||||
@@ -198,6 +226,17 @@ impl<'ctx> GrNativeBatch<'ctx> {
|
||||
blas: &Blas,
|
||||
(w, flags, scalars): ([ffi::BufferHandle; 4], ffi::BufferHandle, &[f32; 3]),
|
||||
(zero, args, eligible): (&[u8], &mut [KernelArguments], &mut [bool; 8]),
|
||||
) -> Result<()> {
|
||||
self.native_commands_head(blas, (w, flags, scalars), (zero, &mut *args, &mut *eligible))?;
|
||||
self.native_commands_tail(blas, (w, scalars), (args, eligible))
|
||||
}
|
||||
|
||||
/// The flag reset, the norm and the first GEMM with its guards (stages 0..=2).
|
||||
fn native_commands_head(
|
||||
&self,
|
||||
blas: &Blas,
|
||||
(w, flags, scalars): ([ffi::BufferHandle; 4], ffi::BufferHandle, &[f32; 3]),
|
||||
(zero, args, eligible): (&[u8], &mut [KernelArguments], &mut [bool; 8]),
|
||||
) -> Result<()> {
|
||||
let (alpha, beta0, beta1) = (&scalars[0], &scalars[1], &scalars[2]);
|
||||
self.context.driver.api.copy_from(flags, zero)?;
|
||||
@@ -220,6 +259,17 @@ impl<'ctx> GrNativeBatch<'ctx> {
|
||||
self.launch(blas, 1, self.tokens * 320, &mut args[3])?;
|
||||
self.launch(blas, 6, self.tokens * 320, &mut args[4])?;
|
||||
eligible[2] = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The remaining GEMMs and kernels (stages 3..=6) in the literal Original order.
|
||||
fn native_commands_tail(
|
||||
&self,
|
||||
blas: &Blas,
|
||||
(w, scalars): ([ffi::BufferHandle; 4], &[f32; 3]),
|
||||
(args, eligible): (&mut [KernelArguments], &mut [bool; 8]),
|
||||
) -> Result<()> {
|
||||
let (alpha, beta0, beta1) = (&scalars[0], &scalars[1], &scalars[2]);
|
||||
self.gemm(blas, 5, 6, w[2], 7, 10240, 320, alpha, beta0, beta1)?;
|
||||
self.launch(blas, 4, self.tokens * 10240, &mut args[5])?;
|
||||
eligible[3] = true;
|
||||
|
||||
@@ -43,8 +43,12 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
|
||||
{
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
// Require the SAME genuine producer's group spans. A different arena with
|
||||
// identical shapes is not a substitute for this layer's affine Mixed source.
|
||||
self.copy_ring_same_spans(read)
|
||||
}
|
||||
|
||||
// Require the SAME genuine producer's group spans. A different arena with
|
||||
// identical shapes is not a substitute for this layer's affine Mixed source.
|
||||
fn copy_ring_same_spans(&self, read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>) -> Result<()> {
|
||||
for index in 0..TMP {
|
||||
let (a, n) = self.span(index)?;
|
||||
let (b, m) = GroupArena::span(read, index)?;
|
||||
@@ -219,6 +223,11 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
|
||||
}
|
||||
|
||||
fn check_group_status([gu, h, q, down]: [u32; 4]) -> Result<()> {
|
||||
Self::check_gate_up_status(gu, h)?;
|
||||
Self::check_q8_down_status(q, down)
|
||||
}
|
||||
|
||||
fn check_gate_up_status(gu: u32, h: u32) -> Result<()> {
|
||||
match gu {
|
||||
0 => {}
|
||||
1 | 3 => return Err(Error::NonFiniteMmqOutput("Gate")),
|
||||
@@ -230,6 +239,10 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
|
||||
1 => return Err(Error::NonFiniteMmqOutput("SwiGLU")),
|
||||
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_q8_down_status(q: u32, down: u32) -> Result<()> {
|
||||
match q {
|
||||
0 => {}
|
||||
1 | 3 => return Err(Error::InvalidQ8Activation),
|
||||
|
||||
@@ -227,24 +227,32 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
|
||||
if lease.cache_expert_span(usize::from(layer), expert as usize)?.is_some() {
|
||||
continue;
|
||||
}
|
||||
let exact = bank.expert_pieces(layer, expert)?;
|
||||
let slot_bytes = targets.iter().map(|t| t.1).min().unwrap_or(0);
|
||||
// page-aligned supersets side by side at page offsets when they fit the slot (claude/ledger), else the
|
||||
// exact pieces back to back
|
||||
let mut entry = None;
|
||||
if aligned_copy {
|
||||
entry = Self::aligned_entry(bank, (layer, expert), exact, slot_bytes)?;
|
||||
}
|
||||
let entry = match entry {
|
||||
Some(e) => e,
|
||||
None => Self::exact_entry((layer, expert), exact, slot_bytes)?,
|
||||
};
|
||||
entries.push(entry);
|
||||
entries.push(Self::stream_entry(bank, (layer, expert), aligned_copy, targets)?);
|
||||
}
|
||||
}
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
/// The entry of one expert: its page-aligned supersets side by side at page offsets when they fit the slot
|
||||
/// (claude/ledger), else the exact pieces back to back.
|
||||
fn stream_entry(
|
||||
bank: &Rc<crate::MappedExpertBank<'ctx>>,
|
||||
(layer, expert): (u8, u32),
|
||||
aligned_copy: bool,
|
||||
targets: &[(ffi::BufferHandle, usize)],
|
||||
) -> Result<StreamEntry> {
|
||||
let exact = bank.expert_pieces(layer, expert)?;
|
||||
let slot_bytes = targets.iter().map(|t| t.1).min().unwrap_or(0);
|
||||
let mut entry = None;
|
||||
if aligned_copy {
|
||||
entry = Self::aligned_entry(bank, (layer, expert), exact, slot_bytes)?;
|
||||
}
|
||||
match entry {
|
||||
Some(e) => Ok(e),
|
||||
None => Self::exact_entry((layer, expert), exact, slot_bytes),
|
||||
}
|
||||
}
|
||||
|
||||
/// The expert's page-aligned supersets side by side, or none when they do not fit the slot.
|
||||
fn aligned_entry(
|
||||
bank: &Rc<crate::MappedExpertBank<'ctx>>,
|
||||
@@ -328,23 +336,30 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
|
||||
|
||||
/// Creates the `copied`, `used` and `start` event blocks (`ring` events each; timing events when the
|
||||
/// statistics are on); on failure destroys the events already created.
|
||||
/// Pushes `count` events; with the statistics on, `copied` (first block) and `start` (third block) carry
|
||||
/// timestamps.
|
||||
fn create_events(
|
||||
api: &crate::ffi::original_stager::Api,
|
||||
events: &mut Vec<usize>,
|
||||
(count, ring, stats): (usize, usize, bool),
|
||||
) -> Result<()> {
|
||||
events.try_reserve_exact(count).map_err(|_| Error::HostAllocation)?;
|
||||
for i in 0..count {
|
||||
events.push(if stats && (i < ring || i >= 2 * ring) {
|
||||
api.event_create_timing()?
|
||||
} else {
|
||||
api.event_create()?
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stream_make_events(&self, api: &crate::ffi::original_stager::Api, ring: usize) -> Result<Vec<usize>> {
|
||||
let guard = self.context.enter()?;
|
||||
let mut events = Vec::new();
|
||||
let stats = std::env::var_os("LELEKA_PREFILL_COPY_STATS").is_some_and(|v| v == "1");
|
||||
let per_slot = if stats { 3 } else { 2 };
|
||||
let created = (|| -> Result<()> {
|
||||
events.try_reserve_exact(per_slot * ring).map_err(|_| Error::HostAllocation)?;
|
||||
for i in 0..per_slot * ring {
|
||||
// with the statistics on, `copied` (first block) and `start` (third block) carry timestamps
|
||||
events.push(if stats && (i < ring || i >= 2 * ring) {
|
||||
api.event_create_timing()?
|
||||
} else {
|
||||
api.event_create()?
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
let created = Self::create_events(api, &mut events, (per_slot * ring, ring, stats));
|
||||
let pop = guard.finish();
|
||||
if let Err(primary) = combine(created, pop) {
|
||||
let guard = self.context.enter()?;
|
||||
|
||||
@@ -89,6 +89,10 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
self.attach_stream(plan)?;
|
||||
let jobs = self.plan_host_jobs(plan)?;
|
||||
self.admit_status(plan)?;
|
||||
self.start_jobs(jobs, plan)
|
||||
}
|
||||
|
||||
fn start_jobs(&mut self, jobs: Vec<Job>, plan: &RingPlan) -> Result<()> {
|
||||
// The old input quantization/metadata upload used default stream.
|
||||
// Admit that dependency once before starting nonblocking producers.
|
||||
self.context.synchronize()?;
|
||||
@@ -210,12 +214,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
let entry =
|
||||
stream.entry(plan.layer as u8, source.spans[0].expert()).ok_or(Error::InvalidProjectionShape)?;
|
||||
// the stream copies exactly the bytes this span names
|
||||
let sources = [
|
||||
bank.cache_source(&source.spans[0])?,
|
||||
bank.cache_source(&source.spans[1])?,
|
||||
bank.cache_source(&source.spans[2])?,
|
||||
];
|
||||
if !stream.entry_matches(entry, sources) {
|
||||
if !stream.entry_matches(entry, Self::source_pieces(bank, source.spans)?) {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
source.entry = Some(entry);
|
||||
@@ -225,6 +224,14 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The gate, up and down host ranges of one expert.
|
||||
fn source_pieces<'b>(
|
||||
bank: &'b crate::MappedExpertBank<'ctx>,
|
||||
spans: &[ResidentExpertBankSpan; 3],
|
||||
) -> Result<[&'b [u8]; 3]> {
|
||||
Ok([bank.cache_source(&spans[0])?, bank.cache_source(&spans[1])?, bank.cache_source(&spans[2])?])
|
||||
}
|
||||
|
||||
/// Experts not page-locked (a pageable bank) are copied by the host stager's helpers into page-locked
|
||||
/// buffers, in launch order, ahead of their DMAs.
|
||||
fn plan_host_jobs(&mut self, plan: &RingPlan) -> Result<Vec<Job>> {
|
||||
@@ -260,15 +267,20 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
{
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
self.status = match self.schedule.status_pool.take() {
|
||||
Some((bytes, buffer)) if bytes >= charge => Some(buffer),
|
||||
self.status = Some(self.status_buffer(charge)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The pooled status buffer when it is large enough, else a fresh one (the pooled one is released).
|
||||
fn status_buffer(&mut self, charge: usize) -> Result<DeviceBuffer<'ctx>> {
|
||||
match self.schedule.status_pool.take() {
|
||||
Some((bytes, buffer)) if bytes >= charge => Ok(buffer),
|
||||
Some((_, other)) => {
|
||||
other.release()?;
|
||||
Some(context.allocate(charge.max(512))?)
|
||||
self.context.allocate(charge.max(512))
|
||||
}
|
||||
None => Some(context.allocate(charge.max(512))?),
|
||||
};
|
||||
Ok(())
|
||||
None => self.context.allocate(charge.max(512)),
|
||||
}
|
||||
}
|
||||
|
||||
fn start_host_stage(&mut self, jobs: Vec<Job>, plan: &RingPlan) -> Result<()> {
|
||||
@@ -295,18 +307,28 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
}
|
||||
}
|
||||
if schedule.host.is_none() {
|
||||
let guard = context.enter()?;
|
||||
let created = HostStage::new(blob, pageable);
|
||||
let pop = guard.finish();
|
||||
let host = match (created, pop) {
|
||||
(Ok(host), Ok(())) => host,
|
||||
(Err(e), _) | (Ok(_), Err(e)) => return Err(e),
|
||||
};
|
||||
for _ in 0..host.ring() {
|
||||
schedule.host_events.push(context.original_gpu_event(OriginalEventKind::Completion)?);
|
||||
}
|
||||
schedule.host = Some(host);
|
||||
Self::create_host_stage(context, schedule, blob, pageable)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_host_stage(
|
||||
context: &'ctx Context<'ctx>,
|
||||
schedule: &mut OriginalMmqCopySchedule<'ctx>,
|
||||
blob: usize,
|
||||
pageable: bool,
|
||||
) -> Result<()> {
|
||||
let guard = context.enter()?;
|
||||
let created = HostStage::new(blob, pageable);
|
||||
let pop = guard.finish();
|
||||
let host = match (created, pop) {
|
||||
(Ok(host), Ok(())) => host,
|
||||
(Err(e), _) | (Ok(_), Err(e)) => return Err(e),
|
||||
};
|
||||
for _ in 0..host.ring() {
|
||||
schedule.host_events.push(context.original_gpu_event(OriginalEventKind::Completion)?);
|
||||
}
|
||||
schedule.host = Some(host);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
+1
-5
@@ -32,11 +32,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
|
||||
let q = Self::prefix_embedding_branch(scalar, &mut cmds, &a, &wh, t)?;
|
||||
Self::prefix_hidden_branch(scalar, &mut cmds, &a, &wh, (q, t))?;
|
||||
Self::prefix_mix_and_gr(scalar, &mut cmds, &a, &wh, (t, &prefix_policy))?;
|
||||
let (kc, vc) = Self::prefix_kv_projection(scalar, ring, &mut cmds, &a, (&wh, q, t))?;
|
||||
for row in 0..t {
|
||||
Self::prefix_row_commands(scalar, ring, &mut cmds, &a, (&policy.kv, &wh, kc, vc, row))?;
|
||||
}
|
||||
Self::prefix_publish_steps(scalar, ring, &mut cmds, (a.step, t))?;
|
||||
Self::prefix_tail(scalar, ring, &mut cmds, &a, (&policy.kv, &wh, q, t))?;
|
||||
Ok((cmds, native_embedding))
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -77,7 +77,8 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
|
||||
]))
|
||||
}
|
||||
|
||||
/// The tail scratch, the extra banks and the ring state may overlap nothing but the genuinely shared scalar scratch.
|
||||
/// The tail scratch, the extra banks and the ring state may overlap nothing but the genuinely shared scalar
|
||||
/// scratch.
|
||||
fn program_reject_aliases(
|
||||
&self,
|
||||
scalar: &OriginalMtpScalarPrefill<'ctx>,
|
||||
|
||||
+37
-88
@@ -84,10 +84,15 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
|
||||
return Err(Error::OutputAliasesInput);
|
||||
}
|
||||
}
|
||||
for output in ring.buffers()?.iter().flatten() {
|
||||
if h.overlaps(b.bytes, output.handle.ok_or(Error::ContextPoisoned)?, output.bytes) {
|
||||
return Err(Error::OutputAliasesInput);
|
||||
}
|
||||
Self::prefix_reject_ring_overlap(ring, h, b.bytes)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn prefix_reject_ring_overlap(ring: &MtpOriginalInt8<'ctx>, h: BufferHandle, bytes: usize) -> Result<()> {
|
||||
for output in ring.buffers()?.iter().flatten() {
|
||||
if h.overlaps(bytes, output.handle.ok_or(Error::ContextPoisoned)?, output.bytes) {
|
||||
return Err(Error::OutputAliasesInput);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -182,20 +187,27 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
|
||||
t: usize,
|
||||
step_row: usize,
|
||||
) -> Result<PrefixAddrs> {
|
||||
let rin = scalar.address(0, t * 40960)?;
|
||||
let emb = scalar.address(2, t * 10240)?;
|
||||
let en = scalar.address(3, t * 10240)?;
|
||||
let e2 = scalar.address(4, t * 10240)?;
|
||||
let hn = scalar.address(5, t * 40960)?;
|
||||
let h2 = scalar.address(6, t * 40960)?;
|
||||
let r = scalar.address(1, t * 40960)?;
|
||||
let mixed = scalar.address(11, t * 10240)?;
|
||||
let tok = scalar.address(12, t * 4)?;
|
||||
let [rin, emb, en, e2, hn, h2, r, mixed, tok] = Self::prefix_scalar_addresses(scalar, t)?;
|
||||
let step = self.inner.address(31)? + (step_row * 16) as u64;
|
||||
let pos = self.inner.address(32)? + (step_row * 96) as u64;
|
||||
Ok(PrefixAddrs { rin, emb, en, e2, hn, h2, r, mixed, tok, step, pos })
|
||||
}
|
||||
|
||||
/// `[rin, emb, en, e2, hn, h2, r, mixed, tok]` scratch addresses of the scalar owner.
|
||||
fn prefix_scalar_addresses(scalar: &OriginalMtpScalarPrefill<'ctx>, t: usize) -> Result<[u64; 9]> {
|
||||
Ok([
|
||||
scalar.address(0, t * 40960)?,
|
||||
scalar.address(2, t * 10240)?,
|
||||
scalar.address(3, t * 10240)?,
|
||||
scalar.address(4, t * 10240)?,
|
||||
scalar.address(5, t * 40960)?,
|
||||
scalar.address(6, t * 40960)?,
|
||||
scalar.address(1, t * 40960)?,
|
||||
scalar.address(11, t * 10240)?,
|
||||
scalar.address(12, t * 4)?,
|
||||
])
|
||||
}
|
||||
|
||||
pub(super) fn prefix_native_embedding(
|
||||
scalar: &OriginalMtpScalarPrefill<'ctx>,
|
||||
retained: &OriginalMtpRetainedPrefix<'ctx>,
|
||||
@@ -215,79 +227,6 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
|
||||
Ok(native_embedding)
|
||||
}
|
||||
|
||||
/// Embedding row lookup of the `t` token ids into `emb`, for a device-resident embedding table.
|
||||
pub(super) fn prefix_embedding_lookup(
|
||||
cmds: &mut Vec<ScalarCommand>,
|
||||
embedding: OriginalMtpEmbedding<'_, 'ctx>,
|
||||
a: &PrefixAddrs,
|
||||
t: usize,
|
||||
) -> Result<()> {
|
||||
let eh = embedding.table.handle.ok_or(Error::ContextPoisoned)?;
|
||||
match embedding.kind {
|
||||
EmbeddingKind::Native { kind, row_bytes, .. } => {
|
||||
Self::prefix_lookup_native(cmds, a, (eh.qwen_address(), kind, row_bytes), t)
|
||||
}
|
||||
EmbeddingKind::Compressed { bits, bias, group, codes, scales, offsets, .. } => {
|
||||
let layout = (eh.qwen_address(), codes, if offsets { Some(scales) } else { None });
|
||||
Self::prefix_lookup_compressed(cmds, a, (layout, bits, bias, group), t)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prefix_lookup_native(
|
||||
cmds: &mut Vec<ScalarCommand>,
|
||||
a: &PrefixAddrs,
|
||||
(table, kind, row_bytes): (u64, i32, usize),
|
||||
t: usize,
|
||||
) -> Result<()> {
|
||||
OriginalMtpScalarPrefill::kernel(
|
||||
cmds,
|
||||
1,
|
||||
0,
|
||||
[10, t as u32, 1],
|
||||
[32, 1, 1],
|
||||
0,
|
||||
vec![
|
||||
Arg::I32(kind),
|
||||
Arg::U64(table),
|
||||
Arg::U64(row_bytes as u64),
|
||||
Arg::U64(a.tok),
|
||||
Arg::I64(2560),
|
||||
Arg::U64(a.emb),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// `layout` is `(table address, code bytes, scale bytes when offsets follow)`.
|
||||
fn prefix_lookup_compressed(
|
||||
cmds: &mut Vec<ScalarCommand>,
|
||||
a: &PrefixAddrs,
|
||||
((table, codes, offsets), bits, bias, group): ((u64, usize, Option<usize>), i32, i32, usize),
|
||||
t: usize,
|
||||
) -> Result<()> {
|
||||
OriginalMtpScalarPrefill::kernel(
|
||||
cmds,
|
||||
0,
|
||||
5,
|
||||
[10, t as u32, 1],
|
||||
[256, 1, 1],
|
||||
0,
|
||||
vec![
|
||||
Arg::U64(table),
|
||||
Arg::U64(table + codes as u64),
|
||||
Arg::U64(if let Some(scales) = offsets { table + (codes + scales) as u64 } else { 0 }),
|
||||
Arg::U64(a.tok),
|
||||
Arg::I64(2560),
|
||||
Arg::I32(bits),
|
||||
Arg::I32(bias),
|
||||
Arg::I32(group as i32),
|
||||
Arg::U64((2560 / (8 / bits)) as u64),
|
||||
Arg::U64((2560 / group) as u64),
|
||||
Arg::U64(a.emb),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// RMS norm of `rows` rows of `width` floats (eps 1e-6).
|
||||
fn prefix_rms_norm(
|
||||
cmds: &mut Vec<ScalarCommand>,
|
||||
@@ -367,12 +306,22 @@ impl<'ctx> OriginalMtpFullForward<'ctx> {
|
||||
)?;
|
||||
scalar.finite(cmds, a.r, t * 10240, group, 5)?;
|
||||
scalar.gr(cmds, t, wh, policy)?;
|
||||
Self::prefix_gr_guards(scalar, cmds, a.mixed, t)
|
||||
}
|
||||
|
||||
/// Finite guards over the GR outputs and the mixed state.
|
||||
fn prefix_gr_guards(
|
||||
scalar: &OriginalMtpScalarPrefill<'ctx>,
|
||||
cmds: &mut Vec<ScalarCommand>,
|
||||
mixed: u64,
|
||||
t: usize,
|
||||
) -> Result<()> {
|
||||
let group = 0usize;
|
||||
scalar.finite(cmds, scalar.address(9, t * 16)?, t * 4, group, 6)?;
|
||||
scalar.finite(cmds, scalar.address(7, t * 40960)?, t * 10240, group, 6)?;
|
||||
scalar.finite(cmds, scalar.address(8, t * 1280)?, t * 320, group, 7)?;
|
||||
scalar.finite(cmds, scalar.address(10, t * 16)?, t * 4, group, 7)?;
|
||||
scalar.finite(cmds, a.mixed, t * 2560, group, 8)?;
|
||||
Ok(())
|
||||
scalar.finite(cmds, mixed, t * 2560, group, 8)
|
||||
}
|
||||
|
||||
/// K and V projections of the mixed state into the current KV cells; returns `(k, v)` addresses.
|
||||
|
||||
+89
-1
@@ -1,10 +1,98 @@
|
||||
//! Per-row and closing commands of `OriginalMtpFullForward::prefix_commands`, split out by STRA-338 (size).
|
||||
//! Embedding lookup, per-row and closing commands of `OriginalMtpFullForward::prefix_commands` (STRA-338 size).
|
||||
|
||||
use super::prefix_parts::PrefixAddrs;
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
impl<'ctx> OriginalMtpFullForward<'ctx> {
|
||||
/// Embedding row lookup of the `t` token ids into `emb`, for a device-resident embedding table.
|
||||
pub(super) fn prefix_embedding_lookup(
|
||||
cmds: &mut Vec<ScalarCommand>,
|
||||
embedding: OriginalMtpEmbedding<'_, 'ctx>,
|
||||
a: &PrefixAddrs,
|
||||
t: usize,
|
||||
) -> Result<()> {
|
||||
let eh = embedding.table.handle.ok_or(Error::ContextPoisoned)?;
|
||||
match embedding.kind {
|
||||
EmbeddingKind::Native { kind, row_bytes, .. } => {
|
||||
Self::prefix_lookup_native(cmds, a, (eh.qwen_address(), kind, row_bytes), t)
|
||||
}
|
||||
EmbeddingKind::Compressed { bits, bias, group, codes, scales, offsets, .. } => {
|
||||
let layout = (eh.qwen_address(), codes, if offsets { Some(scales) } else { None });
|
||||
Self::prefix_lookup_compressed(cmds, a, (layout, bits, bias, group), t)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prefix_lookup_native(
|
||||
cmds: &mut Vec<ScalarCommand>,
|
||||
a: &PrefixAddrs,
|
||||
(table, kind, row_bytes): (u64, i32, usize),
|
||||
t: usize,
|
||||
) -> Result<()> {
|
||||
OriginalMtpScalarPrefill::kernel(
|
||||
cmds,
|
||||
1,
|
||||
0,
|
||||
[10, t as u32, 1],
|
||||
[32, 1, 1],
|
||||
0,
|
||||
vec![
|
||||
Arg::I32(kind),
|
||||
Arg::U64(table),
|
||||
Arg::U64(row_bytes as u64),
|
||||
Arg::U64(a.tok),
|
||||
Arg::I64(2560),
|
||||
Arg::U64(a.emb),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// `layout` is `(table address, code bytes, scale bytes when offsets follow)`.
|
||||
fn prefix_lookup_compressed(
|
||||
cmds: &mut Vec<ScalarCommand>,
|
||||
a: &PrefixAddrs,
|
||||
((table, codes, offsets), bits, bias, group): ((u64, usize, Option<usize>), i32, i32, usize),
|
||||
t: usize,
|
||||
) -> Result<()> {
|
||||
OriginalMtpScalarPrefill::kernel(
|
||||
cmds,
|
||||
0,
|
||||
5,
|
||||
[10, t as u32, 1],
|
||||
[256, 1, 1],
|
||||
0,
|
||||
vec![
|
||||
Arg::U64(table),
|
||||
Arg::U64(table + codes as u64),
|
||||
Arg::U64(if let Some(scales) = offsets { table + (codes + scales) as u64 } else { 0 }),
|
||||
Arg::U64(a.tok),
|
||||
Arg::I64(2560),
|
||||
Arg::I32(bits),
|
||||
Arg::I32(bias),
|
||||
Arg::I32(group as i32),
|
||||
Arg::U64((2560 / (8 / bits)) as u64),
|
||||
Arg::U64((2560 / group) as u64),
|
||||
Arg::U64(a.emb),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// K/V projection, the per-row commands and the closing step publication.
|
||||
pub(super) fn prefix_tail(
|
||||
scalar: &OriginalMtpScalarPrefill<'ctx>,
|
||||
ring: &MtpOriginalInt8<'ctx>,
|
||||
cmds: &mut Vec<ScalarCommand>,
|
||||
a: &PrefixAddrs,
|
||||
(kv, wh, q, t): (&DraftKvPolicy, &[BufferHandle; 11], u64, usize),
|
||||
) -> Result<()> {
|
||||
let (kc, vc) = Self::prefix_kv_projection(scalar, ring, cmds, a, (wh, q, t))?;
|
||||
for row in 0..t {
|
||||
Self::prefix_row_commands(scalar, ring, cmds, a, (kv, wh, kc, vc, row))?;
|
||||
}
|
||||
Self::prefix_publish_steps(scalar, ring, cmds, (a.step, t))
|
||||
}
|
||||
|
||||
/// Per-row K norm, K rope, and the literal step append kernel on the actual private step record.
|
||||
pub(super) fn prefix_row_commands(
|
||||
scalar: &OriginalMtpScalarPrefill<'ctx>,
|
||||
|
||||
@@ -292,20 +292,22 @@ fn native_head_geometry(kind: u32) -> Result<(usize, usize)> {
|
||||
})
|
||||
}
|
||||
|
||||
const HEAD_TABLES: [(u32, &[&str; HEAD_NAMES_PER_KIND]); 10] = [
|
||||
(2, &HEAD_N2),
|
||||
(6, &HEAD_N6),
|
||||
(8, &HEAD_N8),
|
||||
(20, &HEAD_N20),
|
||||
(11, &HEAD_N11),
|
||||
(12, &HEAD_N12),
|
||||
(13, &HEAD_N13),
|
||||
(14, &HEAD_N14),
|
||||
(23, &HEAD_N23),
|
||||
(42, &HEAD_N42),
|
||||
];
|
||||
|
||||
fn native_kernel_name(kind: u32, t: usize, mode: usize) -> Result<&'static str> {
|
||||
let names = match kind {
|
||||
2 => &HEAD_N2,
|
||||
6 => &HEAD_N6,
|
||||
8 => &HEAD_N8,
|
||||
20 => &HEAD_N20,
|
||||
11 => &HEAD_N11,
|
||||
12 => &HEAD_N12,
|
||||
13 => &HEAD_N13,
|
||||
14 => &HEAD_N14,
|
||||
23 => &HEAD_N23,
|
||||
42 => &HEAD_N42,
|
||||
_ => return Err(Error::UnsupportedQwenOperation),
|
||||
};
|
||||
let names = HEAD_TABLES.iter().find(|(k, _)| *k == kind).map(|(_, names)| *names);
|
||||
let names = names.ok_or(Error::UnsupportedQwenOperation)?;
|
||||
let index = if t == 1 { mode } else { 2 + (t - 2) * 3 + (mode - 2) };
|
||||
Ok(names[index])
|
||||
}
|
||||
|
||||
@@ -33,11 +33,17 @@ impl FullGeometry {
|
||||
Some(l) => sizes.iter().try_fold(l.bytes, |a, n| a.checked_add(*n).ok_or(Error::InvalidSize))?,
|
||||
None => layout.bytes,
|
||||
};
|
||||
Self::admit_charge(c, own_bytes)?;
|
||||
Ok(Self { layout, original_layout, sizes })
|
||||
}
|
||||
|
||||
/// The owner's bytes plus the reserve must fit the context budget and the physical free memory.
|
||||
fn admit_charge(c: &Context<'_>, own_bytes: usize) -> Result<()> {
|
||||
let charge = own_bytes.checked_add(RESERVE_BYTES).ok_or(Error::BudgetExceeded)?;
|
||||
if c.allocated_bytes().checked_add(charge).is_none_or(|n| n > c.budget) || c.memory_info()?.0 < charge {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
Ok(Self { layout, original_layout, sizes })
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+33
-16
@@ -87,6 +87,26 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
|
||||
prompt_cap: usize,
|
||||
exact: Option<&OriginalLayoutSetup<'ctx>>,
|
||||
) -> Result<()> {
|
||||
let charge = Self::admit_layout(c, max_t, prompt_cap, exact)?;
|
||||
let required = charge.checked_add(RESERVE_BYTES).ok_or(Error::BudgetExceeded)?;
|
||||
if c.is_poisoned() || c.handle.is_none() {
|
||||
return Err(Error::ContextPoisoned);
|
||||
}
|
||||
if c.allocated_bytes().checked_add(required).is_none_or(|n| n > c.budget_bytes())
|
||||
|| c.memory_info()?.0 < required
|
||||
{
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Shape and sealed-asset admission; returns the device bytes the owner will charge.
|
||||
fn admit_layout(
|
||||
c: &'ctx Context<'ctx>,
|
||||
max_t: usize,
|
||||
prompt_cap: usize,
|
||||
exact: Option<&OriginalLayoutSetup<'ctx>>,
|
||||
) -> Result<usize> {
|
||||
let legacy_charge = Self::planned_device_bytes(max_t, prompt_cap)?;
|
||||
let charge = if exact.is_some() {
|
||||
legacy_charge.checked_sub(Scratch::new(max_t)?.bytes).ok_or(Error::InvalidSize)?
|
||||
@@ -102,16 +122,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
|
||||
if Self::scalar_assets().iter().any(|p| p.windows(8).any(|w| w == b"UNSEALED")) {
|
||||
return Err(Error::UnsupportedQwenOperation);
|
||||
}
|
||||
let required = charge.checked_add(RESERVE_BYTES).ok_or(Error::BudgetExceeded)?;
|
||||
if c.is_poisoned() || c.handle.is_none() {
|
||||
return Err(Error::ContextPoisoned);
|
||||
}
|
||||
if c.allocated_bytes().checked_add(required).is_none_or(|n| n > c.budget_bytes())
|
||||
|| c.memory_info()?.0 < required
|
||||
{
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
Ok(())
|
||||
Ok(charge)
|
||||
}
|
||||
|
||||
/// An owner with no device memory, modules or stream yet.
|
||||
@@ -151,6 +162,18 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
|
||||
|
||||
fn init_device(&mut self, c: &'ctx Context<'ctx>, exact: Option<&OriginalLayoutSetup<'ctx>>) -> Result<()> {
|
||||
self.init_modules(c)?;
|
||||
self.init_buffers(c, exact)?;
|
||||
self.init_mapped(c, exact)?;
|
||||
self.graphs = Some(OriginalGraphRegistry::new(c, 2 * self.max_t)?);
|
||||
self.pending_host.try_reserve_exact(2).map_err(|_| Error::HostAllocation)?;
|
||||
if c.memory_info()?.0 < RESERVE_BYTES {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The scratch bank (shared when `exact`), the record and status buffers, and the private stream.
|
||||
fn init_buffers(&mut self, c: &'ctx Context<'ctx>, exact: Option<&OriginalLayoutSetup<'ctx>>) -> Result<()> {
|
||||
self.scratch = Some(match exact {
|
||||
Some(e) => Rc::clone(&e.bank),
|
||||
None => Rc::new(c.allocate(self.layout.bytes)?),
|
||||
@@ -158,12 +181,6 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> {
|
||||
self.records = Some(Rc::new(c.allocate(self.prompt_cap * 29 * 4)?));
|
||||
self.status = Some(Rc::new(c.allocate((self.prompt_cap.div_ceil(self.max_t) + 1) * SCALAR_FLAGS * 4)?));
|
||||
self.stream = Some(c.original_gpu_stream(OriginalStreamKind::NonBlocking)?);
|
||||
self.init_mapped(c, exact)?;
|
||||
self.graphs = Some(OriginalGraphRegistry::new(c, 2 * self.max_t)?);
|
||||
self.pending_host.try_reserve_exact(2).map_err(|_| Error::HostAllocation)?;
|
||||
if c.memory_info()?.0 < RESERVE_BYTES {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -33,10 +33,10 @@
|
||||
"width": 6
|
||||
},
|
||||
"leleka-cuda-driver": {
|
||||
"fn_lines": 680,
|
||||
"fn_lines": 676,
|
||||
"width": 1093,
|
||||
"complexity": 668,
|
||||
"nesting": 32
|
||||
"nesting": 29
|
||||
},
|
||||
"leleka-deploy": {
|
||||
"fn_lines": 105,
|
||||
|
||||
Reference in New Issue
Block a user