crates/edge/bind/src/manifest.rs 14.9 KiB 437 lines Raw
1 //! The two manifests that a binding reads before it builds a catalogue.2 //!3 //! A bound bundle keeps its facts in the same files as an authored one. The4 //! binder reads only the subset that a bound runtime can honour; an unknown key5 //! is ignored because the model file carries authoring facts that a bound6 //! engine does not use.7 8 use std::collections::BTreeMap;9 use std::path::{Path, PathBuf};10 11 use inf3r_proto::body::PartKind;12 13 use crate::BindError;14 15 /// One model file as a bound engine reads it.16 #[derive(Clone, PartialEq, Eq, Debug)]17 pub struct ModelSpec {18     /// The name that clients ask for.19     pub serve: String,20     /// The source of an alias, when this file renames another model.21     pub alias_of: Option<String>,22     /// The weight files, relative to the bundle root.23     pub files: Vec<String>,24     /// Bytes that the ledger reserves for the weights.25     pub bytes: u64,26     /// The vocabulary version of the chat capability.27     pub vocab: String,28     /// The context window, when the model file declares one.29     pub context: Option<u64>,30     /// The KV-cache bytes of one token, when the model file declares them.31     pub kv_bytes_per_token: Option<u64>,32     /// The template name. A bound engine applies its own template.33     pub template: Option<String>,34     /// The stop strings. A bound engine applies them natively or not at all.35     pub stops: Vec<String>,36     /// The lifecycle word for cancels, when the model file overrides it.37     pub cancel: Option<String>,38     /// The lifecycle word for stop stripping, when the file overrides it.39     pub stops_owner: Option<String>,40     /// The lifecycle word for queueing, when the model file overrides it.41     pub queue: Option<String>,42     /// The capability sections that the file declares, by name. The value is43     /// the vocabulary of that capability.44     pub capabilities: BTreeMap<String, CapabilitySpec>,45 }46 47 /// One capability section of a model file.48 #[derive(Clone, PartialEq, Eq, Debug)]49 pub struct CapabilitySpec {50     /// The vocabulary that this capability speaks.51     pub vocab: String,52     /// The input parts, when the file overrides the binder's default.53     pub parts: Option<Vec<PartKind>>,54 }55 56 /// One hardware profile as the catalogue reports it.57 #[derive(Clone, PartialEq, Eq, Debug)]58 pub struct TargetProfile {59     /// The target half of the bundle pair.60     pub id: String,61     /// The backend that the engine uses.62     pub backend: String,63     /// The architectures that the profile names.64     pub arch: Vec<String>,65     /// The number of devices.66     pub devices: u32,67     /// The memory of each device in MiB.68     pub vram_mb: Vec<u32>,69     /// The most jobs that this target runs at once, when it declares one.70     pub max_inflight: Option<u16>,71     /// The longest wait for the engine to become ready, when it declares one.72     pub start_ms: Option<u32>,73 }74 75 /// Reads every model file in sorted name order.76 ///77 /// One file is the model that the bundle serves; every other file is either an78 /// alias or a mistake. The binder keeps aliases so that the catalogue can carry79 /// the second name, but only one file holds the weights and the capabilities.80 pub fn read_models(dir: &Path) -> Result<Vec<ModelSpec>, BindError> {81     let models = dir.join("models");82     let entries = std::fs::read_dir(&models).map_err(|why| BindError::Io {83         path: models.clone(),84         why: why.to_string(),85     })?;86     let mut files: Vec<PathBuf> = Vec::new();87     for entry in entries {88         let path = entry89             .map_err(|why| BindError::Io {90                 path: models.clone(),91                 why: why.to_string(),92             })?93             .path();94         if path95             .extension()96             .is_some_and(|extension| extension == "toml")97         {98             files.push(path);99         }100     }101     files.sort();102     if files.is_empty() {103         return Err(BindError::NoModel {104             dir: models.clone(),105         });106     }107     let mut out = Vec::with_capacity(files.len());108     for path in files {109         let text = std::fs::read_to_string(&path).map_err(|why| BindError::Io {110             path: path.clone(),111             why: why.to_string(),112         })?;113         out.push(parse_model(&text).map_err(|problem| BindError::Manifest {114             path: path.clone(),115             line: problem.line,116             message: problem.message,117         })?);118     }119     Ok(out)120 }121 122 /// Reads the one model file that holds the weights.123 ///124 /// An alias is skipped: it inherits the capabilities of its source, so it125 /// cannot be the source that the binder loads. A directory with only aliases is126 /// a bundle with no model, which is a load failure rather than a guess.127 pub fn read_first_model(dir: &Path) -> Result<ModelSpec, BindError> {128     let models = read_models(dir)?;129     let index = models130         .iter()131         .position(|model| model.alias_of.is_none())132         .ok_or_else(|| BindError::NoModel {133             dir: dir.join("models"),134         })?;135     Ok(models[index].clone())136 }137 138 /// Reads the target file, with the bundle's target name as the fallback.139 ///140 /// The profile describes the machine, but a catalogue must still name a target141 /// when the file is absent. The fallback keeps `--describe` useful without142 /// inventing a device.143 pub fn read_target(dir: &Path, fallback: &str) -> TargetProfile {144     let mut target = TargetProfile {145         id: fallback.to_string(),146         backend: "cpu".to_string(),147         arch: vec![std::env::consts::ARCH.to_string()],148         devices: 0,149         vram_mb: Vec::new(),150         max_inflight: None,151         start_ms: None,152     };153     let Ok(text) = std::fs::read_to_string(dir.join("target.toml")) else {154         return target;155     };156     let mut section = String::new();157     for raw in text.lines() {158         let line = strip_comment(raw).trim();159         if line.is_empty() {160             continue;161         }162         if let Some(name) = section_name(line) {163             section = name.to_string();164             continue;165         }166         let Some((key, value)) = line.split_once('=') else {167             continue;168         };169         if section == "limits" {170             match key.trim() {171                 "max_inflight" => {172                     target.max_inflight = number(value.trim()).and_then(|n| u16::try_from(n).ok())173                 }174                 "start_ms" => {175                     target.start_ms = number(value.trim()).and_then(|n| u32::try_from(n).ok())176                 }177                 _ => {}178             }179             continue;180         }181         if section != "target" {182             continue;183         }184         match key.trim() {185             "name" => target.id = unquote(value.trim()).to_string(),186             "backend" => target.backend = unquote(value.trim()).to_string(),187             "arch" => {188                 if let Some(items) = array(value.trim()) {189                     target.arch = items;190                 }191             }192             "devices" => {193                 if let Some(n) = number(value.trim()) {194                     target.devices = u32::try_from(n).unwrap_or(u32::MAX);195                 }196             }197             "vram_mb" => {198                 if let Some(values) = numbers(value.trim()) {199                     target.vram_mb = values200                         .into_iter()201                         .map(|n| u32::try_from(n).unwrap_or(u32::MAX))202                         .collect();203                 }204             }205             _ => {}206         }207     }208     if target.id.is_empty() {209         target.id = fallback.to_string();210     }211     target212 }213 214 /// A parse problem with the line that caused it.215 struct Problem {216     line: usize,217     message: String,218 }219 220 fn parse_model(text: &str) -> Result<ModelSpec, Problem> {221     let mut model = ModelSpec {222         serve: String::new(),223         alias_of: None,224         files: Vec::new(),225         bytes: 0,226         vocab: "chat.v1".to_string(),227         context: None,228         kv_bytes_per_token: None,229         template: None,230         stops: Vec::new(),231         cancel: None,232         stops_owner: None,233         queue: None,234         capabilities: BTreeMap::new(),235     };236     let mut section = String::new();237     for (index, raw) in text.lines().enumerate() {238         let line = strip_comment(raw).trim();239         if line.is_empty() {240             continue;241         }242         if let Some(name) = section_name(line) {243             section = name.to_string();244             continue;245         }246         let Some((key, value)) = line.split_once('=') else {247             return Err(problem(index + 1, "expected key = value"));248         };249         let key = key.trim();250         let value = value.trim();251         match (section.as_str(), key) {252             ("model", "serve") => model.serve = string(value, index + 1)?.to_string(),253             ("model", "alias_of") => model.alias_of = Some(string(value, index + 1)?.to_string()),254             ("weights", "files") => {255                 model.files = array(value)256                     .ok_or_else(|| problem(index + 1, "files is not an array of strings"))?257             }258             ("weights", "bytes") => {259                 model.bytes = number(value)260                     .ok_or_else(|| problem(index + 1, "bytes is not an unsigned integer"))?261             }262             (section, key) if section.starts_with("capabilities.") => {263                 let name = &section["capabilities.".len()..];264                 if key == "vocab" {265                     let vocab = string(value, index + 1)?.to_string();266                     model267                         .capabilities268                         .entry(name.to_string())269                         .or_insert(CapabilitySpec {270                             vocab: String::new(),271                             parts: None,272                         })273                         .vocab = vocab.clone();274                     if name == "chat" {275                         model.vocab = vocab;276                     }277                 }278                 if key == "parts" {279                     let parts = parse_parts(value, index + 1)?;280                     if let Some(spec) = model.capabilities.get_mut(name) {281                         spec.parts = Some(parts);282                     } else {283                         model.capabilities.insert(284                             name.to_string(),285                             CapabilitySpec {286                                 vocab: default_vocab(name),287                                 parts: Some(parts),288                             },289                         );290                     }291                 }292                 if name == "chat" {293                     match key {294                         "context" => {295                             model.context = Some(number(value).ok_or_else(|| {296                                 problem(index + 1, "context is not an unsigned integer")297                             })?)298                         }299                         "kv_bytes_per_token" => {300                             model.kv_bytes_per_token = Some(number(value).ok_or_else(|| {301                                 problem(index + 1, "kv_bytes_per_token is not an unsigned integer")302                             })?)303                         }304                         "template" => model.template = Some(string(value, index + 1)?.to_string()),305                         "stops" => {306                             if value.starts_with('[') {307                                 model.stops = array(value).ok_or_else(|| {308                                     problem(index + 1, "stops is not an array of strings")309                                 })?;310                             } else {311                                 model.stops_owner = Some(string(value, index + 1)?.to_string());312                             }313                         }314                         "cancel" => model.cancel = Some(string(value, index + 1)?.to_string()),315                         "queue" => model.queue = Some(string(value, index + 1)?.to_string()),316                         _ => {}317                     }318                 }319             }320             _ => {}321         }322     }323     if model.serve.is_empty() {324         return Err(problem(1, "the model file has no serve name"));325     }326     // A model file with no capability section is the old chat-only shape.327     // Once it names any capability, the catalogue carries only those names:328     // a decision model must not claim chat just because the binder exists.329     if model.capabilities.is_empty() {330         model.capabilities.insert(331             "chat".to_string(),332             CapabilitySpec {333                 vocab: model.vocab.clone(),334                 parts: None,335             },336         );337     }338     Ok(model)339 }340 341 fn default_vocab(name: &str) -> String {342     format!("{name}.v1")343 }344 345 fn parse_parts(value: &str, line: usize) -> Result<Vec<PartKind>, Problem> {346     let words = array(value).ok_or_else(|| problem(line, "parts is not an array of strings"))?;347     let mut parts = Vec::with_capacity(words.len());348     for word in words {349         let part = match word.as_str() {350             "text" => PartKind::Text,351             "image" => PartKind::Image,352             "audio" => PartKind::Audio,353             "video" => PartKind::Video,354             "tokens" => PartKind::Tokens,355             "json" => PartKind::Json,356             other => return Err(problem(line, format!("unknown part kind {other}"))),357         };358         parts.push(part);359     }360     Ok(parts)361 }362 363 fn problem(line: usize, message: impl Into<String>) -> Problem {364     Problem {365         line,366         message: message.into(),367     }368 }369 370 fn section_name(line: &str) -> Option<&str> {371     line.strip_prefix('[')372         .and_then(|rest| rest.strip_suffix(']'))373         .map(str::trim)374 }375 376 fn strip_comment(line: &str) -> &str {377     let mut quoted = false;378     for (index, ch) in line.char_indices() {379         match ch {380             '"' => quoted = !quoted,381             '#' if !quoted => return &line[..index],382             _ => {}383         }384     }385     line386 }387 388 fn string(value: &str, line: usize) -> Result<&str, Problem> {389     let value = unquote(value);390     if value.starts_with('"') || value.is_empty() {391         return Err(problem(line, "expected a quoted string"));392     }393     Ok(value)394 }395 396 fn unquote(value: &str) -> &str {397     value398         .strip_prefix('"')399         .and_then(|rest| rest.strip_suffix('"'))400         .or_else(|| {401             value402                 .strip_prefix('\'')403                 .and_then(|rest| rest.strip_suffix('\''))404         })405         .unwrap_or(value)406 }407 408 fn number(value: &str) -> Option<u64> {409     value.parse().ok()410 }411 412 fn array(value: &str) -> Option<Vec<String>> {413     let inner = value.strip_prefix('[')?.strip_suffix(']')?;414     if inner.trim().is_empty() {415         return Some(Vec::new());416     }417     let mut out = Vec::new();418     for item in inner.split(',') {419         let item = item.trim();420         if item.is_empty() {421             continue;422         }423         if !(item.starts_with('"') || item.starts_with('\'')) {424             return None;425         }426         out.push(unquote(item).to_string());427     }428     Some(out)429 }430 431 fn numbers(value: &str) -> Option<Vec<u64>> {432     let inner = value.strip_prefix('[')?.strip_suffix(']')?;433     if inner.trim().is_empty() {434         return Some(Vec::new());435     }436     inner.split(',').map(|item| number(item.trim())).collect()437 }