"...controller/dynamocomponentdeployment_controller.go" did not exist on "c544e8ec4cbd1af390d49f74899720542ab985e4"
test_kv_bindings.py 10.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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 asyncio
from typing import List

import pytest

22
from dynamo.llm import (
23
    ApproxKvIndexer,
24
    ForwardPassMetrics,
25
26
27
    KvEventPublisher,
    KvIndexer,
    KvMetricsAggregator,
28
    KvStats,
Yan Ru Pei's avatar
Yan Ru Pei committed
29
    RadixTree,
30
    WorkerMetricsPublisher,
31
    WorkerStats,
32
33
)
from dynamo.runtime import Component, DistributedRuntime
34
35
36
37

pytestmark = pytest.mark.pre_merge


38
@pytest.fixture
39
async def distributed_runtime():
40
41
42
    """Function-scoped runtime fixture for use with @pytest.mark.forked tests.

    Each test gets its own runtime in a forked process to avoid singleton conflicts.
43
    """
44
    loop = asyncio.get_running_loop()
45
46
47
    runtime = DistributedRuntime(loop, False)
    yield runtime
    runtime.shutdown()
48

49

50
51
@pytest.mark.asyncio
@pytest.mark.forked
Yan Ru Pei's avatar
Yan Ru Pei committed
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
async def test_radix_tree_binding(distributed_runtime):
    """Test RadixTree binding directly with store event and find matches"""
    import json

    # Create RadixTree instance
    radix_tree = RadixTree()

    # Create a store event with parent_hash=None, block_hash=0
    # Following the KvCacheEvent format from the Rust protocols
    store_event = {
        "event_id": 1,
        "data": {
            "stored": {
                "parent_hash": None,
                "blocks": [
                    {
                        "block_hash": 0,
                        "tokens_hash": 0,  # Using 0 for both hashes to match tokens [0]
                    }
                ],
            }
        },
    }

    # Convert to JSON bytes
    event_bytes = json.dumps(store_event).encode("utf-8")

    # Apply the event to worker_id 0
    worker_id = 0
    radix_tree.apply_event(worker_id, event_bytes)

    # Find matches for tokens [0]
    # The sequence parameter expects token hashes, so we use [0] to match tokens_hash=0
    overlap_scores = radix_tree.find_matches([0])

    # Verify the results
Yan Ru Pei's avatar
Yan Ru Pei committed
88
    # Note: scores is now Dict[(worker_id, dp_rank), score]
Yan Ru Pei's avatar
Yan Ru Pei committed
89
90
91
92
    assert overlap_scores.scores is not None
    assert (
        len(overlap_scores.scores) == 1
    ), f"Expected 1 worker in scores, got {len(overlap_scores.scores)}"
Yan Ru Pei's avatar
Yan Ru Pei committed
93
    worker_key = (worker_id, 0)  # (worker_id, dp_rank)
Yan Ru Pei's avatar
Yan Ru Pei committed
94
    assert (
Yan Ru Pei's avatar
Yan Ru Pei committed
95
96
97
98
99
        worker_key in overlap_scores.scores
    ), f"Worker {worker_key} not found in scores"
    assert (
        overlap_scores.scores[worker_key] == 1
    ), f"Expected score 1 for worker {worker_key}, got {overlap_scores.scores[worker_key]}"
Yan Ru Pei's avatar
Yan Ru Pei committed
100
101

    print(
Yan Ru Pei's avatar
Yan Ru Pei committed
102
        f"✓ RadixTree test passed: worker {worker_key} has score {overlap_scores.scores[worker_key]}"
Yan Ru Pei's avatar
Yan Ru Pei committed
103
104
105
    )


106
107
108
109
110
111
# TODO Figure out how to test with different kv_block_size
# Right now I get an error in EventPublisher init when I run this test
# back to back. It occurs when calling dynamo_llm_init and I think is related to the
# OnceCell initializations not being reset.
# The test works individually if I run it with 32, then 11, then 64.
# @pytest.mark.parametrize("kv_block_size", [11, 32, 64])
112
113
@pytest.mark.asyncio
@pytest.mark.forked
Alec's avatar
Alec committed
114
@pytest.mark.skip(reason="Flakey in CI. Likely race condition going on.")
115
async def test_event_handler(distributed_runtime):
116
    kv_block_size = 32
117
118
    namespace = "kv_test"
    component = "event"
119
120
    kv_listener = distributed_runtime.namespace(namespace).component(component)
    await kv_listener.create_service()
121
122
123

    # publisher
    worker_id = 233
124
    event_publisher = EventPublisher(kv_listener, worker_id, kv_block_size)
125
126

    # indexer
127
    indexer = KvIndexer(kv_listener, kv_block_size)
128

129
    test_token = [3] * kv_block_size
130
131
132
133
134
135
    lora_id = 0  # lora_id is not used in the indexer
    scores = await indexer.find_matches_for_request(test_token, lora_id)
    assert not scores.scores

    event_publisher.store_event(test_token, lora_id)
    # wait for the event to be processed as it is sent asynchronously
136
    # Retry loop for CI environments where processing may take longer
Yan Ru Pei's avatar
Yan Ru Pei committed
137
    worker_key = (worker_id, 0)  # (worker_id, dp_rank)
138
139
140
141
142
    for retry in range(10):  # Try up to 10 times
        await asyncio.sleep(0.5)  # Wait 500ms between retries
        scores = await indexer.find_matches_for_request(test_token, lora_id)
        if (
            scores.scores
Yan Ru Pei's avatar
Yan Ru Pei committed
143
144
            and worker_key in scores.scores
            and scores.scores[worker_key] == 1
145
146
147
148
149
150
        ):
            break
        if retry == 9:  # Last iteration
            # Provide detailed error message for debugging
            assert scores.scores, f"No scores found after {(retry+1)*0.5}s"
            assert (
Yan Ru Pei's avatar
Yan Ru Pei committed
151
152
                worker_key in scores.scores
            ), f"Worker {worker_key} not in scores after {(retry+1)*0.5}s"
153
            assert (
Yan Ru Pei's avatar
Yan Ru Pei committed
154
155
                scores.scores[worker_key] == 1
            ), f"Expected score 1, got {scores.scores.get(worker_key)} after {(retry+1)*0.5}s"
156
157
158

    # remove event
    event_publisher.remove_event()
159
160
161
162
163
164
165
166
167
168
    # Retry loop for event removal verification
    for retry in range(10):  # Try up to 10 times
        await asyncio.sleep(0.5)  # Wait 500ms between retries
        scores = await indexer.find_matches_for_request(test_token, lora_id)
        if not scores.scores:
            break
        if retry == 9:  # Last iteration
            assert (
                not scores.scores
            ), f"Scores still present after {(retry+1)*0.5}s: {scores.scores}"
169

170

171
172
@pytest.mark.asyncio
@pytest.mark.forked
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
async def test_approx_kv_indexer(distributed_runtime):
    kv_block_size = 32
    namespace = "kv_test"
    component = "approx_kv"
    kv_listener = distributed_runtime.namespace(namespace).component(component)
    await kv_listener.create_service()

    indexer = ApproxKvIndexer(kv_listener, kv_block_size, 30.0)

    tokens = [0] * (kv_block_size * 2)

    scores = await indexer.find_matches_for_request(tokens)
    assert not scores.scores

    worker_id = 0

    await indexer.process_routing_decision_for_request(tokens, worker_id)

    scores = await indexer.find_matches_for_request(tokens)
    assert scores.scores
Yan Ru Pei's avatar
Yan Ru Pei committed
193
194
195
    worker_key = (worker_id, 0)  # (worker_id, dp_rank)
    assert worker_key in scores.scores
    assert scores.scores[worker_key] == 2
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
class EventPublisher:
    def __init__(self, component: Component, worker_id: int, kv_block_size: int):
        self.publisher = KvEventPublisher(component, worker_id, kv_block_size)
        self.event_id_counter = 0
        self.block_hashes: List[int] = []

    def store_event(self, tokens, lora_id):
        parent_hash = self.event_id_counter if self.event_id_counter > 0 else None
        self.publisher.publish_stored(
            self.event_id_counter,  # event_id
            tokens,  # token_ids
            [
                len(tokens),
            ],  # num_block_tokens
            [
                self.event_id_counter,
            ],  # block_hashes
            lora_id,  # lora_id
            parent_hash,  # parent_hash
        )
        self.block_hashes.append(self.event_id_counter)
        self.event_id_counter += 1

    def remove_event(self):
        self.publisher.publish_removed(
            self.event_id_counter,  # event_id
            [
                self.block_hashes[-1],
            ],  # block_hashes
        )
        self.event_id_counter += 1
229

230

231
232
@pytest.mark.asyncio
@pytest.mark.forked
233
async def test_metrics_aggregator(distributed_runtime):
234
235
    namespace = "kv_test"
    component = "metrics"
236
    kv_listener = distributed_runtime.namespace(namespace).component(component)
237
238
239
240
241
242
243
244
245
246
247
248
249
250
    await kv_listener.create_service()

    # aggregator
    metrics_aggregator = KvMetricsAggregator(kv_listener)

    # has nothing to aggregate as worker has not started
    metrics = await metrics_aggregator.get_metrics()
    assert not metrics.endpoints

    expected_metrics = {
        "request_active_slots": 0,
        "request_total_slots": 1024,
        "kv_active_blocks": 523,
        "kv_total_blocks": 777,
251
252
253
        "num_requests_waiting": 10,
        "gpu_cache_usage_perc": 0.5,
        "gpu_prefix_cache_hit_rate": 0.75,
254
255
    }

256
257
    # need 'create_task' to put publisher task in the background
    asyncio.create_task(metrics_publisher_task(kv_listener, expected_metrics))
258
259

    # needs time for publisher to spawn up
260
261
262
    # Using shorter intervals for faster detection in normal cases
    for i in range(20):  # Try up to 20 times (10 seconds total)
        await asyncio.sleep(0.5)  # Wait 500ms between retries
263
264
265
        metrics = await metrics_aggregator.get_metrics()
        if metrics.endpoints:
            break
266
    assert metrics.endpoints, f"No metrics endpoints found after {(i+1)*0.5}s"
267
268
269
270
271
272
273
274
275
276
    for endpoint in metrics.endpoints:
        # [TODO] not really checking id for now, can't get it as create_endpoint()
        # create and serve the endpoint internally
        assert endpoint.worker_id != 0
        assert endpoint.request_active_slots == expected_metrics["request_active_slots"]
        assert endpoint.request_total_slots == expected_metrics["request_total_slots"]
        assert endpoint.kv_active_blocks == expected_metrics["kv_active_blocks"]
        assert endpoint.kv_total_blocks == expected_metrics["kv_total_blocks"]


277
async def metrics_publisher_task(kv_listener, expected_metrics):
278
279
280
281
282
283
    # Construct the structured ForwardPassMetrics payload expected by the
    # current Rust bindings instead of passing the individual scalar values
    # directly. The API for `WorkerMetricsPublisher.publish`
    # changed from a list of positional scalars to a single
    # `ForwardPassMetrics` object.

284
    metrics_publisher = WorkerMetricsPublisher()
285
286

    worker_stats = WorkerStats(
287
288
        expected_metrics["request_active_slots"],
        expected_metrics["request_total_slots"],
289
        expected_metrics["num_requests_waiting"],
Yan Ru Pei's avatar
Yan Ru Pei committed
290
        0,  # data_parallel_rank (0 = DP not enabled)
291
292
293
    )

    kv_stats = KvStats(
294
295
        expected_metrics["kv_active_blocks"],
        expected_metrics["kv_total_blocks"],
296
297
        expected_metrics["gpu_cache_usage_perc"],
        expected_metrics["gpu_prefix_cache_hit_rate"],
298
    )
299
300
301
302
303
304

    metrics = ForwardPassMetrics(worker_stats, kv_stats, None)

    # Publish and expose the metrics via the endpoint so that the aggregator
    # test can discover them.
    metrics_publisher.publish(metrics)
305
    await metrics_publisher.create_endpoint(kv_listener)