realizar 0.8.5

Pure Rust ML inference engine built from scratch - model serving for GGUF and safetensors
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
// ============================================================================
// Server Commands (extracted from main.rs for testability)
// WAPR-PERF-004: Gated behind "server" feature since depends on crate::api
// ============================================================================
#[cfg(feature = "server")]
mod server_commands {
    use super::Result;

    /// Result of preparing server state (returned by `prepare_serve_state`)
    pub struct PreparedServer {
        /// The prepared AppState for the server
        pub state: crate::api::AppState,
        /// Whether batch mode is enabled
        pub batch_mode_enabled: bool,
        /// Model type that was loaded
        pub model_type: ModelType,
    }

    impl std::fmt::Debug for PreparedServer {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("PreparedServer")
                .field("batch_mode_enabled", &self.batch_mode_enabled)
                .field("model_type", &self.model_type)
                .finish_non_exhaustive()
        }
    }

    /// Type of model being served
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum ModelType {
        /// GGUF quantized model
        Gguf,
        /// SafeTensors model
        SafeTensors,
        /// APR format model
        Apr,
    }

    impl std::fmt::Display for ModelType {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self {
                ModelType::Gguf => write!(f, "GGUF"),
                ModelType::SafeTensors => write!(f, "SafeTensors"),
                ModelType::Apr => write!(f, "APR"),
            }
        }
    }

    /// Prepare server state by loading a model (GGUF/SafeTensors/APR)
    ///
    /// This function is extracted from `serve_model` for testability.
    /// It handles model loading and AppState creation without starting the server.
    ///
    /// # Arguments
    /// * `model_path` - Path to model file (.gguf, .safetensors, or .apr)
    /// * `batch_mode` - Enable batch processing (requires 'gpu' feature)
    /// * `force_gpu` - Force CUDA backend (requires 'cuda' feature)
    ///
    /// # Returns
    /// A `PreparedServer` containing the AppState and configuration
    /// Load and prepare a GGUF model for serving (CUDA/batch/CPU paths)
    fn prepare_gguf_serve_state(
        model_path: &str,
        batch_mode: bool,
        force_gpu: bool,
    ) -> Result<PreparedServer> {
        use crate::gguf::MappedGGUFModel;

        println!("Parsing GGUF file...");
        let mapped = MappedGGUFModel::from_path(model_path).map_err(|e| {
            crate::error::RealizarError::UnsupportedOperation {
                operation: "load_gguf".to_string(),
                reason: format!("Failed to load GGUF: {e}"),
            }
        })?;

        println!("Successfully loaded GGUF model");
        println!("  Tensors: {}", mapped.model.tensors.len());
        println!("  Metadata: {} entries", mapped.model.metadata.len());
        println!();

        // IMP-100: Use OwnedQuantizedModel with fused Q4_K ops (1.37x faster for single-token)
        println!("Creating quantized model (fused Q4_K ops)...");
        let quantized_model =
            crate::gguf::OwnedQuantizedModel::from_mapped(&mapped).map_err(|e| {
                crate::error::RealizarError::UnsupportedOperation {
                    operation: "create_quantized".to_string(),
                    reason: format!("Failed to create quantized model: {e}"),
                }
            })?;

        println!("Quantized model created successfully!");
        println!("  Vocab size: {}", quantized_model.config.vocab_size);
        println!("  Hidden dim: {}", quantized_model.config.hidden_dim);
        println!("  Layers: {}", quantized_model.layers.len());

        // Extract vocabulary from GGUF for proper token decoding
        let vocab = mapped.model.vocabulary().unwrap_or_else(|| {
            eprintln!("  Warning: No vocabulary in GGUF, using placeholder tokens");
            (0..quantized_model.config.vocab_size)
                .map(|i| format!("token{i}"))
                .collect()
        });
        println!("  Vocab loaded: {} tokens", vocab.len());
        println!();

        // PARITY-113: Enable CUDA backend via --gpu flag or REALIZAR_BACKEND environment variable
        #[cfg(feature = "cuda")]
        let use_cuda = force_gpu
            || std::env::var("REALIZAR_BACKEND")
                .map(|v| v.eq_ignore_ascii_case("cuda"))
                .unwrap_or(false);

        #[cfg(not(feature = "cuda"))]
        let use_cuda = false;

        #[cfg(not(feature = "cuda"))]
        if force_gpu {
            eprintln!("Warning: --gpu flag requires 'cuda' feature. Falling back to CPU.");
            eprintln!("Build with: cargo build --features cuda");
            eprintln!();
        }

        let state = if use_cuda && !batch_mode {
            prepare_gguf_cuda_state(quantized_model, vocab, force_gpu)?
        } else if batch_mode {
            prepare_gguf_batch_state(quantized_model, vocab)?
        } else {
            // CPU mode: Use quantized model for serving (fused CPU ops are faster for m=1)
            crate::api::AppState::with_quantized_model_and_vocab(quantized_model, vocab)?
        };

        Ok(PreparedServer {
            state,
            batch_mode_enabled: batch_mode,
            model_type: ModelType::Gguf,
        })
    }

    /// Create CUDA-backed AppState for GGUF serving (PAR-112-FIX)
    fn prepare_gguf_cuda_state(
        quantized_model: crate::gguf::OwnedQuantizedModel,
        vocab: Vec<String>,
        force_gpu: bool,
    ) -> Result<crate::api::AppState> {
        #[cfg(feature = "cuda")]
        {
            use crate::gguf::OwnedQuantizedModelCuda;

            let source = if force_gpu {
                "--gpu flag"
            } else {
                "REALIZAR_BACKEND=cuda"
            };
            println!("Creating CUDA model ({source})...");

            // GH-286: Configurable context length (was hardcoded 4096)
            let max_seq_len = std::env::var("REALIZR_CONTEXT_LENGTH")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(4096);
            let cuda_model =
                OwnedQuantizedModelCuda::with_max_seq_len(quantized_model, 0, max_seq_len)
                    .map_err(|e| e.error)?;

            println!("  CUDA model created on GPU: {}", cuda_model.device_name());
            println!("  Max sequence length: {} (--context-length)", max_seq_len);
            println!("  TRUE STREAMING: enabled (PAR-112)");

            let state = crate::api::AppState::with_cuda_model_and_vocab(cuda_model, vocab)?;

            // PMAT-088: Choose scheduler based on env var
            let cuda_model_arc = state.cuda_model().expect("just created").clone();
            let use_iteration_scheduler =
                std::env::var("ITERATION_SCHEDULER").as_deref() == Ok("1");

            let batch_tx = if use_iteration_scheduler {
                let iter_config =
                    crate::api::iteration_scheduler::IterationSchedulerConfig::default();
                println!(
                    "  ITERATION SCHEDULER: max_slots={}, prefill_chunk={} (PMAT-088)",
                    iter_config.max_slots, iter_config.prefill_chunk_size,
                );
                crate::api::iteration_scheduler::spawn_iteration_scheduler(
                    cuda_model_arc,
                    iter_config,
                )
            } else {
                let batch_config = crate::api::cuda_batch_scheduler::CudaBatchConfig::default();
                println!(
                    "  CONTINUOUS BATCHING: max_batch={}, window={}ms (PMAT-044)",
                    batch_config.max_batch, batch_config.window_ms
                );
                crate::api::cuda_batch_scheduler::spawn_cuda_batch_scheduler(
                    cuda_model_arc,
                    batch_config,
                )
            };
            println!();

            Ok(state.with_cuda_batch_tx(batch_tx))
        }

        #[cfg(not(feature = "cuda"))]
        {
            let _ = force_gpu;
            crate::api::AppState::with_quantized_model_and_vocab(quantized_model, vocab)
        }
    }

    /// Create batch-processing AppState for GGUF serving (PARITY-093/094)
    fn prepare_gguf_batch_state(
        quantized_model: crate::gguf::OwnedQuantizedModel,
        vocab: Vec<String>,
    ) -> Result<crate::api::AppState> {
        #[cfg(feature = "gpu")]
        {
            use crate::gguf::OwnedQuantizedModelCachedSync;

            println!("Initializing batch inference mode (PARITY-093/094)...");

            let cached_model = OwnedQuantizedModelCachedSync::new(quantized_model);

            println!("  Warming up GPU cache (dequantizing FFN weights)...");
            match cached_model.warmup_gpu_cache() {
                Ok((memory_bytes, num_layers)) => {
                    println!(
                        "  GPU cache ready: {:.2} GB ({} layers)",
                        memory_bytes as f64 / 1e9,
                        num_layers
                    );
                },
                Err(e) => {
                    eprintln!(
                        "  Warning: GPU cache warmup failed: {}. Falling back to CPU batch.",
                        e
                    );
                },
            }

            let state = crate::api::AppState::with_cached_model_and_vocab(cached_model, vocab)?;

            let cached_model_arc = state
                .cached_model()
                .expect("cached_model should exist")
                .clone();

            let batch_config = crate::api::BatchConfig::default();
            println!("  Batch window: {}ms", batch_config.window_ms);
            println!("  Min batch size: {}", batch_config.min_batch);
            println!("  Optimal batch: {}", batch_config.optimal_batch);
            println!("  Max batch size: {}", batch_config.max_batch);
            println!(
                "  GPU threshold: {} (GPU GEMM for batch >= this)",
                batch_config.gpu_threshold
            );

            let batch_tx =
                crate::api::spawn_batch_processor(cached_model_arc, batch_config.clone());

            println!("  Batch processor: RUNNING");
            println!();

            Ok(state.with_batch_config(batch_tx, batch_config))
        }

        #[cfg(not(feature = "gpu"))]
        {
            eprintln!(
                "Warning: --batch requires 'gpu' feature. Falling back to single-request mode."
            );
            crate::api::AppState::with_quantized_model_and_vocab(quantized_model, vocab)
        }
    }

    /// Load and prepare a SafeTensors model for serving
    fn prepare_safetensors_serve_state(model_path: &str, force_gpu: bool) -> Result<PreparedServer> {
        use std::path::Path;

        println!("Loading SafeTensors model for serving...");
        let model_path_obj = Path::new(model_path);

        // #169: GPU path via SafeTensorsCudaModel (format parity with GGUF)
        #[cfg(feature = "cuda")]
        if force_gpu {
            use crate::safetensors_cuda::SafeTensorsCudaModel;

            println!("  Mode: GPU (SafeTensors CUDA — #169 format parity)");
            let mut cuda_model = SafeTensorsCudaModel::load(model_path_obj, 0).map_err(|e| {
                crate::error::RealizarError::UnsupportedOperation {
                    operation: "safetensors_cuda_load".to_string(),
                    reason: format!("Failed to load SafeTensors for GPU: {e}"),
                }
            })?;

            let vocab_size = cuda_model.config().vocab_size;
            #[allow(clippy::map_unwrap_or)]
            let vocab = crate::apr::AprV2Model::load_tokenizer_from_sibling(model_path_obj)
                .map(|(v, _, _)| v)
                .unwrap_or_else(|| {
                    println!("  Warning: No tokenizer.json found, using simple vocabulary");
                    (0..vocab_size).map(|i| format!("token{i}")).collect()
                });

            println!("  Vocab size: {}", vocab.len());

            let state = crate::api::AppState::with_safetensors_cuda_model_and_vocab(
                cuda_model, vocab,
            )?;

            return Ok(PreparedServer {
                state,
                batch_mode_enabled: false,
                model_type: ModelType::SafeTensors,
            });
        }

        #[cfg(not(feature = "cuda"))]
        if force_gpu {
            eprintln!("Warning: --gpu flag requires 'cuda' feature for SafeTensors. Falling back to CPU.");
        }

        // CPU fallback path
        use crate::safetensors_infer::SafetensorsToAprConverter;

        let transformer = SafetensorsToAprConverter::convert(model_path_obj).map_err(|e| {
            crate::error::RealizarError::UnsupportedOperation {
                operation: "convert_safetensors".to_string(),
                reason: format!("Failed to convert SafeTensors: {e}"),
            }
        })?;

        println!("  Architecture: {}", transformer.config.architecture);
        println!("  Layers: {}", transformer.config.num_layers);
        println!("  Hidden: {}", transformer.config.hidden_dim);

        #[allow(clippy::map_unwrap_or)]
        let vocab = crate::apr::AprV2Model::load_tokenizer_from_sibling(model_path_obj)
            .map(|(v, _, _)| v)
            .unwrap_or_else(|| {
                println!("  Warning: No tokenizer.json found, using simple vocabulary");
                (0..transformer.config.vocab_size)
                    .map(|i| format!("token{i}"))
                    .collect()
            });

        println!("  Vocab size: {}", vocab.len());
        println!("  Mode: CPU (F32 inference)");

        let state =
            crate::api::AppState::with_apr_transformer_and_vocab(transformer.into_inner(), vocab)?;

        Ok(PreparedServer {
            state,
            batch_mode_enabled: false,
            model_type: ModelType::SafeTensors,
        })
    }

    /// Load and prepare an APR model for serving
    fn prepare_apr_serve_state(model_path: &str, force_gpu: bool) -> Result<PreparedServer> {
        use std::path::Path;

        println!("Loading APR model for serving...");

        // #170: Route Q4K APR through GGUF CUDA serve path (OwnedQuantizedModelCuda).
        // The Q4K-specific apr_q4k_scheduler produces garbage — disabled.
        #[cfg(feature = "cuda")]
        if force_gpu
            || std::env::var("REALIZAR_BACKEND")
                .map(|v| v.eq_ignore_ascii_case("cuda"))
                .unwrap_or(false)
        {
            return prepare_gguf_cuda_state_from_apr(model_path);
        }

        // F32 CPU path (original)
        use crate::apr_transformer::AprTransformer;

        let file_data = std::fs::read(model_path).map_err(|e| {
            crate::error::RealizarError::UnsupportedOperation {
                operation: "read_model_file".to_string(),
                reason: format!("Failed to read {model_path}: {e}"),
            }
        })?;

        let transformer = AprTransformer::from_apr_bytes(&file_data).map_err(|e| {
            crate::error::RealizarError::UnsupportedOperation {
                operation: "load_apr".to_string(),
                reason: format!("Failed to load APR: {e}"),
            }
        })?;

        println!("  Architecture: {}", transformer.config.architecture);
        println!("  Layers: {}", transformer.config.num_layers);
        println!("  Hidden: {}", transformer.config.hidden_dim);

        let model_path_obj = Path::new(model_path);
        let vocab = crate::apr::AprV2Model::load_tokenizer_from_sibling(model_path_obj)
            .map(|(v, _, _)| v)
            .or_else(|| {
                crate::apr::AprV2Model::load(model_path_obj)
                    .ok()
                    .and_then(|m| m.load_embedded_tokenizer())
                    .map(|t| t.id_to_token.clone())
            })
            .unwrap_or_else(|| {
                println!("  Warning: No vocabulary found, using simple vocabulary");
                (0..transformer.config.vocab_size)
                    .map(|i| format!("token{i}"))
                    .collect()
            });

        println!("  Vocab size: {}", vocab.len());
        println!("  Mode: CPU (F32 inference)");

        let state = crate::api::AppState::with_apr_transformer_and_vocab(transformer, vocab)?;

        Ok(PreparedServer {
            state,
            batch_mode_enabled: false,
            model_type: ModelType::Apr,
        })
    }

    /// ALB-095: Load APR Q4K model and spawn GPU inference thread for serving
    /// #170: Load APR model through GGUF CUDA path (OwnedQuantizedModel::from_apr)
    #[cfg(feature = "cuda")]
    fn prepare_gguf_cuda_state_from_apr(model_path: &str) -> Result<PreparedServer> {
        use crate::apr::MappedAprModel;
        use crate::gguf::{OwnedQuantizedModel, OwnedQuantizedModelCuda};
        use std::path::Path;

        let path = Path::new(model_path);
        println!("  Mode: GPU (APR → GGUF CUDA — #170 fix)");

        let mapped = MappedAprModel::from_path(path).map_err(|e| {
            crate::error::RealizarError::FormatError { reason: format!("APR load: {e}") }
        })?;
        let model = OwnedQuantizedModel::from_apr(&mapped).map_err(|e| {
            crate::error::RealizarError::FormatError { reason: format!("APR→GGUF: {e}") }
        })?;

        println!("  Layers: {}, Hidden: {}, Vocab: {}",
            model.config.num_layers, model.config.hidden_dim, model.config.vocab_size);

        // GH-286: Configurable context length (was hardcoded 4096)
        let max_seq_len = std::env::var("REALIZR_CONTEXT_LENGTH")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(4096);
        let cuda_model = OwnedQuantizedModelCuda::with_max_seq_len(model, 0, max_seq_len)
            .map_err(|e| e.error)?;

        println!("  CUDA model on GPU: {}", cuda_model.device_name());

        // Load vocab from embedded APR metadata
        let apr_v2 = crate::apr::AprV2Model::load(path).ok();
        let vocab = apr_v2.as_ref()
            .and_then(|m| m.metadata().get_embedded_vocabulary())
            .or_else(|| crate::apr::AprV2Model::load_tokenizer_from_sibling(path).map(|(v, _, _)| v))
            .unwrap_or_else(|| {
                println!("  Warning: No tokenizer found");
                (0..cuda_model.model().config.vocab_size).map(|i| format!("token{i}")).collect()
            });

        println!("  Vocab size: {}", vocab.len());

        let state = crate::api::AppState::with_cuda_model_and_vocab(cuda_model, vocab)?;

        Ok(PreparedServer {
            state,
            batch_mode_enabled: false,
            model_type: ModelType::Apr,
        })
    }

    #[cfg(feature = "cuda")]
    fn prepare_apr_q4k_serve_state(model_path: &str) -> Result<PreparedServer> {
        use crate::api::apr_q4k_scheduler;
        use crate::apr::AprV2Model;
        use std::path::Path;

        println!("  Mode: GPU (Q4K CUDA — ALB-095)");

        // Load tokenizer for the HTTP serving path
        // ALB-109: Capture EOS token ID — Qwen3 uses 151643, not 0/2
        let model_path_obj = Path::new(model_path);
        let (vocab, eos_id) = AprV2Model::load_tokenizer_from_sibling(model_path_obj)
            .map(|(v, _, eos)| (v, eos))
            .or_else(|| {
                AprV2Model::load(model_path_obj)
                    .ok()
                    .and_then(|m| m.load_embedded_tokenizer())
                    .map(|t| (t.id_to_token.clone(), None))
            })
            .unwrap_or_else(|| {
                println!("  Warning: No vocabulary found, using simple vocabulary");
                ((0..151936).map(|i| format!("token{i}")).collect(), None)
            });

        println!("  Vocab: {} tokens", vocab.len());
        if let Some(eos) = eos_id {
            println!("  EOS token ID: {eos}");
        }

        // Spawn the Q4K inference thread (loads model, uploads weights to GPU)
        let q4k_tx =
            apr_q4k_scheduler::spawn_apr_q4k_inference_thread(model_path).map_err(|e| {
                crate::error::RealizarError::GpuError {
                    reason: format!("Q4K inference thread failed: {e}"),
                }
            })?;

        let state = crate::api::AppState::with_apr_q4k_and_vocab_eos(q4k_tx, vocab, eos_id)?;

        Ok(PreparedServer {
            state,
            batch_mode_enabled: false,
            model_type: ModelType::Apr,
        })
    }

    /// Prepare server state by loading a model (GGUF/SafeTensors/APR)
    ///
    /// Dispatches to format-specific loaders based on file extension.
    pub fn prepare_serve_state(
        model_path: &str,
        batch_mode: bool,
        force_gpu: bool,
    ) -> Result<PreparedServer> {
        println!("Loading model from: {model_path}");
        if batch_mode {
            println!("Mode: BATCH (PARITY-093 M4 parity)");
        } else {
            println!("Mode: SINGLE-REQUEST");
        }
        if force_gpu {
            println!("GPU: FORCED (--gpu flag)");
        }
        println!();

        if model_path.ends_with(".gguf") {
            prepare_gguf_serve_state(model_path, batch_mode, force_gpu)
        } else if model_path.ends_with(".safetensors") {
            prepare_safetensors_serve_state(model_path, force_gpu)
        } else if model_path.ends_with(".apr") {
            prepare_apr_serve_state(model_path, force_gpu)
        } else {
            Err(crate::error::RealizarError::UnsupportedOperation {
                operation: "detect_model_type".to_string(),
                reason: "Unsupported file extension. Expected .gguf, .safetensors, or .apr"
                    .to_string(),
            })
        }
    }

    /// Serve a GGUF/SafeTensors/APR model via HTTP API
    ///
    /// This function was extracted from main.rs (PAR-112-FIX) to enable:
    /// 1. Unit testing of server initialization logic
    /// 2. Coverage measurement (main.rs was at 3.66%)
    /// 3. Reuse from other entry points
    ///
    /// # Arguments
    /// * `host` - Host to bind to (e.g., "0.0.0.0")
    /// * `port` - Port to listen on
    /// * `model_path` - Path to model file (.gguf, .safetensors, or .apr)
    /// * `batch_mode` - Enable batch processing (requires 'gpu' feature)
    /// * `force_gpu` - Force CUDA backend (requires 'cuda' feature)
    /// * `openai_api` - Enable OpenAI-compatible API at /v1/* (GH-148)
    /// * `trace` - GH-103: Enable inference tracing (propagates into QuantizedGenerateConfig.trace)
    /// * `context_length` - GH-286: Max sequence length for KV cache (default 4096)
    /// * `no_fp8_cache` - GH-286: Skip FP8 weight cache warmup (saves ~1.5 GB RSS)
    #[allow(clippy::too_many_arguments, clippy::fn_params_excessive_bools)]
    pub async fn serve_model(
        host: &str,
        port: u16,
        model_path: &str,
        batch_mode: bool,
        force_gpu: bool,
        openai_api: bool,
        trace: bool,
        context_length: usize,
        no_fp8_cache: bool,
    ) -> Result<()> {
        // GH-286: Set context length and FP8 cache flags for downstream use
        if no_fp8_cache {
            std::env::set_var("REALIZR_NO_FP8_CACHE", "1");
            eprintln!("[GH-286] FP8 weight cache DISABLED (--no-fp8-cache). Saves ~1.5 GB RSS.");
        }
        // Store context_length for prepare_serve_state to pick up
        std::env::set_var("REALIZR_CONTEXT_LENGTH", context_length.to_string());

        // Prepare server state (testable)
        let prepared = prepare_serve_state(model_path, batch_mode, force_gpu)?;

        // GH-103: Wire trace flag into AppState
        let state = if trace {
            eprintln!("Tracing: ENABLED (--trace flag)");
            prepared.state.with_trace(true)
        } else {
            prepared.state
        };

        // GH-148: Create router with OpenAI API flag
        let router_config = crate::api::RouterConfig { openai_api };
        let app = crate::api::create_router_with_config(state, router_config);

        // Parse and validate address
        let addr: std::net::SocketAddr = format!("{host}:{port}").parse().map_err(|e| {
            crate::error::RealizarError::InvalidShape {
                reason: format!("Invalid address: {e}"),
            }
        })?;

        // GH-148: Server info to stderr to avoid stdout contamination
        eprintln!("Server listening on http://{addr}");
        eprintln!();
        eprintln!("Endpoints:");
        eprintln!("  GET  /health         - Health check");
        if openai_api {
            eprintln!("  POST /v1/completions - OpenAI-compatible completions");
        }
        if prepared.batch_mode_enabled && openai_api {
            eprintln!("  POST /v1/batch/completions - GPU batch completions (PARITY-022)");
            eprintln!("  POST /v1/gpu/warmup  - Warmup GPU cache");
            eprintln!("  GET  /v1/gpu/status  - GPU status");
        }
        eprintln!("  POST /generate       - Generate text (Q4_K fused)");
        if !openai_api {
            eprintln!("  (OpenAI-compatible /v1/* routes disabled)");
        }
        eprintln!();

        if prepared.batch_mode_enabled {
            eprintln!("M4 Parity Target: 192 tok/s at concurrency >= 4");
            eprintln!("Benchmark with: wrk -t4 -c4 -d30s http://{addr}/v1/completions");
            eprintln!();
        }

        // Bind and serve
        let listener = tokio::net::TcpListener::bind(addr).await.map_err(|e| {
            crate::error::RealizarError::UnsupportedOperation {
                operation: "bind".to_string(),
                reason: format!("Failed to bind: {e}"),
            }
        })?;

        axum::serve(listener, app).await.map_err(|e| {
            crate::error::RealizarError::UnsupportedOperation {
                operation: "serve".to_string(),
                reason: format!("Server error: {e}"),
            }
        })?;

        Ok(())
    }

    /// Start a demo inference server (no model required)
    ///
    /// This is useful for testing the API without loading a real model.
    /// * `openai_api` - Enable OpenAI-compatible API at /v1/* (GH-148)
    pub async fn serve_demo(host: &str, port: u16, openai_api: bool) -> Result<()> {
        use std::net::SocketAddr;

        // GH-148: Server info to stderr to avoid stdout contamination
        eprintln!("Starting Realizar inference server (demo mode)...");

        let state = crate::api::AppState::demo()?;
        let router_config = crate::api::RouterConfig { openai_api };
        let app = crate::api::create_router_with_config(state, router_config);

        let addr: SocketAddr = format!("{host}:{port}").parse().map_err(|e| {
            crate::error::RealizarError::InvalidShape {
                reason: format!("Invalid address: {e}"),
            }
        })?;

        eprintln!("Server listening on http://{addr}");
        eprintln!();
        eprintln!("Endpoints:");
        eprintln!("  GET  /health   - Health check");
        eprintln!("  POST /tokenize - Tokenize text");
        eprintln!("  POST /generate - Generate text");
        if !openai_api {
            eprintln!("  (OpenAI-compatible /v1/* routes disabled)");
        }
        eprintln!();
        eprintln!("Example:");
        eprintln!("  curl http://{addr}/health");
        eprintln!();

        let listener = tokio::net::TcpListener::bind(addr).await.map_err(|e| {
            crate::error::RealizarError::InvalidShape {
                reason: format!("Failed to bind: {e}"),
            }
        })?;

        axum::serve(listener, app).await.map_err(|e| {
            crate::error::RealizarError::InvalidShape {
                reason: format!("Server error: {e}"),
            }
        })?;

        Ok(())
    }
} // mod server_commands

#[cfg(feature = "server")]
pub use server_commands::*;