Files
leleka/desktop-core/src/planner.rs
T
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

213 lines
6.8 KiB
Rust

use crate::hardware::{Hardware, MemoryKind};
use serde::{Deserialize, Serialize};
/// Runtime allocations supplied by a model/backend adapter, NOT archive size.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Requirements {
pub schema_version: u32,
pub model: String,
pub context_tokens: u64,
pub concurrent_requests: u32,
pub weights_bytes: u64,
pub kv_bytes_per_token_per_request: u64,
pub workspace_bytes: u64,
pub load_scratch_bytes: u64,
pub host_overhead_bytes: u64,
pub host_reserve_bytes: u64,
pub device_reserve_bytes: u64,
/// Explicitly model a worker that retains a complete host weight copy.
pub retains_host_weights: bool,
/// Only true when the selected backend supports this weight split.
pub allow_weight_offload: bool,
}
#[derive(Debug, Serialize)]
pub struct Candidate {
pub device: String,
pub placement: String,
pub device_weight_percent: u32,
pub host_peak_bytes: u64,
pub device_peak_bytes: u64,
pub host_budget_bytes: Option<u64>,
pub device_budget_bytes: Option<u64>,
pub fit: String,
pub reasons: Vec<String>,
}
#[derive(Debug, Serialize)]
pub struct Plan {
pub schema_version: u32,
pub model: String,
pub context_tokens: u64,
pub concurrent_requests: u32,
pub evidence: &'static str,
pub execution_compatibility: &'static str,
pub warnings: Vec<String>,
pub candidates: Vec<Candidate>,
}
fn sum(values: &[u64]) -> Result<u64, String> {
values.iter().try_fold(0u64, |s, n| {
s.checked_add(*n).ok_or("memory size overflow".into())
})
}
pub fn plan(h: &Hardware, r: &Requirements) -> Result<Plan, String> {
if h.schema_version != 1 || r.schema_version != 1 {
return Err("unsupported schema version".into());
}
if r.model.trim().is_empty()
|| r.weights_bytes == 0
|| r.context_tokens == 0
|| r.concurrent_requests == 0
{
return Err("model, weights, context and concurrency must be nonzero".into());
}
for m in std::iter::once(&h.memory).chain(h.accelerators.iter().map(|g| &g.memory)) {
if let (Some(t), Some(a)) = (m.total_bytes, m.available_bytes)
&& a > t
{
return Err("available memory exceeds total".into());
}
}
let kv = r
.kv_bytes_per_token_per_request
.checked_mul(r.context_tokens)
.and_then(|v| v.checked_mul(u64::from(r.concurrent_requests)))
.ok_or("KV size overflow")?;
let runtime = sum(&[kv, r.workspace_bytes, r.load_scratch_bytes])?;
let host_budget = h
.memory
.available_bytes
.map(|n| n.saturating_sub(r.host_reserve_bytes));
let cpu_peak = sum(&[r.weights_bytes, runtime, r.host_overhead_bytes])?;
let mut candidates = vec![candidate(
"cpu",
"host",
0,
cpu_peak,
0,
host_budget,
None,
false,
)];
for g in &h.accelerators {
let device_budget = g
.memory
.available_bytes
.map(|n| n.saturating_sub(r.device_reserve_bytes));
if g.memory_kind != MemoryKind::Dedicated {
// Shared weights/runtime are counted ONCE in host_peak; also enforce device ceiling.
let shared_peak = sum(&[
cpu_peak,
if r.retains_host_weights {
r.weights_bytes
} else {
0
},
])?;
let mut c = candidate(
&g.id,
"shared",
100,
shared_peak,
sum(&[r.weights_bytes, runtime])?,
host_budget,
device_budget,
true,
);
if g.memory_kind == MemoryKind::Unknown {
c.fit = "unknown".into();
c.reasons.push("memory topology unknown".into());
}
candidates.push(c);
continue;
}
let splits: &[u32] = if r.allow_weight_offload {
&[100, 75, 50, 25]
} else {
&[100]
};
for &percent in splits {
let device_weights =
((u128::from(r.weights_bytes) * u128::from(percent)).div_ceil(100)) as u64;
let host_weights = if r.retains_host_weights {
r.weights_bytes
} else {
r.weights_bytes - device_weights
};
// Conservative: reserve scratch on host too for upload/decode staging.
let host_peak = sum(&[host_weights, r.host_overhead_bytes, r.load_scratch_bytes])?;
let device_peak = sum(&[device_weights, runtime])?;
candidates.push(candidate(
&g.id,
if percent == 100 { "device" } else { "offload" },
percent,
host_peak,
device_peak,
host_budget,
device_budget,
true,
));
}
}
Ok(Plan {schema_version:1, model:r.model.clone(),context_tokens:r.context_tokens,
concurrent_requests:r.concurrent_requests,evidence:"estimated",execution_compatibility:"not_validated",
warnings: vec!["Memory fit does not establish model/backend compatibility, quality or speed.".into(),
"Requirements must describe runtime allocations; compressed file size is insufficient. Recheck available memory before load.".into()], candidates})
}
#[allow(clippy::too_many_arguments)]
fn candidate(
device: &str,
placement: &str,
percent: u32,
host_peak: u64,
device_peak: u64,
host_budget: Option<u64>,
device_budget: Option<u64>,
needs_device: bool,
) -> Candidate {
let mut reasons = Vec::new();
let mut unknown = false;
let mut insufficient = false;
for (label, needed, budget) in [
("host", host_peak, host_budget),
("device", device_peak, device_budget),
] {
if label == "device" && !needs_device {
continue;
}
match budget {
None => {
unknown = true;
reasons.push(format!("{label} available budget unknown"));
}
Some(n) if needed > n => {
insufficient = true;
reasons.push(format!("{label} needs {} more bytes", needed - n));
}
_ => {}
}
}
Candidate {
device: device.into(),
placement: placement.into(),
device_weight_percent: percent,
host_peak_bytes: host_peak,
device_peak_bytes: device_peak,
host_budget_bytes: host_budget,
device_budget_bytes: device_budget,
fit: if insufficient {
"insufficient"
} else if unknown {
"unknown"
} else {
"fits_estimate"
}
.into(),
reasons,
}
}