optimum-rbln 0.8.2a4__py3-none-any.whl → 0.9.3rc0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- optimum/rbln/__init__.py +96 -9
- optimum/rbln/__version__.py +16 -3
- optimum/rbln/cli.py +660 -0
- optimum/rbln/configuration_utils.py +153 -42
- optimum/rbln/diffusers/__init__.py +7 -0
- optimum/rbln/diffusers/configurations/models/configuration_autoencoder_kl.py +3 -3
- optimum/rbln/diffusers/configurations/models/configuration_autoencoder_kl_cosmos.py +1 -1
- optimum/rbln/diffusers/configurations/models/configuration_controlnet.py +3 -3
- optimum/rbln/diffusers/configurations/models/configuration_prior_transformer.py +4 -4
- optimum/rbln/diffusers/configurations/models/configuration_transformer_cosmos.py +9 -4
- optimum/rbln/diffusers/configurations/models/configuration_transformer_sd3.py +9 -4
- optimum/rbln/diffusers/configurations/models/configuration_unet_2d_condition.py +3 -3
- optimum/rbln/diffusers/configurations/models/configuration_vq_model.py +3 -3
- optimum/rbln/diffusers/configurations/pipelines/configuration_controlnet.py +35 -19
- optimum/rbln/diffusers/configurations/pipelines/configuration_cosmos.py +14 -11
- optimum/rbln/diffusers/configurations/pipelines/configuration_kandinsky2_2.py +30 -20
- optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion.py +13 -9
- optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion_3.py +17 -13
- optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion_xl.py +17 -10
- optimum/rbln/diffusers/modeling_diffusers.py +30 -14
- optimum/rbln/diffusers/models/__init__.py +3 -13
- optimum/rbln/diffusers/models/autoencoders/autoencoder_kl.py +31 -3
- optimum/rbln/diffusers/models/autoencoders/autoencoder_kl_cosmos.py +28 -3
- optimum/rbln/diffusers/models/autoencoders/vq_model.py +31 -3
- optimum/rbln/diffusers/models/transformers/prior_transformer.py +1 -1
- optimum/rbln/diffusers/models/transformers/transformer_cosmos.py +9 -1
- optimum/rbln/diffusers/models/transformers/transformer_sd3.py +9 -1
- optimum/rbln/diffusers/models/unets/unet_2d_condition.py +6 -3
- optimum/rbln/diffusers/pipelines/__init__.py +11 -5
- optimum/rbln/diffusers/pipelines/auto_pipeline.py +307 -0
- optimum/rbln/diffusers/pipelines/cosmos/configuration_cosmos_guardrail.py +19 -16
- optimum/rbln/diffusers/pipelines/cosmos/cosmos_guardrail.py +14 -18
- optimum/rbln/diffusers/pipelines/cosmos/pipeline_cosmos_text2world.py +31 -1
- optimum/rbln/diffusers/pipelines/cosmos/pipeline_cosmos_video2world.py +31 -1
- optimum/rbln/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +1 -6
- optimum/rbln/modeling.py +71 -19
- optimum/rbln/modeling_base.py +99 -21
- optimum/rbln/ops/attn.py +158 -0
- optimum/rbln/ops/flash_attn.py +166 -0
- optimum/rbln/ops/kv_cache_update.py +5 -0
- optimum/rbln/ops/linear.py +7 -0
- optimum/rbln/transformers/__init__.py +92 -0
- optimum/rbln/transformers/configuration_generic.py +9 -7
- optimum/rbln/transformers/modeling_attention_utils.py +252 -0
- optimum/rbln/transformers/modeling_generic.py +51 -9
- optimum/rbln/transformers/modeling_outputs.py +37 -0
- optimum/rbln/transformers/models/__init__.py +91 -30
- optimum/rbln/transformers/models/auto/__init__.py +2 -0
- optimum/rbln/transformers/models/auto/auto_factory.py +92 -17
- optimum/rbln/transformers/models/auto/modeling_auto.py +45 -0
- optimum/rbln/transformers/models/bart/bart_architecture.py +1 -3
- optimum/rbln/transformers/models/bart/configuration_bart.py +2 -0
- optimum/rbln/transformers/models/bert/bert_architecture.py +16 -0
- optimum/rbln/transformers/models/bert/modeling_bert.py +8 -4
- optimum/rbln/transformers/models/blip_2/configuration_blip_2.py +42 -11
- optimum/rbln/transformers/models/blip_2/modeling_blip_2.py +94 -30
- optimum/rbln/transformers/models/clip/configuration_clip.py +10 -7
- optimum/rbln/transformers/models/clip/modeling_clip.py +27 -4
- optimum/rbln/transformers/models/colpali/colpali_architecture.py +3 -6
- optimum/rbln/transformers/models/colpali/configuration_colpali.py +37 -21
- optimum/rbln/transformers/models/colpali/modeling_colpali.py +113 -96
- optimum/rbln/transformers/models/colqwen2/__init__.py +2 -0
- optimum/rbln/transformers/models/colqwen2/colqwen2_architecture.py +233 -0
- optimum/rbln/transformers/models/colqwen2/configuration_colqwen2.py +74 -0
- optimum/rbln/transformers/models/colqwen2/modeling_colqwen2.py +446 -0
- optimum/rbln/transformers/models/decoderonly/__init__.py +3 -2
- optimum/rbln/transformers/models/decoderonly/configuration_decoderonly.py +109 -37
- optimum/rbln/transformers/models/decoderonly/configuration_lora.py +411 -0
- optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py +318 -309
- optimum/rbln/transformers/models/decoderonly/decoderonly_runtime_utils.py +504 -0
- optimum/rbln/transformers/models/decoderonly/generation_decoderonly.py +111 -0
- optimum/rbln/transformers/models/decoderonly/lora_architecture.py +204 -0
- optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py +453 -897
- optimum/rbln/transformers/models/depth_anything/__init__.py +16 -0
- optimum/rbln/transformers/models/depth_anything/configuration_depth_anything.py +24 -0
- optimum/rbln/transformers/models/depth_anything/modeling_depth_anything.py +25 -0
- optimum/rbln/transformers/models/exaone/modeling_exaone.py +42 -4
- optimum/rbln/transformers/models/gemma/__init__.py +2 -2
- optimum/rbln/transformers/models/gemma/configuration_gemma.py +9 -1
- optimum/rbln/transformers/models/gemma/gemma_architecture.py +1 -4
- optimum/rbln/transformers/models/gemma/modeling_gemma.py +22 -1
- optimum/rbln/transformers/models/gemma3/configuration_gemma3.py +49 -13
- optimum/rbln/transformers/models/gemma3/gemma3_architecture.py +12 -2
- optimum/rbln/transformers/models/gemma3/gemma3_runtime_utils.py +245 -0
- optimum/rbln/transformers/models/gemma3/modeling_gemma3.py +201 -349
- optimum/rbln/transformers/models/gpt2/__init__.py +2 -2
- optimum/rbln/transformers/models/gpt2/configuration_gpt2.py +31 -3
- optimum/rbln/transformers/models/gpt2/gpt2_architecture.py +10 -8
- optimum/rbln/transformers/models/gpt2/modeling_gpt2.py +18 -1
- optimum/rbln/transformers/models/grounding_dino/__init__.py +10 -0
- optimum/rbln/transformers/models/grounding_dino/configuration_grounding_dino.py +92 -0
- optimum/rbln/transformers/models/grounding_dino/grounding_dino_architecture.py +599 -0
- optimum/rbln/transformers/models/grounding_dino/modeling_grounding_dino.py +1032 -0
- optimum/rbln/transformers/models/idefics3/configuration_idefics3.py +35 -7
- optimum/rbln/transformers/models/idefics3/modeling_idefics3.py +26 -27
- optimum/rbln/transformers/models/llama/__init__.py +2 -2
- optimum/rbln/transformers/models/llama/configuration_llama.py +9 -1
- optimum/rbln/transformers/models/llama/modeling_llama.py +22 -1
- optimum/rbln/transformers/models/llava/__init__.py +16 -0
- optimum/rbln/transformers/models/llava/configuration_llava.py +72 -0
- optimum/rbln/transformers/models/llava/modeling_llava.py +478 -0
- optimum/rbln/transformers/models/llava_next/configuration_llava_next.py +15 -17
- optimum/rbln/transformers/models/llava_next/modeling_llava_next.py +235 -375
- optimum/rbln/transformers/models/midm/midm_architecture.py +4 -1
- optimum/rbln/transformers/models/midm/modeling_midm.py +42 -4
- optimum/rbln/transformers/models/mistral/__init__.py +2 -2
- optimum/rbln/transformers/models/mistral/configuration_mistral.py +9 -1
- optimum/rbln/transformers/models/mistral/mistral_architecture.py +1 -1
- optimum/rbln/transformers/models/mistral/modeling_mistral.py +26 -3
- optimum/rbln/transformers/models/opt/__init__.py +2 -2
- optimum/rbln/transformers/models/opt/configuration_opt.py +8 -1
- optimum/rbln/transformers/models/opt/modeling_opt.py +28 -16
- optimum/rbln/transformers/models/opt/opt_architecture.py +4 -4
- optimum/rbln/transformers/models/pegasus/__init__.py +17 -0
- optimum/rbln/transformers/models/pegasus/configuration_pegasus.py +38 -0
- optimum/rbln/transformers/models/pegasus/modeling_pegasus.py +71 -0
- optimum/rbln/transformers/models/pegasus/pegasus_architecture.py +161 -0
- optimum/rbln/transformers/models/phi/__init__.py +2 -2
- optimum/rbln/transformers/models/phi/configuration_phi.py +9 -1
- optimum/rbln/transformers/models/phi/modeling_phi.py +10 -1
- optimum/rbln/transformers/models/phi/phi_architecture.py +11 -7
- optimum/rbln/transformers/models/pixtral/__init__.py +16 -0
- optimum/rbln/transformers/models/pixtral/configuration_pixtral.py +43 -0
- optimum/rbln/transformers/models/pixtral/modeling_pixtral.py +310 -0
- optimum/rbln/transformers/models/pixtral/pixtral_architecture.py +73 -0
- optimum/rbln/transformers/models/qwen2/__init__.py +2 -2
- optimum/rbln/transformers/models/qwen2/configuration_qwen2.py +9 -1
- optimum/rbln/transformers/models/qwen2/modeling_qwen2.py +27 -1
- optimum/rbln/transformers/models/qwen2_5_vl/configuration_qwen2_5_vl.py +21 -6
- optimum/rbln/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py +15 -21
- optimum/rbln/transformers/models/qwen2_5_vl/qwen2_5_vl_architecture.py +28 -7
- optimum/rbln/transformers/models/qwen2_vl/__init__.py +19 -0
- optimum/rbln/transformers/models/qwen2_vl/configuration_qwen2_vl.py +88 -0
- optimum/rbln/transformers/models/qwen2_vl/modeling_qwen2_vl.py +514 -0
- optimum/rbln/transformers/models/qwen2_vl/qwen2_vl_architecture.py +165 -0
- optimum/rbln/transformers/models/qwen3/configuration_qwen3.py +2 -2
- optimum/rbln/transformers/models/qwen3/modeling_qwen3.py +86 -330
- optimum/rbln/transformers/models/qwen3/qwen3_architecture.py +1 -245
- optimum/rbln/transformers/models/seq2seq/configuration_seq2seq.py +20 -13
- optimum/rbln/transformers/models/seq2seq/modeling_seq2seq.py +24 -3
- optimum/rbln/transformers/models/seq2seq/seq2seq_architecture.py +2 -2
- optimum/rbln/transformers/models/siglip/__init__.py +2 -6
- optimum/rbln/transformers/models/siglip/configuration_siglip.py +1 -1
- optimum/rbln/transformers/models/siglip/modeling_siglip.py +5 -16
- optimum/rbln/transformers/models/swin/__init__.py +16 -0
- optimum/rbln/transformers/models/swin/configuration_swin.py +42 -0
- optimum/rbln/transformers/models/swin/modeling_swin.py +341 -0
- optimum/rbln/transformers/models/t5/configuration_t5.py +2 -0
- optimum/rbln/transformers/models/t5/t5_architecture.py +8 -1
- optimum/rbln/transformers/models/time_series_transformer/configuration_time_series_transformer.py +3 -3
- optimum/rbln/transformers/models/time_series_transformer/modeling_time_series_transformer.py +4 -14
- optimum/rbln/transformers/models/time_series_transformer/time_series_transformers_architecture.py +7 -1
- optimum/rbln/transformers/models/wav2vec2/modeling_wav2vec2.py +1 -0
- optimum/rbln/transformers/models/whisper/configuration_whisper.py +12 -13
- optimum/rbln/transformers/models/whisper/generation_whisper.py +28 -6
- optimum/rbln/transformers/models/whisper/modeling_whisper.py +28 -3
- optimum/rbln/transformers/models/xlm_roberta/__init__.py +2 -8
- optimum/rbln/transformers/utils/rbln_quantization.py +391 -75
- optimum/rbln/transformers/utils/rbln_runtime_wrapper.py +79 -0
- optimum/rbln/utils/depreacate_utils.py +16 -0
- optimum/rbln/utils/runtime_utils.py +28 -18
- optimum/rbln/utils/submodule.py +31 -9
- {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.9.3rc0.dist-info}/METADATA +8 -7
- {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.9.3rc0.dist-info}/RECORD +167 -125
- optimum_rbln-0.9.3rc0.dist-info/entry_points.txt +2 -0
- {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.9.3rc0.dist-info}/WHEEL +0 -0
- {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.9.3rc0.dist-info}/licenses/LICENSE +0 -0
|
@@ -3,11 +3,9 @@ from typing import Tuple
|
|
|
3
3
|
|
|
4
4
|
import torch
|
|
5
5
|
import torch.nn as nn
|
|
6
|
+
from transformers import PreTrainedModel
|
|
6
7
|
|
|
7
|
-
from ..decoderonly.decoderonly_architecture import
|
|
8
|
-
DecoderOnlyWrapper,
|
|
9
|
-
apply_rotary_pos_emb,
|
|
10
|
-
)
|
|
8
|
+
from ..decoderonly.decoderonly_architecture import DecoderOnlyWrapper, apply_rotary_pos_emb
|
|
11
9
|
|
|
12
10
|
|
|
13
11
|
class Qwen2_5_VisionTransformerWrapper(nn.Module):
|
|
@@ -159,15 +157,16 @@ class Qwen2_5_VLVisionWindowAttention(nn.Module):
|
|
|
159
157
|
class Qwen2_5_VL_LanguageModelWrapper(DecoderOnlyWrapper):
|
|
160
158
|
def prepare_forward_args(self, *args):
|
|
161
159
|
args = list(args)
|
|
162
|
-
input_ids = None if self.use_inputs_embeds else args.pop(0)
|
|
163
|
-
inputs_embeds = args.pop(0) if self.use_inputs_embeds else None
|
|
160
|
+
input_ids = None if self.rbln_config.use_inputs_embeds else args.pop(0)
|
|
161
|
+
inputs_embeds = args.pop(0) if self.rbln_config.use_inputs_embeds else None
|
|
164
162
|
cache_position = args.pop(0)
|
|
165
163
|
global_block_tables = args.pop(0)
|
|
166
164
|
local_block_tables = None
|
|
167
165
|
position_embeds = args.pop(0)
|
|
168
166
|
query_position = args.pop(0) if self.phase == "prefill" else None
|
|
169
167
|
position_ids = None
|
|
170
|
-
|
|
168
|
+
lora_int_id = None
|
|
169
|
+
attention_mask = args.pop(0) if self.rbln_config.use_attention_mask else None
|
|
171
170
|
past_key_values = args
|
|
172
171
|
|
|
173
172
|
if len(past_key_values) != 2 * self.num_hidden_layers:
|
|
@@ -194,6 +193,28 @@ class Qwen2_5_VL_LanguageModelWrapper(DecoderOnlyWrapper):
|
|
|
194
193
|
query_position,
|
|
195
194
|
attention_mask,
|
|
196
195
|
position_ids,
|
|
196
|
+
lora_int_id,
|
|
197
197
|
past_key_values,
|
|
198
198
|
position_embeds,
|
|
199
199
|
)
|
|
200
|
+
|
|
201
|
+
def convert_to_rbln_class(self, model: PreTrainedModel, max_seq_len: int):
|
|
202
|
+
new_layers = []
|
|
203
|
+
|
|
204
|
+
for layer_idx, layer in enumerate(model.model.language_model.layers):
|
|
205
|
+
is_sliding = layer_idx in self.rbln_config.sliding_window_layers
|
|
206
|
+
new_self_attn = self.get_rbln_attn_class()(
|
|
207
|
+
self.get_attn_layer(layer), self.rbln_config, is_sliding=is_sliding
|
|
208
|
+
)
|
|
209
|
+
new_layer = self.get_rbln_layer_class()(layer, new_self_attn)
|
|
210
|
+
new_layers.append(new_layer)
|
|
211
|
+
|
|
212
|
+
new_model = self.get_rbln_model_class()(
|
|
213
|
+
model.model.language_model,
|
|
214
|
+
new_layers,
|
|
215
|
+
self.rbln_config,
|
|
216
|
+
use_learned_pos_emb=self.__class__._use_learned_pos_emb,
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
new_model = self.get_rbln_causal_lm_class()(model.model, new_model)
|
|
220
|
+
return new_model
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Copyright 2025 Rebellions Inc. All rights reserved.
|
|
2
|
+
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at:
|
|
6
|
+
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
from .configuration_qwen2_vl import (
|
|
16
|
+
RBLNQwen2VisionTransformerPretrainedModelConfig,
|
|
17
|
+
RBLNQwen2VLForConditionalGenerationConfig,
|
|
18
|
+
)
|
|
19
|
+
from .modeling_qwen2_vl import RBLNQwen2VisionTransformerPretrainedModel, RBLNQwen2VLForConditionalGeneration
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Copyright 2025 Rebellions Inc. All rights reserved.
|
|
2
|
+
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at:
|
|
6
|
+
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
from typing import Any, Dict, List, Optional, Union
|
|
16
|
+
|
|
17
|
+
from ....configuration_utils import RBLNModelConfig
|
|
18
|
+
from ..decoderonly.configuration_decoderonly import RBLNDecoderOnlyModelForCausalLMConfig
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class RBLNQwen2VLForConditionalGenerationConfig(RBLNDecoderOnlyModelForCausalLMConfig):
|
|
22
|
+
submodules = ["visual"]
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
use_inputs_embeds: bool = True,
|
|
27
|
+
visual: Optional[RBLNModelConfig] = None,
|
|
28
|
+
**kwargs: Dict[str, Any],
|
|
29
|
+
):
|
|
30
|
+
"""
|
|
31
|
+
Args:
|
|
32
|
+
use_inputs_embeds (bool): Whether or not to use `inputs_embeds` as input. Defaults to `True`.
|
|
33
|
+
visual (Optional[RBLNModelConfig]): Configuration for the vision encoder component.
|
|
34
|
+
kwargs: Additional arguments passed to the parent `RBLNDecoderOnlyModelForCausalLMConfig`.
|
|
35
|
+
|
|
36
|
+
Raises:
|
|
37
|
+
ValueError: If `use_inputs_embeds` is False.
|
|
38
|
+
ValueError: If the visual configuration is provided but contains invalid settings, such as an invalid max_seq_lens (e.g., not a positive integer or insufficient for the expected resolution).
|
|
39
|
+
ValueError: If visual is None and no default vision configuration can be inferred for the model architecture.
|
|
40
|
+
ValueError: If any inherited parameters violate constraints defined in the parent class, such as batch_size not being a positive integer, prefill_chunk_size not being divisible by 64, or max_seq_len not meeting requirements for Flash Attention.
|
|
41
|
+
"""
|
|
42
|
+
super().__init__(use_inputs_embeds=use_inputs_embeds, **kwargs)
|
|
43
|
+
if not self.use_inputs_embeds:
|
|
44
|
+
raise ValueError(
|
|
45
|
+
"RBLNQwen2VLForConditionalGenerationConfig does not allow `use_inputs_embeds` to be set to False, "
|
|
46
|
+
"as RBLNQwen2VLForConditionalGeneration accepts only `inputs_embeds` as input."
|
|
47
|
+
)
|
|
48
|
+
self.visual = visual
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class RBLNQwen2VisionTransformerPretrainedModelConfig(RBLNModelConfig):
|
|
52
|
+
def __init__(self, max_seq_lens: Union[int, List[int]] = None, **kwargs: Dict[str, Any]):
|
|
53
|
+
"""
|
|
54
|
+
Args:
|
|
55
|
+
max_seq_lens (Optional[Union[int, List[int]]]): Maximum sequence lengths for Vision
|
|
56
|
+
Transformer attention. Can be an integer or list of integers, each indicating
|
|
57
|
+
the number of patches in a sequence for an image or video. For example, an image
|
|
58
|
+
of 224x224 pixels with patch size 14 results in (224/14) * (224/14) = 256 patches,
|
|
59
|
+
so `max_seq_lens` must be at least 256. RBLN optimization runs inference per image
|
|
60
|
+
or video frame, so set `max_seq_lens` to match the maximum expected resolution to
|
|
61
|
+
optimize computation. If not provided, a `ValueError` is raised.
|
|
62
|
+
kwargs: Additional arguments passed to the parent RBLNModelConfig.
|
|
63
|
+
|
|
64
|
+
Raises:
|
|
65
|
+
ValueError: If batch_size is not a positive integer.
|
|
66
|
+
ValueError: If `max_seq_lens` (or any value in the list) is not a positive integer.
|
|
67
|
+
ValueError: If `max_seq_lens` is insufficient for the expected image/video resolution.
|
|
68
|
+
ValueError: If `batch_size` (inherited from RBLNModelConfig) is not a positive integer.
|
|
69
|
+
|
|
70
|
+
Max Seq Lens:
|
|
71
|
+
Since `Qwen2VLForConditionalGeneration` performs inference on a per-image or per-frame basis,
|
|
72
|
+
`max_seq_lens` should be set based on the maximum expected resolution of the input images or video frames.
|
|
73
|
+
|
|
74
|
+
The value must be greater than or equal to the number of patches generated from the input image.
|
|
75
|
+
For example, a 224x224 image with a patch size of 14 results in (224 / 14) * (224 / 14) = 256 patches.
|
|
76
|
+
Therefore, `max_seq_lens` must be at least 256.
|
|
77
|
+
"""
|
|
78
|
+
super().__init__(**kwargs)
|
|
79
|
+
|
|
80
|
+
if max_seq_lens is not None:
|
|
81
|
+
if isinstance(max_seq_lens, int):
|
|
82
|
+
max_seq_lens = [max_seq_lens]
|
|
83
|
+
elif isinstance(max_seq_lens, list):
|
|
84
|
+
max_seq_lens.sort(reverse=True)
|
|
85
|
+
else:
|
|
86
|
+
raise ValueError("'max_seq_lens' must be specified.")
|
|
87
|
+
|
|
88
|
+
self.max_seq_lens = max_seq_lens
|
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
# Copyright 2025 Rebellions Inc. All rights reserved.
|
|
2
|
+
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at:
|
|
6
|
+
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
import inspect
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import TYPE_CHECKING, Any, Callable, Optional, Union
|
|
18
|
+
|
|
19
|
+
import torch
|
|
20
|
+
from transformers import (
|
|
21
|
+
AutoModelForVision2Seq,
|
|
22
|
+
PretrainedConfig,
|
|
23
|
+
PreTrainedModel,
|
|
24
|
+
Qwen2VLForConditionalGeneration,
|
|
25
|
+
)
|
|
26
|
+
from transformers.modeling_utils import no_init_weights
|
|
27
|
+
from transformers.models.qwen2_vl.modeling_qwen2_vl import (
|
|
28
|
+
PatchEmbed,
|
|
29
|
+
Qwen2VisionTransformerPretrainedModel,
|
|
30
|
+
Qwen2VLModel,
|
|
31
|
+
Qwen2VLRotaryEmbedding,
|
|
32
|
+
VisionRotaryEmbedding,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
from ....configuration_utils import RBLNCompileConfig
|
|
36
|
+
from ....modeling import RBLNModel
|
|
37
|
+
from ....utils.logging import get_logger
|
|
38
|
+
from ..decoderonly.modeling_decoderonly import RBLNDecoderOnlyModelForCausalLM, RBLNDecoderOnlyOutput
|
|
39
|
+
from .configuration_qwen2_vl import (
|
|
40
|
+
RBLNQwen2VisionTransformerPretrainedModelConfig,
|
|
41
|
+
RBLNQwen2VLForConditionalGenerationConfig,
|
|
42
|
+
)
|
|
43
|
+
from .qwen2_vl_architecture import Qwen2VisionTransformerWrapper, Qwen2VL_LanguageModelWrapper
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
logger = get_logger(__name__)
|
|
47
|
+
|
|
48
|
+
if TYPE_CHECKING:
|
|
49
|
+
from transformers import (
|
|
50
|
+
AutoFeatureExtractor,
|
|
51
|
+
AutoProcessor,
|
|
52
|
+
AutoTokenizer,
|
|
53
|
+
PretrainedConfig,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class RBLNQwen2VisionTransformerPretrainedModel(RBLNModel):
|
|
58
|
+
auto_model_class = None
|
|
59
|
+
|
|
60
|
+
def __post_init__(self, **kwargs):
|
|
61
|
+
self.transformer = self.model[0]
|
|
62
|
+
self.max_seq_lens = torch.tensor(sorted(self.rbln_config.max_seq_lens, reverse=False))
|
|
63
|
+
config = self.config
|
|
64
|
+
|
|
65
|
+
self.patch_size = config.spatial_patch_size
|
|
66
|
+
self.spatial_merge_size = config.spatial_merge_size
|
|
67
|
+
self.spatial_merge_unit = config.spatial_merge_size * config.spatial_merge_size
|
|
68
|
+
self.rotary_pos_emb = VisionRotaryEmbedding((config.embed_dim // config.num_heads) // 2)
|
|
69
|
+
with no_init_weights():
|
|
70
|
+
self.patch_embed = PatchEmbed(
|
|
71
|
+
patch_size=config.patch_size,
|
|
72
|
+
temporal_patch_size=config.temporal_patch_size,
|
|
73
|
+
in_channels=config.in_channels,
|
|
74
|
+
embed_dim=config.embed_dim,
|
|
75
|
+
).eval()
|
|
76
|
+
artifacts = torch.load(self.model_save_dir / self.subfolder / "torch_artifacts.pth", weights_only=False)
|
|
77
|
+
self.patch_embed.load_state_dict(artifacts["patch_embed"])
|
|
78
|
+
|
|
79
|
+
@classmethod
|
|
80
|
+
def save_torch_artifacts(
|
|
81
|
+
cls,
|
|
82
|
+
model: "Qwen2VLForConditionalGeneration",
|
|
83
|
+
save_dir_path: Path,
|
|
84
|
+
subfolder: str,
|
|
85
|
+
rbln_config: RBLNQwen2VisionTransformerPretrainedModelConfig,
|
|
86
|
+
):
|
|
87
|
+
save_dict = {}
|
|
88
|
+
save_dict["patch_embed"] = model.patch_embed.state_dict()
|
|
89
|
+
torch.save(save_dict, save_dir_path / subfolder / "torch_artifacts.pth")
|
|
90
|
+
|
|
91
|
+
@classmethod
|
|
92
|
+
def wrap_model_if_needed(
|
|
93
|
+
cls, model: "PreTrainedModel", rbln_config: RBLNQwen2VisionTransformerPretrainedModelConfig
|
|
94
|
+
):
|
|
95
|
+
return Qwen2VisionTransformerWrapper(model).eval()
|
|
96
|
+
|
|
97
|
+
def __getattr__(self, __name: str) -> Any:
|
|
98
|
+
def redirect(func):
|
|
99
|
+
return lambda *pargs, **kwargs: func(self, *pargs, **kwargs)
|
|
100
|
+
|
|
101
|
+
val = getattr(Qwen2VisionTransformerPretrainedModel, __name)
|
|
102
|
+
|
|
103
|
+
if isinstance(val, Callable) and "self" in set(inspect.signature(val).parameters):
|
|
104
|
+
return redirect(val)
|
|
105
|
+
return val
|
|
106
|
+
|
|
107
|
+
@classmethod
|
|
108
|
+
def _update_rbln_config(
|
|
109
|
+
cls,
|
|
110
|
+
preprocessors: Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"],
|
|
111
|
+
model: Optional["PreTrainedModel"] = None,
|
|
112
|
+
model_config: "PretrainedConfig" = None,
|
|
113
|
+
rbln_config: Optional[RBLNQwen2VisionTransformerPretrainedModelConfig] = None,
|
|
114
|
+
) -> RBLNQwen2VisionTransformerPretrainedModelConfig:
|
|
115
|
+
hidden_size = getattr(model_config, "embed_dim")
|
|
116
|
+
num_heads = getattr(model_config, "num_heads")
|
|
117
|
+
head_dim = hidden_size // num_heads
|
|
118
|
+
|
|
119
|
+
input_infos = []
|
|
120
|
+
for max_seq_len in rbln_config.max_seq_lens:
|
|
121
|
+
input_info = [
|
|
122
|
+
("hidden_states", [max_seq_len, hidden_size], "float32"),
|
|
123
|
+
("full_attn_masks", [1, 1, max_seq_len, max_seq_len], "float32"),
|
|
124
|
+
(
|
|
125
|
+
"cos",
|
|
126
|
+
[1, 1, max_seq_len, head_dim],
|
|
127
|
+
"float32",
|
|
128
|
+
),
|
|
129
|
+
(
|
|
130
|
+
"sin",
|
|
131
|
+
[1, 1, max_seq_len, head_dim],
|
|
132
|
+
"float32",
|
|
133
|
+
),
|
|
134
|
+
]
|
|
135
|
+
input_infos.append(input_info)
|
|
136
|
+
|
|
137
|
+
rbln_compile_config = RBLNCompileConfig(input_info=input_infos)
|
|
138
|
+
rbln_config.set_compile_cfgs([rbln_compile_config])
|
|
139
|
+
|
|
140
|
+
return rbln_config
|
|
141
|
+
|
|
142
|
+
@staticmethod
|
|
143
|
+
def _pad_for_full_attn_layers(hidden_state, cos, sin, max_seq_len):
|
|
144
|
+
if hidden_state.shape[0] < max_seq_len:
|
|
145
|
+
full_padding_size = max_seq_len - hidden_state.shape[0]
|
|
146
|
+
full_padding_hidden = torch.zeros(
|
|
147
|
+
full_padding_size,
|
|
148
|
+
hidden_state.shape[-1],
|
|
149
|
+
dtype=hidden_state.dtype,
|
|
150
|
+
)
|
|
151
|
+
hidden_state_full_padded = torch.cat([hidden_state, full_padding_hidden], dim=0)
|
|
152
|
+
full_padding_pos = torch.zeros(
|
|
153
|
+
full_padding_size,
|
|
154
|
+
cos.shape[-1],
|
|
155
|
+
dtype=cos.dtype,
|
|
156
|
+
)
|
|
157
|
+
cos_full_padded = torch.cat([cos, full_padding_pos], dim=0)
|
|
158
|
+
sin_full_padded = torch.cat([sin, full_padding_pos], dim=0)
|
|
159
|
+
else:
|
|
160
|
+
hidden_state_full_padded = hidden_state
|
|
161
|
+
cos_full_padded = cos
|
|
162
|
+
sin_full_padded = sin
|
|
163
|
+
|
|
164
|
+
full_attn_masks = torch.ones(
|
|
165
|
+
1,
|
|
166
|
+
1,
|
|
167
|
+
max_seq_len,
|
|
168
|
+
max_seq_len,
|
|
169
|
+
dtype=torch.float32,
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
full_attn_masks[:, :, hidden_state.shape[0] : max_seq_len, :] = 0
|
|
173
|
+
full_attn_masks[:, :, :, hidden_state.shape[0] : max_seq_len] = 0
|
|
174
|
+
return hidden_state_full_padded, cos_full_padded, sin_full_padded, full_attn_masks
|
|
175
|
+
|
|
176
|
+
def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor) -> torch.Tensor:
|
|
177
|
+
# Processes a batch of images (or frames) through the vision transformer.
|
|
178
|
+
# Each image is handled independently for padding and attention mask generation.
|
|
179
|
+
|
|
180
|
+
hidden_states = self.patch_embed(hidden_states)
|
|
181
|
+
rotary_pos_emb = self.rot_pos_emb(grid_thw)
|
|
182
|
+
emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
|
|
183
|
+
position_embeddings = (emb.cos(), emb.sin())
|
|
184
|
+
|
|
185
|
+
cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum(
|
|
186
|
+
dim=0,
|
|
187
|
+
dtype=torch.int32,
|
|
188
|
+
)
|
|
189
|
+
cu_seqlens = torch.nn.functional.pad(cu_seqlens, (1, 0), value=0)
|
|
190
|
+
|
|
191
|
+
num_images = len(cu_seqlens) - 1
|
|
192
|
+
output_hidden_states = []
|
|
193
|
+
|
|
194
|
+
# Process each image in the sequence
|
|
195
|
+
for i in range(num_images):
|
|
196
|
+
image_s, image_e = cu_seqlens[i], cu_seqlens[i + 1]
|
|
197
|
+
|
|
198
|
+
# Select the nearest higher max_seq_len from the available compiled models.
|
|
199
|
+
cu_seq_len = image_e - image_s
|
|
200
|
+
try:
|
|
201
|
+
cu_index = torch.searchsorted(self.max_seq_lens, cu_seq_len).item()
|
|
202
|
+
max_seq_len = self.max_seq_lens[cu_index]
|
|
203
|
+
except Exception:
|
|
204
|
+
raise ValueError(
|
|
205
|
+
f"Required seq_len({cu_seq_len}) is larger than available max_seq_lens({self.max_seq_lens.tolist()})."
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
# Padding for Full Attention Layers
|
|
209
|
+
hidden_state_full_padded, cos_full_padded, sin_full_padded, full_attn_masks = (
|
|
210
|
+
self._pad_for_full_attn_layers(
|
|
211
|
+
hidden_states[image_s:image_e],
|
|
212
|
+
position_embeddings[0][image_s:image_e],
|
|
213
|
+
position_embeddings[1][image_s:image_e],
|
|
214
|
+
max_seq_len,
|
|
215
|
+
)
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
# RBLN run with the compiled model
|
|
219
|
+
output = self.transformer(
|
|
220
|
+
hidden_state_full_padded,
|
|
221
|
+
full_attn_masks,
|
|
222
|
+
cos_full_padded[None, None, :, :],
|
|
223
|
+
sin_full_padded[None, None, :, :],
|
|
224
|
+
)
|
|
225
|
+
# Depadding
|
|
226
|
+
depadded_output = output[: cu_seq_len // self.spatial_merge_unit]
|
|
227
|
+
output_hidden_states.append(depadded_output)
|
|
228
|
+
|
|
229
|
+
hidden_states = torch.cat(output_hidden_states)
|
|
230
|
+
return hidden_states
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
class RBLNQwen2VLForConditionalGeneration(RBLNDecoderOnlyModelForCausalLM):
|
|
234
|
+
"""
|
|
235
|
+
RBLNQwen2VLForConditionalGeneration is a multi-modal model that integrates vision and language processing capabilities,
|
|
236
|
+
optimized for RBLN NPUs. It is designed for conditional generation tasks that involve both image and text inputs.
|
|
237
|
+
|
|
238
|
+
This model inherits from [`RBLNDecoderOnlyModelForCausalLM`]. Check the superclass documentation for the generic methods the library implements for all its models.
|
|
239
|
+
|
|
240
|
+
Important Note:
|
|
241
|
+
This model includes a Large Language Model (LLM). For optimal performance, it is highly recommended to use
|
|
242
|
+
tensor parallelism for the language model. This can be achieved by using the `rbln_config` parameter in the
|
|
243
|
+
`from_pretrained` method. Refer to the `from_pretrained` documentation and the RBLNQwen2VLForConditionalGenerationConfig class for details.
|
|
244
|
+
|
|
245
|
+
Examples:
|
|
246
|
+
```python
|
|
247
|
+
from optimum.rbln import RBLNQwen2VLForConditionalGeneration
|
|
248
|
+
|
|
249
|
+
model = RBLNQwen2VLForConditionalGeneration.from_pretrained(
|
|
250
|
+
"Qwen/Qwen2-VL-7B-Instruct",
|
|
251
|
+
export=True,
|
|
252
|
+
rbln_config={
|
|
253
|
+
"visual": {
|
|
254
|
+
"max_seq_lens": 6400,
|
|
255
|
+
"device": 0,
|
|
256
|
+
},
|
|
257
|
+
"tensor_parallel_size": 8,
|
|
258
|
+
"max_seq_len": 32_768,
|
|
259
|
+
"device": [0, 1, 2, 3, 4, 5, 6, 7],
|
|
260
|
+
},
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
model.save_pretrained("compiled-qwen2-vl-7b-instruct")
|
|
264
|
+
```
|
|
265
|
+
"""
|
|
266
|
+
|
|
267
|
+
auto_model_class = AutoModelForVision2Seq
|
|
268
|
+
_rbln_submodules = [
|
|
269
|
+
{"name": "visual"},
|
|
270
|
+
]
|
|
271
|
+
_decoder_wrapper_cls = Qwen2VL_LanguageModelWrapper
|
|
272
|
+
_use_rotary_emb = False
|
|
273
|
+
|
|
274
|
+
def __post_init__(self, **kwargs):
|
|
275
|
+
super().__post_init__(**kwargs)
|
|
276
|
+
self.visual = self.rbln_submodules[0]
|
|
277
|
+
self.mrope_section = self.config.rope_scaling["mrope_section"]
|
|
278
|
+
self.rotary_emb = Qwen2VLRotaryEmbedding(self.config)
|
|
279
|
+
self.rope_deltas = torch.zeros(self.rbln_config.batch_size)
|
|
280
|
+
|
|
281
|
+
def can_generate(self):
|
|
282
|
+
return True
|
|
283
|
+
|
|
284
|
+
@classmethod
|
|
285
|
+
def get_pytorch_model(cls, *args, **kwargs):
|
|
286
|
+
model = super().get_pytorch_model(*args, **kwargs)
|
|
287
|
+
model.model.lm_head = model.lm_head
|
|
288
|
+
model.lm_head = None
|
|
289
|
+
del model.lm_head
|
|
290
|
+
return model
|
|
291
|
+
|
|
292
|
+
@classmethod
|
|
293
|
+
def get_input_info(
|
|
294
|
+
cls,
|
|
295
|
+
batch_size: int,
|
|
296
|
+
query_length: int,
|
|
297
|
+
rbln_config: RBLNQwen2VLForConditionalGenerationConfig,
|
|
298
|
+
model_config: PretrainedConfig,
|
|
299
|
+
):
|
|
300
|
+
input_info = super().get_input_info(batch_size, query_length, rbln_config, model_config)
|
|
301
|
+
pos_idx = 3
|
|
302
|
+
input_info.insert(
|
|
303
|
+
pos_idx,
|
|
304
|
+
(
|
|
305
|
+
"position_emb",
|
|
306
|
+
[2, batch_size, 1, query_length, model_config.hidden_size // model_config.num_attention_heads],
|
|
307
|
+
"float32",
|
|
308
|
+
),
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
return input_info
|
|
312
|
+
|
|
313
|
+
def prepare_inputs_for_generation(
|
|
314
|
+
self,
|
|
315
|
+
input_ids: torch.LongTensor,
|
|
316
|
+
generate_idx: Optional[torch.Tensor] = None,
|
|
317
|
+
attention_mask: Optional[torch.LongTensor] = None,
|
|
318
|
+
inputs_embeds: Optional[torch.Tensor] = None,
|
|
319
|
+
pixel_values=None,
|
|
320
|
+
pixel_values_videos=None,
|
|
321
|
+
image_grid_thw=None,
|
|
322
|
+
video_grid_thw=None,
|
|
323
|
+
**kwargs,
|
|
324
|
+
):
|
|
325
|
+
model_inputs = super().prepare_inputs_for_generation(
|
|
326
|
+
input_ids,
|
|
327
|
+
generate_idx,
|
|
328
|
+
attention_mask,
|
|
329
|
+
inputs_embeds,
|
|
330
|
+
**kwargs,
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
is_prefill_phase = generate_idx is None
|
|
334
|
+
if is_prefill_phase:
|
|
335
|
+
model_inputs.update({"input_ids": input_ids})
|
|
336
|
+
|
|
337
|
+
model_inputs.update(
|
|
338
|
+
{
|
|
339
|
+
"pixel_values": pixel_values,
|
|
340
|
+
"pixel_values_videos": pixel_values_videos,
|
|
341
|
+
"image_grid_thw": image_grid_thw,
|
|
342
|
+
"video_grid_thw": video_grid_thw,
|
|
343
|
+
}
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
return model_inputs
|
|
347
|
+
|
|
348
|
+
def _get_position_embeddings(self, hidden_states, position_ids):
|
|
349
|
+
cos, sin = self.rotary_emb(hidden_states, position_ids)
|
|
350
|
+
mrope_section = self.mrope_section * 2
|
|
351
|
+
cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze(1)
|
|
352
|
+
sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze(1)
|
|
353
|
+
return torch.stack([cos, sin])
|
|
354
|
+
|
|
355
|
+
def _preprocess_prefill(
|
|
356
|
+
self,
|
|
357
|
+
input_ids: torch.LongTensor = None,
|
|
358
|
+
attention_mask: torch.Tensor = None,
|
|
359
|
+
pixel_values: torch.Tensor = None,
|
|
360
|
+
pixel_values_videos: torch.FloatTensor = None,
|
|
361
|
+
image_grid_thw: torch.LongTensor = None,
|
|
362
|
+
video_grid_thw: torch.LongTensor = None,
|
|
363
|
+
):
|
|
364
|
+
batch_size = input_ids.shape[0]
|
|
365
|
+
inputs_embeds = self.embed_tokens(input_ids)
|
|
366
|
+
|
|
367
|
+
if pixel_values is not None:
|
|
368
|
+
image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw)
|
|
369
|
+
n_image_tokens = (input_ids == self.config.image_token_id).sum().item()
|
|
370
|
+
n_image_features = image_embeds.shape[0]
|
|
371
|
+
if n_image_tokens != n_image_features:
|
|
372
|
+
raise ValueError(
|
|
373
|
+
f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
mask = input_ids == self.config.image_token_id
|
|
377
|
+
mask_unsqueezed = mask.unsqueeze(-1)
|
|
378
|
+
mask_expanded = mask_unsqueezed.expand_as(inputs_embeds)
|
|
379
|
+
|
|
380
|
+
image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
|
|
381
|
+
inputs_embeds = inputs_embeds.masked_scatter(mask_expanded, image_embeds)
|
|
382
|
+
|
|
383
|
+
if pixel_values_videos is not None:
|
|
384
|
+
video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw)
|
|
385
|
+
n_video_tokens = (input_ids == self.config.video_token_id).sum().item()
|
|
386
|
+
n_video_features = video_embeds.shape[0]
|
|
387
|
+
if n_video_tokens != n_video_features:
|
|
388
|
+
raise ValueError(
|
|
389
|
+
f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}"
|
|
390
|
+
)
|
|
391
|
+
|
|
392
|
+
mask = input_ids == self.config.video_token_id
|
|
393
|
+
mask_unsqueezed = mask.unsqueeze(-1)
|
|
394
|
+
mask_expanded = mask_unsqueezed.expand_as(inputs_embeds)
|
|
395
|
+
inputs_embeds = inputs_embeds.masked_scatter(mask_expanded, video_embeds)
|
|
396
|
+
|
|
397
|
+
max_inputs_len = input_ids.shape[1]
|
|
398
|
+
|
|
399
|
+
head_dim = getattr(self.config, "head_dim", None) or self.config.hidden_size // self.config.num_attention_heads
|
|
400
|
+
all_position_embeds = torch.zeros(2, batch_size, 1, max_inputs_len, head_dim)
|
|
401
|
+
all_rope_deltas = []
|
|
402
|
+
|
|
403
|
+
image_token_id = self.config.image_token_id
|
|
404
|
+
video_token_id = self.config.video_token_id
|
|
405
|
+
vision_start_token_id = self.config.vision_start_token_id
|
|
406
|
+
image_idx, video_idx = 0, 0
|
|
407
|
+
|
|
408
|
+
for b_idx in range(batch_size):
|
|
409
|
+
input_id = input_ids[b_idx : b_idx + 1][:, attention_mask[b_idx].bool()]
|
|
410
|
+
vision_start_indices = torch.argwhere(input_id == vision_start_token_id).squeeze(1)
|
|
411
|
+
vision_tokens = input_id[0][vision_start_indices + 1]
|
|
412
|
+
image_nums = (vision_tokens == image_token_id).sum()
|
|
413
|
+
video_nums = (vision_tokens == video_token_id).sum()
|
|
414
|
+
position_ids, rope_deltas = Qwen2VLModel.get_rope_index(
|
|
415
|
+
self,
|
|
416
|
+
input_id,
|
|
417
|
+
image_grid_thw[image_idx : image_idx + image_nums] if image_grid_thw is not None else None,
|
|
418
|
+
video_grid_thw[video_idx : video_idx + video_nums] if video_grid_thw is not None else None,
|
|
419
|
+
)
|
|
420
|
+
image_idx += image_nums
|
|
421
|
+
video_idx += video_nums
|
|
422
|
+
|
|
423
|
+
position_embed = self._get_position_embeddings(inputs_embeds, position_ids)
|
|
424
|
+
mask_indices = torch.nonzero(attention_mask[b_idx], as_tuple=True)[0]
|
|
425
|
+
all_position_embeds[:, b_idx : b_idx + 1].index_copy_(dim=-2, index=mask_indices, source=position_embed)
|
|
426
|
+
all_rope_deltas.append(rope_deltas)
|
|
427
|
+
|
|
428
|
+
rope_deltas = torch.stack(all_rope_deltas)
|
|
429
|
+
|
|
430
|
+
return inputs_embeds, all_position_embeds, rope_deltas
|
|
431
|
+
|
|
432
|
+
def _preprocess_decoder(
|
|
433
|
+
self,
|
|
434
|
+
input_ids: torch.LongTensor = None,
|
|
435
|
+
cache_position: torch.LongTensor = None,
|
|
436
|
+
):
|
|
437
|
+
if self.rbln_config.batch_size != cache_position.shape[0]:
|
|
438
|
+
raise RuntimeError(
|
|
439
|
+
f"Cache position size mismatch: got {cache_position.shape[0]}, expected {self.rbln_config.batch_size}."
|
|
440
|
+
)
|
|
441
|
+
|
|
442
|
+
inputs_embeds = self.embed_tokens(input_ids)
|
|
443
|
+
position_embeds = []
|
|
444
|
+
for b_idx in range(self.rbln_config.batch_size):
|
|
445
|
+
delta = cache_position[b_idx] + self.rope_deltas[b_idx]
|
|
446
|
+
position_ids = torch.arange(1).view(1, -1)
|
|
447
|
+
position_ids = position_ids.add(delta)
|
|
448
|
+
position_ids = position_ids.unsqueeze(0).expand(3, -1, -1)
|
|
449
|
+
position_embed = self._get_position_embeddings(torch.zeros(1, dtype=torch.float32), position_ids)
|
|
450
|
+
position_embeds.append(position_embed)
|
|
451
|
+
|
|
452
|
+
position_embeds = torch.cat(position_embeds, dim=1)
|
|
453
|
+
|
|
454
|
+
return inputs_embeds, position_embeds
|
|
455
|
+
|
|
456
|
+
def forward(
|
|
457
|
+
self,
|
|
458
|
+
input_ids: Optional[torch.LongTensor] = None,
|
|
459
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
460
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
461
|
+
pixel_values: Optional[torch.Tensor] = None,
|
|
462
|
+
pixel_values_videos: Optional[torch.FloatTensor] = None,
|
|
463
|
+
image_grid_thw: Optional[torch.LongTensor] = None,
|
|
464
|
+
video_grid_thw: Optional[torch.LongTensor] = None,
|
|
465
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
466
|
+
generate_idx: Optional[torch.Tensor] = None,
|
|
467
|
+
return_dict: Optional[bool] = None,
|
|
468
|
+
**kwargs,
|
|
469
|
+
) -> RBLNDecoderOnlyOutput:
|
|
470
|
+
# Prefill
|
|
471
|
+
if cache_position is None:
|
|
472
|
+
inputs_embeds, position_embed, rope_deltas = self._preprocess_prefill(
|
|
473
|
+
input_ids,
|
|
474
|
+
attention_mask,
|
|
475
|
+
pixel_values,
|
|
476
|
+
pixel_values_videos,
|
|
477
|
+
image_grid_thw,
|
|
478
|
+
video_grid_thw,
|
|
479
|
+
)
|
|
480
|
+
|
|
481
|
+
self.rope_deltas = rope_deltas
|
|
482
|
+
batch_size = inputs_embeds.shape[0]
|
|
483
|
+
|
|
484
|
+
logits = []
|
|
485
|
+
for b_idx in range(batch_size):
|
|
486
|
+
cache_position = torch.arange(0, generate_idx[b_idx].item(), dtype=torch.int32).unsqueeze(0)
|
|
487
|
+
|
|
488
|
+
output = self.prefill_decoder(
|
|
489
|
+
inputs_embeds=inputs_embeds[b_idx : b_idx + 1],
|
|
490
|
+
attention_mask=attention_mask[b_idx] if attention_mask is not None else None,
|
|
491
|
+
cache_position=cache_position,
|
|
492
|
+
batch_idx=b_idx,
|
|
493
|
+
position_embed=position_embed[:, b_idx : b_idx + 1],
|
|
494
|
+
)
|
|
495
|
+
logits.append(output.logits)
|
|
496
|
+
logits = torch.cat(logits, dim=0)
|
|
497
|
+
|
|
498
|
+
# Decoder
|
|
499
|
+
else:
|
|
500
|
+
inputs_embeds, position_embed = self._preprocess_decoder(input_ids, cache_position)
|
|
501
|
+
output = self.decoder(
|
|
502
|
+
inputs_embeds=inputs_embeds,
|
|
503
|
+
cache_position=cache_position,
|
|
504
|
+
position_embed=position_embed,
|
|
505
|
+
)
|
|
506
|
+
logits = output.logits
|
|
507
|
+
|
|
508
|
+
if not return_dict:
|
|
509
|
+
return logits, generate_idx
|
|
510
|
+
else:
|
|
511
|
+
return RBLNDecoderOnlyOutput(
|
|
512
|
+
logits=logits,
|
|
513
|
+
generate_idx=generate_idx,
|
|
514
|
+
)
|