forked from ai-dynamo/dynamo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprotocols.rs
More file actions
1743 lines (1562 loc) · 62.1 KB
/
Copy pathprotocols.rs
File metadata and controls
1743 lines (1562 loc) · 62.1 KB
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
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
use derive_builder::Builder;
use dynamo_kv_router::config::RouterQueuePolicy;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Arc;
use uuid::Uuid;
use validator::{Validate, ValidationError};
use crate::common::perf_model::PerfModel;
use dynamo_kv_router::protocols::{KvCacheEvent, StorageTier};
use dynamo_tokens::blocks::UniqueBlock;
use dynamo_tokens::{BlockHash, PositionalLineageHash, SequenceHash, Token};
/// Metadata marker type for kvbm-logical blocks in the mocker's G1 pool.
#[derive(Clone, Debug)]
pub struct G1;
/// Eviction strategy for the kvbm-logical inactive pool.
///
/// `Lineage` is the default and matches kvbm-logical's own default — it evicts
/// leaf blocks first, which subsumes the preemption-priority behaviour that the
/// mocker's old `LRUEvictor::push_front` provided.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)]
pub enum MockerEvictionBackend {
Lru,
MultiLru,
#[default]
Lineage,
}
/// Trait for publishing KV cache events.
/// This abstracts the runtime dependency so mocker components can remain generic.
pub trait KvCacheEventSink: Send + Sync {
fn publish(&self, event: KvCacheEvent) -> anyhow::Result<()>;
fn publish_with_storage_tier(
&self,
event: KvCacheEvent,
_storage_tier: StorageTier,
) -> anyhow::Result<()> {
self.publish(event)
}
}
/// Raw KV event payload used by transport-specific publishers such as the
/// vLLM-native ZMQ event stream.
#[derive(Debug, Clone)]
pub struct RawKvEvent {
pub event: KvCacheEvent,
pub block_token_ids: Option<Vec<Vec<u32>>>,
pub storage_tier: StorageTier,
}
/// Trait for publishing transport-specific raw KV event payloads.
pub trait RawKvEventSink: Send + Sync {
fn publish(&self, event: RawKvEvent) -> anyhow::Result<()>;
}
/// Shared KV event publisher bundle used by schedulers and KV managers.
#[derive(Clone, Default)]
pub struct KvEventPublishers {
event_sink: Option<Arc<dyn KvCacheEventSink>>,
raw_sink: Option<Arc<dyn RawKvEventSink>>,
}
impl KvEventPublishers {
pub fn new(
event_sink: Option<Arc<dyn KvCacheEventSink>>,
raw_sink: Option<Arc<dyn RawKvEventSink>>,
) -> Self {
Self {
event_sink,
raw_sink,
}
}
pub fn raw_enabled(&self) -> bool {
self.raw_sink.is_some()
}
pub fn is_empty(&self) -> bool {
self.event_sink.is_none() && self.raw_sink.is_none()
}
pub fn publish(
&self,
event: KvCacheEvent,
block_token_ids: Option<&[Vec<u32>]>,
) -> anyhow::Result<()> {
self.publish_with_storage_tier(event, block_token_ids, StorageTier::Device)
}
pub fn publish_with_storage_tier(
&self,
event: KvCacheEvent,
block_token_ids: Option<&[Vec<u32>]>,
storage_tier: StorageTier,
) -> anyhow::Result<()> {
if let Some(sink) = self.event_sink.as_ref() {
sink.publish_with_storage_tier(event.clone(), storage_tier)?;
}
if let Some(sink) = self.raw_sink.as_ref() {
sink.publish(RawKvEvent {
event,
block_token_ids: block_token_ids.map(|token_ids| token_ids.to_vec()),
storage_tier,
})?;
}
Ok(())
}
}
/// Per-iteration forward pass snapshot, mirroring the Python `ForwardPassMetrics`
/// schema in `components/src/dynamo/common/forward_pass_metrics.py`.
///
/// Produced by the scheduler core after each `execute_pass_internal()` call.
/// Runtime publishers may either stamp identity at serialization time or fill
/// the identity fields directly when snapshots are consumed in-process.
#[derive(Debug, Clone, Default)]
pub struct ForwardPassSnapshot {
// -- identity --
// `Default::default()` leaves `version == 0` and identity fields empty or
// zero, which means an unstamped local snapshot. Runtime publishers may
// stamp or overwrite these fields at the serialization boundary.
pub version: u32,
pub worker_id: String,
pub dp_rank: u32,
pub counter_id: u64,
// -- scheduled requests (executed this iteration) --
pub num_prefill_requests: u32,
pub sum_prefill_tokens: u64,
pub var_prefill_length: f64,
pub sum_prefill_kv_tokens: u64,
pub num_decode_requests: u32,
pub sum_decode_kv_tokens: u64,
pub var_decode_kv_tokens: f64,
// -- queued requests (waiting, not scheduled) --
pub num_queued_prefill: u32,
pub sum_queued_prefill_tokens: u64,
pub var_queued_prefill_length: f64,
pub num_queued_decode: u32,
pub sum_queued_decode_kv_tokens: u64,
pub var_queued_decode_kv_tokens: f64,
// -- timing --
pub wall_time_secs: f64,
}
/// Trait for publishing forward pass metrics snapshots.
/// This abstracts the FPM publishing pipeline so mocker schedulers remain generic.
pub trait FpmSink: Send + Sync {
fn publish(&self, snapshot: ForwardPassSnapshot) -> anyhow::Result<()>;
}
/// Optional FPM sink used by schedulers.
/// Wraps `Option<Arc<dyn FpmSink>>` for ergonomic passing and no-op default behavior.
#[derive(Clone, Default)]
pub struct FpmPublisher {
sink: Option<Arc<dyn FpmSink>>,
}
impl FpmPublisher {
pub fn new(sink: Option<Arc<dyn FpmSink>>) -> Self {
Self { sink }
}
pub fn publish(&self, snapshot: ForwardPassSnapshot) -> anyhow::Result<()> {
if let Some(sink) = &self.sink {
sink.publish(snapshot)?;
}
Ok(())
}
}
pub type NumBlocks = usize;
/// Represents different block movement operations in the cache
/// For Use and Promote variants, block hashes are included for KV event publishing
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum MoveBlock {
Use(
Vec<UniqueBlock>,
Vec<BlockHash>,
Vec<PositionalLineageHash>,
Option<Vec<Vec<u32>>>,
Option<UniqueBlock>,
),
Deref(Vec<UniqueBlock>),
Promote(
Uuid,
SequenceHash,
Option<u64>,
Option<BlockHash>,
PositionalLineageHash,
Option<Vec<u32>>,
),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum MoveBlockResponse {
Store(Vec<SequenceHash>, Option<u64>),
Remove(Vec<SequenceHash>),
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DirectRequest {
pub tokens: Vec<Token>,
pub max_output_tokens: usize,
pub uuid: Option<Uuid>,
pub dp_rank: u32,
pub arrival_timestamp_ms: Option<f64>,
/// TODO: Replay maps this to router queue priority only; mock-engine
/// scheduling does not consume it yet.
#[serde(default, skip_serializing_if = "is_zero_i32")]
pub priority: i32,
/// NOTE: Strict priority orders the router's pending queue only. It does
/// not affect scheduling inside the selected mock engine.
#[serde(default, skip_serializing_if = "is_zero_u32")]
pub strict_priority: u32,
}
impl DirectRequest {
pub fn router_priorities(&self) -> (f64, u32) {
(f64::from(self.priority.max(0)), self.strict_priority)
}
}
fn is_zero_i32(value: &i32) -> bool {
*value == 0
}
fn is_zero_u32(value: &u32) -> bool {
*value == 0
}
/// Represents the cost of prefilling content in the cache
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PrefillCost {
pub new_blocks: usize,
pub new_tokens: usize,
/// Number of tokens already cached (prefix hit).
/// isl = cached_tokens + new_tokens
pub cached_tokens: usize,
/// Subset of `cached_tokens` backed by active blocks. Physical-capacity
/// admission discounts only these because inactive reuse is re-consumed.
pub active_cached_tokens: usize,
}
impl PrefillCost {
pub fn predict_prefill_compute(
&self,
new_tokens: Option<usize>,
perf_model: &PerfModel,
) -> f64 {
let tokens = new_tokens.unwrap_or(self.new_tokens);
let isl = self.cached_tokens + tokens;
perf_model.predict_prefill_time(1, isl, self.cached_tokens)
}
}
/// Signal for output token generation with completion status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutputSignal {
pub uuid: Uuid,
/// Terminal flag: the request's lifecycle has ended. Replay drivers free
/// resources and advance/notify on this.
pub completed: bool,
/// Set with `completed` when the request was rejected without ever running
/// (its footprint exceeds the whole KV pool); drivers free/advance but
/// exclude it from token/latency/throughput stats.
#[serde(default)]
pub rejected: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub handoff_delay_ms: Option<f64>,
}
/// Preemption policy for evicting decode requests under memory pressure
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum PreemptionMode {
/// Evict the newest request (matches vLLM v1 default)
#[default]
Lifo,
/// Evict the oldest request
Fifo,
}
impl FromStr for PreemptionMode {
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value.to_ascii_lowercase().as_str() {
"lifo" => Ok(Self::Lifo),
"fifo" => Ok(Self::Fifo),
_ => Err(format!(
"Invalid preemption_mode: '{value}'. Must be 'lifo' or 'fifo'."
)),
}
}
}
/// Engine type for selecting scheduling and KV cache simulation behavior
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum EngineType {
/// vLLM-style scheduling with hash-based block KV cache
#[default]
Vllm,
/// SGLang-style scheduling with radix-tree KV cache
Sglang,
/// TensorRT-LLM-style scheduling. Reuses the vLLM scheduler
/// core with a TensorRT-LLM-style admission policy.
Trtllm,
}
impl FromStr for EngineType {
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value.to_ascii_lowercase().as_str() {
"vllm" => Ok(Self::Vllm),
"sglang" => Ok(Self::Sglang),
"trtllm" => Ok(Self::Trtllm),
_ => Err(format!(
"Invalid engine_type '{value}'. Must be 'vllm', 'sglang', or 'trtllm'."
)),
}
}
}
/// Scheduling policy applied by the shared vLLM scheduler core.
///
/// Derived from [`EngineType`] (+ engine-specific args) so the core reads a
/// single discriminant instead of re-deriving engine behavior per pass.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SchedulingPolicy {
/// vLLM semantics: require the current known sequence to fit at waiting
/// admission, then permit preemption under later KV pressure.
#[default]
Vllm,
/// TRT-LLM `GUARANTEED_NO_EVICT`: reserve `prompt + max_output` per
/// admitted request up front; never preempt.
TrtllmGuaranteedNoEvict,
}
/// Worker type for disaggregated serving configurations
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum WorkerType {
/// Standard aggregated worker handling both prefill and decode
#[default]
Aggregated,
/// Dedicated prefill worker in disaggregated mode
Prefill,
/// Dedicated decode worker in disaggregated mode
Decode,
}
impl FromStr for WorkerType {
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value.to_ascii_lowercase().as_str() {
"aggregated" => Ok(Self::Aggregated),
"prefill" => Ok(Self::Prefill),
"decode" => Ok(Self::Decode),
_ => Err(format!(
"Invalid worker_type '{value}'. Must be 'aggregated', 'prefill', or 'decode'."
)),
}
}
}
/// Configuration for reasoning/thinking token output in the mocker.
///
/// When set, the mocker wraps the first portion of each response in thinking
/// boundary tokens: `[start_token, random..., end_token, random...]`.
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct ReasoningConfig {
pub start_thinking_token_id: u32,
pub end_thinking_token_id: u32,
#[validate(range(min = 0.0, max = 1.0))]
pub thinking_ratio: f64,
}
impl ReasoningConfig {
/// Number of thinking tokens (including start/end boundaries) for a given osl.
/// Returns 0 if osl < 2 (thinking disabled). Otherwise clamps to [2, osl].
pub fn num_thinking_tokens(&self, max_output_tokens: usize) -> usize {
if max_output_tokens < 2 {
return 0;
}
let raw = (max_output_tokens as f64 * self.thinking_ratio).floor() as usize;
if raw == 0 {
return 0;
}
raw.max(2).min(max_output_tokens)
}
/// Number of response tokens after the thinking block.
pub fn num_response_tokens(&self, max_output_tokens: usize) -> usize {
max_output_tokens.saturating_sub(self.num_thinking_tokens(max_output_tokens))
}
}
/// SGLang-specific configuration parameters.
///
/// Grouped into a nested struct to keep the `MockEngineArgs` namespace clean,
/// following the same pattern as [`ReasoningConfig`].
#[derive(Debug, Clone, Serialize, Deserialize, Validate, Default)]
pub struct SglangArgs {
/// Scheduling policy: "fifo"/"fcfs" or "lpm". Default: "fifo".
pub schedule_policy: Option<String>,
/// Radix cache page size in tokens. Default: 1.
#[validate(range(min = 1))]
pub page_size: Option<usize>,
/// Maximum prefill tokens budget per batch. Default: 16384.
#[validate(range(min = 1))]
pub max_prefill_tokens: Option<usize>,
/// Chunked prefill size (max tokens per chunk). Default: 8192.
#[validate(range(min = 1))]
pub chunked_prefill_size: Option<usize>,
/// Clip max new tokens for admission budget. Default: 4096.
#[validate(range(min = 1))]
pub clip_max_new_tokens: Option<usize>,
/// Schedule conservativeness factor (0.0–1.0). Default: 1.0.
#[validate(range(min = 0.0, max = 1.0))]
pub schedule_conservativeness: Option<f64>,
}
/// TensorRT-LLM-specific configuration parameters.
///
/// Grouped into a nested struct to keep the `MockEngineArgs` namespace clean,
/// following the same pattern as [`SglangArgs`].
#[derive(Debug, Clone, Serialize, Deserialize, Validate, Default)]
pub struct TrtllmArgs {
/// Capacity scheduler policy, supported only `"guaranteed_no_evict"`
/// (TensorRT-LLM's default). Default: `"guaranteed_no_evict"`.
pub capacity_scheduler_policy: Option<String>,
}
/// Keeps omitted JSON fields distinct from explicit `null` so serde can replace
/// the old hand-written parser without losing input-config semantics.
#[derive(Debug, Clone, Default)]
enum OptionalConfigValue<T> {
#[default]
Missing,
Present(Option<T>),
}
impl<'de, T> Deserialize<'de> for OptionalConfigValue<T>
where
T: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
Option::<T>::deserialize(deserializer).map(Self::Present)
}
}
impl<T> OptionalConfigValue<T> {
fn into_nullable(self) -> Option<Option<T>> {
match self {
Self::Missing => None,
Self::Present(value) => Some(value),
}
}
fn into_non_null(self, field: &str) -> Result<Option<T>, String> {
match self {
Self::Missing => Ok(None),
Self::Present(Some(value)) => Ok(Some(value)),
Self::Present(None) => Err(format!("{field} must not be null")),
}
}
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct MockEngineArgsSerde {
engine_type: OptionalConfigValue<String>,
num_gpu_blocks: OptionalConfigValue<usize>,
block_size: OptionalConfigValue<usize>,
max_num_seqs: OptionalConfigValue<usize>,
max_num_batched_tokens: OptionalConfigValue<usize>,
enable_prefix_caching: OptionalConfigValue<bool>,
enable_chunked_prefill: OptionalConfigValue<bool>,
speedup_ratio: OptionalConfigValue<f64>,
decode_speedup_ratio: OptionalConfigValue<f64>,
dp_size: OptionalConfigValue<u32>,
startup_time: OptionalConfigValue<f64>,
worker_type: OptionalConfigValue<String>,
is_prefill: OptionalConfigValue<bool>,
is_decode: OptionalConfigValue<bool>,
planner_profile_data: OptionalConfigValue<PathBuf>,
aic_backend: OptionalConfigValue<String>,
aic_system: OptionalConfigValue<String>,
aic_backend_version: OptionalConfigValue<String>,
aic_tp_size: OptionalConfigValue<usize>,
aic_model_path: OptionalConfigValue<String>,
aic_moe_tp_size: OptionalConfigValue<usize>,
aic_moe_ep_size: OptionalConfigValue<usize>,
aic_attention_dp_size: OptionalConfigValue<usize>,
aic_nextn: OptionalConfigValue<usize>,
aic_nextn_accept_rates: OptionalConfigValue<String>,
aic_mtp_seed: OptionalConfigValue<u64>,
gpu_memory_utilization: OptionalConfigValue<f64>,
mem_fraction_static: OptionalConfigValue<f64>,
free_gpu_memory_fraction: OptionalConfigValue<f64>,
enable_local_indexer: OptionalConfigValue<bool>,
bootstrap_port: OptionalConfigValue<u16>,
kv_bytes_per_token: OptionalConfigValue<usize>,
kv_transfer_bandwidth: OptionalConfigValue<f64>,
num_g2_blocks: OptionalConfigValue<usize>,
num_g3_blocks: OptionalConfigValue<usize>,
enable_g4_storage: OptionalConfigValue<bool>,
offload_batch_size: OptionalConfigValue<usize>,
bandwidth_g1_to_g2_gbps: OptionalConfigValue<f64>,
bandwidth_g2_to_g1_gbps: OptionalConfigValue<f64>,
bandwidth_g2_to_g3_gbps: OptionalConfigValue<f64>,
bandwidth_g3_to_g2_gbps: OptionalConfigValue<f64>,
bandwidth_g2_to_g4_gbps: OptionalConfigValue<f64>,
bandwidth_g4_to_g2_gbps: OptionalConfigValue<f64>,
reasoning: OptionalConfigValue<ReasoningConfig>,
zmq_kv_events_port: OptionalConfigValue<u16>,
zmq_replay_port: OptionalConfigValue<u16>,
preemption_mode: OptionalConfigValue<String>,
router_queue_policy: OptionalConfigValue<String>,
sglang: OptionalConfigValue<SglangArgs>,
trtllm: OptionalConfigValue<TrtllmArgs>,
#[serde(rename = "has_perf_model")]
_has_perf_model: OptionalConfigValue<serde_json::Value>,
}
fn load_perf_model(path: &Path) -> Arc<PerfModel> {
match PerfModel::from_npz(path) {
Ok(model) => {
tracing::info!("Successfully loaded performance model from: {:?}", path);
Arc::new(model)
}
Err(e) => {
tracing::error!(
"Failed to load performance model from {:?}: {}. Falling back to polynomial model.",
path,
e
);
Arc::new(PerfModel::default())
}
}
}
/// Configuration arguments for MockEngine
#[derive(Debug, Clone, Serialize, Deserialize, Builder, Validate)]
#[serde(try_from = "MockEngineArgsSerde")]
#[validate(schema(function = "validate_mock_engine_args"))]
#[builder(pattern = "owned", build_fn(public))]
pub struct MockEngineArgs {
/// Engine type: vLLM, SGLang, or TensorRT-LLM simulation
#[builder(default = "EngineType::Vllm")]
pub engine_type: EngineType,
#[builder(default = "16384")]
#[validate(range(min = 1))]
pub num_gpu_blocks: usize,
#[builder(default = "0")]
pub block_size: usize,
// This was 1024 in the past but reverted back to 256
#[builder(default = Some(256))]
#[validate(range(min = 1))]
pub max_num_seqs: Option<usize>,
// default for open api server, for llm class it's 16384
#[builder(default = Some(8192))]
#[validate(range(min = 1))]
pub max_num_batched_tokens: Option<usize>,
#[builder(default = true)]
pub enable_prefix_caching: bool,
#[builder(default = true)]
pub enable_chunked_prefill: bool,
#[builder(default = "1.0")]
#[validate(range(min = 0.0))]
pub speedup_ratio: f64,
/// Additional speedup multiplier applied only to decode steps.
/// Models speculative decoding (e.g. Eagle) where decode throughput improves
/// without affecting prefill latency. The effective decode speedup is
/// `speedup_ratio * decode_speedup_ratio`.
#[builder(default = "1.0")]
#[validate(range(min = 0.0))]
pub decode_speedup_ratio: f64,
#[builder(default = "1")]
#[validate(range(min = 1))]
pub dp_size: u32,
/// Optional startup time in seconds to simulate engine initialization delay
#[builder(default = "None")]
#[validate(range(min = 0.0))]
pub startup_time: Option<f64>,
/// Worker type for disaggregated serving (Aggregated, Prefill, or Decode)
#[builder(default = "WorkerType::Aggregated")]
pub worker_type: WorkerType,
/// Original planner profile NPZ path used to materialize `perf_model`.
#[builder(default = "None")]
pub planner_profile_data: Option<PathBuf>,
/// Performance model for timing predictions (not serialized, loaded from planner_profile_data)
#[serde(skip)]
#[builder(default = "Arc::new(PerfModel::default())")]
pub perf_model: Arc<PerfModel>,
/// If set, indicates direct AIC SDK calls should be used.
/// The value is the backend name (e.g., "sglang", "vllm").
/// The Python layer reads this and overrides perf_model with an Aiconfigurator callback.
#[serde(skip)]
#[builder(default = "None")]
pub aic_backend: Option<String>,
/// AIC GPU system name (e.g., "h200_sxm"). Required when aic_backend is set.
#[serde(skip)]
#[builder(default = "None")]
pub aic_system: Option<String>,
/// AIC backend engine version (e.g., "0.12.0" for vLLM, "0.5.6.post2" for SGLang).
/// If None, uses the default version for the backend.
#[serde(skip)]
#[builder(default = "None")]
pub aic_backend_version: Option<String>,
/// Tensor parallel size for AIC latency prediction.
/// Only affects AIC performance model lookups, not mocker scheduling.
#[serde(skip)]
#[builder(default = "None")]
pub aic_tp_size: Option<usize>,
/// HuggingFace model path for AIC latency prediction (e.g., "nvidia/Llama-3.1-8B-Instruct-FP8").
#[serde(skip)]
#[builder(default = "None")]
pub aic_model_path: Option<String>,
/// MoE tensor-parallel size for AIC latency prediction (e.g., 4 for pure MoE-TP).
/// Required for MoE models; must satisfy: aic_tp_size * aic_attention_dp_size == aic_moe_tp_size * aic_moe_ep_size.
#[serde(skip)]
#[builder(default = "None")]
pub aic_moe_tp_size: Option<usize>,
/// MoE expert-parallel size for AIC latency prediction (e.g., 4 for pure EP).
/// Required for MoE models; must satisfy: aic_tp_size * aic_attention_dp_size == aic_moe_tp_size * aic_moe_ep_size.
#[serde(skip)]
#[builder(default = "None")]
pub aic_moe_ep_size: Option<usize>,
/// Attention data-parallel size for AIC latency prediction (default: 1).
/// Corresponds to the `dp` dimension in AIC CLI output.
/// Must satisfy: aic_tp_size * aic_attention_dp_size == aic_moe_tp_size * aic_moe_ep_size.
#[serde(skip)]
#[builder(default = "None")]
pub aic_attention_dp_size: Option<usize>,
/// MTP/Eagle speculative-decoding draft-token count (1..=5).
/// The mocker samples accepted drafts while AIC supplies undiscounted
/// verification-round latency.
#[builder(default = "None")]
#[validate(range(min = 1, max = 5))]
pub aic_nextn: Option<usize>,
/// Conditional acceptance rates for draft tokens, comma-separated.
/// Entry i is P(draft i accepted | every earlier draft was accepted).
#[builder(default = "None")]
pub aic_nextn_accept_rates: Option<String>,
/// Base RNG seed for MTP burst sampling. Worker rank is added with
/// wrapping arithmetic before constructing each worker-local sampler.
#[builder(default = "42")]
pub aic_mtp_seed: u64,
/// GPU memory fraction for AIC KV capacity estimation with vLLM.
#[builder(default = "None")]
#[validate(range(min = 0.0, max = 1.0))]
pub gpu_memory_utilization: Option<f64>,
/// Static memory fraction for AIC KV capacity estimation with SGLang.
#[builder(default = "None")]
#[validate(range(min = 0.0, max = 1.0))]
pub mem_fraction_static: Option<f64>,
/// Fraction of *free* GPU memory (after weights/buffers) allocated to the KV
/// cache, for AIC KV capacity estimation with TRT-LLM. Mirrors TRT-LLM's
/// `KvCacheConfig.free_gpu_memory_fraction`. Unlike vLLM's
/// `gpu_memory_utilization` (a fraction of *total* memory), this is a
/// fraction of what remains after the model is loaded.
#[builder(default = "None")]
#[validate(range(min = 0.0, max = 1.0))]
pub free_gpu_memory_fraction: Option<f64>,
/// Enable worker-local KV indexer for tracking this worker's own KV cache state
#[builder(default = "false")]
pub enable_local_indexer: bool,
/// Bootstrap port for disaggregated serving rendezvous.
/// Prefill workers listen on this port; decode workers connect to it.
/// If None, bootstrap rendezvous is disabled.
#[builder(default = "None")]
pub bootstrap_port: Option<u16>,
/// KV cache bytes per token, auto-computed from model config by Python CLI.
/// Formula: num_layers * 2 * num_kv_heads * head_dim * dtype_bytes
#[builder(default = "None")]
pub kv_bytes_per_token: Option<usize>,
/// KV cache transfer bandwidth in GB/s for disaggregated serving latency simulation.
/// Default: 64.0 (inter-node InfiniBand). Set to 0 to disable KV transfer delay.
/// For intra-node NVLink, typical value is ~450.
#[builder(default = "None")]
#[validate(range(min = 0.0))]
pub kv_transfer_bandwidth: Option<f64>,
/// KVBM G2 (host DRAM) block capacity. When the `kvbm-offload`
/// feature is enabled, setting this explicitly opts the mocker into
/// G2 offload simulation. When unset or set to 0, no G2 offload engine
/// is attached.
#[builder(default = "None")]
#[validate(range(min = 1))]
pub num_g2_blocks: Option<usize>,
/// KVBM G3 shared lower-tier block capacity. Positive values require
/// `num_g2_blocks` and a resolvable KV block byte size; 0 disables G3.
#[builder(default = "None")]
#[validate(range(min = 1))]
pub num_g3_blocks: Option<usize>,
/// Enable KVBM mock G4 object-storage simulation. G4 stages through G2
/// and uses object presence operations instead of a `BlockManager<G4>`.
#[builder(default = "false")]
pub enable_g4_storage: bool,
/// Batch size for the G1→G2 offload pipeline. Offloads are grouped
/// into batches of this size before being handed to the worker.
/// Only consulted when the `kvbm-offload` feature is enabled;
/// falls back to the `KvbmOffloadConfig` default when unset or 0.
#[builder(default = "None")]
#[validate(range(min = 1))]
pub offload_batch_size: Option<usize>,
/// G1→G2 offload bandwidth in GB/s for the PS-queue simulation.
/// Only consulted when the `kvbm-offload` feature is enabled;
/// falls back to the `KvbmOffloadConfig` default (host DRAM PCIe
/// ballpark) when unset.
#[builder(default = "None")]
#[validate(range(min = 0.0))]
pub bandwidth_g1_to_g2_gbps: Option<f64>,
/// G2→G1 onboard bandwidth in GB/s for the PS-queue simulation.
/// Only consulted when the `kvbm-offload` feature is enabled;
/// falls back to the `KvbmOffloadConfig` default when unset.
#[builder(default = "None")]
#[validate(range(min = 0.0))]
pub bandwidth_g2_to_g1_gbps: Option<f64>,
/// G2→G3 offload bandwidth in GB/s for the shared PS-queue simulation.
#[builder(default = "None")]
#[validate(range(min = 0.0))]
pub bandwidth_g2_to_g3_gbps: Option<f64>,
/// G3→G2 staging bandwidth in GB/s for the shared PS-queue simulation.
#[builder(default = "None")]
#[validate(range(min = 0.0))]
pub bandwidth_g3_to_g2_gbps: Option<f64>,
/// G2→G4 object offload bandwidth in GB/s for the shared PS-queue simulation.
#[builder(default = "None")]
#[validate(range(min = 0.0))]
pub bandwidth_g2_to_g4_gbps: Option<f64>,
/// G4→G2 object staging bandwidth in GB/s for the shared PS-queue simulation.
#[builder(default = "None")]
#[validate(range(min = 0.0))]
pub bandwidth_g4_to_g2_gbps: Option<f64>,
/// Reasoning/thinking token configuration.
/// When set, the mocker wraps output in thinking boundary tokens.
#[builder(default = "None")]
pub reasoning: Option<ReasoningConfig>,
/// ZMQ port for publishing KV events in vLLM's native wire format.
/// When set, the scheduler publishes to a ZMQ PUB socket instead of directly to NATS.
/// A KvEventPublisher relay subscribes to this socket and forwards events to NATS.
#[builder(default = "None")]
pub zmq_kv_events_port: Option<u16>,
/// ZMQ ROUTER port for replay of buffered KV event batches.
/// When set alongside `zmq_kv_events_port`, the mocker binds a ROUTER socket
/// that streams back buffered batches by sequence number on request.
/// Port is offset by dp_rank (replay_port + dp_rank).
#[builder(default = "None")]
pub zmq_replay_port: Option<u16>,
/// Preemption mode for decode eviction under memory pressure.
/// Lifo (default) evicts the newest request; Fifo evicts the oldest.
#[builder(default)]
pub preemption_mode: PreemptionMode,
/// Optional replay-only override for the router queue policy.
#[builder(default = "None")]
pub router_queue_policy: Option<RouterQueuePolicy>,
/// SGLang-specific configuration. Only used when `engine_type == Sglang`.
#[builder(default = "None")]
pub sglang: Option<SglangArgs>,
/// TensorRT-LLM-specific configuration. Only used when `engine_type == Trtllm`.
#[builder(default = "None")]
pub trtllm: Option<TrtllmArgs>,
}
fn mock_engine_args_validation_error(code: &'static str, message: String) -> ValidationError {
let mut error = ValidationError::new(code);
error.message = Some(message.into());
error
}
fn validate_mock_engine_args(args: &MockEngineArgs) -> Result<(), ValidationError> {
if args.block_size == 0 {
return Err(mock_engine_args_validation_error(
"block_size_zero",
"block_size must be greater than 0".to_string(),
));
}
if args.num_g3_blocks.is_some() && args.num_g2_blocks.is_none() {
return Err(mock_engine_args_validation_error(
"g3_requires_g2",
"num_g3_blocks requires num_g2_blocks because mocker stages G3 through G2".to_string(),
));
}
if args.enable_g4_storage && args.num_g2_blocks.is_none() {
return Err(mock_engine_args_validation_error(
"g4_requires_g2",
"enable_g4_storage requires num_g2_blocks because mocker stages G4 through G2"
.to_string(),
));
}
if args.aic_nextn.is_some() && args.decode_speedup_ratio != 1.0 {
return Err(mock_engine_args_validation_error(
"mtp_decode_speedup_conflict",
format!(
"aic_nextn requires decode_speedup_ratio=1.0 because MTP output acceleration is modeled by burst sampling, got {}",
args.decode_speedup_ratio
),
));
}
if args.aic_nextn.is_none() && args.aic_nextn_accept_rates.is_some() {
return Err(mock_engine_args_validation_error(
"mtp_rates_without_nextn",
"aic_nextn_accept_rates requires aic_nextn".to_string(),
));
}
if let Some(policy) = args
.trtllm
.as_ref()
.and_then(|trtllm| trtllm.capacity_scheduler_policy.as_deref())
&& policy != "guaranteed_no_evict"
{
return Err(mock_engine_args_validation_error(
"trtllm_unsupported_capacity_scheduler_policy",
format!(
"engine_type=trtllm v1 supports only capacity_scheduler_policy='guaranteed_no_evict', got '{policy}'",
),
));
}
if args.engine_type != EngineType::Sglang {
return Ok(());
}
if let Some(page_size) = args.sglang.as_ref().and_then(|sglang| sglang.page_size)
&& args.block_size != page_size
{
return Err(mock_engine_args_validation_error(
"sglang_block_size_page_size_mismatch",
format!(
"engine_type=sglang requires block_size and sglang.page_size to match when both are set, got block_size={} and sglang.page_size={page_size}",
args.block_size,
),
));
}
if let Some(chunked_prefill_size) = args
.sglang
.as_ref()
.and_then(|sglang| sglang.chunked_prefill_size)
&& chunked_prefill_size % args.block_size != 0
{
return Err(mock_engine_args_validation_error(
"sglang_chunked_prefill_size_not_divisible_by_block_size",
format!(
"engine_type=sglang requires sglang.chunked_prefill_size to be divisible by block_size, got chunked_prefill_size={} and block_size={}",
chunked_prefill_size, args.block_size,
),
));
}
Ok(())
}
impl TryFrom<MockEngineArgsSerde> for MockEngineArgs {
type Error = String;
fn try_from(compat: MockEngineArgsSerde) -> Result<Self, Self::Error> {
let mut builder = Self::builder();
if let Some(engine_type) = compat.engine_type.into_non_null("engine_type")? {
builder = builder.engine_type(engine_type.parse()?);
}
if let Some(Some(num_gpu_blocks)) = compat.num_gpu_blocks.into_nullable() {
builder = builder.num_gpu_blocks(num_gpu_blocks);
}
if let Some(block_size) = compat.block_size.into_non_null("block_size")? {
builder = builder.block_size(block_size);
}
if let Some(max_num_seqs) = compat.max_num_seqs.into_nullable() {
builder = builder.max_num_seqs(max_num_seqs);
}
if let Some(max_num_batched_tokens) = compat.max_num_batched_tokens.into_nullable() {
builder = builder.max_num_batched_tokens(max_num_batched_tokens);
}
if let Some(enable_prefix_caching) = compat
.enable_prefix_caching
.into_non_null("enable_prefix_caching")?
{
builder = builder.enable_prefix_caching(enable_prefix_caching);
}
if let Some(enable_chunked_prefill) = compat
.enable_chunked_prefill
.into_non_null("enable_chunked_prefill")?
{
builder = builder.enable_chunked_prefill(enable_chunked_prefill);
}
if let Some(speedup_ratio) = compat.speedup_ratio.into_non_null("speedup_ratio")? {
builder = builder.speedup_ratio(speedup_ratio);
}
if let Some(decode_speedup_ratio) = compat
.decode_speedup_ratio
.into_non_null("decode_speedup_ratio")?
{
builder = builder.decode_speedup_ratio(decode_speedup_ratio);
}
if let Some(dp_size) = compat.dp_size.into_non_null("dp_size")? {
builder = builder.dp_size(dp_size);
}
if let Some(startup_time) = compat.startup_time.into_nullable() {
builder = builder.startup_time(startup_time);
}
let worker_type = if let Some(worker_type) =
compat.worker_type.into_non_null("worker_type")?
{
worker_type.parse()?
} else {
let is_prefill = compat
.is_prefill
.into_non_null("is_prefill")?
.unwrap_or(false);
let is_decode = compat
.is_decode
.into_non_null("is_decode")?
.unwrap_or(false);
match (is_prefill, is_decode) {
(false, false) => WorkerType::Aggregated,
(true, false) => WorkerType::Prefill,
(false, true) => WorkerType::Decode,
(true, true) => {
return Err(
"Invalid worker configuration: is_prefill and is_decode cannot both be true."
.to_string(),
);
}
}
};
builder = builder.worker_type(worker_type);
if let Some(planner_profile_data) = compat.planner_profile_data.into_nullable() {