feat(serve): Original serving stack, request flow and empty-prompt reset
OriginalServeStack opens every model-lifetime owner of the mode17 path and serves a request as reset -> batched Original prefill -> verified-window decode over a freshly assembled native Verifier, with the QSA owners handed to and back from it. The per-request sequencing and failure classes are a pure function over RequestOwners with fake-owner tests. The empty-prompt checkpoints are re-stamped onto the current branch generation so a reset stays possible after any abort. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
1b9b729cca
commit
d53fb1a4db
@@ -1,7 +1,7 @@
|
||||
//! Native and explicitly selected experimental CUDA owner actor.
|
||||
//! CUDA owners and borrowed buffers remain ordinary locals on that thread.
|
||||
#[path = "backend_original_prompt.rs"]
|
||||
mod original_prompt;
|
||||
pub(crate) mod original_prompt;
|
||||
use crate::model_binding::kar_expert_source::KarExpertSource;
|
||||
pub use crate::model_binding::kar_expert_source::{
|
||||
KarArchiveRef, KarExpertLevels, KarExpertSourceConfig,
|
||||
|
||||
@@ -98,3 +98,7 @@ pub(crate) mod original_serve_config;
|
||||
pub(crate) mod original_serve_verifier;
|
||||
#[cfg(all(target_os="linux",target_arch="x86_64"))]
|
||||
pub(crate) mod original_serve_host;
|
||||
#[cfg(all(target_os="linux",target_arch="x86_64"))]
|
||||
pub(crate) mod original_serve_request;
|
||||
#[cfg(all(target_os="linux",target_arch="x86_64"))]
|
||||
pub(crate) mod original_serve_stack;
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
//! Request-level rules of the Original serve path that need no device: admission, the sequencing of one
|
||||
//! request over the owners, and the mapping of the controller's outcome. The device owners sit behind
|
||||
//! `RequestOwners`, so the order (reset when the previous request left state behind, condition the prompt
|
||||
//! up to its last token, decode) and its failure classes are exercised with fakes.
|
||||
//!
|
||||
//! Original reference (`generate.cpp` serve): a request with `n + max_new + 8 > max_context` is refused
|
||||
//! before any work; the prompt is read through token n-2 and token n-1 is the first verify input; there is
|
||||
//! no conversation cache here, so every request starts from the empty prompt.
|
||||
use super::{
|
||||
contract::Error,
|
||||
original_serve_engine::ServeOutcome,
|
||||
original_spec_controller::SpecError,
|
||||
};
|
||||
use leleka_cuda_driver::{SamplerParams, SamplerPath};
|
||||
|
||||
/// Cells a request keeps free beyond `n + max_new`: the last verify window may overshoot by up to this.
|
||||
pub(in crate::qwen_forward) const CONTEXT_SLACK: usize = 8;
|
||||
|
||||
/// A validated request, in the closed vocabulary the owners take.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ServeRequest {
|
||||
pub(in crate::qwen_forward) prompt: Vec<i32>,
|
||||
pub(in crate::qwen_forward) max_new: usize,
|
||||
pub(in crate::qwen_forward) params: SamplerParams,
|
||||
pub(in crate::qwen_forward) path: SamplerPath,
|
||||
/// `spec_min_p`: the draft-probability floor of this request (0 = always the full window).
|
||||
pub(in crate::qwen_forward) spec_min_p: f32,
|
||||
pub(in crate::qwen_forward) eos: Vec<i32>,
|
||||
}
|
||||
|
||||
impl ServeRequest {
|
||||
/// From a validated request: the CPU-reference sampler plan (`None` = greedy, no penalties) is mapped
|
||||
/// field for field; `entropy` seeds a request that carries no seed (greedy takes it as its seed too, as
|
||||
/// the Original's `seed = 0` takes the clock).
|
||||
pub(crate) fn new(
|
||||
prompt: Vec<i32>,
|
||||
max_new: usize,
|
||||
sampler: Option<&leleka_sampler_ref::SamplerParams>,
|
||||
entropy: u64,
|
||||
spec_min_p: f32,
|
||||
eos: Vec<i32>,
|
||||
) -> Self {
|
||||
let params = match sampler {
|
||||
Some(params) => super::original_serve_config::driver_sampler_params(params),
|
||||
None => super::original_serve_config::greedy_params(entropy),
|
||||
};
|
||||
Self { prompt, max_new, params, path: super::original_serve_config::sampler_path_from_environment(), spec_min_p, eos }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum Admission {
|
||||
EmptyPrompt,
|
||||
NoOutput,
|
||||
/// `n + max_new + 8 > max_context`, or a count that does not fit the index space.
|
||||
Context,
|
||||
BadToken,
|
||||
}
|
||||
|
||||
/// Refusal before any owner is touched.
|
||||
pub(in crate::qwen_forward) fn admit(request: &ServeRequest, max_context: i64) -> Result<(), Admission> {
|
||||
if request.prompt.is_empty() {
|
||||
return Err(Admission::EmptyPrompt);
|
||||
}
|
||||
if request.max_new == 0 {
|
||||
return Err(Admission::NoOutput);
|
||||
}
|
||||
if request.prompt.iter().chain(&request.eos).any(|&t| !(0..248_320).contains(&t)) {
|
||||
return Err(Admission::BadToken);
|
||||
}
|
||||
let needed = request
|
||||
.prompt
|
||||
.len()
|
||||
.checked_add(request.max_new)
|
||||
.and_then(|n| n.checked_add(CONTEXT_SLACK))
|
||||
.ok_or(Admission::Context)?;
|
||||
if i64::try_from(needed).map_or(true, |needed| needed > max_context) {
|
||||
return Err(Admission::Context);
|
||||
}
|
||||
if !request.spec_min_p.is_finite() || !(0.0..=1.0).contains(&request.spec_min_p) {
|
||||
return Err(Admission::BadToken);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum ServeError {
|
||||
/// Refused before any owner was touched.
|
||||
Refused(Admission),
|
||||
/// The caller's cancel flag ended the request (the owners were closed cleanly or will be reset).
|
||||
Cancelled,
|
||||
/// A forward/commit/draft failure; the next request starts from a reset.
|
||||
Failed(Error),
|
||||
/// The owners could not be brought back to a usable state: the stack must not serve again.
|
||||
Broken(Error),
|
||||
}
|
||||
|
||||
/// What `run_request` needs from the device owners.
|
||||
pub(in crate::qwen_forward) trait RequestOwners {
|
||||
/// The session, draft ring and resident layers stand at the empty prompt (nothing to reset).
|
||||
fn is_fresh(&self) -> bool;
|
||||
/// Bring everything back to the empty prompt. A failure is `Broken`.
|
||||
fn reset(&mut self) -> Result<(), Error>;
|
||||
/// Condition `prompt[..n-1]` into the session and the draft ring. `Err(Cancelled)` only when the
|
||||
/// caller's flag fired.
|
||||
fn prefill(&mut self, request: &ServeRequest, cancel: &mut dyn FnMut() -> bool) -> Result<(), SpecError>;
|
||||
/// Run the verified-window decode of the request; `emit` receives each committed round.
|
||||
fn decode(
|
||||
&mut self,
|
||||
request: &ServeRequest,
|
||||
emit: &mut dyn FnMut(&[i32]) -> Result<(), Error>,
|
||||
cancel: &mut dyn FnMut() -> bool,
|
||||
) -> Result<ServeOutcome, SpecError>;
|
||||
}
|
||||
|
||||
fn classify(error: SpecError) -> ServeError {
|
||||
match error {
|
||||
SpecError::Cancelled => ServeError::Cancelled,
|
||||
SpecError::Forward(error) => ServeError::Failed(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// One request over the owners.
|
||||
pub(in crate::qwen_forward) fn run_request<O: RequestOwners>(
|
||||
owners: &mut O,
|
||||
request: &ServeRequest,
|
||||
max_context: i64,
|
||||
emit: &mut dyn FnMut(&[i32]) -> Result<(), Error>,
|
||||
cancel: &mut dyn FnMut() -> bool,
|
||||
) -> Result<ServeOutcome, ServeError> {
|
||||
admit(request, max_context).map_err(ServeError::Refused)?;
|
||||
if cancel() {
|
||||
return Err(ServeError::Cancelled);
|
||||
}
|
||||
if !owners.is_fresh() {
|
||||
owners.reset().map_err(ServeError::Broken)?;
|
||||
if !owners.is_fresh() {
|
||||
return Err(ServeError::Broken(Error::IdentityMismatch));
|
||||
}
|
||||
}
|
||||
owners.prefill(request, cancel).map_err(classify)?;
|
||||
owners.decode(request, emit, cancel).map_err(classify)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::original_serve_engine::ServeStop;
|
||||
use super::*;
|
||||
use leleka_cuda_driver::SamplerPath;
|
||||
|
||||
fn request(prompt: usize, max_new: usize) -> ServeRequest {
|
||||
ServeRequest {
|
||||
prompt: (0..prompt as i32).collect(),
|
||||
max_new,
|
||||
params: super::super::original_serve_config::greedy_params(1),
|
||||
path: SamplerPath::Split,
|
||||
spec_min_p: 0.0,
|
||||
eos: vec![7],
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Fake {
|
||||
fresh: bool,
|
||||
log: Vec<&'static str>,
|
||||
fail_reset: bool,
|
||||
reset_leaves_state: bool,
|
||||
prefill: Option<SpecError>,
|
||||
decode: Option<SpecError>,
|
||||
emitted: Vec<i32>,
|
||||
}
|
||||
impl RequestOwners for Fake {
|
||||
fn is_fresh(&self) -> bool {
|
||||
self.fresh
|
||||
}
|
||||
fn reset(&mut self) -> Result<(), Error> {
|
||||
self.log.push("reset");
|
||||
if self.fail_reset {
|
||||
return Err(Error::CudaExecution);
|
||||
}
|
||||
self.fresh = !self.reset_leaves_state;
|
||||
Ok(())
|
||||
}
|
||||
fn prefill(&mut self, _: &ServeRequest, cancel: &mut dyn FnMut() -> bool) -> Result<(), SpecError> {
|
||||
self.log.push("prefill");
|
||||
self.fresh = false;
|
||||
if let Some(error) = self.prefill {
|
||||
return Err(error);
|
||||
}
|
||||
if cancel() {
|
||||
return Err(SpecError::Cancelled);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn decode(
|
||||
&mut self,
|
||||
request: &ServeRequest,
|
||||
emit: &mut dyn FnMut(&[i32]) -> Result<(), Error>,
|
||||
_: &mut dyn FnMut() -> bool,
|
||||
) -> Result<ServeOutcome, SpecError> {
|
||||
self.log.push("decode");
|
||||
if let Some(error) = self.decode {
|
||||
return Err(error);
|
||||
}
|
||||
emit(&[3, 4]).map_err(SpecError::Forward)?;
|
||||
self.emitted.extend([3, 4]);
|
||||
Ok(ServeOutcome { stop: ServeStop::Length, produced: 2.min(request.max_new), rounds: 1 })
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admission_follows_generate_cpp() {
|
||||
assert_eq!(admit(&request(10, 20), 38), Ok(()));
|
||||
assert_eq!(admit(&request(10, 21), 38), Err(Admission::Context));
|
||||
assert_eq!(admit(&request(0, 5), 100), Err(Admission::EmptyPrompt));
|
||||
assert_eq!(admit(&request(5, 0), 100), Err(Admission::NoOutput));
|
||||
let mut bad = request(5, 5);
|
||||
bad.prompt[2] = 248_320;
|
||||
assert_eq!(admit(&bad, 100), Err(Admission::BadToken));
|
||||
let mut bad = request(5, 5);
|
||||
bad.eos = vec![-1];
|
||||
assert_eq!(admit(&bad, 100), Err(Admission::BadToken));
|
||||
let mut bad = request(5, 5);
|
||||
bad.spec_min_p = 1.5;
|
||||
assert_eq!(admit(&bad, 100), Err(Admission::BadToken));
|
||||
let mut huge = request(5, 5);
|
||||
huge.max_new = usize::MAX;
|
||||
assert_eq!(admit(&huge, i64::MAX), Err(Admission::Context));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fresh_stack_skips_the_reset_and_a_used_one_resets_first() {
|
||||
let mut fresh = Fake { fresh: true, ..Default::default() };
|
||||
let out = run_request(&mut fresh, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap();
|
||||
assert_eq!(fresh.log, ["prefill", "decode"]);
|
||||
assert_eq!(out.produced, 2);
|
||||
let mut used = Fake::default();
|
||||
run_request(&mut used, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap();
|
||||
assert_eq!(used.log, ["reset", "prefill", "decode"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_request_touches_no_owner() {
|
||||
let mut owners = Fake::default();
|
||||
let error = run_request(&mut owners, &request(8, 400), 100, &mut |_| Ok(()), &mut || false).unwrap_err();
|
||||
assert_eq!(error, ServeError::Refused(Admission::Context));
|
||||
assert!(owners.log.is_empty());
|
||||
// cancelled before the first owner call
|
||||
let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || true).unwrap_err();
|
||||
assert_eq!(error, ServeError::Cancelled);
|
||||
assert!(owners.log.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unrecoverable_reset_is_broken_not_failed() {
|
||||
let mut owners = Fake { fail_reset: true, ..Default::default() };
|
||||
let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap_err();
|
||||
assert_eq!(error, ServeError::Broken(Error::CudaExecution));
|
||||
assert_eq!(owners.log, ["reset"]);
|
||||
// a reset that reports success but leaves state behind is a broken stack as well
|
||||
let mut owners = Fake { reset_leaves_state: true, ..Default::default() };
|
||||
let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap_err();
|
||||
assert_eq!(error, ServeError::Broken(Error::IdentityMismatch));
|
||||
assert_eq!(owners.log, ["reset"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefill_and_decode_errors_keep_their_class() {
|
||||
let mut owners = Fake { fresh: true, prefill: Some(SpecError::Cancelled), ..Default::default() };
|
||||
let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap_err();
|
||||
assert_eq!(error, ServeError::Cancelled);
|
||||
assert_eq!(owners.log, ["prefill"], "no decode after a failed prefill");
|
||||
let mut owners = Fake { fresh: true, prefill: Some(SpecError::Forward(Error::NonFinite)), ..Default::default() };
|
||||
let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap_err();
|
||||
assert_eq!(error, ServeError::Failed(Error::NonFinite));
|
||||
let mut owners = Fake { fresh: true, decode: Some(SpecError::Forward(Error::IdentityMismatch)), ..Default::default() };
|
||||
let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap_err();
|
||||
assert_eq!(error, ServeError::Failed(Error::IdentityMismatch));
|
||||
// a cancel that fires during the prompt surfaces from the prefill
|
||||
let mut owners = Fake { fresh: true, ..Default::default() };
|
||||
let mut calls = 0;
|
||||
let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || {
|
||||
calls += 1;
|
||||
calls > 1
|
||||
})
|
||||
.unwrap_err();
|
||||
assert_eq!(error, ServeError::Cancelled);
|
||||
assert_eq!(owners.log, ["prefill"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emitted_rounds_reach_the_caller_and_an_emit_failure_fails_the_request() {
|
||||
let mut owners = Fake { fresh: true, ..Default::default() };
|
||||
let mut seen = Vec::new();
|
||||
run_request(&mut owners, &request(8, 4), 100, &mut |t| { seen.extend_from_slice(t); Ok(()) }, &mut || false).unwrap();
|
||||
assert_eq!(seen, [3, 4]);
|
||||
let mut owners = Fake { fresh: true, ..Default::default() };
|
||||
let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Err(Error::InputRead), &mut || false).unwrap_err();
|
||||
assert_eq!(error, ServeError::Failed(Error::InputRead));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,537 @@
|
||||
//! The Original serving stack: every model-lifetime owner of the `generate.cpp` mode17 serve path, opened
|
||||
//! once, and the per-request flow over them (prompt conditioning with the batched Original prefill, then the
|
||||
//! verified-window decode with MTP drafting).
|
||||
//!
|
||||
//! Lifetime of the pieces: the dense weights, the MoE arena cache, the native head/embedding, the target
|
||||
//! session, the prompt executor (which owns the MTP actor and the twelve resident QSA layers), the MTP draft
|
||||
//! session, the prefill arena, the penalty-history stage and the PLE history image live as long as the
|
||||
//! stack. Each request resets them to the empty prompt (the checkpoints taken at load, re-stamped onto the
|
||||
//! current branch generation), conditions the prompt through the executor, and then hands the QSA owners to a
|
||||
//! freshly assembled native Verifier for the decode phase; the verifier is closed and the owners are taken
|
||||
//! back afterwards (see `original_serve_verifier`). There is no conversation cache: every request starts at
|
||||
//! position 0.
|
||||
//!
|
||||
//! Nothing here computes a model number. Where an asset or a producer the Original needs is not available the
|
||||
//! error comes from its owner and is surfaced untouched (`ServeFailure`).
|
||||
use super::{
|
||||
contract::{Error, Result},
|
||||
dense_weight_cache::DenseWeightCache,
|
||||
executor::original_prompt::{embedding::OriginalPromptEmbedding, OriginalPromptExecutor},
|
||||
kar_ple_cache::KarPleCache,
|
||||
moe_weight_cache::MoeWeightCache,
|
||||
original_mtp_full_owner::{OriginalMtpFullOwner, OriginalMtpRequest},
|
||||
original_serve_config::{mtp_full_policy, mtp_scalar_policy, prefill_layout_options, ExpertBlobSizes, RopeConstants},
|
||||
original_serve_engine::{serve_request, OriginalServeEngine, OriginalServeSettings, ServeOutcome},
|
||||
original_serve_host::{HostOwners, OriginalServeHost, RequestSampling},
|
||||
original_serve_native::NativeServePort,
|
||||
original_serve_pool::CpuExpertPool,
|
||||
original_serve_request::{run_request, RequestOwners, ServeError, ServeRequest},
|
||||
original_serve_verifier::{assemble, disassemble, seed_ple_history, DecodeResources, ServeFailure, PLE_HISTORY_BYTES},
|
||||
original_spec_controller::{OriginalSpecController, SpecError},
|
||||
output_native::{OriginalNativeOutput, OriginalNativePenaltyHistory},
|
||||
session::{
|
||||
original_prompt::{draft::OriginalDraftCheckpoint, OriginalPromptInput, OriginalSessionCheckpoint},
|
||||
QwenSession,
|
||||
},
|
||||
};
|
||||
use crate::backend::original_prompt::{PlanError, PromptOptions, PromptPath, PromptPlan};
|
||||
use crate::model_binding::qwen4exp_input::ModelBinding;
|
||||
use leleka_cuda_driver::{
|
||||
Context, DeviceBuffer, NativeHeadDispatch, OriginalMtpFullPolicy, OriginalMtpScalarPolicy, OriginalPrefillArena,
|
||||
};
|
||||
use std::{path::PathBuf, rc::Rc, time::Instant};
|
||||
|
||||
/// Prompt-chunk capacities the Original prefill admits (`PromptPlan::new`), ascending.
|
||||
pub(crate) const ADMITTED_CAPACITIES: [usize; 10] = [256, 512, 1024, 2048, 3072, 4096, 6144, 8192, 16384, 32768];
|
||||
/// The default chunk. The Original sizes it from the free expert-cache slots (`--prefill-auto`); with no GPU
|
||||
/// expert tier there is no slot count to derive it from, so the operator picks it (the arena is a few GiB at
|
||||
/// 8192) and a hardware run settles the default.
|
||||
pub(crate) const DEFAULT_CAPACITY: usize = 2048;
|
||||
/// `qsa_kv_resident_min()`: the shipped resident draft-K/V budget in cells.
|
||||
const MTP_RESIDENT_CELLS: u64 = 20_480;
|
||||
const CPU_WORKERS: i32 = 15;
|
||||
const VOCABULARY: u32 = 248_320;
|
||||
|
||||
/// Operator-visible choices of the stack.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct StackConfig {
|
||||
pub(crate) capacity: usize,
|
||||
/// The request ceiling (`--max-context`): at most the process serving cell count.
|
||||
pub(crate) max_context: i64,
|
||||
/// `--mtp DIR`: the Original-literal RT directory; `None` takes the digest-pinned pack of the binding.
|
||||
pub(crate) rt_directory: Option<PathBuf>,
|
||||
pub(crate) coupled: bool,
|
||||
pub(crate) cpu_workers: i32,
|
||||
/// Read the verifier's GDN/PLE state back into the session at the end of every request (needed only by
|
||||
/// a consumer that reuses the session; the default reset-per-request flow skips the 110 MB transfer).
|
||||
pub(crate) settle_state: bool,
|
||||
}
|
||||
impl StackConfig {
|
||||
pub(crate) fn new(max_context: i64) -> Self {
|
||||
Self {
|
||||
capacity: DEFAULT_CAPACITY,
|
||||
max_context,
|
||||
rt_directory: None,
|
||||
coupled: OriginalServeSettings::coupled_from_environment(),
|
||||
cpu_workers: CPU_WORKERS,
|
||||
settle_state: false,
|
||||
}
|
||||
}
|
||||
pub(crate) fn validate(&self) -> Result<()> {
|
||||
if !ADMITTED_CAPACITIES.contains(&self.capacity)
|
||||
|| self.capacity > 8192
|
||||
|| self.max_context < 1
|
||||
|| self.max_context as u64 > super::contract::serving_cells()
|
||||
|| !(1..=64).contains(&self.cpu_workers)
|
||||
{
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn plan_error(error: PlanError) -> Error {
|
||||
match error {
|
||||
PlanError::InvalidInput => Error::InvalidDimension,
|
||||
PlanError::Overflow => Error::Overflow,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct OriginalServeStack<'a, 'ctx> {
|
||||
binding: &'a ModelBinding,
|
||||
context: &'ctx Context<'ctx>,
|
||||
config: StackConfig,
|
||||
settings: OriginalServeSettings,
|
||||
max_cells: usize,
|
||||
rope: RopeConstants,
|
||||
blobs: ExpertBlobSizes,
|
||||
full_policy: OriginalMtpFullPolicy,
|
||||
scalar_policy: OriginalMtpScalarPolicy,
|
||||
controller: OriginalSpecController,
|
||||
/// Why the stack can serve no more (a lost physical owner); `None` while healthy.
|
||||
broken: Option<Error>,
|
||||
// The empty-prompt lineage taken at load: the reset target of every request.
|
||||
empty_session: OriginalSessionCheckpoint<'ctx>,
|
||||
empty_draft: OriginalDraftCheckpoint,
|
||||
// Owners, dependents first (fields drop in declaration order).
|
||||
history: OriginalNativePenaltyHistory<'ctx>,
|
||||
ple_history: DeviceBuffer<'ctx>,
|
||||
arena: OriginalPrefillArena<'ctx, 'ctx>,
|
||||
executor: OriginalPromptExecutor<'ctx>,
|
||||
draft: super::session::original_prompt::draft::OriginalDraftSession<'ctx>,
|
||||
session: QwenSession<'ctx>,
|
||||
pool: CpuExpertPool<'a>,
|
||||
kar: Option<KarPleCache<'ctx>>,
|
||||
moe: MoeWeightCache<'ctx>,
|
||||
dense: DenseWeightCache<'ctx>,
|
||||
output: OriginalNativeOutput<'ctx>,
|
||||
embedding: OriginalPromptEmbedding<'ctx>,
|
||||
}
|
||||
|
||||
fn failure(error: Error) -> ServeFailure {
|
||||
ServeFailure::from(error)
|
||||
}
|
||||
|
||||
impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
/// `generate.cpp` startup over the binding: embedding table, native head + embedding, dense weights at
|
||||
/// the prompt capacity, the MoE arena cache, the target session, the prompt executor with the MTP
|
||||
/// drafter, the prefill arena, and the per-request stages. `shared` is the session's reference to the
|
||||
/// very context `context` borrows.
|
||||
pub(crate) fn open(
|
||||
binding: &'a ModelBinding,
|
||||
context: &'ctx Context<'ctx>,
|
||||
shared: Rc<Context<'ctx>>,
|
||||
config: StackConfig,
|
||||
) -> std::result::Result<Self, ServeFailure> {
|
||||
config.validate()?;
|
||||
if !std::ptr::eq(context, &*shared) || binding.layer_count() != 48 || !binding.has_mtp() {
|
||||
return Err(failure(Error::IdentityMismatch));
|
||||
}
|
||||
let max_cells = usize::try_from(super::contract::serving_cells()).map_err(|_| failure(Error::Overflow))?;
|
||||
let settings = OriginalServeSettings::mode17(config.max_context, VOCABULARY, config.coupled);
|
||||
let controller = settings.controller()?;
|
||||
let rope = RopeConstants::from_serving_context();
|
||||
let blobs = ExpertBlobSizes::from_binding(binding)?;
|
||||
let layout = prefill_layout_options(config.capacity, max_cells, &blobs);
|
||||
|
||||
let embedding = OriginalPromptEmbedding::load(binding, context)?;
|
||||
let output = OriginalNativeOutput::load(binding, context, NativeHeadDispatch::default(), true)?;
|
||||
let kar = match binding.kar_ple_binding() {
|
||||
Some(provider) => Some(KarPleCache::new(context, provider)?),
|
||||
None => None,
|
||||
};
|
||||
let dense = DenseWeightCache::new_original_prompt_capacity(binding, context, config.capacity)?;
|
||||
let moe = MoeWeightCache::new_original_prompt_arena(binding, context, layout)?;
|
||||
let mut session = QwenSession::for_binding_on_shared_device(binding, shared);
|
||||
let request = OriginalMtpRequest::ring_int8(settings.mtp_max_t, config.capacity, settings.coupled, MTP_RESIDENT_CELLS);
|
||||
let (executor, draft) = match &config.rt_directory {
|
||||
Some(directory) => OriginalPromptExecutor::select_rt_mtp(
|
||||
binding, &dense, &mut session, context, &embedding, &output, directory, config.capacity, true, &request,
|
||||
)
|
||||
.map_err(|e| ServeFailure { error: e.error, detail: e.message })?,
|
||||
None => {
|
||||
let mut executor = OriginalPromptExecutor::new(
|
||||
binding, &dense, &mut session, context, &moe, &embedding, config.capacity, settings.mtp_max_t, true,
|
||||
)?;
|
||||
let assembly = OriginalMtpFullOwner::assemble(binding, &session, context, &moe, &embedding, &output, &request)
|
||||
.map_err(|e| ServeFailure { error: e.error, detail: e.message })?;
|
||||
let draft = executor.install_full_mtp(binding, &session, assembly)?;
|
||||
(executor, draft)
|
||||
}
|
||||
};
|
||||
let mut executor = executor;
|
||||
let arena = context.original_prefill_arena(layout)?;
|
||||
let history = OriginalNativePenaltyHistory::new(binding, context)?;
|
||||
let ple_history = context.allocate(PLE_HISTORY_BYTES)?;
|
||||
let pool = CpuExpertPool::new(binding, config.cpu_workers)?;
|
||||
let empty_session = executor.checkpoint_session(binding, &mut session)?;
|
||||
let empty_draft = draft.checkpoint(binding, &session)?;
|
||||
Ok(Self {
|
||||
binding,
|
||||
context,
|
||||
full_policy: mtp_full_policy(&rope),
|
||||
scalar_policy: mtp_scalar_policy(&rope),
|
||||
config,
|
||||
settings,
|
||||
max_cells,
|
||||
rope,
|
||||
blobs,
|
||||
controller,
|
||||
broken: None,
|
||||
empty_session,
|
||||
empty_draft,
|
||||
history,
|
||||
ple_history,
|
||||
arena,
|
||||
executor,
|
||||
draft,
|
||||
session,
|
||||
pool,
|
||||
kar,
|
||||
moe,
|
||||
dense,
|
||||
output,
|
||||
embedding,
|
||||
})
|
||||
}
|
||||
|
||||
/// `Some` once a physical owner was lost: the stack must be closed and rebuilt.
|
||||
pub(crate) fn health(&self) -> Option<Error> {
|
||||
self.broken
|
||||
}
|
||||
|
||||
/// One request. Admission, reset, prompt conditioning and decode in order; see `run_request`.
|
||||
pub(crate) fn serve(
|
||||
&mut self,
|
||||
request: &ServeRequest,
|
||||
emit: &mut dyn FnMut(&[i32]) -> Result<()>,
|
||||
cancel: &mut dyn FnMut() -> bool,
|
||||
) -> std::result::Result<ServeOutcome, ServeError> {
|
||||
let max_context = self.config.max_context;
|
||||
run_request(self, request, max_context, emit, cancel)
|
||||
}
|
||||
|
||||
/// Close every owner in dependency order; the first failure is reported after all were attempted.
|
||||
pub(crate) fn close(self) -> Result<()> {
|
||||
let Self { history, ple_history, arena, executor, draft, session, pool, kar, moe, dense, output, embedding, .. } = self;
|
||||
let mut first: Option<Error> = None;
|
||||
let mut note = |result: Result<()>| {
|
||||
if let Err(error) = result {
|
||||
first.get_or_insert(error);
|
||||
}
|
||||
};
|
||||
note(history.close());
|
||||
note(ple_history.release().map_err(|_| Error::CudaExecution));
|
||||
drop(arena);
|
||||
note(executor.close());
|
||||
note(draft.close());
|
||||
drop((session, pool, kar));
|
||||
note(moe.close());
|
||||
note(dense.close());
|
||||
note(output.close());
|
||||
note(embedding.close());
|
||||
first.map_or(Ok(()), Err)
|
||||
}
|
||||
|
||||
fn mark_broken(&mut self, error: Error) {
|
||||
self.broken.get_or_insert(error);
|
||||
}
|
||||
|
||||
/// Hand the twelve QSA owners to a fresh verifier and run the request's decode phase over it.
|
||||
fn decode_phase(
|
||||
&mut self,
|
||||
request: &ServeRequest,
|
||||
emit: &mut dyn FnMut(&[i32]) -> Result<()>,
|
||||
cancel: &mut dyn FnMut() -> bool,
|
||||
) -> std::result::Result<ServeOutcome, SpecError> {
|
||||
let Self {
|
||||
binding,
|
||||
context,
|
||||
config,
|
||||
settings,
|
||||
max_cells,
|
||||
rope,
|
||||
blobs,
|
||||
full_policy,
|
||||
controller,
|
||||
history,
|
||||
ple_history,
|
||||
executor,
|
||||
draft,
|
||||
session,
|
||||
pool,
|
||||
kar,
|
||||
dense,
|
||||
output,
|
||||
broken,
|
||||
..
|
||||
} = self;
|
||||
let binding: &ModelBinding = *binding;
|
||||
let context: &'ctx Context<'ctx> = *context;
|
||||
if controller.is_failed() {
|
||||
// a failed restore/finish poisoned the controller; its adaptive cadence is the only thing lost
|
||||
*controller = settings.controller()?;
|
||||
}
|
||||
let sampling = RequestSampling::new(request.params, request.path)?;
|
||||
let n = request.prompt.len();
|
||||
let base = session.original_verified_base()?;
|
||||
if base.position != (n as u64 - 1) {
|
||||
return Err(Error::IdentityMismatch.into());
|
||||
}
|
||||
seed_ple_history(&base, ple_history).map_err(|f| SpecError::Forward(f.error))?;
|
||||
let owners = executor.take_qsa_owners()?;
|
||||
let ple_history: &DeviceBuffer<'ctx> = &*ple_history;
|
||||
let assembled = assemble(
|
||||
binding, &*dense, context, &*output, &base, owners, ple_history, rope, blobs, settings.max_t, *max_cells,
|
||||
);
|
||||
let resources = match assembled {
|
||||
Ok(resources) => resources,
|
||||
Err(lost) => {
|
||||
operator_line("assemble", &lost.failure);
|
||||
if let Some(owners) = lost.owners {
|
||||
if let Err(error) = executor.adopt_qsa_owners(binding, &*dense, &*session, owners) {
|
||||
broken.get_or_insert(error);
|
||||
}
|
||||
} else {
|
||||
broken.get_or_insert(Error::IdentityMismatch);
|
||||
}
|
||||
return Err(SpecError::Forward(lost.failure.error));
|
||||
}
|
||||
};
|
||||
let DecodeResources { verifier, qsa, slots } = resources;
|
||||
let committed = request.prompt[..n - 1].to_vec();
|
||||
let owners = HostOwners {
|
||||
binding,
|
||||
dense: &*dense,
|
||||
context,
|
||||
session: &mut *session,
|
||||
draft: &mut *draft,
|
||||
executor: &mut *executor,
|
||||
kar: kar.as_mut(),
|
||||
history: &mut *history,
|
||||
pool: &mut *pool,
|
||||
qsa: Rc::clone(&qsa),
|
||||
slots,
|
||||
ple_history,
|
||||
policy: &*full_policy,
|
||||
};
|
||||
let host = OriginalServeHost::new(owners, committed, config.max_context as u64, sampling);
|
||||
let (served, verifier, outcome) = match host {
|
||||
Err(error) => (Err(SpecError::Forward(error)), verifier, None),
|
||||
Ok(host) => {
|
||||
let port = NativeServePort::new(verifier, host);
|
||||
let engine = OriginalServeEngine::new(port, VOCABULARY, settings.max_t, settings.max_drafts());
|
||||
match engine {
|
||||
Err(error) => {
|
||||
// `new` consumed the port on failure; the verifier is gone with it. Treated as lost below.
|
||||
let _ = error;
|
||||
broken.get_or_insert(Error::IdentityMismatch);
|
||||
return Err(SpecError::Forward(Error::IdentityMismatch));
|
||||
}
|
||||
Ok(mut engine) => {
|
||||
let started = Instant::now();
|
||||
let result = engine.set_min_p(request.spec_min_p).map_err(SpecError::Forward).and_then(|()| {
|
||||
serve_request(
|
||||
controller,
|
||||
&mut engine,
|
||||
&request.prompt,
|
||||
request.max_new,
|
||||
request.spec_min_p,
|
||||
&request.eos,
|
||||
|tokens| emit(tokens),
|
||||
&mut *cancel,
|
||||
|| started.elapsed().as_secs_f64() * 1e3,
|
||||
)
|
||||
});
|
||||
let (mut verifier, mut host) = engine.into_port().into_parts();
|
||||
if result.is_ok() && config.settle_state {
|
||||
if let Err(error) = host.settle_state(&mut verifier) {
|
||||
broken.get_or_insert(error);
|
||||
}
|
||||
}
|
||||
let outcome = host.finish();
|
||||
(result, verifier, Some(outcome))
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
// Close the verifier (drains both streams, drops the graphs) and take the physical owners back at
|
||||
// the session's lineage; an abandoned window is rolled back there.
|
||||
match disassemble(DecodeResources { verifier, qsa, slots }) {
|
||||
Ok(owners) => {
|
||||
if let Err(error) = executor.adopt_qsa_owners(binding, &*dense, &*session, owners) {
|
||||
broken.get_or_insert(error);
|
||||
}
|
||||
}
|
||||
Err(lost) => {
|
||||
operator_line("disassemble", &lost);
|
||||
broken.get_or_insert(lost.error);
|
||||
}
|
||||
}
|
||||
if outcome.is_some_and(|o| o.failed) {
|
||||
broken.get_or_insert(Error::IdentityMismatch);
|
||||
}
|
||||
served
|
||||
}
|
||||
|
||||
/// Condition `prompt[..n-1]` through the batched Original prefill, one chunk transaction at a time.
|
||||
fn prefill_phase(
|
||||
&mut self,
|
||||
request: &ServeRequest,
|
||||
cancel: &mut dyn FnMut() -> bool,
|
||||
) -> std::result::Result<(), SpecError> {
|
||||
let Self { binding, config, settings, moe, arena, executor, draft, session, kar, dense, embedding, scalar_policy, .. } = self;
|
||||
let binding: &ModelBinding = *binding;
|
||||
let n = request.prompt.len();
|
||||
// generate.cpp: mtp.set_prompt_len(n) before the prompt is read; the draft cap and the request's
|
||||
// sampling parameters configure the actor for the whole request.
|
||||
executor.set_mtp_prompt_len(binding, n as i64)?;
|
||||
executor.set_mtp_max_drafts(binding, i32::try_from(settings.max_drafts()).map_err(|_| Error::Overflow)?)?;
|
||||
executor.set_mtp_draft_sampling(binding, &request.params)?;
|
||||
if n < 2 {
|
||||
return Ok(());
|
||||
}
|
||||
let tokens: Vec<u32> = request.prompt.iter().map(|&t| t as u32).collect();
|
||||
let source = OriginalPromptInput::from_tokenized(binding, &tokens)?;
|
||||
let options = PromptOptions {
|
||||
context_tokens: usize::try_from(config.max_context).map_err(|_| Error::Overflow)?,
|
||||
prompt_cache: false,
|
||||
turn_token: None,
|
||||
root_min: 0,
|
||||
// every conditioning read goes through the batched prefill (the verify-window read of short
|
||||
// prompts needs the verifier during the prompt phase; see the open items)
|
||||
short_read: 64,
|
||||
force_batched: true,
|
||||
verify_width: 4,
|
||||
auto_max: 8192,
|
||||
};
|
||||
let plan = PromptPlan::new(&tokens, 0, None, None, options, config.capacity).map_err(plan_error)?;
|
||||
for action in plan {
|
||||
if action.path == PromptPath::FinalSeed {
|
||||
// the last prompt token is the first verify input of the decode phase
|
||||
break;
|
||||
}
|
||||
let PromptPath::Batched { .. } = action.path else {
|
||||
return Err(Error::IdentityMismatch.into());
|
||||
};
|
||||
if session.target_origin()?.next_position() != action.first as u64 {
|
||||
return Err(Error::IdentityMismatch.into());
|
||||
}
|
||||
if cancel() {
|
||||
return Err(SpecError::Cancelled);
|
||||
}
|
||||
let pending = executor.forward(
|
||||
binding,
|
||||
&*dense,
|
||||
&mut *session,
|
||||
&source,
|
||||
action.count,
|
||||
kar.as_mut(),
|
||||
&mut *moe,
|
||||
&mut *arena,
|
||||
&mut *draft,
|
||||
&*embedding,
|
||||
&*scalar_policy,
|
||||
|| cancel(),
|
||||
);
|
||||
let pending = match pending {
|
||||
Ok(pending) => pending,
|
||||
Err(error) if cancel() => {
|
||||
let _ = error;
|
||||
return Err(SpecError::Cancelled);
|
||||
}
|
||||
Err(error) => return Err(SpecError::Forward(error)),
|
||||
};
|
||||
pending.publish()?;
|
||||
}
|
||||
if session.target_origin()?.next_position() != (n as u64 - 1) {
|
||||
return Err(Error::IdentityMismatch.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn operator_line(what: &str, failure: &ServeFailure) {
|
||||
use std::io::Write;
|
||||
let _ = writeln!(std::io::stderr().lock(), "leleka-serve {what}: {}", failure.describe());
|
||||
}
|
||||
|
||||
impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> {
|
||||
fn is_fresh(&self) -> bool {
|
||||
self.broken.is_none()
|
||||
&& self.session.original_state_lag().is_none()
|
||||
&& self.session.target_origin().is_ok_and(|origin| origin.next_position() == 0)
|
||||
}
|
||||
fn reset(&mut self) -> std::result::Result<(), Error> {
|
||||
if let Some(error) = self.broken {
|
||||
return Err(error);
|
||||
}
|
||||
let result = (|| {
|
||||
let empty = self.empty_session.rebased_empty(&self.session)?;
|
||||
self.executor.restore_session(self.binding, &self.dense, &mut self.session, &empty)?;
|
||||
self.draft.reset_to_empty(self.binding, &self.dense, &self.session, &self.empty_draft)
|
||||
})();
|
||||
if let Err(error) = result {
|
||||
self.mark_broken(error);
|
||||
}
|
||||
result
|
||||
}
|
||||
fn prefill(&mut self, request: &ServeRequest, cancel: &mut dyn FnMut() -> bool) -> std::result::Result<(), SpecError> {
|
||||
self.prefill_phase(request, cancel)
|
||||
}
|
||||
fn decode(
|
||||
&mut self,
|
||||
request: &ServeRequest,
|
||||
emit: &mut dyn FnMut(&[i32]) -> Result<()>,
|
||||
cancel: &mut dyn FnMut() -> bool,
|
||||
) -> std::result::Result<ServeOutcome, SpecError> {
|
||||
self.decode_phase(request, emit, cancel)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_default_chunk_is_an_admitted_capacity_and_validation_follows_the_prefill_rules() {
|
||||
let config = StackConfig::new(4096);
|
||||
assert!(ADMITTED_CAPACITIES.contains(&config.capacity));
|
||||
for capacity in [256usize, 1024, 8192] {
|
||||
assert!(StackConfig { capacity, ..config.clone() }.validate().is_ok(), "{capacity}");
|
||||
}
|
||||
for capacity in [0usize, 255, 300, 16384, 32768] {
|
||||
assert!(StackConfig { capacity, ..config.clone() }.validate().is_err(), "{capacity}");
|
||||
}
|
||||
assert!(StackConfig { max_context: 0, ..config.clone() }.validate().is_err());
|
||||
assert!(StackConfig { cpu_workers: 0, ..config.clone() }.validate().is_err());
|
||||
assert!(StackConfig { cpu_workers: 65, ..config.clone() }.validate().is_err());
|
||||
assert!(StackConfig { max_context: i64::MAX, ..config }.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_errors_keep_their_class() {
|
||||
assert_eq!(plan_error(PlanError::InvalidInput), Error::InvalidDimension);
|
||||
assert_eq!(plan_error(PlanError::Overflow), Error::Overflow);
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ pub(in crate::qwen_forward) const PLE_HISTORY_BYTES: usize = PLE_HISTORY_VALUES
|
||||
|
||||
/// A refusal with the driver's own words when it has them (an unbound producer, an unsealed asset).
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(in crate::qwen_forward) struct ServeFailure {
|
||||
pub(crate) struct ServeFailure {
|
||||
pub(in crate::qwen_forward) error: Error,
|
||||
pub(in crate::qwen_forward) detail: Option<String>,
|
||||
}
|
||||
@@ -53,7 +53,7 @@ impl From<leleka_cuda_driver::Error> for ServeFailure {
|
||||
}
|
||||
impl ServeFailure {
|
||||
/// `class=... detail=...` for the operator diagnostic line (the detail text is a fixed driver string).
|
||||
pub(in crate::qwen_forward) fn describe(&self) -> String {
|
||||
pub(crate) fn describe(&self) -> String {
|
||||
match &self.detail {
|
||||
Some(detail) => format!("{:?}: {detail}", self.error),
|
||||
None => format!("{:?}", self.error),
|
||||
|
||||
@@ -37,6 +37,15 @@ impl<'ctx> ResidentQsaPrior<'ctx>{
|
||||
/// index image and mapped K/V for the whole decode phase; after each commit event the runtime records where
|
||||
/// both now end (an index checkpoint and a mapped prefix of the verifier's own journal) as the session's
|
||||
/// resident witness. Binding, owner and weight provider are inherited, never re-derived.
|
||||
/// The EMPTY lineage (index image and mapped K/V both at position 0) re-stamped onto another branch
|
||||
/// generation of the same session. The empty state is content-independent by construction (no cell is
|
||||
/// reachable), so a position-0 prior taken at load remains the exact reset target after any number of
|
||||
/// restores; any later position is refused.
|
||||
pub(in crate::qwen_forward) fn rebased_empty(&self,origin:TargetStepOrigin)->Result<Self>{
|
||||
if self.0.index.next_position()!=0||self.0.kv.next_position()!=0||origin.next_position()!=0||self.0.origin.next_position()!=0
|
||||
||!self.0.origin.same_session(&origin){return Err(Error::IdentityMismatch)}
|
||||
Ok(Self(Rc::new(Prior{binding:self.0.binding.clone(),owner:self.0.owner.clone(),origin,layer:self.0.layer,provider:self.0.provider.clone(),index:self.0.index.clone(),kv:self.0.kv.clone()})))
|
||||
}
|
||||
pub(in crate::qwen_forward) fn advanced(&self,origin:TargetStepOrigin,index:OriginalQsaIndexCheckpoint<'ctx>,kv:OriginalQsaMappedPrefix)->Result<Self>{
|
||||
if index.next_position()!=kv.next_position()||(index.next_position() as u64)<self.next_position(){return Err(Error::IdentityMismatch)}
|
||||
Ok(Self(Rc::new(Prior{binding:self.0.binding.clone(),owner:self.0.owner.clone(),origin,layer:self.0.layer,provider:self.0.provider.clone(),index,kv})))
|
||||
|
||||
@@ -182,6 +182,25 @@ impl<'ctx> OriginalDraftSession<'ctx>{
|
||||
let actual=session.target_origin()?;
|
||||
self.rebind_restored(prior,&actual)
|
||||
}
|
||||
/// A new request starts from the empty prompt: roll the ring back to the empty snapshot taken at load
|
||||
/// (`empty`, position 0) and rebind it to the session, which must stand at position 0 again. Unlike
|
||||
/// `restore_current` the draft's current origin is NOT required to equal the checkpoint's: the whole
|
||||
/// previous request lies between them, and the empty ring holds no history to disagree with.
|
||||
pub(in crate::qwen_forward) fn reset_to_empty(&mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>,
|
||||
session:&QwenSession<'ctx>,empty:&OriginalDraftCheckpoint)->Result<()> {
|
||||
let actual=session.target_origin()?;
|
||||
if self.failed||!self.binding.matches(&binding.identity())||!empty.binding.matches(&self.binding)
|
||||
||empty.origin.next_position()!=0||empty.snapshot.next_position()!=0||empty.first_materialized!=0
|
||||
||actual.next_position()!=0||!actual.same_session(&empty.origin)||!self.origin.same_session(&actual){
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let context=dense.retained_context(binding,self.context)?;
|
||||
let mut workspace=dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?;
|
||||
let result=self.ring.as_mut().ok_or(Error::IdentityMismatch)?.restore(&mut workspace,&empty.snapshot)
|
||||
.map_err(draft_driver_error);
|
||||
if result.is_err(){self.failed=true;return result;}
|
||||
self.origin=actual;self.snapshot=empty.snapshot.clone();self.first_materialized=0;Ok(())
|
||||
}
|
||||
pub(super) fn rebind_restored(&mut self,prior:&OriginalDraftCheckpoint,actual:&TargetStepOrigin)->Result<()> {
|
||||
if self.failed||!self.origin.same_prefix(&prior.origin)||!actual.same_session(&prior.origin)
|
||||
||actual.next_position()!=prior.origin.next_position()
|
||||
|
||||
@@ -73,6 +73,20 @@ pub(in crate::qwen_forward) struct OriginalSessionCheckpoint<'driver>{
|
||||
origin:TargetStepOrigin,predecessors:[i32;2],ple:Option<PlePrior>,
|
||||
gdn:[Option<GdnPrior>;STATE_CAPACITY],qsa:[Option<ResidentQsaPrior<'driver>>;STATE_CAPACITY],
|
||||
}
|
||||
impl<'driver> OriginalSessionCheckpoint<'driver>{
|
||||
/// The empty-prompt checkpoint taken at load, re-stamped onto the session's CURRENT branch generation
|
||||
/// (every restore bumps it, which fences old checkpoints). Only the position-0 checkpoint can be
|
||||
/// re-stamped: the empty lineage holds no history, so it names the same state on every branch.
|
||||
pub(in crate::qwen_forward) fn rebased_empty(&self,session:&QwenSession<'driver>)->Result<Self>{
|
||||
let current=session.target_origin()?;
|
||||
if self.origin.next_position()!=0||!self.origin.same_session(¤t)||self.ple.is_some()
|
||||
||self.gdn.iter().any(Option::is_some){return Err(Error::IdentityMismatch);}
|
||||
let origin=super::checkpoint::origin_at(session,0);
|
||||
let mut qsa:[Option<ResidentQsaPrior<'driver>>;STATE_CAPACITY]=std::array::from_fn(|_|None);
|
||||
for slot in 0..STATE_CAPACITY{if let Some(prior)=&self.qsa[slot]{qsa[slot]=Some(prior.rebased_empty(origin.clone())?);}}
|
||||
Ok(Self{origin,predecessors:[-1,-1],ple:None,gdn:std::array::from_fn(|_|None),qsa})
|
||||
}
|
||||
}
|
||||
impl<'driver> QwenSession<'driver> {
|
||||
pub(in crate::qwen_forward) fn original_checkpoint(&mut self,binding:&ModelBinding)->Result<OriginalSessionCheckpoint<'driver>>{
|
||||
let origin=self.target_origin()?;
|
||||
|
||||
Reference in New Issue
Block a user