Skip to main content

lean_ctx/core/locomo/
report.rs

1//! Aggregate per-question results into publishable LoCoMo metrics (#291).
2
3use serde::{Deserialize, Serialize};
4
5use super::runner::SampleResult;
6
7/// Aggregated metrics for one slice of questions (a category, or `category = 0`
8/// for the overall row).
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct CategoryMetrics {
11    /// LoCoMo category, or 0 for "overall".
12    pub category: u8,
13    pub label: String,
14    pub questions: usize,
15    /// Fraction of questions whose gold answer was contained in recalled context.
16    pub containment_rate: f64,
17    pub mean_f1: f64,
18    pub exact_match_rate: f64,
19    pub mean_recall_tokens: f64,
20}
21
22/// A complete, committable benchmark report.
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct LocomoReport {
25    pub suite: String,
26    pub generated_at: String,
27    pub top_k: usize,
28    pub samples: usize,
29    pub questions: usize,
30    pub overall: CategoryMetrics,
31    pub by_category: Vec<CategoryMetrics>,
32    pub mean_transcript_tokens: f64,
33    pub mean_recall_tokens: f64,
34    /// Token reduction of recalled context vs. dumping the full transcript.
35    pub token_reduction_pct: f64,
36}
37
38fn category_label(category: u8) -> &'static str {
39    match category {
40        0 => "overall",
41        1 => "single-hop",
42        2 => "multi-hop",
43        3 => "temporal",
44        4 => "open-domain",
45        5 => "adversarial",
46        _ => "other",
47    }
48}
49
50fn mean(values: impl Iterator<Item = f64>) -> f64 {
51    let mut n = 0usize;
52    let mut sum = 0.0;
53    for v in values {
54        sum += v;
55        n += 1;
56    }
57    if n == 0 { 0.0 } else { sum / n as f64 }
58}
59
60fn round3(x: f64) -> f64 {
61    (x * 1000.0).round() / 1000.0
62}
63
64fn metrics_for(category: u8, qa: &[&super::runner::QaResult]) -> CategoryMetrics {
65    let questions = qa.len();
66    CategoryMetrics {
67        category,
68        label: category_label(category).to_string(),
69        questions,
70        containment_rate: round3(mean(qa.iter().map(|q| f64::from(u8::from(q.contained))))),
71        mean_f1: round3(mean(qa.iter().map(|q| q.f1))),
72        exact_match_rate: round3(mean(qa.iter().map(|q| f64::from(u8::from(q.exact_match))))),
73        mean_recall_tokens: round3(mean(qa.iter().map(|q| q.recall_tokens as f64))),
74    }
75}
76
77/// Aggregate sample results into a report.
78pub fn aggregate(suite: &str, top_k: usize, results: &[SampleResult]) -> LocomoReport {
79    let all: Vec<&super::runner::QaResult> = results.iter().flat_map(|r| r.qa.iter()).collect();
80    let overall = metrics_for(0, &all);
81
82    let mut categories: Vec<u8> = all.iter().map(|q| q.category).collect();
83    categories.sort_unstable();
84    categories.dedup();
85    let by_category: Vec<CategoryMetrics> = categories
86        .into_iter()
87        .map(|cat| {
88            let slice: Vec<&super::runner::QaResult> =
89                all.iter().copied().filter(|q| q.category == cat).collect();
90            metrics_for(cat, &slice)
91        })
92        .collect();
93
94    let mean_transcript_tokens = round3(mean(
95        results
96            .iter()
97            .flat_map(|r| r.qa.iter().map(|_| r.transcript_tokens as f64)),
98    ));
99    let mean_recall_tokens = overall.mean_recall_tokens;
100    let token_reduction_pct = if mean_transcript_tokens > 0.0 {
101        round3((1.0 - mean_recall_tokens / mean_transcript_tokens) * 100.0)
102    } else {
103        0.0
104    };
105
106    LocomoReport {
107        suite: suite.to_string(),
108        generated_at: chrono::Utc::now().to_rfc3339(),
109        top_k,
110        samples: results.len(),
111        questions: all.len(),
112        overall,
113        by_category,
114        mean_transcript_tokens,
115        mean_recall_tokens,
116        token_reduction_pct,
117    }
118}
119
120impl LocomoReport {
121    pub fn to_json(&self) -> String {
122        serde_json::to_string_pretty(self).unwrap_or_else(|_| "{}".to_string())
123    }
124
125    /// Human/publishable Markdown summary.
126    pub fn to_markdown(&self) -> String {
127        let mut out = String::new();
128        out.push_str("# LoCoMo Memory Benchmark — lean-ctx\n\n");
129        out.push_str(&format!(
130            "Suite: `{}` · samples: {} · questions: {} · top_k: {}\n\n",
131            self.suite, self.samples, self.questions, self.top_k
132        ));
133        out.push_str("Retrieval-recall benchmark: each conversation turn is stored as a memory, then for every question the top-k memories are recalled and scored against the gold answers. Model-free and deterministic.\n\n");
134        out.push_str("## Overall\n\n");
135        out.push_str("| metric | value |\n|---|---|\n");
136        out.push_str(&format!(
137            "| answer containment (recall@{}) | {:.1}% |\n",
138            self.top_k,
139            self.overall.containment_rate * 100.0
140        ));
141        out.push_str(&format!(
142            "| mean best-memory token-F1 | {:.3} |\n",
143            self.overall.mean_f1
144        ));
145        out.push_str(&format!(
146            "| exact-match rate | {:.1}% |\n",
147            self.overall.exact_match_rate * 100.0
148        ));
149        out.push_str(&format!(
150            "| mean recalled-context tokens | {:.0} |\n",
151            self.mean_recall_tokens
152        ));
153        out.push_str(&format!(
154            "| mean full-transcript tokens | {:.0} |\n",
155            self.mean_transcript_tokens
156        ));
157        out.push_str(&format!(
158            "| token reduction vs. full transcript | {:.1}% |\n\n",
159            self.token_reduction_pct
160        ));
161
162        out.push_str("## By category\n\n");
163        out.push_str("| category | questions | containment | mean F1 | recall tokens |\n");
164        out.push_str("|---|---|---|---|---|\n");
165        for c in &self.by_category {
166            out.push_str(&format!(
167                "| {} | {} | {:.1}% | {:.3} | {:.0} |\n",
168                c.label,
169                c.questions,
170                c.containment_rate * 100.0,
171                c.mean_f1,
172                c.mean_recall_tokens
173            ));
174        }
175        out.push('\n');
176        out.push_str(&format!("_Generated {}._\n", self.generated_at));
177        out
178    }
179}