trustformers-debug 0.1.1

Advanced debugging tools for TrustformeRS models
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! Perfetto/Chrome Trace Event Format export
//!
//! Exports profiling data in Perfetto JSON format compatible with
//! `chrome://tracing` and the Perfetto UI at <https://ui.perfetto.dev>.
//!
//! # Example
//!
//! ```no_run
//! use trustformers_debug::export::perfetto::{PerfettoTrace, PerfettoEvent, PerfettoPhase};
//! use std::collections::HashMap;
//!
//! let mut trace = PerfettoTrace::new();
//! let mut args = HashMap::new();
//! args.insert("layer".to_string(), serde_json::json!("attention"));
//! trace.add_event(PerfettoEvent {
//!     name: "layer_forward".to_string(),
//!     phase: PerfettoPhase::Complete,
//!     timestamp_us: 12345,
//!     duration_us: Some(1500),
//!     pid: 1,
//!     tid: 1,
//!     args,
//! });
//! let json = trace.export_to_string().unwrap();
//! println!("{}", json);
//! ```

use std::collections::HashMap;
use std::io::Write;

use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::ProfilerReport;

// ─────────────────────────────────────────────────────────────
// Public types
// ─────────────────────────────────────────────────────────────

/// Phase codes used in the Perfetto/Chrome trace-event format.
///
/// Each variant corresponds to the `ph` field in a trace-event object.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum PerfettoPhase {
    /// `B` — duration begin.
    Begin,
    /// `E` — duration end.
    End,
    /// `X` — complete (begin + duration).
    Complete,
    /// `i` — instant event.
    Instant,
    /// `C` — counter.
    Counter,
}

impl PerfettoPhase {
    /// Returns the single-character phase code.
    pub fn as_code(&self) -> &'static str {
        match self {
            Self::Begin => "B",
            Self::End => "E",
            Self::Complete => "X",
            Self::Instant => "i",
            Self::Counter => "C",
        }
    }
}

/// A single trace event in Perfetto/Chrome format.
///
/// # Example
///
/// ```
/// use std::collections::HashMap;
/// use trustformers_debug::export::perfetto::{PerfettoEvent, PerfettoPhase};
///
/// let event = PerfettoEvent {
///     name: "forward".to_string(),
///     phase: PerfettoPhase::Complete,
///     timestamp_us: 0,
///     duration_us: Some(500),
///     pid: 1,
///     tid: 1,
///     args: HashMap::new(),
/// };
/// assert_eq!(event.phase.as_code(), "X");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerfettoEvent {
    /// Human-readable name shown in the trace viewer.
    pub name: String,
    /// Event phase (Begin, End, Complete, Instant, Counter).
    pub phase: PerfettoPhase,
    /// Timestamp in **microseconds** since the trace start.
    pub timestamp_us: u64,
    /// Duration in microseconds (required for `Complete` events).
    pub duration_us: Option<u64>,
    /// Process ID.
    pub pid: u32,
    /// Thread ID.
    pub tid: u32,
    /// Arbitrary key-value metadata.
    pub args: HashMap<String, Value>,
}

/// An in-memory collection of [`PerfettoEvent`]s that can be serialised to
/// the Chrome trace-event JSON format.
///
/// # Example
///
/// ```
/// use trustformers_debug::export::perfetto::PerfettoTrace;
///
/// let trace = PerfettoTrace::new();
/// assert_eq!(trace.len(), 0);
/// ```
#[derive(Debug, Default)]
pub struct PerfettoTrace {
    events: Vec<PerfettoEvent>,
}

impl PerfettoTrace {
    /// Creates an empty trace.
    pub fn new() -> Self {
        Self::default()
    }

    /// Appends a single event.
    pub fn add_event(&mut self, event: PerfettoEvent) {
        self.events.push(event);
    }

    /// Returns the number of events in the trace.
    pub fn len(&self) -> usize {
        self.events.len()
    }

    /// Returns `true` if the trace contains no events.
    pub fn is_empty(&self) -> bool {
        self.events.is_empty()
    }

    /// Serialises the trace to a JSON string in Perfetto format.
    ///
    /// # Errors
    ///
    /// Returns an error if JSON serialisation fails.
    ///
    /// # Example
    ///
    /// ```
    /// use trustformers_debug::export::perfetto::PerfettoTrace;
    ///
    /// let trace = PerfettoTrace::new();
    /// let json = trace.export_to_string().unwrap();
    /// assert!(json.contains("traceEvents"));
    /// ```
    pub fn export_to_string(&self) -> Result<String> {
        let doc = self.build_doc();
        Ok(serde_json::to_string_pretty(&doc)?)
    }

    /// Writes the trace to a file at `path`.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be created or written to, or if
    /// JSON serialisation fails.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use trustformers_debug::export::perfetto::PerfettoTrace;
    ///
    /// let trace = PerfettoTrace::new();
    /// trace.export_to_file(std::path::Path::new("/tmp/trace.json")).unwrap();
    /// ```
    pub fn export_to_file(&self, path: &std::path::Path) -> Result<()> {
        let json = self.export_to_string()?;
        let mut file = std::fs::File::create(path)?;
        file.write_all(json.as_bytes())?;
        tracing::debug!("Perfetto trace written to {}", path.display());
        Ok(())
    }

    // ── helpers ──────────────────────────────────────────────

    fn build_doc(&self) -> Value {
        let events: Vec<Value> = self.events.iter().map(event_to_value).collect();
        serde_json::json!({
            "traceEvents": events,
            "displayTimeUnit": "ms",
        })
    }
}

// ─────────────────────────────────────────────────────────────
// PerfettoExporter
// ─────────────────────────────────────────────────────────────

/// Converts a [`ProfilerReport`] to a [`PerfettoTrace`] and writes it to disk.
///
/// # Example
///
/// ```no_run
/// use trustformers_debug::export::perfetto::PerfettoExporter;
/// use trustformers_debug::ProfilerReport;
/// use std::collections::HashMap;
/// use std::time::Duration;
///
/// // Build a minimal report for demonstration.
/// let report = ProfilerReport {
///     total_events: 0,
///     total_runtime: Duration::from_millis(0),
///     statistics: HashMap::new(),
///     bottlenecks: vec![],
///     slowest_layers: vec![],
///     memory_efficiency: Default::default(),
///     recommendations: vec![],
/// };
/// PerfettoExporter::export_profiler_report(
///     &report,
///     std::path::Path::new("/tmp/report.json"),
/// ).unwrap();
/// ```
pub struct PerfettoExporter;

impl PerfettoExporter {
    /// Converts a [`ProfilerReport`] into a Perfetto trace file.
    ///
    /// Each layer in [`ProfilerReport::slowest_layers`] becomes a `Complete`
    /// trace event.  Bottlenecks are appended as `Instant` events.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be written.
    pub fn export_profiler_report(
        report: &ProfilerReport,
        path: &std::path::Path,
    ) -> Result<()> {
        let mut trace = PerfettoTrace::new();
        let mut cursor_us: u64 = 0;

        for (layer_name, duration) in &report.slowest_layers {
            let dur_us = duration.as_micros() as u64;
            let mut args = HashMap::new();
            args.insert("layer_name".to_string(), Value::String(layer_name.clone()));
            trace.add_event(PerfettoEvent {
                name: layer_name.clone(),
                phase: PerfettoPhase::Complete,
                timestamp_us: cursor_us,
                duration_us: Some(dur_us),
                pid: 1,
                tid: 1,
                args,
            });
            cursor_us += dur_us;
        }

        for bottleneck in &report.bottlenecks {
            let mut args = HashMap::new();
            args.insert(
                "description".to_string(),
                Value::String(bottleneck.description.clone()),
            );
            args.insert(
                "suggestion".to_string(),
                Value::String(bottleneck.suggestion.clone()),
            );
            trace.add_event(PerfettoEvent {
                name: format!("bottleneck:{}", bottleneck.location),
                phase: PerfettoPhase::Instant,
                timestamp_us: cursor_us,
                duration_us: None,
                pid: 1,
                tid: 1,
                args,
            });
        }

        trace.export_to_file(path)
    }
}

// ─────────────────────────────────────────────────────────────
// Private helpers
// ─────────────────────────────────────────────────────────────

fn event_to_value(e: &PerfettoEvent) -> Value {
    let mut obj = serde_json::json!({
        "name": e.name,
        "ph": e.phase.as_code(),
        "ts": e.timestamp_us,
        "pid": e.pid,
        "tid": e.tid,
    });

    if let Some(dur) = e.duration_us {
        obj["dur"] = Value::Number(dur.into());
    }

    if !e.args.is_empty() {
        obj["args"] = Value::Object(
            e.args
                .iter()
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect(),
        );
    }

    obj
}

// ─────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    fn make_event(name: &str, phase: PerfettoPhase, ts: u64, dur: Option<u64>) -> PerfettoEvent {
        PerfettoEvent {
            name: name.to_string(),
            phase,
            timestamp_us: ts,
            duration_us: dur,
            pid: 1,
            tid: 1,
            args: HashMap::new(),
        }
    }

    #[test]
    fn test_empty_trace_roundtrip() {
        let trace = PerfettoTrace::new();
        let json = trace.export_to_string().unwrap();
        let parsed: Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["traceEvents"].as_array().unwrap().len(), 0);
        assert_eq!(parsed["displayTimeUnit"], "ms");
    }

    #[test]
    fn test_add_complete_event() {
        let mut trace = PerfettoTrace::new();
        trace.add_event(make_event(
            "forward",
            PerfettoPhase::Complete,
            1000,
            Some(500),
        ));
        assert_eq!(trace.len(), 1);

        let json = trace.export_to_string().unwrap();
        let parsed: Value = serde_json::from_str(&json).unwrap();
        let ev = &parsed["traceEvents"][0];
        assert_eq!(ev["ph"], "X");
        assert_eq!(ev["ts"], 1000_u64);
        assert_eq!(ev["dur"], 500_u64);
        assert_eq!(ev["name"], "forward");
    }

    #[test]
    fn test_begin_end_phases() {
        let mut trace = PerfettoTrace::new();
        trace.add_event(make_event("op", PerfettoPhase::Begin, 0, None));
        trace.add_event(make_event("op", PerfettoPhase::End, 200, None));
        let json = trace.export_to_string().unwrap();
        let parsed: Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["traceEvents"][0]["ph"], "B");
        assert_eq!(parsed["traceEvents"][1]["ph"], "E");
    }

    #[test]
    fn test_export_to_file() {
        let mut dir = std::env::temp_dir();
        dir.push("perfetto_test_trace.json");

        let mut trace = PerfettoTrace::new();
        let mut args = HashMap::new();
        args.insert("batch_size".to_string(), serde_json::json!(32));
        trace.add_event(PerfettoEvent {
            name: "attention_forward".to_string(),
            phase: PerfettoPhase::Complete,
            timestamp_us: 0,
            duration_us: Some(1500),
            pid: 1,
            tid: 2,
            args,
        });
        trace.export_to_file(&dir).unwrap();
        assert!(dir.exists());

        let content = std::fs::read_to_string(&dir).unwrap();
        let parsed: Value = serde_json::from_str(&content).unwrap();
        assert_eq!(parsed["traceEvents"].as_array().unwrap().len(), 1);

        std::fs::remove_file(&dir).ok();
    }

    #[test]
    fn test_exporter_from_profiler_report() {
        use crate::profiler::{MemoryEfficiencyAnalysis, PerformanceBottleneck};

        let mut dir = std::env::temp_dir();
        dir.push("perfetto_profiler_report.json");

        let report = ProfilerReport {
            total_events: 2,
            total_runtime: Duration::from_millis(100),
            statistics: HashMap::new(),
            bottlenecks: vec![PerformanceBottleneck {
                bottleneck_type: crate::profiler::BottleneckType::CpuBound,
                location: "attention".to_string(),
                severity: crate::profiler::BottleneckSeverity::Medium,
                description: "CPU saturated".to_string(),
                suggestion: "Use flash attention".to_string(),
                metrics: HashMap::new(),
            }],
            slowest_layers: vec![
                ("attention".to_string(), Duration::from_millis(10)),
                ("ffn".to_string(), Duration::from_millis(15)),
            ],
            memory_efficiency: MemoryEfficiencyAnalysis::default(),
            recommendations: vec![],
        };

        PerfettoExporter::export_profiler_report(&report, &dir).unwrap();
        assert!(dir.exists());

        let content = std::fs::read_to_string(&dir).unwrap();
        let parsed: Value = serde_json::from_str(&content).unwrap();
        let events = parsed["traceEvents"].as_array().unwrap();
        // 2 layer events + 1 bottleneck instant event
        assert_eq!(events.len(), 3);
        assert_eq!(events[2]["ph"], "i");

        std::fs::remove_file(&dir).ok();
    }

    #[test]
    fn test_instant_and_counter_phases() {
        let mut trace = PerfettoTrace::new();
        trace.add_event(make_event("checkpoint", PerfettoPhase::Instant, 500, None));
        trace.add_event(make_event("loss", PerfettoPhase::Counter, 600, None));
        let json = trace.export_to_string().unwrap();
        let parsed: Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["traceEvents"][0]["ph"], "i");
        assert_eq!(parsed["traceEvents"][1]["ph"], "C");
    }
}