oxidelm 0.2.0

Bare-metal pure-Rust Transformer engine with reverse-mode autograd, BPE tokenization, and wgpu acceleration
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! Performance regression thresholds against committed baselines.
//!
//! Dedicated performance jobs compare measured metrics to a baseline file.
//! Threshold failures are ignored until the baseline is marked `stable`, so
//! correctness CI can stay free of noisy timing gates.

use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;
use std::fs::File;
use std::io::{BufReader, BufWriter, Write};
use std::path::Path;
use std::process::Command;

/// Whether a metric should increase or decrease for an improvement.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MetricDirection {
    HigherIsBetter,
    LowerIsBetter,
}

/// One metric's committed baseline and allowed regression.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetricThreshold {
    pub direction: MetricDirection,
    /// Committed reference value. `None` means the metric is not yet enforceable.
    #[serde(default)]
    pub baseline: Option<f64>,
    /// Maximum allowed relative regression as a percentage of the baseline.
    pub max_regression_pct: f64,
}

/// Committed performance baseline for one suite.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PerfBaseline {
    pub name: String,
    /// When false, threshold breaches warn but do not fail the job.
    #[serde(default)]
    pub stable: bool,
    #[serde(default)]
    pub notes: Option<String>,
    pub metrics: BTreeMap<String, MetricThreshold>,
}

/// Whether timed regions include host↔device transfers.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TransferPolicy {
    /// Wall-clock includes transfers and synchronization required by the harness.
    IncludeTransfers,
    /// Timed region is device-resident; transfers happen outside the sample.
    DeviceResidentOnly,
}

impl TransferPolicy {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::IncludeTransfers => "include_transfers",
            Self::DeviceResidentOnly => "device_resident_only",
        }
    }
}

impl fmt::Display for TransferPolicy {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Adapter identity recorded with GPU benchmark results.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct GpuAdapterMetadata {
    pub name: String,
    pub backend: String,
    pub driver: String,
    pub driver_info: String,
    pub vendor: u32,
    pub device: u32,
}

/// Environment and harness settings saved beside measured metrics.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BenchmarkMetadata {
    pub commit: Option<String>,
    pub rust_version: String,
    pub os: String,
    pub arch: String,
    pub cpu_threads: usize,
    pub rayon_threads: usize,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub adapter: Option<GpuAdapterMetadata>,
    /// wgpu power preference when a GPU adapter was used (for example `high_performance`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub power_mode: Option<String>,
    pub warmup_samples: usize,
    pub samples: usize,
    pub transfer_policy: TransferPolicy,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub command_line: Option<String>,
}

/// Inputs for [`collect_benchmark_metadata`] that vary per harness run.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BenchmarkMetadataRequest {
    pub warmup_samples: usize,
    pub samples: usize,
    pub transfer_policy: TransferPolicy,
    pub adapter: Option<GpuAdapterMetadata>,
    pub power_mode: Option<String>,
}

/// Measured results from a benchmark harness.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PerfResults {
    pub suite: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<BenchmarkMetadata>,
    pub metrics: BTreeMap<String, f64>,
}

/// Capture commit, toolchain, host, and adapter metadata for a result file.
pub fn collect_benchmark_metadata(request: BenchmarkMetadataRequest) -> BenchmarkMetadata {
    BenchmarkMetadata {
        commit: resolve_commit(),
        rust_version: resolve_rust_version(),
        os: std::env::consts::OS.to_string(),
        arch: std::env::consts::ARCH.to_string(),
        cpu_threads: std::thread::available_parallelism()
            .map(|value| value.get())
            .unwrap_or(1),
        rayon_threads: rayon::current_num_threads(),
        adapter: request.adapter,
        power_mode: request.power_mode,
        warmup_samples: request.warmup_samples,
        samples: request.samples,
        transfer_policy: request.transfer_policy,
        command_line: Some(std::env::args().collect::<Vec<_>>().join(" ")),
    }
}

fn resolve_commit() -> Option<String> {
    for key in ["OXIDELM_COMMIT", "GITHUB_SHA", "GIT_COMMIT"] {
        if let Ok(value) = std::env::var(key) {
            let trimmed = value.trim();
            if !trimmed.is_empty() {
                return Some(trimmed.to_string());
            }
        }
    }
    let output = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let commit = String::from_utf8(output.stdout).ok()?;
    let trimmed = commit.trim();
    (!trimmed.is_empty()).then(|| trimmed.to_string())
}

fn resolve_rust_version() -> String {
    Command::new("rustc")
        .arg("--version")
        .output()
        .ok()
        .and_then(|output| {
            output
                .status
                .success()
                .then(|| String::from_utf8(output.stdout).ok())
                .flatten()
        })
        .map(|version| version.trim().to_string())
        .filter(|version| !version.is_empty())
        .unwrap_or_else(|| "unknown".to_string())
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MetricStatus {
    Ok,
    MissingMeasurement,
    MissingBaseline,
    Regressed,
}

#[derive(Clone, Debug, PartialEq)]
pub struct MetricComparison {
    pub name: String,
    pub status: MetricStatus,
    pub measured: Option<f64>,
    pub baseline: Option<f64>,
    pub regression_pct: Option<f64>,
    pub max_regression_pct: Option<f64>,
    pub message: String,
}

#[derive(Clone, Debug, PartialEq)]
pub struct RegressionReport {
    pub suite: String,
    pub baseline_stable: bool,
    pub comparisons: Vec<MetricComparison>,
}

impl RegressionReport {
    /// True when any metric exceeded its regression threshold.
    pub fn has_regressions(&self) -> bool {
        self.comparisons
            .iter()
            .any(|row| row.status == MetricStatus::Regressed)
    }

    /// True when the job should exit non-zero for threshold breaches.
    ///
    /// Unstable baselines never fail the job on timing noise.
    pub fn should_fail_job(&self) -> bool {
        self.baseline_stable && self.has_regressions()
    }

    pub fn missing_measurements(&self) -> impl Iterator<Item = &MetricComparison> {
        self.comparisons
            .iter()
            .filter(|row| row.status == MetricStatus::MissingMeasurement)
    }
}

#[derive(Debug)]
pub enum PerfRegressionError {
    Io(String),
    Json(String),
    SuiteMismatch { baseline: String, results: String },
    InvalidThreshold(String),
}

impl fmt::Display for PerfRegressionError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io(message) => write!(formatter, "{message}"),
            Self::Json(message) => write!(formatter, "{message}"),
            Self::SuiteMismatch { baseline, results } => write!(
                formatter,
                "suite mismatch: baseline '{baseline}' vs results '{results}'"
            ),
            Self::InvalidThreshold(message) => write!(formatter, "{message}"),
        }
    }
}

impl Error for PerfRegressionError {}

pub fn load_baseline(path: impl AsRef<Path>) -> Result<PerfBaseline, PerfRegressionError> {
    let path = path.as_ref();
    let file = File::open(path).map_err(|error| {
        PerfRegressionError::Io(format!("failed to open {}: {error}", path.display()))
    })?;
    serde_json::from_reader(BufReader::new(file)).map_err(|error| {
        PerfRegressionError::Json(format!("failed to parse {}: {error}", path.display()))
    })
}

pub fn load_results(path: impl AsRef<Path>) -> Result<PerfResults, PerfRegressionError> {
    let path = path.as_ref();
    let file = File::open(path).map_err(|error| {
        PerfRegressionError::Io(format!("failed to open {}: {error}", path.display()))
    })?;
    serde_json::from_reader(BufReader::new(file)).map_err(|error| {
        PerfRegressionError::Json(format!("failed to parse {}: {error}", path.display()))
    })
}

pub fn write_results(
    path: impl AsRef<Path>,
    results: &PerfResults,
) -> Result<(), PerfRegressionError> {
    let path = path.as_ref();
    let file = File::create(path).map_err(|error| {
        PerfRegressionError::Io(format!("failed to create {}: {error}", path.display()))
    })?;
    let mut writer = BufWriter::new(file);
    serde_json::to_writer_pretty(&mut writer, results).map_err(|error| {
        PerfRegressionError::Json(format!("failed to write {}: {error}", path.display()))
    })?;
    writer.write_all(b"\n").map_err(|error| {
        PerfRegressionError::Io(format!("failed to write {}: {error}", path.display()))
    })?;
    Ok(())
}

pub fn compare(
    baseline: &PerfBaseline,
    results: &PerfResults,
) -> Result<RegressionReport, PerfRegressionError> {
    if baseline.name != results.suite {
        return Err(PerfRegressionError::SuiteMismatch {
            baseline: baseline.name.clone(),
            results: results.suite.clone(),
        });
    }

    let mut comparisons = Vec::with_capacity(baseline.metrics.len());
    for (name, threshold) in &baseline.metrics {
        if !threshold.max_regression_pct.is_finite() || threshold.max_regression_pct < 0.0 {
            return Err(PerfRegressionError::InvalidThreshold(format!(
                "metric '{name}': max_regression_pct must be a non-negative finite number"
            )));
        }
        if let Some(value) = threshold.baseline {
            if !value.is_finite() || value <= 0.0 {
                return Err(PerfRegressionError::InvalidThreshold(format!(
                    "metric '{name}': baseline must be a positive finite number when set"
                )));
            }
        }

        let measured = results.metrics.get(name).copied();
        let comparison = match (measured, threshold.baseline) {
            (None, _) => MetricComparison {
                name: name.clone(),
                status: MetricStatus::MissingMeasurement,
                measured: None,
                baseline: threshold.baseline,
                regression_pct: None,
                max_regression_pct: Some(threshold.max_regression_pct),
                message: format!("missing measurement for '{name}'"),
            },
            (Some(measured), None) => MetricComparison {
                name: name.clone(),
                status: MetricStatus::MissingBaseline,
                measured: Some(measured),
                baseline: None,
                regression_pct: None,
                max_regression_pct: Some(threshold.max_regression_pct),
                message: format!(
                    "'{name}'={measured:.4} recorded; baseline unset (not enforceable)"
                ),
            },
            (Some(measured), Some(reference)) => {
                let regression_pct = regression_percent(measured, reference, threshold.direction);
                if regression_pct > threshold.max_regression_pct {
                    MetricComparison {
                        name: name.clone(),
                        status: MetricStatus::Regressed,
                        measured: Some(measured),
                        baseline: Some(reference),
                        regression_pct: Some(regression_pct),
                        max_regression_pct: Some(threshold.max_regression_pct),
                        message: format!(
                            "'{name}' regressed {regression_pct:.2}% (measured={measured:.4}, baseline={reference:.4}, max={:.2}%)",
                            threshold.max_regression_pct
                        ),
                    }
                } else {
                    MetricComparison {
                        name: name.clone(),
                        status: MetricStatus::Ok,
                        measured: Some(measured),
                        baseline: Some(reference),
                        regression_pct: Some(regression_pct),
                        max_regression_pct: Some(threshold.max_regression_pct),
                        message: format!(
                            "'{name}' ok (measured={measured:.4}, baseline={reference:.4}, regression={regression_pct:.2}%, max={:.2}%)",
                            threshold.max_regression_pct
                        ),
                    }
                }
            }
        };
        comparisons.push(comparison);
    }

    Ok(RegressionReport {
        suite: baseline.name.clone(),
        baseline_stable: baseline.stable,
        comparisons,
    })
}

fn regression_percent(measured: f64, baseline: f64, direction: MetricDirection) -> f64 {
    match direction {
        MetricDirection::HigherIsBetter => {
            if measured >= baseline {
                0.0
            } else {
                (baseline - measured) / baseline * 100.0
            }
        }
        MetricDirection::LowerIsBetter => {
            if measured <= baseline {
                0.0
            } else {
                (measured - baseline) / baseline * 100.0
            }
        }
    }
}

/// Format a human-readable summary for CI logs.
pub fn format_report(report: &RegressionReport) -> String {
    let mut lines = Vec::new();
    lines.push(format!(
        "perf regression: suite={} stable={}",
        report.suite, report.baseline_stable
    ));
    if !report.baseline_stable {
        lines.push(
            "baseline is not stable; threshold breaches are reported but do not fail the job"
                .to_string(),
        );
    }
    for row in &report.comparisons {
        let tag = match row.status {
            MetricStatus::Ok => "ok",
            MetricStatus::MissingMeasurement => "missing",
            MetricStatus::MissingBaseline => "unset",
            MetricStatus::Regressed => "REGRESSED",
        };
        lines.push(format!("  [{tag}] {}", row.message));
    }
    if report.should_fail_job() {
        lines.push("result: FAIL (stable baseline regression)".to_string());
    } else if report.has_regressions() {
        lines.push("result: WARN (unstable baseline; not failing)".to_string());
    } else {
        lines.push("result: PASS".to_string());
    }
    lines.join("\n")
}

#[cfg(test)]
mod tests {
    use super::{
        collect_benchmark_metadata, compare, format_report, BenchmarkMetadataRequest,
        GpuAdapterMetadata, MetricDirection, MetricStatus, MetricThreshold, PerfBaseline,
        PerfResults, TransferPolicy,
    };
    use std::collections::BTreeMap;

    fn baseline(stable: bool, prefill: Option<f64>) -> PerfBaseline {
        let mut metrics = BTreeMap::new();
        metrics.insert(
            "prefill_tok_s".to_string(),
            MetricThreshold {
                direction: MetricDirection::HigherIsBetter,
                baseline: prefill,
                max_regression_pct: 10.0,
            },
        );
        metrics.insert(
            "ttft_median_ms".to_string(),
            MetricThreshold {
                direction: MetricDirection::LowerIsBetter,
                baseline: Some(5.0),
                max_regression_pct: 20.0,
            },
        );
        PerfBaseline {
            name: "kv_cache_cpu".to_string(),
            stable,
            notes: None,
            metrics,
        }
    }

    fn results(prefill: f64, ttft: f64) -> PerfResults {
        let mut metrics = BTreeMap::new();
        metrics.insert("prefill_tok_s".to_string(), prefill);
        metrics.insert("ttft_median_ms".to_string(), ttft);
        PerfResults {
            suite: "kv_cache_cpu".to_string(),
            metadata: None,
            metrics,
        }
    }

    #[test]
    fn metadata_round_trips_in_results_json() {
        let metadata = collect_benchmark_metadata(BenchmarkMetadataRequest {
            warmup_samples: 3,
            samples: 20,
            transfer_policy: TransferPolicy::IncludeTransfers,
            adapter: Some(GpuAdapterMetadata {
                name: "Test GPU".into(),
                backend: "Metal".into(),
                driver: "metal".into(),
                driver_info: "1.0".into(),
                vendor: 1,
                device: 2,
            }),
            power_mode: Some("high_performance".into()),
        });
        assert_eq!(metadata.warmup_samples, 3);
        assert_eq!(metadata.samples, 20);
        assert_eq!(metadata.os, std::env::consts::OS);
        assert_eq!(metadata.transfer_policy, TransferPolicy::IncludeTransfers);
        assert!(metadata.cpu_threads >= 1);
        assert!(metadata.rayon_threads >= 1);
        assert!(!metadata.rust_version.is_empty());

        let results = PerfResults {
            suite: "inference_e2e".into(),
            metadata: Some(metadata.clone()),
            metrics: BTreeMap::new(),
        };
        let json = serde_json::to_string_pretty(&results).unwrap();
        let loaded: PerfResults = serde_json::from_str(&json).unwrap();
        assert_eq!(loaded.metadata, Some(metadata));
    }

    #[test]
    fn results_json_without_metadata_still_loads() {
        let json = r#"{"suite":"inference_e2e","metrics":{"cpu_prefill_tok_s":1.0}}"#;
        let loaded: PerfResults = serde_json::from_str(json).unwrap();
        assert!(loaded.metadata.is_none());
        assert_eq!(loaded.metrics["cpu_prefill_tok_s"], 1.0);
    }

    #[test]
    fn unstable_baseline_never_fails_job() {
        let report = compare(&baseline(false, Some(1000.0)), &results(500.0, 4.0)).unwrap();
        assert!(report.has_regressions());
        assert!(!report.should_fail_job());
        assert!(format_report(&report).contains("WARN"));
    }

    #[test]
    fn stable_baseline_fails_on_regression() {
        let report = compare(&baseline(true, Some(1000.0)), &results(850.0, 4.0)).unwrap();
        assert!(report.has_regressions());
        assert!(report.should_fail_job());
        let prefill = report
            .comparisons
            .iter()
            .find(|row| row.name == "prefill_tok_s")
            .unwrap();
        assert_eq!(prefill.status, MetricStatus::Regressed);
        assert!((prefill.regression_pct.unwrap() - 15.0).abs() < 1e-9);
    }

    #[test]
    fn within_threshold_passes() {
        let report = compare(&baseline(true, Some(1000.0)), &results(920.0, 5.5)).unwrap();
        assert!(!report.has_regressions());
        assert!(!report.should_fail_job());
        assert!(format_report(&report).contains("PASS"));
    }

    #[test]
    fn unset_baseline_is_not_enforceable() {
        let report = compare(&baseline(true, None), &results(100.0, 4.0)).unwrap();
        let prefill = report
            .comparisons
            .iter()
            .find(|row| row.name == "prefill_tok_s")
            .unwrap();
        assert_eq!(prefill.status, MetricStatus::MissingBaseline);
        assert!(!report.should_fail_job());
    }

    #[test]
    fn suite_mismatch_errors() {
        let mut results = results(1000.0, 4.0);
        results.suite = "other".to_string();
        assert!(compare(&baseline(true, Some(1000.0)), &results).is_err());
    }
}