test_replica_calculation.py 28.9 KB
Newer Older
1
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
4
5
6
7
8
9
10
# SPDX-License-Identifier: Apache-2.0

"""
Unit tests for SLA planner replica calculation logic.

These tests focus specifically on the replica calculation formulas without
testing load prediction, interpolation, or correction factors.
"""

11
import asyncio
12
13
import math
import os
14
from unittest.mock import Mock, patch
15
16
17

import pytest

18
from dynamo.planner.utils.decode_planner import DecodePlanner
19
from dynamo.planner.utils.planner_config import PlannerConfig
20
from dynamo.planner.utils.planner_core import (
21
22
23
    PlannerSharedState,
    _apply_global_gpu_budget,
)
24
25
from dynamo.planner.utils.prefill_planner import PrefillPlanner
from dynamo.planner.utils.prometheus import Metrics
26
from dynamo.planner.worker_info import WorkerInfo
27

28
29
pytestmark = [pytest.mark.pre_merge, pytest.mark.gpu_0]

30

31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class PlannerHarness:
    def __init__(self, prefill_planner, decode_planner, shared_state):
        self.prefill_planner = prefill_planner
        self.decode_planner = decode_planner
        self.shared_state = shared_state
        self.last_target_replicas = []

    async def make_adjustments(self):
        if not self.shared_state.last_metrics.is_valid():
            return

        p_endpoints, d_endpoints = await self.prefill_planner.get_workers_info()
        self.shared_state.p_endpoints = p_endpoints
        self.shared_state.d_endpoints = d_endpoints

        next_num_p = self.prefill_planner.plan_adjustment()
        next_num_d = self.decode_planner.plan_adjustment()
        if next_num_p is None or next_num_d is None:
            return

        next_num_p, next_num_d = _apply_global_gpu_budget(
52
            next_num_p, next_num_d, self.prefill_planner.config
53
54
55
56
57
58
59
        )
        self.prefill_planner.update_predicted_replicas_metric(next_num_p)
        self.decode_planner.update_predicted_replicas_metric(next_num_d)

        target_replicas = [
            {
                "sub_component_type": "prefill",
60
                "component_name": self.prefill_planner.prefill_worker_info.k8s_name,
61
62
63
64
                "desired_replicas": next_num_p,
            },
            {
                "sub_component_type": "decode",
65
                "component_name": self.prefill_planner.decode_worker_info.k8s_name,
66
67
68
69
70
                "desired_replicas": next_num_d,
            },
        ]
        self.last_target_replicas = target_replicas

71
        if not self.prefill_planner.config.no_operation:
72
73
74
75
76
77
78
79
80
81
            await self.prefill_planner.connector.set_component_replicas(
                target_replicas, blocking=False
            )

    def __getattr__(self, name):
        shared_attrs = {
            "num_req_predictor",
            "isl_predictor",
            "osl_predictor",
            "connector",
82
            "prometheus_traffic_client",
83
            "config",
84
85
86
        }
        prefill_attrs = {
            "prefill_interpolator",
87
            "prefill_worker_info",
88
89
90
91
            "p_correction_factor",
        }
        decode_attrs = {
            "decode_interpolator",
92
            "decode_worker_info",
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
            "d_correction_factor",
        }
        if name == "last_metrics":
            return self.shared_state.last_metrics
        if name == "get_workers_info":
            return self.prefill_planner.get_workers_info
        if name in shared_attrs:
            return getattr(self.prefill_planner, name)
        if name in prefill_attrs:
            return getattr(self.prefill_planner, name)
        if name in decode_attrs:
            return getattr(self.decode_planner, name)
        raise AttributeError(name)

    def __setattr__(self, name, value):
        if name in {"prefill_planner", "decode_planner", "shared_state"}:
            return super().__setattr__(name, value)
        shared_attrs = {
            "num_req_predictor",
            "isl_predictor",
            "osl_predictor",
            "connector",
115
            "prometheus_traffic_client",
116
            "config",
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
            "get_workers_info",
        }
        prefill_attrs = {"prefill_interpolator", "p_correction_factor"}
        decode_attrs = {"decode_interpolator", "d_correction_factor"}
        if name == "last_metrics":
            self.shared_state.last_metrics = value
            return None
        if name in shared_attrs:
            # Store locally to support patch.object lifecycle (set/del).
            object.__setattr__(self, name, value)
            setattr(self.prefill_planner, name, value)
            setattr(self.decode_planner, name, value)
            return None
        if name in prefill_attrs:
            setattr(self.prefill_planner, name, value)
            return None
        if name in decode_attrs:
            setattr(self.decode_planner, name, value)
            return None
        return super().__setattr__(name, value)


def _replica_count(target_replicas, component_name, default=1):
    for replica in target_replicas:
        if replica.get("component_name") == component_name:
            return replica.get("desired_replicas", default)
    return default


146
147
148
@pytest.fixture
def planner():
    """Set up test environment with mocked dependencies."""
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    config = PlannerConfig.model_construct(
        throughput_adjustment_interval=60,
        prefill_engine_num_gpu=1,
        decode_engine_num_gpu=1,
        min_endpoint=1,
        max_gpu_budget=10,
        ttft=80.0,
        itl=10.0,
        backend="vllm",
        no_operation=True,
        no_correction=False,
        metric_pulling_prometheus_endpoint="http://localhost:9090",
        metric_reporting_prometheus_port=0,
        load_predictor="constant",
        profile_results_dir=os.path.join(
            os.path.dirname(__file__),
            "profiling_results/H200_TP1P_TP1D",
        ),
        environment="kubernetes",
        namespace="test-namespace",
        enable_throughput_scaling=True,
        enable_load_scaling=False,
        load_predictor_warmup_trace=None,
        load_predictor_log1p=False,
173
174
175
176
177
178
179
180
181
    )

    # Mock the runtime
    mock_runtime = Mock()

    # Patch Prometheus Gauge to avoid registry conflicts
    with patch("dynamo.planner.utils.planner_core.Gauge") as mock_gauge:
        mock_gauge.return_value = Mock()

182
        shared_state = PlannerSharedState()
183
184
185
186
        prefill_planner = PrefillPlanner(
            mock_runtime, config, shared_state=shared_state
        )
        decode_planner = DecodePlanner(mock_runtime, config, shared_state=shared_state)
187
        planner = PlannerHarness(prefill_planner, decode_planner, shared_state)
188

189
190
191
192
193
194
195
196
197
198
199
200
201
202
        # Set up WorkerInfo for both planners
        prefill_planner.prefill_worker_info = WorkerInfo(
            k8s_name="VllmPrefillWorker",
            component_name="prefill",
            endpoint="generate",
        )
        prefill_planner.decode_worker_info = WorkerInfo(
            k8s_name="VllmDecodeWorker",
            component_name="backend",
            endpoint="generate",
        )
        decode_planner.prefill_worker_info = prefill_planner.prefill_worker_info
        decode_planner.decode_worker_info = prefill_planner.decode_worker_info

203
204
205
206
207
208
209
210
211
212
213
214
215
        # Mock the interpolators to return fixed values for testing
        planner.prefill_interpolator = Mock()
        planner.decode_interpolator = Mock()

        # Mock the predictors to return fixed values
        planner.num_req_predictor = Mock()
        planner.isl_predictor = Mock()
        planner.osl_predictor = Mock()

        # Mock the connector since we're not testing actual scaling
        planner.connector = Mock()

        # Mock prometheus client
216
        planner.prometheus_traffic_client = Mock()
217
218
219
220
221

        # Set up some baseline correction factors
        planner.p_correction_factor = 1.0
        planner.d_correction_factor = 1.0

222
        planner.config = config
223
224
225
226
227
228
229
230

        yield planner
        # Cleanup is automatic with context manager


class TestReplicaCalculation:
    """Test replica calculation formulas in isolation."""

231
232
233
    @pytest.mark.nightly
    @pytest.mark.gpu_2
    @pytest.mark.performance
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
    def test_prefill_replica_calculation_basic(self, planner):
        """Test basic prefill replica calculation."""
        # Setup test data
        next_num_req = 10
        next_isl = 3000
        prefill_thpt_per_gpu = 40000  # tokens/s/gpu (from the test data)

        # Mock the predictor outputs
        planner.num_req_predictor.predict_next.return_value = next_num_req
        planner.isl_predictor.predict_next.return_value = next_isl
        planner.osl_predictor.predict_next.return_value = 150

        # Mock interpolator output
        planner.prefill_interpolator.interpolate_thpt_per_gpu.return_value = (
            prefill_thpt_per_gpu
        )
        planner.decode_interpolator.find_best_throughput_per_gpu.return_value = (
            10000,
            0.01,
            0.5,
        )

        # Calculate expected result manually
        pred_prefill_load_per_gpu = (
            next_num_req
            * next_isl
260
            / planner.config.throughput_adjustment_interval
261
262
263
264
265
            * min(1, planner.p_correction_factor)
        )
        expected_prefill_replicas = math.ceil(
            pred_prefill_load_per_gpu
            / prefill_thpt_per_gpu
266
            / planner.config.prefill_engine_num_gpu
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
        )

        # Set up valid metrics to trigger calculation
        planner.last_metrics = Metrics(
            num_req=10, isl=3000, osl=150, ttft=80.0, itl=10.0, request_duration=100.0
        )

        # Mock workers info
        async def mock_get_workers_info():
            return (["prefill1"], ["decode1"])

        planner.get_workers_info = mock_get_workers_info

        # Mock interpolation calls for correction factor calculation
        planner.prefill_interpolator.interpolate_ttft.return_value = 80.0
        planner.decode_interpolator.interpolate_itl.return_value = 10.0

        # Run the calculation
        asyncio.run(planner.make_adjustments())

        # Extract the calculated values from the log calls or by checking the mock calls
        # Since we mocked the connector, we can check what replicas were requested
289
290
291
292
293
294
        prefill_component = "VllmPrefillWorker"
        calculated_prefill_replicas = _replica_count(
            planner.last_target_replicas, prefill_component
        )
        print(f"Expected prefill replicas: {expected_prefill_replicas}")
        print(f"Calculated prefill replicas: {calculated_prefill_replicas}")
295

296
297
        # Allow for small differences due to min_endpoint constraints
        assert (
298
            max(expected_prefill_replicas, planner.config.min_endpoint)
299
300
            == calculated_prefill_replicas
        )
301

302
303
304
    @pytest.mark.nightly
    @pytest.mark.gpu_2
    @pytest.mark.performance
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
    def test_decode_replica_calculation_basic(self, planner):
        """Test basic decode replica calculation."""
        # Setup test data
        next_num_req = 10
        next_osl = 150
        decode_thpt_per_gpu = 10000  # tokens/s/gpu

        # Mock the predictor outputs
        planner.num_req_predictor.predict_next.return_value = next_num_req
        planner.isl_predictor.predict_next.return_value = 3000
        planner.osl_predictor.predict_next.return_value = next_osl

        # Mock interpolator outputs
        planner.prefill_interpolator.interpolate_thpt_per_gpu.return_value = 40000
        planner.decode_interpolator.find_best_throughput_per_gpu.return_value = (
            decode_thpt_per_gpu,
            0.01,
            0.5,
        )

        # Calculate expected result manually
        expected_decode_replicas = math.ceil(
            next_num_req
            * next_osl
329
            / planner.config.throughput_adjustment_interval
330
            / decode_thpt_per_gpu
331
            / planner.config.decode_engine_num_gpu
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
        )

        # Set up valid metrics
        planner.last_metrics = Metrics(
            num_req=10, isl=3000, osl=150, ttft=80.0, itl=10.0, request_duration=100.0
        )

        # Mock workers info
        async def mock_get_workers_info():
            return (["prefill1"], ["decode1"])

        planner.get_workers_info = mock_get_workers_info

        # Mock interpolation calls for correction factor calculation
        planner.prefill_interpolator.interpolate_ttft.return_value = 80.0
        planner.decode_interpolator.interpolate_itl.return_value = 10.0

        # Run the calculation
        asyncio.run(planner.make_adjustments())

        # Check the results
353
354
355
356
357
358
        decode_component = "VllmDecodeWorker"
        calculated_decode_replicas = _replica_count(
            planner.last_target_replicas, decode_component
        )
        print(f"Expected decode replicas: {expected_decode_replicas}")
        print(f"Calculated decode replicas: {calculated_decode_replicas}")
359

360
361
        # Allow for small differences due to min_endpoint constraints
        assert (
362
            max(expected_decode_replicas, planner.config.min_endpoint)
363
364
            == calculated_decode_replicas
        )
365
366
367
368
369
370
371
372

    @pytest.mark.parametrize(
        "num_req,decode_thpt,expected_p,expected_d",
        [
            (10, 10000, 1, 1),  # low_load_10_req_per_second
            (500, 1000, 1, 2),  # high_load_500_req_per_second (lower decode throughput)
        ],
    )
373
374
375
    @pytest.mark.nightly
    @pytest.mark.gpu_2
    @pytest.mark.performance
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
    def test_scaling_scenario_low_to_high_load(
        self, planner, num_req, decode_thpt, expected_p, expected_d
    ):
        """Test scaling from low to high load scenarios."""
        # Reset the planner state
        planner.p_correction_factor = 1.0
        planner.d_correction_factor = 1.0

        # Mock predictor outputs for this case
        planner.num_req_predictor.predict_next.return_value = num_req
        planner.isl_predictor.predict_next.return_value = 3000
        planner.osl_predictor.predict_next.return_value = 150

        # Mock interpolator outputs (based on H200 1P1D profiling data)
        planner.prefill_interpolator.interpolate_thpt_per_gpu.return_value = (
            40000  # tokens/s/gpu
        )
        planner.decode_interpolator.find_best_throughput_per_gpu.return_value = (
            decode_thpt,
            0.01,
            0.5,
        )

        # Set up metrics
        planner.last_metrics = Metrics(
            num_req=num_req,
            isl=3000,
            osl=150,
            ttft=80.0,
            itl=10.0,
            request_duration=100.0,
        )

        # Mock workers info
        async def mock_get_workers_info():
            return (["prefill1"], ["decode1"])

        planner.get_workers_info = mock_get_workers_info

        # Mock interpolation calls for correction factor calculation
        planner.prefill_interpolator.interpolate_ttft.return_value = 80.0
        planner.decode_interpolator.interpolate_itl.return_value = 10.0

        # Reset the mock
        planner.connector.reset_mock()

        # Run calculation
        asyncio.run(planner.make_adjustments())

        # Verify results
426
427
428
429
430
431
432
        prefill_replicas = _replica_count(
            planner.last_target_replicas, "VllmPrefillWorker"
        )
        decode_replicas = _replica_count(
            planner.last_target_replicas, "VllmDecodeWorker"
        )
        print(f"Load {num_req} req/s: P={prefill_replicas}, D={decode_replicas}")
433

434
435
436
437
438
439
        assert (
            prefill_replicas == expected_p
        ), f"Prefill replicas mismatch: expected {expected_p}, got {prefill_replicas}"
        assert (
            decode_replicas == expected_d
        ), f"Decode replicas mismatch: expected {expected_d}, got {decode_replicas}"
440

441
442
443
    @pytest.mark.nightly
    @pytest.mark.gpu_2
    @pytest.mark.performance
444
445
446
    def test_gpu_budget_constraint(self, planner):
        """Test that GPU budget constraints are properly applied."""
        # Set a low GPU budget
447
        planner.config.max_gpu_budget = 3
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

        # Mock predictor outputs that would normally require more GPUs
        planner.num_req_predictor.predict_next.return_value = 50  # High load
        planner.isl_predictor.predict_next.return_value = 3000
        planner.osl_predictor.predict_next.return_value = 150

        # Mock interpolator outputs
        planner.prefill_interpolator.interpolate_thpt_per_gpu.return_value = 40000
        planner.decode_interpolator.find_best_throughput_per_gpu.return_value = (
            10000,
            0.01,
            0.5,
        )

        # Set up metrics
        planner.last_metrics = Metrics(
            num_req=50, isl=3000, osl=150, ttft=80.0, itl=10.0, request_duration=100.0
        )

        # Mock workers info
        async def mock_get_workers_info():
            return (["prefill1"], ["decode1"])

        planner.get_workers_info = mock_get_workers_info

        # Mock interpolation calls
        planner.prefill_interpolator.interpolate_ttft.return_value = 80.0
        planner.decode_interpolator.interpolate_itl.return_value = 10.0

        # Run calculation
        asyncio.run(planner.make_adjustments())

        # Verify that total GPU usage doesn't exceed budget
481
482
483
484
485
486
487
        prefill_replicas = _replica_count(
            planner.last_target_replicas, "VllmPrefillWorker"
        )
        decode_replicas = _replica_count(
            planner.last_target_replicas, "VllmDecodeWorker"
        )
        total_gpus = (
488
489
            prefill_replicas * planner.config.prefill_engine_num_gpu
            + decode_replicas * planner.config.decode_engine_num_gpu
490
        )
491

492
493
494
        print(
            f"GPU budget test: P={prefill_replicas}, D={decode_replicas}, Total GPUs={total_gpus}"
        )
495

496
        assert (
497
            total_gpus <= planner.config.max_gpu_budget
498
        ), "Total GPU usage exceeds budget"
499

500
501
502
    @pytest.mark.nightly
    @pytest.mark.gpu_2
    @pytest.mark.performance
503
504
    def test_min_endpoint_constraint(self, planner):
        """Test that minimum endpoint constraints are respected."""
505
        planner.config.min_endpoint = 2
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

        # Mock predictor outputs that would normally require fewer workers
        planner.num_req_predictor.predict_next.return_value = 1  # Very low load
        planner.isl_predictor.predict_next.return_value = 100
        planner.osl_predictor.predict_next.return_value = 10

        # Mock interpolator outputs
        planner.prefill_interpolator.interpolate_thpt_per_gpu.return_value = 40000
        planner.decode_interpolator.find_best_throughput_per_gpu.return_value = (
            10000,
            0.01,
            0.5,
        )

        # Set up metrics
        planner.last_metrics = Metrics(
            num_req=1, isl=100, osl=10, ttft=80.0, itl=10.0, request_duration=100.0
        )

        # Mock workers info
        async def mock_get_workers_info():
            return (["prefill1"], ["decode1"])

        planner.get_workers_info = mock_get_workers_info

        # Mock interpolation calls
        planner.prefill_interpolator.interpolate_ttft.return_value = 80.0
        planner.decode_interpolator.interpolate_itl.return_value = 10.0

        # Run calculation
        asyncio.run(planner.make_adjustments())

        # Verify minimum constraints are respected
539
540
541
542
543
544
545
        prefill_replicas = _replica_count(
            planner.last_target_replicas, "VllmPrefillWorker"
        )
        decode_replicas = _replica_count(
            planner.last_target_replicas, "VllmDecodeWorker"
        )
        print(f"Min endpoint test: P={prefill_replicas}, D={decode_replicas}")
546

547
        assert (
548
            prefill_replicas >= planner.config.min_endpoint
549
550
        ), "Prefill replicas below minimum"
        assert (
551
            decode_replicas >= planner.config.min_endpoint
552
        ), "Decode replicas below minimum"
553

554
555
556
    @pytest.mark.nightly
    @pytest.mark.gpu_2
    @pytest.mark.performance
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
    def test_prefill_correction_factor_clamping(self, planner):
        """Test that prefill correction factor > 1 is clamped to 1."""
        # Set a high correction factor > 1
        planner.p_correction_factor = 2.5
        planner.d_correction_factor = 1.0

        # Mock predictor outputs
        planner.num_req_predictor.predict_next.return_value = 10
        planner.isl_predictor.predict_next.return_value = 3000
        planner.osl_predictor.predict_next.return_value = 150

        # Mock interpolator outputs
        planner.prefill_interpolator.interpolate_thpt_per_gpu.return_value = 40000
        planner.decode_interpolator.find_best_throughput_per_gpu.return_value = (
            10000,
            0.01,
            0.5,
        )

        # Set up metrics
        planner.last_metrics = Metrics(
            num_req=10, isl=3000, osl=150, ttft=80.0, itl=10.0, request_duration=100.0
        )

        # Mock workers info
        async def mock_get_workers_info():
            return (["prefill1"], ["decode1"])

        planner.get_workers_info = mock_get_workers_info

        # Mock interpolation calls
        planner.prefill_interpolator.interpolate_ttft.return_value = 80.0
        planner.decode_interpolator.interpolate_itl.return_value = 10.0

        # Calculate expected result manually with clamping
        # Should use min(1, 2.5) = 1
        pred_prefill_load_per_gpu = (
594
595
596
597
            10
            * 3000
            / planner.config.throughput_adjustment_interval
            * min(1, 2.5)  # Should be * 1
598
599
        )
        expected_prefill_replicas = math.ceil(
600
            pred_prefill_load_per_gpu / 40000 / planner.config.prefill_engine_num_gpu
601
602
603
604
605
606
        )

        # Run calculation
        asyncio.run(planner.make_adjustments())

        # Verify that correction factor was effectively clamped
607
608
609
        prefill_replicas = _replica_count(
            planner.last_target_replicas, "VllmPrefillWorker"
        )
610

611
612
613
        print(
            f"Correction factor clamping test: Expected={expected_prefill_replicas}, Got={prefill_replicas}"
        )
614

615
        assert prefill_replicas == max(
616
            expected_prefill_replicas, planner.config.min_endpoint
617
        ), "Prefill correction factor should be clamped to 1"
618

619
620
621
    @pytest.mark.nightly
    @pytest.mark.gpu_2
    @pytest.mark.performance
622
623
624
625
    def test_decode_correction_factor_zero_handling(self, planner):
        """Test handling of d_correction_factor <= 0."""
        # Test both 0 and negative values
        for correction_factor in [0.0, -1.0]:
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
            planner.p_correction_factor = 1.0
            planner.d_correction_factor = correction_factor

            # Mock predictor outputs
            planner.num_req_predictor.predict_next.return_value = 10
            planner.isl_predictor.predict_next.return_value = 3000
            planner.osl_predictor.predict_next.return_value = 150

            # Mock interpolator outputs
            planner.prefill_interpolator.interpolate_thpt_per_gpu.return_value = 40000
            planner.decode_interpolator.find_best_throughput_per_gpu.return_value = (
                10000,
                0.01,
                0.5,
            )

            # Set up metrics
            planner.last_metrics = Metrics(
                num_req=10,
                isl=3000,
                osl=150,
                ttft=80.0,
                itl=10.0,
                request_duration=100.0,
            )

            # Mock workers info
            async def mock_get_workers_info():
                return (["prefill1"], ["decode1"])

            planner.get_workers_info = mock_get_workers_info

            # Mock interpolation calls
            planner.prefill_interpolator.interpolate_ttft.return_value = 80.0
            planner.decode_interpolator.interpolate_itl.return_value = 10.0

            # Run calculation
            asyncio.run(planner.make_adjustments())

            # Should handle gracefully without crashing
            # The code should use args.itl directly instead of dividing by 0
            decode_replicas = _replica_count(
                planner.last_target_replicas, "VllmDecodeWorker"
            )

            print(
                f"Correction factor {correction_factor} test: Decode replicas={decode_replicas}"
            )

            # Should get a valid result (not crash)
            assert (
                decode_replicas >= 1
            ), f"Should handle correction factor {correction_factor} gracefully"
679

680
681
682
    @pytest.mark.nightly
    @pytest.mark.gpu_2
    @pytest.mark.performance
683
684
685
    def test_multi_gpu_engines(self, planner):
        """Test replica calculation with multi-GPU engines."""
        # Set multi-GPU configuration
686
687
        planner.config.prefill_engine_num_gpu = 2
        planner.config.decode_engine_num_gpu = 4
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

        # Mock predictor outputs
        planner.num_req_predictor.predict_next.return_value = 20
        planner.isl_predictor.predict_next.return_value = 3000
        planner.osl_predictor.predict_next.return_value = 150

        # Mock interpolator outputs
        planner.prefill_interpolator.interpolate_thpt_per_gpu.return_value = 40000
        planner.decode_interpolator.find_best_throughput_per_gpu.return_value = (
            5000,
            0.01,
            0.5,
        )  # Lower for scaling

        # Set up metrics
        planner.last_metrics = Metrics(
            num_req=20, isl=3000, osl=150, ttft=80.0, itl=10.0, request_duration=100.0
        )

        # Mock workers info
        async def mock_get_workers_info():
            return (["prefill1"], ["decode1"])

        planner.get_workers_info = mock_get_workers_info

        # Mock interpolation calls
        planner.prefill_interpolator.interpolate_ttft.return_value = 80.0
        planner.decode_interpolator.interpolate_itl.return_value = 10.0

        # Calculate expected results manually
718
719
720
        pred_prefill_load_per_gpu = (
            20 * 3000 / planner.config.throughput_adjustment_interval * 1.0
        )
721
722
723
724
725
        expected_prefill_replicas = math.ceil(
            pred_prefill_load_per_gpu / 40000 / 2
        )  # 2 GPUs per engine

        expected_decode_replicas = math.ceil(
726
            20 * 150 / planner.config.throughput_adjustment_interval / 5000 / 4
727
728
729
730
731
        )  # 4 GPUs per engine

        # Run calculation
        asyncio.run(planner.make_adjustments())

732
733
734
735
736
737
738
739
740
        prefill_replicas = _replica_count(
            planner.last_target_replicas, "VllmPrefillWorker"
        )
        decode_replicas = _replica_count(
            planner.last_target_replicas, "VllmDecodeWorker"
        )
        print(
            f"Multi-GPU test: P={prefill_replicas} (expected ~{expected_prefill_replicas}), D={decode_replicas} (expected ~{expected_decode_replicas})"
        )
741

742
743
        # Verify calculations account for multiple GPUs per engine
        assert prefill_replicas == max(
744
            expected_prefill_replicas, planner.config.min_endpoint
745
746
        )
        assert decode_replicas == max(
747
            expected_decode_replicas, planner.config.min_endpoint
748
        )
749

750
751
752
    @pytest.mark.weekly
    @pytest.mark.gpu_2
    @pytest.mark.performance
753
754
755
    def test_complex_gpu_budget_scaling(self, planner):
        """Test complex GPU budget scaling with proportional reduction and decode adjustment."""
        # Set tight GPU budget that will trigger complex scaling
756
757
758
759
        planner.config.max_gpu_budget = 5
        planner.config.prefill_engine_num_gpu = 2
        planner.config.decode_engine_num_gpu = 2
        planner.config.min_endpoint = 1
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

        # High load that would normally require more GPUs
        planner.num_req_predictor.predict_next.return_value = 100
        planner.isl_predictor.predict_next.return_value = 3000
        planner.osl_predictor.predict_next.return_value = 150

        # Lower throughput to trigger higher replica needs
        planner.prefill_interpolator.interpolate_thpt_per_gpu.return_value = 10000
        planner.decode_interpolator.find_best_throughput_per_gpu.return_value = (
            1000,
            0.01,
            0.5,
        )

        # Set up metrics
        planner.last_metrics = Metrics(
            num_req=100, isl=3000, osl=150, ttft=80.0, itl=10.0, request_duration=100.0
        )

        # Mock workers info
        async def mock_get_workers_info():
            return (["prefill1"], ["decode1"])

        planner.get_workers_info = mock_get_workers_info

        # Mock interpolation calls
        planner.prefill_interpolator.interpolate_ttft.return_value = 80.0
        planner.decode_interpolator.interpolate_itl.return_value = 10.0

        # Run calculation
        asyncio.run(planner.make_adjustments())

792
793
794
795
796
797
798
799
        prefill_replicas = _replica_count(
            planner.last_target_replicas, "VllmPrefillWorker"
        )
        decode_replicas = _replica_count(
            planner.last_target_replicas, "VllmDecodeWorker"
        )
        # Verify total GPU usage doesn't exceed budget
        total_gpus = (
800
801
            prefill_replicas * planner.config.prefill_engine_num_gpu
            + decode_replicas * planner.config.decode_engine_num_gpu
802
        )
803

804
805
806
        print(
            f"Complex GPU budget test: P={prefill_replicas}, D={decode_replicas}, Total GPUs={total_gpus}"
        )
807

808
        assert (
809
            total_gpus <= planner.config.max_gpu_budget
810
811
        ), "Total GPU usage should not exceed budget"
        assert (
812
            prefill_replicas >= planner.config.min_endpoint
813
814
        ), "Should respect min_endpoint for prefill"
        assert (
815
            decode_replicas >= planner.config.min_endpoint
816
        ), "Should respect min_endpoint for decode"
817
818
819


# No need for unittest.main() with pytest!