forked from kubernetes-sigs/gateway-api-inference-extension
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_dual_server_client.py
More file actions
2316 lines (1886 loc) · 90.8 KB
/
test_dual_server_client.py
File metadata and controls
2316 lines (1886 loc) · 90.8 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
# Copyright 2025 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import time
import asyncio
import aiohttp
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from collections import defaultdict
import random
import requests
import pytest
import joblib
import numpy as np
import tempfile
# Base URLs for the dual-server architecture
PREDICTION_URL = os.getenv("PREDICTION_SERVER_URL", "http://<PREDICTION_IP>:80") # Update this
TRAINING_URL = os.getenv("TRAINING_SERVER_URL", "http://<TRAINING_IP>:8080") # Update this
TARGET_QPS = float(os.getenv("TARGET_QPS", 1000)) # Update this
TARGET_QPS_LARGE_BATCH = float(os.getenv("TARGET_QPS_LARGE_BATCH", 100)) # Update this
# Helper to wait until the servers are ready
def wait_for_ready(url: str, timeout: float = 30.0, interval: float = 1.0):
start = time.time()
while True:
try:
r = requests.get(f"{url}/readyz", timeout=2.0)
if r.status_code == 200:
return
except requests.RequestException:
pass
if time.time() - start > timeout:
pytest.skip(f"Server at {url} did not become ready in time")
time.sleep(interval)
@pytest.fixture(scope="module", autouse=True)
def ensure_servers_ready():
"""Wait for both servers to be ready before running tests."""
print("Waiting for prediction server...")
wait_for_ready(PREDICTION_URL)
print("Waiting for training server...")
wait_for_ready(TRAINING_URL)
def test_prediction_server_healthz():
"""Test prediction server health endpoint."""
r = requests.get(f"{PREDICTION_URL}/healthz")
assert r.status_code == 200
assert r.json().get("status") == "ok"
def test_training_server_healthz():
"""Test training server health endpoint."""
r = requests.get(f"{TRAINING_URL}/healthz")
assert r.status_code == 200
assert r.json().get("status") == "ok"
def test_prediction_server_readyz():
"""Test prediction server readiness."""
r = requests.get(f"{PREDICTION_URL}/readyz")
assert r.status_code == 200
assert r.json().get("status") == "ready"
def test_training_server_readyz():
"""Test training server readiness."""
r = requests.get(f"{TRAINING_URL}/readyz")
assert r.status_code == 200
assert r.json().get("status") == "ready"
def test_prediction_server_status():
"""Test prediction server status endpoint."""
r = requests.get(f"{PREDICTION_URL}/status")
assert r.status_code == 200
data = r.json()
assert "is_ready" in data
assert "model_type" in data
assert "models_exist" in data
assert "quantile" in data
assert "objective_type" in data
assert data["model_type"] in ["bayesian_ridge", "xgboost", "lightgbm"]
assert data["objective_type"] in ["quantile", "mean"]
assert 0 < data["quantile"] <= 1.0
assert "ensemble_active" in data
print(f"Prediction server using model type: {data['model_type']}")
print(f"Objective type: {data['objective_type']}")
print(f"Quantile: {data['quantile']}")
print(f"Models ready: {data['is_ready']}")
print(f"Models exist: {data['models_exist']}")
print(f"Ensemble active: {data['ensemble_active']}")
def test_training_server_model_info():
"""Test training server model info endpoint."""
r = requests.get(f"{TRAINING_URL}/model/download/info")
assert r.status_code == 200
data = r.json()
assert "model_type" in data
assert "available_endpoints" in data
assert data["model_type"] in ["bayesian_ridge", "xgboost", "lightgbm"]
print(f"Training server using model type: {data['model_type']}")
def test_training_server_models_list():
"""Test training server models list endpoint."""
r = requests.get(f"{TRAINING_URL}/models/list")
assert r.status_code == 200
data = r.json()
assert "models" in data
assert "model_type" in data
assert "server_time" in data
models = data["models"]
expected_models = ["ttft", "tpot"]
if data["model_type"] == "bayesian_ridge":
expected_models.extend(["ttft_scaler", "tpot_scaler"])
for model_name in expected_models:
assert model_name in models, f"Model {model_name} should be listed"
print(f"Model {model_name}: exists={models[model_name]['exists']}, size={models[model_name]['size_bytes']} bytes")
# Gated ensemble models should always be listed (may not exist yet)
for gated_name in ["ttft_gated", "tpot_gated"]:
assert gated_name in models, f"Gated model {gated_name} should be listed"
print(f"Model {gated_name}: exists={models[gated_name]['exists']}, size={models[gated_name]['size_bytes']} bytes")
def test_model_download_from_training_server():
"""Test downloading models from training server."""
# First check what models are available
models_r = requests.get(f"{TRAINING_URL}/models/list")
models_data = models_r.json()
for model_name in ["ttft", "tpot"]:
if models_data["models"][model_name]["exists"]:
# Test model info endpoint
info_r = requests.get(f"{TRAINING_URL}/model/{model_name}/info")
assert info_r.status_code == 200
info_data = info_r.json()
assert info_data["exists"] == True
assert info_data["size_bytes"] > 0
# Test model download with retry and streaming
max_retries = 3
for attempt in range(max_retries):
try:
download_r = requests.get(
f"{TRAINING_URL}/model/{model_name}/download",
timeout=30,
stream=True # Use streaming to handle large files better
)
if download_r.status_code == 200:
# Read content in chunks to avoid memory issues
content_length = 0
for chunk in download_r.iter_content(chunk_size=8192):
content_length += len(chunk)
assert content_length > 0, f"Downloaded {model_name} model is empty"
print(f"Successfully downloaded {model_name} model ({content_length} bytes)")
break
except requests.exceptions.ChunkedEncodingError as e:
print(f"Download attempt {attempt + 1}/{max_retries} failed for {model_name}: {e}")
if attempt == max_retries - 1:
print(f"⚠️ Model download test skipped for {model_name} due to connection issues")
# Don't fail the test - this might be a network/server issue
continue
time.sleep(2) # Wait before retry
def test_lightgbm_endpoints_on_training_server():
"""Test LightGBM endpoints on training server if LightGBM is being used."""
model_info_r = requests.get(f"{TRAINING_URL}/model/download/info")
model_type = model_info_r.json().get("model_type")
if model_type != "lightgbm":
print("Skipping LightGBM endpoint tests - not using LightGBM model")
return
print("Testing LightGBM endpoints on training server...")
# Test TTFT model text format
ttft_txt_response = requests.get(f"{TRAINING_URL}/model/ttft/lgb/txt")
if ttft_txt_response.status_code == 200:
print("✓ TTFT LightGBM text model available")
assert ttft_txt_response.headers.get('content-type') == 'text/plain; charset=utf-8'
else:
print(f"TTFT LightGBM text model not yet available (status: {ttft_txt_response.status_code})")
# Test TPOT model text format
tpot_txt_response = requests.get(f"{TRAINING_URL}/model/tpot/lgb/txt")
if tpot_txt_response.status_code == 200:
print("✓ TPOT LightGBM text model available")
assert tpot_txt_response.headers.get('content-type') == 'text/plain; charset=utf-8'
else:
print(f"TPOT LightGBM text model not yet available (status: {tpot_txt_response.status_code})")
# Test TTFT feature importances
ttft_imp_response = requests.get(f"{TRAINING_URL}/model/ttft/lgb/importances")
if ttft_imp_response.status_code == 200:
ttft_importances = ttft_imp_response.json()
assert isinstance(ttft_importances, dict), "TTFT importances should be a dict"
# Check for expected features including prefix_cache_score
expected_features = ["kv_cache_percentage", "input_token_length", "num_request_waiting",
"num_request_running", "prefix_cache_score"]
for feature in expected_features:
assert feature in ttft_importances, f"Missing feature importance: {feature}"
print(f"✓ TTFT LightGBM importances available with {len(ttft_importances)} features")
else:
print(f"TTFT LightGBM importances not yet available (status: {ttft_imp_response.status_code})")
# Test TPOT feature importances
tpot_imp_response = requests.get(f"{TRAINING_URL}/model/tpot/lgb/importances")
if tpot_imp_response.status_code == 200:
tpot_importances = tpot_imp_response.json()
assert isinstance(tpot_importances, dict), "TPOT importances should be a dict"
# Check for expected features
expected_features = ["kv_cache_percentage", "input_token_length", "num_request_waiting",
"num_request_running", "num_tokens_generated"]
for feature in expected_features:
assert feature in tpot_importances, f"Missing feature importance: {feature}"
print(f"✓ TPOT LightGBM importances available with {len(tpot_importances)} features")
else:
print(f"TPOT LightGBM importances not yet available (status: {tpot_imp_response.status_code})")
def test_add_training_data_to_training_server():
"""
Send training data to the training server.
The prediction server should eventually sync these models.
"""
entries = []
# Generate 50 training samples with known pattern
for i in range(1, 51):
waiting = i % 10 # Include 0 to provide noqueue training data for ensemble
tokens = max(waiting, 1)
inp_len = 10 * i
kv = 0.5
running = 1
prefix_cache = random.uniform(0.1, 0.9)
prefill_tif = random.randint(0, 10000)
decode_tif = random.randint(0, 3000)
entries.append({
"kv_cache_percentage": kv,
"input_token_length": inp_len,
"num_request_waiting": waiting,
"num_request_running": running,
"actual_ttft_ms": (inp_len*2.0 + waiting*3.0 + running*4.0 + kv*50.0 + prefix_cache*30.0 + prefill_tif*0.05) + 95,
"actual_tpot_ms": (kv*100.0 + inp_len*0.5 + tokens*1.0 + running*5.0 + decode_tif*0.02) + 9,
"num_tokens_generated": tokens,
"prefix_cache_score": prefix_cache,
"prefill_tokens_in_flight": prefill_tif,
"decode_tokens_in_flight": decode_tif,
})
payload = {"entries": entries}
r = requests.post(f"{TRAINING_URL}/add_training_data_bulk", json=payload)
assert r.status_code == 202, f"Expected 202, got {r.status_code}"
assert r.json().get("message") == "Accepted 50 training samples."
print("Successfully sent training data to training server")
def test_prediction_server_model_sync():
"""
Test that the prediction server can sync models from the training server.
This may take some time as models need to be downloaded.
"""
# Trigger a manual reload on the prediction server
reload_r = requests.post(f"{PREDICTION_URL}/reload")
assert reload_r.status_code == 200
reload_data = reload_r.json()
print(f"Model reload result: synced={reload_data.get('synced')}, loaded={reload_data.get('loaded')}")
# Check status after reload
status_r = requests.get(f"{PREDICTION_URL}/status")
status_data = status_r.json()
# Wait a bit for models to sync if they're not ready yet
max_wait = 60 # 60 seconds max wait
start_time = time.time()
while not status_data.get("is_ready") and (time.time() - start_time) < max_wait:
print("Waiting for prediction server models to be ready...")
time.sleep(5)
# Try reload again
requests.post(f"{PREDICTION_URL}/reload")
status_r = requests.get(f"{PREDICTION_URL}/status")
status_data = status_r.json()
assert status_data.get("is_ready"), f"Prediction server models not ready after {max_wait}s"
print("Prediction server models are ready!")
def test_prediction_via_prediction_server():
"""Test making predictions via the prediction server."""
features = {
"kv_cache_percentage": 0.5,
"input_token_length": 200,
"num_request_waiting": 4,
"num_request_running": 1,
"num_tokens_generated": 4,
"prefix_cache_score": 0.7, # Added prefix_cache_score field
}
r = requests.post(f"{PREDICTION_URL}/predict", json=features)
assert r.status_code == 200
data = r.json()
required_fields = [
"ttft_ms", "tpot_ms",
"predicted_at", "model_type", "objective_type", "last_model_load"
]
for field in required_fields:
assert field in data, f"Missing required field: {field}"
# Verify predictions are reasonable
assert data["ttft_ms"] > 0
assert data["tpot_ms"] > 0
#assert data["ttft_uncertainty"] >= 0
#assert data["tpot_uncertainty"] >= 0
print(f"Prediction successful: TTFT={data['ttft_ms']:.2f}ms, TPOT={data['tpot_ms']:.2f}ms")
print(f"Model type: {data['model_type']}, Objective: {data['objective_type']}")
def test_bulk_prediction_strict():
"""Test bulk predictions with strict error handling."""
print("Testing bulk prediction strict endpoint...")
requests_data = [
{
"kv_cache_percentage": 0.5,
"input_token_length": 200,
"num_request_waiting": 4,
"num_request_running": 1,
"num_tokens_generated": 4,
"prefix_cache_score": 0.7,
},
{
"kv_cache_percentage": 0.3,
"input_token_length": 150,
"num_request_waiting": 2,
"num_request_running": 1,
"num_tokens_generated": 5,
"prefix_cache_score": 0.5,
}
]
bulk_request = {"requests": requests_data}
r = requests.post(f"{PREDICTION_URL}/predict/bulk/strict", json=bulk_request)
assert r.status_code == 200
data = r.json()
# Check bulk response structure
assert "predictions" in data
assert "total_requests" in data
assert "successful_predictions" in data
assert "failed_predictions" in data
assert "processing_time_ms" in data
assert len(data["predictions"]) == 2
assert data["total_requests"] == 2
assert data["successful_predictions"] == 2
assert data["failed_predictions"] == 0
# Check individual prediction structure
for prediction in data["predictions"]:
assert "ttft_ms" in prediction
assert "tpot_ms" in prediction
#assert "ttft_uncertainty" in prediction
#assert "tpot_uncertainty" in prediction
#assert "ttft_prediction_bounds" in prediction
#assert "tpot_prediction_bounds" in prediction
assert "predicted_at" in prediction
assert "model_type" in prediction
assert "objective_type" in prediction
assert "quantile" in prediction
print("✓ Bulk prediction strict endpoint test passed")
def test_bulk_prediction_with_validation_errors():
"""Test that bulk predictions fail completely when any request has validation errors."""
print("Testing bulk prediction validation error handling...")
requests_data = [
# Valid request
{
"kv_cache_percentage": 0.5,
"input_token_length": 200,
"num_request_waiting": 4,
"num_request_running": 1,
"num_tokens_generated": 4,
"prefix_cache_score": 0.7,
},
# Invalid request (missing prefix_cache_score)
{
"kv_cache_percentage": 0.3,
"input_token_length": 150,
"num_request_waiting": 2,
"num_request_running": 1,
"num_tokens_generated": 5,
# Missing prefix_cache_score
}
]
bulk_request = {"requests": requests_data}
r = requests.post(f"{PREDICTION_URL}/predict/bulk", json=bulk_request)
assert r.status_code == 422 # Validation error expected
# Check that error response contains validation details
error_data = r.json()
assert "detail" in error_data
print("✓ Bulk prediction correctly failed when any request had validation errors")
def test_bulk_prediction_all_valid():
"""Test bulk predictions when all requests are valid."""
print("Testing bulk prediction with all valid requests...")
requests_data = [
{
"kv_cache_percentage": 0.5,
"input_token_length": 200,
"num_request_waiting": 4,
"num_request_running": 1,
"num_tokens_generated": 4,
"prefix_cache_score": 0.7,
},
{
"kv_cache_percentage": 0.3,
"input_token_length": 150,
"num_request_waiting": 2,
"num_request_running": 1,
"num_tokens_generated": 5,
"prefix_cache_score": 0.5, # Include required field
}
]
bulk_request = {"requests": requests_data}
r = requests.post(f"{PREDICTION_URL}/predict/bulk", json=bulk_request)
assert r.status_code == 200
data = r.json()
assert data["total_requests"] == 2
assert data["successful_predictions"] == 2
assert data["failed_predictions"] == 0
print("✓ Bulk prediction succeeded with all valid requests")
def test_prediction_missing_prefix_cache_score():
"""Test that predictions fail when prefix_cache_score is missing."""
features = {
"kv_cache_percentage": 0.5,
"input_token_length": 200,
"num_request_waiting": 4,
"num_request_running": 1,
"num_tokens_generated": 4,
# Missing prefix_cache_score
}
r = requests.post(f"{PREDICTION_URL}/predict", json=features)
assert r.status_code == 422 # Should fail validation
print("✓ Prediction correctly failed when prefix_cache_score was missing")
def test_prediction_with_pod_type_prefill():
"""Test predictions with pod_type='prefill' parameter."""
print("Testing prediction with pod_type='prefill'...")
features = {
"kv_cache_percentage": 0.5,
"input_token_length": 200,
"num_request_waiting": 4,
"num_request_running": 1,
"num_tokens_generated": 0, # Prefill doesn't generate tokens
"prefix_cache_score": 0.7,
"pod_type": "prefill",
}
r = requests.post(f"{PREDICTION_URL}/predict", json=features)
assert r.status_code == 200
data = r.json()
assert "ttft_ms" in data
assert "tpot_ms" in data
assert data["ttft_ms"] > 0
assert data["tpot_ms"] >= 0 # Non-negative
print(f"✓ Prefill prediction: TTFT={data['ttft_ms']:.2f}ms, TPOT={data['tpot_ms']:.2f}ms")
def test_prediction_with_pod_type_decode():
"""Test predictions with pod_type='decode' parameter."""
print("Testing prediction with pod_type='decode'...")
features = {
"kv_cache_percentage": 0.5,
"input_token_length": 200,
"num_request_waiting": 4,
"num_request_running": 1,
"num_tokens_generated": 10,
"prefix_cache_score": 0.7,
"pod_type": "decode",
}
r = requests.post(f"{PREDICTION_URL}/predict", json=features)
assert r.status_code == 200
data = r.json()
assert "ttft_ms" in data
assert "tpot_ms" in data
assert data["ttft_ms"] > 0
assert data["tpot_ms"] >= 0 # Non-negative
print(f"✓ Decode prediction: TTFT={data['ttft_ms']:.2f}ms, TPOT={data['tpot_ms']:.2f}ms")
def test_bulk_prediction_with_pod_type():
"""Test bulk predictions with mixed pod types."""
print("Testing bulk prediction with pod_type...")
requests_data = [
# Prefill pod request
{
"kv_cache_percentage": 0.5,
"input_token_length": 200,
"num_request_waiting": 4,
"num_request_running": 1,
"num_tokens_generated": 0,
"prefix_cache_score": 0.7,
"pod_type": "prefill",
},
# Decode pod request
{
"kv_cache_percentage": 0.3,
"input_token_length": 150,
"num_request_waiting": 2,
"num_request_running": 1,
"num_tokens_generated": 10,
"prefix_cache_score": 0.5,
"pod_type": "decode",
},
# Legacy request (no pod_type)
{
"kv_cache_percentage": 0.6,
"input_token_length": 300,
"num_request_waiting": 3,
"num_request_running": 2,
"num_tokens_generated": 5,
"prefix_cache_score": 0.8,
}
]
bulk_request = {"requests": requests_data}
r = requests.post(f"{PREDICTION_URL}/predict/bulk/strict", json=bulk_request)
assert r.status_code == 200
data = r.json()
assert data["total_requests"] == 3
assert data["successful_predictions"] == 3
assert data["failed_predictions"] == 0
predictions = data["predictions"]
# Check prefill prediction (index 0)
prefill_pred = predictions[0]
assert prefill_pred["ttft_ms"] > 0
assert prefill_pred["tpot_ms"] >= 0 # Relaxed constraint for prefill
print(f" Prefill: TTFT={prefill_pred['ttft_ms']:.2f}ms, TPOT={prefill_pred['tpot_ms']:.2f}ms")
# Check decode prediction (index 1)
decode_pred = predictions[1]
assert decode_pred["ttft_ms"] > 0
assert decode_pred["tpot_ms"] > 0 # Should be positive for decode
print(f" Decode: TTFT={decode_pred['ttft_ms']:.2f}ms, TPOT={decode_pred['tpot_ms']:.2f}ms")
# Check legacy prediction (index 2)
legacy_pred = predictions[2]
assert legacy_pred["ttft_ms"] > 0
assert legacy_pred["tpot_ms"] > 0
print(f" Legacy: TTFT={legacy_pred['ttft_ms']:.2f}ms, TPOT={legacy_pred['tpot_ms']:.2f}ms")
print("✓ Bulk prediction with mixed pod types passed")
def test_training_data_with_pod_type():
"""Test that training server accepts pod_type in training data."""
print("Testing training data with pod_type...")
# Generate training samples with pod_type
prefill_entries = []
decode_entries = []
# Prefill training samples (TPOT should be 0)
for i in range(10):
prefill_entries.append({
"kv_cache_percentage": 0.5,
"input_token_length": 200 + i * 10,
"num_request_waiting": i % 5,
"num_request_running": 1,
"actual_ttft_ms": 100.0 + i * 5,
"actual_tpot_ms": 0.0, # Prefill doesn't produce tokens
"num_tokens_generated": 0,
"prefix_cache_score": 0.7,
"pod_type": "prefill",
})
# Decode training samples (both TTFT and TPOT)
for i in range(10):
decode_entries.append({
"kv_cache_percentage": 0.5,
"input_token_length": 200 + i * 10,
"num_request_waiting": i % 5,
"num_request_running": 1,
"actual_ttft_ms": 100.0 + i * 5,
"actual_tpot_ms": 10.0 + i * 2,
"num_tokens_generated": 5 + i,
"prefix_cache_score": 0.7,
"pod_type": "decode",
})
all_entries = prefill_entries + decode_entries
payload = {"entries": all_entries}
r = requests.post(f"{TRAINING_URL}/add_training_data_bulk", json=payload)
assert r.status_code == 202
assert r.json().get("message") == f"Accepted {len(all_entries)} training samples."
print(f"✓ Successfully sent {len(all_entries)} training samples with pod_type")
def test_prediction_noqueue_routing():
"""Test that predictions with num_request_waiting=0 route through noqueue ensemble model."""
print("Testing noqueue prediction routing...")
features_noqueue = {
"kv_cache_percentage": 0.5,
"input_token_length": 200,
"num_request_waiting": 0,
"num_request_running": 1,
"num_tokens_generated": 4,
"prefix_cache_score": 0.7,
}
features_queued = {
"kv_cache_percentage": 0.5,
"input_token_length": 200,
"num_request_waiting": 5,
"num_request_running": 1,
"num_tokens_generated": 4,
"prefix_cache_score": 0.7,
}
r_noqueue = requests.post(f"{PREDICTION_URL}/predict", json=features_noqueue)
assert r_noqueue.status_code == 200
noqueue_data = r_noqueue.json()
assert noqueue_data["ttft_ms"] > 0
assert noqueue_data["tpot_ms"] > 0
print(f" Noqueue prediction: TTFT={noqueue_data['ttft_ms']:.2f}ms, TPOT={noqueue_data['tpot_ms']:.2f}ms")
r_queued = requests.post(f"{PREDICTION_URL}/predict", json=features_queued)
assert r_queued.status_code == 200
queued_data = r_queued.json()
assert queued_data["ttft_ms"] > 0
assert queued_data["tpot_ms"] > 0
print(f" Queued prediction: TTFT={queued_data['ttft_ms']:.2f}ms, TPOT={queued_data['tpot_ms']:.2f}ms")
# Check ensemble status
status_r = requests.get(f"{PREDICTION_URL}/status")
ensemble_active = status_r.json().get("ensemble_active", False)
print(f" Ensemble active: {ensemble_active}")
print(" Noqueue and queued predictions both succeeded")
def test_bulk_prediction_mixed_queue():
"""Test bulk predictions with a mix of noqueue and queued requests."""
print("Testing bulk prediction with mixed queue states...")
requests_data = [
# Noqueue request (num_request_waiting=0)
{
"kv_cache_percentage": 0.5,
"input_token_length": 200,
"num_request_waiting": 0,
"num_request_running": 1,
"num_tokens_generated": 4,
"prefix_cache_score": 0.7,
},
# Queued request (num_request_waiting>0)
{
"kv_cache_percentage": 0.3,
"input_token_length": 150,
"num_request_waiting": 5,
"num_request_running": 1,
"num_tokens_generated": 5,
"prefix_cache_score": 0.5,
},
# Another noqueue request
{
"kv_cache_percentage": 0.6,
"input_token_length": 300,
"num_request_waiting": 0,
"num_request_running": 2,
"num_tokens_generated": 3,
"prefix_cache_score": 0.8,
}
]
bulk_request = {"requests": requests_data}
r = requests.post(f"{PREDICTION_URL}/predict/bulk/strict", json=bulk_request)
assert r.status_code == 200
data = r.json()
assert data["total_requests"] == 3
assert data["successful_predictions"] == 3
assert data["failed_predictions"] == 0
for i, pred in enumerate(data["predictions"]):
assert pred["ttft_ms"] > 0
assert pred["tpot_ms"] > 0
queue_state = "noqueue" if requests_data[i]["num_request_waiting"] == 0 else "queued"
print(f" Request {i+1} ({queue_state}): TTFT={pred['ttft_ms']:.2f}ms, TPOT={pred['tpot_ms']:.2f}ms")
print(" Bulk prediction with mixed queue states passed")
def test_invalid_pod_type():
"""Test that invalid pod_type values are handled correctly."""
print("Testing invalid pod_type handling...")
features = {
"kv_cache_percentage": 0.5,
"input_token_length": 200,
"num_request_waiting": 4,
"num_request_running": 1,
"num_tokens_generated": 10,
"prefix_cache_score": 0.7,
"pod_type": "invalid_type", # Invalid pod type
}
r = requests.post(f"{PREDICTION_URL}/predict", json=features)
# Should either accept it (treating as legacy) or reject with validation error
if r.status_code == 422:
print("✓ Invalid pod_type rejected with validation error (strict validation)")
elif r.status_code == 200:
data = r.json()
# If accepted, should still return valid predictions
assert data["ttft_ms"] > 0
assert data["tpot_ms"] >= 0
print("✓ Invalid pod_type accepted with fallback behavior (permissive validation)")
else:
assert False, f"Unexpected status code {r.status_code} for invalid pod_type"
def test_prediction_with_token_in_flight_features():
"""Test that predictions succeed when prefill/decode_tokens_in_flight are provided."""
print("Testing prediction with token-in-flight features...")
features = {
"kv_cache_percentage": 0.5,
"input_token_length": 200,
"num_request_waiting": 4,
"num_request_running": 1,
"num_tokens_generated": 4,
"prefix_cache_score": 0.7,
"prefill_tokens_in_flight": 5000,
"decode_tokens_in_flight": 1200,
}
r = requests.post(f"{PREDICTION_URL}/predict", json=features)
assert r.status_code == 200, f"Expected 200, got {r.status_code}: {r.text}"
data = r.json()
assert "ttft_ms" in data
assert "tpot_ms" in data
assert data["ttft_ms"] > 0
assert data["tpot_ms"] > 0
print(f"✓ Prediction with TIF features: TTFT={data['ttft_ms']:.2f}ms, TPOT={data['tpot_ms']:.2f}ms")
def test_bulk_prediction_with_token_in_flight_features():
"""Test bulk predictions with prefill/decode_tokens_in_flight included."""
print("Testing bulk prediction with token-in-flight features...")
requests_data = [
{
"kv_cache_percentage": 0.5,
"input_token_length": 200,
"num_request_waiting": 4,
"num_request_running": 1,
"num_tokens_generated": 4,
"prefix_cache_score": 0.7,
"prefill_tokens_in_flight": 5000,
"decode_tokens_in_flight": 1200,
},
{
"kv_cache_percentage": 0.3,
"input_token_length": 150,
"num_request_waiting": 0,
"num_request_running": 2,
"num_tokens_generated": 5,
"prefix_cache_score": 0.5,
"prefill_tokens_in_flight": 300,
"decode_tokens_in_flight": 0,
},
{
"kv_cache_percentage": 0.8,
"input_token_length": 500,
"num_request_waiting": 10,
"num_request_running": 3,
"num_tokens_generated": 10,
"prefix_cache_score": 0.2,
"prefill_tokens_in_flight": 12000,
"decode_tokens_in_flight": 3500,
},
]
r = requests.post(f"{PREDICTION_URL}/predict/bulk/strict", json={"requests": requests_data})
assert r.status_code == 200, f"Expected 200, got {r.status_code}: {r.text}"
data = r.json()
assert data["total_requests"] == 3
assert data["successful_predictions"] == 3
assert data["failed_predictions"] == 0
for i, pred in enumerate(data["predictions"]):
assert pred["ttft_ms"] > 0, f"Request {i}: ttft_ms should be positive"
assert pred["tpot_ms"] > 0, f"Request {i}: tpot_ms should be positive"
print("✓ Bulk prediction with token-in-flight features passed")
def test_backward_compat_without_token_in_flight_features():
"""Test that omitting prefill/decode_tokens_in_flight defaults to 0 and still works."""
print("Testing backward compat: omitting TIF fields...")
# These requests deliberately omit the TIF fields
requests_data = [
{
"kv_cache_percentage": 0.5,
"input_token_length": 200,
"num_request_waiting": 4,
"num_request_running": 1,
"num_tokens_generated": 4,
"prefix_cache_score": 0.7,
# No prefill_tokens_in_flight / decode_tokens_in_flight
},
{
"kv_cache_percentage": 0.3,
"input_token_length": 150,
"num_request_waiting": 0,
"num_request_running": 2,
"num_tokens_generated": 5,
"prefix_cache_score": 0.5,
},
]
r = requests.post(f"{PREDICTION_URL}/predict/bulk/strict", json={"requests": requests_data})
assert r.status_code == 200, f"Expected 200 for legacy requests, got {r.status_code}: {r.text}"
data = r.json()
assert data["total_requests"] == 2
assert data["successful_predictions"] == 2
assert data["failed_predictions"] == 0
for i, pred in enumerate(data["predictions"]):
assert pred["ttft_ms"] > 0, f"Request {i}: ttft_ms should be positive"
assert pred["tpot_ms"] > 0, f"Request {i}: tpot_ms should be positive"
print("✓ Backward compat: omitting TIF fields works (defaults to 0)")
def test_token_in_flight_field_defaults_to_zero():
"""Verify that default value for TIF fields is 0 (not rejected by Pydantic)."""
print("Testing TIF field default values via explicit zeros...")
features = {
"kv_cache_percentage": 0.5,
"input_token_length": 200,
"num_request_waiting": 4,
"num_request_running": 1,
"num_tokens_generated": 4,
"prefix_cache_score": 0.7,
"prefill_tokens_in_flight": 0,
"decode_tokens_in_flight": 0,
}
r = requests.post(f"{PREDICTION_URL}/predict", json=features)
assert r.status_code == 200, f"Expected 200, got {r.status_code}: {r.text}"
data = r.json()
assert data["ttft_ms"] > 0
assert data["tpot_ms"] > 0
print(f"✓ TIF=0 prediction: TTFT={data['ttft_ms']:.2f}ms, TPOT={data['tpot_ms']:.2f}ms")
def test_token_in_flight_negative_rejected():
"""Verify that negative token-in-flight values are rejected (ge=0 validation)."""
print("Testing TIF field validation: negative values rejected...")
features = {
"kv_cache_percentage": 0.5,
"input_token_length": 200,
"num_request_waiting": 4,
"num_request_running": 1,
"num_tokens_generated": 4,
"prefix_cache_score": 0.7,
"prefill_tokens_in_flight": -1, # Invalid
"decode_tokens_in_flight": 0,
}
r = requests.post(f"{PREDICTION_URL}/predict", json=features)
assert r.status_code == 422, f"Expected 422 for negative TIF, got {r.status_code}"
print("✓ Negative prefill_tokens_in_flight correctly rejected with 422")
def test_training_data_with_token_in_flight_features():
"""Test that training server accepts prefill/decode_tokens_in_flight in training data."""
print("Testing training data with token-in-flight features...")
entries = []
for i in range(20):
waiting = i % 5
inp_len = 100 + i * 10
kv = 0.4 + (i % 3) * 0.1
running = 1 + (i % 3)
tokens = max(1, i % 10)
prefix_cache = random.uniform(0.1, 0.9)
prefill_tif = random.randint(0, 10000)
decode_tif = random.randint(0, 3000)
entries.append({
"kv_cache_percentage": kv,
"input_token_length": inp_len,
"num_request_waiting": waiting,
"num_request_running": running,
"actual_ttft_ms": 100.0 + inp_len * 0.5 + waiting * 5.0 + prefill_tif * 0.05,
"actual_tpot_ms": 10.0 + kv * 20.0 + decode_tif * 0.02,
"num_tokens_generated": tokens,
"prefix_cache_score": prefix_cache,
"prefill_tokens_in_flight": prefill_tif,
"decode_tokens_in_flight": decode_tif,
})
r = requests.post(f"{TRAINING_URL}/add_training_data_bulk", json={"entries": entries})
assert r.status_code == 202, f"Expected 202, got {r.status_code}: {r.text}"
assert r.json().get("message") == f"Accepted {len(entries)} training samples."
print(f"✓ Accepted {len(entries)} training samples with TIF features")
def test_training_data_backward_compat_without_tif():
"""Test that training data omitting TIF fields is still accepted (backward compat)."""
print("Testing training data backward compat: omitting TIF fields...")
entries = [
{
"kv_cache_percentage": 0.5,
"input_token_length": 200,