STRA-338 params q04: adaptive preload, draft KV finish, draft schedules, spec config and window failure take domain DTOs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
e935385afe
commit
d6d7e2b32a
+2
-9
@@ -251,15 +251,8 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
working_reserve: WORKING_RESERVE,
|
||||
window_spill: plan.window_spill,
|
||||
};
|
||||
cache_strata_adaptive::AdaptiveCache::preload(
|
||||
binding,
|
||||
context,
|
||||
profile,
|
||||
plan.template,
|
||||
limits,
|
||||
shared_bytes,
|
||||
plan.metadata,
|
||||
)
|
||||
let sizing = cache_strata_adaptive::AdaptiveSizing { profile, template: plan.template, limits };
|
||||
cache_strata_adaptive::AdaptiveCache::preload(binding, context, sizing, shared_bytes, plan.metadata)
|
||||
}
|
||||
|
||||
fn adopt_adaptive(
|
||||
|
||||
@@ -23,6 +23,14 @@ pub(super) struct Slot {
|
||||
pub(super) keys: [MoeWeightDescriptor; 3],
|
||||
pub(super) bytes: usize,
|
||||
}
|
||||
/// What an adaptive policy is sized from: the profile ranking, the first-expert descriptors of every layer and the
|
||||
/// memory limits it must fit.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct AdaptiveSizing<'profile> {
|
||||
pub(super) profile: &'profile RankedProfile,
|
||||
pub(super) template: [[MoeWeightDescriptor; 3]; LAYERS],
|
||||
pub(super) limits: ProfileLimits,
|
||||
}
|
||||
/// All storage is bounded and reserved before any numeric/device consumer.
|
||||
/// `resident` names metadata slots only. The cache adapter must separately own
|
||||
/// the genuine whole weight buffers; no caller receives a raw slot capability.
|
||||
|
||||
+11
-4
@@ -9,6 +9,14 @@ mod preload;
|
||||
type StagedPairs<'ctx> = Vec<(DeviceBuffer<'ctx>, Vec<u8>)>;
|
||||
type Staged<'ctx> = (Swap, StagedPairs<'ctx>);
|
||||
|
||||
/// The device bytes the admission of every slot role upload keeps free: the window spill reserve and the shared pool
|
||||
/// the adaptive tier sits beside.
|
||||
#[derive(Clone, Copy)]
|
||||
struct UploadReserve {
|
||||
spill_reserve: usize,
|
||||
shared_bytes: usize,
|
||||
}
|
||||
|
||||
/// Slot buffers and transfer queue, both reserved up front so later phases never allocate.
|
||||
struct Reserved<'ctx> {
|
||||
buffers: Vec<Option<[DeviceBuffer<'ctx>; 3]>>,
|
||||
@@ -19,18 +27,17 @@ impl<'ctx> AdaptiveCache<'ctx> {
|
||||
pub(in super::super) fn preload(
|
||||
binding: &ModelBinding,
|
||||
context: &'ctx Context<'ctx>,
|
||||
profile: &RankedProfile,
|
||||
template: [[MoeWeightDescriptor; 3]; LAYERS],
|
||||
limits: ProfileLimits,
|
||||
sizing: AdaptiveSizing<'_>,
|
||||
shared_bytes: usize,
|
||||
external_metadata: usize,
|
||||
) -> Result<Self> {
|
||||
let AdaptiveSizing { profile, template, limits } = sizing;
|
||||
let largest = template.iter().try_fold(0usize, |max, keys| Ok::<_, Error>(max.max(blob_bytes(keys)?)))?;
|
||||
let spill_reserve = limits.window_spill.checked_add(largest).ok_or(Error::Overflow)?;
|
||||
let policy = AdaptivePolicy::new(profile, template, limits)?;
|
||||
let reserved = Self::reserve_owners(&policy, external_metadata)?;
|
||||
let mut owner = Self::unpublished(binding, context, policy, reserved);
|
||||
if let Err(primary) = owner.preload_slots(binding, spill_reserve, shared_bytes) {
|
||||
if let Err(primary) = owner.preload_slots(binding, UploadReserve { spill_reserve, shared_bytes }) {
|
||||
let _ = owner.close();
|
||||
return Err(primary);
|
||||
}
|
||||
|
||||
+6
-12
@@ -19,17 +19,12 @@ impl<'ctx> AdaptiveCache<'ctx> {
|
||||
}
|
||||
Ok(Reserved { buffers, transfers })
|
||||
}
|
||||
pub(super) fn preload_slots(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
spill_reserve: usize,
|
||||
shared_bytes: usize,
|
||||
) -> Result<()> {
|
||||
pub(super) fn preload_slots(&mut self, binding: &ModelBinding, reserve: UploadReserve) -> Result<()> {
|
||||
for slot in 0..self.buffers.len() {
|
||||
let keys = self.policy.slots[slot].keys;
|
||||
self.revalidate_keys(binding, keys)?;
|
||||
let mut loaded: [Option<DeviceBuffer<'ctx>>; 3] = std::array::from_fn(|_| None);
|
||||
if let Err(primary) = self.load_slot(binding, keys, spill_reserve, shared_bytes, &mut loaded) {
|
||||
if let Err(primary) = self.load_slot(binding, keys, reserve, &mut loaded) {
|
||||
for buffer in loaded.into_iter().rev().flatten() {
|
||||
if buffer.release().is_err() {
|
||||
self.failed = true;
|
||||
@@ -45,12 +40,11 @@ impl<'ctx> AdaptiveCache<'ctx> {
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
keys: [MoeWeightDescriptor; 3],
|
||||
spill_reserve: usize,
|
||||
shared_bytes: usize,
|
||||
reserve: UploadReserve,
|
||||
loaded: &mut [Option<DeviceBuffer<'ctx>>; 3],
|
||||
) -> Result<()> {
|
||||
for (role, key) in keys.iter().copied().enumerate() {
|
||||
self.admit_role_upload(&keys[role..], spill_reserve, shared_bytes)?;
|
||||
self.admit_role_upload(&keys[role..], reserve)?;
|
||||
loaded[role] = Some(self.upload_role(binding, key)?);
|
||||
self.uploads = self.uploads.checked_add(key.bytes as u64).ok_or(Error::Overflow)?;
|
||||
}
|
||||
@@ -61,9 +55,9 @@ impl<'ctx> AdaptiveCache<'ctx> {
|
||||
pub(super) fn admit_role_upload(
|
||||
&self,
|
||||
remaining_keys: &[MoeWeightDescriptor],
|
||||
spill_reserve: usize,
|
||||
shared_bytes: usize,
|
||||
reserve: UploadReserve,
|
||||
) -> Result<()> {
|
||||
let UploadReserve { spill_reserve, shared_bytes } = reserve;
|
||||
let context = self.context;
|
||||
let remaining = remaining_keys.iter().try_fold(0usize, |n, k| n.checked_add(k.bytes).ok_or(Error::Overflow))?;
|
||||
let required =
|
||||
|
||||
@@ -112,13 +112,12 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx
|
||||
/// The pending prompt, the Final phase and the lease the draft conditioning reads must be one and the same.
|
||||
fn check_final_sources(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
weights: PromptWeights<'_, 'ctx>,
|
||||
txn: &OriginalPromptTxn<'_, '_>,
|
||||
preview: &PromptDeviceFinal,
|
||||
last_next: TokenId,
|
||||
) -> Result<Rc<OriginalPromptPhase>> {
|
||||
let phase = self.sources_phase(binding, dense, txn, preview, last_next)?;
|
||||
let phase = self.sources_phase(weights, txn, preview, last_next)?;
|
||||
if !self.final_sources_agree(txn, &phase)? {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
@@ -129,13 +128,12 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx
|
||||
/// The sources, the pending prompt and the preview validate, and the sources name one Original phase.
|
||||
fn sources_phase(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
weights: PromptWeights<'_, 'ctx>,
|
||||
txn: &OriginalPromptTxn<'_, '_>,
|
||||
preview: &PromptDeviceFinal,
|
||||
last_next: TokenId,
|
||||
) -> Result<Rc<OriginalPromptPhase>> {
|
||||
self.sources.validate(binding, dense)?;
|
||||
self.sources.validate(weights.binding, weights.dense)?;
|
||||
txn.validate_final(preview)?;
|
||||
preview.validate_conditioning(last_next)?;
|
||||
self.sources.original_phase()?.ok_or(Error::IdentityMismatch)
|
||||
@@ -173,14 +171,13 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx
|
||||
/// After the producer: the sources and the phase are unchanged, and the outcome carries the pending receipt.
|
||||
fn finish_draft_kv(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
pending: (&OriginalPromptTxn<'_, '_>, &PromptDeviceFinal, TokenId),
|
||||
phase: Rc<OriginalPromptPhase>,
|
||||
weights: PromptWeights<'_, 'ctx>,
|
||||
prompt: FinalPromptPhase<'_, 'ctx>,
|
||||
result: DraftKvOutcome,
|
||||
ring: &MtpOriginalInt8<'ctx>,
|
||||
) -> Result<OriginalPromptDraftOutcome> {
|
||||
let (txn, preview, last_next) = pending;
|
||||
let PromptWeights { binding, dense } = weights;
|
||||
let FinalPromptPhase { txn, preview, last_next, phase } = prompt;
|
||||
self.sources.validate(binding, dense)?;
|
||||
txn.validate_final(preview)?;
|
||||
if !phase.same(&txn.phase()) {
|
||||
@@ -234,6 +231,14 @@ pub(in crate::qwen_forward) struct FinalPromptSources<'a, 'ctx> {
|
||||
pub(in crate::qwen_forward) preview: &'a PromptDeviceFinal,
|
||||
pub(in crate::qwen_forward) last_next: TokenId,
|
||||
}
|
||||
/// The prompt transaction with its final row and known next token, and the Original phase their sources name: what
|
||||
/// the outcome of a draft KV producer is checked against before it is handed on.
|
||||
pub(in crate::qwen_forward) struct FinalPromptPhase<'a, 'ctx> {
|
||||
pub(in crate::qwen_forward) txn: &'a OriginalPromptTxn<'a, 'ctx>,
|
||||
pub(in crate::qwen_forward) preview: &'a PromptDeviceFinal,
|
||||
pub(in crate::qwen_forward) last_next: TokenId,
|
||||
pub(in crate::qwen_forward) phase: Rc<OriginalPromptPhase>,
|
||||
}
|
||||
/// What the draft KV is computed from: the prior ring snapshot, the embedding table, the first prompt row that is
|
||||
/// still missing and the draft policy.
|
||||
pub(in crate::qwen_forward) struct DraftKvRequest<'a> {
|
||||
@@ -255,7 +260,7 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx
|
||||
) -> Result<OriginalPromptDraftOutcome> {
|
||||
let FinalPromptSources { binding, dense, mtp, txn, preview, last_next } = sources;
|
||||
let DraftKvRequest { prior, embedding, first_needed, policy } = request;
|
||||
let phase = self.check_final_sources(binding, dense, txn, preview, last_next)?;
|
||||
let phase = self.check_final_sources(PromptWeights::new(binding, dense), txn, preview, last_next)?;
|
||||
let next = self.shifted_next_ids(txn, last_next)?;
|
||||
let weights = self.prefill_weights(binding, mtp)?;
|
||||
let start = usize::try_from(txn.start_position()).map_err(|_| Error::Overflow)?;
|
||||
@@ -264,7 +269,8 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx
|
||||
let rows = PrefillRows { tokens: &next, cell0: start, first_needed };
|
||||
let sources = DraftKvSources { prior, policy, weights, embedding };
|
||||
let result = producer.record(&mut self.device, &mut run, rows, sources).map_err(micro_driver_error)?;
|
||||
self.finish_draft_kv(binding, dense, (txn, preview, last_next), phase, result, run.ring)
|
||||
let prompt = FinalPromptPhase { txn, preview, last_next, phase };
|
||||
self.finish_draft_kv(PromptWeights::new(binding, dense), prompt, result, run.ring)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,8 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx
|
||||
let rows = PrefillRows { tokens: &next, cell0: start, first_needed };
|
||||
let result =
|
||||
producer.record_scalar_prefill(&mut self.device, &mut run, rows, kv).map_err(micro_driver_error)?;
|
||||
self.finish_draft_kv(binding, dense, (txn, preview, last_next), phase, result, run.ring)
|
||||
let prompt = FinalPromptPhase { txn, preview, last_next, phase };
|
||||
self.finish_draft_kv(PromptWeights::new(binding, dense), prompt, result, run.ring)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,7 +121,7 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx
|
||||
/// The scalar producer also pins the lease and the prompt's known next token.
|
||||
fn check_scalar_sources(&self, sources: ScalarPromptSources<'_, 'ctx>) -> Result<Rc<OriginalPromptPhase>> {
|
||||
let ScalarPromptSources { binding, dense, txn, preview, last_next, .. } = sources;
|
||||
let phase = self.sources_phase(binding, dense, txn, preview, last_next)?;
|
||||
let phase = self.sources_phase(PromptWeights::new(binding, dense), txn, preview, last_next)?;
|
||||
if !self.sources_agree(txn, preview, &phase)? {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,14 @@ use leleka_cuda_driver::{
|
||||
OriginalMtpFullPolicy, OriginalVerifyWindow, RepeatRowWindow, SamplerParams,
|
||||
};
|
||||
|
||||
/// A completed verifier window with its head selection and the row up to which the target accepted it: what a draft
|
||||
/// receipt is made from.
|
||||
pub(in crate::qwen_forward) struct VerifiedWindow<'ctx> {
|
||||
pub(in crate::qwen_forward) window: OriginalVerifyWindow<'ctx>,
|
||||
pub(in crate::qwen_forward) selection: NativeHeadSelection,
|
||||
pub(in crate::qwen_forward) accepted_row: usize,
|
||||
}
|
||||
|
||||
/// One completed `Verifier::run` receipt, before the target commit. It owns
|
||||
/// the actual residual window and sampled target rows; the caller may only
|
||||
/// transform it into `OriginalCommittedMtpReceipt` after verifier commit has
|
||||
|
||||
+4
-6
@@ -42,10 +42,9 @@ impl<'ctx> OriginalVerifiedMtpReceipt<'ctx> {
|
||||
binding: &ModelBinding,
|
||||
session: &QwenSession<'ctx>,
|
||||
context: &'ctx Context<'ctx>,
|
||||
window: OriginalVerifyWindow<'ctx>,
|
||||
selection: NativeHeadSelection,
|
||||
accepted_row: usize,
|
||||
verified: VerifiedWindow<'ctx>,
|
||||
) -> Result<Self> {
|
||||
let VerifiedWindow { window, selection, accepted_row } = verified;
|
||||
let before = session.target_origin()?;
|
||||
window.validate_context(context).map_err(driver_error)?;
|
||||
window.validate_selection(&selection).map_err(driver_error)?;
|
||||
@@ -112,11 +111,10 @@ impl<'ctx> OriginalCommittedMtpReceipt<'ctx> {
|
||||
binding: &ModelBinding,
|
||||
session: &QwenSession<'ctx>,
|
||||
context: &'ctx Context<'ctx>,
|
||||
window: OriginalVerifyWindow<'ctx>,
|
||||
selection: NativeHeadSelection,
|
||||
verified: VerifiedWindow<'ctx>,
|
||||
before: TargetStepOrigin,
|
||||
accepted_row: usize,
|
||||
) -> Result<Self> {
|
||||
let VerifiedWindow { window, selection, accepted_row } = verified;
|
||||
let committed = session.target_origin()?;
|
||||
check_window(&window, context, &selection)?;
|
||||
let (first, expected) = published_bounds(&window, accepted_row)?;
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
//! a missing owner is `Error::Unsupported`, never a synthesized result.
|
||||
use super::contract::{Error, Result};
|
||||
use super::original_spec_adaptive::AdaptiveConfig;
|
||||
use super::original_spec_controller::{NanGuard, OriginalSpecController, OriginalSpecEngine, SpecConfig, SpecError};
|
||||
use super::original_spec_controller::{
|
||||
NanGuard, OriginalSpecController, OriginalSpecEngine, SpecConfig, SpecError, SpecWindow,
|
||||
};
|
||||
use super::original_spec_draft::{DraftPick, OriginalDraftEngine, OriginalFirstDraftEngine, TargetSeedRow};
|
||||
use super::original_spec_policy::MAX_T;
|
||||
use crate::settings::EnvSource;
|
||||
|
||||
+1
-2
@@ -161,8 +161,7 @@ impl OriginalServeSettings {
|
||||
pub(crate) fn controller(&self) -> Result<OriginalSpecController> {
|
||||
OriginalSpecController::new(
|
||||
SpecConfig::new(
|
||||
self.max_t,
|
||||
self.mtp_max_t,
|
||||
SpecWindow { max_t: self.max_t, mtp_max_t: self.mtp_max_t },
|
||||
self.max_context,
|
||||
self.vocabulary,
|
||||
self.suffix_min_match,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).
|
||||
|
||||
use super::super::original_spec_controller::{NanGuard, OriginalSpecController, SpecConfig, SpecError};
|
||||
use super::super::original_spec_controller::{NanGuard, OriginalSpecController, SpecConfig, SpecError, SpecWindow};
|
||||
use super::super::original_spec_draft::{DraftPreparation, DraftSampling, VerifiedWindow};
|
||||
use super::*;
|
||||
use std::cell::RefCell;
|
||||
@@ -256,7 +256,10 @@ fn run_request(skew: i32, max_t: usize, max_new: usize) -> (Vec<i32>, Vec<String
|
||||
w.borrow_mut().committed = p.clone();
|
||||
w.borrow_mut().skew = skew;
|
||||
let mut e = OriginalServeEngine::new(f, VOCAB, max_t, max_t - 1).unwrap();
|
||||
let mut c = OriginalSpecController::new(SpecConfig::new(max_t, 0, 4096, VOCAB, 0, false).unwrap()).unwrap();
|
||||
let mut c = OriginalSpecController::new(
|
||||
SpecConfig::new(SpecWindow { max_t: max_t, mtp_max_t: 0 }, 4096, VOCAB, 0, false).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
c.begin_request(&p, max_new, 0.0, &[]).unwrap();
|
||||
e.set_min_p(0.0).unwrap();
|
||||
let mut out = Vec::new();
|
||||
|
||||
+4
-1
@@ -113,7 +113,10 @@ fn controller_both_restores_run_when_the_verifier_fails() {
|
||||
let p = prompt_long();
|
||||
let (f, w) = Fake::new(&p);
|
||||
let mut e = OriginalServeEngine::new(f, VOCAB, 4, 3).unwrap();
|
||||
let mut c = OriginalSpecController::new(SpecConfig::new(4, 0, 4096, VOCAB, 0, false).unwrap()).unwrap();
|
||||
let mut c = OriginalSpecController::new(
|
||||
SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 0 }, 4096, VOCAB, 0, false).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
c.begin_request(&p, 8, 0.0, &[]).unwrap();
|
||||
w.borrow_mut().fail = Some("run");
|
||||
let err = c.verify_commit(&mut e, || false).err().unwrap();
|
||||
|
||||
+3
-3
@@ -2,6 +2,7 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::qwen_forward::original_mtp_verified_adapter::VerifiedWindow;
|
||||
use crate::qwen_forward::original_serve_engine::{DraftLimits, FirstDraftSeed};
|
||||
use crate::qwen_forward::original_serve_native::NativeCommittedWindow;
|
||||
|
||||
@@ -122,14 +123,13 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> {
|
||||
let DraftLimits { max_drafts, min_p } = limits;
|
||||
let before = self.admit_draft_origin(position, max_drafts)?;
|
||||
let p = profile::span("draft.receipt");
|
||||
let verified = VerifiedWindow { window, selection, accepted_row };
|
||||
let receipt = OriginalCommittedMtpReceipt::for_published_window(
|
||||
self.binding,
|
||||
self.session,
|
||||
self.context,
|
||||
window,
|
||||
selection,
|
||||
verified,
|
||||
before,
|
||||
accepted_row,
|
||||
)?;
|
||||
drop(p);
|
||||
let _p = profile::span("draft.drafter");
|
||||
|
||||
@@ -112,6 +112,10 @@ use super::*;
|
||||
fn row(ids: [i32; 10]) -> Vec<i32> {
|
||||
ids.to_vec()
|
||||
}
|
||||
/// The PCIe split policy of a test group.
|
||||
fn policy(pcie_num: u32, staging: usize, tail_rank: u32) -> PcieSplitPolicy {
|
||||
PcieSplitPolicy { pcie_num, staging, tail_rank }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn residents_are_vram_groups_in_routing_order_and_the_rest_is_the_cpus_without_pcie() {
|
||||
@@ -156,57 +160,23 @@ fn the_pcie_share_is_the_last_misses_in_routing_order_capped_by_staging() {
|
||||
fn a_restricted_pcie_share_takes_only_eligible_misses_and_never_more_than_the_unrestricted_one() {
|
||||
// 10 misses, share 141/256 -> m = 5 of all misses; only 11, 14, 16, 17 may be staged
|
||||
let ids = row([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]);
|
||||
let group = RoutedGroup::new(&ids, 10, 40);
|
||||
let none = |_: u32| None;
|
||||
let ok = |e: u32| matches!(e, 11 | 14 | 16 | 17);
|
||||
let s = split_group_pcie(
|
||||
RoutedGroup::new(&ids, 10, 40),
|
||||
none,
|
||||
PcieSplitPolicy { pcie_num: 141, staging: 16, tail_rank: 0 },
|
||||
ok,
|
||||
)
|
||||
.unwrap();
|
||||
let s = split_group_pcie(group, none, policy(141, 16, 0), ok).unwrap();
|
||||
assert_eq!(s.pcie_experts, vec![11, 14, 16, 17], "capped by the eligible misses, routing order");
|
||||
assert_eq!(s.kinds, vec![-1, 1, -1, -1, 1, -1, 1, 1, -1, -1]);
|
||||
// a smaller share takes the last eligible misses
|
||||
let s = split_group_pcie(
|
||||
RoutedGroup::new(&ids, 10, 40),
|
||||
none,
|
||||
PcieSplitPolicy { pcie_num: 64, staging: 16, tail_rank: 0 },
|
||||
ok,
|
||||
)
|
||||
.unwrap(); // m = 10 * 64 >> 8 = 2
|
||||
let s = split_group_pcie(group, none, policy(64, 16, 0), ok).unwrap(); // m = 10 * 64 >> 8 = 2
|
||||
assert_eq!(s.pcie_experts, vec![16, 17]);
|
||||
// nothing eligible, nothing staged; and the unrestricted split is the old one
|
||||
assert!(
|
||||
split_group_pcie(
|
||||
RoutedGroup::new(&ids, 10, 40),
|
||||
none,
|
||||
PcieSplitPolicy { pcie_num: 256, staging: 16, tail_rank: 0 },
|
||||
|_| false
|
||||
)
|
||||
.unwrap()
|
||||
.plan
|
||||
.pcie()
|
||||
.is_empty()
|
||||
);
|
||||
let all = split_group_pcie(
|
||||
RoutedGroup::new(&ids, 10, 40),
|
||||
none,
|
||||
PcieSplitPolicy { pcie_num: 141, staging: 16, tail_rank: 0 },
|
||||
|_| true,
|
||||
)
|
||||
.unwrap();
|
||||
let old = split_group(RoutedGroup::new(&ids, 10, 40), none, 141, 16).unwrap();
|
||||
assert!(split_group_pcie(group, none, policy(256, 16, 0), |_| false).unwrap().plan.pcie().is_empty());
|
||||
let all = split_group_pcie(group, none, policy(141, 16, 0), |_| true).unwrap();
|
||||
let old = split_group(group, none, 141, 16).unwrap();
|
||||
assert_eq!((all.pcie_experts, all.kinds), (old.pcie_experts, old.kinds));
|
||||
// residents and skipped experts are not eligible misses
|
||||
let resident = |e: u32| (e == 11).then_some(2usize);
|
||||
let s = split_group_pcie(
|
||||
RoutedGroup::new(&ids, 10, 40),
|
||||
resident,
|
||||
PcieSplitPolicy { pcie_num: 256, staging: 16, tail_rank: 0 },
|
||||
ok,
|
||||
)
|
||||
.unwrap();
|
||||
let s = split_group_pcie(group, resident, policy(256, 16, 0), ok).unwrap();
|
||||
assert_eq!(s.pcie_experts, vec![14, 16, 17]);
|
||||
}
|
||||
|
||||
@@ -227,41 +197,19 @@ fn the_tail_skip_drops_missed_experts_every_token_routes_at_or_below_the_rank()
|
||||
let mut ids = row([1, 2, 3, 4, 5, 6, 12, 30, 31, 40]);
|
||||
ids.extend(row([7, 8, 9, 10, 11, 13, 14, 15, 12, 30]));
|
||||
let resident = |e: u32| (e == 40).then_some(3usize);
|
||||
let off = split_group_tail(
|
||||
RoutedGroup::new(&ids, 10, 20),
|
||||
resident,
|
||||
PcieSplitPolicy { pcie_num: 0, staging: 16, tail_rank: 0 },
|
||||
)
|
||||
.unwrap();
|
||||
let off = split_group_tail(RoutedGroup::new(&ids, 10, 20), resident, policy(0, 16, 0)).unwrap();
|
||||
assert_eq!(off.skipped_experts, 0);
|
||||
assert!(off.kinds.iter().all(|&k| k != -2));
|
||||
let on = split_group_tail(
|
||||
RoutedGroup::new(&ids, 10, 20),
|
||||
resident,
|
||||
PcieSplitPolicy { pcie_num: 0, staging: 16, tail_rank: 7 },
|
||||
)
|
||||
.unwrap();
|
||||
let on = split_group_tail(RoutedGroup::new(&ids, 10, 20), resident, policy(0, 16, 7)).unwrap();
|
||||
assert_tail_skip_at_rank_seven_keeps_the_rest(&on, &off);
|
||||
// rank 8: only expert 31 (rank 8 in its only row); rank 9: nothing (the rank-9 entries are resident 40 and 30,
|
||||
// best rank 7)
|
||||
assert_eq!(
|
||||
split_group_tail(
|
||||
RoutedGroup::new(&ids, 10, 20),
|
||||
resident,
|
||||
PcieSplitPolicy { pcie_num: 0, staging: 16, tail_rank: 8 }
|
||||
)
|
||||
.unwrap()
|
||||
.skipped_experts,
|
||||
split_group_tail(RoutedGroup::new(&ids, 10, 20), resident, policy(0, 16, 8)).unwrap().skipped_experts,
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
split_group_tail(
|
||||
RoutedGroup::new(&ids, 10, 20),
|
||||
resident,
|
||||
PcieSplitPolicy { pcie_num: 0, staging: 16, tail_rank: 9 }
|
||||
)
|
||||
.unwrap()
|
||||
.skipped_experts,
|
||||
split_group_tail(RoutedGroup::new(&ids, 10, 20), resident, policy(0, 16, 9)).unwrap().skipped_experts,
|
||||
0
|
||||
);
|
||||
}
|
||||
@@ -292,34 +240,19 @@ fn the_tail_skip_shrinks_the_miss_count_before_the_pcie_share_is_taken() {
|
||||
// ten)
|
||||
let ids = row([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]);
|
||||
let none = |_: u32| None;
|
||||
let s = split_group_tail(
|
||||
RoutedGroup::new(&ids, 10, 40),
|
||||
none,
|
||||
PcieSplitPolicy { pcie_num: 141, staging: 16, tail_rank: 7 },
|
||||
)
|
||||
.unwrap();
|
||||
let s = split_group_tail(RoutedGroup::new(&ids, 10, 40), none, policy(141, 16, 7)).unwrap();
|
||||
assert_eq!(s.skipped_experts, 3);
|
||||
assert_eq!(s.kinds, vec![-1, -1, -1, -1, 1, 1, 1, -2, -2, -2]);
|
||||
assert_eq!(s.pcie_experts, vec![14, 15, 16]);
|
||||
// a rank past the last slot skips nothing
|
||||
let off = split_group_tail(
|
||||
RoutedGroup::new(&ids, 10, 40),
|
||||
none,
|
||||
PcieSplitPolicy { pcie_num: 141, staging: 16, tail_rank: 10 },
|
||||
)
|
||||
.unwrap();
|
||||
let off = split_group_tail(RoutedGroup::new(&ids, 10, 40), none, policy(141, 16, 10)).unwrap();
|
||||
assert_eq!(off.skipped_experts, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tail_skip_leaves_invalid_ids_to_the_cpu_check() {
|
||||
let ids = row([600, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
|
||||
let s = split_group_tail(
|
||||
RoutedGroup::new(&ids, 10, 40),
|
||||
|_| None,
|
||||
PcieSplitPolicy { pcie_num: 0, staging: 16, tail_rank: 1 },
|
||||
)
|
||||
.unwrap();
|
||||
let s = split_group_tail(RoutedGroup::new(&ids, 10, 40), |_| None, policy(0, 16, 1)).unwrap();
|
||||
assert_eq!(s.kinds[0], -1, "an out-of-range id is never a skip: the CPU path reports it");
|
||||
}
|
||||
|
||||
|
||||
@@ -64,6 +64,17 @@ pub(crate) struct NanGuard {
|
||||
inject_at: u64,
|
||||
inject_times: u32,
|
||||
}
|
||||
/// How wide the speculative windows are: the verify window and the cap of the MTP chain (0 means the verify width).
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct SpecWindow {
|
||||
pub(crate) max_t: usize,
|
||||
pub(crate) mtp_max_t: usize,
|
||||
}
|
||||
/// A window that failed to verify: the error and the restart attempt counter that a restart advances.
|
||||
struct WindowFailure<'a> {
|
||||
error: Error,
|
||||
attempt: &'a mut u32,
|
||||
}
|
||||
pub(crate) struct SpecConfig {
|
||||
max_t: usize,
|
||||
mtp_t: usize,
|
||||
|
||||
+5
-5
@@ -210,12 +210,11 @@ impl OriginalSpecController {
|
||||
round: &Round<'_, E>,
|
||||
cancel: &mut impl FnMut() -> bool,
|
||||
) -> SpecResult<E::Verified> {
|
||||
let guard = self.config.nan_guard;
|
||||
self.windows_checked = self.windows_checked.saturating_add(1);
|
||||
let mut attempt = 0u32;
|
||||
loop {
|
||||
let consumed = &self.request.as_ref().ok_or(Error::IdentityMismatch)?.consumed;
|
||||
let checks = (self.config.vocabulary, guard, self.windows_checked, attempt);
|
||||
let checks = (self.config.vocabulary, self.config.nan_guard, self.windows_checked, attempt);
|
||||
match run_window(engine, round, consumed, checks) {
|
||||
Ok(v) => {
|
||||
if attempt > 0 {
|
||||
@@ -227,7 +226,8 @@ impl OriginalSpecController {
|
||||
if let Some(v) = leftover {
|
||||
let _ = engine.drain_verified(v);
|
||||
}
|
||||
if let Some(refused) = self.window_failed(engine, round, e, &mut attempt, cancel) {
|
||||
let failure = WindowFailure { error: e, attempt: &mut attempt };
|
||||
if let Some(refused) = self.window_failed(engine, round, failure, cancel) {
|
||||
return Err(refused);
|
||||
}
|
||||
}
|
||||
@@ -247,10 +247,10 @@ impl OriginalSpecController {
|
||||
&mut self,
|
||||
engine: &mut E,
|
||||
round: &Round<'_, E>,
|
||||
e: Error,
|
||||
attempt: &mut u32,
|
||||
failure: WindowFailure<'_>,
|
||||
cancel: &mut impl FnMut() -> bool,
|
||||
) -> Option<SpecError> {
|
||||
let WindowFailure { error: e, attempt } = failure;
|
||||
let (p, t) = (round.p, round.t);
|
||||
let guard = self.config.nan_guard;
|
||||
let what = format!("position {p}, {t} rows, attempt {} of {}: {e:?}", *attempt + 1, guard.retries);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).
|
||||
|
||||
use super::super::original_spec_draft::{DraftPick, OriginalFirstDraftEngine, TargetSeedRow};
|
||||
use super::super::original_spec_draft::{DraftPick, FirstSeedPoint, OriginalFirstDraftEngine, TargetSeedRow};
|
||||
use super::*;
|
||||
|
||||
mod golden;
|
||||
@@ -186,7 +186,7 @@ impl Fake {
|
||||
}
|
||||
|
||||
fn config(max_t: usize, mtp: usize, suffix: usize) -> SpecConfig {
|
||||
SpecConfig::new(max_t, mtp, 4096, VOCAB, suffix, false).unwrap()
|
||||
SpecConfig::new(SpecWindow { max_t: max_t, mtp_max_t: mtp }, 4096, VOCAB, suffix, false).unwrap()
|
||||
}
|
||||
fn prompt(n: usize) -> Vec<i32> {
|
||||
let mut v = vec![11];
|
||||
@@ -221,22 +221,30 @@ fn begin(c: &mut OriginalSpecController, p: &[i32], max_new: usize, eos: &[i32])
|
||||
c.begin_request(p, max_new, 0.0, eos).unwrap();
|
||||
}
|
||||
|
||||
/// The speculation setup of a run to the context's end: the verify width, the MTP chain cap, the suffix match and
|
||||
/// whether the adaptive window policy is on.
|
||||
#[derive(Clone, Copy)]
|
||||
struct EndRunSetup {
|
||||
max_t: usize,
|
||||
mtp: usize,
|
||||
suffix: usize,
|
||||
adaptive: bool,
|
||||
}
|
||||
|
||||
/// Upstream 41cf05a0 `e85567b6`: the window and the MTP chain near the context's end must stay inside `max_context`
|
||||
/// cells (before: the whole request died with "ran out of context", or the draft wrote cells that do not exist).
|
||||
fn run_to_the_end(
|
||||
max_context: i64,
|
||||
prompt_len: usize,
|
||||
max_new: usize,
|
||||
max_t: usize,
|
||||
mtp: usize,
|
||||
suffix: usize,
|
||||
setup: EndRunSetup,
|
||||
min_p: f32,
|
||||
adaptive: bool,
|
||||
) -> (Fake, Vec<i32>, OriginalSpecController) {
|
||||
use super::super::original_spec_adaptive::AdaptiveConfig;
|
||||
let EndRunSetup { max_t, mtp, suffix, adaptive } = setup;
|
||||
let p = prompt(prompt_len);
|
||||
let mut e = Fake::new(&p[..prompt_len - 1]);
|
||||
let mut cfg = SpecConfig::new(max_t, mtp, 64, VOCAB, suffix, false).unwrap();
|
||||
let mut cfg = SpecConfig::new(SpecWindow { max_t: max_t, mtp_max_t: mtp }, 64, VOCAB, suffix, false).unwrap();
|
||||
cfg.max_context = max_context;
|
||||
if adaptive {
|
||||
cfg = cfg.with_adaptive(Some(AdaptiveConfig::new(max_t, max_t - 1)));
|
||||
|
||||
+7
-3
@@ -133,7 +133,10 @@ fn check_shape(g: &Greedy, shape: Shape) {
|
||||
let mut e = Fake::new(&g.p[..g.p.len() - 1]);
|
||||
e.bad_draft = bad;
|
||||
e.probs = pr.to_vec();
|
||||
let mut c = OriginalSpecController::new(SpecConfig::new(max_t, mtp, 4096, VOCAB, suffix, false).unwrap()).unwrap();
|
||||
let mut c = OriginalSpecController::new(
|
||||
SpecConfig::new(SpecWindow { max_t: max_t, mtp_max_t: mtp }, 4096, VOCAB, suffix, false).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
c.begin_request(&g.p, max_new, min_p, &eos).unwrap();
|
||||
let out = drive(&mut c, &mut e, &mut || false).unwrap();
|
||||
c.finish_request(&mut e).unwrap();
|
||||
@@ -229,11 +232,12 @@ impl OriginalFirstDraftEngine<u8> for First {
|
||||
#[test]
|
||||
fn draft_first_entry_is_a_separate_literal_path_and_drains() {
|
||||
let prep = DraftPreparation::new(4, 3, VOCAB).unwrap();
|
||||
let (point, sampling) = (FirstSeedPoint { cell: 9, token: 5 }, DraftSampling { min_p: 0.0, coupled: false });
|
||||
let mut f = First { log: Vec::new(), fail: false };
|
||||
let b = prep.from_committed_seed(&mut f, &0u8, 9, 5, 0.0, false).unwrap();
|
||||
let b = prep.from_committed_seed(&mut f, &0u8, point, sampling).unwrap();
|
||||
assert_eq!(b.produced(), 3);
|
||||
assert_eq!(f.log, ["replay", "seed", "chain", "chain", "drain"]);
|
||||
let mut f = First { log: Vec::new(), fail: true };
|
||||
assert_eq!(prep.from_committed_seed(&mut f, &0u8, 9, 5, 0.0, false).err(), Some(Error::CudaExecution));
|
||||
assert_eq!(prep.from_committed_seed(&mut f, &0u8, point, sampling).err(), Some(Error::CudaExecution));
|
||||
assert_eq!(f.log.last(), Some(&"drain"));
|
||||
}
|
||||
|
||||
+14
-13
@@ -8,14 +8,14 @@ use super::*;
|
||||
|
||||
#[test]
|
||||
fn config_rejects_out_of_range_and_mtp_zero_means_max_t() {
|
||||
assert!(SpecConfig::new(0, 0, 4096, VOCAB, 0, false).is_err());
|
||||
assert!(SpecConfig::new(9, 0, 4096, VOCAB, 0, false).is_err());
|
||||
assert!(SpecConfig::new(4, 0, 0, VOCAB, 0, false).is_err());
|
||||
assert!(SpecConfig::new(4, 0, 262145, VOCAB, 0, false).is_err());
|
||||
assert!(SpecConfig::new(4, 0, 4096, 0, 0, false).is_err());
|
||||
assert_eq!(SpecConfig::new(4, 0, 4096, VOCAB, 0, false).unwrap().mtp_t, 4);
|
||||
assert_eq!(SpecConfig::new(4, 9, 4096, VOCAB, 0, false).unwrap().mtp_t, 4);
|
||||
assert_eq!(SpecConfig::new(4, 2, 4096, VOCAB, 0, false).unwrap().mtp_t, 2);
|
||||
assert!(SpecConfig::new(SpecWindow { max_t: 0, mtp_max_t: 0 }, 4096, VOCAB, 0, false).is_err());
|
||||
assert!(SpecConfig::new(SpecWindow { max_t: 9, mtp_max_t: 0 }, 4096, VOCAB, 0, false).is_err());
|
||||
assert!(SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 0 }, 0, VOCAB, 0, false).is_err());
|
||||
assert!(SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 0 }, 262145, VOCAB, 0, false).is_err());
|
||||
assert!(SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 0 }, 4096, 0, 0, false).is_err());
|
||||
assert_eq!(SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 0 }, 4096, VOCAB, 0, false).unwrap().mtp_t, 4);
|
||||
assert_eq!(SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 9 }, 4096, VOCAB, 0, false).unwrap().mtp_t, 4);
|
||||
assert_eq!(SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 2 }, 4096, VOCAB, 0, false).unwrap().mtp_t, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -181,7 +181,7 @@ fn max_new_ends_inside_a_window_without_overshooting_output() {
|
||||
fn a_window_near_the_context_end_takes_only_the_rows_that_fit() {
|
||||
let p = prompt(4);
|
||||
let mut e = Fake::new(&p[..3]);
|
||||
let mut cfg = SpecConfig::new(4, 4, 6, VOCAB, 0, false).unwrap();
|
||||
let mut cfg = SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 4 }, 6, VOCAB, 0, false).unwrap();
|
||||
cfg.max_context = 6;
|
||||
let mut c = OriginalSpecController::new(cfg).unwrap();
|
||||
begin(&mut c, &p, 100, &[]);
|
||||
@@ -204,7 +204,8 @@ fn spec_windows_and_drafts_never_pass_max_context_at_any_distance_from_the_end()
|
||||
{
|
||||
let prompt_len = 10usize;
|
||||
let max_context = prompt_len as i64 - 1 + k;
|
||||
let (e, out, c) = run_to_the_end(max_context, prompt_len, 1000, max_t, max_t, suffix, min_p, adaptive);
|
||||
let setup = EndRunSetup { max_t, mtp: max_t, suffix, adaptive };
|
||||
let (e, out, c) = run_to_the_end(max_context, prompt_len, 1000, setup, min_p);
|
||||
let tag = format!("max_t {max_t} k {k} suffix {suffix} min_p {min_p} adaptive {adaptive}");
|
||||
assert!(e.max_end <= max_context, "{tag}: touched cell {} of {max_context}", e.max_end);
|
||||
// the request ended because the context is full, with the greedy text of every row that fits
|
||||
@@ -222,13 +223,13 @@ fn spec_windows_and_drafts_never_pass_max_context_at_any_distance_from_the_end()
|
||||
fn the_chain_is_shortened_near_the_end_and_restored_after_it() {
|
||||
// fixed window, perfect drafter: 4-wide windows, 3 drafts. The last round before the end drafts only the cells
|
||||
// left.
|
||||
let (e, _, _) = run_to_the_end(30, 10, 1000, 4, 4, 0, 0.0, false);
|
||||
let (e, _, _) = run_to_the_end(30, 10, 1000, EndRunSetup { max_t: 4, mtp: 4, suffix: 0, adaptive: false }, 0.0);
|
||||
assert!(e.max_end <= 30);
|
||||
// plans: a clamped chain is asked for explicitly, never longer than the cells left
|
||||
assert!(e.plans.iter().all(|&(n, _)| (1..=3).contains(&n)), "{:?}", e.plans);
|
||||
assert!(e.plans.iter().any(|&(n, _)| n < 3), "the last rounds draft fewer than the full chain: {:?}", e.plans);
|
||||
// a request that never gets near the end never sets a plan (the fixed chain needs none)
|
||||
let (e, _, _) = run_to_the_end(4096, 10, 40, 4, 4, 0, 0.0, false);
|
||||
let (e, _, _) = run_to_the_end(4096, 10, 40, EndRunSetup { max_t: 4, mtp: 4, suffix: 0, adaptive: false }, 0.0);
|
||||
assert!(e.plans.is_empty(), "{:?}", e.plans);
|
||||
}
|
||||
|
||||
@@ -236,7 +237,7 @@ fn the_chain_is_shortened_near_the_end_and_restored_after_it() {
|
||||
fn a_chain_clamped_by_one_request_is_restored_for_the_next() {
|
||||
let p = prompt(10);
|
||||
let mut e = Fake::new(&p[..9]);
|
||||
let mut cfg = SpecConfig::new(4, 4, 64, VOCAB, 0, false).unwrap();
|
||||
let mut cfg = SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 4 }, 64, VOCAB, 0, false).unwrap();
|
||||
cfg.max_context = 20;
|
||||
let mut c = OriginalSpecController::new(cfg).unwrap();
|
||||
c.begin_request(&p, 1000, 0.0, &[]).unwrap();
|
||||
|
||||
@@ -73,7 +73,8 @@ impl Scenario {
|
||||
let p = prompt(self.prompt_len);
|
||||
let mut e = Fake::new(&p[..self.prompt_len - 1]);
|
||||
e.bad_draft = self.bad_draft;
|
||||
let mut cfg = SpecConfig::new(self.max_t, self.mtp, 64, VOCAB, 0, false).unwrap();
|
||||
let mut cfg =
|
||||
SpecConfig::new(SpecWindow { max_t: self.max_t, mtp_max_t: self.mtp }, 64, VOCAB, 0, false).unwrap();
|
||||
cfg.max_context = self.max_context;
|
||||
if self.adaptive {
|
||||
cfg = cfg.with_adaptive(Some(AdaptiveConfig::new(self.max_t, self.max_t - 1)));
|
||||
|
||||
+2
-2
@@ -100,13 +100,13 @@ impl NanGuard {
|
||||
}
|
||||
impl SpecConfig {
|
||||
pub(crate) fn new(
|
||||
max_t: usize,
|
||||
mtp_max_t: usize,
|
||||
window: SpecWindow,
|
||||
max_context: i64,
|
||||
vocabulary: u32,
|
||||
suffix_min_match: usize,
|
||||
coupled: bool,
|
||||
) -> Result<Self> {
|
||||
let SpecWindow { max_t, mtp_max_t } = window;
|
||||
if !(1..=MAX_T).contains(&max_t)
|
||||
|| max_context < 1
|
||||
|| max_context > crate::qwen_forward::contract::serving_cells() as i64
|
||||
|
||||
@@ -90,6 +90,13 @@ pub(crate) struct VerifiedWindow<'a> {
|
||||
pub(crate) vetted: &'a mut PrefixMemo,
|
||||
}
|
||||
|
||||
/// Where a first draft seed sits: its cell and the target token there.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct FirstSeedPoint {
|
||||
pub(crate) cell: i64,
|
||||
pub(crate) token: i32,
|
||||
}
|
||||
|
||||
/// How a draft samples: the confidence floor that cuts the chain, and whether sampling is coupled to the history.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct DraftSampling {
|
||||
@@ -125,11 +132,11 @@ impl DraftPreparation {
|
||||
&self,
|
||||
engine: &mut E,
|
||||
verified: &V,
|
||||
window: VerifiedWindow<'_>,
|
||||
mut window: VerifiedWindow<'_>,
|
||||
sampling: DraftSampling,
|
||||
) -> Result<DraftBatch> {
|
||||
let VerifiedWindow { first_cell: p, accepted: a, outputs, consumed, vetted } = window;
|
||||
self.check_verified(p, a, outputs, consumed, vetted, sampling.min_p)?;
|
||||
self.check_verified(&mut window, sampling.min_p)?;
|
||||
let VerifiedWindow { first_cell: p, accepted: a, outputs, consumed, .. } = window;
|
||||
let window = SeedWindow { first_cell: p, accepted: a, outputs, consumed };
|
||||
let result = self.seed_and_chain(engine, verified, window, sampling);
|
||||
let drain = engine.drain_draft();
|
||||
@@ -137,15 +144,8 @@ impl DraftPreparation {
|
||||
// when an earlier finite/admission error is returned to the caller.
|
||||
drain_after(result, drain)
|
||||
}
|
||||
fn check_verified(
|
||||
&self,
|
||||
p: i64,
|
||||
a: usize,
|
||||
outputs: &[i32],
|
||||
consumed: &[i32],
|
||||
vetted: &mut PrefixMemo,
|
||||
min_p: f32,
|
||||
) -> Result<()> {
|
||||
fn check_verified(&self, window: &mut VerifiedWindow<'_>, min_p: f32) -> Result<()> {
|
||||
let VerifiedWindow { first_cell: p, accepted: a, outputs, consumed, ref mut vetted } = *window;
|
||||
if outputs.is_empty()
|
||||
|| outputs.len() > self.max_t
|
||||
|| a >= outputs.len()
|
||||
@@ -216,7 +216,7 @@ fn drain_after(result: Result<DraftBatch>, drain: Result<()>) -> Result<DraftBat
|
||||
}
|
||||
|
||||
mod prefill_records;
|
||||
pub(crate) use prefill_records::{PrefillGroups, PrefillRecords};
|
||||
pub(crate) use prefill_records::{PrefillGroups, PrefillRecords, PrefillSchedule};
|
||||
|
||||
/// Literal draft_first for the CLI/current-residual entry. This is separate
|
||||
/// from serve's first T1 verify window; a prompt receipt never relabels a
|
||||
@@ -234,22 +234,21 @@ impl DraftPreparation {
|
||||
&self,
|
||||
engine: &mut E,
|
||||
seed: &S,
|
||||
cell: i64,
|
||||
token: i32,
|
||||
min_p: f32,
|
||||
coupled: bool,
|
||||
point: FirstSeedPoint,
|
||||
sampling: DraftSampling,
|
||||
) -> Result<DraftBatch> {
|
||||
let FirstSeedPoint { cell, token } = point;
|
||||
if cell < 0
|
||||
|| cell
|
||||
.checked_add(self.max_t as i64)
|
||||
.is_none_or(|end| end > (crate::qwen_forward::contract::serving_cells() as i64))
|
||||
|| token < 0
|
||||
|| token as u32 >= self.vocabulary
|
||||
|| !min_p.is_finite()
|
||||
|| !sampling.min_p.is_finite()
|
||||
{
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
let result = self.first_seed_and_chain(engine, seed, cell, token, min_p, coupled);
|
||||
let result = self.first_seed_and_chain(engine, seed, point, sampling);
|
||||
let drain = engine.drain_first_seed();
|
||||
drain_after(result, drain)
|
||||
}
|
||||
@@ -257,11 +256,11 @@ impl DraftPreparation {
|
||||
&self,
|
||||
engine: &mut E,
|
||||
seed: &S,
|
||||
cell: i64,
|
||||
token: i32,
|
||||
min_p: f32,
|
||||
coupled: bool,
|
||||
point: FirstSeedPoint,
|
||||
sampling: DraftSampling,
|
||||
) -> Result<DraftBatch> {
|
||||
let FirstSeedPoint { cell, token } = point;
|
||||
let DraftSampling { min_p, coupled } = sampling;
|
||||
engine.replay_first_seed_kv(seed, self.max_t, cell, token)?;
|
||||
let mut batch = DraftBatch::empty();
|
||||
batch.push(engine.full_first_seed(seed, cell, token, coupled)?, self.vocabulary)?;
|
||||
@@ -285,16 +284,14 @@ pub(crate) trait OriginalPrefillDraftEngine<Prompt> {
|
||||
) -> Result<()>;
|
||||
fn drain_prefill(&mut self) -> Result<()>;
|
||||
}
|
||||
/// Runs the batched draft prefill of `prompt`: the records uploaded once, then every group of `schedule` appended.
|
||||
pub(crate) fn prefill_draft<P, E: OriginalPrefillDraftEngine<P>>(
|
||||
engine: &mut E,
|
||||
prompt: &P,
|
||||
records: &PrefillRecords,
|
||||
max_t: usize,
|
||||
cell0: i64,
|
||||
window: i64,
|
||||
prompt_len: i64,
|
||||
schedule: PrefillSchedule,
|
||||
) -> Result<()> {
|
||||
let groups = records.groups(max_t, cell0, window, prompt_len)?;
|
||||
let groups = records.groups(schedule)?;
|
||||
let result = (|| {
|
||||
engine.upload_prefill_records(prompt, records)?;
|
||||
for (first, rows) in groups {
|
||||
|
||||
@@ -65,7 +65,8 @@ impl PrefillRecords {
|
||||
pub(crate) fn bytes(&self) -> usize {
|
||||
self.records.len() * 4
|
||||
}
|
||||
pub(crate) fn groups(&self, max_t: usize, cell0: i64, window: i64, prompt_len: i64) -> Result<PrefillGroups> {
|
||||
pub(crate) fn groups(&self, schedule: PrefillSchedule) -> Result<PrefillGroups> {
|
||||
let PrefillSchedule { max_t, cell0, window, prompt_len } = schedule;
|
||||
if !(1..=MAX_T).contains(&max_t)
|
||||
|| cell0 != self.cell0
|
||||
|| !(0..=(crate::qwen_forward::contract::serving_cells() as i64)).contains(&window)
|
||||
@@ -77,6 +78,14 @@ impl PrefillRecords {
|
||||
Ok(PrefillGroups { next: 0, rows: self.rows, max_t, cell0, first_needed })
|
||||
}
|
||||
}
|
||||
/// How a prompt's draft prefill is grouped: rows per group, the first cell, the attention window and the prompt length.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct PrefillSchedule {
|
||||
pub(crate) max_t: usize,
|
||||
pub(crate) cell0: i64,
|
||||
pub(crate) window: i64,
|
||||
pub(crate) prompt_len: i64,
|
||||
}
|
||||
pub(crate) struct PrefillGroups {
|
||||
next: usize,
|
||||
rows: usize,
|
||||
|
||||
+13
-13
@@ -45,13 +45,13 @@ pub(super) struct GdnLayer<'ctx> {
|
||||
}
|
||||
impl<'ctx> GdnLayer<'ctx> {
|
||||
pub(super) fn enter(
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
weights: PromptWeights<'_, 'ctx>,
|
||||
txn: &OriginalPromptTxn<'_, '_>,
|
||||
context: &'ctx Context<'ctx>,
|
||||
layer: LayerId,
|
||||
site: PromptLayerSite<'ctx>,
|
||||
lap: &mut Lap,
|
||||
) -> Result<(Self, Vec<GdnChunkRow>)> {
|
||||
let PromptWeights { binding, dense } = weights;
|
||||
let PromptLayerSite { layer, context } = site;
|
||||
let prior = txn.gdn_prior(layer)?;
|
||||
lap.at(1, "in: gdn_prior");
|
||||
let (start, rows) = GdnChunkStart::from_original_prompt(txn, layer, &prior)?;
|
||||
@@ -75,12 +75,12 @@ impl<'ctx> GdnLayer<'ctx> {
|
||||
}
|
||||
pub(super) fn leave(
|
||||
self,
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
weights: PromptWeights<'_, 'ctx>,
|
||||
txn: &OriginalPromptTxn<'_, '_>,
|
||||
edges: Vec<ChunkEdge>,
|
||||
lap: &mut Lap,
|
||||
) -> Result<()> {
|
||||
let PromptWeights { binding, dense } = weights;
|
||||
let seal = GdnChunkSeal::from_original_prompt(txn, &self.start, edges)?;
|
||||
lap.at(5, "out: seal (row edges)");
|
||||
let next = self.owner.finish(seal, binding, dense)?;
|
||||
@@ -108,18 +108,18 @@ pub(in super::super) fn produce_original_gdn<'arena, 'loan, 'ctx>(
|
||||
) -> Result<OriginalDeviceBlock<'arena, 'loan, 'ctx>> {
|
||||
use super::super::super::prefill_profile::{Drain, Stage as P, span};
|
||||
let PromptWeights { binding, dense } = weights;
|
||||
let PromptLayerSite { layer, context } = site;
|
||||
let context = site.context;
|
||||
let drain = Some(context as &dyn Drain);
|
||||
let mut lap = Lap::new("gdn-host");
|
||||
let state_in = span(P::GdnStateIn, drain);
|
||||
let (mut state, rows) = GdnLayer::enter(binding, dense, txn, context, layer, &mut lap)?;
|
||||
let (mut state, rows) = GdnLayer::enter(weights, txn, site, &mut lap)?;
|
||||
drop(state_in);
|
||||
let compute = span(P::GdnCompute, drain);
|
||||
let (block, edges) = state.compute(binding, dense, PromptSource { rows, read }, gdn)?;
|
||||
drop(compute);
|
||||
lap.at(4, "compute: produce_prompt_device");
|
||||
let _state_out = span(P::GdnStateOut, drain);
|
||||
state.leave(binding, dense, txn, edges, &mut lap)?;
|
||||
state.leave(weights, txn, edges, &mut lap)?;
|
||||
Ok(block)
|
||||
}
|
||||
|
||||
@@ -214,14 +214,14 @@ impl<'a, 's, 'ctx> QsaLayerRun<'a, 's, 'ctx> {
|
||||
}
|
||||
}
|
||||
pub(in super::super) fn produce_original_qsa<'arena, 'loan, 'ctx>(
|
||||
binding: &ModelBinding,
|
||||
dense: &DenseWeightCache<'ctx>,
|
||||
weights: PromptWeights<'_, 'ctx>,
|
||||
txn: &OriginalPromptTxn<'_, 'ctx>,
|
||||
context: &'ctx Context<'ctx>,
|
||||
layer: LayerId,
|
||||
site: PromptLayerSite<'ctx>,
|
||||
read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>,
|
||||
devices: QsaLayerDevices<'_, 'ctx>,
|
||||
) -> Result<OriginalDeviceBlock<'arena, 'loan, 'ctx>> {
|
||||
let PromptWeights { binding, dense } = weights;
|
||||
let PromptLayerSite { layer, context } = site;
|
||||
let QsaLayerDevices { layer_owner, qsa, transport, attention } = devices;
|
||||
let mut run = QsaLayerRun::new(binding, dense, txn, context, layer)?;
|
||||
let selected = run.prepare(layer_owner, qsa, transport, read)?;
|
||||
|
||||
+5
-6
@@ -64,9 +64,10 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx
|
||||
let (layer, context) = self.attention_layer(|phase| phase.same(&txn.phase()))?;
|
||||
self.complete_with(weights, producer, GrRole::Ffn(layer.get()), |read| {
|
||||
let mut lap = Lap::off();
|
||||
let (mut state, rows) = GdnLayer::enter(binding, dense, txn, context, layer, &mut lap)?;
|
||||
let site = PromptLayerSite { layer, context };
|
||||
let (mut state, rows) = GdnLayer::enter(weights, txn, site, &mut lap)?;
|
||||
let (block, edges) = state.compute(binding, dense, PromptSource { rows, read }, gdn)?;
|
||||
state.leave(binding, dense, txn, edges, &mut lap)?;
|
||||
state.leave(weights, txn, edges, &mut lap)?;
|
||||
Ok(block)
|
||||
})
|
||||
}
|
||||
@@ -89,10 +90,9 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx
|
||||
producer: &mut OriginalPromptDevice<'ctx>,
|
||||
devices: QsaLayerDevices<'_, 'ctx>,
|
||||
) -> Result<PromptDeviceRows<'source, 'arena, 'loan, 'ctx>> {
|
||||
let PromptWeights { binding, dense } = weights;
|
||||
let (layer, context) = self.attention_layer(|phase| phase.same(&txn.phase()))?;
|
||||
self.complete_with(weights, producer, GrRole::Ffn(layer.get()), |read| {
|
||||
produce_original_qsa(binding, dense, txn, context, layer, read, devices)
|
||||
produce_original_qsa(weights, txn, PromptLayerSite { layer, context }, read, devices)
|
||||
})
|
||||
}
|
||||
pub(in crate::qwen_forward) fn complete_original_qsa_normed<'weight>(
|
||||
@@ -102,10 +102,9 @@ impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx
|
||||
producer: &mut OriginalPromptDevice<'ctx>,
|
||||
devices: QsaLayerDevices<'_, 'ctx>,
|
||||
) -> Result<PromptDeviceNormedRows<'weight, 'source, 'arena, 'loan, 'ctx>> {
|
||||
let PromptWeights { binding, dense } = weights;
|
||||
let (layer, context) = self.attention_layer(|phase| phase.same(&txn.phase()))?;
|
||||
self.complete_with_normed(weights, producer, GrRole::Ffn(layer.get()), |read| {
|
||||
produce_original_qsa(binding, dense, txn, context, layer, read, devices)
|
||||
produce_original_qsa(weights, txn, PromptLayerSite { layer, context }, read, devices)
|
||||
})
|
||||
}
|
||||
/// Complete actual FFN arithmetic on the same physical arena, then the
|
||||
|
||||
@@ -146,17 +146,13 @@ pub(super) fn gather_rows<'ctx>(
|
||||
context: &Context<'_>,
|
||||
) -> Result<(Vec<f32>, Vec<f32>)> {
|
||||
let t = rows.len();
|
||||
let (weights, position) = (PromptWeights::new(binding, cache), ChunkLayer { chunk, layer });
|
||||
let mut attended = Vec::new();
|
||||
let mut gates = Vec::new();
|
||||
attended.try_reserve_exact(t * 6144).map_err(|_| Error::InputAllocation)?;
|
||||
gates.try_reserve_exact(t * 6144).map_err(|_| Error::InputAllocation)?;
|
||||
for (local, row) in rows.iter().enumerate() {
|
||||
row.validate(
|
||||
PromptWeights::new(binding, cache),
|
||||
ChunkLayer { chunk, layer },
|
||||
ProvenRow { local, proof: &proofs[local] },
|
||||
context,
|
||||
)?;
|
||||
row.validate(weights, position, ProvenRow { local, proof: &proofs[local] }, context)?;
|
||||
attended.extend_from_slice(row.values());
|
||||
gates.extend_from_slice(row.gate());
|
||||
}
|
||||
@@ -174,15 +170,11 @@ pub(super) fn ready_rows<'ctx>(
|
||||
(context, output): (&'ctx Context<'ctx>, &[f32]),
|
||||
) -> Result<Vec<super::super::qsa_attention::QsaReady>> {
|
||||
let t = rows.len();
|
||||
let (weights, position) = (PromptWeights::new(binding, cache), ChunkLayer { chunk, layer });
|
||||
let mut ready = Vec::new();
|
||||
ready.try_reserve_exact(t).map_err(|_| Error::InputAllocation)?;
|
||||
for (local, row) in rows.iter().enumerate() {
|
||||
row.validate(
|
||||
PromptWeights::new(binding, cache),
|
||||
ChunkLayer { chunk, layer },
|
||||
ProvenRow { local, proof: &proofs[local] },
|
||||
context,
|
||||
)?;
|
||||
row.validate(weights, position, ProvenRow { local, proof: &proofs[local] }, context)?;
|
||||
let mut values = Vec::new();
|
||||
values.try_reserve_exact(2560).map_err(|_| Error::InputAllocation)?;
|
||||
values.extend_from_slice(&output[local * 2560..(local + 1) * 2560]);
|
||||
|
||||
Reference in New Issue
Block a user