crates/state/host/src/profile.rs 25.7 KiB 760 lines Raw
1 //! The hardware profile that a bundle was built for.2 //!3 //! A bundle is one model on one target. `target.toml` records that target, and4 //! the host checks the record before it spawns a child (spec section 16.1,5 //! requirements R6 and R34, decision D17). The check names the devices that the6 //! bind selected: a mixed host must not judge a bundle by a card that the7 //! bundle does not use. A warning-only mode would start a child that cannot8 //! allocate, so every failure is a refusal that names the field, the required9 //! value, and the measured value.10 11 use std::fmt;12 use std::fs;13 use std::path::Path;14 15 use crate::Host;16 17 /// Bytes in one mebibyte. `target.toml` counts device memory in MB, while the18 /// driver reports bytes, so the comparison needs one named factor.19 const MIB: u64 = 1 << 20;20 21 /// The budgets that a bundle declares for its work.22 ///23 /// The values are absent when the file omits the key. They are the bundle's24 /// statement about itself, not a measurement of the machine, so the host25 /// carries them to the caller instead of checking them here.26 #[derive(Clone, PartialEq, Eq, Debug, Default)]27 pub struct Limits {28     /// The most jobs that one load may run at once.29     pub max_inflight: Option<u16>,30     /// The largest part, in bytes, that the bundle accepts.31     pub max_part_bytes: Option<u64>,32     /// The longest load that the bundle budgets, in milliseconds.33     pub load_ms: Option<u32>,34     /// The longest wait for an HTTP engine to answer `/health`, in35     /// milliseconds. A binder reads it; the host carries it unchanged.36     pub start_ms: Option<u32>,37     /// How the bundle accounts for memory, as its own word. `declared` names38     /// the catalogue number; `split` names a resident set that is partly on the39     /// selected devices and partly in host RAM.40     pub accounting: Option<String>,41     /// Per-device resident bytes for `accounting = "split"`. The order is the42     /// target's own device order, which is also the bind's order.43     pub vram_bytes: Option<Vec<u64>>,44     /// Host-RAM resident bytes for `accounting = "split"`.45     pub ram_bytes: Option<u64>,46 }47 48 /// The target that a bundle declares.49 #[derive(Clone, PartialEq, Eq, Debug)]50 pub struct Profile {51     /// The name that the operator and the deploy file use.52     pub name: String,53     /// The backend that the devices must speak: `cuda`, `rocm`, `vulkan`,54     /// `metal`, or `cpu`. A selected device whose id names another backend is55     /// refused.56     pub backend: String,57     /// The architectures that the bundle has a binary for.58     pub arch: Vec<String>,59     /// The compute capability of each selected device, as `sm00` or `gfx0000`.60     /// A missing value does not constrain the device.61     pub compute: Option<String>,62     /// The least number of devices that the bundle needs.63     pub devices: u32,64     /// The device memory that the bundle needs, in MB, in the order of the65     /// bind's selected devices.66     pub vram_mb: Vec<u64>,67     /// The lowest driver version that the engine was built against.68     pub driver_min: Option<String>,69     /// The lowest CUDA runtime that the engine was built against.70     pub cuda_min: Option<String>,71     /// The libraries that the engine links: `name` or `name>=major`.72     pub requires: Vec<String>,73     /// The budgets from `[limits]`.74     pub limits: Limits,75 }76 77 /// One field that the host does not meet.78 ///79 /// Both values travel together because a refusal that names only the80 /// requirement leaves the operator to guess what the machine reported.81 #[derive(Clone, PartialEq, Eq, Debug)]82 pub struct Mismatch {83     /// The profile field that failed.84     pub field: &'static str,85     /// The value from `target.toml`.86     pub required: String,87     /// The value from the host probe.88     pub measured: String,89 }90 91 /// The reason a profile was refused.92 #[derive(Clone, PartialEq, Eq, Debug)]93 pub enum ProfileError {94     /// The file could not be read.95     Io(String),96     /// A line is outside the supported subset, or a field is absent. A field97     /// that is absent points at the `[target]` line because the file does not98     /// give the missing key a line of its own.99     Syntax {100         /// The one-based line number.101         line: usize,102         /// What the parser found and what it expected.103         message: String,104     },105 }106 107 impl fmt::Display for ProfileError {108     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {109         match self {110             ProfileError::Io(why) => write!(f, "cannot read the target profile: {why}"),111             ProfileError::Syntax { line, message } => write!(f, "line {line}: {message}"),112         }113     }114 }115 116 impl std::error::Error for ProfileError {}117 118 impl Profile {119     /// Reads a `target.toml`.120     ///121     /// An unknown key and a missing required key are errors. A profile that122     /// skipped an unknown line would claim a target that the bundle never123     /// declared.124     pub fn read(path: &Path) -> Result<Profile, ProfileError> {125         let text = fs::read_to_string(path).map_err(|why| ProfileError::Io(why.to_string()))?;126         Profile::parse(&text)127     }128 129     /// Whether this host meets every field of the profile on the selected130     /// devices.131     ///132     /// `devices` is the bind's list, not every device that the machine has.133     /// A mixed host can hold a card that the bundle does not target; that card134     /// must not decide the check. The checks run in profile order and stop at135     /// the first failure. The caller refuses the bundle on any mismatch136     /// (requirement R34).137     pub fn check<D: AsRef<str>>(&self, host: &Host, devices: &[D]) -> Result<(), Mismatch> {138         if !self.arch.iter().any(|arch| arch == &host.arch) {139             return Err(Mismatch {140                 field: "arch",141                 required: self.arch.join(","),142                 measured: host.arch.clone(),143             });144         }145 146         let count = u64::try_from(devices.len()).unwrap_or(u64::MAX);147         if count < u64::from(self.devices) {148             return Err(Mismatch {149                 field: "devices",150                 required: self.devices.to_string(),151                 measured: count.to_string(),152             });153         }154 155         // Resolve the selected devices once. A selected name that the host156         // does not expose is a refusal with the name, not a count that hides157         // which card is absent.158         let mut selected = Vec::with_capacity(devices.len());159         for device in devices {160             let device = device.as_ref();161             let Some(gpu) = host.gpu(device) else {162                 return Err(Mismatch {163                     field: "devices",164                     required: device.to_string(),165                     measured: "absent".to_string(),166                 });167             };168             if gpu.backend() != self.backend {169                 return Err(Mismatch {170                     field: "backend",171                     required: self.backend.clone(),172                     measured: gpu.backend().to_string(),173                 });174             }175             selected.push(gpu);176         }177 178         if let Some(compute) = &self.compute {179             if selected.is_empty() {180                 return Err(Mismatch {181                     field: "compute",182                     required: compute.clone(),183                     measured: "unknown".to_string(),184                 });185             }186             for gpu in &selected {187                 let measured = gpu.compute.clone();188                 if measured.as_deref() != Some(compute.as_str()) {189                     return Err(Mismatch {190                         field: "compute",191                         required: compute.clone(),192                         measured: measured.unwrap_or_else(|| "unknown".to_string()),193                     });194                 }195             }196         }197 198         for (index, wanted) in self.vram_mb.iter().enumerate() {199             let required = wanted.saturating_mul(MIB);200             let Some(gpu) = selected.get(index) else {201                 return Err(Mismatch {202                     field: "vram_mb",203                     required: required.to_string(),204                     measured: "none".to_string(),205                 });206             };207             match gpu.bytes {208                 Some(bytes) if bytes >= required => {}209                 Some(bytes) => {210                     return Err(Mismatch {211                         field: "vram_mb",212                         required: required.to_string(),213                         measured: bytes.to_string(),214                     });215                 }216                 None => {217                     return Err(Mismatch {218                         field: "vram_mb",219                         required: required.to_string(),220                         measured: "unknown".to_string(),221                     });222                 }223             }224         }225 226         if self.backend != "cuda"227             && let Some(required) = &self.cuda_min228         {229             return Err(Mismatch {230                 field: "cuda_min",231                 required: required.clone(),232                 measured: format!("{} target", self.backend),233             });234         }235 236         if let Some(required) = self.limits.ram_bytes {237             let measured = host.gpu("cpu:0").and_then(|gpu| gpu.bytes);238             match measured {239                 Some(bytes) if bytes >= required => {}240                 Some(bytes) => {241                     return Err(Mismatch {242                         field: "ram_bytes",243                         required: required.to_string(),244                         measured: bytes.to_string(),245                     });246                 }247                 None => {248                     return Err(Mismatch {249                         field: "ram_bytes",250                         required: required.to_string(),251                         measured: "unknown".to_string(),252                     });253                 }254             }255         }256 257         if let Some(required) = &self.driver_min {258             let Some(measured) = &host.driver else {259                 return Err(Mismatch {260                     field: "driver_min",261                     required: required.clone(),262                     measured: "unknown".to_string(),263                 });264             };265             if !version_at_least(measured, required) {266                 return Err(Mismatch {267                     field: "driver_min",268                     required: required.clone(),269                     measured: measured.clone(),270                 });271             }272         }273 274         if let Some(required) = &self.cuda_min {275             let Some(measured) = &host.cuda else {276                 return Err(Mismatch {277                     field: "cuda_min",278                     required: required.clone(),279                     measured: "unknown".to_string(),280                 });281             };282             if !version_at_least(measured, required) {283                 return Err(Mismatch {284                     field: "cuda_min",285                     required: required.clone(),286                     measured: measured.clone(),287                 });288             }289         }290 291         for require in &self.requires {292             if !host.has_library(require) {293                 return Err(Mismatch {294                     field: "requires",295                     required: require.clone(),296                     measured: "absent".to_string(),297                 });298             }299         }300 301         Ok(())302     }303 304     fn parse(text: &str) -> Result<Profile, ProfileError> {305         let mut target = Builder::default();306         let mut section: Option<Section> = None;307         let mut target_line = 1;308 309         for (index, raw) in text.lines().enumerate() {310             let line = index + 1;311             let content = strip_comment(raw).trim();312             if content.is_empty() {313                 continue;314             }315             match content {316                 "[target]" => {317                     section = Some(Section::Target);318                     target_line = line;319                     continue;320                 }321                 "[limits]" => {322                     section = Some(Section::Limits);323                     continue;324                 }325                 _ => {}326             }327             if content.starts_with('[') {328                 return Err(syntax(line, "expected [target] or [limits]"));329             }330 331             let (key, value) = parse_pair(content, line)?;332             match section {333                 Some(Section::Target) => target_key(&mut target, &key, value, line)?,334                 Some(Section::Limits) => limits_key(&mut target.limits, &key, value, line)?,335                 None => return Err(syntax(line, "key outside a section")),336             }337         }338 339         let missing = |key: &str| syntax(target_line, format!("target.toml has no {key}"));340         let profile = Profile {341             name: target.name.ok_or_else(|| missing("name"))?,342             backend: target.backend.ok_or_else(|| missing("backend"))?,343             arch: target.arch.ok_or_else(|| missing("arch"))?,344             compute: target.compute,345             devices: target.devices.ok_or_else(|| missing("devices"))?,346             vram_mb: target.vram_mb.ok_or_else(|| missing("vram_mb"))?,347             driver_min: target.driver_min,348             cuda_min: target.cuda_min,349             requires: target.requires.unwrap_or_default(),350             limits: target.limits,351         };352         if profile.limits.accounting.as_deref() == Some("split") {353             let vram = profile354                 .limits355                 .vram_bytes356                 .as_ref()357                 .ok_or_else(|| syntax(target_line, "accounting split needs vram_bytes"))?;358             if vram.len() != profile.devices as usize {359                 return Err(syntax(360                     target_line,361                     format!(362                         "vram_bytes has {} values for {} devices",363                         vram.len(),364                         profile.devices365                     ),366                 ));367             }368             if profile.limits.ram_bytes.is_none() {369                 return Err(syntax(target_line, "accounting split needs ram_bytes"));370             }371             for (index, bytes) in vram.iter().enumerate() {372                 let capacity = profile373                     .vram_mb374                     .get(index)375                     .copied()376                     .unwrap_or(0)377                     .saturating_mul(MIB);378                 if *bytes > capacity {379                     return Err(syntax(380                         target_line,381                         format!("vram_bytes[{index}] is above vram_mb"),382                     ));383                 }384             }385         } else if profile.limits.vram_bytes.is_some() || profile.limits.ram_bytes.is_some() {386             return Err(syntax(387                 target_line,388                 "vram_bytes and ram_bytes need accounting = \"split\"",389             ));390         }391         Ok(profile)392     }393 394     /// The resident split that the target declares, if it declares one.395     ///396     /// The first value is one byte count per selected device; the second is the397     /// bytes that the bundle expects in host RAM. The caller checks both parts398     /// against the same memory seam that measured the load.399     pub fn split_resident(&self) -> Option<(Vec<u64>, u64)> {400         if self.limits.accounting.as_deref() != Some("split") {401             return None;402         }403         Some((404             self.limits.vram_bytes.clone().unwrap_or_default(),405             self.limits.ram_bytes.unwrap_or(0),406         ))407     }408 }409 410 /// Which table the parser is inside.411 #[derive(Clone, Copy)]412 enum Section {413     Target,414     Limits,415 }416 417 /// The `[target]` values before the required ones are checked.418 #[derive(Default)]419 struct Builder {420     name: Option<String>,421     backend: Option<String>,422     arch: Option<Vec<String>>,423     compute: Option<String>,424     devices: Option<u32>,425     vram_mb: Option<Vec<u64>>,426     driver_min: Option<String>,427     cuda_min: Option<String>,428     requires: Option<Vec<String>>,429     limits: Limits,430 }431 432 /// A value in the supported subset: a quoted string, an integer, or an array433 /// of either.434 enum Value {435     Str(String),436     Int(u64),437     Array(Vec<Value>),438 }439 440 impl Value {441     /// The name that a kind mismatch uses.442     fn kind(&self) -> &'static str {443         match self {444             Value::Str(_) => "string",445             Value::Int(_) => "integer",446             Value::Array(_) => "array",447         }448     }449 }450 451 fn syntax(line: usize, message: impl Into<String>) -> ProfileError {452     ProfileError::Syntax {453         line,454         message: message.into(),455     }456 }457 458 fn target_key(459     target: &mut Builder,460     key: &str,461     value: Value,462     line: usize,463 ) -> Result<(), ProfileError> {464     match key {465         "name" => target.name = Some(string(value, key, line)?),466         "backend" => target.backend = Some(string(value, key, line)?),467         "arch" => target.arch = Some(strings(value, key, line)?),468         "compute" => target.compute = Some(string(value, key, line)?),469         "devices" => {470             let number = integer(value, key, line)?;471             target.devices = Some(472                 u32::try_from(number)473                     .map_err(|_| syntax(line, format!("{key} is larger than {}", u32::MAX)))?,474             );475         }476         "vram_mb" => target.vram_mb = Some(integers(value, key, line)?),477         "driver_min" => target.driver_min = Some(string(value, key, line)?),478         "cuda_min" => target.cuda_min = Some(string(value, key, line)?),479         "requires" => target.requires = Some(strings(value, key, line)?),480         // `sharing` belongs to the deploy decision, not to the hardware probe.481         "sharing" => {482             string(value, key, line)?;483         }484         _ => return Err(unknown(line, key)),485     }486     Ok(())487 }488 489 /// A limit is a budget of the bundle, not a property of the machine. The490 /// parser keeps every value on `Profile` so the caller does not have to read491 /// the file a second time to find out what the bundle promised.492 fn limits_key(493     limits: &mut Limits,494     key: &str,495     value: Value,496     line: usize,497 ) -> Result<(), ProfileError> {498     match key {499         "max_inflight" => {500             let number = integer(value, key, line)?;501             limits.max_inflight = Some(502                 u16::try_from(number)503                     .map_err(|_| syntax(line, format!("{key} is larger than {}", u16::MAX)))?,504             );505         }506         "max_part_bytes" => limits.max_part_bytes = Some(integer(value, key, line)?),507         "load_ms" => {508             let number = integer(value, key, line)?;509             limits.load_ms = Some(510                 u32::try_from(number)511                     .map_err(|_| syntax(line, format!("{key} is larger than {}", u32::MAX)))?,512             );513         }514         "start_ms" => {515             let number = integer(value, key, line)?;516             limits.start_ms = Some(517                 u32::try_from(number)518                     .map_err(|_| syntax(line, format!("{key} is larger than {}", u32::MAX)))?,519             );520         }521         "accounting" => limits.accounting = Some(string(value, key, line)?),522         "vram_bytes" => limits.vram_bytes = Some(integers(value, key, line)?),523         "ram_bytes" => limits.ram_bytes = Some(integer(value, key, line)?),524         _ => return Err(unknown(line, key)),525     }526     Ok(())527 }528 529 fn unknown(line: usize, key: &str) -> ProfileError {530     syntax(line, format!("unknown key {key}"))531 }532 533 /// Cuts a comment at the first `#` that is outside a string.534 fn strip_comment(line: &str) -> &str {535     let mut in_string = false;536     let mut escaped = false;537     for (index, c) in line.char_indices() {538         if in_string {539             if escaped {540                 escaped = false;541             } else if c == '\\' {542                 escaped = true;543             } else if c == '"' {544                 in_string = false;545             }546         } else if c == '"' {547             in_string = true;548         } else if c == '#' {549             return &line[..index];550         }551     }552     line553 }554 555 fn is_bare_key(key: &str) -> bool {556     !key.is_empty() && key.bytes().all(|b| b.is_ascii_lowercase() || b == b'_')557 }558 559 fn parse_pair(text: &str, line: usize) -> Result<(String, Value), ProfileError> {560     let equals = text561         .find('=')562         .ok_or_else(|| syntax(line, "expected key = value"))?;563     let key = text[..equals].trim();564     if !is_bare_key(key) {565         return Err(syntax(line, format!("key {key:?} is not [a-z_]+")));566     }567     let mut parser = ValueParser {568         text: text[equals + 1..].trim(),569         pos: 0,570         line,571     };572     let value = parser.value()?;573     parser.space();574     if !parser.done() {575         return Err(syntax(line, "trailing text after the value"));576     }577     Ok((key.to_string(), value))578 }579 580 fn string(value: Value, key: &str, line: usize) -> Result<String, ProfileError> {581     match value {582         Value::Str(text) => Ok(text),583         other => Err(syntax(584             line,585             format!("{key} needs a string, found {}", other.kind()),586         )),587     }588 }589 590 fn strings(value: Value, key: &str, line: usize) -> Result<Vec<String>, ProfileError> {591     match value {592         Value::Array(items) => items593             .into_iter()594             .map(|item| string(item, key, line))595             .collect(),596         other => Err(syntax(597             line,598             format!("{key} needs an array, found {}", other.kind()),599         )),600     }601 }602 603 fn integers(value: Value, key: &str, line: usize) -> Result<Vec<u64>, ProfileError> {604     match value {605         Value::Array(items) => items606             .into_iter()607             .map(|item| integer(item, key, line))608             .collect(),609         other => Err(syntax(610             line,611             format!("{key} needs an array, found {}", other.kind()),612         )),613     }614 }615 616 fn integer(value: Value, key: &str, line: usize) -> Result<u64, ProfileError> {617     match value {618         Value::Int(number) => Ok(number),619         other => Err(syntax(620             line,621             format!("{key} needs an integer, found {}", other.kind()),622         )),623     }624 }625 626 /// Whether a dotted version is at least another one, compared per component.627 ///628 /// A version has no single numeric value: `13.5` is above `9.10`, and a string629 /// comparison would say the opposite. A component that a side omits is zero, so630 /// `550` equals `550.0`.631 fn version_at_least(measured: &str, required: &str) -> bool {632     let mut measured = measured.split('.');633     let mut required = required.split('.');634     loop {635         let next = (measured.next(), required.next());636         if next == (None, None) {637             return true;638         }639         let (Some(got), Some(want)) = (component(next.0), component(next.1)) else {640             return false;641         };642         if got != want {643             return got > want;644         }645     }646 }647 648 /// One version component, where an omitted component is zero.649 fn component(text: Option<&str>) -> Option<u64> {650     match text {651         None => Some(0),652         Some(text) => text.parse().ok(),653     }654 }655 656 /// A cursor over one value on one line.657 struct ValueParser<'a> {658     text: &'a str,659     pos: usize,660     line: usize,661 }662 663 impl ValueParser<'_> {664     fn peek(&self) -> Option<char> {665         self.text[self.pos..].chars().next()666     }667 668     fn bump(&mut self) -> Option<char> {669         let c = self.peek()?;670         self.pos += c.len_utf8();671         Some(c)672     }673 674     fn done(&self) -> bool {675         self.pos == self.text.len()676     }677 678     fn space(&mut self) {679         while matches!(self.peek(), Some(' ' | '\t')) {680             self.pos += 1;681         }682     }683 684     fn value(&mut self) -> Result<Value, ProfileError> {685         self.space();686         match self.peek() {687             Some('"') => self.string().map(Value::Str),688             Some('[') => self.array(),689             Some(c) if c.is_ascii_digit() => self.integer().map(Value::Int),690             Some(c) => Err(syntax(self.line, format!("unexpected {c:?}"))),691             None => Err(syntax(self.line, "missing value")),692         }693     }694 695     fn string(&mut self) -> Result<String, ProfileError> {696         self.bump();697         let mut out = String::new();698         loop {699             let c = self700                 .bump()701                 .ok_or_else(|| syntax(self.line, "unclosed string"))?;702             match c {703                 '"' => return Ok(out),704                 '\\' => {705                     let escape = self706                         .bump()707                         .ok_or_else(|| syntax(self.line, "unclosed string"))?;708                     match escape {709                         '"' => out.push('"'),710                         '\\' => out.push('\\'),711                         'n' => out.push('\n'),712                         't' => out.push('\t'),713                         other => {714                             return Err(syntax(715                                 self.line,716                                 format!("escape \\{other} is not supported"),717                             ));718                         }719                     }720                 }721                 other => out.push(other),722             }723         }724     }725 726     fn integer(&mut self) -> Result<u64, ProfileError> {727         let start = self.pos;728         while matches!(self.peek(), Some(c) if c.is_ascii_digit()) {729             self.bump();730         }731         let text = &self.text[start..self.pos];732         text.parse::<u64>()733             .map_err(|_| syntax(self.line, format!("integer {text} does not fit u64")))734     }735 736     fn array(&mut self) -> Result<Value, ProfileError> {737         self.bump();738         let mut items: Vec<Value> = Vec::new();739         self.space();740         if self.peek() == Some(']') {741             self.bump();742             return Ok(Value::Array(items));743         }744         loop {745             let item = self.value()?;746             if let Some(first) = items.first()747                 && first.kind() != item.kind()748             {749                 return Err(syntax(self.line, "array values have different kinds"));750             }751             items.push(item);752             self.space();753             match self.bump() {754                 Some(',') => self.space(),755                 Some(']') => return Ok(Value::Array(items)),756                 _ => return Err(syntax(self.line, "expected , or ] in an array")),757             }758         }759     }760 }