File size: 6,376 Bytes
4a54697 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | //! Polymorphic model engine unifying closed 48-class and open bi-encoder artifacts.
//!
//! Basis: Single runtime dispatch over `Closed(ModelBundle)` and `BiEncoder(BiEncoderBundle)`
//! producing canonical `OpenProgram` values (`to_lisp()` and `to_json()`).
use std::fs;
use std::path::Path;
use serde_json::Value;
use sha2::{Digest, Sha256};
use crate::biencoder::{BIENCODER_MODEL_TYPE, BiEncoderBundle, CompiledCatalog};
use crate::catalog::{ActionCatalog, CatalogError, OpenAction, OpenProgram};
use crate::config::{ConfigError, Thresholds};
use crate::episodic::EpisodicMemory;
use crate::inference::{InferenceError, predict_with_episodic};
use crate::model::{ModelBundle, ModelError};
/// Polymorphic inference engine supporting both historical 48-action and open bi-encoder models.
pub enum ModelEngine {
/// Legacy fixed 48-action linear classifier.
Closed {
/// Loaded closed-set model bundle.
bundle: ModelBundle,
/// Builtin 48-action catalog for uniform `OpenProgram` conversion.
builtin: ActionCatalog,
},
/// Open-vocabulary dual-tower bi-encoder with pre-encoded catalog embeddings.
BiEncoder {
/// Loaded dual-tower weights and tokenizer metadata.
bundle: BiEncoderBundle,
/// Pre-encoded active catalog matrix.
compiled: CompiledCatalog,
/// SHA-256 of the last external `catalog.json` compiled into `compiled`.
compiled_digest: Option<[u8; 32]>,
},
}
/// Inspect `<directory>/config.json` to determine whether it names a bi-encoder artifact.
pub fn is_biencoder_artifact(directory: &Path) -> Result<bool, ModelError> {
let raw = fs::read(directory.join("config.json"))?;
let value: Value = serde_json::from_slice(&raw).map_err(ConfigError::Json)?;
Ok(value.get("model_type").and_then(Value::as_str) == Some(BIENCODER_MODEL_TYPE))
}
impl ModelEngine {
/// Load either a `BiEncoder` or legacy `Closed` model from `directory`.
pub fn load(directory: impl AsRef<Path>) -> Result<Self, ModelError> {
let directory = directory.as_ref();
if is_biencoder_artifact(directory)? {
let bundle = BiEncoderBundle::load(directory)?;
let compiled = bundle
.compile_catalog(&bundle.default_catalog)
.map_err(|_| ConfigError::Metadata("failed to compile default catalog"))?;
Ok(Self::BiEncoder {
bundle,
compiled,
compiled_digest: None,
})
} else {
let bundle = ModelBundle::load(directory)?;
Ok(Self::Closed {
bundle,
builtin: ActionCatalog::builtin(),
})
}
}
/// Replace the active `ActionCatalog` on a `BiEncoder` engine without reloading weights.
pub fn set_catalog(&mut self, catalog: &ActionCatalog) -> Result<(), InferenceError> {
if let Self::BiEncoder {
bundle,
compiled,
compiled_digest,
} = self
{
*compiled = bundle.compile_catalog(catalog)?;
*compiled_digest = None;
}
Ok(())
}
/// Hot-reload `<path>` into `compiled` only when its SHA-256 digest changes on disk.
pub fn refresh_catalog_optional(&mut self, path: &Path) -> Result<(), String> {
let Self::BiEncoder {
bundle,
compiled,
compiled_digest,
} = self
else {
return Ok(());
};
match fs::read(path) {
Ok(bytes) => {
let hash: [u8; 32] = Sha256::digest(&bytes).into();
if *compiled_digest == Some(hash) {
return Ok(());
}
let catalog =
ActionCatalog::from_bytes(&bytes).map_err(|err: CatalogError| err.to_string())?;
*compiled = bundle
.compile_catalog(&catalog)
.map_err(|err| err.to_string())?;
*compiled_digest = Some(hash);
Ok(())
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
if compiled_digest.is_some() {
*compiled = bundle
.compile_catalog(&bundle.default_catalog)
.map_err(|e| e.to_string())?;
*compiled_digest = None;
}
Ok(())
}
Err(err) => Err(err.to_string()),
}
}
/// Return whether this engine supports open-vocabulary catalogs (`BiEncoder`).
pub const fn is_open(&self) -> bool {
matches!(self, Self::BiEncoder { .. })
}
/// Return calibrated runtime thresholds of the loaded model.
pub fn thresholds(&self) -> Thresholds {
match self {
Self::Closed { bundle, .. } => bundle.metadata.thresholds,
Self::BiEncoder { bundle, .. } => bundle.metadata.thresholds,
}
}
/// Borrow the active `ActionCatalog` (48 builtin for `Closed`, dynamic for `BiEncoder`).
pub fn catalog(&self) -> &ActionCatalog {
match self {
Self::Closed { builtin, .. } => builtin,
Self::BiEncoder { compiled, .. } => &compiled.catalog,
}
}
/// Predict one or two validated operations, consulting optional `episodic` and `active_modes`.
pub fn predict(
&self,
command: &str,
episodic: Option<&EpisodicMemory>,
active_modes: Option<&[String]>,
) -> Result<OpenProgram, InferenceError> {
match self {
Self::Closed { bundle, builtin } => {
let program = predict_with_episodic(bundle, episodic, command)?;
let mut open_actions = Vec::with_capacity(program.actions().len());
for act in program.actions() {
let spec = builtin
.get(act.kind().label())
.ok_or(InferenceError::InvalidScores)?;
open_actions.push(OpenAction::new(spec, act.name().map(str::to_owned))?);
}
Ok(OpenProgram::new(open_actions)?)
}
Self::BiEncoder {
bundle, compiled, ..
} => bundle.predict_open(compiled, episodic, active_modes, command),
}
}
}
|