sentencepiece_tokenizer.py 15.6 KB
Newer Older
zhuwenwen's avatar
zhuwenwen committed
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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
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
147
148
149
150
151
152
153
154
155
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
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
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
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
407
408
409
410
411
412
413
414
415
416
# SPDX-License-Identifier: Apache-2.0
# mypy: ignore-errors
import glob
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union

import sentencepiece

from vllm.transformers_utils.tokenizer_base import TokenizerBase

if TYPE_CHECKING:
    from vllm.entrypoints.chat_utils import ConversationMessage


@dataclass
class Encoding:
    input_ids: List[int]


class SentencePieceTokenizer(TokenizerBase):
    """SentencePieceTokenizer"""

    def __init__(self, model_file):
        self.name = "SentencePieceTokenizer"
        self.sp_model = sentencepiece.SentencePieceProcessor(
            model_file=model_file)

        # Set special tokens
        self._special_tokens = {}
        self._all_special_tokens = []
        self._all_special_ids = []
        self._vocab = {}
        for idx in range(self.sp_model.get_piece_size()):
            self._vocab[self.sp_model.id_to_piece(idx)] = idx

            if not self.sp_model.is_control(idx):
                continue

            self._special_tokens[self.sp_model.id_to_piece(idx)] = idx
            self._all_special_tokens.append(self.sp_model.id_to_piece(idx))
            self._all_special_ids.append(idx)

        self._special_tokens[self.sp_model.id_to_piece(
            self.sp_model.unk_id())] = self.sp_model.unk_id()
        self._all_special_tokens.append(
            self.sp_model.id_to_piece(self.sp_model.unk_id()))
        self._all_special_ids.append(self.sp_model.unk_id())

        # FIXME: compatible for decode
        self.length = self.sp_model.get_piece_size()

    @property
    def all_special_tokens_extended(self) -> List[str]:
        return self._all_special_tokens

    @property
    def all_special_tokens(self) -> List[str]:
        return self._all_special_tokens
    
    @property
    def all_special_ids(self) -> List[int]:
        return self._all_special_ids
    
    @property
    def eos_token_id(self):
        return self.sp_model.eos_id()

    @property
    def eos_token(self):
        return self.sp_model.id_to_piece(self.eos_token_id)

    @property
    def bos_token_id(self):
        return self.sp_model.bos_id()

    @property
    def unk_token_id(self):
        return self.sp_model.unk_id()

    @property
    def sep_token(self) -> str:
        raise NotImplementedError()

    @property
    def pad_token(self) -> str:
        raise NotImplementedError()
    
    @property
    def vocab_size(self):
        return self.length
    
    @property
    def is_fast(self) -> bool:
        return True

    @property
    def max_token_id(self) -> int:
        return self.sp_model.get_piece_size() - 1
    
    def get_vocab(self):
        return self._vocab
    
    def encode_one(
        self,
        text: str,
        truncation: bool = False,
        max_length: Optional[int] = None,
    ) -> List[int]:
        # Mistral Tokenizers should not add special tokens
        input_ids = self.encode(text)

        if truncation:
            input_ids = input_ids[:max_length]
        return input_ids

    def encode(self,
               text: str,
               add_special_tokens: bool = False,
               add_bos: bool = True) -> List[int]:
        if add_special_tokens:
            # encode control token as normal string
            parts = []
            current_text = text
            
            # Find all special tokens and their positions
            token_positions = []
            for token in self._special_tokens:
                start = 0
                while True:
                    idx = current_text.find(token, start)
                    if idx == -1:
                        break
                    token_positions.append((idx, token))
                    start = idx + 1
            
            # Sort by position to process tokens in order they appear
            token_positions.sort(key=lambda x: x[0])
            
            # Process tokens in order
            last_end = 0
            for pos, token in token_positions:
                # Add text before this token
                if pos > last_end:
                    parts.append(current_text[last_end:pos])
                # Add the token
                parts.append({"token": token})
                last_end = pos + len(token)
            
            # Add remaining text after last token
            if last_end < len(current_text):
                parts.append(current_text[last_end:])

            return self.encode_chatml(parts, add_bos=add_bos)
        else:
            return self.sp_model.encode(text, add_bos=add_bos)

    def decode(self,
               token_ids: Union[List[int], int],
               skip_special_tokens: bool = True) -> str:
        if isinstance(token_ids, int):
            token_ids = [token_ids]
        elif isinstance(token_ids, list) and token_ids and not isinstance(token_ids[0], int):
            token_ids = [int(token) for token in token_ids]
        
        if skip_special_tokens:
            # Original behavior: decode all tokens including special ones
            return self.sp_model.decode(token_ids)
        else:
            # Handle special tokens separately
            result = []
            normal_tokens = []
            
            for token_id in token_ids:
                if token_id in self._all_special_ids:
                    # Decode any accumulated normal tokens first
                    if normal_tokens:
                        result.append(self.sp_model.decode(normal_tokens))
                        normal_tokens = []
                    # Add the special token as string
                    result.append(self.convert_id_to_token(token_id))
                else:
                    # Accumulate normal tokens
                    normal_tokens.append(token_id)
            
            # Decode any remaining normal tokens
            if normal_tokens:
                result.append(self.sp_model.decode(normal_tokens))
            
            return ''.join(result)

    def __call__(
        self,
        text: Union[str, List[str], List[int]],
        text_pair: Optional[str] = None,
        add_special_tokens: bool = False,
        truncation: bool = False,
        max_length: Optional[int] = None,
    ):
        input_ids = self.encode(text, add_bos=True)
        if truncation:
            input_ids = input_ids[:max_length]
        return Encoding(input_ids=input_ids)

    def convert_token_to_id(self, token):
        """Converts a token (str) in an id using the vocab."""
        return self.sp_model.piece_to_id(token)

    def convert_tokens_to_ids(self, tokens):
        return self.sp_model.piece_to_id(tokens)

    def convert_id_to_token(self, index):
        """Converts an index (integer) in a token (str) using the vocab."""
        return self.sp_model.id_to_piece(index)

    def convert_ids_to_tokens(
            self, ids, **kwargs):  # kwargs for compatibility of HF tokenizer
        return self.sp_model.id_to_piece(ids)

    def convert_tokens_to_string(self, tokens, skip_special_tokens=True):
        # FIXME(ys): hack for tool call tokens
        if skip_special_tokens:
            return self.sp_model.decode(tokens)
        else:
            # Handle special tokens separately
            result = []
            normal_tokens = []
            
            for token in tokens:
                if token in self._all_special_tokens:
                    if normal_tokens:
                        result.append(self.sp_model.decode(normal_tokens))
                        normal_tokens = []
                    result.append(token)
                else:
                    # Accumulate normal tokens
                    normal_tokens.append(token)
            
            # Decode any remaining normal tokens
            if normal_tokens:
                result.append(self.sp_model.decode(normal_tokens))
            
            return ''.join(result)

    @classmethod
    def from_pretrained(cls, model_path):
        if model_path.endswith(".model"):
            model_file = model_path
        else:
            possible_files = glob.glob(f"{model_path}/*.model")
            if len(possible_files) != 1:
                raise ValueError(
                    f"Expected exactly one .model file for tokenizer initialization in {model_path}, but found {possible_files}"
                )
            model_file = possible_files[0]
        return cls(model_file=model_file)

    def encode_chatml(self, input, add_bos=True):
        input_ids = [self.bos_token_id] if add_bos else []
        if isinstance(input, str):
            input = [input]
        # Compatible with the StepChat ChatML Protocol.
        for subprompt in input:
            if isinstance(subprompt, str):
                subprompt_ids = self.encode(subprompt, add_bos=False)
                input_ids += subprompt_ids
            elif isinstance(subprompt, dict):
                if "token" in subprompt:
                    input_ids += [self.convert_token_to_id(subprompt["token"])]
        return input_ids

    def get_added_vocab(self):
        return None

    def __len__(self):
        return self.length

    def apply_chat_template(self,
                            conversation: List["ConversationMessage"],
                            tools: Optional[Dict[str, Any]] = None,
                            **kwargs) -> List[int]:
        """Convert chat messages to token IDs sequence.
        
        Args:
            conversation: List of chat messages
            tools: Tool configurations (optional)
            
        Returns:
            List[int]: Sequence of token IDs
        """
        ret = [self.bos_token_id]
        continue_final_message = kwargs.get("continue_final_message", False)

        # Handle tools parameter - properly insert tool_json_schemas message
        processed_conversation = []
        
        # Add tool schemas message following preprocess_python logic
        if tools:
            import json
            tools_message = {
                "role": "tool_json_schemas",
                "content": json.dumps(tools, ensure_ascii=False)  # tools should already be in the right format
            }
            
            if conversation and conversation[0]["role"] == "system":
                processed_conversation.append(conversation[0])
                processed_conversation.append(tools_message)
                processed_conversation.extend(conversation[1:])
            else:
                processed_conversation.append(tools_message)
                processed_conversation.extend(conversation)
        else:
            processed_conversation.extend(conversation)
        
        history_tool_calls_map = {}

        for message in processed_conversation:            
            # Add BOT token
            ret.append(self._special_tokens["<|BOT|>"])
            
            # Handle tool role - map to appropriate output role
            if message["role"] == "tool" and message.get("tool_call_id") in history_tool_calls_map:
                target_tool_call = history_tool_calls_map[message["tool_call_id"]]
                role = f"{target_tool_call['type']}_output\n{target_tool_call['name']}"
            else:
                role = "human" if message["role"] == "user" else message["role"]
            
            content = message.get("content") or ""

            # Process message content
            if isinstance(content, str):
                text = f"{role}\n{content}"
                ret.extend(self.encode(text, add_bos=False))
            elif isinstance(content, list):
                text = f"{role}\n"
                for item in content:
                    if isinstance(item, dict) and item.get("type") == "text":
                        ret.extend(
                            self.encode(text + item["text"], add_bos=False))
                        text = ""
                    elif isinstance(item,
                                    dict) and item.get("type") == "image":
                        if text:
                            ret.extend(self.encode(text, add_bos=False))
                            text = ""
                        ret.append(self._special_tokens["<im_patch>"])
                    elif isinstance(item, dict) and item.get("type") == "audio":
                        if text:
                            ret.extend(self.encode(text, add_bos=False))
                            text = ""
                        ret.append(self._special_tokens["<audio_patch>"])
                    elif isinstance(item, dict) and item.get("type") == "audio_token":
                        if text:
                            ret.extend(self.encode(text, add_bos=False))
                            text = ""
                        ret.append(self._special_tokens["<audio_start>"])
                        ret.extend(self.encode(item["audio_token"], add_bos=False))
                        ret.append(self._special_tokens["<audio_end>"])
                    else:
                        # Handle other multimodal content types
                        if text:
                            ret.extend(self.encode(text, add_bos=False))
                            text = ""

            # Handle tool calls
            if message.get("tool_calls"):
                for tool_call in message["tool_calls"]:
                    if tool_call.get("type") == "function":
                        type_name = "function"
                        function = tool_call.get("function")
                        if function is None:
                            raise ValueError(f"Function is not set for tool call {tool_call.get('id')}: {tool_call}")
                        name = function.get("name")
                        arguments = function.get("arguments")
                        if isinstance(arguments, str):
                            content = arguments
                        else:
                            import json
                            content = json.dumps(arguments, ensure_ascii=False)
                    elif tool_call.get("type") == "code_interpreter":
                        type_name = "code_interpreter"
                        code_interpreter = tool_call.get("code_interpreter")
                        if code_interpreter is None:
                            raise ValueError(
                                f"Code interpreter is not set for tool call {tool_call.get('id')}: {tool_call}"
                            )
                        name = code_interpreter.get("language")
                        content = code_interpreter.get("code")
                    else:
                        raise ValueError(
                            f"Unknown tool call type {tool_call.get('type')}, must be either 'function' or 'code_interpreter': {tool_call}"
                        )

                    # Store tool call info for mapping responses
                    history_tool_calls_map[tool_call.get("id")] = {
                        "type": type_name,
                        "name": name,
                        "content": content,
                    }

                    # Add tool call tokens
                    ret.append(self._special_tokens["<|CALL_START|>"])
                    tool_call_text = f"{type_name}\n{name}\n{content}"
                    ret.extend(self.encode(tool_call_text, add_bos=False))
                    ret.append(self._special_tokens["<|CALL_END|>"])

            ret.append(self._special_tokens["<|EOT|>"])

        # If the last message is not from assistant, add assistant prompt
        if processed_conversation[-1]["role"] != "assistant" and not continue_final_message:
            ret.append(self._special_tokens["<|BOT|>"])
            ret.extend(self.encode("assistant\n", add_bos=False))
        # If the last message is from assistant, remove the last EOT token
        elif ret[-1] == self._special_tokens["<|EOT|>"]:
            ret.pop()

        return ret