|
| 1 | +import asyncio |
| 2 | +import math |
| 3 | +from typing import List, Union |
| 4 | + |
| 5 | +import torch |
| 6 | +from PIL import Image |
| 7 | + |
| 8 | +from sglang.srt.managers.multimodal_processors.base_processor import ( |
| 9 | + BaseMultimodalProcessor as SGLangBaseProcessor, |
| 10 | +) |
| 11 | +from sglang.srt.managers.multimodal_processors.base_processor import ( |
| 12 | + MultimodalSpecialTokens, |
| 13 | +) |
| 14 | +from sglang.srt.managers.schedule_batch import Modality, MultimodalDataItem |
| 15 | +from sglang.srt.models.kimi_vl import KimiVLForConditionalGeneration |
| 16 | + |
| 17 | + |
| 18 | +# Compatible with KimiVLForConditionalGeneration |
| 19 | +class KimiVLImageProcessor(SGLangBaseProcessor): |
| 20 | + models = [KimiVLForConditionalGeneration] |
| 21 | + |
| 22 | + def __init__(self, hf_config, server_args, _processor): |
| 23 | + super().__init__(hf_config, server_args, _processor) |
| 24 | + self.IMAGE_TOKEN = "<|media_pad|>" |
| 25 | + self.im_token_id = _processor.tokenizer.convert_tokens_to_ids(self.IMAGE_TOKEN) |
| 26 | + |
| 27 | + self.im_start = "<|media_start|>" |
| 28 | + self.im_start_id = _processor.tokenizer.convert_tokens_to_ids(self.im_start) |
| 29 | + |
| 30 | + self.im_end = "<|media_end|>" |
| 31 | + self.im_end_id = _processor.tokenizer.convert_tokens_to_ids(self.im_end) |
| 32 | + |
| 33 | + self.im_content = "<|media_content|>" |
| 34 | + self.im_content_id = _processor.tokenizer.convert_tokens_to_ids(self.im_content) |
| 35 | + |
| 36 | + async def process_mm_data_async( |
| 37 | + self, |
| 38 | + image_data: List[Union[str, bytes]], |
| 39 | + input_text, |
| 40 | + request_obj, |
| 41 | + max_req_input_len, |
| 42 | + *args, |
| 43 | + **kwargs, |
| 44 | + ): |
| 45 | + if not image_data: |
| 46 | + return None |
| 47 | + if isinstance(image_data, str): |
| 48 | + image_data = [image_data] |
| 49 | + |
| 50 | + base_output = self.load_mm_data( |
| 51 | + prompt=input_text, |
| 52 | + image_data=image_data, |
| 53 | + multimodal_tokens=MultimodalSpecialTokens(image_token=self.IMAGE_TOKEN), |
| 54 | + max_req_input_len=max_req_input_len, |
| 55 | + ) |
| 56 | + ret = self.process_mm_data( |
| 57 | + input_text=base_output.input_text, |
| 58 | + images=base_output.images, |
| 59 | + ) |
| 60 | + return { |
| 61 | + "input_ids": ret["input_ids"].flatten().tolist(), |
| 62 | + "mm_items": [ |
| 63 | + MultimodalDataItem( |
| 64 | + pixel_values=ret["pixel_values"], |
| 65 | + image_grid_thws=ret["image_grid_hws"], |
| 66 | + modality=Modality.IMAGE, |
| 67 | + ) |
| 68 | + ], |
| 69 | + "im_token_id": self.im_token_id, |
| 70 | + "im_start_id": self.im_start_id, |
| 71 | + "im_end_id": self.im_end_id, |
| 72 | + "im_content_id": self.im_content_id, |
| 73 | + } |
0 commit comments