tract 0.22.1

Tiny, no-nonsense, self contained, TensorFlow and ONNX inference
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
#![allow(clippy::len_zero)]
#![allow(clippy::redundant_closure_call)]
#![allow(clippy::collapsible_if)]
#[macro_use]
extern crate log;

#[macro_use]
mod macros;

#[allow(unused_imports)]
use tract_itertools::Itertools;

use tract_core::internal::*;
use tract_hir::internal::*;

use nu_ansi_term::Color::*;
use tract_libcli::annotations::Annotations;
use tract_libcli::display_params::DisplayParams;
use tract_libcli::model::Model;
use tract_libcli::profile::BenchLimits;

use fs_err as fs;
use readings_probe::*;

mod bench;
mod compare;
mod cost;
mod dump;
mod hwbench;
mod llm;
mod memory_arena;
mod params;
mod plan_options;
mod run;
#[cfg(feature = "pulse")]
mod stream_check;
mod tensor;
mod utils;

use params::*;
use tract_linalg::WeightType;
use tract_linalg::block_quant::Q4_0;
use tract_linalg::mmm::MatMatMul;

readings_probe::instrumented_allocator!();

pub const QUALITY_COLORS: [nu_ansi_term::Color; 5] = [LightGreen, Green, White, Yellow, LightRed];

fn info_usage(stage: &str, probe: Option<&Probe>) {
    if let Some(mon) = probe {
        let _ = mon.log_event(stage);
    }
    if log::log_enabled!(log::Level::Info) {
        let usage = readings_probe::get_os_readings().unwrap();
        let allocated = readings_probe::alloc::ALLOCATED.load(std::sync::atomic::Ordering::Relaxed);
        let freeed = readings_probe::alloc::FREEED.load(std::sync::atomic::Ordering::Relaxed);
        info!(
            "Resource usage {}: vsz:{} rsz:{} rszmax:{} alloc:{}",
            stage,
            usage.virtual_size,
            usage.resident_size,
            usage.resident_size_max,
            allocated.saturating_sub(freeed),
        );
    }
}

pub const STAGES: &[&str] = &[
    "load",
    "analyse",
    "incorporate",
    "type",
    "declutter",
    "pulse",
    "pulse-to-type",
    "pulse-declutter",
    "set",
    "set-declutter",
    "nnef-cycle",
    "nnef-cycle-declutter",
    "tflite-cycle-predump",
    "tflite-cycle",
    "tflite-cycle-declutter",
    "before-optimize",
    "optimize",
];

/// Entrypoint for the command-line interface.
fn main() -> TractResult<()> {
    use clap::*;
    let mut app = command!()
        .setting(AppSettings::DeriveDisplayOrder)
        .allow_hyphen_values(true)
        .arg(arg!(--readings "Start readings instrumentation"))
        .arg(arg!(--"readings-heartbeat" [MS] "Heartbeat for readings background collector").default_value("5"))
        .arg(arg!(verbose: -v ... "Sets the level of verbosity."))
        .arg(arg!(--"keep-last" "Keep last model alive to dump if there is an error"))
        .arg(arg!([model] "Sets the model to use").required(false))
        .arg(arg!(-f --format [format]
                  "Hint the model format ('onnx', 'nnef', 'tflite' or 'tf') instead of guess from extension."))
        .arg(Arg::new("input").long("input").short('i').multiple_occurrences(true).takes_value(true).long_help(
                "Set input shape and type (@file.pb or @file.npz:thing.npy or 3,4,i32)."))
        .arg(Arg::new("constantize").long("constantize").multiple_occurrences(true).takes_value(true).long_help(
                "Transorm an input into a Constant"))

        .arg(arg!(--"assert").multiple_occurrences(true).takes_value(true).long_help("Adds a TDim pre-condition (prefix by optional \"scenario_name:\")"))
        .arg(arg!(--"scenario").multiple_occurrences(true).takes_value(true).long_help("Adds a scenario"))

        // deprecated
        .arg(arg!(--"input-bundle" [input_bundle] "Path to an input container (.npz). This sets input facts and tensor values.").hide(true))
        // deprecated
        .arg(arg!(--"allow-random-input" "Will use random generated input").hide(true))

        .arg(arg!(--"input-facts-from-bundle" [input_bundle] "Path to an input container (.npz). This only sets input facts."))

        .arg(arg!(--"edge-left-context" [frames] "Add lines of left context to input (dupping first time frame)").alias("kaldi-left-context"))
        .arg(arg!(--"edge-right-context" [frames] "Add lines of right context to input (dupping last time frame)").alias("kaldi-right-context"))

        .arg(arg!(--"onnx-test-data-set" [data_set] "Use onnx-test data-set as input (expect test_data_set_N dir with input_X.pb, etc. inside)"))
        .arg(arg!(--"onnx-ignore-output-shapes" "Ignore output shapes from model (workaround for pytorch export bug with mask axes)"))
        .arg(arg!(--"onnx-ignore-output-types" "Ignore output shapes from types (workaround for tdim conflicting with integer types)"))

        .arg(arg!(--"input-node" [node] ... "Override input nodes names (auto-detects otherwise)."))
        .arg(Arg::new("output-node").long("output-node").multiple_occurrences(true).takes_value(true).long_help(
                "Override output nodes by name."))
        .arg(arg!(--"label-wires" "Propagate node labels to wires"))

        .arg(arg!(--"tf-initializer-output-node" [node] "Set an initializer node"))

        .arg(arg!(--"override-fact" [fact] "Override a fact."))

        .arg(arg!(--"analyse-fail-fast" "Stop analyse at first error."))
        .arg(arg!(--recursive "Apply to sub graphes"))
        .arg(arg!(--proto "Keep proto model around after parse"))
        .arg(arg!(--determinize "Enforce a seed in random operator"))
        .arg(arg!(--partial "Before analyse, eliminate dead branches"))

        .arg(arg!(--pass [STAGE] "Pass to stop preprocessing after.").possible_values(STAGES))
        .arg(arg!(--"declutter-step" [STEP] "Stop decluttering process after application of patch number N"))
        .arg(arg!(--"declutter-set-step" [STEP] "Stop decluttering process (the one after --set application) at patch number N"))
        .arg(arg!(--"optimize-step" [STEP] "Stop optimizing process after application of patch number N"))
        .arg(arg!(--"extract-decluttered-sub" [SUB] "Zoom on a subgraph after decluttering by parent node name"))

        .arg(Arg::new("f32-to-f16").long("f32-to-f16").alias("half-floats").long_help("Convert the decluttered network from f32 to f16"))
        .arg(arg!(--"f16-to-f32" "Convert the decluttered network from f16 to f32"))
        .arg(arg!(--"metal").long_help("Convert supported operators to Metal GPU equivalent. Only available on MacOS and iOS"))
        .arg(Arg::new("force-metal-backend").long("force-metal-backend").takes_value(true).long_help("Force specific implementations for MM kernels. Possible values: mlx, ggml, mfa. Backend is dynamically selected if option is not present"))
        .arg(arg!(--"cuda").long_help("Convert supported operators to CUDA equivalent"))
        .arg(Arg::new("transform").short('t').long("transform").multiple_occurrences(true).takes_value(true).help("Apply a built-in transformation to the model"))
        .arg(Arg::new("set").long("set").multiple_occurrences(true).takes_value(true)
             .long_help("Set a symbol to a concrete value after decluttering"))

        // deprecated
        .arg(arg!(--"allow-float-casts" "Allow casting between f16, f32 and f64 around model").hide(true))

        .arg(arg!(--"nnef-cycle" "Perform NNEF dump and reload before optimizing"))
        .arg(arg!(--"tflite-cycle" "Perform TFLITE dump and reload before optimizing"))

        .arg(arg!(--"nnef-tract-core" "Allow usage of tract-core extension in NNEF dump and load"))
        .arg(arg!(--"nnef-tract-resource" "Allow usage of tract-resource extension in NNEF dump and load"))
        .arg(arg!(--"nnef-tract-onnx" "Allow usage of tract-onnx extension in NNEF dump and load"))
        .arg(arg!(--"nnef-tract-pulse" "Allow usage of tract-pulse extension in NNEF dump and load"))
        .arg(arg!(--"nnef-tract-extra" "Allow usage of tract-extra extension in NNEF dump and load"))
        .arg(arg!(--"nnef-tract-transformers" "Allow usage of tract-transformers extension in NNEF dump and load"))
        .arg(arg!(--"nnef-extended-identifier" "Allow usage of the i\"...\" syntax to escape identifier names"))

        .arg(arg!(--"threads" [THREADS] "Setup a thread pool for computing. 0 will guess the number of physical cores"))

        .arg(arg!(-O --optimize "Optimize before running"))
        .arg(arg!(--"assert-maximal-mm-quality-cost" [MAX] "Maximum value for quality category (0=assembly, 4=dreadful rust code)"))
        .arg(arg!(--pulse [PULSE] "Translate to pulse network"))

        .arg(arg!(--"machine-friendly" "Machine friendly output"))

        .subcommand(Command::new("list-ops").about("List ops in TF/ONNX frameworks"))
        .subcommand(Command::new("kernels").about("Print kernels for the current plaform"))
        .subcommand(Command::new("hwbench").about("Print current hardware key metrics"));

    let compare = clap::Command::new("compare")
        .long_about("Compares the output of tract and tensorflow on randomly generated input.")
        .arg(
            Arg::new("stage")
                .long("stage")
                .takes_value(true)
                .possible_values(STAGES)
                .help("Loading pipeline stage to compare with"),
        )
        .arg(Arg::new("tf").long("tf").takes_value(false).help("Compare against tensorflow"))
        .arg(Arg::new("twice").long("twice").takes_value(false).help("Run twice and compare"))
        .arg(Arg::new("npz").long("npz").takes_value(true).help("NPZ file to compare against"))
        .arg(
            Arg::new("pbdir")
                .long("pbdir")
                .takes_value(true)
                .help("protobuf directory file to compare against (like ONNX tests)"),
        )
        .group(
            ArgGroup::new("reference")
                .args(&["npz", "pbdir", "stage", "tf", "twice"])
                .required(true),
        )
        .arg(
            Arg::new("cumulative")
                .long("cumulative")
                .takes_value(false)
                .help("Do not reset with reference values at each node"),
        )
        .arg(
            Arg::new("resilient")
                .long("resilient")
                .takes_value(false)
                .help("Try nodes one per one to mitigate crashes"),
        );
    let compare = run_options(compare);
    let compare = assertions_options(compare);
    app = app.subcommand(output_options(compare));

    let bench =
        clap::Command::new("bench").long_about("Benchmarks tract on randomly generated input.");
    let bench = run_options(bench);
    let bench = output_options(bench);
    let bench = bench_options(bench);
    let bench = assertions_options(bench);
    app = app.subcommand(bench);

    let criterion = clap::Command::new("criterion")
        .long_about("Benchmarks tract on randomly generated input using criterion.");
    let criterion = run_options(criterion);
    app = app.subcommand(criterion);

    app = app.subcommand(dump_subcommand());

    let run = clap::Command::new("run")
        .long_about("Run the graph")
        .arg(Arg::new("dump").long("dump").help("Show output"))
        .arg(
            Arg::new("save-outputs-npz")
                .long("save-outputs-npz")
                .alias("save-outputs")
                .takes_value(true)
                .help("Save the outputs into a npz file"),
        )
        .arg(
            Arg::new("save-outputs-nnef")
                .long("save-outputs-nnef")
                .takes_value(true)
                .help("Save the output tensor into a folder of nnef .dat files"),
        )
        .arg(Arg::new("steps").long("steps").help("Show all inputs and outputs"))
        .arg(
            Arg::new("save-steps")
                .long("save-steps")
                .takes_value(true)
                .help("Save intermediary values as a npz file"),
        )
        .arg(
            Arg::new("check-f16-overflow")
                .long("check-f16-overflow")
                .help("Check for f16 overflow in all outputs"),
        )
        .arg(
            Arg::new("assert-sane-floats")
                .long("assert-sane-floats")
                .help("Check float for NaN and infinites at each step"),
        );
    let run = run_options(run);
    let run = output_options(run);
    let run = assertions_options(run);
    app = app.subcommand(run);

    let llm_bench =
        clap::Command::new("llm-bench").long_about("llamas.cpp-style bench (tg128 and pp512)");
    let llm_bench = assertions_options(llm_bench);
    let llm_bench = run_options(llm_bench);
    app = app.subcommand(llm_bench);

    let stream_check = clap::Command::new("stream-check")
        .long_about("Compare output of streamed and regular exec");
    app = app.subcommand(output_options(stream_check));

    let matches = app.get_matches();

    let probe = if matches.is_present("readings") {
        let file = fs::File::create("readings.out").unwrap();
        let mut probe = Probe::new(file).unwrap();
        probe.register_i64("progress").unwrap();
        let heartbeat = matches.value_of("readings-heartbeat").unwrap().parse::<f32>().unwrap();
        probe.spawn_heartbeat(std::time::Duration::from_secs_f32(heartbeat / 1000.0)).unwrap();
        Some(probe)
    } else {
        None
    };

    if ::std::env::var("TRACT_LOG").is_err() {
        let level = match matches.occurrences_of("verbose") {
            0 => "cli=warn,tract=warn",
            1 => "cli=info,tract=info",
            2 => "cli=debug,tract=debug",
            _ => "cli=trace,tract=trace",
        };
        unsafe {
            std::env::set_var("TRACT_LOG", level);
        }
    }

    let env = env_logger::Env::default().filter_or("TRACT_LOG", "warn");

    env_logger::Builder::from_env(env).format_timestamp_nanos().init();
    info_usage("init", probe.as_ref());

    let res = handle(matches, probe.as_ref());

    if let Err(e) = res {
        error!("{e:?}");
        std::process::exit(1);
    }

    info_usage("done", probe.as_ref());
    Ok(())
}

#[allow(clippy::let_and_return)]
fn dump_subcommand<'a>() -> clap::Command<'a> {
    use clap::*;
    let dump = clap::Command::new("dump")
        .long_about("Dumps the graph in human readable form.")
        .arg(
            Arg::new("axes")
            .long("axes")
            .help("Compute and display axis tracking")
            )
        .arg(
            Arg::new("axes-names")
            .takes_value(true)
            .number_of_values(1)
            .multiple_occurrences(true)
            .long("axes-names")
            .help("Gave meaningful names to axes: [node_name=]axis0,axis1,..,axisN (apply to first input if no node_name is provided)")
            )
        .arg(
            Arg::new("assert-cost")
            .takes_value(true)
            .long("assert-cost")
            .help("Checks computed against the provided value (form: \"FMA(F32)=2060448 DIV(F32)=24576\")")
            )
        .arg(
            Arg::new("memory-arena")
            .takes_value(true)
            .long("memory-arena")
            .help("Dump arena memory statistics to a JSON file (MacOS / iOS only)")
        )
        .arg(
            Arg::new("nnef-override-output-name")
            .takes_value(true)
            .number_of_values(1)
            .long("nnef-override-output-name")
            .help("Rename output before dumping network")
            )
        .arg(
            Arg::new("nnef-dir")
            .takes_value(true)
            .long("nnef-dir")
            .help("Dump the network in NNEF format (as a directory)"),
            )
        .arg(
            Arg::new("nnef-tar")
            .takes_value(true)
            .long("nnef-tar")
            .help("Dump the network in NNEF format (as a tar file)"),
            )
        .arg(
            Arg::new("nnef")
            .takes_value(true)
            .long("nnef")
            .help("Dump the network in NNEF format (as a tar.gz file)"),
            )
        .arg(
            Arg::new("tflite")
            .takes_value(true)
            .long("tflite")
            .help("Dump the network in TfLite format"),
            )
        .arg(
            Arg::new("compress-submodels")
            .long("compress-submodels")
            .help("Compress submodels if any (as a .tgz file)"),
        )
        .arg(
            Arg::new("nnef-deterministic")
            .long("nnef-deterministic")
            .help("If provided, will try to make output .nnef.tar files deterministic"),
            )
        .arg(
            Arg::new("nnef-graph")
            .takes_value(true)
            .long("nnef-graph")
            .help("Dump the network definition (without the weights) as a graph.nnef-like file"),
            )
        .arg(
            Arg::new("inner")
            .takes_value(true)
            .number_of_values(1)
            .multiple_occurrences(true)
            .long("inner")
            .help("Navigate to a sub-model"),
            );
    let dump = run_options(dump);
    let dump = output_options(dump);
    let dump = assertions_options(dump);
    let dump = bench_options(dump);
    dump
}

fn assertions_options(command: clap::Command) -> clap::Command {
    use clap::*;
    command
        .arg(
            Arg::new("approx")
            .takes_value(true)
            .possible_values(["exact", "close", "approximate", "very", "super", "ultra"])
            .default_value("close")
            .long("approx")
            .help("Approximation level used in assertions."),
            )
        .arg(
            Arg::new("approx-custom")
            .takes_value(true)
            .long("approx-custom")
            .help("Approximation level used in assertions (atol, rtol, outlier ratio). 3 coma-separated floats."),
            )
        .arg(
            Arg::new("assert-output")
            .takes_value(true)
            .multiple_occurrences(true)
            .number_of_values(1)
            .long("assert-output")
            .help("Fact to check the ouput tensor against (@filename, or 3x4xf32)"),
            )
        .arg(
            Arg::new("assert-output-bundle")
            .takes_value(true)
            .long("assert-output-bundle")
            .help("Checks values against these tensor (.npz)"),
            )
        .arg(
            Arg::new("assert-output-fact")
            .takes_value(true)
            .long("assert-output-fact")
            .help("Infered shape and datum type must match exactly this"),
            )
        .arg(
            Arg::new("assert-output-count")
            .takes_value(true)
            .long("assert-output-count")
            .help("Check the number of outputs found."),
            )
        .arg(
            Arg::new("allow-missing-outputs")
            .long("allow-missing-outputs")
            .help("Allow missing output in checks")
            )
        .arg(
            Arg::new("assert-op-count")
            .takes_value(true)
            .forbid_empty_values(true)
            .number_of_values(2)
            .value_names(&["operator", "count"])
            .multiple_occurrences(true)
            .long("assert-op-count")
            .help("Specified operator must appear exactly the specified number of times. This argument can appear multiple times."),
            )
}

fn bench_options(command: clap::Command) -> clap::Command {
    use clap::*;
    command.args(&[
                 arg!(--"warmup-time" [warmup_time] "Time to run (approx.) before starting the clock."),
                 arg!(--"warmup-loops" [warmup_loops] "Number of loops to run before starting the clock."),
                 arg!(--"max-loops" [max_iters] "Sets the maximum number of iterations for each node [default: 100_000].").alias("max-iters"),
                 arg!(--"max-time" [max_time] "Sets the maximum execution time for each node (in ms) [default: 5000].") ])
}

fn run_options(command: clap::Command) -> clap::Command {
    use clap::*;
    command
        .arg(
            Arg::new("input-from-npz")
            .long("input-from-npz")
            .alias("input-from-bundle")
            .takes_value(true)
            .help("Path to an input container (.npz). This sets tensor values."),
            )
        .arg(
            Arg::new("set")
                .long("set")
                .takes_value(true)
                .multiple_occurrences(true)
                .number_of_values(1)
                .help("Set a symbol value before running the model (--set S=12)"),
        )
        .arg(
            Arg::new("input-from-nnef").long("input-from-nnef").takes_value(true).help(
                "Path to a directory containing input tensors in NNEF format (.dat files). This sets tensor values.",
                ),
                )
        .arg(arg!(--pp [pp] "Random input for LLM-like prompt processing"))
        .arg(arg!(--tg [tg] "Random input for LLM-like text generation"))
        .arg(Arg::new("skip-order-opt-ram")
            .long("skip-order-opt-ram")
            .help("Plan node evaluation order without RAM optimisation"),
            )
        .arg(
            Arg::new("allow-random-input")
            .short('R')
            .long("allow-random-input")
            .help("Will use random generated input"),
            )
        .arg(
            Arg::new("random-range")
            .long("random-range")
            .multiple_occurrences(true)
            .takes_value(true)
            .help("Constraint random values to a given range (example: input=1.0..10.0)"),
            )
        .arg(
            Arg::new("allow-float-casts")
            .long("allow-float-casts")
            .help("Allow casting between f16, f32 and f64 around model"),
            )
        .arg(
            Arg::new("metal-gpu-trace")
                .long("metal-gpu-trace")
                .takes_value(true)
                .help("Capture Metal GPU trace and save it at given path. Only available on MacOS and iOS")
        )
        .arg(
            Arg::new("cuda-gpu-trace")
                .long("cuda-gpu-trace")
                .help("Capture CUDA GPU trace. Must be used with nsys profile -c cudaProfilerApi before cargo command")
        )
}

fn output_options(command: clap::Command) -> clap::Command {
    use clap::*;
    command
        .args(&[
            arg!(--"natural-order" "dump nodes in id order instead of evaluation order"),
            arg!(--"opt-ram-order" "dump nodes in RAM optimising order"),
            arg!(-q --quiet "don't dump"),
        ])
        .arg(Arg::new("debug-op").long("debug-op").help("show debug dump for each op"))
        .arg(Arg::new("node-id").long("node-id").takes_value(true).help("Select a node to dump"))
        .arg(
            Arg::new("successors")
                .long("successors")
                .takes_value(true)
                .help("Show successors of node"),
        )
        .arg(Arg::new("op-name").long("op-name").takes_value(true).help("Select one op to dump"))
        .arg(
            Arg::new("node-name")
                .long("node-name")
                .takes_value(true)
                .help("Select one node to dump"),
        )
        .arg(Arg::new("const").long("const").help("also display consts nodes"))
        .arg(Arg::new("info").long("info").help("show op inner information"))
        .arg(Arg::new("io-long").long("io-long").help("show full i/o information"))
        .arg(Arg::new("io-none").long("io-none").help("hide i/o information"))
        .arg(Arg::new("json").long("json").help("dump performance info as json"))
        .arg(Arg::new("mm").long("mm").help("display Matrix Multiplication report"))
        .arg(Arg::new("outlet-labels").long("outlet-labels").help("display outlet labels"))
        .arg(Arg::new("cost").long("cost").help("Include const information"))
        .arg(
            Arg::new("tmp_mem_usage")
                .long("tmp-mem-usage")
                .help("Include temporary memory usage information"),
        )
        .arg(Arg::new("profile").long("profile").help("Include results for profile run"))
        .arg(Arg::new("folded").long("folded").help("Don't display submodel informations"))
        .arg(
            Arg::new("invariants")
                .takes_value(false)
                .long("invariants")
                .help("Display operators invariants"),
        )
}

/// Handles the command-line input.
fn handle(matches: clap::ArgMatches, probe: Option<&Probe>) -> TractResult<()> {
    match matches.subcommand() {
        Some(("list-ops", _)) => {
            #[cfg(feature = "onnx")]
            {
                let onnx = tract_onnx::onnx();
                let names = onnx.op_register.0.keys().sorted().join(", ");
                println!("Onnx:\n");
                println!("{names}");
                println!("\n");
            }
            #[cfg(feature = "tf")]
            {
                let tf = tract_tensorflow::tensorflow();
                let names = tf.op_register.0.keys().sorted().join(", ");
                println!("Tensorflow:\n");
                println!("{names}");
                println!("\n");
            }
            return Ok(());
        }
        Some(("hwbench", _)) => return hwbench::handle(),
        Some(("kernels", _)) => {
            println!();
            fn colored_name(m: &dyn MatMatMul) -> String {
                format!(
                    "{} {}",
                    QUALITY_COLORS[m.quality().cost()].paint(m.name()),
                    match m.dynamic_boost().signum() {
                        1 => Green.paint(""),
                        -1 => Red.paint(""),
                        _ => "-".to_string().into(),
                    }
                )
            }
            println!("{}", White.bold().paint("# By implementation"));
            println!();
            for m in tract_linalg::ops().mmm_impls() {
                println!("{} -> {:?}", colored_name(&**m), m.stores());
                for packings in m.packings() {
                    println!("   - {:?}{:?}", packings.0, packings.1);
                }
            }
            println!();
            println!("{}", White.bold().paint("# By weights"));
            println!();
            for w in [
                WeightType::Plain(f16::datum_type()),
                WeightType::Plain(f32::datum_type()),
                WeightType::Plain(f64::datum_type()),
                WeightType::Plain(i8::datum_type()),
                WeightType::from(Q4_0),
            ] {
                println!("{}", White.bold().paint(format!("{w:?}")));
                for packing in tract_linalg::ops()
                    .all_possible_packing(w)
                    .sorted_by_key(|f| format!("{f:?}"))
                    .dedup()
                {
                    println!("  * {packing:?}");
                    for mmm in tract_linalg::ops().mmm_impls() {
                        for (ix, p) in mmm.packings().iter().enumerate() {
                            if p.0.same_as(packing) {
                                println!(
                                    "    - {} ({ix}) {:?} {:?}",
                                    colored_name(&**mmm),
                                    p.0,
                                    p.1
                                );
                            } else if let Some(pe) = tract_linalg::ops()
                                .panel_extractors()
                                .iter()
                                .find(|pe| pe.from.same_as(packing) && p.0.same_as(&pe.to))
                            {
                                println!(
                                    "    - {} ({ix}) {:?} {:?} using {}",
                                    colored_name(&**mmm),
                                    p.0,
                                    p.1,
                                    pe.name
                                );
                            }
                        }
                    }
                }
            }
            return Ok(());
        }
        Some(("dump", m)) => {
            if m.is_present("metal-gpu-trace") {
                // Set env variable before loading metal lib
                unsafe {
                    std::env::set_var("METAL_CAPTURE_ENABLED", "1");
                    std::env::set_var("METAL_DEVICE_WRAPPER_TYPE", "1");
                }
            }
        }
        _ => (),
    }

    let builder_result = Parameters::from_clap(&matches, probe);
    #[allow(unused_mut)]
    let mut params = match builder_result {
        Ok(params) => params,
        Err(e) => {
            if let Some(params::ModelBuildingError(broken_model, _)) = e.downcast_ref() {
                let mut broken_model: Box<dyn Model> =
                    tract_hir::tract_core::dyn_clone::clone(broken_model);
                let annotations = Annotations::from_model(broken_model.as_ref())?;
                let display_params = if let Some(("dump", sm)) = matches.subcommand() {
                    display_params_from_clap(&matches, sm)?
                } else {
                    DisplayParams::default()
                };

                if broken_model.output_outlets().len() == 0 {
                    broken_model.auto_outputs()?;
                }
                tract_libcli::terminal::render(
                    broken_model.as_ref(),
                    &annotations,
                    &display_params,
                )?;
            }
            Err(e)?
        }
    };

    let mut need_optimisations = false;

    #[cfg(feature = "multithread-mm")]
    if let Some(threads) = matches.value_of("threads") {
        let threads: usize = threads.parse()?;
        let threads = if threads == 0 { num_cpus::get_physical() } else { threads };
        multithread::set_default_executor(multithread::Executor::multithread(threads));
    }
    #[cfg(not(feature = "multithread-mm"))]
    if matches.value_of("threads").is_some() {
        bail!("tract is compiled without multithread support")
    }

    match matches.subcommand() {
        Some(("bench", m)) => {
            need_optimisations = true;
            bench::handle(&params, &matches, m, &params::bench_limits_from_clap(m)?, probe)
        }

        Some(("criterion", m)) => {
            need_optimisations = true;
            bench::criterion(&params, &matches, m)
        }

        Some(("compare", m)) => {
            compare::handle(&mut params, &matches, m, display_params_from_clap(&matches, m)?)
        }

        Some(("run", m)) => run::handle(&params, &matches, m),

        #[cfg(feature = "pulse")]
        Some(("stream-check", m)) => {
            stream_check::handle(&params, &display_params_from_clap(&matches, m)?)
        }

        None => dump::handle(
            &params,
            &DisplayParams::default(),
            &matches,
            &dump_subcommand().get_matches_from::<_, &'static str>([]),
            &BenchLimits::default(),
            vec![],
        ),

        Some(("dump", m)) => {
            need_optimisations = m.is_present("profile");
            let inner = m
                .values_of("inner")
                .map(|ss| ss.map(|s| s.to_string()).collect())
                .unwrap_or_default();
            dump::handle(
                &params,
                &display_params_from_clap(&matches, m)?,
                &matches,
                m,
                &params::bench_limits_from_clap(m)?,
                inner,
            )
        }

        Some(("llm-bench", m)) => {
            need_optimisations = true;
            llm::handle(&params, &matches, m, &params::bench_limits_from_clap(m)?, probe)
        }

        Some((s, _)) => bail!("Unknown subcommand {}.", s),
    }?;

    if need_optimisations {
        let style = nu_ansi_term::Style::new().fg(nu_ansi_term::Color::Red).bold();
        if !matches.is_present("optimize") {
            warn!("{}", style.paint("Profiling an un-optimized network. Consider adding -O."));
        }
        if cfg!(debug_assertions) {
            warn!("{}", style.paint("Profiling a debug build of tract!"));
        }
    }
    Ok(())
}

fn nnef(matches: &clap::ArgMatches) -> tract_nnef::internal::Nnef {
    let mut fw = tract_nnef::nnef();
    if matches.is_present("nnef-tract-onnx") {
        #[cfg(feature = "onnx")]
        {
            use tract_onnx::WithOnnx;
            fw = fw.with_onnx();
        }
        #[cfg(not(feature = "onnx"))]
        {
            panic!("tract is build without ONNX support")
        }
    }
    if matches.is_present("nnef-tract-pulse") {
        #[cfg(feature = "pulse-opl")]
        {
            use tract_pulse::WithPulse;
            fw = fw.with_pulse();
        }
        #[cfg(not(feature = "pulse-opl"))]
        {
            panic!("tract is build without pulse-opl support")
        }
    }
    if matches.is_present("nnef-tract-extra") {
        #[cfg(feature = "extra")]
        {
            use tract_extra::WithTractExtra;
            fw = fw.with_tract_extra();
        }
        #[cfg(not(feature = "extra"))]
        {
            panic!("tract is build without tract-extra support")
        }
    }
    if matches.is_present("nnef-tract-transformers") {
        #[cfg(feature = "transformers")]
        {
            use tract_transformers::WithTractTransformers;
            fw = fw.with_tract_transformers();
        }
        #[cfg(not(feature = "transformers"))]
        {
            panic!("tract is build without tract-transformers support")
        }
    }
    if matches.is_present("nnef-tract-core") {
        fw = fw.with_tract_core();
    }
    if matches.is_present("nnef-tract-resource") {
        use tract_nnef_resources::internal::JsonLoader;
        fw = fw.with_tract_resource().with_resource_loader(JsonLoader);
    }
    if matches.is_present("nnef-extended-identifier") {
        fw.allow_extended_identifier_syntax(true);
    }
    fw
}