Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Cli list models (#691)

Aleksandr Golokoz2fb9385c7e95
diff --git a/crates/cli/src/interactive/app.rs b/crates/cli/src/interactive/app.rs
new file mode 100644
index 000000000..ba79aeda4
--- /dev/null
+++ b/crates/cli/src/interactive/app.rs
@@ -0,0 +1,94 @@
+use std::io::IsTerminal;
+
+use iocraft::prelude::*;
+use uzu::{
+ engine::{Engine, EngineConfig, EngineError},
+ settings::SettingsError,
+};
+
+use crate::interactive::{
+ components::{AppSettings, Application, Preferences, Theme},
+ model::{ModelResolutionError, resolve_model_id},
+};
+
+#[derive(Debug, Clone, PartialEq, thiserror::Error)]
+#[non_exhaustive]
+pub enum CliError {
+ #[error(transparent)]
+ Engine(#[from] EngineError),
+ #[error(transparent)]
+ ModelResolution(#[from] ModelResolutionError),
+ #[error(transparent)]
+ Settigs(#[from] SettingsError),
+ #[error("Rendering error: {message}")]
+ RenderingError {
+ message: String,
+ },
+}
+
+#[derive(Clone)]
+pub struct CliApplication {
+ engine: Engine,
+}
+
+impl CliApplication {
+ pub async fn create(config: EngineConfig) -> Result<Self, CliError> {
+ let engine = Engine::new(config).await?;
+ Ok(Self::new(engine))
+ }
+
+ pub fn new(engine: Engine) -> Self {
+ Self {
+ engine,
+ }
+ }
+
+ pub async fn run_with_model(
+ &self,
+ model: Option<String>,
+ ) -> Result<(), CliError> {
+ if !std::io::stdout().is_terminal() {
+ return Err(CliError::RenderingError {
+ message: "stdout is not a terminal".to_string(),
+ });
+ }
+
+ let settings = self.engine.settings().await.ok();
+ let theme = match &settings {
+ Some(settings) => Theme::load(settings)?.unwrap_or_default(),
+ None => Theme::default(),
+ };
+ let preferences = match &settings {
+ Some(settings) => Preferences::load(settings)?,
+ None => Preferences::default(),
+ };
+ let app_settings = match &settings {
+ Some(settings) => AppSettings::load(settings)?,
+ None => AppSettings::default(),
+ };
+
+ let requested_model = model.or_else(|| app_settings.selected_model_id.clone());
+ let selected_model = match requested_model {
+ Some(model) => resolve_model_id(&self.engine, model).await?,
+ None => None,
+ };
+
+ element! {
+ Application(
+ engine: Some(self.engine.clone()),
+ settings: settings,
+ theme: Some(theme),
+ preferences: Some(preferences),
+ app_settings: Some(app_settings),
+ model: selected_model,
+ )
+ }
+ .render_loop()
+ .await
+ .map_err(|error| CliError::RenderingError {
+ message: error.to_string(),
+ })?;
+
+ Ok(())
+ }
+}
diff --git a/crates/cli/src/interactive/list.rs b/crates/cli/src/interactive/list.rs
new file mode 100644
index 000000000..ddb76267d
--- /dev/null
+++ b/crates/cli/src/interactive/list.rs
@@ -0,0 +1,59 @@
+use std::collections::HashSet;
+
+use shoji::types::model::Model;
+
+pub struct ModelCheckpoint {
+ pub id: String,
+ pub name: String,
+}
+
+pub fn get_checkpoints(
+ models: &[Model],
+ model_id: &str,
+) -> Vec<ModelCheckpoint> {
+ models
+ .iter()
+ .filter(|model| {
+ let Some(family) = &model.family else {
+ return false;
+ };
+ let Some(properties) = &model.properties else {
+ return false;
+ };
+
+ let family_id = family.identifier.rsplit(':').next().unwrap_or(&family.identifier);
+ format!("{family_id}:{}", properties.identifier) == model_id
+ })
+ .map(|model| ModelCheckpoint {
+ id: model.identifier.clone(),
+ name: model.name(),
+ })
+ .collect()
+}
+
+pub struct ModelFamily {
+ pub id: String,
+ pub name: String,
+}
+
+pub fn get_families(models: &[Model]) -> Vec<ModelFamily> {
+ let mut families = Vec::<ModelFamily>::new();
+ let mut ids_set = HashSet::<String>::new();
+
+ for model in models.iter() {
+ if let Some(ref family) = model.family
+ && let Some(ref properties) = model.properties
+ {
+ let model_id = format!("{}:{}", family.identifier.split(":").last().unwrap(), properties.identifier);
+ if !ids_set.contains(&model_id) {
+ ids_set.insert(model_id.clone());
+ families.push(ModelFamily {
+ id: model_id,
+ name: format!("{} {}", family.metadata.name, properties.metadata.name),
+ })
+ }
+ }
+ }
+
+ families
+}
diff --git a/crates/cli/src/interactive/mod.rs b/crates/cli/src/interactive/mod.rs
index 50850089d..dffd62450 100644
--- a/crates/cli/src/interactive/mod.rs
+++ b/crates/cli/src/interactive/mod.rs
@@ -1,103 +1,78 @@
+use comfy_table::{
+ ContentArrangement, Table,
+ modifiers::{UTF8_ROUND_CORNERS, UTF8_SOLID_INNER_BORDERS},
+ presets::UTF8_FULL,
+};
+use uzu::engine::{Engine, EngineConfig};
+
+use crate::interactive::{
+ app::CliApplication,
+ list::{get_checkpoints, get_families},
+};
+
+mod app;
mod components;
mod flows;
mod helpers;
+mod list;
+mod model;
mod sessions;
-use std::io::IsTerminal;
-
-use components::{Application, Preferences, Theme};
-use iocraft::prelude::*;
-use uzu::{
- engine::{Engine, EngineConfig, EngineError},
- settings::SettingsError,
-};
-
-use crate::interactive::components::AppSettings;
-
-#[derive(Debug, Clone, PartialEq, thiserror::Error)]
-#[non_exhaustive]
-pub enum CliError {
- #[error(transparent)]
- Engine(#[from] EngineError),
- #[error(transparent)]
- Settigs(#[from] SettingsError),
- #[error("Rendering error: {message}")]
- RenderingError {
- message: String,
- },
-}
+const APP_IDENTIFIER: &str = "com.trymirai.cli";
-#[derive(Clone)]
-pub struct CliApplication {
- engine: Engine,
+pub async fn run_interactive(model: Option<String>) -> anyhow::Result<()> {
+ let engine_config = EngineConfig::default().with_application_identifier(APP_IDENTIFIER.to_string());
+ let application = CliApplication::create(engine_config).await?;
+ application.run_with_model(model).await?;
+ Ok(())
}
-impl CliApplication {
- pub fn new(engine: Engine) -> Self {
- Self {
- engine,
- }
+pub async fn run_list_models() -> anyhow::Result<()> {
+ let engine_config = EngineConfig::default().with_application_identifier(APP_IDENTIFIER.to_string());
+ let engine = Engine::new(engine_config).await?;
+ let models = engine.models().await?;
+ if models.is_empty() {
+ return Err(anyhow::anyhow!("No models to run"));
}
- pub async fn run_with_model(
- &self,
- model: Option<String>,
- ) -> Result<(), CliError> {
- if !std::io::stdout().is_terminal() {
- return Err(CliError::RenderingError {
- message: "stdout is not a terminal".to_string(),
- });
- }
-
- let settings = self.engine.settings().await.ok();
- let theme = match &settings {
- Some(settings) => Theme::load(settings)?.unwrap_or_default(),
- None => Theme::default(),
- };
- let preferences = match &settings {
- Some(settings) => Preferences::load(settings)?,
- None => Preferences::default(),
- };
- let app_settings = match &settings {
- Some(settings) => AppSettings::load(settings)?,
- None => AppSettings::default(),
- };
+ let families = get_families(&models);
+ let mut table = Table::new();
+ table
+ .load_preset(UTF8_FULL)
+ .apply_modifier(UTF8_ROUND_CORNERS)
+ .apply_modifier(UTF8_SOLID_INNER_BORDERS)
+ .set_content_arrangement(ContentArrangement::Dynamic)
+ .set_header(vec!["Name", "ID"]);
- let mut selected_model = model;
- if selected_model.is_none() {
- selected_model = app_settings.selected_model_id.clone();
- }
+ for family in &families {
+ table.add_row(vec![&family.name, &family.id]);
+ }
+ println!("{table}");
- element! {
- Application(
- engine: Some(self.engine.clone()),
- settings: settings,
- theme: Some(theme),
- preferences: Some(preferences),
- app_settings: Some(app_settings),
- model: selected_model,
- )
- }
- .render_loop()
- .await
- .map_err(|error| CliError::RenderingError {
- message: error.to_string(),
- })?;
+ Ok(())
+}
- Ok(())
+pub async fn run_list_checkpoints(model_id: String) -> anyhow::Result<()> {
+ let engine_config = EngineConfig::default().with_application_identifier(APP_IDENTIFIER.to_string());
+ let engine = Engine::new(engine_config).await?;
+ let models = engine.models().await?;
+ let checkpoints = get_checkpoints(&models, &model_id);
+ if checkpoints.is_empty() {
+ return Err(anyhow::anyhow!("No checkpoints found for model: {model_id}"));
}
-}
-impl CliApplication {
- pub async fn create(config: EngineConfig) -> Result<Self, CliError> {
- let engine = Engine::new(config).await?;
- Ok(Self::new(engine))
+ let mut table = Table::new();
+ table
+ .load_preset(UTF8_FULL)
+ .apply_modifier(UTF8_ROUND_CORNERS)
+ .apply_modifier(UTF8_SOLID_INNER_BORDERS)
+ .set_content_arrangement(ContentArrangement::Dynamic)
+ .set_header(vec!["Name", "ID"]);
+
+ for checkpoint in &checkpoints {
+ table.add_row(vec![&checkpoint.name, &checkpoint.id]);
}
-}
+ println!("{table}");
-pub async fn run_interactive(model: Option<String>) -> anyhow::Result<()> {
- let engine_config = EngineConfig::default().with_application_identifier("com.trymirai.cli".to_string());
- let application = CliApplication::create(engine_config).await?;
- application.run_with_model(model).await?;
Ok(())
}
diff --git a/crates/cli/src/interactive/model.rs b/crates/cli/src/interactive/model.rs
new file mode 100644
index 000000000..cd124bb39
--- /dev/null
+++ b/crates/cli/src/interactive/model.rs
@@ -0,0 +1,156 @@
+use shoji::types::model::{Model, ModelAccessibility, ModelReference};
+use sysinfo::System;
+use uzu::engine::{Engine, EngineError};
+
+#[derive(Debug, Clone, PartialEq, thiserror::Error)]
+pub enum ModelResolutionError {
+ #[error(transparent)]
+ Engine(#[from] EngineError),
+ #[error("model `{model}` has checkpoints, but none fit in {memory_total} bytes of total memory")]
+ InsufficientMemory {
+ model: String,
+ memory_total: u64,
+ },
+}
+
+pub async fn resolve_model_id(
+ engine: &Engine,
+ model: String,
+) -> Result<Option<String>, ModelResolutionError> {
+ let models = engine.models().await?;
+ let mut system = System::new();
+ system.refresh_memory();
+ let resolved = if let Some(model) = models.iter().find(|candidate| candidate.identifier == model) {
+ model.identifier.clone()
+ } else if let Some(model) = resolve_model_shorthand(&models, &model, system.total_memory())? {
+ model.identifier.clone()
+ } else {
+ model
+ };
+ Ok(Some(resolved))
+}
+
+fn resolve_model_shorthand<'a>(
+ models: &'a [Model],
+ requested: &str,
+ memory_total: u64,
+) -> Result<Option<&'a Model>, ModelResolutionError> {
+ let mut candidates = models.iter().filter(|model| model_shorthand_matches(model, requested)).collect::<Vec<_>>();
+ if candidates.is_empty() {
+ return Ok(None);
+ }
+
+ candidates.retain(|model| checkpoint_size_bytes(model).is_some_and(|size| size <= memory_total));
+ if candidates.is_empty() {
+ return Err(ModelResolutionError::InsufficientMemory {
+ model: requested.to_string(),
+ memory_total,
+ });
+ }
+
+ candidates.sort_by(|left, right| {
+ quantization_priority(left)
+ .cmp(&quantization_priority(right))
+ .then_with(|| model_parameter_count(right).cmp(&model_parameter_count(left)))
+ .then_with(|| quantization_bits(right).cmp(&quantization_bits(left)))
+ .then_with(|| left.identifier.cmp(&right.identifier))
+ });
+ Ok(candidates.into_iter().next())
+}
+
+fn model_shorthand_matches(
+ model: &Model,
+ requested: &str,
+) -> bool {
+ let Some(family) = &model.family else {
+ return false;
+ };
+ let Some(properties) = &model.properties else {
+ return false;
+ };
+
+ let vendor = family.vendor.identifier.as_str();
+ let family_id = family.identifier.strip_prefix(&format!("{vendor}:")).unwrap_or(&family.identifier);
+ let size = properties.identifier.as_str();
+ let bits = model.quantization.as_ref().map(|quantization| quantization.bits_per_weight.to_string());
+
+ for include_vendor in [false, true] {
+ for include_size in [false, true] {
+ for include_quantization_vendor in [false, true] {
+ for include_quantization in [false, true] {
+ for include_bits in [false, true] {
+ let mut parts = Vec::with_capacity(6);
+ if include_vendor {
+ parts.push(vendor);
+ }
+ parts.push(family_id);
+ if include_size {
+ parts.push(size);
+ }
+
+ if include_quantization_vendor || include_quantization || include_bits {
+ let Some(quantization) = &model.quantization else {
+ continue;
+ };
+ if include_quantization_vendor {
+ parts.push(quantization.vendor.identifier.as_str());
+ }
+ if include_quantization {
+ parts.push(quantization.method.as_str());
+ }
+ if include_bits {
+ parts.push(bits.as_deref().expect("quantization bits are available"));
+ }
+ }
+
+ if parts.join(":") == requested {
+ return true;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ false
+}
+
+fn checkpoint_size_bytes(model: &Model) -> Option<u64> {
+ if let ModelAccessibility::Local {
+ reference: ModelReference::Mirai {
+ files,
+ ..
+ },
+ } = &model.accessibility
+ && !files.is_empty()
+ {
+ return files.iter().try_fold(0_u64, |total, file| {
+ let size = u64::try_from(file.size).ok()?;
+ total.checked_add(size)
+ });
+ }
+
+ let parameters = u64::try_from(model.properties.as_ref()?.size).ok()?;
+ let bits = u64::from(model.quantization.as_ref().map_or(16, |quantization| quantization.bits_per_weight));
+ Some(parameters.checked_mul(bits)?.div_ceil(8))
+}
+
+fn model_parameter_count(model: &Model) -> i64 {
+ model.properties.as_ref().map_or(0, |properties| properties.size)
+}
+
+fn quantization_priority(model: &Model) -> u8 {
+ match model.quantization.as_ref().map(|quantization| quantization.method.as_str()) {
+ Some(method) if method.eq_ignore_ascii_case("mirai-m") => 0,
+ Some(method) if method.eq_ignore_ascii_case("mirai-s") => 1,
+ _ => 2,
+ }
+}
+
+fn quantization_bits(model: &Model) -> u32 {
+ model.quantization.as_ref().map_or(16, |quantization| quantization.bits_per_weight)
+}
+
+#[cfg(test)]
+#[path = "../../unit/interactive/model_test.rs"]
+mod tests;
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index 6c8ec4d65..a1b2bf370 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -23,6 +23,12 @@ enum Commands {
task_path: String,
output_path: String,
},
+ ListCheckpoints {
+ /// Model ID shown by `list-models`.
+ #[arg(value_name = "MODEL_ID")]
+ model_id: String,
+ },
+ ListModels,
Server {
#[arg(long, value_name = "MODEL")]
model: String,
@@ -47,6 +53,10 @@ async fn main() -> Result<()> {
task_path,
output_path,
}) => bench::run_bench(model_path, task_path, output_path).await?,
+ Some(Commands::ListCheckpoints {
+ model_id,
+ }) => interactive::run_list_checkpoints(model_id).await?,
+ Some(Commands::ListModels) => interactive::run_list_models().await?,
Some(Commands::Server {
model,
port,
diff --git a/crates/cli/unit/interactive/model_test.rs b/crates/cli/unit/interactive/model_test.rs
new file mode 100644
index 000000000..4a0ea8a91
--- /dev/null
+++ b/crates/cli/unit/interactive/model_test.rs
@@ -0,0 +1,151 @@
+use shoji::types::{
+ basic::{File, Metadata},
+ model::{ModelFamily, ModelProperties, ModelQuantization, ModelRegistry, ModelVendor},
+};
+
+use super::*;
+
+const GB: i64 = 1_000_000_000;
+
+#[test]
+fn family_only_prefers_largest_mirai_model_that_fits() {
+ let models = vec![
+ checkpoint("0.8b", 800_000_000, "mirai", "mirai-m", 4, GB),
+ checkpoint("4b", 4 * GB, "mirai", "mirai-m", 4, 4 * GB),
+ checkpoint("27b", 27 * GB, "mlx-community", "mlx", 4, 16 * GB),
+ ];
+
+ let resolved = resolve_model_shorthand(&models, "qwen3.5", 32 * GB as u64).unwrap().unwrap();
+
+ assert_eq!(resolved.properties.as_ref().unwrap().identifier, "4b");
+ assert_eq!(resolved.quantization.as_ref().unwrap().method, "mirai-m");
+}
+
+#[test]
+fn family_only_uses_largest_checkpoint_when_no_mirai_model_exists() {
+ let models = vec![
+ checkpoint("4b", 4 * GB, "mlx-community", "mlx", 8, 4 * GB),
+ checkpoint("27b", 27 * GB, "mlx-community", "mlx", 4, 16 * GB),
+ ];
+
+ let resolved = resolve_model_shorthand(&models, "qwen3.5", 32 * GB as u64).unwrap().unwrap();
+
+ assert_eq!(resolved.properties.as_ref().unwrap().identifier, "27b");
+}
+
+#[test]
+fn shorthand_prefers_mirai_m_then_mirai_s() {
+ let mlx = checkpoint("4b", 4 * GB, "mlx-community", "mlx", 8, 4 * GB);
+ let mirai_s = checkpoint("4b", 4 * GB, "mirai", "mirai-s", 4, 4 * GB);
+ let mirai_m = checkpoint("4b", 4 * GB, "mirai", "mirai-m", 4, 4 * GB);
+
+ let models = vec![mlx.clone(), mirai_s.clone(), mirai_m.clone()];
+ assert_eq!(resolve_model_shorthand(&models, "qwen3.5:4b", 8 * GB as u64), Ok(Some(&mirai_m)));
+
+ let models = vec![mlx, mirai_s.clone()];
+ assert_eq!(resolve_model_shorthand(&models, "qwen3.5:4b", 8 * GB as u64), Ok(Some(&mirai_s)));
+}
+
+#[test]
+fn shorthand_infers_family_and_quantization_vendors() {
+ let model = checkpoint("4b", 4 * GB, "mlx-community", "mlx", 8, 4 * GB);
+ let models = [model.clone()];
+
+ assert_eq!(resolve_model_shorthand(&models, "qwen3.5:4b:mlx:8", 8 * GB as u64), Ok(Some(&model)));
+ assert_eq!(
+ resolve_model_shorthand(&models, "alibaba:qwen3.5:4b:mlx-community:mlx:8", 8 * GB as u64),
+ Ok(Some(&model))
+ );
+}
+
+#[test]
+fn valid_shorthand_returns_insufficient_memory_when_no_checkpoint_fits() {
+ let models = [checkpoint("4b", 4 * GB, "mirai", "mirai-m", 4, 4 * GB)];
+
+ let result = resolve_model_shorthand(&models, "qwen3.5:4b", GB as u64);
+
+ assert_eq!(
+ result,
+ Err(ModelResolutionError::InsufficientMemory {
+ model: "qwen3.5:4b".to_string(),
+ memory_total: GB as u64,
+ })
+ );
+}
+
+#[test]
+fn unknown_shorthand_remains_unresolved() {
+ let models = [checkpoint("4b", 4 * GB, "mirai", "mirai-m", 4, 4 * GB)];
+
+ assert_eq!(resolve_model_shorthand(&models, "unknown", GB as u64), Ok(None));
+}
+
+fn checkpoint(
+ size_id: &str,
+ parameters: i64,
+ quantization_vendor_id: &str,
+ quantization_method: &str,
+ bits_per_weight: u32,
+ checkpoint_size: i64,
+) -> Model {
+ let vendor = ModelVendor {
+ identifier: "alibaba".to_string(),
+ metadata: metadata("Alibaba"),
+ };
+ let quantization_vendor = ModelVendor {
+ identifier: quantization_vendor_id.to_string(),
+ metadata: metadata(quantization_vendor_id),
+ };
+ Model {
+ identifier: format!(
+ "alibaba:qwen3.5:{size_id}:{quantization_vendor_id}:{quantization_method}:{bits_per_weight}"
+ ),
+ registry: ModelRegistry {
+ identifier: "mirai".to_string(),
+ metadata: metadata("Mirai"),
+ },
+ backends: vec![],
+ family: Some(ModelFamily {
+ identifier: "alibaba:qwen3.5".to_string(),
+ vendor,
+ metadata: metadata("Qwen3.5"),
+ }),
+ properties: Some(ModelProperties {
+ identifier: size_id.to_string(),
+ size: parameters,
+ version: None,
+ metadata: metadata(size_id),
+ }),
+ quantization: Some(ModelQuantization {
+ identifier: format!("{quantization_vendor_id}:{quantization_method}:{bits_per_weight}"),
+ method: quantization_method.to_string(),
+ bits_per_weight,
+ vendor: quantization_vendor,
+ metadata: metadata(quantization_method),
+ }),
+ specializations: vec![],
+ accessibility: ModelAccessibility::Local {
+ reference: ModelReference::Mirai {
+ toolchain_version: "test".to_string(),
+ repository: None,
+ source_repository: None,
+ files: vec![File {
+ url: "https://example.com/model.safetensors".to_string(),
+ name: "model.safetensors".to_string(),
+ size: checkpoint_size,
+ hashes: vec![],
+ }],
+ },
+ },
+ encodings: vec![],
+ }
+}
+
+fn metadata(name: &str) -> Metadata {
+ Metadata {
+ identifier: name.to_lowercase(),
+ name: name.to_string(),
+ description: None,
+ icons: vec![],
+ }
+}