tokenizer_manager.py 8.51 KB
Newer Older
Lianmin Zheng's avatar
Lianmin Zheng committed
1
2
3
import asyncio
import concurrent.futures
import dataclasses
4
import multiprocessing as mp
Lianmin Zheng's avatar
Lianmin Zheng committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import os
from typing import List

import numpy as np
import transformers
import uvloop
import zmq
import zmq.asyncio
from sglang.srt.hf_transformers_utils import (
    get_config,
    get_context_length,
    get_processor,
    get_tokenizer,
)
from sglang.srt.managers.io_struct import (
    BatchStrOut,
    GenerateReqInput,
    TokenizedGenerateReqInput,
)
shiyi.c_98's avatar
shiyi.c_98 committed
24
from sglang.srt.mm_utils import expand2square, process_anyres_image
Lianmin Zheng's avatar
Lianmin Zheng committed
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from sglang.srt.sampling_params import SamplingParams
from sglang.srt.server_args import PortArgs, ServerArgs
from sglang.srt.utils import get_exception_traceback, is_multimodal_model, load_image

asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())


@dataclasses.dataclass
class ReqState:
    out_list: List
    finished: bool
    event: asyncio.Event
    lock: asyncio.Lock


global global_processor


def init_global_processor(server_args: ServerArgs):
    global global_processor
    transformers.logging.set_verbosity_error()
    global_processor = get_processor(
        server_args.tokenizer_path,
        tokenizer_mode=server_args.tokenizer_mode,
        trust_remote_code=server_args.trust_remote_code,
    )


shiyi.c_98's avatar
shiyi.c_98 committed
53
54
def get_pixel_values(image_data, model_cfg, processor=None):
    image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None)
Lianmin Zheng's avatar
Lianmin Zheng committed
55
56
57
58
    try:
        processor = processor or global_processor
        image = load_image(image_data)
        image_hash = hash(image_data)
shiyi.c_98's avatar
shiyi.c_98 committed
59
60
61
62
63
64
65
66
67
68
69
        if image_aspect_ratio == "pad":
            image = expand2square(
                image, tuple(int(x * 255) for x in processor.image_processor.image_mean)
            )
            pixel_values = processor.image_processor(image)["pixel_values"][0]
        elif image_aspect_ratio == "anyres":
            pixel_values = process_anyres_image(
                image, processor.image_processor, model_cfg.image_grid_pinpoints
            )
        else:
            pixel_values = processor.image_processor(image)["pixel_values"][0]
Lianmin Zheng's avatar
Lianmin Zheng committed
70
        pixel_values = pixel_values.astype(np.float16)
shiyi.c_98's avatar
shiyi.c_98 committed
71
        return pixel_values, image_hash, image.size
Lianmin Zheng's avatar
Lianmin Zheng committed
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
    except Exception:
        print("Exception in TokenizerManager:\n" + get_exception_traceback())


class TokenizerManager:
    def __init__(
        self,
        server_args: ServerArgs,
        port_args: PortArgs,
    ):
        context = zmq.asyncio.Context(2)
        self.recv_from_detokenizer = context.socket(zmq.PULL)
        self.recv_from_detokenizer.bind(f"tcp://127.0.0.1:{port_args.tokenizer_port}")

        self.send_to_router = context.socket(zmq.PUSH)
        self.send_to_router.connect(f"tcp://127.0.0.1:{port_args.router_port}")

        self.model_path = server_args.model_path
        self.hf_config = get_config(
            self.model_path, trust_remote_code=server_args.trust_remote_code
        )
shiyi.c_98's avatar
shiyi.c_98 committed
93

Lianmin Zheng's avatar
Lianmin Zheng committed
94
95
96
97
98
99
100
101
102
103
104
        self.context_len = get_context_length(self.hf_config)

        if is_multimodal_model(self.model_path):
            self.processor = get_processor(
                server_args.tokenizer_path,
                tokenizer_mode=server_args.tokenizer_mode,
                trust_remote_code=server_args.trust_remote_code,
            )
            self.tokenizer = self.processor.tokenizer
            os.environ["TOKENIZERS_PARALLELISM"] = "false"
            self.executor = concurrent.futures.ProcessPoolExecutor(
105
106
107
                initializer=init_global_processor,
                mp_context=mp.get_context("fork"),
                initargs=(server_args,),
Lianmin Zheng's avatar
Lianmin Zheng committed
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
            )
        else:
            self.tokenizer = get_tokenizer(
                server_args.tokenizer_path,
                tokenizer_mode=server_args.tokenizer_mode,
                trust_remote_code=server_args.trust_remote_code,
            )

        self.to_create_loop = True
        self.rid_to_state = {}  # Dict[str -> ReqState]

    async def get_pixel_values(self, image_data):
        if self.executor is not None:
            loop = asyncio.get_event_loop()
            return await loop.run_in_executor(
shiyi.c_98's avatar
shiyi.c_98 committed
123
                self.executor, get_pixel_values, image_data, self.hf_config
Lianmin Zheng's avatar
Lianmin Zheng committed
124
125
            )
        else:
shiyi.c_98's avatar
shiyi.c_98 committed
126
            return get_pixel_values(image_data, self.hf_config, self.processor)
Lianmin Zheng's avatar
Lianmin Zheng committed
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141

    async def generate_request(self, obj: GenerateReqInput):
        if self.to_create_loop:
            await self.create_handle_loop()

        is_single = isinstance(obj.text, str)

        if is_single:
            rid = obj.rid
            input_ids = self.tokenizer.encode(obj.text)
            sampling_params = SamplingParams(**obj.sampling_params)
            if sampling_params.max_new_tokens != 0:
                sampling_params.normalize(self.tokenizer)
                sampling_params.verify()
            if obj.image_data is None:
shiyi.c_98's avatar
shiyi.c_98 committed
142
                pixel_values, image_hash, image_size = None, None, None
Lianmin Zheng's avatar
Lianmin Zheng committed
143
            else:
shiyi.c_98's avatar
shiyi.c_98 committed
144
145
146
                pixel_values, image_hash, image_size = await self.get_pixel_values(
                    obj.image_data
                )
Lianmin Zheng's avatar
Lianmin Zheng committed
147
148
149
150
151
            tokenized_obj = TokenizedGenerateReqInput(
                rid=rid,
                input_ids=input_ids,
                pixel_values=pixel_values,
                image_hash=image_hash,
shiyi.c_98's avatar
shiyi.c_98 committed
152
                image_size=image_size,
Lianmin Zheng's avatar
Lianmin Zheng committed
153
                sampling_params=sampling_params,
154
155
                return_logprob=obj.return_logprob,
                logprob_start_len=obj.logprob_start_len,
Lianmin Zheng's avatar
Lianmin Zheng committed
156
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
                stream=obj.stream,
            )
            self.send_to_router.send_pyobj(tokenized_obj)

            lock = asyncio.Lock()
            event = asyncio.Event()
            state = ReqState([], False, event, lock)
            self.rid_to_state[rid] = state

            while True:
                await event.wait()
                yield state.out_list[-1]
                state.out_list = []
                if state.finished:
                    del self.rid_to_state[rid]
                    break
                event.clear()
        else:
            assert obj.stream is False
            bs = len(obj.text)
            for i in range(bs):
                rid = obj.rid[i]
                input_ids = self.tokenizer.encode(obj.text[i])
                sampling_params = SamplingParams(**obj.sampling_params[i])
                if sampling_params.max_new_tokens != 0:
                    sampling_params.normalize(self.tokenizer)
                    sampling_params.verify()
                if obj.image_data[i] is None:
shiyi.c_98's avatar
shiyi.c_98 committed
184
                    pixel_values, image_hash, image_size = None, None, None
Lianmin Zheng's avatar
Lianmin Zheng committed
185
                else:
shiyi.c_98's avatar
shiyi.c_98 committed
186
                    pixel_values, image_hash, image_size = await self.get_pixel_values(
Lianmin Zheng's avatar
Lianmin Zheng committed
187
188
189
190
191
192
193
                        obj.image_data[i]
                    )
                tokenized_obj = TokenizedGenerateReqInput(
                    rid=rid,
                    input_ids=input_ids,
                    pixel_values=pixel_values,
                    image_hash=image_hash,
shiyi.c_98's avatar
shiyi.c_98 committed
194
                    image_size=image_size,
Lianmin Zheng's avatar
Lianmin Zheng committed
195
                    sampling_params=sampling_params,
196
197
                    return_logprob=obj.return_logprob[i],
                    logprob_start_len=obj.logprob_start_len[i],
Lianmin Zheng's avatar
Lianmin Zheng committed
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
                    stream=obj.stream,
                )
                self.send_to_router.send_pyobj(tokenized_obj)

                lock = asyncio.Lock()
                event = asyncio.Event()
                state = ReqState([], False, event, lock)
                self.rid_to_state[rid] = state

            output_list = []
            for i in range(bs):
                rid = obj.rid[i]
                state = self.rid_to_state[rid]
                await state.event.wait()
                output_list.append(state.out_list[-1])
                assert state.finished
                del self.rid_to_state[rid]

            yield output_list

    async def create_handle_loop(self):
        self.to_create_loop = False
        loop = asyncio.get_event_loop()
        loop.create_task(self.handle_loop())

    async def handle_loop(self):
        while True:
            recv_obj = await self.recv_from_detokenizer.recv_pyobj()

            if isinstance(recv_obj, BatchStrOut):
                for i, rid in enumerate(recv_obj.rids):
                    recv_obj.meta_info[i]["id"] = rid
                    out_dict = {
                        "text": recv_obj.output_str[i],
                        "meta_info": recv_obj.meta_info[i],
                    }
                    state = self.rid_to_state[rid]
                    state.out_list.append(out_dict)
                    state.finished = recv_obj.finished[i]
                    state.event.set()
            else:
                raise ValueError(f"Invalid object: {recv_obj}")