aprender-cgp 0.31.1

Compute-GPU-Profile: Unified performance analysis CLI for scalar, SIMD, wgpu, and CUDA workloads
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
//! CPU SIMD profiling via perf stat + renacer + trueno-explain.
//! Spec section 4.2.

use anyhow::Result;
use std::collections::HashMap;
use std::process::Command;

/// perf stat hardware counters for SIMD analysis.
pub const SIMD_PERF_EVENTS: &[&str] = &[
    "cycles",
    "instructions",
    "cache-references",
    "cache-misses",
    "L1-dcache-load-misses",
    "LLC-loads",
    "branches",
    "branch-misses",
];

/// Architecture-specific perf events for SIMD utilization.
pub const AVX2_EVENTS: &[&str] = &[
    "fp_arith_inst_retired.scalar_single",
    "fp_arith_inst_retired.128b_packed_single",
    "fp_arith_inst_retired.256b_packed_single",
];

pub const AVX512_EVENTS: &[&str] = &[
    "fp_arith_inst_retired.scalar_single",
    "fp_arith_inst_retired.256b_packed_single",
    "fp_arith_inst_retired.512b_packed_single",
];

/// Parsed perf stat output.
#[derive(Debug, Clone, Default)]
pub struct PerfStatResult {
    pub counters: HashMap<String, u64>,
    pub wall_time_secs: f64,
}

impl PerfStatResult {
    /// Compute IPC (instructions per cycle).
    pub fn ipc(&self) -> f64 {
        let cycles = *self.counters.get("cycles").unwrap_or(&0) as f64;
        let instructions = *self.counters.get("instructions").unwrap_or(&0) as f64;
        if cycles > 0.0 {
            instructions / cycles
        } else {
            0.0
        }
    }

    /// Compute cache miss rate.
    pub fn cache_miss_rate(&self) -> f64 {
        let refs = *self.counters.get("cache-references").unwrap_or(&0) as f64;
        let misses = *self.counters.get("cache-misses").unwrap_or(&0) as f64;
        if refs > 0.0 {
            misses / refs * 100.0
        } else {
            0.0
        }
    }

    /// Compute branch misprediction rate.
    pub fn branch_miss_rate(&self) -> f64 {
        let branches = *self.counters.get("branches").unwrap_or(&0) as f64;
        let misses = *self.counters.get("branch-misses").unwrap_or(&0) as f64;
        if branches > 0.0 {
            misses / branches * 100.0
        } else {
            0.0
        }
    }

    /// Compute SIMD utilization: vector_ops / (vector_ops + scalar_ops) * 100.
    pub fn simd_utilization(&self) -> Option<f64> {
        let scalar = *self
            .counters
            .get("fp_arith_inst_retired.scalar_single")
            .unwrap_or(&0) as f64;
        let vec128 = *self
            .counters
            .get("fp_arith_inst_retired.128b_packed_single")
            .unwrap_or(&0) as f64;
        let vec256 = *self
            .counters
            .get("fp_arith_inst_retired.256b_packed_single")
            .unwrap_or(&0) as f64;
        let vec512 = *self
            .counters
            .get("fp_arith_inst_retired.512b_packed_single")
            .unwrap_or(&0) as f64;

        let vector = vec128 + vec256 + vec512;
        let total = scalar + vector;
        if total > 0.0 {
            Some(vector / total * 100.0)
        } else {
            None
        }
    }
}

/// Run perf stat and parse the output.
pub fn run_perf_stat(binary: &str, args: &[&str], events: &[&str]) -> Result<PerfStatResult> {
    let event_str = events.join(",");
    let mut cmd = Command::new("perf");
    cmd.arg("stat")
        .arg("-e")
        .arg(&event_str)
        .arg("-x")
        .arg(",") // CSV separator
        .arg(binary)
        .args(args);

    let output = cmd.output()?;
    let stderr = String::from_utf8_lossy(&output.stderr);

    parse_perf_stat_csv(&stderr)
}

/// Parse perf stat CSV output (perf writes stats to stderr).
/// Format: value,unit,event_name,... (with -x ,)
pub fn parse_perf_stat_csv(output: &str) -> Result<PerfStatResult> {
    let mut result = PerfStatResult::default();

    for line in output.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') || line.starts_with("Performance") {
            continue;
        }

        // Extract wall time from "X.YZ seconds time elapsed" lines
        if line.contains("seconds time elapsed") {
            if let Some(time_str) = line.split_whitespace().next() {
                if let Ok(t) = time_str.parse::<f64>() {
                    result.wall_time_secs = t;
                }
            }
            continue;
        }

        // CSV format: value,unit,event-name,...
        let fields: Vec<&str> = line.split(',').collect();
        if fields.len() >= 3 {
            let value_str = fields[0].trim().replace(' ', "");
            let event_name = fields[2].trim();

            if let Ok(value) = value_str.parse::<u64>() {
                result.counters.insert(event_name.to_string(), value);
            }
        }
    }

    Ok(result)
}

/// Profile a SIMD function.
pub fn profile_simd(function: &str, size: u32, arch: &str) -> Result<()> {
    println!("\n=== CGP SIMD Profile: {function} (size={size}, arch={arch}) ===\n");

    let Some(simd_events) = resolve_simd_events(arch)? else {
        println!();
        return Ok(());
    };

    if which::which("perf").is_err() {
        print_perf_missing(function, arch);
        println!();
        return Ok(());
    }

    let Some(binary) = find_bench_binary() else {
        println!("  No benchmark binary found.");
        println!("  Build with: cargo build --release --bench vector_ops");
        println!("  Then re-run cgp profile simd.");
        println!();
        return Ok(());
    };

    profile_with_perf(&binary, simd_events);
    println!();
    Ok(())
}

/// Return the SIMD perf event list for `arch`, or `None` when the arch is
/// unsupported on the host (early-exit for caller). Warning printed to stdout.
fn resolve_simd_events(arch: &str) -> Result<Option<&'static [&'static str]>> {
    match arch {
        "avx2" => {
            #[cfg(target_arch = "x86_64")]
            {
                if !std::arch::is_x86_feature_detected!("avx2") {
                    println!("  Warning: AVX2 not available on this CPU.");
                }
            }
            Ok(Some(AVX2_EVENTS))
        }
        "avx512" => {
            #[cfg(target_arch = "x86_64")]
            {
                if !std::arch::is_x86_feature_detected!("avx512f") {
                    println!("  Warning: AVX-512 not available on this CPU.");
                }
            }
            Ok(Some(AVX512_EVENTS))
        }
        "neon" => {
            #[cfg(not(target_arch = "aarch64"))]
            {
                println!("  NEON not available -- use --cross-profile for QEMU-based analysis");
                Ok(None)
            }
            #[cfg(target_arch = "aarch64")]
            {
                const NEON_EVENTS: &[&str] = &["INST_RETIRED", "CPU_CYCLES", "ASE_SPEC"];
                Ok(Some(NEON_EVENTS))
            }
        }
        "sse2" => {
            const SSE2_EVENTS: &[&str] = &[
                "fp_arith_inst_retired.scalar_single",
                "fp_arith_inst_retired.128b_packed_single",
            ];
            Ok(Some(SSE2_EVENTS))
        }
        _ => {
            anyhow::bail!("Unknown SIMD architecture: {arch}. Supported: avx2, avx512, neon, sse2")
        }
    }
}

fn print_perf_missing(function: &str, arch: &str) {
    println!("  perf not found. Install linux-tools-common for hardware counter profiling.");
    println!("  Showing static analysis only.");
    println!("\n  Function: {function}");
    println!("  Architecture: {arch}");
}

fn profile_with_perf(binary: &str, simd_events: &[&str]) {
    println!("  Backend: perf stat");
    println!("  Binary: {binary}");

    let mut all_events: Vec<&str> = SIMD_PERF_EVENTS.to_vec();
    all_events.extend_from_slice(simd_events);

    match run_perf_stat(binary, &[], &all_events) {
        Ok(result) => {
            warn_if_counters_blocked(&result);
            print_hardware_counters(&result);
            print_simd_utilization(&result);
            if result.wall_time_secs > 0.0 {
                println!("\n  Wall time: {:.3}s", result.wall_time_secs);
            }
        }
        Err(e) => {
            println!("  perf stat failed: {e}");
            println!("  Try: sudo sysctl kernel.perf_event_paranoid=2");
        }
    }
}

/// Emit a warning when cycles counter is zero despite a non-empty counter set
/// (typical sign of blocked perf paranoia).
fn warn_if_counters_blocked(result: &PerfStatResult) {
    let cycles = *result.counters.get("cycles").unwrap_or(&0);
    if cycles != 0 || result.counters.is_empty() {
        return;
    }
    let paranoid = std::fs::read_to_string("/proc/sys/kernel/perf_event_paranoid")
        .ok()
        .and_then(|s| s.trim().parse::<i32>().ok())
        .unwrap_or(-1);
    if paranoid > 2 {
        println!(
            "  \x1b[33m[WARN]\x1b[0m perf_event_paranoid={paranoid} — hardware counters blocked."
        );
        println!("  Fix: sudo sysctl kernel.perf_event_paranoid=2");
        println!("  Or run: sudo cgp profile simd ...\n");
    }
}

fn print_hardware_counters(result: &PerfStatResult) {
    let cycles = *result.counters.get("cycles").unwrap_or(&0);
    println!("\n  Hardware Counters:");
    println!("    Cycles:       {:>14}", format_count(cycles));
    println!(
        "    Instructions: {:>14}",
        format_count(*result.counters.get("instructions").unwrap_or(&0))
    );
    println!("    IPC:          {:>14.2}", result.ipc());
    println!("    Cache miss:   {:>13.1}%", result.cache_miss_rate());
    println!("    Branch miss:  {:>13.1}%", result.branch_miss_rate());
}

fn print_simd_utilization(result: &PerfStatResult) {
    let Some(simd_pct) = result.simd_utilization() else {
        return;
    };
    println!("\n  SIMD Utilization:");
    println!("    Vector ops:    {simd_pct:.1}%");
    println!("    Scalar ops:    {:.1}%", 100.0 - simd_pct);
    if simd_pct < 50.0 {
        println!("    [WARN] Low SIMD utilization — check for scalar fallbacks");
    } else {
        println!("    [OK] Good SIMD utilization");
    }
}

/// Format a large number with comma separators.
fn format_count(n: u64) -> String {
    let s = n.to_string();
    let mut result = String::new();
    for (i, c) in s.chars().rev().enumerate() {
        if i > 0 && i % 3 == 0 {
            result.push(',');
        }
        result.push(c);
    }
    result.chars().rev().collect()
}

/// Find a trueno benchmark binary.
/// Checks CARGO_TARGET_DIR, standard locations, and glob for bench deps.
fn find_bench_binary() -> Option<String> {
    // Check CARGO_TARGET_DIR first (user's zsh function sets this)
    let target_dir = std::env::var("CARGO_TARGET_DIR").unwrap_or_default();

    let mut candidates: Vec<String> = Vec::new();
    if !target_dir.is_empty() {
        candidates.push(format!(
            "{target_dir}/release/examples/benchmark_matrix_suite"
        ));
    }
    candidates.extend_from_slice(&[
        "/mnt/nvme-raid0/targets/trueno/release/examples/benchmark_matrix_suite".to_string(),
        "./target/release/examples/benchmark_matrix_suite".to_string(),
    ]);

    for path in &candidates {
        if std::path::Path::new(path).exists() {
            return Some(path.clone());
        }
    }

    // Try glob for bench binaries
    let glob_dirs = if !target_dir.is_empty() {
        vec![format!("{target_dir}/release/deps")]
    } else {
        vec![
            "/mnt/nvme-raid0/targets/trueno/release/deps".to_string(),
            "./target/release/deps".to_string(),
        ]
    };
    for dir in &glob_dirs {
        if let Ok(entries) = std::fs::read_dir(dir) {
            for entry in entries.flatten() {
                let name = entry.file_name();
                let name_str = name.to_string_lossy();
                if name_str.starts_with("vector_ops-") && !name_str.contains('.') {
                    return Some(entry.path().display().to_string());
                }
            }
        }
    }

    None
}

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

    #[test]
    fn test_simd_events_defined() {
        assert!(!SIMD_PERF_EVENTS.is_empty());
        assert!(!AVX2_EVENTS.is_empty());
        assert!(!AVX512_EVENTS.is_empty());
    }

    #[test]
    fn test_invalid_arch_rejected() {
        let result = profile_simd("test_fn", 1024, "invalid_arch");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_perf_stat_csv() {
        let output = "1234567,,cycles,,,\n456789,,instructions,,,\n100,,cache-references,,,\n5,,cache-misses,,,\n";
        let result = parse_perf_stat_csv(output).unwrap();
        assert_eq!(*result.counters.get("cycles").unwrap(), 1234567);
        assert_eq!(*result.counters.get("instructions").unwrap(), 456789);
    }

    #[test]
    fn test_perf_stat_ipc() {
        let mut result = PerfStatResult::default();
        result.counters.insert("cycles".to_string(), 1000);
        result.counters.insert("instructions".to_string(), 2000);
        assert!((result.ipc() - 2.0).abs() < 0.01);
    }

    #[test]
    fn test_perf_stat_cache_miss_rate() {
        let mut result = PerfStatResult::default();
        result.counters.insert("cache-references".to_string(), 1000);
        result.counters.insert("cache-misses".to_string(), 50);
        assert!((result.cache_miss_rate() - 5.0).abs() < 0.01);
    }

    #[test]
    fn test_simd_utilization() {
        let mut result = PerfStatResult::default();
        result
            .counters
            .insert("fp_arith_inst_retired.scalar_single".to_string(), 100);
        result
            .counters
            .insert("fp_arith_inst_retired.256b_packed_single".to_string(), 900);
        let util = result.simd_utilization().unwrap();
        assert!((util - 90.0).abs() < 0.01);
    }

    #[test]
    fn test_format_count() {
        assert_eq!(format_count(0), "0");
        assert_eq!(format_count(999), "999");
        assert_eq!(format_count(1000), "1,000");
        assert_eq!(format_count(1234567), "1,234,567");
    }
}