tessera-command 0.6.0

The tesserax command: opens a recipe, then serves, fetches or runs tasks
Documentation
use super::{
    Args, BUILTIN, Backend, Guard, SharedSink, Tune, drive, enable_tune, format_toml, script_config,
};
use crate::source::Stop;
use serde_json::{Value, json};
use std::cell::RefCell;
use std::rc::Rc;
use tessera_frontend::script::Guest;
use tessera_frontend::tasks::task::{Collect, Sink, Task};

fn parse(rest: &[String]) -> Result<Args, Stop> {
    if rest.iter().any(|a| a == "-h" || a == "--help") {
        return Err(Stop::Usage);
    }
    let tune = Tune::parse(rest, &|flag| {
        Some(flag != "--also" && !tessera_frontend::serve::start::Options::default().switch(flag))
    })
    .map_err(|e| Stop::Failed(e.0))?;
    tune.into_args()
}

struct Mock {
    shape: RefCell<Vec<Value>>,
    favor: RefCell<Option<String>>,
    applies: RefCell<usize>,
    flaky_parity: bool,
    parity_calls: RefCell<usize>,
}

impl Mock {
    fn new() -> Self {
        Self {
            shape: RefCell::new(Vec::new()),
            favor: RefCell::new(None),
            applies: RefCell::new(0),
            flaky_parity: false,
            parity_calls: RefCell::new(0),
        }
    }

    fn flaky() -> Self {
        Self {
            flaky_parity: true,
            ..Self::new()
        }
    }

    fn get(&self, prefix: &str, default: u64) -> u64 {
        self.shape
            .borrow()
            .iter()
            .rev()
            .find_map(|p| {
                p[0].as_str()
                    .is_some_and(|s| s.starts_with(prefix))
                    .then(|| p[1].as_u64())
                    .flatten()
            })
            .unwrap_or(default)
    }

    fn val(&self) -> u64 {
        self.get("k:w", 2)
    }
}

impl Backend for Mock {
    fn schema(&self) -> Result<Value, String> {
        Ok(json!({
            "model": "toy", "device": "mock-gpu", "slots": 4, "prefill_rows": 256,
            "knobs": [
                { "kernel": "k", "name": "w", "least": 1, "most": 6, "default": 2 },
                { "kernel": "k2", "name": "b", "least": 1, "most": 2, "default": 1 },
                { "kernel": "metal", "name": "x", "least": 1, "most": 2, "default": 1 },
            ],
        }))
    }

    fn recipe(&self) -> Result<Value, String> {
        Ok(json!({
            "recipe": { "shape": *self.shape.borrow(), "favor": *self.favor.borrow() },
            "applying": false, "loads": *self.applies.borrow(), "seconds": 0.01, "error": null,
        }))
    }

    fn explain(&self, ask: &Value) -> Result<Value, String> {
        let find = |prefix: &str, def: u64| {
            ask["recipe"]["shape"]
                .as_array()
                .and_then(|a| {
                    a.iter()
                        .rev()
                        .find(|p| p[0].as_str().is_some_and(|s| s.starts_with(prefix)))
                })
                .and_then(|p| p[1].as_u64())
                .unwrap_or_else(|| self.get(prefix, def))
        };
        let (v, b) = (find("k:w", 2), find("k2:b", 1));
        let mut vals = vec![
            json!({ "kernel": "k", "name": "w", "rule": "r", "value": v, "from": "default", "chosen": true }),
            json!({ "kernel": "metal", "name": "x", "rule": "m", "value": 1, "from": "default", "chosen": false }),
        ];
        if v == 3 {
            vals.push(json!({ "kernel": "k2", "name": "b", "rule": "r2", "value": b, "from": "default", "chosen": true }));
        }
        Ok(json!({
            "decode": [{ "fallbacks": true, "findings": [{ "rule": "lanes", "kernel": "lanes_m", "count": 4, "ms": 1.0, "site": "s", "rejections": [{ "rule": "fast_r", "reason": "estimated slower" }] }], "kernels": [{"rule": "r", "kernel": "k", "count": 1}], "values": vals }],
            "prefill": { "fallbacks": false, "findings": [], "kernels": [], "values": [] },
        }))
    }

    fn apply(&self, ask: &Value) -> Result<Value, String> {
        *self.applies.borrow_mut() += 1;
        if let Some(shape) = ask["recipe"]["shape"].as_array() {
            *self.shape.borrow_mut() = shape.clone();
        }
        if let Some(fav) = ask["recipe"].get("favor") {
            *self.favor.borrow_mut() = fav.as_str().map(String::from);
        }
        Ok(json!({ "applying": true, "lowered": self.explain(ask)? }))
    }

    fn measure(&self, ask: &Value) -> Result<Value, String> {
        let tokens = ask["tokens"].as_u64().unwrap_or(32);
        let pt = ask["prompt_tokens"].as_u64().unwrap_or(128);
        let (mut tps, local, mut ids, first) = match self.val() {
            1 => (90.0, 0, [1, 2], 0.05),
            3 => (125.0, 0, [1, 2], 0.05),
            4 => (140.0, 64, [1, 2], 0.05),
            5 => (150.0, 0, [9, 9], 0.05),
            6 => (160.0, 0, [1, 2], if pt >= 256 { 0.20 } else { 0.05 }),
            _ => (100.0, 0, [1, 2], 0.05),
        };
        if self.flaky_parity
            && ask["text"]
                .as_str()
                .is_some_and(|t| t.starts_with("parity check:"))
        {
            let mut n = self.parity_calls.borrow_mut();
            ids = [1, 2 + *n as u64];
            *n += 1;
        }
        if self.get("k2:b", 1) == 2 {
            tps += 10.0;
        }
        if self.favor.borrow().as_deref() == Some("fast_r") {
            tps = 135.0;
        }
        let dec = (tokens.saturating_sub(1)) as f64 / tps;
        Ok(json!({
            "launches": 10, "prompt_tokens": pt, "tokens": tokens, "seconds": first + dec,
            "spent": {
                "engine: launch": { "seconds": 1.0, "count": 10, "attrs": null },
                "plan: dec": { "seconds": 0.5, "count": 10, "attrs": null },
                "k 1x64 [l0]": { "seconds": dec * 0.5, "count": 5, "attrs": { "regs": 64, "local": local, "shared": 0, "ctas": 4 } },
                "k 1x64 [l1]": { "seconds": dec * 0.5, "count": 5, "attrs": { "regs": 64, "local": local, "shared": 0, "ctas": 4 } },
                "other 1x64 [r]": { "seconds": 0.001, "count": 1, "attrs": { "regs": 32, "local": 8, "shared": 0, "ctas": 4 } },
            },
            "ranks": [], "streams": [{ "prompt_tokens": pt, "tokens": tokens, "cached": 0, "first": first, "last": first + dec, "seconds": first + dec, "token_ids": ids }],
        }))
    }
}

#[test]
fn parse_and_toml() {
    let raw: Vec<String> = [
        "--profile-only",
        "--target",
        "prefill",
        "--scope-rows",
        "--guard",
        "128x32x8,256x4x1:prefill",
        "--probe-rules",
        "--knobs",
        "k:w,m",
        "--no-abba",
        "--arg",
        "n=4",
    ]
    .into_iter()
    .map(String::from)
    .collect();
    let parsed = parse(&raw).unwrap();
    assert!(
        parsed.profile_only
            && parsed.scope_rows
            && parsed.probe_rules
            && parsed.target == "prefill"
    );
    assert_eq!(parsed.guards.len(), 2);
    assert!(parsed.guards[0].streams == 8 && parsed.guards[1].target == "prefill");
    assert!(parse(&["--target".into(), "bogus".into()]).is_err());
    assert!(parse(&["--guard".into(), "bad".into()]).is_err());
    let shape = vec![json!(["k:w", 3]), json!(["q:b,rows=1..1", 2])];
    let toml = format_toml(&shape).unwrap();
    assert_eq!(
        toml,
        "[lower]\nknobs = [\n  \"k:w=3\",\n  \"q:b=2,rows=1..1\",\n]\n"
    );
    let mut opts = tessera_frontend::serve::start::Options::default();
    enable_tune(&mut opts, 4).unwrap();
    assert_eq!(opts.slots, 4);
}

#[test]
fn driver_tunes_knobs() {
    let guest = Guest::shared().unwrap();
    let mock = Rc::new(Mock::new());
    let sink: Rc<RefCell<Box<dyn Sink>>> = Rc::new(RefCell::new(Box::new(Collect::default())));
    let guard = super::Guard {
        prompt_tokens: 256,
        tokens: 4,
        streams: 1,
        target: "prefill".into(),
    };
    let prof_cfg = script_config(&Args {
        profile_only: true,
        probe_rules: true,
        guards: vec![guard.clone()],
        json: true,
        ..Args::default()
    });
    let prof = drive(
        guest,
        "tune.js",
        BUILTIN,
        &prof_cfg,
        mock.clone(),
        None,
        sink.clone(),
    )
    .unwrap();
    assert_eq!(prof["mode"], "profile");
    assert_eq!(prof["top_kernels"][0]["name"], "k");
    assert_eq!(prof["top_kernels"][0]["sites"], 2);
    assert_eq!(prof["knobs"].as_array().unwrap().len(), 1);
    assert_eq!(prof["rule_probes"][0]["rule"], "fast_r");
    assert!(prof["rule_probes"][0]["gain_pct"].as_f64().unwrap() > 30.0);
    assert!(mock.favor.borrow().is_none());
    let tune_cfg = script_config(&Args {
        scope_rows: true,
        guards: vec![guard],
        json: true,
        ..Args::default()
    });
    let tuned = drive(
        guest,
        "tune.js",
        BUILTIN,
        &tune_cfg,
        mock.clone(),
        None,
        sink,
    )
    .unwrap();
    assert_eq!(
        tuned["shape"],
        json!([["k:w,rows=1..1", 3], ["k2:b,rows=1..1", 2]])
    );
    let trials = tuned["trials"].as_array().unwrap();
    assert!(trials.iter().any(|t| t["status"] == "spill"));
    assert!(trials.iter().any(|t| t["status"] == "parity"));
    assert!(trials.iter().any(|t| t["status"] == "regression"));
}

fn prefill_guard() -> Guard {
    Guard {
        prompt_tokens: 256,
        tokens: 4,
        streams: 1,
        target: "prefill".into(),
    }
}

fn run_tune(mock: Rc<Mock>, args: Args) -> (Value, Collect) {
    let guest = Guest::shared().unwrap();
    let buf = Rc::new(RefCell::new(Collect::default()));
    let sink: Rc<RefCell<Box<dyn Sink>>> = Rc::new(RefCell::new(Box::new(SharedSink(buf.clone()))));
    let cfg = script_config(&args);
    let out = drive(guest, "tune.js", BUILTIN, &cfg, mock, None, sink).unwrap();
    (out, buf.take())
}

#[test]
fn parity_reject_logs() {
    let mock = Rc::new(Mock::new());
    let (tuned, collected) = run_tune(
        mock,
        Args {
            guards: vec![prefill_guard()],
            ..Args::default()
        },
    );
    let parity = tuned["trials"]
        .as_array()
        .unwrap()
        .iter()
        .find(|t| t["status"] == "parity")
        .expect("parity trial");
    assert_eq!(parity["knob"], "k:w");
    assert_eq!(parity["value"], 5);
    assert!((parity["score"].as_f64().unwrap() - 150.0).abs() < 1e-6);
    assert!((parity["decode_tps"].as_f64().unwrap() - 150.0).abs() < 1e-6);
    assert!((parity["prefill_tps"].as_f64().unwrap() - 2560.0).abs() < 1e-6);
    assert!((parity["ref_tps"].as_f64().unwrap() - 125.0).abs() < 1e-6);
    assert!((parity["gain_pct"].as_f64().unwrap() - 20.0).abs() < 1e-6);
    assert!(collected.records.contains(parity));
    assert!(
        collected.notes.iter().any(|n| n
            == "rejected k:w=5: greedy token_ids mismatch (125.0 -> 150.0 tok/s decode, +20.00%)")
    );
    assert!(
        !collected
            .notes
            .iter()
            .any(|n| n.contains("non-deterministic"))
    );
}

#[test]
fn flaky_parity_skips() {
    let mock = Rc::new(Mock::flaky());
    let (tuned, collected) = run_tune(
        mock.clone(),
        Args {
            guards: vec![prefill_guard()],
            ..Args::default()
        },
    );
    assert_eq!(*mock.parity_calls.borrow(), 2);
    assert!(
        collected
            .notes
            .iter()
            .any(|n| n == "baseline greedy token_ids are non-deterministic; skipping parity guard")
    );
    assert_eq!(tuned["shape"], json!([["k:w", 5]]));
    let trials = tuned["trials"].as_array().unwrap();
    assert!(!trials.iter().any(|t| t["status"] == "parity"));
    assert!(
        trials
            .iter()
            .any(|t| t["knob"] == "k:w" && t["value"] == 5 && t["status"] == "accepted")
    );
}