diff --git a/architecture-baseline.json b/architecture-baseline.json index 70adb3d2..1ec22606 100644 --- a/architecture-baseline.json +++ b/architecture-baseline.json @@ -5,8 +5,6 @@ "source": { "allow-unused-imports:leleka-cpu-sys": 35, "allow-unused-imports:leleka-cuda-driver": 410, - "allow-unused-imports:leleka-engine-core": 18, - "allow-unused-imports:leleka-engine-qwen35-cuda": 166, "allow-unused-imports:leleka-experimental-ref": 1, "allow-unused-imports:leleka-harmony": 2, "allow-unused-imports:leleka-igpu": 2, @@ -47,7 +45,6 @@ "env-read:leleka-tokenizer": 2, "env-read:strata-control": 3, "glob-super-import:leleka-cuda-driver": 3, - "glob-super-import:leleka-engine-qwen35-cuda": 70, "instant-now:leleka-cpu-worker": 9, "instant-now:leleka-cuda-driver": 25, "instant-now:leleka-engine-qwen35-cuda": 16, diff --git a/crates/engine-core/src/conversation/cache.rs b/crates/engine-core/src/conversation/cache.rs index fc713640..14df98fa 100644 --- a/crates/engine-core/src/conversation/cache.rs +++ b/crates/engine-core/src/conversation/cache.rs @@ -120,8 +120,6 @@ pub struct ConversationCache { mod tests; mod conversation_checkpoint; -#[allow(unused_imports)] pub use conversation_checkpoint::conversation_prefix; -#[allow(unused_imports)] pub use conversation_checkpoint::prefix_len; mod conversation_cache; diff --git a/crates/engine-core/src/conversation/kv.rs b/crates/engine-core/src/conversation/kv.rs index 45b44a82..5b2522b9 100644 --- a/crates/engine-core/src/conversation/kv.rs +++ b/crates/engine-core/src/conversation/kv.rs @@ -45,29 +45,15 @@ struct Verifier<'a> { } mod layout; -#[allow(unused_imports)] pub use layout::kv_bytes; -#[allow(unused_imports)] pub use layout::kv_capture_bytes; -#[allow(unused_imports)] -use layout::kv_q4_bytes_per_head; -#[allow(unused_imports)] use layout::layout; -#[allow(unused_imports)] use layout::region; -#[allow(unused_imports)] use layout::transfer_err; -#[allow(unused_imports)] use layout::valid; -#[allow(unused_imports)] -use layout::valid_extent; mod kv_image_save_restore; -#[allow(unused_imports)] pub use kv_image_save_restore::kv_restore; -#[allow(unused_imports)] pub use kv_image_save_restore::kv_save; -#[allow(unused_imports)] pub use kv_image_save_restore::kv_validate; mod kv_image_readback; -#[allow(unused_imports)] pub use kv_image_readback::kv_verify; diff --git a/crates/engine-core/src/conversation/manager.rs b/crates/engine-core/src/conversation/manager.rs index 70a11c90..d5da37e4 100644 --- a/crates/engine-core/src/conversation/manager.rs +++ b/crates/engine-core/src/conversation/manager.rs @@ -113,10 +113,7 @@ pub struct ConversationManager { } mod conversation_options_default; -#[allow(unused_imports)] pub use conversation_options_default::images_below; -#[allow(unused_imports)] use conversation_options_default::is_allocation; -#[allow(unused_imports)] pub use conversation_options_default::starts_with; mod conversation_manager; diff --git a/crates/engine-core/src/conversation/manager_tests.rs b/crates/engine-core/src/conversation/manager_tests.rs index 8a5968f2..7db74a4a 100644 --- a/crates/engine-core/src/conversation/manager_tests.rs +++ b/crates/engine-core/src/conversation/manager_tests.rs @@ -61,24 +61,10 @@ mod continuing_chat_reuses; mod random_traffic_resumes_into_exact_prefix_state; mod hash; -#[allow(unused_imports)] -use hash::hash; -#[allow(unused_imports)] use hash::idx; -#[allow(unused_imports)] -use hash::pat; -#[allow(unused_imports)] -use hash::pattern; mod sim_device_session_device; -#[allow(unused_imports)] use sim_device_session_device::ReplayedRequest; -#[allow(unused_imports)] use sim_device_session_device::chat; -#[allow(unused_imports)] use sim_device_session_device::gen_tokens; -#[allow(unused_imports)] use sim_device_session_device::options; -#[allow(unused_imports)] -use sim_device_session_device::prompt_options; -#[allow(unused_imports)] use sim_device_session_device::world; diff --git a/crates/engine-core/src/conversation/snapshot_tests.rs b/crates/engine-core/src/conversation/snapshot_tests.rs index ea1811bb..dd77699a 100644 --- a/crates/engine-core/src/conversation/snapshot_tests.rs +++ b/crates/engine-core/src/conversation/snapshot_tests.rs @@ -57,34 +57,18 @@ struct Pools { mod layer_snapshots_are_byte_exact; mod kv_region; -#[allow(unused_imports)] use kv_region::equal; -#[allow(unused_imports)] pub(super) use kv_region::kv_region; -#[allow(unused_imports)] use kv_region::mk_view; -#[allow(unused_imports)] use kv_region::q4_per_head; mod kv_level; -#[allow(unused_imports)] use kv_level::kv_level; mod full_session; -#[allow(unused_imports)] use full_session::full_session; mod fixture; mod pools; -#[allow(unused_imports)] use fixture::fixture; mod golden_state; -#[allow(unused_imports)] -use golden_state::assert_checkpoint; -#[allow(unused_imports)] use golden_state::assert_image; -#[allow(unused_imports)] use golden_state::assert_kv; -#[allow(unused_imports)] -use golden_state::fnv; -#[allow(unused_imports)] -use golden_state::fnv_buf; -#[allow(unused_imports)] use golden_state::golden_state; diff --git a/crates/engine-core/src/prefix_cache/store.rs b/crates/engine-core/src/prefix_cache/store.rs index 7a09fb52..b895c66f 100644 --- a/crates/engine-core/src/prefix_cache/store.rs +++ b/crates/engine-core/src/prefix_cache/store.rs @@ -201,5 +201,4 @@ mod tests; mod decayed; mod policy_params_default; mod prefix_store; -#[allow(unused_imports)] use decayed::decayed; diff --git a/crates/engine-core/src/prefix_cache/store/decayed.rs b/crates/engine-core/src/prefix_cache/store/decayed.rs index ac306720..3b0bf7b9 100644 --- a/crates/engine-core/src/prefix_cache/store/decayed.rs +++ b/crates/engine-core/src/prefix_cache/store/decayed.rs @@ -1,6 +1,5 @@ //! Half-life decay of a hit mass or prior with age, shared by the store's value estimate. - pub(super) fn decayed(value: f64, age: u64, half_life: f64) -> f64 { if value == 0.0 { 0.0 } else { value * 0.5f64.powf(age as f64 / half_life) } } diff --git a/crates/engine-core/src/prefix_cache/store/prefix_store/prefix_store_evict_and_budget.rs b/crates/engine-core/src/prefix_cache/store/prefix_store/prefix_store_evict_and_budget.rs index 8cd67ed9..5bc56679 100644 --- a/crates/engine-core/src/prefix_cache/store/prefix_store/prefix_store_evict_and_budget.rs +++ b/crates/engine-core/src/prefix_cache/store/prefix_store/prefix_store_evict_and_budget.rs @@ -1,9 +1,9 @@ //! Removal from the prefix store: enforcing the byte budget, aborting a candidate, evicting a node together with the //! blocks only it covered, orphan release, clearing, and the invariant check. -use super::{ByteSize, Candidate, HashSet, Node, PrefixStore}; #[cfg(any(test, feature = "testing"))] use super::HashMap; +use super::{ByteSize, Candidate, HashSet, Node, PrefixStore}; impl PrefixStore { pub(in super::super) fn enforce_budget(&mut self, fresh: u64) { diff --git a/crates/engine-core/src/prompt.rs b/crates/engine-core/src/prompt.rs index 25ad9e49..8c291099 100644 --- a/crates/engine-core/src/prompt.rs +++ b/crates/engine-core/src/prompt.rs @@ -139,9 +139,6 @@ mod grid_tests; #[path = "prompt/prompt_options.rs"] mod prompt_options; -#[allow(unused_imports)] pub use prompt_options::choose_auto_capacity; -#[allow(unused_imports)] pub use prompt_options::drive; -#[allow(unused_imports)] pub use prompt_options::request_capacity; diff --git a/crates/engine-core/src/spec/adaptive.rs b/crates/engine-core/src/spec/adaptive.rs index 09209276..f41220cb 100644 --- a/crates/engine-core/src/spec/adaptive.rs +++ b/crates/engine-core/src/spec/adaptive.rs @@ -192,13 +192,9 @@ pub struct SpecStats { mod tests; mod adaptive_config; -#[allow(unused_imports)] use adaptive_config::logit; -#[allow(unused_imports)] use adaptive_config::m_bucket; -#[allow(unused_imports)] use adaptive_config::p_bucket; -#[allow(unused_imports)] use adaptive_config::sigmoid; mod adaptive_policy; mod decide; diff --git a/crates/engine-qwen35-cuda/src/backend/combined_changed_boundary_proof.rs b/crates/engine-qwen35-cuda/src/backend/combined_changed_boundary_proof.rs index b9ca28c8..5edc3b16 100644 --- a/crates/engine-qwen35-cuda/src/backend/combined_changed_boundary_proof.rs +++ b/crates/engine-qwen35-cuda/src/backend/combined_changed_boundary_proof.rs @@ -1,10 +1,10 @@ //! Private sole new changed-path model gate; actual source identity/load preserved. +#[cfg(feature = "preview-path")] +use super::{DenseWeightCache, KarPleCache, MoeWeightCache, OutputStage, QwenForward, QwenSession}; use super::{ Driver, EvaluationExecution, InheritedKarArchive, ModelBinding, PathBuf, Qwen4ExpArtifact, Rc, SHARD0, SHARD1, Tokenizer, VerifiedGgufFile, }; -#[cfg(feature = "preview-path")] -use super::{DenseWeightCache, KarPleCache, MoeWeightCache, OutputStage, QwenForward, QwenSession}; use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners as LoadedTarget; use std::env; pub(super) mod rig; diff --git a/crates/engine-qwen35-cuda/src/backend/combined_changed_boundary_proof/rig.rs b/crates/engine-qwen35-cuda/src/backend/combined_changed_boundary_proof/rig.rs index e09f59d2..3126edcd 100644 --- a/crates/engine-qwen35-cuda/src/backend/combined_changed_boundary_proof/rig.rs +++ b/crates/engine-qwen35-cuda/src/backend/combined_changed_boundary_proof/rig.rs @@ -1,11 +1,11 @@ //! The loaded real owners the single-load GPU proofs share: the pinned binding over the inherited sealed archive, //! the device owners built on one bounded Context, a phase run on a fresh target owner, and the teardown whose //! results are asserted only after every attempt was made. Opening and scheduling stay with each proof. +#[cfg(feature = "preview-path")] +use super::{DenseWeightCache, KarPleCache, MoeWeightCache, OutputStage, QwenSession}; use super::{ InheritedKarArchive, ModelBinding, PathBuf, Qwen4ExpArtifact, Rc, SHARD0, SHARD1, Tokenizer, VerifiedGgufFile, }; -#[cfg(feature = "preview-path")] -use super::{DenseWeightCache, KarPleCache, MoeWeightCache, OutputStage, QwenSession}; use std::{ env, panic::{AssertUnwindSafe, catch_unwind}, diff --git a/crates/engine-qwen35-cuda/src/backend/native_down_public_pair.rs b/crates/engine-qwen35-cuda/src/backend/native_down_public_pair.rs index 94be2c58..07f0b859 100644 --- a/crates/engine-qwen35-cuda/src/backend/native_down_public_pair.rs +++ b/crates/engine-qwen35-cuda/src/backend/native_down_public_pair.rs @@ -1,4 +1,6 @@ //! One-load private PUBLIC generation pair; actual owner timings, never HTTP timings. +#[cfg(test)] +use super::prepare_prompt; use super::{ AtomicBool, CacheCounts, Digest, Driver, Duration, EvaluationExecution, EvaluationMeasurement, FRAME_LIMIT, FinishReason, Generation, GenerationEvent, GenerationFailure, GenerationRequest, GenerationSink, GenerationStream, @@ -8,8 +10,6 @@ use super::{ }; #[cfg(feature = "preview-path")] use super::{DenseWeightCache, KarPleCache, MoeWeightCache, OutputStage, QwenSession}; -#[cfg(test)] -use super::prepare_prompt; use serde_json::{Value, json}; use std::{ env, diff --git a/crates/engine-qwen35-cuda/src/backend/native_down_public_pair/long_public_preflight.rs b/crates/engine-qwen35-cuda/src/backend/native_down_public_pair/long_public_preflight.rs index eb3e3e64..9d28f1a3 100644 --- a/crates/engine-qwen35-cuda/src/backend/native_down_public_pair/long_public_preflight.rs +++ b/crates/engine-qwen35-cuda/src/backend/native_down_public_pair/long_public_preflight.rs @@ -1,5 +1,6 @@ //! Offline/private producer; call with the actual already-bound model tokenizer. //! No asset opening, model hash scan, GPU allocation or inference occurs here. +use leleka_gateway_text::prompt as public_renderer; use leleka_tokenizer::Tokenizer; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; @@ -9,7 +10,6 @@ use std::{ os::unix::fs::OpenOptionsExt, path::Path, }; -use leleka_gateway_text::prompt as public_renderer; const BYTE_CAP: usize = 1024 * 1024; const ARTIFACT_CAP: usize = 16 * 1024 * 1024; const CONTEXT: usize = 262144; diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve/runner/owner_run_steps.rs b/crates/engine-qwen35-cuda/src/backend/original_serve/runner/owner_run_steps.rs index f740d369..e95d15bd 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve/runner/owner_run_steps.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve/runner/owner_run_steps.rs @@ -2,11 +2,11 @@ //! sweep idle sessions and close everything; early exits stay in `run`. use super::{ - QUEUE, ActiveGuard, AtomicBool, BackendError, ClientLink, DeferredTail, ErrorCode, GenerationFailure, - GenerationRequest, GenerationSink, GenerationTerminal, IdleSweep, LoadedModel, LoadPhase, ModelBinding, Ordering, - OriginalServeOptions, OriginalServeStack, PathBuf, Rc, Reply, RequestToServe, Shared, SystemClock, Tokenizer, - TokenVocabulary, context_fits, emit_terminal, exhausted, generate, invalid, load_failure, meta_facts, open_error, - prepare_prompt, publish_prefix_summary, stack_config, unavailable, + ActiveGuard, AtomicBool, BackendError, ClientLink, DeferredTail, ErrorCode, GenerationFailure, GenerationRequest, + GenerationSink, GenerationTerminal, IdleSweep, LoadPhase, LoadedModel, ModelBinding, Ordering, + OriginalServeOptions, OriginalServeStack, PathBuf, QUEUE, Rc, Reply, RequestToServe, Shared, SystemClock, + TokenVocabulary, Tokenizer, context_fits, emit_terminal, exhausted, generate, invalid, load_failure, meta_facts, + open_error, prepare_prompt, publish_prefix_summary, stack_config, unavailable, }; use leleka_backend_api::GenerationStream; use leleka_cuda_driver::Context; diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_laptop.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_laptop.rs index 3b521e32..5edc97f3 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_laptop.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_laptop.rs @@ -27,7 +27,9 @@ //! //! Run: `cargo test -p leleka-engine-qwen35-cuda --features cuda-driver[,sm86] --release -- --ignored --nocapture //! original_serve_laptop_bench`. -use super::{Driver, InheritedKarArchive, ModelBinding, PathBuf, Qwen4ExpArtifact, Rc, SHARD0, SHARD1, VerifiedGgufFile}; +use super::{ + Driver, InheritedKarArchive, ModelBinding, PathBuf, Qwen4ExpArtifact, Rc, SHARD0, SHARD1, VerifiedGgufFile, +}; use crate::qwen_forward::{ original_serve_engine::ServeOutcome, original_serve_request::{ServeError, ServeRequest}, diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_replay.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_replay.rs index 42ab06d4..0d5f3300 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_replay.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_replay.rs @@ -30,7 +30,9 @@ //! //! Run (inside a holder job): ` --ignored --nocapture original_serve_replay_smoke`. use super::super::qwen_forward::original_serve_stack::dbg_el; -use super::{Driver, InheritedKarArchive, ModelBinding, PathBuf, Qwen4ExpArtifact, Rc, SHARD0, SHARD1, VerifiedGgufFile}; +use super::{ + Driver, InheritedKarArchive, ModelBinding, PathBuf, Qwen4ExpArtifact, Rc, SHARD0, SHARD1, VerifiedGgufFile, +}; use crate::qwen_forward::{ original_serve_request::{ServeError, ServeRequest}, original_serve_stack::{OriginalServeStack, PrefixBudget, PrefixConfig, StackConfig}, diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_smoke.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_smoke.rs index 1db20934..49346a98 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_smoke.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_smoke.rs @@ -25,12 +25,12 @@ //! While the verifier window producers listed in `UNBOUND_PRODUCERS` are unbound the stack refuses to open //! with the first missing producer's name; that refusal is the expected result of this smoke until they land. use super::super::qwen_forward::original_serve_stack::dbg_el; +#[cfg(all(test, target_arch = "x86_64"))] +use super::original_serve_arms; use super::{ Driver, InheritedKarArchive, ModelBinding, PathBuf, Qwen4ExpArtifact, Rc, SHARD0, SHARD1, Tokenizer, VerifiedGgufFile, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::original_serve_arms; use crate::qwen_forward::{ original_serve_request::{RequestSampling, ServeError, ServeRequest}, original_serve_stack::{OriginalServeStack, StackConfig}, diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_smoke/smoke_long.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_smoke/smoke_long.rs index 5e2c4335..d6bea2b6 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_smoke/smoke_long.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_smoke/smoke_long.rs @@ -1,11 +1,11 @@ //! Long-context smoke of the streamed INT8 KV: one greedy request over a prompt far longer than the resident //! window (documented on `original_serve_long_context_streamed_kv_smoke`). +#[cfg(all(test, target_arch = "x86_64"))] +use super::original_serve_arms; use super::{ OriginalServeStack, PathBuf, ServeRequest, StackConfig, Tokenizer, collect, dbg_el, env, env_or, ids, number, open_pinned, open_stack, request, with_context, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::original_serve_arms; use std::time::Instant; const COLORS: [&str; 8] = ["amber", "blue", "crimson", "green", "grey", "ivory", "orange", "violet"]; diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_smoke/smoke_main.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_smoke/smoke_main.rs index 017e513c..5fe4d668 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_smoke/smoke_main.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_smoke/smoke_main.rs @@ -1,11 +1,11 @@ //! The main smoke: greedy twice across a reset, a sampled request, a cancellation, the optional parity corpus //! and a short prompt on the scalar draft-KV path. +#[cfg(all(test, target_arch = "x86_64"))] +use super::original_serve_arms; use super::{ OriginalServeStack, PROMPT, PathBuf, ServeError, ServeRequest, StackConfig, Tokenizer, agent_sampler, collect, dbg_el, env, env_or, open_pinned, open_stack, optin, report_timing, request, with_context, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::original_serve_arms; mod corpus; diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_smoke/smoke_main/corpus.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_smoke/smoke_main/corpus.rs index 7219897f..a79db841 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_smoke/smoke_main/corpus.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_smoke/smoke_main/corpus.rs @@ -1,9 +1,9 @@ //! The parity corpus of the main smoke: every line of `LELEKA_SMOKE_PROMPTS` is tokenized with the verified //! tokenizer, served greedily for `LELEKA_SMOKE_MAX_NEW` tokens (default 64) and printed as ids so the Original //! can be run on the same ids. -use super::{ServeError, ServeRequest, Smoke, Tokenizer, agent_sampler, env, env_or, report_timing}; #[cfg(all(test, target_arch = "x86_64"))] use super::original_serve_arms; +use super::{ServeError, ServeRequest, Smoke, Tokenizer, agent_sampler, env, env_or, report_timing}; use crate::qwen_forward::{ original_serve_engine::ServeOutcome, original_serve_request::{RequestSampling, original_stop_tokens}, diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_ttft.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_ttft.rs index cd760f86..a7fc296c 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_ttft.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_ttft.rs @@ -11,7 +11,9 @@ //! Inputs: those of the replay (`LELEKA_ORIGINAL_SERVE_REPLAY=yes`, model, expert tier, `LELEKA_REPLAY_CAPACITY`, //! `LELEKA_REPLAY_PREFIX_MIB`, `LELEKA_ORIGINAL_SERVE_RT_DIR`), `LELEKA_SWEEP_MAX_NEW` (4). use super::super::qwen_forward::original_serve_stack::dbg_el; -use super::{Driver, InheritedKarArchive, ModelBinding, PathBuf, Qwen4ExpArtifact, Rc, SHARD0, SHARD1, VerifiedGgufFile}; +use super::{ + Driver, InheritedKarArchive, ModelBinding, PathBuf, Qwen4ExpArtifact, Rc, SHARD0, SHARD1, VerifiedGgufFile, +}; use crate::qwen_forward::{ original_serve_request::ServeRequest, original_serve_stack::{OriginalServeStack, PrefixBudget, PrefixConfig, StackConfig}, diff --git a/crates/engine-qwen35-cuda/src/backend/serve_generate.rs b/crates/engine-qwen35-cuda/src/backend/serve_generate.rs index 72906a83..fc80c128 100644 --- a/crates/engine-qwen35-cuda/src/backend/serve_generate.rs +++ b/crates/engine-qwen35-cuda/src/backend/serve_generate.rs @@ -1,4 +1,6 @@ //! One Generate command of the serve loop: admit it, resume or start a session, generate, publish the terminal. +#[cfg(feature = "preview-path")] +use super::QwenSession; use super::{ ActiveGuard, Arc, AtomicBool, BackendError, Conversations, Counters, GenerationRequest, GenerationSink, GenerationStream, LoadedModel, ModelBinding, MtpContinuation, Ordering, Outcome, PrefixSession, QUEUE, Rc, Reply, @@ -6,8 +8,6 @@ use super::{ log_conversation_events, log_generation_cache, measurement, prepare_prompt, run_generation, terminal_admit, terminal_of, unavailable, verdict, }; -#[cfg(feature = "preview-path")] -use super::QwenSession; use std::cell::RefCell; /// One Generate command as it arrived. diff --git a/crates/engine-qwen35-cuda/src/conversation/memory.rs b/crates/engine-qwen35-cuda/src/conversation/memory.rs index d56a4d7a..739c2013 100644 --- a/crates/engine-qwen35-cuda/src/conversation/memory.rs +++ b/crates/engine-qwen35-cuda/src/conversation/memory.rs @@ -5,7 +5,6 @@ //! every ambiguity (malformed, duplicated, wrongly-united, I/O failure) //! reads as unknown so admission fails closed. - pub use leleka_engine_core::memory::{mem_available, memory_admit}; /// Available host physical memory right now; `None` when unknown (any diff --git a/crates/engine-qwen35-cuda/src/memory_governor.rs b/crates/engine-qwen35-cuda/src/memory_governor.rs index 5885f621..ee3320c6 100644 --- a/crates/engine-qwen35-cuda/src/memory_governor.rs +++ b/crates/engine-qwen35-cuda/src/memory_governor.rs @@ -9,8 +9,8 @@ use crate::settings::{EnvSource, Settings}; use leleka_backend_api::BackendError; use leleka_memory::ledger::{DeviceSample, OpenStage}; use leleka_memory::{ - CacheWish, Entry, FixedItem, Governor, GovernorConfig, HostFacts, KarForm, PlanInput, SamplerGuard, - Space, VramFacts, When, + CacheWish, Entry, FixedItem, Governor, GovernorConfig, HostFacts, KarForm, PlanInput, SamplerGuard, Space, + VramFacts, When, }; use leleka_memory_os::{HostProc, real_governor}; use std::sync::Mutex; diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/mtp/backing.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/mtp/backing.rs index 8708bb4b..dc31258b 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/mtp/backing.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/mtp/backing.rs @@ -1,9 +1,9 @@ //! 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. -use super::{File, InputBindingError, InputResult, Path}; #[cfg(test)] use super::{EXPERT_BLOB, MtpExpertMatrix, MtpKind, read_exact_range, read_expert_rows}; +use super::{File, InputBindingError, InputResult, Path}; use sha2::{Digest, Sha256}; use std::io::Read; use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt}; diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/mtp/mtp_kind_types.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/mtp/mtp_kind_types.rs index 66e8346e..73253e58 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/mtp/mtp_kind_types.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/mtp/mtp_kind_types.rs @@ -1,7 +1,6 @@ //! The vocabulary of the MTP pack: storage kinds, expert matrices, the roles of its tensors, and the `Descriptor` //! and `Dense` records that describe one tensor. - #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum MtpKind { Q8_0, diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/mtp/mtp_weight_reads.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/mtp/mtp_weight_reads.rs index e356776b..adb749ef 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/mtp/mtp_weight_reads.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/mtp/mtp_weight_reads.rs @@ -1,9 +1,9 @@ //! The reads of the MTP weights: dense rows, expert rows and the binding identity check. use super::{ - DENSE_BYTES, DESCRIPTORS, EXPERT_BLOB, EXPERT_BYTES, FILE_PINS, INDEX_BYTES, MAX_ROWS, BindingIdentity, - InputBindingError, InputResult, ModelBinding, MtpExpertRef, MtpIndex, MtpKind, MtpRole, MtpRows, MtpWeights, - Path, backing, descriptor, read_exact_range, read_expert_rows, row_range, validate_numeric, + BindingIdentity, DENSE_BYTES, DESCRIPTORS, EXPERT_BLOB, EXPERT_BYTES, FILE_PINS, INDEX_BYTES, InputBindingError, + InputResult, MAX_ROWS, ModelBinding, MtpExpertRef, MtpIndex, MtpKind, MtpRole, MtpRows, MtpWeights, Path, backing, + descriptor, read_exact_range, read_expert_rows, row_range, validate_numeric, }; impl MtpWeights { diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/mtp/read_expert_rows.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/mtp/read_expert_rows.rs index bc32d4a8..3c75033f 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/mtp/read_expert_rows.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/mtp/read_expert_rows.rs @@ -1,9 +1,9 @@ //! 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. -use super::{EXPERT_BLOB, MAX_READ, MAX_ROWS, File, InputBindingError, InputResult, MtpExpertMatrix, MtpKind, MtpRows}; #[cfg(not(target_os = "linux"))] use super::backing; +use super::{EXPERT_BLOB, File, InputBindingError, InputResult, MAX_READ, MAX_ROWS, MtpExpertMatrix, MtpKind, MtpRows}; pub(super) fn read_expert_rows( experts: &File, diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/validate_ple_descriptor.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/validate_ple_descriptor.rs index 63e755c1..6eecb9b7 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/validate_ple_descriptor.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/validate_ple_descriptor.rs @@ -1,12 +1,12 @@ //! Bind-time admission of a Qwen4Exp artifact: the per-layer token-embedding (PLE) descriptor and the ordered list of //! bound layers with their kinds. Also the test fixtures for `InputConstants` and `BindingIdentity`. +#[cfg(test)] +use super::{BindingIdentity, InputConstants, Rc}; use super::{ BoundLayer, BoundLayerKind, GlobalRole, InputBindingError, InputResult, LayerRole, PLE_ROWS, Qwen4ExpArtifact, TensorRole, }; -#[cfg(test)] -use super::{BindingIdentity, InputConstants, Rc}; pub(super) fn validate_ple_descriptor(artifact: &Qwen4ExpArtifact) -> InputResult<()> { let ple = artifact diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/inherited_kar_archive.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/inherited_kar_archive.rs index a320d75d..5521d204 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/inherited_kar_archive.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/inherited_kar_archive.rs @@ -2,8 +2,8 @@ //! Functions: `open_sealed_archive_fd`, `open_read_only_archive`, `check_read_only_archive`, `reopen_read_only_archi... use super::{ - ARCHIVE_DIGEST, PINNED_ARCHIVE_BYTES, PROVENANCE_DIGEST, File, InheritedKarArchive, InputBindingError, - InputResult, Path, PathBuf, SparseArchive, private_copy, + ARCHIVE_DIGEST, File, InheritedKarArchive, InputBindingError, InputResult, PINNED_ARCHIVE_BYTES, PROVENANCE_DIGEST, + Path, PathBuf, SparseArchive, private_copy, }; use leleka_model_format::weight_source::{BackingKind, FileWeightSource, Verification, WeightIdentity}; diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/load_pinned_inherited_archive.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/load_pinned_inherited_archive.rs index 8f8bcde2..afa36b82 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/load_pinned_inherited_archive.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/load_pinned_inherited_archive.rs @@ -2,8 +2,8 @@ //! Functions: `open_archive_reader`, `load_pinned_inherited_archive`, `log_startup_read`, `load_pinned_inherited_arc... use super::{ - NATIVE_DIGESTS, PINNED_ARCHIVE_BYTES, PLE_ROWS, PROVENANCE_DIGEST, BindingIdentity, File, InheritedKarArchive, - InputBindingError, InputResult, KarError, KarPleBinding, KarRowPacket, KarRowReader, LoadPhase, RefCell, + BindingIdentity, File, InheritedKarArchive, InputBindingError, InputResult, KarError, KarPleBinding, KarRowPacket, + KarRowReader, LoadPhase, NATIVE_DIGESTS, PINNED_ARCHIVE_BYTES, PLE_ROWS, PROVENANCE_DIGEST, RefCell, VerifiedKarPleArtifact, open_sealed_archive_fd, pinned_profile, reopen_read_only_archive, verify_open_provenance, }; diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile.rs index b3588b0d..136c70bf 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile.rs @@ -2,9 +2,9 @@ //! Functions: `pinned_profile`, `pinned_parts`, `pinned_profile_spec`, `load_pinned_archive` and 3 more. use super::{ - ARCHIVE_DIGEST, NATIVE_DIGESTS, PART0_F32_DIGEST, PART1_F32_DIGEST, PROVENANCE_DIGEST, VIRTUAL_F32_DIGEST, File, - InheritedKarArchive, InputBindingError, InputResult, KarPlePartProvenance, KarPleProfile, KarPleProfileSpec, - LoadPhase, Path, VerifiedKarPleArtifact, error, input_failure, kar_failure, private_copy, + ARCHIVE_DIGEST, File, InheritedKarArchive, InputBindingError, InputResult, KarPlePartProvenance, KarPleProfile, + KarPleProfileSpec, LoadPhase, NATIVE_DIGESTS, PART0_F32_DIGEST, PART1_F32_DIGEST, PROVENANCE_DIGEST, Path, + VIRTUAL_F32_DIGEST, VerifiedKarPleArtifact, error, input_failure, kar_failure, private_copy, }; /// Candidate expectations from independently verified v4 conversion receipts diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile_tests.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile_tests.rs index fb64dc2c..fc20946a 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile_tests.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile_tests.rs @@ -2,7 +2,7 @@ //! Functions: `diagnostic_cases`, `assert_kar_diagnostic_redacts`, `assert_input_diagnostic_survives_broken_sink`, `... use super::{ - NATIVE_DIGESTS, PLE_ROWS, InputBindingError, KarError, LoadPhase, error, input_diagnostic, kar_diagnostic, + InputBindingError, KarError, LoadPhase, NATIVE_DIGESTS, PLE_ROWS, error, input_diagnostic, kar_diagnostic, pinned_profile, pinned_profile_spec, }; diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/checked_reader.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/checked_reader.rs index f3886295..e4b13051 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/checked_reader.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/checked_reader.rs @@ -3,7 +3,7 @@ use super::{COPY_BUFFER, InputBindingError, InputResult, IoPhase, LoadPhase, Read, Write, input_failure, report_io}; #[cfg(not(target_os = "linux"))] -use super::{SOURCE_FLAGS, File, Metadata, MetadataExt, OpenOptions, OpenOptionsExt, Seek, inode, phase_error}; +use super::{File, Metadata, MetadataExt, OpenOptions, OpenOptionsExt, SOURCE_FLAGS, Seek, inode, phase_error}; #[cfg(target_os = "macos")] pub(super) fn checked_reader(own: &OwnedCopy, bytes: u64) -> InputResult { diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/inode.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/inode.rs index b6afbfbe..22418bf1 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/inode.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/inode.rs @@ -2,8 +2,8 @@ //! Functions: `inode`, `diagnostic`, `report_io`, `phase_error` and 8 more. use super::{ - SOURCE_FLAGS, File, Inode, InputBindingError, InputResult, IoPhase, LoadPhase, Metadata, MetadataExt, - OpenOptions, OpenOptionsExt, Path, Seek, Write, copy_exact, input_failure, + File, Inode, InputBindingError, InputResult, IoPhase, LoadPhase, Metadata, MetadataExt, OpenOptions, + OpenOptionsExt, Path, SOURCE_FLAGS, Seek, Write, copy_exact, input_failure, }; #[cfg(not(target_os = "linux"))] use super::{Read, checked_reader}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/workspaces.rs b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/workspaces.rs index 4fe9d212..1ce1c86a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/workspaces.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/workspaces.rs @@ -2,12 +2,12 @@ //! GDN state buffers), all empty at construction and filled on first use. The fields are declared in the order the //! cache drops them, so the drop order is unchanged. +#[cfg(test)] +use super::Cell; use super::{ DeviceBuffer, GdnInputScratch, GrBatchInjectWorkspace, GrScratch, QkScratch, QsaAttentionScratch, QsaIndexKeyCache, QsaInputScratch, QsaSelectedCache, Rc, RefCell, RouterScratch, }; -#[cfg(test)] -use super::Cell; /// Every scratch owner of the cache that starts empty (`None` or an empty list) and is filled on first use. #[derive(Default)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/original_prompt/staged_input_enabled.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/original_prompt/staged_input_enabled.rs index 172eb120..56b18179 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/original_prompt/staged_input_enabled.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/original_prompt/staged_input_enabled.rs @@ -1,6 +1,5 @@ //! The `prefill_staged_input` switch: staged chunk input, or the per-token host path of the KAR inputs (the A/B arm). - /// `LELEKA_PREFILL_STAGED_INPUT=0` keeps the per-token host path of the KAR inputs (the A/B arm). pub(super) fn staged_input_enabled() -> bool { crate::settings::process().kv.prefill_staged_input diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk.rs index c19701ab..bdf57656 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk.rs @@ -6,8 +6,8 @@ use super::super::session::chunk::QwenChunkTxn; use super::{ BoundLayerKind, DenseWeightCache, Dimension, Error, ForwardPhase, GdnStage, GrStage, InjectedResidual, InputStage, KarPleCache, LayerEntry, LayerId, ModelBinding, MoeExpertStage, MoeRouteStage, MoeWeightCache, OutputStage, - Position, QsaAttentionStage, QsaIndexStage, QwenForward, QwenSession, QwenStepTxn, Result, Stage, TargetStepProduct, - TokenId, diagnose, prepare_layer_attention_micro, read_layer_attention, validate_layer_plan, + Position, QsaAttentionStage, QsaIndexStage, QwenForward, QwenSession, QwenStepTxn, Result, Stage, + TargetStepProduct, TokenId, diagnose, prepare_layer_attention_micro, read_layer_attention, validate_layer_plan, }; #[cfg(test)] use super::{StepCaches, StepRequest}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/joint_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/joint_chunk.rs index 501f8aff..4b2db0cd 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/joint_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/joint_chunk.rs @@ -1,11 +1,11 @@ //! The inputs and the joint target+draft publication shared by the prefill chunk entry points. +#[cfg(all(test, target_arch = "x86_64"))] +use super::window_numeric; use super::{ ChunkMoePolicy, DenseWeightCache, Error, KarPleCache, ModelBinding, MoeWeightCache, OutputStage, QwenForward, QwenSession, Result, Stage, TargetStepProduct, TokenId, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::window_numeric; use crate::qwen_forward::mtp_decode::MtpDecoder; #[cfg(test)] use leleka_cuda_driver::Context; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_cached_windowed.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_cached_windowed.rs index 090a2c7a..c5c4bad6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_cached_windowed.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_cached_windowed.rs @@ -1,12 +1,12 @@ //! Entry points of `QwenForward` for the cached prefill chunk: MMQ joint, cached joint and the private outer256 //! windowed experiments (plain and retained-GR transport). Normal serving stays on outer64 with the host transport. +#[cfg(all(test, target_arch = "x86_64"))] +use super::check_chunk_on_loaded; use super::{ ChunkMoePolicy, MoeWeightCache, PrefillChunkInputs, PrefillChunkPlan, QwenChunkTxn, QwenForward, QwenSession, Result, TargetStepProduct, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::check_chunk_on_loaded; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_planned.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_planned.rs index 474fa71a..f8ecf175 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_planned.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_planned.rs @@ -2,16 +2,16 @@ //! and the layer loop that ends in the output head. The phases are the child modules (setup, layer, window attention, //! FFN, experts). +#[cfg(all(test, target_arch = "x86_64"))] +use super::window_numeric; use super::{ AttentionHandoff, BoundLayerKind, ChunkMoePolicy, DenseWeightCache, Dimension, Error, ForwardPhase, GdnStage, GrStage, InjectedResidual, InputStage, KarPleCache, LayerEntry, LayerId, MicroEnv, ModelBinding, MoeExpertStage, MoeRouteStage, MoeWeightCache, OutputStage, Position, PrefillChunkInputs, PrefillChunkPlan, QsaAttentionStage, QsaIndexStage, QwenChunkTxn, QwenForward, QwenSession, QwenStepTxn, Result, Stage, TokenId, chunk_diagnostic, - diagnose, prepare_layer_attention_micro, prepare_micro_ffn_rows, prepare_q6_layer_columns, read_chunk_attention_ffn, - read_layer_attention, validate_layer_plan, + diagnose, prepare_layer_attention_micro, prepare_micro_ffn_rows, prepare_q6_layer_columns, + read_chunk_attention_ffn, read_layer_attention, validate_layer_plan, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::window_numeric; use leleka_cuda_driver::Context; mod chunk_layer; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_planned/chunk_layer.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_planned/chunk_layer.rs index fef33659..ed548294 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_planned/chunk_layer.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_planned/chunk_layer.rs @@ -2,12 +2,12 @@ use super::window_experts::ExpertRun; use super::window_ffn::WindowOwners; +#[cfg(all(test, target_arch = "x86_64"))] +use super::window_numeric; use super::{ BoundLayerKind, ChunkEnv, ChunkRun, Context, Dimension, Error, GdnPlan, InjectedResidual, LayerId, MoeWeightCache, NativeMoe, QwenChunkTxn, QwenForward, Result, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::window_numeric; use crate::qwen_forward::gdn::chunk_device::GdnChunkDevice; use crate::qwen_forward::moe_expert::ChunkFfnLayer; use crate::qwen_forward::session::chunk::{ChunkFfnRow, ChunkMicroWindow}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_planned/chunk_setup.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_planned/chunk_setup.rs index 0d720bb1..d2e6d6a0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_planned/chunk_setup.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_planned/chunk_setup.rs @@ -1,12 +1,12 @@ //! Admission, transaction begin, input rows and output head of one prefill chunk. +#[cfg(all(test, target_arch = "x86_64"))] +use super::window_numeric; use super::{ ChunkEnv, ChunkMoePolicy, ChunkOpening, Context, DenseWeightCache, Error, InjectedResidual, InputStage, KarPleCache, ModelBinding, MoeWeightCache, OutputStage, PrefillChunkInputs, PrefillChunkPlan, QwenChunkTxn, QwenForward, QwenSession, QwenStepTxn, Result, Stage, chunk_diagnostic, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::window_numeric; /// The MMQ actor context, and the contexts of the recurrence and verification GDN owners when they are in use. type ChunkContexts<'ctx, 'driver> = diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_planned/window_attention.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_planned/window_attention.rs index 2fb5da02..b2f5069f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_planned/window_attention.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/qwen_forward/prefill_chunk_planned/window_attention.rs @@ -1,13 +1,13 @@ //! The attention reads of one window of a prefill layer. +#[cfg(test)] +use super::QwenStepTxn; +#[cfg(all(test, target_arch = "x86_64"))] +use super::window_numeric; use super::{ ChunkEnv, ChunkRun, Error, GrStage, InjectedResidual, InputStage, LayerEntry, LayerId, MicroBank, QwenChunkTxn, QwenForward, Result, Stage, chunk_diagnostic, prepare_layer_attention_micro, read_layer_attention, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::window_numeric; -#[cfg(test)] -use super::QwenStepTxn; use crate::qwen_forward::session::chunk::ChunkAttentionRow; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use crate::qwen_forward::{ diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/read_chunk_attention_ffn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/read_chunk_attention_ffn.rs index 006ebbdb..1d3b104c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/read_chunk_attention_ffn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/prefill_chunk/read_chunk_attention_ffn.rs @@ -2,12 +2,12 @@ //! go to the retained GR bank. Also the layer-0 pair diagnostic, whose four-row chunk must refuse with the executor //! error. -use super::{DenseWeightCache, ForwardPhase, GrStage, ModelBinding, Result, diagnose}; #[cfg(test)] use super::{ ChunkMoePolicy, Dimension, Error, KarPleCache, MoeWeightCache, OutputStage, PrefillChunkInputs, QwenForward, QwenSession, Stage, TokenId, }; +use super::{DenseWeightCache, ForwardPhase, GrStage, ModelBinding, Result, diagnose}; use crate::qwen_forward::gr::AttentionBlockOutput; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/qwen_forward.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/qwen_forward.rs index 57f3bebc..f4b9b428 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/qwen_forward.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/qwen_forward.rs @@ -6,6 +6,6 @@ use super::{ Stage, StepCaches, StepCoreResult, StepPurpose, StepRequest, TargetStepProduct, TokenId, }; -mod qwen_forward_reset; mod forward_step_body; +mod qwen_forward_reset; mod step_entries; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layers.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layers.rs index 8947e066..dbb5e1d6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layers.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/step_layers.rs @@ -11,11 +11,11 @@ use crate::qwen_forward::gdn::GdnLayerInput; use crate::qwen_forward::moe_expert::ExpertRowRequest; use crate::qwen_forward::qsa_attention::QsaReady; -#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -use crate::qwen_forward::oracle_capture; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use super::step_residual_capture::capture_input; pub(super) use super::step_residual_capture::capture_streams; +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +use crate::qwen_forward::oracle_capture; /// The per-step identity every layer phase validates against. #[derive(Clone, Copy)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn.rs index 6783fc0e..86897271 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn.rs @@ -196,7 +196,6 @@ mod tests { } } - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mod four_borrow_gpu; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/cached_step.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/cached_step.rs index a0548099..e60c0a1f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/cached_step.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/cached_step.rs @@ -2,13 +2,13 @@ //! Runs on a step-local `Chain`, then publishes the next recurrent state through the mirror only if the whole step //! succeeded; on failure the computed candidate is discarded and the chain is cleaned up. +#[cfg(all(test, target_arch = "x86_64"))] +use super::four_borrow_gpu; use super::{ CandidatePair, Context, DEVICE_PEAK, DenseWeightCache, DeviceBuffer, Error, GdnInputLease, GdnLayerInput, GdnMatrixKind, GdnMatrixRole, GdnPrior, GdnReady, GdnStateMirror, GdnWeights, LeaseClaim, LeasedProjection, MirrorStep, ModelBinding, ProjectedQkvSource, QwenStepTxn, ResidualReady, Result, chain, mirror, validate_values, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::four_borrow_gpu; use crate::qwen_forward::dense_weight_cache::GdnResident; use std::{cell::Cell, rc::Rc}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/chunk_device/gdn_chunk_device_methods.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/chunk_device/gdn_chunk_device_methods.rs index 6ad48c03..4a38a2c2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/chunk_device/gdn_chunk_device_methods.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/chunk_device/gdn_chunk_device_methods.rs @@ -1,10 +1,11 @@ //! The `GdnChunkDevice` methods by phase: construction and admission, per-row and batch compute, finish and cleanup. use super::{ - BindingIdentity, CHUNK_DEVICE_CHARGE, Cell, ChunkEdge, ChunkReadout, Context, DenseWeightCache, DeviceBuffer, Error, - GdnChunkDevice, GdnChunkMicro, GdnChunkRow, GdnChunkSeal, GdnChunkStart, GdnPrior, GdnRowQueue, HISTORY_ELEMENTS, - ModelBinding, Rc, ReadoutDownload, Result, STATE_ELEMENTS, VALUES, allocate, download, download_unchecked, - driver_error, micro_rows, mirror_reuse_enabled, pool_enabled, preflight_budget, upload, validate_values, + BindingIdentity, CHUNK_DEVICE_CHARGE, Cell, ChunkEdge, ChunkReadout, Context, DenseWeightCache, DeviceBuffer, + Error, GdnChunkDevice, GdnChunkMicro, GdnChunkRow, GdnChunkSeal, GdnChunkStart, GdnPrior, GdnRowQueue, + HISTORY_ELEMENTS, ModelBinding, Rc, ReadoutDownload, Result, STATE_ELEMENTS, VALUES, allocate, download, + download_unchecked, driver_error, micro_rows, mirror_reuse_enabled, pool_enabled, preflight_budget, upload, + validate_values, }; mod chunk_device_batch_compute; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/chunk_device/gdn_chunk_device_methods/chunk_device_batch_compute.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/chunk_device/gdn_chunk_device_methods/chunk_device_batch_compute.rs index 5eca8118..1a76cf5f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/chunk_device/gdn_chunk_device_methods/chunk_device_batch_compute.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/chunk_device/gdn_chunk_device_methods/chunk_device_batch_compute.rs @@ -2,12 +2,12 @@ //! read the readout back and mint the row edges. The earliest full-state refusal precedes the readout and any user. //! Also adopts the final state of a batch that drained clean. +#[cfg(test)] +use super::upload; use super::{ ChunkEdge, ChunkReadout, DeviceBuffer, Error, GdnChunkDevice, GdnChunkRow, HISTORY_ELEMENTS, Rc, ReadoutDownload, Result, VALUES, allocate, download, driver_error, preflight_budget, validate_values, }; -#[cfg(test)] -use super::upload; impl<'ctx> GdnChunkDevice<'ctx> { /// Adopt the final state of a batch that drained clean: the separate `next` diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/chunk_device/numeric_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/chunk_device/numeric_gpu.rs index 0f8a3a3e..2b8aae8f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/chunk_device/numeric_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/chunk_device/numeric_gpu.rs @@ -4,9 +4,9 @@ use super::super::super::contract::{Dimension, LayerId}; use super::super::super::session::chunk::TestGdnComponentRows; use super::super::{RecurrenceOperands, convolve, recur}; use super::{ - BindingIdentity, CHUNK_DEVICE_CHARGE, Cell, ChunkReadout, Context, DeviceBuffer, Error, GdnChunkDevice, GdnChunkRow, - GdnChunkSeal, GdnChunkStart, GdnPrior, GdnStateFiniteGuard, HISTORY_ELEMENTS, Rc, Result, STATE_ELEMENTS, allocate, - download, driver_error, preflight_budget, upload, validate_values, + BindingIdentity, CHUNK_DEVICE_CHARGE, Cell, ChunkReadout, Context, DeviceBuffer, Error, GdnChunkDevice, + GdnChunkRow, GdnChunkSeal, GdnChunkStart, GdnPrior, GdnStateFiniteGuard, HISTORY_ELEMENTS, Rc, Result, + STATE_ELEMENTS, allocate, download, driver_error, preflight_budget, upload, validate_values, }; use leleka_cuda_driver::Driver; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/driver_error.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/driver_error.rs index c0082b22..81465cae 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/driver_error.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/driver_error.rs @@ -1,9 +1,9 @@ //! Maps CUDA driver errors to the GDN `Error` and holds the GDN state addressing checks (`state_index`, `key_head`). //! The state address is the exact native layout, never a head-major reinterpretation. -use super::{DriverError, Error, KEY_HEADS, Result, Stage, VALUE_HEADS, WIDTH}; #[cfg(test)] use super::CandidateFixture; +use super::{DriverError, Error, KEY_HEADS, Result, Stage, VALUE_HEADS, WIDTH}; #[cfg(test)] use super::{HISTORY_ELEMENTS, STATE_ELEMENTS, TokenLayer, validate_values}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr/retained_handoff.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/retained_handoff.rs index b3621bc8..f2b56769 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr/retained_handoff.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/retained_handoff.rs @@ -2,6 +2,8 @@ //! The actual finite host witness remains canonical; only its duplicate H2D //! is removed. No device-only host proof or changed arithmetic is introduced. use super::read_cached_cuda::borrow_injection; +#[cfg(test)] +use super::{BindingIdentity, inject_cached_cuda, upload_bf16, upload_f32}; use super::{ Cell, Context, DenseWeightCache, DetachedGrRead, DeviceBuffer, Error, GrMicroAttentionBank, GrMicroAttentionBlock, GrPhase, GrRead, GrRole, GrScratch, GrStage, InjectedResidual, LayerId, ModelBinding, QwenStepTxn, @@ -9,8 +11,6 @@ use super::{ copy_cached_f32, diagnose, download_f32, driver_error, read_cached_cuda, validate_layer, validate_streams, validate_values, }; -#[cfg(test)] -use super::{BindingIdentity, inject_cached_cuda, upload_bf16, upload_f32}; /// The attention block output an attention residual is injected with, and the token and layer it was computed for. #[derive(Clone, Copy)] pub(in crate::qwen_forward) struct AttentionBlockOutput<'a> { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_transport/ple_inner_composition.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_transport/ple_inner_composition.rs index faae1d76..2a355e6c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_transport/ple_inner_composition.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_transport/ple_inner_composition.rs @@ -1,12 +1,12 @@ //! The composition of one PLE row: project key and value, gate, normalise, convolve the history and finish the //! residual streams. Separate from `ple_transport`, which holds the transport and its row types. +#[cfg(test)] +use super::ObservedOutput; use super::{ Bf16ProjectionShape, Cell, Context, DeviceBuffer, Error, Finite, PLE_HC, PLE_HISTORY, PleCandidate, PleRows, Rc, Result, Role, Transport, admit, at, ple_driver_error, ple_values, }; -#[cfg(test)] -use super::ObservedOutput; use leleka_cuda_driver::PleClosedWeights; pub(super) fn compose_inner( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_transport/ple_key_retained_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_transport/ple_key_retained_gpu.rs index 0abad6b0..c54c9c5f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_transport/ple_key_retained_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_transport/ple_key_retained_gpu.rs @@ -2,8 +2,8 @@ #![cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use super::super::{ple_upload, ple_upload_f32}; use super::{ - Bf16ProjectionShape, Cell, Context, DeviceBuffer, Error, Finite, PleCandidate, PleRows, Rc, Result, Role, Transport, - at, compose, ple_download, ple_driver_error, + Bf16ProjectionShape, Cell, Context, DeviceBuffer, Error, Finite, PleCandidate, PleRows, Rc, Result, Role, + Transport, at, compose, ple_download, ple_driver_error, }; #[cfg(test)] use super::{Observations, compose_observed}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_transport/ple_key_retained_gpu/bf16.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_transport/ple_key_retained_gpu/bf16.rs index 57ab95cc..c35f51ab 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_transport/ple_key_retained_gpu/bf16.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_transport/ple_key_retained_gpu/bf16.rs @@ -1,12 +1,12 @@ //! Test support for the retained-PLE proof: synthetic BF16 PLE matrices and the legacy chain (one key projection and //! forty ephemeral value tiles) that the whole-matrix retained path must reproduce bit for bit. +#[cfg(test)] +use super::Observations; use super::{ Bf16ProjectionShape, Context, DeviceBuffer, Finite, Matrices, Role, Transport, at, ple_download, ple_driver_error, ple_upload, ple_upload_f32, }; -#[cfg(test)] -use super::Observations; pub(super) fn bf16(rows: usize, columns: usize, seed: usize) -> Vec { (0..rows) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_matrix_projection.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_matrix_projection.rs index 86e3e2a4..ee97474a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_matrix_projection.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_matrix_projection.rs @@ -3,16 +3,16 @@ //! routed prepared Q8 or cached MMQ), and a kind without a plan is refused. The uncached diagnostic path uploads the //! raw matrix here. +#[cfg(test)] +use super::TILE; +#[cfg(test)] +use super::validate_values; use super::{ BoundExpert, CachedMoeMatrix, Context, DEVICE_PEAK, DenseFormat, DeviceBuffer, Error, FF, ModelBinding, MoeExpertBlock, MoeExpertSelection, MoeExpertWeights, MoeMatrixKind, MoeMatrixRole, MoeWeightCache, N, ProjectionKind, ProjectionSpec, Q5KProjectionShape, Q6KProjectionShape, Result, RoutedFormat, RoutedGateUpQ8, Stage, binding_error, download_f32, driver_error, upload_bytes, }; -#[cfg(test)] -use super::TILE; -#[cfg(test)] -use super::validate_values; /// Shape and format of one expert matrix as the binding declares it. #[derive(Clone, Copy)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/bound_rows.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/bound_rows.rs index d540abb7..1c3d2d5c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/bound_rows.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/bound_rows.rs @@ -1,5 +1,7 @@ //! The uploaded rows of one chunk and their ungrouped/grouped execution (STRA-338 size: extract-method only). +#[cfg(all(test, target_arch = "x86_64"))] +use super::direct_gpu; use super::direct_packets_fns::PacketRun; use super::finish_shared_with::RowTail; use super::{ @@ -8,8 +10,6 @@ use super::{ TransportBuffer, adaptive, execute_cuda_cached, finish_shared, grouped_pairs, project_group, prompt_finish, use_direct_packets, uses_adaptive, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::direct_gpu; /// The uploaded rows of one chunk: activations and Q8 owners all alive for the whole execution. pub(super) struct BoundRows<'a, 'ctx> { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/direct_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/direct_gpu.rs index 082188af..7416d7c9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/direct_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/direct_gpu.rs @@ -2,8 +2,8 @@ //! session advancement, standalone Load or full-model qualification is minted. use super::{ ChunkFfnLayer, ChunkFfnRow, Context, DEVICE_PEAK, DeviceBuffer, DownScope, DownSelection, DriverError, Error, - ExpertReady, FF, GrStage, K, LayerId, ModelBinding, MoeExpertStage, MoeWeightCache, N, PreparedMoeRow, QwenChunkTxn, - Rc, Result, Stage, TransportBuffer, download_f32, driver_error, validate_values, + ExpertReady, FF, GrStage, K, LayerId, ModelBinding, MoeExpertStage, MoeWeightCache, N, PreparedMoeRow, + QwenChunkTxn, Rc, Result, Stage, TransportBuffer, download_f32, driver_error, validate_values, }; use crate::qwen_forward::gr::DetachedGrRead; use crate::qwen_forward::session::{QwenStepTxn, ResetReplaySnapshot, chunk::ChunkAttentionRow}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/direct_packets_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/direct_packets_fns.rs index e28173f3..8d843f83 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/direct_packets_fns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/direct_packets_fns.rs @@ -1,5 +1,7 @@ //! Phases of the direct-packet layer batch (STRA-338 size: extract-method only). +#[cfg(all(test, target_arch = "x86_64"))] +use super::direct_gpu; use super::finish_shared_with::RowTail; use super::ordered_down_refusal::close_packets; use super::packet_run_project_group_direct::DirectRun; @@ -8,8 +10,6 @@ use super::{ Pair, PreparedMoeRow, QwenChunkTxn, Rc, Result, RoutedGateUpQ8, Stage, TransportBuffer, adaptive_packets, finish_shared_queued, finish_shared_with, prompt_finish, use_shared_tail, uses_adaptive, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::direct_gpu; /// The sealed rows, their origins, expert groups and shared activations of one direct-packet layer batch. pub(super) struct PacketRun<'a, 'session, 'ctx, 'l, 'd, 'q> { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/ordered_down_refusal.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/ordered_down_refusal.rs index 7550d988..f25207c5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/ordered_down_refusal.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/ordered_down_refusal.rs @@ -3,6 +3,8 @@ //! quantizer refusal must not overtake an earlier column's Down NonFinite, so the refusal is replayed ascending; //! every packet is closed whatever the first failure was. +#[cfg(all(test, target_arch = "x86_64"))] +use super::direct_gpu; use super::finish_shared_with::RowTail; use super::packet_run_project_group_direct::{DownProjection, RefusalReplay}; use super::{ @@ -10,8 +12,6 @@ use super::{ MatrixDims, ModelBinding, MoeWeightCache, N, PackedDown, Pair, QwenChunkTxn, Rc, Result, SharedTailRow, Stage, finish_shared_with, launch_cached_projection, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::direct_gpu; pub(super) fn ordered_down_refusal( context: &Context<'_>, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/packet_run_project_group_direct.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/packet_run_project_group_direct.rs index d23a38fb..f3afb872 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/packet_run_project_group_direct.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/packet_run_project_group_direct.rs @@ -3,6 +3,8 @@ //! direct and source paths share. Origins of all rows are validated before any packet is mutably loaned, and every //! group buffer is closed whatever the outcome. +#[cfg(all(test, target_arch = "x86_64"))] +use super::direct_gpu; use super::direct_packets_fns::PacketRun; use super::project_group_shared_fns::*; use super::{ @@ -11,8 +13,6 @@ use super::{ MoeWeightCache, PacketGroupMembers, Pair, QwenChunkTxn, Rc, Result, RoutedFormat, RoutedGateUpQ8, Stage, TransportBuffer, binding_error, download_f32, driver_error, ordered_down_refusal, validate_packet_pairs, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::direct_gpu; impl<'ctx> PacketRun<'_, '_, 'ctx, '_, '_, '_> { /// Project one expert group of the batch through the plain device path (no source fence), filling the slot diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/project_group_source_consumers.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/project_group_source_consumers.rs index d9a78724..cbb20df1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/project_group_source_consumers.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/grouped/project_group_source_consumers.rs @@ -2,6 +2,8 @@ //! The scope ends after the last private consumer and before any packet coverage or group acceptance; a failure //! discards every copied private packet. Also checks that the source members match the group descriptors. +#[cfg(all(test, target_arch = "x86_64"))] +use super::direct_gpu; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use super::packet_run_project_group_direct::{ DirectGroup, DirectRun, DownBuffers, DownProjection, GroupBuffers, RefusalReplay, @@ -16,8 +18,6 @@ use super::{ PacketGroupMembers, Result, RoutedFormat, RoutedGateUpQ8, SourceMatrix, Stage, TransportBuffer, binding_error, download_f32, driver_error, dual_routed_format, ordered_down_refusal, validate_packet_pairs, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::direct_gpu; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use crate::model_binding::qwen4exp_input::MoeRoutedSourceScope; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/tests.rs index 7ccaf69b..d9146f67 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/tests.rs @@ -1,9 +1,9 @@ //! Pins the expert-row collection and finite checks: completed tiles keep all rows, a late failure withholds the //! candidate, and a non-finite last expert output is refused while a signed zero is retained. -use super::{DEVICE_PEAK, Error, FF, N, admit_budget}; #[cfg(test)] use super::collect_rows; +use super::{DEVICE_PEAK, Error, FF, N, admit_budget}; #[test] fn completed_tiles_keep_all_rows_and_late_failure_withholds_candidate() { let values = collect_rows(N, |first, count| { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs index b01ff389..c38846c9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs @@ -34,10 +34,10 @@ mod cache_routed_outputs; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mod cache_strata_adaptive; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -pub(in crate::qwen_forward) use cache_original_prompt::PromptWeightOwners; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[cfg(test)] pub(crate) use cache_original_prompt::PREFILL_STREAM_OVERRIDE; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub(in crate::qwen_forward) use cache_original_prompt::PromptWeightOwners; #[cfg(test)] pub(crate) use cache_original_prompt::set_span_cache_override; pub(crate) use cache_profile::{LearnedMainWitness, SharedPermanentWitness}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_lru_index/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_lru_index/tests.rs index b6a82219..ae76e405 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_lru_index/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_lru_index/tests.rs @@ -1,9 +1,9 @@ //! Pins the bounded LRU index against a scan oracle: oldest-first order with protected keys, atomic batch refusals, //! descriptor collisions, a full index and long deterministic churn. Literal descriptors carry no model or device //! authority, so these tests run without a GPU. -use super::{LruIndex, MAX_KEYS, MoeWeightDescriptor, PER_LAYER, slot}; #[cfg(any(test))] use super::HOST_LIMIT; +use super::{LruIndex, MAX_KEYS, MoeWeightDescriptor, PER_LAYER, slot}; use std::collections::HashMap; type Oracle = HashMap; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill.rs index dcf4b789..de87e1ac 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill.rs @@ -1,12 +1,12 @@ //! Binding-authenticated constructor; metadata alone cannot produce weights. +#[cfg(test)] +use super::room_fits; use super::{ Context, DeviceBuffer, DeviceRef, EncodedWeight, Entry, Error, HashMap, MAIN_LIMIT, ModelBinding, MoeMatrixRole, MoeWeightCache, MoeWeightDescriptor, Rc, RefCell, Result, WORKING_RESERVE, WeightCacheCounters, binding_error, cache_profile, cache_strata_adaptive, driver_error, }; #[cfg(test)] -use super::room_fits; -#[cfg(test)] use cache_profile::ProfileWitness; use cache_profile::{HOST_CAP, PROFILE_SHA, PinnedPool, PrefixPlan, ProfileLimits, RankedProfile}; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill/moe_weight_cache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill/moe_weight_cache.rs index cf672050..37e4e154 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill/moe_weight_cache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill/moe_weight_cache.rs @@ -1,13 +1,13 @@ //! The `MoeWeightCache` constructors of the profile fill: the ranked fill with its pinned pool and the pinned triplet //! preload. +#[cfg(test)] +use super::ProfileWitness; use super::{ Context, DeviceRef, EncodedWeight, Entry, Error, HOST_CAP, HashMap, MAIN_LIMIT, ModelBinding, MoeMatrixRole, MoeWeightCache, MoeWeightDescriptor, PROFILE_SHA, PinnedPool, PrefixPlan, ProfileLimits, RankedProfile, Result, WORKING_RESERVE, binding_error, driver_error, profile_window_spill_with_floor, }; -#[cfg(test)] -use super::ProfileWitness; mod pinned_triplet_preload; mod profile_ranked_fill_and_pool; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill/moe_weight_cache/pinned_triplet_preload.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill/moe_weight_cache/pinned_triplet_preload.rs index 46ddd439..65d186a9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill/moe_weight_cache/pinned_triplet_preload.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill/moe_weight_cache/pinned_triplet_preload.rs @@ -2,14 +2,14 @@ //! its three raw blocks from the binding, upload them (dual or mixed layout) and commit them as pinned main entries //! with the traffic counters. Also the profile witness that reads those counters back for tests. +#[cfg(test)] +use super::PinnedPool; +#[cfg(test)] +use super::ProfileWitness; use super::{ DeviceRef, EncodedWeight, Entry, Error, MAIN_LIMIT, ModelBinding, MoeWeightCache, MoeWeightDescriptor, Result, WORKING_RESERVE, binding_error, driver_error, }; -#[cfg(test)] -use super::ProfileWitness; -#[cfg(test)] -use super::PinnedPool; /// Layouts, charges and the checked next counters of one pinned triplet upload. #[derive(Clone, Copy)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill/profile_build.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill/profile_build.rs index 5d90efa4..0485a802 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill/profile_build.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill/profile_build.rs @@ -1,7 +1,5 @@ -//! The shared-permanent profile build behind the fixed-prefix and learned-main constructors (STRA-338 size: -//! extract-method only). +//! The shared-permanent profile build behind the fixed-prefix and learned-main constructors. -// Stays a glob on purpose: the file is at the 400-line limit and the explicit list would put it over. use super::{ Context, Entry, Error, HOST_CAP, HashMap, MAIN_LIMIT, ModelBinding, MoeMatrixRole, MoeWeightCache, MoeWeightDescriptor, PinnedPool, PrefixPlan, ProfileLimits, RankedProfile, Result, WORKING_RESERVE, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill/shared_quartet_preload.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill/shared_quartet_preload.rs index 627bff67..9d1d79d4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill/shared_quartet_preload.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/cache_profile_fill/shared_quartet_preload.rs @@ -5,12 +5,12 @@ #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[cfg(test)] use super::profile_build::{ProfileFile, ProfileKind, ProfileRequest}; +#[cfg(test)] +use super::{Context, PROFILE_SHA, RankedProfile}; use super::{ DeviceRef, EncodedWeight, Entry, Error, MAIN_LIMIT, ModelBinding, MoeWeightCache, MoeWeightDescriptor, Result, WORKING_RESERVE, binding_error, cache_profile, driver_error, }; -#[cfg(test)] -use super::{Context, PROFILE_SHA, RankedProfile}; /// The room a shared quartet upload must leave free: the spill allowance and the main pool size once the quartet is /// inserted. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/kv_only.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/kv_only.rs index 7f659162..cbf97fc1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/kv_only.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/kv_only.rs @@ -1,7 +1,7 @@ //! Private canonical cell producer. It never represents a ready draft/residual. -use super::{Error, ModelBinding, MoeWeightCache, MtpFrame, MtpInput, QwenSession, Result}; #[cfg(test)] use super::{Cell, MtpSession, Rc}; +use super::{Error, ModelBinding, MoeWeightCache, MtpFrame, MtpInput, QwenSession, Result}; use crate::qwen_forward::session::chunk::{ChunkRowResidual, QwenChunkTxn}; // The same validated frame and canonical packed K/V tuple. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/prefix_draft_snapshot.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/prefix_draft_snapshot.rs index 74f6aae7..c2ef55a6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/prefix_draft_snapshot.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/prefix_draft_snapshot.rs @@ -2,9 +2,9 @@ //! the admission checks of its owner and frame. Also keeps the live-checkpoint count honest: dropping an //! `MtpCheckpoint` releases its slot against the cap. -use super::{CellPair, Error, HALF_ROW, MtpCheckpoint, MtpFrame, Rc, Result}; #[cfg(all(test, target_arch = "x86_64"))] use super::PrefixDraftSnapshot; +use super::{CellPair, Error, HALF_ROW, MtpCheckpoint, MtpFrame, Rc, Result}; #[cfg(test)] use super::{ModelBinding, MtpSession}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/batch_gpu/check_loaded.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/batch_gpu/check_loaded.rs index ea9edd93..e0c7f5d1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/batch_gpu/check_loaded.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/batch_gpu/check_loaded.rs @@ -3,8 +3,8 @@ use super::{ Collection, DenseWeightCache, Dimension, Error, Expected, KarPleCache, ModelBinding, MoeWeightCache, MtpDecoder, - MtpWindowError, MtpWindowSpec, OutputStage, Position, PostcommitCancellation, QwenForward, QwenSession, ROW_CAP, Rc, - Report, ResetReplaySnapshot, Result, SNAPSHOT_CAP, Stage, TRANSACTION_CAP, TargetStepProduct, TokenId, VOCAB, + MtpWindowError, MtpWindowSpec, OutputStage, Position, PostcommitCancellation, QwenForward, QwenSession, ROW_CAP, + Rc, Report, ResetReplaySnapshot, Result, SNAPSHOT_CAP, Stage, TRANSACTION_CAP, TargetStepProduct, TokenId, VOCAB, different_token, mtp, observe, row_matches, }; use crate::qwen_forward::mtp_decode::MtpVerifiedWindow; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/first_seed_reuse_enabled.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/first_seed_reuse_enabled.rs index 16afe095..b5aff2b2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/first_seed_reuse_enabled.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/first_seed_reuse_enabled.rs @@ -3,9 +3,9 @@ //! adaptive expert policy and no numerical observer active. The seed already fills slot zero, so the bounds change //! speculative work only; verification and accepted-prefix limits are unchanged. -use super::{Error, MoeWeightCache, MtpWindowError, Result}; #[cfg(all(test, target_arch = "x86_64"))] use super::batch_gpu; +use super::{Error, MoeWeightCache, MtpWindowError, Result}; // Only the selected adaptive policy, with numerical observer paths unchanged. pub(super) fn first_seed_reuse_enabled(cache: &MoeWeightCache<'_>) -> bool { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder.rs index e7f5b514..54ebfb97 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder.rs @@ -1,6 +1,8 @@ //! The methods of `MtpDecoder` that run a window: the batched window (with its plan), the scalar window and the //! draft warm-up. Separate from `mtp_decode`, which holds the decoder itself. +#[cfg(all(test, target_arch = "x86_64"))] +use super::batch_gpu; use super::{ DenseWeightCache, Dimension, DraftHeadOwners, Error, KnownNext, ModelBinding, MoeWeightCache, MtpDecoder, MtpInput, MtpSession, MtpVerifiedWindow, MtpWindowError, MtpWindowRequest, MtpWindowSpec, OutputStage, Position, @@ -8,10 +10,8 @@ use super::{ VerificationSource, WindowCaches, WindowOwners, first_seed_reuse_enabled, kv_prefill_host_charge, mtp, needed_draft_predictions, reserve, window_limit, window_stage_error, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::batch_gpu; -mod batched_window_plan; mod batched_window; +mod batched_window_plan; mod draft_warm_and_window; mod scalar_window; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/batched_window_plan.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/batched_window_plan.rs index 98b16cc6..5bb0dbe1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/batched_window_plan.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/batched_window_plan.rs @@ -1,12 +1,12 @@ //! The plan, the context and the head of one batched MTP window. Separate from `batched_window`, which runs the //! window, so that what a window is made of reads apart from how it runs. +#[cfg(all(test, target_arch = "x86_64"))] +use super::batch_gpu; use super::{ DenseWeightCache, Error, ModelBinding, MoeWeightCache, MtpInput, MtpWindowError, MtpWindowRequest, MtpWindowSpec, OutputStage, Result, TargetStepProduct, TokenId, mtp, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::batch_gpu; use crate::qwen_forward::mtp::{MtpCheckpoint, RetainedFirstSeed}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/fixed_workspace/fixed_workspace_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/fixed_workspace/fixed_workspace_gpu.rs index 378fdfa5..7b7d6d9e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/fixed_workspace/fixed_workspace_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/fixed_workspace/fixed_workspace_gpu.rs @@ -3,14 +3,14 @@ //! cleanly. use super::super::mtp_expert_transport::{ExpertWeights, FixedReference, SelectedRoute, fixed_reference}; +#[cfg(test)] +use super::Observations; +#[cfg(all(test, target_arch = "x86_64"))] +use super::ObservedOutput; use super::{ ALLOCATED_BYTES, CHARGES, Cell, Context, DeviceBuffer, Error, ExpertInputs, FF, FixedBuffers, K, N, Rc, Result, Role, Slot, Transport, at, compose, compose_inner, download, moe_driver_error, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::ObservedOutput; -#[cfg(test)] -use super::Observations; use leleka_cuda_driver::Driver; const BANK_BYTES: usize = 707_788_800; const BLOB_BYTES: usize = 1_382_400; @@ -47,9 +47,7 @@ fn bank_fixture() -> Vec { bank } fn fill_blob(blob: &mut [u8], expert: usize) { - for (rows, columns, codes, scales, chunks) in - [(1280, 640, 0, 1_228_800, 40), (2560, 160, 819_200, 1_331_200, 10)] - { + for (rows, columns, codes, scales, chunks) in [(1280, 640, 0, 1_228_800, 40), (2560, 160, 819_200, 1_331_200, 10)] { fill_blob_matrix(blob, expert, &BlobMatrix { rows, columns, codes, scales, chunks }); } } @@ -185,12 +183,8 @@ impl<'ctx> Rig<'ctx> { .produce(Role::RoutedGu(0, IDS[0]), |inputs, out| { let input = leleka_cuda_driver::MtpQuantizedInput { values: at(inputs, q)?, scales: at(inputs, scales)? }; - ctx.mtp_s2_gate_up_full( - leleka_cuda_driver::MtpS2SelectedExpert { bank, expert: IDS[0] }, - input, - out, - ) - .map_err(moe_driver_error) + ctx.mtp_s2_gate_up_full(leleka_cuda_driver::MtpS2SelectedExpert { bank, expert: IDS[0] }, input, out) + .map_err(moe_driver_error) }) .unwrap(); assert_eq!(t.validate(&gu, Role::RoutedGu(1, IDS[1])).err(), Some(Error::IdentityMismatch)); @@ -199,12 +193,7 @@ impl<'ctx> Rig<'ctx> { assert_eq!(t.finish::<()>(Err(Error::IdentityMismatch)), Err(Error::IdentityMismatch)); } // Late actual expert GU nonfinite: both original and fixed must refuse. - fn refuse_late_nonfinite( - &mut self, - storage: &mut FixedBuffers<'ctx>, - corpus: &mut [u8], - mixed: &[f32], - ) -> usize { + fn refuse_late_nonfinite(&mut self, storage: &mut FixedBuffers<'ctx>, corpus: &mut [u8], mixed: &[f32]) -> usize { let at = IDS[9] as usize * BLOB_BYTES + 1_228_800 + (1279 * 40 + 39) * 2; let saved: [u8; 2] = corpus[at..at + 2].try_into().unwrap(); corpus[at..at + 2].copy_from_slice(&0x7c00u16.to_le_bytes()); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/fixed_workspace/role.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/fixed_workspace/role.rs index 44c02fc0..213d4123 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/fixed_workspace/role.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/fixed_workspace/role.rs @@ -3,12 +3,12 @@ //! Also runs the original FP32-scale quantizers, whose completed scales are inspected before any grouped dot uses //! them. +#[cfg(test)] +use super::K; use super::{ Cell, DEVICE_PEAK, DeviceBuffer, Error, FF, Finite, FixedBuffers, N, Rc, Result, Role, Slot, Transport, at, download, moe_driver_error, preflight, validate_values, }; -#[cfg(test)] -use super::K; impl Role { pub(super) fn slot(self) -> Slot { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/fixed_workspace/transport_drop.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/fixed_workspace/transport_drop.rs index 2c100937..47c14348 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/fixed_workspace/transport_drop.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/fixed_workspace/transport_drop.rs @@ -2,13 +2,13 @@ //! scaled by its scalar), the packed routed Downs and the final combine in router slot order. Also releases every //! leased buffer when a transport drops; the first failure stops before any later expert runs. +#[cfg(test)] +use super::download; use super::{ CHARGES, Cell, DenseFormat, DeviceBuffer, Error, ExpertInputs, FF, Finite, FixedBuffers, K, N, Packed, ProjectionKind, ProjectionSpec, QuantizedIndices, Rc, Result, Role, RouteSlot, Slot, Transport, moe_driver_error, preflight, validate_route, validate_values, }; -#[cfg(test)] -use super::download; impl Drop for Transport<'_, '_> { fn drop(&mut self) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/mtp_expert_transport/mtp_expert_transport_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/mtp_expert_transport/mtp_expert_transport_gpu.rs index c02d7bfb..4ac9e14c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/mtp_expert_transport/mtp_expert_transport_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/mtp_expert_transport/mtp_expert_transport_gpu.rs @@ -1,13 +1,13 @@ //! New lossless MTP expert transport proof, not an S2 arithmetic requalification. #![cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use super::super::super::qsa_index::{allocate, download_bytes, release, upload}; +#[cfg(test)] +use super::compose_observed; use super::{ Cell, Context, DEVICE_PEAK, DenseFormat, DeviceBuffer, Error, ExpertWeights, FF, K, N, Packed, ProjectionKind, ProjectionSpec, Rc, Result, Role, RoutedExpert, SelectedRoute, Transport, compose, download, routed, shared, shared_project, }; -#[cfg(test)] -use super::compose_observed; use leleka_cuda_driver::Driver; const BANK_BYTES: usize = 707_788_800; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/mtp_expert_transport/mtp_expert_transport_gpu/exact.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/mtp_expert_transport/mtp_expert_transport_gpu/exact.rs index e08d9cd4..80bafc0f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/mtp_expert_transport/mtp_expert_transport_gpu/exact.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/mtp_expert_transport/mtp_expert_transport_gpu/exact.rs @@ -2,13 +2,13 @@ //! Builds a synthetic expert bank, runs each routed expert and the shared expert through the original stages with //! every stage read back, and checks the retained transport matches that baseline bit for bit. +#[cfg(test)] +use super::compose_observed; use super::{ BANK_BYTES, BLOB_BYTES, Cell, Context, DenseFormat, DeviceBuffer, Env, Error, ExpertWeights, FF, IDS, N, Original, ProjectionKind, ProjectionSpec, ROUTE, Result, Role, SelectedRoute, allocate, download, download_bytes, release, upload, }; -#[cfg(test)] -use super::compose_observed; pub(super) fn exact(a: &[f32], b: &[f32]) { assert_eq!(a.len(), b.len()); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/mtp_expert_transport/shared_project.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/mtp_expert_transport/shared_project.rs index b6041e1a..b0e2acae 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/mtp_expert_transport/shared_project.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/mtp_expert_transport/shared_project.rs @@ -2,16 +2,16 @@ //! the routed Downs packed in slot order, and the weighted combine. Entry points `compose` and `compose_observed` run //! a whole block; the first failure stops before any later expert runs. -use super::{ - Cell, Context, DenseFormat, DeviceBuffer, Error, FF, Finite, K, N, Packed, ProjectionKind, ProjectionSpec, Rc, - Result, Role, RoutedExpert, Transport, at, moe_driver_error, preflight, routed, validate_route, validate_values, -}; #[cfg(all(test, target_arch = "x86_64"))] use super::FixedReference; #[cfg(test)] use super::ObservedOutput; #[cfg(test)] use super::download; +use super::{ + Cell, Context, DenseFormat, DeviceBuffer, Error, FF, Finite, K, N, Packed, ProjectionKind, ProjectionSpec, Rc, + Result, Role, RoutedExpert, Transport, at, moe_driver_error, preflight, routed, validate_route, validate_values, +}; pub(super) fn shared_project( transport: &mut Transport<'_>, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config/tests.rs index e5a50f94..d27eb645 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config/tests.rs @@ -1,13 +1,13 @@ //! Pins the Mode17 values derived for the Original serve path: pack expert bank and footprint switches, blob sizes, //! rope theta scale, MTP policies, sampler path flags, request parameter mapping and the geometry and prefill carve. +#[cfg(test)] +use super::legacy_footprint_from; use super::{ Error, ExpertBlobSizes, OriginalMtpGrVariant, RopeConstants, SamplerPath, driver_sampler_params, greedy_params, legacy_footprint, mtp_full_policy, mtp_pack_experts_needed, mtp_scalar_policy, prefill_layout_options, sampler_path, verify_geometry, }; -#[cfg(test)] -use super::legacy_footprint_from; #[test] fn the_pack_expert_bank_is_needed_only_without_an_rt_directory() { // pack-driven draft (no RT directory): the pack's experts are the draft layer's experts diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/draft_completion.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/draft_completion.rs index dece4ef9..b33b630e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/draft_completion.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/draft_completion.rs @@ -7,5 +7,5 @@ use super::{ TargetSeedRow, }; -mod spec_engine_for_serve_engine; mod serve_engine_draft_commit; +mod spec_engine_for_serve_engine; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host.rs index 56c0b7b7..2b61a4f7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host.rs @@ -40,8 +40,8 @@ use super::{ use crate::model_binding::qwen4exp_input::{BoundLayerKind, ModelBinding}; use leleka_cuda_driver::{ AcceptedWindow, Context, DeviceBuffer, OriginalGpuEvent, OriginalMtpFullPolicy, OriginalNativeHeadGraphResources, - OriginalVerifier, OriginalVerifyGraphResources, OriginalVerifyQsaJournal, OriginalVerifyWindowResult, SamplerParams, - SamplerPath, + OriginalVerifier, OriginalVerifyGraphResources, OriginalVerifyQsaJournal, OriginalVerifyWindowResult, + SamplerParams, SamplerPath, }; use std::rc::Rc; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/pool_layer_trace.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/pool_layer_trace.rs index 442646fd..6adb94e2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/pool_layer_trace.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/pool_layer_trace.rs @@ -4,7 +4,7 @@ //! tasks spread over the threads and how long a task took. All times are microseconds from the publication of the //! phase; `[a,b,c,d]` is min, p50, p90, max over the threads (`task`: over the tasks). -use leleka_native_cpu_expert::{PhaseTrace, POOL_TIMING_STAGES}; +use leleka_native_cpu_expert::{POOL_TIMING_STAGES, PhaseTrace}; /// What the engine knows about the group the pool just computed. pub(super) struct GroupTraceInfo { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/tests.rs index c5350e6b..c5a7dcf7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/tests.rs @@ -1,9 +1,9 @@ //! Pins the expert group plan: every (row, slot) pair planned once with experts in first-use order, masked GPU //! entries left out but still validated, bad router output refused, and scatter offsets of each output slot. -use super::{Error, ExpertJob, HIDDEN, TOP_K, output_offset, plan_experts_where, scatter, selection}; #[cfg(test)] use super::plan_experts; +use super::{Error, ExpertJob, HIDDEN, TOP_K, output_offset, plan_experts_where, scatter, selection}; fn ids(rows: &[[i32; TOP_K]]) -> Vec { rows.iter().flatten().copied().collect() diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_request.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_request.rs index 48ec360a..07c84687 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_request.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_request.rs @@ -10,9 +10,9 @@ use super::{contract::Error, original_serve_engine::ServeOutcome, original_spec_controller::SpecError}; use leleka_cuda_driver::{SamplerParams, SamplerPath}; -pub(crate) use leleka_engine_core::request::{Admission, original_stop_tokens}; #[cfg(test)] pub(crate) use leleka_engine_core::request::ENDOFTEXT_TOKEN; +pub(crate) use leleka_engine_core::request::{Admission, original_stop_tokens}; /// How a request ended when it did not complete, over this stack's forward error. pub(crate) type ServeError = leleka_engine_core::request::ServeError; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs index 0f01bbbd..f4515ec8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs @@ -286,21 +286,21 @@ mod split_group_pcie; #[cfg(test)] use split_group_pcie::adapt_decay; use split_group_pcie::adapt_tuning; -pub(in crate::qwen_forward) use split_group_pcie::{choose_swaps, choose_swaps_by}; #[cfg(test)] use split_group_pcie::choose_swaps_reference; pub(in crate::qwen_forward) use split_group_pcie::pcie_locked_only; pub(in crate::qwen_forward) use split_group_pcie::split_group_pcie; pub(in crate::qwen_forward) use split_group_pcie::{PcieSplitPolicy, RoutedGroup}; +pub(in crate::qwen_forward) use split_group_pcie::{choose_swaps, choose_swaps_by}; mod cross_layer_potential; mod swap_tie_order; pub(in crate::qwen_forward) use swap_tie_order::TieOrder; mod strata_pcie_auto; use strata_pcie_auto::StrataPcieAuto; mod pcie_auto_on_window_pool; +mod span_cache_and_pcie_lag; #[cfg(test)] mod strata_pcie_auto_tests; -mod span_cache_and_pcie_lag; use span_cache_and_pcie_lag::span_cache_enabled; mod source_spans; pub(super) use source_spans::source_spans; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/open_tier.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/open_tier.rs index 4c659764..4293ca74 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/open_tier.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/open_tier.rs @@ -1,13 +1,13 @@ //! Functions: `open_tier`, `fill_and_pin`, `read_profile`, `warn_decode_headroom` and 15 more. //! Split out of `original_serve_residency` to keep its files under the line limit. -use super::{ - LOAN_FLOOR, VANILLA_FREE_FLOOR_MIB, VERIFIER_ASSEMBLY_MIB, Context, Error, ExpertTierConfig, ModelBinding, - MoeWeightCache, OriginalCacheOptions, OriginalExpertCache, OriginalRankedExperts, Rc, ResidentExpertBankSpan, - Result, SpanCache, driver_error, original_cache_startup, span_cache_enabled, -}; #[cfg(not(target_os = "linux"))] use super::MappedExpertBank; +use super::{ + Context, Error, ExpertTierConfig, LOAN_FLOOR, ModelBinding, MoeWeightCache, OriginalCacheOptions, + OriginalExpertCache, OriginalRankedExperts, Rc, ResidentExpertBankSpan, Result, SpanCache, VANILLA_FREE_FLOOR_MIB, + VERIFIER_ASSEMBLY_MIB, driver_error, original_cache_startup, span_cache_enabled, +}; use leleka_cuda_driver::RefillBatchOptions; /// generate.cpp startup of the tier for the serve stack: size and open the cache after every other owner, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/conversation/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/conversation/tests.rs index e7617ff2..eb7f65a1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/conversation/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/conversation/tests.rs @@ -1,5 +1,4 @@ -//! Pins the serve conversation policy over a fake stack: a continuing request resumes at its last turn, a settled -//! session continues live, cancel and failure keep or drop checkpoints, the chain is bounded and reread mode works. +//! Pins the serve conversation policy over a fake stack: resume, settle, cancel, failure, bounded chain, reread. use super::{ConversationConfig, Error, PromptOptions, RequestStart, ResumeDevice, ServeConversation, TURN_TOKEN}; use crate::backend::original_prompt::{PlanLimits, PromptPath, PromptPlan, ResumePoint}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods.rs index ad95b9d4..58ca4811 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods.rs @@ -33,9 +33,10 @@ mod executor_opening; use executor_opening::ExecutorOpening; mod open_phase_steps; use open_phase_steps::{ - Policies, Weights, check_open, load_weights, loan_ladder, log_open_inventory, open_executor, open_expert_cache, - open_prefix, serve_policies, share_rt_dense_roles, + Policies, Weights, check_open, load_weights, open_executor, serve_policies, share_rt_dense_roles, }; +mod open_cache_steps; +use open_cache_steps::{loan_ladder, log_open_inventory, open_expert_cache, open_prefix}; mod serve_request_step; use serve_request_step::{ServeEnv, serve_over_host}; mod original_serve_stack_decode_phase; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods/open_cache_steps.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods/open_cache_steps.rs new file mode 100644 index 00000000..a37918c3 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods/open_cache_steps.rs @@ -0,0 +1,157 @@ +//! The caches `open` sizes from what the host has: the cross-session prefix cache (budget from the memory governor), +//! the VRAM expert tier with its loan ladder, and the governor's startup inventory log. + +use super::{ + Context, LOAN_TIER_ROWS, LoanTier, ModelBinding, MoeWeightCache, OriginalExpertCache, PARKED_BYTES_PER_TOKEN, + PARKED_STATE_ESTIMATE, PINNED_MODEL, PrefillLayoutOptions, PrefixServe, ServeFailure, StackBlock, StackConfig, + StackState, at, operator_note, original_serve_residency, prefill_bytes, +}; + +/// The cross-session prefix cache of the config, sized from the memory governor's budget; `None` when it is off or has +/// no budget. +pub(super) fn open_prefix(config: &StackConfig) -> Option> { + let prefix_config = config.prefix.as_ref()?; + let available = crate::conversation::memory::available_memory(); + // the budget comes from the memory governor (what is left above the floors), not from an independent default + let complement_pending = (config.expert_tier.resident_budget_gib.max(0.0) * (1u64 << 30) as f64) as u64; + let bytes = crate::memory_governor::resolve_prefix_budget(prefix_config.budget, available, complement_pending) + .unwrap_or_else(|| prefix_config.resolve_budget(available)); + let mut prefix_config = prefix_config.clone(); + if let Some(g) = leleka_memory::Governor::global() { + // stop admitting before anything has to be shed: soft floor + reserve (the real CRM session sat 4.4 GiB above + // a 3 GiB floor) + prefix_config.memory_floor = prefix_config.memory_floor.max(g.policy().admit_floor()); + } + let prefix_config = &prefix_config; + if bytes == 0 { + operator_note(&format!( + "prefix cache off (budget {:?}, available host memory {:?} MiB)", + prefix_config.budget, + available.map(|b| b >> 20) + )); + return None; + } + let identity = format!("qwen4exp:{PINNED_MODEL}:kv={:?}:resident={}", config.kv_format, config.kv_resident); + let clock = config.clock.clone(); + let serve = PrefixServe::new(prefix_config.clone(), config.capacity, bytes, &identity).with_clock(clock); + note_prefix_on(&serve, bytes, available); + Some(serve) +} + +fn note_prefix_on(serve: &PrefixServe, bytes: u64, available: Option) { + operator_note(&format!( + "prefix cache on: block/grid {} tokens, budget {} MiB, state ~{} MiB + {} B per token, \ + host memory available {:?} MiB, namespace {}", + serve.block_tokens(), + bytes >> 20, + PARKED_STATE_ESTIMATE >> 20, + PARKED_BYTES_PER_TOKEN, + available.map(|b| b >> 20), + crate::prefix_cache::summary::hex(serve.namespace()) + )); +} + +/// The VRAM expert tier and the number of its last slots the prompt path borrows (`None`: it allocates its own +/// buffers). +pub(super) fn open_expert_cache<'ctx>( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + moe: &MoeWeightCache<'ctx>, + config: &StackConfig, + layout: PrefillLayoutOptions, +) -> std::result::Result<(Option>, Option), ServeFailure> { + let mut loan = None; + let tier_open = staged!( + "expert tier (VRAM slots + profile fill)", + context, + original_serve_residency::open_tier(binding, context, moe, &config.expert_tier, config.capacity) + .map_err(at("expert tier"))? + ); + let expert_cache = match tier_open { + Some((cache, filled)) => { + if config.expert_tier.prefill_borrow && config.expert_tier.profile.is_some() { + loan = + original_serve_residency::loan_slots(&cache, prefill_bytes(layout).map_err(at("prefill bytes"))?) + .map_err(at("expert-cache loan"))?; + } + note_expert_cache(&cache, filled, loan); + note_tier_adaptation(&config.expert_tier); + Some(cache) + } + None => None, + }; + Ok((expert_cache, loan)) +} + +/// The tier's adaptation settings on the operator log (an A/B arm that sets them can show the engine got them). +fn note_tier_adaptation(tier: &original_serve_residency::ExpertTierConfig) { + operator_note(&format!( + "expert tier adaptation: every {} rounds, up to {} swaps", + tier.adapt_every, tier.adapt_swaps + )); +} + +fn note_expert_cache(cache: &OriginalExpertCache<'_>, filled: usize, loan: Option) { + operator_note(&format!( + "expert cache {} slots ({:.2} GiB, {}), {filled} filled from the profile; the prompt path {}; \ + GPU experts round differently from the CPU's (bench/results/2026-09-27-cache-parity)", + cache.slots(), + cache.bytes() as f64 / f64::from(1u32 << 30), + if cache.per_layer_admission() { "per layer" } else { "global" }, + match loan { + Some(k) => format!("borrows its last {k} slots"), + None => "allocates its own buffers".to_owned(), + } + )); +} + +/// Smaller loans for smaller chunks (`LELEKA_PREFILL_LOAN_TIERS=1`), ascending by rows; empty when the ladder is off. +pub(super) fn loan_ladder( + config: &StackConfig, + layout: PrefillLayoutOptions, + loan: Option, + expert_cache: Option<&OriginalExpertCache<'_>>, +) -> std::result::Result, ServeFailure> { + let mut loan_tiers: Vec = Vec::new(); + if let (Some(full), Some(cache), true) = (loan, expert_cache, config.loan_tiers) { + for rows in LOAN_TIER_ROWS.into_iter().filter(|&r| r < config.capacity) { + let tier_layout = PrefillLayoutOptions { capacity: rows, ..layout }; + let slots = original_serve_residency::loan_slots( + cache, + prefill_bytes(tier_layout).map_err(at("prefill bytes (tier)"))?, + ) + .map_err(at("expert-cache loan (tier)"))?; + if let Some(slots) = slots.filter(|&s| s < full && loan_tiers.last().is_none_or(|t| s > t.slots)) { + loan_tiers.push(LoanTier { rows, layout: tier_layout, slots }); + } + } + if !loan_tiers.is_empty() { + note_loan_ladder(&loan_tiers, full, config.capacity); + } + } + Ok(loan_tiers) +} + +fn note_loan_ladder(loan_tiers: &[LoanTier], full: usize, capacity: usize) { + operator_note(&format!( + "prompt loan ladder: {}, up to {capacity} rows {full} slots", + loan_tiers.iter().map(|t| format!("up to {} rows {} slots", t.rows, t.slots)).collect::>().join(", ") + )); +} + +/// The governor's startup log: the inventory of allocation classes and the load ledger. +pub(super) fn log_open_inventory() { + if let Some(governor) = leleka_memory::Governor::global() { + governor.log(&format!( + "stack open; inventory of allocation classes (accounted by their owners): +{}", + governor.inventory().table() + )); + governor.log(&format!( + "load ledger (measured: kernel and driver deltas per opening step): +{}", + governor.ledger().table() + )); + governor.publish(); + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods/open_phase_steps.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods/open_phase_steps.rs index 48b42a19..cd6af9b2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods/open_phase_steps.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods/open_phase_steps.rs @@ -1,15 +1,12 @@ //! The steps of `OriginalServeStack::open`: check the model shape, resolve the policies, load the weights (KAR, //! embedding), in the order `open` runs them. Each step keeps its stage marks, notes and error context. -// Stays a glob on purpose: the file is at the 400-line limit and the explicit list would put it over. use super::{ Context, DenseWeightCache, DraftAttachmentTables, DraftAttachmentTarget, Error, ExecutorOpening, ExecutorSizing, - ExecutorTarget, KarPleCache, LOAN_TIER_ROWS, LoanTier, ModelBinding, MoeWeightCache, NativeHeadDispatch, - OriginalExpertCache, OriginalMtpFullOwner, OriginalNativeOutput, OriginalPromptEmbedding, OriginalPromptExecutor, - OriginalServeSettings, OriginalSpecController, PARKED_BYTES_PER_TOKEN, PARKED_STATE_ESTIMATE, PINNED_MODEL, - PrefillLayoutOptions, PrefixServe, PromptWeights, QwenSession, Rc, RtMtpLoad, ServeFailure, StackBlock, - StackConfig, StackState, VOCABULARY, at, dbg_el, failure, operator_note, original_serve_residency, prefill_bytes, - vram_note, + ExecutorTarget, KarPleCache, ModelBinding, MoeWeightCache, NativeHeadDispatch, OriginalMtpFullOwner, + OriginalNativeOutput, OriginalPromptEmbedding, OriginalPromptExecutor, OriginalServeSettings, + OriginalSpecController, PrefillLayoutOptions, PromptWeights, QwenSession, Rc, RtMtpLoad, ServeFailure, StackConfig, + VOCABULARY, at, dbg_el, failure, operator_note, vram_note, }; use crate::qwen_forward::session::original_prompt::draft::OriginalDraftSession; @@ -256,152 +253,3 @@ pub(super) fn share_rt_dense_roles<'ctx>( } Ok(()) } - -/// The cross-session prefix cache of the config, sized from the memory governor's budget; `None` when it is off or has -/// no budget. -pub(super) fn open_prefix(config: &StackConfig) -> Option> { - let prefix_config = config.prefix.as_ref()?; - let available = crate::conversation::memory::available_memory(); - // the budget comes from the memory governor (what is left above the floors), not from an independent default - let complement_pending = (config.expert_tier.resident_budget_gib.max(0.0) * (1u64 << 30) as f64) as u64; - let bytes = crate::memory_governor::resolve_prefix_budget(prefix_config.budget, available, complement_pending) - .unwrap_or_else(|| prefix_config.resolve_budget(available)); - let mut prefix_config = prefix_config.clone(); - if let Some(g) = leleka_memory::Governor::global() { - // stop admitting before anything has to be shed: soft floor + reserve (the real CRM session sat 4.4 GiB above - // a 3 GiB floor) - prefix_config.memory_floor = prefix_config.memory_floor.max(g.policy().admit_floor()); - } - let prefix_config = &prefix_config; - if bytes == 0 { - operator_note(&format!( - "prefix cache off (budget {:?}, available host memory {:?} MiB)", - prefix_config.budget, - available.map(|b| b >> 20) - )); - return None; - } - let identity = format!("qwen4exp:{PINNED_MODEL}:kv={:?}:resident={}", config.kv_format, config.kv_resident); - let clock = config.clock.clone(); - let serve = PrefixServe::new(prefix_config.clone(), config.capacity, bytes, &identity).with_clock(clock); - note_prefix_on(&serve, bytes, available); - Some(serve) -} - -fn note_prefix_on(serve: &PrefixServe, bytes: u64, available: Option) { - operator_note(&format!( - "prefix cache on: block/grid {} tokens, budget {} MiB, state ~{} MiB + {} B per token, \ - host memory available {:?} MiB, namespace {}", - serve.block_tokens(), - bytes >> 20, - PARKED_STATE_ESTIMATE >> 20, - PARKED_BYTES_PER_TOKEN, - available.map(|b| b >> 20), - crate::prefix_cache::summary::hex(serve.namespace()) - )); -} - -/// The VRAM expert tier and the number of its last slots the prompt path borrows (`None`: it allocates its own -/// buffers). -pub(super) fn open_expert_cache<'ctx>( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - moe: &MoeWeightCache<'ctx>, - config: &StackConfig, - layout: PrefillLayoutOptions, -) -> std::result::Result<(Option>, Option), ServeFailure> { - let mut loan = None; - let tier_open = staged!( - "expert tier (VRAM slots + profile fill)", - context, - original_serve_residency::open_tier(binding, context, moe, &config.expert_tier, config.capacity) - .map_err(at("expert tier"))? - ); - let expert_cache = match tier_open { - Some((cache, filled)) => { - if config.expert_tier.prefill_borrow && config.expert_tier.profile.is_some() { - loan = - original_serve_residency::loan_slots(&cache, prefill_bytes(layout).map_err(at("prefill bytes"))?) - .map_err(at("expert-cache loan"))?; - } - note_expert_cache(&cache, filled, loan); - note_tier_adaptation(&config.expert_tier); - Some(cache) - } - None => None, - }; - Ok((expert_cache, loan)) -} - -/// The tier's adaptation settings on the operator log (an A/B arm that sets them can show the engine got them). -fn note_tier_adaptation(tier: &original_serve_residency::ExpertTierConfig) { - operator_note(&format!( - "expert tier adaptation: every {} rounds, up to {} swaps", - tier.adapt_every, tier.adapt_swaps - )); -} - -fn note_expert_cache(cache: &OriginalExpertCache<'_>, filled: usize, loan: Option) { - operator_note(&format!( - "expert cache {} slots ({:.2} GiB, {}), {filled} filled from the profile; the prompt path {}; \ - GPU experts round differently from the CPU's (bench/results/2026-09-27-cache-parity)", - cache.slots(), - cache.bytes() as f64 / f64::from(1u32 << 30), - if cache.per_layer_admission() { "per layer" } else { "global" }, - match loan { - Some(k) => format!("borrows its last {k} slots"), - None => "allocates its own buffers".to_owned(), - } - )); -} - -/// Smaller loans for smaller chunks (`LELEKA_PREFILL_LOAN_TIERS=1`), ascending by rows; empty when the ladder is off. -pub(super) fn loan_ladder( - config: &StackConfig, - layout: PrefillLayoutOptions, - loan: Option, - expert_cache: Option<&OriginalExpertCache<'_>>, -) -> std::result::Result, ServeFailure> { - let mut loan_tiers: Vec = Vec::new(); - if let (Some(full), Some(cache), true) = (loan, expert_cache, config.loan_tiers) { - for rows in LOAN_TIER_ROWS.into_iter().filter(|&r| r < config.capacity) { - let tier_layout = PrefillLayoutOptions { capacity: rows, ..layout }; - let slots = original_serve_residency::loan_slots( - cache, - prefill_bytes(tier_layout).map_err(at("prefill bytes (tier)"))?, - ) - .map_err(at("expert-cache loan (tier)"))?; - if let Some(slots) = slots.filter(|&s| s < full && loan_tiers.last().is_none_or(|t| s > t.slots)) { - loan_tiers.push(LoanTier { rows, layout: tier_layout, slots }); - } - } - if !loan_tiers.is_empty() { - note_loan_ladder(&loan_tiers, full, config.capacity); - } - } - Ok(loan_tiers) -} - -fn note_loan_ladder(loan_tiers: &[LoanTier], full: usize, capacity: usize) { - operator_note(&format!( - "prompt loan ladder: {}, up to {capacity} rows {full} slots", - loan_tiers.iter().map(|t| format!("up to {} rows {} slots", t.rows, t.slots)).collect::>().join(", ") - )); -} - -/// The governor's startup log: the inventory of allocation classes and the load ledger. -pub(super) fn log_open_inventory() { - if let Some(governor) = leleka_memory::Governor::global() { - governor.log(&format!( - "stack open; inventory of allocation classes (accounted by their owners): -{}", - governor.inventory().table() - )); - governor.log(&format!( - "load ledger (measured: kernel and driver deltas per opening step): -{}", - governor.ledger().table() - )); - governor.publish(); - } -} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests.rs index 4b26e395..c447f0a2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests.rs @@ -3,8 +3,8 @@ use super::super::original_spec_draft::{DraftPick, FirstSeedPoint, OriginalFirstDraftEngine, TargetSeedRow}; use super::{ - AdaptiveConfig, DraftPreparation, DraftSampling, Error, NanGuard, OriginalDraftEngine, OriginalSpecController, OriginalSpecEngine, - Result, SpecConfig, SpecError, SpecWindow, + AdaptiveConfig, DraftPreparation, DraftSampling, Error, NanGuard, OriginalDraftEngine, OriginalSpecController, + OriginalSpecEngine, Result, SpecConfig, SpecError, SpecWindow, }; mod golden; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/config_rejects_out_of_range.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/config_rejects_out_of_range.rs index d3224760..f9ee0902 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/config_rejects_out_of_range.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/config_rejects_out_of_range.rs @@ -3,8 +3,8 @@ //! drafter. use super::{ - AdaptiveConfig, EndRunSetup, Error, Fake, NanGuard, OriginalSpecController, SpecConfig, SpecWindow, VOCAB, begin, config, drive, - expected, prompt, run_to_the_end, + AdaptiveConfig, EndRunSetup, Error, Fake, NanGuard, OriginalSpecController, SpecConfig, SpecWindow, VOCAB, begin, + config, drive, expected, prompt, run_to_the_end, }; #[test] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output/output_stage_test_replay.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output/output_stage_test_replay.rs index 023dcf37..aeab5ce9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output/output_stage_test_replay.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output/output_stage_test_replay.rs @@ -1,13 +1,13 @@ //! Test-only replay hooks of OutputStage (record logits of a reset or prefix replay, count compact completions) and //! the shared helpers of the stage: greedy pick, activation and logit encoding, weight-owner check and error mapping. +#[cfg(test)] +use super::OutputStage; use super::{ ACTIVATION_BYTES, BindingIdentity, Dimension, EMBEDDING, Error, FiniteF32, FiniteLogits, HeadGreedySelection, LOGIT_BYTES, LogitValues, OUTPUT_WEIGHT_BYTES, OutputBindingError, OutputWeights, Result, Stage, TokenId, VOCABULARY, }; -#[cfg(test)] -use super::OutputStage; // The real ignored reset test opts in explicitly. Other test callers retain // no extra values; production builds have neither this storage nor a reader. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention.rs index 90e5ec92..6a0580b1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention.rs @@ -100,8 +100,8 @@ pub(super) struct NativePromptAttentionBatch<'source, 'lease, 'ctx> { provider: Rc, } -mod qsa_ready; mod decode_selected_cached; +mod qsa_ready; use decode_selected_cached::SelectedKvBytes; use decode_selected_cached::attend_retained; use decode_selected_cached::attention_driver_error; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/context.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/context.rs index 46505962..a8c3655e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/context.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/context.rs @@ -2,14 +2,14 @@ //! layer's KV pages, pooled index keys and tail at a position), with their equality, extent and gather checks. //! Also the serving context size and the device headroom a QSA step requires. -use super::{ - BindingIdentity, Directory, Error, KV, LayerId, PackedKv, Position, QsaOwner, QsaPrior, Rc, Result, Stage, State, - reserve, validate_half, validate_ids, validate_values, -}; #[cfg(all(test, target_arch = "x86_64"))] use super::OracleQsaParts; #[cfg(test)] use super::PAGE; +use super::{ + BindingIdentity, Directory, Error, KV, LayerId, PackedKv, Position, QsaOwner, QsaPrior, Rc, Result, Stage, State, + reserve, validate_half, validate_ids, validate_values, +}; /// The serving context in cells (262144 unless configured; see `contract::serving_cells`). pub(super) fn context() -> usize { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_resident.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_resident.rs index e49029f6..3a7d26da 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_resident.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_resident.rs @@ -1,13 +1,13 @@ //! Actor-owned bounded index-key mirror; host QsaPrior remains canonical. //! Only exact immutable parent identity permits incremental device publication. +#[cfg(all(test, target_arch = "x86_64"))] +use super::combined_qsa_observer; use super::{ BindingIdentity, BlockQuery, Context, DeviceBuffer, Error, QsaPrior, QsaSelectionRequest, Rc, Result, admit_budget, context, device_peak, driver_error, reserve, select_with_keys, validate_values, }; #[cfg(test)] use super::{Directory, KvPage, LayerId, PAGE, Position, QsaOwner, State, TokenLayer}; -#[cfg(all(test, target_arch = "x86_64"))] -use super::combined_qsa_observer; #[cfg(test)] use super::{KV, QsaPending, select}; use std::cell::Cell; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_resident/max_rows.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_resident/max_rows.rs index e784d4c2..1536ddc7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_resident/max_rows.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/index_resident/max_rows.rs @@ -2,13 +2,13 @@ //! that brings it from one `QsaPrior` to its successor: reload, append one pooled row, or change only the spare row. //! Reset, replay and speculative branches are misses. A layer's mirror is allocated on its first selection. +#[cfg(all(test, target_arch = "x86_64"))] +use super::combined_qsa_observer; use super::{ BindingIdentity, BlockQuery, Cell, Context, Entry, Error, QsaIndexKeyCache, QsaPrior, QsaSelectionRequest, ROW_BYTES, Rc, Result, Update, admit_budget, context, device_peak, driver_error, reserve, select_with_keys, validate_values, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::combined_qsa_observer; /// Pooled key rows of the serving context (`65537` at 262144 cells). pub(super) fn max_rows() -> usize { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/qsa_index_stage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/qsa_index_stage.rs index baaa73bf..8940076d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/qsa_index_stage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/qsa_index_stage.rs @@ -2,14 +2,14 @@ //! Projects the host rows or the native prompt row, then builds the next prior as a pending candidate that is //! published only at token commit. Admission checks the binding, layer, position and residual input first. +#[cfg(all(test, target_arch = "x86_64"))] +use super::combined_qsa_observer; use super::{ Context, DenseWeightCache, DeviceBuffer, Error, GrRole, LayerId, ModelBinding, Norm, Position, ProjectionSources, QGate, QsaIndexStage, QsaLayerProjection, QsaMatrixRole, QsaPending, QsaPrepareRequest, QsaPrepared, QsaPrior, QsaSelectionRequest, QsaWeights, QwenStepTxn, Rc, ResidualReady, Result, admit_budget, append, binding_error, context, norm, pack, project_input, rope, select, split, validate_ids, validate_values, }; -#[cfg(all(test, target_arch = "x86_64"))] -use super::combined_qsa_observer; use crate::qwen_forward::prompt_device_rows::PromptWeights; use crate::qwen_forward::q6_attention_columns::{ColumnKey, RowAdmission}; use crate::qwen_forward::qsa_prefill_batch::AttentionRow; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/original_prompt.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/original_prompt.rs index 2718068b..92c6c426 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/original_prompt.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/original_prompt.rs @@ -7,9 +7,9 @@ use super::super::qsa_index::prompt_device::resident_device::{ ParkedLayerSpan, ParkedPrefix, ResidentQsaLayer, ResidentQsaOwners, ResidentQsaPrior, ResidentQsaSeal, SpanExport, }; use super::{ - BindingIdentity, Context, Dimension, Error, GdnPrior, GrRole, InputReady, LayerId, ModelBinding, PlePrior, Position, - QsaIndexPrior, QsaOwner, QwenSession, QwenStepTxn, Rc, Result, STATE_CAPACITY, Stage, TargetStepOrigin, TokenId, - TokenLayer, + BindingIdentity, Context, Dimension, Error, GdnPrior, GrRole, InputReady, LayerId, ModelBinding, PlePrior, + Position, QsaIndexPrior, QsaOwner, QwenSession, QwenStepTxn, Rc, Result, STATE_CAPACITY, Stage, TargetStepOrigin, + TokenId, TokenLayer, }; use std::cell::{Cell, RefCell}; pub(in crate::qwen_forward) mod draft; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/tests.rs index e5e06d4b..56ff33ff 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/tests.rs @@ -2,8 +2,8 @@ //! the PLE, GDN and QSA priors keep their exact identity (child modules); the helpers build tokens and positions. use super::{ - Error, GdnOwner, GdnPending, GdnPrior, InputReady, LayerId, PleOwner, PlePending, PlePrior, Position, QsaIndexPrior, - QsaOwner, QwenSession, Rc, Stage, TokenId, TokenLayer, + Error, GdnOwner, GdnPending, GdnPrior, InputReady, LayerId, PleOwner, PlePending, PlePrior, Position, + QsaIndexPrior, QsaOwner, QwenSession, Rc, Stage, TokenId, TokenLayer, }; use crate::model_binding::qwen4exp_input::BindingIdentity; use crate::qwen_forward::contract::Dimension;