Skip to content

Commit 9da045e

Browse files
authored
Merge pull request #97 from femboyisp/emry-058-tui-overlay
EMRY-058: TUI run comparison overlay
2 parents fc92a2b + f157f16 commit 9da045e

10 files changed

Lines changed: 468 additions & 220 deletions

File tree

‎crates/emry-cli/src/lib.rs‎

Lines changed: 116 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -47,11 +47,17 @@ pub enum Commands {
4747
/// Sidecar socket to read events from.
4848
#[arg(long)]
4949
socket: Option<PathBuf>,
50+
/// Prior run directory (or `metrics.jsonl`) to overlay as a baseline.
51+
#[arg(long)]
52+
compare: Option<PathBuf>,
5053
},
5154
/// Tail a run directory's `metrics.jsonl` and render it live.
5255
Watch {
5356
/// Run directory (or a `metrics.jsonl` file directly).
5457
path: PathBuf,
58+
/// Prior run directory (or `metrics.jsonl`) to overlay as a baseline.
59+
#[arg(long)]
60+
compare: Option<PathBuf>,
5561
},
5662
/// Serve the live web dashboard for a run directory or sidecar socket.
5763
Web {
@@ -142,8 +148,12 @@ pub fn run() -> ExitCode {
142148
fn dispatch(command: Commands) -> ExitCode {
143149
let result = match command {
144150
Commands::Demo { steps } => cmd_demo(steps),
145-
Commands::Watch { path } => cmd_watch(&path),
146-
Commands::Tui { run_dir, socket } => cmd_tui(run_dir.as_deref(), socket.as_deref()),
151+
Commands::Watch { path, compare } => cmd_watch(&path, compare.as_deref()),
152+
Commands::Tui {
153+
run_dir,
154+
socket,
155+
compare,
156+
} => cmd_tui(run_dir.as_deref(), socket.as_deref(), compare.as_deref()),
147157
Commands::Web {
148158
run_dir,
149159
socket,
@@ -173,20 +183,48 @@ fn dispatch(command: Commands) -> ExitCode {
173183
}
174184
}
175185

176-
/// Builds the dashboard state (seeded with `labels`) and renders `events` to the
177-
/// terminal until the user quits.
186+
/// Builds the dashboard state (seeded with `labels` and an optional comparison
187+
/// `baseline`) and renders `events` to the terminal until the user quits.
178188
fn run_dashboard(
179189
events: &Receiver<Event>,
180190
labels: &[(MetricId, String)],
191+
baseline: Vec<emry_tui::BaselineSeries>,
181192
) -> Result<(), Box<dyn Error>> {
182193
let label_refs: Vec<(MetricId, &str)> = labels
183194
.iter()
184195
.map(|(id, name)| (*id, name.as_str()))
185196
.collect();
186-
run_terminal(events, UiState::with_labels(&label_refs))?;
197+
let mut state = UiState::with_labels(&label_refs);
198+
state.set_baseline(baseline);
199+
run_terminal(events, state)?;
187200
Ok(())
188201
}
189202

203+
/// Loads a `--compare` baseline run into the TUI's series, warning (and
204+
/// continuing without an overlay) if it cannot be read.
205+
fn load_compare(compare: Option<&Path>) -> Vec<emry_tui::BaselineSeries> {
206+
let Some(path) = compare else {
207+
return Vec::new();
208+
};
209+
match emry_store::load_baseline(path) {
210+
Ok(series) => series
211+
.into_iter()
212+
.map(|s| emry_tui::BaselineSeries {
213+
label: s.label,
214+
steps: s.steps,
215+
values: s.values,
216+
})
217+
.collect(),
218+
Err(err) => {
219+
eprintln!(
220+
"emry: could not load --compare baseline {}: {err}",
221+
path.display()
222+
);
223+
Vec::new()
224+
}
225+
}
226+
}
227+
190228
/// `emry demo` — a synthetic run streamed to the live dashboard.
191229
fn cmd_demo(steps: u64) -> Result<(), Box<dyn Error>> {
192230
let run_dir = std::env::temp_dir().join("emry-demo");
@@ -219,7 +257,30 @@ fn cmd_demo(steps: u64) -> Result<(), Box<dyn Error>> {
219257
run.finish().ok();
220258
});
221259

222-
run_dashboard(&events, &labels)
260+
// A synthetic prior run (slower-decaying loss) overlaid as the amber
261+
// comparison baseline, so the demo also exercises `--compare`.
262+
let baseline = demo_baseline(steps);
263+
run_dashboard(&events, &labels, baseline)
264+
}
265+
266+
/// A synthetic prior-run baseline for the demo's `loss` / `loss_ema` curves.
267+
fn demo_baseline(steps: u64) -> Vec<emry_tui::BaselineSeries> {
268+
let stride = (steps / 400).max(1);
269+
let (mut s, mut v) = (Vec::new(), Vec::new());
270+
let mut step = 0;
271+
while step < steps {
272+
#[allow(clippy::cast_precision_loss)]
273+
let loss = 2.3 / (1.0 + step as f64 * 0.0032);
274+
s.push(step);
275+
v.push(loss);
276+
step += stride;
277+
}
278+
let series = |label: &str| emry_tui::BaselineSeries {
279+
label: label.to_string(),
280+
steps: s.clone(),
281+
values: v.clone(),
282+
};
283+
vec![series("loss"), series("loss_ema")]
223284
}
224285

225286
/// `emry watch PATH` — tail a run directory's `metrics.jsonl` into the dashboard.
@@ -228,9 +289,10 @@ fn cmd_demo(steps: u64) -> Result<(), Box<dyn Error>> {
228289
/// only after the dashboard starts render with the `m{id}` fallback name until a
229290
/// name-table protocol exists (a future `MetricRegistered` event); in practice
230291
/// metrics are registered at run start, so they are present in the first poll.
231-
fn cmd_watch(path: &Path) -> Result<(), Box<dyn Error>> {
292+
fn cmd_watch(path: &Path, compare: Option<&Path>) -> Result<(), Box<dyn Error>> {
293+
let baseline = load_compare(compare);
232294
let (rx, labels, stop, poller) = spawn_run_dir_tailer(path)?;
233-
let result = run_dashboard(&rx, &labels);
295+
let result = run_dashboard(&rx, &labels, baseline);
234296
stop.store(true, Ordering::Release);
235297
let _ = poller.join();
236298
result
@@ -283,19 +345,24 @@ fn spawn_run_dir_tailer(path: &Path) -> Result<RunDirTailer, Box<dyn Error>> {
283345
}
284346

285347
/// `emry tui` — attach to a run directory (`--run-dir`) or a socket (`--socket`).
286-
fn cmd_tui(run_dir: Option<&Path>, socket: Option<&Path>) -> Result<(), Box<dyn Error>> {
348+
fn cmd_tui(
349+
run_dir: Option<&Path>,
350+
socket: Option<&Path>,
351+
compare: Option<&Path>,
352+
) -> Result<(), Box<dyn Error>> {
287353
match (run_dir, socket) {
288-
(Some(dir), _) => cmd_watch(dir),
289-
(None, Some(sock)) => cmd_socket_tui(sock),
354+
(Some(dir), _) => cmd_watch(dir, compare),
355+
(None, Some(sock)) => cmd_socket_tui(sock, compare),
290356
(None, None) => Err("specify --run-dir or --socket".into()),
291357
}
292358
}
293359

294360
/// Reads framed events from a sidecar socket into the dashboard.
295-
fn cmd_socket_tui(sock: &Path) -> Result<(), Box<dyn Error>> {
361+
fn cmd_socket_tui(sock: &Path, compare: Option<&Path>) -> Result<(), Box<dyn Error>> {
362+
let baseline = load_compare(compare);
296363
let rx = spawn_socket_reader(sock)?;
297364
// Socket frames carry MetricIds, not names; labels fall back to `m{id}`.
298-
run_dashboard(&rx, &[])
365+
run_dashboard(&rx, &[], baseline)
299366
}
300367

301368
/// Connects to a sidecar socket and drains framed events into a bounded channel
@@ -335,8 +402,20 @@ fn cmd_web(
335402
(None, Some(sock)) => (spawn_socket_reader(sock)?, Vec::new()),
336403
(None, None) => return Err("specify --run-dir or --socket".into()),
337404
};
405+
// Load the comparison baseline via the one canonical reader
406+
// (`emry_store::load_baseline`) and map it into the web crate's serializable
407+
// types — same path the TUI overlay uses, so behaviour is consistent.
338408
let baseline = match compare {
339-
Some(path) => Some(emry_web::load_baseline(path)?),
409+
Some(path) => Some(emry_web::Baseline {
410+
metrics: emry_store::load_baseline(path)?
411+
.into_iter()
412+
.map(|s| emry_web::BaselineSeries {
413+
label: s.label,
414+
steps: s.steps,
415+
values: s.values,
416+
})
417+
.collect(),
418+
}),
340419
None => None,
341420
};
342421

@@ -602,7 +681,22 @@ mod tests {
602681
fn watch_requires_a_path() {
603682
assert!(parse(&["emry", "watch"]).is_err());
604683
match parse(&["emry", "watch", "./logs/run"]).unwrap() {
605-
Commands::Watch { path } => assert_eq!(path, PathBuf::from("./logs/run")),
684+
Commands::Watch { path, compare } => {
685+
assert_eq!(path, PathBuf::from("./logs/run"));
686+
assert!(compare.is_none());
687+
}
688+
other => panic!("unexpected {other:?}"),
689+
}
690+
}
691+
692+
#[test]
693+
fn watch_and_tui_accept_compare() {
694+
match parse(&["emry", "watch", "run", "--compare", "old"]).unwrap() {
695+
Commands::Watch { compare, .. } => assert_eq!(compare, Some(PathBuf::from("old"))),
696+
other => panic!("unexpected {other:?}"),
697+
}
698+
match parse(&["emry", "tui", "--run-dir", "run", "--compare", "old"]).unwrap() {
699+
Commands::Tui { compare, .. } => assert_eq!(compare, Some(PathBuf::from("old"))),
606700
other => panic!("unexpected {other:?}"),
607701
}
608702
}
@@ -619,7 +713,9 @@ mod tests {
619713
])
620714
.unwrap()
621715
{
622-
Commands::Tui { run_dir, socket } => {
716+
Commands::Tui {
717+
run_dir, socket, ..
718+
} => {
623719
assert_eq!(run_dir, Some(PathBuf::from("./logs/run")));
624720
assert_eq!(socket, Some(PathBuf::from("/tmp/e.sock")));
625721
}
@@ -630,7 +726,9 @@ mod tests {
630726
#[test]
631727
fn tui_flags_are_optional() {
632728
match parse(&["emry", "tui"]).unwrap() {
633-
Commands::Tui { run_dir, socket } => {
729+
Commands::Tui {
730+
run_dir, socket, ..
731+
} => {
634732
assert!(run_dir.is_none() && socket.is_none());
635733
}
636734
other => panic!("unexpected {other:?}"),
@@ -846,7 +944,7 @@ mod tests {
846944
#[test]
847945
fn tui_with_no_target_errors() {
848946
// Pure validation path (no terminal): both targets absent is an error.
849-
assert!(cmd_tui(None, None).is_err());
947+
assert!(cmd_tui(None, None, None).is_err());
850948
}
851949

852950
#[test]

‎crates/emry-store/src/lib.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,6 @@ pub use meta::{
1717
create_run_dir, run_dir_name, write_json, RunMetaFile, Summary, CONFIG_FILE, RUN_META_FILE,
1818
SUMMARY_FILE,
1919
};
20-
pub use runs::{final_metrics, list_runs, RunInfo};
20+
pub use runs::{final_metrics, list_runs, load_baseline, BaselineSeries, RunInfo};
2121
pub use sink::{JsonlSink, FLUSH_EVERY, FLUSH_INTERVAL};
2222
pub use writer::{JsonlWriter, EVENTS_FILE, METRICS_FILE};

‎crates/emry-store/src/runs.rs‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,63 @@ pub fn final_metrics(path: &Path) -> Result<BTreeMap<String, f64>, EmryError> {
105105
Ok(latest)
106106
}
107107

108+
/// One metric's full series from a run, for the comparison overlay (`emry watch
109+
/// --compare`). Steps and values are parallel and in file order.
110+
#[derive(Debug, Clone, PartialEq)]
111+
pub struct BaselineSeries {
112+
/// Metric name.
113+
pub label: String,
114+
/// Step of each value.
115+
pub steps: Vec<u64>,
116+
/// Values (parallel to `steps`).
117+
pub values: Vec<f64>,
118+
}
119+
120+
/// Reads a run's `metrics.jsonl` (`path` is the run directory or the file) into
121+
/// per-metric series, in first-seen metric order — the comparison baseline a run
122+
/// is overlaid against.
123+
///
124+
/// # Errors
125+
///
126+
/// Returns [`EmryError::Io`] if the file cannot be read or [`EmryError::Json`]
127+
/// if a line is not a valid [`MetricRecord`].
128+
pub fn load_baseline(path: &Path) -> Result<Vec<BaselineSeries>, EmryError> {
129+
let file = if path.is_dir() {
130+
path.join(METRICS_FILE)
131+
} else {
132+
path.to_path_buf()
133+
};
134+
let mut order: Vec<String> = Vec::new();
135+
let mut series: BTreeMap<String, (Vec<u64>, Vec<f64>)> = BTreeMap::new();
136+
for line in BufReader::new(std::fs::File::open(file)?).lines() {
137+
let line = line?;
138+
let trimmed = line.trim();
139+
if trimmed.is_empty() {
140+
continue;
141+
}
142+
let record: MetricRecord = serde_json::from_str(trimmed)?;
143+
for (name, value) in record.values {
144+
let entry = series.entry(name.clone()).or_insert_with(|| {
145+
order.push(name.clone());
146+
(Vec::new(), Vec::new())
147+
});
148+
entry.0.push(record.step);
149+
entry.1.push(value);
150+
}
151+
}
152+
Ok(order
153+
.into_iter()
154+
.map(|label| {
155+
let (steps, values) = series.remove(&label).unwrap_or_default();
156+
BaselineSeries {
157+
label,
158+
steps,
159+
values,
160+
}
161+
})
162+
.collect())
163+
}
164+
108165
/// Reads `summary.json` from a run directory, returning `None` if it is absent
109166
/// or unreadable (an unfinished or partially written run).
110167
fn read_summary(dir: &Path) -> Option<Summary> {
@@ -203,6 +260,32 @@ mod tests {
203260
assert_eq!(final_m["lr"], 0.1); // carried from the earlier row
204261
}
205262

263+
#[test]
264+
fn load_baseline_returns_series_in_first_seen_order() {
265+
let dir = crate::test_util::TempRunDir::new();
266+
std::fs::write(
267+
dir.path().join(METRICS_FILE),
268+
"{\"step\":0,\"epoch\":0,\"phase\":\"TRAIN\",\"values\":{\"loss\":1.0,\"lr\":0.1}}\n\
269+
{\"step\":2,\"epoch\":0,\"phase\":\"TRAIN\",\"values\":{\"loss\":0.4}}\n",
270+
)
271+
.unwrap();
272+
let series = load_baseline(dir.path()).unwrap();
273+
let loss = series.iter().find(|s| s.label == "loss").unwrap();
274+
assert_eq!(loss.steps, vec![0, 2]);
275+
assert_eq!(loss.values, vec![1.0, 0.4]);
276+
// lr only appears on the first row.
277+
let lr = series.iter().find(|s| s.label == "lr").unwrap();
278+
assert_eq!(lr.steps, vec![0]);
279+
}
280+
281+
#[test]
282+
fn load_baseline_errors_on_missing_file() {
283+
assert!(matches!(
284+
load_baseline(Path::new("/no/such/emry/metrics.jsonl")),
285+
Err(EmryError::Io(_))
286+
));
287+
}
288+
206289
#[test]
207290
fn final_metrics_errors_on_missing_file() {
208291
assert!(matches!(

‎crates/emry-tui/examples/tui_demo.rs‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1-
//! Live TUI demo: a synthetic training run streams to the dashboard.
1+
//! Live TUI demo: a synthetic training run streams to the dashboard, overlaid
2+
//! against a synthetic "previous run" baseline (the amber comparison curve).
23
//!
34
//! Run in a real terminal with: `cargo run -p emry-tui --example tui_demo`
45
//! Keys: `q`/`Esc` quit, `1`–`4` select metric, `p` pause.
6+
//! Select `loss` (`1`) or `loss_ema` (`3`) to see the dashed amber baseline.
57
68
use emry_engine::{Engine, RunConfig};
7-
use emry_tui::{run_terminal, UiState};
9+
use emry_tui::{run_terminal, BaselineSeries, UiState};
810
use std::time::Duration;
911

1012
fn main() -> Result<(), Box<dyn std::error::Error>> {
@@ -41,14 +43,34 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
4143
run.finish().ok();
4244
});
4345

44-
let state = UiState::with_labels(&[
46+
let mut state = UiState::with_labels(&[
4547
(loss, "loss"),
4648
(lr, "lr"),
4749
(loss_ema, "loss_ema"),
4850
(lr_ema, "lr_ema"),
4951
(sps, "steps_per_sec"),
5052
(eta, "eta_secs"),
5153
]);
54+
// A synthetic "previous run" whose loss decays more slowly, overlaid as the
55+
// amber comparison baseline behind the live (terracotta) curve.
56+
state.set_baseline(synthetic_baseline());
5257
run_terminal(&events, state)?;
5358
Ok(())
5459
}
60+
61+
/// A prior-run baseline for `loss` / `loss_ema` that sits above the live curve.
62+
fn synthetic_baseline() -> Vec<BaselineSeries> {
63+
let (mut steps, mut values) = (Vec::new(), Vec::new());
64+
for step in (0..2000u64).step_by(5) {
65+
#[allow(clippy::cast_precision_loss)]
66+
let loss = 2.3 / (1.0 + step as f64 * 0.0032);
67+
steps.push(step);
68+
values.push(loss);
69+
}
70+
let series = |label: &str| BaselineSeries {
71+
label: label.to_string(),
72+
steps: steps.clone(),
73+
values: values.clone(),
74+
};
75+
vec![series("loss"), series("loss_ema")]
76+
}

0 commit comments

Comments
 (0)