tessera-command 0.5.4

The tesserax command: opens a recipe, then serves, fetches or runs tasks
Documentation
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! 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::kindling::Machine;
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 from kindlingai/recipes, as `<model>[:<backend>][:<N>x][@<ref>]`.
    Kindling(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:";

/// The `--recipe` prefix that names a kindlingai/recipes model.
pub(crate) const KINDLING_PREFIX: &str = "kindling:";

/// 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)
}

/// The kindlingai/recipes recipe `spec` names for this machine.
fn kindling(spec: &str, cache: Option<&Path>) -> Result<Recipe, Stop> {
    let specs = crate::size::specs(&tessera_frontend::frontend_settings::read());
    let machine = Machine {
        backend: &specs.backend,
        version: release(),
        bytes: crate::size::room(&specs),
    };
    Ok(tessera_frontend::recipe::kindling::open(spec, &machine, cache)?)
}

/// 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 => match value.strip_prefix(KINDLING_PREFIX) {
                            Some(spec) => Origin::Kindling(spec.into()),
                            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(_) | Origin::Kindling(_) => {
                (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),
            Some(Origin::Kindling(spec)) => Some(kindling(spec, cache.as_deref())?),
            _ => 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),
    }
}