Files
leleka/control-plane/src/cuda_memory.rs
T

255 lines
8.3 KiB
Rust

//! Declared-budget admission only: no allocation, model sizing or CUDA context.
use serde::{Deserialize, Serialize};
use std::{collections::HashSet, process::Stdio, time::Duration};
use tokio::{io::AsyncReadExt, process::Command, time::timeout};
#[derive(Clone, Copy, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Policy {
pub required_mib: u64,
pub reserve_mib: u64,
}
impl Policy {
pub fn validate(self) -> Result<u64, &'static str> {
if self.required_mib == 0 {
return Err("cuda_memory.required_mib must be positive");
}
self.required_mib
.checked_add(self.reserve_mib)
.ok_or("cuda_memory budget overflow")
}
pub async fn select(self) -> Result<Selection, String> {
self.validate()?;
let visible = std::env::var("CUDA_VISIBLE_DEVICES")
.map(Some)
.or_else(|e| match e {
std::env::VarError::NotPresent => Ok(None),
_ => Err("CUDA_VISIBLE_DEVICES must be UTF-8".to_owned()),
})?;
let allowed = visibility(visible.as_deref())?;
let devices = inventory().await?;
choose(self, devices, allowed.as_deref())
}
}
#[derive(Clone)]
pub struct Selection {
pub uuid: String,
pub policy: Policy,
}
impl Selection {
pub async fn recheck(&self) -> Result<(), String> {
let devices = inventory().await?;
choose(self.policy, devices, Some(std::slice::from_ref(&self.uuid))).map(|_| ())
}
}
/// Free VRAM in MiB of the selected GPU, or of the freest visible one; `None` when it cannot be read
/// (then nothing is refused, as in the Original's `free_vram_mib`).
pub async fn free_mib(selection: Option<&Selection>) -> Option<u64> {
let devices = inventory().await.ok()?;
match selection {
Some(selection) => devices
.iter()
.find(|d| d.uuid == selection.uuid)
.map(|d| d.free),
None => devices.iter().map(|d| d.free).max(),
}
}
struct Device {
uuid: String,
free: u64,
eligible: bool,
}
fn uuid_valid(uuid: &str) -> bool {
uuid.len() == 40
&& uuid.starts_with("GPU-")
&& uuid[4..].bytes().enumerate().all(|(i, b)| {
if [8, 13, 18, 23].contains(&i) {
b == b'-'
} else {
b.is_ascii_hexdigit()
}
})
}
fn visibility(value: Option<&str>) -> Result<Option<Vec<String>>, String> {
let Some(value) = value else { return Ok(None) };
if value.is_empty() {
return Ok(Some(Vec::new()));
}
let ids: Vec<_> = value.split(',').map(str::to_owned).collect();
if ids.iter().any(|id| !uuid_valid(id)) || ids.iter().collect::<HashSet<_>>().len() != ids.len()
{
return Err(concat!(
"cuda_memory requires CUDA_VISIBLE_DEVICES unset or a comma-separated list of full GPU UUIDs; ",
"ordinal, abbreviated and MIG identifiers are unsupported"
)
.into());
}
Ok(Some(ids))
}
fn parse(text: &str) -> Result<Vec<Device>, String> {
let mut ids = HashSet::new();
let mut devices = Vec::new();
for line in text.lines() {
devices.push(parse_line(line, &mut ids)?);
}
if devices.is_empty() {
return Err("GPU inventory is empty".into());
}
Ok(devices)
}
fn parse_line<'a>(line: &'a str, ids: &mut HashSet<&'a str>) -> Result<Device, String> {
let v: Vec<_> = line.split(',').map(str::trim).collect();
if v.len() != 4 || !uuid_valid(v[0]) || !ids.insert(v[0]) {
return Err("malformed or duplicate GPU inventory".into());
}
let total: u64 = v[1].parse().map_err(|_| "invalid GPU total memory")?;
let free: u64 = v[2].parse().map_err(|_| "invalid GPU free memory")?;
if total == 0 || free > total {
return Err("inconsistent GPU memory inventory".into());
}
let eligible = match v[3] {
"Disabled" | "[N/A]" => true,
"Enabled" => false,
_ => return Err("unknown GPU MIG mode".into()),
};
Ok(Device {
uuid: v[0].to_owned(),
free,
eligible,
})
}
fn choose(
policy: Policy,
mut devices: Vec<Device>,
allowed: Option<&[String]>,
) -> Result<Selection, String> {
let needed = policy.validate()?;
devices.retain(|d| {
d.eligible && d.free >= needed && allowed.is_none_or(|ids| ids.contains(&d.uuid))
});
devices.sort_by(|a, b| b.free.cmp(&a.free).then(a.uuid.cmp(&b.uuid)));
let device = devices.into_iter().next().ok_or_else(|| {
format!(
concat!(
"no visible non-MIG GPU has {} MiB free for cuda_memory; ",
"free capacity or select a qualified smaller profile"
),
needed
)
})?;
Ok(Selection {
uuid: device.uuid,
policy,
})
}
/// The devices `nvidia-smi` lists: at most 8 KiB of output, a successful exit and valid UTF-8.
async fn read_devices(child: &mut tokio::process::Child) -> Result<Vec<Device>, String> {
let mut bytes = Vec::new();
child
.stdout
.take()
.ok_or("GPU query stdout unavailable")?
.take(8193)
.read_to_end(&mut bytes)
.await
.map_err(|_| "GPU query read failed")?;
if bytes.len() > 8192 {
return Err("GPU inventory exceeds 8 KiB".to_owned());
}
if !child
.wait()
.await
.map_err(|_| "GPU query wait failed")?
.success()
{
return Err("GPU memory query failed".into());
}
parse(std::str::from_utf8(&bytes).map_err(|_| "GPU inventory is not UTF-8")?)
}
async fn inventory() -> Result<Vec<Device>, String> {
if !cfg!(target_os = "linux") {
return Err("cuda_memory requires Linux".into());
}
let mut child = Command::new("nvidia-smi")
.args([
"--query-gpu=uuid,memory.total,memory.free,mig.mode.current",
"--format=csv,noheader,nounits",
])
.stdin(Stdio::null())
.stderr(Stdio::null())
.stdout(Stdio::piped())
.kill_on_drop(true)
.spawn()
.map_err(|_| "cannot query GPU memory; make nvidia-smi available")?;
let result = timeout(Duration::from_secs(5), read_devices(&mut child)).await;
match result {
Ok(Ok(devices)) => Ok(devices),
result => {
let _ = child.kill().await;
Err(match result {
Ok(Err(e)) => e,
_ => "GPU memory query timed out after 5 seconds".into(),
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const A: &str = "GPU-00000000-0000-0000-0000-000000000001";
const B: &str = "GPU-00000000-0000-0000-0000-000000000002";
#[test]
fn selection_respects_budget_visibility_and_mig() {
let p = Policy {
required_mib: 7000,
reserve_mib: 1000,
};
let data = format!("{A},8192,8000,Disabled\n{B},16384,16000,[N/A]\n");
assert_eq!(choose(p, parse(&data).unwrap(), None).unwrap().uuid, B);
assert_eq!(
choose(p, parse(&data).unwrap(), Some(&[A.into()]))
.unwrap()
.uuid,
A
);
assert!(choose(p, parse(&data).unwrap(), Some(&[])).is_err());
assert!(choose(p, parse(&format!("{A},8192,7999,Disabled")).unwrap(), None).is_err());
assert!(choose(p, parse(&format!("{A},8192,8000,Enabled")).unwrap(), None).is_err());
for s in ["0", "-1", "all", "GPU-123", "MIG-123", &format!("{A},{A}")] {
assert!(visibility(Some(s)).is_err());
}
assert_eq!(visibility(Some(A)).unwrap(), Some(vec![A.into()]));
}
#[test]
fn rejects_untrusted_inventory_and_budget() {
for s in [
String::new(),
format!("{A},1,2,Disabled"),
format!("{A},0,0,Disabled"),
format!("{A},8192,NaN,Disabled"),
format!("{A},8192,8192,Unknown"),
format!("{A},8192,8192,Disabled\n{A},8192,8192,Disabled"),
] {
assert!(parse(&s).is_err());
}
assert!(
Policy {
required_mib: 0,
reserve_mib: 1
}
.validate()
.is_err()
);
assert!(
Policy {
required_mib: u64::MAX,
reserve_mib: 1
}
.validate()
.is_err()
);
}
}