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
226 lines
7.5 KiB
Rust
226 lines
7.5 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(|_| ())
|
|
}
|
|
}
|
|
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("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() {
|
|
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()),
|
|
};
|
|
devices.push(Device {
|
|
uuid: v[0].to_owned(),
|
|
free,
|
|
eligible,
|
|
});
|
|
}
|
|
if devices.is_empty() {
|
|
return Err("GPU inventory is empty".into());
|
|
}
|
|
Ok(devices)
|
|
}
|
|
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!("no visible non-MIG GPU has {needed} MiB free for cuda_memory; free capacity or select a qualified smaller profile"))?;
|
|
Ok(Selection {
|
|
uuid: device.uuid,
|
|
policy,
|
|
})
|
|
}
|
|
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), async {
|
|
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")?)
|
|
})
|
|
.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()
|
|
);
|
|
}
|
|
}
|