use std::io::Write;
use std::sync::OnceLock;
use frink_models::{Decoder, Engine};
static DEVICE_LINE: OnceLock<String> = OnceLock::new();
pub fn set_device_line(line: String) {
let _ = DEVICE_LINE.set(line);
}
fn device_line() -> Option<&'static str> {
DEVICE_LINE.get().map(String::as_str)
}
mod colour {
use std::io::IsTerminal;
use std::sync::OnceLock;
pub const GREEN: &str = "\x1b[32m";
pub const MAGENTA: &str = "\x1b[35m";
pub const BOLD_CYAN: &str = "\x1b[1;36m";
pub const RESET: &str = "\x1b[0m";
static ON: OnceLock<bool> = OnceLock::new();
pub fn force(on: Option<bool>) {
if let Some(on) = on {
let _ = ON.set(on);
}
}
pub fn enabled() -> bool {
*ON.get_or_init(|| {
if std::env::var_os("NO_COLOR").is_some() {
return false;
}
if std::env::var_os("FRINK_COLOR").is_some() {
return true;
}
std::io::stderr().is_terminal()
})
}
}
use colour::{enabled as colour_enabled, BOLD_CYAN, GREEN, MAGENTA, RESET};
pub fn set_colour(on: Option<bool>) {
colour::force(on);
}
static SHOW_TIMINGS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
pub fn set_show_timings(on: bool) {
SHOW_TIMINGS.store(on, std::sync::atomic::Ordering::Relaxed);
}
pub fn show_timings() -> bool {
SHOW_TIMINGS.load(std::sync::atomic::Ordering::Relaxed)
}
fn paint(code: &str, text: &str) -> String {
if colour_enabled() {
format!("{code}{text}{RESET}")
} else {
text.to_string()
}
}
pub fn warm_up(decoder: &Decoder, enabled: bool) {
if !enabled {
return;
}
let mut scratch = decoder.config.new_kv_caches_with_capacity(1);
let _ = decoder.forward_token(0, 0, &mut scratch);
}
pub fn warm_up_engine<E: Engine>(engine: &E, enabled: bool) {
if !enabled {
return;
}
let mut scratch = engine.new_state();
let _ = engine.forward_token(0, 0, &mut scratch);
}
pub struct Timings {
pub prompt_tokens: usize,
pub prompt_secs: f64,
pub predicted_tokens: usize,
pub predicted_secs: f64,
}
impl Timings {
fn rate(tokens: usize, secs: f64) -> Option<f64> {
(secs > 0.0 && tokens > 0).then(|| tokens as f64 / secs)
}
pub fn prompt_per_second(&self) -> Option<f64> {
Self::rate(self.prompt_tokens, self.prompt_secs)
}
pub fn predicted_per_second(&self) -> Option<f64> {
Self::rate(self.predicted_tokens, self.predicted_secs)
}
pub fn line(&self) -> String {
let fmt = |r: Option<f64>| match r {
Some(v) => format!("{v:.1} t/s"),
None => "-".to_string(),
};
format!(
"[ Prompt: {} | Generation: {} ]",
fmt(self.prompt_per_second()),
fmt(self.predicted_per_second())
)
}
pub fn print(&self, w: &mut impl Write) -> std::io::Result<()> {
if !show_timings() {
return Ok(());
}
writeln!(w, "\n{}", paint(MAGENTA, &self.line()))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn t(pt: usize, ps: f64, gt: usize, gs: f64) -> Timings {
Timings {
prompt_tokens: pt,
prompt_secs: ps,
predicted_tokens: gt,
predicted_secs: gs,
}
}
#[test]
fn the_line_matches_llama_cpps_shape() {
let line = t(197, 1.0, 152, 1.0).line();
assert_eq!(line, "[ Prompt: 197.0 t/s | Generation: 152.0 t/s ]");
}
#[test]
fn an_unmeasured_rate_is_a_dash() {
assert_eq!(t(0, 0.0, 8, 1.0).prompt_per_second(), None);
assert!(
t(0, 0.0, 8, 1.0).line().contains("Prompt: -"),
"an unmeasured prompt rate must not print as a number"
);
assert_eq!(t(5, 0.0, 8, 1.0).prompt_per_second(), None);
}
#[test]
fn both_rates_come_from_the_same_guard() {
let x = t(10, 2.0, 30, 3.0);
assert_eq!(x.prompt_per_second(), Some(5.0));
assert_eq!(x.predicted_per_second(), Some(10.0));
}
}
pub fn version_block() -> String {
let version = env!("CARGO_PKG_VERSION");
let head = match option_env!("FRINK_GIT_SHA") {
Some(sha) => format!("version: {version} (commit {sha})"),
None => format!("version: {version}"),
};
format!(
"{head}\nbuilt for {}\n",
option_env!("FRINK_TARGET").unwrap_or("unknown")
)
}
pub fn licenses_block() -> std::io::Result<String> {
Ok(include_str!("../THIRD_PARTY_NOTICES.md").to_string())
}
pub struct Banner<'a> {
pub model_path: &'a str,
pub ftype: &'a str,
pub modalities: &'a str,
}
const LABEL_WIDTH: usize = 10;
impl Banner<'_> {
pub fn render(&self) -> String {
let build = match option_env!("FRINK_GIT_SHA") {
Some(sha) => format!("{}-{sha}", env!("CARGO_PKG_VERSION")),
None => env!("CARGO_PKG_VERSION").to_string(),
};
let row = |k: &str, v: &str| format!("{k:<LABEL_WIDTH$} : {v}\n");
let device = device_line()
.map(|d| {
let v = d
.trim_start_matches("frink: ")
.trim_start_matches("device=");
row("device", v)
})
.unwrap_or_default();
format!(
"{}{}{}{}{}",
row("build", &build),
row("model", self.model_path),
row("ftype", self.ftype),
row("modalities", self.modalities),
device,
)
}
pub fn print(&self, w: &mut impl Write) -> std::io::Result<()> {
write!(w, "\n{}\n", self.render())
}
}
#[cfg(test)]
mod banner_tests {
use super::*;
fn banner() -> Banner<'static> {
Banner {
model_path: "models/Llama-3.2-1B-Instruct-Q4_K_M.gguf",
ftype: "Q4_K - Medium",
modalities: "text",
}
}
#[test]
fn the_banner_matches_llama_cpps_labels_and_alignment() {
let out = banner().render();
let lines: Vec<&str> = out.lines().collect();
assert!(
(4..=5).contains(&lines.len()),
"four rows, plus device when known:\n{out}"
);
for (i, key) in ["build", "model", "ftype", "modalities"].iter().enumerate() {
assert!(
lines[i].starts_with(key),
"row {i} should be `{key}`, is: {}",
lines[i]
);
}
let cols: Vec<usize> = lines
.iter()
.map(|l| l.find(':').expect("every row has a colon"))
.collect();
assert!(
cols.windows(2).all(|w| w[0] == w[1]),
"the colons are not aligned: {cols:?}\n{out}"
);
assert_eq!(
cols[3],
LABEL_WIDTH + 1,
"the longest label should sit flush against its colon"
);
}
#[test]
fn the_banner_prints_the_values_it_is_given() {
let out = banner().render();
assert!(out.contains("models/Llama-3.2-1B-Instruct-Q4_K_M.gguf"));
assert!(out.contains("Q4_K - Medium"));
assert!(out.contains("modalities : text\n"));
}
}
pub fn ftype_name(ftype: Option<u64>) -> String {
let Some(v) = ftype else {
return "unknown".to_string();
};
match frink_gguf::ftype::llama_ftype_name(v) {
Some(name) => name.to_string(),
None => format!("ftype {v}"),
}
}
#[cfg(test)]
mod ftype_tests {
use super::*;
#[test]
fn the_common_quants_read_as_llama_cpp_names_them() {
assert_eq!(ftype_name(Some(15)), "Q4_K - Medium");
assert_eq!(ftype_name(Some(7)), "Q8_0");
assert_eq!(ftype_name(Some(1)), "F16");
}
#[test]
fn an_unknown_ftype_reports_its_number() {
assert_eq!(ftype_name(Some(99)), "ftype 99");
assert_eq!(ftype_name(None), "unknown");
}
}
const LOGO: &[&str] = &[
r"______ _ _ ",
r"| ___| (_) | | ",
r"| |_ _ __ _ _ __ | | __",
r"| _| '__| | '_ \| |/ /",
r"| | | | | | | | | < ",
r"\_| |_| |_|_| |_|_|\_\",
];
pub fn print_logo(w: &mut impl Write) -> std::io::Result<()> {
writeln!(w)?;
for row in LOGO {
writeln!(w, "{}", paint(BOLD_CYAN, row))?;
}
Ok(())
}
pub fn print_prompt_echo(w: &mut impl Write, prompt: &str) -> std::io::Result<()> {
let first = prompt.lines().next().unwrap_or("").trim();
let shown = if prompt.lines().count() > 1 || first.chars().count() > 120 {
let cut: String = first.chars().take(117).collect();
format!("{cut}...")
} else {
first.to_string()
};
writeln!(w, "\n{}", paint(GREEN, &format!("> {shown}")))
}
pub fn print_exiting(w: &mut impl Write) -> std::io::Result<()> {
writeln!(w, "\nExiting...")
}
#[cfg(test)]
mod presentation_tests {
use super::*;
#[test]
fn the_logo_is_frinks_own() {
assert!(LOGO.len() >= 3, "the wordmark has rows");
assert!(
LOGO.iter().any(|r| r.chars().any(|c| !c.is_whitespace())),
"the wordmark is blank"
);
assert!(
!LOGO.join("").to_ascii_lowercase().contains("llama"),
"the wordmark must not carry another project's name"
);
}
#[test]
fn the_wordmark_stacks_and_is_pure_ascii() {
let width = LOGO[0].chars().count();
for (i, row) in LOGO.iter().enumerate() {
assert_eq!(
row.chars().count(),
width,
"row {i} is {} wide against {width}; the columns do not stack",
row.chars().count()
);
assert!(
row.is_ascii(),
"row {i} carries a non-ASCII glyph, which is what made the \
previous two wordmarks font-dependent: {row:?}"
);
}
assert!(
LOGO.len() >= 3 && width < 60,
"the wordmark is {}x{width}, outside anything a terminal wants",
LOGO.len()
);
}
#[test]
fn output_is_plain_when_the_stream_is_not_a_terminal() {
let mut echo = Vec::new();
print_prompt_echo(&mut echo, "hi").expect("write");
let echo = String::from_utf8(echo).expect("utf8");
assert!(
!echo.contains('\x1b'),
"the prompt echo carries escape codes into a pipe: {echo:?}"
);
let mut timing = Vec::new();
Timings {
prompt_tokens: 5,
prompt_secs: 1.0,
predicted_tokens: 8,
predicted_secs: 1.0,
}
.print(&mut timing)
.expect("write");
let timing = String::from_utf8(timing).expect("utf8");
assert!(
!timing.contains('\x1b'),
"the timing line carries escape codes into a pipe: {timing:?}"
);
let mut logo = Vec::new();
print_logo(&mut logo).expect("write");
assert!(
!String::from_utf8(logo).expect("utf8").contains('\x1b'),
"the wordmark carries escape codes into a pipe"
);
}
#[test]
fn a_short_prompt_is_echoed_whole() {
let mut out = Vec::new();
print_prompt_echo(&mut out, "Capital of France?").expect("write");
assert_eq!(
String::from_utf8(out).expect("utf8"),
"\n> Capital of France?\n"
);
}
}