Skip to content

Commit 88f5e23

Browse files
voidstackloopclaude
andcommitted
profiler: op-level profiler (aggregate table, Chrome trace), user ranges, NaN/inf anomaly detection; SummaryWriter for TensorBoard event files (verified with TensorBoard's reader)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 9914b48 commit 88f5e23

8 files changed

Lines changed: 516 additions & 0 deletions

File tree

‎crates/oxideon-core/src/backend/mod.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,7 @@ impl Storage {
250250
}
251251

252252
pub fn unary_op(&self, layout: &Layout, op: UnaryOp) -> Result<Self> {
253+
let _prof = crate::profiler::scope("unary_op", layout.shape());
253254
match &*self.read() {
254255
StorageInner::Cpu(s) => Ok(Self::new_cpu(s.unary_op(layout, op)?)),
255256
#[cfg(feature = "wgpu")]
@@ -272,6 +273,7 @@ impl Storage {
272273
rhs_layout: &Layout,
273274
op: BinaryOp,
274275
) -> Result<Self> {
276+
let _prof = crate::profiler::scope("binary_op", lhs_layout.shape());
275277
if self.device() != rhs.device() {
276278
return Err(Error::DeviceMismatch {
277279
op: "binary_op",
@@ -333,6 +335,7 @@ impl Storage {
333335
rhs_layout: &Layout,
334336
op: CmpOp,
335337
) -> Result<Self> {
338+
let _prof = crate::profiler::scope("cmp_op", lhs_layout.shape());
336339
if self.device() != rhs.device() {
337340
return Err(Error::DeviceMismatch {
338341
op: "cmp_op",
@@ -562,6 +565,7 @@ impl Storage {
562565
}
563566

564567
pub fn reduce_op(&self, layout: &Layout, axes: &[usize], op: ReduceOp) -> Result<Self> {
568+
let _prof = crate::profiler::scope("reduce_op", layout.shape());
565569
match &*self.read() {
566570
StorageInner::Cpu(s) => Ok(Self::new_cpu(s.reduce_op(layout, axes, op)?)),
567571
#[cfg(feature = "wgpu")]
@@ -622,6 +626,7 @@ impl Storage {
622626
}
623627

624628
pub fn matmul(&self, lhs_l: &Layout, rhs: &Self, rhs_l: &Layout) -> Result<(Self, Vec<usize>)> {
629+
let _prof = crate::profiler::scope("matmul", lhs_l.shape());
625630
if self.device() != rhs.device() {
626631
return Err(Error::DeviceMismatch {
627632
op: "matmul",
@@ -697,6 +702,7 @@ impl Storage {
697702
}
698703

699704
pub fn to_contiguous(&self, layout: &Layout) -> Result<Self> {
705+
let _prof = crate::profiler::scope("to_contiguous", layout.shape());
700706
match &*self.read() {
701707
StorageInner::Cpu(s) => Ok(Self::new_cpu(s.to_contiguous(layout)?)),
702708
#[cfg(feature = "wgpu")]
@@ -713,6 +719,7 @@ impl Storage {
713719
}
714720

715721
pub fn to_dtype(&self, layout: &Layout, dst: DType) -> Result<Self> {
722+
let _prof = crate::profiler::scope("to_dtype", layout.shape());
716723
match &*self.read() {
717724
StorageInner::Cpu(s) => Ok(Self::new_cpu(s.to_dtype(layout, dst)?)),
718725
#[cfg(feature = "wgpu")]

‎crates/oxideon-core/src/lib.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,8 @@ pub mod serving;
111111
pub mod signal;
112112
pub mod sparse;
113113
pub mod structured;
114+
pub mod profiler;
115+
pub mod summary_writer;
114116
pub mod transforms;
115117
pub mod sparse_ext;
116118
pub mod ops_stats;
Lines changed: 263 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,263 @@
1+
//! Operator profiler and anomaly detection.
2+
//!
3+
//! [`profile`] (or [`start`] / [`stop`]) records every backend operation (unary / binary / comparison / reduction / matmul /
4+
//! dtype and device conversions) with its wall time, thread and input shape, plus user ranges opened with [`record_function`].
5+
//! A [`Profile`] prints an aggregated table (like `torch.profiler`'s `key_averages().table()`) and exports a Chrome trace
6+
//! (`chrome://tracing`, Perfetto). When profiling is off the hooks cost one atomic load.
7+
//!
8+
//! [`set_detect_anomaly`] makes the library remember the first operation whose result contained a NaN or infinity
9+
//! ([`first_non_finite`]), the tool for finding where a training run first diverged.
10+
11+
use crate::error::Result;
12+
use std::collections::HashMap;
13+
use std::sync::atomic::{AtomicBool, Ordering};
14+
use std::sync::{Mutex, OnceLock};
15+
use std::time::Instant;
16+
17+
static ACTIVE: AtomicBool = AtomicBool::new(false);
18+
static ANOMALY: AtomicBool = AtomicBool::new(false);
19+
20+
struct State {
21+
origin: Instant,
22+
events: Vec<Event>,
23+
}
24+
25+
fn state() -> &'static Mutex<State> {
26+
static S: OnceLock<Mutex<State>> = OnceLock::new();
27+
S.get_or_init(|| Mutex::new(State { origin: Instant::now(), events: Vec::new() }))
28+
}
29+
30+
fn first_bad() -> &'static Mutex<Option<(String, Vec<usize>)>> {
31+
static S: OnceLock<Mutex<Option<(String, Vec<usize>)>>> = OnceLock::new();
32+
S.get_or_init(|| Mutex::new(None))
33+
}
34+
35+
/// One recorded operation or user range.
36+
#[derive(Debug, Clone)]
37+
pub struct Event {
38+
pub name: String,
39+
pub category: &'static str,
40+
pub thread: u64,
41+
/// Start, in microseconds since the profile began.
42+
pub start_us: f64,
43+
pub dur_us: f64,
44+
pub shape: Vec<usize>,
45+
}
46+
47+
fn thread_id() -> u64 {
48+
use std::hash::{Hash, Hasher};
49+
let mut h = std::collections::hash_map::DefaultHasher::new();
50+
std::thread::current().id().hash(&mut h);
51+
h.finish() % 100_000
52+
}
53+
54+
/// RAII timer returned by the hooks; records its event when dropped.
55+
pub struct Scope {
56+
name: String,
57+
category: &'static str,
58+
shape: Vec<usize>,
59+
start: Instant,
60+
}
61+
62+
impl Drop for Scope {
63+
fn drop(&mut self) {
64+
let end = Instant::now();
65+
let mut s = state().lock().unwrap();
66+
let start_us = self.start.saturating_duration_since(s.origin).as_secs_f64() * 1e6;
67+
let dur_us = end.duration_since(self.start).as_secs_f64() * 1e6;
68+
s.events.push(Event { name: std::mem::take(&mut self.name), category: self.category, thread: thread_id(), start_us, dur_us, shape: std::mem::take(&mut self.shape) });
69+
}
70+
}
71+
72+
/// The hook the backend calls at the start of an operation (`None`, and free, when no profile is running).
73+
#[inline]
74+
pub fn scope(name: &'static str, shape: &[usize]) -> Option<Scope> {
75+
if !ACTIVE.load(Ordering::Relaxed) {
76+
return None;
77+
}
78+
Some(Scope { name: name.to_string(), category: "op", shape: shape.to_vec(), start: Instant::now() })
79+
}
80+
81+
/// A named range of user code (a layer, a training phase) shown next to the operations it contains.
82+
pub fn record_function(name: &str) -> Option<Scope> {
83+
if !ACTIVE.load(Ordering::Relaxed) {
84+
return None;
85+
}
86+
Some(Scope { name: name.to_string(), category: "user", shape: Vec::new(), start: Instant::now() })
87+
}
88+
89+
/// Starts recording (discarding any earlier events).
90+
pub fn start() {
91+
let mut s = state().lock().unwrap();
92+
s.origin = Instant::now();
93+
s.events.clear();
94+
ACTIVE.store(true, Ordering::SeqCst);
95+
}
96+
97+
/// Stops recording and returns what was captured.
98+
pub fn stop() -> Profile {
99+
ACTIVE.store(false, Ordering::SeqCst);
100+
let mut s = state().lock().unwrap();
101+
let mut events = std::mem::take(&mut s.events);
102+
events.sort_by(|a, b| a.start_us.partial_cmp(&b.start_us).unwrap_or(std::cmp::Ordering::Equal));
103+
Profile { events }
104+
}
105+
106+
/// Runs `f` under the profiler.
107+
pub fn profile<R>(f: impl FnOnce() -> R) -> (R, Profile) {
108+
start();
109+
let r = f();
110+
(r, stop())
111+
}
112+
113+
pub fn is_profiling() -> bool {
114+
ACTIVE.load(Ordering::Relaxed)
115+
}
116+
117+
/// Aggregated statistics of one operation name.
118+
#[derive(Debug, Clone)]
119+
pub struct OpStats {
120+
pub name: String,
121+
pub calls: usize,
122+
pub total_us: f64,
123+
pub mean_us: f64,
124+
pub max_us: f64,
125+
}
126+
127+
#[derive(Debug, Clone, Default)]
128+
pub struct Profile {
129+
pub events: Vec<Event>,
130+
}
131+
132+
impl Profile {
133+
/// Per-operation totals, slowest first. User ranges are listed too (their time includes the operations inside them).
134+
pub fn key_averages(&self) -> Vec<OpStats> {
135+
let mut m: HashMap<&str, (usize, f64, f64)> = HashMap::new();
136+
for e in &self.events {
137+
let x = m.entry(&e.name).or_insert((0, 0.0, 0.0));
138+
x.0 += 1;
139+
x.1 += e.dur_us;
140+
x.2 = x.2.max(e.dur_us);
141+
}
142+
let mut v: Vec<OpStats> = m.into_iter().map(|(n, (c, t, mx))| OpStats { name: n.to_string(), calls: c, total_us: t, mean_us: t / c as f64, max_us: mx }).collect();
143+
v.sort_by(|a, b| b.total_us.partial_cmp(&a.total_us).unwrap_or(std::cmp::Ordering::Equal).then(a.name.cmp(&b.name)));
144+
v
145+
}
146+
147+
/// Sum of the time spent in backend operations (user ranges excluded; nested operations are counted once each).
148+
pub fn total_op_time_us(&self) -> f64 {
149+
self.events.iter().filter(|e| e.category == "op").map(|e| e.dur_us).sum()
150+
}
151+
152+
/// A fixed-width table of [`key_averages`](Self::key_averages).
153+
pub fn table(&self) -> String {
154+
let total = self.total_op_time_us().max(1e-9);
155+
let mut out = format!("{:<24} {:>8} {:>12} {:>12} {:>12} {:>7}\n", "name", "calls", "total (us)", "mean (us)", "max (us)", "% ops");
156+
for s in self.key_averages() {
157+
out.push_str(&format!("{:<24} {:>8} {:>12.1} {:>12.2} {:>12.1} {:>6.1}%\n", s.name, s.calls, s.total_us, s.mean_us, s.max_us, 100.0 * s.total_us / total));
158+
}
159+
out
160+
}
161+
162+
/// Chrome trace event format (open in `chrome://tracing` or Perfetto).
163+
pub fn chrome_trace(&self) -> String {
164+
let esc = |s: &str| s.replace('\\', "\\\\").replace('"', "\\\"");
165+
let items: Vec<String> = self
166+
.events
167+
.iter()
168+
.map(|e| {
169+
format!(
170+
"{{\"name\":\"{}\",\"cat\":\"{}\",\"ph\":\"X\",\"ts\":{:.3},\"dur\":{:.3},\"pid\":1,\"tid\":{},\"args\":{{\"shape\":\"{:?}\"}}}}",
171+
esc(&e.name),
172+
e.category,
173+
e.start_us,
174+
e.dur_us,
175+
e.thread,
176+
e.shape
177+
)
178+
})
179+
.collect();
180+
format!("{{\"traceEvents\":[{}],\"displayTimeUnit\":\"ms\"}}", items.join(","))
181+
}
182+
183+
pub fn save_chrome_trace(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
184+
std::fs::write(path.as_ref(), self.chrome_trace()).map_err(|e| crate::error::Error::Msg(format!("profiler: cannot write {}: {e}", path.as_ref().display())))
185+
}
186+
}
187+
188+
// ------------------------------------------------------------------------------------------------ anomaly detection
189+
190+
/// Turns the NaN / infinity watch on or off. While on, every operation result created through autograd is checked and the
191+
/// first offender is remembered.
192+
pub fn set_detect_anomaly(on: bool) {
193+
ANOMALY.store(on, Ordering::SeqCst);
194+
if on {
195+
*first_bad().lock().unwrap() = None;
196+
}
197+
}
198+
199+
#[inline]
200+
pub(crate) fn anomaly_enabled() -> bool {
201+
ANOMALY.load(Ordering::Relaxed)
202+
}
203+
204+
pub(crate) fn note_non_finite(op: &str, shape: &[usize]) {
205+
let mut g = first_bad().lock().unwrap();
206+
if g.is_none() {
207+
*g = Some((op.to_string(), shape.to_vec()));
208+
}
209+
}
210+
211+
/// The operation (and its output shape) that first produced a NaN or infinity since [`set_detect_anomaly`]`(true)`.
212+
pub fn first_non_finite() -> Option<(String, Vec<usize>)> {
213+
first_bad().lock().unwrap().clone()
214+
}
215+
216+
#[cfg(test)]
217+
mod tests {
218+
use super::*;
219+
use crate::dtype::DType;
220+
use crate::tensor::Tensor;
221+
222+
// the profiler and anomaly flags are global: run these tests one at a time
223+
static ONE: Mutex<()> = Mutex::new(());
224+
225+
#[test]
226+
fn records_operations_user_ranges_and_exports_a_trace() {
227+
let _g = ONE.lock().unwrap_or_else(|p| p.into_inner());
228+
let a = Tensor::randn(&[64, 64]).unwrap();
229+
let (_, prof) = profile(|| {
230+
let _r = record_function("my_block");
231+
let y = a.matmul(&a).unwrap().relu().unwrap().add(&a).unwrap();
232+
y.sum().unwrap()
233+
});
234+
let names: Vec<String> = prof.key_averages().into_iter().map(|s| s.name).collect();
235+
for want in ["matmul", "unary_op", "binary_op", "reduce_op", "my_block"] {
236+
assert!(names.iter().any(|n| n == want), "{want} missing from {names:?}");
237+
}
238+
assert!(prof.total_op_time_us() > 0.0);
239+
assert!(prof.table().contains("matmul"));
240+
let trace = prof.chrome_trace();
241+
assert!(trace.starts_with("{\"traceEvents\":[") && trace.contains("\"ph\":\"X\"") && trace.contains("my_block"));
242+
// nothing is recorded once stopped
243+
a.matmul(&a).unwrap();
244+
assert!(!is_profiling());
245+
assert!(stop().events.is_empty());
246+
}
247+
248+
#[test]
249+
fn anomaly_detection_names_the_first_non_finite_operation() {
250+
let _g = ONE.lock().unwrap_or_else(|p| p.into_inner());
251+
set_detect_anomaly(true);
252+
let x = Tensor::from_slice(&[1.0f32, 0.0, 2.0], &[3]).unwrap().requires_grad_(true);
253+
let _ = x.exp().unwrap().sum().unwrap(); // finite
254+
assert!(first_non_finite().is_none());
255+
let bad = x.recip().unwrap(); // 1 / 0 = inf
256+
let _ = bad.mul_scalar(2.0).unwrap();
257+
let (op, shape) = first_non_finite().expect("the infinity should have been noticed");
258+
assert!(op.contains("recip") || op.contains("div"), "{op}");
259+
assert_eq!(shape, vec![3]);
260+
set_detect_anomaly(false);
261+
let _ = DType::F32;
262+
}
263+
}

0 commit comments

Comments
 (0)