diff --git a/AGENTS.md b/AGENTS.md index 2318de4e..eb190933 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -240,7 +240,8 @@ in the same change that adds, removes or renames a folder it lists. node, which unified GPUs share. - **occupancy**: what is in use in a memory pool: measured use per deployment, other use, and claims. A **claim** is a starting model deployment's estimate, counted until it reports measured - use; advisory, never a reservation. + use, or for its whole life when it is claimed while running (growing engines); advisory, never a + reservation. - **demand**: a configuration's estimated bytes per memory pool on one target. - **placement preview**: the capacity component's answer for one configuration on one target: each pool's occupancy with the demand and the fit line. diff --git a/backend/AGENTS.md b/backend/AGENTS.md index b9c2bda2..d04a13e7 100644 --- a/backend/AGENTS.md +++ b/backend/AGENTS.md @@ -74,6 +74,7 @@ backend/ - Keep one inherent impl directly after its type unless responsibility modules justify a split. Put exactly one blank line between functions, impl blocks and adjacent enum variants (the blank line goes before a variant's attributes and docs). - Every authored module opens with a `//!` doc a junior developer can read first: a one-line summary, a blank line, then two or three plain sentences on what it does for its callers and its guarantees, naming no internal items. Library crates name the component or capability. Major components also state their boundary. Model: `backend/catalog/src/sizing/expression.rs`. - Give public value and error types and non-trivial public APIs short capability-focused docs. +- An engine that reads its own variant of a per-engine enum (configuration, resolved state) matches every other variant with `_`, so adding an engine doesn't touch the others. Keep matches exhaustive where each engine needs its own answer, such as dispatch and the engine list. - Prefer root-cause fixes over lint suppressions. Every suppression gives `reason = "..."`, with `#[expect]` when the lint reliably fires; generated bindings may use one justified crate-level suppression. - `backend/proto` holds only generated bindings and generic protobuf utilities; [`proto/AGENTS.md`](../proto/AGENTS.md) owns generation. diff --git a/backend/core/src/application/workloads.rs b/backend/core/src/application/workloads.rs index 6fdf8f9e..a7a9accd 100644 --- a/backend/core/src/application/workloads.rs +++ b/backend/core/src/application/workloads.rs @@ -95,6 +95,7 @@ pub(crate) fn node_workloads( memory_architecture, device_ids, estimate: Estimate::default(), + claim_while_running: false, attributed: attributed.filter(|attributed| !attributed.is_empty()), }); } diff --git a/backend/core/src/hardware/capacity/mod.rs b/backend/core/src/hardware/capacity/mod.rs index 02116e8f..12392629 100644 --- a/backend/core/src/hardware/capacity/mod.rs +++ b/backend/core/src/hardware/capacity/mod.rs @@ -62,10 +62,11 @@ impl TargetCapacity { } /// Counts in the target's pools what the workloads of its node hold there, each in the pools - /// it shares with the target: its own devices and the node's host pool. Starting workloads - /// claim memory beyond what is measured of them, and a claim whose size or devices aren't known - /// makes the pools it may use unknown. Other workloads only split the measured use: what the - /// node attributes to them, or a ready workload's estimate where nothing is attributed. + /// it shares with the target: its own devices and the node's host pool. Starting workloads, + /// and ready ones claimed while running, claim memory beyond what is measured of them, and a + /// claim whose size or devices aren't known makes the pools it may use unknown. Other + /// workloads only split the measured use: what the node attributes to them, or a ready + /// workload's estimate where nothing is attributed. pub(crate) fn with_workloads(mut self, workloads: &[Workload]) -> Self { occupy(&mut self.pools, workloads); self @@ -236,9 +237,9 @@ pub(crate) struct Occupancy { /// it moves with every observation and is never retained. pub(crate) measured_bytes: Option, - /// Bytes starting workloads are expected to take beyond what is measured of them: their - /// claims. Absent when a starting workload that may use the pool has an unknown claim there. - /// Advisory, never a reservation. + /// Bytes starting workloads, and ready ones claimed while running, are expected to take beyond + /// what is measured of them: their claims. Absent when a claiming workload that may use the + /// pool has an unknown claim there. Advisory, never a reservation. pub(crate) claimed_bytes: Option, /// What each workload holds of the measured and claimed bytes, in workload order; the rest of @@ -290,7 +291,7 @@ pub(crate) enum SegmentSource { /// A ready workload's estimate standing for measured use the node doesn't attribute to it. Estimated, - /// A starting workload's estimate beyond what is measured of it. + /// A claiming workload's estimate beyond what is measured of it. Claimed, /// Measured use no workload accounts for. @@ -305,7 +306,8 @@ pub(crate) enum SegmentSource { /// estimate: its accelerator estimate counts beyond what the node already attributes to it, while /// its host estimate counts whole, since attribution sees only accelerator memory and host memory /// loads through the whole start. Once ready and measured, its claim ends and it holds only -/// measured use. +/// measured use, unless it is claimed while running: it then holds the larger of its estimate and +/// its measured use in each pool for its whole life. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Workload { /// Identity of the workload, which a pool's segments name. @@ -326,6 +328,10 @@ pub(crate) struct Workload { pub(crate) estimate: Estimate, + /// Whether the workload keeps claiming its estimate once ready, because it may take that + /// memory at any point of its life. + pub(crate) claim_while_running: bool, + /// Accelerator memory the node attributes to the workload's processes, by device id; absent /// until the node attributes any. pub(crate) attributed: Option>, @@ -451,6 +457,45 @@ impl Workload { (SegmentSource::Estimated, estimated) } + /// Whether the workload is ready and still claims its estimate beyond what is measured of it. + fn claims_while_ready(&self) -> bool { + self.claim_while_running && self.phase == WorkloadPhase::Ready + } + + /// The workload's estimate in `pool` while it runs: its accelerator share on one of its + /// devices, its accelerator and host estimates together in a unified target's host pool, and + /// nothing elsewhere. Absent when it may use the pool but that estimate or its devices aren't + /// known. + /// + /// The host estimate counts on unified memory because, on macOS, what the node attributes there + /// is the process's whole footprint, host memory included, and an engine that grows after ready + /// fills its host estimate after ready too. Where attribution covers only accelerator memory, + /// such as a GB10, this counts host use twice; no engine that grows after ready runs there. + fn running_estimate_in(&self, pool: &Pool) -> Option { + match (self.memory_architecture, pool.kind) { + (MemoryArchitecture::Dedicated, PoolKind::Device) => { + if self.device_ids.is_empty() { + return None; + } + let Some(index) = self.device_index(pool) else { + return Some(0); + }; + Some(device_share( + self.estimate.accelerator_bytes?, + self.device_ids.len(), + index, + )) + } + (MemoryArchitecture::Unified, PoolKind::Host) => Some( + self.estimate + .accelerator_bytes? + .saturating_add(self.estimate.host_bytes.unwrap_or_default()), + ), + (MemoryArchitecture::Dedicated, PoolKind::Host) + | (MemoryArchitecture::Unified, PoolKind::Device) => Some(0), + } + } + /// Whether the workload may use `pool`: a device it holds, or any device when its devices /// don't resolve; the host pool when its devices share host memory, or when it has a host /// estimate beside dedicated devices. @@ -620,7 +665,8 @@ struct HostMemory { } /// Counts in each pool what the workloads hold there: claims of starting workloads first, then -/// what the others hold of the measured use, each segment in workload order. +/// what the others hold of the measured use, each segment in workload order. A ready workload +/// claimed while running also claims what its estimate leaves above its share of that use. fn occupy(pools: &mut [Pool], workloads: &[Workload]) { for pool in pools { // Attribution can be newer than the pool's reading, so what it accounts for never @@ -668,6 +714,20 @@ fn occupy(pools: &mut [Pool], workloads: &[Workload]) { let bytes = bytes.min(measured_left); measured_left -= bytes; segments.push((index, workload.segment(source, bytes))); + if !workload.claims_while_ready() { + continue; + } + match workload.running_estimate_in(pool) { + Some(estimate) => { + let claimed = estimate.saturating_sub(bytes); + pool.occupancy.claimed_bytes = pool + .occupancy + .claimed_bytes + .map(|total| total.saturating_add(claimed)); + segments.push((index, workload.segment(SegmentSource::Claimed, claimed))); + } + None => pool.occupancy.claimed_bytes = None, + } } segments.sort_by_key(|(index, _)| *index); pool.occupancy.workloads.extend( diff --git a/backend/core/src/hardware/capacity/node.rs b/backend/core/src/hardware/capacity/node.rs index 58304cda..89bb15d5 100644 --- a/backend/core/src/hardware/capacity/node.rs +++ b/backend/core/src/hardware/capacity/node.rs @@ -695,6 +695,7 @@ mod tests { key, phase: WorkloadPhase::Ready, expects_use: true, + claim_while_running: false, memory_architecture: Dedicated, device_ids: vec![gpu.to_owned()], estimate, diff --git a/backend/core/src/hardware/capacity/tests.rs b/backend/core/src/hardware/capacity/tests.rs index e53632f1..08fe23ce 100644 --- a/backend/core/src/hardware/capacity/tests.rs +++ b/backend/core/src/hardware/capacity/tests.rs @@ -415,6 +415,7 @@ fn a_starting_workload_counts_its_accelerator_memory_once_and_holds_its_host_est let claim = |attributed: Option| Workload { key: WorkloadKey::inference("starting"), expects_use: true, + claim_while_running: false, phase: WorkloadPhase::Starting, memory_architecture, device_ids: vec![gpu.clone()], @@ -498,6 +499,7 @@ fn a_unified_claim_subtracts_all_of_its_attributed_memory_whatever_the_device_id let claim = Workload { key: WorkloadKey::inference("starting"), expects_use: true, + claim_while_running: false, phase: WorkloadPhase::Starting, memory_architecture: Unified, device_ids: Vec::new(), @@ -533,6 +535,7 @@ fn an_unsized_starting_workload_makes_the_pools_it_may_use_unknown() { let unsized_claim = |memory_architecture, device_ids: Vec| Workload { key: WorkloadKey::inference("starting"), expects_use: true, + claim_while_running: false, phase: WorkloadPhase::Starting, memory_architecture, device_ids, @@ -608,6 +611,7 @@ fn a_starting_workload_with_an_unknown_claim_keeps_its_measured_use() { let starting = |device_ids: Vec| Workload { key: WorkloadKey::inference("starting"), expects_use: true, + claim_while_running: false, phase: WorkloadPhase::Starting, memory_architecture: Dedicated, device_ids, @@ -648,6 +652,7 @@ fn a_starting_workload_whose_gpus_dont_resolve_makes_its_nodes_gpu_pools_unknown let claim = Workload { key: WorkloadKey::inference("starting"), expects_use: true, + claim_while_running: false, phase: WorkloadPhase::Starting, memory_architecture: Dedicated, device_ids: Vec::new(), @@ -681,6 +686,7 @@ fn attribution_newer_than_the_gpu_reading_subtracts_at_most_its_measured_use() { let claim = |estimate_bytes: u64, attributed: u64| Workload { key: WorkloadKey::inference("starting"), expects_use: true, + claim_while_running: false, phase: WorkloadPhase::Starting, memory_architecture: Dedicated, device_ids: vec![gpu.clone()], @@ -730,6 +736,7 @@ fn a_claim_counts_only_in_the_pools_it_shares_with_the_target() { let claim = Workload { key: WorkloadKey::inference("starting"), expects_use: true, + claim_while_running: false, phase: WorkloadPhase::Starting, memory_architecture: Dedicated, device_ids: vec![gpus[0].clone()], @@ -771,6 +778,7 @@ fn a_preview_draws_each_pool_with_the_verdicts_the_evaluator_gives_on_named_mach let ready = |gpu: &str, memory_architecture, estimate, attributed: Option| Workload { key: WorkloadKey::inference("running"), expects_use: true, + claim_while_running: false, phase: WorkloadPhase::Ready, memory_architecture, device_ids: vec![gpu.to_owned()], @@ -872,6 +880,48 @@ fn a_preview_draws_each_pool_with_the_verdicts_the_evaluator_gives_on_named_mach ), ], ), + // A running model claimed while running keeps claiming what its attributed use hasn't + // reached yet. + ( + "rtx-5090 with a model claimed while running", + &rtx_5090_desktop, + vec![MachineWorkload { + gpu_bytes: [(rtx_5090_gpu.to_owned(), 4 * GIB)].into(), + host_bytes: GIB, + }], + vec![Workload { + claim_while_running: true, + ..ready( + rtx_5090_gpu, + Dedicated, + estimate(10 * GIB, GIB), + Some(4 * GIB), + ) + }], + estimate(8 * GIB, 0), + vec![ + device_pool( + vec![ + segment(SegmentSource::Measured, "running", 4 * GIB), + segment(SegmentSource::Claimed, "running", 6 * GIB), + other(497 * MIB), + previewed(8 * GIB), + ], + Fits, + 0, + false, + ), + host_pool( + 64 * GIB, + HOST_64G_LINE, + vec![ + segment(SegmentSource::Estimated, "running", GIB), + other(4 * GIB), + ], + Fits, + ), + ], + ), // One byte past the line, the demand still fits under the total but not the headroom. ( "rtx-5090 within the headroom", @@ -992,6 +1042,7 @@ fn a_preview_of_an_unknown_pool_draws_what_is_known_and_judges_nothing() { let unsized_workload = Workload { key: WorkloadKey::inference("starting"), expects_use: true, + claim_while_running: false, phase: WorkloadPhase::Starting, memory_architecture: Dedicated, device_ids: vec![gpus[0].clone()], @@ -1066,6 +1117,7 @@ fn ready_and_stopping_workloads_split_measured_use_without_changing_what_is_free let workload = |workload_id: &str, phase, attributed: Option| Workload { key: WorkloadKey::inference(workload_id), expects_use: true, + claim_while_running: false, phase, memory_architecture: Dedicated, device_ids: vec![gpu.clone()], @@ -1095,6 +1147,114 @@ fn ready_and_stopping_workloads_split_measured_use_without_changing_what_is_free assert_eq!(gpu_pool.occupancy.other_bytes(), Some(0)); } +#[test] +fn a_workload_claimed_while_running_holds_the_larger_of_its_estimate_and_its_measured_use() { + const RTX_5090_TOTAL: u64 = 32_607 * MIB; + const MAC_TOTAL: u64 = 64 * GIB; + const MAC_IDLE_USED: u64 = 8 * GIB; + let ready = |gpu: &str, memory_architecture, claim_while_running, attributed: u64| Workload { + key: WorkloadKey::inference("ready"), + expects_use: true, + claim_while_running, + phase: WorkloadPhase::Ready, + memory_architecture, + device_ids: vec![gpu.to_owned()], + estimate: Estimate { + accelerator_bytes: Some(10 * GIB), + host_bytes: Some(GIB), + }, + attributed: (attributed > 0).then(|| BTreeMap::from([(gpu.to_owned(), attributed)])), + }; + let pools = |machine: &str, gpu_bytes: u64, workload: &dyn Fn(&str) -> Workload| { + let description = described(machine); + let gpu = description.gpu_ids().next().expect("a GPU").to_owned(); + let snapshot = description + .render( + &[MachineWorkload { + gpu_bytes: [(gpu.clone(), gpu_bytes)].into(), + host_bytes: 0, + }], + SystemTime::now(), + ) + .expect("rendered snapshot"); + snapshot_capacity(&snapshot, vec![gpu.as_str()]) + .with_workloads(&[workload(&gpu)]) + .pools + }; + + // On a dedicated GPU it claims the rest of its accelerator estimate; its host estimate stands + // for its host use. + let growing = pools("rtx-5090", 4 * GIB, &|gpu| { + ready(gpu, Dedicated, true, 4 * GIB) + }); + assert_eq!( + growing[0].occupancy.workloads, + vec![ + segment(SegmentSource::Measured, "ready", 4 * GIB), + segment(SegmentSource::Claimed, "ready", 6 * GIB), + ] + ); + assert_eq!(growing[0].occupancy.claimed_bytes, Some(6 * GIB)); + assert_eq!( + growing[0].free_bytes(), + Some(RTX_5090_TOTAL - RESERVED - 10 * GIB) + ); + assert_eq!( + growing[1].occupancy.workloads, + vec![segment(SegmentSource::Estimated, "ready", GIB)] + ); + assert_eq!(growing[1].occupancy.claimed_bytes, Some(0)); + + // An engine that doesn't grow claims nothing once ready. + let holding = pools("rtx-5090", 4 * GIB, &|gpu| { + ready(gpu, Dedicated, false, 4 * GIB) + }); + assert_eq!( + holding[0].occupancy.workloads, + vec![segment(SegmentSource::Measured, "ready", 4 * GIB)] + ); + assert_eq!(holding[0].occupancy.claimed_bytes, Some(0)); + assert_eq!( + holding[0].free_bytes(), + Some(RTX_5090_TOTAL - RESERVED - 4 * GIB) + ); + + // Measured past its estimate, it claims nothing and all of its use is its own. + let past = pools("rtx-5090", 12 * GIB, &|gpu| { + ready(gpu, Dedicated, true, 12 * GIB) + }); + assert_eq!( + past[0].occupancy.workloads, + vec![segment(SegmentSource::Measured, "ready", 12 * GIB)] + ); + assert_eq!(past[0].occupancy.claimed_bytes, Some(0)); + + // On unified memory it claims the rest of both estimates in the host pool. + let unified = pools("mac-64g", 4 * GIB, &|gpu| { + ready(gpu, Unified, true, 4 * GIB) + }); + assert_eq!( + unified[0].occupancy.workloads, + vec![ + segment(SegmentSource::Measured, "ready", 4 * GIB), + segment(SegmentSource::Claimed, "ready", 7 * GIB), + ] + ); + assert_eq!(unified[0].occupancy.claimed_bytes, Some(7 * GIB)); + assert_eq!( + unified[0].free_bytes(), + Some(MAC_TOTAL - MAC_IDLE_USED - 11 * GIB) + ); + + // With nothing attributed, its estimate stands for its use and it claims nothing. + let unattributed = pools("mac-64g", 4 * GIB, &|gpu| ready(gpu, Unified, true, 0)); + assert_eq!( + unattributed[0].occupancy.workloads, + vec![segment(SegmentSource::Estimated, "ready", 11 * GIB)] + ); + assert_eq!(unattributed[0].occupancy.claimed_bytes, Some(0)); +} + #[test] fn an_application_named_in_a_preview_splits_other_use_without_changing_its_verdicts() { const TOTAL: u64 = 32_607 * MIB; @@ -1111,6 +1271,7 @@ fn an_application_named_in_a_preview_splits_other_use_without_changing_its_verdi key: WorkloadKey::inference("model"), phase: WorkloadPhase::Ready, expects_use: true, + claim_while_running: false, memory_architecture: Dedicated, device_ids: vec![gpu.clone()], estimate: Estimate::default(), diff --git a/backend/core/src/model/compatibility.rs b/backend/core/src/model/compatibility.rs index e0fc7bf2..be9c960f 100644 --- a/backend/core/src/model/compatibility.rs +++ b/backend/core/src/model/compatibility.rs @@ -41,7 +41,7 @@ use crate::{ }, model::{ advisory::local_deployment_advisories, - engine::{EngineIntegrationRegistry, engine_artifact_kinds}, + engine::{EngineIntegrationRegistry, engine_artifact_kinds, grows_after_ready}, resolution::{ ModelLaunchResolutionError, apply_profile_defaults, resolve_local_launch_on_selected_target, select_profile_configuration, @@ -303,7 +303,8 @@ pub(crate) fn evaluate_profile( /// the accelerator memory its node attributes to it. Deployments queued, preparing, downloading, /// loading or warming up are starting and claim their estimate, an unknown size without a /// resolved estimate, and so do ready ones whose memory no reading has measured yet; other ready -/// ones count their measured use, and the others only what is attributed to them. +/// ones count their measured use, or the larger of it and their estimate when their engine path +/// grows after ready, and the others only what is attributed to them. pub(crate) fn node_workloads( deployments: &[ModelDeployment], inventory: Option<&TargetCapabilityInventory>, @@ -372,6 +373,13 @@ pub(crate) fn node_workloads( host_bytes: sizing.host_memory_bytes, }) .unwrap_or_default(), + claim_while_running: local + .engine_artifact + .as_ref() + .zip(local.resolved_engine_state.as_ref()) + .is_some_and(|(artifact, state)| { + grows_after_ready(artifact.engine_kind, state) + }), attributed, }); } @@ -738,6 +746,7 @@ mod tests { phase, // Only starting and ready deployments are expected to hold memory. expects_use: phase != WorkloadPhase::Other, + claim_while_running: false, memory_architecture: MemoryArchitecture::Dedicated, device_ids: vec!["GPU-0".to_owned()], estimate: Estimate { @@ -800,6 +809,58 @@ mod tests { ); } + #[test] + fn an_omlx_deployment_is_claimed_while_running() { + use dotcore_proto::dotcore::{ + engine::v1::EngineKind, + model::v1::{ModelDeploymentStatus, model_deployment_snapshot}, + }; + + let (target, inventory) = + crate::test_support::execution_target_capabilities(ExecutionPlatform::linux_amd64()); + let deployment = |engine_kind: EngineKind| { + let mut deployment = sized_deployment(&target, ModelDeploymentStatus::Ready, None); + if let Some(model_deployment_snapshot::Source::Local(local)) = deployment + .snapshot + .as_mut() + .and_then(|snapshot| snapshot.source.as_mut()) + { + local + .engine_artifact + .as_mut() + .expect("engine artifact") + .engine_kind = engine_kind as i32; + } + deployment.model_deployment_id = engine_kind.as_str_name().to_owned(); + deployment + }; + + let workloads = node_workloads( + &[ + deployment(EngineKind::Omlx), + deployment(EngineKind::LlamaCpp), + ], + Some(&inventory), + ); + + assert_eq!( + workloads[&target.site_node_id] + .iter() + .map(|workload| (workload.key.clone(), workload.claim_while_running)) + .collect::>(), + [ + ( + crate::hardware::capacity::WorkloadKey::inference("ENGINE_KIND_OMLX"), + true + ), + ( + crate::hardware::capacity::WorkloadKey::inference("ENGINE_KIND_LLAMA_CPP"), + false + ), + ] + ); + } + #[test] fn a_ready_deployment_keeps_its_claim_until_its_memory_is_measured() { use dotcore_proto::dotcore::{ diff --git a/backend/core/src/model/controller/operations.rs b/backend/core/src/model/controller/operations.rs index 1ca599c8..4ba60f02 100644 --- a/backend/core/src/model/controller/operations.rs +++ b/backend/core/src/model/controller/operations.rs @@ -1488,6 +1488,7 @@ mod tests { key: WorkloadKey::applications("app"), phase: WorkloadPhase::Other, expects_use: true, + claim_while_running: false, memory_architecture: MemoryArchitecture::Dedicated, device_ids: vec!["GPU-a".to_owned()], estimate: Estimate::default(), diff --git a/backend/core/src/model/controller/state.rs b/backend/core/src/model/controller/state.rs index 2adb4736..ddeaf8d9 100644 --- a/backend/core/src/model/controller/state.rs +++ b/backend/core/src/model/controller/state.rs @@ -705,6 +705,15 @@ pub(super) fn engine_startup_failed_state( gib(*free_bytes), ), ), + Some(StartupRefusal::UnsupportedOperatingSystem { + required, found, .. + }) => ( + "engine_unsupported_operating_system", + format!( + "The engine needs {required} or newer and the node runs {found}; update the \ + node's operating system or deploy the model with another engine" + ), + ), }; state.failure = Some(ModelDeploymentFailure { code: code.to_owned(), @@ -1357,6 +1366,39 @@ mod tests { ); } + #[test] + fn an_operating_system_refusal_names_the_required_and_found_versions() { + const LINE: &str = "omlx: macOS 26 or newer is required, found 15.5"; + let refusal = StartupRefusal::UnsupportedOperatingSystem { + required: "macOS 26".to_owned(), + found: "macOS 15.5".to_owned(), + line: LINE.to_owned(), + }; + + let failed = engine_startup_failed_state( + &loading_state(), + Some(&refusal), + vec![ + "Stage: engine startup".to_owned(), + format!("Engine refusal: {LINE}"), + ], + ); + + assert_eq!( + failed.failure, + Some(ModelDeploymentFailure { + code: "engine_unsupported_operating_system".to_owned(), + message: "The engine needs macOS 26 or newer and the node runs macOS 15.5; update \ + the node's operating system or deploy the model with another engine" + .to_owned(), + diagnostics: vec![ + "Stage: engine startup".to_owned(), + format!("Engine refusal: {LINE}"), + ], + }) + ); + } + #[test] fn engine_image_acquisition_failures_carry_the_loader_output_tail() { let state = super::engine_image_acquisition_failed_state( diff --git a/backend/core/src/model/engine/declaration.rs b/backend/core/src/model/engine/declaration.rs index 5975f88e..61ce615d 100644 --- a/backend/core/src/model/engine/declaration.rs +++ b/backend/core/src/model/engine/declaration.rs @@ -294,12 +294,13 @@ mod tests { } #[test] - fn only_vllm_and_strata_launches_require_sizing() { + fn only_vllm_strata_and_omlx_launches_require_sizing() { for (engine_kind, expected) in [ (EngineKind::Vllm, true), (EngineKind::LlamaCpp, false), (EngineKind::Ninfer, false), (EngineKind::Strata, true), + (EngineKind::Omlx, true), (EngineKind::Unspecified, false), ] { let release = EngineRelease { diff --git a/backend/core/src/model/engine/definition.rs b/backend/core/src/model/engine/definition.rs index 243d66f2..d584a787 100644 --- a/backend/core/src/model/engine/definition.rs +++ b/backend/core/src/model/engine/definition.rs @@ -1,6 +1,6 @@ //! The behavior every supported inference engine provides, and the single list of those engines. //! -//! Each engine package (llama.cpp, vLLM, ninfer, Strata) describes itself once: how its catalog +//! Each engine package (llama.cpp, vLLM, ninfer, Strata, oMLX) describes itself once: how its catalog //! declarations are validated, how options become a launch plan and container workload, how //! readiness is probed, and which transport reaches it. Catalog validation, deployment //! realization, and the engine integration registry all look engines up here by kind, so adding @@ -23,7 +23,7 @@ use dotcore_proto::dotcore::{ use dotcore_runtime::{ExecutionTarget, LoopbackEndpoint, WorkloadSpec}; use super::{ - EngineSettings, llama_cpp, ninfer, realization::ResolvedEngineSelection, + EngineSettings, llama_cpp, ninfer, omlx, realization::ResolvedEngineSelection, startup_facts::StartupFactExtractor, startup_refusal::StartupRefusal, strata, vllm, }; use crate::{ @@ -32,11 +32,12 @@ use crate::{ }; /// Every supported engine, keyed by its unique engine kind. -pub(crate) static ENGINES: [&dyn EngineDefinition; 4] = [ +pub(crate) static ENGINES: [&dyn EngineDefinition; 5] = [ &llama_cpp::LlamaCpp, &vllm::Vllm, &ninfer::Ninfer, &strata::Strata, + &omlx::Omlx, ]; /// Stateless, engine-owned behavior selected by engine kind. @@ -74,6 +75,13 @@ pub(crate) trait EngineDefinition: Send + Sync { false } + /// Whether an engine path with these settings takes more memory after it is ready, so a + /// deployment's estimate counts for its whole life; glue for what the release's declaration + /// can't express per configuration. + fn grows_after_ready(&self, _settings: EngineSettings<'_>) -> bool { + false + } + /// Rejects complete engine parameter values by the engine's own launch limits, beyond the /// context behavior's checks and each value's range. Launch resolution applies it after sizing /// derivations. @@ -286,6 +294,7 @@ mod tests { EngineKind::Vllm, EngineKind::Ninfer, EngineKind::Strata, + EngineKind::Omlx, ] { assert_eq!( definition(kind as i32).map(|engine| engine.kind()), @@ -301,6 +310,7 @@ mod tests { for engine in ENGINES { let expected: &[WorkloadArtifactKind] = match engine.kind() { EngineKind::LlamaCpp => &[WorkloadArtifactKind::Oci, WorkloadArtifactKind::Nix], + EngineKind::Omlx => &[WorkloadArtifactKind::Nix], _ => &[WorkloadArtifactKind::Oci], }; assert_eq!(engine.artifact_kinds(), expected, "{}", engine.name()); diff --git a/backend/core/src/model/engine/llama_cpp/declaration.rs b/backend/core/src/model/engine/llama_cpp/declaration.rs index 2ac6fdce..839b5255 100644 --- a/backend/core/src/model/engine/llama_cpp/declaration.rs +++ b/backend/core/src/model/engine/llama_cpp/declaration.rs @@ -816,9 +816,7 @@ mod tests { .and_then(|payload| payload.configuration.as_mut()) .and_then(|payload| match payload { Configuration::LlamaCpp(payload) => Some(payload), - Configuration::Vllm(_) | Configuration::Ninfer(_) | Configuration::Strata(_) => { - None - } + _ => None, }) .expect("llama.cpp payload"); let vision = payload.option_realizations[0] @@ -870,9 +868,7 @@ mod tests { .and_then(|payload| payload.configuration.as_mut()) .and_then(|payload| match payload { Configuration::LlamaCpp(payload) => Some(payload), - Configuration::Vllm(_) | Configuration::Ninfer(_) | Configuration::Strata(_) => { - None - } + _ => None, }) .expect("llama.cpp payload"); let mtp = payload.option_realizations[1] diff --git a/backend/core/src/model/engine/llama_cpp/plan.rs b/backend/core/src/model/engine/llama_cpp/plan.rs index cda0dc50..0f52a7b4 100644 --- a/backend/core/src/model/engine/llama_cpp/plan.rs +++ b/backend/core/src/model/engine/llama_cpp/plan.rs @@ -239,7 +239,7 @@ fn resolved_state( .and_then(|state| state.state.as_ref()) .and_then(|state| match state { State::LlamaCpp(state) => Some(state), - State::Vllm(_) | State::Ninfer(_) | State::Strata(_) => None, + _ => None, }) .ok_or(LlamaCppPlanError::InvalidResolvedState) } diff --git a/backend/core/src/model/engine/llama_cpp/realization.rs b/backend/core/src/model/engine/llama_cpp/realization.rs index 7deda06f..3645066f 100644 --- a/backend/core/src/model/engine/llama_cpp/realization.rs +++ b/backend/core/src/model/engine/llama_cpp/realization.rs @@ -203,7 +203,7 @@ fn llama_cpp_payload( .and_then(|payload| payload.configuration.as_ref()) .and_then(|payload| match payload { Configuration::LlamaCpp(payload) => Some(payload), - Configuration::Vllm(_) | Configuration::Ninfer(_) | Configuration::Strata(_) => None, + _ => None, }) } diff --git a/backend/core/src/model/engine/mod.rs b/backend/core/src/model/engine/mod.rs index d4fad714..9f3eea74 100644 --- a/backend/core/src/model/engine/mod.rs +++ b/backend/core/src/model/engine/mod.rs @@ -28,6 +28,7 @@ pub(crate) use registry::{ pub(crate) mod llama_cpp; pub(crate) mod loopback_http; pub(crate) mod ninfer; +pub(crate) mod omlx; pub(crate) mod openai_compatible_transport; pub(crate) mod strata; mod system_one_transport; @@ -55,3 +56,13 @@ pub(crate) fn selectable_auxiliary_artifact_sets( pub(crate) fn engine_artifact_kinds(kind: i32) -> &'static [dotcore_domain::WorkloadArtifactKind] { definition::definition(kind).map_or(&[], |engine| engine.artifact_kinds()) } + +/// Returns whether the engine path of a resolved engine state, on the engine of raw kind `kind`, +/// takes more memory after it is ready; an unsupported kind doesn't. +pub(crate) fn grows_after_ready( + kind: i32, + state: &dotcore_proto::dotcore::engine::v1::ResolvedEngineModelState, +) -> bool { + definition::definition(kind) + .is_some_and(|engine| engine.grows_after_ready(EngineSettings::Resolved(state))) +} diff --git a/backend/core/src/model/engine/ninfer/plan.rs b/backend/core/src/model/engine/ninfer/plan.rs index 33db49f8..3803b8cc 100644 --- a/backend/core/src/model/engine/ninfer/plan.rs +++ b/backend/core/src/model/engine/ninfer/plan.rs @@ -226,7 +226,7 @@ fn resolved_state( .and_then(|state| state.state.as_ref()) .and_then(|state| match state { State::Ninfer(state) => Some(state), - State::LlamaCpp(_) | State::Vllm(_) | State::Strata(_) => None, + _ => None, }) .ok_or(NinferPlanError::InvalidResolvedState) } diff --git a/backend/core/src/model/engine/ninfer/realization.rs b/backend/core/src/model/engine/ninfer/realization.rs index ff33fb73..16dd5e31 100644 --- a/backend/core/src/model/engine/ninfer/realization.rs +++ b/backend/core/src/model/engine/ninfer/realization.rs @@ -40,7 +40,7 @@ pub(crate) fn realize_model( .and_then(|payload| payload.configuration.as_ref()) .and_then(|payload| match payload { Configuration::Ninfer(payload) => Some(payload), - Configuration::LlamaCpp(_) | Configuration::Vllm(_) | Configuration::Strata(_) => None, + _ => None, }) .ok_or_else(|| anyhow::anyhow!("configuration has no ninfer payload"))?; let fixed_settings = payload diff --git a/backend/core/src/model/engine/omlx/binding.rs b/backend/core/src/model/engine/omlx/binding.rs new file mode 100644 index 00000000..131878c7 --- /dev/null +++ b/backend/core/src/model/engine/omlx/binding.rs @@ -0,0 +1,166 @@ +//! Binds one oMLX loopback service to the engine-neutral inference contract. +//! +//! The binding performs exactly one transport attempt through the shared OpenAI-compatible +//! loopback transport and preserves cancellation, fallback disposition, streaming, and +//! passthrough response evidence for the router. It recognizes oMLX's refusal of a chat prompt +//! too large for the deployment, so clients learn to shorten the request instead of seeing an +//! engine failure. Every other refusal, such as its memory guard turning a prompt away, passes +//! through unclassified. + +use std::sync::Arc; + +use crate::inference::{EngineInvoker, EngineTransportFactory, InvalidRequest}; +use crate::model::engine::loopback_http::{LoopbackInvoker, RejectionClassifiers}; + +/// Creates endpoint-bound oMLX transport invokers for engine bindings. +pub(crate) struct OmlxTransportFactory; + +impl EngineTransportFactory for OmlxTransportFactory { + fn bind_loopback(&self, port: u16, served_model_id: String) -> Arc { + LoopbackInvoker::bind( + port, + served_model_id, + super::REQUEST_KINDS, + RejectionClassifiers { + chat: Some(classify_chat_rejection), + decision: None, + }, + ) + } +} + +/// Recognizes oMLX's refusal of a chat prompt larger than the deployment's context. +/// +/// oMLX names that refusal with OpenAI's error code on an HTTP 400, so the code is matched rather +/// than the message. +fn classify_chat_rejection(status: u16, body: &[u8]) -> Option { + let body = serde_json::from_slice::(body).ok()?; + (status == 400 + && body + .pointer("/error/code") + .and_then(serde_json::Value::as_str) + == Some("context_length_exceeded")) + .then(InvalidRequest::context_length) +} + +#[cfg(test)] +mod tests { + use std::io::Write as _; + + use serde_json::{Value, json}; + + use super::*; + use crate::{ + inference::{InferenceAttempt, InferenceError, InferenceResponse, inference_cancellation}, + router::openai::{self, OpenAiRequest}, + }; + + /// oMLX 0.8.4's answer to a prompt above the context per request (`server.py`, + /// `_ContextLengthExceededError`). + const OVERSIZED_PROMPT: &str = r#"{"error":{"message":"Prompt is too long: 40010 tokens > 32768 maximum context length","type":"invalid_request_error","param":null,"code":"context_length_exceeded"}}"#; + + /// oMLX 0.8.4's memory guard turning a prompt away before generation: an HTTP 400 with no code. + const MEMORY_GUARD_REFUSAL: &str = r#"{"error":{"message":"oMLX prefill memory guard rejected this prompt: Prefill would require ~9.1 GB peak but the prefill limit is 8.6 GB","type":"invalid_request_error","param":null,"code":null}}"#; + + #[test] + fn only_a_context_length_refusal_is_an_invalid_request() { + assert_eq!( + classify_chat_rejection(400, OVERSIZED_PROMPT.as_bytes()), + Some(InvalidRequest::context_length()) + ); + for (status, body) in [ + (500, OVERSIZED_PROMPT.as_bytes()), + (400, MEMORY_GUARD_REFUSAL.as_bytes()), + (400, b"context_length_exceeded".as_slice()), + ] { + assert_eq!(classify_chat_rejection(status, body), None, "{status}"); + } + } + + #[tokio::test] + async fn an_oversized_prompt_fails_as_a_context_length_invalid_request() { + let attempt = invoke_answering(400, OVERSIZED_PROMPT).await; + + let InferenceAttempt::Failed { error, .. } = attempt else { + panic!("classified refusal"); + }; + assert!( + matches!(&error, InferenceError::InvalidRequest(invalid) if *invalid == InvalidRequest::context_length()), + "{error:?}" + ); + } + + #[tokio::test] + async fn a_memory_guard_refusal_passes_through_unclassified() { + let attempt = invoke_answering(400, MEMORY_GUARD_REFUSAL).await; + + let InferenceAttempt::Response(InferenceResponse::Passthrough(response)) = attempt else { + panic!("passthrough response"); + }; + assert_eq!(response.status, 400); + assert_eq!(response.body, MEMORY_GUARD_REFUSAL.as_bytes()); + + // The router projects the passed-through refusal into its safe envelope, keeping the + // client error status. + let public = openai::upstream(response.status, Vec::new(), response.body); + assert_eq!(public.status, 400); + assert_eq!( + serde_json::from_slice::(&public.body).expect("error JSON"), + json!({"error":{"message":"The inference engine rejected the request.","type":"upstream_error","param":null,"code":null}}) + ); + } + + /// Sends one chat request through an oMLX binding to a loopback engine answering `status` + /// with the JSON `body`. + async fn invoke_answering(status: u16, body: &str) -> InferenceAttempt { + let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).expect("engine listener"); + let port = listener.local_addr().expect("engine address").port(); + let response = format!( + "HTTP/1.1 {status} Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let engine = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().expect("engine connection"); + let mut request = Vec::new(); + let mut buffer = [0_u8; 4096]; + loop { + let read = std::io::Read::read(&mut stream, &mut buffer).expect("request bytes"); + request.extend_from_slice(&buffer[..read]); + if read == 0 || request_complete(&request) { + break; + } + } + stream.write_all(response.as_bytes()).expect("response"); + }); + let OpenAiRequest::Chat(request) = openai::decode( + "POST", + "/v1/chat/completions", + br#"{"model":"route","messages":[{"role":"user","content":"hi"}]}"#, + ) + .expect("chat request") else { + panic!("chat request"); + }; + + let (_signal, cancellation) = inference_cancellation(); + let attempt = OmlxTransportFactory + .bind_loopback(port, "served-model".to_owned()) + .invoke(request, cancellation) + .await; + engine.join().expect("engine thread"); + attempt + } + + /// Whether a buffered HTTP request holds its headers and the body they declare. + fn request_complete(request: &[u8]) -> bool { + let Some(end) = request.windows(4).position(|window| window == b"\r\n\r\n") else { + return false; + }; + let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase(); + let length = headers + .lines() + .find_map(|line| line.strip_prefix("content-length:")) + .and_then(|value| value.trim().parse::().ok()) + .unwrap_or_default(); + request.len() >= end + 4 + length + } +} diff --git a/backend/core/src/model/engine/omlx/declaration.rs b/backend/core/src/model/engine/omlx/declaration.rs new file mode 100644 index 00000000..d2dec16f --- /dev/null +++ b/backend/core/src/model/engine/omlx/declaration.rs @@ -0,0 +1,722 @@ +//! oMLX-specific validation of catalog engine releases and model engine configurations. +//! +//! A release must declare well-formed unsigned-integer parameters and only native Nix programs +//! for darwin/arm64 with Apple accelerators, the one platform oMLX's release runs on. A +//! configuration must bind pinned MLX snapshots, run text-only on one Apple accelerator, declare no +//! options, and reference a host prompt cache memory parameter so that every release parameter it +//! keeps reaches the launch. + +use std::collections::BTreeSet; + +use dotcore_catalog::shared_parameters::{ + CONTEXT_PER_REQUEST_PARAMETER_ID, PARALLEL_REQUESTS_PARAMETER_ID, TOTAL_CONTEXT_PARAMETER_ID, + is_shared_parameter, +}; +use dotcore_domain::Accelerator; +use dotcore_proto::dotcore::{ + catalog::v1::{ + EngineRelease, HardwareClass, MemoryPool, Model, ModelEngineConfiguration, + ModelInputModality, ModelParallelShape, ParameterDefinition, + engine_artifact::Kind as EngineArtifactKind, + hugging_face_artifact_source::Content as HuggingFaceContent, nix_artifact::Provides, + parameter_definition::ParameterType, + }, + engine::{ + omlx::v1::{OmlxFixedModelSettings, OmlxModelConfiguration}, + v1::{EngineKind, engine_model_configuration::Configuration}, + }, +}; + +use crate::model::engine::declaration::classes_outside_vendors; + +/// File at a snapshot's root that oMLX discovers a model folder by. +const MODEL_CONFIG_FILE: &str = "config.json"; + +/// Extension of the MLX weight files oMLX loads. +const WEIGHTS_FILE_EXTENSION: &str = ".safetensors"; + +/// Unit of the prompt cache memory parameter, which the plan converts for the launcher. +const PROMPT_CACHE_UNIT: &str = "MiB"; + +/// Accepts a release of non-empty unsigned-integer parameters whose artifacts are all native Nix +/// programs selected for darwin/arm64 Apple targets. The catalog checks the shared parameters' +/// fixed shape, and each release declares oMLX's own bounds. +pub(crate) fn validate_engine_release(engine: &EngineRelease) -> Vec { + let mut errors = Vec::new(); + if engine.engine_kind != EngineKind::Omlx as i32 { + errors.push(anyhow::anyhow!( + "oMLX engine release has a mismatched engine kind" + )); + } + let valid = engine.parameter_schema.as_ref().is_some_and(|schema| { + !schema.parameters.is_empty() + && schema.parameters.iter().all(|definition| { + !definition.parameter_id.is_empty() + && matches!( + definition.parameter_type.as_ref(), + Some(ParameterType::UnsignedInteger(range)) if !range.unit.is_empty() + ) + }) + }); + if !valid { + errors.push(anyhow::anyhow!( + "oMLX engine release requires non-empty unsigned-integer parameter definitions" + )); + } + let native_apple = !engine.artifacts.is_empty() + && engine.artifacts.iter().all(|artifact| { + let native = matches!( + artifact.kind.as_ref(), + Some(EngineArtifactKind::Nix(nix)) + if matches!(nix.provides, Some(Provides::Executable(_))) + ); + native + && !artifact.selectors.is_empty() + && artifact.selectors.iter().all(|selector| { + selector.accelerators == [Accelerator::Apple.catalog_name()] + && selector.platform.as_ref().is_some_and(|platform| { + platform.operating_system == "darwin" + && platform.architecture == "arm64" + }) + }) + }); + if !native_apple { + errors.push(anyhow::anyhow!( + "oMLX engine release supports only native Nix programs for darwin/arm64 with Apple accelerators" + )); + } + errors +} + +/// Accepts supported hardware classes that select only Apple accelerators. Selectors match +/// single-device targets only, so oMLX runs on exactly one Apple GPU. +pub(crate) fn validate_hardware_support( + configuration: &ModelEngineConfiguration, + hardware_classes: &[&HardwareClass], +) -> Vec { + classes_outside_vendors(hardware_classes, &[Accelerator::Apple]) + .into_iter() + .map(|hardware_class_id| { + anyhow::anyhow!( + "configuration {:?} hardware class {hardware_class_id:?} must select only Apple accelerators for oMLX", + configuration.configuration_id + ) + }) + .collect() +} + +pub(crate) fn validate_model_configuration( + model: &Model, + configuration: &ModelEngineConfiguration, + engine: &EngineRelease, +) -> Vec { + let mut errors = Vec::new(); + if engine.engine_kind != EngineKind::Omlx as i32 + || configuration + .engine_configuration + .as_ref() + .is_none_or(|wrapper| wrapper.engine_kind != EngineKind::Omlx as i32) + { + errors.push(anyhow::anyhow!( + "oMLX configuration has a mismatched engine wrapper or release kind" + )); + } + let Some(payload) = configuration.engine_configuration.as_ref() else { + return errors; + }; + let Some(Configuration::Omlx(payload)) = payload.configuration.as_ref() else { + errors.push(anyhow::anyhow!( + "configuration {:?} has a payload that does not match oMLX", + configuration.configuration_id + )); + return errors; + }; + + validate_payload(model, configuration, engine, payload, &mut errors); + errors +} + +fn validate_payload( + model: &Model, + configuration: &ModelEngineConfiguration, + engine: &EngineRelease, + payload: &OmlxModelConfiguration, + errors: &mut Vec, +) { + let Some(fixed) = payload.fixed_settings.as_ref() else { + errors.push(anyhow::anyhow!( + "configuration {:?} requires fixed oMLX settings", + configuration.configuration_id + )); + return; + }; + + validate_parameters(configuration, engine, fixed, errors); + validate_artifacts(model, configuration, errors); + validate_execution_shape(configuration, errors); + validate_inputs_and_options(configuration, errors); +} + +fn validate_parameters( + configuration: &ModelEngineConfiguration, + engine: &EngineRelease, + fixed: &OmlxFixedModelSettings, + errors: &mut Vec, +) { + let parameters = engine + .parameter_schema + .as_ref() + .map(|schema| schema.parameters.as_slice()) + .unwrap_or_default(); + let prompt_cache = fixed.prompt_cache_mib_parameter_id.as_str(); + let valid_prompt_cache = !is_shared_parameter(prompt_cache) + && parameters + .iter() + .find(|definition| definition.parameter_id == prompt_cache) + .is_some_and(is_host_memory_mib); + if !valid_prompt_cache { + errors.push(anyhow::anyhow!( + "configuration {:?} prompt cache parameter must name a release parameter in {PROMPT_CACHE_UNIT} drawn from host memory", + configuration.configuration_id + )); + } + + // Every parameter of the configuration must reach the launch plan, so none can be set without + // effect. The total context reaches it through the memory ceiling sizing derives from it. + let declared = parameters + .iter() + .map(|definition| definition.parameter_id.as_str()) + .collect::>(); + let launched = BTreeSet::from([ + TOTAL_CONTEXT_PARAMETER_ID, + CONTEXT_PER_REQUEST_PARAMETER_ID, + PARALLEL_REQUESTS_PARAMETER_ID, + prompt_cache, + ]); + if declared != launched { + errors.push(anyhow::anyhow!( + "configuration {:?} must keep exactly the shared context parameters and its prompt cache parameter", + configuration.configuration_id + )); + } +} + +/// Whether a parameter is an unsigned memory size in MiB drawn from the host pool. +fn is_host_memory_mib(definition: &ParameterDefinition) -> bool { + matches!( + definition.parameter_type.as_ref(), + Some(ParameterType::UnsignedInteger(range)) + if range.unit == PROMPT_CACHE_UNIT && range.memory_pool == Some(MemoryPool::Host as i32) + ) +} + +/// Accepts bindings of MLX snapshots: a model configuration and weight files at the snapshot's +/// root, which oMLX loads as one model folder, and no auxiliary artifacts. +fn validate_artifacts( + model: &Model, + configuration: &ModelEngineConfiguration, + errors: &mut Vec, +) { + let valid = !configuration.artifact_bindings.is_empty() + && configuration.artifact_bindings.iter().all(|binding| { + binding.auxiliary_artifact_ids.is_empty() + && model + .artifacts + .iter() + .find(|artifact| artifact.artifact_id == binding.model_artifact_id) + .and_then(|artifact| artifact.source.as_ref()) + .and_then(|source| source.content.as_ref()) + .is_some_and(is_mlx_snapshot) + }); + if !valid { + errors.push(anyhow::anyhow!( + "configuration {:?} requires snapshot model artifacts holding {MODEL_CONFIG_FILE} and {WEIGHTS_FILE_EXTENSION} weights at their root, without auxiliary artifacts", + configuration.configuration_id + )); + } +} + +fn is_mlx_snapshot(content: &HuggingFaceContent) -> bool { + let HuggingFaceContent::Snapshot(snapshot) = content else { + return false; + }; + let root_files = || { + snapshot + .files + .iter() + .map(|file| file.path.as_str()) + .filter(|path| !path.contains('/')) + }; + root_files().any(|path| path == MODEL_CONFIG_FILE) + && root_files().any(|path| { + path.len() > WEIGHTS_FILE_EXTENSION.len() && path.ends_with(WEIGHTS_FILE_EXTENSION) + }) +} + +fn validate_execution_shape( + configuration: &ModelEngineConfiguration, + errors: &mut Vec, +) { + let one_target = configuration + .execution_capabilities + .as_ref() + .is_some_and(|capabilities| { + capabilities.supported_parallel_shapes == [ModelParallelShape::One as i32] + }); + if !one_target { + errors.push(anyhow::anyhow!( + "configuration {:?} supports only one-target oMLX execution", + configuration.configuration_id + )); + } +} + +/// The adapter launches oMLX with fixed settings and text input only, so a configuration has no +/// options to realize and no image input. +fn validate_inputs_and_options( + configuration: &ModelEngineConfiguration, + errors: &mut Vec, +) { + if !configuration.options.is_empty() { + errors.push(anyhow::anyhow!( + "configuration {:?} declares options, which oMLX does not realize", + configuration.configuration_id + )); + } + let image_input = configuration + .input_capabilities + .as_ref() + .is_some_and(|capabilities| { + capabilities + .supported_modalities + .contains(&(ModelInputModality::Image as i32)) + || capabilities.image_input_capacity.is_some() + }); + if image_input { + errors.push(anyhow::anyhow!( + "configuration {:?} declares image input, which oMLX does not serve", + configuration.configuration_id + )); + } +} + +#[cfg(test)] +mod tests { + use dotcore_catalog::test_support::vendor_hardware_class; + use dotcore_proto::dotcore::catalog::v1::{ + BooleanParameterSchema, EngineArtifact, HuggingFaceArtifactSource, HuggingFaceFileArtifact, + ModelConfigurationOption, ModelImageInputCapacity, NixArtifact, NixDockerImage, + UnsignedIntegerParameterSchema, + }; + + use super::*; + use crate::test_support::{ + omlx::{PROMPT_CACHE_MIB_PARAMETER_ID, configuration, model, release}, + unsigned_parameter_values, + }; + + #[test] + fn accepts_the_synthetic_release_and_configuration() { + assert_eq!( + messages(validate_engine_release(&release())), + Vec::::new() + ); + assert_eq!( + messages(validate_model_configuration( + &model(), + &configuration(), + &release() + )), + Vec::::new() + ); + assert_eq!( + messages(validate_hardware_support( + &configuration(), + &[&vendor_hardware_class("apple")] + )), + Vec::::new() + ); + } + + #[test] + fn rejects_release_with_wrong_kind_or_unsupported_parameter_schema() { + let mut wrong_kind = release(); + wrong_kind.engine_kind = EngineKind::LlamaCpp as i32; + assert_eq!( + messages(validate_engine_release(&wrong_kind)), + ["oMLX engine release has a mismatched engine kind"] + ); + + let mut boolean = release(); + parameter(&mut boolean, PROMPT_CACHE_MIB_PARAMETER_ID).parameter_type = + Some(ParameterType::Boolean(BooleanParameterSchema::default())); + assert_eq!( + messages(validate_engine_release(&boolean)), + ["oMLX engine release requires non-empty unsigned-integer parameter definitions"] + ); + } + + #[test] + fn rejects_release_artifacts_other_than_native_darwin_apple_programs() { + let docker_image = |artifact: &mut EngineArtifact| { + artifact.kind = Some(EngineArtifactKind::Nix(NixArtifact { + flake: "self".to_owned(), + package: Some("engines.omlx.docker".to_owned()), + provides: Some(Provides::DockerImage(NixDockerImage {})), + store_paths: Vec::new(), + })); + }; + let oci = |artifact: &mut EngineArtifact| { + *artifact = dotcore_domain::test_support::oci::engine_artifact( + "darwin-arm64", + Some("registry.dotcore.test"), + "omlx", + "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + "darwin", + "arm64", + "apple", + ); + }; + let linux = |artifact: &mut EngineArtifact| { + artifact.selectors[0] + .platform + .as_mut() + .expect("platform") + .operating_system = "linux".to_owned(); + }; + let nvidia = |artifact: &mut EngineArtifact| { + artifact.selectors[0].accelerators = vec!["nvidia".to_owned()]; + }; + let no_selector = |artifact: &mut EngineArtifact| artifact.selectors.clear(); + + for (case, edit) in [ + ( + "Docker image", + &docker_image as &dyn Fn(&mut EngineArtifact), + ), + ("OCI image", &oci), + ("Linux", &linux), + ("NVIDIA", &nvidia), + ("no selector", &no_selector), + ] { + let mut release = release(); + edit(&mut release.artifacts[0]); + + assert_eq!( + messages(validate_engine_release(&release)), + [ + "oMLX engine release supports only native Nix programs for darwin/arm64 with Apple accelerators" + ], + "{case}" + ); + } + + let mut none = release(); + none.artifacts.clear(); + assert_eq!( + messages(validate_engine_release(&none)), + [ + "oMLX engine release supports only native Nix programs for darwin/arm64 with Apple accelerators" + ] + ); + } + + #[test] + fn rejects_hardware_classes_beyond_apple() { + assert_eq!( + messages(validate_hardware_support( + &configuration(), + &[ + &vendor_hardware_class("apple"), + &vendor_hardware_class("nvidia") + ] + )), + [ + "configuration \"omlx-apple\" hardware class \"nvidia\" must select only Apple accelerators for oMLX" + ] + ); + } + + #[test] + fn rejects_a_mismatched_or_incomplete_payload() { + let mut no_fixed = configuration(); + payload(&mut no_fixed).fixed_settings = None; + assert_eq!( + messages(validate_model_configuration( + &model(), + &no_fixed, + &release() + )), + ["configuration \"omlx-apple\" requires fixed oMLX settings"] + ); + + let mut other_engine = configuration(); + other_engine.engine_configuration = Some( + dotcore_proto::dotcore::engine::v1::EngineModelConfiguration { + engine_kind: EngineKind::Omlx as i32, + configuration: Some(Configuration::Strata(Default::default())), + }, + ); + assert_eq!( + messages(validate_model_configuration( + &model(), + &other_engine, + &release() + )), + ["configuration \"omlx-apple\" has a payload that does not match oMLX"] + ); + } + + #[test] + fn rejects_a_prompt_cache_reference_that_is_missing_shared_or_not_host_mib() { + let invalid = "configuration \"omlx-apple\" prompt cache parameter must name a release parameter in MiB drawn from host memory"; + let not_kept = "configuration \"omlx-apple\" must keep exactly the shared context parameters and its prompt cache parameter"; + for reference in ["missing", TOTAL_CONTEXT_PARAMETER_ID, ""] { + let mut configuration = configuration(); + fixed(&mut configuration).prompt_cache_mib_parameter_id = reference.to_owned(); + + assert_eq!( + messages(validate_model_configuration( + &model(), + &configuration, + &release() + )), + [invalid, not_kept], + "{reference:?}" + ); + } + + for (case, unit, memory_pool) in [ + ("GiB", "GiB", Some(MemoryPool::Host as i32)), + ( + "accelerator pool", + "MiB", + Some(MemoryPool::Accelerator as i32), + ), + ("no pool", "MiB", None), + ] { + let mut release = release(); + parameter(&mut release, PROMPT_CACHE_MIB_PARAMETER_ID).parameter_type = Some( + ParameterType::UnsignedInteger(UnsignedIntegerParameterSchema { + minimum: 0, + maximum: None, + unit: unit.to_owned(), + default_value: None, + memory_pool, + }), + ); + + assert_eq!( + messages(validate_model_configuration( + &model(), + &configuration(), + &release + )), + [invalid], + "{case}" + ); + } + } + + #[test] + fn rejects_release_parameters_that_would_not_reach_the_launch() { + let mut extra = release(); + let mut kv_bits = parameter(&mut extra, PROMPT_CACHE_MIB_PARAMETER_ID).clone(); + kv_bits.parameter_id = "kv-bits".to_owned(); + extra + .parameter_schema + .as_mut() + .expect("schema") + .parameters + .push(kv_bits); + + assert_eq!( + messages(validate_engine_release(&extra)), + Vec::::new() + ); + assert_eq!( + messages(validate_model_configuration( + &model(), + &configuration(), + &extra + )), + [ + "configuration \"omlx-apple\" must keep exactly the shared context parameters and its prompt cache parameter" + ] + ); + } + + #[test] + fn rejects_bindings_other_than_mlx_snapshots() { + let message = "configuration \"omlx-apple\" requires snapshot model artifacts holding config.json and .safetensors weights at their root, without auxiliary artifacts"; + let mut gguf = model(); + gguf.artifacts[0].source = Some(HuggingFaceArtifactSource { + repository: "dotcore/fixture".to_owned(), + revision: "0123456789abcdef0123456789abcdef01234567".to_owned(), + content: Some(HuggingFaceContent::File(HuggingFaceFileArtifact { + path: "fixture-Q4_K_M.gguf".to_owned(), + provenance_digest: "0".repeat(64), + })), + }); + let mut no_config = model(); + snapshot_files(&mut no_config).retain(|file| file.path != "config.json"); + let mut no_weights = model(); + snapshot_files(&mut no_weights).retain(|file| file.path != "model.safetensors"); + let mut nested = model(); + for file in snapshot_files(&mut nested) { + file.path = format!("4bit/{}", file.path); + } + + for (case, model) in [ + ("GGUF file", gguf), + ("no config", no_config), + ("no weights", no_weights), + ("nested", nested), + ] { + assert_eq!( + messages(validate_model_configuration( + &model, + &configuration(), + &release() + )), + [message], + "{case}" + ); + } + + let mut auxiliary = configuration(); + auxiliary.artifact_bindings[0].auxiliary_artifact_ids = vec!["draft".to_owned()]; + assert_eq!( + messages(validate_model_configuration( + &model(), + &auxiliary, + &release() + )), + [message] + ); + } + + #[test] + fn rejects_execution_without_one_target_options_and_image_input() { + let mut no_shape = configuration(); + no_shape + .execution_capabilities + .as_mut() + .expect("execution capabilities") + .supported_parallel_shapes + .clear(); + assert_eq!( + messages(validate_model_configuration( + &model(), + &no_shape, + &release() + )), + ["configuration \"omlx-apple\" supports only one-target oMLX execution"] + ); + + let mut options = configuration(); + options.options = vec![ModelConfigurationOption { + option_id: "mtp".to_owned(), + ..Default::default() + }]; + assert_eq!( + messages(validate_model_configuration(&model(), &options, &release())), + ["configuration \"omlx-apple\" declares options, which oMLX does not realize"] + ); + + let mut image = configuration(); + let capabilities = image.input_capabilities.as_mut().expect("inputs"); + capabilities + .supported_modalities + .push(ModelInputModality::Image as i32); + capabilities.image_input_capacity = Some(ModelImageInputCapacity::default()); + assert_eq!( + messages(validate_model_configuration(&model(), &image, &release())), + ["configuration \"omlx-apple\" declares image input, which oMLX does not serve"] + ); + } + + #[test] + fn launches_split_the_total_context_into_one_share_per_parallel_request() { + let context = crate::model::engine::EngineContext::for_configuration( + EngineKind::Omlx as i32, + &model(), + &configuration(), + &release().parameter_schema.expect("schema"), + ) + .expect("declared context behavior"); + let values = |total_context: u64| { + unsigned_parameter_values([ + (TOTAL_CONTEXT_PARAMETER_ID, total_context), + (CONTEXT_PER_REQUEST_PARAMETER_ID, 32_768), + (PARALLEL_REQUESTS_PARAMETER_ID, 2), + ]) + }; + + assert_eq!(context.check_launch(&values(65_536)), Ok(())); + assert_eq!( + context.check_launch(&values(65_535)).map_err(|error| error.to_string()), + Err("context per request of 32768 tokens is above the 32767 tokens one request can use of the total context; lower the context per request or raise the total context".to_owned()) + ); + assert_eq!( + context.check_launch(&values(131_072)).map_err(|error| error.to_string()), + Err("total context of 131072 tokens is above the 65536 tokens the parallel requests use at this context per request; lower the total context, or raise the parallel requests or the context per request".to_owned()) + ); + assert_eq!( + context.derived_context_values(&unsigned_parameter_values([ + (CONTEXT_PER_REQUEST_PARAMETER_ID, 16_384), + (PARALLEL_REQUESTS_PARAMETER_ID, 3), + ])), + unsigned_parameter_values([(TOTAL_CONTEXT_PARAMETER_ID, 49_152)]).values + ); + } + + fn messages(errors: Vec) -> Vec { + errors.into_iter().map(|error| error.to_string()).collect() + } + + fn parameter<'a>( + release: &'a mut EngineRelease, + parameter_id: &str, + ) -> &'a mut ParameterDefinition { + release + .parameter_schema + .as_mut() + .expect("schema") + .parameters + .iter_mut() + .find(|definition| definition.parameter_id == parameter_id) + .expect("parameter") + } + + fn payload(configuration: &mut ModelEngineConfiguration) -> &mut OmlxModelConfiguration { + match configuration + .engine_configuration + .as_mut() + .and_then(|payload| payload.configuration.as_mut()) + { + Some(Configuration::Omlx(payload)) => payload, + _ => panic!("oMLX payload"), + } + } + + fn fixed(configuration: &mut ModelEngineConfiguration) -> &mut OmlxFixedModelSettings { + payload(configuration) + .fixed_settings + .as_mut() + .expect("fixed settings") + } + + fn snapshot_files( + model: &mut Model, + ) -> &mut Vec { + match model.artifacts[0] + .source + .as_mut() + .and_then(|source| source.content.as_mut()) + { + Some(HuggingFaceContent::Snapshot(snapshot)) => &mut snapshot.files, + _ => panic!("snapshot artifact"), + } + } +} diff --git a/backend/core/src/model/engine/omlx/mod.rs b/backend/core/src/model/engine/omlx/mod.rs new file mode 100644 index 00000000..91bdb33d --- /dev/null +++ b/backend/core/src/model/engine/omlx/mod.rs @@ -0,0 +1,172 @@ +//! The oMLX engine: catalog declaration validation, launch-plan translation, native Nix workload +//! materialization, loopback readiness probing, loopback inference binding, and startup refusals. +//! +//! oMLX serves MLX-format weights from one pinned Hugging Face snapshot on an Apple Silicon Mac as +//! a native host process, started through its package launcher, which writes oMLX's own settings +//! into the workload's working directory. oMLX manages its own memory under a whole-process +//! ceiling derived from the deployment's estimate, and grows into that estimate as requests arrive. +//! Callers reach it only through its engine definition. + +mod binding; +mod declaration; +mod plan; +mod readiness; +mod realization; +mod startup_refusal; +mod workload; + +use std::sync::Arc; + +use dotcore_artifact::PreparedModelArtifacts; +use dotcore_domain::WorkloadArtifactKind; +use dotcore_proto::dotcore::{ + catalog::v1::{ + EngineRelease, HardwareClass, InferenceRequestKind, Model, ModelArtifactBinding, + ModelEngineConfiguration, ModelOptionValues, + }, + engine::v1::{EngineKind, ResolvedEngineModelState}, + model::v1::{PortableModelLaunchPlan, ResolvedLocalModelDeploymentSnapshot}, +}; +use dotcore_runtime::{ExecutionTarget, LoopbackEndpoint, WorkloadSpec}; + +use super::{ + EngineSettings, + definition::{CustomArgumentConflict, EngineDefinition}, + realization::ResolvedEngineSelection, + startup_refusal::StartupRefusal, +}; +use crate::{ + inference::{EngineReadinessProbe, EngineTransportFactory}, + model::resolved::ResolvedModelLaunch, +}; +#[cfg(test)] +pub(crate) use plan::translate; +#[cfg(test)] +pub(crate) use realization::realize_model; + +/// The oMLX engine. +pub(crate) struct Omlx; + +/// Inference request kinds oMLX serves: chat only. +const REQUEST_KINDS: &[InferenceRequestKind] = &[InferenceRequestKind::Chat]; + +impl EngineDefinition for Omlx { + fn kind(&self) -> EngineKind { + EngineKind::Omlx + } + + fn name(&self) -> &'static str { + "oMLX" + } + + fn request_kinds(&self) -> &'static [InferenceRequestKind] { + REQUEST_KINDS + } + + fn validate_engine_release(&self, engine: &EngineRelease) -> Vec { + declaration::validate_engine_release(engine) + } + + fn validate_model_configuration( + &self, + model: &Model, + configuration: &ModelEngineConfiguration, + engine: &EngineRelease, + ) -> Vec { + declaration::validate_model_configuration(model, configuration, engine) + } + + fn validate_hardware_support( + &self, + configuration: &ModelEngineConfiguration, + hardware_classes: &[&HardwareClass], + ) -> Vec { + declaration::validate_hardware_support(configuration, hardware_classes) + } + + /// oMLX's memory ceiling comes from the deployment's estimate, so every launch needs one. + fn launch_requires_sizing(&self) -> bool { + true + } + + /// oMLX allocates its KV cache and prompt cache as requests arrive, so a ready deployment holds + /// only its weights until load fills the rest of its estimate. + fn grows_after_ready(&self, _settings: EngineSettings<'_>) -> bool { + true + } + + fn realize_model( + &self, + model: &Model, + configuration: &ModelEngineConfiguration, + binding: &ModelArtifactBinding, + option_values: &[ModelOptionValues], + ) -> anyhow::Result { + realization::realize_model(model, configuration, binding, option_values) + } + + fn validate_snapshot( + &self, + snapshot: &ResolvedLocalModelDeploymentSnapshot, + ) -> anyhow::Result<()> { + Ok(plan::validate_snapshot(snapshot)?) + } + + fn translate( + &self, + snapshot: &ResolvedLocalModelDeploymentSnapshot, + ) -> anyhow::Result { + plan::translate(snapshot).map_err(|error| match error { + plan::OmlxPlanError::CustomArgument(flag) => { + CustomArgumentConflict::unsupported("oMLX", &flag).into() + } + error => error.into(), + }) + } + + fn artifact_kinds(&self) -> &'static [WorkloadArtifactKind] { + workload::ARTIFACT_KINDS + } + + fn workload( + &self, + model: &ResolvedModelLaunch, + target: &ExecutionTarget, + artifacts: &PreparedModelArtifacts, + ) -> anyhow::Result { + Ok(workload::workload(model, target, artifacts)?) + } + + fn readiness_probe( + &self, + endpoint: LoopbackEndpoint, + served_model_id: String, + _resolved_engine_state: &ResolvedEngineModelState, + context_per_request: Option, + ) -> Arc { + Arc::new(readiness::OmlxReadinessProbe::new( + endpoint, + served_model_id, + context_per_request, + )) + } + + fn transport_factory(&self) -> Arc { + Arc::new(binding::OmlxTransportFactory) + } + + fn startup_refusal(&self, output: &str) -> Option { + startup_refusal::startup_refusal(output) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_support::omlx::configuration; + + #[test] + fn omlx_grows_after_ready() { + assert!(Omlx.grows_after_ready(EngineSettings::Configuration(&configuration()))); + } +} diff --git a/backend/core/src/model/engine/omlx/plan.rs b/backend/core/src/model/engine/omlx/plan.rs new file mode 100644 index 00000000..4958ae08 --- /dev/null +++ b/backend/core/src/model/engine/omlx/plan.rs @@ -0,0 +1,496 @@ +//! Translation and validation of the portable oMLX launch plan for a resolved deployment. +//! +//! From a resolved deployment snapshot it builds the canonical command line of oMLX's package +//! launcher: the model snapshot, the deployment's model identity as the served id, the service +//! port, the context per request and parallel requests oMLX enforces, the whole-process memory +//! ceiling derived from the deployment's estimate, and the in-memory prompt cache size. The +//! launcher takes no other arguments, so custom arguments are refused. It also checks that a +//! retained plan exactly matches the plan its resolved state would produce. + +use dotcore_catalog::shared_parameters::{ + CONTEXT_PER_REQUEST_PARAMETER_ID, PARALLEL_REQUESTS_PARAMETER_ID, +}; +use dotcore_proto::{ + dotcore::{ + catalog::v1::parameter_value::Value as EngineParameterValueKind, + engine::{ + omlx::v1::OmlxResolvedModelState, + v1::{EngineKind, resolved_engine_model_state::State}, + }, + model::v1::{ + PortableModelArtifactBinding, PortableModelLaunchArgumentToken, + PortableModelLaunchPlan, ResolvedLocalModelDeploymentSnapshot, + portable_model_artifact_binding::Artifact as BoundArtifact, + portable_model_launch_argument_token::Value as ArgumentValue, + }, + }, + google::protobuf::Empty, +}; + +/// Version of the symbolic plan; plans retained in another format must be recreated. +pub(super) const PLAN_FORMAT_VERSION: u32 = 1; +pub(super) const MODEL_BINDING_ID: &str = "model"; +/// Name of the HTTP service the plan binds through its port token. +pub(super) const SERVICE_NAME: &str = "http"; + +/// oMLX's peak whole-process footprint over its memory guard ceiling under full load, as a +/// fraction in hundredths: it measured 1.07 at the pinned release. The ceiling is the estimate +/// divided by it, so the peak lands on the estimate. Re-measured on every engine bump. +const MEMORY_OVERSHOOT_HUNDREDTHS: u128 = 107; + +/// Decimal places of the memory ceiling, rounded down so the ceiling never exceeds its share of +/// the estimate. +const CEILING_DECIMALS: u32 = 3; + +const BYTES_PER_GIB: u128 = 1 << 30; +const MIB_PER_GIB: u64 = 1024; + +/// Produces the single portable desired plan for an accepted oMLX selection. +pub(crate) fn translate( + snapshot: &ResolvedLocalModelDeploymentSnapshot, +) -> Result { + let state = resolved_state(snapshot)?; + let fixed = state + .fixed_settings + .as_ref() + .ok_or(OmlxPlanError::NoFixedSettings)?; + let model = snapshot + .model_artifact + .as_ref() + .ok_or(OmlxPlanError::NoModelArtifact)?; + // The launcher parses with argparse, where any token could name or abbreviate an option the + // plan sets, and it takes no other arguments. + if let Some(token) = snapshot.custom_argument_tokens.first() { + return Err(OmlxPlanError::CustomArgument( + crate::model::engine::custom_argument_flag(token).to_owned(), + )); + } + let context_per_request = positive_parameter(snapshot, CONTEXT_PER_REQUEST_PARAMETER_ID)?; + let parallel_requests = positive_parameter(snapshot, PARALLEL_REQUESTS_PARAMETER_ID)?; + let prompt_cache_mib = unsigned_parameter(snapshot, &fixed.prompt_cache_mib_parameter_id)?; + + let mut arguments = vec![ + token(ArgumentValue::EngineExecutable(Empty {})), + literal("--snapshot"), + token(ArgumentValue::ArtifactBindingId( + MODEL_BINDING_ID.to_owned(), + )), + literal("--served-id"), + literal(&snapshot.model_id), + literal("--port"), + token(ArgumentValue::ServicePort(SERVICE_NAME.to_owned())), + ]; + arguments.extend(literals([ + "--context-per-request", + &context_per_request.to_string(), + "--parallel-requests", + ¶llel_requests.to_string(), + "--memory-ceiling-gb", + &memory_ceiling_gib(snapshot)?, + "--prompt-cache-gb", + &mib_as_gib(prompt_cache_mib), + ])); + Ok(PortableModelLaunchPlan { + arguments, + format_version: PLAN_FORMAT_VERSION, + artifact_bindings: vec![PortableModelArtifactBinding { + binding_id: MODEL_BINDING_ID.to_owned(), + artifact: Some(BoundArtifact::ModelArtifactId(model.artifact_id.clone())), + read_only: true, + }], + }) +} + +/// Validates that a retained plan is canonical for its versioned resolved state. +pub(crate) fn validate_snapshot( + snapshot: &ResolvedLocalModelDeploymentSnapshot, +) -> Result<(), OmlxPlanError> { + if let Some(plan) = snapshot.desired_launch_plan.as_ref() { + let found = plan.format_version; + if found < PLAN_FORMAT_VERSION { + return Err(OmlxPlanError::RetainedPlanFormat { found }); + } + if found > PLAN_FORMAT_VERSION { + return Err(OmlxPlanError::NewerRetainedPlanFormat { found }); + } + } + if !snapshot.resolved_options.is_empty() || !snapshot.auxiliary_artifacts.is_empty() { + return Err(OmlxPlanError::InvalidResolvedState); + } + let expected = translate(snapshot)?; + if snapshot.desired_launch_plan.as_ref() != Some(&expected) { + return Err(OmlxPlanError::NonCanonicalPlan); + } + Ok(()) +} + +fn resolved_state( + snapshot: &ResolvedLocalModelDeploymentSnapshot, +) -> Result<&OmlxResolvedModelState, OmlxPlanError> { + snapshot + .resolved_engine_state + .as_ref() + .filter(|state| { + state.engine_kind == EngineKind::Omlx as i32 + && state.semantics_version == super::realization::SEMANTICS_VERSION + }) + .and_then(|state| state.state.as_ref()) + .and_then(|state| match state { + State::Omlx(state) => Some(state), + _ => None, + }) + .ok_or(OmlxPlanError::InvalidResolvedState) +} + +/// Renders the whole-process memory ceiling in GiB: the deployment's accelerator and host +/// estimates together, since both draw from the unified memory oMLX's guard measures, divided by +/// oMLX's overshoot and rounded down to [`CEILING_DECIMALS`] places. +fn memory_ceiling_gib( + snapshot: &ResolvedLocalModelDeploymentSnapshot, +) -> Result { + let sizing = snapshot.sizing.as_ref(); + let accelerator = sizing + .and_then(|sizing| sizing.accelerator_memory_bytes) + .ok_or(OmlxPlanError::SizingUnavailable)?; + let host = sizing + .and_then(|sizing| sizing.host_memory_bytes) + .unwrap_or_default(); + let scale = 10_u128.pow(CEILING_DECIMALS); + let scaled = (u128::from(accelerator) + u128::from(host)) * 100 * scale + / (MEMORY_OVERSHOOT_HUNDREDTHS * BYTES_PER_GIB); + if scaled == 0 { + return Err(OmlxPlanError::EstimateBelowCeilingPrecision); + } + Ok(format!( + "{}.{:0width$}", + scaled / scale, + scaled % scale, + width = CEILING_DECIMALS as usize + )) +} + +/// Renders a MiB size as the exact decimal GiB the launcher takes: one MiB is 1/1024 GiB, a +/// fraction with at most ten decimal places. +fn mib_as_gib(mib: u64) -> String { + let whole = mib / MIB_PER_GIB; + let remainder = mib % MIB_PER_GIB; + if remainder == 0 { + return whole.to_string(); + } + // 1/1024 = 0.0009765625, so the remainder in ten-billionths is exact. + let fraction = format!("{:010}", remainder * 9_765_625); + format!("{whole}.{}", fraction.trim_end_matches('0')) +} + +fn positive_parameter( + snapshot: &ResolvedLocalModelDeploymentSnapshot, + parameter_id: &str, +) -> Result { + unsigned_parameter(snapshot, parameter_id).and_then(|value| { + (value > 0) + .then_some(value) + .ok_or_else(|| OmlxPlanError::ParameterNotConfigured(parameter_id.to_owned())) + }) +} + +fn unsigned_parameter( + snapshot: &ResolvedLocalModelDeploymentSnapshot, + parameter_id: &str, +) -> Result { + snapshot + .engine_parameter_values + .as_ref() + .and_then(|values| { + values + .values + .iter() + .find(|value| value.parameter_id == parameter_id) + }) + .and_then(|value| match value.value.as_ref() { + Some(EngineParameterValueKind::UnsignedInteger(value)) => Some(*value), + _ => None, + }) + .ok_or_else(|| OmlxPlanError::ParameterNotConfigured(parameter_id.to_owned())) +} + +fn literals(values: [&str; N]) -> Vec { + values.into_iter().map(literal).collect() +} + +fn literal(value: &str) -> PortableModelLaunchArgumentToken { + token(ArgumentValue::Literal(value.to_owned())) +} + +fn token(value: ArgumentValue) -> PortableModelLaunchArgumentToken { + PortableModelLaunchArgumentToken { value: Some(value) } +} + +/// Indicates that resolved values cannot produce a complete portable oMLX plan. +#[derive(Debug, thiserror::Error)] +pub(crate) enum OmlxPlanError { + #[error("oMLX launch plan has invalid resolved engine state")] + InvalidResolvedState, + + #[error("oMLX launch plan is not canonical for its resolved state")] + NonCanonicalPlan, + + #[error( + "oMLX deployment was created with launch plan format {found}, which this Dotcore version \ + no longer supports; delete and recreate the deployment" + )] + RetainedPlanFormat { found: u32 }, + + #[error( + "oMLX deployment was created with launch plan format {found} by a newer Dotcore version; \ + upgrade Dotcore, or delete and recreate the deployment with this version" + )] + NewerRetainedPlanFormat { found: u32 }, + + #[error("oMLX launch plan has no fixed settings")] + NoFixedSettings, + + #[error("oMLX launch plan has no model artifact")] + NoModelArtifact, + + #[error("oMLX launch plan has no valid value for engine parameter {0:?}")] + ParameterNotConfigured(String), + + #[error( + "oMLX launch plan has no accelerator memory footprint; the catalog binding must declare \ + an acceleratorMemory estimate" + )] + SizingUnavailable, + + #[error("oMLX launch plan has a memory estimate too small to set a memory ceiling")] + EstimateBelowCeilingPrecision, + + #[error( + "oMLX takes no custom arguments, but got {0:?}; its package launcher accepts only the \ + options Dotcore sets" + )] + CustomArgument(String), +} + +#[cfg(test)] +mod tests { + use dotcore_proto::dotcore::model::v1::{ + ModelDeploymentSnapshot, ResolvedModelOption, ResolvedSizing, model_deployment_snapshot, + }; + + use super::*; + use crate::{ + model::engine::definition::EngineDefinition, test_support::omlx::local_model_snapshot, + }; + + #[test] + fn the_profile_launches_the_package_launcher_with_its_limits_and_memory_ceiling() { + let snapshot = local(local_model_snapshot("qwen3-5-4b")); + + let plan = translate(&snapshot).expect("oMLX plan"); + + assert_eq!( + plan.arguments + .iter() + .map(|argument| match argument.value.as_ref().expect("token") { + ArgumentValue::EngineExecutable(_) => "{executable}".to_owned(), + ArgumentValue::ArtifactBindingId(id) => format!("{{artifact:{id}}}"), + ArgumentValue::ServicePort(name) => format!("{{port:{name}}}"), + ArgumentValue::Literal(value) => value.clone(), + other => panic!("unexpected token {other:?}"), + }) + .collect::>(), + [ + "{executable}", + "--snapshot", + "{artifact:model}", + "--served-id", + "qwen3-5-4b", + "--port", + "{port:http}", + "--context-per-request", + "32768", + "--parallel-requests", + "2", + // (10,000,000,000 + 2 GiB) / 1.07 = 10.5731 GiB, rounded down. + "--memory-ceiling-gb", + "10.573", + "--prompt-cache-gb", + "2", + ] + ); + assert_eq!( + plan.artifact_bindings, + [PortableModelArtifactBinding { + binding_id: "model".to_owned(), + artifact: Some(BoundArtifact::ModelArtifactId( + "fixture-mlx-4bit".to_owned() + )), + read_only: true, + }] + ); + assert_eq!(plan.format_version, 1); + } + + #[test] + fn the_memory_ceiling_divides_the_whole_estimate_by_the_overshoot() { + let mut snapshot = local(local_model_snapshot("qwen3-5-4b")); + let mut ceiling = |accelerator, host| { + snapshot.sizing = Some(ResolvedSizing { + accelerator_memory_bytes: accelerator, + host_memory_bytes: host, + ..Default::default() + }); + memory_ceiling_gib(&snapshot).map_err(|error| error.to_string()) + }; + + // 1.07 GiB of estimate is exactly a 1 GiB ceiling. + assert_eq!( + ceiling(Some(1_148_903_751), Some(0)), + Ok("0.999".to_owned()) + ); + assert_eq!(ceiling(Some(1_148_903_752), None), Ok("1.000".to_owned())); + assert_eq!( + ceiling(Some(16 * 1024 * 1024 * 1024), Some(4 * 1024 * 1024 * 1024)), + Ok("18.691".to_owned()) + ); + assert_eq!( + ceiling(Some(1_000), Some(1_000)), + Err( + "oMLX launch plan has a memory estimate too small to set a memory ceiling" + .to_owned() + ) + ); + assert_eq!( + ceiling(None, Some(1_000_000_000)), + Err( + "oMLX launch plan has no accelerator memory footprint; the catalog binding must \ + declare an acceleratorMemory estimate" + .to_owned() + ) + ); + } + + #[test] + fn the_prompt_cache_reaches_the_launcher_as_exact_gib() { + for (mib, gib) in [ + (0, "0"), + (1, "0.0009765625"), + (100, "0.09765625"), + (1_536, "1.5"), + (2_048, "2"), + (40_960, "40"), + ] { + assert_eq!(mib_as_gib(mib), gib, "{mib}"); + } + } + + #[test] + fn custom_arguments_are_refused() { + let mut snapshot = local(local_model_snapshot("qwen3-5-4b")); + snapshot.custom_argument_tokens = vec!["--max-tokens=8".to_owned()]; + + assert_eq!( + super::super::Omlx + .translate(&snapshot) + .expect_err("custom argument") + .to_string(), + "oMLX takes no custom arguments, but got \"--max-tokens\"" + ); + } + + #[test] + fn a_retained_plan_must_be_canonical_for_its_resolved_state() { + let snapshot = local(local_model_snapshot("qwen3-5-4b")); + validate_snapshot(&snapshot).expect("canonical plan"); + + let mut edited = snapshot.clone(); + edited + .desired_launch_plan + .as_mut() + .expect("plan") + .arguments + .pop(); + let mut older = snapshot.clone(); + older + .desired_launch_plan + .as_mut() + .expect("plan") + .format_version = 0; + let mut newer = snapshot.clone(); + newer + .desired_launch_plan + .as_mut() + .expect("plan") + .format_version = 2; + let mut options = snapshot.clone(); + options.resolved_options = vec![ResolvedModelOption::default()]; + let mut resized = snapshot; + resized + .sizing + .as_mut() + .expect("sizing") + .accelerator_memory_bytes = Some(20_000_000_000); + + for (case, snapshot, message) in [ + ( + "edited", + edited, + "oMLX launch plan is not canonical for its resolved state", + ), + ( + "older", + older, + "oMLX deployment was created with launch plan format 0, which this Dotcore version \ + no longer supports; delete and recreate the deployment", + ), + ( + "newer", + newer, + "oMLX deployment was created with launch plan format 2 by a newer Dotcore version; \ + upgrade Dotcore, or delete and recreate the deployment with this version", + ), + ( + "options", + options, + "oMLX launch plan has invalid resolved engine state", + ), + ( + "resized", + resized, + "oMLX launch plan is not canonical for its resolved state", + ), + ] { + assert_eq!( + validate_snapshot(&snapshot).expect_err(case).to_string(), + message, + "{case}" + ); + } + } + + #[test] + fn a_zero_context_per_request_has_no_plan() { + let mut snapshot = local(local_model_snapshot("qwen3-5-4b")); + snapshot + .engine_parameter_values + .as_mut() + .expect("values") + .values + .iter_mut() + .find(|value| value.parameter_id == CONTEXT_PER_REQUEST_PARAMETER_ID) + .expect("context per request") + .value = Some(EngineParameterValueKind::UnsignedInteger(0)); + + assert_eq!( + translate(&snapshot).expect_err("no context").to_string(), + "oMLX launch plan has no valid value for engine parameter \"context-per-request\"" + ); + } + + fn local(snapshot: ModelDeploymentSnapshot) -> ResolvedLocalModelDeploymentSnapshot { + match snapshot.source.expect("snapshot source") { + model_deployment_snapshot::Source::Local(local) => local, + _ => panic!("local snapshot"), + } + } +} diff --git a/backend/core/src/model/engine/omlx/readiness.rs b/backend/core/src/model/engine/omlx/readiness.rs new file mode 100644 index 00000000..d24d9d06 --- /dev/null +++ b/backend/core/src/model/engine/omlx/readiness.rs @@ -0,0 +1,338 @@ +//! Bounded readiness probing for an oMLX service on its loopback endpoint. +//! +//! oMLX is ready when `/health` answers 200 as healthy, which it does once its pinned model has +//! loaded, and `/v1/models` lists the exact served model id. Until the server listens the +//! connection is refused, and while the model loads health answers 503; both count as still +//! loading, and a failed start exits the process and surfaces as a workload exit instead. oMLX +//! reports the context it caps each request at, so a listing below the deployment's context per +//! request fails the deployment instead of being retried. + +use std::time::Duration; + +use dotcore_domain::real_time; +use dotcore_runtime::LoopbackEndpoint; +use serde::Deserialize; + +use crate::{ + inference::{ + EngineProbeError, EngineReadiness, EngineReadinessProbe, InferenceCancellation, + InferenceFuture, + }, + model::engine::probe, +}; + +/// A loaded oMLX answers on loopback in milliseconds. The controller probes deployments one after +/// another in each reconcile pass, so this bounds how long a pass waits on a stalled one; a slow +/// answer only defers readiness to a later pass. +const READINESS_IO_TIMEOUT: Duration = Duration::from_secs(5); + +/// Health status oMLX reports once its pinned model has loaded. +const HEALTHY_STATUS: &str = "healthy"; + +/// Probes one oMLX service on its loopback endpoint for readiness under its served model id, with +/// at least the deployment's context per request when it has one. +pub(super) struct OmlxReadinessProbe { + endpoint: LoopbackEndpoint, + served_model_id: String, + context_per_request: Option, +} + +impl OmlxReadinessProbe { + pub(super) fn new( + endpoint: LoopbackEndpoint, + served_model_id: String, + context_per_request: Option, + ) -> Self { + Self { + endpoint, + served_model_id, + context_per_request, + } + } +} + +impl EngineReadinessProbe for OmlxReadinessProbe { + fn probe<'a>( + &'a self, + cancellation: InferenceCancellation, + ) -> InferenceFuture<'a, Result> { + probe::probe_readiness( + cancellation, + &self.served_model_id, + is_ready( + &self.endpoint, + &self.served_model_id, + self.context_per_request, + ), + ) + } +} + +/// The field of oMLX's `/health` answer that readiness reads. +#[derive(Deserialize)] +struct Health { + status: String, +} + +/// The fields of oMLX's `/v1/models` answer that readiness reads. +#[derive(Deserialize)] +struct Models { + data: Vec, +} + +#[derive(Deserialize)] +struct ListedModel { + id: String, + max_model_len: Option, +} + +/// Evaluates oMLX's health and served model listing from an assigned runtime endpoint. +async fn is_ready( + endpoint: &LoopbackEndpoint, + served_model_id: &str, + context_per_request: Option, +) -> Result { + let client = reqwest::Client::builder() + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .retry(reqwest::retry::never()) + .build() + .map_err(|error| { + probe::unexpected(anyhow::Error::new(error).context("oMLX readiness client failed")) + })?; + let Some(health) = get_ok::(&client, endpoint, "/health").await? else { + return Ok(false); + }; + if health.status != HEALTHY_STATUS { + return Ok(false); + } + let Some(models) = get_ok::(&client, endpoint, "/v1/models").await? else { + return Ok(false); + }; + let Some(model) = models + .data + .into_iter() + .find(|model| model.id == served_model_id) + else { + return Ok(false); + }; + let Some(context_per_request) = context_per_request else { + return Ok(true); + }; + match model.max_model_len { + Some(started) if started >= context_per_request => Ok(true), + Some(started) => Err(EngineProbeError::ContextBelowDeployment( + StartedContextBelowDeployment { + started, + context_per_request, + } + .into(), + )), + // The launcher always sets the context cap, so a listing without one is not the server + // the plan started. + None => Err(probe::unexpected(anyhow::anyhow!( + "oMLX /v1/models lists the served model without its context" + ))), + } +} + +/// Gets `path` and decodes its 200 answer, or none when the server is unreachable, stalled or +/// answers another status, as it does while still loading. +async fn get_ok( + client: &reqwest::Client, + endpoint: &LoopbackEndpoint, + path: &str, +) -> Result, EngineProbeError> { + let request = async { + let response = client + .get(format!("http://127.0.0.1:{}{path}", endpoint.host_port)) + .header("accept", "application/json") + .send() + .await?; + let status = response.status(); + response.bytes().await.map(|body| (status, body)) + }; + // A refused, reset or stalled exchange is a server still starting or restarting; a start that + // fails ends the workload, which the controller observes on its own. + let Ok(Ok((status, body))) = real_time::bound(READINESS_IO_TIMEOUT, request).await else { + return Ok(None); + }; + if status != reqwest::StatusCode::OK { + return Ok(None); + } + serde_json::from_slice::(&body) + .map(Some) + .map_err(|error| { + probe::unexpected( + anyhow::Error::new(error) + .context(format!("oMLX {path} returned an unexpected body")), + ) + }) +} + +/// oMLX caps each request below the deployment's context per request, so it would refuse prompts +/// the deployment admits. +#[derive(Debug, thiserror::Error)] +#[error( + "oMLX started with a context per request of {started} tokens, below the deployment's \ + {context_per_request} tokens; recreate the deployment" +)] +struct StartedContextBelowDeployment { + started: u64, + context_per_request: u64, +} + +#[cfg(test)] +mod tests { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + use super::*; + + /// oMLX 0.8.4's `/health` once its pinned model has loaded, and while it loads. + const HEALTHY: &str = r#"{"status": "healthy", "default_model": "qwen3-5-4b", "engine_pool": {"model_count": 1, "loaded_count": 1, "final_ceiling": 8589934592, "current_model_memory": 2684354560}, "mcp": null}"#; + const LOADING: &str = + r#"{"status": "loading", "default_model": "qwen3-5-4b", "engine_pool": null, "mcp": null}"#; + + /// oMLX 0.8.4's `/v1/models` serving the model with a 32,768-token cap. + const MODELS: &str = r#"{"object": "list", "data": [{"id": "qwen3-5-4b", "object": "model", "created": 1764115200, "owned_by": "omlx", "model_type": "llm", "max_model_len": 32768}]}"#; + + #[tokio::test] + async fn ready_requires_health_and_the_exact_served_model_id() { + let port = serve([(200, HEALTHY), (200, MODELS)]).await; + assert!( + is_ready(&endpoint(port), "qwen3-5-4b", Some(32_768)) + .await + .expect("probe") + ); + + let port = serve([(200, HEALTHY), (200, MODELS)]).await; + assert!( + !is_ready(&endpoint(port), "qwen3-5", Some(32_768)) + .await + .expect("probe") + ); + } + + #[tokio::test] + async fn loading_health_is_not_ready() { + let port = serve([(503, LOADING)]).await; + assert!( + !is_ready(&endpoint(port), "qwen3-5-4b", Some(32_768)) + .await + .expect("probe") + ); + + // A healthy status is required even on a 200. + let port = serve([(200, LOADING)]).await; + assert!( + !is_ready(&endpoint(port), "qwen3-5-4b", Some(32_768)) + .await + .expect("probe") + ); + } + + #[tokio::test] + async fn refused_connection_while_starting_is_not_ready() { + let reserved = dotcore_domain::test_support::ports::reserve_port(); + + assert!( + !is_ready(&endpoint(reserved.port()), "qwen3-5-4b", None) + .await + .expect("probe") + ); + } + + #[tokio::test] + async fn a_listed_context_below_the_context_per_request_cannot_serve_the_deployment() { + let port = serve([(200, HEALTHY), (200, MODELS)]).await; + let error = is_ready(&endpoint(port), "qwen3-5-4b", Some(32_769)) + .await + .expect_err("a context per request above the listed one"); + + assert_eq!( + error.to_string(), + "engine cannot serve the deployment: oMLX started with a context per request of 32768 \ + tokens, below the deployment's 32769 tokens; recreate the deployment" + ); + } + + #[tokio::test] + async fn a_listing_without_the_context_cap_is_retried() { + let port = serve([ + (200, HEALTHY), + ( + 200, + &MODELS.replace(r#""max_model_len": 32768"#, r#""max_model_len": null"#), + ), + ]) + .await; + let error = is_ready(&endpoint(port), "qwen3-5-4b", Some(32_768)) + .await + .expect_err("no context cap"); + + assert_eq!( + error.to_string(), + "engine readiness probe failed: oMLX /v1/models lists the served model without its context" + ); + } + + #[tokio::test] + async fn unexpected_health_body_is_retried() { + let port = serve([(200, r#"{"ok": true}"#)]).await; + + let error = is_ready(&endpoint(port), "qwen3-5-4b", None) + .await + .expect_err("unexpected body"); + + assert_eq!( + error.to_string(), + "engine readiness probe failed: oMLX /health returned an unexpected body" + ); + } + + fn endpoint(port: u16) -> LoopbackEndpoint { + LoopbackEndpoint { + port_name: "http".to_owned(), + host_port: port, + } + } + + /// Serves one response per connection, in order: `/health` first, then `/v1/models`. + async fn serve(responses: [(u16, &str); N]) -> u16 { + let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)) + .await + .expect("loopback listener"); + let port = listener.local_addr().expect("listener address").port(); + let responses = responses + .into_iter() + .zip(["/health", "/v1/models"]) + .map(|((status, body), path)| { + ( + path, + format!( + "HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ), + ) + }) + .collect::>(); + tokio::spawn(async move { + for (path, response) in responses { + let (mut stream, _) = listener.accept().await.expect("probe connection"); + let mut request = Vec::new(); + let mut buffer = [0_u8; 256]; + while !request.ends_with(b"\r\n\r\n") { + let read = stream.read(&mut buffer).await.expect("request bytes"); + assert_ne!(read, 0, "request ended before its headers"); + request.extend_from_slice(&buffer[..read]); + } + assert!(request.starts_with(format!("GET {path} HTTP/1.1\r\n").as_bytes())); + stream + .write_all(response.as_bytes()) + .await + .expect("response"); + } + }); + port + } +} diff --git a/backend/core/src/model/engine/omlx/realization.rs b/backend/core/src/model/engine/omlx/realization.rs new file mode 100644 index 00000000..cef7d3e4 --- /dev/null +++ b/backend/core/src/model/engine/omlx/realization.rs @@ -0,0 +1,136 @@ +//! Materializes the resolved oMLX engine selection from a model configuration. +//! +//! The retained state is the configuration's fixed settings. oMLX configurations declare no +//! options and bind no auxiliary artifacts, so nothing else is selected, and the input +//! capabilities are the configuration's own. + +use dotcore_proto::dotcore::{ + catalog::v1::{Model, ModelArtifactBinding, ModelEngineConfiguration, ModelOptionValues}, + engine::{ + omlx::v1::OmlxResolvedModelState, + v1::{ + EngineKind, ResolvedEngineModelState, engine_model_configuration::Configuration, + resolved_engine_model_state::State, + }, + }, +}; + +use crate::model::engine::realization::ResolvedEngineSelection; + +pub(crate) const SEMANTICS_VERSION: u32 = 1; + +pub(crate) fn realize_model( + _model: &Model, + configuration: &ModelEngineConfiguration, + binding: &ModelArtifactBinding, + option_values: &[ModelOptionValues], +) -> anyhow::Result { + let payload = configuration + .engine_configuration + .as_ref() + .and_then(|payload| payload.configuration.as_ref()) + .and_then(|payload| match payload { + Configuration::Omlx(payload) => Some(payload), + _ => None, + }) + .ok_or_else(|| anyhow::anyhow!("configuration has no oMLX payload"))?; + let fixed_settings = payload + .fixed_settings + .clone() + .ok_or_else(|| anyhow::anyhow!("configuration has no fixed oMLX settings"))?; + if !binding.auxiliary_artifact_ids.is_empty() { + anyhow::bail!("oMLX binding selects auxiliary artifacts"); + } + if !option_values.is_empty() { + anyhow::bail!("oMLX configuration has no options to resolve"); + } + let input_capabilities = configuration + .input_capabilities + .clone() + .ok_or_else(|| anyhow::anyhow!("configuration has no input capabilities"))?; + + Ok(ResolvedEngineSelection { + state: ResolvedEngineModelState { + engine_kind: EngineKind::Omlx as i32, + semantics_version: SEMANTICS_VERSION, + state: Some(State::Omlx(OmlxResolvedModelState { + fixed_settings: Some(fixed_settings), + })), + }, + auxiliary_artifact_ids: Vec::new(), + input_capabilities, + }) +} + +#[cfg(test)] +mod tests { + use dotcore_proto::dotcore::catalog::v1::ModelOptionParameterValue; + + use super::*; + use crate::test_support::omlx::{configuration, model}; + + #[test] + fn realization_retains_the_fixed_settings_and_the_configuration_inputs() { + let configuration = configuration(); + + let selection = realize_model( + &model(), + &configuration, + &configuration.artifact_bindings[0], + &[], + ) + .expect("realized selection"); + + let Some(Configuration::Omlx(payload)) = configuration + .engine_configuration + .as_ref() + .and_then(|payload| payload.configuration.clone()) + else { + panic!("oMLX payload"); + }; + assert_eq!( + selection.state, + ResolvedEngineModelState { + engine_kind: EngineKind::Omlx as i32, + semantics_version: 1, + state: Some(State::Omlx(OmlxResolvedModelState { + fixed_settings: payload.fixed_settings, + })), + } + ); + assert_eq!(selection.auxiliary_artifact_ids, Vec::::new()); + assert_eq!( + Some(selection.input_capabilities), + configuration.input_capabilities + ); + } + + #[test] + fn realization_rejects_auxiliary_artifacts_and_option_values() { + let configuration = configuration(); + let mut binding = configuration.artifact_bindings[0].clone(); + binding.auxiliary_artifact_ids = vec!["draft".to_owned()]; + assert_eq!( + realize_model(&model(), &configuration, &binding, &[]) + .err() + .map(|error| error.to_string()), + Some("oMLX binding selects auxiliary artifacts".to_owned()) + ); + + let values = ModelOptionValues { + option_id: "mtp".to_owned(), + values: vec![ModelOptionParameterValue::default()], + }; + assert_eq!( + realize_model( + &model(), + &configuration, + &configuration.artifact_bindings[0], + &[values] + ) + .err() + .map(|error| error.to_string()), + Some("oMLX configuration has no options to resolve".to_owned()) + ); + } +} diff --git a/backend/core/src/model/engine/omlx/startup_refusal.rs b/backend/core/src/model/engine/omlx/startup_refusal.rs new file mode 100644 index 00000000..c43c72c3 --- /dev/null +++ b/backend/core/src/model/engine/omlx/startup_refusal.rs @@ -0,0 +1,71 @@ +//! Recognizes the oMLX package launcher's refusal to start on a macOS older than the pinned +//! release supports, for example `omlx: macOS 26 or newer is required, found 15.5`. +//! +//! The refusal is reported with the macOS version required and the one found. Only the +//! launcher's fixed wording is matched, so other lines are not recognized. When the line repeats, +//! the last occurrence wins. + +use crate::model::engine::startup_refusal::StartupRefusal; + +/// Start of the launcher's refusal, after which it names the required major version. +const REFUSAL_MARKER: &str = "omlx: macOS "; + +/// Text between the required version and the version found. +const REFUSAL_COMPARISON: &str = " or newer is required, found "; + +/// Returns the launcher's refusal in startup output, in chronological order with one entry per +/// line. +pub(super) fn startup_refusal(output: &str) -> Option { + output.lines().rev().find_map(macos_refusal) +} + +fn macos_refusal(line: &str) -> Option { + let refusal = &line[line.find(REFUSAL_MARKER)? + REFUSAL_MARKER.len()..]; + let (required, found) = refusal.split_once(REFUSAL_COMPARISON)?; + let found = found.trim(); + if !is_version(required) || !is_version(found) { + return None; + } + Some(StartupRefusal::UnsupportedOperatingSystem { + required: format!("macOS {required}"), + found: format!("macOS {found}"), + line: line.trim().to_owned(), + }) +} + +/// Whether `value` is a dotted version such as `26` or `15.5.1`. +fn is_version(value: &str) -> bool { + value + .split('.') + .all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_launcher_refusal_reports_the_required_and_found_macos() { + let output = "Traceback (most recent call last):\nomlx: macOS 26 or newer is required, found 15.5.1\n"; + + assert_eq!( + startup_refusal(output), + Some(StartupRefusal::UnsupportedOperatingSystem { + required: "macOS 26".to_owned(), + found: "macOS 15.5.1".to_owned(), + line: "omlx: macOS 26 or newer is required, found 15.5.1".to_owned(), + }) + ); + } + + #[test] + fn other_startup_failures_have_no_refusal() { + for output in [ + "omlx: macOS 26 or newer is required, found ", + "omlx: macOS twenty-six or newer is required, found 15.5", + "RuntimeError: Metal device not found", + ] { + assert_eq!(startup_refusal(output), None, "{output}"); + } + } +} diff --git a/backend/core/src/model/engine/omlx/workload.rs b/backend/core/src/model/engine/omlx/workload.rs new file mode 100644 index 00000000..df4bbf79 --- /dev/null +++ b/backend/core/src/model/engine/omlx/workload.rs @@ -0,0 +1,405 @@ +//! Materializes a resolved oMLX model launch into the native workload the runtime executes. +//! +//! It verifies the engine constraints, a native Nix package for darwin/arm64 with one Apple +//! accelerator, then binds the stored plan to the package launcher under the retained store path, +//! keeping the snapshot and service port tokens for the native runtime to resolve. The launcher +//! sets oMLX's environment itself, so the workload passes none. + +use std::collections::BTreeMap; + +use dotcore_artifact::PreparedModelArtifacts; +use dotcore_domain::{Accelerator, ExecutionPlatform, WorkloadArtifactKind}; +use dotcore_proto::dotcore::{ + engine::v1::{EngineKind, resolved_engine_model_state::State}, + model::v1::{ + PortableModelLaunchPlan, portable_model_launch_argument_token::Value as ArgumentValue, + }, +}; +use dotcore_runtime::{ + ExecutionTarget, WorkloadArtifactBinding, WorkloadExecutable, WorkloadExecutableArtifact, + WorkloadIpcMode, WorkloadPort, WorkloadSpec, WorkloadToken, WorkloadValue, +}; + +use super::plan::{MODEL_BINDING_ID, PLAN_FORMAT_VERSION, SERVICE_NAME}; +use crate::model::resolved::{ResolvedEngineSource, ResolvedModelLaunch}; + +/// Executable artifact kinds an oMLX engine artifact can provide: a Nix package for native +/// runtimes. +pub(super) const ARTIFACT_KINDS: &[WorkloadArtifactKind] = &[WorkloadArtifactKind::Nix]; + +/// Port the workload declares for its service. The native runtime assigns a loopback port in its +/// place, which the plan's port token resolves to. +const SERVICE_PORT: u16 = 8000; + +/// Builds the workload spec by binding the stored symbolic plan to the package launcher. +pub(crate) fn workload( + model: &ResolvedModelLaunch, + target: &ExecutionTarget, + artifacts: &PreparedModelArtifacts, +) -> Result { + validate_runtime_constraints(model, target)?; + let ResolvedEngineSource::Nix { executable, .. } = &model.engine.source else { + return Err(OmlxWorkloadError::UnsupportedEngine); + }; + let materialized = materialize_plan(&model.plan, artifacts)?; + Ok(WorkloadSpec { + executable: WorkloadExecutable { + artifact: WorkloadExecutableArtifact::NixStorePath( + model.engine.launch_identity.clone(), + ), + path: format!("bin/{executable}"), + }, + required_platform: ExecutionPlatform::darwin_arm64(), + arguments: materialized.arguments, + environment: BTreeMap::new(), + artifacts: materialized.artifacts, + storage: Vec::new(), + ports: vec![WorkloadPort { + name: SERVICE_NAME.to_owned(), + container_port: SERVICE_PORT, + }], + accelerator_device_ids: target.accelerator_device_ids.clone(), + required_accelerator_device_count: model.hardware.accelerator_device_count(), + ipc_mode: WorkloadIpcMode::Isolated, + expected_memory: Default::default(), + }) +} + +fn validate_runtime_constraints( + model: &ResolvedModelLaunch, + target: &ExecutionTarget, +) -> Result<(), OmlxWorkloadError> { + let state_matches = model + .snapshot + .resolved_engine_state + .as_ref() + .is_some_and(|state| { + state.engine_kind == EngineKind::Omlx as i32 + && state.semantics_version == super::realization::SEMANTICS_VERSION + && matches!(state.state, Some(State::Omlx(_))) + }); + let platform = &model.engine.platform; + if model.engine.kind != EngineKind::Omlx as i32 + || !state_matches + || ( + platform.operating_system.as_str(), + platform.architecture.as_str(), + platform.accelerator.as_str(), + ) != ("darwin", "arm64", Accelerator::Apple.catalog_name()) + { + return Err(OmlxWorkloadError::UnsupportedEngine); + } + let [requirement] = model.hardware.accelerator_requirements.as_slice() else { + return Err(OmlxWorkloadError::InvalidAcceleratorRequirement); + }; + if requirement.vendor != Accelerator::Apple.catalog_name() || requirement.minimum_count != 1 { + return Err(OmlxWorkloadError::InvalidAcceleratorRequirement); + } + if target.accelerator_device_ids.len() > 1 + || target + .accelerator_device_ids + .iter() + .any(|device| !valid_device_id(device)) + { + return Err(OmlxWorkloadError::UnsafeAcceleratorDevice); + } + Ok(()) +} + +/// Binds the plan to the prepared snapshot: the executable token must lead, and every other token +/// is a literal, the snapshot binding, or the service port. +fn materialize_plan( + plan: &PortableModelLaunchPlan, + artifacts: &PreparedModelArtifacts, +) -> Result { + if plan.format_version != PLAN_FORMAT_VERSION { + return Err(OmlxWorkloadError::UnsupportedPlan); + } + let [binding] = plan.artifact_bindings.as_slice() else { + return Err(OmlxWorkloadError::InvalidPlan); + }; + if binding.binding_id != MODEL_BINDING_ID || !binding.read_only || binding.artifact.is_none() { + return Err(OmlxWorkloadError::InvalidPlan); + } + let source = artifacts + .artifacts + .get(MODEL_BINDING_ID) + .ok_or(OmlxWorkloadError::MissingPreparedArtifact)?; + if artifacts.artifacts.len() != 1 { + return Err(OmlxWorkloadError::UnexpectedPreparedArtifact); + } + let Some((executable, arguments)) = plan.arguments.split_first() else { + return Err(OmlxWorkloadError::InvalidPlan); + }; + if !matches!(executable.value, Some(ArgumentValue::EngineExecutable(_))) { + return Err(OmlxWorkloadError::InvalidPlan); + } + let arguments = arguments + .iter() + .map(|argument| match argument.value.as_ref() { + Some(ArgumentValue::Literal(value)) => Ok(WorkloadValue::literal(value)), + Some(ArgumentValue::ArtifactBindingId(id)) if id == MODEL_BINDING_ID => { + Ok(WorkloadValue::token(WorkloadToken::Artifact(id.clone()))) + } + Some(ArgumentValue::ServicePort(name)) if name == SERVICE_NAME => Ok( + WorkloadValue::token(WorkloadToken::ServicePort(name.clone())), + ), + _ => Err(OmlxWorkloadError::InvalidPlan), + }) + .collect::, _>>()?; + Ok(MaterializedPlan { + arguments, + artifacts: vec![WorkloadArtifactBinding { + name: MODEL_BINDING_ID.to_owned(), + source: source.clone(), + // Native runtimes pass the host path through the artifact token and mount nothing. + destination: "/opt/dotcore/models/snapshot".to_owned(), + read_only: true, + }], + }) +} + +#[derive(Debug)] +struct MaterializedPlan { + arguments: Vec, + artifacts: Vec, +} + +/// Indicates the stored plan cannot safely materialize into an oMLX workload. +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +pub enum OmlxWorkloadError { + #[error( + "oMLX model profile requires a native Nix engine artifact for darwin/arm64 with Apple accelerators" + )] + UnsupportedEngine, + + #[error("oMLX model profile requires one Apple accelerator")] + InvalidAcceleratorRequirement, + + #[error("oMLX model profile has an unsafe accelerator device identity")] + UnsafeAcceleratorDevice, + + #[error("oMLX workload has an unsupported desired-plan format")] + UnsupportedPlan, + + #[error("oMLX workload has corrupt desired-plan bindings or arguments")] + InvalidPlan, + + #[error("oMLX workload has no prepared artifact for a plan binding")] + MissingPreparedArtifact, + + #[error("oMLX workload has an unexpected prepared artifact binding")] + UnexpectedPreparedArtifact, +} + +fn valid_device_id(value: &str) -> bool { + !value.is_empty() + && value.len() <= 128 + && value.chars().all(|character| { + !character.is_control() && !character.is_whitespace() && character != ',' + }) +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use super::*; + use crate::test_support::omlx::{STORE_PATH, local_model_snapshot}; + + #[test] + fn the_package_launcher_runs_from_the_retained_store_path_on_the_apple_gpu() { + let model = resolved(); + + let spec = workload( + &model, + &apple_gpu(), + &prepared([("model", "/artifacts/snapshot")]), + ) + .expect("oMLX workload"); + + assert_eq!( + spec.executable, + WorkloadExecutable { + artifact: WorkloadExecutableArtifact::NixStorePath(STORE_PATH.to_owned()), + path: "bin/omlx-launcher".to_owned(), + } + ); + assert_eq!(spec.required_platform, ExecutionPlatform::darwin_arm64()); + assert_eq!( + spec.arguments + .iter() + .map(ToString::to_string) + .collect::>(), + [ + "--snapshot", + "{artifact:model}", + "--served-id", + "qwen3-5-4b", + "--port", + "{service:http.port}", + "--context-per-request", + "32768", + "--parallel-requests", + "2", + "--memory-ceiling-gb", + "10.573", + "--prompt-cache-gb", + "2", + ] + ); + assert_eq!(spec.environment, BTreeMap::new()); + assert_eq!( + spec.artifacts, + [WorkloadArtifactBinding { + name: "model".to_owned(), + source: PathBuf::from("/artifacts/snapshot"), + destination: "/opt/dotcore/models/snapshot".to_owned(), + read_only: true, + }] + ); + assert_eq!( + spec.ports, + [WorkloadPort { + name: "http".to_owned(), + container_port: 8000, + }] + ); + assert_eq!(spec.accelerator_device_ids, ["apple-gpu-0"]); + assert_eq!(spec.required_accelerator_device_count, 1); + } + + #[test] + fn workload_rejects_engines_other_than_a_native_apple_package() { + let mut image = resolved(); + image.engine.source = ResolvedEngineSource::OciImage { + reference: "registry.dotcore.test/omlx:dev".to_owned(), + }; + let mut linux = resolved(); + linux.engine.platform.operating_system = "linux".to_owned(); + let mut nvidia = resolved(); + nvidia.engine.platform.accelerator = "nvidia".to_owned(); + let mut other_kind = resolved(); + other_kind.engine.kind = EngineKind::LlamaCpp as i32; + + for (case, model) in [ + ("OCI image", image), + ("Linux", linux), + ("NVIDIA", nvidia), + ("other kind", other_kind), + ] { + assert_eq!( + workload( + &model, + &apple_gpu(), + &prepared([("model", "/artifacts/snapshot")]) + ), + Err(OmlxWorkloadError::UnsupportedEngine), + "{case}" + ); + } + assert_eq!( + OmlxWorkloadError::UnsupportedEngine.to_string(), + "oMLX model profile requires a native Nix engine artifact for darwin/arm64 with Apple \ + accelerators" + ); + } + + #[test] + fn workload_rejects_another_accelerator_requirement_or_several_devices() { + let mut nvidia = resolved(); + nvidia.hardware.accelerator_requirements[0].vendor = "nvidia".to_owned(); + assert_eq!( + workload( + &nvidia, + &apple_gpu(), + &prepared([("model", "/artifacts/snapshot")]) + ), + Err(OmlxWorkloadError::InvalidAcceleratorRequirement) + ); + + let two_devices = ExecutionTarget { + accelerator_device_ids: vec!["apple-gpu-0".to_owned(), "apple-gpu-1".to_owned()], + ..apple_gpu() + }; + assert_eq!( + workload( + &resolved(), + &two_devices, + &prepared([("model", "/artifacts/snapshot")]) + ), + Err(OmlxWorkloadError::UnsafeAcceleratorDevice) + ); + } + + #[test] + fn materialization_fails_closed_on_corrupt_plans_and_prepared_artifacts() { + let plan = resolved().plan; + assert_eq!( + materialize_plan(&plan, &prepared([])).expect_err("missing prepared artifact"), + OmlxWorkloadError::MissingPreparedArtifact + ); + assert_eq!( + materialize_plan( + &plan, + &prepared([ + ("model", "/artifacts/snapshot"), + ("extra", "/artifacts/extra") + ]) + ) + .expect_err("unexpected prepared artifact"), + OmlxWorkloadError::UnexpectedPreparedArtifact + ); + + let mut unsupported = plan.clone(); + unsupported.format_version = 2; + assert_eq!( + materialize_plan(&unsupported, &prepared([("model", "/artifacts/snapshot")])) + .expect_err("unsupported plan"), + OmlxWorkloadError::UnsupportedPlan + ); + + let mut missing_executable = plan.clone(); + missing_executable.arguments.remove(0); + let mut service_host = plan.clone(); + service_host.arguments[6].value = Some(ArgumentValue::ServiceHost("http".to_owned())); + let mut unknown_binding = plan.clone(); + unknown_binding.artifact_bindings[0].binding_id = "weights".to_owned(); + let mut writable = plan; + writable.artifact_bindings[0].read_only = false; + for (case, corrupt) in [ + ("missing executable", missing_executable), + ("service host", service_host), + ("unknown binding", unknown_binding), + ("writable", writable), + ] { + assert_eq!( + materialize_plan(&corrupt, &prepared([("model", "/artifacts/snapshot")])) + .expect_err(case), + OmlxWorkloadError::InvalidPlan, + "{case}" + ); + } + } + + fn resolved() -> ResolvedModelLaunch { + ResolvedModelLaunch::from_snapshot(&local_model_snapshot("qwen3-5-4b")) + .expect("resolved launch") + } + + fn apple_gpu() -> ExecutionTarget { + ExecutionTarget { + managed_node_id: dotcore_domain::SiteNodeId::for_test("node"), + accelerator_device_ids: vec![dotcore_domain::APPLE_GPU_DEVICE_ID.to_owned()], + } + } + + fn prepared(values: [(&str, &str); N]) -> PreparedModelArtifacts { + PreparedModelArtifacts { + artifacts: values + .into_iter() + .map(|(binding_id, path)| (binding_id.to_owned(), PathBuf::from(path))) + .collect(), + } + } +} diff --git a/backend/core/src/model/engine/openai_compatible_transport.rs b/backend/core/src/model/engine/openai_compatible_transport.rs index cff4899f..4d8752ca 100644 --- a/backend/core/src/model/engine/openai_compatible_transport.rs +++ b/backend/core/src/model/engine/openai_compatible_transport.rs @@ -1,10 +1,10 @@ //! Loopback chat transport for local OpenAI-compatible engines. //! -//! The llama.cpp, vLLM, and ninfer bindings share this one-attempt transport: it sends the +//! The llama.cpp, vLLM, ninfer and oMLX bindings share this one-attempt transport: it sends the //! validated request under the engine's served model id, with its instruction messages shaped for -//! model chat templates, decodes complete or streamed answers, -//! and passes unsuccessful engine responses through unchanged. Streams are checked for order -//! and completeness before any event reaches the router. +//! model chat templates, decodes complete or streamed answers, and passes unsuccessful engine +//! responses through unchanged. Streams are checked for order and completeness before any event +//! reaches the router, and an engine failing a stream ends it with a typed engine error. #[cfg(test)] use dotcore_proto::dotcore::inference::v1::{ChatMessage, ChatMessageRole, chat_message}; @@ -190,6 +190,7 @@ async fn read_stream( let result = forward_stream( &mut stream, &request, + classify, &mut cancellation, pending, chunked, @@ -218,6 +219,7 @@ async fn read_stream( async fn forward_stream( stream: &mut TcpStream, request: &ChatRequest, + classify: Option, cancellation: &mut RequestCancellation, mut pending: Vec, mut chunked: Option, @@ -225,6 +227,7 @@ async fn forward_stream( ) -> Result<(), AdapterError> { const MAX_UPSTREAM_STREAM_BUFFER_BYTES: usize = 1024 * 1024; let mut done = false; + let mut forwarded = false; let include_usage = request.include_stream_usage.unwrap_or(false); let mut validator = codec::StreamValidator::new(include_usage); loop { @@ -244,9 +247,15 @@ async fn forward_stream( done = true; break; } - for mut event in codec::decode_sse_frame(data) + let events = match codec::decode_sse_frame(data) .map_err(|error| upstream_transport(TransportError::StreamDecode(error)))? { + codec::SseFrame::Events(events) => events, + codec::SseFrame::Error(error) => { + return Err(stream_failure(error, forwarded, classify)); + } + }; + for mut event in events { if validator .apply(&event) .map_err(|error| upstream_transport(TransportError::StreamPolicy(error)))? @@ -264,6 +273,7 @@ async fn forward_stream( if result.is_err() { return Ok(()); } + forwarded = true; } } } @@ -319,6 +329,28 @@ async fn forward_stream( Ok(()) } +/// Fails a stream the engine ended with an error frame. Before any event reached the router, the +/// response is not committed yet, so a rejection `classify` recognizes fails as an invalid +/// request; any other error frame is an engine failure. +fn stream_failure( + error: codec::StreamErrorFrame, + forwarded: bool, + classify: Option, +) -> AdapterError { + error.log_failure(forwarded); + if !forwarded + && let Some(invalid) = classify.and_then(|classify| classify(error.status, &error.body)) + { + debug!( + status = error.status, + category = %invalid.category, + "Engine stream error classified as an invalid request" + ); + return AdapterError::InvalidRequest(invalid); + } + upstream_transport(TransportError::EngineStreamError(error)) +} + fn sse_frame_end(pending: &[u8]) -> Option<(usize, usize)> { pending .windows(2) @@ -336,16 +368,20 @@ fn sse_frame_end(pending: &[u8]) -> Option<(usize, usize)> { mod tests { use std::{io, sync::Arc}; - use dotcore_proto::dotcore::inference::v1::{FunctionToolDefinition, chat_stream_event::Event}; + use dotcore_domain::test_support::tracing::{Record, capture_records_async}; + use dotcore_proto::dotcore::inference::v1::{ + ChatStreamStarted, ChatTextDelta, FunctionToolDefinition, chat_stream_event::Event, + chat_text_delta, + }; use tokio::{io::AsyncWriteExt, sync::watch}; use super::*; - use crate::inference::{InferenceAttemptDisposition, InferenceError}; + use crate::inference::{InferenceAttemptDisposition, InferenceError, InvalidRequest}; use crate::test_support::http::read_request; use crate::{ model::controller::serving_targets::ServingTargetsRevocationReason, router::{ - adapters::{AdapterAttempt, AdapterAttemptDisposition}, + adapters::{AdapterAttempt, AdapterAttemptDisposition, failure_stage}, cancellation::RequestCancellationReason, openai::OpenAiRequest, }, @@ -906,6 +942,73 @@ mod tests { assert!(error.to_string().contains("after [DONE]")); } + #[tokio::test] + async fn an_error_frame_before_any_event_fails_as_the_rejection_its_engine_recognizes() { + let refusal = b"data: {\"error\":{\"message\":\"prompt is too long\",\"type\":\"BadRequestError\",\"param\":null,\"code\":400}}\n\ndata: [DONE]\n\n"; + + let (events, error) = engine_stream_failure(refusal, Some(reject_long_prompts)).await; + + assert_eq!(events, []); + assert!( + matches!(error, AdapterError::InvalidRequest(invalid) if invalid == InvalidRequest::context_length()), + "{error:?}" + ); + + let (events, error) = engine_stream_failure(refusal, None).await; + + assert_eq!(events, []); + assert!(matches!(error, AdapterError::Upstream(_)), "{error:?}"); + assert_eq!(failure_stage(&error), "engine_error"); + } + + #[tokio::test] + async fn an_error_frame_after_the_first_chunk_fails_as_an_engine_error_with_its_safe_fields_logged() + { + let ((events, error), records, _) = capture_records_async(|| { + engine_stream_failure( + b"data: {\"id\":\"chatcmpl_failed\",\"model\":\"served-model\",\"created\":7,\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"Hi\"},\"finish_reason\":null}]}\n\ndata: {\"error\":{\"message\":\"prompt is too long\",\"type\":\"BadRequestError\",\"param\":null,\"code\":400}}\n\ndata: [DONE]\n\n", + Some(reject_long_prompts), + ) + }) + .await; + + assert_eq!( + events, + [ + ChatStreamEvent { + event: Some(Event::Started(ChatStreamStarted { + completion_id: "chatcmpl_failed".to_owned(), + model_id: "requested-model".to_owned(), + created_at_unix_seconds: 7, + })), + }, + ChatStreamEvent { + event: Some(Event::TextDelta(ChatTextDelta { + choice_index: 0, + role: Some(ChatMessageRole::Assistant as i32), + content: Some(chat_text_delta::Content::TextContent("Hi".to_owned())), + })), + }, + ] + ); + assert!(matches!(error, AdapterError::Upstream(_)), "{error:?}"); + assert_eq!(failure_stage(&error), "engine_error"); + assert!( + records.iter().any(|record| matches!( + record, + Record::Event { level, fields } + if level == "WARN" + && fields.get("error_code") == Some(&"\"400\"".to_owned()) + && fields.get("error_type") == Some(&"\"BadRequestError\"".to_owned()) + && !fields.contains_key("engine_message") + && !format!("{fields:?}").contains("prompt is too long") + && fields.get("status") == Some(&"400".to_owned()) + && fields.get("forwarded") == Some(&"true".to_owned()) + )), + "{records:?}" + ); + } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn route_revocation_before_connect_returns_typed_cancellation() { let (cancellation, _client, route) = uncancelled(); @@ -1195,6 +1298,57 @@ mod tests { error } + /// Streams `body` from an engine whose chat rejections `classify` recognizes, and returns the + /// events forwarded before the stream failed with its error. + async fn engine_stream_failure( + body: &'static [u8], + classify: Option, + ) -> (Vec, AdapterError) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("upstream listener"); + let port = listener.local_addr().expect("upstream address").port(); + let upstream = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.expect("upstream connection"); + read_request(&mut stream).await; + stream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n") + .await + .expect("upstream headers"); + stream.write_all(body).await.expect("upstream body"); + }); + let (cancellation, _client, _route) = uncancelled(); + let response = invoke_loopback( + port, + TEST_SERVED_MODEL_ID, + request(true), + classify, + cancellation, + ) + .await + .expect("stream response"); + let AdapterResponse::Stream(mut events) = response else { + panic!("stream response") + }; + let mut forwarded = Vec::new(); + let error = loop { + match events.recv().await { + Some(Ok(event)) => forwarded.push(event), + Some(Err(error)) => break error, + None => panic!("a failed stream must report its error"), + } + }; + assert!(events.recv().await.is_none(), "the error ends the stream"); + upstream.await.expect("upstream task"); + (forwarded, error) + } + + /// Recognizes an engine's refusal of a prompt longer than its context. + fn reject_long_prompts(status: u16, body: &[u8]) -> Option { + (status == 400 && http::error_message(body).as_deref() == Some("prompt is too long")) + .then(InvalidRequest::context_length) + } + fn assert_no_fallback(attempt: &AdapterAttempt) { assert!( !attempt.allows_fallback(), diff --git a/backend/core/src/model/engine/registry.rs b/backend/core/src/model/engine/registry.rs index b70c6d90..f72e91c1 100644 --- a/backend/core/src/model/engine/registry.rs +++ b/backend/core/src/model/engine/registry.rs @@ -426,6 +426,7 @@ mod tests { EngineKind::Vllm, EngineKind::Ninfer, EngineKind::Strata, + EngineKind::Omlx, ] { assert!(factories.get(kind).is_some(), "{kind:?}"); } @@ -441,6 +442,7 @@ mod tests { EngineKind::Vllm, EngineKind::Ninfer, EngineKind::Strata, + EngineKind::Omlx, ] { let integration = registry.integration(kind).expect("integration"); assert_eq!(integration.definition.kind(), kind); @@ -466,6 +468,7 @@ mod tests { assert!(!has_extractor(EngineKind::LlamaCpp)); assert!(!has_extractor(EngineKind::Ninfer)); assert!(!has_extractor(EngineKind::Strata)); + assert!(!has_extractor(EngineKind::Omlx)); } #[test] diff --git a/backend/core/src/model/engine/startup_refusal.rs b/backend/core/src/model/engine/startup_refusal.rs index 968e950f..34b57ddd 100644 --- a/backend/core/src/model/engine/startup_refusal.rs +++ b/backend/core/src/model/engine/startup_refusal.rs @@ -13,13 +13,22 @@ pub(crate) enum StartupRefusal { free_bytes: u64, line: String, }, + + /// The node's operating system is older than the engine runs on, so the engine can't start + /// there at all. + UnsupportedOperatingSystem { + required: String, + found: String, + line: String, + }, } impl StartupRefusal { /// The output line the refusal was read from. pub(crate) fn line(&self) -> &str { match self { - Self::InsufficientFreeMemory { line, .. } => line, + Self::InsufficientFreeMemory { line, .. } + | Self::UnsupportedOperatingSystem { line, .. } => line, } } } diff --git a/backend/core/src/model/engine/strata/plan.rs b/backend/core/src/model/engine/strata/plan.rs index af32e464..80e51ca3 100644 --- a/backend/core/src/model/engine/strata/plan.rs +++ b/backend/core/src/model/engine/strata/plan.rs @@ -226,7 +226,7 @@ fn resolved_state( .and_then(|state| state.state.as_ref()) .and_then(|state| match state { State::Strata(state) => Some(state), - State::LlamaCpp(_) | State::Vllm(_) | State::Ninfer(_) => None, + _ => None, }) .ok_or(StrataPlanError::InvalidResolvedState) } diff --git a/backend/core/src/model/engine/strata/realization.rs b/backend/core/src/model/engine/strata/realization.rs index d6aac189..664089a4 100644 --- a/backend/core/src/model/engine/strata/realization.rs +++ b/backend/core/src/model/engine/strata/realization.rs @@ -162,7 +162,7 @@ fn strata_payload(configuration: &ModelEngineConfiguration) -> Option<&StrataMod .and_then(|payload| payload.configuration.as_ref()) .and_then(|payload| match payload { Configuration::Strata(payload) => Some(payload), - Configuration::LlamaCpp(_) | Configuration::Vllm(_) | Configuration::Ninfer(_) => None, + _ => None, }) } diff --git a/backend/core/src/model/engine/vllm/mod.rs b/backend/core/src/model/engine/vllm/mod.rs index d8f4bdda..ca21fc1b 100644 --- a/backend/core/src/model/engine/vllm/mod.rs +++ b/backend/core/src/model/engine/vllm/mod.rs @@ -185,6 +185,6 @@ fn readiness_mode(state: &ResolvedEngineModelState) -> Option { .readiness_policy .as_ref() .map(|policy| policy.mode), - State::LlamaCpp(_) | State::Ninfer(_) | State::Strata(_) => None, + _ => None, } } diff --git a/backend/core/src/model/engine/vllm/plan.rs b/backend/core/src/model/engine/vllm/plan.rs index a53445f2..ffcfab52 100644 --- a/backend/core/src/model/engine/vllm/plan.rs +++ b/backend/core/src/model/engine/vllm/plan.rs @@ -391,7 +391,7 @@ fn resolved_state( .and_then(|state| state.state.as_ref()) .and_then(|state| match state { State::Vllm(state) => Some(state), - State::LlamaCpp(_) | State::Ninfer(_) | State::Strata(_) => None, + _ => None, }) .ok_or(VllmPlanError::InvalidResolvedState) } diff --git a/backend/core/src/model/engine/vllm/realization.rs b/backend/core/src/model/engine/vllm/realization.rs index 504b2a84..c1c99841 100644 --- a/backend/core/src/model/engine/vllm/realization.rs +++ b/backend/core/src/model/engine/vllm/realization.rs @@ -154,9 +154,7 @@ fn vllm_payload(configuration: &ModelEngineConfiguration) -> Option<&VllmModelCo .and_then(|payload| payload.configuration.as_ref()) .and_then(|payload| match payload { Configuration::Vllm(payload) => Some(payload), - Configuration::LlamaCpp(_) | Configuration::Ninfer(_) | Configuration::Strata(_) => { - None - } + _ => None, }) } diff --git a/backend/core/src/model/engine/vllm/workload.rs b/backend/core/src/model/engine/vllm/workload.rs index 6cadd08d..0d265fa2 100644 --- a/backend/core/src/model/engine/vllm/workload.rs +++ b/backend/core/src/model/engine/vllm/workload.rs @@ -95,7 +95,7 @@ fn validate_runtime_constraints<'a>( .and_then(|state| state.state.as_ref()) .and_then(|state| match state { State::Vllm(state) => state.fixed_settings.as_ref(), - State::LlamaCpp(_) | State::Ninfer(_) | State::Strata(_) => None, + _ => None, }) .ok_or(VllmWorkloadError::UnsupportedEngine)?; if fixed.container_port == 0 diff --git a/backend/core/src/model/resolution.rs b/backend/core/src/model/resolution.rs index cdd4f6fc..eb938c58 100644 --- a/backend/core/src/model/resolution.rs +++ b/backend/core/src/model/resolution.rs @@ -2791,7 +2791,7 @@ mod tests { .expect("resolved llama.cpp state") { State::LlamaCpp(state) => state, - State::Vllm(_) | State::Ninfer(_) | State::Strata(_) => { + _ => { panic!("resolved llama.cpp state") } } diff --git a/backend/core/src/router/adapters/mod.rs b/backend/core/src/router/adapters/mod.rs index eb019dd5..52baae93 100644 --- a/backend/core/src/router/adapters/mod.rs +++ b/backend/core/src/router/adapters/mod.rs @@ -286,6 +286,9 @@ pub(crate) enum AdapterTransportError { #[error("adapter transport stream terminal policy error: {0}")] StreamPolicy(#[source] crate::router::openai_compatible_codec::CodecError), + #[error("adapter transport stream ended with an engine error")] + EngineStreamError(#[source] crate::router::openai_compatible_codec::StreamErrorFrame), + #[error("adapter transport limit exceeded: {0}")] Limit(&'static str), @@ -326,6 +329,7 @@ impl AdapterTransportError { Self::StreamDecode(_) => "sse_decoding", Self::DecisionDecode(_) => "decision_decoding", Self::StreamPolicy(_) => "terminal_policy", + Self::EngineStreamError(_) => "engine_error", Self::Limit(_) => "limit", Self::Connect(_) => "connect", Self::Io(_) => "transport_io", diff --git a/backend/core/src/router/adapters/openai_compatible.rs b/backend/core/src/router/adapters/openai_compatible.rs index 52d3114b..dd3218d9 100644 --- a/backend/core/src/router/adapters/openai_compatible.rs +++ b/backend/core/src/router/adapters/openai_compatible.rs @@ -161,6 +161,7 @@ async fn forward_stream( let mut done = false; let include_usage = request.include_stream_usage.unwrap_or(false); let mut validator = codec::StreamValidator::new(include_usage); + let mut forwarded = false; loop { while !done { let Some((end, separator_length)) = sse_frame_end(&pending) else { @@ -186,9 +187,16 @@ async fn forward_stream( done = true; break; } - for mut event in codec::decode_sse_frame(&data) + let events = match codec::decode_sse_frame(&data) .map_err(|error| AdapterError::from(AdapterTransportError::StreamDecode(error)))? { + codec::SseFrame::Events(events) => events, + codec::SseFrame::Error(error) => { + error.log_failure(forwarded); + return Err(AdapterTransportError::EngineStreamError(error).into()); + } + }; + for mut event in events { if validator.apply(&event).map_err(|error| { AdapterError::from(AdapterTransportError::StreamPolicy(error)) })? == codec::StreamAction::Filter @@ -198,6 +206,7 @@ async fn forward_stream( if let Some(Event::Started(started)) = &mut event.event { started.model_id = request.model_id.clone(); } + forwarded = true; tokio::select! { biased; reason = cancellation.cancelled() => return Err(AdapterError::Cancelled(reason)), diff --git a/backend/core/src/router/http/stream.rs b/backend/core/src/router/http/stream.rs index cc7a1923..835bde8b 100644 --- a/backend/core/src/router/http/stream.rs +++ b/backend/core/src/router/http/stream.rs @@ -289,6 +289,10 @@ fn cancelled( #[cfg(test)] mod tests { + use dotcore_proto::dotcore::inference::v1::{ + ChatMessageRole, ChatStreamStarted, ChatTextDelta, chat_stream_event::Event, + chat_text_delta, + }; use serde_json::{Value, json}; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, @@ -301,8 +305,9 @@ mod tests { use crate::{ model::controller::serving_targets::ServingTargetsRevocationReason, router::{ - adapters::AdapterError, + adapters::{AdapterError, AdapterTransportError}, cancellation::{RequestCancellation, RequestCancellationReason}, + openai_compatible_codec::StreamErrorFrame, }, }; @@ -433,6 +438,120 @@ mod tests { assert!(events.contains(r#""code":"context_length_exceeded""#)); } + #[tokio::test] + async fn an_engine_error_frame_before_start_answers_its_classified_rejection_or_bad_gateway() { + let cases = [ + ( + AdapterError::InvalidRequest(crate::inference::InvalidRequest::context_length()), + StreamWriteOutcome::Failed { + error_kind: "invalid_request", + failure_stage: "invalid_request", + committed: false, + status: 400, + }, + "HTTP/1.1 400 Bad Request\r\n", + json!({"error":{"message":"The request is larger than the deployment's context.","type":"invalid_request_error","param":null,"code":"context_length_exceeded"}}), + ), + ( + engine_stream_error(), + StreamWriteOutcome::Failed { + error_kind: "upstream", + failure_stage: "engine_error", + committed: false, + status: 502, + }, + "HTTP/1.1 502 Bad Gateway\r\n", + json!({"error":{"message":"The inference engine returned an invalid response.","type":"upstream_error","param":null,"code":null}}), + ), + ]; + for (error, expected_outcome, status_line, expected_body) in cases { + let (mut client, mut writer) = connected_writer().await; + let (sender, receiver) = mpsc::channel(1); + sender.send(Err(error)).await.expect("stream receiver"); + drop(sender); + + let result = write_openai_stream( + &mut writer, + receiver, + uncancelled(), + "fixture-route".to_owned(), + false, + &mut |_| {}, + ) + .await; + writer.shutdown().await.expect("stream writer shutdown"); + let body = read_stream(&mut client).await; + + assert_eq!(result.expect("stream write"), expected_outcome); + assert!(body.starts_with(status_line), "{body}"); + assert_eq!(response_body(&body), expected_body); + assert!(!body.contains("prompt is too long")); + } + } + + #[tokio::test] + async fn an_engine_error_frame_after_start_ends_the_committed_stream_with_the_safe_frame() { + let (mut client, mut writer) = connected_writer().await; + let (sender, receiver) = mpsc::channel(3); + for event in [ + Event::Started(ChatStreamStarted { + completion_id: "chatcmpl_failed".to_owned(), + model_id: "served-model".to_owned(), + created_at_unix_seconds: 7, + }), + Event::TextDelta(ChatTextDelta { + choice_index: 0, + role: Some(ChatMessageRole::Assistant as i32), + content: Some(chat_text_delta::Content::TextContent("Hi".to_owned())), + }), + ] { + sender + .send(Ok(ChatStreamEvent { event: Some(event) })) + .await + .expect("stream receiver"); + } + sender + .send(Err(engine_stream_error())) + .await + .expect("stream receiver"); + drop(sender); + + let result = write_openai_stream( + &mut writer, + receiver, + uncancelled(), + "fixture-route".to_owned(), + false, + &mut |_| {}, + ) + .await; + writer.shutdown().await.expect("stream writer shutdown"); + let body = read_stream(&mut client).await; + + assert_eq!( + result.expect("stream write"), + StreamWriteOutcome::Failed { + error_kind: "upstream", + failure_stage: "engine_error", + committed: true, + status: 200, + } + ); + let (head, frames) = body.split_once("\r\n\r\n").expect("HTTP response"); + assert!(head.starts_with("HTTP/1.1 200 OK\r\n"), "{head}"); + assert_eq!( + frames, + concat!( + r#"data: {"choices":[],"created":7,"id":"chatcmpl_failed","model":"fixture-route","object":"chat.completion.chunk"}"#, + "\n\n", + r#"data: {"choices":[{"delta":{"content":"Hi","role":"assistant"},"finish_reason":null,"index":0}],"created":7,"id":"chatcmpl_failed","model":"fixture-route","object":"chat.completion.chunk"}"#, + "\n\n", + r#"data: {"error":{"code":null,"message":"The inference engine returned an invalid response.","param":null,"type":"upstream_error"}}"#, + "\n\n", + ) + ); + } + #[tokio::test] async fn a_failure_answer_cancelled_before_its_write_reports_the_cancellation() { let (mut client, mut writer) = connected_writer().await; @@ -486,6 +605,15 @@ mod tests { serde_json::from_str(body).expect("OpenAI response JSON") } + /// The failure the OpenAI-compatible transport reports for an engine's error frame. + fn engine_stream_error() -> AdapterError { + AdapterTransportError::EngineStreamError(StreamErrorFrame { + status: 400, + body: br#"{"error":{"message":"prompt is too long","code":400}}"#.to_vec(), + }) + .into() + } + fn uncancelled() -> RequestCancellation { let (_client, client) = watch::channel(None); let (_route, route) = watch::channel::>(None); diff --git a/backend/core/src/router/openai_compatible_codec.rs b/backend/core/src/router/openai_compatible_codec.rs index bdd8bc0c..29943462 100644 --- a/backend/core/src/router/openai_compatible_codec.rs +++ b/backend/core/src/router/openai_compatible_codec.rs @@ -349,12 +349,75 @@ pub(crate) fn decode_completion(body: &[u8]) -> Result Result, CodecError> { - let value = serde_json::from_str(data)?; - stream_events_from_value(&value) +/// Decodes one complete upstream SSE JSON payload: the stream events of a chunk, or the error +/// an engine sends in place of a chunk when it fails the stream. +pub(crate) fn decode_sse_frame(data: &str) -> Result { + let value: Value = serde_json::from_str(data)?; + if let Some(error) = stream_error(&value) { + return Ok(SseFrame::Error(StreamErrorFrame { + status: stream_error_status(error), + body: data.as_bytes().to_vec(), + })); + } + stream_events_from_value(&value).map(SseFrame::Events) +} + +/// One decoded upstream SSE JSON payload. +#[derive(Debug, PartialEq)] +pub(crate) enum SseFrame { + /// The stream events a chunk carries. + Events(Vec), + + /// The engine failed the stream. + Error(StreamErrorFrame), +} + +/// An OpenAI error object an engine streamed in place of a chunk, ending the stream. +/// +/// It keeps the status the error stands for and the frame's payload, which has the shape of an +/// unsuccessful response body, so an engine's rejection rules can read it as one. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("OpenAI-compatible engine failed the stream with status {status}")] +pub(crate) struct StreamErrorFrame { + /// The error's numeric code when it is an HTTP error status, otherwise 500. + pub(crate) status: u16, + + /// The frame's JSON payload, unchanged. + pub(crate) body: Vec, } +impl StreamErrorFrame { + /// Logs that the engine failed the stream, with the error's status, code and type but never + /// its message, which can echo request content. `forwarded` tells whether events already + /// reached the router. + pub(crate) fn log_failure(&self, forwarded: bool) { + let error = serde_json::from_slice::(&self.body).ok(); + let field = |key: &str| { + let value = error.as_ref()?.pointer("/error")?.get(key)?; + let text = match value { + Value::String(text) => text.clone(), + Value::Number(number) => number.to_string(), + _ => return None, + }; + Some( + text.chars() + .take(MAX_LOGGED_ERROR_FIELD_CHARS) + .collect::(), + ) + }; + tracing::warn!( + status = self.status, + forwarded, + error_code = field("code").as_deref(), + error_type = field("type").as_deref(), + "Engine failed the chat stream" + ); + } +} + +/// The most characters of an error's code or type that a log record keeps. +const MAX_LOGGED_ERROR_FIELD_CHARS: usize = 64; + pub(crate) fn stream_event_choice_index(event: &ChatStreamEvent) -> Option { match event.event.as_ref()? { Event::TextDelta(event) => Some(event.choice_index), @@ -748,6 +811,27 @@ fn tool_call_from_value(value: &Value) -> Result { .to_owned(), }) } + +/// Returns a frame's OpenAI error object when the frame carries one instead of chunk choices. +fn stream_error(value: &Value) -> Option<&Map> { + let object = value.as_object()?; + if object.contains_key("choices") { + return None; + } + object.get("error")?.as_object() +} + +/// The HTTP status a streamed error stands for; an error naming none is a server failure. +fn stream_error_status(error: &Map) -> u16 { + // vLLM and llama.cpp carry the status as the error's numeric code. + error + .get("code") + .and_then(Value::as_u64) + .and_then(|code| u16::try_from(code).ok()) + .filter(|code| (400..=599).contains(code)) + .unwrap_or(500) +} + fn stream_events_from_value(value: &Value) -> Result, CodecError> { let object = upstream_object(value, "stream event")?; let mut events = Vec::new(); @@ -1268,9 +1352,36 @@ mod tests { ); } + #[test] + fn an_error_frame_decodes_as_the_engine_error_with_its_status_and_payload() { + for (data, status) in [ + ( + r#"{"error":{"message":"memory guard aborted this request mid-prefill","type":"invalid_request_error","param":null,"code":"prefill_memory_aborted"},"type":"error"}"#, + 500, + ), + ( + r#"{"error":{"message":"prompt is too long","type":"BadRequestError","param":null,"code":400}}"#, + 400, + ), + ( + r#"{"error":{"message":"engine crashed","type":"server_error","code":200}}"#, + 500, + ), + ] { + assert_eq!( + decode_sse_frame(data).expect("error frame"), + SseFrame::Error(StreamErrorFrame { + status, + body: data.as_bytes().to_vec(), + }), + "{data}" + ); + } + } + #[test] fn reasoning_only_stream_chunks_emit_one_reasoning_event() { - let events = decode_sse_frame( + let SseFrame::Events(events) = decode_sse_frame( &json!({ "id": "completion", "model": "upstream-model", @@ -1283,7 +1394,9 @@ mod tests { }) .to_string(), ) - .expect("reasoning stream chunk"); + .expect("reasoning stream chunk") else { + panic!("a chunk decodes as stream events") + }; assert_eq!(event_kinds(&events), ["started", "reasoning"]); assert!(matches!( diff --git a/backend/core/src/test_support/mod.rs b/backend/core/src/test_support/mod.rs index 54f016c4..f41b2e18 100644 --- a/backend/core/src/test_support/mod.rs +++ b/backend/core/src/test_support/mod.rs @@ -8,6 +8,7 @@ use dotcore_proto::dotcore::{ pub(crate) mod http; pub(crate) mod ninfer; pub(crate) mod nix; +pub(crate) mod omlx; pub(crate) mod strata; pub(crate) use dotcore_domain::test_support::{ diff --git a/backend/core/src/test_support/omlx.rs b/backend/core/src/test_support/omlx.rs new file mode 100644 index 00000000..37d3a20a --- /dev/null +++ b/backend/core/src/test_support/omlx.rs @@ -0,0 +1,324 @@ +//! In-code oMLX fixtures for backend unit tests, shaped like a Qwen3.5 4B oMLX profile on an +//! Apple Silicon Mac. +//! +//! They provide a text-only model with one MLX snapshot, a valid oMLX configuration, its release +//! with a native darwin/arm64 Nix artifact, and an accepted deployment snapshot whose launch plan +//! is the canonical plan for the profile: a 32,768-token context per request for 2 parallel +//! requests, a 65,536-token total context, a 2 GiB prompt cache, and a 10 GB accelerator plus +//! 2 GiB host estimate. + +use dotcore_catalog::shared_parameters::{ + CONTEXT_PER_REQUEST_PARAMETER_ID, PARALLEL_REQUESTS_PARAMETER_ID, TOTAL_CONTEXT_PARAMETER_ID, +}; +use dotcore_domain::ExecutionPlatform; +use dotcore_proto::dotcore::{ + catalog::v1::{ + ContextBehavior, EngineArtifact, EngineParameterSchema, EngineRelease, + HardwareRequirements, HardwareSupport, HuggingFaceArtifactSource, + HuggingFaceSnapshotArtifact, HuggingFaceSnapshotFile, InferenceRequestKind, MemoryPool, + Model, ModelArtifact, ModelArtifactBinding, ModelEngineConfiguration, + ModelExecutionCapabilities, ModelInputCapabilities, ModelInputModality, ModelParallelShape, + NixArtifact, OciPlatform, ParameterDefinition, ParameterValue, ParameterValues, + ParameterVisibility, RequestShareContextPool, Selector, UnsignedIntegerParameterSchema, + context_behavior, engine_artifact::Kind as EngineArtifactKind, + hugging_face_artifact_source, nix_artifact::Provides, parameter_definition, + parameter_value, + }, + deployment::v1::ArtifactPreparationPolicy, + engine::{ + omlx::v1::{OmlxFixedModelSettings, OmlxModelConfiguration}, + v1::{EngineKind, EngineModelConfiguration, engine_model_configuration::Configuration}, + }, + model::v1::{ + ModelDeploymentSnapshot, ResolvedLocalModelDeploymentSnapshot, ResolvedSizing, + model_deployment_snapshot, + }, + observation::v1::AcceleratorMemoryArchitecture, +}; + +/// Engine parameter holding the in-memory prompt cache size, in MiB. +pub(crate) const PROMPT_CACHE_MIB_PARAMETER_ID: &str = "prompt-cache-memory-mib"; + +/// Store path the fixture's native Nix artifact is retained at. +pub(crate) const STORE_PATH: &str = "/nix/store/0123456789abcdfghijklmnpqrsvwxyz-omlx-0.8.4"; + +/// Accelerator and host memory estimates of the profile, in bytes. +pub(crate) const ACCELERATOR_ESTIMATE_BYTES: u64 = 10_000_000_000; +pub(crate) const HOST_ESTIMATE_BYTES: u64 = 2 * 1024 * 1024 * 1024; + +/// Resolved engine parameter values of the profile: the engine's default context per request for +/// 2 parallel requests, their product as the total context, and a 2 GiB prompt cache. +const PROFILE_PARAMETERS: [(&str, u64); 4] = [ + (TOTAL_CONTEXT_PARAMETER_ID, 65_536), + (CONTEXT_PER_REQUEST_PARAMETER_ID, 32_768), + (PARALLEL_REQUESTS_PARAMETER_ID, 2), + (PROMPT_CACHE_MIB_PARAMETER_ID, 2_048), +]; + +/// Returns an accepted oMLX snapshot for the profile values on an Apple native target, serving +/// `model_id`. +pub(crate) fn local_model_snapshot(model_id: &str) -> ModelDeploymentSnapshot { + let model = model(); + let configuration = configuration(); + let selection = crate::model::engine::omlx::realize_model( + &model, + &configuration, + &configuration.artifact_bindings[0], + &[], + ) + .expect("oMLX fixture realization"); + + let mut snapshot = super::local_model_snapshot(model_id); + let Some(model_deployment_snapshot::Source::Local(local)) = snapshot.source.as_mut() else { + panic!("local fixture snapshot"); + }; + let engine = local.engine_artifact.as_mut().expect("engine artifact"); + engine.engine_release_id = "fixture-omlx".to_owned(); + engine.engine_kind = EngineKind::Omlx as i32; + engine.engine_version = "0.8.4".to_owned(); + engine.artifact = Some(EngineArtifact { + selectors: Vec::new(), + ..release().artifacts[0].clone() + }); + if let Some(EngineArtifactKind::Nix(nix)) = engine + .artifact + .as_mut() + .and_then(|artifact| artifact.kind.as_mut()) + { + // A deployment retains the locked revision the materialized catalog pins. + nix.flake = dotcore_domain::test_support::nix::locked_flake(); + nix.store_paths = vec![dotcore_proto::dotcore::catalog::v1::NixSystemStorePath { + system: "aarch64-darwin".to_owned(), + store_path: STORE_PATH.to_owned(), + }]; + } + engine.platform = Some(ExecutionPlatform::darwin_arm64().to_oci_platform()); + engine.accelerator = "apple".to_owned(); + engine.minimum_nvidia_driver_major_version = 0; + engine.preparation_policy = ArtifactPreparationPolicy::ImmutableRemote as i32; + engine.launch_identity = STORE_PATH.to_owned(); + local.model_artifact = Some(model.artifacts[0].clone()); + let hardware_support = local.hardware_support.as_mut().expect("hardware support"); + hardware_support.hardware_class_id = "apple".to_owned(); + hardware_support + .selector + .as_mut() + .expect("hardware class selector") + .accelerators = vec!["apple".to_owned()]; + hardware_support.hardware_requirements = + configuration.hardware_support[0].hardware_requirements; + local.resolved_engine_state = Some(selection.state); + local.input_capabilities = Some(selection.input_capabilities); + local.engine_parameter_schema = release().parameter_schema; + local.engine_parameter_schema_id = "fixture-omlx-v1".to_owned(); + local.engine_parameter_values = Some(parameter_values(PROFILE_PARAMETERS)); + local.resolved_options = Vec::new(); + local + .selected_target + .as_mut() + .expect("selected target") + .accelerator_memory_architecture = AcceleratorMemoryArchitecture::Unified as i32; + local.sizing = Some(ResolvedSizing { + accelerator_memory_bytes: Some(ACCELERATOR_ESTIMATE_BYTES), + host_memory_bytes: Some(HOST_ESTIMATE_BYTES), + ..Default::default() + }); + local.desired_launch_plan = None; + refresh_launch_plan(local); + snapshot +} + +/// Recomputes the canonical launch plan after a test edits an oMLX snapshot. +pub(crate) fn refresh_launch_plan(local: &mut ResolvedLocalModelDeploymentSnapshot) { + local.desired_launch_plan = + Some(crate::model::engine::omlx::translate(local).expect("oMLX fixture plan")); +} + +/// Returns oMLX engine parameter values for the given pairs. +pub(crate) fn parameter_values(values: [(&str, u64); N]) -> ParameterValues { + ParameterValues { + values: values + .into_iter() + .map(|(parameter_id, value)| ParameterValue { + parameter_id: parameter_id.to_owned(), + value: Some(parameter_value::Value::UnsignedInteger(value)), + }) + .collect(), + } +} + +/// Returns an oMLX engine release with the shared context parameters, their engine defaults and +/// the prompt cache drawn from host memory, and one native darwin/arm64 Apple artifact. +pub(crate) fn release() -> EngineRelease { + EngineRelease { + engine_release_id: "fixture-omlx".to_owned(), + engine_kind: EngineKind::Omlx as i32, + version: "0.8.4".to_owned(), + parameter_schema: Some(EngineParameterSchema { + schema_id: "fixture-omlx-v1".to_owned(), + parameters: [ + ( + TOTAL_CONTEXT_PARAMETER_ID, + "Total context", + 512, + "tokens", + None, + None, + ), + ( + CONTEXT_PER_REQUEST_PARAMETER_ID, + "Context per request", + 512, + "tokens", + Some(32_768), + None, + ), + ( + PARALLEL_REQUESTS_PARAMETER_ID, + "Parallel requests", + 1, + "requests", + Some(2), + None, + ), + ( + PROMPT_CACHE_MIB_PARAMETER_ID, + "Prompt cache memory", + 0, + "MiB", + None, + Some(MemoryPool::Host as i32), + ), + ] + .into_iter() + .map( + |(parameter_id, display_name, minimum, unit, default_value, memory_pool)| { + ParameterDefinition { + parameter_id: parameter_id.to_owned(), + display_name: display_name.to_owned(), + parameter_type: Some(parameter_definition::ParameterType::UnsignedInteger( + UnsignedIntegerParameterSchema { + minimum, + maximum: None, + unit: unit.to_owned(), + default_value, + memory_pool, + }, + )), + visibility: if memory_pool.is_some() { + ParameterVisibility::Advanced + } else { + ParameterVisibility::Basic + } as i32, + description: parameter_id.to_owned(), + summary: "Summary.".to_owned(), + enabled_by_parameter_id: None, + group_id: None, + } + }, + ) + .collect(), + parameter_groups: Vec::new(), + context_behavior: Some(ContextBehavior { + pool: Some(context_behavior::Pool::RequestShares( + RequestShareContextPool {}, + )), + }), + }), + artifacts: vec![EngineArtifact { + artifact_id: "darwin-arm64".to_owned(), + kind: Some(EngineArtifactKind::Nix(NixArtifact { + flake: "self".to_owned(), + package: Some("engines.omlx.native".to_owned()), + provides: Some(Provides::Executable("omlx-launcher".to_owned())), + store_paths: Vec::new(), + })), + selectors: vec![Selector { + platform: Some(OciPlatform { + operating_system: "darwin".to_owned(), + architecture: "arm64".to_owned(), + variant: None, + }), + accelerators: vec!["apple".to_owned()], + ..Default::default() + }], + }], + ..Default::default() + } +} + +/// Returns a text-only model with a 262,144-token maximum context, one MLX 4-bit snapshot and no +/// options. +pub(crate) fn model() -> Model { + Model { + model_id: "fixture-omlx-model".to_owned(), + maximum_context_tokens: 262_144, + artifacts: vec![ModelArtifact { + artifact_id: "fixture-mlx-4bit".to_owned(), + weight_quantization: "4bit".to_owned(), + source: Some(HuggingFaceArtifactSource { + repository: "dotcore/fixture-mlx-4bit".to_owned(), + revision: "0123456789abcdef0123456789abcdef01234567".to_owned(), + content: Some(hugging_face_artifact_source::Content::Snapshot( + HuggingFaceSnapshotArtifact { + files: SNAPSHOT_FILES + .into_iter() + .map(|path| HuggingFaceSnapshotFile { + path: path.to_owned(), + provenance_digest: + "74d2c57145e6ff11d1d2faa79594477f9bc903a611af1fb20218189fbbb77d82" + .to_owned(), + }) + .collect(), + }, + )), + }), + }], + ..Default::default() + } +} + +/// Files of the fixture's MLX snapshot, as an mlx-community 4-bit conversion publishes them. +const SNAPSHOT_FILES: [&str; 5] = [ + "config.json", + "model.safetensors", + "model.safetensors.index.json", + "tokenizer.json", + "tokenizer_config.json", +]; + +/// Returns a valid text-only oMLX configuration for [`model`] and [`release`]. +pub(crate) fn configuration() -> ModelEngineConfiguration { + ModelEngineConfiguration { + configuration_id: "omlx-apple".to_owned(), + artifact_bindings: vec![ModelArtifactBinding { + binding_id: "fixture-mlx-4bit".to_owned(), + model_artifact_id: "fixture-mlx-4bit".to_owned(), + auxiliary_artifact_ids: Vec::new(), + }], + hardware_support: vec![HardwareSupport { + hardware_class_id: "apple".to_owned(), + hardware_requirements: Some(HardwareRequirements { + minimum_memory_bytes_per_device: 0, + minimum_system_memory_bytes: 16_000_000_000, + }), + }], + engine_configuration: Some(EngineModelConfiguration { + engine_kind: EngineKind::Omlx as i32, + configuration: Some(Configuration::Omlx(OmlxModelConfiguration { + fixed_settings: Some(OmlxFixedModelSettings { + prompt_cache_mib_parameter_id: PROMPT_CACHE_MIB_PARAMETER_ID.to_owned(), + }), + })), + }), + execution_capabilities: Some(ModelExecutionCapabilities { + supported_parallel_shapes: vec![ModelParallelShape::One as i32], + }), + request_kinds: vec![InferenceRequestKind::Chat as i32], + input_capabilities: Some(ModelInputCapabilities { + supported_modalities: vec![ModelInputModality::Text as i32], + image_input_capacity: None, + }), + ..Default::default() + } +} diff --git a/backend/core/tests/backend/catalog_contracts.rs b/backend/core/tests/backend/catalog_contracts.rs index 3a4fe050..c1e3ef66 100644 --- a/backend/core/tests/backend/catalog_contracts.rs +++ b/backend/core/tests/backend/catalog_contracts.rs @@ -329,7 +329,8 @@ fn repository_catalog_memory_parameters_never_shrink_their_declared_estimate() { /// Every repository profile's largest fit on each GPU target of each simulated hardware choice /// (each named GPU alone on the simulated host, and each named machine), idle, fills /// the target's free memory less the headroom: both verdicts read "fits" there, and the -/// free-memory verdict reads "exceeds" 1024 tokens later, unless the engine's range or a derived +/// free-memory verdict reads "exceeds" one step later (1024 tokens, per parallel request when each +/// request holds its own share), unless the engine's range or a derived /// value stops the total first. A profile without a largest fit exceeds at its lowest total /// context, on the hardware's total or on its free memory. Machines run as their rendered /// readings through the site's reconciliation, so no hardware is needed. @@ -423,11 +424,12 @@ fn repository_largest_fits_fill_free_memory_on_every_simulated_choice() { ), "{label}: largest fit of {largest} tokens" ); - match verdict(largest + STEP_TOKENS) { + let step = largest_fit_step(&catalog, &models[0], &entry.profile_id, STEP_TOKENS); + match verdict(largest + step) { (on_free, _, SizingScenarioUnsupportedReason::Unspecified) => assert_eq!( on_free, MemoryFit::Exceeds, - "{label}: {largest} tokens leave room for {STEP_TOKENS} more" + "{label}: {largest} tokens leave room for {step} more" ), (_, _, reason) => { clamped.push(format!("{label}: {largest} tokens, next {reason:?}")) @@ -2685,6 +2687,113 @@ fn vllm_launch_rejects_a_context_per_request_above_the_model_maximum() { launch(4096).expect("context per request within the maximum"); } +/// An oMLX launch on a Mac holds the context per request for each parallel request: resolution +/// derives whichever context value is left out, and the plan's memory ceiling is the whole +/// estimate over oMLX's overshoot. A total context other than their product is refused. +#[test] +fn omlx_launch_holds_the_context_per_request_for_each_parallel_request_on_a_mac() { + let catalog = omlx_catalog(); + let model_id = CatalogModelId("fixture-omlx-model".to_owned()); + let (target, inventory) = macos_native_target_capabilities(); + let launch = |values: &[(&str, u64)]| { + resolve_local_launch( + &catalog, + &model_id, + "omlx-4bit", + &LocalModelDeploymentConfiguration { + model_artifact_binding_id: "fixture-mlx-4bit".to_owned(), + engine_parameter_values: Some(unsigned_values(values)), + ..Default::default() + }, + &target, + &inventory, + None, + ) + .and_then(|resolution| resolution.generate_missing_secrets(&dotcore::RandomSecretGenerator)) + .and_then(|resolution| resolution.into_snapshot()) + }; + let literals = |snapshot: &ResolvedLocalModelDeploymentSnapshot| { + snapshot + .desired_launch_plan + .as_ref() + .expect("desired launch plan") + .arguments + .iter() + .filter_map(|argument| match argument.value.as_ref() { + Some(PortableArgument::Literal(literal)) => Some(literal.clone()), + _ => None, + }) + .collect::>() + }; + + let derived_total = launch(&[ + ("context-per-request", 16_384), + ("parallel-requests", 3), + ("prompt-cache-memory-mib", 2_048), + ]) + .expect("a left-out total context"); + assert_eq!( + derived_total + .sizing + .as_ref() + .map(|sizing| (sizing.accelerator_memory_bytes, sizing.host_memory_bytes)), + Some(( + Some(3_000_000_000 + 1_000 * 49_152), + Some(2_048 * 1_048_576) + )) + ); + // (3,049,152,000 + 2 GiB) / 1.07 = 4.5232 GiB, rounded down. + assert_eq!( + literals(&derived_total), + [ + "--snapshot", + "--served-id", + "fixture-omlx-model", + "--port", + "--context-per-request", + "16384", + "--parallel-requests", + "3", + "--memory-ceiling-gb", + "4.523", + "--prompt-cache-gb", + "2", + ] + ); + + let filled = launch(&[ + ("total-context", 65_536), + ("parallel-requests", 2), + ("prompt-cache-memory-mib", 0), + ]) + .expect("a left-out context per request"); + assert_eq!( + literals(&filled)[4..], + [ + "--context-per-request", + "32768", + "--parallel-requests", + "2", + "--memory-ceiling-gb", + "2.668", + "--prompt-cache-gb", + "0", + ] + ); + + assert_eq!( + launch(&[ + ("total-context", 32_768), + ("context-per-request", 32_768), + ("parallel-requests", 2), + ("prompt-cache-memory-mib", 0), + ]) + .expect_err("a total context below the product") + .to_string(), + "engine parameter values can't launch: context per request of 32768 tokens is above the 16384 tokens one request can use of the total context; lower the context per request or raise the total context" + ); +} + #[test] fn catalog_retains_boolean_engine_parameters_and_their_schema() { let catalog = synthetic_boolean_catalog(synthetic_boolean_model()); @@ -2869,6 +2978,55 @@ fn lowest_total_context(catalog: &Catalog, model: &Model, profile_id: &str) -> ( }; use dotcore_proto::dotcore::catalog::v1::parameter_definition::ParameterType; + let (profile, schema) = profile_engine_schema(catalog, model, profile_id); + let smallest_total = schema + .parameters + .into_iter() + .find(|parameter| parameter.parameter_id == TOTAL_CONTEXT_PARAMETER_ID) + .and_then(|parameter| match parameter.parameter_type { + Some(ParameterType::UnsignedInteger(range)) => Some(range.minimum), + _ => None, + }) + .expect("the engine's total context range"); + let context_per_request = profile + .engine_parameter_defaults + .iter() + .flat_map(|defaults| &defaults.values) + .find(|value| value.parameter_id == CONTEXT_PER_REQUEST_PARAMETER_ID) + .and_then(|value| match value.value { + Some(parameter_value::Value::UnsignedInteger(tokens)) => Some(tokens), + _ => None, + }); + let lowest = context_per_request.map_or(smallest_total, |tokens| tokens.max(smallest_total)); + (lowest, context_per_request) +} + +/// Returns the tokens between two total contexts a profile's largest fit can land on: one step +/// for a shared pool, one step per parallel request when each request holds its own share. +fn largest_fit_step(catalog: &Catalog, model: &Model, profile_id: &str, step: u64) -> u64 { + use dotcore_catalog::context_behavior::{ContextBehavior, ContextValues}; + + let (profile, schema) = profile_engine_schema(catalog, model, profile_id); + let behavior = ContextBehavior::from_schema(&schema).expect("the engine's context behavior"); + if behavior.can_be_overcommitted() { + return step; + } + let defaults = profile + .engine_parameter_defaults + .clone() + .unwrap_or_default(); + step * ContextValues::read(&schema, &defaults).parallel_requests +} + +/// Returns a profile with the parameter schema of its first configuration's engine release. +fn profile_engine_schema<'a>( + catalog: &Catalog, + model: &'a Model, + profile_id: &str, +) -> ( + &'a dotcore_proto::dotcore::catalog::v1::ModelProfile, + dotcore_proto::dotcore::catalog::v1::EngineParameterSchema, +) { let profile = model .profiles .iter() @@ -2885,33 +3043,13 @@ fn lowest_total_context(catalog: &Catalog, model: &Model, profile_id: &str) -> ( .and_then(|configuration| configuration.engine_artifacts.first()) .map(|artifact| artifact.engine_release_id.clone()) .expect("the profile's engine release"); - let smallest_total = catalog + let schema = catalog .list_engine_releases() .into_iter() .find(|release| release.engine_release_id == release_id) .and_then(|release| release.parameter_schema) - .and_then(|schema| { - schema - .parameters - .into_iter() - .find(|parameter| parameter.parameter_id == TOTAL_CONTEXT_PARAMETER_ID) - }) - .and_then(|parameter| match parameter.parameter_type { - Some(ParameterType::UnsignedInteger(range)) => Some(range.minimum), - _ => None, - }) - .expect("the engine's total context range"); - let context_per_request = profile - .engine_parameter_defaults - .iter() - .flat_map(|defaults| &defaults.values) - .find(|value| value.parameter_id == CONTEXT_PER_REQUEST_PARAMETER_ID) - .and_then(|value| match value.value { - Some(parameter_value::Value::UnsignedInteger(tokens)) => Some(tokens), - _ => None, - }); - let lowest = context_per_request.map_or(smallest_total, |tokens| tokens.max(smallest_total)); - (lowest, context_per_request) + .expect("the engine release's parameter schema"); + (profile, schema) } /// Returns the targets of `platform` a profile may resolve on: the fixture target, then each GPU @@ -3892,3 +4030,89 @@ fn catalog_builder() -> CatalogBuilder { vendor_hardware_class("apple"), ) } + +/// Loads a synthetic oMLX release and a profile-shaped model sized from its total context and +/// prompt cache, with the shared hardware classes. +fn omlx_catalog() -> Catalog { + const ENGINE: &str = r#" +engineReleaseId: "fixture-omlx" +engineKind: "ENGINE_KIND_OMLX" +version: "0.8.4" +parameterSchema: + schemaId: "fixture-omlx-v1" + contextBehavior: { requestShares: {} } + parameters: + - { parameterId: "total-context", summary: "Summary.", displayName: "Total context", visibility: "PARAMETER_VISIBILITY_BASIC", description: "total-context", unsignedInteger: { minimum: "512", unit: "tokens" } } + - { parameterId: "context-per-request", summary: "Summary.", displayName: "Context per request", visibility: "PARAMETER_VISIBILITY_BASIC", description: "context-per-request", unsignedInteger: { minimum: "512", unit: "tokens", defaultValue: "32768" } } + - { parameterId: "parallel-requests", summary: "Summary.", displayName: "Parallel requests", visibility: "PARAMETER_VISIBILITY_BASIC", description: "parallel-requests", unsignedInteger: { minimum: "1", unit: "requests", defaultValue: "2" } } + - { parameterId: "prompt-cache-memory-mib", summary: "Summary.", displayName: "Prompt cache memory", visibility: "PARAMETER_VISIBILITY_ADVANCED", description: "prompt-cache-memory-mib", unsignedInteger: { minimum: "0", unit: "MiB", memoryPool: "MEMORY_POOL_HOST" } } +artifacts: + - artifactId: "metal" + nix: { flake: "self", package: "engines.omlx.native", executable: "omlx-launcher" } + selectors: + - platform: { operatingSystem: "darwin", architecture: "arm64" } + accelerators: ["apple"] +"#; + const MODEL: &str = r#" +modelId: "fixture-omlx-model" +displayName: "Fixture oMLX model" +version: "1" +maximumContextTokens: 262144 +artifacts: + - artifactId: "fixture-mlx-4bit" + weightQuantization: "4bit" + source: + repository: "dotcore/fixture-mlx-4bit" + revision: "0123456789abcdef0123456789abcdef01234567" + snapshot: + files: + - { path: "config.json", provenanceDigest: "74d2c57145e6ff11d1d2faa79594477f9bc903a611af1fb20218189fbbb77d82" } + - { path: "model.safetensors", provenanceDigest: "74d2c57145e6ff11d1d2faa79594477f9bc903a611af1fb20218189fbbb77d82" } + - { path: "tokenizer.json", provenanceDigest: "74d2c57145e6ff11d1d2faa79594477f9bc903a611af1fb20218189fbbb77d82" } +configurations: + - configurationId: "omlx-apple" + engineArtifacts: [{ engineReleaseId: "fixture-omlx", engineArtifactId: "metal" }] + artifactBindings: [{ bindingId: "fixture-mlx-4bit", modelArtifactId: "fixture-mlx-4bit" }] + sizing: + parameters: { baseBytes: 3000000000, bytesPerKvToken: 1000 } + estimates: + acceleratorMemory: + unit: bytes + equation: "${baseBytes} + ${bytesPerKvToken} * ${total-context}" + hostMemory: + unit: bytes + equation: "${prompt-cache-memory-mib} * MiB" + hardwareSupport: + - hardwareClassId: "apple" + hardwareRequirements: { minimumSystemMemoryBytes: "16000000000" } + bindingSizing: [{ bindingId: "fixture-mlx-4bit" }] + engineConfiguration: + engineKind: "ENGINE_KIND_OMLX" + omlx: { fixedSettings: { promptCacheMibParameterId: "prompt-cache-memory-mib" } } + executionCapabilities: { supportedParallelShapes: ["MODEL_PARALLEL_SHAPE_ONE"] } + requestKinds: ["INFERENCE_REQUEST_KIND_CHAT"] + inputCapabilities: { supportedModalities: ["MODEL_INPUT_MODALITY_TEXT"] } +profiles: + - profileId: "omlx-4bit" + displayName: "4-bit oMLX" + description: "Runs the fixture through oMLX." + configurationIds: ["omlx-apple"] + defaultModelArtifactBindingId: "fixture-mlx-4bit" + engineParameterDefaults: + values: [{ parameterId: "prompt-cache-memory-mib", unsignedInteger: "2048" }] +"#; + + let root = temporary_catalog_root(); + create_empty_catalog_source(&root); + std::fs::write(root.join("engines/omlx.yaml"), ENGINE).expect("oMLX engine release"); + std::fs::write(root.join("models/omlx.yaml"), MODEL).expect("oMLX model"); + dotcore_catalog::test_support::write_hardware_classes(&root); + let catalog = Catalog::load_with_policy( + &root, + dotcore_catalog::OciArtifactPolicy::Development, + dotcore::model::engine::declaration_validator(), + ) + .expect("oMLX catalog"); + std::fs::remove_dir_all(&root).expect("catalog root cleanup"); + catalog +} diff --git a/backend/core/tests/gated/apple_hardware_integration.rs b/backend/core/tests/gated/apple_hardware_integration.rs index 90c73edc..6dd737bb 100644 --- a/backend/core/tests/gated/apple_hardware_integration.rs +++ b/backend/core/tests/gated/apple_hardware_integration.rs @@ -1,12 +1,13 @@ //! Explicitly gated Apple Silicon tests for macOS hosts: Apple GPU observation, and llama.cpp -//! on Metal served end to end by the native runtime. +//! and oMLX on the Apple GPU served end to end by the native runtime. //! //! The observation test collects real node snapshots through Metal and checks the host's one //! Apple GPU. The end-to-end test deploys the smallest Gemma on a site with an persistent native //! target in a separate backend process, chats through its route, and proves the engine survives //! a backend restart. The decision test deploys clef-flash and sends decision requests through //! the router. The largest-fit test loads a model at the largest context the Mac's unified memory -//! fits. All are ignored without the explicit hardware gate. +//! fits. The oMLX test deploys the Qwen3.5 9B oMLX profile and checks a streamed chat completion. +//! All are ignored without the explicit hardware gate. #![cfg(target_os = "macos")] @@ -25,7 +26,7 @@ use dotcore_node_hardware::{ hardware::{SystemHardwareSnapshotCollector, SystemNvidiaAcceleratorAdapter}, }; use dotcore_proto::dotcore::{ - catalog::v1::parameter_value, + catalog::v1::{ParameterValue, ParameterValues, parameter_value}, deployment::v1::accelerator_memory_observation, model::v1::{ CreateLocalModelDeploymentRequest, CreateModelDeploymentRequest, DirectRouteExposure, @@ -81,6 +82,14 @@ const COMPLETION_TIMEOUT: Duration = Duration::from_secs(120); const POLL_INTERVAL: Duration = Duration::from_millis(500); const PROGRESS_INTERVAL: Duration = Duration::from_secs(15); +const OMLX_MODEL_ID: &str = "qwen3-5-9b"; +const OMLX_PROFILE_ID: &str = "omlx-4bit"; +const OMLX_ROUTE_NAME: &str = "qwen3-5-9b-omlx"; +const OMLX_BINDING_ID: &str = "mlx-4bit"; +const OMLX_PARALLEL_REQUESTS: u64 = 2; +const OMLX_CONTEXT_PER_REQUEST: u64 = 4_096; +const OMLX_STREAM_MAX_TOKENS: u64 = 64; + /// Lowest plausible footprint of the engine holding the Q4 weights in the shared pool. const MINIMUM_ENGINE_FOOTPRINT_BYTES: u64 = 1024 * 1024 * 1024; @@ -401,6 +410,62 @@ async fn hw_apple_clef_flash_serves_decisions_and_rejects_oversized_requests() { backend.shutdown(); } +/// Deploys the Qwen3.5 9B oMLX profile through the native launcher at a small size, waits for it +/// to be ready and checks one streamed chat completion through its route. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "hardware: just backend::test-apple"] +async fn hw_apple_omlx_serves_a_streamed_chat_completion() { + // Drop order matters: the backend stops first, then leftover engines, then the site files. + let site = AppleSite::initialize().await; + let _leftovers = NativeProcessGuard { + state_root: site.native_state_root(), + }; + let mut backend = ExternalBackendProcess::start( + site.root.clone(), + ProcessTestControls { + native_host: true, + shared_artifact_cache: true, + ..Default::default() + }, + ); + + let mut models = model_client(&backend).await; + let deployment_id = create_deployment( + &mut models, + &site, + OMLX_MODEL_ID, + OMLX_PROFILE_ID, + OMLX_ROUTE_NAME, + omlx_configuration(), + ) + .await; + wait_for_status( + &mut models, + &deployment_id, + ModelDeploymentStatus::Ready, + DEPLOYMENT_TIMEOUT, + ) + .await; + NativeWorkload::find(&site.native_state_root()).assert_running(); + assert_route_stream_chat(inference_address(&backend), OMLX_ROUTE_NAME).await; + + let workload = NativeWorkload::find(&site.native_state_root()); + models + .remove_model_deployment(RemoveModelDeploymentRequest { + model_deployment_id: deployment_id.clone(), + }) + .await + .expect("remove the deployment"); + wait_for_absence(&mut models, &deployment_id).await; + workload.wait_for_exit().await; + assert_eq!( + workload_directories(&site.native_state_root()), + Vec::::new(), + "teardown must remove every native workload directory" + ); + backend.shutdown(); +} + /// Temporary site with one persistent native Apple inference target, initialized the way site /// initialization does it on this host. struct AppleSite { @@ -651,6 +716,31 @@ fn model_configuration() -> LocalModelDeploymentConfiguration { configuration } +/// oMLX deployment configuration for a small load: its total context is always the parallel +/// requests times the context per request, and the prompt cache is off. +fn omlx_configuration() -> LocalModelDeploymentConfiguration { + let values = [ + ( + "total-context", + OMLX_PARALLEL_REQUESTS * OMLX_CONTEXT_PER_REQUEST, + ), + ("context-per-request", OMLX_CONTEXT_PER_REQUEST), + ("parallel-requests", OMLX_PARALLEL_REQUESTS), + ("prompt-cache-memory-mib", 0), + ]; + let mut configuration = support::local_model_configuration(OMLX_BINDING_ID, 0); + configuration.engine_parameter_values = Some(ParameterValues { + values: values + .into_iter() + .map(|(parameter_id, value)| ParameterValue { + parameter_id: parameter_id.to_owned(), + value: Some(parameter_value::Value::UnsignedInteger(value)), + }) + .collect(), + }); + configuration +} + async fn deployment( models: &mut ModelDeploymentServiceClient, deployment_id: &str, @@ -890,6 +980,90 @@ async fn assert_route_chat(inference_address: SocketAddr) { ); } +/// Sends one streamed Chat Completions request through the route and checks the frames: generated +/// text, a stop or length finish, the usage frame and the terminating marker. +async fn assert_route_stream_chat(inference_address: SocketAddr, route_name: &str) { + let started = Instant::now(); + let body = serde_json::to_vec(&serde_json::json!({ + "model": route_name, + "messages": [{"role": "user", "content": "Reply with exactly READY."}], + "max_completion_tokens": OMLX_STREAM_MAX_TOKENS, + "temperature": 0, + "stream": true, + "stream_options": {"include_usage": true}, + })) + .expect("stream payload"); + let mut request = format!( + "POST /v1/chat/completions HTTP/1.1\r\nHost: test\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ) + .into_bytes(); + request.extend_from_slice(&body); + let response = tokio::time::timeout( + COMPLETION_TIMEOUT, + route_request(inference_address, &request), + ) + .await + .expect("stream completion deadline"); + assert!( + response.starts_with(b"HTTP/1.1 200"), + "stream failed: {}", + String::from_utf8_lossy(&response) + ); + let text = String::from_utf8_lossy(&response); + let data: Vec<&str> = text + .lines() + .filter_map(|line| line.trim_end().strip_prefix("data: ")) + .collect(); + assert_eq!( + data.last().copied(), + Some("[DONE]"), + "the stream must end with the done marker: {text}" + ); + let frames: Vec = data[..data.len() - 1] + .iter() + .map(|frame| serde_json::from_str(frame).expect("stream JSON frame")) + .collect(); + + // A reasoning model may spend a bounded completion on reasoning text only. + let generated: String = frames + .iter() + .flat_map(|frame| { + ["content", "reasoning_content", "reasoning"] + .into_iter() + .filter_map(|field| frame.pointer(&format!("/choices/0/delta/{field}"))) + .filter_map(Value::as_str) + }) + .collect(); + assert!( + !generated.trim().is_empty(), + "stream has no generated text: {text}" + ); + let finish_reasons: Vec<&str> = frames + .iter() + .filter_map(|frame| frame.pointer("/choices/0/finish_reason")) + .filter_map(Value::as_str) + .collect(); + assert!( + matches!(finish_reasons.as_slice(), ["stop"] | ["length"]), + "stream must finish exactly once with stop or length: {finish_reasons:?}" + ); + let completion_tokens = frames + .iter() + .find_map(|frame| frame.pointer("/usage/completion_tokens")) + .and_then(Value::as_u64) + .unwrap_or_else(|| panic!("stream has no usage frame: {text}")); + assert!( + (1..=OMLX_STREAM_MAX_TOKENS).contains(&completion_tokens), + "completion tokens {completion_tokens} outside 1..={OMLX_STREAM_MAX_TOKENS}" + ); + eprintln!( + "[apple-omlx] streamed chat answered {generated:?} ({completion_tokens} tokens, {}) in {:?}", + finish_reasons[0], + started.elapsed() + ); +} + /// Sends one raw HTTP request to the router and reads the whole response. async fn route_request(address: SocketAddr, request: &[u8]) -> Vec { let mut stream = TcpStream::connect(address).await.expect("route connection"); diff --git a/backend/core/tests/gated/nvidia_docker_integration.rs b/backend/core/tests/gated/nvidia_docker_integration.rs index c19fc47b..7fabfaaf 100644 --- a/backend/core/tests/gated/nvidia_docker_integration.rs +++ b/backend/core/tests/gated/nvidia_docker_integration.rs @@ -753,9 +753,7 @@ fn llama_cpp_settings( .and_then(|state| state.state.as_ref()) .and_then(|state| match state { ResolvedEngineState::LlamaCpp(state) => state.fixed_settings.clone(), - ResolvedEngineState::Vllm(_) - | ResolvedEngineState::Ninfer(_) - | ResolvedEngineState::Strata(_) => None, + _ => None, }) .ok_or_else(|| anyhow!("Catalog snapshot has no llama.cpp fixed settings")) } diff --git a/backend/core/tests/transport/openai_compatibility.rs b/backend/core/tests/transport/openai_compatibility.rs index de62f252..a42d8b3e 100644 --- a/backend/core/tests/transport/openai_compatibility.rs +++ b/backend/core/tests/transport/openai_compatibility.rs @@ -1464,6 +1464,15 @@ async fn engine_stream_failures_are_terminal_attributable_and_never_retried() { "no event is emitted per streamed token" ); + // An engine error frame whose message echoes the prompt is logged without its message. + engine.script( + 200, + "text/event-stream", + b"data: {\"error\":{\"message\":\"prompt-sentinel is too long\",\"type\":\"BadRequestError\",\"param\":null,\"code\":400}}\n\ndata: [DONE]\n\n", + ); + let response = engine.request("/v1/chat/completions", request).await; + assert!(response.status >= 400, "{}", response.status); + // A complete Responses result with a second choice is refused and attributed once. engine.script( 200, diff --git a/backend/proto/build.rs b/backend/proto/build.rs index 01c7956f..d7d1b486 100644 --- a/backend/proto/build.rs +++ b/backend/proto/build.rs @@ -33,6 +33,7 @@ const PROTO_FILES: &[&str] = &[ "dotcore/catalog/v1/service.proto", "dotcore/engine/llama_cpp/v1/model.proto", "dotcore/engine/ninfer/v1/model.proto", + "dotcore/engine/omlx/v1/model.proto", "dotcore/engine/strata/v1/model.proto", "dotcore/engine/vllm/v1/model.proto", "dotcore/engine/v1/engine.proto", @@ -121,6 +122,7 @@ fn main() -> Result<(), Box> { ".dotcore.diagnostic.v1", ".dotcore.engine.llama_cpp.v1", ".dotcore.engine.ninfer.v1", + ".dotcore.engine.omlx.v1", ".dotcore.engine.strata.v1", ".dotcore.engine.vllm.v1", ".dotcore.engine.v1", diff --git a/backend/proto/src/lib.rs b/backend/proto/src/lib.rs index 1b907c0b..440b0601 100644 --- a/backend/proto/src/lib.rs +++ b/backend/proto/src/lib.rs @@ -86,6 +86,13 @@ pub mod dotcore { } } + pub mod omlx { + pub mod v1 { + tonic::include_proto!("dotcore.engine.omlx.v1"); + include!(concat!(env!("OUT_DIR"), "/dotcore.engine.omlx.v1.serde.rs")); + } + } + pub mod strata { pub mod v1 { tonic::include_proto!("dotcore.engine.strata.v1"); diff --git a/backend/proto/tests/engine_contract.rs b/backend/proto/tests/engine_contract.rs index e8afbb36..13680d5b 100644 --- a/backend/proto/tests/engine_contract.rs +++ b/backend/proto/tests/engine_contract.rs @@ -15,6 +15,7 @@ fn descriptors_keep_engine_payloads_out_of_catalog_and_deployment_contracts() { let llama_cpp = descriptor_file(&descriptor, "dotcore/engine/llama_cpp/v1/model.proto"); let vllm = descriptor_file(&descriptor, "dotcore/engine/vllm/v1/model.proto"); let ninfer = descriptor_file(&descriptor, "dotcore/engine/ninfer/v1/model.proto"); + let omlx = descriptor_file(&descriptor, "dotcore/engine/omlx/v1/model.proto"); let strata = descriptor_file(&descriptor, "dotcore/engine/strata/v1/model.proto"); let catalog = descriptor_file(&descriptor, "dotcore/catalog/v1/model.proto"); let deployment = descriptor_file(&descriptor, "dotcore/model/v1/deployment.proto"); @@ -40,6 +41,7 @@ fn descriptors_keep_engine_payloads_out_of_catalog_and_deployment_contracts() { 5, ".dotcore.engine.strata.v1.StrataModelConfiguration", ), + ("omlx", 6, ".dotcore.engine.omlx.v1.OmlxModelConfiguration"), ] ); assert_eq!( @@ -63,6 +65,7 @@ fn descriptors_keep_engine_payloads_out_of_catalog_and_deployment_contracts() { 6, ".dotcore.engine.strata.v1.StrataResolvedModelState", ), + ("omlx", 7, ".dotcore.engine.omlx.v1.OmlxResolvedModelState"), ] ); assert_eq!( @@ -151,6 +154,18 @@ fn descriptors_keep_engine_payloads_out_of_catalog_and_deployment_contracts() { field_numbers(ninfer, "NinferMtpOptionRealization"), [("optimized_proposal_head", 3)] ); + assert_eq!( + field_numbers(omlx, "OmlxModelConfiguration"), + [("fixed_settings", 1)] + ); + assert_eq!( + field_numbers(omlx, "OmlxResolvedModelState"), + [("fixed_settings", 1)] + ); + assert_eq!( + field_layout(omlx, "OmlxFixedModelSettings"), + [("prompt_cache_mib_parameter_id", 1, "TYPE_STRING")] + ); assert_eq!( field_numbers(strata, "StrataModelConfiguration"), [("fixed_settings", 1), ("option_realizations", 2)] @@ -311,6 +326,7 @@ fn descriptors_keep_engine_payloads_out_of_catalog_and_deployment_contracts() { && !name.contains("Vllm") && !name.contains("Ninfer") && !name.contains("Strata") + && !name.contains("Omlx") }), "Catalog messages must not define engine-owned payloads" ); diff --git a/catalog/engines/omlx.yaml b/catalog/engines/omlx.yaml new file mode 100644 index 00000000..3f7fef8b --- /dev/null +++ b/catalog/engines/omlx.yaml @@ -0,0 +1,71 @@ +# Official oMLX macOS 26-27 release packaged with its package launcher in engines/omlx and exposed by +# the repository flake as `engines.omlx.native`. The packaged master catalog rewrites `self` to the +# locked Dotcore revision with precomputed store paths, and fails unless the version equals the +# engine package version (checked by `checks.dotcore-catalog`). Bounds come from oMLX 0.8.4 and the +# launcher in engines/omlx. +engineReleaseId: "omlx-0-8-4" +engineKind: "ENGINE_KIND_OMLX" +version: "0.8.4" +parameterSchema: + schemaId: "omlx-v1" + # How oMLX uses the total context, at 0.8.4. It takes no total: the launcher passes a context per + # request, which oMLX enforces on each request, and a cap on requests generated at once, and each + # request keeps its own cache, so the total is always their product. + contextBehavior: + requestShares: {} + parameters: + # Shared parameters: the engine adapter in backend/core/src/model/engine/ maps them to flags. + - parameterId: "total-context" + displayName: "Total context" + visibility: "PARAMETER_VISIBILITY_BASIC" + description: "Memory the model holds for all requests at once. Each parallel request may use a full context per request, so it is always the parallel requests times the context per request; change those two instead. oMLX manages its own memory: it grows into this as requests arrive and may use somewhat more than the estimate, so leave the machine room." + summary: "Context memory for all requests: always context per request times parallel requests." + # At least Dotcore's context floor. No oMLX argument: the context behavior keeps it the + # parallel requests times the context per request, and the adapter derives oMLX's memory + # ceiling from the sizing it sets. + unsignedInteger: + minimum: "512" + unit: "tokens" + - parameterId: "context-per-request" + displayName: "Context per request" + visibility: "PARAMETER_VISIBILITY_BASIC" + description: "Largest context one request may use; longer prompts are refused. It reserves nothing up front: requests take memory as they grow." + summary: "Longest conversation one request can hold." + # At least Dotcore's context floor. The launcher sets it as the model's maximum context + # window, which oMLX enforces on every request and sets no maximum for. + unsignedInteger: + minimum: "512" + unit: "tokens" + defaultValue: "32768" + - parameterId: "parallel-requests" + displayName: "Parallel requests" + visibility: "PARAMETER_VISIBILITY_BASIC" + description: "Requests generated at once; more wait in a queue. The total context grows with them, so each added request uses more memory; raise it when several people or agents use the model together." + summary: "How many requests run at the same time; each adds its own context memory." + # oMLX requires at least one concurrent request and sets no maximum. + unsignedInteger: + minimum: "1" + unit: "requests" + defaultValue: "4" + - parameterId: "prompt-cache-memory-mib" + displayName: "Prompt cache memory" + visibility: "PARAMETER_VISIBILITY_ADVANCED" + description: "Memory used to reuse repeated prompts, such as agent system prompts, without processing them again. Raise it if the same long prompts come back often; it competes with the model for the Mac's memory, and 0 turns it off." + summary: "Memory to reuse repeated prompts; 0 turns it off." + # The launcher turns the cache off at 0 and otherwise sets oMLX's in-memory hot cache to + # this size, which oMLX takes without a maximum. + unsignedInteger: + minimum: "0" + unit: "MiB" + memoryPool: "MEMORY_POOL_HOST" +artifacts: + - artifactId: "metal" + nix: + flake: "self" + package: "engines.omlx.native" + executable: "omlx-launcher" + # Each selector is one set of target facts this build runs on. The launcher refuses macOS + # older than 26, which selectors can't express. + selectors: + - platform: { operatingSystem: "darwin", architecture: "arm64" } + accelerators: ["apple"] diff --git a/catalog/models/qwen3-5-9b.yaml b/catalog/models/qwen3-5-9b.yaml index f9669af2..93d4b5b7 100644 --- a/catalog/models/qwen3-5-9b.yaml +++ b/catalog/models/qwen3-5-9b.yaml @@ -1,5 +1,6 @@ -# Immutable provenance for Qwen3.5 9B's public GGUF tiers. -# Qualification tier: q4-xl on Linux NVIDIA; every tier carries a measured sizing equation. +# Immutable provenance for Qwen3.5 9B's public GGUF tiers and its MLX 4-bit build for oMLX. +# Qualification tiers: q4-xl on Linux NVIDIA, and mlx-4bit on oMLX on an Apple Silicon Mac; every +# tier carries a measured sizing equation. modelId: "qwen3-5-9b" displayName: "Qwen3.5 9B" version: "3.5-9b" @@ -37,6 +38,37 @@ artifacts: file: path: "Qwen3.5-9B-UD-Q5_K_XL.gguf" provenanceDigest: "96cf42ddb97f9572410a72b9ed6f2299b1e887ee08da4c2a6c01e897cfa9f673" + # MLX community's 4-bit affine conversion (group size 64) for oMLX; its weight files also hold + # the vision tower, which the oMLX configuration doesn't serve. + - artifactId: "mlx-4bit" + weightQuantization: "MLX_4BIT" + source: + repository: "mlx-community/Qwen3.5-9B-4bit" + revision: "8b2b98c00a6b4d291155e4890773ca8f769aee53" + snapshot: + files: + - path: "chat_template.jinja" + provenanceDigest: "a4aee8afcf2e0711942cf848899be66016f8d14a889ff9ede07bca099c28f715" + - path: "config.json" + provenanceDigest: "a96942cb6a8a1d3f1d17514d81a1925d04362a6a3233b389d13012211baaa9f8" + - path: "model-00001-of-00002.safetensors" + provenanceDigest: "a68b87558c6ef43f74c2bd63ce7e9092ceddc3101f3def0030774bae5f42aadd" + - path: "model-00002-of-00002.safetensors" + provenanceDigest: "b0a770bf8469c7f3f18756a0e0283f1c1174344a83e059a4e483f6af4907352d" + - path: "model.safetensors.index.json" + provenanceDigest: "dd023913fb87cfdae27fb11dcf695117c925833796ccac3c64117d6652d8ff1e" + - path: "preprocessor_config.json" + provenanceDigest: "27225450ac9c6529872ee1924fcb0962ff5634834f817040f444118116f4e516" + - path: "processor_config.json" + provenanceDigest: "14932921ca485d458a04dafd8069fbb0a4505622a48208d19ed247115801385b" + - path: "tokenizer.json" + provenanceDigest: "87a7830d63fcf43bf241c3c5242e96e62dd3fdc29224ca26fed8ea333db72de4" + - path: "tokenizer_config.json" + provenanceDigest: "e98f1901ac6f0adff67b1d540bfa0c36ac1a0cf59eb72ed78146ef89aafa1182" + - path: "video_preprocessor_config.json" + provenanceDigest: "7768af27c1fafa9cc9011c1dc20067e03f8915e03b63504550e11d5066986d13" + - path: "vocab.json" + provenanceDigest: "ce99b4cb2983d118806ce0a8b777a35b093e2000a503ebde25853284c9dfa003" auxiliaryArtifacts: - auxiliaryArtifactId: "vision-projector" source: @@ -203,6 +235,83 @@ configurations: values: - parameterId: "enabled" boolean: false + # oMLX on Apple Silicon Macs with macOS 26 or later, text only. oMLX allocates memory as requests + # arrive, under a whole-process ceiling the adapter derives from this estimate. + - configurationId: "omlx-apple" + engineArtifacts: + - engineReleaseId: "omlx-0-8-4" + engineArtifactId: "metal" + artifactBindings: + - bindingId: "mlx-4bit" + modelArtifactId: "mlx-4bit" + sizing: + bindingParameters: ["baseBytes", "marginBytes"] + parameters: + # MLX KV cache in bfloat16, from config.json: 8 full-attention layers x 2 (K and V) x 4 KV + # heads x 256 dimensions x 2 bytes. + kvBytesPerToken: 32768 + # Gated DeltaNet recurrent state per request, from config.json: 24 linear-attention layers x + # (conv 3 x 8192 + state 32 heads x 128 x 128) values, counted at 4 bytes. + slotStateBytes: 52690944 + # Attention scores of one full prefill chunk at the default 32k context per request: oMLX's + # 2048-token chunk x 16 attention heads x 4 bytes x 32768 tokens. oMLX prefills one chunk at + # a time and shrinks chunks of longer contexts to fit its ceiling rather than refusing them. + prefillBytes: 4294967296 + # oMLX refuses prompts above 95% of its ceiling less the prompt cache, and the adapter sets + # the ceiling to the estimate / 1.07, so the estimate holds 1.07 / 0.95 of the engine's + # memory: these add 0.1264 of the per-token and per-request terms, and marginBytes holds + # that share of the fixed terms. + guardBytesPerToken: 4140 + guardBytesPerRequest: 6655699 + estimates: + # What oMLX holds at full load: weights and runtime, the KV cache of every request, their + # recurrent state and one prefill chunk's attention scores. + acceleratorMemory: + unit: bytes + equation: >- + ${baseBytes} + + ${kvBytesPerToken} * ${total-context} + + ${parallel-requests} * ${slotStateBytes} + + ${prefillBytes} + # The memory guard's headroom, and 0.07 of the prompt cache for the ceiling's overshoot. + allowance: >- + ${marginBytes} + + ${guardBytesPerToken} * ${total-context} + + ${parallel-requests} * ${guardBytesPerRequest} + + ${prompt-cache-memory-mib} * 72 * KiB + # The in-memory prompt cache, which oMLX keeps out of its prompt admission limit. + hostMemory: + unit: bytes + equation: >- + ${prompt-cache-memory-mib} * MiB + hardwareSupport: + - hardwareClassId: "apple" + # The default 4 x 32k context estimates about 20.5 GB. + hardwareRequirements: + minimumSystemMemoryBytes: "24000000000" + # Measured on an M3 Max (36 GiB, macOS 26) at 2 parallel requests x 32k context with a 2 GiB + # prompt cache: 6.78 GB at start, at most 14.26 GB in two 6-minute runs of near-full prompts, + # no refusals. oMLX throttled prefill chunks against the host's free memory, so the scores + # term is derived, not measured unthrottled; 4 parallel requests are extrapolated by the + # KV and state terms. + bindingSizing: + - bindingId: "mlx-4bit" + parameters: + # Measured footprint at start: 5.95 GB of weight files plus the MLX runtime. + baseBytes: 6778246688 + # 512 MiB for allocator slack beyond the equation, plus the guard share of the base, + # the prefill scores and that slack. + marginBytes: 2003407952 + engineConfiguration: + engineKind: "ENGINE_KIND_OMLX" + omlx: + fixedSettings: + promptCacheMibParameterId: "prompt-cache-memory-mib" + executionCapabilities: + supportedParallelShapes: ["MODEL_PARALLEL_SHAPE_ONE"] + requestKinds: ["INFERENCE_REQUEST_KIND_CHAT"] + inputCapabilities: + supportedModalities: ["MODEL_INPUT_MODALITY_TEXT"] profiles: - profileId: "q3-xl" displayName: "Unsloth Q3_K_XL" @@ -246,6 +355,18 @@ profiles: values: - parameterId: "enabled" boolean: false + - profileId: "omlx-4bit" + displayName: "MLX 4-bit on oMLX" + description: "Runs the MLX 4-bit weights through oMLX on a Mac with macOS 26 or later, faster than llama.cpp. Text only." + configurationIds: ["omlx-apple"] + defaultModelArtifactBindingId: "mlx-4bit" + engineParameterDefaults: + values: + - parameterId: "prompt-cache-memory-mib" + unsignedInteger: "2048" + # oMLX's total context is always the parallel requests times the context per request. + engineParameterVisibilityOverrides: + - { parameterId: "total-context", visibility: "PARAMETER_VISIBILITY_HIDDEN" } intelligence: overall: 11 license: diff --git a/catalog/models/qwen3-6-35b-a3b.yaml b/catalog/models/qwen3-6-35b-a3b.yaml index 4bd6bd7c..306fcd57 100644 --- a/catalog/models/qwen3-6-35b-a3b.yaml +++ b/catalog/models/qwen3-6-35b-a3b.yaml @@ -1,5 +1,6 @@ -# Qwen3.6 35B A3B's public GGUF and NVFP4 tiers. The GGUFs come from Unsloth's MTP repository, which -# embeds the MTP head in each file; the vision projector comes from the original repository. +# Qwen3.6 35B A3B's public GGUF, NVFP4 and MLX 4-bit tiers. The GGUFs come from Unsloth's MTP +# repository, which embeds the MTP head in each file; the vision projector comes from the original +# repository. modelId: "qwen3-6-35b-a3b" displayName: "Qwen3.6 35B A3B" version: "3.6-35b-a3b" @@ -100,6 +101,45 @@ artifacts: provenanceDigest: "7768af27c1fafa9cc9011c1dc20067e03f8915e03b63504550e11d5066986d13" - path: "vocab.json" provenanceDigest: "ce99b4cb2983d118806ce0a8b777a35b093e2000a503ebde25853284c9dfa003" + # MLX community's 4-bit affine conversion (group size 64, router gates at 8 bits) for oMLX, + # without MTP weights; its weight files also hold the vision tower, which oMLX doesn't serve. + - artifactId: "mlx-4bit" + weightQuantization: "MLX_4BIT" + source: + repository: "mlx-community/Qwen3.6-35B-A3B-4bit" + revision: "38740b847e4cb78f352aba30aa41c76e08e6eb46" + snapshot: + files: + - path: "chat_template.jinja" + provenanceDigest: "e84f32a23fdda27689f868aa4a1a5621f41133e51a48d7f3efcbea2839574259" + - path: "config.json" + provenanceDigest: "a822a9e48b0aafbe3144ec37d4fb067e178ed96615ce6e4420b3149893cc5767" + - path: "configuration.json" + provenanceDigest: "c1b09db419119513247e9b8b912c4b9897106c9b20c6cada7e107d993c5435eb" + - path: "generation_config.json" + provenanceDigest: "e70c136c1b78ddc1fb0905bac8e733a4dc448d4f852a5dd75143fffc70be550e" + - path: "model-00001-of-00004.safetensors" + provenanceDigest: "09f3e6ecb0b7af6e6a38bc8169a134c821b0924c2679b2bb8f4426ad38d032b8" + - path: "model-00002-of-00004.safetensors" + provenanceDigest: "31dcdb1c49eebdb1505bd14e3cb33f9cf900bd2546b638f2464694ae763a033f" + - path: "model-00003-of-00004.safetensors" + provenanceDigest: "3e66de06a1f03dade16a612a368cfce4a4c9caa4efd7d28185454384082cec03" + - path: "model-00004-of-00004.safetensors" + provenanceDigest: "a5d0cf03519c26f8b506df6b0ba60526e5c08c8cea22d0c21ce92950e58a5422" + - path: "model.safetensors.index.json" + provenanceDigest: "0b28df60e33753a14e816d3b31577ae2c93884c58430a4a6de6ae9ea483842ea" + - path: "preprocessor_config.json" + provenanceDigest: "27225450ac9c6529872ee1924fcb0962ff5634834f817040f444118116f4e516" + - path: "processor_config.json" + provenanceDigest: "51c5f33646392e0bf1ed3e96be02504da47406c21c6cb86925d8908d1a6c4da7" + - path: "tokenizer.json" + provenanceDigest: "87a7830d63fcf43bf241c3c5242e96e62dd3fdc29224ca26fed8ea333db72de4" + - path: "tokenizer_config.json" + provenanceDigest: "e98f1901ac6f0adff67b1d540bfa0c36ac1a0cf59eb72ed78146ef89aafa1182" + - path: "video_preprocessor_config.json" + provenanceDigest: "7768af27c1fafa9cc9011c1dc20067e03f8915e03b63504550e11d5066986d13" + - path: "vocab.json" + provenanceDigest: "ce99b4cb2983d118806ce0a8b777a35b093e2000a503ebde25853284c9dfa003" auxiliaryArtifacts: - auxiliaryArtifactId: "vision-projector" source: @@ -585,6 +625,85 @@ configurations: requestKinds: ["INFERENCE_REQUEST_KIND_CHAT"] inputCapabilities: supportedModalities: ["MODEL_INPUT_MODALITY_TEXT"] + # oMLX on Apple Silicon Macs with macOS 26 or later, text only. oMLX allocates memory as requests + # arrive, under a whole-process ceiling the adapter derives from this estimate. + - configurationId: "omlx-apple" + engineArtifacts: + - engineReleaseId: "omlx-0-8-4" + engineArtifactId: "metal" + artifactBindings: + - bindingId: "mlx-4bit" + modelArtifactId: "mlx-4bit" + # The same equation as Qwen3.5 9B's oMLX configuration, measured there; see the hardware + # support entry for what is unmeasured here. + sizing: + bindingParameters: ["baseBytes", "marginBytes"] + parameters: + # MLX KV cache in bfloat16, from config.json: 10 full-attention layers x 2 (K and V) x 2 KV + # heads x 256 dimensions x 2 bytes. + kvBytesPerToken: 20480 + # Gated DeltaNet recurrent state per request, from config.json: 30 linear-attention layers x + # (conv 3 x 8192 + state 32 heads x 128 x 128) values, counted at 4 bytes. + slotStateBytes: 65863680 + # Attention scores of one full prefill chunk at the default 32k context per request: oMLX's + # 2048-token chunk x 16 attention heads x 4 bytes x 32768 tokens. oMLX prefills one chunk at + # a time and shrinks chunks of longer contexts to fit its ceiling rather than refusing them. + prefillBytes: 4294967296 + # oMLX refuses prompts above 95% of its ceiling less the prompt cache, and the adapter sets + # the ceiling to the estimate / 1.07, so the estimate holds 1.07 / 0.95 of the engine's + # memory: these add 0.1264 of the per-token and per-request terms, and marginBytes holds + # that share of the fixed terms. + guardBytesPerToken: 2587 + guardBytesPerRequest: 8319623 + estimates: + # What oMLX holds at full load: weights and runtime, the KV cache of every request, their + # recurrent state and one prefill chunk's attention scores. + acceleratorMemory: + unit: bytes + equation: >- + ${baseBytes} + + ${kvBytesPerToken} * ${total-context} + + ${parallel-requests} * ${slotStateBytes} + + ${prefillBytes} + # The memory guard's headroom, and 0.07 of the prompt cache for the ceiling's overshoot. + allowance: >- + ${marginBytes} + + ${guardBytesPerToken} * ${total-context} + + ${parallel-requests} * ${guardBytesPerRequest} + + ${prompt-cache-memory-mib} * 72 * KiB + # The in-memory prompt cache, which oMLX keeps out of its prompt admission limit. + hostMemory: + unit: bytes + equation: >- + ${prompt-cache-memory-mib} * MiB + hardwareSupport: + - hardwareClassId: "apple" + # The default 4 x 32k context estimates about 37.7 GB, so a 36 GiB Mac doesn't fit. + hardwareRequirements: + minimumSystemMemoryBytes: "48000000000" + # Unmeasured: no Mac with enough memory was available. Extrapolated from the Qwen3.5 9B + # oMLX measurements on an M3 Max with explicit padding, and to be measured on a 48 GB or + # larger Mac before it is relied on. The KV, state and prefill terms follow this model's + # config.json; the expert routing's own work memory is unmeasured. + bindingSizing: + - bindingId: "mlx-4bit" + parameters: + # Padded: 20.40 GB of weight files, plus twice the 9B's 0.83 GB measured runtime + # beyond its weights, plus 1 GiB for the unmeasured mixture-of-experts work memory. + baseBytes: 23131997327 + # Padded: twice the 9B's 512 MiB slack, plus the guard share of the base, the + # prefill scores and that slack. + marginBytes: 4673831060 + engineConfiguration: + engineKind: "ENGINE_KIND_OMLX" + omlx: + fixedSettings: + promptCacheMibParameterId: "prompt-cache-memory-mib" + executionCapabilities: + supportedParallelShapes: ["MODEL_PARALLEL_SHAPE_ONE"] + requestKinds: ["INFERENCE_REQUEST_KIND_CHAT"] + inputCapabilities: + supportedModalities: ["MODEL_INPUT_MODALITY_TEXT"] profiles: - profileId: "q3-xl" displayName: "Unsloth Q3_K_XL" @@ -673,6 +792,18 @@ profiles: # Strata's total context is always the parallel requests times the context per request. engineParameterVisibilityOverrides: - { parameterId: "total-context", visibility: "PARAMETER_VISIBILITY_HIDDEN" } + - profileId: "omlx-4bit" + displayName: "MLX 4-bit on oMLX" + description: "Runs the MLX 4-bit weights through oMLX on a Mac with macOS 26 or later. Text only." + configurationIds: ["omlx-apple"] + defaultModelArtifactBindingId: "mlx-4bit" + engineParameterDefaults: + values: + - parameterId: "prompt-cache-memory-mib" + unsignedInteger: "2048" + # oMLX's total context is always the parallel requests times the context per request. + engineParameterVisibilityOverrides: + - { parameterId: "total-context", visibility: "PARAMETER_VISIBILITY_HIDDEN" } intelligence: overall: 18 license: diff --git a/docs/specs/machines.md b/docs/specs/machines.md index cbfb69e9..2e4cbf40 100644 --- a/docs/specs/machines.md +++ b/docs/specs/machines.md @@ -157,6 +157,8 @@ What is in use in a pool. claims. - A starting local model deployment claims its resolved estimate until it's ready and measured, less the use already measured for it. +- A deployment resolved as claimed while running keeps counting the larger of its estimate and its + measured use for its whole life. Engine paths that keep growing after ready do. - Application deployments occupy pools by the GPU memory attributed to them, in the host pool on unified GPUs. They carry no estimate and claim nothing. diff --git a/docs/specs/runtime.md b/docs/specs/runtime.md index f880e1c0..d0aa2968 100644 --- a/docs/specs/runtime.md +++ b/docs/specs/runtime.md @@ -10,7 +10,7 @@ Code: `backend/runtime/` (owner-neutral contracts), `backend/runtime_backends/`, ## Capabilities - Run models and apps on Linux with Docker and NVIDIA GPUs. -- Run models as native llama.cpp processes on a Mac, and apps in Docker Desktop. +- Run models as native llama.cpp or oMLX processes on a Mac, and apps in Docker Desktop. - Restart the Dotcore server without stopping native workloads. - Run a development site on a declared machine, without its hardware, and see memory and fit behave as on the real machine. diff --git a/engines/Justfile b/engines/Justfile index 3dcdd7ac..bd578cff 100644 --- a/engines/Justfile +++ b/engines/Justfile @@ -1,6 +1,7 @@ mod llama-cpp 'llama-cpp/Justfile' mod llama-cpp-v1-0 'llama-cpp/v1-0/Justfile' mod ninfer 'ninfer/Justfile' +mod omlx 'omlx/Justfile' mod strata 'strata/Justfile' mod vllm 'vllm/Justfile' mod vllm-inkling-2-mini 'vllm/inkling-2-mini/Justfile' diff --git a/engines/README.md b/engines/README.md index a39b7be1..beeb24cc 100644 --- a/engines/README.md +++ b/engines/README.md @@ -5,7 +5,8 @@ use, and you pick one when you deploy it. | Engine | Runs on | Good to know | | ----------------------- | ---------------------------------------- | -------------------------------------------------- | -| [llama.cpp](llama-cpp/) | NVIDIA GPUs on Linux, Apple Silicon Macs | The only engine on a Mac | +| [llama.cpp](llama-cpp/) | NVIDIA GPUs on Linux, Apple Silicon Macs | Runs on every supported Mac | +| [oMLX](omlx/) | Apple Silicon Macs on macOS 26 or newer | Manages its own memory; chat models only | | [vLLM](vllm/) | NVIDIA GPUs on Linux | Shares prompt prefixes between requests | | [ninfer](ninfer/) | RTX 5090, RTX PRO 6000 on x86_64 Linux | Shares prompt prefixes; first deployment builds it | | [Strata](strata/) | NVIDIA GPUs on x86_64 Linux | Splits large models between GPU and host memory | diff --git a/engines/omlx/AGENTS.md b/engines/omlx/AGENTS.md new file mode 100644 index 00000000..fcad389f --- /dev/null +++ b/engines/omlx/AGENTS.md @@ -0,0 +1,48 @@ +# oMLX agentic instructions + +## How it is built + +* [`package.nix`](package.nix) installs upstream's macOS 26-27 release app unmodified; rewriting its + Mach-O files would break their signatures. It is unpacked with `7zz`, since `undmg` can't read + the image. +* [`launcher.py`](launcher.py) is the package launcher, installed as `bin/omlx-launcher` and run by + the bundle's Python. Adapters emit plain flags only; the launcher writes oMLX's settings files + into the workload's working directory, links the model snapshot, sets the environment and execs + the server. Its flags are `--help`; keep every oMLX quirk here or in the adapter. +* The package builds with the repository flake's nixpkgs. +* Nothing here is part of root `just build`, `test` or `check`. + +## macOS floor + +* The pinned release is the macOS 26-27 build and the launcher refuses to start below macOS 26. + Artifact selectors carry no OS version, so only one build can be pinned. +* Moving the floor means a different upstream build: change the DMG name in `package.nix`, the + launcher's default minimum, and every doc that names macOS 26. + +## Update + +* Take upstream's newest stable release that still publishes a `macos26-27` DMG. +* Set `version` and the DMG `hash` in `package.nix`; the version must equal the catalog release's + version (the catalog check fails otherwise). +* Rerun the phase checks on a Mac with the new build, under a cleared environment from an empty + directory like Dotcore's launcher: the server starts and `/health` turns healthy, a chat request + streams, a too-long prompt returns `context_length_exceeded`, and no file is written outside + the working directory. +* Check that the settings keys and server flags the launcher writes still exist in the new + release, and that `ssd_cache_max_size` must still be positive. +* Re-measure the memory overshoot: force a low ceiling under full load and compare peak + `phys_footprint` to it. The adapter divides its estimate by that constant (1.07 at 0.8.4); update + it when the measurement moves. Never run long full-load tests on a personal laptop. +* Re-check the refusal margin: oMLX refuses a prompt that would cross 95% of the ceiling, so each + model's estimate must stay at least 1.126 times its engine memory plus 1.07 times its prompt + cache (1.07 / 0.95). Update the catalog sizing when the margin or the overshoot changes. +* Re-check the memory guard's refusal forms (HTTP 400 and the in-stream error frame) and the + adapter's error classification. +* Releases are immutable: declare the new one in `catalog/engines/omlx.yaml` and move every model + approving the old one. + +## Validate + +* `just smoke` on a Mac checks the package version, the launcher's generated settings and its + macOS refusal. It loads no model. +* The backend's `test-apple` recipe on a Mac, in the root "Platform scope". diff --git a/engines/omlx/Justfile b/engines/omlx/Justfile new file mode 100644 index 00000000..e02b4fb1 --- /dev/null +++ b/engines/omlx/Justfile @@ -0,0 +1,55 @@ +# List oMLX engine recipes. +help: + @just --list + +# Build the repository flake's engine package, then check its version and the launcher's generated settings. +smoke: + #!/usr/bin/env sh + set -eu + root=$(cd ../.. && pwd) + out=$(cd "$root" && nix build --no-link --print-out-paths .#engines.omlx.native) + echo "omlx package: $out" + "$out/bin/omlx" --version + + work=$(mktemp -d) + trap 'rm -rf "$work"' EXIT + mkdir "$work/snapshot" "$work/run" + cd "$work/run" + env -i "$out/bin/omlx-launcher" --prepare-only --snapshot "$work/snapshot" --served-id model-a \ + --port 18080 --context-per-request 32768 --parallel-requests 4 \ + --memory-ceiling-gb 14.5 --prompt-cache-gb 4 + + expect() { + jq -e --argjson want "$2" '. == $want' "$1" >/dev/null \ + || { echo "unexpected $1:"; cat "$1"; exit 1; } + } + expect omlx/settings.json "{ + \"version\": \"1.0\", + \"auth\": {\"allow_unauthenticated_inference\": true, \"skip_api_key_verification\": false}, + \"usage\": {\"usage_history\": false}, + \"logging\": {\"retention_days\": 1}, + \"huggingface\": {\"hf_cache_enabled\": false}, + \"cache\": {\"enabled\": true, \"hot_cache_only\": true, \"hot_cache_max_size\": \"4.0GB\", + \"ssd_cache_dir\": \"$(pwd -P)/omlx/cache\", \"ssd_cache_max_size\": \"1GB\"} + }" + expect omlx/model_settings.json '{ + "version": 3, + "models": {"model-a": {"max_context_window": 32768, "is_pinned": true, "is_default": true}} + }' + [ "$(readlink models/model-a)" = "$(cd "$work/snapshot" && pwd -P)" ] \ + || { echo "unexpected model link: $(readlink models/model-a)"; exit 1; } + + env -i "$out/bin/omlx-launcher" --prepare-only --snapshot "$work/snapshot" --served-id model-a \ + --port 18080 --context-per-request 8192 --parallel-requests 1 --memory-ceiling-gb 6 + jq -e '.cache.enabled == false' omlx/settings.json >/dev/null + + if msg=$(env -i "$out/bin/omlx-launcher" --prepare-only --min-macos 99 --snapshot "$work/snapshot" \ + --served-id model-a --port 18080 --context-per-request 1 --parallel-requests 1 \ + --memory-ceiling-gb 1 2>&1); then + echo "launcher accepted an unsupported macOS"; exit 1 + fi + case "$msg" in + "omlx: macOS 99 or newer is required, found "*) ;; + *) echo "unexpected refusal: $msg"; exit 1 ;; + esac + echo "omlx smoke passed" diff --git a/engines/omlx/README.md b/engines/omlx/README.md new file mode 100644 index 00000000..86e7032f --- /dev/null +++ b/engines/omlx/README.md @@ -0,0 +1,13 @@ +# oMLX engine + +[oMLX](https://github.com/jundot/omlx), an MLX-based engine for Apple Silicon Macs. Chat models +only. + +## Good to know + +* It needs macOS 26 or newer on an Apple Silicon Mac. Models run directly on the GPU, outside + Docker. +* It manages its own memory, so it can use more than the estimate. Dotcore gives it a memory + ceiling it respects, and it refuses prompts that would cross it. + +Maintaining it: [`AGENTS.md`](AGENTS.md). diff --git a/engines/omlx/launcher.py b/engines/omlx/launcher.py new file mode 100644 index 00000000..e20485f8 --- /dev/null +++ b/engines/omlx/launcher.py @@ -0,0 +1,149 @@ +"""Prepares oMLX's working directory for one model and execs `omlx serve`. + +Dotcore adapters only pass flags and environment, and each workload starts in an empty private +working directory. This launcher turns its flags into the settings files oMLX reads, links the +model snapshot, sets the environment and replaces itself with the server. +""" + +import argparse +import json +import os +import platform +import secrets +import sys +from pathlib import Path + +DEFAULT_MIN_MACOS = 26 + + +def main(): + args = parse_args() + check_macos(args.min_macos) + + work = Path.cwd() + dirs = Directories(work) + dirs.create() + link_model(dirs.models / args.served_id, Path(args.snapshot)) + write_json(dirs.base / "settings.json", settings(args, dirs)) + write_json(dirs.base / "model_settings.json", model_settings(args)) + + if args.prepare_only: + return + + os.execve(sys.executable, serve_argv(args, dirs), serve_env(dirs)) + + +class Directories: + """The working directory layout the server runs in.""" + + def __init__(self, work): + self.base = work / "omlx" + self.home = work / "home" + self.tmp = work / "tmp" + self.models = work / "models" + + def create(self): + for directory in (self.base, self.home, self.tmp, self.models): + directory.mkdir(parents=True, exist_ok=True) + + +def parse_args(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--snapshot", required=True, help="model snapshot directory") + parser.add_argument("--served-id", required=True, help="model id the server answers to") + parser.add_argument("--port", type=int, required=True) + parser.add_argument("--context-per-request", type=int, required=True) + parser.add_argument("--parallel-requests", type=int, required=True) + parser.add_argument("--memory-ceiling-gb", type=float, required=True, help="GiB, whole process") + parser.add_argument("--prompt-cache-gb", type=float, default=0, help="in-RAM prompt cache") + parser.add_argument("--min-macos", type=int, default=DEFAULT_MIN_MACOS) + parser.add_argument( + "--prepare-only", action="store_true", help="write the files, then exit without serving" + ) + return parser.parse_args() + + +def check_macos(minimum): + found = platform.mac_ver()[0] + if int(found.split(".")[0] or 0) < minimum: + sys.exit(f"omlx: macOS {minimum} or newer is required, found {found}") + + +def link_model(link, snapshot): + if link.is_symlink() or link.exists(): + link.unlink() + link.symlink_to(snapshot.resolve(), target_is_directory=True) + + +def settings(args, dirs): + cache_on = args.prompt_cache_gb > 0 + return { + "version": "1.0", + "auth": {"allow_unauthenticated_inference": True, "skip_api_key_verification": False}, + "usage": {"usage_history": False}, + "logging": {"retention_days": 1}, + "huggingface": {"hf_cache_enabled": False}, + "cache": { + "enabled": cache_on, + "hot_cache_only": True, + "hot_cache_max_size": f"{args.prompt_cache_gb}GB", + "ssd_cache_dir": str(dirs.base / "cache"), + "ssd_cache_max_size": "1GB", + }, + } + + +def model_settings(args): + return { + "version": 3, + "models": { + args.served_id: { + "max_context_window": args.context_per_request, + "is_pinned": True, + "is_default": True, + } + }, + } + + +def serve_env(dirs): + return { + "HOME": str(dirs.home), + "TMPDIR": str(dirs.tmp), + "HF_HOME": str(dirs.home / "hf"), + "HF_HUB_OFFLINE": "1", + "TRANSFORMERS_OFFLINE": "1", + "HF_HUB_DISABLE_TELEMETRY": "1", + "OMLX_BASE_PATH": str(dirs.base), + "OMLX_API_KEY": secrets.token_urlsafe(32), + "PATH": "/usr/bin:/bin:/usr/sbin:/sbin", + "PYTHONHOME": os.environ["PYTHONHOME"], + "PYTHONPATH": os.environ["PYTHONPATH"], + "PYTHONDONTWRITEBYTECODE": "1", + } + + +def serve_argv(args, dirs): + argv = [ + sys.executable, "-m", "omlx.cli", "serve", + "--model-dir", str(dirs.models), + "--base-path", str(dirs.base), + "--host", "127.0.0.1", + "--port", str(args.port), + "--headless", + "--no-hf-cache", + "--sse-keepalive-mode", "comment", + "--max-concurrent-requests", str(args.parallel_requests), + "--memory-guard-gb", str(args.memory_ceiling_gb), + ] # fmt: skip + if args.prompt_cache_gb > 0: + return argv + ["--hot-cache-max-size", f"{args.prompt_cache_gb}GB"] + return argv + ["--no-cache"] + + +def write_json(path, value): + path.write_text(json.dumps(value, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/engines/omlx/package.nix b/engines/omlx/package.nix new file mode 100644 index 00000000..f488dfb5 --- /dev/null +++ b/engines/omlx/package.nix @@ -0,0 +1,68 @@ +{ + lib, + stdenvNoCC, + fetchurl, + _7zz, +}: + +# Packages the upstream macOS 26-27 release app untouched: rewriting its Mach-O files would +# invalidate their arm64 signatures, so the fixup phase is disabled. The package launcher runs with +# the bundle's own Python. +stdenvNoCC.mkDerivation (finalAttrs: { + pname = "omlx"; + version = "0.8.4"; + + src = fetchurl { + url = "https://github.com/jundot/omlx/releases/download/v${finalAttrs.version}/oMLX-${finalAttrs.version}-macos26-27.dmg"; + hash = "sha256-RFw9QrGsXb3R2PHq3KCtTjXd7YRgJrPKPYU33Xzgigs="; + }; + + nativeBuildInputs = [ _7zz ]; + + # `undmg` rejects this image; `-snld` keeps the bundle's relative symlinks. + unpackPhase = '' + runHook preUnpack + 7zz x -snld -y "$src" >/dev/null + runHook postUnpack + ''; + + dontConfigure = true; + dontBuild = true; + dontFixup = true; + dontUpdateAutotoolsGnuConfigScripts = true; + + installPhase = '' + runHook preInstall + + mkdir -p "$out/libexec" "$out/bin" + cp -R oMLX.app "$out/libexec/oMLX.app" + + # 7zz stores the code-signature extended attributes of scripts as side files; they mean + # nothing in the store. + find "$out/libexec" -name '*:com.apple.*' -delete + + ln -s "$out/libexec/oMLX.app/Contents/MacOS/omlx-cli" "$out/bin/omlx" + + install -m 0644 ${./launcher.py} "$out/libexec/omlx-launcher.py" + cat > "$out/bin/omlx-launcher" < = { "llama-cpp": "llama.cpp", ninfer: "ninfer", + omlx: "oMLX", strata: "Strata", vllm: "vLLM", }; diff --git a/frontend/src/features/models/runtime/engine-parameter-values.test.ts b/frontend/src/features/models/runtime/engine-parameter-values.test.ts index 1224282d..f9d8664e 100644 --- a/frontend/src/features/models/runtime/engine-parameter-values.test.ts +++ b/frontend/src/features/models/runtime/engine-parameter-values.test.ts @@ -17,6 +17,10 @@ describe("engineKindLabel", () => { it("names Strata", () => { expect(engineKindLabel("strata")).toBe("Strata"); }); + + it("names oMLX", () => { + expect(engineKindLabel("omlx")).toBe("oMLX"); + }); }); describe("sizing-derived parameters", () => { diff --git a/frontend/src/gen/dotcore/engine/omlx/v1/model_pb.ts b/frontend/src/gen/dotcore/engine/omlx/v1/model_pb.ts new file mode 100644 index 00000000..bb2ce9c3 --- /dev/null +++ b/frontend/src/gen/dotcore/engine/omlx/v1/model_pb.ts @@ -0,0 +1,79 @@ +// @generated by protoc-gen-es v2.11.0 with parameter "target=ts" +// @generated from file dotcore/engine/omlx/v1/model.proto (package dotcore.engine.omlx.v1, syntax proto3) +/* eslint-disable */ + +import type { GenFile, GenMessage } from "@bufbuild/protobuf/codegenv2"; +import { fileDesc, messageDesc } from "@bufbuild/protobuf/codegenv2"; +import type { Message } from "@bufbuild/protobuf"; + +/** + * Describes the file dotcore/engine/omlx/v1/model.proto. + */ +export const file_dotcore_engine_omlx_v1_model: GenFile = /*@__PURE__*/ + fileDesc("CiJkb3Rjb3JlL2VuZ2luZS9vbWx4L3YxL21vZGVsLnByb3RvEhZkb3Rjb3JlLmVuZ2luZS5vbWx4LnYxImAKFk9tbHhNb2RlbENvbmZpZ3VyYXRpb24SRgoOZml4ZWRfc2V0dGluZ3MYASABKAsyLi5kb3Rjb3JlLmVuZ2luZS5vbWx4LnYxLk9tbHhGaXhlZE1vZGVsU2V0dGluZ3MiYAoWT21seFJlc29sdmVkTW9kZWxTdGF0ZRJGCg5maXhlZF9zZXR0aW5ncxgBIAEoCzIuLmRvdGNvcmUuZW5naW5lLm9tbHgudjEuT21seEZpeGVkTW9kZWxTZXR0aW5ncyI/ChZPbWx4Rml4ZWRNb2RlbFNldHRpbmdzEiUKHXByb21wdF9jYWNoZV9taWJfcGFyYW1ldGVyX2lkGAEgASgJYgZwcm90bzM"); + +/** + * Engine-owned oMLX configuration embedded in one catalog model + * configuration. Generic catalog code treats this payload as opaque typed data. + * + * @generated from message dotcore.engine.omlx.v1.OmlxModelConfiguration + */ +export type OmlxModelConfiguration = Message<"dotcore.engine.omlx.v1.OmlxModelConfiguration"> & { + /** + * Fixed oMLX settings shared by every selection of this configuration. + * + * @generated from field: dotcore.engine.omlx.v1.OmlxFixedModelSettings fixed_settings = 1; + */ + fixedSettings?: OmlxFixedModelSettings; +}; + +/** + * Describes the message dotcore.engine.omlx.v1.OmlxModelConfiguration. + * Use `create(OmlxModelConfigurationSchema)` to create a new message. + */ +export const OmlxModelConfigurationSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_dotcore_engine_omlx_v1_model, 0); + +/** + * Concrete oMLX state retained in a resolved deployment snapshot. + * + * @generated from message dotcore.engine.omlx.v1.OmlxResolvedModelState + */ +export type OmlxResolvedModelState = Message<"dotcore.engine.omlx.v1.OmlxResolvedModelState"> & { + /** + * Fixed settings copied from the selected configuration. + * + * @generated from field: dotcore.engine.omlx.v1.OmlxFixedModelSettings fixed_settings = 1; + */ + fixedSettings?: OmlxFixedModelSettings; +}; + +/** + * Describes the message dotcore.engine.omlx.v1.OmlxResolvedModelState. + * Use `create(OmlxResolvedModelStateSchema)` to create a new message. + */ +export const OmlxResolvedModelStateSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_dotcore_engine_omlx_v1_model, 1); + +/** + * Fixed oMLX launch inputs. Editable values use generic engine parameter + * schema and value contracts. + * + * @generated from message dotcore.engine.omlx.v1.OmlxFixedModelSettings + */ +export type OmlxFixedModelSettings = Message<"dotcore.engine.omlx.v1.OmlxFixedModelSettings"> & { + /** + * Generic engine parameter containing the in-memory prompt cache size in MiB; 0 disables the cache. + * + * @generated from field: string prompt_cache_mib_parameter_id = 1; + */ + promptCacheMibParameterId: string; +}; + +/** + * Describes the message dotcore.engine.omlx.v1.OmlxFixedModelSettings. + * Use `create(OmlxFixedModelSettingsSchema)` to create a new message. + */ +export const OmlxFixedModelSettingsSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_dotcore_engine_omlx_v1_model, 2); + diff --git a/frontend/src/gen/dotcore/engine/v1/engine_pb.ts b/frontend/src/gen/dotcore/engine/v1/engine_pb.ts index 71f917b0..2f6dd0b6 100644 --- a/frontend/src/gen/dotcore/engine/v1/engine_pb.ts +++ b/frontend/src/gen/dotcore/engine/v1/engine_pb.ts @@ -8,6 +8,8 @@ import type { LlamaCppModelConfiguration, LlamaCppResolvedModelState } from "../ import { file_dotcore_engine_llama_cpp_v1_model } from "../llama_cpp/v1/model_pb"; import type { NinferModelConfiguration, NinferResolvedModelState } from "../ninfer/v1/model_pb"; import { file_dotcore_engine_ninfer_v1_model } from "../ninfer/v1/model_pb"; +import type { OmlxModelConfiguration, OmlxResolvedModelState } from "../omlx/v1/model_pb"; +import { file_dotcore_engine_omlx_v1_model } from "../omlx/v1/model_pb"; import type { StrataModelConfiguration, StrataResolvedModelState } from "../strata/v1/model_pb"; import { file_dotcore_engine_strata_v1_model } from "../strata/v1/model_pb"; import type { VllmModelConfiguration, VllmResolvedModelState } from "../vllm/v1/model_pb"; @@ -18,7 +20,7 @@ import type { Message } from "@bufbuild/protobuf"; * Describes the file dotcore/engine/v1/engine.proto. */ export const file_dotcore_engine_v1_engine: GenFile = /*@__PURE__*/ - fileDesc("Ch5kb3Rjb3JlL2VuZ2luZS92MS9lbmdpbmUucHJvdG8SEWRvdGNvcmUuZW5naW5lLnYxIvkCChhFbmdpbmVNb2RlbENvbmZpZ3VyYXRpb24SMgoLZW5naW5lX2tpbmQYASABKA4yHS5kb3Rjb3JlLmVuZ2luZS52MS5FbmdpbmVLaW5kEkwKCWxsYW1hX2NwcBgCIAEoCzI3LmRvdGNvcmUuZW5naW5lLmxsYW1hX2NwcC52MS5MbGFtYUNwcE1vZGVsQ29uZmlndXJhdGlvbkgAEj4KBHZsbG0YAyABKAsyLi5kb3Rjb3JlLmVuZ2luZS52bGxtLnYxLlZsbG1Nb2RlbENvbmZpZ3VyYXRpb25IABJECgZuaW5mZXIYBCABKAsyMi5kb3Rjb3JlLmVuZ2luZS5uaW5mZXIudjEuTmluZmVyTW9kZWxDb25maWd1cmF0aW9uSAASRAoGc3RyYXRhGAUgASgLMjIuZG90Y29yZS5lbmdpbmUuc3RyYXRhLnYxLlN0cmF0YU1vZGVsQ29uZmlndXJhdGlvbkgAQg8KDWNvbmZpZ3VyYXRpb24ijAMKGFJlc29sdmVkRW5naW5lTW9kZWxTdGF0ZRIyCgtlbmdpbmVfa2luZBgBIAEoDjIdLmRvdGNvcmUuZW5naW5lLnYxLkVuZ2luZUtpbmQSGQoRc2VtYW50aWNzX3ZlcnNpb24YAiABKA0STAoJbGxhbWFfY3BwGAMgASgLMjcuZG90Y29yZS5lbmdpbmUubGxhbWFfY3BwLnYxLkxsYW1hQ3BwUmVzb2x2ZWRNb2RlbFN0YXRlSAASPgoEdmxsbRgEIAEoCzIuLmRvdGNvcmUuZW5naW5lLnZsbG0udjEuVmxsbVJlc29sdmVkTW9kZWxTdGF0ZUgAEkQKBm5pbmZlchgFIAEoCzIyLmRvdGNvcmUuZW5naW5lLm5pbmZlci52MS5OaW5mZXJSZXNvbHZlZE1vZGVsU3RhdGVIABJECgZzdHJhdGEYBiABKAsyMi5kb3Rjb3JlLmVuZ2luZS5zdHJhdGEudjEuU3RyYXRhUmVzb2x2ZWRNb2RlbFN0YXRlSABCBwoFc3RhdGUqigEKCkVuZ2luZUtpbmQSGwoXRU5HSU5FX0tJTkRfVU5TUEVDSUZJRUQQABIZChVFTkdJTkVfS0lORF9MTEFNQV9DUFAQARIUChBFTkdJTkVfS0lORF9WTExNEAISFgoSRU5HSU5FX0tJTkRfTklORkVSEAMSFgoSRU5HSU5FX0tJTkRfU1RSQVRBEARiBnByb3RvMw", [file_dotcore_engine_llama_cpp_v1_model, file_dotcore_engine_ninfer_v1_model, file_dotcore_engine_strata_v1_model, file_dotcore_engine_vllm_v1_model]); + fileDesc("Ch5kb3Rjb3JlL2VuZ2luZS92MS9lbmdpbmUucHJvdG8SEWRvdGNvcmUuZW5naW5lLnYxIrkDChhFbmdpbmVNb2RlbENvbmZpZ3VyYXRpb24SMgoLZW5naW5lX2tpbmQYASABKA4yHS5kb3Rjb3JlLmVuZ2luZS52MS5FbmdpbmVLaW5kEkwKCWxsYW1hX2NwcBgCIAEoCzI3LmRvdGNvcmUuZW5naW5lLmxsYW1hX2NwcC52MS5MbGFtYUNwcE1vZGVsQ29uZmlndXJhdGlvbkgAEj4KBHZsbG0YAyABKAsyLi5kb3Rjb3JlLmVuZ2luZS52bGxtLnYxLlZsbG1Nb2RlbENvbmZpZ3VyYXRpb25IABJECgZuaW5mZXIYBCABKAsyMi5kb3Rjb3JlLmVuZ2luZS5uaW5mZXIudjEuTmluZmVyTW9kZWxDb25maWd1cmF0aW9uSAASRAoGc3RyYXRhGAUgASgLMjIuZG90Y29yZS5lbmdpbmUuc3RyYXRhLnYxLlN0cmF0YU1vZGVsQ29uZmlndXJhdGlvbkgAEj4KBG9tbHgYBiABKAsyLi5kb3Rjb3JlLmVuZ2luZS5vbWx4LnYxLk9tbHhNb2RlbENvbmZpZ3VyYXRpb25IAEIPCg1jb25maWd1cmF0aW9uIswDChhSZXNvbHZlZEVuZ2luZU1vZGVsU3RhdGUSMgoLZW5naW5lX2tpbmQYASABKA4yHS5kb3Rjb3JlLmVuZ2luZS52MS5FbmdpbmVLaW5kEhkKEXNlbWFudGljc192ZXJzaW9uGAIgASgNEkwKCWxsYW1hX2NwcBgDIAEoCzI3LmRvdGNvcmUuZW5naW5lLmxsYW1hX2NwcC52MS5MbGFtYUNwcFJlc29sdmVkTW9kZWxTdGF0ZUgAEj4KBHZsbG0YBCABKAsyLi5kb3Rjb3JlLmVuZ2luZS52bGxtLnYxLlZsbG1SZXNvbHZlZE1vZGVsU3RhdGVIABJECgZuaW5mZXIYBSABKAsyMi5kb3Rjb3JlLmVuZ2luZS5uaW5mZXIudjEuTmluZmVyUmVzb2x2ZWRNb2RlbFN0YXRlSAASRAoGc3RyYXRhGAYgASgLMjIuZG90Y29yZS5lbmdpbmUuc3RyYXRhLnYxLlN0cmF0YVJlc29sdmVkTW9kZWxTdGF0ZUgAEj4KBG9tbHgYByABKAsyLi5kb3Rjb3JlLmVuZ2luZS5vbWx4LnYxLk9tbHhSZXNvbHZlZE1vZGVsU3RhdGVIAEIHCgVzdGF0ZSqgAQoKRW5naW5lS2luZBIbChdFTkdJTkVfS0lORF9VTlNQRUNJRklFRBAAEhkKFUVOR0lORV9LSU5EX0xMQU1BX0NQUBABEhQKEEVOR0lORV9LSU5EX1ZMTE0QAhIWChJFTkdJTkVfS0lORF9OSU5GRVIQAxIWChJFTkdJTkVfS0lORF9TVFJBVEEQBBIUChBFTkdJTkVfS0lORF9PTUxYEAViBnByb3RvMw", [file_dotcore_engine_llama_cpp_v1_model, file_dotcore_engine_ninfer_v1_model, file_dotcore_engine_omlx_v1_model, file_dotcore_engine_strata_v1_model, file_dotcore_engine_vllm_v1_model]); /** * Neutral wrapper for one engine-owned catalog model configuration payload. @@ -68,6 +70,14 @@ export type EngineModelConfiguration = Message<"dotcore.engine.v1.EngineModelCon */ value: StrataModelConfiguration; case: "strata"; + } | { + /** + * Engine-owned oMLX model configuration. + * + * @generated from field: dotcore.engine.omlx.v1.OmlxModelConfiguration omlx = 6; + */ + value: OmlxModelConfiguration; + case: "omlx"; } | { case: undefined; value?: undefined }; }; @@ -133,6 +143,14 @@ export type ResolvedEngineModelState = Message<"dotcore.engine.v1.ResolvedEngine */ value: StrataResolvedModelState; case: "strata"; + } | { + /** + * Concrete resolved oMLX state. + * + * @generated from field: dotcore.engine.omlx.v1.OmlxResolvedModelState omlx = 7; + */ + value: OmlxResolvedModelState; + case: "omlx"; } | { case: undefined; value?: undefined }; }; @@ -183,6 +201,13 @@ export enum EngineKind { * @generated from enum value: ENGINE_KIND_STRATA = 4; */ STRATA = 4, + + /** + * The engine kind oMLX value. + * + * @generated from enum value: ENGINE_KIND_OMLX = 5; + */ + OMLX = 5, } /** diff --git a/proto/dotcore/engine/omlx/v1/model.proto b/proto/dotcore/engine/omlx/v1/model.proto new file mode 100644 index 00000000..daa782ae --- /dev/null +++ b/proto/dotcore/engine/omlx/v1/model.proto @@ -0,0 +1,23 @@ +syntax = "proto3"; + +package dotcore.engine.omlx.v1; + +// Engine-owned oMLX configuration embedded in one catalog model +// configuration. Generic catalog code treats this payload as opaque typed data. +message OmlxModelConfiguration { + // Fixed oMLX settings shared by every selection of this configuration. + OmlxFixedModelSettings fixed_settings = 1; +} + +// Concrete oMLX state retained in a resolved deployment snapshot. +message OmlxResolvedModelState { + // Fixed settings copied from the selected configuration. + OmlxFixedModelSettings fixed_settings = 1; +} + +// Fixed oMLX launch inputs. Editable values use generic engine parameter +// schema and value contracts. +message OmlxFixedModelSettings { + // Generic engine parameter containing the in-memory prompt cache size in MiB; 0 disables the cache. + string prompt_cache_mib_parameter_id = 1; +} diff --git a/proto/dotcore/engine/v1/engine.proto b/proto/dotcore/engine/v1/engine.proto index 10bd0795..d6d73d3c 100644 --- a/proto/dotcore/engine/v1/engine.proto +++ b/proto/dotcore/engine/v1/engine.proto @@ -4,6 +4,7 @@ package dotcore.engine.v1; import "dotcore/engine/llama_cpp/v1/model.proto"; import "dotcore/engine/ninfer/v1/model.proto"; +import "dotcore/engine/omlx/v1/model.proto"; import "dotcore/engine/strata/v1/model.proto"; import "dotcore/engine/vllm/v1/model.proto"; @@ -23,6 +24,9 @@ enum EngineKind { // The engine kind Strata value. ENGINE_KIND_STRATA = 4; + + // The engine kind oMLX value. + ENGINE_KIND_OMLX = 5; } // Neutral wrapper for one engine-owned catalog model configuration payload. @@ -42,6 +46,9 @@ message EngineModelConfiguration { // Engine-owned Strata model configuration. dotcore.engine.strata.v1.StrataModelConfiguration strata = 5; + + // Engine-owned oMLX model configuration. + dotcore.engine.omlx.v1.OmlxModelConfiguration omlx = 6; } } @@ -65,5 +72,8 @@ message ResolvedEngineModelState { // Concrete resolved Strata state. dotcore.engine.strata.v1.StrataResolvedModelState strata = 6; + + // Concrete resolved oMLX state. + dotcore.engine.omlx.v1.OmlxResolvedModelState omlx = 7; } }