oxibonsai-cli 0.2.2

Pure Rust 1-bit LLM inference engine for PrismML Bonsai models — CLI
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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
//! OxiBonsai — 1-bit LLM inference engine for Bonsai-8B.
//!
//! This binary is not functional on WASM targets; the WASM entry points
//! are exposed via [`oxibonsai_runtime`] library APIs instead.

/// WASM stub: this binary is a no-op on wasm32 targets.
/// Consumers should use the `oxibonsai_runtime` library crate APIs directly.
#[cfg(target_arch = "wasm32")]
fn main() {}

#[cfg(not(target_arch = "wasm32"))]
mod cli {
    use clap::{Parser, Subcommand};
    use std::io::{self, BufRead, Write};
    use std::path::{Path, PathBuf};
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;

    use oxibonsai_runtime::OxiBonsaiConfig;

    mod repl;
    mod term;

    #[derive(Parser)]
    #[command(
        name = "oxibonsai",
        version,
        about = "1-bit LLM inference engine for Bonsai-8B"
    )]
    pub struct Cli {
        /// Path to an OxiBonsai TOML configuration file.
        #[arg(long, global = true)]
        config: Option<String>,

        #[command(subcommand)]
        pub command: Commands,
    }

    #[derive(Subcommand)]
    pub enum Commands {
        /// Run inference on a GGUF model.
        Run {
            /// Path to the GGUF model file (default: env OXI_MODEL).
            #[arg(short, long)]
            model: Option<String>,

            /// Prompt text. Use "-" for stdin.
            #[arg(short, long)]
            prompt: String,

            /// Maximum number of tokens to generate.
            #[arg(long, default_value_t = 256)]
            max_tokens: usize,

            /// Sampling temperature (0.0 = greedy).
            #[arg(long, default_value_t = 0.7)]
            temperature: f32,

            /// Top-k sampling (0 = disabled).
            #[arg(long, default_value_t = 40)]
            top_k: usize,

            /// Top-p (nucleus) sampling.
            #[arg(long, default_value_t = 0.9)]
            top_p: f32,

            /// Random seed.
            #[arg(long, default_value_t = 42)]
            seed: u64,

            /// Maximum sequence length (prompt + generated).
            #[arg(long, default_value_t = 4096)]
            max_seq_len: usize,

            /// Path to tokenizer.json file.
            #[arg(long)]
            tokenizer: Option<String>,
        },

        /// Generate an image from a text prompt (Bonsai-Image: TE → DiT → VAE → PNG).
        Image {
            /// Text prompt. Use "-" for stdin.
            #[arg(short, long)]
            prompt: String,

            /// Output PNG path.
            #[arg(short, long)]
            out: String,

            /// RNG seed for the initial noise.
            #[arg(long, default_value_t = 42)]
            seed: u64,

            /// Number of Euler sampler steps.
            #[arg(long, default_value_t = 4)]
            steps: usize,

            /// Image width in pixels.
            #[arg(long, default_value_t = 512)]
            width: usize,

            /// Image height in pixels.
            #[arg(long, default_value_t = 512)]
            height: usize,

            /// Guidance scale.
            #[arg(long, default_value_t = 1.0)]
            guidance: f32,

            /// DiT GGUF path (default: env OXI_DIT_GGUF or /tmp/parity.gguf).
            #[arg(long)]
            dit: Option<String>,

            /// VAE weights dir (default: env OXI_VAE_WEIGHTS or /tmp/bonsai_golden/vae/weights).
            #[arg(long)]
            vae: Option<String>,

            /// Text-encoder weights: a 4-bit model.safetensors file or an f32 .npy dir
            /// (default: env OXI_TE_4BIT, else env OXI_TE_WEIGHTS, else /tmp/bonsai_golden/te/weights).
            #[arg(long)]
            te: Option<String>,

            /// Tokenizer dir containing tokenizer.json
            /// (default: env OXI_TE_TOKENIZER_DIR, else the TE dir).
            #[arg(long)]
            tokenizer: Option<String>,
        },

        /// Interactive image REPL: load the pipeline once, render many prompts.
        ///
        /// Keeps the DiT, VAE, and (resident) text encoder in memory so each
        /// prompt skips the load/dequant cost. On Ghostty the image is shown
        /// inline; elsewhere it is written to a file. Model paths resolve the
        /// same way as `image` (flag → env → default).
        Repl {
            /// Initial RNG seed (changeable at runtime with :seed).
            #[arg(long, default_value_t = 42)]
            seed: u64,

            /// Initial sampler steps (changeable with :steps / :fast / :hq).
            #[arg(long, default_value_t = 4)]
            steps: usize,

            /// Initial image width in pixels.
            #[arg(long, default_value_t = 512)]
            width: usize,

            /// Initial image height in pixels.
            #[arg(long, default_value_t = 512)]
            height: usize,

            /// Guidance scale.
            #[arg(long, default_value_t = 1.0)]
            guidance: f32,

            /// Run the text-encoder GEMM on the CPU instead of the Metal GPU.
            #[arg(long)]
            cpu_te: bool,

            /// DiT GGUF path (default: env OXI_DIT_GGUF or /tmp/parity.gguf).
            #[arg(long)]
            dit: Option<String>,

            /// VAE weights path (default: env OXI_VAE_WEIGHTS).
            #[arg(long)]
            vae: Option<String>,

            /// Text-encoder weights: a 4-bit model.safetensors file or an f32
            /// .npy dir (default: env OXI_TE_4BIT, else OXI_TE_WEIGHTS).
            #[arg(long)]
            te: Option<String>,

            /// Tokenizer dir containing tokenizer.json
            /// (default: env OXI_TE_TOKENIZER_DIR, else the TE dir).
            #[arg(long)]
            tokenizer: Option<String>,
        },

        /// Interactive multi-turn conversation.
        Chat {
            /// Path to the GGUF model file (default: env OXI_MODEL).
            #[arg(short, long)]
            model: Option<String>,

            /// Maximum number of tokens to generate per turn.
            #[arg(long, default_value_t = 512)]
            max_tokens: usize,

            /// Sampling temperature (0.0 = greedy).
            #[arg(long, default_value_t = 0.7)]
            temperature: f32,

            /// Top-k sampling (0 = disabled).
            #[arg(long, default_value_t = 40)]
            top_k: usize,

            /// Top-p (nucleus) sampling.
            #[arg(long, default_value_t = 0.9)]
            top_p: f32,

            /// Random seed.
            #[arg(long, default_value_t = 42)]
            seed: u64,

            /// Maximum sequence length.
            #[arg(long, default_value_t = 4096)]
            max_seq_len: usize,

            /// Path to tokenizer.json file.
            #[arg(long)]
            tokenizer: Option<String>,
        },

        /// Start an OpenAI-compatible API server.
        #[cfg(feature = "server")]
        Serve {
            /// Path to the GGUF model file (default: env OXI_MODEL).
            #[arg(short, long)]
            model: Option<String>,

            /// Host to bind to.
            #[arg(long, default_value = "127.0.0.1")]
            host: String,

            /// Port to listen on.
            #[arg(long, default_value_t = 8080)]
            port: u16,

            /// Maximum sequence length.
            #[arg(long, default_value_t = 4096)]
            max_seq_len: usize,

            /// Path to tokenizer.json file.
            #[arg(long)]
            tokenizer: Option<String>,

            /// Number of engine replicas (default: min(4, CPU cores);
            /// auto-clamped to 1 on GPU/Metal). Replicas share one token-embedding
            /// table, so each adds only a KV cache.
            #[arg(long)]
            pool_size: Option<usize>,
        },

        /// Display model info from a GGUF file.
        Info {
            /// Path to the GGUF model file (default: env OXI_MODEL).
            #[arg(short, long)]
            model: Option<String>,

            /// Emit info as JSON instead of human-readable text.
            #[arg(long, default_value_t = false)]
            json: bool,
        },

        /// Run a quick throughput benchmark (no real model weights required).
        Benchmark {
            /// Total tokens to generate during the benchmark pass.
            #[arg(long, default_value_t = 100)]
            tokens: usize,

            /// Number of warmup tokens generated before timing begins.
            #[arg(long, default_value_t = 10)]
            warmup: usize,

            /// Sampling temperature.
            #[arg(long, default_value_t = 0.7)]
            temperature: f32,

            /// Random seed.
            #[arg(long, default_value_t = 42)]
            seed: u64,
        },

        /// Quantize a GGUF model to a lower-precision format (simulation).
        Quantize {
            /// Path to the input GGUF model file.
            #[arg(long)]
            input: String,

            /// Destination path for the quantized file.
            #[arg(long)]
            output: String,

            /// Target quantization format (e.g. q1_0, q4_0, q8_0).
            #[arg(long, default_value = "q1_0")]
            format: String,
        },

        /// Validate that a GGUF file is well-formed and display a metadata summary.
        Validate {
            /// Path to the GGUF model file to validate.
            #[arg(short, long)]
            model: String,
        },

        /// Convert a HuggingFace safetensors model to GGUF format.
        Convert {
            /// Input directory containing model.safetensors (or shards) and config.json.
            #[arg(long)]
            from: String,

            /// Output GGUF file path.
            #[arg(long)]
            to: String,

            /// Quantization format: tq2_0_g128 (default), q1_0_g128.
            #[arg(long, default_value = "tq2_0_g128")]
            quant: String,

            /// Treat --from as an ONNX model file (MatMulNBits, bits=2) and use the ONNX→GGUF converter.
            #[arg(long, default_value_t = false)]
            onnx: bool,
        },

        /// Manage the Qwen3 tokenizer (download / inspect).
        Tokenizer {
            #[command(subcommand)]
            cmd: TokenizerCmd,
        },
    }

    #[derive(Subcommand)]
    pub enum TokenizerCmd {
        /// Download tokenizer.json from HuggingFace and save it next to the model.
        ///
        /// Example:
        ///   oxibonsai tokenizer download --output models/tokenizer.json
        Download {
            /// Destination path (default: models/tokenizer.json in the current directory).
            #[arg(long, default_value = "models/tokenizer.json")]
            output: String,

            /// HuggingFace repo to download from (must contain tokenizer.json).
            #[arg(long, default_value = "Qwen/Qwen3-8B")]
            repo: String,

            /// Overwrite an existing tokenizer.json without prompting.
            #[arg(long, default_value_t = false)]
            force: bool,
        },

        /// Show the vocabulary size and model type stored in tokenizer.json.
        Info {
            /// Path to tokenizer.json.
            #[arg(long, default_value = "models/tokenizer.json")]
            path: String,
        },
    }

    pub fn read_prompt_stdin() -> String {
        let stdin = io::stdin();
        let mut lines = Vec::new();
        for line in stdin.lock().lines() {
            match line {
                Ok(l) => lines.push(l),
                Err(_) => break,
            }
        }
        lines.join("\n")
    }

    /// Result of attempting to locate a `tokenizer.json` for a given model.
    ///
    /// `found` is `Some(path)` when either an explicit override was supplied
    /// or auto-detection succeeded.  `searched` lists every candidate path
    /// inspected during auto-detection so the user can see exactly where we
    /// looked when nothing turned up.
    pub(crate) struct TokenizerLookup {
        pub(crate) found: Option<String>,
        pub(crate) searched: Vec<PathBuf>,
    }

    /// Strip a trailing GGUF quantization suffix (e.g. `-Q2_0`, `-Q4_K_M`,
    /// `-F16`, `-BF16`, `-F32`) from a model basename without pulling in the
    /// `regex` crate.  Returns the basename unchanged when no recognized
    /// suffix is present.
    pub(crate) fn strip_quant_suffix(basename: &str) -> &str {
        // Locate the last '-' segment; only that segment is a quant suffix
        // candidate.
        let Some(dash_pos) = basename.rfind('-') else {
            return basename;
        };
        let suffix = &basename[dash_pos + 1..];
        if suffix.is_empty() {
            return basename;
        }

        let is_float = matches!(suffix, "F16" | "BF16" | "F32");
        let is_quant = {
            let mut chars = suffix.chars();
            match chars.next() {
                Some('Q') => {
                    // Accept Q<digits>(_<alnum>+)*  e.g. Q1_0, Q2_K, Q4_K_M, Q8_0.
                    let rest: String = chars.collect();
                    if rest.is_empty() {
                        false
                    } else {
                        let mut parts = rest.split('_');
                        let first = parts.next().unwrap_or("");
                        if first.is_empty() || !first.chars().all(|c| c.is_ascii_digit()) {
                            false
                        } else {
                            parts.all(|p| {
                                !p.is_empty() && p.chars().all(|c| c.is_ascii_alphanumeric())
                            })
                        }
                    }
                }
                _ => false,
            }
        };

        if is_float || is_quant {
            &basename[..dash_pos]
        } else {
            basename
        }
    }

    /// Build the ordered list of candidate `tokenizer.json` paths to probe
    /// for a given model file.  Duplicates (after canonical lexical form)
    /// are removed so the warning message stays compact.
    pub(crate) fn tokenizer_candidates(model_path: &Path) -> Vec<PathBuf> {
        let parent = model_path
            .parent()
            .filter(|p| !p.as_os_str().is_empty())
            .map(Path::to_path_buf)
            .unwrap_or_else(|| PathBuf::from("."));

        let mut out: Vec<PathBuf> = Vec::new();
        let push_unique = |p: PathBuf, out: &mut Vec<PathBuf>| {
            if !out.iter().any(|existing| existing == &p) {
                out.push(p);
            }
        };

        // 1. Same directory as the model.
        push_unique(parent.join("tokenizer.json"), &mut out);

        // 2. Parent of the model directory.
        push_unique(parent.join("..").join("tokenizer.json"), &mut out);

        // 3. Sibling directories derived from the model basename.
        if let Some(stem) = model_path.file_stem().and_then(|s| s.to_str()) {
            let base = strip_quant_suffix(stem);
            for variant in [
                base.to_string(),
                format!("{base}-unpacked"),
                format!("{base}-ONNX"),
            ] {
                push_unique(parent.join(&variant).join("tokenizer.json"), &mut out);
            }
        }

        // 4. Top-level `models/` directory if the model lives anywhere under it.
        for ancestor in model_path.ancestors().skip(1) {
            if ancestor.file_name().and_then(|n| n.to_str()) == Some("models") {
                push_unique(ancestor.join("tokenizer.json"), &mut out);
                break;
            }
        }

        out
    }

    /// Resolve the tokenizer path: use the explicit path if given, otherwise
    /// auto-detect `tokenizer.json` in a small set of conventional locations
    /// derived from the model path.
    pub(crate) fn resolve_tokenizer(tokenizer: Option<&str>, model_path: &str) -> TokenizerLookup {
        if let Some(p) = tokenizer {
            return TokenizerLookup {
                found: Some(p.to_string()),
                searched: Vec::new(),
            };
        }

        let model = Path::new(model_path);
        let candidates = tokenizer_candidates(model);
        for candidate in &candidates {
            if candidate.exists() {
                tracing::info!(
                    path = %candidate.display(),
                    "auto-detected tokenizer alongside model"
                );
                return TokenizerLookup {
                    found: Some(candidate.to_string_lossy().into_owned()),
                    searched: candidates,
                };
            }
        }

        TokenizerLookup {
            found: None,
            searched: candidates,
        }
    }

    /// Build the multi-line "no tokenizer found" warning shown by the run /
    /// chat / serve paths.  Centralized so all three surfaces stay in sync.
    pub(crate) fn missing_tokenizer_warning(searched: &[PathBuf]) -> String {
        let mut msg = String::from("no tokenizer found. Searched:\n");
        if searched.is_empty() {
            msg.push_str("  (no candidate paths — model path was not provided)\n");
        } else {
            for path in searched {
                msg.push_str(&format!("  - {}\n", path.display()));
            }
        }
        msg.push_str("To fix:\n");
        msg.push_str("  - Pass --tokenizer <path/to/tokenizer.json>, OR\n");
        msg.push_str(
            "  - Run ./scripts/download_tokenizer.sh to fetch the Qwen3 tokenizer to models/tokenizer.json\n",
        );
        msg.push_str("Continuing with raw token IDs in output.");
        msg
    }

    pub async fn run() -> anyhow::Result<()> {
        let cli = Cli::parse();
        let config = OxiBonsaiConfig::load_or_default(cli.config.as_deref().map(Path::new));

        let tracing_config =
            oxibonsai_runtime::TracingConfig::from_observability(&config.observability);
        if let Err(e) = oxibonsai_runtime::init_tracing(&tracing_config) {
            eprintln!("warning: failed to initialize tracing: {e}");
        }

        match cli.command {
            Commands::Run {
                model,
                prompt,
                max_tokens,
                temperature,
                top_k,
                top_p,
                seed,
                max_seq_len,
                tokenizer,
            } => {
                let model = model
                    .or_else(|| std::env::var("OXI_MODEL").ok().filter(|s| !s.is_empty()))
                    .ok_or_else(|| {
                        anyhow::anyhow!(
                            "no model: pass --model <gguf> or set OXI_MODEL (e.g. in .env)"
                        )
                    })?;
                let tokenizer = tokenizer.or_else(|| {
                    std::env::var("OXI_TOKENIZER")
                        .ok()
                        .filter(|s| !s.is_empty())
                });

                let prompt_text = if prompt == "-" {
                    read_prompt_stdin()
                } else {
                    prompt
                };

                tracing::info!(
                    model = %model,
                    max_tokens,
                    temperature,
                    "starting inference"
                );

                // Memory-map the GGUF file
                let mmap =
                    oxibonsai_core::gguf::reader::mmap_gguf_file(std::path::Path::new(&model))?;
                let gguf = oxibonsai_core::gguf::reader::GgufFile::parse(&mmap)?;

                let params = oxibonsai_runtime::sampling::SamplingParams {
                    temperature,
                    top_k,
                    top_p,
                    repetition_penalty: 1.1,
                    ..oxibonsai_runtime::sampling::SamplingParams::default()
                };

                let mut engine = oxibonsai_runtime::InferenceEngine::from_gguf(
                    &gguf,
                    params,
                    seed,
                    max_seq_len,
                )?;

                // Tokenize prompt and retain the bridge for streaming decode
                let lookup = resolve_tokenizer(tokenizer.as_deref(), &model);
                let (prompt_tokens, tok_bridge) = if let Some(tok_path) = &lookup.found {
                    let tok = oxibonsai_runtime::TokenizerBridge::from_file(tok_path)?;
                    let tokens = tok.encode(&prompt_text)?;
                    (tokens, Some(tok))
                } else {
                    tracing::warn!("{}", missing_tokenizer_warning(&lookup.searched));
                    (vec![151644], None) // <|im_start|>
                };

                tracing::info!(prompt_tokens = prompt_tokens.len(), "prefilling");

                let start = std::time::Instant::now();

                // Greedy GPU path: when temperature=0 and Metal is available,
                // run argmax on GPU and download only 4-byte token IDs instead
                // of the full ~607KB logits vector per token.
                #[cfg(all(feature = "metal", target_os = "macos"))]
                let use_greedy_gpu = temperature == 0.0;
                #[cfg(not(all(feature = "metal", target_os = "macos")))]
                let use_greedy_gpu = false;

                let (prompt_len, output_count) = if use_greedy_gpu {
                    #[cfg(all(feature = "metal", target_os = "macos"))]
                    {
                        tracing::info!("using greedy GPU path (argmax on Metal, 4-byte download)");
                        let p_len = prompt_tokens.len();
                        let tokens = engine.generate_greedy_gpu(&prompt_tokens, max_tokens)?;
                        // Print tokens via the streaming decoder so multi-byte
                        // UTF-8 characters that span more than one token (CJK,
                        // emoji, etc.) round-trip correctly instead of
                        // surfacing as U+FFFD replacement chars.
                        let mut stream_state =
                            tok_bridge.as_ref().map(|t| t.new_decode_stream(true));
                        for &token_id in &tokens {
                            match (&tok_bridge, stream_state.as_mut()) {
                                (Some(tok), Some(state)) => {
                                    if let Some(text) = tok.step_decode(state, token_id)? {
                                        print!("{text}");
                                    }
                                }
                                _ => {
                                    print!(" {token_id}");
                                }
                            }
                            let _ = io::stdout().flush();
                        }
                        (p_len, tokens.len())
                    }
                    #[cfg(not(all(feature = "metal", target_os = "macos")))]
                    unreachable!("use_greedy_gpu was set true outside the Metal+macOS feature path; check cfg-gate consistency in the use_greedy_gpu computation above")
                } else {
                    // CUDA direct path (Linux / Windows): call engine.generate() directly on the
                    // main thread, bypassing std::thread::scope and its ~107ms OS scheduling
                    // overhead.  Tokens are printed synchronously after the full generation
                    // completes, which is fine for non-interactive benchmarking.
                    #[cfg(all(
                        feature = "native-cuda",
                        not(all(feature = "metal", target_os = "macos")),
                        any(target_os = "linux", target_os = "windows")
                    ))]
                    {
                        let p_len = prompt_tokens.len();
                        let tokens = engine.generate(&prompt_tokens, max_tokens)?;
                        let mut stream_state =
                            tok_bridge.as_ref().map(|t| t.new_decode_stream(true));
                        for &token_id in &tokens {
                            match (&tok_bridge, stream_state.as_mut()) {
                                (Some(tok), Some(state)) => {
                                    if let Some(text) = tok.step_decode(state, token_id)? {
                                        print!("{text}");
                                    }
                                }
                                _ => {
                                    print!(" {token_id}");
                                }
                            }
                            let _ = io::stdout().flush();
                        }
                        (p_len, tokens.len())
                    }

                    // All other platforms (no CUDA): streaming path via a worker thread so that
                    // the main thread can decode and print tokens as they arrive.
                    #[cfg(not(all(
                        feature = "native-cuda",
                        not(all(feature = "metal", target_os = "macos")),
                        any(target_os = "linux", target_os = "windows")
                    )))]
                    {
                        let (tx, rx) = std::sync::mpsc::channel::<u32>();

                        let p_len = prompt_tokens.len();
                        let count = std::thread::scope(|s| -> anyhow::Result<usize> {
                            let thread_tx = tx.clone();
                            let gen_handle = s.spawn(move || {
                                engine.generate_streaming_sync(
                                    &prompt_tokens,
                                    max_tokens,
                                    &thread_tx,
                                )
                            });
                            drop(tx);

                            let mut stream_state =
                                tok_bridge.as_ref().map(|t| t.new_decode_stream(true));
                            let mut count = 0usize;
                            for token_id in rx {
                                count += 1;
                                match (&tok_bridge, stream_state.as_mut()) {
                                    (Some(tok), Some(state)) => {
                                        if let Some(text) = tok.step_decode(state, token_id)? {
                                            print!("{text}");
                                        }
                                    }
                                    _ => {
                                        if count == 1 {
                                            print!("Tokens:");
                                        }
                                        print!(" {token_id}");
                                    }
                                }
                                let _ = io::stdout().flush();
                            }

                            match gen_handle.join() {
                                Ok(Ok(_)) => {}
                                Ok(Err(e)) => return Err(e.into()),
                                Err(_) => {
                                    return Err(anyhow::anyhow!("generation thread panicked"))
                                }
                            }
                            Ok(count)
                        })?;
                        (p_len, count)
                    }
                };

                let elapsed = start.elapsed();

                let total_tokens = prompt_len + output_count;
                let tok_per_sec = if elapsed.as_secs_f64() > 0.0 {
                    output_count as f64 / elapsed.as_secs_f64()
                } else {
                    0.0
                };

                eprintln!();
                eprintln!(
                    "---\n{} prompt + {} generated = {} total tokens in {:.2}s ({:.1} tok/s)",
                    prompt_len,
                    output_count,
                    total_tokens,
                    elapsed.as_secs_f64(),
                    tok_per_sec
                );

                // Print GPU profiling summary if OXIBONSAI_PROFILE_GPU=1 was set
                #[cfg(all(feature = "metal", target_os = "macos"))]
                {
                    let model_size = std::fs::metadata(&model).map(|m| m.len()).unwrap_or(0);
                    oxibonsai_kernels::print_gpu_profile_summary(model_size);
                }
            }

            Commands::Image {
                prompt,
                out,
                seed,
                steps,
                width,
                height,
                guidance,
                dit,
                vae,
                te,
                tokenizer,
            } => {
                use oxibonsai_image::pipeline::{text_to_image, TeSource, TextToImageCfg};

                let prompt_text = if prompt == "-" {
                    read_prompt_stdin()
                } else {
                    prompt
                };

                // Resolve paths: explicit arg → env → default.
                let resolve = |arg: Option<String>, env: &str, default: &str| -> String {
                    arg.or_else(|| std::env::var(env).ok().filter(|s| !s.is_empty()))
                        .unwrap_or_else(|| default.to_string())
                };

                let dit_path = resolve(dit, "OXI_DIT_GGUF", "/tmp/parity.gguf");
                let vae_path = resolve(vae, "OXI_VAE_WEIGHTS", "/tmp/bonsai_golden/vae/weights");

                // TE source: a `.safetensors` path → 4-bit MLX loader; otherwise a
                // directory of f32 `.npy` dumps. Resolution order: --te → OXI_TE_4BIT
                // → OXI_TE_WEIGHTS → default npy dir.
                let te_path = te
                    .or_else(|| std::env::var("OXI_TE_4BIT").ok().filter(|s| !s.is_empty()))
                    .or_else(|| {
                        std::env::var("OXI_TE_WEIGHTS")
                            .ok()
                            .filter(|s| !s.is_empty())
                    })
                    .unwrap_or_else(|| "/tmp/bonsai_golden/te/weights".to_string());
                let te_source = if te_path.ends_with(".safetensors") {
                    TeSource::Mlx4bit(PathBuf::from(&te_path))
                } else {
                    TeSource::NpyDir(PathBuf::from(&te_path))
                };

                // Tokenizer dir: --tokenizer → OXI_TE_TOKENIZER_DIR → the TE dir
                // (its parent if the TE is a safetensors file).
                let tokenizer_dir = tokenizer
                    .or_else(|| {
                        std::env::var("OXI_TE_TOKENIZER_DIR")
                            .ok()
                            .filter(|s| !s.is_empty())
                    })
                    .map(PathBuf::from)
                    .unwrap_or_else(|| {
                        let p = PathBuf::from(&te_path);
                        if te_path.ends_with(".safetensors") {
                            p.parent().map(Path::to_path_buf).unwrap_or(p)
                        } else {
                            p
                        }
                    });

                let cfg = TextToImageCfg {
                    prompt: prompt_text,
                    seed,
                    steps,
                    width,
                    height,
                    guidance,
                    dit_gguf: PathBuf::from(&dit_path),
                    vae_weights_dir: PathBuf::from(&vae_path),
                    te_source,
                    tokenizer_dir,
                    golden_override: None,
                };

                tracing::info!(
                    seed,
                    steps,
                    width,
                    height,
                    dit = %dit_path,
                    "starting text-to-image generation"
                );

                let start = std::time::Instant::now();
                let result = text_to_image(&cfg)
                    .map_err(|e| anyhow::anyhow!("text-to-image generation failed: {e}"))?;
                let elapsed = start.elapsed();

                std::fs::write(&out, &result.png)
                    .map_err(|e| anyhow::anyhow!("failed to write {out}: {e}"))?;

                println!(
                    "Wrote {}x{} RGB PNG ({} bytes) to {out}",
                    result.width,
                    result.height,
                    result.png.len()
                );
                println!(
                    "  seed={seed} steps={steps} guidance={guidance} in {:.1}s",
                    elapsed.as_secs_f64()
                );
            }

            Commands::Repl {
                seed,
                steps,
                width,
                height,
                guidance,
                cpu_te,
                dit,
                vae,
                te,
                tokenizer,
            } => {
                use oxibonsai_image::pipeline::TeSource;
                use oxibonsai_image::RenderParams;

                // Same resolution as `image`: explicit arg → env → default.
                let resolve = |arg: Option<String>, env: &str, default: &str| -> String {
                    arg.or_else(|| std::env::var(env).ok().filter(|s| !s.is_empty()))
                        .unwrap_or_else(|| default.to_string())
                };

                let dit_path = resolve(dit, "OXI_DIT_GGUF", "/tmp/parity.gguf");
                let vae_path = resolve(vae, "OXI_VAE_WEIGHTS", "/tmp/bonsai_golden/vae/weights");

                let te_path = te
                    .or_else(|| std::env::var("OXI_TE_4BIT").ok().filter(|s| !s.is_empty()))
                    .or_else(|| {
                        std::env::var("OXI_TE_WEIGHTS")
                            .ok()
                            .filter(|s| !s.is_empty())
                    })
                    .unwrap_or_else(|| "/tmp/bonsai_golden/te/weights".to_string());
                let te_source = if te_path.ends_with(".safetensors") {
                    TeSource::Mlx4bit(PathBuf::from(&te_path))
                } else {
                    TeSource::NpyDir(PathBuf::from(&te_path))
                };

                let tokenizer_dir = tokenizer
                    .or_else(|| {
                        std::env::var("OXI_TE_TOKENIZER_DIR")
                            .ok()
                            .filter(|s| !s.is_empty())
                    })
                    .map(PathBuf::from)
                    .unwrap_or_else(|| {
                        let p = PathBuf::from(&te_path);
                        if te_path.ends_with(".safetensors") {
                            p.parent().map(Path::to_path_buf).unwrap_or(p)
                        } else {
                            p
                        }
                    });

                let params = RenderParams {
                    prompt: String::new(),
                    seed,
                    steps,
                    width,
                    height,
                    guidance,
                };
                let paths = repl::ReplPaths {
                    dit: dit_path,
                    vae: vae_path,
                    te_source,
                    tokenizer_dir,
                };
                repl::run(paths, params, !cpu_te)?;
            }

            Commands::Chat {
                model,
                max_tokens,
                temperature,
                top_k,
                top_p,
                seed,
                max_seq_len,
                tokenizer,
            } => {
                let model = model
                    .or_else(|| std::env::var("OXI_MODEL").ok().filter(|s| !s.is_empty()))
                    .ok_or_else(|| {
                        anyhow::anyhow!(
                            "no model: pass --model <gguf> or set OXI_MODEL (e.g. in .env)"
                        )
                    })?;
                let tokenizer = tokenizer.or_else(|| {
                    std::env::var("OXI_TOKENIZER")
                        .ok()
                        .filter(|s| !s.is_empty())
                });

                // Memory-map the GGUF file
                let mmap =
                    oxibonsai_core::gguf::reader::mmap_gguf_file(std::path::Path::new(&model))?;
                let gguf = oxibonsai_core::gguf::reader::GgufFile::parse(&mmap)?;

                let params = oxibonsai_runtime::sampling::SamplingParams {
                    temperature,
                    top_k,
                    top_p,
                    repetition_penalty: 1.1,
                    ..oxibonsai_runtime::sampling::SamplingParams::default()
                };

                let mut engine = oxibonsai_runtime::InferenceEngine::from_gguf(
                    &gguf,
                    params,
                    seed,
                    max_seq_len,
                )?;

                let tok = {
                    let lookup = resolve_tokenizer(tokenizer.as_deref(), &model);
                    if let Some(tok_path) = lookup.found {
                        Some(oxibonsai_runtime::TokenizerBridge::from_file(&tok_path)?)
                    } else {
                        tracing::warn!("{}", missing_tokenizer_warning(&lookup.searched));
                        None
                    }
                };

                println!("OxiBonsai Interactive Chat (type 'quit' or Ctrl-D to exit)");
                println!(
                    "Tip: press Ctrl-C during generation to interrupt output without exiting."
                );
                println!("---");

                // Shared cancellation flag.  The ctrlc handler sets this to true;
                // the generation receive loop checks it and drops the receiver,
                // which causes tx.send() in generate_streaming_sync to fail and
                // stop the generation thread naturally.
                let interrupted = Arc::new(AtomicBool::new(false));
                {
                    let flag = Arc::clone(&interrupted);
                    ctrlc::set_handler(move || {
                        flag.store(true, Ordering::SeqCst);
                    })
                    .map_err(|e| anyhow::anyhow!("failed to install Ctrl-C handler: {e}"))?;
                }

                let stdin = io::stdin();
                loop {
                    print!("> ");
                    io::stdout().flush()?;

                    let mut input = String::new();
                    match stdin.lock().read_line(&mut input) {
                        Ok(0) => {
                            // EOF (Ctrl-D)
                            println!();
                            break;
                        }
                        Ok(_) => {}
                        Err(e) if e.kind() == io::ErrorKind::Interrupted => {
                            // Ctrl-C while waiting for input (not during generation).
                            interrupted.store(false, Ordering::SeqCst);
                            println!();
                            eprintln!("[Ctrl-C: type 'quit' or press Ctrl-D to exit]");
                            continue;
                        }
                        Err(e) => return Err(e.into()),
                    }
                    let input = input.trim();
                    if input.is_empty() {
                        // Reset stale interrupt flag that fired just before the prompt
                        interrupted.store(false, Ordering::SeqCst);
                        continue;
                    }
                    if input == "quit" || input == "exit" {
                        break;
                    }
                    if input == "/reset" {
                        engine.reset();
                        println!("[context cleared]");
                        continue;
                    }

                    let prompt_tokens = if let Some(tok) = &tok {
                        tok.encode(input)?
                    } else {
                        vec![151644]
                    };

                    // Clear any stale interrupt before starting generation
                    interrupted.store(false, Ordering::SeqCst);

                    let start = std::time::Instant::now();
                    let (tx, rx) = std::sync::mpsc::channel::<u32>();

                    // Use std::thread::scope so engine's borrow stays valid.
                    // The receive loop breaks (dropping rx) when the interrupted flag
                    // is set; generate_streaming_sync detects tx.send() failure and
                    // returns cleanly, so gen_handle.join() never blocks indefinitely.
                    let interrupted_ref = Arc::clone(&interrupted);
                    // Fresh decode-stream state per chat turn: each `> ` cycle is an
                    // independent generation request, so multi-byte UTF-8 buffering
                    // must NOT carry across turns.
                    let mut stream_state = tok.as_ref().map(|t| t.new_decode_stream(true));
                    let output_count = std::thread::scope(|s| -> anyhow::Result<usize> {
                        let thread_tx = tx.clone();
                        let engine_ref = &mut engine;
                        let tokens_ref = &prompt_tokens;
                        let gen_handle = s.spawn(move || {
                            engine_ref.generate_streaming_sync(tokens_ref, max_tokens, &thread_tx)
                        });
                        drop(tx);

                        let mut count = 0usize;
                        for token_id in rx {
                            // Check cancellation before printing each token.
                            // Breaking here drops the Receiver, which makes the
                            // next tx.send() in the generation thread return Err,
                            // stopping generation after at most one more forward pass.
                            if interrupted_ref.load(Ordering::SeqCst) {
                                break;
                            }
                            count += 1;
                            match (&tok, stream_state.as_mut()) {
                                (Some(tok), Some(state)) => {
                                    if let Some(text) = tok.step_decode(state, token_id)? {
                                        print!("{text}");
                                    }
                                }
                                _ => {
                                    if count == 1 {
                                        print!("Tokens:");
                                    }
                                    print!(" {token_id}");
                                }
                            }
                            let _ = io::stdout().flush();
                        }
                        // rx is dropped here; gen_handle will stop within one token step

                        match gen_handle.join() {
                            Ok(Ok(_)) => {}
                            Ok(Err(e)) => return Err(e.into()),
                            Err(_) => return Err(anyhow::anyhow!("generation thread panicked")),
                        }
                        Ok(count)
                    })?;

                    let elapsed = start.elapsed();
                    println!(); // newline after streamed output

                    if interrupted.swap(false, Ordering::SeqCst) {
                        eprintln!("[interrupted after {} tokens]", output_count);
                    } else {
                        let tok_per_sec = if elapsed.as_secs_f64() > 0.0 {
                            output_count as f64 / elapsed.as_secs_f64()
                        } else {
                            0.0
                        };
                        eprintln!(
                            "[{} tokens in {:.2}s, {:.1} tok/s]",
                            output_count,
                            elapsed.as_secs_f64(),
                            tok_per_sec
                        );
                    }
                }
            }

            #[cfg(feature = "server")]
            Commands::Serve {
                model,
                host,
                port,
                max_seq_len,
                tokenizer,
                pool_size,
            } => {
                let model = model
                    .or_else(|| std::env::var("OXI_MODEL").ok().filter(|s| !s.is_empty()))
                    .ok_or_else(|| {
                        anyhow::anyhow!(
                            "no model: pass --model <gguf> or set OXI_MODEL (e.g. in .env)"
                        )
                    })?;
                let tokenizer = tokenizer.or_else(|| {
                    std::env::var("OXI_TOKENIZER")
                        .ok()
                        .filter(|s| !s.is_empty())
                });

                // Engine-pool size precedence: --pool-size flag > env
                // OXIBONSAI_ENGINE_POOL_SIZE > unset. When unset we pass `None`
                // so `build_pool_from_gguf`/`resolve_pool_size` apply the CPU
                // default of `min(4, cores)` — replicas now share one `Arc<[f32]>`
                // token-embedding table, so the extra per-replica cost is just a
                // KV cache. GPU/Metal is always clamped back to 1 by the resolver.
                let requested_pool_size: Option<usize> = pool_size.or_else(|| {
                    std::env::var("OXIBONSAI_ENGINE_POOL_SIZE")
                        .ok()
                        .and_then(|s| s.parse::<usize>().ok())
                });

                tracing::info!(model = %model, host = %host, port, "starting server");

                let params = oxibonsai_runtime::sampling::SamplingParams::default();
                let metrics = Arc::new(oxibonsai_runtime::InferenceMetrics::new());

                // Build a pool of engine replicas sharing one leaked `'static`
                // GGUF (replica #1 mmaps + leaks; the rest reuse it zero-copy).
                let (pool, _tier, _size) = oxibonsai_runtime::engine_pool::build_pool_from_gguf(
                    &model,
                    params,
                    42,
                    max_seq_len,
                    requested_pool_size,
                )?;
                // Wire the shared metrics onto every replica, preserving the
                // per-engine telemetry the single-engine path recorded.
                pool.set_metrics_all(&metrics)?;

                let tok = {
                    let lookup = resolve_tokenizer(tokenizer.as_deref(), &model);
                    match lookup.found {
                        Some(p) => Some(oxibonsai_runtime::TokenizerBridge::from_file(&p)?),
                        None => {
                            tracing::warn!("{}", missing_tokenizer_warning(&lookup.searched));
                            None
                        }
                    }
                };

                let router = oxibonsai_runtime::server::create_router_with_pool(pool, tok, metrics);
                let addr = format!("{host}:{port}");
                let listener = tokio::net::TcpListener::bind(&addr).await?;
                tracing::info!("listening on {addr}");
                axum::serve(listener, router).await?;
            }

            Commands::Info { model, json } => {
                let model = model
                    .or_else(|| std::env::var("OXI_MODEL").ok().filter(|s| !s.is_empty()))
                    .ok_or_else(|| {
                        anyhow::anyhow!(
                            "no model: pass --model <gguf> or set OXI_MODEL (e.g. in .env)"
                        )
                    })?;

                let mmap =
                    oxibonsai_core::gguf::reader::mmap_gguf_file(std::path::Path::new(&model))?;
                let gguf = oxibonsai_core::gguf::reader::GgufFile::parse(&mmap)?;
                let config = oxibonsai_core::config::Qwen3Config::from_metadata(&gguf.metadata)?;
                let type_counts = gguf.tensors.count_by_type();

                // Determine dominant quant type from tensor counts for accurate variant detection.
                let dominant_type = type_counts
                    .iter()
                    .max_by_key(|(_, count)| *count)
                    .map(|(ty, _)| *ty)
                    .unwrap_or(oxibonsai_core::GgufTensorType::Q1_0_g128);

                let variant = oxibonsai_model::ModelVariant::from_config_and_sample_tensor_type(
                    &config,
                    dominant_type,
                );

                if json {
                    let tensor_types: std::collections::HashMap<String, usize> = type_counts
                        .iter()
                        .map(|(k, v)| (k.to_string(), *v))
                        .collect();

                    let info = serde_json::json!({
                        "model": model,
                        "gguf_version": gguf.header.version,
                        "tensor_count": gguf.header.tensor_count,
                        "metadata_entries": gguf.header.metadata_kv_count,
                        "architecture": format!("Qwen3 ({})", variant.name()),
                        "variant": variant.name(),
                        "num_layers": config.num_layers,
                        "hidden_size": config.hidden_size,
                        "num_attention_heads": config.num_attention_heads,
                        "num_kv_heads": config.num_kv_heads,
                        "head_dim": config.head_dim,
                        "vocab_size": config.vocab_size,
                        "max_context_length": config.max_context_length,
                        "intermediate_size": config.intermediate_size,
                        "tensor_types": tensor_types,
                    });
                    println!("{}", serde_json::to_string_pretty(&info)?);
                } else {
                    println!("Model: {model}");
                    println!("GGUF version: {}", gguf.header.version);
                    println!("Tensor count: {}", gguf.header.tensor_count);
                    println!("Metadata entries: {}", gguf.header.metadata_kv_count);
                    println!();

                    println!("Architecture: Qwen3 ({})", variant.name());
                    println!("  Layers:       {}", config.num_layers);
                    println!("  Hidden size:  {}", config.hidden_size);
                    println!("  Q heads:      {}", config.num_attention_heads);
                    println!("  KV heads:     {}", config.num_kv_heads);
                    println!("  Head dim:     {}", config.head_dim);
                    println!("  Vocab:        {}", config.vocab_size);
                    println!("  Max context:  {}", config.max_context_length);
                    println!("  Intermediate: {}", config.intermediate_size);
                    println!();

                    println!("Tensor types:");
                    for (tensor_type, count) in &type_counts {
                        println!("  {tensor_type}: {count}");
                    }
                }
            }

            Commands::Benchmark {
                tokens,
                warmup,
                temperature,
                seed,
            } => {
                use oxibonsai_core::config::Qwen3Config;
                use oxibonsai_runtime::model_cache::ModelWarmup;
                use oxibonsai_runtime::sampling::SamplingParams;

                let config = Qwen3Config::tiny_test();
                let params = SamplingParams {
                    temperature,
                    top_k: 40,
                    top_p: 0.9,
                    repetition_penalty: 1.0,
                    ..SamplingParams::default()
                };

                let mut engine =
                    oxibonsai_runtime::InferenceEngine::new(config, params.clone(), seed);

                // ── Warmup pass ──────────────────────────────────────────────
                let warmup_helper = ModelWarmup::new().with_tokens(warmup);
                let warmup_ms = warmup_helper.run(&mut engine, &params);
                eprintln!("Warmup: {warmup} tokens in {warmup_ms} ms");

                // ── Benchmark pass ───────────────────────────────────────────
                let prompt_tokens: Vec<u32> = vec![151644u32]; // <|im_start|>
                let bench_start = std::time::Instant::now();
                let output_tokens = engine.generate(&prompt_tokens, tokens)?;
                let bench_elapsed = bench_start.elapsed();

                let generated = output_tokens.len();
                let tok_per_sec = if bench_elapsed.as_secs_f64() > 0.0 {
                    generated as f64 / bench_elapsed.as_secs_f64()
                } else {
                    0.0
                };

                println!(
                    "Warmup: {warmup} tokens, Benchmark: {tok_per_sec:.1} tokens/sec \
                     ({generated} tokens in {:.2}s)",
                    bench_elapsed.as_secs_f64()
                );
            }

            Commands::Quantize {
                input,
                output,
                format,
            } => {
                use std::path::Path;

                let input_path = Path::new(&input);
                if !input_path.exists() {
                    anyhow::bail!("input file does not exist: {input}");
                }

                // Read the original file size.
                let original_bytes = std::fs::metadata(input_path).map(|m| m.len()).unwrap_or(0);
                let original_mb = original_bytes as f64 / (1024.0 * 1024.0);

                // Validate the format string.
                let known_formats = ["q1_0", "q2_k", "q4_0", "q4_1", "q8_0", "f16", "f32"];
                if !known_formats.contains(&format.as_str()) {
                    eprintln!(
                        "warning: unknown quantization format '{format}'; \
                         known formats: {known_formats:?}"
                    );
                }

                // Compression ratio heuristic per format.
                let compression_ratio: f64 = match format.as_str() {
                    "q1_0" => 32.0,
                    "q2_k" => 16.0,
                    "q4_0" | "q4_1" => 8.0,
                    "q8_0" => 4.0,
                    "f16" => 2.0,
                    _ => 1.0,
                };

                println!("Quantizing {input} -> {output} (format: {format})...");

                // For an actual implementation we would call into oxibonsai_core
                // quantization routines.  For now we simulate by copying the file
                // metadata and estimating the output size.
                let quantized_bytes = (original_bytes as f64 / compression_ratio).ceil() as u64;
                let quantized_mb = quantized_bytes as f64 / (1024.0 * 1024.0);

                println!(
                    "Quantizing... Original: {original_mb:.1} MB \
                     → Quantized: {quantized_mb:.1} MB \
                     ({compression_ratio:.0}:1 compression)"
                );
                println!("Output: {output}");
            }

            Commands::Convert {
                from,
                to,
                quant,
                onnx,
            } => {
                use std::path::Path;
                let from_path = Path::new(&from);
                let to_path = Path::new(&to);
                if !from_path.exists() {
                    anyhow::bail!("input path not found: {from}");
                }
                let format = if onnx { "onnx" } else { "hf" };
                println!("Converting {from} -> {to} (quant: {quant}, format: {format})");
                let stats = if onnx {
                    oxibonsai_model::convert_onnx_to_gguf(from_path, to_path, &quant)?
                } else {
                    oxibonsai_model::convert::convert_hf_to_gguf(from_path, to_path, &quant)?
                };
                println!(
                    "Done: {} tensors ({} ternary + {} fp32), output: {:.1} MB",
                    stats.n_tensors,
                    stats.n_ternary,
                    stats.n_fp32,
                    stats.output_bytes as f64 / (1024.0 * 1024.0),
                );
            }

            Commands::Validate { model } => {
                let mmap =
                    oxibonsai_core::gguf::reader::mmap_gguf_file(std::path::Path::new(&model))?;
                let gguf = oxibonsai_core::gguf::reader::GgufFile::parse(&mmap)?;

                // Attempt to parse model config — validates metadata consistency.
                let config_result =
                    oxibonsai_core::config::Qwen3Config::from_metadata(&gguf.metadata);

                println!("Validating: {model}");
                println!("  GGUF version:     {}", gguf.header.version);
                println!("  Tensor count:     {}", gguf.header.tensor_count);
                println!("  Metadata entries: {}", gguf.header.metadata_kv_count);

                match config_result {
                    Ok(config) => {
                        println!("  Architecture:     Qwen3");
                        println!("  Layers:           {}", config.num_layers);
                        println!("  Hidden size:      {}", config.hidden_size);
                        println!("  Vocab size:       {}", config.vocab_size);
                        println!();
                        println!("Validation: OK");
                    }
                    Err(e) => {
                        println!();
                        println!("Validation: FAILED");
                        println!("  Error: {e}");
                        return Err(anyhow::anyhow!("GGUF validation failed: {e}"));
                    }
                }
            }

            Commands::Tokenizer { cmd: tok_cmd } => match tok_cmd {
                TokenizerCmd::Download {
                    output,
                    repo,
                    force,
                } => {
                    let out_path = std::path::Path::new(&output);
                    if out_path.exists() && !force {
                        println!("tokenizer.json already exists at {output}");
                        println!("Use --force to overwrite.");
                        return Ok(());
                    }
                    if let Some(parent) = out_path.parent() {
                        if !parent.as_os_str().is_empty() {
                            std::fs::create_dir_all(parent).map_err(|e| {
                                anyhow::anyhow!(
                                    "failed to create directory {}: {e}",
                                    parent.display()
                                )
                            })?;
                        }
                    }
                    let url = format!("https://huggingface.co/{repo}/resolve/main/tokenizer.json");
                    println!("Downloading tokenizer.json from {url}");
                    let response = reqwest::blocking::get(&url)
                        .map_err(|e| anyhow::anyhow!("HTTP request failed: {e}"))?;
                    if !response.status().is_success() {
                        anyhow::bail!("server returned {} for {url}", response.status());
                    }
                    let bytes = response
                        .bytes()
                        .map_err(|e| anyhow::anyhow!("failed to read response body: {e}"))?;
                    std::fs::write(out_path, &bytes)
                        .map_err(|e| anyhow::anyhow!("failed to write {output}: {e}"))?;
                    println!("Saved to {output} ({} KB)", bytes.len() / 1024);
                }

                TokenizerCmd::Info { path } => {
                    let data = std::fs::read_to_string(&path)
                        .map_err(|e| anyhow::anyhow!("cannot read {path}: {e}"))?;
                    let v: serde_json::Value = serde_json::from_str(&data)
                        .map_err(|e| anyhow::anyhow!("invalid JSON in {path}: {e}"))?;
                    let model_type = v
                        .get("model")
                        .and_then(|m| m.get("type"))
                        .and_then(|t| t.as_str())
                        .unwrap_or("unknown");
                    let vocab_size = v
                        .get("model")
                        .and_then(|m| m.get("vocab"))
                        .map(|vocab| {
                            if let Some(obj) = vocab.as_object() {
                                obj.len()
                            } else {
                                0
                            }
                        })
                        .unwrap_or(0);
                    let added_tokens = v
                        .get("added_tokens")
                        .and_then(|t| t.as_array())
                        .map(|a| a.len())
                        .unwrap_or(0);
                    println!("Tokenizer: {path}");
                    println!("  Type:         {model_type}");
                    println!("  Vocab size:   {vocab_size}");
                    println!("  Added tokens: {added_tokens}");
                }
            },
        }

        Ok(())
    }

    #[cfg(test)]
    mod tests {
        use super::{
            missing_tokenizer_warning, resolve_tokenizer, strip_quant_suffix, tokenizer_candidates,
        };
        use std::fs;
        use std::path::PathBuf;
        use tempfile::TempDir;

        /// Helper: write an empty `tokenizer.json` at the given path, creating
        /// any missing parent directories.
        fn touch_tokenizer(path: &std::path::Path) {
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent).expect("create_dir_all");
            }
            fs::write(path, b"{}").expect("write tokenizer.json");
        }

        #[test]
        fn resolve_tokenizer_finds_in_same_dir() {
            let tmp = TempDir::new().expect("tempdir");
            let model_dir = tmp.path().join("models");
            fs::create_dir_all(&model_dir).expect("create model_dir");
            let model_path = model_dir.join("Foo-Q2_0.gguf");
            fs::write(&model_path, b"").expect("touch model");
            touch_tokenizer(&model_dir.join("tokenizer.json"));

            let lookup = resolve_tokenizer(None, model_path.to_str().expect("utf8"));
            let found = lookup.found.as_deref().expect("expected to find tokenizer");
            assert_eq!(
                PathBuf::from(found),
                model_dir.join("tokenizer.json"),
                "should locate tokenizer in the same dir as the model"
            );
        }

        #[test]
        fn resolve_tokenizer_finds_in_parent_dir() {
            let tmp = TempDir::new().expect("tempdir");
            let model_dir = tmp.path().join("models").join("variant");
            fs::create_dir_all(&model_dir).expect("create model_dir");
            let model_path = model_dir.join("Foo-Q2_0.gguf");
            fs::write(&model_path, b"").expect("touch model");
            // Place tokenizer in the parent directory only.
            let parent_tokenizer = tmp.path().join("models").join("tokenizer.json");
            touch_tokenizer(&parent_tokenizer);

            let lookup = resolve_tokenizer(None, model_path.to_str().expect("utf8"));
            let found = lookup.found.as_deref().expect("expected to find tokenizer");
            // Either the literal `..` candidate or the canonicalized `models/tokenizer.json`
            // candidate is acceptable; both refer to the same file.
            let found_path = PathBuf::from(found);
            let canon_found = fs::canonicalize(&found_path).expect("canonicalize found");
            let canon_target = fs::canonicalize(&parent_tokenizer).expect("canonicalize target");
            assert_eq!(
                canon_found, canon_target,
                "should locate tokenizer in the model's parent directory"
            );
        }

        #[test]
        fn resolve_tokenizer_finds_via_unpacked_sibling() {
            let tmp = TempDir::new().expect("tempdir");
            let model_dir = tmp.path().join("models");
            fs::create_dir_all(&model_dir).expect("create model_dir");
            let model_path = model_dir.join("Ternary-Bonsai-8B-Q2_0.gguf");
            fs::write(&model_path, b"").expect("touch model");
            // Tokenizer only lives in the sibling unpacked directory.
            let unpacked = model_dir.join("Ternary-Bonsai-8B-unpacked");
            touch_tokenizer(&unpacked.join("tokenizer.json"));

            let lookup = resolve_tokenizer(None, model_path.to_str().expect("utf8"));
            let found = lookup.found.as_deref().expect("expected to find tokenizer");
            assert_eq!(
                PathBuf::from(found),
                unpacked.join("tokenizer.json"),
                "should locate tokenizer via <base>-unpacked sibling directory"
            );
        }

        #[test]
        fn resolve_tokenizer_strips_quant_suffix_for_sibling_lookup() {
            // Verifies the candidate list (without filesystem) for the
            // `Foo-Q2_0.gguf` case includes Foo/, Foo-unpacked/, Foo-ONNX/.
            let model_path = PathBuf::from("models/Foo-Q2_0.gguf");
            let candidates = tokenizer_candidates(&model_path);
            let candidate_strs: Vec<String> = candidates
                .iter()
                .map(|p| p.to_string_lossy().into_owned())
                .collect();

            let expected = [
                "models/Foo/tokenizer.json",
                "models/Foo-unpacked/tokenizer.json",
                "models/Foo-ONNX/tokenizer.json",
            ];
            for needle in expected {
                assert!(
                    candidate_strs.iter().any(|c| c == needle),
                    "missing expected candidate {needle}; got {candidate_strs:?}"
                );
            }
        }

        #[test]
        fn resolve_tokenizer_records_searched_paths_when_missing() {
            let tmp = TempDir::new().expect("tempdir");
            let model_dir = tmp.path().join("models");
            fs::create_dir_all(&model_dir).expect("create model_dir");
            let model_path = model_dir.join("Ternary-Bonsai-8B-Q2_0.gguf");
            fs::write(&model_path, b"").expect("touch model");

            let lookup = resolve_tokenizer(None, model_path.to_str().expect("utf8"));
            assert!(
                lookup.found.is_none(),
                "should not find tokenizer in empty tree"
            );
            assert!(
                !lookup.searched.is_empty(),
                "searched list must be populated when nothing is found"
            );
            // Confirm at least the "same dir" candidate is recorded.
            assert!(
                lookup
                    .searched
                    .iter()
                    .any(|p| p == &model_dir.join("tokenizer.json")),
                "searched list should include the same-directory candidate"
            );
            // Warning text must mention every searched path and both remedies.
            let warning = missing_tokenizer_warning(&lookup.searched);
            for path in &lookup.searched {
                assert!(
                    warning.contains(&path.display().to_string()),
                    "warning should list {}, got: {warning}",
                    path.display()
                );
            }
            assert!(
                warning.contains("--tokenizer"),
                "warning must mention --tokenizer remedy"
            );
            assert!(
                warning.contains("download_tokenizer.sh"),
                "warning must mention download_tokenizer.sh remedy"
            );
        }

        #[test]
        fn resolve_tokenizer_explicit_override_skips_search() {
            let lookup = resolve_tokenizer(Some("/custom/path/tokenizer.json"), "models/foo.gguf");
            assert_eq!(
                lookup.found.as_deref(),
                Some("/custom/path/tokenizer.json"),
                "explicit override must be returned verbatim"
            );
            assert!(
                lookup.searched.is_empty(),
                "explicit override must not trigger a filesystem search"
            );
        }

        #[test]
        fn strip_quant_suffix_handles_known_formats() {
            assert_eq!(
                strip_quant_suffix("Ternary-Bonsai-8B-Q2_0"),
                "Ternary-Bonsai-8B"
            );
            assert_eq!(strip_quant_suffix("Foo-Q1_0"), "Foo");
            assert_eq!(strip_quant_suffix("Foo-Q4_K_M"), "Foo");
            assert_eq!(strip_quant_suffix("Foo-Q8_0"), "Foo");
            assert_eq!(strip_quant_suffix("Foo-F16"), "Foo");
            assert_eq!(strip_quant_suffix("Foo-BF16"), "Foo");
            assert_eq!(strip_quant_suffix("Foo-F32"), "Foo");
            // Non-quant suffix should be left alone.
            assert_eq!(strip_quant_suffix("Foo-bar"), "Foo-bar");
            assert_eq!(strip_quant_suffix("Foo"), "Foo");
        }

        #[test]
        fn tokenizer_candidates_includes_top_level_models_dir() {
            let model_path = PathBuf::from("models/sub/dir/Foo-Q2_0.gguf");
            let candidates = tokenizer_candidates(&model_path);
            let candidate_strs: Vec<String> = candidates
                .iter()
                .map(|p| p.to_string_lossy().into_owned())
                .collect();
            assert!(
                candidate_strs.iter().any(|c| c == "models/tokenizer.json"),
                "expected top-level models/tokenizer.json candidate, got {candidate_strs:?}"
            );
        }
    }
}

/// Native (non-WASM) entry point.
#[cfg(not(target_arch = "wasm32"))]
fn main() -> anyhow::Result<()> {
    // Auto-load `.env` (cwd or any parent dir) as the very first thing, before
    // the tokio runtime, tracing, or any `std::env::var` read. `dotenvy::dotenv`
    // does NOT override already-set real env vars, so precedence stays
    // explicit --flag > shell env > .env file > built-in default. A missing
    // `.env` is a silent no-op via `.ok()`, so behavior is unchanged without one.
    match dotenvy::dotenv() {
        Ok(path) => tracing::debug!(path = %path.display(), "loaded .env"),
        Err(_) => { /* no .env found (or unreadable): silently continue */ }
    }

    tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .map_err(|e| anyhow::anyhow!("failed to build tokio runtime: {e}"))?
        .block_on(cli::run())
}