crates/edge/bind/src/catalogue.rs 8.5 KiB 248 lines Raw
1 //! The catalogue that a bound bundle declares.2 //!3 //! The binder maps every capability that the model file declares and that the4 //! neutral bridge can carry. The lifecycle words are defaults for the engine5 //! kind, and a model file may override them because only the author knows6 //! where the runtime really stops.7 8 use std::collections::BTreeMap;9 use std::path::Path;10 11 use inf3r_bundle::{Bundle, EngineKind};12 use inf3r_proto::body::{13     CONTEXT_LIMIT, Cancel, Capability, Catalogue, KV_BYTES_PER_TOKEN_LIMIT, Model as WireModel,14     PartKind, Queue, Stops, Target,15 };16 17 use crate::BindError;18 use crate::manifest::{CapabilitySpec, ModelSpec, TargetProfile, read_models, read_target};19 20 /// The channel that carries answer text.21 pub const TEXT_CHANNEL: &str = "text";22 23 /// The channel that carries reasoning or prefill progress.24 pub const PROGRESS_CHANNEL: &str = "progress";25 26 /// The MIME of a text or progress chunk.27 pub const TEXT_MIME: &str = "text/plain; charset=utf-8";28 29 /// The capability that this binding serves.30 pub const CHAT: &str = "chat";31 32 /// Builds the catalogue from the bundle's own files.33 ///34 /// `--describe` uses this path so that it can answer before any engine starts35 /// and without opening a weight file.36 pub fn read_catalogue(dir: &Path, bundle: &Bundle) -> Result<Catalogue, BindError> {37     let models = read_models(dir)?;38     let (model, aliases) = split(&models, dir)?;39     let target = read_target(dir, &bundle.target);40     Ok(build(bundle, model, &aliases, target, 0))41 }42 43 /// Splits the model files into the one that holds the weights and its aliases.44 ///45 /// An alias must name the model that this process serves. A chain, or a name46 /// that no file defines, is refused here because the catalogue would otherwise47 /// carry a name that the binder could not answer.48 pub fn split<'a>(49     models: &'a [ModelSpec],50     dir: &Path,51 ) -> Result<(&'a ModelSpec, Vec<&'a ModelSpec>), BindError> {52     let mut primaries = models.iter().filter(|model| model.alias_of.is_none());53     let model = primaries.next().ok_or_else(|| BindError::Alias {54         dir: dir.join("models"),55         why: "every model file is an alias".to_string(),56     })?;57     if primaries.next().is_some() {58         return Err(BindError::Alias {59             dir: dir.join("models"),60             why: "two model files hold weights; keep one and alias the other".to_string(),61         });62     }63     let mut aliases = Vec::new();64     for alias in models {65         let Some(source) = &alias.alias_of else {66             continue;67         };68         if source != &model.serve {69             return Err(BindError::Alias {70                 dir: dir.join("models"),71                 why: format!("{} names {source}, not {}", alias.serve, model.serve),72             });73         }74         aliases.push(alias);75     }76     Ok((model, aliases))77 }78 79 /// Builds the wire catalogue for one model, its aliases, and a measured load.80 pub fn build(81     bundle: &Bundle,82     model: &ModelSpec,83     aliases: &[&ModelSpec],84     target: TargetProfile,85     load_ms: u32,86 ) -> Catalogue {87     let (cancel, stops, queue) = lifecycle(bundle, model);88     let serve = if model.serve.is_empty() {89         bundle.model.clone()90     } else {91         model.serve.clone()92     };93     let capabilities = capabilities(model, bundle.engine, cancel, stops, queue);94     let mut models = vec![WireModel {95         serve: serve.clone(),96         alias_of: None,97         weights_bytes: model.bytes,98         load_ms,99         capabilities,100     }];101     for alias in aliases {102         models.push(WireModel {103             serve: alias.serve.clone(),104             alias_of: Some(serve.clone()),105             weights_bytes: model.bytes,106             load_ms,107             capabilities: BTreeMap::new(),108         });109     }110     Catalogue {111         target: Target {112             id: target.id,113             backend: target.backend,114             arch: target.arch,115             devices: target.devices,116             vram_mb: target.vram_mb,117         },118         models,119         runtime: None,120         cache: None,121     }122 }123 124 /// The capabilities of the primary model.125 ///126 /// The binder knows one request shape per capability that it can map. A127 /// section for a capability outside that set is not in the catalogue: a name128 /// that the binder could not answer would be a false claim, and the gate would129 /// be right to fail it.130 fn capabilities(131     model: &ModelSpec,132     engine: EngineKind,133     cancel: Cancel,134     stops: Stops,135     queue: Queue,136 ) -> BTreeMap<String, Capability> {137     let mut limits = BTreeMap::new();138     if let Some(context) = model.context {139         limits.insert(CONTEXT_LIMIT.to_string(), context);140     }141     if let Some(bytes) = model.kv_bytes_per_token {142         limits.insert(KV_BYTES_PER_TOKEN_LIMIT.to_string(), bytes);143     }144     // A model file with no capability section keeps the historical implicit145     // chat. A file that names capabilities carries exactly those names.146     let mut out = BTreeMap::new();147     for (name, spec) in &model.capabilities {148         let Some(shape) = shape(name, engine) else {149             continue;150         };151         let parts = spec.parts.clone().unwrap_or(shape.parts);152         out.insert(153             name.clone(),154             Capability {155                 vocab: vocab(spec, name),156                 parts,157                 channels: shape.channels.iter().map(|ch| (*ch).to_string()).collect(),158                 limits: if name == CHAT {159                     limits.clone()160                 } else {161                     BTreeMap::new()162                 },163                 cancel: cancel.clone(),164                 stops: stops.clone(),165                 queue: queue.clone(),166             },167         );168     }169     out170 }171 172 fn vocab(spec: &CapabilitySpec, name: &str) -> String {173     if spec.vocab.is_empty() {174         format!("{name}.v1")175     } else {176         spec.vocab.clone()177     }178 }179 180 /// The input parts and output channels of one capability.181 struct Shape {182     parts: Vec<PartKind>,183     channels: &'static [&'static str],184 }185 186 fn shape(name: &str, engine: EngineKind) -> Option<Shape> {187     let http = engine == EngineKind::Http;188     let (parts, channels): (Vec<PartKind>, &'static [&'static str]) = match name {189         CHAT if http => (190             vec![191                 PartKind::Text,192                 PartKind::Image,193                 PartKind::Audio,194                 PartKind::Json,195             ],196             &[TEXT_CHANNEL, PROGRESS_CHANNEL],197         ),198         // The binary chat bridge is a prompt of text lines; HTTP chat carries199         // the OpenAI content parts and a reasoning progress channel.200         CHAT => (vec![PartKind::Text], &[TEXT_CHANNEL]),201         "embed" => (vec![PartKind::Text], &["embedding"]),202         "rerank" => (vec![PartKind::Text, PartKind::Json], &["embedding"]),203         "stt" if http => (vec![PartKind::Audio, PartKind::Text], &[TEXT_CHANNEL]),204         "stt" => (205             vec![PartKind::Audio, PartKind::Text],206             &[TEXT_CHANNEL, "tokens", PROGRESS_CHANNEL],207         ),208         "tts" if http => (vec![PartKind::Text], &["pcm"]),209         "tts" => (vec![PartKind::Text], &["pcm", PROGRESS_CHANNEL]),210         "image-gen" if http => (vec![PartKind::Text], &["image"]),211         "image-gen" => (212             vec![PartKind::Text, PartKind::Image],213             &["image", PROGRESS_CHANNEL],214         ),215         "image-edit" if http => (vec![PartKind::Image, PartKind::Text], &["image"]),216         "image-edit" => (217             vec![PartKind::Image, PartKind::Text],218             &["image", PROGRESS_CHANNEL],219         ),220         "music" => (221             vec![PartKind::Text, PartKind::Audio],222             &["pcm", PROGRESS_CHANNEL],223         ),224         "t2v-gen" => (225             vec![PartKind::Text, PartKind::Image],226             &["clip", PROGRESS_CHANNEL],227         ),228         "i2v-gen" => (229             vec![PartKind::Image, PartKind::Text],230             &["clip", PROGRESS_CHANNEL],231         ),232         "decide" | "extract" => (vec![PartKind::Text, PartKind::Json], &["decision"]),233         _ => return None,234     };235     Some(Shape { parts, channels })236 }237 238 fn lifecycle(bundle: &Bundle, model: &ModelSpec) -> (Cancel, Stops, Queue) {239     let (cancel, stops, queue) = match bundle.engine {240         inf3r_bundle::EngineKind::Binary => (Cancel::Frame, Stops::Native, Queue::None),241         inf3r_bundle::EngineKind::Http => (Cancel::Request, Stops::Native, Queue::Internal),242         _ => (Cancel::Token, Stops::Plugin, Queue::None),243     };244     let cancel = model.cancel.as_deref().map_or(cancel, Cancel::from_str);245     let stops = model.stops_owner.as_deref().map_or(stops, Stops::from_str);246     let queue = model.queue.as_deref().map_or(queue, Queue::from_str);247     (cancel, stops, queue)248 }