engine crates: dyn closures and sinks become generics (engine-core 18 -> 2, engine 53 -> 9 outside the Box<dyn Backend> process boundary), load laps on the Clock port, named exceptions for what must stay, real headers for the last generated ones

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-11-14 21:44:58 +01:00
co-authored by Claude Sonnet 5.5
parent fbca47bd75
commit 5b84cd2cf8
51 changed files with 182 additions and 123 deletions
+1 -6
View File
@@ -4,20 +4,15 @@
"oversize": {},
"source": {
"dyn-trait:leleka-cuda-driver": 45,
"dyn-trait:leleka-engine-core": 18,
"dyn-trait:leleka-engine-fake": 1,
"dyn-trait:leleka-engine-qwen35-cuda": 53,
"env-read:leleka-engine-qwen35-cuda": 1,
"dyn-trait:leleka-engine-qwen35-cuda": 9,
"env-read:strata-control": 3,
"glob-super-import:leleka-cuda-driver": 2,
"instant-now:leleka-cuda-driver": 25,
"instant-now:leleka-engine-qwen35-cuda": 16,
"instant-now:leleka-native-cpu-expert": 27,
"instant-now:strata-control": 15,
"instant-now:strata-desktop-core": 4,
"path-include:leleka-cuda-driver": 1,
"process-global:leleka-cuda-driver": 96,
"process-global:leleka-engine-qwen35-cuda": 59,
"process-global:leleka-native-cpu-expert": 27,
"process-global:strata-control": 2
},
+58 -1
View File
@@ -158,7 +158,64 @@
{"crate": "leleka-gateway-text", "file": "src/prompt/renderer.rs", "ratchet": "process-global", "reason": "the compiled pinned chat template: immutable, built on first use, read by every request"},
{"crate": "strata-control", "file": "src/request_log.rs", "ratchet": "process-global", "reason": "the process-wide request counters and histograms that /metrics renders; written by every request"},
{"crate": "strata-control", "file": "src/responses/harmony_prompt.rs", "ratchet": "process-global", "reason": "the gpt-oss prompt date: configuration set once by serve before the first request"},
{"crate": "strata-control", "file": "src/stage_trace.rs", "ratchet": "process-global", "reason": "diagnostic stage table of the replay harness and STRATA_STAGE_TRACE: one table per process by design"}
{"crate": "strata-control", "file": "src/stage_trace.rs", "ratchet": "process-global", "reason": "diagnostic stage table of the replay harness and STRATA_STAGE_TRACE: one table per process by design"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/settings/source.rs", "ratchet": "env-read", "reason": "the one reader of the process environment of the engine: ProcessEnv is the adapter of the EnvSource port, and Settings parses every variable into typed fields there (S13)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_engine/round_tally/serve_rounds.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per traced port call, only when the bring-up trace is on); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_lookahead.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per routing prediction on the lookahead thread); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool/direct_group_steps.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per CPU expert group of a decode round); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool/direct_tier.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per eager admission, once at start-up); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per pool phase lap of a decode round); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/span_cache_and_pcie_lag.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per PCIe lag probe and adaptation round); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/prefill_profile.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per prefill stage span, only when the profile switch is on); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/prompt_device_rows/prompt_device_read/produce_original_gdn.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per GDN layer producer lap, only when the command profile is on); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-core", "file": "src/family.rs", "ratchet": "dyn-trait", "reason": "EngineFamily::spawn returns Box<dyn Backend>: the family seam is the process boundary of the engine, called once at start-up"},
{"crate": "leleka-engine-fake", "file": "src/lib.rs", "ratchet": "dyn-trait", "reason": "Box<dyn Backend> is the process boundary: the factory hands the composed engine to the host, which holds one Backend per process (startup composition only, never per round)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/family.rs", "ratchet": "dyn-trait", "reason": "Box<dyn Backend> is the process boundary: the factory hands the composed engine to the host, which holds one Backend per process (startup composition only, never per round)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/spawn.rs", "ratchet": "dyn-trait", "reason": "Box<dyn Backend> is the process boundary: the factory hands the composed engine to the host, which holds one Backend per process (startup composition only, never per round)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/spawn_optimized.rs", "ratchet": "dyn-trait", "reason": "Box<dyn Backend> is the process boundary: the factory hands the composed engine to the host, which holds one Backend per process (startup composition only, never per round)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/spawn_original.rs", "ratchet": "dyn-trait", "reason": "Box<dyn Backend> is the process boundary: the factory hands the composed engine to the host, which holds one Backend per process (startup composition only, never per round)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/spawn_preview.rs", "ratchet": "dyn-trait", "reason": "Box<dyn Backend> is the process boundary: the factory hands the composed engine to the host, which holds one Backend per process (startup composition only, never per round)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/measurement.rs", "ratchet": "dyn-trait", "reason": "the evaluation measurement sink is a stored callback handed in by the host (observer port, called once per request)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/original_serve/runner.rs", "ratchet": "dyn-trait", "reason": "the GPU telemetry probe is a stored callback handed in by the host at load (port, sampled by the telemetry tick, not per token)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/original_serve/runner/owner_run_steps.rs", "ratchet": "process-global", "reason": "reaches the process-wide memory governor through Governor::global(); the governor is one per process by design (host RAM is process-wide) and the handle is threaded through StackConfig and the request environment in the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/original_serve/runner/reconfigure_command.rs", "ratchet": "process-global", "reason": "reaches the process-wide memory governor through Governor::global(); the governor is one per process by design (host RAM is process-wide) and the handle is threaded through StackConfig and the request environment in the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/session.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/conversation/memory.rs", "ratchet": "process-global", "reason": "reaches the process-wide memory governor through Governor::global(); the governor is one per process by design (host RAM is process-wide) and the handle is threaded through StackConfig and the request environment in the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/memory_governor.rs", "ratchet": "process-global", "reason": "reaches the process-wide memory governor through Governor::global(); the governor is one per process by design (host RAM is process-wide) and the handle is threaded through StackConfig and the request environment in the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/memory_governor/page_cache.rs", "ratchet": "process-global", "reason": "reaches the process-wide memory governor through Governor::global(); the governor is one per process by design (host RAM is process-wide) and the handle is threaded through StackConfig and the request environment in the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/qwen4exp_input.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/qwen4exp_input/binding_identity_and_input_binding_error.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/qwen4exp_input/model_binding.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/contract.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/mtp/mtp_frame.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/mtp/state/chunk/checked_chunk_end.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/mtp/state/dense_kv.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/mtp/state/prefix_draft_snapshot.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/mtp/state/warming.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/mtp_attention/dense_geometry.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/mtp_decode/first_seed_reuse_enabled.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/mtp_decode/mtp_decoder/draft_warm_and_window.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/mtp_decode/mtp_window_spec.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/split_group_pcie.rs", "ratchet": "process-global", "reason": "the adaptive-tier tuning constants, derived once from the settings capture (immutable after the first read)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack.rs", "ratchet": "process-global", "reason": "the epoch of the bring-up trace timestamps (DBG_T0), set once; diagnostics only"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack/original_serve_stack_methods/open_cache_steps.rs", "ratchet": "process-global", "reason": "reaches the process-wide memory governor through Governor::global(); the governor is one per process by design (host RAM is process-wide) and the handle is threaded through StackConfig and the request environment in the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack/original_serve_stack_methods/original_serve_stack_memory_classes.rs", "ratchet": "process-global", "reason": "reaches the process-wide memory governor through Governor::global(); the governor is one per process by design (host RAM is process-wide) and the handle is threaded through StackConfig and the request environment in the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack/original_serve_stack_methods/original_serve_stack_open/assemble.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack/original_serve_stack_methods/original_serve_stack_prefill_phase.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack/prefix/prefix_config.rs", "ratchet": "process-global", "reason": "reaches the process-wide memory governor through Governor::global(); the governor is one per process by design (host RAM is process-wide) and the handle is threaded through StackConfig and the request environment in the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack/prefix/prefix_serve/prefix_serve_after_phase_parking.rs", "ratchet": "process-global", "reason": "reaches the process-wide memory governor through Governor::global(); the governor is one per process by design (host RAM is process-wide) and the handle is threaded through StackConfig and the request environment in the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack/stack_config_and_ttft_marks.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_spec_controller/trace_enabled.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_spec_draft.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_spec_draft/prefill_records.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/qsa_index/context.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/qsa_native_resources.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/chunk/host_charge_bounded.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/chunk/qwen_chunk_txn/qwen_chunk_txn_begin.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/chunk/verify/qwen_chunk_txn/qwen_chunk_txn_begin_verification.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/chunk/verify/verified_target_prefix.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/qwen_session.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"}
],
"source_patterns": [
{"id": "env-read", "regex": "\\benv::var(_os)?\\(", "why": "configuration must be parsed once into a Settings struct (S13), not read all over the code"},
+2 -2
View File
@@ -37,8 +37,8 @@ pub struct KvTarget<'a> {
pub has_index_rows: bool,
}
struct Verifier<'a> {
mem: &'a mut dyn StateMemory,
struct Verifier<'a, M: StateMemory + ?Sized> {
mem: &'a mut M,
buffer: Vec<u8>,
hash: u64,
error: Option<ConvError>,
@@ -7,8 +7,8 @@ use super::{
/// Compare the pages of the drafter ring (the last `st.n_slots` pages of the saved pool) with the device's resident
/// copy of them; false once a page differs or cannot be read (the verifier holds the failure).
fn verify_ring(
v: &mut Verifier<'_>,
fn verify_ring<M: StateMemory + ?Sized>(
v: &mut Verifier<'_, M>,
saved: &crate::conversation::buffer::ConversationBuffer,
(begin, end): (i64, i64),
(layer, pool, st): (KvLayer, KvPool, &QsaDesc),
@@ -30,7 +30,7 @@ fn verify_ring(
/// Diagnostic read-back after a synchronised restore: compares the
/// authoritative bytes (and the resident draft-ring pages), fingerprinting the
/// authoritative payload only (FNV-1a 64). Never changes model state.
pub fn kv_verify(image: &ConversationKv, target: KvTarget<'_>, mem: &mut dyn StateMemory) -> ConvResult<u64> {
pub fn kv_verify<M: StateMemory + ?Sized>(image: &ConversationKv, target: KvTarget<'_>, mem: &mut M) -> ConvResult<u64> {
let KvTarget { layer, st, g, upto, has_index_rows: index } = target;
kv_validate(image, st, g, upto, index)?;
let mut v = Verifier { mem, buffer: vec![0; 65536], hash: 1469598103934665603, error: None };
@@ -91,11 +91,11 @@ fn capture_layer(
/// only for storage retained from an image actually restored into this
/// session, bounded by every subsequent rewrite: equal token IDs alone do not
/// establish that its K/V bytes are unchanged.
pub fn kv_save(
pub fn kv_save<M: StateMemory + ?Sized>(
image: &mut ConversationKv,
target: KvTarget<'_>,
unchanged_tokens: i64,
mem: &mut dyn StateMemory,
mem: &mut M,
reused_bytes: Option<&mut usize>,
) -> ConvResult<()> {
let KvTarget { layer, st, g, upto, has_index_rows: index } = target;
@@ -159,7 +159,7 @@ fn restore_buffer(
/// Write the image into the layer; refills streamed residency afterwards.
/// The caller synchronises the device before and after the whole session.
pub fn kv_restore(image: &ConversationKv, target: KvTarget<'_>, mem: &mut dyn StateMemory) -> ConvResult<()> {
pub fn kv_restore<M: StateMemory + ?Sized>(image: &ConversationKv, target: KvTarget<'_>, mem: &mut M) -> ConvResult<()> {
let KvTarget { layer, st, g, upto, has_index_rows: index } = target;
kv_validate(image, st, g, upto, index)?;
for (buffer, pool) in image.buffers().into_iter().zip(KvPool::ALL) {
@@ -180,7 +180,7 @@ pub fn kv_restore(image: &ConversationKv, target: KvTarget<'_>, mem: &mut dyn St
Ok(())
}
impl Verifier<'_> {
impl<M: StateMemory + ?Sized> Verifier<'_, M> {
/// Compare device bytes at `base + ..` with `expected`, chunked through a
/// 64 KiB workspace; optionally fold them into the fingerprint.
pub(super) fn compare(&mut self, loc: StateRegion, base: usize, expected: &[u8], include_hash: bool) -> bool {
@@ -167,9 +167,9 @@ impl ConversationManager {
/// continue the live session, restore a checkpoint, restore a parked
/// conversation (parking the outgoing one first), or start empty. Any
/// error is fatal for the request and the device state is then undefined.
pub fn begin_request(
pub fn begin_request<E: SessionEngine + ?Sized>(
&mut self,
engine: &mut dyn SessionEngine,
engine: &mut E,
ids: &[i32],
req_imgs: &[ConversationImageKey],
want_cvec: bool,
@@ -215,9 +215,9 @@ impl ConversationManager {
/// A checkpoint of the state after `ids[..position]`. `Ok` also when
/// checkpoints are off. An existing checkpoint at the position just
/// becomes the most recently used.
pub fn checkpoint_at(
pub fn checkpoint_at<E: SessionEngine + ?Sized>(
&mut self,
engine: &mut dyn SessionEngine,
engine: &mut E,
ids: &[i32],
req_imgs: &[ConversationImageKey],
position: usize,
@@ -247,9 +247,9 @@ impl ConversationManager {
/// A batched prompt chunk finished and the prompt is read up to `done`:
/// take the periodic checkpoint when it is due.
pub fn chunk_done(
pub fn chunk_done<E: SessionEngine + ?Sized>(
&mut self,
engine: &mut dyn SessionEngine,
engine: &mut E,
ids: &[i32],
req_imgs: &[ConversationImageKey],
done: usize,
@@ -267,9 +267,9 @@ impl ConversationManager {
/// and the turn/root checkpoint when the action ends its segment.
// Used by the Original-path prompt driver (the plan type is crate-private).
#[allow(dead_code)]
pub fn after_prompt_action(
pub fn after_prompt_action<E: SessionEngine + ?Sized>(
&mut self,
engine: &mut dyn SessionEngine,
engine: &mut E,
ids: &[i32],
req_imgs: &[ConversationImageKey],
action: &PromptAction,
@@ -170,7 +170,7 @@ impl ConversationManager {
/// an incoming image that is still alive during the exchange. Anything
/// recoverable (nothing to park, no room, no RAM, allocation failure)
/// skips parking and returns `Ok`; a device failure is fatal.
pub(in super::super) fn park_current(&mut self, engine: &mut dyn SessionEngine, held: usize) -> ConvResult<()> {
pub(in super::super) fn park_current<E: SessionEngine + ?Sized>(&mut self, engine: &mut E, held: usize) -> ConvResult<()> {
if !self.cache.enabled() || !self.live_ok || self.live.is_empty() {
return Ok(());
}
@@ -241,11 +241,11 @@ fn begin_capture(
}
/// Capture the K/V of every layer, then the draft's; returns the bytes the retained storage let it skip.
fn capture_kv(
fn capture_kv<M: StateMemory + ?Sized>(
captured: &mut SavedConversation,
view: &ConversationView<'_>,
session: SnapshotSession<'_>,
mem: &mut dyn StateMemory,
mem: &mut M,
unchanged: i64,
) -> ConvResult<usize> {
let SnapshotSession { ss, g, draft } = session;
@@ -270,10 +270,10 @@ fn capture_kv(
/// Builds into a new object so a failure cannot publish a partial snapshot.
/// `reuse` is consumed, including on failure. The caller admits the estimate
/// first; the active session is never modified by capture.
pub fn snapshot_save(
pub fn snapshot_save<M: StateMemory + ?Sized>(
view: &ConversationView<'_>,
session: SnapshotSession<'_>,
mem: &mut dyn StateMemory,
mem: &mut M,
reuse: ConversationKvReuse,
reused_bytes: Option<&mut usize>,
) -> ConvResult<SavedConversation> {
@@ -335,12 +335,12 @@ pub fn snapshot_validate(
// Restore a whole image. Invalid images are rejected before any device
/// write; a transfer failure may leave partial state.
pub fn snapshot_restore(
pub fn snapshot_restore<M: StateMemory + ?Sized>(
image: &SavedConversation,
ss: &SessionSpec,
g: &ModelGeometry,
draft: &QsaDesc,
mem: &mut dyn StateMemory,
mem: &mut M,
) -> RestoreOutcome {
if let Err(e) = snapshot_validate(image, ss, g, draft) {
return RestoreOutcome::Invalid(e.0);
@@ -349,7 +349,7 @@ pub fn snapshot_restore(
return RestoreOutcome::TransferFailed(e.0);
}
let upto = image.live.ids.len() as i64;
let restore = |mem: &mut dyn StateMemory| -> ConvResult<()> {
let restore = |mem: &mut M| -> ConvResult<()> {
for j in 0..ss.owned_qsa() {
let st = ss.owned(j).ok_or_else(|| ConvError("conversation snapshot: missing QSA state".into()))?;
kv_restore(&image.kv[j], KvTarget { layer: KvLayer::Main(j), st, g, upto, has_index_rows: true }, mem)?;
+6 -6
View File
@@ -188,11 +188,11 @@ fn alloc_payloads(c: &mut ConversationCheckpoint, ss: &SessionSpec, z: &StateSiz
/// Capture the running state at `c.ids.len()` tokens into `c`'s payloads.
/// The caller synchronises the device first.
pub fn checkpoint_save(
pub fn checkpoint_save<M: StateMemory + ?Sized>(
c: &mut ConversationCheckpoint,
ss: &SessionSpec,
g: &ModelGeometry,
mem: &mut dyn StateMemory,
mem: &mut M,
) -> ConvResult<()> {
let z = checkpoint_targets(ss, g, c.ids.len())?;
alloc_payloads(c, ss, &z)?;
@@ -208,11 +208,11 @@ pub fn checkpoint_save(
}
/// Restore the indexer state of QSA layer `j`; the spare (moving) pooled row is reconstructed from the dead key.
fn restore_indexer(
fn restore_indexer<M: StateMemory + ?Sized>(
c: &ConversationCheckpoint,
j: usize,
(z, g): (&StateSizes, &ModelGeometry),
mem: &mut dyn StateMemory,
mem: &mut M,
) -> ConvResult<()> {
let idx = |kind| StateRegion::Idx { layer: j, kind };
let dead = &c.dead[j * z.dead..(j + 1) * z.dead];
@@ -228,11 +228,11 @@ fn restore_indexer(
}
/// Restore a validated checkpoint; invalid input writes nothing.
pub fn checkpoint_restore(
pub fn checkpoint_restore<M: StateMemory + ?Sized>(
c: &ConversationCheckpoint,
ss: &SessionSpec,
g: &ModelGeometry,
mem: &mut dyn StateMemory,
mem: &mut M,
) -> ConvResult<()> {
checkpoint_validate(c, ss, g)?;
let z = session_sizes(g, ss)?;
@@ -1,5 +1,5 @@
//! Defines `GpuProbe`, `Run`.
//! Split out of `original_serve` to keep its files under the line limit.
//! The state of the Original owner loop: `Run` (everything `serve_load` hands the loop once the context exists) and the
//! GPU telemetry probe port the host injects. The loop's steps live in the `runner/` files.
use super::super::{
ActiveGuard, BackendError, Command, DeferredTail, ErrorCode, FinishReason, GENERATION_TIMEOUT, GenerationEvent,
@@ -244,6 +244,11 @@ fn capture_json(
)
}
/// Token ids as the comma-separated line of the capture file.
fn join_ids<T: std::fmt::Display>(ids: &[T]) -> String {
ids.iter().map(ToString::to_string).collect::<Vec<_>>().join(",")
}
/// The prompt ids and the generated ids of one request, as the capture records them.
#[derive(Clone, Copy)]
pub(super) struct CapturedIds<'a> {
@@ -265,9 +270,8 @@ pub(super) fn capture_request(
let CapturedIds { prompt, generated } = ids;
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
let index = NEXT.fetch_add(1, Ordering::Relaxed);
let join = |ids: &mut dyn Iterator<Item = i64>| ids.map(|t| t.to_string()).collect::<Vec<_>>().join(",");
let prompt_line = join(&mut prompt.iter().map(|&t| i64::from(t)));
let generated_line = join(&mut generated.iter().map(|&t| i64::from(t)));
let prompt_line = join_ids(prompt);
let generated_line = join_ids(generated);
let lines = (prompt_line.as_str(), generated_line.as_str());
let json = capture_json(index, request, lines, (rounds, reused, prompt.len(), generated.len()));
if std::fs::create_dir_all(dir).is_err() {
@@ -26,7 +26,7 @@ pub(super) struct ArmShape {
pub(super) flags: ArmFlags,
}
/// 1 when `on` is set, 0 when `off` is, else -1.
fn tri(has: &dyn Fn(&str) -> bool, on: &str, off: &str) -> i8 {
fn tri(has: &impl Fn(&str) -> bool, on: &str, off: &str) -> i8 {
if has(on) {
1
} else if has(off) {
@@ -43,7 +43,7 @@ fn tail_flag(flags: &str) -> Option<u32> {
/// docs/upstream-port-plan.md rows 2.4 / 2.5: `kh` / `rec` / `orig` (the prompt GDN recurrence: the
/// three-value-heads kernel, the two-barrier kernel, the sealed Original one); `wide` / `fast` (the prompt top-k) and
/// `cluster` / `nocluster` (the decode window's top-k on a thread-block cluster) are plain on/off flags.
fn gdn_flag(has: &dyn Fn(&str) -> bool) -> i8 {
fn gdn_flag(has: &impl Fn(&str) -> bool) -> i8 {
if has("kh") {
1
} else if has("rec") {
@@ -113,7 +113,7 @@ impl ArmFlags {
}
/// `mode@CAP[/BLOCK][!flag...]`: the mode may carry the arm's own prefill chunk and grid: `reply@8192` (chunk 8192,
/// grid = chunk) or `reply@8192/2048`. A bare mode takes `default_capacity()`.
pub(super) fn parse(arm: &str, default_capacity: &dyn Fn() -> usize) -> ArmShape {
pub(super) fn parse(arm: &str, default_capacity: &impl Fn() -> usize) -> ArmShape {
let Some((mode, shape)) = arm.split_once('@') else {
let flags = ArmFlags::environment();
return ArmShape { mode: arm.to_owned(), capacity: default_capacity(), block: 0, tiers: None, flags };
@@ -67,7 +67,7 @@ pub(super) fn emit_terminal(
/// says so or the reader is gone.
pub(super) fn emit_event(
sink: &GenerationSink,
cancelled: &dyn Fn() -> bool,
cancelled: &impl Fn() -> bool,
clock: &impl Clock,
event: GenerationEvent,
) -> Result<(), GenerationFailure> {
+4 -3
View File
@@ -4,6 +4,7 @@
//!
//! `lap` times a phase of the loading thread since the previous lap; `span` times a phase that ran on
//! another thread (the parallel verifications), so overlapping phases can be told apart in the log.
use leleka_obs::time::{Clock as _, SystemClock};
use std::{
io::Write,
sync::Mutex,
@@ -28,7 +29,7 @@ fn emit(phase: &str, seconds: Duration, total: Duration) {
/// Start the clock of one load.
pub(crate) fn begin() {
let now = Instant::now();
let now = SystemClock.now();
if let Ok(mut clock) = CLOCK.lock() {
*clock = Some(Clock { start: now, last: now });
}
@@ -36,7 +37,7 @@ pub(crate) fn begin() {
/// The phase of the calling thread that ended now, started at the previous lap.
pub(crate) fn lap(phase: &str) {
let now = Instant::now();
let now = SystemClock.now();
if let Ok(mut guard) = CLOCK.lock()
&& let Some(clock) = guard.as_mut()
{
@@ -49,7 +50,7 @@ pub(crate) fn lap(phase: &str) {
/// A phase that started at `started` (possibly on another thread) and ended now. Does not move the lap mark.
pub(crate) fn span(phase: &str, started: Instant) {
let now = Instant::now();
let now = SystemClock.now();
if let Ok(guard) = CLOCK.lock()
&& let Some(clock) = guard.as_ref()
{
@@ -1,4 +1,5 @@
//! Page-cache release after the load (`drop_file_cache`), moved out of `memory_governor` by STRA-338 (size).
//! Page-cache release after the load (`drop_file_cache`): the kernel gets the pages of the shard files back once the
//! weights are on the device.
use super::{Governor, HostFacts, HostProc};
@@ -1,5 +1,5 @@
//! Methods of `OwnedCopy`: `create`, `writer`, `owns_directory`, `owns_file` and 1 more.
//! Implements `Drop for OwnedCopy`. Functions: `inode`, `regular`, `root`, `copy_exact` and 8 more.
//! Linux and macOS test-build backing of the MTP pack: the pinned file is copied into a private, sealed, unlinked inode
//! (`OwnedCopy`) that the verifier reads, so a writer of the source can no longer change what was verified.
#[cfg(test)]
use super::{EXPERT_BLOB, MtpExpertMatrix, MtpKind, read_exact_range, read_expert_rows};
@@ -1,5 +1,5 @@
//! Functions: `read_expert_rows`, `read_expert_row`, `row_range`, `allocate` and 3 more.
//! Split out of `mtp` to keep its files under the line limit.
//! Reads the rows of one MTP expert matrix from the pinned pack: range arithmetic, positional reads on the frozen copy,
//! the interleave of the Q2 codes and scales, and the finiteness check of what was read.
#[cfg(not(target_os = "linux"))]
use super::backing;
@@ -1,5 +1,5 @@
//! Methods of `InheritedKarArchive`: `open`, `open_sparse`, `open_sparse`, `sparse_extents` and 7 more.
//! Functions: `open_sealed_archive_fd`, `open_read_only_archive`, `check_read_only_archive`, `reopen_read_only_archi...
//! The KAR PLE archive handed down by the parent process: a sealed memfd, a sparse extent map or an ordinary read-only
//! file. Opening it checks the kind, length, links, owner and permission bits; readers are independent reopens of it.
use super::{
ARCHIVE_DIGEST, File, InheritedKarArchive, InputBindingError, InputResult, PINNED_ARCHIVE_BYTES, PROVENANCE_DIGEST,
@@ -1,5 +1,5 @@
//! Methods of `KarRowPacket`: `payload`, `partition`. Methods of `KarRowReader`: `read_rows`.
//! Functions: `open_archive_reader`, `load_pinned_inherited_archive`, `log_startup_read`, `load_pinned_inherited_arc...
//! Loads the verified PLE artifact from the inherited archive: the read handle, the startup log line of what was read,
//! and the row packets and readers the PLE cache takes its rows from. Windows keeps only the file-backed form.
use super::{
BindingIdentity, File, InheritedKarArchive, InputBindingError, InputResult, KarError, KarPleBinding, KarRowPacket,
@@ -1,5 +1,5 @@
//! Methods of `InheritedKarArchive`: `expert_capture_observation`.
//! Functions: `pinned_profile`, `pinned_parts`, `pinned_profile_spec`, `load_pinned_archive` and 3 more.
//! The pinned KAR PLE profile: the conversion receipts it expects, the partition of the rows, and the verification of
//! the archive against them. Linux freezes a private inode before inspection; other platforms refuse the path form.
use super::{
ARCHIVE_DIGEST, File, InheritedKarArchive, InputBindingError, InputResult, KarPlePartProvenance, KarPleProfile,
@@ -1,5 +1,5 @@
//! Implements `Write for BrokenSink`.
//! Functions: `diagnostic_cases`, `assert_kar_diagnostic_redacts`, `assert_input_diagnostic_survives_broken_sink`, `...
//! Pins the PLE profile: its numbers match the independent conversion receipts, the partitions cover the rows exactly,
//! and load diagnostics redact their causes yet keep the typed failure even when the diagnostic sink is broken.
use super::{
InputBindingError, KarError, LoadPhase, NATIVE_DIGESTS, PLE_ROWS, error, input_diagnostic, kar_diagnostic,
@@ -1,5 +1,5 @@
//! Defines `Inode`, `IoPhase`, `OwnedCopy`.
//! Split out of `qwen4exp_kar_ple` to keep its files under the line limit.
//! Types of the private copy: the inode identity, the I/O phase a failure is reported against, and `OwnedCopy`, the
//! handle that removes its file when dropped. The operations are in `inode` and `checked_reader`.
use super::{InputBindingError, InputResult, LoadPhase, input_failure};
#[cfg(target_os = "linux")]
@@ -1,5 +1,5 @@
//! Functions: `checked_reader`, `copy_exact`, `copy_exact_reporting`, `copy_buffer` and 1 more.
//! Split out of `private_copy` to keep its files under the line limit.
//! Reading side of the private copy: a checked reader over the frozen inode and `copy_exact`, which copies exactly the
//! pinned byte count and refuses a source that holds more.
use super::{COPY_BUFFER, InputBindingError, InputResult, IoPhase, LoadPhase, Read, Write, input_failure, report_io};
#[cfg(not(target_os = "linux"))]
@@ -1,5 +1,5 @@
//! Methods of `OwnedCopy`: `create`, `created`, `writer`, `detach` and 2 more. Implements `Drop for OwnedCopy`.
//! Functions: `inode`, `diagnostic`, `report_io`, `phase_error` and 8 more.
//! The private copy of a source file as an owned inode: create, write, seal, reopen read-only and detach, with the
//! checks that the sealed inode is the one this owner created and that no name refers to it any more.
use super::{
File, Inode, InputBindingError, InputResult, IoPhase, LoadPhase, Metadata, MetadataExt, OpenOptions,
@@ -1,5 +1,5 @@
//! Functions: `io_error`, `open_regular`, `open_read_only_archive`, `check_len` and 3 more.
//! Split out of `qwen4exp_kar_ple` to keep its files under the line limit.
//! Windows form of the inherited archive: a regular file opened with a sharing mode that keeps writers out, a length
//! check, independent positional reopens and the provenance digest check.
use super::{InputBindingError, InputResult};
use std::{
@@ -126,7 +126,7 @@ pub(in crate::qwen_forward) struct NoPromptHooks;
/// [`PromptPlan`](crate::backend::original_prompt::PromptPlan) is walked by `drive`; every `Batched` action is one
/// real `OriginalPromptExecutor::forward` + `publish` transaction on the shared arena/session/draft, so the chunk loop
/// of `Prefill::run` is the action sequence. This is an unselected source owner: nothing in `backend` constructs it.
pub(in crate::qwen_forward) struct OriginalPromptComposer<'a, 'arena, 'ctx> {
pub(in crate::qwen_forward) struct OriginalPromptComposer<'a, 'arena, 'ctx, C: FnMut() -> bool, H: OriginalPromptHooks + ?Sized> {
pub executor: &'a mut OriginalPromptExecutor<'ctx>,
pub binding: &'a ModelBinding,
pub dense: &'a DenseWeightCache<'ctx>,
@@ -139,8 +139,8 @@ pub(in crate::qwen_forward) struct OriginalPromptComposer<'a, 'arena, 'ctx> {
pub embedding: &'a OriginalPromptEmbedding<'ctx>,
pub policy: &'a OriginalMtpScalarPolicy,
/// `should_stop` of the Original; also forwarded into every chunk's draft-KV recording.
pub cancel: &'a mut dyn FnMut() -> bool,
pub hooks: &'a mut dyn OriginalPromptHooks,
pub cancel: &'a mut C,
pub hooks: &'a mut H,
/// The last chunk's publication (new origin and the known-next sample), for the caller's first decode window.
pub last_published: Option<(TargetStepOrigin, Option<TokenId>)>,
}
@@ -41,7 +41,9 @@ impl Drop for OriginalPromptPending<'_, '_, '_> {
}
}
impl OriginalPromptHooks for NoPromptHooks {}
impl crate::backend::original_prompt::PromptRunner for OriginalPromptComposer<'_, '_, '_> {
impl<C: FnMut() -> bool, H: OriginalPromptHooks + ?Sized> crate::backend::original_prompt::PromptRunner
for OriginalPromptComposer<'_, '_, '_, C, H>
{
type Error = Error;
fn cancelled(&mut self) -> bool {
(self.cancel)()
@@ -75,10 +77,10 @@ impl crate::backend::original_prompt::PromptRunner for OriginalPromptComposer<'_
}
/// Runs `plan` to its final seed through `composer`. `admitted_capacity` is the capacity the executor, arena and cache
/// were built for. Cancellation maps to the same refusal `forward` returns when its draft recording is cancelled.
pub(in crate::qwen_forward) fn run_original_prompt(
pub(in crate::qwen_forward) fn run_original_prompt<C: FnMut() -> bool, H: OriginalPromptHooks + ?Sized>(
plan: crate::backend::original_prompt::PromptPlan<'_>,
admitted_capacity: usize,
composer: &mut OriginalPromptComposer<'_, '_, '_>,
composer: &mut OriginalPromptComposer<'_, '_, '_, C, H>,
) -> Result<crate::backend::original_prompt::DriveSummary> {
use crate::backend::original_prompt::{DriveError, drive};
drive(plan, admitted_capacity, composer).map_err(|e| match e {
@@ -1,4 +1,4 @@
//! Numerical transport proof of the MTP verification journal (test-only; moved out of the parent file by STRA-338).
//! Numerical transport proof of the MTP verification journal (test-only).
use super::{
COUNTS, CandidatePair, Context, DeviceBuffer, Error, GdnStateFiniteGuard, Result, STATE_ELEMENTS, VALUES,
VerifiedRowBuffers, allocate, compute_row, download, driver_error, upload,
@@ -1,5 +1,4 @@
//! Admission checks and the scratch lease of the retained attention -> FFN handoff (moved out of the parent file by
//! STRA-338).
//! Admission checks and the scratch lease of the retained attention -> FFN handoff.
use super::{
Cell, Context, DenseWeightCache, DetachedGrRead, Error, GrPhase, GrRole, GrScratch, InjectedResidual, ModelBinding,
@@ -1,4 +1,4 @@
//! The adaptive wave: resident GPU groups beside owned CPU miss batches (STRA-338 size: extract-method only).
//! The adaptive wave: resident GPU groups beside owned CPU miss batches.
use super::{
ActualDown, ChunkFfnRow, Context, DownOrigin, DownScope, Error, ExpertGroup, K, ModelBinding, MoeWeightCache, Pair,
@@ -1,4 +1,4 @@
//! Expert-group plan of one adaptive packet wave (STRA-338 size: extract-method only).
//! Expert-group plan of one adaptive packet wave.
use super::super::direct_packets_fns::PacketRun;
use super::packet_wave::PacketWave;
@@ -1,4 +1,4 @@
//! GPU queue and CPU miss batches of one adaptive packet wave (STRA-338 size: extract-method only).
//! GPU queue and CPU miss batches of one adaptive packet wave.
use super::super::adaptive::{miss_batch_end, prepare_cpu_jobs, source_keys};
use super::super::packet_run_project_group_direct::DirectRun;
@@ -1,4 +1,4 @@
//! The uploaded rows of one chunk and their ungrouped/grouped execution (STRA-338 size: extract-method only).
//! The uploaded rows of one chunk and their ungrouped/grouped execution.
#[cfg(all(test, target_arch = "x86_64"))]
use super::direct_gpu;
@@ -1,4 +1,4 @@
//! Phases of the direct-packet layer batch (STRA-338 size: extract-method only).
//! Phases of the direct-packet layer batch.
#[cfg(all(test, target_arch = "x86_64"))]
use super::direct_gpu;
@@ -1,4 +1,4 @@
//! Helpers shared by the resident, direct and source Down groups (STRA-338 size: extract-method only).
//! Helpers shared by the resident, direct and source Down groups.
use super::{
ActualSlotPacket, CachedMoeMatrix, ChunkFfnRow, Context, DeviceBuffer, DownColumns, DownScope, DriverError, Error,
@@ -1,4 +1,4 @@
//! Support and descriptor admission of one MMQ chunk (STRA-338 size: extract-method only).
//! Support and descriptor admission of one MMQ chunk.
use super::{
ChunkFfnRow, Error, K, LayerId, ModelBinding, MoeExpertSelection, MoeMatrixKind, MoeMatrixRole, QwenChunkTxn,
@@ -1,4 +1,4 @@
//! Gather of one expert's matrices into the admitted bank (STRA-338 size: extract-method only).
//! Gather of one expert's matrices into the admitted bank.
use super::layer_walk::{ExpertGroup, Walk, WalkOwners};
use super::{
@@ -1,4 +1,4 @@
//! The adaptive prompt layer walk over staged and resident experts (STRA-338 size: extract-method only).
//! The adaptive prompt layer walk over staged and resident experts.
use super::{
ChunkFfnRow, Context, DeviceBuffer, Error, LayerId, ModelBinding, MoeExpertSelection, MoeMatrixRole,
@@ -1,4 +1,4 @@
//! The resident MMQ chunk execution (STRA-338 size: extract-method only).
//! The resident MMQ chunk execution.
use super::{
BoundExpert, Cell, ChunkFfnRow, Context, DEVICE_PEAK, DeviceBuffer, DownScope, Error, ExpertReady, K, LayerId,
@@ -1,4 +1,4 @@
//! Validation and device phases of `MoePrefillStage::route_shared_micro` (STRA-338 size: extract-method only).
//! Validation and device phases of `MoePrefillStage::route_shared_micro`.
use super::{
Buffers, CombineInput, DeviceBuffer, Dimension, EXPERTS, Error, GdnNativeFormat, GemmRef, GrRole, LayerId, MIXED,
@@ -1,4 +1,4 @@
//! One original-prompt MoE layer: expert spans, copy ring and finish (STRA-338 size: extract-method only).
//! One original-prompt MoE layer: expert spans, copy ring and finish.
use super::{
Context, DenseWeightCache, DeviceBuffer, Error, GdnNativeFormat, LayerId, ModelBinding, MoeExpertWeights,
@@ -93,14 +93,14 @@ pub(in crate::qwen_forward) trait RequestOwners {
&mut self,
request: &ServeRequest,
resume: usize,
cancel: &mut dyn FnMut() -> bool,
cancel: &mut impl 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,
emit: &mut impl FnMut(&[i32]) -> Result<(), Error>,
cancel: &mut impl FnMut() -> bool,
) -> Result<ServeOutcome, SpecError>;
/// The request that `resume` placed is over (`Ok`, or how it ended); the conversation bookkeeping for the
/// next one.
@@ -186,8 +186,8 @@ 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,
emit: &mut impl FnMut(&[i32]) -> Result<(), Error>,
cancel: &mut impl FnMut() -> bool,
) -> Result<ServeOutcome, ServeError> {
// sized closures over the caller's trait objects: the core is generic, so no trait object is added to the lifecycle
let mut emit = |tokens: &[i32]| emit(tokens);
@@ -57,7 +57,7 @@ impl RequestOwners for Fake {
self.fresh = false;
Some(resume)
}
fn prefill(&mut self, _: &ServeRequest, resume: usize, cancel: &mut dyn FnMut() -> bool) -> Result<(), SpecError> {
fn prefill(&mut self, _: &ServeRequest, resume: usize, cancel: &mut impl FnMut() -> bool) -> Result<(), SpecError> {
self.log.push("prefill");
self.prefilled_from = Some(resume);
self.fresh = false;
@@ -72,8 +72,8 @@ impl RequestOwners for Fake {
fn decode(
&mut self,
request: &ServeRequest,
emit: &mut dyn FnMut(&[i32]) -> Result<(), Error>,
_: &mut dyn FnMut() -> bool,
emit: &mut impl FnMut(&[i32]) -> Result<(), Error>,
_: &mut impl FnMut() -> bool,
) -> Result<ServeOutcome, SpecError> {
self.log.push("decode");
if let Some(error) = self.decode {
@@ -140,7 +140,7 @@ pub(super) fn pin_resident_complement(
let room = crate::memory_governor::complement_room(available);
let budget = ((budget_gib * GIB) as u64).min(room);
let ranked = ranked_complement(cache, profile);
let started = std::time::Instant::now();
let started = leleka_obs::time::Clock::now(&leleka_obs::time::SystemClock);
match bank.pin_resident(&ranked, budget) {
Ok((held, bytes)) => eprintln!(
"leleka-serve: resident RAM budget {:.2} GiB (asked {budget_gib:.2}, {:.2} GiB available): \
@@ -141,7 +141,7 @@ impl FakeStack {
&mut self,
request: &ServeRequest,
resume: usize,
cancel: &mut dyn FnMut() -> bool,
cancel: &mut impl FnMut() -> bool,
) -> Result<(), SpecError> {
let n = request.prompt.len();
if n < 2 {
@@ -178,7 +178,7 @@ impl FakeStack {
&mut self,
prompt: &[i32],
action: &PromptAction,
cancel: &mut dyn FnMut() -> bool,
cancel: &mut impl FnMut() -> bool,
) -> Result<(), SpecError> {
let PromptPath::Batched { .. } = action.path else {
return Err(Error::IdentityMismatch.into());
@@ -216,8 +216,8 @@ impl FakeStack {
fn serve_rounds(
&mut self,
request: &ServeRequest,
emit: &mut dyn FnMut(&[i32]) -> Result<(), Error>,
cancel: &mut dyn FnMut() -> bool,
emit: &mut impl FnMut(&[i32]) -> Result<(), Error>,
cancel: &mut impl FnMut() -> bool,
) -> Result<ServeOutcome, SpecError> {
self.dev.begin_decode(&request.prompt)?;
if self.controller.is_failed() {
@@ -241,8 +241,8 @@ impl FakeStack {
fn decode_over_graphs(
&mut self,
request: &ServeRequest,
emit: &mut dyn FnMut(&[i32]) -> Result<(), Error>,
cancel: &mut dyn FnMut() -> bool,
emit: &mut impl FnMut(&[i32]) -> Result<(), Error>,
cancel: &mut impl FnMut() -> bool,
) -> Result<ServeOutcome, SpecError> {
let (key, seed) = (self.graph_key, self.dev.digest());
let owners = self.owners.take().ok_or(Error::IdentityMismatch)?;
@@ -301,7 +301,7 @@ impl RequestOwners for FakeStack {
&mut self,
request: &ServeRequest,
resume: usize,
cancel: &mut dyn FnMut() -> bool,
cancel: &mut impl FnMut() -> bool,
) -> Result<(), SpecError> {
let started = self.clock.now();
self.timing = (0.0, 0.0);
@@ -315,8 +315,8 @@ impl RequestOwners for FakeStack {
fn decode(
&mut self,
request: &ServeRequest,
emit: &mut dyn FnMut(&[i32]) -> Result<(), Error>,
cancel: &mut dyn FnMut() -> bool,
emit: &mut impl FnMut(&[i32]) -> Result<(), Error>,
cancel: &mut impl FnMut() -> bool,
) -> Result<ServeOutcome, SpecError> {
let started = self.clock.now();
let result = self.decode_over_graphs(request, emit, cancel);
@@ -128,7 +128,7 @@ impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> {
&mut self,
request: &ServeRequest,
resume: usize,
cancel: &mut dyn FnMut() -> bool,
cancel: &mut impl FnMut() -> bool,
) -> std::result::Result<(), SpecError> {
let started = self.config.clock.now();
self.state.timing = (0.0, 0.0);
@@ -144,8 +144,8 @@ impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> {
fn decode(
&mut self,
request: &ServeRequest,
emit: &mut dyn FnMut(&[i32]) -> Result<()>,
cancel: &mut dyn FnMut() -> bool,
emit: &mut impl FnMut(&[i32]) -> Result<()>,
cancel: &mut impl FnMut() -> bool,
) -> std::result::Result<ServeOutcome, SpecError> {
let started = self.config.clock.now();
let tier0 = self.tier.residency.stats;
@@ -22,8 +22,8 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
pub(in super::super) fn decode_phase(
&mut self,
request: &ServeRequest,
emit: &mut dyn FnMut(&[i32]) -> Result<()>,
cancel: &mut dyn FnMut() -> bool,
emit: &mut impl FnMut(&[i32]) -> Result<()>,
cancel: &mut impl FnMut() -> bool,
) -> std::result::Result<ServeOutcome, SpecError> {
let (sampling, staged) = self.decode_stage(request)?;
let mut view = self.decode_view(&staged.shared);
@@ -33,8 +33,8 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
pub(crate) fn serve(
&mut self,
request: &ServeRequest,
emit: &mut dyn FnMut(&[i32]) -> Result<()>,
cancel: &mut dyn FnMut() -> bool,
emit: &mut impl FnMut(&[i32]) -> Result<()>,
cancel: &mut impl FnMut() -> bool,
) -> std::result::Result<ServeOutcome, ServeError> {
self.apply_memory_directive();
self.state.marks = TtftMarks::start(&self.config.clock);
@@ -15,7 +15,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
&mut self,
source: &Rc<OriginalPromptInput>,
count: usize,
cancel: &mut dyn FnMut() -> bool,
cancel: &mut impl FnMut() -> bool,
) -> std::result::Result<(), SpecError> {
let mut chunk = PromptChunk {
binding: self.binding,
@@ -20,7 +20,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
&mut self,
request: &ServeRequest,
resume: usize,
cancel: &mut dyn FnMut() -> bool,
cancel: &mut impl FnMut() -> bool,
) -> std::result::Result<(), SpecError> {
let seeding = self.begin_prefill()?;
let p = profile::span("prefill.read");
@@ -162,7 +162,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
&mut self,
request: &ServeRequest,
resume: usize,
cancel: &mut dyn FnMut() -> bool,
cancel: &mut impl FnMut() -> bool,
) -> std::result::Result<(), SpecError> {
let binding: &ModelBinding = self.binding;
let n = request.prompt.len();
@@ -255,7 +255,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
request: &ServeRequest,
source: &Rc<OriginalPromptInput>,
action: crate::backend::original_prompt::PromptAction,
cancel: &mut dyn FnMut() -> bool,
cancel: &mut impl FnMut() -> bool,
) -> std::result::Result<std::ops::ControlFlow<()>, SpecError> {
trace_action(&action);
if action.path == PromptPath::FinalSeed {
@@ -12,7 +12,7 @@ impl<'ctx> PromptChunk<'_, 'ctx> {
&mut self,
count: usize,
arena: &mut OriginalPrefillArena<'_, 'ctx>,
cancel: &mut dyn FnMut() -> bool,
cancel: &mut impl FnMut() -> bool,
) -> std::result::Result<(), SpecError> {
let target = PromptChunkTarget {
weights: PromptWeights::new(self.binding, self.dense),
@@ -31,7 +31,7 @@ impl<'ctx> PromptChunk<'_, 'ctx> {
}
}
/// The forward's result: a failure after a cancel request is the cancel, any other is the forward's own error.
fn forward_outcome<P>(pending: Result<P>, cancel: &mut dyn FnMut() -> bool) -> std::result::Result<P, SpecError> {
fn forward_outcome<P>(pending: Result<P>, cancel: &mut impl FnMut() -> bool) -> std::result::Result<P, SpecError> {
if let Err(e) = &pending {
crate::bringup_trace!("DBG[{:.0}s] executor.forward err {e:?}", dbg_el());
}