Files
leleka/desktop-core/src/planner.rs
T

334 lines
10 KiB
Rust

use crate::hardware::{Accelerator, 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())
})
}
/// Refuses unsupported schemas, empty requirements and memory figures that contradict themselves.
fn validate(h: &Hardware, r: &Requirements) -> Result<(), 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());
}
}
Ok(())
}
/// Device and host weight bytes when `percent` of the weights go to the device.
fn split_weights(r: &Requirements, percent: u32) -> (u64, u64) {
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
};
(device_weights, host_weights)
}
/// The sizes every placement of one requirement shares.
struct Sizing<'a> {
r: &'a Requirements,
runtime: u64,
cpu_peak: u64,
host_budget: Option<u64>,
}
impl Sizing<'_> {
/// The device-side budget of `g` after the reserve.
fn device_budget(&self, g: &Accelerator) -> Option<u64> {
let reserve = self.r.device_reserve_bytes;
g.memory.available_bytes.map(|n| n.saturating_sub(reserve))
}
/// The host budget and the device budget of `g`.
fn budgets(&self, g: &Accelerator) -> Budgets {
Budgets {
host: self.host_budget,
device: self.device_budget(g),
}
}
/// Memory the device shares with the host: weights and runtime are counted ONCE in the host peak, and the
/// device ceiling is enforced as well.
fn shared(&self, g: &Accelerator) -> Result<Candidate, String> {
let r = self.r;
let retained = if r.retains_host_weights {
r.weights_bytes
} else {
0
};
let shared_peak = sum(&[self.cpu_peak, retained])?;
let placement = Placement {
device: &g.id,
kind: "shared",
percent: 100,
needs_device: true,
};
let peaks = Peaks {
host: shared_peak,
device: sum(&[r.weights_bytes, self.runtime])?,
};
let mut c = candidate(placement, peaks, self.budgets(g));
if g.memory_kind == MemoryKind::Unknown {
c.fit = "unknown".into();
c.reasons.push("memory topology unknown".into());
}
Ok(c)
}
/// Dedicated device memory: the whole weights, or (when the backend allows it) a share of them, on the device.
fn dedicated(&self, g: &Accelerator, out: &mut Vec<Candidate>) -> Result<(), String> {
let r = self.r;
let splits: &[u32] = if r.allow_weight_offload {
&[100, 75, 50, 25]
} else {
&[100]
};
for &percent in splits {
let (device_weights, host_weights) = split_weights(r, percent);
// 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, self.runtime])?;
let placement = Placement {
device: &g.id,
kind: if percent == 100 { "device" } else { "offload" },
percent,
needs_device: true,
};
let peaks = Peaks {
host: host_peak,
device: device_peak,
};
out.push(candidate(placement, peaks, self.budgets(g)));
}
Ok(())
}
}
const PLAN_WARNINGS: [&str; 2] = [
"Memory fit does not establish model/backend compatibility, quality or speed.",
concat!(
"Requirements must describe runtime allocations; compressed file size is insufficient. ",
"Recheck available memory before load."
),
];
pub fn plan(h: &Hardware, r: &Requirements) -> Result<Plan, String> {
validate(h, r)?;
let runtime = sum_runtime_bytes(r)?;
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 sizing = Sizing {
r,
runtime,
cpu_peak,
host_budget,
};
let mut candidates = vec![host_candidate(cpu_peak, host_budget)];
add_accelerator_candidates(&sizing, h, &mut candidates)?;
Ok(build_estimated_plan(r, candidates))
}
/// KV cache for every request at the full context, plus the workspace and the load scratch.
fn sum_runtime_bytes(r: &Requirements) -> Result<u64, String> {
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")?;
sum(&[kv, r.workspace_bytes, r.load_scratch_bytes])
}
/// One candidate per shared accelerator, and the dedicated ones through their own placements.
fn add_accelerator_candidates(
sizing: &Sizing,
h: &Hardware,
candidates: &mut Vec<Candidate>,
) -> Result<(), String> {
for g in &h.accelerators {
if g.memory_kind != MemoryKind::Dedicated {
candidates.push(sizing.shared(g)?);
} else {
sizing.dedicated(g, candidates)?;
}
}
Ok(())
}
fn build_estimated_plan(r: &Requirements, candidates: Vec<Candidate>) -> Plan {
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: PLAN_WARNINGS.iter().map(|w| w.to_string()).collect(),
candidates,
}
}
/// How a placement fits: too small beats unknown, which beats fitting the estimate.
fn fit_name(insufficient: bool, unknown: bool) -> &'static str {
if insufficient {
"insufficient"
} else if unknown {
"unknown"
} else {
"fits_estimate"
}
}
/// What the budgets say about a placement: the reasons, whether a budget is unknown and whether one is too small.
/// The device budget counts only when the placement needs a device.
fn budget_findings(
needs: [(&str, u64, Option<u64>); 2],
needs_device: bool,
) -> (Vec<String>, bool, bool) {
let mut reasons = Vec::new();
let mut unknown = false;
let mut insufficient = false;
for (label, needed, budget) in needs {
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));
}
_ => {}
}
}
(reasons, unknown, insufficient)
}
/// Where a placement puts the weights: the device, the placement kind, the percent of weights on the device, and
/// whether the placement needs the device's budget at all.
struct Placement<'a> {
device: &'a str,
kind: &'a str,
percent: u32,
needs_device: bool,
}
/// The peak bytes a placement needs on the host and on the device.
struct Peaks {
host: u64,
device: u64,
}
/// The bytes available to a placement on the host and on the device, when known.
struct Budgets {
host: Option<u64>,
device: Option<u64>,
}
/// The candidate that runs everything on the CPU.
fn host_candidate(cpu_peak: u64, host_budget: Option<u64>) -> Candidate {
let placement = Placement {
device: "cpu",
kind: "host",
percent: 0,
needs_device: false,
};
let peaks = Peaks {
host: cpu_peak,
device: 0,
};
let budgets = Budgets {
host: host_budget,
device: None,
};
candidate(placement, peaks, budgets)
}
fn candidate(placement: Placement<'_>, peaks: Peaks, budgets: Budgets) -> Candidate {
let (reasons, unknown, insufficient) = budget_findings(
[
("host", peaks.host, budgets.host),
("device", peaks.device, budgets.device),
],
placement.needs_device,
);
Candidate {
device: placement.device.into(),
placement: placement.kind.into(),
device_weight_percent: placement.percent,
host_peak_bytes: peaks.host,
device_peak_bytes: peaks.device,
host_budget_bytes: budgets.host,
device_budget_bytes: budgets.device,
fit: fit_name(insufficient, unknown).into(),
reasons,
}
}