{{ message }}
Repository navigation
Expand file tree
/
Copy pathlatency_system_design.rs
More file actions
1411 lines (1232 loc) · 46 KB
/
Copy pathlatency_system_design.rs
File metadata and controls
1411 lines (1232 loc) · 46 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
// ============================================================================
// LLM-Simulator: Enterprise-Grade Latency Modeling System
// ============================================================================
// Module: latency
// Purpose: Statistically accurate latency simulation for LLM inference
// Accuracy Target: Within 10% of real provider measurements
//
// Architecture:
// - latency::distributions - Statistical distribution implementations
// - latency::profiles - Provider-specific latency profiles
// - latency::streaming - Token-by-token timing simulation
// - latency::degradation - Load-dependent performance modeling
// - latency::validation - Measurement validation and calibration
// ============================================================================
use std::time::Duration;
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
// ============================================================================
// Core Latency Modeling Traits
// ============================================================================
/// Trait for sampling latency values from statistical distributions
///
/// All distributions must be:
/// - Thread-safe (Send + Sync)
/// - Deterministic given the same RNG state
/// - Capable of computing percentiles for validation
pub trait LatencyDistribution: Send + Sync {
/// Sample a single latency value from the distribution
fn sample(&self, rng: &mut DeterministicRng) -> Duration;
/// Compute the value at a given percentile (0.0 to 1.0)
/// Used for validation against real measurements
fn percentile(&self, p: f64) -> Duration;
/// Get mean latency for the distribution
fn mean(&self) -> Duration;
/// Get standard deviation
fn std_dev(&self) -> Duration;
/// Clone the distribution for multi-threaded use
fn clone_box(&self) -> Box<dyn LatencyDistribution>;
/// Validate distribution parameters are physically reasonable
fn validate(&self) -> Result<(), DistributionError>;
}
/// Deterministic random number generator for reproducible simulations
pub struct DeterministicRng {
state: u64,
seed: u64,
}
impl DeterministicRng {
pub fn new(seed: u64) -> Self {
Self { state: seed, seed }
}
pub fn reset(&mut self) {
self.state = self.seed;
}
/// Generate uniform random in [0, 1) using xorshift64
pub fn next_f64(&mut self) -> f64 {
self.state ^= self.state << 13;
self.state ^= self.state >> 7;
self.state ^= self.state << 17;
(self.state as f64) / (u64::MAX as f64)
}
/// Generate standard normal using Box-Muller transform
pub fn next_normal(&mut self) -> f64 {
let u1 = self.next_f64();
let u2 = self.next_f64();
(-2.0 * u1.ln()).sqrt() * (2.0 * std::f64::consts::PI * u2).cos()
}
pub fn get_seed(&self) -> u64 {
self.seed
}
}
// ============================================================================
// Statistical Distribution Implementations
// ============================================================================
/// Normal (Gaussian) distribution
/// Best for: Stable, symmetric latency patterns
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NormalDistribution {
mean_ms: f64,
std_dev_ms: f64,
min_clamp_ms: Option<f64>, // Prevent negative values
}
impl NormalDistribution {
pub fn new(mean: Duration, std_dev: Duration) -> Self {
Self {
mean_ms: mean.as_secs_f64() * 1000.0,
std_dev_ms: std_dev.as_secs_f64() * 1000.0,
min_clamp_ms: Some(0.0), // Default: clamp at 0
}
}
pub fn with_min_clamp(mut self, min_ms: f64) -> Self {
self.min_clamp_ms = Some(min_ms);
self
}
}
impl LatencyDistribution for NormalDistribution {
fn sample(&self, rng: &mut DeterministicRng) -> Duration {
let sample = self.mean_ms + self.std_dev_ms * rng.next_normal();
let clamped = if let Some(min) = self.min_clamp_ms {
sample.max(min)
} else {
sample
};
Duration::from_secs_f64(clamped / 1000.0)
}
fn percentile(&self, p: f64) -> Duration {
// Use inverse normal CDF approximation (Abramowitz and Stegun)
let z = inverse_normal_cdf(p);
let value_ms = self.mean_ms + self.std_dev_ms * z;
let clamped = if let Some(min) = self.min_clamp_ms {
value_ms.max(min)
} else {
value_ms
};
Duration::from_secs_f64(clamped / 1000.0)
}
fn mean(&self) -> Duration {
Duration::from_secs_f64(self.mean_ms / 1000.0)
}
fn std_dev(&self) -> Duration {
Duration::from_secs_f64(self.std_dev_ms / 1000.0)
}
fn clone_box(&self) -> Box<dyn LatencyDistribution> {
Box::new(self.clone())
}
fn validate(&self) -> Result<(), DistributionError> {
if self.mean_ms <= 0.0 {
return Err(DistributionError::InvalidParameter(
"mean must be positive".to_string()
));
}
if self.std_dev_ms < 0.0 {
return Err(DistributionError::InvalidParameter(
"std_dev must be non-negative".to_string()
));
}
Ok(())
}
}
/// Log-normal distribution
/// Best for: Right-skewed latency with occasional spikes (realistic for LLMs)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogNormalDistribution {
mu: f64, // Mean of log(X)
sigma: f64, // Std dev of log(X)
}
impl LogNormalDistribution {
/// Create from desired mean and std_dev of the *actual* latency (not log)
pub fn from_mean_std(mean: Duration, std_dev: Duration) -> Self {
let mean_ms = mean.as_secs_f64() * 1000.0;
let std_ms = std_dev.as_secs_f64() * 1000.0;
// Convert to log-space parameters
let variance = std_ms * std_ms;
let mean_sq = mean_ms * mean_ms;
let sigma_sq = (variance / mean_sq + 1.0).ln();
let mu = mean_ms.ln() - 0.5 * sigma_sq;
Self {
mu,
sigma: sigma_sq.sqrt(),
}
}
/// Create from p50 and p99 percentiles (common measurement format)
pub fn from_percentiles(p50: Duration, p99: Duration) -> Self {
let p50_ms = p50.as_secs_f64() * 1000.0;
let p99_ms = p99.as_secs_f64() * 1000.0;
// For log-normal: p50 = exp(mu), p99 = exp(mu + 2.326*sigma)
let mu = p50_ms.ln();
let sigma = (p99_ms.ln() - mu) / 2.326; // 2.326 is z-score for 99th percentile
Self { mu, sigma }
}
}
impl LatencyDistribution for LogNormalDistribution {
fn sample(&self, rng: &mut DeterministicRng) -> Duration {
let normal_sample = rng.next_normal();
let log_value = self.mu + self.sigma * normal_sample;
let value_ms = log_value.exp();
Duration::from_secs_f64(value_ms / 1000.0)
}
fn percentile(&self, p: f64) -> Duration {
let z = inverse_normal_cdf(p);
let log_value = self.mu + self.sigma * z;
let value_ms = log_value.exp();
Duration::from_secs_f64(value_ms / 1000.0)
}
fn mean(&self) -> Duration {
let mean_ms = (self.mu + 0.5 * self.sigma * self.sigma).exp();
Duration::from_secs_f64(mean_ms / 1000.0)
}
fn std_dev(&self) -> Duration {
let variance = (self.sigma * self.sigma).exp() - 1.0;
let mean_sq = (2.0 * self.mu + self.sigma * self.sigma).exp();
let std_ms = (variance * mean_sq).sqrt();
Duration::from_secs_f64(std_ms / 1000.0)
}
fn clone_box(&self) -> Box<dyn LatencyDistribution> {
Box::new(self.clone())
}
fn validate(&self) -> Result<(), DistributionError> {
if self.sigma < 0.0 {
return Err(DistributionError::InvalidParameter(
"sigma must be non-negative".to_string()
));
}
Ok(())
}
}
/// Exponential distribution
/// Best for: Modeling wait times and queue delays
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExponentialDistribution {
lambda: f64, // Rate parameter (1/mean)
}
impl ExponentialDistribution {
pub fn new(mean: Duration) -> Self {
let mean_ms = mean.as_secs_f64() * 1000.0;
Self {
lambda: 1.0 / mean_ms,
}
}
}
impl LatencyDistribution for ExponentialDistribution {
fn sample(&self, rng: &mut DeterministicRng) -> Duration {
let u = rng.next_f64();
let value_ms = -(1.0 - u).ln() / self.lambda;
Duration::from_secs_f64(value_ms / 1000.0)
}
fn percentile(&self, p: f64) -> Duration {
let value_ms = -(1.0 - p).ln() / self.lambda;
Duration::from_secs_f64(value_ms / 1000.0)
}
fn mean(&self) -> Duration {
Duration::from_secs_f64(1.0 / (self.lambda * 1000.0))
}
fn std_dev(&self) -> Duration {
Duration::from_secs_f64(1.0 / (self.lambda * 1000.0))
}
fn clone_box(&self) -> Box<dyn LatencyDistribution> {
Box::new(self.clone())
}
fn validate(&self) -> Result<(), DistributionError> {
if self.lambda <= 0.0 {
return Err(DistributionError::InvalidParameter(
"lambda must be positive".to_string()
));
}
Ok(())
}
}
/// Bimodal distribution (mixture of two normals)
/// Best for: Modeling cache hits/misses, fast path vs slow path
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BimodalDistribution {
fast_mode: NormalDistribution,
slow_mode: NormalDistribution,
fast_probability: f64, // Probability of sampling from fast mode
}
impl BimodalDistribution {
pub fn new(
fast_mean: Duration,
fast_std: Duration,
slow_mean: Duration,
slow_std: Duration,
fast_probability: f64,
) -> Self {
Self {
fast_mode: NormalDistribution::new(fast_mean, fast_std),
slow_mode: NormalDistribution::new(slow_mean, slow_std),
fast_probability: fast_probability.clamp(0.0, 1.0),
}
}
/// Create from cache scenario: hit_rate and two latency profiles
pub fn from_cache_scenario(
cache_hit_latency: Duration,
cache_miss_latency: Duration,
hit_rate: f64,
variance_factor: f64, // Fraction of mean as std dev
) -> Self {
let hit_std = Duration::from_secs_f64(
cache_hit_latency.as_secs_f64() * variance_factor
);
let miss_std = Duration::from_secs_f64(
cache_miss_latency.as_secs_f64() * variance_factor
);
Self::new(
cache_hit_latency,
hit_std,
cache_miss_latency,
miss_std,
hit_rate,
)
}
}
impl LatencyDistribution for BimodalDistribution {
fn sample(&self, rng: &mut DeterministicRng) -> Duration {
if rng.next_f64() < self.fast_probability {
self.fast_mode.sample(rng)
} else {
self.slow_mode.sample(rng)
}
}
fn percentile(&self, p: f64) -> Duration {
// For mixture distributions, percentile calculation is approximate
// We use a weighted combination (not mathematically exact but practical)
let fast_p = self.fast_mode.percentile(p);
let slow_p = self.slow_mode.percentile(p);
let fast_weight = self.fast_probability;
let slow_weight = 1.0 - self.fast_probability;
let weighted_ms = fast_p.as_secs_f64() * fast_weight
+ slow_p.as_secs_f64() * slow_weight;
Duration::from_secs_f64(weighted_ms)
}
fn mean(&self) -> Duration {
let fast_mean = self.fast_mode.mean().as_secs_f64();
let slow_mean = self.slow_mode.mean().as_secs_f64();
let weighted = fast_mean * self.fast_probability
+ slow_mean * (1.0 - self.fast_probability);
Duration::from_secs_f64(weighted)
}
fn std_dev(&self) -> Duration {
// Variance of mixture: E[Var] + Var[E]
let fast_var = self.fast_mode.std_dev().as_secs_f64().powi(2);
let slow_var = self.slow_mode.std_dev().as_secs_f64().powi(2);
let fast_mean = self.fast_mode.mean().as_secs_f64();
let slow_mean = self.slow_mode.mean().as_secs_f64();
let overall_mean = self.mean().as_secs_f64();
let e_var = fast_var * self.fast_probability
+ slow_var * (1.0 - self.fast_probability);
let var_e = (fast_mean - overall_mean).powi(2) * self.fast_probability
+ (slow_mean - overall_mean).powi(2) * (1.0 - self.fast_probability);
let total_variance = e_var + var_e;
Duration::from_secs_f64(total_variance.sqrt())
}
fn clone_box(&self) -> Box<dyn LatencyDistribution> {
Box::new(self.clone())
}
fn validate(&self) -> Result<(), DistributionError> {
self.fast_mode.validate()?;
self.slow_mode.validate()?;
if self.fast_probability < 0.0 || self.fast_probability > 1.0 {
return Err(DistributionError::InvalidParameter(
"fast_probability must be in [0, 1]".to_string()
));
}
Ok(())
}
}
/// Empirical distribution from measured data
/// Best for: Using real production measurements directly
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmpiricalDistribution {
samples_ms: Vec<f64>, // Sorted samples
interpolation: InterpolationMethod,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum InterpolationMethod {
Linear,
Nearest,
}
impl EmpiricalDistribution {
pub fn from_measurements(mut samples: Vec<Duration>) -> Self {
samples.sort();
let samples_ms: Vec<f64> = samples
.iter()
.map(|d| d.as_secs_f64() * 1000.0)
.collect();
Self {
samples_ms,
interpolation: InterpolationMethod::Linear,
}
}
pub fn with_interpolation(mut self, method: InterpolationMethod) -> Self {
self.interpolation = method;
self
}
}
impl LatencyDistribution for EmpiricalDistribution {
fn sample(&self, rng: &mut DeterministicRng) -> Duration {
if self.samples_ms.is_empty() {
return Duration::from_secs(0);
}
let idx = (rng.next_f64() * self.samples_ms.len() as f64) as usize;
let idx = idx.min(self.samples_ms.len() - 1);
Duration::from_secs_f64(self.samples_ms[idx] / 1000.0)
}
fn percentile(&self, p: f64) -> Duration {
if self.samples_ms.is_empty() {
return Duration::from_secs(0);
}
let position = p * (self.samples_ms.len() - 1) as f64;
let lower_idx = position.floor() as usize;
let upper_idx = (position.ceil() as usize).min(self.samples_ms.len() - 1);
let value_ms = match self.interpolation {
InterpolationMethod::Linear => {
if lower_idx == upper_idx {
self.samples_ms[lower_idx]
} else {
let fraction = position - lower_idx as f64;
self.samples_ms[lower_idx] * (1.0 - fraction)
+ self.samples_ms[upper_idx] * fraction
}
}
InterpolationMethod::Nearest => {
if position - lower_idx as f64 < 0.5 {
self.samples_ms[lower_idx]
} else {
self.samples_ms[upper_idx]
}
}
};
Duration::from_secs_f64(value_ms / 1000.0)
}
fn mean(&self) -> Duration {
if self.samples_ms.is_empty() {
return Duration::from_secs(0);
}
let sum: f64 = self.samples_ms.iter().sum();
let mean_ms = sum / self.samples_ms.len() as f64;
Duration::from_secs_f64(mean_ms / 1000.0)
}
fn std_dev(&self) -> Duration {
if self.samples_ms.len() < 2 {
return Duration::from_secs(0);
}
let mean_ms = self.mean().as_secs_f64() * 1000.0;
let variance: f64 = self.samples_ms
.iter()
.map(|&x| (x - mean_ms).powi(2))
.sum::<f64>() / (self.samples_ms.len() - 1) as f64;
Duration::from_secs_f64(variance.sqrt() / 1000.0)
}
fn clone_box(&self) -> Box<dyn LatencyDistribution> {
Box::new(self.clone())
}
fn validate(&self) -> Result<(), DistributionError> {
if self.samples_ms.is_empty() {
return Err(DistributionError::InvalidParameter(
"samples must not be empty".to_string()
));
}
Ok(())
}
}
// ============================================================================
// Latency Profile Configuration
// ============================================================================
/// Complete latency profile for a provider/model
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LatencyProfile {
pub name: String,
pub provider: String,
pub model: String,
/// Time to First Token distribution
pub ttft: DistributionConfig,
/// Inter-Token Latency distribution
pub itl: DistributionConfig,
/// Network jitter added to each token
pub network_jitter: Option<DistributionConfig>,
/// Load degradation curve
pub degradation: DegradationConfig,
/// Validation metrics from real measurements
pub validation_metrics: Option<ValidationMetrics>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DistributionConfig {
Normal {
mean_ms: f64,
std_dev_ms: f64,
},
LogNormal {
p50_ms: f64,
p99_ms: f64,
},
Exponential {
mean_ms: f64,
},
Bimodal {
fast_mean_ms: f64,
fast_std_ms: f64,
slow_mean_ms: f64,
slow_std_ms: f64,
fast_probability: f64,
},
Empirical {
samples_ms: Vec<f64>,
},
}
impl DistributionConfig {
pub fn build(&self) -> Box<dyn LatencyDistribution> {
match self {
DistributionConfig::Normal { mean_ms, std_dev_ms } => {
Box::new(NormalDistribution::new(
Duration::from_secs_f64(*mean_ms / 1000.0),
Duration::from_secs_f64(*std_dev_ms / 1000.0),
))
}
DistributionConfig::LogNormal { p50_ms, p99_ms } => {
Box::new(LogNormalDistribution::from_percentiles(
Duration::from_secs_f64(*p50_ms / 1000.0),
Duration::from_secs_f64(*p99_ms / 1000.0),
))
}
DistributionConfig::Exponential { mean_ms } => {
Box::new(ExponentialDistribution::new(
Duration::from_secs_f64(*mean_ms / 1000.0)
))
}
DistributionConfig::Bimodal {
fast_mean_ms,
fast_std_ms,
slow_mean_ms,
slow_std_ms,
fast_probability,
} => {
Box::new(BimodalDistribution::new(
Duration::from_secs_f64(*fast_mean_ms / 1000.0),
Duration::from_secs_f64(*fast_std_ms / 1000.0),
Duration::from_secs_f64(*slow_mean_ms / 1000.0),
Duration::from_secs_f64(*slow_std_ms / 1000.0),
*fast_probability,
))
}
DistributionConfig::Empirical { samples_ms } => {
let samples: Vec<Duration> = samples_ms
.iter()
.map(|&ms| Duration::from_secs_f64(ms / 1000.0))
.collect();
Box::new(EmpiricalDistribution::from_measurements(samples))
}
}
}
}
/// Validation metrics from real provider measurements
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationMetrics {
pub ttft_p50_ms: f64,
pub ttft_p99_ms: f64,
pub itl_mean_ms: f64,
pub itl_p99_ms: f64,
pub tokens_per_sec: f64,
pub measurement_date: String,
pub sample_size: usize,
}
// ============================================================================
// Load-Dependent Degradation
// ============================================================================
/// Models how latency degrades under load
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DegradationConfig {
pub model: DegradationModel,
pub baseline_qps: f64, // Queries per second at baseline performance
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DegradationModel {
/// No degradation (for testing)
None,
/// Linear increase: latency_multiplier = 1 + slope * (qps / baseline_qps)
Linear {
slope: f64,
},
/// Exponential: latency_multiplier = exp(alpha * (qps / baseline_qps))
Exponential {
alpha: f64,
},
/// Queueing theory (M/M/1): accounts for utilization
/// latency = base_latency / (1 - utilization)
MMOne {
service_rate: f64, // Max requests per second
},
/// Piecewise linear with multiple breakpoints
Piecewise {
breakpoints: Vec<(f64, f64)>, // (qps, multiplier) pairs
},
}
impl DegradationConfig {
pub fn compute_multiplier(&self, current_qps: f64) -> f64 {
match &self.model {
DegradationModel::None => 1.0,
DegradationModel::Linear { slope } => {
let load_ratio = current_qps / self.baseline_qps;
1.0 + slope * load_ratio
}
DegradationModel::Exponential { alpha } => {
let load_ratio = current_qps / self.baseline_qps;
(alpha * load_ratio).exp()
}
DegradationModel::MMOne { service_rate } => {
let utilization = (current_qps / service_rate).min(0.99); // Cap at 99%
1.0 / (1.0 - utilization)
}
DegradationModel::Piecewise { breakpoints } => {
if breakpoints.is_empty() {
return 1.0;
}
// Find the segment
for i in 0..breakpoints.len() - 1 {
let (qps1, mult1) = breakpoints[i];
let (qps2, mult2) = breakpoints[i + 1];
if current_qps >= qps1 && current_qps <= qps2 {
// Linear interpolation
let fraction = (current_qps - qps1) / (qps2 - qps1);
return mult1 + fraction * (mult2 - mult1);
}
}
// Below first or above last
if current_qps < breakpoints[0].0 {
breakpoints[0].1
} else {
breakpoints[breakpoints.len() - 1].1
}
}
}
}
}
// ============================================================================
// Streaming Token Timing
// ============================================================================
/// Simulates the timing of individual token arrivals in streaming mode
pub struct StreamingSimulator {
profile: LatencyProfile,
rng: DeterministicRng,
degradation_multiplier: f64,
}
impl StreamingSimulator {
pub fn new(profile: LatencyProfile, seed: u64) -> Self {
Self {
profile,
rng: DeterministicRng::new(seed),
degradation_multiplier: 1.0,
}
}
pub fn set_load(&mut self, current_qps: f64) {
self.degradation_multiplier = self.profile.degradation.compute_multiplier(current_qps);
}
/// Generate timing for a complete streaming response
pub fn generate_stream_timing(&mut self, num_tokens: usize) -> StreamTiming {
let mut timings = Vec::with_capacity(num_tokens + 1);
// Time to First Token
let ttft_dist = self.profile.ttft.build();
let mut ttft = ttft_dist.sample(&mut self.rng);
ttft = multiply_duration(ttft, self.degradation_multiplier);
timings.push(TokenTiming {
token_index: 0,
elapsed_since_start: ttft,
delta_from_previous: ttft,
});
// Inter-Token Latencies
let itl_dist = self.profile.itl.build();
let jitter_dist = self.profile.network_jitter.as_ref().map(|cfg| cfg.build());
let mut cumulative = ttft;
for i in 1..=num_tokens {
let mut itl = itl_dist.sample(&mut self.rng);
itl = multiply_duration(itl, self.degradation_multiplier);
// Add network jitter if configured
if let Some(ref jitter) = jitter_dist {
let jitter_amount = jitter.sample(&mut self.rng);
itl += jitter_amount;
}
cumulative += itl;
timings.push(TokenTiming {
token_index: i,
elapsed_since_start: cumulative,
delta_from_previous: itl,
});
}
StreamTiming {
timings,
total_duration: cumulative,
ttft,
mean_itl: self.compute_mean_itl(&timings),
}
}
fn compute_mean_itl(&self, timings: &[TokenTiming]) -> Duration {
if timings.len() <= 1 {
return Duration::from_secs(0);
}
let total: Duration = timings[1..]
.iter()
.map(|t| t.delta_from_previous)
.sum();
total / (timings.len() - 1) as u32
}
}
#[derive(Debug, Clone)]
pub struct StreamTiming {
pub timings: Vec<TokenTiming>,
pub total_duration: Duration,
pub ttft: Duration,
pub mean_itl: Duration,
}
#[derive(Debug, Clone)]
pub struct TokenTiming {
pub token_index: usize,
pub elapsed_since_start: Duration,
pub delta_from_previous: Duration,
}
impl StreamTiming {
/// Get the timestamp when a specific token should arrive
pub fn get_token_arrival(&self, token_index: usize) -> Option<Duration> {
self.timings.get(token_index).map(|t| t.elapsed_since_start)
}
/// Calculate tokens per second for this stream
pub fn tokens_per_second(&self) -> f64 {
if self.total_duration.as_secs_f64() == 0.0 {
return 0.0;
}
(self.timings.len() - 1) as f64 / self.total_duration.as_secs_f64()
}
/// Validate against expected metrics
pub fn validate(&self, expected: &ValidationMetrics) -> ValidationResult {
let mut errors = Vec::new();
// Check TTFT (allow 10% tolerance)
let ttft_ms = self.ttft.as_secs_f64() * 1000.0;
let ttft_error = (ttft_ms - expected.ttft_p50_ms).abs() / expected.ttft_p50_ms;
if ttft_error > 0.10 {
errors.push(format!(
"TTFT error: {:.1}% (expected {:.0}ms, got {:.0}ms)",
ttft_error * 100.0,
expected.ttft_p50_ms,
ttft_ms
));
}
// Check ITL
let itl_ms = self.mean_itl.as_secs_f64() * 1000.0;
let itl_error = (itl_ms - expected.itl_mean_ms).abs() / expected.itl_mean_ms;
if itl_error > 0.10 {
errors.push(format!(
"ITL error: {:.1}% (expected {:.0}ms, got {:.0}ms)",
itl_error * 100.0,
expected.itl_mean_ms,
itl_ms
));
}
// Check tokens/sec
let tps = self.tokens_per_second();
let tps_error = (tps - expected.tokens_per_sec).abs() / expected.tokens_per_sec;
if tps_error > 0.10 {
errors.push(format!(
"Tokens/sec error: {:.1}% (expected {:.1}, got {:.1})",
tps_error * 100.0,
expected.tokens_per_sec,
tps
));
}
ValidationResult {
passed: errors.is_empty(),
errors,
}
}
}
#[derive(Debug)]
pub struct ValidationResult {
pub passed: bool,
pub errors: Vec<String>,
}
// ============================================================================
// Complete Latency Model (Main API)
// ============================================================================
/// High-level latency model that orchestrates all components
pub struct LatencyModel {
profiles: HashMap<String, LatencyProfile>,
current_load_qps: f64,
seed: u64,
}
impl LatencyModel {
pub fn new(seed: u64) -> Self {
Self {
profiles: HashMap::new(),
current_load_qps: 0.0,
seed,
}
}
/// Load built-in provider profiles
pub fn with_builtin_profiles(mut self) -> Self {
self.profiles.insert(
"gpt-4-turbo".to_string(),
Self::gpt4_turbo_profile(),
);
self.profiles.insert(
"gpt-3.5-turbo".to_string(),
Self::gpt35_turbo_profile(),
);
self.profiles.insert(
"claude-3-opus".to_string(),
Self::claude3_opus_profile(),
);
self.profiles.insert(
"claude-3-sonnet".to_string(),
Self::claude3_sonnet_profile(),
);
self.profiles.insert(
"gemini-1.5-pro".to_string(),
Self::gemini15_pro_profile(),
);
self
}
pub fn add_profile(&mut self, key: String, profile: LatencyProfile) {
self.profiles.insert(key, profile);
}
pub fn set_load(&mut self, qps: f64) {
self.current_load_qps = qps;
}
/// Create a streaming simulator for a specific profile
pub fn create_simulator(&self, profile_key: &str) -> Result<StreamingSimulator, ModelError> {
let profile = self.profiles
.get(profile_key)
.ok_or_else(|| ModelError::ProfileNotFound(profile_key.to_string()))?
.clone();
let mut simulator = StreamingSimulator::new(profile, self.seed);
simulator.set_load(self.current_load_qps);
Ok(simulator)
}
/// Simulate a single request end-to-end
pub fn simulate_request(
&self,
profile_key: &str,
num_tokens: usize,
) -> Result<StreamTiming, ModelError> {
let mut simulator = self.create_simulator(profile_key)?;
Ok(simulator.generate_stream_timing(num_tokens))
}
/// Batch validation across many requests
pub fn validate_profile(
&self,
profile_key: &str,
num_simulations: usize,
tokens_per_request: usize,
) -> Result<ProfileValidationReport, ModelError> {
let profile = self.profiles
.get(profile_key)
.ok_or_else(|| ModelError::ProfileNotFound(profile_key.to_string()))?;
let validation_metrics = profile.validation_metrics.as_ref()
.ok_or(ModelError::NoValidationMetrics)?;
let mut simulator = self.create_simulator(profile_key)?;
let mut ttft_samples = Vec::with_capacity(num_simulations);
let mut itl_samples = Vec::with_capacity(num_simulations);
let mut tps_samples = Vec::with_capacity(num_simulations);
for _ in 0..num_simulations {
let timing = simulator.generate_stream_timing(tokens_per_request);
ttft_samples.push(timing.ttft.as_secs_f64() * 1000.0);
itl_samples.push(timing.mean_itl.as_secs_f64() * 1000.0);
tps_samples.push(timing.tokens_per_second());
}
// Sort for percentile calculations
ttft_samples.sort_by(|a, b| a.partial_cmp(b).unwrap());
itl_samples.sort_by(|a, b| a.partial_cmp(b).unwrap());
let ttft_p50 = percentile_sorted(&ttft_samples, 0.50);
let ttft_p99 = percentile_sorted(&ttft_samples, 0.99);
let itl_mean = itl_samples.iter().sum::<f64>() / itl_samples.len() as f64;
let tps_mean = tps_samples.iter().sum::<f64>() / tps_samples.len() as f64;
// Compute errors
let ttft_p50_error = ((ttft_p50 - validation_metrics.ttft_p50_ms).abs()
/ validation_metrics.ttft_p50_ms) * 100.0;
let ttft_p99_error = ((ttft_p99 - validation_metrics.ttft_p99_ms).abs()
/ validation_metrics.ttft_p99_ms) * 100.0;
let itl_error = ((itl_mean - validation_metrics.itl_mean_ms).abs()
/ validation_metrics.itl_mean_ms) * 100.0;
let tps_error = ((tps_mean - validation_metrics.tokens_per_sec).abs()
/ validation_metrics.tokens_per_sec) * 100.0;
let all_within_tolerance = ttft_p50_error <= 10.0
&& ttft_p99_error <= 10.0
&& itl_error <= 10.0
You can’t perform that action at this time.
