use super::{Args, BUILTIN, Backend, drive, format_toml, parse, script_config};
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};
struct Mock {
shape: RefCell<Vec<Value>>,
applies: RefCell<usize>,
}
impl Mock {
fn new() -> Self {
Self {
shape: RefCell::new(Vec::new()),
applies: RefCell::new(0),
}
}
fn val(&self) -> u64 {
self.shape
.borrow()
.iter()
.rev()
.find_map(|p| (p[0] == "k:w").then(|| p[1].as_u64()).flatten())
.unwrap_or(2)
}
}
impl Backend for Mock {
fn schema(&self) -> Result<Value, String> {
Ok(json!({
"model": "toy", "device": "mock-gpu", "slots": 1, "prefill_rows": 128,
"knobs": [{ "kernel": "k", "name": "w", "least": 1, "most": 4, "default": 2 }],
}))
}
fn recipe(&self) -> Result<Value, String> {
Ok(json!({
"recipe": { "shape": *self.shape.borrow() },
"applying": false, "loads": *self.applies.borrow(), "seconds": 0.01, "error": null,
}))
}
fn explain(&self, ask: &Value) -> Result<Value, String> {
let v = ask["recipe"]["shape"]
.as_array()
.and_then(|a| a.iter().rev().find(|p| p[0] == "k:w"))
.and_then(|p| p[1].as_u64())
.unwrap_or(self.val());
Ok(json!({
"decode": [{ "fallbacks": false, "kernels": [{"rule": "r", "kernel": "k", "count": 1}],
"values": [{ "kernel": "k", "name": "w", "rule": "r", "value": v, "from": "default" }] }],
"prefill": { "fallbacks": false, "kernels": [], "values": [] },
}))
}
fn apply(&self, ask: &Value) -> Result<Value, String> {
*self.applies.borrow_mut() += 1;
let shape = ask["recipe"]["shape"]
.as_array()
.cloned()
.unwrap_or_default();
*self.shape.borrow_mut() = shape;
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 (tps, local) = match self.val() {
1 => (90.0, 0),
3 => (125.0, 0),
4 => (140.0, 64),
_ => (100.0, 0),
};
let dec = (tokens - 1) as f64 / tps;
Ok(json!({
"launches": 10, "prompt_tokens": 128, "tokens": tokens, "seconds": 0.05 + dec,
"spent": { "k 1x64 [r]": { "seconds": dec, "count": 10, "attrs": { "regs": 64, "local": local, "shared": 0, "ctas": 4 } } },
"ranks": [], "streams": [{ "prompt_tokens": 128, "tokens": tokens, "cached": 0, "first": 0.05, "last": 0.05 + dec, "seconds": 0.05 + dec }],
}))
}
}
#[test]
fn parse_and_toml() {
let raw: Vec<String> = [
"--profile-only",
"--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.abba && parsed.knobs == ["k:w", "m"]);
assert_eq!(parsed.extra["n"], json!(4));
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"
);
}
#[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 prof_cfg = script_config(&Args {
profile_only: true,
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!(*mock.applies.borrow(), 0);
let tune_cfg = script_config(&Args {
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", 3]]));
assert_eq!(mock.val(), 3);
assert!(
tuned["trials"]
.as_array()
.unwrap()
.iter()
.any(|t| t["status"] == "spill")
);
}