use super::GpuLayers;
use std::str::FromStr;
use super::{banner_line, kv_elem_for, InferArgs, OffloadDevice};
use clap::Parser;
#[derive(Parser, Debug)]
struct Cli {
#[command(flatten)]
infer: InferArgs,
}
fn args(argv: &[&str]) -> InferArgs {
let mut full = vec!["frink"];
full.extend_from_slice(argv);
Cli::parse_from(full).infer
}
#[test]
fn the_default_flags_forbid_the_metal_greedy_argmax_fold() {
let step = super::TokenStep::new(frink_models::sampling::Sampler::new(1), None);
let sampling = |argv: &[&str]| {
args(argv)
.sampling(None, 4096)
.expect("no --dry-multiplier, so no vocabulary is needed")
};
let defaults = sampling(&["-m", "m.gguf", "--temp", "0"]);
assert_eq!(defaults.repetition_penalty, 1.1, "llama.cpp's is 1.0");
assert!(
step.needs_vocab_logits(&defaults),
"the default repetition penalty is applied on the host, so the \
device must hand back a vocabulary and not one token id"
);
for off in [
["-m", "m.gguf", "--temp", "0", "--repeat-penalty", "1.0"],
["-m", "m.gguf", "--temp", "0", "--repeat-last-n", "0"],
] {
let s = sampling(&off);
assert!(
!step.needs_vocab_logits(&s),
"{off:?} switches the penalties off, so the fold is exact again"
);
}
}
#[test]
fn the_banner_reports_the_kv_dtype_the_run_will_actually_keep() {
let a = args(&["-m", "m.gguf", "--device", "cpu", "--ctk", "f16"]);
assert_eq!(kv_elem_for(&a).as_str(), "f16", "llama.cpp's default width");
assert_eq!(
frink_models::KvElem::from(super::host_kv_dtype_for(&a)),
kv_elem_for(&a),
"the caches and the budget read one function"
);
let line = banner_line(&a, OffloadDevice::Cpu);
assert!(
line.contains("ctk=f16") && !line.contains("--ctk f16"),
"{line}"
);
let a = args(&["-m", "m.gguf", "--device", "cpu", "--ctk", "f32"]);
assert_eq!(kv_elem_for(&a).as_str(), "f32");
assert!(banner_line(&a, OffloadDevice::Cpu).contains("ctk=f32"));
let a = args(&["-m", "m.gguf", "--device", "cpu", "--ctk", "q8_0"]);
assert_eq!(kv_elem_for(&a).as_str(), "f16");
let line = banner_line(&a, OffloadDevice::Cpu);
assert!(line.contains("ctk=f16"), "{line}");
assert!(
line.contains("--ctk q8_0 has no cpu host store; using f16"),
"a flag the host cannot honour must say so: {line}"
);
}
#[test]
fn the_environment_supplies_the_kv_dtype_when_the_flag_does_not() {
static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let restore = std::env::var("FRINK_CTK").ok();
unsafe { std::env::set_var("FRINK_CTK", "q4_0") };
let a = args(&["-m", "m.gguf"]);
assert_eq!(a.ctk, "q4_0", "the environment was ignored");
let a = args(&["-m", "m.gguf", "--ctk", "q8_0"]);
assert_eq!(a.ctk, "q8_0", "the flag lost to the environment");
unsafe {
match restore {
Some(v) => std::env::set_var("FRINK_CTK", v),
None => std::env::remove_var("FRINK_CTK"),
}
}
}
#[test]
fn the_banner_does_not_promise_gpu_layers_on_a_cpu_device() {
let a = args(&["-m", "m.gguf", "--device", "cpu", "--ngl", "all"]);
let line = banner_line(&a, OffloadDevice::Cpu);
assert!(line.contains("device=cpu"), "{line}");
assert!(line.contains("ignored, no GPU offload"), "{line}");
}
#[test]
fn a_metal_run_reports_the_requested_dtype_with_no_caveat() {
let a = args(&[
"-m", "m.gguf", "--device", "metal", "--ngl", "all", "--ctk", "f16",
]);
let line = banner_line(&a, OffloadDevice::Metal);
assert!(line.contains("ctk=f16"), "{line}");
assert!(!line.contains("ignored"), "{line}");
}
#[test]
fn a_partial_gpu_layer_count_is_refused_rather_than_rounded_up() {
let err = GpuLayers::Count(10)
.check_supported(32)
.expect_err("10 of 32 is partial");
let msg = err.to_string();
assert!(msg.contains("PARTIAL"), "{msg}");
assert!(
msg.contains("--ngl 0"),
"the message must say what works: {msg}"
);
assert!(msg.contains("--ngl 32"), "{msg}");
GpuLayers::Count(0)
.check_supported(32)
.expect("0 = CPU only");
GpuLayers::Count(32).check_supported(32).expect("32 = all");
GpuLayers::Count(99)
.check_supported(32)
.expect("clamps to all");
GpuLayers::All.check_supported(32).expect("all");
GpuLayers::Auto.check_supported(32).expect("auto");
}
#[test]
fn escapes_are_processed_by_default_like_llama_cpp() {
use clap::Parser;
#[derive(Parser)]
struct Probe {
#[command(flatten)]
args: super::InferArgs,
}
let parsed = Probe::try_parse_from(["frink", "-m", "x.gguf"]).expect("defaults parse");
assert!(parsed.args.escape, "llama.cpp common/common.h:563 is true");
assert!(!parsed.args.no_escape);
let off = Probe::try_parse_from(["frink", "-m", "x.gguf", "--no-escape"])
.expect("--no-escape parses");
assert!(off.args.no_escape, "llama.cpp spells the negation this way");
}
#[test]
fn samplers_defaults_to_the_chain_frink_already_ran() {
let default = args(&["-m", "x.gguf"])
.sampling(None, 4096)
.expect("no dry, so no vocabulary is needed")
.sampler_order;
assert_eq!(default, frink_models::SamplerOrder::default());
assert_eq!(
default.to_string(),
"penalties;dry;top_n_sigma;top_k;typ_p;top_p;min_p;xtc;temperature"
);
}
#[test]
fn a_caller_supplied_order_reaches_the_sampler() {
let order = args(&["-m", "x.gguf", "--samplers", "penalties;temperature;top_k"])
.sampling(None, 4096)
.expect("no dry")
.sampler_order;
assert_eq!(order.to_string(), "penalties;temperature;top_k");
assert_eq!(
args(&["-m", "x.gguf", "--samplers", "top-k;min-p;temp"])
.sampling(None, 4096)
.expect("no dry")
.sampler_order
.to_string(),
"top_k;min_p;temperature"
);
}
#[test]
fn a_sampler_frink_lacks_is_refused_by_name_on_the_command_line() {
let err = Cli::try_parse_from([
"frink",
"-m",
"x.gguf",
"--samplers",
"penalties;mirostat;temperature",
])
.expect_err("mirostat is not a chain member here")
.to_string();
assert!(err.contains("mirostat"), "{err}");
assert!(err.contains("not implemented"), "{err}");
Cli::try_parse_from([
"frink",
"-m",
"x.gguf",
"--samplers",
"penalties;dry;top_n_sigma;top_k;typ_p;top_p;min_p;xtc;temperature",
])
.expect("llama.cpp's default chain is frink's default chain");
let unknown = Cli::try_parse_from(["frink", "-m", "x.gguf", "--samplers", "top_kk"])
.expect_err("no such sampler")
.to_string();
assert!(unknown.contains("top_kk"), "{unknown}");
assert!(unknown.contains("unknown sampler"), "{unknown}");
}
#[test]
fn parses_llama_gpu_layer_values() {
assert_eq!(GpuLayers::from_str("0"), Ok(GpuLayers::Count(0)));
assert_eq!(GpuLayers::from_str("42"), Ok(GpuLayers::Count(42)));
assert_eq!(GpuLayers::from_str("auto"), Ok(GpuLayers::Auto));
assert_eq!(GpuLayers::from_str("all"), Ok(GpuLayers::All));
assert!(GpuLayers::from_str("-1").is_err());
assert!(GpuLayers::from_str("some").is_err());
}
fn with_model(argv: &[&str]) -> InferArgs {
let mut full = vec!["-m", "x.gguf"];
full.extend_from_slice(argv);
args(&full)
}
fn temp_file(tag: &str, text: &str) -> std::path::PathBuf {
let path = std::env::temp_dir().join(format!("frink-run-{}-{tag}", std::process::id()));
std::fs::write(&path, text).unwrap();
path
}
#[test]
fn json_schema_file_is_the_json_schema_flag_read_from_a_file() {
let schema = r#"{"type": "object", "properties": {"n": {"type": "integer"}}}"#;
let path = temp_file("schema.json", schema);
let p = path.to_str().unwrap();
let from_file = with_model(&["--json-schema-file", p]);
let inline = with_model(&["--json-schema", schema]);
let got = from_file.grammar_source().unwrap();
assert!(got.is_some(), "-jf produced no grammar");
assert_eq!(got, inline.grammar_source().unwrap());
let both = with_model(&["--json-schema-file", p, "--grammar", "root ::= \"a\""]);
let err = both.grammar_source().unwrap_err().to_string();
assert!(err.contains("mutually exclusive"), "{err}");
std::fs::remove_file(path).ok();
}
#[test]
fn system_prompt_file_drops_one_trailing_newline_like_llama_cpp() {
for (text, want) in [
("be terse\n", "be terse"),
("two\n\n", "two\n"),
("none", "none"),
] {
let path = temp_file("sys.txt", text);
let mut a = with_model(&["--system-prompt-file", path.to_str().unwrap()]);
a.read_system_prompt_file().unwrap();
assert_eq!(a.system.as_deref(), Some(want), "{text:?}");
std::fs::remove_file(path).ok();
}
let clash = Cli::try_parse_from([
"frink",
"-m",
"x.gguf",
"--system",
"a",
"--system-prompt-file",
"b",
]);
assert!(
clash.is_err(),
"--system and --system-prompt-file both accepted"
);
let mut missing = with_model(&["--system-prompt-file", "/nonexistent/frink-sysf"]);
let err = missing.read_system_prompt_file().unwrap_err().to_string();
assert!(err.contains("--system-prompt-file"), "{err}");
}
#[test]
fn jinja_and_flash_attn_refuse_what_frink_cannot_do() {
let err = with_model(&["--no-jinja"])
.apply_llama_flags()
.unwrap_err()
.to_string();
assert!(err.contains("--no-jinja"), "{err}");
with_model(&["--jinja"]).apply_llama_flags().unwrap();
for off in ["off", "0", "disabled", "false"] {
let err = with_model(&["--flash-attn", off])
.apply_llama_flags()
.unwrap_err()
.to_string();
assert!(err.contains("backend property"), "{off}: {err}");
}
let err = with_model(&["--flash-attn", "maybe"])
.apply_llama_flags()
.unwrap_err()
.to_string();
assert!(err.contains("expected on, off or auto"), "{err}");
assert_eq!(
with_model(&["--flash-attn"]).flash_attn.as_deref(),
Some("auto")
);
with_model(&["--flash-attn", "on"])
.apply_llama_flags()
.unwrap();
}
#[test]
fn warmup_and_show_timings_default_on_and_the_last_spelling_wins() {
assert!(with_model(&[]).warmup_enabled());
assert!(!with_model(&["--no-warmup"]).warmup_enabled());
assert!(with_model(&["--no-warmup", "--warmup"]).warmup_enabled());
assert!(!with_model(&["--warmup", "--no-warmup"]).warmup_enabled());
assert!(with_model(&[]).show_timings_enabled());
assert!(!with_model(&["--no-show-timings"]).show_timings_enabled());
assert!(with_model(&["--no-show-timings", "--show-timings"]).show_timings_enabled());
}
#[test]
fn color_takes_llama_cpps_values() {
for (argv, want) in [
(&["--color", "on"][..], Some(true)),
(&["--color", "1"], Some(true)),
(&["--color", "off"], Some(false)),
(&["--color", "false"], Some(false)),
(&["--color", "auto"], None),
(&["--color"], Some(true)),
(&[], None),
] {
assert_eq!(with_model(argv).colour_choice().unwrap(), want, "{argv:?}");
}
let err = with_model(&["--color", "rainbow"])
.colour_choice()
.unwrap_err()
.to_string();
assert!(err.contains("expected on, off or auto"), "{err}");
}