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
//! 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;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use oxibonsai_runtime::OxiBonsaiConfig;
#[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.
#[arg(short, long)]
model: 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>,
},
/// Interactive multi-turn conversation.
Chat {
/// Path to the GGUF model file.
#[arg(short, long)]
model: 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.
#[arg(short, long)]
model: 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>,
},
/// Display model info from a GGUF file.
Info {
/// Path to the GGUF model file.
#[arg(short, long)]
model: 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")
}
/// Resolve the tokenizer path: use the explicit path if given, otherwise
/// auto-detect `tokenizer.json` in the same directory as the model file.
/// Returns `None` when neither source exists.
fn resolve_tokenizer(tokenizer: Option<&str>, model_path: &str) -> Option<String> {
if let Some(p) = tokenizer {
return Some(p.to_string());
}
// Auto-detect: look for tokenizer.json next to the model file
let model = Path::new(model_path);
let candidate = model
.parent()
.unwrap_or_else(|| Path::new("."))
.join("tokenizer.json");
if candidate.exists() {
tracing::info!(
path = %candidate.display(),
"auto-detected tokenizer alongside model"
);
Some(candidate.to_string_lossy().into_owned())
} else {
None
}
}
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 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 resolved_tok = resolve_tokenizer(tokenizer.as_deref(), &model);
let (prompt_tokens, tok_bridge) = if let Some(tok_path) = &resolved_tok {
let tok = oxibonsai_runtime::TokenizerBridge::from_file(tok_path)?;
let tokens = tok.encode(&prompt_text)?;
(tokens, Some(tok))
} else {
tracing::warn!("no tokenizer specified or found — using dummy token; pass --tokenizer <path>");
(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
for &token_id in &tokens {
if let Some(tok) = &tok_bridge {
let text = tok.decode(&[token_id]).unwrap_or_default();
print!("{text}");
} else {
print!(" {token_id}");
}
let _ = io::stdout().flush();
}
(p_len, tokens.len())
}
#[cfg(not(all(feature = "metal", target_os = "macos")))]
unreachable!()
} 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)?;
for &token_id in &tokens {
if let Some(tok) = &tok_bridge {
let text = tok.decode(&[token_id]).unwrap_or_default();
print!("{text}");
} else {
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 count = 0usize;
for token_id in rx {
count += 1;
if let Some(tok) = &tok_bridge {
let text = tok.decode(&[token_id]).unwrap_or_default();
print!("{text}");
} else {
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::Chat {
model,
max_tokens,
temperature,
top_k,
top_p,
seed,
max_seq_len,
tokenizer,
} => {
// 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 = if let Some(tok_path) = resolve_tokenizer(tokenizer.as_deref(), &model) {
Some(oxibonsai_runtime::TokenizerBridge::from_file(&tok_path)?)
} else {
tracing::warn!("no tokenizer specified or found — token IDs will be printed; pass --tokenizer <path>");
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);
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;
if let Some(tok) = &tok {
let text = tok.decode(&[token_id]).unwrap_or_default();
print!("{text}");
} else {
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,
} => {
tracing::info!(model = %model, host = %host, port, "starting server");
let mmap =
oxibonsai_core::gguf::reader::mmap_gguf_file(std::path::Path::new(&model))?;
// Leak the mmap to get 'static lifetime for the server
let mmap: &'static memmap2::Mmap = Box::leak(Box::new(mmap));
let gguf = oxibonsai_core::gguf::reader::GgufFile::parse(mmap)?;
let gguf: &'static oxibonsai_core::gguf::reader::GgufFile<'static> =
Box::leak(Box::new(gguf));
let params = oxibonsai_runtime::sampling::SamplingParams::default();
let metrics = Arc::new(oxibonsai_runtime::InferenceMetrics::new());
let mut engine =
oxibonsai_runtime::InferenceEngine::from_gguf(gguf, params, 42, max_seq_len)?;
engine.set_metrics(Arc::clone(&metrics));
let tok = resolve_tokenizer(tokenizer.as_deref(), &model)
.map(|p| oxibonsai_runtime::TokenizerBridge::from_file(&p))
.transpose()?;
let router =
oxibonsai_runtime::server::create_router_with_metrics(engine, 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 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, ¶ms);
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(())
}
}
/// Native (non-WASM) entry point.
#[cfg(not(target_arch = "wasm32"))]
fn main() -> anyhow::Result<()> {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.map_err(|e| anyhow::anyhow!("failed to build tokio runtime: {e}"))?
.block_on(cli::run())
}