ADAPT-Chase commited on
Commit
a6d1a54
·
verified ·
1 Parent(s): 501448b

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/__init__.cpython-312.pyc +0 -0
  2. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/config.cpython-312.pyc +0 -0
  3. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/detokenizer.cpython-312.pyc +0 -0
  4. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/detokenizer_utils.cpython-312.pyc +0 -0
  5. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/dynamic_module.cpython-312.pyc +0 -0
  6. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/processor.cpython-312.pyc +0 -0
  7. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/configs/mistral.py +164 -0
  8. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/configs/mlp_speculator.py +68 -0
  9. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/configs/moonvit.py +33 -0
  10. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/configs/nemotron.py +205 -0
  11. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/configs/nemotron_h.py +259 -0
  12. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/configs/nemotron_vl.py +56 -0
  13. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/configs/ovis.py +176 -0
  14. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/configs/step3_vl.py +123 -0
  15. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/configs/ultravox.py +112 -0
  16. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/processors/__init__.py +15 -0
  17. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/processors/deepseek_vl2.py +363 -0
  18. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/processors/ovis.py +420 -0
  19. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/tokenizers/__init__.py +10 -0
  20. tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/tokenizers/mistral.py +516 -0
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (962 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/config.cpython-312.pyc ADDED
Binary file (32.7 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/detokenizer.cpython-312.pyc ADDED
Binary file (5.79 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/detokenizer_utils.cpython-312.pyc ADDED
Binary file (5.89 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/dynamic_module.cpython-312.pyc ADDED
Binary file (1.93 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/processor.cpython-312.pyc ADDED
Binary file (7.93 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/configs/mistral.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+ from typing import Any
4
+
5
+ from transformers import PretrainedConfig, WhisperConfig
6
+
7
+ from vllm.logger import init_logger
8
+
9
+ logger = init_logger(__name__)
10
+
11
+
12
+ def adapt_config_dict(config_dict: dict[str, Any],
13
+ **kwargs) -> PretrainedConfig:
14
+ config_dict.update(kwargs)
15
+ config_dict = _remap_general_mistral_args(config_dict)
16
+
17
+ if bool(config_dict.get("quantization")):
18
+ config_dict = _remap_mistral_quantization_args(config_dict)
19
+
20
+ if bool(config_dict.get("moe")):
21
+ config_dict["architectures"] = ["MixtralForCausalLM"]
22
+ else:
23
+ config_dict["architectures"] = ["MistralForCausalLM"]
24
+
25
+ if bool(config_dict.get("yarn")):
26
+ config_dict = _remap_mistral_yarn_args(config_dict)
27
+
28
+ is_vision = ((config_dict.get("multimodal")
29
+ or {}).get("vision_encoder_args")
30
+ or config_dict.get("vision_encoder"))
31
+ is_audio = bool(
32
+ ((config_dict.get("multimodal") or {}).get("whisper_model_args")
33
+ or {}).get("encoder_args"))
34
+
35
+ assert not (is_vision and is_audio), \
36
+ "Vision and audio are mutually exclusive"
37
+
38
+ if is_vision:
39
+ config_dict = _remap_mistral_vision_args(config_dict)
40
+ if is_audio:
41
+ config_dict = _remap_mistral_audio_args(config_dict)
42
+
43
+ config = PretrainedConfig.from_dict(config_dict)
44
+
45
+ logger.debug("Initialized config %s", config)
46
+
47
+ return config
48
+
49
+
50
+ def _remap_mistral_vision_args(config: dict) -> dict:
51
+ if config.get("multimodal"):
52
+ vision_config = config.pop("multimodal")
53
+ else:
54
+ vision_config = config.pop("vision_encoder")
55
+
56
+ quant_config = config.get("quantization_config")
57
+ config = {
58
+ "model_type": "pixtral",
59
+ "architectures": ["PixtralForConditionalGeneration"],
60
+ "text_config": PretrainedConfig.from_dict(config),
61
+ "vision_config": PretrainedConfig.from_dict(vision_config),
62
+ }
63
+ if quant_config:
64
+ config["quantization_config"] = quant_config
65
+ return config
66
+
67
+
68
+ def _remap_mistral_yarn_args(config: dict) -> dict:
69
+ # Direct remaps: yarn.X -> rope_scaling.Y
70
+ # Source keys are from mistral.model.args.YarnArgs
71
+ _map = {
72
+ "beta": "beta_fast",
73
+ "alpha": "beta_slow",
74
+ }
75
+ yarn_config = config.get("yarn") or {}
76
+ renamed_yarn_config = {_map.get(k, k): v for k, v in yarn_config.items()}
77
+ config["rope_scaling"] = {
78
+ "rope_type": "yarn",
79
+ "mscale_all_dim": 1, # We hardcoded this to 1
80
+ **renamed_yarn_config
81
+ }
82
+ return config
83
+
84
+
85
+ def _remap_general_mistral_args(config: dict) -> dict:
86
+ # Mistral key -> HF key
87
+ config_mapping = {
88
+ "dim": "hidden_size",
89
+ "norm_eps": "rms_norm_eps",
90
+ "n_kv_heads": "num_key_value_heads",
91
+ "n_layers": "num_hidden_layers",
92
+ "n_heads": "num_attention_heads",
93
+ "hidden_dim": "intermediate_size",
94
+ }
95
+ # HF key -> (Mistral key, default value)
96
+ top_level_mapping_with_default = {
97
+ "model_type": ("model_type", "transformer"),
98
+ "hidden_act": ("activation", "silu"),
99
+ "tie_word_embeddings": ("tied_embeddings", False),
100
+ "max_seq_len": ("max_seq_len", 128_000),
101
+ "max_position_embeddings": ("max_position_embeddings", 128_000),
102
+ }
103
+
104
+ for key, new_key in config_mapping.items():
105
+ if key in config:
106
+ config[new_key] = config.pop(key)
107
+
108
+ for new_key, (key,
109
+ default_value) in top_level_mapping_with_default.items():
110
+ config[new_key] = config.pop(key, default_value)
111
+
112
+ return config
113
+
114
+
115
+ def _remap_mistral_quantization_args(config: dict) -> dict:
116
+ quantization = config.get("quantization", {})
117
+ if quantization.get("qformat_weight") == "fp8_e4m3":
118
+ # This maps to the FP8 static per-tensor quantization scheme
119
+ quantization_config = {
120
+ "quant_method": "fp8",
121
+ "activation_scheme": "static"
122
+ }
123
+ elif quantization.get("quant_method") == "compressed-tensors":
124
+ # Pass through the quantization config to compressed-tensors
125
+ quantization_config = quantization
126
+ else:
127
+ raise ValueError(
128
+ f"Found unknown quantization='{quantization}' in config")
129
+
130
+ config["quantization_config"] = quantization_config
131
+
132
+ return config
133
+
134
+
135
+ def _remap_mistral_audio_args(config: dict) -> dict:
136
+ whisper_args = config["multimodal"].pop("whisper_model_args")
137
+ encoder_args = whisper_args["encoder_args"]
138
+ downsample_args = whisper_args["downsample_args"]
139
+
140
+ quant_config = config.get("quantization_config")
141
+ config = {
142
+ "model_type":
143
+ "whixtral",
144
+ "architectures": ["VoxtralForConditionalGeneration"],
145
+ "text_config":
146
+ PretrainedConfig.from_dict(config),
147
+ "audio_config":
148
+ WhisperConfig(
149
+ num_mel_bins=encoder_args["audio_encoding_args"]["num_mel_bins"],
150
+ window_size=encoder_args["audio_encoding_args"]["window_size"],
151
+ sampling_rate=encoder_args["audio_encoding_args"]["sampling_rate"],
152
+ hop_length=encoder_args["audio_encoding_args"]["hop_length"],
153
+ downsample_factor=downsample_args["downsample_factor"],
154
+ d_model=encoder_args["dim"],
155
+ encoder_layers=encoder_args["n_layers"],
156
+ encoder_ffn_dim=encoder_args["hidden_dim"],
157
+ encoder_attention_heads=encoder_args["n_heads"],
158
+ vocab_size=encoder_args["vocab_size"],
159
+ max_source_positions=encoder_args["max_source_positions"],
160
+ )
161
+ }
162
+ if quant_config:
163
+ config["quantization_config"] = quant_config
164
+ return config
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/configs/mlp_speculator.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+
4
+ from typing import Optional
5
+
6
+ from transformers import PretrainedConfig
7
+
8
+
9
+ class MLPSpeculatorConfig(PretrainedConfig):
10
+ model_type = "mlp_speculator"
11
+
12
+ attribute_map = {
13
+ "hidden_size": "emb_dim",
14
+ }
15
+
16
+ def __init__(self,
17
+ vocab_size: int = 32000,
18
+ emb_dim: int = 4096,
19
+ inner_dim: int = 0,
20
+ n_predict: int = 3,
21
+ top_k_tokens_per_head: Optional[list[int]] = None,
22
+ n_candidates: int = 5,
23
+ tie_weights: bool = False,
24
+ scale_input: bool = False,
25
+ **kwargs):
26
+ """
27
+ Initialize an MLPSpeculatorConfig
28
+
29
+ Args:
30
+ vocab_size: int
31
+ the model vocab size
32
+ emb_dim: int
33
+ the model embedding dimension
34
+ inner_dim: int
35
+ the inner dimension of the model. If 0, will be the emb_dim.
36
+ n_predict: int
37
+ the number of lookaheads for the speculator
38
+ top_k_tokens_per_head: list[int]
39
+ Number of tokens to consider from each head when forming the
40
+ candidate tree.
41
+ For each candidate branch in the tree, head n produces topk[n]
42
+ additional sub-branches.
43
+ NOTE: This parameter is currently unused.
44
+ n_candidates: int
45
+ number of child candidates to create per sequence
46
+ tie_weights: bool
47
+ If true, use a single set of weights for every model
48
+ head/stage after the first. The initial projection
49
+ from the base model may have a different size, so that
50
+ stays separate.
51
+ scale_input: bool
52
+ if True, will scale the initial hidden states from
53
+ the base model.
54
+ """
55
+ if top_k_tokens_per_head is None:
56
+ top_k_tokens_per_head = [5, 4, 3]
57
+ assert len(top_k_tokens_per_head) == n_predict
58
+ self.vocab_size = vocab_size
59
+ self.emb_dim = emb_dim
60
+ self.inner_dim = inner_dim
61
+ self.n_predict = n_predict
62
+ self.top_k_tokens_per_head = top_k_tokens_per_head
63
+ self.n_candidates = n_candidates
64
+ self.num_lookahead_tokens = n_predict
65
+ self.tie_weights = tie_weights
66
+ self.scale_input = scale_input
67
+
68
+ super().__init__(**kwargs)
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/configs/moonvit.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+ # Adapted from https://huggingface.co/moonshotai/Kimi-VL-A3B-Instruct/blob/main/configuration_kimi_vl.py
4
+ from transformers.configuration_utils import PretrainedConfig
5
+
6
+
7
+ class MoonViTConfig(PretrainedConfig):
8
+ model_type = "moonvit"
9
+
10
+ def __init__(
11
+ self,
12
+ patch_size: int = 14,
13
+ init_pos_emb_height: int = 64,
14
+ init_pos_emb_width: int = 64,
15
+ num_attention_heads: int = 16,
16
+ num_hidden_layers: int = 27,
17
+ hidden_size: int = 1152,
18
+ intermediate_size: int = 4304,
19
+ merge_kernel_size: tuple[int, int] = (2, 2),
20
+ **kwargs,
21
+ ):
22
+ super().__init__(**kwargs)
23
+ self.patch_size = patch_size
24
+ # Positional embedding config
25
+ self.init_pos_emb_height = init_pos_emb_height
26
+ self.init_pos_emb_width = init_pos_emb_width
27
+ # Transformer config
28
+ self.num_hidden_layers = num_hidden_layers
29
+ self.num_attention_heads = num_attention_heads
30
+ self.hidden_size = hidden_size
31
+ self.intermediate_size = intermediate_size
32
+ # Patch merger config
33
+ self.merge_kernel_size = merge_kernel_size
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/configs/nemotron.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+
4
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
5
+ # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+ """Nemotron model configuration"""
19
+
20
+ from transformers import PretrainedConfig
21
+ from transformers.utils import logging
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class NemotronConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a
29
+ [`NemotronModel`]. It is used to instantiate an Nemotron model
30
+ according to the specified arguments, defining the model architecture.
31
+ Instantiating a configuration with the defaults will yield a similar
32
+ configuration to that of the Nemotron-8B.
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be
35
+ used to control the model outputs. Read the documentation from
36
+ [`PretrainedConfig`] for more information.
37
+
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 256000):
41
+ Vocabulary size of the Nemotron model. Defines the number of
42
+ different tokens that can be represented by the
43
+ `inputs_ids` passed when calling [`NemotronModel`]
44
+ hidden_size (`int`, *optional*, defaults to 6144):
45
+ Dimension of the hidden representations.
46
+ intermediate_size (`int`, *optional*, defaults to 24576):
47
+ Dimension of the MLP representations.
48
+ num_hidden_layers (`int`, *optional*, defaults to 32):
49
+ Number of hidden layers in the Transformer decoder.
50
+ num_attention_heads (`int`, *optional*, defaults to 48):
51
+ Number of attention heads for each attention layer in the
52
+ Transformer decoder.
53
+ head_dim (`int`, *optional*):
54
+ Projection weights dimension in multi-head attention. Set to
55
+ hidden_size // num_attention_heads if None
56
+ num_key_value_heads (`int`, *optional*):
57
+ This is the number of key_value heads that should be used to
58
+ implement Grouped Query Attention. If
59
+ `num_key_value_heads=num_attention_heads`, the model will use
60
+ Multi Head Attention (MHA), if
61
+ `num_key_value_heads=1 the model will use Multi Query Attention
62
+ (MQA) otherwise GQA is used. When converting a multi-head
63
+ checkpoint to a GQA checkpoint, each group key and value
64
+ head should be constructed by meanpooling all the original
65
+ heads within that group. For more details checkout
66
+ [this paper](https://arxiv.org/pdf/2305.13245.pdf). If it
67
+ is not specified, will default to `num_attention_heads`.
68
+ hidden_act (`str` or `function`, *optional*, defaults to `"relu2"`):
69
+ The non-linear activation function (function or string) in the
70
+ decoder.
71
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
72
+ The maximum sequence length that this model might ever be used
73
+ with.
74
+ initializer_range (`float`, *optional*, defaults to 0.0134):
75
+ The standard deviation of the truncated_normal_initializer for
76
+ initializing all weight matrices.
77
+ norm_eps (`float`, *optional*, defaults to 1e-05):
78
+ The epsilon used by the normalization layers.
79
+ use_cache (`bool`, *optional*, defaults to `True`):
80
+ Whether or not the model should return the last key/values
81
+ attentions (not used by all models). Only relevant if
82
+ `config.is_decoder=True`.
83
+ pad_token_id (`int`, *optional*):
84
+ Padding token id.
85
+ bos_token_id (`int`, *optional*, defaults to 2):
86
+ Beginning of stream token id.
87
+ eos_token_id (`int`, *optional*, defaults to 3):
88
+ End of stream token id.
89
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
90
+ Whether to tie weight embeddings
91
+ rope_theta (`float`, *optional*, defaults to 10000.0):
92
+ The base period of the RoPE embeddings.
93
+ partial_rotary_factor (`float`, *optional*, defaults to 0.5):
94
+ Percentage of the query and keys which will have rotary embedding.
95
+ attention_bias (`bool`, *optional*, defaults to `False`):
96
+ Whether to use a bias in the query, key, value and output
97
+ projection layers during self-attention.
98
+ attention_dropout (`float`, *optional*, defaults to 0.0):
99
+ The dropout ratio for the attention probabilities.
100
+ mlp_bias (`bool`, *optional*, defaults to `False`):
101
+ Whether to use a bias in up_proj and down_proj layers in the MLP
102
+ layers.
103
+
104
+ ```python
105
+ >>> from transformers import NemotronModel, NemotronConfig
106
+ >>> # Initializing a Nemotron nemotron-15b style configuration
107
+ >>> configuration = NemotronConfig()
108
+ >>> # Initializing a model from the nemotron-15b style configuration
109
+ >>> model = NemotronModel(configuration)
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "nemotron"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=256000,
120
+ hidden_size=6144,
121
+ intermediate_size=24576,
122
+ num_hidden_layers=32,
123
+ num_attention_heads=48,
124
+ head_dim=None,
125
+ num_key_value_heads=None,
126
+ hidden_act="relu2",
127
+ max_position_embeddings=4096,
128
+ initializer_range=0.0134,
129
+ norm_eps=1e-5,
130
+ use_cache=True,
131
+ pad_token_id=None,
132
+ bos_token_id=2,
133
+ eos_token_id=3,
134
+ tie_word_embeddings=False,
135
+ rope_theta=10000.0,
136
+ rope_scaling=None,
137
+ partial_rotary_factor=0.5,
138
+ attention_bias=False,
139
+ attention_dropout=0.0,
140
+ mlp_bias=False,
141
+ **kwargs,
142
+ ):
143
+ self.vocab_size = vocab_size
144
+ self.max_position_embeddings = max_position_embeddings
145
+ self.hidden_size = hidden_size
146
+ self.intermediate_size = intermediate_size
147
+ self.num_hidden_layers = num_hidden_layers
148
+ self.num_attention_heads = num_attention_heads
149
+ head_dim = head_dim or kwargs.get("kv_channels")
150
+ self.head_dim = head_dim if head_dim is not None else (
151
+ hidden_size // num_attention_heads)
152
+
153
+ # for backward compatibility
154
+ if num_key_value_heads is None:
155
+ num_key_value_heads = num_attention_heads
156
+
157
+ self.num_key_value_heads = num_key_value_heads
158
+ self.hidden_act = hidden_act
159
+ self.initializer_range = initializer_range
160
+ self.norm_eps = norm_eps
161
+ self.use_cache = use_cache
162
+ self.rope_theta = rope_theta
163
+ self.rope_scaling = rope_scaling
164
+ # for backward compatibility
165
+ partial_rotary_factor = kwargs.get("rope_percent") or kwargs.get(
166
+ "rope_percentage") or partial_rotary_factor
167
+ self.partial_rotary_factor = partial_rotary_factor
168
+ self._rope_scaling_validation()
169
+ self.attention_bias = attention_bias
170
+ self.attention_dropout = attention_dropout
171
+ self.mlp_bias = mlp_bias
172
+
173
+ super().__init__(
174
+ pad_token_id=pad_token_id,
175
+ bos_token_id=bos_token_id,
176
+ eos_token_id=eos_token_id,
177
+ tie_word_embeddings=tie_word_embeddings,
178
+ **kwargs,
179
+ )
180
+
181
+ def _rope_scaling_validation(self):
182
+ """
183
+ Validate the `rope_scaling` configuration.
184
+ """
185
+ if self.rope_scaling is None:
186
+ return
187
+
188
+ if not isinstance(self.rope_scaling, dict) or len(
189
+ self.rope_scaling) != 2:
190
+ raise ValueError(
191
+ "`rope_scaling` must be a dictionary with two fields, "
192
+ f"`type` and `factor`, got {self.rope_scaling}")
193
+ rope_scaling_type = self.rope_scaling.get("type", None)
194
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
195
+ if rope_scaling_type is None or rope_scaling_type not in [
196
+ "linear", "dynamic"
197
+ ]:
198
+ raise ValueError(
199
+ "`rope_scaling`'s type field must be one of ['linear', "
200
+ f"'dynamic'], got {rope_scaling_type}")
201
+ if rope_scaling_factor is None or not isinstance(
202
+ rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
203
+ raise ValueError(
204
+ "`rope_scaling`'s factor field must be a float > 1, got "
205
+ f"{rope_scaling_factor}")
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/configs/nemotron_h.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+
4
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
5
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+ """NemotronH model configuration"""
19
+
20
+ import regex as re
21
+ from transformers.configuration_utils import PretrainedConfig
22
+ from transformers.utils import logging
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ class NemotronHConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a
30
+ [`NemotronHModel`]. It is used to instantiate a NemotronH model according
31
+ to the specified arguments, defining the model architecture. Instantiating
32
+ a configuration with the defaults will yield a similar configuration to
33
+ that of the NemotronH-v0.1 model.
34
+ Args:
35
+ vocab_size (`int`, *optional*, defaults to 131072):
36
+ Vocabulary size of the NemotronH model. Defines the number of
37
+ different tokens that can be represented by the `inputs_ids`
38
+ passed when calling [`NemotronHModel`]
39
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
40
+ Whether the model's input and output word embeddings should be
41
+ tied. Note that this is only relevant if the model has a output
42
+ word embedding layer.
43
+ hidden_size (`int`, *optional*, defaults to 4096):
44
+ Dimension of the hidden representations.
45
+ intermediate_size (`int`, *optional*, defaults to 21504):
46
+ Dimension of the MLP representations.
47
+ num_hidden_layers (`int`, *optional*, defaults to 52):
48
+ Number of hidden layers in the Transformer encoder.
49
+ hybrid_override_pattern (`str`, *optional*, defaults to
50
+ `"M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M-"`):
51
+ The pattern of the hybrid model. The pattern is a string of
52
+ characters where each character represents
53
+ M: Mamba2, *: Attention, -: MLP
54
+ num_attention_heads (`int`, *optional*, defaults to 32):
55
+ Number of attention heads for each attention layer in the
56
+ Transformer encoder.
57
+ attention_head_dim (`int`, *optional*, defaults to 128):
58
+ Dimension of each attention head.
59
+ num_key_value_heads (`int`, *optional*, defaults to 8):
60
+ This is the number of key_value heads that should be used to
61
+ implement Grouped Query Attention. If
62
+ `num_key_value_heads=num_attention_heads`, the model will use
63
+ Multi Head Attention (MHA), if `num_key_value_heads=1` the model
64
+ will use Multi Query Attention (MQA) otherwise GQA is used.
65
+ mlp_hidden_act (`str`, *optional*, defaults to "relu2"):
66
+ The non-linear activation function in the MLP layers.
67
+ attention_bias (`bool`, *optional*, defaults to `False`):
68
+ Whether to use bias in attention layers.
69
+ mlp_bias (`bool`, *optional*, defaults to `False`):
70
+ Whether to use bias in MLP layers.
71
+ use_bias (`bool`, *optional*, defaults to `False`):
72
+ Whether to use bias in the model.
73
+ initializer_range (`float`, *optional*, defaults to 0.02):
74
+ The standard deviation of the truncated_normal_initializer for
75
+ initializing all weight matrices.
76
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
77
+ The epsilon used by the layer normalization layers.
78
+ residual_in_fp32 (`bool`, *optional*, defaults to `False`):
79
+ Whether or not residuals should be in `float32`. If set to `False`
80
+ residuals will keep the same `dtype` as the rest of the model.
81
+ use_cache (`bool`, *optional*, defaults to `True`):
82
+ Whether or not the model should return the last key/values
83
+ attentions (not used by all models). Only relevant if
84
+ `config.is_decoder=True`.
85
+ num_logits_to_keep (`int` or `None`, *optional*, defaults to 1):
86
+ Number of prompt logits to calculate during generation. If `None`,
87
+ all logits will be calculated. If an integer value, only last
88
+ `num_logits_to_keep` logits will be calculated.
89
+ pad_token_id (`int`, *optional*, defaults to 0):
90
+ The id of the padding token.
91
+ bos_token_id (`int`, *optional*, defaults to 1):
92
+ The id of the "beginning-of-sequence" token.
93
+ eos_token_id (`int`, *optional*, defaults to 2):
94
+ The id of the "end-of-sequence" token.
95
+ sliding_window (`int`, *optional*, defaults to None):
96
+ Sliding window attention window size.
97
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
98
+ The maximum sequence length that this model might ever be used
99
+ with.
100
+ attention_dropout (`float`, *optional*, defaults to 0.0):
101
+ The dropout ratio for the attention probabilities.
102
+ hidden_dropout (`float`, *optional*, defaults to 0.0):
103
+ The dropout ratio for the hidden states.
104
+ use_mamba_kernels (`bool`, *optional*, defaults to `True`):
105
+ Flag indicating whether or not to use the fast mamba kernels.
106
+ These are available only if `mamba-ssm` and `causal-conv1d`
107
+ are installed, and the mamba modules are running on a CUDA device.
108
+ ssm_state_size (`int`, *optional*, defaults to 128):
109
+ The dimension of the mamba state space latents.
110
+ mamba_num_heads (`int`, *optional*, defaults to 128):
111
+ Number of heads in Mamba layers.
112
+ mamba_n_groups (`int`, *optional*, defaults to 8):
113
+ Number of groups in Mamba layers.
114
+ mamba_head_dim (`int`, *optional*, defaults to 64):
115
+ Dimension of each Mamba head.
116
+ mamba_d_conv (`int`, *optional*, defaults to 4):
117
+ The size of the mamba convolution kernel.
118
+ mamba_expand (`int`, *optional*, defaults to 2):
119
+ Expanding factor used to determine the mamba intermediate size.
120
+ mamba_hidden_act (`str`, *optional*, defaults to "silu"):
121
+ The non-linear activation function in the Mamba layers.
122
+ mamba_dt_min (`float`, *optional*, defaults to 0.001):
123
+ Minimum value for the time step in Mamba.
124
+ mamba_dt_max (`float`, *optional*, defaults to 0.1):
125
+ Maximum value for the time step in Mamba.
126
+ mamba_dt_limit (`tuple`, *optional*, defaults to (0.0, float("inf"))):
127
+ Limits for the time step in Mamba.
128
+ mamba_dt_init_floor (`float`, *optional*, defaults to 1e-4):
129
+ Floor value for time step initialization in Mamba.
130
+ mamba_conv_bias (`bool`, *optional*, defaults to `True`):
131
+ Whether to use bias in the convolution layer of the mamba mixer
132
+ block.
133
+ mamba_proj_bias (`bool`, *optional*, defaults to `False`):
134
+ Whether to use bias in the input and output projections of the
135
+ mamba mixer block.
136
+ mamba_chunk_size (`int`, *optional*, defaults to 256):
137
+ Size of chunks for Mamba processing.
138
+ rescale_prenorm_residual (`bool`, *optional*, defaults to `True`):
139
+ Whether to rescale the pre-normalization residual connections.
140
+ """
141
+
142
+ model_type = "nemotron_h"
143
+ keys_to_ignore_at_inference = ["past_key_values"]
144
+
145
+ def __init__(
146
+ self,
147
+ vocab_size=131072,
148
+ tie_word_embeddings=False,
149
+ hidden_size=4096,
150
+ intermediate_size=21504,
151
+ num_hidden_layers=52,
152
+ hybrid_override_pattern="M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M-",
153
+ num_attention_heads=32,
154
+ head_dim=128,
155
+ num_key_value_heads=8, # nemo: num_query_groups
156
+ mlp_hidden_act="relu2",
157
+ attention_bias=False,
158
+ mlp_bias=False,
159
+ use_bias=False,
160
+ initializer_range=0.02, # nemo: init_method_std
161
+ layer_norm_epsilon=1e-5, # nemo: layernorm_epsilon
162
+ residual_in_fp32=False, # Megatron Core default value
163
+ use_cache=True,
164
+ num_logits_to_keep=1,
165
+ pad_token_id=0,
166
+ bos_token_id=1,
167
+ eos_token_id=2,
168
+ sliding_window=None,
169
+ max_position_embeddings=4096,
170
+ attention_dropout=0.0,
171
+ hidden_dropout=0.0, # * ADDED
172
+ use_mamba_kernels=True,
173
+ ssm_state_size=128, # mamba_state_size
174
+ mamba_num_heads=128,
175
+ mamba_n_groups=8, # nemo: mamba_ssm_ngroups = num_heads
176
+ mamba_head_dim=64,
177
+ mamba_d_conv=4,
178
+ mamba_expand=2,
179
+ mamba_hidden_act="silu",
180
+ mamba_dt_min=0.001,
181
+ mamba_dt_max=0.1,
182
+ mamba_dt_limit=(0.0, float("inf")),
183
+ mamba_dt_init_floor=1e-4,
184
+ mamba_conv_bias=True,
185
+ mamba_proj_bias=False,
186
+ mamba_chunk_size=256,
187
+ rescale_prenorm_residual=True,
188
+ **kwargs,
189
+ ):
190
+ self.vocab_size = vocab_size
191
+ self.tie_word_embeddings = tie_word_embeddings
192
+ self.hidden_size = hidden_size
193
+ self.intermediate_size = intermediate_size
194
+ self.num_hidden_layers = num_hidden_layers
195
+ self.hybrid_override_pattern = hybrid_override_pattern
196
+ self.num_attention_heads = num_attention_heads
197
+ self.head_dim = head_dim
198
+ self.sliding_window = sliding_window
199
+ self.max_position_embeddings = max_position_embeddings
200
+ self.attention_dropout = attention_dropout
201
+ self.hidden_dropout = hidden_dropout
202
+
203
+ # Validate hybrid_override_pattern
204
+ # M: Mamba2, *: Attention, -: MLP
205
+ assert len(self.hybrid_override_pattern) == self.num_hidden_layers, (
206
+ "hybrid_override_pattern must have same length as "
207
+ "num_hidden_layers")
208
+ assert re.match(r"^[*-M]+$", self.hybrid_override_pattern), (
209
+ "hybrid_override_pattern must only contain characters "
210
+ "'M', '*', or '-'")
211
+
212
+ # for backward compatibility
213
+ if num_key_value_heads is None:
214
+ num_key_value_heads = num_attention_heads
215
+
216
+ self.num_key_value_heads = num_key_value_heads
217
+ self.mlp_hidden_act = mlp_hidden_act
218
+ self.attention_bias = attention_bias
219
+ self.mlp_bias = mlp_bias
220
+ self.use_bias = use_bias
221
+ self.initializer_range = initializer_range
222
+ self.layer_norm_epsilon = layer_norm_epsilon
223
+ self.residual_in_fp32 = residual_in_fp32
224
+
225
+ self.use_cache = use_cache
226
+ self.num_logits_to_keep = num_logits_to_keep
227
+
228
+ self.use_mamba_kernels = use_mamba_kernels
229
+ self.n_groups = mamba_n_groups
230
+ self.mamba_head_dim = mamba_head_dim
231
+ self.ssm_state_size = ssm_state_size
232
+ self.mamba_num_heads = mamba_num_heads
233
+ self.conv_kernel = mamba_d_conv
234
+ self.expand = mamba_expand
235
+ self.mamba_hidden_act = mamba_hidden_act
236
+ self.time_step_min = mamba_dt_min
237
+ self.time_step_max = mamba_dt_max
238
+ self.time_step_limit = mamba_dt_limit
239
+ self.time_step_floor = mamba_dt_init_floor
240
+ self.use_conv_bias = mamba_conv_bias
241
+ self.mamba_proj_bias = mamba_proj_bias
242
+ self.chunk_size = mamba_chunk_size
243
+ self.rescale_prenorm_residual = rescale_prenorm_residual
244
+
245
+ super().__init__(
246
+ pad_token_id=pad_token_id,
247
+ bos_token_id=bos_token_id,
248
+ eos_token_id=eos_token_id,
249
+ tie_word_embeddings=tie_word_embeddings,
250
+ **kwargs,
251
+ )
252
+
253
+ @property
254
+ def layers_block_type(self):
255
+ return [
256
+ "mamba" if self.hybrid_override_pattern[i] == "M" else
257
+ "attention" if self.hybrid_override_pattern[i] == "*" else "mlp"
258
+ for i in range(self.num_hidden_layers)
259
+ ]
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/configs/nemotron_vl.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+
4
+ # yapf: disable
5
+ # ruff: noqa: E501
6
+ # Adapted from
7
+ # https://huggingface.co/nvidia/Llama-3.1-Nemotron-Nano-VL-8B-V1/blob/main/configuration.py
8
+ # --------------------------------------------------------
9
+ # Adapted from https://huggingface.co/OpenGVLab/InternVL2-Llama3-76B under MIT License
10
+ # LICENSE is in incl_licenses directory.
11
+ # --------------------------------------------------------
12
+
13
+ from transformers import LlamaConfig
14
+ from transformers.configuration_utils import PretrainedConfig
15
+ from transformers.dynamic_module_utils import get_class_from_dynamic_module
16
+
17
+
18
+ class Nemotron_Nano_VL_Config(PretrainedConfig):
19
+ model_type = 'Llama_Nemotron_Nano_VL'
20
+ is_composition = True
21
+
22
+ def __init__(
23
+ self,
24
+ vision_config=None,
25
+ llm_config=None,
26
+ force_image_size=None,
27
+ downsample_ratio=0.5,
28
+ template=None,
29
+ ps_version='v1',
30
+ image_tag_type="internvl",
31
+ projector_hidden_size=4096,
32
+ vit_hidden_size=1280,
33
+ **kwargs
34
+ ):
35
+ super().__init__(**kwargs)
36
+
37
+ if vision_config is not None:
38
+ assert "auto_map" in vision_config and "AutoConfig" in vision_config["auto_map"]
39
+ vision_auto_config = get_class_from_dynamic_module(*vision_config["auto_map"]["AutoConfig"].split("--")[::-1])
40
+ self.vision_config = vision_auto_config(**vision_config)
41
+ else:
42
+ self.vision_config = PretrainedConfig()
43
+
44
+ if llm_config is None:
45
+ self.text_config = LlamaConfig()
46
+ else:
47
+ self.text_config = LlamaConfig(**llm_config)
48
+
49
+ # Assign configuration values
50
+ self.force_image_size = force_image_size
51
+ self.downsample_ratio = downsample_ratio
52
+ self.template = template # TODO move out of here and into the tokenizer
53
+ self.ps_version = ps_version # Pixel shuffle version
54
+ self.image_tag_type = image_tag_type # TODO: into the tokenizer too?
55
+ self.projector_hidden_size = projector_hidden_size
56
+ self.vit_hidden_size = vit_hidden_size
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/configs/ovis.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+
4
+ # yapf: disable
5
+ # ruff: noqa: E501
6
+ # adapted from https://huggingface.co/AIDC-AI/Ovis2-1B/blob/main/configuration_aimv2.py
7
+ # and https://huggingface.co/AIDC-AI/Ovis2-1B/blob/main/configuration_ovis.py
8
+ # Ovis Config with AimV2 config registration removed for Transformers compatibility
9
+ from typing import Any, Optional, Union
10
+
11
+ from transformers import AutoConfig, PretrainedConfig
12
+
13
+
14
+ class AIMv2Config(PretrainedConfig):
15
+ """This is the configuration class to store the configuration of an [`AIMv2Model`].
16
+ Instantiating a configuration with the defaults will yield a similar configuration
17
+ to that of the [apple/aimv2-large-patch14-224](https://huggingface.co/apple/aimv2-large-patch14-224).
18
+ Args:
19
+ hidden_size: Dimension of the hidden representations.
20
+ intermediate_size: Dimension of the SwiGLU representations.
21
+ num_hidden_layers: Number of hidden layers in the Transformer.
22
+ num_attention_heads: Number of attention heads for each attention layer
23
+ in the Transformer.
24
+ num_channels: Number of input channels.
25
+ image_size: Image size.
26
+ patch_size: Patch size.
27
+ rms_norm_eps: Epsilon value used for the RMS normalization layer.
28
+ attention_dropout: Dropout ratio for attention probabilities.
29
+ projection_dropout: Dropout ratio for the projection layer after the attention.
30
+ qkv_bias: Whether to add a bias to the queries, keys and values.
31
+ use_bias: Whether to add a bias in the feed-forward and projection layers.
32
+ kwargs: Keyword arguments for the [`PretrainedConfig`].
33
+ """
34
+
35
+ model_type: str = "aimv2"
36
+
37
+ def __init__(
38
+ self,
39
+ hidden_size: int = 1024,
40
+ intermediate_size: int = 2816,
41
+ num_hidden_layers: int = 24,
42
+ num_attention_heads: int = 8,
43
+ num_channels: int = 3,
44
+ image_size: int = 224,
45
+ patch_size: int = 14,
46
+ rms_norm_eps: float = 1e-5,
47
+ attention_dropout: float = 0.0,
48
+ projection_dropout: float = 0.0,
49
+ qkv_bias: bool = False,
50
+ use_bias: bool = False,
51
+ **kwargs: Any,
52
+ ):
53
+ super().__init__(**kwargs)
54
+ self.hidden_size = hidden_size
55
+ self.intermediate_size = intermediate_size
56
+ self.num_hidden_layers = num_hidden_layers
57
+ self.num_attention_heads = num_attention_heads
58
+ self.num_channels = num_channels
59
+ self.patch_size = patch_size
60
+ self.image_size = image_size
61
+ self.attention_dropout = attention_dropout
62
+ self.rms_norm_eps = rms_norm_eps
63
+
64
+ self.projection_dropout = projection_dropout
65
+ self.qkv_bias = qkv_bias
66
+ self.use_bias = use_bias
67
+
68
+
69
+ # ----------------------------------------------------------------------
70
+ # Visual Tokenizer Configuration
71
+ # ----------------------------------------------------------------------
72
+ class BaseVisualTokenizerConfig(PretrainedConfig):
73
+
74
+ def __init__(self,
75
+ vocab_size=16384,
76
+ tokenize_function="softmax",
77
+ tau=1.0,
78
+ depths=None,
79
+ drop_cls_token=False,
80
+ backbone_config: Optional[Union[PretrainedConfig,
81
+ dict]] = None,
82
+ hidden_stride: int = 1,
83
+ **kwargs):
84
+ super().__init__(**kwargs)
85
+ self.vocab_size = vocab_size
86
+ self.tokenize_function = tokenize_function
87
+ self.tau = tau
88
+ if isinstance(depths, str):
89
+ depths = [int(x) for x in depths.split('|')]
90
+ self.depths = depths
91
+ self.backbone_kwargs = dict[str, Any]()
92
+ self.drop_cls_token = drop_cls_token
93
+ if backbone_config is not None:
94
+ assert isinstance(backbone_config, (PretrainedConfig, dict)), \
95
+ f"expect `backbone_config` to be instance of PretrainedConfig or dict, but got {type(backbone_config)} type"
96
+ if not isinstance(backbone_config, PretrainedConfig):
97
+ model_type = backbone_config['model_type']
98
+ if model_type != "aimv2":
99
+ backbone_config.pop('model_type')
100
+ backbone_config = AutoConfig.for_model(model_type, **backbone_config)
101
+ else:
102
+ backbone_config = AIMv2Config(**backbone_config)
103
+ self.backbone_config = backbone_config
104
+ self.hidden_stride = hidden_stride
105
+
106
+
107
+ class Aimv2VisualTokenizerConfig(BaseVisualTokenizerConfig):
108
+ model_type = "aimv2_visual_tokenizer"
109
+
110
+ def __init__(self, **kwargs):
111
+ super().__init__(**kwargs)
112
+ if self.drop_cls_token:
113
+ self.drop_cls_token = False
114
+ if self.depths:
115
+ assert len(self.depths) == 1
116
+ self.backbone_kwargs['num_hidden_layers'] = self.depths[0]
117
+
118
+
119
+ class SiglipVisualTokenizerConfig(BaseVisualTokenizerConfig):
120
+ model_type = "siglip_visual_tokenizer"
121
+
122
+ def __init__(self, **kwargs):
123
+ super().__init__(**kwargs)
124
+ if self.drop_cls_token:
125
+ self.drop_cls_token = False
126
+ if self.depths:
127
+ assert len(self.depths) == 1
128
+ self.backbone_kwargs['num_hidden_layers'] = self.depths[0]
129
+
130
+
131
+ AutoConfig.register("siglip_visual_tokenizer", SiglipVisualTokenizerConfig)
132
+ AutoConfig.register("aimv2_visual_tokenizer", Aimv2VisualTokenizerConfig)
133
+
134
+
135
+ # ----------------------------------------------------------------------
136
+ # Ovis Configuration
137
+ # ----------------------------------------------------------------------
138
+ class OvisConfig(PretrainedConfig):
139
+ model_type = "ovis"
140
+
141
+ def __init__(self,
142
+ llm_config: Optional[Union[PretrainedConfig, dict]] = None,
143
+ visual_tokenizer_config: Optional[Union[PretrainedConfig,
144
+ dict]] = None,
145
+ multimodal_max_length=8192,
146
+ hidden_size=None,
147
+ conversation_formatter_class=None,
148
+ llm_attn_implementation=None,
149
+ disable_tie_weight=False,
150
+ **kwargs):
151
+ super().__init__(**kwargs)
152
+ if llm_config is not None:
153
+ assert isinstance(llm_config, (PretrainedConfig, dict)), \
154
+ f"expect `llm_config` to be instance of PretrainedConfig or dict, but got {type(llm_config)} type"
155
+ if not isinstance(llm_config, PretrainedConfig):
156
+ model_type = llm_config['model_type']
157
+ llm_config.pop('model_type')
158
+ llm_config = AutoConfig.for_model(model_type, **llm_config)
159
+
160
+ # map llm_config to text_config
161
+ self.text_config = llm_config
162
+ if visual_tokenizer_config is not None:
163
+ assert isinstance(visual_tokenizer_config, (PretrainedConfig, dict)), \
164
+ f"expect `visual_tokenizer_config` to be instance of PretrainedConfig or dict, but got {type(visual_tokenizer_config)} type"
165
+ if not isinstance(visual_tokenizer_config, PretrainedConfig):
166
+ model_type = visual_tokenizer_config['model_type']
167
+ visual_tokenizer_config.pop('model_type')
168
+ visual_tokenizer_config = AutoConfig.for_model(
169
+ model_type, **visual_tokenizer_config)
170
+
171
+ self.visual_tokenizer_config = visual_tokenizer_config
172
+ self.multimodal_max_length = multimodal_max_length
173
+ self.hidden_size = hidden_size
174
+ self.conversation_formatter_class = conversation_formatter_class
175
+ self.llm_attn_implementation = llm_attn_implementation
176
+ self.disable_tie_weight = disable_tie_weight
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/configs/step3_vl.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+ from typing import Any, Optional, Union
4
+
5
+ from transformers.configuration_utils import PretrainedConfig
6
+
7
+
8
+ class Step3VisionEncoderConfig(PretrainedConfig):
9
+ model_type = "step3_vision_encoder"
10
+
11
+ def __init__(
12
+ self,
13
+ hidden_size=1792,
14
+ intermediate_size=3072,
15
+ output_hidden_size=4096,
16
+ num_hidden_layers=63,
17
+ num_attention_heads=16,
18
+ num_channels=3,
19
+ image_size=728,
20
+ patch_size=14,
21
+ hidden_act="quick_gelu",
22
+ layer_norm_eps=1e-5,
23
+ **kwargs,
24
+ ):
25
+ self.hidden_size = hidden_size
26
+ self.intermediate_size = intermediate_size
27
+ self.output_hidden_size = output_hidden_size
28
+ self.num_hidden_layers = num_hidden_layers
29
+ self.num_attention_heads = num_attention_heads
30
+ self.num_channels = num_channels
31
+ self.patch_size = patch_size
32
+ self.image_size = image_size
33
+ self.layer_norm_eps = layer_norm_eps
34
+ self.hidden_act = hidden_act
35
+ super().__init__(**kwargs)
36
+
37
+
38
+ class Step3TextConfig(PretrainedConfig):
39
+ model_type = "step3_text"
40
+ architectures = ["Step3TextForCausalLM"]
41
+
42
+ def __init__(
43
+ self,
44
+ hidden_size: int = 7168,
45
+ intermediate_size: int = 18432,
46
+ num_attention_heads: int = 64,
47
+ num_attention_groups: int = 1,
48
+ num_hidden_layers: int = 61,
49
+ max_seq_len: int = 65536,
50
+ vocab_size: int = 128815,
51
+ rms_norm_eps: float = 1e-5,
52
+ moe_intermediate_size: int = 5120,
53
+ moe_num_experts: int = 48,
54
+ moe_top_k: int = 3,
55
+ rope_theta: float = 500000,
56
+ rope_scaling: Optional[dict[str, Any]] = None,
57
+ max_position_embedding: int = 65536,
58
+ share_expert_dim: int = 5120,
59
+ share_q_dim: int = 2048,
60
+ head_dim: int = 256,
61
+ norm_expert_weight: bool = False,
62
+ moe_layers_enum: tuple[int,
63
+ ...] = (4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
64
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
65
+ 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
66
+ 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
67
+ 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
68
+ 55, 56, 57, 58, 59),
69
+ **kwargs,
70
+ ) -> None:
71
+ self.hidden_size = hidden_size
72
+ self.intermediate_size = intermediate_size
73
+ self.num_attention_heads = num_attention_heads
74
+ self.num_attention_groups = num_attention_groups
75
+ self.num_hidden_layers = num_hidden_layers
76
+ self.max_seq_len = max_seq_len
77
+ self.vocab_size = vocab_size
78
+ self.rms_norm_eps = rms_norm_eps
79
+ self.moe_intermediate_size = moe_intermediate_size
80
+ self.moe_num_experts = moe_num_experts
81
+ self.moe_top_k = moe_top_k
82
+ self.rope_theta = rope_theta
83
+ self.rope_scaling = rope_scaling
84
+ self.max_position_embedding = max_position_embedding
85
+ self.share_expert_dim = share_expert_dim
86
+ self.share_q_dim = share_q_dim
87
+ self.head_dim = head_dim
88
+ self.norm_expert_weight = norm_expert_weight
89
+ self.moe_layers_enum = moe_layers_enum
90
+
91
+ super().__init__(**kwargs)
92
+
93
+
94
+ class Step3VLConfig(PretrainedConfig):
95
+ model_type = "step3_vl"
96
+
97
+ def __init__(
98
+ self,
99
+ vision_config: Optional[Union[dict, Step3VisionEncoderConfig]] = None,
100
+ text_config: Optional[Union[dict, Step3TextConfig]] = None,
101
+ understand_projector_stride: int = 1,
102
+ projector_bias: bool = True,
103
+ image_token_id: int = 128001,
104
+ **kwargs,
105
+ ) -> None:
106
+ if vision_config is None:
107
+ vision_config = Step3VisionEncoderConfig()
108
+ elif isinstance(vision_config, dict):
109
+ vision_config = Step3VisionEncoderConfig(**vision_config)
110
+ self.vision_config = vision_config
111
+
112
+ if text_config is None:
113
+ text_config = Step3TextConfig()
114
+ elif isinstance(text_config, dict):
115
+ text_config = Step3TextConfig(**text_config)
116
+ self.text_config = text_config
117
+
118
+ self.understand_projector_stride = understand_projector_stride
119
+ self.projector_bias = projector_bias
120
+ self.hidden_size = text_config.hidden_size
121
+ self.image_token_id = image_token_id
122
+
123
+ super().__init__(**kwargs)
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/configs/ultravox.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+
4
+ # Adapted from https://github.com/fixie-ai/ultravox/blob/ecd58c4041030bae2ad15aa6bcf04ab43199ea02/ultravox/model/ultravox_config.py
5
+ from typing import Any, Optional
6
+
7
+ import transformers
8
+
9
+
10
+ class UltravoxConfig(transformers.PretrainedConfig):
11
+ r"""
12
+ This is the configuration class to store the configuration of a
13
+ [`UltravoxForConditionalGeneration`]. It is used to instantiate an
14
+ Ultravox model according to the specified arguments, defining the model
15
+ architecture.
16
+
17
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to
18
+ control the model outputs. Read the documentation from [`PretrainedConfig`]
19
+ for more information.
20
+
21
+ Args:
22
+ audio_config (`Union[AutoConfig, dict]`, *optional*):
23
+ Custom audio config or dict
24
+ text_config (`Union[AutoConfig, dict]`, *optional*):
25
+ The config object of the text backbone. Can be any of `LlamaConfig`
26
+ or `MistralConfig`.
27
+ ignore_index (`int`, *optional*, defaults to -100):
28
+ The ignore index for the loss function.
29
+ audio_token_index (`int`, *optional*, defaults to 32000):
30
+ The audio token index to encode the audio prompt.
31
+ stack_factor (`int`, *optional*, defaults to 8):
32
+ Audio downsampling factor for the multimodal projector.
33
+ norm_init (`float`, *optional*, defaults to 0.4):
34
+ The initialization value for the layer normalization.
35
+ projector_act (`str`, *optional*, defaults to `"swiglu"`):
36
+ The activation function used by the multimodal projector.
37
+ text_model_lora_config (`LoraConfigSimplified`, *optional*):
38
+ The LoRA configuration for finetuning the text model.
39
+ audio_model_lora_config (`LoraConfigSimplified`, *optional*):
40
+ The LoRA configuration for finetuning the audio model.
41
+ projector_ln_mid (`bool`, *optional*, defaults to `False`):
42
+ Whether to apply layer normalization at the middle of the
43
+ projector or at the end. Versions v0.4.1 and below
44
+ use `False`, but v0.5 and above use `True`.
45
+ """
46
+
47
+ model_type = "ultravox"
48
+ audio_token = "<|audio|>"
49
+ is_composition = False
50
+
51
+ def __init__(
52
+ self,
53
+ audio_config: Optional[dict[str, Any]] = None,
54
+ text_config: Optional[dict[str, Any]] = None,
55
+ audio_model_id: Optional[str] = None,
56
+ text_model_id: Optional[str] = None,
57
+ ignore_index: int = -100,
58
+ audio_token_index: int = 32000,
59
+ hidden_size: int = 4096,
60
+ stack_factor: int = 8,
61
+ norm_init: float = 0.4,
62
+ projector_act: str = "swiglu",
63
+ text_model_lora_config: Optional[dict[str, Any]] = None,
64
+ audio_model_lora_config: Optional[dict[str, Any]] = None,
65
+ projector_ln_mid: bool = False,
66
+ **kwargs,
67
+ ):
68
+ self.ignore_index = ignore_index
69
+
70
+ self.audio_model_id = audio_model_id
71
+ self.text_model_id = text_model_id
72
+ self.audio_token_index = audio_token_index
73
+
74
+ self.hidden_size = hidden_size
75
+ self.stack_factor = stack_factor
76
+ self.norm_init = norm_init
77
+ self.projector_act = projector_act
78
+ self.projector_ln_mid = projector_ln_mid
79
+
80
+ if text_model_id is not None:
81
+ # Avoid circular import
82
+ from vllm.transformers_utils.config import get_config
83
+
84
+ text_config_obj = get_config(text_model_id,
85
+ trust_remote_code=False)
86
+ else:
87
+ text_config = text_config or {}
88
+ text_config_obj = transformers.CONFIG_MAPPING[text_config.get(
89
+ "model_type", "llama")](**text_config)
90
+
91
+ inner_text_config = text_config_obj.get_text_config()
92
+
93
+ if audio_model_id is not None:
94
+ # Avoid circular import
95
+ from vllm.transformers_utils.config import get_config
96
+
97
+ audio_config = get_config(audio_model_id, trust_remote_code=False)
98
+ else:
99
+ audio_config = audio_config or {}
100
+ audio_config = transformers.CONFIG_MAPPING[audio_config.get(
101
+ "model_type", "whisper")](**audio_config)
102
+
103
+ self.text_config = text_config_obj
104
+ self.audio_config = audio_config
105
+ self.text_model_lora_config = text_model_lora_config or {}
106
+ self.audio_model_lora_config = audio_model_lora_config or {}
107
+
108
+ self.vocab_size = inner_text_config.vocab_size
109
+ self.initializer_range = inner_text_config.initializer_range
110
+ self.text_hidden_size = inner_text_config.hidden_size
111
+
112
+ super().__init__(**kwargs)
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/processors/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+ """
4
+ Multi-modal processors may be defined in this directory for the following
5
+ reasons:
6
+
7
+ - There is no processing file defined by HF Hub or Transformers library.
8
+ - There is a need to override the existing processor to support vLLM.
9
+ """
10
+
11
+ from vllm.transformers_utils.processors.deepseek_vl2 import (
12
+ DeepseekVLV2Processor)
13
+ from vllm.transformers_utils.processors.ovis import OvisProcessor
14
+
15
+ __all__ = ["DeepseekVLV2Processor", "OvisProcessor"]
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/processors/deepseek_vl2.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+
4
+ # yapf: disable
5
+ # ruff: noqa: E501
6
+ # coding=utf-8
7
+ # adapted from https://github.com/deepseek-ai/DeepSeek-VL2/blob/ff23960c5cf9e6874b44be38af930cfb0ccbb620/deepseek_vl2/models/processing_deepseek_vl_v2.py
8
+ # Copyright (c) 2023-2024 DeepSeek.
9
+ #
10
+ # Permission is hereby granted, free of charge, to any person obtaining a copy of
11
+ # this software and associated documentation files (the "Software"), to deal in
12
+ # the Software without restriction, including without limitation the rights to
13
+ # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
14
+ # the Software, and to permit persons to whom the Software is furnished to do so,
15
+ # subject to the following conditions:
16
+ #
17
+ # The above copyright notice and this permission notice shall be included in all
18
+ # copies or substantial portions of the Software.
19
+ #
20
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
22
+ # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
23
+ # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
24
+ # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
25
+ # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26
+
27
+ import math
28
+
29
+ import torch
30
+ import torchvision.transforms as T
31
+ from PIL import Image, ImageOps
32
+ from transformers import AutoProcessor, BatchFeature, LlamaTokenizerFast
33
+ from transformers.processing_utils import ProcessorMixin
34
+
35
+
36
+ class ImageTransform:
37
+
38
+ def __init__(self,
39
+ mean: tuple[float, float, float] = (0.5, 0.5, 0.5),
40
+ std: tuple[float, float, float] = (0.5, 0.5, 0.5),
41
+ normalize: bool = True):
42
+ self.mean = mean
43
+ self.std = std
44
+ self.normalize = normalize
45
+
46
+ transform_pipelines = [T.ToTensor()]
47
+
48
+ if normalize:
49
+ transform_pipelines.append(T.Normalize(mean, std))
50
+
51
+ self.transform = T.Compose(transform_pipelines)
52
+
53
+ def __call__(self, pil_img: Image.Image):
54
+ x = self.transform(pil_img)
55
+ return x
56
+
57
+
58
+ class DeepseekVLV2Processor(ProcessorMixin):
59
+ tokenizer_class = ("LlamaTokenizer", "LlamaTokenizerFast")
60
+ attributes = ["tokenizer"]
61
+
62
+ def __init__(
63
+ self,
64
+ tokenizer: LlamaTokenizerFast,
65
+ candidate_resolutions: tuple[tuple[int, int]],
66
+ patch_size: int,
67
+ downsample_ratio: int,
68
+ image_mean: tuple[float, float, float] = (0.5, 0.5, 0.5),
69
+ image_std: tuple[float, float, float] = (0.5, 0.5, 0.5),
70
+ normalize: bool = True,
71
+ image_token: str = "<image>",
72
+ pad_token: str = "<|▁pad▁|>",
73
+ add_special_token: bool = False,
74
+ sft_format: str = "deepseek",
75
+ mask_prompt: bool = True,
76
+ ignore_id: int = -100,
77
+ **kwargs,
78
+ ):
79
+
80
+ self.candidate_resolutions = candidate_resolutions
81
+ self.image_size = candidate_resolutions[0][0]
82
+ self.patch_size = patch_size
83
+ self.image_mean = image_mean
84
+ self.image_std = image_std
85
+ self.normalize = normalize
86
+ self.downsample_ratio = downsample_ratio
87
+
88
+ self.image_transform = ImageTransform(mean=image_mean, std=image_std, normalize=normalize)
89
+ self.tokenizer = tokenizer
90
+ self.tokenizer.padding_side = 'left' # must set this,padding side with make a difference in batch inference
91
+
92
+ # add the pad_token as special token to use 'tokenizer.pad_token' and 'tokenizer.pad_token_id'
93
+ if tokenizer.pad_token is None:
94
+ self.tokenizer.add_special_tokens({'pad_token': pad_token})
95
+
96
+ # add image token
97
+ image_token_id = self.tokenizer.vocab.get(image_token)
98
+ if image_token_id is None:
99
+ special_tokens = [image_token]
100
+ special_tokens_dict = {"additional_special_tokens": special_tokens}
101
+ self.tokenizer.add_special_tokens(special_tokens_dict)
102
+ self.image_token_id = self.tokenizer.vocab.get(image_token)
103
+
104
+ # add five special tokens for grounding-related tasks
105
+ # <|ref|>, <|/ref|>, <|det|>, <|/det|>, <|grounding|>
106
+ special_tokens = ['<|ref|>', '<|/ref|>', '<|det|>', '<|/det|>', '<|grounding|>']
107
+ special_tokens_dict = {"additional_special_tokens": special_tokens}
108
+ self.tokenizer.add_special_tokens(special_tokens_dict)
109
+
110
+ # add special tokens for SFT data
111
+ special_tokens = ["<|User|>", "<|Assistant|>"]
112
+ special_tokens_dict = {"additional_special_tokens": special_tokens}
113
+ self.tokenizer.add_special_tokens(special_tokens_dict)
114
+
115
+ self.image_token = image_token
116
+ self.pad_token = pad_token
117
+ self.add_special_token = add_special_token
118
+ self.sft_format = sft_format
119
+ self.mask_prompt = mask_prompt
120
+ self.ignore_id = ignore_id
121
+
122
+ super().__init__(
123
+ tokenizer,
124
+ **kwargs,
125
+ )
126
+
127
+ def select_best_resolution(self, image_size):
128
+ # used for cropping
129
+ original_width, original_height = image_size
130
+ best_fit = None
131
+ max_effective_resolution = 0
132
+ min_wasted_resolution = float("inf")
133
+
134
+ for width, height in self.candidate_resolutions:
135
+ scale = min(width / original_width, height / original_height)
136
+ downscaled_width, downscaled_height = int(
137
+ original_width * scale), int(original_height * scale)
138
+ effective_resolution = min(downscaled_width * downscaled_height,
139
+ original_width * original_height)
140
+ wasted_resolution = (width * height) - effective_resolution
141
+
142
+ if effective_resolution > max_effective_resolution or (
143
+ effective_resolution == max_effective_resolution
144
+ and wasted_resolution < min_wasted_resolution):
145
+ max_effective_resolution = effective_resolution
146
+ min_wasted_resolution = wasted_resolution
147
+ best_fit = (width, height)
148
+
149
+ return best_fit
150
+
151
+ @property
152
+ def bos_id(self):
153
+ return self.tokenizer.bos_token_id
154
+
155
+ @property
156
+ def eos_id(self):
157
+ return self.tokenizer.eos_token_id
158
+
159
+ @property
160
+ def pad_id(self):
161
+ return self.tokenizer.pad_token_id
162
+
163
+ def encode(self, text: str, bos: bool = True, eos: bool = False):
164
+ t = self.tokenizer.encode(text, add_special_tokens=False)
165
+
166
+ if bos:
167
+ t = [self.bos_id] + t
168
+ if eos:
169
+ t = t + [self.eos_id]
170
+
171
+ return t
172
+
173
+ def decode(self, t: list[int], **kwargs) -> str:
174
+ return self.tokenizer.decode(t, **kwargs)
175
+
176
+ def process_one(
177
+ self,
178
+ prompt: str,
179
+ images: list[Image.Image],
180
+ inference_mode: bool = True,
181
+ **kwargs,
182
+ ):
183
+ """
184
+
185
+ Args:
186
+ prompt (str): the formatted prompt;
187
+ conversations (list[dict]): conversations with a list of messages;
188
+ images (list[ImageType]): the list of images;
189
+ inference_mode (bool): if True, then remove the last eos token;
190
+ system_prompt (str): the system prompt;
191
+ **kwargs:
192
+
193
+ Returns:
194
+ outputs (BaseProcessorOutput): the output of the processor,
195
+ - input_ids (torch.LongTensor): [N + image tokens]
196
+ - target_ids (torch.LongTensor): [N + image tokens]
197
+ - pixel_values (torch.FloatTensor): [n_patches, 3, H, W]
198
+ - image_id (int): the id of the image token
199
+ - num_image_tokens (list[int]): the number of image tokens
200
+ """
201
+
202
+ assert (prompt is not None and images is not None
203
+ ), "prompt and images must be used at the same time."
204
+
205
+ sft_format = prompt
206
+ tokenized_str, images_list, images_seq_mask, images_spatial_crop, num_image_tokens = self.tokenize_with_images(
207
+ sft_format, images, bos=True, eos=True, cropping=len(images) <= 2)
208
+ masked_tokenized_str = []
209
+ for token_index in tokenized_str:
210
+ if token_index != self.image_token_id:
211
+ masked_tokenized_str.append(token_index)
212
+ else:
213
+ masked_tokenized_str.append(self.ignore_id)
214
+
215
+ assert len(tokenized_str) == len(images_seq_mask) == len(masked_tokenized_str), \
216
+ (f"tokenized_str's length {len(tokenized_str)}, input_ids' length {len(masked_tokenized_str)}, "
217
+ f"imags_seq_mask's length {len(images_seq_mask)}, are not equal")
218
+
219
+ input_ids = torch.LongTensor(tokenized_str)
220
+ target_ids = torch.LongTensor(masked_tokenized_str)
221
+ images_seq_mask = torch.tensor(images_seq_mask, dtype=torch.bool)
222
+
223
+ # set input_ids < 0 | input_ids == self.image_token_id as ignore_id
224
+ target_ids[(input_ids < 0) |
225
+ (input_ids == self.image_token_id)] = self.ignore_id
226
+ input_ids[input_ids < 0] = self.pad_id
227
+
228
+ if inference_mode:
229
+ # Remove the ending eos token
230
+ assert input_ids[-1] == self.eos_id
231
+ input_ids = input_ids[:-1]
232
+ target_ids = target_ids[:-1]
233
+ images_seq_mask = images_seq_mask[:-1]
234
+
235
+ if len(images_list) == 0:
236
+ pixel_values = torch.zeros((1, 3, self.image_size, self.image_size))
237
+ images_spatial_crop = torch.zeros((1, 2), dtype=torch.long)
238
+ else:
239
+ pixel_values = torch.stack(images_list, dim=0)
240
+ images_spatial_crop = torch.tensor(images_spatial_crop, dtype=torch.long)
241
+
242
+ input_ids = input_ids.unsqueeze(0)
243
+
244
+ prepare = BatchFeature(
245
+ data=dict(
246
+ input_ids=input_ids,
247
+ pixel_values=pixel_values,
248
+ images_seq_mask=images_seq_mask,
249
+ images_spatial_crop=images_spatial_crop,
250
+ num_image_tokens=num_image_tokens,
251
+ ),
252
+ tensor_type="pt",
253
+ )
254
+ return prepare
255
+
256
+ def __call__(
257
+ self,
258
+ *,
259
+ text: str,
260
+ images: list[Image.Image],
261
+ inference_mode: bool = True,
262
+ **kwargs,
263
+ ):
264
+ """
265
+
266
+ Args:
267
+ text (str): the formatted prompt;
268
+ images (list[ImageType]): the list of images;
269
+ inference_mode (bool): if True, then remove the last eos token;
270
+ **kwargs:
271
+
272
+ Returns:
273
+ outputs (BaseProcessorOutput): the output of the processor,
274
+ - input_ids (torch.LongTensor): [N + image tokens]
275
+ - images (torch.FloatTensor): [n_images, 3, H, W]
276
+ - image_id (int): the id of the image token
277
+ - num_image_tokens (list[int]): the number of image tokens
278
+ """
279
+
280
+ prepare = self.process_one(
281
+ prompt=text,
282
+ images=images,
283
+ inference_mode=inference_mode,
284
+ )
285
+
286
+ return prepare
287
+
288
+ def tokenize_with_images(
289
+ self,
290
+ conversation: str,
291
+ images: list[Image.Image],
292
+ bos: bool = True,
293
+ eos: bool = True,
294
+ cropping: bool = True,
295
+ ):
296
+ """Tokenize text with <image> tags."""
297
+ assert conversation.count(self.image_token) == len(images)
298
+ text_splits = conversation.split(self.image_token)
299
+ images_list, images_seq_mask, images_spatial_crop = [], [], []
300
+ num_image_tokens = []
301
+ tokenized_str = []
302
+ for text_sep, image in zip(text_splits, images):
303
+ """encode text_sep"""
304
+ tokenized_sep = self.encode(text_sep, bos=False, eos=False)
305
+ tokenized_str += tokenized_sep
306
+ images_seq_mask += [False] * len(tokenized_sep)
307
+
308
+ """select best resolution for anyres"""
309
+ if cropping:
310
+ best_width, best_height = self.select_best_resolution(image.size)
311
+ else:
312
+ best_width, best_height = self.image_size, self.image_size
313
+
314
+ """process the global view"""
315
+ global_view = ImageOps.pad(image, (self.image_size, self.image_size),
316
+ color=tuple(int(x * 255) for x in self.image_transform.mean))
317
+ images_list.append(self.image_transform(global_view))
318
+
319
+ """process the local views"""
320
+ local_view = ImageOps.pad(image, (best_width, best_height),
321
+ color=tuple(int(x * 255) for x in self.image_transform.mean))
322
+ for i in range(0, best_height, self.image_size):
323
+ for j in range(0, best_width, self.image_size):
324
+ images_list.append(
325
+ self.image_transform(local_view.crop((j, i, j + self.image_size, i + self.image_size))))
326
+
327
+ """record height / width crop num"""
328
+ num_width_tiles, num_height_tiles = best_width // self.image_size, best_height // self.image_size
329
+ images_spatial_crop.append([num_width_tiles, num_height_tiles])
330
+
331
+ """add image tokens"""
332
+ h = w = math.ceil((self.image_size // self.patch_size) / self.downsample_ratio)
333
+ # global views tokens h * (w + 1), 1 is for line separator
334
+ tokenized_image = [self.image_token_id] * h * (w + 1)
335
+ # add a separator between global and local views
336
+ tokenized_image += [self.image_token_id]
337
+ # local views tokens, (num_height_tiles * h) * (num_width_tiles * w + 1)
338
+ tokenized_image += [self.image_token_id] * (num_height_tiles * h) * (num_width_tiles * w + 1)
339
+
340
+ tokenized_str += tokenized_image
341
+ images_seq_mask += [True] * len(tokenized_image)
342
+ num_image_tokens.append(len(tokenized_image))
343
+
344
+ """process the last text split"""
345
+ tokenized_sep = self.encode(text_splits[-1], bos=False, eos=False)
346
+ tokenized_str += tokenized_sep
347
+ images_seq_mask += [False] * len(tokenized_sep)
348
+
349
+ """add the bos and eos tokens"""
350
+ if bos:
351
+ tokenized_str = [self.bos_id] + tokenized_str
352
+ images_seq_mask = [False] + images_seq_mask
353
+ if eos:
354
+ tokenized_str = tokenized_str + [self.eos_id]
355
+ images_seq_mask = images_seq_mask + [False]
356
+
357
+ assert len(tokenized_str) == len(
358
+ images_seq_mask), f"tokenize_with_images func: tokenized_str's length {len(tokenized_str)} is not equal to imags_seq_mask's length {len(images_seq_mask)}"
359
+
360
+ return tokenized_str, images_list, images_seq_mask, images_spatial_crop, num_image_tokens
361
+
362
+
363
+ AutoProcessor.register("DeepseekVLV2Processor", DeepseekVLV2Processor)
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/processors/ovis.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+
4
+ # yapf: disable
5
+ # ruff: noqa: E501
6
+ # coding=utf-8
7
+ # adapted from https://github.com/AIDC-AI/Ovis/blob/35ab51a1a1e3542fa6db260a1084cefbc8f164bb/ovis/vllm/processing_ovis.py
8
+ # Copyright 2025 The Qwen Team and The HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
11
+ # and OPT implementations in this library. It has been modified from its
12
+ # original forms to accommodate minor architectural differences compared
13
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
14
+ #
15
+ # Licensed under the Apache License, Version 2.0 (the "License");
16
+ # you may not use this file except in compliance with the License.
17
+ # You may obtain a copy of the License at
18
+ #
19
+ # http://www.apache.org/licenses/LICENSE-2.0
20
+ #
21
+ # Unless required by applicable law or agreed to in writing, software
22
+ # distributed under the License is distributed on an "AS IS" BASIS,
23
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
+ # See the License for the specific language governing permissions and
25
+ # limitations under the License.
26
+ from functools import cached_property
27
+ from typing import Union
28
+
29
+ import PIL
30
+ import torch
31
+ from transformers import AutoProcessor, BatchFeature
32
+ from transformers.image_utils import ImageInput
33
+ from transformers.processing_utils import (ProcessingKwargs, ProcessorMixin,
34
+ Unpack)
35
+ from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
36
+
37
+ from vllm.multimodal.image import convert_image_mode
38
+
39
+ __all__ = ['OvisProcessor']
40
+ IGNORE_ID = -100
41
+
42
+ class OvisProcessorKwargs(ProcessingKwargs, total=False): # type: ignore[call-arg]
43
+ _defaults = {
44
+ "text_kwargs": {
45
+ "padding": False,
46
+ },
47
+ "images_kwargs": {
48
+ 'max_partition':9,
49
+ 'covering_threshold':0.9,
50
+ 'convert_to_rgb':True,
51
+ 'return_tensors':'pt'},
52
+ }
53
+
54
+
55
+
56
+ class OvisProcessor(ProcessorMixin):
57
+ r"""
58
+ Constructs a Ovis processor which wraps a Ovis image processor and a Qwen2 tokenizer into a single processor.
59
+ [`OvisProcessor`] offers all the functionalities of [`Qwen2VLImageProcessor`] and [`Qwen2TokenizerFast`]. See the
60
+ [`~OvisProcessor.__call__`] and [`~OvisProcessor.decode`] for more information.
61
+ Args:
62
+ image_processor ([`Qwen2VLImageProcessor`], *optional*):
63
+ The image processor is a required input.
64
+ tokenizer ([`Qwen2TokenizerFast`], *optional*):
65
+ The tokenizer is a required input.
66
+ chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
67
+ in a chat into a tokenizable string.
68
+ """
69
+
70
+ attributes = ["image_processor", "tokenizer"]
71
+ valid_kwargs = ["chat_template", "image_pad_token", "image_segment_len"]
72
+
73
+ image_processor_class = "AutoImageProcessor"
74
+ tokenizer_class = "AutoTokenizer"
75
+
76
+ def __init__(
77
+ self,
78
+ image_processor=None,
79
+ tokenizer=None,
80
+ chat_template=None,
81
+ image_pad_token=None,
82
+ image_segment_len=255,
83
+ **kwargs,
84
+ ):
85
+ self.image_token = "<image>"
86
+ self.image_pad_token = image_pad_token
87
+ self.image_segment_len = image_segment_len
88
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
89
+
90
+ @cached_property
91
+ def extra_special_tokens(self):
92
+ image_pad_token_id = self.tokenizer.get_vocab()[self.image_pad_token]
93
+ extra_special_tokens = {
94
+ "image_token": -200,
95
+ "image_atom": -300,
96
+ "image_start": -301,
97
+ "image_prefix": -302,
98
+ "image_col_sep": -303,
99
+ "image_row_sep": -304,
100
+ "image_end": -305,
101
+ 'image_pad': image_pad_token_id,
102
+ }
103
+ return extra_special_tokens
104
+
105
+ def __call__(
106
+ self,
107
+ images: ImageInput = None,
108
+ text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
109
+ **kwargs: Unpack[OvisProcessorKwargs],
110
+ ) -> BatchFeature:
111
+ """
112
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
113
+ and `kwargs` arguments to Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode
114
+ the text. To prepare the vision inputs, this method forwards the `vision_infos` and `kwrags` arguments to
115
+ Qwen2VLImageProcessor's [`~Qwen2VLImageProcessor.__call__`] if `vision_infos` is not `None`.
116
+ Args:
117
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
118
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
119
+ tensor. Both channels-first and channels-last formats are supported.
120
+ text (`str`, `list[str]`, `list[list[str]]`):
121
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
122
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
123
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
124
+ videos (`np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`):
125
+ The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch
126
+ tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported.
127
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
128
+ If set, will return tensors of a particular framework. Acceptable values are:
129
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
130
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
131
+ - `'np'`: Return NumPy `np.ndarray` objects.
132
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
133
+ Returns:
134
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
135
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
136
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
137
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
138
+ `None`).
139
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
140
+ - **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.
141
+ - **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.
142
+ - **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`.
143
+ - **second_per_grid_ts** -- List of video seconds per time grid. Returned when `videos` is not `None`.
144
+ """
145
+ output_kwargs = self._merge_kwargs(
146
+ OvisProcessorKwargs,
147
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
148
+ **kwargs,
149
+ )
150
+
151
+ # Process all images first
152
+ image_features = {}
153
+ if images is not None:
154
+ processed_images = []
155
+ image_placeholders_list = []
156
+ grids = []
157
+
158
+ # Process each image
159
+ for image in images if isinstance(images, list) else [images]:
160
+ pixel_values, image_placeholders, grid = self.preprocess_image(
161
+ image=image, **output_kwargs["images_kwargs"]
162
+ )
163
+ processed_images.append(pixel_values)
164
+ image_placeholders_list.append(image_placeholders)
165
+ grids.append(grid)
166
+
167
+ # assign all processed images
168
+ if processed_images:
169
+ image_features["image_placeholders"] = image_placeholders_list
170
+
171
+ # Process text input
172
+ if text is not None:
173
+
174
+ if not isinstance(text, list):
175
+ text = [text]
176
+
177
+ tokenized_batched_text = self._tokenize_with_image_symbol(text)
178
+ image_token_id = self.get_token_value("image_token")
179
+ replaced_ids_list = []
180
+ idx = 0
181
+ for ids_tensor in tokenized_batched_text:
182
+ if image_token_id in ids_tensor and "image_placeholders" in image_features:
183
+ if idx < len(image_features["image_placeholders"]):
184
+ # Converts in list for ease of use
185
+ ids_list = ids_tensor.tolist()
186
+
187
+ new_ids = []
188
+
189
+ # replace placeholders
190
+ for i, token_id in enumerate(ids_list):
191
+ if token_id == image_token_id:
192
+ placeholder_ids = image_features["image_placeholders"][idx]
193
+ new_ids.extend(placeholder_ids)
194
+ idx += 1
195
+ else:
196
+ new_ids.append(token_id)
197
+
198
+ # Converts back to tensors
199
+ ids_tensor = torch.tensor(new_ids, dtype=torch.long)
200
+ else:
201
+ raise RuntimeError(
202
+ 'Mismatch between the images you provided and the number of placeholder present in the text')
203
+
204
+ replaced_ids_list.append(ids_tensor)
205
+
206
+ if replaced_ids_list:
207
+ replaced_and_tokenized_ids = torch.stack(replaced_ids_list)
208
+ else:
209
+ replaced_and_tokenized_ids = torch.tensor([], dtype=torch.long)
210
+
211
+ # Create the output with text features
212
+ output = BatchFeature(
213
+ data={
214
+ "input_ids": replaced_and_tokenized_ids,
215
+ }
216
+ )
217
+
218
+ # Add image features if present
219
+ if image_features:
220
+ output["pixel_values"] = processed_images
221
+ output['grids'] = grids
222
+
223
+ return output
224
+
225
+ # If only images were provided
226
+ return BatchFeature(data=image_features)
227
+
228
+ def _tokenize_with_image_symbol(self, text_list: list[str]) -> torch.LongTensor:
229
+ batch_token_ids = []
230
+ for text in text_list:
231
+ text_chunks = [self.tokenizer(chunk, add_special_tokens=False).input_ids for chunk in
232
+ text.split(self.image_token)]
233
+ token_ids = []
234
+ num_chuck = len(text_chunks)
235
+ for i, chunk in enumerate(text_chunks):
236
+ token_ids.extend(chunk)
237
+ if i < num_chuck - 1:
238
+ token_ids.append(self.get_token_value("image_token"))
239
+ batch_token_ids.append(token_ids)
240
+ return torch.tensor(batch_token_ids, dtype=torch.long)
241
+
242
+ def get_image_size(self):
243
+ size = self.image_processor.size
244
+ if 'shortest_edge' in size:
245
+ width = height = size['shortest_edge']
246
+ elif "height" in size and "width" in size:
247
+ width = size['width']
248
+ height = size['height']
249
+ else:
250
+ raise ValueError( "Can't parse image size from image_processor config.")
251
+ return height, width
252
+
253
+ def get_token_value(self, tok):
254
+ return self.extra_special_tokens[tok]
255
+
256
+ def construct_image_indicators(self, grid):
257
+ image_placeholders = [self.get_token_value('image_start'),
258
+ self.get_token_value('image_atom'),
259
+ self.get_token_value('image_prefix')]
260
+ if grid[0] * grid[1] > 1:
261
+ for r in range(grid[0]):
262
+ for c in range(grid[1]):
263
+ image_placeholders.append(self.get_token_value('image_atom') )
264
+ if c < grid[1] - 1:
265
+ image_placeholders.append(self.get_token_value('image_col_sep'))
266
+ if r < grid[0] - 1:
267
+ image_placeholders.append(self.get_token_value('image_row_sep'))
268
+ image_placeholders.append(self.get_token_value('image_end'))
269
+ return image_placeholders
270
+
271
+ def construct_image_placeholders(self, grid):
272
+
273
+ image_placeholders = self.construct_image_indicators(grid)
274
+
275
+ image_atom_token_id = self.get_token_value('image_atom')
276
+ # Extract the padding token ID from tokenizer
277
+ image_padding_token_id = self.get_token_value('image_pad')
278
+
279
+ # Create a new list with padding tokens inserted
280
+ padded_placeholder_tokens = []
281
+ for token in image_placeholders:
282
+ padded_placeholder_tokens.append(image_padding_token_id)
283
+ if token == image_atom_token_id:
284
+ padded_placeholder_tokens.extend([image_padding_token_id] * self.image_segment_len)
285
+ return padded_placeholder_tokens
286
+
287
+ def preprocess_image(self, image: PIL.Image.Image, max_partition, covering_threshold, convert_to_rgb, return_tensors):
288
+ def _preprocess(img: PIL.Image.Image, side):
289
+ # first resize and preprocess
290
+ w, h = img.size
291
+ if w == h:
292
+ new_width = new_height = side
293
+ elif w > h:
294
+ new_width = side
295
+ new_height = int(h / w * new_width)
296
+ else:
297
+ new_height = side
298
+ new_width = int(w / h * new_height)
299
+ new_size = dict(height=new_height, width=new_width)
300
+ pixel_values = self.image_processor.preprocess(img, size=new_size, return_tensors=return_tensors)['pixel_values']
301
+
302
+ # then pad to square
303
+ square_values = torch.zeros([1, 3, side, side], dtype=pixel_values.dtype, device=pixel_values.device)
304
+ new_height, new_width = pixel_values.shape[2:]
305
+ if new_height == new_width:
306
+ square_values[:, :, :, :] = pixel_values
307
+ elif new_height > new_width:
308
+ from_index = (side - new_width) // 2
309
+ square_values[:, :, :, from_index:from_index + new_width] = pixel_values
310
+ else:
311
+ from_index = (side - new_height) // 2
312
+ square_values[:, :, from_index:from_index + new_height, :] = pixel_values
313
+
314
+ return square_values
315
+
316
+ def _partition(img, grid) -> list[tuple[int, int, int, int]]:
317
+ w, h = img.size
318
+ row_height = h // grid[0]
319
+ col_width = w // grid[1]
320
+
321
+ partition = []
322
+ for row in range(grid[0]):
323
+ for col in range(grid[1]):
324
+ left = col * col_width
325
+ upper = row * row_height
326
+ right = w if col == grid[1] - 1 else (col + 1) * col_width
327
+ lower = h if row == grid[0] - 1 else (row + 1) * row_height
328
+ partition.append((left, upper, right, lower))
329
+
330
+ return partition
331
+
332
+ def _covering_area(left, upper, right, lower, side):
333
+ w = right - left
334
+ h = lower - upper
335
+ w, h = max(w, h), min(w, h)
336
+ if w > side:
337
+ h = h / w * side
338
+ w = side
339
+ return w * h
340
+
341
+ def _get_best_grid(img, side):
342
+ img_area = img.size[0] * img.size[1]
343
+
344
+ candidate_grids = []
345
+ for i in range(1, max_partition + 1):
346
+ for j in range(1, max_partition + 1):
347
+ if i * j <= max_partition:
348
+ candidate_grids.append((i, j))
349
+
350
+ all_grids = []
351
+ good_grids = []
352
+ for grid in candidate_grids:
353
+ partition = _partition(img, grid)
354
+ covering_ratio = sum([_covering_area(*p, side) for p in partition]) / img_area
355
+ assert covering_ratio <= 1.0
356
+ all_grids.append((grid, covering_ratio))
357
+ if covering_ratio > covering_threshold:
358
+ good_grids.append((grid, covering_ratio))
359
+
360
+ if len(good_grids) > 0:
361
+ # pick the good partition with minimum #sub_images and break the tie using covering_ratio
362
+ return sorted(good_grids, key=lambda x: (x[0][0] * x[0][1], -x[1]))[0][0]
363
+ else:
364
+ # pick the partition with maximum covering_ratio and break the tie using #sub_images
365
+ return sorted(all_grids, key=lambda x: (-x[1], x[0][0] * x[0][1]))[0][0]
366
+
367
+ if convert_to_rgb:
368
+ image = convert_image_mode(image, 'RGB')
369
+
370
+
371
+ sides = self.get_image_size()
372
+ if sides[0] != sides[1]:
373
+ raise ValueError('get_image_size() returns non-square size')
374
+ side = sides[0]
375
+ grid = _get_best_grid(image, side)
376
+ partition = _partition(image, grid)
377
+ crops = [image.crop(p) for p in partition]
378
+ if len(crops) > 1:
379
+ crops.insert(0, image)
380
+ pixel_values = torch.cat([_preprocess(crop, side) for crop in crops], dim=0)
381
+ image_placeholders = self.construct_image_placeholders(grid)
382
+ return pixel_values, image_placeholders, grid
383
+
384
+ def batch_decode(self, *args, **kwargs):
385
+ """
386
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
387
+ refer to the docstring of this method for more information.
388
+ """
389
+ return self.tokenizer.batch_decode(*args, **kwargs)
390
+
391
+ def decode(self, *args, **kwargs):
392
+ """
393
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
394
+ the docstring of this method for more information.
395
+ """
396
+ return self.tokenizer.decode(*args, **kwargs)
397
+
398
+ def post_process_image_text_to_text(self, generated_outputs):
399
+ """
400
+ Post-process the output of the model to decode the text.
401
+ Args:
402
+ generated_outputs (`torch.Tensor` or `np.ndarray`):
403
+ The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
404
+ or `(sequence_length,)`.
405
+ Returns:
406
+ `list[str]`: The decoded text.
407
+ """
408
+ return self.tokenizer.batch_decode(
409
+ generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False
410
+ )
411
+
412
+ @property
413
+ def model_input_names(self):
414
+ tokenizer_input_names = self.tokenizer.model_input_names
415
+ image_processor_input_names = self.image_processor.model_input_names
416
+ names_from_processor = list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
417
+ return names_from_processor + ["second_per_grid_ts"]
418
+
419
+
420
+ AutoProcessor.register("OvisProcessor", OvisProcessor)
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/tokenizers/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+
4
+ from .mistral import (MistralTokenizer, maybe_serialize_tool_calls,
5
+ truncate_tool_call_ids, validate_request_params)
6
+
7
+ __all__ = [
8
+ "MistralTokenizer", "maybe_serialize_tool_calls", "truncate_tool_call_ids",
9
+ "validate_request_params"
10
+ ]
tool_server/.venv/lib/python3.12/site-packages/vllm/transformers_utils/tokenizers/mistral.py ADDED
@@ -0,0 +1,516 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+
4
+ import os
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING, Any, Optional, Union, cast
7
+
8
+ import huggingface_hub
9
+ import regex as re
10
+ from huggingface_hub import HfApi, hf_hub_download
11
+ from transformers.tokenization_utils_base import BatchEncoding
12
+
13
+ from vllm.logger import init_logger
14
+ from vllm.transformers_utils.tokenizer_base import TokenizerBase
15
+ from vllm.utils import is_list_of
16
+
17
+ if TYPE_CHECKING:
18
+ # make sure `mistral_common` is lazy imported,
19
+ # so that users who only use non-mistral models
20
+ # will not be bothered by the dependency.
21
+ from mistral_common.protocol.instruct.request import ChatCompletionRequest
22
+ from mistral_common.tokens.tokenizers.mistral import (
23
+ MistralTokenizer as PublicMistralTokenizer)
24
+
25
+ from vllm.entrypoints.chat_utils import ChatCompletionMessageParam
26
+
27
+ logger = init_logger(__name__)
28
+
29
+
30
+ def maybe_serialize_tool_calls(request: "ChatCompletionRequest"):
31
+ # SEE: https://github.com/vllm-project/vllm/pull/9951
32
+ # Credits go to: @gcalmettes
33
+ # NOTE: There is currently a bug in pydantic where attributes
34
+ # declared as iterables are replaced in in the instances by
35
+ # pydantic-core ValidatorIterator instance. In particular, this
36
+ # affects tool_calls defined in ChatCompletionAssistantMessageParam
37
+ # model:
38
+ # see:
39
+ # - https://github.com/pydantic/pydantic/issues/9467
40
+ # As a result, tool_calls from assistant messages are never
41
+ # deserialized in the request object if the tool_calls iterator is
42
+ # not consumed. This affect messages passed to the MistralTokenizer
43
+ # since no chat template is applied and therefore the tools_calls
44
+ # iterator is not directly consumed.
45
+ # Issue is tracked on Pydantic side, with resolution planned for
46
+ # v2.11 release. In the meantime, the official workaround is to
47
+ # consume the iterator so the tool_calls are correctly deserialized
48
+ # in the OpenAI ChatCompletionAssistantMessageParam object
49
+ # https://github.com/pydantic/pydantic/issues/9467#issuecomment-2442097291 # noqa: E501
50
+ # Official Pydantic Issues:
51
+ # - https://github.com/pydantic/pydantic/issues/9541
52
+ # TODO: remove when pydantic v2.11 is released
53
+ for i, message in enumerate(request.messages):
54
+ if message.get("role") == 'assistant':
55
+ tool_calls_validator = message.get("tool_calls", ().__iter__())
56
+ validated_tool_calls = []
57
+ while True:
58
+ try:
59
+ tool_call = next(tool_calls_validator) # type: ignore
60
+ validated_tool_calls.append(tool_call)
61
+ except StopIteration:
62
+ break
63
+
64
+ request.messages[i]["tool_calls"] = validated_tool_calls
65
+
66
+
67
+ def truncate_tool_call_ids(request: "ChatCompletionRequest"):
68
+ """Truncates tool call IDs for Mistral's ID requirements."""
69
+ for i, message in enumerate(request.messages):
70
+ if message.get("role") == 'assistant':
71
+ tool_calls = message.get("tool_calls", [])
72
+ for tool_call in tool_calls:
73
+ if len(tool_call["id"]) > 9:
74
+ logger.warning(
75
+ "Truncating tool call ID: %s to %s",
76
+ tool_call["id"],
77
+ tool_call["id"][-9:],
78
+ )
79
+ tool_call["id"] = tool_call["id"][-9:]
80
+
81
+ request.messages[i]["tool_calls"] = tool_calls
82
+
83
+ elif message.get("role") in {"tool_results", "tool"}:
84
+ if "tool_call_id" in message:
85
+ tool_call_id = message["tool_call_id"]
86
+
87
+ if len(tool_call_id) > 9:
88
+ logger.warning(
89
+ "Truncating tool_call_id: %s to %s",
90
+ tool_call_id,
91
+ tool_call_id[-9:],
92
+ )
93
+ tool_call_id = tool_call_id[-9:]
94
+ request.messages[i]["tool_call_id"] = tool_call_id
95
+
96
+
97
+ def validate_request_params(request: "ChatCompletionRequest"):
98
+ if (request.skip_special_tokens is not None
99
+ and not request.skip_special_tokens):
100
+ raise ValueError("skip_special_tokens=False is not supported "
101
+ "for Mistral tokenizers.")
102
+
103
+
104
+ def list_local_repo_files(repo_id: str, revision: Optional[str]) -> list[str]:
105
+ repo_cache = os.path.join(
106
+ huggingface_hub.constants.HF_HUB_CACHE,
107
+ huggingface_hub.constants.REPO_ID_SEPARATOR.join(
108
+ ["models", *repo_id.split("/")]))
109
+
110
+ if revision is None:
111
+ revision_file = os.path.join(repo_cache, "refs", "main")
112
+ if os.path.isfile(revision_file):
113
+ with open(revision_file) as file:
114
+ revision = file.read()
115
+
116
+ if revision:
117
+ revision_dir = os.path.join(repo_cache, "snapshots", revision)
118
+ if os.path.isdir(revision_dir):
119
+ return os.listdir(revision_dir)
120
+
121
+ return []
122
+
123
+
124
+ def find_tokenizer_file(files: list[str]):
125
+ file_pattern = re.compile(
126
+ r"^tokenizer\.model\.v.*$|^tekken\.json$|^tokenizer\.mm\.model\.v.*$")
127
+
128
+ matched_files = [file for file in files if file_pattern.match(file)]
129
+ if len(matched_files) > 1:
130
+ raise OSError(
131
+ f"Found {len(matched_files)} files matching the "
132
+ f"pattern: `{file_pattern.pattern}`. Make sure only one Mistral "
133
+ f"tokenizer is present in {files}.")
134
+ elif len(matched_files) == 0:
135
+ raise OSError(
136
+ f"Found {len(matched_files)} files matching the "
137
+ f"pattern: `{file_pattern.pattern}`. Make sure that a Mistral "
138
+ f"tokenizer is present in {files}.")
139
+
140
+ return matched_files[0]
141
+
142
+
143
+ def _aggregate_content(content: list) -> list[dict[str, Any]]:
144
+ aggregated_content: list[dict[str, Any]] = []
145
+ for chunk in content:
146
+ if chunk.get("type"
147
+ ) == "text" and aggregated_content and aggregated_content[
148
+ -1].get("type") == "text":
149
+ aggregated_content[-1]["text"] += "\n\n" + chunk.get("text")
150
+ else:
151
+ aggregated_content.append(chunk)
152
+ if len(aggregated_content) == 1 and aggregated_content[0].get(
153
+ "type") == "text":
154
+ content = aggregated_content[0]["text"]
155
+ return content
156
+
157
+
158
+ def make_mistral_chat_completion_request(
159
+ messages: list["ChatCompletionMessageParam"],
160
+ tools: Optional[list[dict[str,
161
+ Any]]] = None) -> "ChatCompletionRequest":
162
+ last_message = cast(dict[str, Any], messages[-1])
163
+ if last_message["role"] == "assistant":
164
+ last_message["prefix"] = True
165
+
166
+ # mistral-common requires AssistantMessage content to be string [1].
167
+ #
168
+ # [1]: https://github.com/mistralai/mistral-common/blob/f4a06998b75ed78bbf5aaf569590b772ea26c9f6/src/mistral_common/protocol/instruct/messages.py#L80
169
+ for message in messages:
170
+ # Remove reasoning_content as unsupported by Mistral
171
+ _ = message.pop("reasoning_content", None) # type: ignore
172
+
173
+ # Convert list text content to string
174
+ if message.get("role") in ("assistant", "tool"):
175
+ content: Any = message.get("content")
176
+ if isinstance(content, list):
177
+ content = _aggregate_content(content)
178
+ message["content"] = content
179
+
180
+ # The Mistral client, in comparison to the OpenAI client, requires the
181
+ # "parameters" dict and the "description" string to be present
182
+ # even if they are empty.
183
+ if tools:
184
+ for function in [
185
+ tool["function"] for tool in tools
186
+ if tool["type"] == "function"
187
+ ]:
188
+ if function.get("parameters") is None:
189
+ function["parameters"] = {}
190
+ if function.get("description") is None:
191
+ function["description"] = ""
192
+
193
+ from mistral_common.protocol.instruct.request import ChatCompletionRequest
194
+ return ChatCompletionRequest(messages=messages,
195
+ tools=tools) # type: ignore[type-var]
196
+
197
+
198
+ class MistralTokenizer(TokenizerBase):
199
+
200
+ def __init__(self, tokenizer: "PublicMistralTokenizer") -> None:
201
+ self.mistral = tokenizer
202
+ self.instruct = tokenizer.instruct_tokenizer
203
+ _mistral_version_str = self.instruct.tokenizer.version.value
204
+ self.version: int = int(_mistral_version_str.split("v")[-1])
205
+
206
+ tokenizer_ = tokenizer.instruct_tokenizer.tokenizer
207
+ from mistral_common.tokens.tokenizers.tekken import (
208
+ SpecialTokenPolicy, Tekkenizer)
209
+ self.is_tekken = isinstance(tokenizer_, Tekkenizer)
210
+ from mistral_common.tokens.tokenizers.sentencepiece import (
211
+ SentencePieceTokenizer)
212
+ self.is_spm = isinstance(tokenizer_, SentencePieceTokenizer)
213
+ if self.is_tekken:
214
+ # Make sure special tokens will not raise
215
+ tokenizer_.special_token_policy = SpecialTokenPolicy.IGNORE
216
+ elif self.is_spm:
217
+ pass
218
+ else:
219
+ raise TypeError(f"Unsupported tokenizer: {type(tokenizer_)}")
220
+
221
+ self._vocab = tokenizer_.vocab()
222
+ # Convert to a dict[str, int] to match protocol, but this is a lossy
223
+ # conversion. There may be multiple token ids that decode to the same
224
+ # string due to partial UTF-8 byte sequences being converted to �
225
+ self._vocab_dict = {
226
+ token: idx
227
+ for idx, token in enumerate(self._vocab)
228
+ }
229
+ self.tokenizer = tokenizer_
230
+ self._max_token_id = self.vocab_size - 1
231
+
232
+ @classmethod
233
+ def from_pretrained(cls,
234
+ path_or_repo_id: str,
235
+ *,
236
+ revision: Optional[str] = None) -> "MistralTokenizer":
237
+ if not Path(path_or_repo_id).exists():
238
+ assert len(path_or_repo_id.split("/")) == 2, (
239
+ "You have either provided a non-existent path: "
240
+ "{path_or_repo_id} or an invalid HF Hub repo id.")
241
+ tokenizer_file = cls._download_mistral_tokenizer_from_hf(
242
+ path_or_repo_id, revision)
243
+ elif Path(path_or_repo_id).is_dir():
244
+ tokenizer_file_name = find_tokenizer_file(
245
+ os.listdir(path_or_repo_id))
246
+ tokenizer_file = str(Path(path_or_repo_id) / tokenizer_file_name)
247
+ else:
248
+ assert Path(
249
+ path_or_repo_id).is_file(), f"Invalid path: {path_or_repo_id}"
250
+ tokenizer_file = str(Path(path_or_repo_id))
251
+
252
+ from mistral_common.tokens.tokenizers.mistral import (
253
+ MistralTokenizer as PublicMistralTokenizer)
254
+ mistral_tokenizer = PublicMistralTokenizer.from_file(tokenizer_file)
255
+ return cls(mistral_tokenizer)
256
+
257
+ @staticmethod
258
+ def _download_mistral_tokenizer_from_hf(tokenizer_name: str,
259
+ revision: Optional[str]) -> str:
260
+ try:
261
+ hf_api = HfApi()
262
+ files = hf_api.list_repo_files(repo_id=tokenizer_name,
263
+ revision=revision)
264
+ except ConnectionError as exc:
265
+ files = list_local_repo_files(repo_id=tokenizer_name,
266
+ revision=revision)
267
+
268
+ if len(files) == 0:
269
+ raise exc
270
+
271
+ filename = find_tokenizer_file(files)
272
+
273
+ tokenizer_file = hf_hub_download(tokenizer_name,
274
+ filename=filename,
275
+ revision=revision)
276
+ return tokenizer_file
277
+
278
+ # the following attributes are set to fit vLLM's design and are used
279
+ # by the guided structured output backends.
280
+ @property
281
+ def all_special_tokens_extended(self) -> list[str]:
282
+ from mistral_common.tokens.tokenizers.base import SpecialTokens
283
+
284
+ # tekken defines its own extended special tokens list
285
+ if hasattr(self.tokenizer, "SPECIAL_TOKENS"):
286
+ special_tokens = self.tokenizer.SPECIAL_TOKENS
287
+ else:
288
+ special_tokens = list(SpecialTokens)
289
+ return [
290
+ s.value if isinstance(s, SpecialTokens) else s
291
+ for s in special_tokens
292
+ ]
293
+
294
+ @property
295
+ def all_special_tokens(self) -> list[str]:
296
+ return self.all_special_tokens_extended
297
+
298
+ @property
299
+ def all_special_ids(self) -> list[int]:
300
+ return [
301
+ self.all_special_tokens.index(t) for t in self.all_special_tokens
302
+ ]
303
+
304
+ @property
305
+ def bos_token_id(self) -> int:
306
+ return self.tokenizer.bos_id
307
+
308
+ @property
309
+ def eos_token_id(self) -> int:
310
+ return self.tokenizer.eos_id
311
+
312
+ @property
313
+ def sep_token(self) -> str:
314
+ raise NotImplementedError()
315
+
316
+ @property
317
+ def pad_token(self) -> str:
318
+ raise NotImplementedError()
319
+
320
+ @property
321
+ def is_fast(self) -> bool:
322
+ return True
323
+
324
+ @property
325
+ def vocab_size(self) -> int:
326
+ return len(self._vocab)
327
+
328
+ @property
329
+ def max_token_id(self) -> int:
330
+ return self._max_token_id
331
+
332
+ def __len__(self) -> int:
333
+ return self.vocab_size
334
+
335
+ def __call__(
336
+ self,
337
+ text: Union[str, list[str], list[int]],
338
+ text_pair: Optional[str] = None,
339
+ add_special_tokens: bool = False,
340
+ truncation: bool = False,
341
+ max_length: Optional[int] = None,
342
+ ):
343
+ input_ids: Union[list[int], list[list[int]]]
344
+ # For list[str], original prompt text
345
+ if is_list_of(text, str):
346
+ input_ids_: list[list[int]] = []
347
+ for p in text:
348
+ each_input_ids = self.encode_one(p, truncation, max_length)
349
+ input_ids_.append(each_input_ids)
350
+ input_ids = input_ids_
351
+ # For list[int], apply chat template output, already tokens.
352
+ elif is_list_of(text, int):
353
+ input_ids = text
354
+ # For str, single prompt text
355
+ else:
356
+ input_ids = self.encode_one(text, truncation, max_length)
357
+ return BatchEncoding({"input_ids": input_ids})
358
+
359
+ def get_vocab(self) -> dict[str, int]:
360
+ # NB: the dictionary form of the vocabulary collapses token ids that map
361
+ # to the same string but have different bytes
362
+ return self._vocab_dict
363
+
364
+ def get_added_vocab(self) -> dict[str, int]:
365
+ # Mistral tokenizers have no added vocabulary
366
+ return {}
367
+
368
+ def encode_one(
369
+ self,
370
+ text: str,
371
+ truncation: bool = False,
372
+ max_length: Optional[int] = None,
373
+ ) -> list[int]:
374
+ # Mistral Tokenizers should not add special tokens
375
+ input_ids = self.encode(text)
376
+
377
+ if truncation:
378
+ input_ids = input_ids[:max_length]
379
+ return input_ids
380
+
381
+ def encode(self,
382
+ text: str,
383
+ truncation: Optional[bool] = None,
384
+ max_length: Optional[int] = None,
385
+ add_special_tokens: Optional[bool] = None) -> list[int]:
386
+ # `encode` should only be used for prompt completion
387
+ # it should never be used for chat_completion.
388
+ # For chat completion use `apply_chat_template`
389
+ if add_special_tokens is not None:
390
+ return self.tokenizer.encode(text,
391
+ bos=add_special_tokens,
392
+ eos=add_special_tokens)
393
+ else:
394
+ return self.tokenizer.encode(text, bos=True, eos=False)
395
+
396
+ def apply_chat_template(self,
397
+ messages: list["ChatCompletionMessageParam"],
398
+ tools: Optional[list[dict[str, Any]]] = None,
399
+ **kwargs) -> list[int]:
400
+
401
+ request = make_mistral_chat_completion_request(messages, tools)
402
+ encoded = self.mistral.encode_chat_completion(request)
403
+
404
+ # encode-decode to get clean prompt
405
+ return encoded.tokens
406
+
407
+ def convert_tokens_to_string(self, tokens: list[str]) -> str:
408
+ from mistral_common.tokens.tokenizers.base import SpecialTokens
409
+ if self.is_tekken:
410
+ tokens = [
411
+ t for t in tokens
412
+ if (t is SpecialTokens.tool_calls
413
+ or t not in self.tokenizer._all_special_tokens)
414
+ ]
415
+
416
+ if any(isinstance(t, bytes) for t in tokens):
417
+ # we need to encode and decode all tokens again
418
+ shift = self.tokenizer.num_special_tokens
419
+
420
+ def _token_to_id(t: str):
421
+ t_bytes = t.encode("utf-8") \
422
+ if not isinstance(t, bytes) else t
423
+ try:
424
+ return shift + \
425
+ self.tokenizer._tekken_token2id_nospecial[t_bytes]
426
+ except KeyError:
427
+ logger.warning(
428
+ "Failed to convert token %s to id,"
429
+ " replacing with <unk>", t_bytes)
430
+ return self.tokenizer.unk_id
431
+
432
+ ids = [_token_to_id(t) for t in tokens]
433
+ decoded = self.tokenizer.decode(ids)
434
+ else:
435
+ decoded = "".join(tokens)
436
+ else:
437
+ # make sure certain special tokens like Tool calls are
438
+ # not decoded
439
+ special_tokens = {SpecialTokens.tool_calls}
440
+ regular_tokens: list[str] = []
441
+ decoded_list = []
442
+
443
+ for token in tokens:
444
+ if token in special_tokens:
445
+ if regular_tokens:
446
+ decoded_list.append(
447
+ self.tokenizer.decode(regular_tokens))
448
+ regular_tokens = []
449
+ decoded_list.append(token)
450
+ else:
451
+ regular_tokens.append(token)
452
+
453
+ if regular_tokens:
454
+ decoded_list.append(
455
+ self.tokenizer.decode(regular_tokens)) # type: ignore
456
+
457
+ decoded = ''.join(decoded_list)
458
+
459
+ return decoded
460
+
461
+ # WARN: Outlines logits processors can overwrite this method.
462
+ # See: guided_decoding/outlines_logits_processors.py::_adapt_tokenizer
463
+ # for more.
464
+ def decode(self,
465
+ ids: Union[list[int], int],
466
+ skip_special_tokens: bool = True) -> str:
467
+ assert (
468
+ skip_special_tokens
469
+ ), "skip_special_tokens=False is not supported for Mistral tokenizers."
470
+
471
+ if isinstance(ids, int):
472
+ ids = [ids]
473
+ return self.tokenizer.decode(ids)
474
+
475
+ def convert_ids_to_tokens(
476
+ self,
477
+ ids: list[int],
478
+ skip_special_tokens: bool = True,
479
+ ) -> list[str]:
480
+ from mistral_common.tokens.tokenizers.base import SpecialTokens
481
+ from mistral_common.tokens.tokenizers.instruct import (
482
+ InstructTokenizerV13)
483
+
484
+ # TODO(Patrick) - potentially allow special tokens to not be skipped
485
+ assert (
486
+ skip_special_tokens
487
+ ), "skip_special_tokens=False is not supported for Mistral tokenizers."
488
+
489
+ assert self.is_tekken or self.is_spm, type(self.tokenizer)
490
+
491
+ if self.is_tekken:
492
+ # skip special tokens except tool call and think tokens
493
+ non_skip_special_tokens = {
494
+ self.tokenizer.get_control_token(SpecialTokens.tool_calls)
495
+ }
496
+ if isinstance(self.instruct, InstructTokenizerV13):
497
+ if self.instruct.BEGIN_THINK:
498
+ non_skip_special_tokens.add(self.instruct.BEGIN_THINK)
499
+ if self.instruct.END_THINK:
500
+ non_skip_special_tokens.add(self.instruct.END_THINK)
501
+ ids = [
502
+ i for i in ids if i > self.tokenizer.num_special_tokens
503
+ or i in non_skip_special_tokens
504
+ ]
505
+
506
+ tokens = [self.tokenizer.id_to_piece(id) for id in ids]
507
+
508
+ if any("�" in t for t in tokens) and self.is_tekken:
509
+ # if a decoded token contains the replacement character, then the
510
+ # token has an incomplete UTF-8 character so we must use bytes
511
+ # See: https://github.com/vllm-project/vllm/pull/8640
512
+ # https://github.com/vllm-project/vllm/pull/9625
513
+ # if underlying tokenizeir is sentencepiece, we just add "�"
514
+ tokens = [self.tokenizer.id_to_byte_piece(id) for id in ids]
515
+
516
+ return tokens