tessera-command 0.5.0

The tesserax command: opens a recipe, then serves, fetches or runs tasks
Documentation
//! Where the model comes from, and the options it gives.

use include_dir::{Dir, include_dir};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tessera_engine::progress::Progress;
use tessera_engine::wasm::{Module, Trace};
use tessera_frontend::recipe::{Catalog, Files, Miss, Pick, Recipe};
use tessera_frontend::serve::start::Options;

/// Why a run stops early.
#[derive(Debug)]
pub enum Stop {
    Usage,
    /// The task list, after a message if given.
    Tasks(Option<String>),
    Failed(String),
}

impl std::fmt::Display for Stop {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Stop::Usage | Stop::Tasks(None) => f.write_str("bad usage"),
            Stop::Tasks(Some(text)) | Stop::Failed(text) => f.write_str(text),
        }
    }
}

impl std::error::Error for Stop {}

impl From<tessera_frontend::recipe::Error> for Stop {
    fn from(e: tessera_frontend::recipe::Error) -> Self {
        Stop::Failed(e.to_string())
    }
}

/// Where the model comes from.
pub enum Origin {
    Recipe(String),
    Model(String),
    /// `owner/name` or `owner/name@revision` on Hugging Face.
    Hub(String),
    /// A recipe built into tesserax, by catalog name.
    Builtin(&'static str),
    /// A catalog family's first pick that fits this machine.
    Catalog(String),
    /// A recipe paired with overriding weights.
    Paired(Box<Origin>, Box<Origin>),
}

/// One TOML file per built-in recipe, keyed by stem.
static RECIPES: Dir = include_dir!("$CARGO_MANIFEST_DIR/recipe");

/// Default built-in recipe name.
const DEFAULT: &str = "gemma-4-e4b";

/// Built-in recipes by name, default first, then sorted.
pub(crate) fn builtins() -> Vec<(&'static str, &'static str)> {
    let mut out = Vec::new();
    for file in RECIPES.files() {
        let Some(name) = file.path().file_stem().and_then(|s| s.to_str()) else {
            continue;
        };
        if file.path().extension().and_then(|e| e.to_str()) != Some("toml") {
            continue;
        }
        let Some(text) = file.contents_utf8() else {
            continue;
        };
        out.push((name, text));
    }
    out.sort_by_key(|(name, _)| (*name != DEFAULT, *name));
    out
}

/// The `--recipe` prefix that names a model catalog family.
pub(crate) const CATALOG_PREFIX: &str = "catalog:";

/// Catalog recipe `name`.
pub fn builtin(name: &str) -> Option<Result<Recipe, Stop>> {
    let (_, text) = builtins().into_iter().find(|(n, _)| *n == name)?;
    let path = PathBuf::from(format!("builtin/{name}.toml"));
    Some(Recipe::parse(text, &path).map_err(Stop::from))
}

/// Whether `name` is a catalog family and no path.
fn family_named(name: &str) -> bool {
    let plain = !name.contains(['/', ':', '#']) && !Path::new(name).exists();
    plain && Catalog::current().families.iter().any(|f| f.family == name)
}

/// Catalog family `name`'s first pick that fits this machine.
pub fn choose(name: &str) -> Result<(&'static Pick, Recipe), Stop> {
    let none = || Stop::Failed(format!("{name:?} is not in the model catalog"));
    let family = Catalog::current().find(name).ok_or_else(none)?;
    let available = crate::size::available();
    let version = release();
    family.pick(version, available).map_err(|miss| match miss {
        Miss::Memory(least) => Stop::Failed(format!(
            "{} needs {:.1} GB for its weights and this machine has {:.1} GB: \
             pick a smaller model",
            family.family,
            gb(least),
            gb(available)
        )),
        Miss::Version => Stop::Failed(format!(
            "{} has no pick that tesserax {} runs",
            family.family,
            env!("CARGO_PKG_VERSION")
        )),
    })
}

/// The version of a build the release tool never stamped.
const UNSTAMPED: &str = "0.1.0";

/// This build's release number. Unstamped builds skip version gates.
fn release() -> Option<&'static str> {
    Some(env!("CARGO_PKG_VERSION")).filter(|v| *v != UNSTAMPED)
}

/// Bytes in decimal GB.
pub fn gb(bytes: u64) -> f64 {
    bytes as f64 / 1e9
}

/// A recipe's kind: its serve task, or text generation.
pub fn kind(r: &Recipe) -> &str {
    r.serve
        .get("task")
        .and_then(|v| v.as_str())
        .unwrap_or("generate")
}

/// Every catalog recipe that reads.
pub fn catalog() -> Vec<Recipe> {
    let read = |(name, _): (&str, &str)| builtin(name)?.ok();
    builtins().into_iter().filter_map(read).collect()
}

/// The default recipe's name and Hugging Face repository.
pub(crate) fn default_model() -> String {
    let Some(Ok(recipe)) = builtin(DEFAULT) else {
        return DEFAULT.into();
    };
    let hf = recipe.weights.hf.unwrap_or_default();
    let repo = hf.split('@').next().unwrap_or_default();
    format!("{} from {repo}", recipe.name)
}

/// The repository in a `--model hf:<owner>/<name>[@<revision>]` value.
fn hub_spec(value: &str) -> Option<Result<String, Stop>> {
    let spec = value.strip_prefix("hf:")?;
    let (repo, revision) = spec.split_once('@').unwrap_or((spec, "main"));
    let valid = |part: &str| !part.is_empty() && !part.contains(['/', '@']);
    let named = matches!(repo.split_once('/'), Some((o, n)) if valid(o) && valid(n));
    Some(if named && !revision.is_empty() {
        Ok(spec.to_string())
    } else {
        Err(Stop::Failed(format!(
            "{value}: use hf:<owner>/<name>[@<revision>]"
        )))
    })
}

/// Splits out the model flags, up to `--`.
pub fn split(given: &[String]) -> Result<(Option<Origin>, Vec<String>), Stop> {
    let (mut recipe, mut model) = (None, None);
    let mut rest = Vec::new();
    let mut args = given.iter();
    while let Some(arg) = args.next() {
        if arg == "--" || arg == "--also" {
            rest.push(arg.clone());
            rest.extend(args.by_ref().cloned());
            break;
        }
        if arg != "--recipe" && arg != "--model" {
            rest.push(arg.clone());
            continue;
        }
        let value = args.next().ok_or(Stop::Usage)?.clone();
        match arg.as_str() {
            // A directory or source wins over a catalog name.
            "--recipe" => {
                let found = match builtins().into_iter().find(|(n, _)| *n == value) {
                    Some((name, _)) if !Path::new(&value).exists() => Origin::Builtin(name),
                    _ => match value.strip_prefix(CATALOG_PREFIX) {
                        Some(family) => Origin::Catalog(family.into()),
                        None if family_named(&value) => Origin::Catalog(value),
                        None => Origin::Recipe(value),
                    },
                };
                if recipe.replace(found).is_some() {
                    return Err(Stop::Usage);
                }
            }
            _ => {
                let found = match hub_spec(&value) {
                    Some(spec) => Origin::Hub(spec?),
                    None => Origin::Model(value),
                };
                if model.replace(found).is_some() {
                    return Err(Stop::Usage);
                }
            }
        }
    }
    let origin = match (recipe, model) {
        (Some(r), Some(m)) => Some(Origin::Paired(Box::new(r), Box::new(m))),
        (Some(o), None) | (None, Some(o)) => Some(o),
        (None, None) => None,
    };
    Ok((origin, rest))
}

/// An opened origin.
pub struct Source {
    origin: Origin,
    pub recipe: Option<Recipe>,
    pub cache: Option<PathBuf>,
    pub token: Option<String>,
    /// The snapshot directory, for a Hugging Face origin.
    pub fetched: Option<PathBuf>,
    dump_sites: Option<PathBuf>,
    /// Where downloads and the model load report.
    pub progress: Progress,
    /// Which bytes of remote weights to fetch.
    files: Files,
}

impl Source {
    /// Opens the recipe, if the origin is one.
    pub fn open(origin: Option<Origin>, progress: Progress) -> Result<Source, Stop> {
        Self::open_as(origin, progress, (Files::Whole, None))
    }

    /// As `open`, fetching `files` of remote weights for `manifest`.
    pub fn open_as(
        origin: Option<Origin>,
        progress: Progress,
        (files, manifest): (Files, Option<&str>),
    ) -> Result<Source, Stop> {
        let origin = origin.ok_or(Stop::Usage)?;
        let settings = tessera_frontend::frontend_settings::read();
        let (cache, token, dump_sites) = (settings.recipes, settings.hf_token, settings.dump_sites);
        let (recipe_side, model_side) = match &origin {
            Origin::Paired(r, m) => (Some(r.as_ref()), Some(m.as_ref())),
            Origin::Recipe(_) | Origin::Builtin(_) | Origin::Catalog(_) => (Some(&origin), None),
            Origin::Model(_) | Origin::Hub(_) => (None, Some(&origin)),
        };
        let recipe = match recipe_side {
            Some(Origin::Recipe(src)) => Some(Recipe::open(src, cache.as_deref())?),
            Some(Origin::Builtin(name)) => Some(builtin(name).ok_or(Stop::Usage)??),
            Some(Origin::Catalog(family)) => Some(choose(family)?.1),
            _ => None,
        };
        let manifest = manifest.or_else(|| {
            recipe
                .as_ref()
                .and_then(|r| r.serve.get("manifest"))
                .and_then(|v| v.as_str())
        });
        let fetched = match model_side {
            Some(Origin::Hub(spec)) => {
                let dir = cache.as_deref().ok_or(tessera_frontend::recipe::Error::NoCache)?;
                Some(tessera_frontend::recipe::fetch_hf(
                    spec,
                    dir,
                    token.as_deref(),
                    &progress,
                    (files, manifest),
                )?)
            }
            _ => None,
        };
        Ok(Source {
            origin,
            recipe,
            cache,
            token,
            fetched,
            dump_sites,
            progress,
            files,
        })
    }

    /// Opens `origin`, else the first catalog recipe of `of`.
    pub fn open_or_kind(
        origin: Option<Origin>,
        of: Option<&str>,
        progress: Progress,
    ) -> Result<Source, Stop> {
        if origin.is_some() {
            return Self::open(origin, progress);
        }
        for (name, _) in builtins() {
            let Some(Ok(recipe)) = builtin(name) else {
                continue;
            };
            if of.is_none_or(|k| k == kind(&recipe)) {
                return Self::open(Some(Origin::Builtin(name)), progress);
            }
        }
        let of = of.unwrap_or_default();
        let none = format!("no built-in model does {of}: give --recipe or --model");
        Err(Stop::Failed(none))
    }

    /// Serve options. Each `--also` starts one more model.
    pub fn options(&self, rest: &[String]) -> Result<Options, Stop> {
        let Some(at) = rest.iter().position(|flag| flag == "--also") else {
            return self.one(rest);
        };
        let mut options = self.one(&rest[..at])?;
        let (origin, flags) = split(&rest[at + 1..])?;
        let more = Source::open(origin, self.progress.clone())?;
        let mut more = more.options(&flags)?;
        let further = std::mem::take(&mut more.also);
        options.also.push(more);
        options.also.extend(further);
        Ok(options)
    }

    /// Explicit weights directory from `--model`, if given.
    pub fn override_weights(&self) -> Option<PathBuf> {
        if let Some(dir) = &self.fetched {
            return Some(dir.clone());
        }
        match &self.origin {
            Origin::Model(dir) => Some(PathBuf::from(dir)),
            Origin::Paired(_, m) => match m.as_ref() {
                Origin::Model(dir) => Some(PathBuf::from(dir)),
                _ => None,
            },
            _ => None,
        }
    }

    /// Serve options for this model alone.
    fn one(&self, rest: &[String]) -> Result<Options, Stop> {
        let mut options = Options::default();
        options.progress = self.progress.clone();
        let custom = self.override_weights();
        if let Some(r) = &self.recipe {
            let (cache, token) = (self.cache.as_deref(), self.token.as_deref());
            if custom.is_none() {
                options.model = r.weights_as(self.files, cache, token, &self.progress)?;
            }
            options.name = Some(r.name.clone());
            options.lower = r.lower.clone();
            options.names = r.names();
            options.config = tessera_frontend::bundle::Overrides::new(r.overrides());
            if let Some(bytes) = r.module_bytes(cache)? {
                let trace = Trace {
                    dump: self.dump_sites.clone(),
                    favor: r.lower.as_ref().and_then(|l| l.favor.clone()),
                };
                let module =
                    Module::open_with(&bytes, trace).map_err(|e| Stop::Failed(e.to_string()))?;
                let rules = module.rules.iter().copied();
                options.lower.get_or_insert_default().rules.extend(rules);
                options.module = Some(Arc::new(module));
            }
            for (flag, dir) in r.extras_as(self.files, cache, token, &self.progress)? {
                apply(&mut options, &flag, Some(dir.display().to_string()))?;
            }
            for (flag, value) in r.flags() {
                apply(&mut options, &flag, value)?;
            }
        }
        let mut given = rest.iter().cloned();
        while let Some(flag) = given.next() {
            if options.switch(&flag) {
                continue;
            }
            let value = given.next().ok_or(Stop::Usage)?;
            apply(&mut options, &flag, Some(value))?;
        }
        if let Some(dir) = custom {
            options.model = dir;
        }
        Ok(options)
    }
}

/// Takes one serve flag. `Usage` when it is bad.
fn apply(options: &mut Options, flag: &str, value: Option<String>) -> Result<(), Stop> {
    match value {
        None if options.switch(flag) => Ok(()),
        Some(value) => options.flag(flag, value).ok_or(Stop::Usage),
        None => Err(Stop::Usage),
    }
}