test_vision_openai_server_common.py 19.8 KB
Newer Older
1
2
3
import base64
import io
import os
4
from concurrent.futures import ThreadPoolExecutor
Ying Sheng's avatar
Ying Sheng committed
5

6
import numpy as np
Ying Sheng's avatar
Ying Sheng committed
7
import openai
8
9
import requests
from PIL import Image
Ying Sheng's avatar
Ying Sheng committed
10

11
from sglang.srt.utils import kill_process_tree
12
13
14
15
16
17
from sglang.test.test_utils import (
    DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
    DEFAULT_URL_FOR_TEST,
    CustomTestCase,
    popen_launch_server,
)
Ying Sheng's avatar
Ying Sheng committed
18

19
20
21
22
23
24
25
26
27
28
29
# image
IMAGE_MAN_IRONING_URL = "https://raw.githubusercontent.com/sgl-project/sgl-test-files/refs/heads/main/images/man_ironing_on_back_of_suv.png"
IMAGE_SGL_LOGO_URL = "https://raw.githubusercontent.com/sgl-project/sgl-test-files/refs/heads/main/images/sgl_logo.png"

# video
VIDEO_JOBS_URL = "https://raw.githubusercontent.com/sgl-project/sgl-test-files/refs/heads/main/videos/jobs_presenting_ipod.mp4"

# audio
AUDIO_TRUMP_SPEECH_URL = "https://raw.githubusercontent.com/sgl-project/sgl-test-files/refs/heads/main/audios/Trump_WEF_2018_10s.mp3"
AUDIO_BIRD_SONG_URL = "https://raw.githubusercontent.com/sgl-project/sgl-test-files/refs/heads/main/audios/bird_song.mp3"

Ying Sheng's avatar
Ying Sheng committed
30

31
class TestOpenAIMLLMServerBase(CustomTestCase):
32
33
34
35
    model: str
    extra_args: list = []
    fixed_args: list = ["--trust-remote-code", "--enable-multimodal"]

Ying Sheng's avatar
Ying Sheng committed
36
37
    @classmethod
    def setUpClass(cls):
38
        cls.base_url = DEFAULT_URL_FOR_TEST
Ying Sheng's avatar
Ying Sheng committed
39
        cls.api_key = "sk-123456"
40
41
42
43
44
45
46
        cls.process = popen_launch_server(
            cls.model,
            cls.base_url,
            timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
            api_key=cls.api_key,
            other_args=cls.extra_args + cls.fixed_args,
        )
Ying Sheng's avatar
Ying Sheng committed
47
48
49
50
        cls.base_url += "/v1"

    @classmethod
    def tearDownClass(cls):
51
        kill_process_tree(cls.process.pid)
Ying Sheng's avatar
Ying Sheng committed
52

53
54
55
    def get_vision_request_kwargs(self):
        return self.get_request_kwargs()

56
57
58
    def get_request_kwargs(self):
        return {}

59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
    def get_or_download_file(self, url: str) -> str:
        cache_dir = os.path.expanduser("~/.cache")
        if url is None:
            raise ValueError()
        file_name = url.split("/")[-1]
        file_path = os.path.join(cache_dir, file_name)
        os.makedirs(cache_dir, exist_ok=True)

        if not os.path.exists(file_path):
            response = requests.get(url)
            response.raise_for_status()

            with open(file_path, "wb") as f:
                f.write(response.content)
        return file_path


76
77
78
79
80
81
82
83
84
85
86
87
88
89
class AudioOpenAITestMixin(TestOpenAIMLLMServerBase):
    def verify_speech_recognition_response(self, text):
        check_list = [
            "thank you",
            "it's a privilege to be here",
            "leader",
            "science",
            "art",
        ]
        for check_word in check_list:
            assert (
                check_word in text.lower()
            ), f"audio_response: |{text}| should contain |{check_word}|"

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
    def prepare_audio_messages(self, prompt, audio_file_name):
        messages = [
            {
                "role": "user",
                "content": [
                    {
                        "type": "audio_url",
                        "audio_url": {"url": f"{audio_file_name}"},
                    },
                    {
                        "type": "text",
                        "text": prompt,
                    },
                ],
            }
        ]

        return messages

    def get_audio_request_kwargs(self):
        return self.get_request_kwargs()

    def get_audio_response(self, url: str, prompt, category):
        audio_file_path = self.get_or_download_file(url)
        client = openai.Client(api_key="sk-123456", base_url=self.base_url)

        messages = self.prepare_audio_messages(prompt, audio_file_path)

        response = client.chat.completions.create(
            model="default",
            messages=messages,
            temperature=0,
            max_tokens=128,
            stream=False,
            **(self.get_audio_request_kwargs()),
        )

        audio_response = response.choices[0].message.content

        print("-" * 30)
        print(f"audio {category} response:\n{audio_response}")
        print("-" * 30)

        audio_response = audio_response.lower()

        self.assertIsNotNone(audio_response)
        self.assertGreater(len(audio_response), 0)

        return audio_response.lower()

    def test_audio_speech_completion(self):
        # a fragment of Trump's speech
        audio_response = self.get_audio_response(
            AUDIO_TRUMP_SPEECH_URL,
            "Listen to this audio and write down the audio transcription in English.",
            category="speech",
        )
147
        self.verify_speech_recognition_response(audio_response)
148
149
150
151
152
153
154
155
156
157
158

    def test_audio_ambient_completion(self):
        # bird song
        audio_response = self.get_audio_response(
            AUDIO_BIRD_SONG_URL,
            "Please listen to the audio snippet carefully and transcribe the content in English.",
            "ambient",
        )
        assert "bird" in audio_response


159
160
class ImageOpenAITestMixin(TestOpenAIMLLMServerBase):
    def run_decode_with_image(self, image_id):
Ying Sheng's avatar
Ying Sheng committed
161
162
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)

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
        content = []
        if image_id == 0:
            content.append(
                {
                    "type": "image_url",
                    "image_url": {"url": IMAGE_MAN_IRONING_URL},
                }
            )
        elif image_id == 1:
            content.append(
                {
                    "type": "image_url",
                    "image_url": {"url": IMAGE_SGL_LOGO_URL},
                }
            )
        else:
            pass

        content.append(
            {
                "type": "text",
                "text": "Describe this image in a sentence.",
            }
        )

Ying Sheng's avatar
Ying Sheng committed
188
189
190
        response = client.chat.completions.create(
            model="default",
            messages=[
191
                {"role": "user", "content": content},
Ying Sheng's avatar
Ying Sheng committed
192
193
            ],
            temperature=0,
194
            **(self.get_vision_request_kwargs()),
Ying Sheng's avatar
Ying Sheng committed
195
196
197
        )

        assert response.choices[0].message.role == "assistant"
Ying Sheng's avatar
Ying Sheng committed
198
199
        text = response.choices[0].message.content
        assert isinstance(text, str)
200
201
202
203
204
205
206
207
208
209
210

    def test_mixed_batch(self):
        image_ids = [0, 1, 2] * 4
        with ThreadPoolExecutor(4) as executor:
            list(executor.map(self.run_decode_with_image, image_ids))

    def verify_single_image_response(self, response):
        assert response.choices[0].message.role == "assistant"
        text = response.choices[0].message.content
        assert isinstance(text, str)

211
        # `driver` is for gemma-3-it
212
213
214
215
216
217
218
219
220
221
        assert (
            "man" in text or "person" or "driver" in text
        ), f"text: {text}, should contain man, person or driver"
        assert (
            "cab" in text
            or "taxi" in text
            or "SUV" in text
            or "vehicle" in text
            or "car" in text
        ), f"text: {text}, should contain cab, taxi, SUV, vehicle or car"
Mick's avatar
Mick committed
222
        # MiniCPMO fails to recognize `iron`, but `hanging`
223
        assert (
224
225
            "iron" in text or "hang" in text or "cloth" in text or "holding" in text
        ), f"text: {text}, should contain iron, hang, cloth or holding"
226
227
228
229
230
231
        assert response.id
        assert response.created
        assert response.usage.prompt_tokens > 0
        assert response.usage.completion_tokens > 0
        assert response.usage.total_tokens > 0

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
    def test_single_image_chat_completion(self):
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)

        response = client.chat.completions.create(
            model="default",
            messages=[
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "image_url",
                            "image_url": {"url": IMAGE_MAN_IRONING_URL},
                        },
                        {
                            "type": "text",
                            "text": "Describe this image in a sentence.",
                        },
                    ],
                },
            ],
            temperature=0,
            **(self.get_vision_request_kwargs()),
        )

        print("-" * 30)
        print(f"Single image response:\n{response.choices[0].message.content}")
        print("-" * 30)

        self.verify_single_image_response(response)

262
263
264
265
266
267
268
269
270
271
272
    def test_multi_turn_chat_completion(self):
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)

        response = client.chat.completions.create(
            model="default",
            messages=[
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "image_url",
273
                            "image_url": {"url": IMAGE_MAN_IRONING_URL},
274
275
276
                        },
                        {
                            "type": "text",
277
                            "text": "Describe this image in a sentence.",
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
                        },
                    ],
                },
                {
                    "role": "assistant",
                    "content": [
                        {
                            "type": "text",
                            "text": "There is a man at the back of a yellow cab ironing his clothes.",
                        }
                    ],
                },
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "Repeat your previous answer."}
                    ],
                },
            ],
            temperature=0,
298
            **(self.get_vision_request_kwargs()),
299
300
301
302
303
        )

        assert response.choices[0].message.role == "assistant"
        text = response.choices[0].message.content
        assert isinstance(text, str)
304
305
306
        assert (
            "man" in text or "cab" in text
        ), f"text: {text}, should contain man or cab"
Ying Sheng's avatar
Ying Sheng committed
307
308
309
310
        assert response.id
        assert response.created
        assert response.usage.prompt_tokens > 0
        assert response.usage.completion_tokens > 0
311
312
        assert response.usage.total_tokens > 0

313
    def test_multi_images_chat_completion(self):
314
315
316
317
318
319
320
321
322
323
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)

        response = client.chat.completions.create(
            model="default",
            messages=[
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "image_url",
Mick's avatar
Mick committed
324
                            "image_url": {"url": IMAGE_MAN_IRONING_URL},
325
                            "modalities": "multi-images",
326
327
328
                        },
                        {
                            "type": "image_url",
329
                            "image_url": {"url": IMAGE_SGL_LOGO_URL},
330
                            "modalities": "multi-images",
331
332
333
                        },
                        {
                            "type": "text",
334
                            "text": "I have two very different images. Please describe them.",
335
336
337
338
339
                        },
                    ],
                },
            ],
            temperature=0,
340
            **(self.get_vision_request_kwargs()),
341
342
343
344
345
        )

        assert response.choices[0].message.role == "assistant"
        text = response.choices[0].message.content
        assert isinstance(text, str)
Mick's avatar
Mick committed
346
347
348
        print("-" * 30)
        print(f"Multi images response:\n{text}")
        print("-" * 30)
349
        assert (
350
351
352
353
354
355
            "man" in text
            or "cab" in text
            or "SUV" in text
            or "taxi" in text
            or "car" in text
        ), f"text: {text}, should contain man, cab, SUV, taxi or car"
356
        assert (
357
358
            "logo" in text or '"S"' in text or "SG" in text or "graphic" in text
        ), f"text: {text}, should contain logo, S or SG or graphic"
359
360
361
362
        assert response.id
        assert response.created
        assert response.usage.prompt_tokens > 0
        assert response.usage.completion_tokens > 0
363
364
        assert response.usage.total_tokens > 0

365
    def prepare_video_images_messages(self, video_path):
366
367
        # the memory consumed by the Vision Attention varies a lot, e.g. blocked qkv vs full-sequence sdpa
        # the size of the video embeds differs from the `modality` argument when preprocessed
368
369
370
371
372
373
374

        # We import decord here to avoid a strange Segmentation fault (core dumped) issue.
        # The following import order will cause Segmentation fault.
        # import decord
        # from transformers import AutoTokenizer
        from decord import VideoReader, cpu

375
        max_frames_num = 10
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
        vr = VideoReader(video_path, ctx=cpu(0))
        total_frame_num = len(vr)
        uniform_sampled_frames = np.linspace(
            0, total_frame_num - 1, max_frames_num, dtype=int
        )
        frame_idx = uniform_sampled_frames.tolist()
        frames = vr.get_batch(frame_idx).asnumpy()

        base64_frames = []
        for frame in frames:
            pil_img = Image.fromarray(frame)
            buff = io.BytesIO()
            pil_img.save(buff, format="JPEG")
            base64_str = base64.b64encode(buff.getvalue()).decode("utf-8")
            base64_frames.append(base64_str)

        messages = [{"role": "user", "content": []}]
        frame_format = {
            "type": "image_url",
            "image_url": {"url": "data:image/jpeg;base64,{}"},
396
            "modalities": "image",
397
398
399
400
401
402
403
404
405
406
407
408
409
        }

        for base64_frame in base64_frames:
            frame_format["image_url"]["url"] = "data:image/jpeg;base64,{}".format(
                base64_frame
            )
            messages[0]["content"].append(frame_format.copy())

        prompt = {"type": "text", "text": "Please describe the video in detail."}
        messages[0]["content"].append(prompt)

        return messages

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
    def test_video_images_chat_completion(self):
        url = VIDEO_JOBS_URL
        file_path = self.get_or_download_file(url)

        client = openai.Client(api_key=self.api_key, base_url=self.base_url)

        messages = self.prepare_video_images_messages(file_path)

        response = client.chat.completions.create(
            model="default",
            messages=messages,
            temperature=0,
            max_tokens=1024,
            stream=False,
        )

        video_response = response.choices[0].message.content

        print("-" * 30)
        print(f"Video images response:\n{video_response}")
        print("-" * 30)

        # Add assertions to validate the video response
        assert (
            "iPod" in video_response
            or "device" in video_response
            or "microphone" in video_response
437
        ), f"""
438
        ====================== video_images response =====================
439
440
441
442
        {video_response}
        ===========================================================
        should contain 'iPod' or 'device' or 'microphone'
        """
443
444
445
446
447
        assert (
            "man" in video_response
            or "person" in video_response
            or "individual" in video_response
            or "speaker" in video_response
448
            or "presenter" in video_response
449
            or "Steve" in video_response
450
            or "hand" in video_response
451
        ), f"""
452
        ====================== video_images response =====================
453
454
        {video_response}
        ===========================================================
455
        should contain 'man' or 'person' or 'individual' or 'speaker' or 'presenter' or 'Steve' or 'hand'
456
        """
457
458
459
460
461
        assert (
            "present" in video_response
            or "examine" in video_response
            or "display" in video_response
            or "hold" in video_response
462
        ), f"""
463
        ====================== video_images response =====================
464
465
466
467
        {video_response}
        ===========================================================
        should contain 'present' or 'examine' or 'display' or 'hold'
        """
468
469
470
        self.assertIsNotNone(video_response)
        self.assertGreater(len(video_response), 0)

471

472
class VideoOpenAITestMixin(TestOpenAIMLLMServerBase):
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
    def prepare_video_messages(self, video_path):
        messages = [
            {
                "role": "user",
                "content": [
                    {
                        "type": "video_url",
                        "video_url": {"url": f"{video_path}"},
                    },
                    {"type": "text", "text": "Please describe the video in detail."},
                ],
            },
        ]
        return messages

    def test_video_chat_completion(self):
489
490
        url = VIDEO_JOBS_URL
        file_path = self.get_or_download_file(url)
491
492
493
494
495

        client = openai.Client(api_key=self.api_key, base_url=self.base_url)

        messages = self.prepare_video_messages(file_path)

Mick's avatar
Mick committed
496
        response = client.chat.completions.create(
497
498
499
500
            model="default",
            messages=messages,
            temperature=0,
            max_tokens=1024,
Mick's avatar
Mick committed
501
            stream=False,
502
            **(self.get_vision_request_kwargs()),
503
        )
504

505
        video_response = response.choices[0].message.content.lower()
Mick's avatar
Mick committed
506

507
        print("-" * 30)
Mick's avatar
Mick committed
508
        print(f"Video response:\n{video_response}")
509
510
511
        print("-" * 30)

        # Add assertions to validate the video response
512
        assert (
513
            "ipod" in video_response
514
515
            or "device" in video_response
            or "microphone" in video_response
516
            or "phone" in video_response
517
        ), f"video_response: {video_response}, should contain 'iPod' or 'device'"
Mick's avatar
Mick committed
518
519
520
521
        assert (
            "man" in video_response
            or "person" in video_response
            or "individual" in video_response
522
            or "speaker" in video_response
523
            or "presenter" in video_response
524
            or "hand" in video_response
525
        ), f"video_response: {video_response}, should either have 'man' in video_response, or 'person' in video_response, or 'individual' in video_response or 'speaker' in video_response or 'presenter' or 'hand' in video_response"
Mick's avatar
Mick committed
526
527
528
529
        assert (
            "present" in video_response
            or "examine" in video_response
            or "display" in video_response
530
            or "hold" in video_response
531
532
533
534
        ), f"video_response: {video_response}, should contain 'present', 'examine', 'display', or 'hold'"
        assert (
            "black" in video_response or "dark" in video_response
        ), f"video_response: {video_response}, should contain 'black' or 'dark'"
535
536
        self.assertIsNotNone(video_response)
        self.assertGreater(len(video_response), 0)
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


class OmniOpenAITestMixin(
    ImageOpenAITestMixin, VideoOpenAITestMixin, AudioOpenAITestMixin
):
    def test_mixed_modality_chat_completion(self):
        client = openai.Client(api_key=self.api_key, base_url=self.base_url)
        messages = [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {"url": IMAGE_MAN_IRONING_URL},
                    },
                    {
                        "type": "audio_url",
                        "audio_url": {"url": AUDIO_TRUMP_SPEECH_URL},
                    },
                    {
                        "type": "text",
                        "text": "I have an image and audio, which are not related at all. Please:  1. Describe the image in a sentence, 2. Repeat the exact words from the audio I provided. Be exact",
                    },
                ],
            },
        ]
        response = client.chat.completions.create(
            model="default",
            messages=messages,
            temperature=0,
            max_tokens=128,
            stream=False,
        )

        text = response.choices[0].message.content

        print("-" * 30)
        print(f"Mixed modality response:\n{text}")
        print("-" * 30)

        self.verify_single_image_response(response=response)
        self.verify_speech_recognition_response(text=text)