test_mock_disaggregated_serving.py 9.61 KB
Newer Older
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
# SPDX-FileCopyrightText: Copyright (c) 2024-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
import queue
import sys
import time
from functools import partial
from multiprocessing import Process

import cupy
import numpy
import pytest
import tritonclient.grpc as grpcclient
import ucp
from cupy_backends.cuda.api.runtime import CUDARuntimeError
from transformers import XLNetTokenizer
30
31
32
from tritonclient.utils import InferenceServerException
from tritonserver import Tensor

33
34
from triton_distributed.icp.nats_request_plane import NatsRequestPlane
from triton_distributed.icp.ucp_data_plane import UcpDataPlane
35
36
37
38
39
40
from triton_distributed.runtime.deployment import Deployment
from triton_distributed.runtime.logger import get_logger
from triton_distributed.runtime.operator import OperatorConfig
from triton_distributed.runtime.remote_operator import RemoteOperator
from triton_distributed.runtime.triton_core_operator import TritonCoreOperator
from triton_distributed.runtime.worker import WorkerConfig
41
42
43

NATS_PORT = 4223
MODEL_REPOSITORY = (
44
    "/workspace/runtime/tests/python/integration/operators/triton_core_models"
45
)
46
OPERATORS_REPOSITORY = "/workspace/runtime/tests/python/integration/operators"
47
48
TRITON_LOG_LEVEL = 6

49
logger = get_logger(__name__)
50
51
52
53
54
55
56
57
58
59
60

# Run cupy's cuda.is_available once to
# avoid the exception hitting runtime code.
try:
    if cupy.cuda.is_available():
        pass
    else:
        print("CUDA not available.")
except CUDARuntimeError:
    print("CUDA not available")

61
62
# Slower test than others - make it nightly for now
pytestmark = pytest.mark.nightly
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


@pytest.fixture
def workers(request, log_dir):
    operator_configs = {}

    # Add configs for triton core operators
    triton_core_operators = ["preprocessing", "context", "generation", "postprocessing"]
    for operator_name in triton_core_operators:
        operator_configs[operator_name] = OperatorConfig(
            name=operator_name,
            implementation=TritonCoreOperator,
            version=1,
            max_inflight_requests=10,
            repository=MODEL_REPOSITORY,
        )

    # Add configs for other custom operators
    operator_name = "mock_disaggregated_serving"
    operator_configs[operator_name] = OperatorConfig(
        name=operator_name,
        implementation="mock_disaggregated_serving:MockDisaggregatedServing",
        version=1,
        max_inflight_requests=10,
        repository=OPERATORS_REPOSITORY,
    )

    worker_configs = []

    test_log_dir = log_dir / request.node.name
    test_log_dir.mkdir(parents=True, exist_ok=True)

    # We will instantiate a worker for each operator
    for name, operator_config in operator_configs.items():
        # Set the logging directory
        worker_log_dir = test_log_dir / name
        worker_configs.append(
            WorkerConfig(
101
                name=name,
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
                request_plane=NatsRequestPlane,
                data_plane=UcpDataPlane,
                request_plane_args=(
                    [],
                    {"request_plane_uri": f"nats://localhost:{NATS_PORT}"},
                ),
                log_level=TRITON_LOG_LEVEL,
                log_dir=str(worker_log_dir),
                operators=[operator_config],
            )
        )

    worker_deployment = Deployment(worker_configs)

    worker_deployment.start()
    yield worker_deployment
    worker_deployment.shutdown()


def _create_inputs(number):
    inputs = []
    outputs = []

    for _ in range(number):
        request_output_len = 10
        query_arr = numpy.array(["This is a sample prompt"], dtype=numpy.object_)
        request_output_len_arr = numpy.array([request_output_len], dtype=numpy.int32)
        input_ = {"query": query_arr, "request_output_len": request_output_len_arr}

        expected_output = numpy.repeat(query_arr, request_output_len)

        tokenizer = XLNetTokenizer.from_pretrained("xlnet-base-cased")
        tokens = numpy.array(tokenizer.encode(query_arr[0]))
        expected_output = numpy.array(
            tokenizer.convert_ids_to_tokens((tokens.tolist()))
        )

        output_data_ = {"output": Tensor._from_object(expected_output)}

        inputs.append(input_)
        outputs.append(output_data_)
    return inputs, outputs


async def post_requests(num_requests):
    ucp.reset()

    data_plane = UcpDataPlane()
    data_plane.connect()

    request_plane = NatsRequestPlane(f"nats://localhost:{NATS_PORT}")
    await request_plane.connect()

    mock_disaggregated_serving_operator = RemoteOperator(
Neelay Shah's avatar
Neelay Shah committed
156
        "mock_disaggregated_serving", request_plane, data_plane
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
    )

    expected_results = {}

    inputs, outputs = _create_inputs(num_requests)
    begin = None
    token_latency = []
    timeout = True
    for i, input_dict in enumerate(inputs):
        request_id = str(i)
        request = mock_disaggregated_serving_operator.create_request(
            inputs=input_dict, request_id=request_id
        )

        begin = time.time()
        response_count = 0

        try:
            async for response in await mock_disaggregated_serving_operator.async_infer(
                inference_request=request
            ):
                token_latency.append(time.time() - begin)
                expected_results[request_id] = outputs[i]
                if not response.final:
                    for output_name, expected_value in expected_results[
                        response.request_id
                    ].items():
                        output = response.outputs[output_name]
                        output_value = output.to_bytes_array()
                        print(f"Final Output: {output_value}")
                        numpy.testing.assert_equal(
                            output_value, expected_value.to_bytes_array()
                        )
                    response_count += 1

            # 1 response from context and 10 responses from generation
            assert response_count == 11

        except Exception as e:
            print("Failed collecting responses:" + repr(e))
            del response
            print(f"Token latency: {token_latency}")
            data_plane.close(wait_for_release=timeout)
            await request_plane.close()
            raise e

    print(f"Token latency: {token_latency}")
    data_plane.close(wait_for_release=timeout)
    await request_plane.close()


def run(num_requests):
    sys.exit(asyncio.run(post_requests(num_requests=num_requests)))


@pytest.mark.skipif(
    "(not os.path.exists('/usr/local/bin/nats-server'))",
    reason="NATS.io not present or test is not configured to run with mock disaggregated serving",
)
def test_mock_disaggregated_serving(request, nats_server, workers):
    # Using a separate process to use data plane across multiple tests.
    p = Process(target=run, args=(1,))
    p.start()
    p.join()
    assert p.exitcode == 0


class UserData:
    def __init__(self):
        self._completed_requests: queue.Queue[
            grpcclient.Result | InferenceServerException
        ] = queue.Queue()


# Define the callback function. Note the last two parameters should be
# result and error. InferenceServerClient would povide the results of an
# inference as grpcclient.InferResult in result. For successful
# inference, error will be None, otherwise it will be an object of
# tritonclientutils.InferenceServerException holding the error details
def callback(user_data, result, error):
    if error:
        user_data._completed_requests.put(error)
    else:
        user_data._completed_requests.put(result)


async def send_kserve_requests(num_requests):
    inputs_dict, outputs_dicts = _create_inputs(num_requests)
    inputs = []
    inputs.append(grpcclient.InferInput("query", [1], "BYTES"))
    inputs.append(grpcclient.InferInput("request_output_len", [1], "INT32"))

    user_data = UserData()
    with grpcclient.InferenceServerClient("localhost:8001") as client:
        client.start_stream(
            callback=partial(callback, user_data),
        )
        for i, input_dict in enumerate(inputs_dict):
            inputs[0].set_data_from_numpy(input_dict["query"])
            inputs[1].set_data_from_numpy(input_dict["request_output_len"])

            client.async_stream_infer(
                model_name="mock_disaggregated_serving", inputs=inputs
            )

        recv_count = 0
        while recv_count < 10:
            data_item = user_data._completed_requests.get()
            recv_count += 1
            if isinstance(data_item, InferenceServerException):
                raise data_item
            else:
                result = data_item.as_numpy("output")
                print("test \n")
                print(result)

    # Wait for the tensor clean-up
    time.sleep(5)


def run_kserve(num_requests):
    sys.exit(asyncio.run(send_kserve_requests(num_requests=num_requests)))


@pytest.mark.skipif(
    "(not os.path.exists('/usr/local/bin/nats-server'))",
    reason="NATS.io not present",
)
def test_mock_disaggregated_serving_kserve(request, nats_server, workers, api_server):
    # Using a separate process to use data plane across multiple tests.
    p = Process(target=run_kserve, args=(1,))
    p.start()
    p.join()
    assert p.exitcode == 0