apr-cli 0.31.2

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
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

/// Run warmup iterations with progress display.
fn run_bench_warmup<F: FnMut()>(config: &BenchConfig, count: usize, mut f: F) {
    if !config.quiet {
        eprintln!("{}", "Running warmup...".yellow());
    }
    for i in 0..count {
        f();
        if !config.quiet {
            eprint!("  Warmup {}/{}\r", i + 1, count);
            std::io::Write::flush(&mut std::io::stderr()).ok();
        }
    }
    if !config.quiet {
        eprintln!("  Warmup complete        ");
        eprintln!();
    }
}

/// Print benchmark progress for a single iteration.
fn print_bench_progress(config: &BenchConfig, i: usize, tokens: usize, time: Duration) {
    if !config.quiet {
        eprint!(
            "  Iteration {}/{}: {} tokens in {:.2}s\r",
            i + 1,
            config.iterations,
            tokens,
            time.as_secs_f32()
        );
        std::io::Write::flush(&mut std::io::stderr()).ok();
    }
}

fn print_results(result: &BenchResult) {
    output::section("Results");
    println!();

    // Throughput (the key metric)
    let throughput_str = format!("{:.1} tok/s", result.tokens_per_second);
    if result.passed {
        println!(
            "{} {} {}",
            "Throughput:".white().bold(),
            throughput_str.green().bold(),
            "(PASS: >= 10 tok/s)".green()
        );
    } else {
        println!(
            "{} {} {}",
            "Throughput:".white().bold(),
            throughput_str.red().bold(),
            "(FAIL: < 10 tok/s)".red()
        );
    }

    println!();
    output::kv("Total tokens", result.total_tokens);
    output::kv(
        "Total time",
        format!("{:.2}s", result.total_time.as_secs_f32()),
    );
    output::kv(
        "Time to first token",
        format!("{:.0}ms", result.time_to_first_token.as_secs_f64() * 1000.0),
    );
    println!();
    output::kv(
        "Mean iteration time",
        format!("{:.2}s", result.mean_time.as_secs_f32()),
    );
    output::kv(
        "Median iteration time",
        format!("{:.2}s", result.median_time.as_secs_f32()),
    );
    output::kv(
        "Std deviation",
        format!("{:.0}ms", result.std_dev.as_secs_f64() * 1000.0),
    );
    println!();

    // Performance grade (Dean & Ghemawat 2025 style)
    let grade = if result.tokens_per_second >= 100.0 {
        "A+ (Excellent)".green()
    } else if result.tokens_per_second >= 50.0 {
        "A (Very Good)".green()
    } else if result.tokens_per_second >= 20.0 {
        "B (Good)".blue()
    } else if result.tokens_per_second >= 10.0 {
        "C (Acceptable)".yellow()
    } else {
        "F (Below Threshold)".red()
    };
    output::kv("Performance Grade", grade);
}

/// Realizar-based benchmark for model inference
///
/// Supports all formats: GGUF, APR, and SafeTensors.
/// Automatically uses CUDA GPU acceleration when available for GGUF.
#[cfg(feature = "inference")]
fn run_realizar_benchmark(path: &Path, config: &BenchConfig) -> Result<BenchResult> {
    use realizar::format::{detect_format, ModelFormat};

    // Read first 8 bytes for format detection
    let header_bytes = std::fs::read(path)
        .map_err(|e| CliError::ValidationFailed(format!("Failed to read model: {e}")))?;

    // Detect format
    let format = detect_format(&header_bytes[..8.min(header_bytes.len())])
        .map_err(|e| CliError::ValidationFailed(format!("Failed to detect format: {e}")))?;

    if !config.quiet {
        eprintln!("{} {}", "Format:".cyan().bold(), format.to_string().green());
    }

    // Check CUDA availability (only used for GGUF currently)
    #[cfg(feature = "cuda")]
    let (cuda_available, cuda_devices) = {
        use realizar::cuda::CudaExecutor;
        (CudaExecutor::is_available(), CudaExecutor::num_devices())
    };
    #[cfg(not(feature = "cuda"))]
    let (cuda_available, cuda_devices) = (false, 0usize);

    if !config.quiet {
        if cuda_available && cuda_devices > 0 {
            eprintln!(
                "{} {} GPU(s) detected",
                "CUDA:".cyan().bold(),
                cuda_devices.to_string().green()
            );
        } else {
            eprintln!(
                "{} {}",
                "CUDA:".cyan().bold(),
                "Not available (CPU mode)".yellow()
            );
        }
    }

    // Route to format-specific benchmark
    // GH-192: All formats now support CUDA acceleration
    let use_cuda = cuda_available && cuda_devices > 0;
    let tracer = TracerImpl::new_local();
    match format {
        ModelFormat::Gguf => run_gguf_benchmark(path, config, use_cuda, &tracer),
        ModelFormat::Apr => run_apr_benchmark(path, config, use_cuda, &tracer),
        ModelFormat::SafeTensors => run_safetensors_benchmark(path, config, use_cuda, &tracer),
    }
}

/// GGUF format benchmark (supports GPU acceleration)
#[cfg(feature = "inference")]
fn run_gguf_benchmark(
    path: &Path,
    config: &BenchConfig,
    use_cuda: bool,
    tracer: &TracerImpl,
) -> Result<BenchResult> {
    use realizar::gguf::{GGUFModel, QuantizedGenerateConfig};

    if !config.quiet {
        eprintln!("{}", "Loading GGUF model...".yellow());
    }
    let start = Instant::now();

    // Load model for tokenization
    let model_bytes = std::fs::read(path)
        .map_err(|e| CliError::ValidationFailed(format!("Failed to read model: {e}")))?;
    let gguf = GGUFModel::from_bytes(&model_bytes)
        .map_err(|e| CliError::ValidationFailed(format!("Failed to parse GGUF: {e}")))?;

    // Tokenize prompt
    let bos = aprender::demo::SpecialTokens::qwen2().bos_id;
    let prompt_tokens: Vec<u32> = gguf
        .encode(&config.prompt)
        .unwrap_or_else(|| vec![bos, 9707, 11, 358, 1079, 264, 11761, 18328, 13, 9842]);

    let gen_config = QuantizedGenerateConfig {
        max_tokens: config.max_tokens.min(128),
        temperature: 0.0,
        top_k: 1,
        ..Default::default()
    };

    #[cfg(feature = "cuda")]
    if use_cuda {
        match run_cuda_benchmark(
            &gguf,
            &model_bytes,
            &prompt_tokens,
            &gen_config,
            config,
            start,
            path,
            tracer,
        ) {
            Ok(result) => return Ok(result),
            Err(e) => {
                // GH-284: Fall back to CPU on CUDA capability mismatch (e.g. missing QkNorm kernel)
                if !config.quiet {
                    eprintln!(
                        "{}",
                        format!("CUDA init failed, falling back to CPU: {e}").yellow()
                    );
                }
                let cpu_start = Instant::now();
                return run_cpu_benchmark(&prompt_tokens, &gen_config, config, cpu_start, path, tracer);
            }
        }
    }
    run_cpu_benchmark(&prompt_tokens, &gen_config, config, start, path, tracer)
}

/// Resolve prompt tokens from APR model's tokenizer, with fallbacks.
#[cfg(feature = "inference")]
fn resolve_apr_prompt_tokens(path: &Path, prompt: &str) -> Vec<u32> {
    use realizar::apr::AprV2Model;

    if let Some(tokenizer) = realizar::safetensors::find_sibling_file(path, "tokenizer.json")
        .and_then(|tp| AprV2Model::load_tokenizer_from_path(&tp))
    {
        tokenizer.encode(prompt)
    } else if let Some((vocab, _, _)) = AprV2Model::load_tokenizer_from_sibling(path) {
        let token_to_id: std::collections::HashMap<String, u32> = vocab
            .iter()
            .enumerate()
            .map(|(i, t)| (t.clone(), i as u32))
            .collect();
        prompt
            .split_whitespace()
            .filter_map(|w| token_to_id.get(w).copied())
            .collect()
    } else {
        vec![1, 2, 3, 4, 5]
    }
}

/// Handle fallback when generation produced zero new tokens (GH-254).
///
/// Returns adjusted `total_tokens` for forward-pass throughput reporting.
#[cfg(feature = "inference")]
fn handle_zero_generation_fallback(
    generation_failed: bool,
    total_tokens: usize,
    iterations: usize,
    prompt_len: usize,
    _quiet: bool,
) -> usize {
    if generation_failed && total_tokens == 0 {
        eprintln!(
            "{}",
            "Note: Generation produced 0 new tokens, reporting forward-pass throughput.".yellow()
        );
        iterations * prompt_len
    } else {
        total_tokens
    }
}

/// Try CUDA benchmark, returning None if GPU produced 0 tokens (extracted to reduce complexity).
#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(all(feature = "inference", feature = "cuda"))]
fn try_cuda_benchmark(
    path: &Path,
    config: &BenchConfig,
    tracer: &TracerImpl,
) -> Result<Option<BenchResult>> {
    let result = run_apr_cuda_benchmark(path, config, tracer)?;
    if result.total_tokens > 0 {
        return Ok(Some(result));
    }
    if !config.quiet {
        eprintln!(
            "{}",
            "GPU generated 0 tokens, falling back to CPU...".yellow()
        );
    }
    Ok(None)
}

/// APR format benchmark
/// GH-192: Now supports CUDA GPU acceleration and uses KV cache for O(n) generation
#[cfg(feature = "inference")]
fn run_apr_benchmark(
    path: &Path,
    config: &BenchConfig,
    use_cuda: bool,
    tracer: &TracerImpl,
) -> Result<BenchResult> {
    use realizar::apr_transformer::{AprTransformer, GenerateConfig};

    #[cfg(feature = "cuda")]
    if use_cuda {
        if let Some(result) = try_cuda_benchmark(path, config, tracer)? {
            return Ok(result);
        }
    }

    if !config.quiet {
        eprintln!("{}", "Loading APR model (CPU)...".yellow());
    }
    let start = Instant::now();

    let transformer = AprTransformer::from_apr_file(path)
        .map_err(|e| CliError::ValidationFailed(format!("Failed to load APR: {e}")))?;

    let load_time = start.elapsed();
    if !config.quiet {
        eprintln!(
            "{} in {:.2}s",
            "Model ready".green(),
            load_time.as_secs_f32()
        );
        eprintln!();
    }

    let prompt_tokens = resolve_apr_prompt_tokens(path, &config.prompt);

    let gen_config = GenerateConfig {
        max_tokens: config.max_tokens.min(32),
        temperature: 0.0,
        top_p: 1.0,
        top_k: 0,
        repetition_penalty: 1.0,
        trace: false,
    stop_tokens: vec![],
    };

    // Warmup (untraced)
    run_bench_warmup(config, config.warmup, || {
        let _ = transformer.generate_with_cache(&prompt_tokens, &gen_config);
    });

    let (iteration_times, total_tokens, first_token_time) =
        run_apr_measurement(&transformer, &prompt_tokens, &gen_config, config, tracer)?;

    calculate_benchmark_stats(iteration_times, total_tokens, first_token_time, config)
}

/// Run the measurement phase of APR benchmark, collecting timing and token data.
#[cfg(feature = "inference")]
fn run_apr_measurement(
    transformer: &realizar::apr_transformer::AprTransformer,
    prompt_tokens: &[u32],
    gen_config: &realizar::apr_transformer::GenerateConfig,
    config: &BenchConfig,
    tracer: &TracerImpl,
) -> Result<(Vec<Duration>, usize, Duration)> {
    if !config.quiet {
        eprintln!("{}", "Running benchmark...".yellow());
    }
    let mut iteration_times = Vec::with_capacity(config.iterations);
    let mut total_tokens = 0usize;
    let mut first_token_time = Duration::ZERO;
    let mut generation_failed = false;
    let budget_us = config.max_tokens as u64 * 100_000;
    let mut generate_errors = 0usize;

    for i in 0..config.iterations {
        let traced = tracer.trace("bench_apr_iter", budget_us, || {
            transformer.generate_with_cache(prompt_tokens, gen_config)
        });
        let output = match traced.result {
            Ok(tokens) => tokens,
            Err(e) => {
                if generate_errors == 0 {
                    eprintln!(
                        "{}",
                        format!("Warning: generate_with_cache() failed on iteration {i}: {e}").yellow()
                    );
                }
                generate_errors += 1;
                prompt_tokens.to_vec()
            }
        };
        let tokens_generated = output.len().saturating_sub(prompt_tokens.len());
        let iter_time = Duration::from_micros(traced.duration_us);
        iteration_times.push(iter_time);
        total_tokens += tokens_generated;

        if i == 0 {
            first_token_time =
                Duration::from_secs_f64(iter_time.as_secs_f64() / tokens_generated.max(1) as f64);
            if tokens_generated == 0 {
                generation_failed = true;
            }
        }
        print_bench_progress(config, i, tokens_generated, iter_time);
    }
    if !config.quiet {
        eprintln!();
    }

    total_tokens = handle_zero_generation_fallback(
        generation_failed, total_tokens, config.iterations, prompt_tokens.len(), config.quiet,
    );
    if !config.quiet {
        eprintln!();
    }

    Ok((iteration_times, total_tokens, first_token_time))
}

/// APR format CUDA benchmark using fused Q4K kernels (GH-87)
///
/// F-KERNEL-DISPATCH-001: Uses OwnedQuantizedModelCuda (fused Q4K/Q6K GEMV,
/// 190+ tok/s) instead of AprV2ModelCuda (generic transformer, 0.5 tok/s).
/// Loading path: MappedAprModel → OwnedQuantizedModel::from_apr() → OwnedQuantizedModelCuda.
#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(all(feature = "inference", feature = "cuda"))]
fn run_apr_cuda_benchmark(
    path: &Path,
    config: &BenchConfig,
    tracer: &TracerImpl,
) -> Result<BenchResult> {
    use realizar::apr::{AprV2Model, MappedAprModel};
    use realizar::gguf::{OwnedQuantizedModel, OwnedQuantizedModelCuda, QuantizedGenerateConfig};

    if !config.quiet {
        eprintln!("{}", "Loading APR model (GPU, fused Q4K kernels)...".yellow());
    }
    let start = Instant::now();

    // GH-87: Load via MappedAprModel -> OwnedQuantizedModel for fused kernel path
    let mapped = MappedAprModel::from_path(path)
        .map_err(|e| CliError::ValidationFailed(format!("Failed to map APR: {e}")))?;

    let tensor_count = mapped.tensors.len();

    // Use embedded tokenizer if available, else fall back to sibling/default
    let prompt_tokens: Vec<u32> = {
        let cpu_model = AprV2Model::load(path)
            .map_err(|e| CliError::ValidationFailed(format!("Failed to load APR for tokenizer: {e}")))?;
        if let Some(tokenizer) = cpu_model.load_embedded_bpe_tokenizer() {
            tokenizer.encode(&config.prompt)
        } else {
            resolve_apr_prompt_tokens(path, &config.prompt)
        }
    };

    let model = OwnedQuantizedModel::from_apr(&mapped)
        .map_err(|e| CliError::ValidationFailed(format!("Failed to create quantized model from APR: {e}")))?;

    let mut cuda_model = OwnedQuantizedModelCuda::new(model, 0)
        .map_err(|e| CliError::ValidationFailed(format!("Failed to init CUDA: {e}")))?;

    let gen_config = QuantizedGenerateConfig {
        max_tokens: config.max_tokens.min(128),
        temperature: 0.0,
        top_k: 1,
        ..Default::default()
    };

    let load_time = start.elapsed();
    if !config.quiet {
        eprintln!(
            "{} in {:.2}s ({} tensors, GPU device 0, fused Q4K kernels)",
            "Model ready".green(),
            load_time.as_secs_f32(),
            tensor_count
        );
        eprintln!();
    }

    // Warmup (untraced)
    run_bench_warmup(config, config.warmup, || {
        let _ = cuda_model.generate_gpu_resident(&prompt_tokens, &gen_config);
    });

    // Measurement
    if !config.quiet {
        eprintln!("{}", "Running benchmark (GPU)...".yellow());
    }
    let mut iteration_times = Vec::with_capacity(config.iterations);
    let mut total_tokens = 0usize;
    let mut first_token_time = Duration::ZERO;
    let budget_us = config.max_tokens as u64 * 100_000;

    for i in 0..config.iterations {
        let traced = tracer.trace("bench_apr_gpu_iter", budget_us, || {
            cuda_model
                .generate_gpu_resident(&prompt_tokens, &gen_config)
                .unwrap_or_default()
        });
        let output = traced.result;
        let tokens_generated = output.len().saturating_sub(prompt_tokens.len());

        let iter_time = Duration::from_micros(traced.duration_us);
        iteration_times.push(iter_time);
        total_tokens += tokens_generated;

        if i == 0 {
            first_token_time =
                Duration::from_secs_f64(iter_time.as_secs_f64() / tokens_generated.max(1) as f64);
        }

        print_bench_progress(config, i, tokens_generated, iter_time);
    }
    if !config.quiet {
        eprintln!();
        eprintln!();
    }

    calculate_benchmark_stats(iteration_times, total_tokens, first_token_time, config)
}