test_srt_endpoint.py 16.9 KB
Newer Older
1
2
"""
python3 -m unittest test_srt_endpoint.TestSRTEndpoint.test_simple_decode
3
python3 -m unittest test_srt_endpoint.TestSRTEndpoint.test_logprob_with_chunked_prefill
4
5
"""

6
import json
7
import random
8
import time
9
import unittest
10
from concurrent.futures import ThreadPoolExecutor
11
from typing import Optional
12

13
import numpy as np
14
15
import requests

16
from sglang.srt.sampling.custom_logit_processor import CustomLogitProcessor
17
from sglang.srt.utils import kill_process_tree
18
from sglang.test.test_utils import (
Lianmin Zheng's avatar
Lianmin Zheng committed
19
    DEFAULT_SMALL_MODEL_NAME_FOR_TEST,
20
21
    DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
    DEFAULT_URL_FOR_TEST,
22
23
    popen_launch_server,
)
24
25
26
27
28


class TestSRTEndpoint(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
Lianmin Zheng's avatar
Lianmin Zheng committed
29
        cls.model = DEFAULT_SMALL_MODEL_NAME_FOR_TEST
30
31
        cls.base_url = DEFAULT_URL_FOR_TEST
        cls.process = popen_launch_server(
32
33
34
            cls.model,
            cls.base_url,
            timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
Lianmin Zheng's avatar
Lianmin Zheng committed
35
36
37
38
39
            other_args=(
                "--enable-custom-logit-processor",
                "--mem-fraction-static",
                "0.8",
            ),
40
        )
41
42
43

    @classmethod
    def tearDownClass(cls):
44
        kill_process_tree(cls.process.pid)
45
46

    def run_decode(
47
48
49
50
51
52
        self,
        return_logprob=False,
        top_logprobs_num=0,
        return_text=False,
        n=1,
        stream=False,
53
        batch=False,
54
    ):
55
56
57
58
59
        if batch:
            text = ["The capital of France is"]
        else:
            text = "The capital of France is"

60
61
62
        response = requests.post(
            self.base_url + "/generate",
            json={
63
                "text": text,
64
65
                "sampling_params": {
                    "temperature": 0 if n == 1 else 0.5,
66
                    "max_new_tokens": 16,
67
68
                    "n": n,
                },
69
                "stream": stream,
70
71
72
73
74
75
                "return_logprob": return_logprob,
                "top_logprobs_num": top_logprobs_num,
                "return_text_in_logprobs": return_text,
                "logprob_start_len": 0,
            },
        )
76
77
78
79
80
81
82
        if not stream:
            response_json = response.json()
        else:
            response_json = []
            for line in response.iter_lines():
                if line.startswith(b"data: ") and line[6:] != b"[DONE]":
                    response_json.append(json.loads(line[6:]))
83
84

        print(json.dumps(response_json, indent=2))
85
86
87
88
89
        print("=" * 100)

    def test_simple_decode(self):
        self.run_decode()

90
91
92
    def test_simple_decode_batch(self):
        self.run_decode(batch=True)

93
94
95
    def test_parallel_sample(self):
        self.run_decode(n=3)

96
97
98
    def test_parallel_sample_stream(self):
        self.run_decode(n=3, stream=True)

99
    def test_logprob(self):
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
        self.run_decode(
            return_logprob=True,
            top_logprobs_num=5,
            return_text=True,
        )

    def test_logprob_start_len(self):
        logprob_start_len = 4
        new_tokens = 4
        prompts = [
            "I have a very good idea on",
            "Today is a sunndy day and",
        ]

        response = requests.post(
            self.base_url + "/generate",
            json={
                "text": prompts,
                "sampling_params": {
                    "temperature": 0,
                    "max_new_tokens": new_tokens,
                },
                "return_logprob": True,
                "top_logprobs_num": 5,
                "return_text_in_logprobs": True,
                "logprob_start_len": logprob_start_len,
            },
        )
        response_json = response.json()
        print(json.dumps(response_json, indent=2))

        for i, res in enumerate(response_json):
132
133
134
            self.assertEqual(
                res["meta_info"]["prompt_tokens"],
                logprob_start_len + 1 + len(res["meta_info"]["input_token_logprobs"]),
135
136
137
138
139
            )
            assert prompts[i].endswith(
                "".join([x[-1] for x in res["meta_info"]["input_token_logprobs"]])
            )

140
141
142
143
144
            self.assertEqual(res["meta_info"]["completion_tokens"], new_tokens)
            self.assertEqual(len(res["meta_info"]["output_token_logprobs"]), new_tokens)
            self.assertEqual(
                res["text"],
                "".join([x[-1] for x in res["meta_info"]["output_token_logprobs"]]),
145
            )
146

147
    def test_logprob_with_chunked_prefill(self):
148
        """Test a long prompt that requests output logprobs will not hit OOM."""
149
150
151
152
153
154
155
156
157
158
159
160
161
        new_tokens = 4
        prompts = "I have a very good idea on this. " * 8000

        response = requests.post(
            self.base_url + "/generate",
            json={
                "text": prompts,
                "sampling_params": {
                    "temperature": 0,
                    "max_new_tokens": new_tokens,
                },
                "return_logprob": True,
                "logprob_start_len": -1,
Lianmin Zheng's avatar
Lianmin Zheng committed
162
                "top_logprobs_num": 5,
163
164
165
            },
        )
        response_json = response.json()
Lianmin Zheng's avatar
Lianmin Zheng committed
166
        # print(json.dumps(response_json, indent=2))
167
168
169

        res = response_json
        self.assertEqual(res["meta_info"]["completion_tokens"], new_tokens)
Lianmin Zheng's avatar
Lianmin Zheng committed
170
171

        # Test the number of tokens are correct
172
        self.assertEqual(len(res["meta_info"]["output_token_logprobs"]), new_tokens)
Lianmin Zheng's avatar
Lianmin Zheng committed
173
174
175
176
177
178
179
180
181
        self.assertEqual(len(res["meta_info"]["output_top_logprobs"]), new_tokens)

        # Test the top-1 tokens are the same as output tokens (because temp = 0.0)
        for i in range(new_tokens):
            self.assertListEqual(
                res["meta_info"]["output_token_logprobs"][i],
                res["meta_info"]["output_top_logprobs"][i][0],
            )
            self.assertEqual(len(res["meta_info"]["output_top_logprobs"][i]), 5)
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
    def test_logprob_match(self):
        """Test the output logprobs are close to the input logprobs if we run a prefill again."""

        def run_generate(
            prompt, return_logprob=False, max_new_tokens=512, logprob_start_len=-1
        ):

            if isinstance(prompt, str):
                prompt_kwargs = {"text": prompt}
            else:
                prompt_kwargs = {"input_ids": prompt}

            response = requests.post(
                self.base_url + "/generate",
                json={
                    **prompt_kwargs,
                    "sampling_params": {
                        "temperature": 1.0,
                        "max_new_tokens": max_new_tokens,
                        "ignore_eos": True,
                    },
                    "return_logprob": return_logprob,
                    "return_text_in_logprobs": True,
                    "logprob_start_len": logprob_start_len,
                },
            )
            return response.json()

        prompt = "I have a very good idea on how to"

        gen = run_generate(prompt, return_logprob=True, logprob_start_len=0)
        output_logprobs = np.array(
            [x[0] for x in gen["meta_info"]["output_token_logprobs"]]
        )
        num_prompts_tokens = gen["meta_info"]["prompt_tokens"]

        input_tokens = [x[1] for x in gen["meta_info"]["input_token_logprobs"]]
        output_tokens = [x[1] for x in gen["meta_info"]["output_token_logprobs"]]

        new_prompt = input_tokens + output_tokens
        score = run_generate(
            new_prompt, return_logprob=True, logprob_start_len=0, max_new_tokens=0
        )
        output_logprobs_score = np.array(
            [
                x[0]
                for x in score["meta_info"]["input_token_logprobs"][num_prompts_tokens:]
            ]
        )

        print(f"{output_logprobs[-10:]=}")
        print(f"{output_logprobs_score[-10:]=}")

        diff = np.abs(output_logprobs - output_logprobs_score)
        max_diff = np.max(diff)
238
        self.assertLess(max_diff, 0.25)
239

Lianmin Zheng's avatar
Lianmin Zheng committed
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
    def run_logprob_check(self, arg):
        (
            input_len,
            output_len,
            temperature,
            logprob_start_len,
            return_logprob,
            top_logprobs_num,
        ) = arg
        input_ids = list(range(input_len))

        response = requests.post(
            self.base_url + "/generate",
            json={
                "input_ids": input_ids,
                "sampling_params": {
                    "temperature": temperature,
                    "max_new_tokens": output_len,
                },
                "return_logprob": return_logprob,
                "logprob_start_len": logprob_start_len,
                "top_logprobs_num": top_logprobs_num,
            },
        )
        response_json = response.json()

        res = response_json
        self.assertEqual(res["meta_info"]["prompt_tokens"], input_len)
        self.assertEqual(res["meta_info"]["completion_tokens"], output_len)

        # Test the number of tokens are correct
        if return_logprob:
            # This is because if logprob_start_len == 0, we added a padding for the first token.
            # In other cases, we do not add the padding
            delta = 0 if logprob_start_len == 0 else 1

            self.assertEqual(
                len(res["meta_info"]["input_token_logprobs"])
                + logprob_start_len
                + delta,
                res["meta_info"]["prompt_tokens"],
            )
            self.assertEqual(len(res["meta_info"]["output_token_logprobs"]), output_len)

            if top_logprobs_num:
                self.assertEqual(
                    len(res["meta_info"]["input_top_logprobs"])
                    + logprob_start_len
                    + delta,
                    res["meta_info"]["prompt_tokens"],
                )
                self.assertEqual(
                    len(res["meta_info"]["output_top_logprobs"]), output_len
                )

                for i in range(output_len):
                    self.assertEqual(
                        len(res["meta_info"]["output_top_logprobs"][i]),
                        top_logprobs_num,
                    )

                    # Test the top-1 tokens are the same as output tokens if temperature == 0
                    if temperature == 0:
                        self.assertListEqual(
                            res["meta_info"]["output_token_logprobs"][i],
                            res["meta_info"]["output_top_logprobs"][i][0],
                        )

    def test_logprob_mixed(self):
        args = []
        temperature = 0
        # input_len, output_len, temperature, logprob_start_len, return_logprob, top_logprobs_num
        for input_len in [1000, 2000]:
            for output_len in [4, 8]:
                for logprob_start_len in [0, 500, 1000]:
                    for return_logprob in [True, False]:
                        for top_logprobs_num in [0, 5]:

                            if logprob_start_len >= input_len:
                                continue

                            args.append(
                                (
                                    input_len,
                                    output_len,
                                    temperature,
                                    logprob_start_len,
                                    return_logprob,
                                    top_logprobs_num,
                                )
                            )

        random.shuffle(args)

        with ThreadPoolExecutor(8) as executor:
            list(executor.map(self.run_logprob_check, args))

337
338
339
340
341
342
343
344
345
346
347
348
349
350
    def test_logprob_grammar(self):
        prompts = "Question: Is Paris the Capital of France? Answer:"
        allowed_tokens = [" Yes", " No"]

        response = requests.post(
            self.base_url + "/generate",
            json={
                "text": prompts,
                "sampling_params": {
                    "temperature": 1.0,
                    "max_new_tokens": 1,
                    "regex": "( Yes| No)",
                },
                "return_logprob": True,
351
                "top_logprobs_num": 5,  # The grammar constraint allows all prefix tokens so we need to use a larger top_k.
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
                "return_text_in_logprobs": True,
            },
        )
        response_json = response.json()
        output_top_logprobs = response_json["meta_info"]["output_top_logprobs"][0]
        print(f"{output_top_logprobs=}")

        # Parse results
        # This is becaues the grammar constraint allows all prefix tokens
        logprobs = [None] * 2
        for i in range(len(output_top_logprobs)):
            try:
                idx = allowed_tokens.index(output_top_logprobs[i][2])
            except ValueError:
                # Not found
                continue
            logprobs[idx] = output_top_logprobs[i][0]

        self.assertTrue(all(x is not None for x in logprobs))

372
373
374
375
376
    def run_custom_logit_processor(self, target_token_id: Optional[int] = None):
        """Test custom logit processor with custom params.

        If target_token_id is None, the custom logit processor won't be passed in.
        """
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

        custom_params = {"token_id": target_token_id}

        class DeterministicLogitProcessor(CustomLogitProcessor):
            """A dummy logit processor that changes the logits to always
            sample the given token id.
            """

            def __call__(self, logits, custom_param_list):
                assert logits.shape[0] == len(custom_param_list)
                key = "token_id"

                for i, param_dict in enumerate(custom_param_list):
                    # Mask all other tokens
                    logits[i, :] = -float("inf")
                    # Assign highest probability to the specified token
                    logits[i, param_dict[key]] = 0.0
                return logits

        prompts = "Question: Is Paris the Capital of France? Answer:"

        # Base case json data to be posted to the server.
        base_json = {
            "text": prompts,
            "sampling_params": {"temperature": 0.0},
            "return_logprob": True,
        }

        # Custom json data with custom logit processor and params.
        custom_json = base_json.copy()
407
408
409
410
411
412
        # Only set the custom logit processor if target_token_id is not None.
        if target_token_id is not None:
            custom_json["custom_logit_processor"] = (
                DeterministicLogitProcessor().to_str()
            )
            custom_json["sampling_params"]["custom_params"] = custom_params
413
414
415
416
417
418
419
420
421
422

        custom_response = requests.post(
            self.base_url + "/generate",
            json=custom_json,
        ).json()

        output_token_logprobs = custom_response["meta_info"]["output_token_logprobs"]
        sampled_tokens = [x[1] for x in output_token_logprobs]

        # The logit processor should always sample the given token as the logits is deterministic.
423
424
425
426
427
428
        if target_token_id is not None:
            self.assertTrue(
                all(x == custom_params["token_id"] for x in sampled_tokens),
                # Print the detailed test case info if the test fails.
                f"{target_token_id=}\n{sampled_tokens=}\n{custom_response=}",
            )
429
430
431
432
433

    def test_custom_logit_processor(self):
        """Test custom logit processor with a single request."""
        self.run_custom_logit_processor(target_token_id=5)

434
435
436
437
438
439
440
    def test_custom_logit_processor_batch_mixed(self):
        """Test a batch of requests mixed of requests with and without custom logit processor."""
        target_token_ids = list(range(32)) + [None] * 16
        random.shuffle(target_token_ids)
        with ThreadPoolExecutor(len(target_token_ids)) as executor:
            list(executor.map(self.run_custom_logit_processor, target_token_ids))

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
    def test_cache_tokens(self):
        for _ in range(2):
            time.sleep(1)
            response = requests.post(self.base_url + "/flush_cache")
            assert response.status_code == 200

        def send_and_check_cached_tokens(input_ids):
            response = requests.post(
                self.base_url + "/generate",
                json={
                    "input_ids": list(input_ids),
                    "sampling_params": {
                        "max_new_tokens": 1,
                    },
                },
            )
            response_json = response.json()
            return response_json["meta_info"]["cached_tokens"]

        self.assertEqual(send_and_check_cached_tokens(range(0, 100)), 0)
        self.assertEqual(send_and_check_cached_tokens(range(0, 10000)), 100)
        self.assertEqual(send_and_check_cached_tokens(range(0, 10000)), 9999)
        self.assertEqual(send_and_check_cached_tokens(range(0, 1000)), 999)
        self.assertEqual(send_and_check_cached_tokens(range(0, 11000)), 10000)

466
467
468
469
470
471
472
473
474
    def test_get_server_info(self):
        response = requests.get(self.base_url + "/get_server_info")
        response_json = response.json()

        max_total_num_tokens = response_json["max_total_num_tokens"]
        self.assertIsInstance(max_total_num_tokens, int)

        attention_backend = response_json["attention_backend"]
        self.assertIsInstance(attention_backend, str)
475

476
477
478
        version = response_json["version"]
        self.assertIsInstance(version, str)

479
480

if __name__ == "__main__":
Lianmin Zheng's avatar
Lianmin Zheng committed
481
    unittest.main()