STRA-338 S5a: split backend.rs into responsibility-named child modules
backend.rs (3797 lines) becomes a 258-line parent that keeps the imports, the
#[path] children (original serve, measurement, prompt, GPU proofs) and the two
policy test modules, plus backend/{config, spawn, spawn_optimized, spawn_original,
sources, proxy, owner, load, validate, digests, probes, request, session, generate,
generate_mtp, utf8, errors, tests}.rs. Every public path stays: the children are
re-exported with `use child::*`, so leleka_runtime::backend::* and crate::backend::*
resolve as before, and the code that used `super::name` from the #[path] children
still finds its names.
Items moved verbatim by the lexer-based item parser of scripts/dev/rustsplit; only
visibility changed (pub(super) on moved private items, struct fields and inherent
methods) and the new files were run through rustfmt. Two lints of the moved code
(a needless borrow of `config` in serve_load, a useless `.into()` in the context
admission error) were removed; both are value-neutral.
Test ids: 689 before, 690 after (the one added is the digest golden test of the
previous commit); the same 2 tests fail before and after in this WSL setup
(model_binding::qwen4exp_input::mtp::backing, unrelated), 58 ignored both times.
cargo check --all-targets -p leleka-runtime -p leleka-deploy: same warning counts
(runtime lib 80, lib test 64), none in backend files.
Architecture gate: the baseline entry of backend.rs (3770) is replaced by one for the
new child backend/load.rs (1170 lines). load.rs holds serve_load unchanged and is
decomposed in the S5b commits that follow, which remove the entry again. The 8
remaining gate errors are not from this change (deploy file sizes, backend_original_serve.rs,
env-read ratchet 261 vs 256, all introduced by the kar-off-ab integration).
This commit is contained in:
@@ -84,7 +84,7 @@
|
||||
"crates/igpu/src/lib.rs": 1386,
|
||||
"crates/igpu/src/shaders.rs": 440,
|
||||
"crates/leleka-memory/src/lock.rs": 432,
|
||||
"crates/leleka-runtime/src/backend.rs": 3770,
|
||||
"crates/leleka-runtime/src/backend/load.rs": 1170,
|
||||
"crates/leleka-runtime/src/backend_original_serve.rs": 1115,
|
||||
"crates/leleka-runtime/src/conversation/cache/tests.rs": 407,
|
||||
"crates/leleka-runtime/src/conversation/manager_tests.rs": 1129,
|
||||
|
||||
+151
-3693
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,131 @@
|
||||
//! Pinned model identity, resource limits and the operator-facing configuration types of the CUDA owner.
|
||||
use super::*;
|
||||
|
||||
pub(super) const SHARD0: &str =
|
||||
"sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3";
|
||||
pub(super) const SHARD1: &str =
|
||||
"sha256:316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113";
|
||||
// SHA256(raw32 shard0 digest || raw32 shard1 digest), independently computed.
|
||||
pub(super) const MODEL_DIGEST: &str =
|
||||
"sha256:80d5e3333801cedbca81a5c19c24ed6bb48fd56977acd190318f66b23a1766a3";
|
||||
// SHA256 of the newline-terminated profile declaration documented below.
|
||||
// leleka-native-v1\nmodel=<MODEL_DIGEST without prefix>\nqsa=fp16\nmtp=none\ngreedy=ordered-finite-logits\n
|
||||
pub(super) const MODE_DIGEST: &str =
|
||||
"sha256:82b774f9c0daaf4290ae96b079224efea7da49dae74770cb32db3da69e4e3eb5";
|
||||
pub(super) const KAR_PROFILE: &str = "qwen-iq3-s-l2-v4-ple";
|
||||
pub(super) const NATIVE_MTP_PROFILE: &str = "qwen4exp-native-mtp-v1";
|
||||
pub(super) const KAR_MTP_PROFILE: &str = "qwen4exp-kar-ple-mtp-v1";
|
||||
pub(super) const INTEGER_WINDOWED_EXECUTION: &str =
|
||||
"experimental-native-integer-iq3-native-down-windowed256-retained-gr-native-t1";
|
||||
pub(super) const PROMPT_LIMIT: usize = 1024 * 1024;
|
||||
pub(super) const FRAME_LIMIT: usize = 64 * 1024;
|
||||
pub(super) const OUTPUT_LIMIT: u32 = leleka_backend_api::MAX_OUTPUT_TOKENS;
|
||||
pub(super) const QUEUE: usize = 16;
|
||||
pub(super) const REPLY_TIMEOUT: Duration = Duration::from_secs(1200);
|
||||
/// A reconfigure reopens the serve stack (about 25 s on the server; the weights stay loaded).
|
||||
/// A reconfigure is reopening the serve stack (one engine per process): new generations are refused, retryable, meanwhile.
|
||||
pub(super) static RECONFIGURING: AtomicBool = AtomicBool::new(false);
|
||||
pub(super) const RECONFIGURE_TIMEOUT: Duration = Duration::from_secs(900);
|
||||
// Explicit KAR/MTP files require private copies and complete pinned admission
|
||||
// after the base GGUF hashes. Their cold physical load has a separate finite
|
||||
// budget; ordinary controls and Native stay unchanged.
|
||||
pub(super) const KAR_LOAD_REPLY_TIMEOUT: Duration = Duration::from_secs(7200);
|
||||
pub(super) const BACKPRESSURE_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
pub(super) const GENERATION_TIMEOUT: Duration = Duration::from_secs(24 * 60 * 60);
|
||||
pub(super) static INSTANCE: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// Operator-owned files must remain immutable until explicit unload.
|
||||
pub struct NativeBackendConfig {
|
||||
pub shard0: PathBuf,
|
||||
pub shard1: PathBuf,
|
||||
pub gpu_device_ordinal: u32,
|
||||
pub gpu_budget_bytes: u64,
|
||||
pub context_tokens: u32,
|
||||
/// Local archive and private staging parent; never sourced from RPCs.
|
||||
pub kar_ple_source: Option<(PathBuf, PathBuf)>,
|
||||
/// Explicit presealed operator handle; mutually exclusive with kar_ple_source.
|
||||
pub kar_ple_inherited: Option<InheritedKarArchive>,
|
||||
/// Fixed draft pack and its private staging parent, operator supplied only.
|
||||
pub mtp_source: Option<(PathBuf, PathBuf)>,
|
||||
/// Optional KAR archive (+overlay) that supplies the routed experts at a
|
||||
/// runtime level 2..=5 instead of the GGUF/MMQ expert path. Operator
|
||||
/// supplied and SHA-256 pinned; exclusive with the optimized owners.
|
||||
pub kar_expert_source: Option<KarExpertSourceConfig>,
|
||||
/// EXPERIMENTAL Strata modes (Q4_0 / K8V4 / rotated KV, keyless V-only, KV streaming, control vectors).
|
||||
/// `Default` is all-off and changes nothing; an enabled mode is admitted, digest-mixed and probed, and is
|
||||
/// refused at Load until the forward pass consumes it (`experimental::FORWARD_CONSUMER_WIRED`).
|
||||
pub experimental: ExperimentalConfig,
|
||||
}
|
||||
|
||||
/// Operator-owned immutable metadata; no file path or policy enters RPCs.
|
||||
pub struct RankedExpertProfileSource {
|
||||
pub path: PathBuf,
|
||||
pub sha256: String,
|
||||
}
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum OptimizedOwnerPolicy {
|
||||
Original,
|
||||
QueuedOwners,
|
||||
StreamedSpill,
|
||||
RetainedScratch,
|
||||
ResidentOwners,
|
||||
AdaptiveSlots,
|
||||
}
|
||||
pub(super) struct OptimizedBackendConfig {
|
||||
pub(super) ranked_profile: Option<RankedExpertProfileSource>,
|
||||
pub(super) policy: OptimizedOwnerPolicy,
|
||||
}
|
||||
pub(super) struct OwnerExecution {
|
||||
pub(super) kind: EvaluationExecution,
|
||||
pub(super) optimized: Option<OptimizedBackendConfig>,
|
||||
/// The Original verified-window serve path (`backend_original_serve.rs`); exclusive with `optimized`.
|
||||
pub(super) original: Option<original_serve::OriginalServeOptions>,
|
||||
}
|
||||
pub(super) const OPTIMIZED_EXECUTION: &str =
|
||||
"experimental-iq3-integer-window256-mtp-selected-qsa-router-shared-tail-indexed-lru-v1";
|
||||
pub(super) const QUEUED_OWNERS_EXECUTION: &str = "experimental-iq3-integer-window256-mtp-selected-qsa-router-shared-tail-indexed-lru-pinned-profile-queued-input-compact-head-gr-batch-v1";
|
||||
pub(super) const ADAPTIVE_SLOTS_EXECUTION: &str = "experimental-iq3-window256-mtp-strata-adapt4-96-shared192-cpu-miss-event-refill-gdn-journal-incremental-prompt-gpu-seed-singleton-original-group16-v6";
|
||||
pub(super) const RESIDENT_OWNERS_EXECUTION: &str = "experimental-iq3-window256-mtp-learned-main-shared192-gdn-device-journal-incremental-capture-original-v2";
|
||||
pub(super) const RETAINED_SCRATCH_EXECUTION: &str =
|
||||
"experimental-iq3-window256-mtp-streamed-spill-retained-gdn-qk-qsa-attention-v1";
|
||||
pub(super) const STREAMED_SPILL_EXECUTION: &str = "experimental-iq3-window256-mtp-queued-input-compact-head-gr-batch-digest-capture-spill-floor-1gib-v1";
|
||||
pub(super) const ORIGINAL_SERVE_EXECUTION: &str =
|
||||
"experimental-original-mode17-verified-window-batched-prefill-mtp-cpu-expert-tier-v1";
|
||||
pub(super) const RANKED_EXPERT_PROFILE_SHA: &str =
|
||||
"8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf";
|
||||
pub(super) const RANKED_EXPERT_PROFILE_BYTES: usize = 196632;
|
||||
|
||||
/// Provenance only: this descriptor does not attest a successful load.
|
||||
pub fn pinned_model_descriptor() -> ModelDescriptor {
|
||||
ModelDescriptor {
|
||||
family: "qwen4exp".into(),
|
||||
architecture: "qwen4exp".into(),
|
||||
artifact_digest: MODEL_DIGEST.into(),
|
||||
weight_format: "gguf:iq3_s".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum EvaluationExecution {
|
||||
Native,
|
||||
ExperimentalResidentMmq,
|
||||
ExperimentalNativeResidentMmq,
|
||||
ExperimentalNativeIntegerIq3Mmq,
|
||||
ExperimentalWindowed256RetainedGr,
|
||||
ExperimentalNativeIntegerIq3Windowed256RetainedGr,
|
||||
}
|
||||
impl EvaluationExecution {
|
||||
pub(super) fn prefill_tile_cap(self) -> usize {
|
||||
match self {
|
||||
Self::ExperimentalWindowed256RetainedGr
|
||||
| Self::ExperimentalNativeIntegerIq3Windowed256RetainedGr => 256,
|
||||
_ => 64,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Validated sampling plan of a request: `None` keeps the ordinary greedy path
|
||||
/// (temperature 0 and no penalty), `Some` carries the Original `SamplerParams` for
|
||||
/// the host sampler. `entropy` seeds requests that carry no seed (Original `seed = 0`).
|
||||
/// The CUDA ordinal of the loaded device, for the telemetry sampler (NVML indexes the same physical order).
|
||||
pub(crate) static GPU_ORDINAL: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
@@ -0,0 +1,290 @@
|
||||
//! Identity digests of the mode a load publishes (mode, execution policy, KAR expert source).
|
||||
use super::*;
|
||||
|
||||
pub(super) fn selected_bound_mode(
|
||||
binding: &ModelBinding,
|
||||
mode: &InferenceMode,
|
||||
) -> Result<(InferenceMode, String), BackendError> {
|
||||
let (base, base_digest) = bound_mode(binding);
|
||||
match mode {
|
||||
InferenceMode::ExperimentalMtp { profile_id } => {
|
||||
if requires_kar(mode) != matches!(base, InferenceMode::ExperimentalKarPle { .. }) {
|
||||
return Err(invalid("MTP input provider mismatch"));
|
||||
}
|
||||
let pins = binding
|
||||
.mtp_pack_identity()
|
||||
.map_err(|_| invalid("MTP pack identity absent"))?;
|
||||
Ok((
|
||||
mode.clone(),
|
||||
mtp_mode_digest(&base_digest, profile_id, pins),
|
||||
))
|
||||
}
|
||||
_ => Ok((base, base_digest)),
|
||||
}
|
||||
}
|
||||
pub(super) fn optimized_execution_digest(
|
||||
bound_digest: &str,
|
||||
ranked_profile: Option<&str>,
|
||||
) -> String {
|
||||
let mut digest = Sha256::new();
|
||||
for field in [
|
||||
"leleka-optimized-execution-v2",
|
||||
"bounded-resident-raw-expert-source-52gib-headroom8gib-v1",
|
||||
"complete-routed-gpu-finite-guard-v1",
|
||||
bound_digest,
|
||||
OPTIMIZED_EXECUTION,
|
||||
if ranked_profile.is_some() {
|
||||
"ranked-pinned-prefix-bounded-spill-v1"
|
||||
} else {
|
||||
"original-matrix-lru-index-v1"
|
||||
},
|
||||
ranked_profile.unwrap_or("none"),
|
||||
] {
|
||||
digest.update(field.as_bytes());
|
||||
digest.update(b"\n");
|
||||
}
|
||||
let mut result = String::from("sha256:");
|
||||
for value in digest.finalize() {
|
||||
use std::fmt::Write;
|
||||
let _ = write!(result, "{value:02x}");
|
||||
}
|
||||
result
|
||||
}
|
||||
// Fixed actor policy and profile identity; no caller-controlled mode field.
|
||||
pub(super) fn queued_owners_execution_digest(bound_digest: &str, ranked_profile: &str) -> String {
|
||||
let mut digest = Sha256::new();
|
||||
for field in [
|
||||
"leleka-optimized-queued-owners-execution-v1",
|
||||
"bounded-resident-raw-expert-source-52gib-headroom8gib-v1",
|
||||
"complete-routed-gpu-finite-guard-v1",
|
||||
bound_digest,
|
||||
QUEUED_OWNERS_EXECUTION,
|
||||
"ranked-pinned-prefix-bounded-spill-v1",
|
||||
ranked_profile,
|
||||
"compact-head-finite-greedy-v1",
|
||||
"gr-batch-inject-t1-t3-v1",
|
||||
"mtp-admitted-input-prefix-v1",
|
||||
] {
|
||||
digest.update(field.as_bytes());
|
||||
digest.update(b"\n");
|
||||
}
|
||||
let mut result = String::from("sha256:");
|
||||
for value in digest.finalize() {
|
||||
use std::fmt::Write;
|
||||
let _ = write!(result, "{value:02x}");
|
||||
}
|
||||
result
|
||||
}
|
||||
pub(super) fn adaptive_slots_execution_digest(bound_digest: &str, ranked_profile: &str) -> String {
|
||||
let mut digest = Sha256::new();
|
||||
for field in [
|
||||
"leleka-strata-adaptive-slots-v6-original-group16-prompt",
|
||||
&retained_scratch_execution_digest(bound_digest, ranked_profile),
|
||||
ADAPTIVE_SLOTS_EXECUTION,
|
||||
"adapt4-max96-gain1.5-decay0.7-whole-raw-triplet-event-completed",
|
||||
"shared192-raw24g-reserve128m-three-allocations-all-host-bank",
|
||||
"prompt-all-used-nonresident-gpu-ascending-expert-id-single16-real-whole-triplets",
|
||||
"verification-private-first-occurrence-last-floor-nmiss-times141-div256-single16-owner-real-whole-triplets",
|
||||
"first-window-real-current-source-seed-reuse-coupled-target-draft-rollback",
|
||||
"adaptive-final-singleton-joint-chunk-fresh-tail-one-shortens-prior-tile-final-pair",
|
||||
"ephemeral-host16m-actual-preparation-owned-capacities-and-metadata",
|
||||
"whole-output-t1-to64-four-roles-256owners37273600-plus-working-reserve128m",
|
||||
"request-host512m-cpu48m-ephemeral16m-real-dynamic-prefix-and-journal-charge",
|
||||
"native-cpu-original-3cf03257-upto8-rows-concurrent-owned-jobs",
|
||||
"model-pool160m-source52g-real8g-headroom-request16jobs48m-outer64-native-qsa-ledger",
|
||||
"gdn-journal18350596-all36-accepted-prefix-replay-t3-host512m",
|
||||
"original-moe-prompt-gu1280-group16-down2560-actual-maxr-tile-streamk-bounds-d4-down20-42",
|
||||
"original-mmq-group-bank-explicit-admitted-model-prompt-capacity1-to8192",
|
||||
"native-qsa-page4-int8-clock-original-decode-fastmath-norm256-rope-text",
|
||||
"original-fused-gdn-t1-native-bf16-conv-ab-stepnorm-precise",
|
||||
"incremental-capacity52g-pretouch-future-plus8g-full-sha-index-before-publication",
|
||||
] {
|
||||
digest.update(field.as_bytes());
|
||||
digest.update(b"\n");
|
||||
}
|
||||
let mut result = String::from("sha256:");
|
||||
for value in digest.finalize() {
|
||||
use std::fmt::Write;
|
||||
let _ = write!(result, "{value:02x}");
|
||||
}
|
||||
result
|
||||
}
|
||||
pub(super) fn resident_owners_execution_digest(bound_digest: &str, ranked_profile: &str) -> String {
|
||||
let mut digest = Sha256::new();
|
||||
for field in [
|
||||
"leleka-resident-owners-v2-original-prompt",
|
||||
&retained_scratch_execution_digest(bound_digest, ranked_profile),
|
||||
RESIDENT_OWNERS_EXECUTION,
|
||||
"shared192-main-lru24g-preload-floor1g-reserve128m-metadata16m",
|
||||
"gdn-journal18350596-all36-accepted-prefix-replay-t3-host512m",
|
||||
"original-moe-prompt-gu1280-group16-down2560-actual-maxr-tile-streamk-bounds-d4-down20-42",
|
||||
"original-mmq-group-bank-explicit-admitted-model-prompt-capacity1-to8192",
|
||||
"native-qsa-page4-int8-clock-original-decode-fastmath-norm256-rope-text",
|
||||
"original-fused-gdn-t1-native-bf16-conv-ab-stepnorm-precise",
|
||||
"incremental-capacity52g-pretouch-future-plus8g-full-sha-index-before-publication",
|
||||
] {
|
||||
digest.update(field.as_bytes());
|
||||
digest.update(b"\n");
|
||||
}
|
||||
let mut result = String::from("sha256:");
|
||||
for value in digest.finalize() {
|
||||
use std::fmt::Write;
|
||||
let _ = write!(result, "{value:02x}");
|
||||
}
|
||||
result
|
||||
}
|
||||
pub(super) fn retained_scratch_execution_digest(
|
||||
bound_digest: &str,
|
||||
ranked_profile: &str,
|
||||
) -> String {
|
||||
let mut digest = Sha256::new();
|
||||
for field in [
|
||||
"leleka-retained-gdn-qk-qsa-scratch-v1",
|
||||
&streamed_spill_execution_digest(bound_digest, ranked_profile),
|
||||
RETAINED_SCRATCH_EXECUTION,
|
||||
"whole-qk40960-tail6144-positive-zero-fullfinite-v1",
|
||||
"qsa-five-actual-owners108544-three-fullfinite-v1",
|
||||
"eager149504-before-profile-128mib-guard-v1",
|
||||
] {
|
||||
digest.update(field.as_bytes());
|
||||
digest.update(b"\n");
|
||||
}
|
||||
let mut result = String::from("sha256:");
|
||||
for value in digest.finalize() {
|
||||
use std::fmt::Write;
|
||||
let _ = write!(result, "{value:02x}");
|
||||
}
|
||||
result
|
||||
}
|
||||
pub(super) fn streamed_spill_execution_digest(bound_digest: &str, ranked_profile: &str) -> String {
|
||||
let mut digest = Sha256::new();
|
||||
for field in [
|
||||
"leleka-streamed-spill-queued-owners-execution-v1",
|
||||
bound_digest,
|
||||
STREAMED_SPILL_EXECUTION,
|
||||
"same-fd-full-sha-opaque-capture-adopt-v1",
|
||||
"bounded-resident-raw-expert-source-52gib-headroom8gib-v1",
|
||||
"complete-routed-gpu-finite-guard-v1",
|
||||
"ranked-prefix-spill-floor-1073741824-v1",
|
||||
ranked_profile,
|
||||
"compact-head-finite-greedy-v1",
|
||||
"gr-batch-inject-t1-t3-v1",
|
||||
"mtp-admitted-input-prefix-v1",
|
||||
] {
|
||||
digest.update(field.as_bytes());
|
||||
digest.update(b"\n");
|
||||
}
|
||||
let mut result = String::from("sha256:");
|
||||
for value in digest.finalize() {
|
||||
use std::fmt::Write;
|
||||
let _ = write!(result, "{value:02x}");
|
||||
}
|
||||
result
|
||||
}
|
||||
pub(super) fn original_serve_execution_digest(bound_digest: &str) -> String {
|
||||
let mut digest = Sha256::new();
|
||||
for field in [
|
||||
"leleka-original-serve-execution-v1",
|
||||
bound_digest,
|
||||
ORIGINAL_SERVE_EXECUTION,
|
||||
"original-generate-cpp-mode17-spec4-suffix3-verify-t6-mtp-t4",
|
||||
"original-batched-prefill-fused-gr-high-only-bf16-mixed-force-batched",
|
||||
"native-verifier-window-gdn-journal-qsa-journal-accepted-prefix-commit",
|
||||
"routed-experts-all-cpu-tier-empty-gpu-plan",
|
||||
"request-reset-to-empty-prompt-no-conversation-cache",
|
||||
] {
|
||||
digest.update(field.as_bytes());
|
||||
digest.update(b"\n");
|
||||
}
|
||||
let mut result = String::from("sha256:");
|
||||
for value in digest.finalize() {
|
||||
use std::fmt::Write;
|
||||
let _ = write!(result, "{value:02x}");
|
||||
}
|
||||
result
|
||||
}
|
||||
pub(super) fn kar_expert_mode_digest(bound_digest: &str, identity: &[u8; 32]) -> String {
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(b"leleka-kar-expert-mode-v1\n");
|
||||
digest.update(bound_digest.as_bytes());
|
||||
digest.update(b"\n");
|
||||
digest.update(identity);
|
||||
let mut result = String::from("sha256:");
|
||||
for value in digest.finalize() {
|
||||
use std::fmt::Write;
|
||||
let _ = write!(result, "{value:02x}");
|
||||
}
|
||||
result
|
||||
}
|
||||
pub(super) fn execution_mode_digest(bound_digest: &str) -> String {
|
||||
let mut digest = Sha256::new();
|
||||
for field in [
|
||||
"leleka-execution-v1",
|
||||
bound_digest,
|
||||
INTEGER_WINDOWED_EXECUTION,
|
||||
] {
|
||||
digest.update(field.as_bytes());
|
||||
digest.update(b"\n");
|
||||
}
|
||||
let mut result = String::from("sha256:");
|
||||
for value in digest.finalize() {
|
||||
use std::fmt::Write;
|
||||
let _ = write!(result, "{value:02x}");
|
||||
}
|
||||
result
|
||||
}
|
||||
pub(super) fn mtp_mode_digest(base: &str, profile: &str, pins: [&str; 3]) -> String {
|
||||
let mut digest = Sha256::new();
|
||||
for field in [
|
||||
"leleka-mtp-v1",
|
||||
base,
|
||||
profile,
|
||||
"depth=4",
|
||||
"attention=fp16-dense",
|
||||
"experts=s2-greedy",
|
||||
]
|
||||
.into_iter()
|
||||
.chain(pins)
|
||||
{
|
||||
digest.update(field.as_bytes());
|
||||
digest.update(b"\n");
|
||||
}
|
||||
let mut result = String::from("sha256:");
|
||||
for value in digest.finalize() {
|
||||
use std::fmt::Write;
|
||||
let _ = write!(result, "{value:02x}");
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
// The mode identity binds actual verified archive/profile bytes and the native
|
||||
// FP16-QSA/no-MTP implementation, independently of the requested mode label.
|
||||
pub(super) fn bound_mode(binding: &ModelBinding) -> (InferenceMode, String) {
|
||||
match binding.kar_ple_binding() {
|
||||
None => (InferenceMode::Native, MODE_DIGEST.into()),
|
||||
Some(provider) => (
|
||||
InferenceMode::ExperimentalKarPle {
|
||||
profile_id: KAR_PROFILE.into(),
|
||||
},
|
||||
kar_mode_digest(provider.archive_digest(), provider.profile_digest()),
|
||||
),
|
||||
}
|
||||
}
|
||||
pub(super) fn kar_mode_digest(archive: &[u8; 32], profile: &[u8; 32]) -> String {
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(b"leleka-kar-ple-v1\n");
|
||||
digest.update(MODE_DIGEST.as_bytes());
|
||||
digest.update(b"\n");
|
||||
digest.update(KAR_PROFILE.as_bytes());
|
||||
digest.update(b"\n");
|
||||
digest.update(archive);
|
||||
digest.update(profile);
|
||||
let bytes = digest.finalize();
|
||||
let mut result = String::with_capacity(71);
|
||||
result.push_str("sha256:");
|
||||
for value in bytes {
|
||||
use std::fmt::Write;
|
||||
let _ = write!(result, "{value:02x}");
|
||||
}
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//! Constructors of the fixed `BackendError` refusals.
|
||||
use super::*;
|
||||
|
||||
pub(super) fn error(code: ErrorCode, message: &'static str) -> BackendError {
|
||||
BackendError {
|
||||
code,
|
||||
message: message.into(),
|
||||
retryable: false,
|
||||
}
|
||||
}
|
||||
pub(super) fn invalid(message: &'static str) -> BackendError {
|
||||
error(ErrorCode::InvalidRequest, message)
|
||||
}
|
||||
pub(super) fn invalid_dynamic(message: String) -> BackendError {
|
||||
BackendError {
|
||||
code: ErrorCode::InvalidRequest,
|
||||
message,
|
||||
retryable: false,
|
||||
}
|
||||
}
|
||||
pub(super) fn unsupported_dynamic(message: String) -> BackendError {
|
||||
BackendError {
|
||||
code: ErrorCode::UnsupportedModel,
|
||||
message,
|
||||
retryable: false,
|
||||
}
|
||||
}
|
||||
pub(super) fn unsupported(message: &'static str) -> BackendError {
|
||||
error(ErrorCode::UnsupportedModel, message)
|
||||
}
|
||||
pub(super) fn exhausted(message: &'static str) -> BackendError {
|
||||
error(ErrorCode::ResourceExhausted, message)
|
||||
}
|
||||
pub(super) fn unavailable(message: &'static str) -> BackendError {
|
||||
error(ErrorCode::BackendUnavailable, message)
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
//! The single-token generation step loop.
|
||||
use super::*;
|
||||
|
||||
pub(super) struct Generation<'a, 'context, 'driver> {
|
||||
pub(super) execution: EvaluationExecution,
|
||||
pub(super) measurement: Option<&'a std::cell::RefCell<measurement::Recorder>>,
|
||||
pub(super) binding: &'a ModelBinding,
|
||||
pub(super) output: &'a OutputStage<'context, 'driver>,
|
||||
pub(super) kar_cache: Option<&'a mut KarPleCache<'context>>,
|
||||
pub(super) moe_cache: &'a mut MoeWeightCache<'context>,
|
||||
pub(super) dense_cache: &'a DenseWeightCache<'context>,
|
||||
// The cache and session share the actual actor Context lifetime. Driver
|
||||
// ownership remains separate in OutputStage; no reference is extended.
|
||||
pub(super) session: &'a mut QwenSession<'context>,
|
||||
pub(super) tokenizer: &'a Tokenizer,
|
||||
pub(super) sink: &'a GenerationSink,
|
||||
pub(super) cancel: &'a AtomicBool,
|
||||
pub(super) shared: &'a Shared,
|
||||
pub(super) context_tokens: u32,
|
||||
pub(super) eos: u32,
|
||||
pub(super) mtp: bool,
|
||||
}
|
||||
pub(super) enum GenerationFailure {
|
||||
Cancelled,
|
||||
Backend(BackendError),
|
||||
}
|
||||
impl From<BackendError> for GenerationFailure {
|
||||
fn from(error: BackendError) -> Self {
|
||||
Self::Backend(error)
|
||||
}
|
||||
}
|
||||
impl Generation<'_, '_, '_> {
|
||||
pub(super) fn observe(&self, f: impl FnOnce(&mut measurement::Recorder)) {
|
||||
if let Some(recorder) = self.measurement {
|
||||
f(&mut recorder.borrow_mut());
|
||||
}
|
||||
}
|
||||
pub(super) fn cancelled(&self) -> bool {
|
||||
self.cancel.load(Ordering::Acquire)
|
||||
|| self.shared.shutdown.load(Ordering::Acquire)
|
||||
|| self.sink.is_closed()
|
||||
}
|
||||
pub(super) fn step(&mut self, token: u32, position: usize) -> Result<u32, GenerationFailure> {
|
||||
if self.cancelled() {
|
||||
return Err(GenerationFailure::Cancelled);
|
||||
}
|
||||
let vocabulary =
|
||||
Dimension::new(248_320).map_err(|_| invalid("native vocabulary invalid"))?;
|
||||
|
||||
let token = TokenId::new(u64::from(token), vocabulary)
|
||||
.map_err(|_| invalid("native token invalid"))?;
|
||||
let position = native_position(
|
||||
self.binding.input_constants(),
|
||||
self.context_tokens,
|
||||
position,
|
||||
)?;
|
||||
let forwarded = QwenForward::step_cached(
|
||||
self.binding,
|
||||
token,
|
||||
position,
|
||||
self.session,
|
||||
self.output,
|
||||
self.kar_cache.as_deref_mut(),
|
||||
self.moe_cache,
|
||||
self.dense_cache,
|
||||
);
|
||||
let token = forwarded.map_err(|failure| {
|
||||
// Fixed enums and numeric position only; no token/prompt/path
|
||||
// diagnostics. A stderr failure cannot replace the real error.
|
||||
use std::io::Write;
|
||||
let _ = writeln!(
|
||||
std::io::stderr().lock(),
|
||||
"leleka-native phase=forward position={} error={failure:?}",
|
||||
position.get()
|
||||
);
|
||||
// A failed full step never commits its session. Keep the retained
|
||||
// owners for explicit unload, but withdraw serving readiness.
|
||||
self.shared.ready.store(false, Ordering::Release);
|
||||
match failure {
|
||||
crate::qwen_forward::contract::Error::InputAllocation => {
|
||||
exhausted("native step allocation failed")
|
||||
}
|
||||
crate::qwen_forward::contract::Error::Unsupported(_) => {
|
||||
unsupported("native forward operator unavailable")
|
||||
}
|
||||
crate::qwen_forward::contract::Error::NonFinite => error(
|
||||
ErrorCode::Internal,
|
||||
"native forward produced invalid values",
|
||||
),
|
||||
_ => unavailable("native forward failed"),
|
||||
}
|
||||
})?;
|
||||
if self.cancelled() {
|
||||
return Err(GenerationFailure::Cancelled);
|
||||
}
|
||||
Ok(token.get())
|
||||
}
|
||||
pub(super) fn mtp_error(
|
||||
&self,
|
||||
failure: crate::qwen_forward::contract::Error,
|
||||
) -> GenerationFailure {
|
||||
use crate::qwen_forward::contract::Error;
|
||||
#[cfg(test)]
|
||||
eprintln!("PUBLIC MTP contract failure={failure:?}");
|
||||
self.shared.ready.store(false, Ordering::Release);
|
||||
let error = match failure {
|
||||
Error::InputAllocation => exhausted("MTP allocation failed"),
|
||||
Error::Unsupported(_) => unsupported("MTP operator unavailable"),
|
||||
Error::NonFinite => error(ErrorCode::Internal, "MTP produced invalid values"),
|
||||
_ => unavailable("MTP forward failed"),
|
||||
};
|
||||
GenerationFailure::Backend(error)
|
||||
}
|
||||
pub(super) fn target_step(
|
||||
&mut self,
|
||||
token: u32,
|
||||
position: usize,
|
||||
) -> Result<TargetStepProduct, GenerationFailure> {
|
||||
if self.cancelled() {
|
||||
return Err(GenerationFailure::Cancelled);
|
||||
}
|
||||
let token = TokenId::new(
|
||||
u64::from(token),
|
||||
Dimension::new(248320).map_err(|e| self.mtp_error(e))?,
|
||||
)
|
||||
.map_err(|e| self.mtp_error(e))?;
|
||||
let position = native_position(
|
||||
self.binding.input_constants(),
|
||||
self.context_tokens,
|
||||
position,
|
||||
)?;
|
||||
let result = QwenForward::step_for_mtp_cached(
|
||||
self.binding,
|
||||
token,
|
||||
position,
|
||||
self.session,
|
||||
self.output,
|
||||
self.kar_cache.as_deref_mut(),
|
||||
Some(self.moe_cache),
|
||||
Some(self.dense_cache),
|
||||
);
|
||||
let product = result.map_err(|e| self.mtp_error(e))?;
|
||||
if self.cancelled() {
|
||||
return Err(GenerationFailure::Cancelled);
|
||||
}
|
||||
Ok(product)
|
||||
}
|
||||
pub(super) fn prefill_tile_cap(&self) -> usize {
|
||||
#[cfg(all(
|
||||
any(target_os = "linux", target_os = "windows"),
|
||||
target_arch = "x86_64"
|
||||
))]
|
||||
// The selected native prompt admits its actual simultaneous index,
|
||||
// INT8 KV and FFN owners under the unchanged request host ceiling.
|
||||
if self.moe_cache.uses_strata_adaptive_experts() {
|
||||
return 64;
|
||||
}
|
||||
self.execution.prefill_tile_cap()
|
||||
}
|
||||
pub(super) fn prefill_chunk(
|
||||
&mut self,
|
||||
tokens: &[u32],
|
||||
position: usize,
|
||||
known_next: Option<u32>,
|
||||
draft: &mut MtpDecoder,
|
||||
started: Instant,
|
||||
) -> Result<Option<TargetStepProduct>, GenerationFailure> {
|
||||
if self.cancelled() {
|
||||
return Err(GenerationFailure::Cancelled);
|
||||
}
|
||||
if started.elapsed() > GENERATION_TIMEOUT {
|
||||
return Err(unavailable("generation deadline exceeded").into());
|
||||
}
|
||||
if tokens.is_empty() || tokens.len() > self.prefill_tile_cap() {
|
||||
return Err(invalid("invalid prefill tile").into());
|
||||
}
|
||||
let vocabulary = Dimension::new(248320).map_err(|e| self.mtp_error(e))?;
|
||||
let mut typed = Vec::new();
|
||||
typed
|
||||
.try_reserve_exact(tokens.len())
|
||||
.map_err(|_| exhausted("prefill tile allocation failed"))?;
|
||||
for (offset, &token) in tokens.iter().enumerate() {
|
||||
let actual = position
|
||||
.checked_add(offset)
|
||||
.ok_or_else(|| exhausted("MTP context exhausted"))?;
|
||||
let _ = native_position(self.binding.input_constants(), self.context_tokens, actual)?;
|
||||
typed.push(TokenId::new(u64::from(token), vocabulary).map_err(|e| self.mtp_error(e))?);
|
||||
}
|
||||
let next = known_next
|
||||
.map(|token| TokenId::new(u64::from(token), vocabulary))
|
||||
.transpose()
|
||||
.map_err(|e| self.mtp_error(e))?;
|
||||
let cancel = self.cancel;
|
||||
let shared = self.shared;
|
||||
let sink = self.sink;
|
||||
let stopped = || {
|
||||
cancel.load(Ordering::Acquire)
|
||||
|| shared.shutdown.load(Ordering::Acquire)
|
||||
|| sink.is_closed()
|
||||
|| started.elapsed() > GENERATION_TIMEOUT
|
||||
};
|
||||
// This is an incremental transaction cap, not an unbounded host pool.
|
||||
// Verified model and already committed KV/cache owners stay outside it.
|
||||
let forward = match self.execution {
|
||||
EvaluationExecution::Native => QwenForward::prefill_chunk_cached_joint,
|
||||
EvaluationExecution::ExperimentalWindowed256RetainedGr => {
|
||||
QwenForward::prefill_chunk_windowed256_retained_gr_joint
|
||||
}
|
||||
EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr => {
|
||||
QwenForward::prefill_chunk_native_integer_iq3_windowed256_retained_gr_joint
|
||||
}
|
||||
EvaluationExecution::ExperimentalResidentMmq
|
||||
| EvaluationExecution::ExperimentalNativeResidentMmq
|
||||
| EvaluationExecution::ExperimentalNativeIntegerIq3Mmq => {
|
||||
QwenForward::prefill_chunk_mmq_joint
|
||||
}
|
||||
};
|
||||
let host_remaining = draft
|
||||
.prefill_host_remaining(512 * 1024 * 1024)
|
||||
.map_err(|e| self.mtp_error(e))?;
|
||||
let result = forward(
|
||||
self.binding,
|
||||
&typed,
|
||||
next,
|
||||
self.session,
|
||||
draft,
|
||||
self.output,
|
||||
self.kar_cache.as_deref_mut(),
|
||||
self.moe_cache,
|
||||
self.dense_cache,
|
||||
host_remaining,
|
||||
stopped,
|
||||
);
|
||||
let product = match result {
|
||||
Err(crate::qwen_forward::contract::Error::Unsupported(
|
||||
crate::qwen_forward::contract::Stage::Executor,
|
||||
)) if stopped() => {
|
||||
if started.elapsed() > GENERATION_TIMEOUT {
|
||||
return Err(unavailable("generation deadline exceeded").into());
|
||||
}
|
||||
return Err(GenerationFailure::Cancelled);
|
||||
}
|
||||
other => other.map_err(|e| self.mtp_error(e))?,
|
||||
};
|
||||
if self.cancelled() {
|
||||
return Err(GenerationFailure::Cancelled);
|
||||
}
|
||||
Ok(product)
|
||||
}
|
||||
pub(super) fn emit(&self, event: GenerationEvent) -> Result<(), GenerationFailure> {
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
if self.cancelled() {
|
||||
return Err(GenerationFailure::Cancelled);
|
||||
}
|
||||
match self.sink.try_emit(event.clone()) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(ContractError::GenerationBackpressure)
|
||||
if start.elapsed() < BACKPRESSURE_TIMEOUT =>
|
||||
{
|
||||
thread::sleep(Duration::from_millis(5))
|
||||
}
|
||||
Err(ContractError::GenerationClosed) => return Err(GenerationFailure::Cancelled),
|
||||
_ => {
|
||||
return Err(
|
||||
exhausted("generation output backpressure deadline exceeded").into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn generate(
|
||||
mut run: Generation<'_, '_, '_>,
|
||||
prompt: &[u32],
|
||||
max: u32,
|
||||
) -> Result<(FinishReason, Usage), GenerationFailure> {
|
||||
if run.mtp {
|
||||
return generate_mtp(run, prompt, max);
|
||||
}
|
||||
let start = Instant::now();
|
||||
let mut next = 0;
|
||||
for (position, &token) in prompt.iter().enumerate() {
|
||||
if start.elapsed() > GENERATION_TIMEOUT {
|
||||
return Err(unavailable("generation deadline exceeded").into());
|
||||
}
|
||||
next = run.step(token, position)?;
|
||||
}
|
||||
run.observe(|r| r.prefilled());
|
||||
let mut utf8 = Utf8Pending::default();
|
||||
let mut count = 0;
|
||||
for index in 0..max {
|
||||
if start.elapsed() > GENERATION_TIMEOUT {
|
||||
return Err(unavailable("generation deadline exceeded").into());
|
||||
}
|
||||
if run.cancelled() {
|
||||
return Err(GenerationFailure::Cancelled);
|
||||
}
|
||||
run.observe(|r| r.token(next));
|
||||
if next == run.eos {
|
||||
utf8.finish()?;
|
||||
let usage = Usage {
|
||||
input_tokens: prompt.len() as u64,
|
||||
output_tokens: count + 1,
|
||||
reused_input_tokens: 0,
|
||||
};
|
||||
run.emit(GenerationEvent::Usage(usage.clone()))?;
|
||||
run.observe(|r| r.decoded());
|
||||
return Ok((FinishReason::Stop, usage));
|
||||
}
|
||||
let bytes = run
|
||||
.tokenizer
|
||||
.decode_bytes(&[next])
|
||||
.map_err(|_| unavailable("native token decoding failed"))?;
|
||||
if let Some(text) = utf8.push(&bytes)? {
|
||||
run.emit(GenerationEvent::TextDelta { text })?;
|
||||
}
|
||||
count += 1;
|
||||
if index + 1 < max {
|
||||
next = run.step(next, prompt.len() + index as usize)?;
|
||||
}
|
||||
}
|
||||
utf8.finish_length(|text| run.emit(GenerationEvent::TextDelta { text }))?;
|
||||
let usage = Usage {
|
||||
input_tokens: prompt.len() as u64,
|
||||
output_tokens: count,
|
||||
reused_input_tokens: 0,
|
||||
};
|
||||
run.emit(GenerationEvent::Usage(usage.clone()))?;
|
||||
run.observe(|r| r.decoded());
|
||||
Ok((FinishReason::Length, usage))
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
//! The MTP speculative generation loop.
|
||||
use super::*;
|
||||
|
||||
pub(super) fn generate_mtp(
|
||||
run: Generation<'_, '_, '_>,
|
||||
prompt: &[u32],
|
||||
max: u32,
|
||||
) -> Result<(FinishReason, Usage), GenerationFailure> {
|
||||
generate_mtp_resume(run, prompt, max, None, &mut None)
|
||||
}
|
||||
|
||||
pub(super) fn generate_mtp_resume(
|
||||
mut run: Generation<'_, '_, '_>,
|
||||
prompt: &[u32],
|
||||
max: u32,
|
||||
resume: Option<MtpContinuation>,
|
||||
publish: &mut Option<MtpContinuation>,
|
||||
) -> Result<(FinishReason, Usage), GenerationFailure> {
|
||||
*publish = None;
|
||||
let start = Instant::now();
|
||||
let (mut decoder, mut latest, reused, mut committed) = match resume {
|
||||
Some(old) => {
|
||||
if !append_compatible(&old.tokens, prompt) {
|
||||
return Err(invalid("resident MTP prefix mismatch").into());
|
||||
}
|
||||
old.decoder
|
||||
.validate_resume(run.binding, run.session, &old.product, &old.tokens)
|
||||
.map_err(|e| run.mtp_error(e))?;
|
||||
let reused = old.tokens.len();
|
||||
(old.decoder, Some(old.product), reused, old.tokens)
|
||||
}
|
||||
None => (
|
||||
if run.execution
|
||||
== EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr
|
||||
{
|
||||
MtpDecoder::new_kv_prefill(run.binding, run.session, prompt)
|
||||
} else {
|
||||
MtpDecoder::new(run.binding)
|
||||
}
|
||||
.map_err(|e| run.mtp_error(e))?,
|
||||
None,
|
||||
0,
|
||||
Vec::new(),
|
||||
),
|
||||
};
|
||||
run.observe(|r| r.retained(reused));
|
||||
let vocabulary = Dimension::new(248320).map_err(|e| run.mtp_error(e))?;
|
||||
let eos = TokenId::new(u64::from(run.eos), vocabulary).map_err(|e| run.mtp_error(e))?;
|
||||
let capacity = prompt
|
||||
.len()
|
||||
.checked_add(max as usize)
|
||||
.filter(|n| *n <= run.context_tokens as usize)
|
||||
.ok_or_else(|| exhausted("resident MTP prefix exceeds context"))?;
|
||||
committed
|
||||
.try_reserve(capacity.saturating_sub(committed.len()))
|
||||
.map_err(|_| exhausted("resident MTP prefix allocation failed"))?;
|
||||
// The retained draft ends immediately before the retained last target
|
||||
// cell. Its known-next edge must be warmed before advancing that target.
|
||||
if let Some(&next) = prompt.get(reused)
|
||||
&& let Some(product) = latest.as_ref()
|
||||
{
|
||||
if run.cancelled() {
|
||||
return Err(GenerationFailure::Cancelled);
|
||||
}
|
||||
let next = TokenId::new(u64::from(next), vocabulary).map_err(|e| run.mtp_error(e))?;
|
||||
decoder
|
||||
.warm_retained(run.binding, run.session, product, next, run.moe_cache)
|
||||
.map_err(|e| run.mtp_error(e))?;
|
||||
}
|
||||
// Each tile preserves the genuine last-known-next edge. A final tile
|
||||
// obtains its actual head product; no intermediate greedy IDs are minted.
|
||||
#[cfg(all(
|
||||
any(target_os = "linux", target_os = "windows"),
|
||||
target_arch = "x86_64"
|
||||
))]
|
||||
let adaptive_prefill = run.moe_cache.uses_strata_adaptive_experts();
|
||||
#[cfg(not(all(
|
||||
any(target_os = "linux", target_os = "windows"),
|
||||
target_arch = "x86_64"
|
||||
)))]
|
||||
let adaptive_prefill = false;
|
||||
let mut position = reused;
|
||||
while position < prompt.len() {
|
||||
if start.elapsed() > GENERATION_TIMEOUT {
|
||||
return Err(unavailable("generation deadline exceeded").into());
|
||||
}
|
||||
let mut end = position
|
||||
.saturating_add(run.prefill_tile_cap())
|
||||
.min(prompt.len());
|
||||
// Keep the last known-next edge and final head in one joint tile.
|
||||
// A completed fresh KV warmer cannot admit a second final tile.
|
||||
if adaptive_prefill && prompt.len() - end == 1 && end - position > 1 {
|
||||
end -= 1;
|
||||
}
|
||||
let next = prompt.get(end).copied();
|
||||
let product = if end - position == 1 && next.is_none() && !adaptive_prefill {
|
||||
// Other policies keep the original lone-row actual-head producer.
|
||||
Some(run.target_step(prompt[position], position)?)
|
||||
} else {
|
||||
run.prefill_chunk(&prompt[position..end], position, next, &mut decoder, start)?
|
||||
};
|
||||
if next.is_none() {
|
||||
latest = Some(product.ok_or_else(|| invalid("missing final prefill source"))?);
|
||||
} else if product.is_some() {
|
||||
return Err(invalid("unexpected intermediate prefill head").into());
|
||||
}
|
||||
committed.extend_from_slice(&prompt[position..end]);
|
||||
position = end;
|
||||
}
|
||||
let mut product = latest.ok_or_else(|| invalid("empty MTP prompt"))?;
|
||||
if reused == 0
|
||||
&& run.execution == EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr
|
||||
{
|
||||
decoder
|
||||
.finish_kv_prefill(run.binding, run.session, &product, &committed)
|
||||
.map_err(|e| run.mtp_error(e))?;
|
||||
}
|
||||
run.observe(|r| r.prefilled());
|
||||
let mut utf8 = Utf8Pending::default();
|
||||
let mut count = 0_u64;
|
||||
let reason = loop {
|
||||
if start.elapsed() > GENERATION_TIMEOUT {
|
||||
return Err(unavailable("generation deadline exceeded").into());
|
||||
}
|
||||
if run.cancelled() {
|
||||
return Err(GenerationFailure::Cancelled);
|
||||
}
|
||||
if count == u64::from(max) {
|
||||
break FinishReason::Length;
|
||||
}
|
||||
let authoritative = product
|
||||
.predicted(run.session)
|
||||
.map_err(|e| run.mtp_error(e))?;
|
||||
if authoritative == eos {
|
||||
run.observe(|r| r.token(eos.get()));
|
||||
count += 1;
|
||||
break FinishReason::Stop;
|
||||
}
|
||||
if count + 1 == u64::from(max) {
|
||||
run.observe(|r| r.token(authoritative.get()));
|
||||
// The last public token is already authoritative. As in Native,
|
||||
// no draft or unused next-position target step runs at max output.
|
||||
let bytes = run
|
||||
.tokenizer
|
||||
.decode_bytes(&[authoritative.get()])
|
||||
.map_err(|_| unavailable("MTP token decoding failed"))?;
|
||||
if let Some(text) = utf8.push(&bytes)? {
|
||||
run.emit(GenerationEvent::TextDelta { text })?;
|
||||
}
|
||||
count += 1;
|
||||
break FinishReason::Length;
|
||||
}
|
||||
// Bound the target advances by the operator's context, independently
|
||||
// of the verified model's larger Position dimension.
|
||||
let position = prompt
|
||||
.len()
|
||||
.checked_add(count as usize)
|
||||
.ok_or_else(|| exhausted("MTP context exhausted"))?;
|
||||
let _ = native_position(run.binding.input_constants(), run.context_tokens, position)?;
|
||||
let remaining =
|
||||
(max as usize - count as usize - 1).min(run.context_tokens as usize - position);
|
||||
let spec = MtpWindowSpec::new(4, remaining, Some(eos)).map_err(|e| run.mtp_error(e))?;
|
||||
let cancel = run.cancel;
|
||||
let shared = run.shared;
|
||||
let sink = run.sink;
|
||||
let window = decoder
|
||||
.window(
|
||||
run.binding,
|
||||
product,
|
||||
run.session,
|
||||
run.output,
|
||||
run.kar_cache.as_deref_mut(),
|
||||
run.moe_cache,
|
||||
run.dense_cache,
|
||||
spec,
|
||||
|| {
|
||||
cancel.load(Ordering::Acquire)
|
||||
|| shared.shutdown.load(Ordering::Acquire)
|
||||
|| sink.is_closed()
|
||||
|| start.elapsed() > GENERATION_TIMEOUT
|
||||
},
|
||||
)
|
||||
.map_err(|e| match e {
|
||||
MtpWindowError::Cancelled if start.elapsed() > GENERATION_TIMEOUT => {
|
||||
GenerationFailure::Backend(unavailable("generation deadline exceeded"))
|
||||
}
|
||||
MtpWindowError::Cancelled => GenerationFailure::Cancelled,
|
||||
MtpWindowError::Forward(error) => run.mtp_error(error),
|
||||
})?;
|
||||
{
|
||||
use std::io::Write;
|
||||
let _ = writeln!(
|
||||
std::io::stderr().lock(),
|
||||
"leleka-mtp phase=verified-window draft_steps={} accepted={}",
|
||||
window.draft_steps(),
|
||||
window.tokens().len()
|
||||
);
|
||||
}
|
||||
let draft_steps = window.draft_steps();
|
||||
let (tokens, next, stopped) = window.into_parts();
|
||||
run.observe(|r| {
|
||||
let mut ids = [0; 4];
|
||||
if tokens.len() <= ids.len() {
|
||||
for (slot, token) in ids.iter_mut().zip(&tokens) {
|
||||
*slot = token.get();
|
||||
}
|
||||
r.window(draft_steps, &ids[..tokens.len()], stopped);
|
||||
} else {
|
||||
r.window(draft_steps, &[u32::MAX; 5], stopped);
|
||||
}
|
||||
});
|
||||
if tokens.is_empty() && !stopped {
|
||||
return Err(run.mtp_error(crate::qwen_forward::contract::Error::IdentityMismatch));
|
||||
}
|
||||
for token in tokens {
|
||||
run.observe(|r| r.token(token.get()));
|
||||
committed.push(token.get());
|
||||
let bytes = run
|
||||
.tokenizer
|
||||
.decode_bytes(&[token.get()])
|
||||
.map_err(|_| unavailable("MTP token decoding failed"))?;
|
||||
if let Some(text) = utf8.push(&bytes)? {
|
||||
run.emit(GenerationEvent::TextDelta { text })?;
|
||||
}
|
||||
count += 1;
|
||||
}
|
||||
product = next;
|
||||
if count == u64::from(max) {
|
||||
break FinishReason::Length;
|
||||
}
|
||||
if stopped {
|
||||
run.observe(|r| r.token(eos.get()));
|
||||
count += 1; // Authoritative EOS, as in the ordinary mode.
|
||||
break FinishReason::Stop;
|
||||
}
|
||||
};
|
||||
if matches!(reason, FinishReason::Length) {
|
||||
utf8.finish_length(|text| run.emit(GenerationEvent::TextDelta { text }))?;
|
||||
} else {
|
||||
utf8.finish()?;
|
||||
}
|
||||
let usage = Usage {
|
||||
input_tokens: prompt.len() as u64,
|
||||
output_tokens: count,
|
||||
reused_input_tokens: reused as u64,
|
||||
};
|
||||
run.emit(GenerationEvent::Usage(usage.clone()))?;
|
||||
decoder
|
||||
.validate_resume(run.binding, run.session, &product, &committed)
|
||||
.map_err(|e| run.mtp_error(e))?;
|
||||
if run.cancelled() {
|
||||
return Err(GenerationFailure::Cancelled);
|
||||
}
|
||||
run.observe(|r| r.decoded());
|
||||
*publish = Some(MtpContinuation {
|
||||
decoder,
|
||||
product,
|
||||
tokens: committed,
|
||||
});
|
||||
Ok((reason, usage))
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,112 @@
|
||||
//! The owner thread loop and the load-failure diagnostics.
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) enum LoadPhase {
|
||||
Config,
|
||||
Selection,
|
||||
Shard0,
|
||||
Shard1,
|
||||
Artifact,
|
||||
Tokenizer,
|
||||
Eos,
|
||||
SelectedBinding,
|
||||
EffectiveMode,
|
||||
Cancellation,
|
||||
Driver,
|
||||
Device,
|
||||
Context,
|
||||
OutputHead,
|
||||
KarCache,
|
||||
MoeWeightCache,
|
||||
DenseWeightCache,
|
||||
OriginalStack,
|
||||
Identity,
|
||||
}
|
||||
|
||||
pub(super) fn load_failure(phase: LoadPhase, error: BackendError) -> BackendError {
|
||||
use std::io::Write;
|
||||
// BackendError.message is deliberately excluded from operator diagnostics.
|
||||
let _ = writeln!(
|
||||
std::io::stderr().lock(),
|
||||
"leleka-load phase={phase:?} class={:?}",
|
||||
error.code
|
||||
);
|
||||
error
|
||||
}
|
||||
pub(super) fn selected_binding_failure(error: InputBindingError) -> BackendError {
|
||||
use std::io::Write;
|
||||
let phase = LoadPhase::SelectedBinding;
|
||||
let _ = writeln!(
|
||||
std::io::stderr().lock(),
|
||||
"leleka-load phase={phase:?} class={error:?}"
|
||||
);
|
||||
invalid("selected input binding failed")
|
||||
}
|
||||
pub(super) fn load_forward_failure(
|
||||
phase: LoadPhase,
|
||||
error: crate::qwen_forward::contract::Error,
|
||||
result: BackendError,
|
||||
) -> BackendError {
|
||||
use std::io::Write;
|
||||
let _ = writeln!(
|
||||
std::io::stderr().lock(),
|
||||
"leleka-load phase={phase:?} class={error:?}"
|
||||
);
|
||||
result
|
||||
}
|
||||
|
||||
pub(super) fn owner(
|
||||
config: NativeBackendConfig,
|
||||
rx: Receiver<Command>,
|
||||
shared: &Shared,
|
||||
instance: u64,
|
||||
observer: Option<EvaluationObserver>,
|
||||
selection: OwnerExecution,
|
||||
) {
|
||||
let execution = selection.kind;
|
||||
let mut serial = 0_u64;
|
||||
while !shared.shutdown.load(Ordering::Acquire) {
|
||||
let command = match rx.recv_timeout(Duration::from_millis(100)) {
|
||||
Ok(command) => command,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => continue,
|
||||
Err(_) => break,
|
||||
};
|
||||
match command {
|
||||
Command::Load(model, requested, reply) => {
|
||||
serial = match serial.checked_add(1) {
|
||||
Some(value) => value,
|
||||
None => break,
|
||||
};
|
||||
if let Err(error) = serve_load(
|
||||
&config,
|
||||
&rx,
|
||||
shared,
|
||||
model,
|
||||
requested,
|
||||
&reply,
|
||||
(
|
||||
instance,
|
||||
serial,
|
||||
observer.as_ref(),
|
||||
execution,
|
||||
selection.optimized.as_ref(),
|
||||
selection.original.as_ref(),
|
||||
),
|
||||
) {
|
||||
let _ = reply.send(Err(error));
|
||||
}
|
||||
}
|
||||
Command::Generate(_, _, _, reply) => {
|
||||
clear_active(shared);
|
||||
let _ = reply.send(Err(invalid("no model is loaded")));
|
||||
}
|
||||
Command::Unload(_, reply) => {
|
||||
let _ = reply.send(Err(invalid("no model is loaded")));
|
||||
}
|
||||
Command::Reconfigure(_, reply) => {
|
||||
let _ = reply.send(Err(invalid("no model is loaded")));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
//! Load-time probes of the experimental and KAR level-decode PTX.
|
||||
use super::*;
|
||||
|
||||
pub(super) fn experimental_error(error: experimental_modes::ExperimentalError) -> BackendError {
|
||||
match error {
|
||||
experimental_modes::ExperimentalError::Invalid(message) => invalid(message),
|
||||
experimental_modes::ExperimentalError::Unsupported(message) => unsupported(message),
|
||||
}
|
||||
}
|
||||
#[cfg(all(
|
||||
any(target_os = "linux", target_os = "windows"),
|
||||
target_pointer_width = "64"
|
||||
))]
|
||||
pub(super) fn probe_experimental(
|
||||
context: &leleka_cuda_driver::Context<'_>,
|
||||
config: &ExperimentalConfig,
|
||||
plan: &experimental_modes::Plan,
|
||||
) -> Result<(), BackendError> {
|
||||
use leleka_cuda_driver::experimental::ExperimentalError;
|
||||
for program in &plan.programs {
|
||||
leleka_cuda_driver::experimental_gpu::Experimental::open(context, *program, &config.opt_in)
|
||||
.and_then(|opened| opened.close())
|
||||
.map_err(|error| match error {
|
||||
ExperimentalError::Unpinned(_) => unsupported("experimental PTX is not pinned"),
|
||||
ExperimentalError::NotEnabled(_) | ExperimentalError::Invalid(_) => {
|
||||
invalid("experimental program is not enabled for this configuration")
|
||||
}
|
||||
ExperimentalError::Driver(_) => unavailable("experimental program failed to load"),
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(all(
|
||||
any(target_os = "linux", target_os = "windows"),
|
||||
target_pointer_width = "64"
|
||||
)))]
|
||||
pub(super) fn probe_experimental(
|
||||
_: &leleka_cuda_driver::Context<'_>,
|
||||
_: &ExperimentalConfig,
|
||||
_: &experimental_modes::Plan,
|
||||
) -> Result<(), BackendError> {
|
||||
Err(unsupported("experimental modes require Linux CUDA"))
|
||||
}
|
||||
#[cfg(all(
|
||||
any(target_os = "linux", target_os = "windows"),
|
||||
target_pointer_width = "64"
|
||||
))]
|
||||
pub(super) fn probe_kar_level_decode(
|
||||
context: &leleka_cuda_driver::Context<'_>,
|
||||
) -> Result<(), BackendError> {
|
||||
leleka_cuda_driver::kar_decode_levels_gpu::KarDecodeLevels::open(context)
|
||||
.map(|_| ())
|
||||
.map_err(|error| match error {
|
||||
leleka_cuda_driver::kar_decode_levels::KarDecodeError::Unpinned => {
|
||||
unsupported("KAR level-decode PTX is not pinned")
|
||||
}
|
||||
_ => unavailable("KAR level-decode program failed to load"),
|
||||
})
|
||||
}
|
||||
#[cfg(not(all(
|
||||
any(target_os = "linux", target_os = "windows"),
|
||||
target_pointer_width = "64"
|
||||
)))]
|
||||
pub(super) fn probe_kar_level_decode(
|
||||
_: &leleka_cuda_driver::Context<'_>,
|
||||
) -> Result<(), BackendError> {
|
||||
Err(unsupported("KAR expert source requires Linux CUDA"))
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
//! The caller-side handle of the owner actor: shared state, commands and the `Backend` implementation.
|
||||
use super::*;
|
||||
|
||||
pub(super) struct Active {
|
||||
pub(super) id: String,
|
||||
pub(super) cancel: Arc<AtomicBool>,
|
||||
}
|
||||
pub(super) struct Shared {
|
||||
pub(super) ready: AtomicBool,
|
||||
pub(super) shutdown: AtomicBool,
|
||||
pub(super) active: Mutex<Option<Active>>,
|
||||
}
|
||||
pub(super) struct Proxy {
|
||||
pub(super) tx: SyncSender<Command>,
|
||||
pub(super) shared: Arc<Shared>,
|
||||
pub(super) seen: RecentIds,
|
||||
pub(super) kar_configured: bool,
|
||||
pub(super) mtp_configured: bool,
|
||||
pub(super) kar_experts_configured: bool,
|
||||
pub(super) kar_expert_native_digest: Option<String>,
|
||||
pub(super) execution: EvaluationExecution,
|
||||
pub(super) optimized_execution: bool,
|
||||
pub(super) queued_owners: bool,
|
||||
pub(super) streamed_spill: bool,
|
||||
pub(super) retained_scratch: bool,
|
||||
pub(super) resident_owners: bool,
|
||||
pub(super) adaptive_slots: bool,
|
||||
pub(super) original_serve: bool,
|
||||
}
|
||||
pub(super) type Reply<T> = SyncSender<Result<T, BackendError>>;
|
||||
pub(super) enum Command {
|
||||
Load(ModelDescriptor, RuntimeConfig, Reply<LoadedModel>),
|
||||
Generate(
|
||||
LoadedModel,
|
||||
GenerationRequest,
|
||||
Arc<AtomicBool>,
|
||||
Reply<GenerationStream>,
|
||||
),
|
||||
Unload(LoadedModel, Reply<()>),
|
||||
/// New inference settings as a JSON document (`serve_tuning.rs`); the reply is the effective settings.
|
||||
Reconfigure(String, Reply<String>),
|
||||
}
|
||||
impl Proxy {
|
||||
pub(super) fn idle(&self) -> Result<(), BackendError> {
|
||||
if self.shared.shutdown.load(Ordering::Acquire) {
|
||||
return Err(unavailable("native owner stopped"));
|
||||
}
|
||||
if self
|
||||
.shared
|
||||
.active
|
||||
.lock()
|
||||
.map_err(|_| unavailable("native owner state unavailable"))?
|
||||
.is_some()
|
||||
{
|
||||
return Err(exhausted("native generation is active"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn send(&self, command: Command) -> Result<(), BackendError> {
|
||||
self.tx.try_send(command).map_err(|error| match error {
|
||||
mpsc::TrySendError::Full(_) => exhausted("native control queue is full"),
|
||||
mpsc::TrySendError::Disconnected(_) => unavailable("native owner stopped"),
|
||||
})
|
||||
}
|
||||
pub(super) fn wait<T>(
|
||||
&self,
|
||||
reply: Receiver<Result<T, BackendError>>,
|
||||
) -> Result<T, BackendError> {
|
||||
self.wait_with_timeout(reply, REPLY_TIMEOUT)
|
||||
}
|
||||
pub(super) fn wait_with_timeout<T>(
|
||||
&self,
|
||||
reply: Receiver<Result<T, BackendError>>,
|
||||
timeout: Duration,
|
||||
) -> Result<T, BackendError> {
|
||||
match reply.recv_timeout(timeout) {
|
||||
Ok(result) => result,
|
||||
Err(_) => {
|
||||
// A late/uncertain operation is never retried on this owner.
|
||||
self.shared.shutdown.store(true, Ordering::Release);
|
||||
cancel_active(&self.shared);
|
||||
Err(unavailable("native operation outcome unavailable"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Backend for Proxy {
|
||||
fn identity(&self) -> BackendIdentity {
|
||||
BackendIdentity {
|
||||
name: "leleka-native".into(),
|
||||
implementation_version: if self.original_serve {
|
||||
ORIGINAL_SERVE_EXECUTION.into()
|
||||
} else if self.adaptive_slots {
|
||||
ADAPTIVE_SLOTS_EXECUTION.into()
|
||||
} else if self.resident_owners {
|
||||
RESIDENT_OWNERS_EXECUTION.into()
|
||||
} else if self.retained_scratch {
|
||||
RETAINED_SCRATCH_EXECUTION.into()
|
||||
} else if self.streamed_spill {
|
||||
STREAMED_SPILL_EXECUTION.into()
|
||||
} else if self.queued_owners {
|
||||
QUEUED_OWNERS_EXECUTION.into()
|
||||
} else if self.optimized_execution {
|
||||
OPTIMIZED_EXECUTION.into()
|
||||
} else if self.execution
|
||||
== EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr
|
||||
{
|
||||
INTEGER_WINDOWED_EXECUTION.into()
|
||||
} else {
|
||||
"0.1.0-fp16-qsa-explicit-modes".into()
|
||||
},
|
||||
api_version: BACKEND_API_VERSION,
|
||||
}
|
||||
}
|
||||
fn capabilities(&self) -> BackendCapabilities {
|
||||
let models = if self.shared.ready.load(Ordering::Acquire)
|
||||
&& !self.shared.shutdown.load(Ordering::Acquire)
|
||||
{
|
||||
vec![SupportedModelTuple {
|
||||
family: "qwen4exp".into(),
|
||||
architecture: "qwen4exp".into(),
|
||||
weight_format: "gguf:iq3_s".into(),
|
||||
}]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
BackendCapabilities {
|
||||
supported_models: models,
|
||||
max_concurrent_generations: 1,
|
||||
supports_cancellation: true,
|
||||
supports_tool_call_streaming: false,
|
||||
}
|
||||
}
|
||||
fn prefix_cache_summary(&self) -> Option<String> {
|
||||
if !self.shared.ready.load(Ordering::Acquire)
|
||||
|| self.shared.shutdown.load(Ordering::Acquire)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
original_serve::published_prefix_summary()
|
||||
}
|
||||
fn memory_report(&self) -> Option<String> {
|
||||
if self.shared.shutdown.load(Ordering::Acquire) {
|
||||
return None;
|
||||
}
|
||||
leleka_memory::published_report()
|
||||
}
|
||||
fn telemetry_report(&self) -> Option<String> {
|
||||
if self.shared.shutdown.load(Ordering::Acquire) {
|
||||
return None;
|
||||
}
|
||||
leleka_memory::telemetry::published_telemetry()
|
||||
}
|
||||
fn load(
|
||||
&mut self,
|
||||
model: ModelDescriptor,
|
||||
config: RuntimeConfig,
|
||||
) -> Result<LoadedModel, BackendError> {
|
||||
validate_load(&model, &config)?;
|
||||
validate_kar_selection(&config, self.kar_configured)?;
|
||||
validate_mtp_selection(&config, self.mtp_configured)?;
|
||||
self.idle()?;
|
||||
// A KAR expert archive (and overlay) is hashed whole during Load, after
|
||||
// the base shards, so it gets the same cold-load budget as KAR/MTP files.
|
||||
let timeout = load_reply_timeout(&config.inference_mode, self.kar_experts_configured);
|
||||
let (tx, rx) = mpsc::sync_channel(1);
|
||||
self.send(Command::Load(model, config, tx))?;
|
||||
self.wait_with_timeout(rx, timeout)
|
||||
}
|
||||
fn start_generation(
|
||||
&mut self,
|
||||
model: &LoadedModel,
|
||||
request: GenerationRequest,
|
||||
) -> Result<GenerationStream, BackendError> {
|
||||
validate_request(&request)?;
|
||||
validate_handle(model, self.kar_expert_native_digest.as_deref())?;
|
||||
if RECONFIGURING.load(Ordering::Acquire) {
|
||||
return Err(BackendError {
|
||||
code: ErrorCode::ResourceExhausted,
|
||||
message: "reconfiguring: retry_after=30: the engine is being reconfigured".into(),
|
||||
retryable: true,
|
||||
});
|
||||
}
|
||||
self.idle()?;
|
||||
if !self.shared.ready.load(Ordering::Acquire) {
|
||||
return Err(unavailable("native model is not ready"));
|
||||
}
|
||||
if self.seen.contains(&request.request_id) {
|
||||
return Err(invalid("generation request was already accepted"));
|
||||
}
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
*self
|
||||
.shared
|
||||
.active
|
||||
.lock()
|
||||
.map_err(|_| unavailable("native owner state unavailable"))? = Some(Active {
|
||||
id: request.request_id.clone(),
|
||||
cancel: Arc::clone(&cancel),
|
||||
});
|
||||
let id = request.request_id.clone();
|
||||
let (tx, rx) = mpsc::sync_channel(1);
|
||||
if let Err(error) = self.send(Command::Generate(model.clone(), request, cancel, tx)) {
|
||||
clear_active(&self.shared);
|
||||
return Err(error);
|
||||
}
|
||||
let result = self.wait(rx);
|
||||
if result.is_ok() {
|
||||
self.seen.insert(&id);
|
||||
} else {
|
||||
clear_active(&self.shared);
|
||||
}
|
||||
result
|
||||
}
|
||||
fn cancel(&mut self, request_id: &str) -> Result<(), BackendError> {
|
||||
let active = self
|
||||
.shared
|
||||
.active
|
||||
.lock()
|
||||
.map_err(|_| unavailable("native owner state unavailable"))?;
|
||||
match active.as_ref() {
|
||||
Some(active) if active.id == request_id => {
|
||||
active.cancel.store(true, Ordering::Release);
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(invalid("generation is not active")),
|
||||
}
|
||||
}
|
||||
fn reconfigure(&mut self, settings_json: &str) -> Result<String, BackendError> {
|
||||
if !self.original_serve {
|
||||
return Err(unsupported(
|
||||
"only the Original serve path can be reconfigured at run time",
|
||||
));
|
||||
}
|
||||
self.idle()?;
|
||||
if !self.shared.ready.load(Ordering::Acquire) {
|
||||
return Err(unavailable("native model is not ready"));
|
||||
}
|
||||
if RECONFIGURING.swap(true, Ordering::AcqRel) {
|
||||
return Err(exhausted("a reconfiguration is already running"));
|
||||
}
|
||||
let (tx, rx) = mpsc::sync_channel(1);
|
||||
let result = self
|
||||
.send(Command::Reconfigure(settings_json.to_owned(), tx))
|
||||
.and_then(|()| self.wait_with_timeout(rx, RECONFIGURE_TIMEOUT));
|
||||
RECONFIGURING.store(false, Ordering::Release);
|
||||
result
|
||||
}
|
||||
fn unload(&mut self, model: LoadedModel) -> Result<(), BackendError> {
|
||||
validate_handle(&model, self.kar_expert_native_digest.as_deref())?;
|
||||
self.idle()?;
|
||||
let (tx, rx) = mpsc::sync_channel(1);
|
||||
self.send(Command::Unload(model, tx))?;
|
||||
self.wait(rx)
|
||||
}
|
||||
}
|
||||
impl Drop for Proxy {
|
||||
fn drop(&mut self) {
|
||||
self.shared.shutdown.store(true, Ordering::Release);
|
||||
cancel_active(&self.shared);
|
||||
}
|
||||
}
|
||||
pub(super) struct OwnerGuard(pub(super) Arc<Shared>);
|
||||
impl Drop for OwnerGuard {
|
||||
fn drop(&mut self) {
|
||||
self.0.ready.store(false, Ordering::Release);
|
||||
self.0.shutdown.store(true, Ordering::Release);
|
||||
cancel_active(&self.0);
|
||||
}
|
||||
}
|
||||
pub(super) struct ActiveGuard<'a>(pub(super) &'a Shared);
|
||||
impl Drop for ActiveGuard<'_> {
|
||||
fn drop(&mut self) {
|
||||
clear_active(self.0);
|
||||
}
|
||||
}
|
||||
pub(super) fn cancel_active(shared: &Shared) {
|
||||
if let Ok(active) = shared.active.lock()
|
||||
&& let Some(active) = active.as_ref()
|
||||
{
|
||||
active.cancel.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
pub(super) fn clear_active(shared: &Shared) {
|
||||
if let Ok(mut active) = shared.active.lock() {
|
||||
*active = None;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//! Request preparation: sampler plan, prompt tokens, positions.
|
||||
use super::*;
|
||||
|
||||
pub(super) fn request_sampler(
|
||||
request: &GenerationRequest,
|
||||
entropy: u64,
|
||||
) -> Result<Option<leleka_sampler_ref::SamplerParams>, leleka_sampler_ref::SamplingError> {
|
||||
let s = &request.sampling;
|
||||
let raw =
|
||||
leleka_sampler_ref::RequestSampling::from_fixed_point(&leleka_sampler_ref::FixedPoint {
|
||||
temperature_milli: request.temperature_milli,
|
||||
top_p_micro: s.top_p_micro,
|
||||
top_k: s.top_k,
|
||||
min_p_micro: s.min_p_micro,
|
||||
repetition_penalty_micro: s.repetition_penalty_micro,
|
||||
frequency_penalty_micro: s.frequency_penalty_micro,
|
||||
presence_penalty_micro: s.presence_penalty_micro,
|
||||
penalty_last_n: s.penalty_last_n,
|
||||
seed: s.seed,
|
||||
});
|
||||
let params = leleka_sampler_ref::SamplingParams::resolve(&raw)?;
|
||||
Ok(params
|
||||
.needs_sampler()
|
||||
.then(|| params.to_sampler_params(entropy)))
|
||||
}
|
||||
|
||||
/// The steady-clock tick the Original takes as the seed of a request without one.
|
||||
pub(super) fn clock_seed() -> u64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(1, |d| d.as_nanos() as u64)
|
||||
.max(1)
|
||||
}
|
||||
pub(super) fn prepare_prompt(
|
||||
tokenizer: &Tokenizer,
|
||||
request: &GenerationRequest,
|
||||
context: u32,
|
||||
) -> Result<Vec<u32>, BackendError> {
|
||||
validate_request(request)?;
|
||||
// The prompt may carry marks (`LiteralMarks`) for control-token text that was inside a message: that text is encoded as
|
||||
// ordinary text, the template's own literals as special tokens. A prompt without marks encodes as before.
|
||||
let tokens = tokenizer
|
||||
.encode_marked(&request.prompt)
|
||||
.map_err(|_| invalid("prompt tokenization failed"))?;
|
||||
if tokens.is_empty()
|
||||
|| tokens
|
||||
.len()
|
||||
.checked_add(request.max_output_tokens as usize)
|
||||
.is_none_or(|total| total > context as usize)
|
||||
{
|
||||
return Err(exhausted("prompt and output exceed configured context"));
|
||||
}
|
||||
Ok(tokens)
|
||||
}
|
||||
|
||||
/// The operator ceiling governs admission, while the opaque Position carries
|
||||
/// the verified model dimension used by every stage's identity validation.
|
||||
pub(super) fn native_position(
|
||||
constants: &InputConstants,
|
||||
configured: u32,
|
||||
value: usize,
|
||||
) -> Result<Position, BackendError> {
|
||||
let model_context = constants.context_length();
|
||||
if configured == 0 || configured > model_context {
|
||||
return Err(invalid("native context configuration invalid"));
|
||||
}
|
||||
let value = u64::try_from(value).map_err(|_| exhausted("native context exhausted"))?;
|
||||
if value >= u64::from(configured) {
|
||||
return Err(exhausted("native configured context exhausted"));
|
||||
}
|
||||
let bound = Dimension::new(u64::from(model_context))
|
||||
.map_err(|_| invalid("verified native context invalid"))?;
|
||||
Position::new(value, bound).map_err(|_| exhausted("native model context exhausted"))
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//! The resident numeric prefix kept between generations.
|
||||
use super::*;
|
||||
|
||||
/// One actual successful resident numeric prefix. Actor/model lifetime is
|
||||
/// the lifecycle fence; LoadedModel adds handle/mode/config identity.
|
||||
pub(super) struct PrefixSession<'driver> {
|
||||
pub(super) loaded: LoadedModel,
|
||||
pub(super) session: QwenSession<'driver>,
|
||||
pub(super) continuation: MtpContinuation,
|
||||
}
|
||||
pub(super) struct MtpContinuation {
|
||||
pub(super) decoder: MtpDecoder,
|
||||
pub(super) product: TargetStepProduct,
|
||||
/// Exactly target-committed IDs, never a speculative or merely emitted ID.
|
||||
pub(super) tokens: Vec<u32>,
|
||||
}
|
||||
pub(super) fn append_compatible(committed: &[u32], incoming: &[u32]) -> bool {
|
||||
!committed.is_empty()
|
||||
&& committed.len() as u64 <= crate::qwen_forward::contract::serving_cells()
|
||||
&& incoming.len() as u64 <= crate::qwen_forward::contract::serving_cells()
|
||||
&& incoming.starts_with(committed)
|
||||
}
|
||||
|
||||
/// Completion is the conjunction of numeric success, bounded terminal queue
|
||||
/// publication and a still-live serving lifecycle. Failed gates drop ownership.
|
||||
pub(super) fn terminal_admit<T>(
|
||||
candidate: Option<T>,
|
||||
completed: bool,
|
||||
published: bool,
|
||||
cancelled: bool,
|
||||
shutdown: bool,
|
||||
closed: bool,
|
||||
ready: bool,
|
||||
) -> Option<T> {
|
||||
candidate.filter(|_| completed && published && !cancelled && !shutdown && !closed && ready)
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
//! Verification of the pinned sources (shards, KAR archive, ranked profile) at load time.
|
||||
use super::*;
|
||||
|
||||
/// What the three source verifications returned. Errors are reduced to text because the verifying threads hand
|
||||
/// them over; the callers map each to the same fixed refusal as before.
|
||||
pub(super) struct VerifiedSources {
|
||||
pub(super) shard0: Result<VerifiedGgufFile, String>,
|
||||
pub(super) shard1: Result<VerifiedGgufFile, String>,
|
||||
/// `None` when no inherited archive is configured.
|
||||
pub(super) kar: Option<InputResultKar>,
|
||||
}
|
||||
|
||||
pub(super) type InputResultKar =
|
||||
Result<leleka_model_format::kar::VerifiedKarPleArtifact, InputBindingError>;
|
||||
|
||||
/// Verify shard 0, shard 1 and the inherited KAR archive at the same time. They are independent files; the
|
||||
/// SHA-256 of each is sequential, so the wall time is the slowest one instead of their sum. Each verification
|
||||
/// is the very function the sequential load used (full hash, strict index, pinned profile), and the results are
|
||||
/// consumed in the original order, so every refusal is the same as before.
|
||||
pub(super) fn verify_sources_parallel(
|
||||
config: &NativeBackendConfig,
|
||||
want_kar: bool,
|
||||
) -> VerifiedSources {
|
||||
use std::time::Instant;
|
||||
let begun = Instant::now();
|
||||
let result = std::thread::scope(|scope| {
|
||||
let shard1 = scope.spawn(|| {
|
||||
let started = Instant::now();
|
||||
let result = VerifiedGgufFile::open(&config.shard1, SHARD1).map_err(|e| e.to_string());
|
||||
crate::load_clock::span("shard1_sha256_and_index", started);
|
||||
result
|
||||
});
|
||||
let kar = config
|
||||
.kar_ple_inherited
|
||||
.as_ref()
|
||||
.filter(|_| want_kar)
|
||||
.map(|archive| {
|
||||
scope.spawn(move || {
|
||||
let started = Instant::now();
|
||||
let result =
|
||||
crate::model_binding::qwen4exp_kar_ple::load_pinned_inherited_archive(
|
||||
archive,
|
||||
);
|
||||
crate::load_clock::span("kar_inspect_verify", started);
|
||||
result
|
||||
})
|
||||
});
|
||||
let started = Instant::now();
|
||||
let shard0 = VerifiedGgufFile::open(&config.shard0, SHARD0).map_err(|e| e.to_string());
|
||||
crate::load_clock::span("shard0_sha256_and_index", started);
|
||||
VerifiedSources {
|
||||
shard0,
|
||||
shard1: shard1
|
||||
.join()
|
||||
.unwrap_or_else(|_| Err("verification thread failed".into())),
|
||||
kar: kar.map(|handle| handle.join().unwrap_or(Err(InputBindingError::Busy))),
|
||||
}
|
||||
});
|
||||
crate::load_clock::span("sources_verified_in_parallel_wall", begun);
|
||||
result
|
||||
}
|
||||
|
||||
/// `leleka-inference --verify-only`: the load-time verification of the sources (both shards, the KAR archive)
|
||||
/// and nothing else: no CUDA, no GPU, no model state. Prints the `leleka-load-time` lines and returns.
|
||||
/// It uses exactly the functions of `serve_load`, so what it measures is what a start spends.
|
||||
pub fn verify_sources_only(config: NativeBackendConfig) -> Result<(), BackendError> {
|
||||
crate::load_clock::begin();
|
||||
let sources = verify_sources_parallel(&config, true);
|
||||
sources
|
||||
.shard0
|
||||
.map_err(|_| invalid("pinned shard 0 verification failed"))?;
|
||||
sources
|
||||
.shard1
|
||||
.map_err(|_| invalid("pinned shard 1 verification failed"))?;
|
||||
if let Some(kar) = sources.kar {
|
||||
kar.map_err(|_| invalid("pinned KAR archive verification failed"))?;
|
||||
}
|
||||
crate::load_clock::lap("all_sources_verified");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `leleka-inference --kar-attested-by-stamp`: the parent copied the sealed archive from a file whose verification
|
||||
/// stamp matched and was unchanged while it was copied; skip hashing the memfd again. Never implied.
|
||||
pub fn set_archive_attested() {
|
||||
leleka_model_format::verify_stamp::set_attested_archive();
|
||||
}
|
||||
|
||||
/// Operator switch of `leleka-inference --verify-stamps DIR [--verify-rehash]`: a file that matched its pinned
|
||||
/// digest before and is unchanged (device, inode, size, mtime, ctime) is not hashed again. Set once, before Load.
|
||||
pub fn set_verify_stamps(directory: PathBuf, rehash: bool) -> bool {
|
||||
leleka_model_format::verify_stamp::set_global(
|
||||
leleka_model_format::verify_stamp::VerifyStamps::new(directory, rehash),
|
||||
)
|
||||
}
|
||||
pub(super) fn read_ranked_expert_profile(
|
||||
source: &RankedExpertProfileSource,
|
||||
) -> Result<Vec<u8>, BackendError> {
|
||||
use std::io::Read;
|
||||
if source.sha256 != RANKED_EXPERT_PROFILE_SHA {
|
||||
return Err(invalid("unrecognized ranked expert profile"));
|
||||
}
|
||||
let file = std::fs::File::open(&source.path)
|
||||
.map_err(|_| invalid("ranked expert profile unavailable"))?;
|
||||
if file
|
||||
.metadata()
|
||||
.map_err(|_| invalid("ranked expert profile unavailable"))?
|
||||
.len()
|
||||
!= RANKED_EXPERT_PROFILE_BYTES as u64
|
||||
{
|
||||
return Err(invalid("ranked expert profile extent mismatch"));
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
bytes
|
||||
.try_reserve_exact(RANKED_EXPERT_PROFILE_BYTES + 1)
|
||||
.map_err(|_| exhausted("ranked expert profile metadata unavailable"))?;
|
||||
file.take((RANKED_EXPERT_PROFILE_BYTES + 1) as u64)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|_| invalid("ranked expert profile read failed"))?;
|
||||
let mut actual_digest = String::with_capacity(64);
|
||||
for value in Sha256::digest(&bytes) {
|
||||
use std::fmt::Write;
|
||||
let _ = write!(actual_digest, "{value:02x}");
|
||||
}
|
||||
if bytes.len() != RANKED_EXPERT_PROFILE_BYTES || actual_digest != source.sha256 {
|
||||
return Err(invalid("ranked expert profile digest mismatch"));
|
||||
}
|
||||
#[cfg(all(
|
||||
any(target_os = "linux", target_os = "windows"),
|
||||
target_arch = "x86_64"
|
||||
))]
|
||||
{
|
||||
crate::qwen_forward::moe_weight_cache::validate_ranked_profile(&bytes)
|
||||
.map_err(|_| invalid("ranked expert profile domain mismatch"))?;
|
||||
Ok(bytes)
|
||||
}
|
||||
#[cfg(not(all(
|
||||
any(target_os = "linux", target_os = "windows"),
|
||||
target_arch = "x86_64"
|
||||
)))]
|
||||
{
|
||||
Err(unsupported(
|
||||
"optimized CUDA execution requires Linux x86_64",
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
//! Factories of the Native and the evaluation-only backends, and the common owner-thread spawn.
|
||||
use super::*;
|
||||
|
||||
pub fn spawn_backend(config: NativeBackendConfig) -> Result<Box<dyn Backend>, BackendError> {
|
||||
spawn_backend_inner(config, None, EvaluationExecution::Native)
|
||||
}
|
||||
/// Explicit operator-selected experiment. Selection is fixed for this owner
|
||||
/// lifetime and does not certify quality, speed or long-context completion.
|
||||
/// The existing typed KAR PLE MTP Load remains mandatory; no observer is needed.
|
||||
pub fn spawn_backend_experimental_native_integer_iq3_windowed256_retained_gr(
|
||||
config: NativeBackendConfig,
|
||||
) -> Result<Box<dyn Backend>, BackendError> {
|
||||
if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none())
|
||||
|| config.mtp_source.is_none()
|
||||
{
|
||||
return Err(invalid(
|
||||
"IQ3 windowed256 retained GR experiment requires KAR PLE and MTP sources",
|
||||
));
|
||||
}
|
||||
spawn_backend_inner(
|
||||
config,
|
||||
None,
|
||||
EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr,
|
||||
)
|
||||
}
|
||||
/// Explicit public evaluation only. Normal serving has no observer and never
|
||||
/// exposes token IDs; this does not change the RPC or backend protocol.
|
||||
pub fn spawn_backend_observed(
|
||||
config: NativeBackendConfig,
|
||||
observer: EvaluationObserver,
|
||||
) -> Result<Box<dyn Backend>, BackendError> {
|
||||
spawn_backend_inner(config, Some(observer), EvaluationExecution::Native)
|
||||
}
|
||||
/// Private evaluation candidate only: fixed operator selection for subsequent
|
||||
/// typed model Load. Neither RPCs nor normal spawns can choose this policy.
|
||||
/// Still experimental; selection is not a quality/performance certificate.
|
||||
pub fn spawn_backend_observed_resident_mmq(
|
||||
config: NativeBackendConfig,
|
||||
observer: EvaluationObserver,
|
||||
) -> Result<Box<dyn Backend>, BackendError> {
|
||||
if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none())
|
||||
|| config.mtp_source.is_none()
|
||||
{
|
||||
return Err(invalid(
|
||||
"resident MMQ evaluation requires KAR PLE and MTP sources",
|
||||
));
|
||||
}
|
||||
spawn_backend_inner(
|
||||
config,
|
||||
Some(observer),
|
||||
EvaluationExecution::ExperimentalResidentMmq,
|
||||
)
|
||||
}
|
||||
/// Explicit evaluation-only native-certified activation policy. This retains
|
||||
/// original MMQ tensor kernels and does not certify model quality or speed.
|
||||
pub fn spawn_backend_observed_native_resident_mmq(
|
||||
config: NativeBackendConfig,
|
||||
observer: EvaluationObserver,
|
||||
) -> Result<Box<dyn Backend>, BackendError> {
|
||||
if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none())
|
||||
|| config.mtp_source.is_none()
|
||||
{
|
||||
return Err(invalid(
|
||||
"native-certified resident MMQ evaluation requires KAR PLE and MTP sources",
|
||||
));
|
||||
}
|
||||
spawn_backend_inner(
|
||||
config,
|
||||
Some(observer),
|
||||
EvaluationExecution::ExperimentalNativeResidentMmq,
|
||||
)
|
||||
}
|
||||
/// Explicit operator evaluation candidate only: IQ3 GU integer MMA with native
|
||||
/// integer truncation/order. Ineligible GU layers use actual native execution.
|
||||
/// Down retains existing candidate arithmetic; no quality/performance admission.
|
||||
/// Normal spawns, RPCs, configuration and production defaults cannot select it.
|
||||
pub fn spawn_backend_observed_native_integer_iq3_mmq(
|
||||
config: NativeBackendConfig,
|
||||
observer: EvaluationObserver,
|
||||
) -> Result<Box<dyn Backend>, BackendError> {
|
||||
if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none())
|
||||
|| config.mtp_source.is_none()
|
||||
{
|
||||
return Err(invalid(
|
||||
"IQ3 integer MMA evaluation requires KAR PLE and MTP sources",
|
||||
));
|
||||
}
|
||||
spawn_backend_inner(
|
||||
config,
|
||||
Some(observer),
|
||||
EvaluationExecution::ExperimentalNativeIntegerIq3Mmq,
|
||||
)
|
||||
}
|
||||
/// Explicit private evaluation: real outer256 with bounded64 kernels and
|
||||
/// retained GR transport. Native MoE arithmetic and normal serving are kept.
|
||||
/// This selection is experimental, not a quality or performance certificate.
|
||||
pub fn spawn_backend_observed_windowed256_retained_gr(
|
||||
config: NativeBackendConfig,
|
||||
observer: EvaluationObserver,
|
||||
) -> Result<Box<dyn Backend>, BackendError> {
|
||||
if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none())
|
||||
|| config.mtp_source.is_none()
|
||||
{
|
||||
return Err(invalid(
|
||||
"windowed256 retained GR evaluation requires KAR PLE and MTP sources",
|
||||
));
|
||||
}
|
||||
spawn_backend_inner(
|
||||
config,
|
||||
Some(observer),
|
||||
EvaluationExecution::ExperimentalWindowed256RetainedGr,
|
||||
)
|
||||
}
|
||||
/// Explicit private evaluation composition: outer256 retained GR transport,
|
||||
/// IQ3-only native-order integer GU, and native whole-layer fallback for other GU.
|
||||
/// Down keeps existing candidate arithmetic. No quality/performance admission;
|
||||
/// normal spawns, RPCs and production configuration cannot select this policy.
|
||||
pub fn spawn_backend_observed_native_integer_iq3_windowed256_retained_gr(
|
||||
config: NativeBackendConfig,
|
||||
observer: EvaluationObserver,
|
||||
) -> Result<Box<dyn Backend>, BackendError> {
|
||||
if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none())
|
||||
|| config.mtp_source.is_none()
|
||||
{
|
||||
return Err(invalid(
|
||||
"IQ3 windowed256 retained GR evaluation requires KAR PLE and MTP sources",
|
||||
));
|
||||
}
|
||||
spawn_backend_inner(
|
||||
config,
|
||||
Some(observer),
|
||||
EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr,
|
||||
)
|
||||
}
|
||||
pub(super) fn spawn_backend_inner(
|
||||
config: NativeBackendConfig,
|
||||
observer: Option<EvaluationObserver>,
|
||||
execution: EvaluationExecution,
|
||||
) -> Result<Box<dyn Backend>, BackendError> {
|
||||
spawn_backend_configured(
|
||||
config,
|
||||
observer,
|
||||
OwnerExecution {
|
||||
original: None,
|
||||
kind: execution,
|
||||
optimized: None,
|
||||
},
|
||||
)
|
||||
}
|
||||
pub(super) fn spawn_backend_configured(
|
||||
config: NativeBackendConfig,
|
||||
observer: Option<EvaluationObserver>,
|
||||
selection: OwnerExecution,
|
||||
) -> Result<Box<dyn Backend>, BackendError> {
|
||||
let execution = selection.kind;
|
||||
let optimized_execution = selection.optimized.is_some();
|
||||
let queued_owners = selection
|
||||
.optimized
|
||||
.as_ref()
|
||||
.is_some_and(|options| options.policy != OptimizedOwnerPolicy::Original);
|
||||
let streamed_spill = selection.optimized.as_ref().is_some_and(|options| {
|
||||
matches!(
|
||||
options.policy,
|
||||
OptimizedOwnerPolicy::StreamedSpill
|
||||
| OptimizedOwnerPolicy::RetainedScratch
|
||||
| OptimizedOwnerPolicy::ResidentOwners
|
||||
| OptimizedOwnerPolicy::AdaptiveSlots
|
||||
)
|
||||
});
|
||||
let retained_scratch = selection.optimized.as_ref().is_some_and(|options| {
|
||||
matches!(
|
||||
options.policy,
|
||||
OptimizedOwnerPolicy::RetainedScratch
|
||||
| OptimizedOwnerPolicy::ResidentOwners
|
||||
| OptimizedOwnerPolicy::AdaptiveSlots
|
||||
)
|
||||
});
|
||||
let adaptive_slots = selection
|
||||
.optimized
|
||||
.as_ref()
|
||||
.is_some_and(|options| options.policy == OptimizedOwnerPolicy::AdaptiveSlots);
|
||||
let resident_owners = selection.optimized.as_ref().is_some_and(|options| {
|
||||
matches!(
|
||||
options.policy,
|
||||
OptimizedOwnerPolicy::ResidentOwners | OptimizedOwnerPolicy::AdaptiveSlots
|
||||
)
|
||||
});
|
||||
let original_serve = selection.original.is_some();
|
||||
if config.context_tokens == 0
|
||||
|| u64::from(config.context_tokens) > leleka_context::rope_scaling::MAX_CHARTER_CONTEXT
|
||||
|| config.gpu_budget_bytes == 0
|
||||
|| usize::try_from(config.gpu_budget_bytes).is_err()
|
||||
|| i32::try_from(config.gpu_device_ordinal).is_err()
|
||||
|| (config.kar_ple_source.is_some() && config.kar_ple_inherited.is_some())
|
||||
{
|
||||
return Err(invalid("invalid native resource configuration"));
|
||||
}
|
||||
// The serving context (cells, RoPE scaling) is fixed once per process before any CUDA owner exists.
|
||||
crate::serving::admit_context_tokens(config.context_tokens, config.gpu_budget_bytes).map_err(
|
||||
|e| BackendError {
|
||||
code: ErrorCode::InvalidRequest,
|
||||
message: format!("native context not servable: {e}"),
|
||||
retryable: false,
|
||||
},
|
||||
)?;
|
||||
let (tx, rx) = mpsc::sync_channel(QUEUE);
|
||||
let shared = Arc::new(Shared {
|
||||
ready: AtomicBool::new(false),
|
||||
shutdown: AtomicBool::new(false),
|
||||
active: Mutex::new(None),
|
||||
});
|
||||
let kar_configured = config.kar_ple_source.is_some() || config.kar_ple_inherited.is_some();
|
||||
let mtp_configured = config.mtp_source.is_some();
|
||||
let kar_experts_configured = config.kar_expert_source.is_some();
|
||||
// The Native handle a KAR-expert Load will publish: the base Native digest
|
||||
// mixed with the source identity (pure function of the operator config).
|
||||
let kar_expert_native_digest = config.kar_expert_source.as_ref().map(|source| {
|
||||
kar_expert_mode_digest(
|
||||
MODE_DIGEST,
|
||||
&crate::model_binding::kar_expert_source::config_identity_digest(source),
|
||||
)
|
||||
});
|
||||
let worker_shared = Arc::clone(&shared);
|
||||
let instance = INSTANCE.fetch_add(1, Ordering::Relaxed);
|
||||
thread::Builder::new()
|
||||
.name("leleka-cuda-owner".into())
|
||||
.spawn(move || {
|
||||
let _guard = OwnerGuard(Arc::clone(&worker_shared));
|
||||
owner(config, rx, &worker_shared, instance, observer, selection);
|
||||
})
|
||||
.map_err(|_| unavailable("native owner thread unavailable"))?;
|
||||
Ok(Box::new(Proxy {
|
||||
tx,
|
||||
shared,
|
||||
seen: RecentIds::default(),
|
||||
kar_configured,
|
||||
mtp_configured,
|
||||
kar_experts_configured,
|
||||
kar_expert_native_digest,
|
||||
execution,
|
||||
optimized_execution,
|
||||
queued_owners,
|
||||
streamed_spill,
|
||||
retained_scratch,
|
||||
resident_owners,
|
||||
adaptive_slots,
|
||||
original_serve,
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
//! Factories of the optimized windowed256 experiments (queued owners .. adaptive slots).
|
||||
use super::*;
|
||||
|
||||
/// Separately selected optimized experiment. Default and earlier experiment
|
||||
/// factories remain unchanged; this selection certifies neither speed nor quality.
|
||||
pub fn spawn_backend_experimental_optimized_windowed256(
|
||||
config: NativeBackendConfig,
|
||||
ranked_profile: Option<RankedExpertProfileSource>,
|
||||
) -> Result<Box<dyn Backend>, BackendError> {
|
||||
if !cfg!(all(
|
||||
any(target_os = "linux", target_os = "windows"),
|
||||
target_arch = "x86_64"
|
||||
)) {
|
||||
return Err(unsupported(
|
||||
"optimized CUDA execution requires Linux x86_64",
|
||||
));
|
||||
}
|
||||
if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none())
|
||||
|| config.mtp_source.is_none()
|
||||
|| ranked_profile.as_ref().is_some_and(|source| {
|
||||
source.path.as_os_str().is_empty() || source.sha256 != RANKED_EXPERT_PROFILE_SHA
|
||||
})
|
||||
{
|
||||
return Err(invalid("invalid optimized KAR PLE MTP profile selection"));
|
||||
}
|
||||
spawn_backend_configured(
|
||||
config,
|
||||
None,
|
||||
OwnerExecution {
|
||||
original: None,
|
||||
kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr,
|
||||
optimized: Some(OptimizedBackendConfig {
|
||||
ranked_profile,
|
||||
policy: OptimizedOwnerPolicy::Original,
|
||||
}),
|
||||
},
|
||||
)
|
||||
}
|
||||
/// Separately opt-in pinned-profile owner. This prepares the configured candidate
|
||||
/// factories for serving; selection does not certify quality or performance.
|
||||
/// The earlier optimized route and Native defaults remain unchanged.
|
||||
pub fn spawn_backend_experimental_optimized_windowed256_queued_owners(
|
||||
config: NativeBackendConfig,
|
||||
ranked_profile: RankedExpertProfileSource,
|
||||
) -> Result<Box<dyn Backend>, BackendError> {
|
||||
if !cfg!(all(
|
||||
any(target_os = "linux", target_os = "windows"),
|
||||
target_arch = "x86_64"
|
||||
)) {
|
||||
return Err(unsupported("queued CUDA owners require Linux x86_64"));
|
||||
}
|
||||
if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none())
|
||||
|| config.mtp_source.is_none()
|
||||
|| ranked_profile.path.as_os_str().is_empty()
|
||||
|| ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA
|
||||
{
|
||||
return Err(invalid(
|
||||
"invalid queued-owner KAR PLE MTP profile selection",
|
||||
));
|
||||
}
|
||||
spawn_backend_configured(
|
||||
config,
|
||||
None,
|
||||
OwnerExecution {
|
||||
original: None,
|
||||
kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr,
|
||||
optimized: Some(OptimizedBackendConfig {
|
||||
ranked_profile: Some(ranked_profile),
|
||||
policy: OptimizedOwnerPolicy::QueuedOwners,
|
||||
}),
|
||||
},
|
||||
)
|
||||
}
|
||||
/// Explicit inherited-KAR operator experiment. Original and queued-owner
|
||||
/// factories preserve their previous meanings. Qualification is separate.
|
||||
pub fn spawn_backend_experimental_optimized_windowed256_streamed_spill(
|
||||
config: NativeBackendConfig,
|
||||
ranked_profile: RankedExpertProfileSource,
|
||||
) -> Result<Box<dyn Backend>, BackendError> {
|
||||
if !cfg!(all(
|
||||
any(target_os = "linux", target_os = "windows"),
|
||||
target_arch = "x86_64"
|
||||
)) {
|
||||
return Err(unsupported(
|
||||
"streamed spill CUDA owners require Linux x86_64",
|
||||
));
|
||||
}
|
||||
if config.kar_ple_inherited.is_none()
|
||||
|| config.kar_ple_source.is_some()
|
||||
|| config.mtp_source.is_none()
|
||||
|| ranked_profile.path.as_os_str().is_empty()
|
||||
|| ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA
|
||||
{
|
||||
return Err(invalid(
|
||||
"streamed spill requires inherited sealed KAR, MTP and pinned profile",
|
||||
));
|
||||
}
|
||||
spawn_backend_configured(
|
||||
config,
|
||||
None,
|
||||
OwnerExecution {
|
||||
original: None,
|
||||
kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr,
|
||||
optimized: Some(OptimizedBackendConfig {
|
||||
ranked_profile: Some(ranked_profile),
|
||||
policy: OptimizedOwnerPolicy::StreamedSpill,
|
||||
}),
|
||||
},
|
||||
)
|
||||
}
|
||||
/// Additional retained whole-buffer owners; distinct unadopted operator mode.
|
||||
pub fn spawn_backend_experimental_optimized_windowed256_retained_scratch(
|
||||
config: NativeBackendConfig,
|
||||
ranked_profile: RankedExpertProfileSource,
|
||||
) -> Result<Box<dyn Backend>, BackendError> {
|
||||
if !cfg!(all(
|
||||
any(target_os = "linux", target_os = "windows"),
|
||||
target_arch = "x86_64"
|
||||
)) {
|
||||
return Err(unsupported(
|
||||
"streamed spill CUDA owners require Linux x86_64",
|
||||
));
|
||||
}
|
||||
if config.kar_ple_inherited.is_none()
|
||||
|| config.kar_ple_source.is_some()
|
||||
|| config.mtp_source.is_none()
|
||||
|| ranked_profile.path.as_os_str().is_empty()
|
||||
|| ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA
|
||||
{
|
||||
return Err(invalid(
|
||||
"streamed spill requires inherited sealed KAR, MTP and pinned profile",
|
||||
));
|
||||
}
|
||||
spawn_backend_configured(
|
||||
config,
|
||||
None,
|
||||
OwnerExecution {
|
||||
original: None,
|
||||
kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr,
|
||||
optimized: Some(OptimizedBackendConfig {
|
||||
ranked_profile: Some(ranked_profile),
|
||||
policy: OptimizedOwnerPolicy::RetainedScratch,
|
||||
}),
|
||||
},
|
||||
)
|
||||
}
|
||||
/// Separate experimental owner policy; actual model qualification required.
|
||||
pub fn spawn_backend_experimental_optimized_windowed256_resident_owners(
|
||||
config: NativeBackendConfig,
|
||||
ranked_profile: RankedExpertProfileSource,
|
||||
) -> Result<Box<dyn Backend>, BackendError> {
|
||||
if !cfg!(all(
|
||||
any(target_os = "linux", target_os = "windows"),
|
||||
target_arch = "x86_64"
|
||||
)) {
|
||||
return Err(unsupported(
|
||||
"streamed spill CUDA owners require Linux x86_64",
|
||||
));
|
||||
}
|
||||
if config.kar_ple_inherited.is_none()
|
||||
|| config.kar_ple_source.is_some()
|
||||
|| config.mtp_source.is_none()
|
||||
|| ranked_profile.path.as_os_str().is_empty()
|
||||
|| ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA
|
||||
{
|
||||
return Err(invalid(
|
||||
"streamed spill requires inherited sealed KAR, MTP and pinned profile",
|
||||
));
|
||||
}
|
||||
spawn_backend_configured(
|
||||
config,
|
||||
None,
|
||||
OwnerExecution {
|
||||
original: None,
|
||||
kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr,
|
||||
optimized: Some(OptimizedBackendConfig {
|
||||
ranked_profile: Some(ranked_profile),
|
||||
policy: OptimizedOwnerPolicy::ResidentOwners,
|
||||
}),
|
||||
},
|
||||
)
|
||||
}
|
||||
/// Authentic adaptive slot policy; experimental until paired quality/time gates.
|
||||
pub fn spawn_backend_experimental_optimized_windowed256_adaptive_slots(
|
||||
config: NativeBackendConfig,
|
||||
ranked_profile: RankedExpertProfileSource,
|
||||
) -> Result<Box<dyn Backend>, BackendError> {
|
||||
if !cfg!(all(
|
||||
any(target_os = "linux", target_os = "windows"),
|
||||
target_arch = "x86_64"
|
||||
)) {
|
||||
return Err(unsupported(
|
||||
"streamed spill CUDA owners require Linux x86_64",
|
||||
));
|
||||
}
|
||||
if config.kar_ple_inherited.is_none()
|
||||
|| config.kar_ple_source.is_some()
|
||||
|| config.mtp_source.is_none()
|
||||
|| ranked_profile.path.as_os_str().is_empty()
|
||||
|| ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA
|
||||
{
|
||||
return Err(invalid(
|
||||
"streamed spill requires inherited sealed KAR, MTP and pinned profile",
|
||||
));
|
||||
}
|
||||
spawn_backend_configured(
|
||||
config,
|
||||
None,
|
||||
OwnerExecution {
|
||||
original: None,
|
||||
kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr,
|
||||
optimized: Some(OptimizedBackendConfig {
|
||||
ranked_profile: Some(ranked_profile),
|
||||
policy: OptimizedOwnerPolicy::AdaptiveSlots,
|
||||
}),
|
||||
},
|
||||
)
|
||||
}
|
||||
/// Explicit PUBLIC-FIXTURE attachment to the identical adaptive policy.
|
||||
/// No token IDs enter the public RPC schema; only the operator observer sees them.
|
||||
pub fn spawn_backend_observed_experimental_optimized_windowed256_adaptive_slots(
|
||||
config: NativeBackendConfig,
|
||||
ranked_profile: RankedExpertProfileSource,
|
||||
observer: EvaluationObserver,
|
||||
) -> Result<Box<dyn Backend>, BackendError> {
|
||||
if std::env::var("LELEKA_PUBLIC_EVALUATION").as_deref() != Ok("yes") {
|
||||
return Err(invalid("explicit public evaluation required"));
|
||||
}
|
||||
if !cfg!(all(
|
||||
any(target_os = "linux", target_os = "windows"),
|
||||
target_arch = "x86_64"
|
||||
)) {
|
||||
return Err(unsupported(
|
||||
"streamed spill CUDA owners require Linux x86_64",
|
||||
));
|
||||
}
|
||||
if config.kar_ple_inherited.is_none()
|
||||
|| config.kar_ple_source.is_some()
|
||||
|| config.mtp_source.is_none()
|
||||
|| ranked_profile.path.as_os_str().is_empty()
|
||||
|| ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA
|
||||
{
|
||||
return Err(invalid(
|
||||
"streamed spill requires inherited sealed KAR, MTP and pinned profile",
|
||||
));
|
||||
}
|
||||
spawn_backend_configured(
|
||||
config,
|
||||
Some(observer),
|
||||
OwnerExecution {
|
||||
original: None,
|
||||
kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr,
|
||||
optimized: Some(OptimizedBackendConfig {
|
||||
ranked_profile: Some(ranked_profile),
|
||||
policy: OptimizedOwnerPolicy::AdaptiveSlots,
|
||||
}),
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
//! Choice of the Original-literal mode17 serve path and its factories.
|
||||
use super::*;
|
||||
|
||||
/// The path an operator configuration resolves to for `mode` (see `OriginalServeMode`): pure over the
|
||||
/// configuration and the build's asset probe. `Auto` picks the Original path only when it can start;
|
||||
/// `Original` returns a precise refusal instead of falling back; `Preview` never starts it. The caller
|
||||
/// spawns the matching backend (`spawn_backend_original_serve`, or its own preview chain).
|
||||
pub fn original_serve_choice(
|
||||
mode: OriginalServeMode,
|
||||
config: &NativeBackendConfig,
|
||||
) -> Result<OriginalServeChoice, BackendError> {
|
||||
let facts = original_serve::ConfigFacts {
|
||||
kar_inherited: config.kar_ple_inherited.is_some(),
|
||||
kar_staged: config.kar_ple_source.is_some(),
|
||||
mtp: config.mtp_source.is_some(),
|
||||
kar_expert: config.kar_expert_source.is_some(),
|
||||
gguf_ple: std::env::var("LELEKA_ORIGINAL_SERVE_GGUF_PLE").is_ok_and(|v| v == "1"),
|
||||
experimental: !config.experimental.is_off(),
|
||||
context_tokens: config.context_tokens,
|
||||
};
|
||||
// The probe is only consulted when the mode could select the Original path.
|
||||
let unsealed = if mode == OriginalServeMode::Preview {
|
||||
Vec::new()
|
||||
} else {
|
||||
original_serve::current_unsealed()
|
||||
};
|
||||
original_serve::choose(mode, &facts, &unsealed)
|
||||
}
|
||||
/// The Original-literal mode17 serve backend: the generate.cpp serve loop (`OriginalSpecController` over
|
||||
/// `OriginalServeEngine` and the native Verifier) with the Original batched prompt read and MTP drafting,
|
||||
/// instead of the Rust-native preview decoder. `options.mode` is resolved with `original_serve_choice`;
|
||||
/// a mode that resolves to the preview path is refused here (spawn that backend instead). The expert tier
|
||||
/// is the all-CPU pool over the pinned model's mapped routed weights; selection certifies neither
|
||||
/// quality nor speed.
|
||||
pub fn spawn_backend_original_serve(
|
||||
config: NativeBackendConfig,
|
||||
options: OriginalServeOptions,
|
||||
) -> Result<Box<dyn Backend>, BackendError> {
|
||||
if !cfg!(all(
|
||||
any(target_os = "linux", target_os = "windows"),
|
||||
target_arch = "x86_64"
|
||||
)) {
|
||||
return Err(unsupported(
|
||||
"Original serve CUDA owners require Linux x86_64",
|
||||
));
|
||||
}
|
||||
options.validate()?;
|
||||
match original_serve_choice(options.mode, &config)? {
|
||||
OriginalServeChoice::Original => {}
|
||||
OriginalServeChoice::Preview { reason } => {
|
||||
return Err(invalid_dynamic(format!(
|
||||
"the selected backend mode resolves to the preview path ({reason}); spawn the preview backend"
|
||||
)));
|
||||
}
|
||||
}
|
||||
spawn_backend_configured(
|
||||
config,
|
||||
None,
|
||||
OwnerExecution {
|
||||
original: Some(options),
|
||||
kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr,
|
||||
optimized: None,
|
||||
},
|
||||
)
|
||||
}
|
||||
/// Explicit Original-literal mode17 serve (the earlier factory name, kept for its callers): the pinned
|
||||
/// ranked profile is still validated as before but is not consumed (the Original expert tier here has no
|
||||
/// GPU residency to rank). Equivalent to `spawn_backend_original_serve` with `OriginalServeMode::Original`.
|
||||
pub fn spawn_backend_experimental_original_serve(
|
||||
config: NativeBackendConfig,
|
||||
ranked_profile: RankedExpertProfileSource,
|
||||
) -> Result<Box<dyn Backend>, BackendError> {
|
||||
if ranked_profile.path.as_os_str().is_empty()
|
||||
|| ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA
|
||||
{
|
||||
return Err(invalid(
|
||||
"Original serve requires the pinned ranked profile selection",
|
||||
));
|
||||
}
|
||||
spawn_backend_original_serve(
|
||||
config,
|
||||
OriginalServeOptions {
|
||||
mode: OriginalServeMode::Original,
|
||||
..OriginalServeOptions::default()
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
use super::*;
|
||||
#[test]
|
||||
fn queued_owner_identity_is_distinct_and_binds_profile_and_actual_bound_mode() {
|
||||
let old_fields = [
|
||||
"leleka-optimized-execution-v2",
|
||||
"bounded-resident-raw-expert-source-52gib-headroom8gib-v1",
|
||||
"complete-routed-gpu-finite-guard-v1",
|
||||
"sanitized-bound-mode",
|
||||
OPTIMIZED_EXECUTION,
|
||||
"ranked-pinned-prefix-bounded-spill-v1",
|
||||
RANKED_EXPERT_PROFILE_SHA,
|
||||
];
|
||||
let mut oracle = Sha256::new();
|
||||
for field in old_fields {
|
||||
oracle.update(field.as_bytes());
|
||||
oracle.update(b"\n");
|
||||
}
|
||||
let mut expected_old = String::from("sha256:");
|
||||
for byte in oracle.finalize() {
|
||||
use std::fmt::Write;
|
||||
let _ = write!(expected_old, "{byte:02x}");
|
||||
}
|
||||
let original =
|
||||
optimized_execution_digest("sanitized-bound-mode", Some(RANKED_EXPERT_PROFILE_SHA));
|
||||
assert_eq!(original, expected_old);
|
||||
let queued = queued_owners_execution_digest("sanitized-bound-mode", RANKED_EXPERT_PROFILE_SHA);
|
||||
assert_ne!(queued, original);
|
||||
assert_ne!(
|
||||
queued,
|
||||
optimized_execution_digest("sanitized-bound-mode", None)
|
||||
);
|
||||
assert_ne!(
|
||||
queued,
|
||||
queued_owners_execution_digest("different-bound-mode", RANKED_EXPERT_PROFILE_SHA)
|
||||
);
|
||||
assert_ne!(
|
||||
queued,
|
||||
queued_owners_execution_digest("sanitized-bound-mode", "different-profile")
|
||||
);
|
||||
assert_ne!(QUEUED_OWNERS_EXECUTION, OPTIMIZED_EXECUTION);
|
||||
}
|
||||
|
||||
fn native_config() -> RuntimeConfig {
|
||||
RuntimeConfig {
|
||||
load_config_version: LOAD_CONFIG_VERSION,
|
||||
inference_mode: InferenceMode::Native,
|
||||
gpu_memory_limit_bytes: None,
|
||||
allow_experimental: false,
|
||||
}
|
||||
}
|
||||
fn request() -> GenerationRequest {
|
||||
GenerationRequest {
|
||||
request_id: "synthetic-1".into(),
|
||||
prompt: "x".into(),
|
||||
max_output_tokens: 1,
|
||||
temperature_milli: 0,
|
||||
sampling: Default::default(),
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn explicit_kar_selection_requires_source_and_binds_actual_digests() {
|
||||
let model = pinned_model_descriptor();
|
||||
let mut requested = native_config();
|
||||
// Availability/permission alone never selects KAR.
|
||||
requested.allow_experimental = true;
|
||||
assert!(validate_load(&model, &requested).is_ok());
|
||||
assert!(validate_kar_selection(&requested, false).is_ok());
|
||||
requested.inference_mode = InferenceMode::ExperimentalKarPle {
|
||||
profile_id: KAR_PROFILE.into(),
|
||||
};
|
||||
assert!(validate_load(&model, &requested).is_ok());
|
||||
assert_eq!(
|
||||
validate_kar_selection(&requested, false).unwrap_err().code,
|
||||
ErrorCode::UnsupportedModel
|
||||
);
|
||||
assert!(validate_kar_selection(&requested, true).is_ok());
|
||||
requested.allow_experimental = false;
|
||||
assert!(validate_load(&model, &requested).is_err());
|
||||
requested.allow_experimental = true;
|
||||
requested.inference_mode = InferenceMode::ExperimentalKarPle {
|
||||
profile_id: "wrong".into(),
|
||||
};
|
||||
assert!(validate_load(&model, &requested).is_err());
|
||||
let digest = kar_mode_digest(&[1; 32], &[2; 32]);
|
||||
assert_ne!(digest, MODE_DIGEST);
|
||||
assert_ne!(digest, kar_mode_digest(&[2; 32], &[1; 32]));
|
||||
assert_ne!(digest, kar_mode_digest(&[1; 32], &[3; 32]));
|
||||
let mut loaded = LoadedModel {
|
||||
handle: "synthetic-kar".into(),
|
||||
descriptor: model,
|
||||
load_config_version: LOAD_CONFIG_VERSION,
|
||||
effective_mode: InferenceMode::ExperimentalKarPle {
|
||||
profile_id: KAR_PROFILE.into(),
|
||||
},
|
||||
mode_identity_digest: digest,
|
||||
};
|
||||
assert!(validate_handle(&loaded, None).is_ok());
|
||||
loaded.mode_identity_digest = "sha256:bad".into();
|
||||
assert!(validate_handle(&loaded, None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configured_context_admission_preserves_verified_position_identity() {
|
||||
let constants = InputConstants::test_fixture();
|
||||
let model_bound = Dimension::new(u64::from(constants.context_length())).unwrap();
|
||||
let configured_bound = Dimension::new(128).unwrap();
|
||||
for value in [0, 127] {
|
||||
let position = native_position(&constants, 128, value).unwrap();
|
||||
assert_eq!(position, Position::new(value as u64, model_bound).unwrap());
|
||||
assert_ne!(
|
||||
position,
|
||||
Position::new(value as u64, configured_bound).unwrap()
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
native_position(&constants, 128, 128).unwrap_err().code,
|
||||
ErrorCode::ResourceExhausted
|
||||
);
|
||||
assert!(native_position(&constants, 0, 0).is_err());
|
||||
assert!(native_position(&constants, constants.context_length() + 1, 0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_identity_and_native_refusal_precede_artifact_access() {
|
||||
let model = pinned_model_descriptor();
|
||||
assert_eq!(model.artifact_digest, MODEL_DIGEST);
|
||||
assert!(validate_load(&model, &native_config()).is_ok());
|
||||
let mut config = native_config();
|
||||
config.allow_experimental = true;
|
||||
assert!(validate_load(&model, &config).is_ok());
|
||||
config.inference_mode = InferenceMode::ExperimentalKarPle {
|
||||
profile_id: "synthetic".into(),
|
||||
};
|
||||
assert_eq!(
|
||||
validate_load(&model, &config).unwrap_err().code,
|
||||
ErrorCode::UnsupportedModel
|
||||
);
|
||||
let mut loaded = LoadedModel {
|
||||
handle: "synthetic-handle".into(),
|
||||
descriptor: model.clone(),
|
||||
load_config_version: LOAD_CONFIG_VERSION,
|
||||
effective_mode: InferenceMode::Native,
|
||||
mode_identity_digest: MODE_DIGEST.into(),
|
||||
};
|
||||
assert!(validate_handle(&loaded, None).is_ok());
|
||||
// A KAR-expert Native Load publishes the source-bound digest, never the
|
||||
// plain Native one; each owner accepts only its own.
|
||||
let kar_native = kar_expert_mode_digest(MODE_DIGEST, &[7; 32]);
|
||||
assert_ne!(kar_native, MODE_DIGEST);
|
||||
assert!(validate_handle(&loaded, Some(&kar_native)).is_err());
|
||||
loaded.mode_identity_digest = kar_native.clone();
|
||||
assert!(validate_handle(&loaded, Some(&kar_native)).is_ok());
|
||||
assert!(validate_handle(&loaded, None).is_err());
|
||||
assert!(
|
||||
validate_handle(
|
||||
&loaded,
|
||||
Some(&kar_expert_mode_digest(MODE_DIGEST, &[8; 32]))
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
loaded.mode_identity_digest = MODE_DIGEST.into();
|
||||
// The cold KAR archive hash needs the long budget even in Native mode.
|
||||
assert_eq!(
|
||||
load_reply_timeout(&InferenceMode::Native, false),
|
||||
REPLY_TIMEOUT
|
||||
);
|
||||
assert_eq!(
|
||||
load_reply_timeout(&InferenceMode::Native, true),
|
||||
KAR_LOAD_REPLY_TIMEOUT
|
||||
);
|
||||
loaded.handle = "x".repeat(129);
|
||||
assert!(validate_handle(&loaded, None).is_err());
|
||||
let mut wrong = model;
|
||||
wrong.artifact_digest = SHARD0.into();
|
||||
assert!(validate_load(&wrong, &native_config()).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn request_caps_are_checked_before_acceptance() {
|
||||
let mut r = request();
|
||||
assert!(validate_request(&r).is_ok());
|
||||
r.max_output_tokens = OUTPUT_LIMIT + 1;
|
||||
assert!(validate_request(&r).is_err());
|
||||
r.max_output_tokens = 1;
|
||||
r.temperature_milli = 2001;
|
||||
assert!(validate_request(&r).is_err());
|
||||
r.temperature_milli = 700;
|
||||
assert!(validate_request(&r).is_ok());
|
||||
r.temperature_milli = 0;
|
||||
r.prompt = "x".repeat(PROMPT_LIMIT + 1);
|
||||
assert!(validate_request(&r).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn sampling_requests_are_planned_instead_of_refused() {
|
||||
let mut r = request();
|
||||
// plain greedy: no sampler, the ordinary compact path
|
||||
assert!(matches!(request_sampler(&r, 5), Ok(None)));
|
||||
// temperature: a sampler with the request's seed or the supplied entropy
|
||||
r.temperature_milli = 700;
|
||||
r.sampling.top_p_micro = Some(950_000);
|
||||
r.sampling.top_k = Some(40);
|
||||
let p = request_sampler(&r, 5).unwrap().expect("sampler");
|
||||
assert!(!p.greedy && p.seed == 5 && p.top_k == 40 && p.counter == 0);
|
||||
r.sampling.seed = Some(77);
|
||||
assert_eq!(request_sampler(&r, 5).unwrap().unwrap().seed, 77);
|
||||
// greedy plus a penalty still needs the penalised argmax
|
||||
r.temperature_milli = 0;
|
||||
r.sampling = Default::default();
|
||||
r.sampling.presence_penalty_micro = Some(500_000);
|
||||
let p = request_sampler(&r, 5).unwrap().expect("penalised greedy");
|
||||
assert!(p.greedy && p.penalty_last_n == 64);
|
||||
// out-of-contract fields are refused before acceptance
|
||||
for bad in [
|
||||
|r: &mut GenerationRequest| r.sampling.top_p_micro = Some(1_000_001),
|
||||
|r: &mut GenerationRequest| r.sampling.repetition_penalty_micro = Some(0),
|
||||
|r: &mut GenerationRequest| r.sampling.min_p_micro = Some(2_000_000),
|
||||
|r: &mut GenerationRequest| r.sampling.frequency_penalty_micro = Some(3_000_000),
|
||||
] {
|
||||
let mut r = request();
|
||||
bad(&mut r);
|
||||
assert!(validate_request(&r).is_err());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn utf8_split_tokens_publish_only_complete_prefix() {
|
||||
let mut pending = Utf8Pending::default();
|
||||
assert_eq!(pending.push(&[b'a', 0xf0]).unwrap(), Some("a".into()));
|
||||
assert!(pending.finish().is_err());
|
||||
assert_eq!(pending.push(&[0x9f, 0x98]).unwrap(), None);
|
||||
assert_eq!(pending.push(&[0x80]).unwrap(), Some("😀".into()));
|
||||
assert!(pending.finish().is_ok());
|
||||
assert!(pending.push(&[0xff]).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn utf8_length_replaces_incomplete_unicode_suffix_once() {
|
||||
for suffix in [&[0xe2][..], &[0xf0, 0x9f, 0x98][..]] {
|
||||
let mut pending = Utf8Pending::default();
|
||||
let mut deltas = vec![pending.push(b"a").unwrap().unwrap()];
|
||||
assert_eq!(pending.push(suffix).unwrap(), None);
|
||||
assert!(
|
||||
pending
|
||||
.finish_length(|text| {
|
||||
deltas.push(text);
|
||||
Ok(())
|
||||
})
|
||||
.is_ok()
|
||||
);
|
||||
let mut original = b"a".to_vec();
|
||||
original.extend_from_slice(suffix);
|
||||
assert_eq!(deltas.concat(), String::from_utf8_lossy(&original));
|
||||
assert!(pending.finish().is_ok());
|
||||
assert!(
|
||||
pending
|
||||
.finish_length(|_| panic!("completed suffix emitted twice"))
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn utf8_length_preserves_completed_split_unicode() {
|
||||
let mut pending = Utf8Pending::default();
|
||||
let first = pending.push(&[b'a', 0xf0]).unwrap().unwrap();
|
||||
assert_eq!(pending.push(&[0x9f, 0x98]).unwrap(), None);
|
||||
let last = pending.push(&[0x80]).unwrap().unwrap();
|
||||
assert!(
|
||||
pending
|
||||
.finish_length(|_| panic!("complete Unicode emitted a replacement"))
|
||||
.is_ok()
|
||||
);
|
||||
assert_eq!(first + &last, "a😀");
|
||||
assert!(pending.finish().is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn utf8_stop_keeps_incomplete_unicode_refusal() {
|
||||
for suffix in [&[0xe2][..], &[0xf0, 0x9f, 0x98][..]] {
|
||||
let mut pending = Utf8Pending::default();
|
||||
assert_eq!(pending.push(suffix).unwrap(), None);
|
||||
assert!(pending.finish().is_err());
|
||||
assert_eq!(pending.0, suffix);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn utf8_interior_invalid_remains_refused_at_push() {
|
||||
let mut pending = Utf8Pending::default();
|
||||
assert!(pending.push(&[b'a', 0xff, b'b']).is_err());
|
||||
assert!(
|
||||
pending
|
||||
.finish_length(|_| panic!("invalid interior bytes emitted a replacement"))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn utf8_frame_bound_refuses_before_growth() {
|
||||
let mut pending = Utf8Pending::default();
|
||||
assert!(pending.push(&vec![b'x'; FRAME_LIMIT + 1]).is_err());
|
||||
assert!(pending.0.is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn cancel_is_independent_of_full_control_queue() {
|
||||
let (tx, _rx) = mpsc::sync_channel(1);
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let shared = Arc::new(Shared {
|
||||
ready: AtomicBool::new(true),
|
||||
shutdown: AtomicBool::new(false),
|
||||
active: Mutex::new(Some(Active {
|
||||
id: "synthetic-1".into(),
|
||||
cancel: Arc::clone(&cancel),
|
||||
})),
|
||||
});
|
||||
let mut proxy = Proxy {
|
||||
tx,
|
||||
shared,
|
||||
seen: RecentIds::default(),
|
||||
kar_configured: false,
|
||||
mtp_configured: false,
|
||||
kar_experts_configured: false,
|
||||
kar_expert_native_digest: None,
|
||||
execution: EvaluationExecution::Native,
|
||||
optimized_execution: false,
|
||||
queued_owners: false,
|
||||
streamed_spill: false,
|
||||
retained_scratch: false,
|
||||
resident_owners: false,
|
||||
adaptive_slots: false,
|
||||
original_serve: false,
|
||||
};
|
||||
let (reply, _) = mpsc::sync_channel(1);
|
||||
proxy
|
||||
.send(Command::Load(
|
||||
pinned_model_descriptor(),
|
||||
native_config(),
|
||||
reply,
|
||||
))
|
||||
.unwrap();
|
||||
proxy.cancel("synthetic-1").unwrap();
|
||||
assert!(cancel.load(Ordering::Acquire));
|
||||
assert!(proxy.cancel("unknown").is_err());
|
||||
assert!(proxy.idle().is_err());
|
||||
}
|
||||
#[test]
|
||||
fn prompt_context_admission_is_before_forward() {
|
||||
let tokenizer =
|
||||
Tokenizer::from_vocabulary("gpt2", "qwen35", vec!["x".into()], vec![], None).unwrap();
|
||||
assert_eq!(prepare_prompt(&tokenizer, &request(), 2).unwrap(), vec![0]);
|
||||
assert!(prepare_prompt(&tokenizer, &request(), 1).is_err());
|
||||
let mut r = request();
|
||||
r.prompt.clear();
|
||||
assert!(prepare_prompt(&tokenizer, &r, 2).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn marked_control_token_text_is_encoded_as_text_and_the_templates_own_literals_stay_special() {
|
||||
let (alphabet, _) = leleka_tokenizer::byte_alphabet();
|
||||
let mut tokens: Vec<String> = alphabet.iter().map(char::to_string).collect();
|
||||
tokens.push("<think>".into());
|
||||
tokens.push("</think>".into());
|
||||
let mut types = vec![1u32; 256];
|
||||
types.extend([4, 4]);
|
||||
let tokenizer =
|
||||
Tokenizer::from_vocabulary("gpt2", "qwen35", tokens, vec![], Some(types)).unwrap();
|
||||
let mut r = request();
|
||||
r.max_output_tokens = 1;
|
||||
// The template's own `<think>` and a quoted `</think>` in the message.
|
||||
r.prompt = format!("<think>\n{}", tokenizer.marks().mark("a</think>"));
|
||||
let ids = prepare_prompt(&tokenizer, &r, 100).unwrap();
|
||||
assert_eq!(ids.iter().filter(|&&id| id == 256).count(), 1);
|
||||
assert_eq!(ids.iter().filter(|&&id| id == 257).count(), 0);
|
||||
assert_eq!(tokenizer.decode(&ids).unwrap(), "<think>\na</think>");
|
||||
// A prompt without marks is encoded as before.
|
||||
r.prompt = "<think>\na</think>".into();
|
||||
assert_eq!(
|
||||
prepare_prompt(&tokenizer, &r, 100).unwrap(),
|
||||
tokenizer.encode(&r.prompt, true).unwrap()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//! Incremental UTF-8 publication of generated tokens and the terminal event.
|
||||
use super::*;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Utf8Pending(pub(super) Vec<u8>);
|
||||
impl Utf8Pending {
|
||||
pub(super) fn push(&mut self, bytes: &[u8]) -> Result<Option<String>, BackendError> {
|
||||
if self
|
||||
.0
|
||||
.len()
|
||||
.checked_add(bytes.len())
|
||||
.is_none_or(|len| len > FRAME_LIMIT)
|
||||
{
|
||||
return Err(exhausted("decoded token exceeds output frame limit"));
|
||||
}
|
||||
self.0
|
||||
.try_reserve(bytes.len())
|
||||
.map_err(|_| exhausted("token decoding allocation failed"))?;
|
||||
self.0.extend_from_slice(bytes);
|
||||
let valid = match std::str::from_utf8(&self.0) {
|
||||
Ok(_) => self.0.len(),
|
||||
Err(error) if error.error_len().is_none() => error.valid_up_to(),
|
||||
Err(_) => return Err(unavailable("native token contains invalid UTF8")),
|
||||
};
|
||||
if valid == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let text = std::str::from_utf8(&self.0[..valid])
|
||||
.map_err(|_| unavailable("native UTF8 prefix invalid"))?
|
||||
.to_owned();
|
||||
self.0.drain(..valid);
|
||||
Ok(Some(text))
|
||||
}
|
||||
/// Length may cut a valid code point between tokens. Match the existing
|
||||
/// tokenizer/daemon terminal replacement without advancing model state.
|
||||
pub(super) fn finish_length(
|
||||
&mut self,
|
||||
emit: impl FnOnce(String) -> Result<(), GenerationFailure>,
|
||||
) -> Result<(), GenerationFailure> {
|
||||
if self.0.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
match std::str::from_utf8(&self.0) {
|
||||
Err(error) if error.error_len().is_none() && error.valid_up_to() == 0 => {}
|
||||
_ => return Err(unavailable("native token contains invalid UTF8").into()),
|
||||
}
|
||||
emit("\u{fffd}".to_owned())?;
|
||||
self.0.clear();
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn finish(&self) -> Result<(), BackendError> {
|
||||
if self.0.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(unavailable("generation ended with incomplete UTF8"))
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn emit_terminal(
|
||||
sink: &GenerationSink,
|
||||
terminal: GenerationTerminal,
|
||||
) -> Result<(), ContractError> {
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
match sink.try_emit(GenerationEvent::Terminal(terminal.clone())) {
|
||||
Err(ContractError::GenerationBackpressure)
|
||||
if start.elapsed() < BACKPRESSURE_TIMEOUT =>
|
||||
{
|
||||
thread::sleep(Duration::from_millis(5))
|
||||
}
|
||||
result => return result,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! Admission checks of loads, handles and generation requests.
|
||||
use super::*;
|
||||
|
||||
pub(super) fn validate_load(
|
||||
model: &ModelDescriptor,
|
||||
config: &RuntimeConfig,
|
||||
) -> Result<(), BackendError> {
|
||||
config
|
||||
.validate()
|
||||
.map_err(|_| invalid("invalid load configuration"))?;
|
||||
if model != &pinned_model_descriptor() {
|
||||
return Err(unsupported("unsupported pinned model identity"));
|
||||
}
|
||||
match &config.inference_mode {
|
||||
InferenceMode::Native => {}
|
||||
InferenceMode::ExperimentalKarPle { profile_id } if profile_id == KAR_PROFILE => {}
|
||||
InferenceMode::ExperimentalMtp { profile_id }
|
||||
if profile_id == NATIVE_MTP_PROFILE || profile_id == KAR_MTP_PROFILE => {}
|
||||
_ => return Err(unsupported("experimental mode is not supported")),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn load_reply_timeout(mode: &InferenceMode, kar_experts_configured: bool) -> Duration {
|
||||
if requires_kar(mode)
|
||||
|| kar_experts_configured
|
||||
|| matches!(mode, InferenceMode::ExperimentalMtp { .. })
|
||||
{
|
||||
KAR_LOAD_REPLY_TIMEOUT
|
||||
} else {
|
||||
REPLY_TIMEOUT
|
||||
}
|
||||
}
|
||||
pub(super) fn validate_kar_selection(
|
||||
config: &RuntimeConfig,
|
||||
source_present: bool,
|
||||
) -> Result<(), BackendError> {
|
||||
if requires_kar(&config.inference_mode) && !source_present {
|
||||
return Err(unsupported("KAR PLE operator source is absent"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn requires_kar(mode: &InferenceMode) -> bool {
|
||||
matches!(mode, InferenceMode::ExperimentalKarPle { .. })
|
||||
|| matches!(mode, InferenceMode::ExperimentalMtp { profile_id } if profile_id == KAR_MTP_PROFILE)
|
||||
}
|
||||
pub(super) fn validate_mtp_selection(
|
||||
config: &RuntimeConfig,
|
||||
present: bool,
|
||||
) -> Result<(), BackendError> {
|
||||
if matches!(config.inference_mode, InferenceMode::ExperimentalMtp { .. }) && !present {
|
||||
return Err(unsupported("MTP operator source is absent"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn validate_handle(
|
||||
model: &LoadedModel,
|
||||
kar_expert_native_digest: Option<&str>,
|
||||
) -> Result<(), BackendError> {
|
||||
if model.handle.is_empty()
|
||||
|| model.handle.len() > 128
|
||||
|| model.handle.chars().any(char::is_control)
|
||||
|| model.descriptor != pinned_model_descriptor()
|
||||
|| model.load_config_version != LOAD_CONFIG_VERSION
|
||||
|| !match &model.effective_mode {
|
||||
// With a KAR expert source the Native handle carries the source
|
||||
// identity; it must equal the digest this owner would publish.
|
||||
InferenceMode::Native => {
|
||||
model.mode_identity_digest == kar_expert_native_digest.unwrap_or(MODE_DIGEST)
|
||||
}
|
||||
InferenceMode::ExperimentalKarPle { profile_id } => {
|
||||
profile_id == KAR_PROFILE
|
||||
&& model
|
||||
.mode_identity_digest
|
||||
.strip_prefix("sha256:")
|
||||
.is_some_and(|hex| {
|
||||
hex.len() == 64
|
||||
&& hex
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
|
||||
})
|
||||
}
|
||||
InferenceMode::ExperimentalMtp { profile_id } => {
|
||||
(profile_id == NATIVE_MTP_PROFILE || profile_id == KAR_MTP_PROFILE)
|
||||
&& model
|
||||
.mode_identity_digest
|
||||
.strip_prefix("sha256:")
|
||||
.is_some_and(|hex| {
|
||||
hex.len() == 64
|
||||
&& hex
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
|
||||
})
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
{
|
||||
return Err(invalid("invalid loaded model identity"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn validate_request(request: &GenerationRequest) -> Result<(), BackendError> {
|
||||
if request.request_id.is_empty()
|
||||
|| request.request_id.len() > 128
|
||||
|| request.request_id.chars().any(char::is_control)
|
||||
|| request.prompt.len() > PROMPT_LIMIT
|
||||
|| request.max_output_tokens == 0
|
||||
|| request.max_output_tokens > OUTPUT_LIMIT
|
||||
|| request_sampler(request, 1).is_err()
|
||||
{
|
||||
return Err(invalid("unsupported generation request"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user