Skip to main content

rig_evals/report/
compare.rs

1//! Comparing two reports of one experiment: a baseline run against a candidate
2//! run, such as yesterday's against today's or model A against model B.
3
4use std::collections::BTreeMap;
5use std::fmt::Write as _;
6use std::time::Duration;
7
8use serde::{Deserialize, Serialize};
9
10use super::{EvaluatorSummary, LatencySummary, Report, Tokens, TrialResult, cell, one_line};
11
12/// One evaluator in a [`Comparison`].
13#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
14#[non_exhaustive]
15pub struct EvaluatorDelta {
16    /// The evaluator.
17    pub evaluator: String,
18    /// Its summary in the baseline; `None` when the baseline has no such
19    /// evaluator.
20    pub baseline: Option<EvaluatorSummary>,
21    /// Its summary in the candidate; `None` when the candidate has no such
22    /// evaluator.
23    pub candidate: Option<EvaluatorSummary>,
24    /// `candidate.pass_rate - baseline.pass_rate`; `None` unless both reports
25    /// have the evaluator with at least one scored trial (`count > 0`).
26    pub pass_rate_delta: Option<f64>,
27    /// `candidate.mean - baseline.mean`; `None` unless both reports have the
28    /// evaluator with at least one scored trial (`count > 0`).
29    pub mean_delta: Option<f64>,
30}
31
32/// A case whose outcome changed between the two reports.
33///
34/// A case passes in a report when every one of its trials passes. Trials that
35/// share a case id are pooled into one case (see [`Report::compare`]).
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37#[non_exhaustive]
38pub struct CaseChange {
39    /// The case's id.
40    pub case_id: String,
41    /// The evaluators that failed the case in the report where it failed: the
42    /// candidate's for a regression, the baseline's for a fix.
43    pub evaluators: Vec<String>,
44}
45
46/// How a candidate run differs from a baseline run of the same experiment.
47///
48/// Built by [`Report::compare`]. Cases are matched by id. Trials that share
49/// an id are pooled into one case, in both reports, so a duplicated id counts
50/// once in the regression, fix and only-in lists.
51#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
52#[non_exhaustive]
53pub struct Comparison {
54    /// The baseline's experiment name.
55    pub baseline_experiment: String,
56    /// The candidate's experiment name.
57    pub candidate_experiment: String,
58    /// Per evaluator: those of the baseline first, in its order, then those
59    /// only the candidate has.
60    pub evaluators: Vec<EvaluatorDelta>,
61    /// Cases that passed in the baseline and fail in the candidate, by id.
62    pub regressions: Vec<CaseChange>,
63    /// Cases that failed in the baseline and pass in the candidate, by id.
64    pub fixes: Vec<CaseChange>,
65    /// Case ids only the baseline has, sorted.
66    pub only_in_baseline: Vec<String>,
67    /// Case ids only the candidate has, sorted.
68    pub only_in_candidate: Vec<String>,
69    /// The baseline's model tokens.
70    pub baseline_tokens: Tokens,
71    /// The candidate's model tokens.
72    pub candidate_tokens: Tokens,
73    /// `candidate_tokens.total - baseline_tokens.total`.
74    pub tokens_delta: i64,
75    /// The baseline's run latencies.
76    pub baseline_latency: LatencySummary,
77    /// The candidate's run latencies.
78    pub candidate_latency: LatencySummary,
79    /// The candidate's p50 minus the baseline's, in milliseconds.
80    pub p50_delta_ms: f64,
81    /// The candidate's p95 minus the baseline's, in milliseconds.
82    pub p95_delta_ms: f64,
83}
84
85impl Report {
86    /// Compares this report (the candidate) with `baseline`: per evaluator the
87    /// pass-rate and mean deltas, the cases that regressed or were fixed, the
88    /// cases only one report has, and the token and latency deltas.
89    ///
90    /// Cases are matched by id. Trials that share an id within a report are
91    /// pooled into one case: it passes only when all of them pass, and its
92    /// failing evaluators are those of all of them. Repetitions of a case
93    /// therefore count as one case here, not as separate cases.
94    ///
95    /// An evaluator's deltas are `None` unless both reports score it in at
96    /// least one trial.
97    ///
98    /// ```
99    /// use rig_evals::Report;
100    ///
101    /// fn regressed(baseline: &Report, candidate: &Report) -> bool {
102    ///     !candidate.compare(baseline).regressions.is_empty()
103    /// }
104    /// ```
105    pub fn compare(&self, baseline: &Report) -> Comparison {
106        let base_cases = cases(baseline);
107        let cand_cases = cases(self);
108        let mut regressions = Vec::new();
109        let mut fixes = Vec::new();
110        let mut only_in_baseline = Vec::new();
111        for (id, base_trials) in &base_cases {
112            let Some(cand_trials) = cand_cases.get(id) else {
113                only_in_baseline.push((*id).to_owned());
114                continue;
115            };
116            let base_passed = base_trials.iter().all(|trial| trial.passed());
117            let cand_passed = cand_trials.iter().all(|trial| trial.passed());
118            if base_passed && !cand_passed {
119                regressions.push(CaseChange {
120                    case_id: (*id).to_owned(),
121                    evaluators: failing_evaluators(cand_trials),
122                });
123            } else if !base_passed && cand_passed {
124                fixes.push(CaseChange {
125                    case_id: (*id).to_owned(),
126                    evaluators: failing_evaluators(base_trials),
127                });
128            }
129        }
130        let only_in_candidate = cand_cases
131            .keys()
132            .filter(|id| !base_cases.contains_key(*id))
133            .map(|id| (*id).to_owned())
134            .collect();
135
136        let mut evaluators = Vec::new();
137        for base in &baseline.summary {
138            let cand = self
139                .summary
140                .iter()
141                .find(|summary| summary.evaluator == base.evaluator);
142            evaluators.push(evaluator_delta(&base.evaluator, Some(base), cand));
143        }
144        for cand in &self.summary {
145            let in_baseline = baseline
146                .summary
147                .iter()
148                .any(|summary| summary.evaluator == cand.evaluator);
149            if !in_baseline {
150                evaluators.push(evaluator_delta(&cand.evaluator, None, Some(cand)));
151            }
152        }
153
154        Comparison {
155            baseline_experiment: baseline.experiment.clone(),
156            candidate_experiment: self.experiment.clone(),
157            evaluators,
158            regressions,
159            fixes,
160            only_in_baseline,
161            only_in_candidate,
162            baseline_tokens: baseline.tokens,
163            candidate_tokens: self.tokens,
164            tokens_delta: signed_delta(self.tokens.total, baseline.tokens.total),
165            baseline_latency: baseline.latency,
166            candidate_latency: self.latency,
167            p50_delta_ms: millis_delta(self.latency.p50, baseline.latency.p50),
168            p95_delta_ms: millis_delta(self.latency.p95, baseline.latency.p95),
169        }
170    }
171}
172
173impl Comparison {
174    /// The comparison as pretty-printed JSON.
175    pub fn to_json(&self) -> Result<String, serde_json::Error> {
176        serde_json::to_string_pretty(self)
177    }
178
179    /// The comparison as Markdown: a table per evaluator with the deltas, the
180    /// regressions and fixes, the cases only one report has, and the token and
181    /// latency deltas. A delta or value that does not apply is `-`.
182    pub fn to_markdown(&self) -> String {
183        let mut md = format!(
184            "# Comparison: {} vs {}\n\n{} regressions, {} fixes.\n\n",
185            cell(&self.candidate_experiment),
186            cell(&self.baseline_experiment),
187            self.regressions.len(),
188            self.fixes.len()
189        );
190        md.push_str(
191            "| Evaluator | Baseline pass rate | Candidate pass rate | Pass rate delta | Baseline mean | Candidate mean | Mean delta |\n|---|---|---|---|---|---|---|\n",
192        );
193        for delta in &self.evaluators {
194            let rate = |summary: &Option<EvaluatorSummary>| {
195                summary
196                    .as_ref()
197                    .filter(|s| s.count > 0)
198                    .map_or("-".to_owned(), |s| format!("{:.0}%", s.pass_rate * 100.0))
199            };
200            let mean = |summary: &Option<EvaluatorSummary>| {
201                summary
202                    .as_ref()
203                    .filter(|s| s.count > 0)
204                    .map_or("-".to_owned(), |s| format!("{:.2}", s.mean))
205            };
206            let pass_delta = delta
207                .pass_rate_delta
208                .map_or("-".to_owned(), |d| format!("{:+.1} pts", d * 100.0));
209            let mean_delta = delta
210                .mean_delta
211                .map_or("-".to_owned(), |d| format!("{d:+.2}"));
212            let _ = writeln!(
213                md,
214                "| {} | {} | {} | {pass_delta} | {} | {} | {mean_delta} |",
215                cell(&delta.evaluator),
216                rate(&delta.baseline),
217                rate(&delta.candidate),
218                mean(&delta.baseline),
219                mean(&delta.candidate),
220            );
221        }
222        md.push_str("\n## Regressions\n\n");
223        push_changes(&mut md, &self.regressions, "No regressions.");
224        md.push_str("\n## Fixes\n\n");
225        push_changes(&mut md, &self.fixes, "No fixes.");
226        md.push_str("\n## Cases in one report only\n\n");
227        md.push_str("Only in the baseline: ");
228        push_ids(&mut md, &self.only_in_baseline);
229        md.push_str("\nOnly in the candidate: ");
230        push_ids(&mut md, &self.only_in_candidate);
231        let _ = writeln!(
232            md,
233            "\n\nTokens: {} baseline, {} candidate, {:+} delta. Latency: p50 {:+.1} ms, p95 {:+.1} ms (candidate minus baseline).",
234            self.baseline_tokens.total,
235            self.candidate_tokens.total,
236            self.tokens_delta,
237            self.p50_delta_ms,
238            self.p95_delta_ms
239        );
240        md
241    }
242}
243
244/// Each case's trials in `report`, by case id. Trials sharing an id are pooled.
245fn cases(report: &Report) -> BTreeMap<&str, Vec<&TrialResult>> {
246    let mut map: BTreeMap<&str, Vec<&TrialResult>> = BTreeMap::new();
247    for result in &report.trials {
248        map.entry(result.trial.case_id.as_str())
249            .or_default()
250            .push(result);
251    }
252    map
253}
254
255/// The evaluators that failed one of `trials`, in first-seen order, once each.
256fn failing_evaluators(trials: &[&TrialResult]) -> Vec<String> {
257    let mut names: Vec<String> = Vec::new();
258    for score in trials.iter().flat_map(|trial| trial.failures()) {
259        if !names.contains(&score.evaluator) {
260            names.push(score.evaluator.clone());
261        }
262    }
263    names
264}
265
266fn evaluator_delta(
267    name: &str,
268    baseline: Option<&EvaluatorSummary>,
269    candidate: Option<&EvaluatorSummary>,
270) -> EvaluatorDelta {
271    let both = baseline
272        .zip(candidate)
273        .filter(|(base, cand)| base.count > 0 && cand.count > 0);
274    EvaluatorDelta {
275        evaluator: name.to_owned(),
276        baseline: baseline.cloned(),
277        candidate: candidate.cloned(),
278        pass_rate_delta: both.map(|(base, cand)| cand.pass_rate - base.pass_rate),
279        mean_delta: both.map(|(base, cand)| cand.mean - base.mean),
280    }
281}
282
283/// `candidate - baseline`, saturating at the `i64` bounds.
284fn signed_delta(candidate: u64, baseline: u64) -> i64 {
285    let delta = i128::from(candidate) - i128::from(baseline);
286    i64::try_from(delta).unwrap_or(if delta < 0 { i64::MIN } else { i64::MAX })
287}
288
289/// `candidate - baseline` in milliseconds.
290fn millis_delta(candidate: Duration, baseline: Duration) -> f64 {
291    candidate.as_secs_f64() * 1000.0 - baseline.as_secs_f64() * 1000.0
292}
293
294/// `text` as a Markdown code span on one line. The fence is one backtick
295/// longer than the longest backtick run in `text`, so the span cannot end early.
296fn code_span(text: &str) -> String {
297    let text = one_line(text);
298    let longest = text.split(|c| c != '`').map(str::len).max().unwrap_or(0);
299    let fence = "`".repeat(longest + 1);
300    let pad = if text.starts_with('`') || text.ends_with('`') {
301        " "
302    } else {
303        ""
304    };
305    format!("{fence}{pad}{text}{pad}{fence}")
306}
307
308fn push_changes(md: &mut String, changes: &[CaseChange], none: &str) {
309    if changes.is_empty() {
310        md.push_str(none);
311        md.push('\n');
312    }
313    for change in changes {
314        let evaluators: Vec<String> = change
315            .evaluators
316            .iter()
317            .map(|name| one_line(name))
318            .collect();
319        let _ = writeln!(
320            md,
321            "- {}: {}",
322            code_span(&change.case_id),
323            evaluators.join(", ")
324        );
325    }
326}
327
328fn push_ids(md: &mut String, ids: &[String]) {
329    if ids.is_empty() {
330        md.push_str("none");
331    } else {
332        let spans: Vec<String> = ids.iter().map(|id| code_span(id)).collect();
333        md.push_str(&spans.join(", "));
334    }
335}