apr-cli 0.4.12

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
//! Prune command implementation (GH-247)
//!
//! Structured pruning pipeline for removing attention heads, MLP neurons,
//! or entire layers from transformer models.
//!
//! # Example
//!
//! ```bash
//! apr prune model.apr --method structured --target-ratio 0.5 -o pruned.apr
//! apr prune model.apr --method depth --remove-layers 20-24 -o pruned.apr
//! apr prune model.apr --method magnitude --sparsity 0.5 -o pruned.apr
//! apr prune model.apr --analyze --json
//! ```

use crate::error::{CliError, Result};
use crate::output;
use aprender::format::v2::{AprV2Header, AprV2Metadata, HEADER_SIZE_V2};
use std::io::{Read as _, Seek, SeekFrom};
use std::path::Path;

/// Pruning method selection
#[derive(Debug, Clone, Copy, Default)]
pub enum PruneMethod {
    /// Unstructured magnitude pruning (zero out small weights)
    #[default]
    Magnitude,
    /// Structured pruning (remove attention heads / MLP neurons)
    Structured,
    /// Depth pruning (remove entire layers)
    Depth,
    /// Width pruning (reduce hidden dimensions)
    Width,
    /// Wanda pruning (weights and activations)
    Wanda,
    /// SparseGPT pruning
    SparseGpt,
}

impl std::str::FromStr for PruneMethod {
    type Err = String;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "magnitude" | "mag" => Ok(Self::Magnitude),
            "structured" | "struct" => Ok(Self::Structured),
            "depth" | "layer" => Ok(Self::Depth),
            "width" | "hidden" => Ok(Self::Width),
            "wanda" => Ok(Self::Wanda),
            "sparsegpt" | "sparse_gpt" => Ok(Self::SparseGpt),
            _ => Err(format!(
                "Unknown pruning method: {s}. Supported: magnitude, structured, depth, width, wanda, sparsegpt"
            )),
        }
    }
}

/// Validate prune command parameters (target ratio, sparsity, method).
fn validate_prune_params(
    file: &Path,
    method: &str,
    target_ratio: f32,
    sparsity: f32,
) -> Result<PruneMethod> {
    if !file.exists() {
        return Err(CliError::FileNotFound(file.to_path_buf()));
    }
    let prune_method: PruneMethod = method.parse().map_err(CliError::ValidationFailed)?;
    if target_ratio <= 0.0 || target_ratio >= 1.0 {
        return Err(CliError::ValidationFailed(format!(
            "Target ratio must be between 0 and 1 (exclusive), got {target_ratio}"
        )));
    }
    if !(0.0..=1.0).contains(&sparsity) {
        return Err(CliError::ValidationFailed(format!(
            "Sparsity must be between 0 and 1, got {sparsity}"
        )));
    }
    Ok(prune_method)
}

/// Print the configuration summary table before pruning.
#[allow(clippy::disallowed_methods)]
fn print_config_table(
    file: &Path,
    out: &Path,
    prune_method: PruneMethod,
    target_ratio: f32,
    sparsity: f32,
    remove_layers: Option<&str>,
    calibration: Option<&Path>,
) {
    output::header("APR Prune");
    let mut pairs = vec![
        ("Input", file.display().to_string()),
        ("Method", format!("{prune_method:?}")),
        ("Target ratio", format!("{target_ratio:.2}")),
        ("Output", out.display().to_string()),
    ];
    if sparsity > 0.0 {
        pairs.push(("Sparsity", format!("{sparsity:.2}")));
    }
    if let Some(layers) = remove_layers {
        pairs.push(("Remove layers", layers.to_string()));
    }
    if let Some(cal) = calibration {
        pairs.push(("Calibration", cal.display().to_string()));
    }
    println!("{}", output::kv_table(&pairs));
    println!();
}

/// Validate depth-pruning specific arguments.
fn validate_depth_args(prune_method: PruneMethod, remove_layers: Option<&str>) -> Result<()> {
    if matches!(prune_method, PruneMethod::Depth) && remove_layers.is_none() {
        return Err(CliError::ValidationFailed(
            "Depth pruning requires --remove-layers (e.g., --remove-layers 20-24)".to_string(),
        ));
    }
    Ok(())
}

/// Run the prune command
#[allow(clippy::too_many_arguments)]
#[allow(clippy::disallowed_methods)]
pub(crate) fn run(
    file: &Path,
    method: &str,
    target_ratio: f32,
    sparsity: f32,
    output_path: Option<&Path>,
    remove_layers: Option<&str>,
    analyze_only: bool,
    plan_only: bool,
    calibration: Option<&Path>,
    json_output: bool,
) -> Result<()> {
    let prune_method = validate_prune_params(file, method, target_ratio, sparsity)?;

    // GH-513: Reject --calibration since calibration-aware pruning is not yet implemented
    if calibration.is_some() {
        return Err(CliError::ValidationFailed(
            "--calibration is not yet implemented. Use magnitude or depth pruning without calibration data.".to_string(),
        ));
    }

    // Analyze mode
    if analyze_only {
        return run_analyze(file, prune_method, json_output);
    }

    // Plan mode
    if plan_only {
        return run_plan(file, prune_method, target_ratio, sparsity, json_output);
    }

    let out = output_path.ok_or_else(|| {
        CliError::ValidationFailed(
            "Output path required. Use -o <path> to specify output.".to_string(),
        )
    })?;

    if !json_output {
        print_config_table(
            file,
            out,
            prune_method,
            target_ratio,
            sparsity,
            remove_layers,
            calibration,
        );
    }

    validate_depth_args(prune_method, remove_layers)?;

    if !json_output {
        output::pipeline_stage("Pruning", output::StageStatus::Running);
    }

    let prune_result = execute_pruning(
        file,
        prune_method,
        target_ratio,
        sparsity,
        remove_layers,
        out,
    )?;

    if !json_output {
        output::pipeline_stage("Pruning", output::StageStatus::Done);
    }

    print_prune_output(
        file,
        out,
        prune_method,
        target_ratio,
        sparsity,
        &prune_result,
        json_output,
    );

    Ok(())
}

/// Result of the pruning operation, containing all metrics needed for output.
struct PruneResult {
    file_size: u64,
    output_size: u64,
    original_count: usize,
    pruned_count: usize,
    original_params: usize,
    pruned_params: usize,
    zeros: usize,
}

/// Load model, apply pruning, and write the output file.
fn execute_pruning(
    file: &Path,
    prune_method: PruneMethod,
    target_ratio: f32,
    sparsity: f32,
    remove_layers: Option<&str>,
    out: &Path,
) -> Result<PruneResult> {
    let file_size = std::fs::metadata(file)
        .map_err(|e| CliError::ValidationFailed(format!("Cannot read model: {e}")))?
        .len();

    let rosetta = aprender::format::rosetta::RosettaStone::new();
    let report = rosetta
        .inspect(file)
        .map_err(|e| CliError::ValidationFailed(format!("Failed to inspect model: {e}")))?;

    let mut tensors = std::collections::BTreeMap::new();
    for ti in &report.tensors {
        if let Ok(data) = rosetta.load_tensor_f32(file, &ti.name) {
            tensors.insert(ti.name.clone(), (data, ti.shape.clone()));
        }
    }

    let original_count = tensors.len();
    let original_params: usize = tensors
        .values()
        .map(|(data, _shape): &(Vec<f32>, Vec<usize>)| data.len())
        .sum();

    let pruned_tensors = apply_pruning(
        &tensors,
        prune_method,
        target_ratio,
        sparsity,
        remove_layers,
    )?;

    let pruned_count = pruned_tensors.len();
    let pruned_params: usize = pruned_tensors
        .values()
        .map(|(data, _shape): &(Vec<f32>, Vec<usize>)| data.len())
        .sum();
    let zeros: usize = pruned_tensors
        .values()
        .map(|(data, _shape): &(Vec<f32>, Vec<usize>)| data.iter().filter(|v| **v == 0.0).count())
        .sum();

    let bytes = write_pruned_model(
        file,
        prune_method,
        target_ratio,
        sparsity,
        &pruned_tensors,
        out,
    )?;
    let output_size = bytes.len() as u64;

    Ok(PruneResult {
        file_size,
        output_size,
        original_count,
        pruned_count,
        original_params,
        pruned_params,
        zeros,
    })
}

/// Apply the selected pruning method to the tensor map.
#[allow(clippy::type_complexity)]
fn apply_pruning(
    tensors: &std::collections::BTreeMap<String, (Vec<f32>, Vec<usize>)>,
    prune_method: PruneMethod,
    target_ratio: f32,
    sparsity: f32,
    remove_layers: Option<&str>,
) -> Result<std::collections::BTreeMap<String, (Vec<f32>, Vec<usize>)>> {
    match prune_method {
        PruneMethod::Magnitude => Ok(prune_magnitude(tensors, sparsity.max(target_ratio))),
        PruneMethod::Depth => {
            let layers = remove_layers.expect("validated above");
            prune_depth(tensors, layers)
        }
        PruneMethod::Structured | PruneMethod::Width => {
            Ok(prune_magnitude(tensors, sparsity.max(target_ratio)))
        }
        PruneMethod::Wanda | PruneMethod::SparseGpt => {
            Ok(prune_magnitude(tensors, sparsity.max(target_ratio)))
        }
    }
}

/// Serialize pruned tensors and write the APR file to disk.
#[allow(clippy::disallowed_methods)]
fn write_pruned_model(
    source_file: &Path,
    prune_method: PruneMethod,
    target_ratio: f32,
    sparsity: f32,
    pruned_tensors: &std::collections::BTreeMap<String, (Vec<f32>, Vec<usize>)>,
    out: &Path,
) -> Result<Vec<u8>> {
    let mut writer = aprender::serialization::apr::AprWriter::new();
    writer.set_metadata(
        "pruning_method",
        serde_json::json!(format!("{prune_method:?}")),
    );
    writer.set_metadata("pruning_ratio", serde_json::json!(target_ratio));
    writer.set_metadata("pruning_sparsity", serde_json::json!(sparsity));
    writer.set_metadata(
        "source_file",
        serde_json::json!(source_file.display().to_string()),
    );

    for (name, (data, shape)) in pruned_tensors {
        writer.add_tensor_f32(name, shape.clone(), data);
    }

    let bytes = writer.to_bytes().map_err(|e| {
        CliError::ValidationFailed(format!("Failed to serialize pruned model: {e}"))
    })?;
    std::fs::write(out, &bytes)
        .map_err(|e| CliError::ValidationFailed(format!("Failed to write output: {e}")))?;

    Ok(bytes)
}

/// Print pruning results as JSON or human-readable table.
#[allow(clippy::disallowed_methods)]
fn print_prune_output(
    file: &Path,
    out: &Path,
    prune_method: PruneMethod,
    target_ratio: f32,
    sparsity: f32,
    result: &PruneResult,
    json_output: bool,
) {
    if json_output {
        let json = serde_json::json!({
            "status": "completed",
            "input": file.display().to_string(),
            "output": out.display().to_string(),
            "method": format!("{prune_method:?}"),
            "target_ratio": target_ratio,
            "sparsity": sparsity,
            "input_size": result.file_size,
            "output_size": result.output_size,
            "tensors": result.pruned_count,
            "original_params": result.original_params,
            "pruned_params": result.pruned_params,
            "zero_params": result.zeros,
            "actual_sparsity": if result.pruned_params > 0 { result.zeros as f64 / result.pruned_params as f64 } else { 0.0 },
        });
        println!(
            "{}",
            serde_json::to_string_pretty(&json).unwrap_or_default()
        );
    } else {
        println!();
        output::subheader("Pruning Complete");
        println!(
            "{}",
            output::kv_table(&[
                (
                    "Input size",
                    humansize::format_size(result.file_size, humansize::BINARY)
                ),
                (
                    "Output size",
                    humansize::format_size(result.output_size, humansize::BINARY)
                ),
                (
                    "Tensors",
                    format!("{}{}", result.original_count, result.pruned_count)
                ),
                (
                    "Parameters",
                    format!("{}{}", result.original_params, result.pruned_params)
                ),
                (
                    "Zeros",
                    format!(
                        "{} ({:.1}%)",
                        result.zeros,
                        if result.pruned_params > 0 {
                            result.zeros as f64 / result.pruned_params as f64 * 100.0
                        } else {
                            0.0
                        }
                    )
                ),
                ("Output", out.display().to_string()),
            ])
        );
    }
}

/// Analyze model for pruning opportunities
#[allow(clippy::disallowed_methods)]
fn run_analyze(file: &Path, method: PruneMethod, json_output: bool) -> Result<()> {
    let file_size = std::fs::metadata(file)
        .map_err(|e| CliError::ValidationFailed(format!("Cannot read model: {e}")))?
        .len();

    // Read actual parameter count from model metadata (GH-499)
    let estimated_params = read_param_count(file).unwrap_or_else(|_| {
        // Fallback: estimate from file size assuming F32 (4 bytes/param)
        file_size / 4
    });

    if json_output {
        let json = serde_json::json!({
            "analysis": true,
            "input": file.display().to_string(),
            "file_size": file_size,
            "estimated_params": estimated_params,
            "method": format!("{method:?}"),
            "recommendations": [
                {"ratio": 0.2, "description": "Conservative (minimal quality loss)"},
                {"ratio": 0.5, "description": "Balanced (moderate compression)"},
                {"ratio": 0.8, "description": "Aggressive (significant quality loss)"},
            ],
        });
        println!(
            "{}",
            serde_json::to_string_pretty(&json).unwrap_or_default()
        );
    } else {
        output::header("APR Prune — Analysis");
        println!(
            "{}",
            output::kv_table(&[
                ("Input", file.display().to_string()),
                (
                    "File size",
                    humansize::format_size(file_size, humansize::BINARY),
                ),
                ("Est. parameters", format_params(estimated_params),),
                ("Method", format!("{method:?}")),
            ])
        );
        println!();
        output::subheader("Pruning Recommendations");
        println!("  20% — Conservative (minimal quality loss)");
        println!("  50% — Balanced (moderate compression)");
        println!("  80% — Aggressive (significant quality loss)");
        println!();
        println!(
            "  {} Use --target-ratio <0-1> to set pruning target.",
            output::badge_info("INFO"),
        );
    }

    Ok(())
}

/// Read param_count from APR v2 metadata header (GH-499)
fn read_param_count(file: &Path) -> Result<u64> {
    let mut reader = std::io::BufReader::new(std::fs::File::open(file).map_err(CliError::Io)?);
    let mut header_bytes = [0u8; HEADER_SIZE_V2];
    reader.read_exact(&mut header_bytes)?;
    let header = AprV2Header::from_bytes(&header_bytes)
        .map_err(|e| CliError::InvalidFormat(format!("Failed to parse header: {e}")))?;
    if header.metadata_size > 0 {
        reader
            .seek(SeekFrom::Start(header.metadata_offset))
            .map_err(CliError::Io)?;
        let mut meta_bytes = vec![0u8; header.metadata_size as usize];
        reader.read_exact(&mut meta_bytes)?;
        if let Ok(meta) = AprV2Metadata::from_json(&meta_bytes) {
            if meta.param_count > 0 {
                return Ok(meta.param_count);
            }
        }
    }
    Err(CliError::ValidationFailed(
        "No param_count in metadata".into(),
    ))
}

include!("prune_include_01.rs");