apr-cli 0.64.0

CLI tool for APR model inspection, debugging, and operations
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
//! Shared domain validation for numeric tolerance/threshold CLI flags.
//!
//! Every CRUX lint gate is of the form `if observed > tolerance { fail }` or
//! `if observed < floor { fail }`. IEEE-754 says *every* comparison involving
//! NaN is false, so a NaN tolerance makes the failing branch unreachable: the
//! gate can never fire, the report prints a positive `Ok` for an observation it
//! never actually checked, and the command exits 0. A negative tolerance does
//! the same for the floor-style gates. Neither is a legitimate tolerance.
//!
//! The classifiers already refuse to judge a non-finite *observation*
//! (`AttnParityNumericsOutcome::NonFiniteMaxAbsDiff`); this module is the
//! symmetric guard on the *threshold* side. It is used twice:
//!
//! 1. as a clap `value_parser`, so a bad value is rejected at parse time
//!    (exit 2) before any gate runs, and
//! 2. as a `guard()` call at the top of each lint `run()`, so a caller that
//!    bypasses clap still fails closed instead of printing `Ok`.

use crate::error::{CliError, Result};

/// The closed interval a threshold flag must lie in, plus a human name used in
/// the error message.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct ThresholdDomain {
    /// Inclusive lower bound.
    pub lo: f64,
    /// Inclusive upper bound.
    pub hi: f64,
    /// How the domain is described to the user, e.g. "a non-negative finite tolerance".
    pub what: &'static str,
}

/// A tolerance / epsilon: finite and non-negative, no upper bound.
pub(crate) const TOLERANCE: ThresholdDomain = ThresholdDomain {
    lo: 0.0,
    hi: f64::MAX,
    what: "a finite tolerance >= 0",
};

/// A fraction of one, e.g. a utilization threshold or a scaling-efficiency floor.
pub(crate) const FRACTION: ThresholdDomain = ThresholdDomain {
    lo: 0.0,
    hi: 1.0,
    what: "a finite fraction in [0.0, 1.0]",
};

/// A cosine-similarity floor, which legitimately spans the whole cosine range.
pub(crate) const COSINE: ThresholdDomain = ThresholdDomain {
    lo: -1.0,
    hi: 1.0,
    what: "a finite cosine similarity in [-1.0, 1.0]",
};

/// Reason a threshold value was rejected. Kept separate from the rendered
/// message so both the clap parser and `guard()` phrase it consistently.
fn reject_reason(value: f64, domain: ThresholdDomain) -> Option<String> {
    if value.is_nan() {
        return Some(format!(
            "NaN is not a threshold: every comparison against NaN is false, so the gate could never fail. Expected {}",
            domain.what
        ));
    }
    if value.is_infinite() {
        return Some(format!(
            "{value} disarms the gate rather than setting it. Expected {}",
            domain.what
        ));
    }
    if value < domain.lo || value > domain.hi {
        return Some(format!(
            "{value} is outside the valid domain. Expected {}",
            domain.what
        ));
    }
    None
}

/// Validate an already-parsed threshold. Returns the value unchanged when it is
/// usable, or a rendered rejection message.
pub(crate) fn check(value: f64, domain: ThresholdDomain) -> std::result::Result<f64, String> {
    match reject_reason(value, domain) {
        Some(msg) => Err(msg),
        None => Ok(value),
    }
}

/// clap `value_parser` for a tolerance/epsilon flag.
pub(crate) fn parse_tolerance(s: &str) -> std::result::Result<f64, String> {
    parse_in(s, TOLERANCE)
}

/// clap `value_parser` for a `[0.0, 1.0]` fraction flag.
pub(crate) fn parse_fraction(s: &str) -> std::result::Result<f64, String> {
    parse_in(s, FRACTION)
}

/// clap `value_parser` for a cosine-similarity floor flag.
pub(crate) fn parse_cosine(s: &str) -> std::result::Result<f64, String> {
    parse_in(s, COSINE)
}

fn parse_in(s: &str, domain: ThresholdDomain) -> std::result::Result<f64, String> {
    let value: f64 = s.parse().map_err(|_| "invalid float literal".to_string())?;
    check(value, domain)
}

/// clap `value_parser` for an `f32` tolerance/floor flag.
///
/// The `f32` family exists because roughly half the gate thresholds in the CLI
/// are declared `f32` (cosine floors on `apr diff`, sigma thresholds on
/// `apr rosetta validate-stats`, the perplexity ceiling on `apr eval`). Parsing
/// as `f32` first and widening for the domain check keeps the round-trip exact:
/// parsing as `f64` and narrowing would accept `1e-300` and then hand the gate a
/// silent `0.0`.
pub(crate) fn parse_tolerance_f32(s: &str) -> std::result::Result<f32, String> {
    parse_in_f32(s, TOLERANCE)
}

/// clap `value_parser` for an `f32` `[0.0, 1.0]` fraction flag.
pub(crate) fn parse_fraction_f32(s: &str) -> std::result::Result<f32, String> {
    parse_in_f32(s, FRACTION)
}

/// clap `value_parser` for an `f32` cosine-similarity floor flag.
pub(crate) fn parse_cosine_f32(s: &str) -> std::result::Result<f32, String> {
    parse_in_f32(s, COSINE)
}

fn parse_in_f32(s: &str, domain: ThresholdDomain) -> std::result::Result<f32, String> {
    let value: f32 = s.parse().map_err(|_| "invalid float literal".to_string())?;
    check(f64::from(value), domain)?;
    Ok(value)
}

/// `guard()` for an `f32` threshold. Same fail-closed contract as [`guard`].
pub(crate) fn guard_f32(flag: &str, value: f32, domain: ThresholdDomain) -> Result<()> {
    guard(flag, f64::from(value), domain)
}

/// `guard()` for an optional threshold: `None` means "no assertion", which is
/// not a disarmed gate, so it passes. `Some(NaN)` is a disarmed gate.
pub(crate) fn guard_opt(flag: &str, value: Option<f64>, domain: ThresholdDomain) -> Result<()> {
    match value {
        Some(v) => guard(flag, v, domain),
        None => Ok(()),
    }
}

/// Fail-closed guard for the `run()` entry points, so a non-clap caller cannot
/// disarm a gate either. Errors as `ValidationFailed` (exit 5), matching the
/// exit code the gate itself would have produced.
pub(crate) fn guard(flag: &str, value: f64, domain: ThresholdDomain) -> Result<()> {
    match reject_reason(value, domain) {
        Some(msg) => Err(CliError::ValidationFailed(format!(
            "invalid value for {flag}: {msg}"
        ))),
        None => Ok(()),
    }
}

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

    #[test]
    fn nan_is_rejected_in_every_domain() {
        for d in [TOLERANCE, FRACTION, COSINE] {
            let err = check(f64::NAN, d).unwrap_err();
            assert!(
                err.contains("NaN is not a threshold"),
                "NaN must be rejected for {d:?}; got: {err}"
            );
        }
    }

    #[test]
    fn infinities_are_rejected_in_every_domain() {
        for d in [TOLERANCE, FRACTION, COSINE] {
            assert!(check(f64::INFINITY, d).is_err(), "+inf must be rejected");
            assert!(
                check(f64::NEG_INFINITY, d).is_err(),
                "-inf must be rejected"
            );
        }
    }

    #[test]
    fn negative_tolerance_is_rejected() {
        let err = check(-1.0, TOLERANCE).unwrap_err();
        assert!(err.contains("outside the valid domain"), "got: {err}");
        assert!(check(-1.0, FRACTION).is_err());
        // A cosine floor legitimately reaches -1.0.
        assert_eq!(check(-1.0, COSINE), Ok(-1.0));
    }

    #[test]
    fn legitimate_values_pass_through_unchanged() {
        assert_eq!(check(0.0, TOLERANCE), Ok(0.0));
        assert_eq!(check(5e-3, TOLERANCE), Ok(5e-3));
        assert_eq!(check(1e9, TOLERANCE), Ok(1e9));
        assert_eq!(check(0.95, FRACTION), Ok(0.95));
        assert_eq!(check(1.0, FRACTION), Ok(1.0));
        assert_eq!(check(0.9999, COSINE), Ok(0.9999));
    }

    #[test]
    fn fraction_rejects_out_of_range_upper_bound() {
        let err = check(99.0, FRACTION).unwrap_err();
        assert!(err.contains("outside the valid domain"), "got: {err}");
    }

    #[test]
    fn parsers_reject_nan_and_keep_rejecting_garbage() {
        assert!(parse_tolerance("nan").is_err());
        assert!(parse_tolerance("NaN").is_err());
        assert!(parse_fraction("nan").is_err());
        assert!(parse_cosine("nan").is_err());
        assert_eq!(
            parse_tolerance("banana").unwrap_err(),
            "invalid float literal"
        );
        assert_eq!(parse_tolerance("1e-5"), Ok(1e-5));
        assert_eq!(parse_fraction("0.85"), Ok(0.85));
    }

    /// `Commands` is a very large enum; building the clap command tree needs
    /// more stack than the 2 MiB a test thread gets by default.
    fn on_big_stack(f: impl FnOnce() + Send + 'static) {
        std::thread::Builder::new()
            .stack_size(32 * 1024 * 1024)
            .spawn(f)
            .expect("spawn")
            .join()
            .expect("join");
    }

    /// The user-visible half of the fix: clap itself must refuse the value, so
    /// no gate ever runs and no `Ok` is ever printed. One case per flag in the
    /// family, each with the literal that shipped the disarm in 0.63.0.
    #[test]
    fn cli_rejects_nan_on_every_threshold_flag_in_the_lint_family() {
        on_big_stack(cli_rejects_nan_body);
    }

    fn cli_rejects_nan_body() {
        use clap::Parser;

        let disarming: &[&[&str]] = &[
            &[
                "apr",
                "kv-timeline-lint",
                "--timeline-file",
                "kv.json",
                "--preempt-threshold",
                "nan",
            ],
            &[
                "apr",
                "kv-timeline-lint",
                "--timeline-file",
                "kv.json",
                "--preempt-threshold=-1",
            ],
            &[
                "apr",
                "attn-parity-lint",
                "--parity-file",
                "p.json",
                "--tol-abs",
                "nan",
            ],
            &[
                "apr",
                "attn-parity-lint",
                "--parity-file",
                "p.json",
                "--tol-cos",
                "NaN",
            ],
            &[
                "apr",
                "attn-viz-lint",
                "--attn-file",
                "a.json",
                "--tolerance",
                "nan",
            ],
            &[
                "apr",
                "attn-viz-lint",
                "--attn-file",
                "a.json",
                "--epsilon",
                "nan",
            ],
            &[
                "apr",
                "explain-token-lint",
                "--jsonl-file",
                "e.jsonl",
                "--tolerance",
                "nan",
            ],
            &[
                "apr",
                "ddp-metrics-lint",
                "--metrics-1gpu-file",
                "a.json",
                "--metrics-ngpu-file",
                "b.json",
                "--world-size",
                "4",
                "--scaling-floor",
                "nan",
            ],
            &[
                "apr",
                "ddp-metrics-lint",
                "--metrics-1gpu-file",
                "a.json",
                "--metrics-ngpu-file",
                "b.json",
                "--world-size",
                "4",
                "--loss-tolerance",
                "nan",
            ],
            &[
                "apr",
                "ddp-metrics-lint",
                "--metrics-1gpu-file",
                "a.json",
                "--metrics-ngpu-file",
                "b.json",
                "--world-size",
                "4",
                "--scaling-floor=-1",
            ],
        ];

        for argv in disarming {
            let parsed = crate::Cli::try_parse_from(argv.iter().copied());
            assert!(
                parsed.is_err(),
                "clap accepted a gate-disarming threshold: {argv:?}"
            );
        }
    }

    /// The fix must not narrow the legitimate domain: every value the shipped
    /// falsification suites pass on the command line still parses.
    #[test]
    fn cli_still_accepts_the_documented_threshold_values() {
        on_big_stack(cli_accepts_documented_body);
    }

    fn cli_accepts_documented_body() {
        use clap::Parser;

        let legitimate: &[&[&str]] = &[
            &[
                "apr",
                "kv-timeline-lint",
                "--timeline-file",
                "kv.json",
                "--preempt-threshold",
                "0.80",
            ],
            &[
                "apr",
                "attn-parity-lint",
                "--parity-file",
                "p.json",
                "--tol-abs",
                "0.01",
                "--tol-cos",
                "0.9999",
            ],
            &[
                "apr",
                "attn-viz-lint",
                "--attn-file",
                "a.json",
                "--tolerance",
                "0.05",
                "--epsilon",
                "1e-9",
            ],
            &[
                "apr",
                "explain-token-lint",
                "--jsonl-file",
                "e.jsonl",
                "--tolerance",
                "0.05",
            ],
            &[
                "apr",
                "ddp-metrics-lint",
                "--metrics-1gpu-file",
                "a.json",
                "--metrics-ngpu-file",
                "b.json",
                "--world-size",
                "4",
                "--scaling-floor",
                "0.5",
                "--loss-tolerance",
                "0.01",
            ],
        ];

        for argv in legitimate {
            let parsed = crate::Cli::try_parse_from(argv.iter().copied());
            assert!(
                parsed.is_ok(),
                "clap rejected a legitimate threshold: {argv:?}"
            );
        }
    }

    #[test]
    fn guard_reports_the_flag_name_and_is_validation_failed() {
        let err = guard("--tol-abs", f64::NAN, TOLERANCE).unwrap_err();
        match err {
            CliError::ValidationFailed(msg) => {
                assert!(msg.contains("--tol-abs"), "got: {msg}");
                assert!(msg.contains("NaN"), "got: {msg}");
            }
            other => panic!("expected ValidationFailed, got {other:?}"),
        }
        assert!(guard("--tol-abs", 5e-3, TOLERANCE).is_ok());
    }
}