optimum-rbln 0.8.4a1__py3-none-any.whl → 0.8.4a2__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.

Potentially problematic release.


This version of optimum-rbln might be problematic. Click here for more details.

optimum/rbln/__init__.py CHANGED
@@ -148,6 +148,10 @@ _import_structure = {
148
148
  "RBLNQwen3ForCausalLMConfig",
149
149
  "RBLNQwen3Model",
150
150
  "RBLNQwen3ModelConfig",
151
+ "RBLNQwen2VisionTransformerPretrainedModel",
152
+ "RBLNQwen2VisionTransformerPretrainedModelConfig",
153
+ "RBLNQwen2VLForConditionalGeneration",
154
+ "RBLNQwen2VLForConditionalGenerationConfig",
151
155
  "RBLNResNetForImageClassification",
152
156
  "RBLNResNetForImageClassificationConfig",
153
157
  "RBLNRobertaForMaskedLM",
@@ -430,6 +434,10 @@ if TYPE_CHECKING:
430
434
  RBLNQwen2ForCausalLMConfig,
431
435
  RBLNQwen2Model,
432
436
  RBLNQwen2ModelConfig,
437
+ RBLNQwen2VisionTransformerPretrainedModel,
438
+ RBLNQwen2VisionTransformerPretrainedModelConfig,
439
+ RBLNQwen2VLForConditionalGeneration,
440
+ RBLNQwen2VLForConditionalGenerationConfig,
433
441
  RBLNQwen3ForCausalLM,
434
442
  RBLNQwen3ForCausalLMConfig,
435
443
  RBLNQwen3Model,
@@ -28,7 +28,7 @@ version_tuple: VERSION_TUPLE
28
28
  commit_id: COMMIT_ID
29
29
  __commit_id__: COMMIT_ID
30
30
 
31
- __version__ = version = '0.8.4a1'
32
- __version_tuple__ = version_tuple = (0, 8, 4, 'a1')
31
+ __version__ = version = '0.8.4a2'
32
+ __version_tuple__ = version_tuple = (0, 8, 4, 'a2')
33
33
 
34
34
  __commit_id__ = commit_id = None
@@ -130,6 +130,10 @@ _import_structure = {
130
130
  "RBLNQwen2_5_VisionTransformerPretrainedModelConfig",
131
131
  "RBLNQwen2_5_VLForConditionalGeneration",
132
132
  "RBLNQwen2_5_VLForConditionalGenerationConfig",
133
+ "RBLNQwen2VisionTransformerPretrainedModel",
134
+ "RBLNQwen2VisionTransformerPretrainedModelConfig",
135
+ "RBLNQwen2VLForConditionalGeneration",
136
+ "RBLNQwen2VLForConditionalGenerationConfig",
133
137
  "RBLNQwen2Model",
134
138
  "RBLNQwen2ModelConfig",
135
139
  "RBLNQwen2ForCausalLM",
@@ -282,6 +286,10 @@ if TYPE_CHECKING:
282
286
  RBLNQwen2ForCausalLMConfig,
283
287
  RBLNQwen2Model,
284
288
  RBLNQwen2ModelConfig,
289
+ RBLNQwen2VisionTransformerPretrainedModel,
290
+ RBLNQwen2VisionTransformerPretrainedModelConfig,
291
+ RBLNQwen2VLForConditionalGeneration,
292
+ RBLNQwen2VLForConditionalGenerationConfig,
285
293
  RBLNQwen3ForCausalLM,
286
294
  RBLNQwen3ForCausalLMConfig,
287
295
  RBLNQwen3Model,
@@ -85,6 +85,12 @@ _import_structure = {
85
85
  "RBLNQwen2_5_VLForConditionalGeneration",
86
86
  "RBLNQwen2_5_VLForConditionalGenerationConfig",
87
87
  ],
88
+ "qwen2_vl": [
89
+ "RBLNQwen2VisionTransformerPretrainedModel",
90
+ "RBLNQwen2VisionTransformerPretrainedModelConfig",
91
+ "RBLNQwen2VLForConditionalGeneration",
92
+ "RBLNQwen2VLForConditionalGenerationConfig",
93
+ ],
88
94
  "decoderonly": [
89
95
  "RBLNDecoderOnlyModelConfig",
90
96
  "RBLNDecoderOnlyModel",
@@ -281,6 +287,12 @@ if TYPE_CHECKING:
281
287
  RBLNQwen2_5_VLForConditionalGeneration,
282
288
  RBLNQwen2_5_VLForConditionalGenerationConfig,
283
289
  )
290
+ from .qwen2_vl import (
291
+ RBLNQwen2VisionTransformerPretrainedModel,
292
+ RBLNQwen2VisionTransformerPretrainedModelConfig,
293
+ RBLNQwen2VLForConditionalGeneration,
294
+ RBLNQwen2VLForConditionalGenerationConfig,
295
+ )
284
296
  from .qwen3 import RBLNQwen3ForCausalLM, RBLNQwen3ForCausalLMConfig, RBLNQwen3Model, RBLNQwen3ModelConfig
285
297
  from .resnet import RBLNResNetForImageClassification, RBLNResNetForImageClassificationConfig
286
298
  from .roberta import (
@@ -579,7 +579,7 @@ class DecoderOnlyAttention(nn.Module):
579
579
  )
580
580
  self.head_dim = self._original_mod.head_dim
581
581
  self._phase = "prefill"
582
- self.scale = torch.tensor(self.get_attn_scale())
582
+ self.scale = torch.nn.Parameter(torch.tensor(self.get_attn_scale()))
583
583
  self.quantization = rbln_config.quantization
584
584
 
585
585
  if hasattr(self._original_mod, "num_key_value_heads"):
@@ -11,6 +11,7 @@
11
11
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
+ import math
14
15
  from functools import wraps
15
16
  from typing import TYPE_CHECKING, List, Optional, Tuple
16
17
 
@@ -20,7 +21,6 @@ from torch import Tensor
20
21
  from transformers.models.grounding_dino.modeling_grounding_dino import (
21
22
  GroundingDinoDecoder,
22
23
  GroundingDinoEncoder,
23
- get_sine_pos_embed,
24
24
  )
25
25
 
26
26
 
@@ -33,31 +33,46 @@ def monkey_patch():
33
33
  GroundingDinoBiMultiHeadAttention,
34
34
  GroundingDinoEncoderLayer,
35
35
  GroundingDinoMultiscaleDeformableAttention,
36
+ MultiScaleDeformableAttention,
36
37
  )
37
38
 
38
39
  original_forward = GroundingDinoMultiscaleDeformableAttention.forward
39
40
  original_bi_multihead_attention_forward = GroundingDinoBiMultiHeadAttention.forward
40
41
  original_encoder_layer_forward = GroundingDinoEncoderLayer.forward
42
+ original_multiscale_deform_attn = MultiScaleDeformableAttention.forward
41
43
 
42
44
  # Patch the methods with the custom implementations
43
45
  GroundingDinoMultiscaleDeformableAttention.forward = _GroundingDinoMultiscaleDeformableAttention.forward
44
46
  GroundingDinoBiMultiHeadAttention.forward = _GroundingDinoBiMultiHeadAttention.forward
45
47
  GroundingDinoEncoderLayer.forward = _GroundingDinoEncoderLayer.forward
48
+ MultiScaleDeformableAttention.forward = _MultiScaleDeformableAttention.forward
46
49
 
47
- return (original_forward, original_bi_multihead_attention_forward, original_encoder_layer_forward)
50
+ return (
51
+ original_forward,
52
+ original_bi_multihead_attention_forward,
53
+ original_encoder_layer_forward,
54
+ original_multiscale_deform_attn,
55
+ )
48
56
 
49
57
 
50
- def restore_monkey_patch(original_forward, original_bi_multihead_attention_forward, original_encoder_layer_forward):
58
+ def restore_monkey_patch(
59
+ original_forward,
60
+ original_bi_multihead_attention_forward,
61
+ original_encoder_layer_forward,
62
+ original_multiscale_deform_attn,
63
+ ):
51
64
  from transformers.models.grounding_dino.modeling_grounding_dino import (
52
65
  GroundingDinoBiMultiHeadAttention,
53
66
  GroundingDinoEncoderLayer,
54
67
  GroundingDinoMultiscaleDeformableAttention,
68
+ MultiScaleDeformableAttention,
55
69
  )
56
70
 
57
71
  # Restore the original methods
58
72
  GroundingDinoMultiscaleDeformableAttention.forward = original_forward
59
73
  GroundingDinoBiMultiHeadAttention.forward = original_bi_multihead_attention_forward
60
74
  GroundingDinoEncoderLayer.forward = original_encoder_layer_forward
75
+ MultiScaleDeformableAttention.forward = original_multiscale_deform_attn
61
76
 
62
77
 
63
78
  def monkey_patch_decorator(func):
@@ -76,6 +91,30 @@ def monkey_patch_decorator(func):
76
91
  return wrapper
77
92
 
78
93
 
94
+ def get_sine_pos_embed(
95
+ pos_tensor: torch.Tensor, num_pos_feats: int = 128, temperature: int = 10000, exchange_xy: bool = True
96
+ ) -> Tensor:
97
+ scale = 2 * math.pi
98
+ dim_t = torch.arange(num_pos_feats, dtype=torch.float32, device=pos_tensor.device)
99
+ dim_t = temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / num_pos_feats)
100
+
101
+ scaled_pos = pos_tensor.unsqueeze(-1) * scale / dim_t
102
+ reshaped_pos = scaled_pos.view(*scaled_pos.shape[:-1], -1, 2)
103
+ sin_chunk, cos_chunk = torch.split(reshaped_pos, 1, dim=-1)
104
+ sin_embed = sin_chunk.squeeze(-1).sin()
105
+ cos_embed = cos_chunk.squeeze(-1).cos()
106
+
107
+ pos_embed = torch.stack((sin_embed, cos_embed), dim=-1).flatten(-2)
108
+
109
+ if exchange_xy and pos_tensor.shape[-1] >= 2:
110
+ swapped_embeds = torch.cat([pos_embed[..., 1:2, :], pos_embed[..., 0:1, :], pos_embed[..., 2:, :]], dim=-2)
111
+ pos_embed = swapped_embeds
112
+
113
+ position_embeddings = pos_embed.flatten(start_dim=-2)
114
+
115
+ return position_embeddings
116
+
117
+
79
118
  class _GroundingDinoEncoder(torch.nn.Module):
80
119
  def __init__(self, model: "GroundingDinoEncoder", rbln_config: "RBLNGroundingDinoEncoderConfig"):
81
120
  super().__init__()
@@ -386,16 +425,20 @@ class _GroundingDinoMultiscaleDeformableAttention(torch.nn.Module):
386
425
  # batch_size, num_queries, n_heads, n_levels, n_points, 2
387
426
  num_coordinates = reference_points.shape[-1]
388
427
  if num_coordinates == 2:
389
- offset_normalizer = torch.stack([spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
390
- sampling_locations = (
391
- reference_points[:, :, None, :, None, :]
428
+ offset_normalizer = 0.5 * torch.stack([spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
429
+ sampling_grids = (
430
+ 2 * reference_points[:, :, None, :, None, :]
431
+ - 1
392
432
  + sampling_offsets / offset_normalizer[None, None, None, :, None, :]
393
433
  )
394
434
  elif num_coordinates == 4:
395
- sampling_locations = (
396
- reference_points[:, :, None, :, None, :2]
397
- + sampling_offsets / self.n_points * reference_points[:, :, None, :, None, 2:] * 0.5
398
- )
435
+ ref_points_xy, ref_points_wh = torch.split(reference_points, 2, dim=-1)
436
+ ref_points_xy = ref_points_xy[:, :, None, :, None, :]
437
+ ref_points_wh = ref_points_wh[:, :, None, :, None, :]
438
+ ref_points_grids = 2 * ref_points_xy - 1
439
+ offset_grids = sampling_offsets / self.n_points * ref_points_wh
440
+ sampling_grids = ref_points_grids + offset_grids
441
+
399
442
  else:
400
443
  raise ValueError(f"Last dim of reference_points must be 2 or 4, but got {reference_points.shape[-1]}")
401
444
 
@@ -404,7 +447,7 @@ class _GroundingDinoMultiscaleDeformableAttention(torch.nn.Module):
404
447
  spatial_shapes,
405
448
  spatial_shapes_list,
406
449
  level_start_index,
407
- sampling_locations,
450
+ sampling_grids,
408
451
  attention_weights,
409
452
  self.im2col_step,
410
453
  )
@@ -456,15 +499,14 @@ class _GroundingDinoBiMultiHeadAttention(torch.nn.Module):
456
499
  # # Do not increase -50000/50000, data type half has quite limited range
457
500
  attn_weights = torch.clamp(attn_weights, min=-50000, max=50000)
458
501
 
459
- attn_weights_transposed = attn_weights.transpose(1, 2)
460
502
  # RBLN FIX: max_values from scalar to vector
461
- text_attn_weights = attn_weights_transposed - torch.max(attn_weights_transposed, dim=-1, keepdim=True)[
462
- 0
463
- ].repeat(1, 1, tgt_len)
503
+ text_attn_weights = attn_weights - torch.max(attn_weights, dim=1, keepdim=True)[0].repeat(1, tgt_len, 1)
464
504
 
465
505
  # # Do not increase -50000/50000, data type half has quite limited range
466
506
  text_attn_weights = torch.clamp(text_attn_weights, min=-50000, max=50000)
467
507
 
508
+ text_attn_weights = text_attn_weights.transpose(1, 2)
509
+
468
510
  # mask vision for language
469
511
  if vision_attention_mask is not None:
470
512
  # RBLN FIX: bool tensor to float tensor
@@ -511,3 +553,47 @@ class _GroundingDinoBiMultiHeadAttention(torch.nn.Module):
511
553
  text_attn_output = self.out_text_proj(text_attn_output)
512
554
 
513
555
  return (vision_attn_output, vision_attn_weights), (text_attn_output, text_attn_weights)
556
+
557
+
558
+ class _MultiScaleDeformableAttention(torch.nn.Module):
559
+ def forward(
560
+ self,
561
+ value: Tensor,
562
+ value_spatial_shapes: Tensor,
563
+ value_spatial_shapes_list: List[Tuple],
564
+ level_start_index: Tensor,
565
+ sampling_grids: Tensor,
566
+ attention_weights: Tensor,
567
+ im2col_step: int,
568
+ ):
569
+ batch_size, _, num_heads, hidden_dim = value.shape
570
+ _, num_queries, num_heads, num_levels, num_points, _ = sampling_grids.shape
571
+ value_list = value.split([height * width for height, width in value_spatial_shapes_list], dim=1)
572
+ sampling_value_list = []
573
+ sampling_grids_list = [t.squeeze(3) for t in torch.split(sampling_grids, 1, dim=3)]
574
+ for level_id, (height, width) in enumerate(value_spatial_shapes_list):
575
+ value_l_ = (
576
+ value_list[level_id].permute(0, 2, 3, 1).reshape(batch_size * num_heads, hidden_dim, height, width)
577
+ )
578
+ sampling_grid_l_ = sampling_grids_list[level_id].transpose(1, 2).flatten(0, 1)
579
+ sampling_value_l_ = torch.nn.functional.grid_sample(
580
+ value_l_,
581
+ sampling_grid_l_,
582
+ mode="bilinear",
583
+ padding_mode="zeros",
584
+ align_corners=False,
585
+ )
586
+ sampling_value_list.append(sampling_value_l_)
587
+
588
+ sampling_values = torch.cat(sampling_value_list, dim=-1)
589
+ attention_weights_prep = attention_weights.transpose(1, 2)
590
+ values_permuted = sampling_values.permute(0, 2, 3, 1)
591
+
592
+ weights_for_matmul = attention_weights_prep.reshape(
593
+ batch_size * num_heads, num_queries, 1, num_levels * num_points
594
+ )
595
+ output_before_permute = torch.matmul(weights_for_matmul, values_permuted)
596
+ output_before_view = output_before_permute.squeeze(2).permute(0, 2, 1)
597
+ output = output_before_view.reshape(batch_size, num_heads * hidden_dim, num_queries)
598
+
599
+ return output.transpose(1, 2).contiguous()
@@ -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,506 @@
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
+ Qwen2VLRotaryEmbedding,
31
+ VisionRotaryEmbedding,
32
+ )
33
+
34
+ from ....configuration_utils import RBLNCompileConfig
35
+ from ....modeling import RBLNModel
36
+ from ....utils.logging import get_logger
37
+ from ..decoderonly.modeling_decoderonly import RBLNDecoderOnlyModelForCausalLM, RBLNDecoderOnlyOutput
38
+ from .configuration_qwen2_vl import (
39
+ RBLNQwen2VisionTransformerPretrainedModelConfig,
40
+ RBLNQwen2VLForConditionalGenerationConfig,
41
+ )
42
+ from .qwen2_vl_architecture import Qwen2VisionTransformerWrapper, Qwen2VL_LanguageModelWrapper
43
+
44
+
45
+ logger = get_logger(__name__)
46
+
47
+ if TYPE_CHECKING:
48
+ from transformers import (
49
+ AutoFeatureExtractor,
50
+ AutoProcessor,
51
+ AutoTokenizer,
52
+ PretrainedConfig,
53
+ )
54
+
55
+
56
+ class RBLNQwen2VisionTransformerPretrainedModel(RBLNModel):
57
+ auto_model_class = None
58
+
59
+ def __post_init__(self, **kwargs):
60
+ self.transformer = self.model[0]
61
+ self.max_seq_lens = torch.tensor(sorted(self.rbln_config.max_seq_lens, reverse=False))
62
+ config = self.config
63
+
64
+ self.patch_size = config.spatial_patch_size
65
+ self.spatial_merge_size = config.spatial_merge_size
66
+ self.spatial_merge_unit = config.spatial_merge_size * config.spatial_merge_size
67
+ self.rotary_pos_emb = VisionRotaryEmbedding((config.embed_dim // config.num_heads) // 2)
68
+ with no_init_weights():
69
+ self.patch_embed = PatchEmbed(
70
+ patch_size=config.patch_size,
71
+ temporal_patch_size=config.temporal_patch_size,
72
+ in_channels=config.in_channels,
73
+ embed_dim=config.embed_dim,
74
+ ).eval()
75
+ artifacts = torch.load(self.model_save_dir / self.subfolder / "torch_artifacts.pth", weights_only=False)
76
+ self.patch_embed.load_state_dict(artifacts["patch_embed"])
77
+
78
+ @classmethod
79
+ def save_torch_artifacts(
80
+ cls,
81
+ model: "Qwen2VLForConditionalGeneration",
82
+ save_dir_path: Path,
83
+ subfolder: str,
84
+ rbln_config: RBLNQwen2VisionTransformerPretrainedModelConfig,
85
+ ):
86
+ save_dict = {}
87
+ save_dict["patch_embed"] = model.patch_embed.state_dict()
88
+ torch.save(save_dict, save_dir_path / subfolder / "torch_artifacts.pth")
89
+
90
+ @classmethod
91
+ def wrap_model_if_needed(
92
+ cls, model: "PreTrainedModel", rbln_config: RBLNQwen2VisionTransformerPretrainedModelConfig
93
+ ):
94
+ return Qwen2VisionTransformerWrapper(model).eval()
95
+
96
+ def __getattr__(self, __name: str) -> Any:
97
+ def redirect(func):
98
+ return lambda *pargs, **kwargs: func(self, *pargs, **kwargs)
99
+
100
+ val = getattr(Qwen2VisionTransformerPretrainedModel, __name)
101
+
102
+ if isinstance(val, Callable) and "self" in set(inspect.signature(val).parameters):
103
+ return redirect(val)
104
+ return val
105
+
106
+ @classmethod
107
+ def _update_rbln_config(
108
+ cls,
109
+ preprocessors: Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"],
110
+ model: Optional["PreTrainedModel"] = None,
111
+ model_config: "PretrainedConfig" = None,
112
+ rbln_config: Optional[RBLNQwen2VisionTransformerPretrainedModelConfig] = None,
113
+ ) -> RBLNQwen2VisionTransformerPretrainedModelConfig:
114
+ hidden_size = getattr(model_config, "embed_dim")
115
+ num_heads = getattr(model_config, "num_heads")
116
+ head_dim = hidden_size // num_heads
117
+
118
+ input_infos = []
119
+ for max_seq_len in rbln_config.max_seq_lens:
120
+ input_info = [
121
+ ("hidden_states", [max_seq_len, hidden_size], "float32"),
122
+ ("full_attn_masks", [1, 1, max_seq_len, max_seq_len], "float32"),
123
+ (
124
+ "cos",
125
+ [1, 1, max_seq_len, head_dim],
126
+ "float32",
127
+ ),
128
+ (
129
+ "sin",
130
+ [1, 1, max_seq_len, head_dim],
131
+ "float32",
132
+ ),
133
+ ]
134
+ input_infos.append(input_info)
135
+
136
+ rbln_compile_config = RBLNCompileConfig(input_info=input_infos)
137
+ rbln_config.set_compile_cfgs([rbln_compile_config])
138
+
139
+ return rbln_config
140
+
141
+ @staticmethod
142
+ def _pad_for_full_attn_layers(hidden_state, cos, sin, max_seq_len):
143
+ if hidden_state.shape[0] < max_seq_len:
144
+ full_padding_size = max_seq_len - hidden_state.shape[0]
145
+ full_padding_hidden = torch.zeros(
146
+ full_padding_size,
147
+ hidden_state.shape[-1],
148
+ dtype=hidden_state.dtype,
149
+ )
150
+ hidden_state_full_padded = torch.cat([hidden_state, full_padding_hidden], dim=0)
151
+ full_padding_pos = torch.zeros(
152
+ full_padding_size,
153
+ cos.shape[-1],
154
+ dtype=cos.dtype,
155
+ )
156
+ cos_full_padded = torch.cat([cos, full_padding_pos], dim=0)
157
+ sin_full_padded = torch.cat([sin, full_padding_pos], dim=0)
158
+ else:
159
+ hidden_state_full_padded = hidden_state
160
+ cos_full_padded = cos
161
+ sin_full_padded = sin
162
+
163
+ full_attn_masks = torch.ones(
164
+ 1,
165
+ 1,
166
+ max_seq_len,
167
+ max_seq_len,
168
+ dtype=torch.float32,
169
+ )
170
+
171
+ full_attn_masks[:, :, hidden_state.shape[0] : max_seq_len, :] = 0
172
+ full_attn_masks[:, :, :, hidden_state.shape[0] : max_seq_len] = 0
173
+ return hidden_state_full_padded, cos_full_padded, sin_full_padded, full_attn_masks
174
+
175
+ def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor) -> torch.Tensor:
176
+ # Processes a batch of images (or frames) through the vision transformer.
177
+ # Each image is handled independently for padding and attention mask generation.
178
+
179
+ hidden_states = self.patch_embed(hidden_states)
180
+ rotary_pos_emb = self.rot_pos_emb(grid_thw)
181
+ emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
182
+ position_embeddings = (emb.cos(), emb.sin())
183
+
184
+ cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum(
185
+ dim=0,
186
+ dtype=torch.int32,
187
+ )
188
+ cu_seqlens = torch.nn.functional.pad(cu_seqlens, (1, 0), value=0)
189
+
190
+ num_images = len(cu_seqlens) - 1
191
+ output_hidden_states = []
192
+
193
+ # Process each image in the sequence
194
+ for i in range(num_images):
195
+ image_s, image_e = cu_seqlens[i], cu_seqlens[i + 1]
196
+
197
+ # Select the nearest higher max_seq_len from the available compiled models.
198
+ cu_seq_len = image_e - image_s
199
+ try:
200
+ cu_index = torch.searchsorted(self.max_seq_lens, cu_seq_len).item()
201
+ max_seq_len = self.max_seq_lens[cu_index]
202
+ except Exception:
203
+ raise ValueError(
204
+ f"Required seq_len({cu_seq_len}) is larger than available max_seq_lens({self.max_seq_lens.tolist()})."
205
+ )
206
+
207
+ # Padding for Full Attention Layers
208
+ hidden_state_full_padded, cos_full_padded, sin_full_padded, full_attn_masks = (
209
+ self._pad_for_full_attn_layers(
210
+ hidden_states[image_s:image_e],
211
+ position_embeddings[0][image_s:image_e],
212
+ position_embeddings[1][image_s:image_e],
213
+ max_seq_len,
214
+ )
215
+ )
216
+
217
+ # RBLN run with the compiled model
218
+ output = self.transformer(
219
+ hidden_state_full_padded,
220
+ full_attn_masks,
221
+ cos_full_padded[None, None, :, :],
222
+ sin_full_padded[None, None, :, :],
223
+ )
224
+ # Depadding
225
+ depadded_output = output[: cu_seq_len // self.spatial_merge_unit]
226
+ output_hidden_states.append(depadded_output)
227
+
228
+ hidden_states = torch.cat(output_hidden_states)
229
+ return hidden_states
230
+
231
+
232
+ class RBLNQwen2VLForConditionalGeneration(RBLNDecoderOnlyModelForCausalLM):
233
+ """
234
+ RBLNQwen2VLForConditionalGeneration is a multi-modal model that integrates vision and language processing capabilities,
235
+ optimized for RBLN NPUs. It is designed for conditional generation tasks that involve both image and text inputs.
236
+
237
+ This model inherits from [`RBLNDecoderOnlyModelForCausalLM`]. Check the superclass documentation for the generic methods the library implements for all its models.
238
+
239
+ Important Note:
240
+ This model includes a Large Language Model (LLM). For optimal performance, it is highly recommended to use
241
+ tensor parallelism for the language model. This can be achieved by using the `rbln_config` parameter in the
242
+ `from_pretrained` method. Refer to the `from_pretrained` documentation and the RBLNQwen2VLForConditionalGenerationConfig class for details.
243
+
244
+ Examples:
245
+ ```python
246
+ from optimum.rbln import RBLNQwen2VLForConditionalGeneration
247
+
248
+ model = RBLNQwen2VLForConditionalGeneration.from_pretrained(
249
+ "Qwen/Qwen2-VL-7B-Instruct",
250
+ export=True,
251
+ rbln_config={
252
+ "visual": {
253
+ "max_seq_lens": 6400,
254
+ "device": 0,
255
+ },
256
+ "tensor_parallel_size": 8,
257
+ "kvcache_partition_len": 16_384,
258
+ "max_seq_len": 114_688,
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_input_info(
286
+ cls,
287
+ batch_size: int,
288
+ query_length: int,
289
+ rbln_config: RBLNQwen2VLForConditionalGenerationConfig,
290
+ model_config: PretrainedConfig,
291
+ ):
292
+ input_info = super().get_input_info(batch_size, query_length, rbln_config, model_config)
293
+ pos_idx = 3
294
+ input_info.insert(
295
+ pos_idx,
296
+ (
297
+ "position_emb",
298
+ [2, batch_size, 1, query_length, model_config.hidden_size // model_config.num_attention_heads],
299
+ "float32",
300
+ ),
301
+ )
302
+
303
+ return input_info
304
+
305
+ def prepare_inputs_for_generation(
306
+ self,
307
+ input_ids: torch.LongTensor,
308
+ generate_idx: Optional[torch.Tensor] = None,
309
+ attention_mask: Optional[torch.LongTensor] = None,
310
+ inputs_embeds: Optional[torch.Tensor] = None,
311
+ pixel_values=None,
312
+ pixel_values_videos=None,
313
+ image_grid_thw=None,
314
+ video_grid_thw=None,
315
+ **kwargs,
316
+ ):
317
+ model_inputs = super().prepare_inputs_for_generation(
318
+ input_ids,
319
+ generate_idx,
320
+ attention_mask,
321
+ inputs_embeds,
322
+ **kwargs,
323
+ )
324
+
325
+ is_prefill_phase = generate_idx is None
326
+ if is_prefill_phase:
327
+ model_inputs.update({"input_ids": input_ids})
328
+
329
+ model_inputs.update(
330
+ {
331
+ "pixel_values": pixel_values,
332
+ "pixel_values_videos": pixel_values_videos,
333
+ "image_grid_thw": image_grid_thw,
334
+ "video_grid_thw": video_grid_thw,
335
+ }
336
+ )
337
+
338
+ return model_inputs
339
+
340
+ def _get_position_embeddings(self, hidden_states, position_ids):
341
+ cos, sin = self.rotary_emb(hidden_states, position_ids)
342
+ mrope_section = self.mrope_section * 2
343
+ cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze(1)
344
+ sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze(1)
345
+ return torch.stack([cos, sin])
346
+
347
+ def _preprocess_prefill(
348
+ self,
349
+ input_ids: torch.LongTensor = None,
350
+ attention_mask: torch.Tensor = None,
351
+ pixel_values: torch.Tensor = None,
352
+ pixel_values_videos: torch.FloatTensor = None,
353
+ image_grid_thw: torch.LongTensor = None,
354
+ video_grid_thw: torch.LongTensor = None,
355
+ ):
356
+ batch_size = input_ids.shape[0]
357
+ inputs_embeds = self.embed_tokens(input_ids)
358
+
359
+ if pixel_values is not None:
360
+ image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw)
361
+ n_image_tokens = (input_ids == self.config.image_token_id).sum().item()
362
+ n_image_features = image_embeds.shape[0]
363
+ if n_image_tokens != n_image_features:
364
+ raise ValueError(
365
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
366
+ )
367
+
368
+ mask = input_ids == self.config.image_token_id
369
+ mask_unsqueezed = mask.unsqueeze(-1)
370
+ mask_expanded = mask_unsqueezed.expand_as(inputs_embeds)
371
+
372
+ image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
373
+ inputs_embeds = inputs_embeds.masked_scatter(mask_expanded, image_embeds)
374
+
375
+ if pixel_values_videos is not None:
376
+ video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw)
377
+ n_video_tokens = (input_ids == self.config.video_token_id).sum().item()
378
+ n_video_features = video_embeds.shape[0]
379
+ if n_video_tokens != n_video_features:
380
+ raise ValueError(
381
+ f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}"
382
+ )
383
+
384
+ mask = input_ids == self.config.video_token_id
385
+ mask_unsqueezed = mask.unsqueeze(-1)
386
+ mask_expanded = mask_unsqueezed.expand_as(inputs_embeds)
387
+ inputs_embeds = inputs_embeds.masked_scatter(mask_expanded, video_embeds)
388
+
389
+ max_inputs_len = input_ids.shape[1]
390
+
391
+ head_dim = getattr(self.config, "head_dim", None) or self.config.hidden_size // self.config.num_attention_heads
392
+ all_position_embeds = torch.zeros(2, batch_size, 1, max_inputs_len, head_dim)
393
+ all_rope_deltas = []
394
+
395
+ image_token_id = self.config.image_token_id
396
+ video_token_id = self.config.video_token_id
397
+ vision_start_token_id = self.config.vision_start_token_id
398
+ image_idx, video_idx = 0, 0
399
+
400
+ for b_idx in range(batch_size):
401
+ input_id = input_ids[b_idx : b_idx + 1][:, attention_mask[b_idx].bool()]
402
+ vision_start_indices = torch.argwhere(input_id == vision_start_token_id).squeeze(1)
403
+ vision_tokens = input_id[0][vision_start_indices + 1]
404
+ image_nums = (vision_tokens == image_token_id).sum()
405
+ video_nums = (vision_tokens == video_token_id).sum()
406
+ position_ids, rope_deltas = self.get_rope_index(
407
+ input_id,
408
+ image_grid_thw[image_idx : image_idx + image_nums] if image_grid_thw is not None else None,
409
+ video_grid_thw[video_idx : video_idx + video_nums] if video_grid_thw is not None else None,
410
+ attention_mask=attention_mask[b_idx : b_idx + 1] if attention_mask is not None else None,
411
+ )
412
+ image_idx += image_nums
413
+ video_idx += video_nums
414
+
415
+ position_embed = self._get_position_embeddings(inputs_embeds, position_ids)
416
+ mask_indices = torch.nonzero(attention_mask[b_idx], as_tuple=True)[0]
417
+ all_position_embeds[:, b_idx : b_idx + 1].index_copy_(dim=-2, index=mask_indices, source=position_embed)
418
+ all_rope_deltas.append(rope_deltas)
419
+
420
+ rope_deltas = torch.stack(all_rope_deltas)
421
+
422
+ return inputs_embeds, all_position_embeds, rope_deltas
423
+
424
+ def _preprocess_decoder(
425
+ self,
426
+ input_ids: torch.LongTensor = None,
427
+ cache_position: torch.LongTensor = None,
428
+ ):
429
+ if self.rbln_config.batch_size != cache_position.shape[0]:
430
+ raise RuntimeError(
431
+ f"Cache position size mismatch: got {cache_position.shape[0]}, expected {self.rbln_config.batch_size}."
432
+ )
433
+
434
+ inputs_embeds = self.embed_tokens(input_ids)
435
+ position_embeds = []
436
+ for b_idx in range(self.rbln_config.batch_size):
437
+ delta = cache_position[b_idx] + self.rope_deltas[b_idx]
438
+ position_ids = torch.arange(1).view(1, -1)
439
+ position_ids = position_ids.add(delta)
440
+ position_ids = position_ids.unsqueeze(0).expand(3, -1, -1)
441
+ position_embed = self._get_position_embeddings(torch.zeros(1, dtype=torch.float32), position_ids)
442
+ position_embeds.append(position_embed)
443
+
444
+ position_embeds = torch.cat(position_embeds, dim=1)
445
+
446
+ return inputs_embeds, position_embeds
447
+
448
+ def forward(
449
+ self,
450
+ input_ids: Optional[torch.LongTensor] = None,
451
+ inputs_embeds: Optional[torch.FloatTensor] = None,
452
+ attention_mask: Optional[torch.Tensor] = None,
453
+ pixel_values: Optional[torch.Tensor] = None,
454
+ pixel_values_videos: Optional[torch.FloatTensor] = None,
455
+ image_grid_thw: Optional[torch.LongTensor] = None,
456
+ video_grid_thw: Optional[torch.LongTensor] = None,
457
+ cache_position: Optional[torch.LongTensor] = None,
458
+ generate_idx: Optional[torch.Tensor] = None,
459
+ return_dict: Optional[bool] = None,
460
+ **kwargs,
461
+ ) -> RBLNDecoderOnlyOutput:
462
+ # Prefill
463
+ if cache_position is None:
464
+ inputs_embeds, position_embed, rope_deltas = self._preprocess_prefill(
465
+ input_ids,
466
+ attention_mask,
467
+ pixel_values,
468
+ pixel_values_videos,
469
+ image_grid_thw,
470
+ video_grid_thw,
471
+ )
472
+
473
+ self.rope_deltas = rope_deltas
474
+ batch_size = inputs_embeds.shape[0]
475
+
476
+ logits = []
477
+ for b_idx in range(batch_size):
478
+ cache_position = torch.arange(0, generate_idx[b_idx].item(), dtype=torch.int32).unsqueeze(0)
479
+
480
+ output = self.prefill_decoder(
481
+ inputs_embeds=inputs_embeds[b_idx : b_idx + 1],
482
+ attention_mask=attention_mask[b_idx] if attention_mask is not None else None,
483
+ cache_position=cache_position,
484
+ batch_idx=b_idx,
485
+ position_embed=position_embed[:, b_idx : b_idx + 1],
486
+ )
487
+ logits.append(output.logits)
488
+ logits = torch.cat(logits, dim=0)
489
+
490
+ # Decoder
491
+ else:
492
+ inputs_embeds, position_embed = self._preprocess_decoder(input_ids, cache_position)
493
+ output = self.decoder(
494
+ inputs_embeds=inputs_embeds,
495
+ cache_position=cache_position,
496
+ position_embed=position_embed,
497
+ )
498
+ logits = output.logits
499
+
500
+ if not return_dict:
501
+ return logits, generate_idx
502
+ else:
503
+ return RBLNDecoderOnlyOutput(
504
+ logits=logits,
505
+ generate_idx=generate_idx,
506
+ )
@@ -0,0 +1,141 @@
1
+ import math
2
+ from typing import Tuple
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+
7
+ from ..decoderonly.decoderonly_architecture import (
8
+ DecoderOnlyWrapper,
9
+ apply_rotary_pos_emb,
10
+ )
11
+
12
+
13
+ class Qwen2VisionTransformerWrapper(nn.Module):
14
+ def __init__(self, model: torch.nn.Module):
15
+ super().__init__()
16
+ self._original_mod = model
17
+ self.merger = model.merger
18
+ self.blocks = self.wrap_vision_blocks(model.blocks)
19
+
20
+ def wrap_vision_blocks(self, blocks: torch.nn.ModuleList):
21
+ wrapped_blocks = []
22
+ for i, block in enumerate(blocks):
23
+ wrapped_blocks.append(Qwen2VLVisionBlock(block))
24
+ return nn.ModuleList(wrapped_blocks)
25
+
26
+ def forward(
27
+ self,
28
+ hidden_states: torch.Tensor,
29
+ full_attn_masks: torch.Tensor,
30
+ cos: torch.Tensor,
31
+ sin: torch.Tensor,
32
+ ):
33
+ full_attn_masks = (1 - full_attn_masks) * torch.finfo(torch.float32).min
34
+
35
+ for block in self.blocks:
36
+ hidden_states = block(hidden_states, full_attn_masks, [cos, sin])
37
+
38
+ return self.merger(hidden_states)
39
+
40
+
41
+ class Qwen2VLVisionBlock(torch.nn.Module):
42
+ def __init__(self, model: torch.nn.Module):
43
+ super().__init__()
44
+ self._origin_model = model
45
+ self.norm1 = model.norm1
46
+ self.norm2 = model.norm2
47
+
48
+ self.attn = VisionAttention(model.attn)
49
+ self.mlp = model.mlp
50
+
51
+ def forward(
52
+ self,
53
+ hidden_states: torch.Tensor,
54
+ attn_masks: torch.Tensor,
55
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
56
+ ) -> torch.Tensor:
57
+ hidden_states = hidden_states + self.attn(
58
+ self.norm1(hidden_states),
59
+ attn_masks,
60
+ position_embeddings,
61
+ )
62
+ hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
63
+ return hidden_states
64
+
65
+
66
+ class VisionAttention(nn.Module):
67
+ def __init__(self, model: nn.Module) -> None:
68
+ super().__init__()
69
+ self._origin_model = model
70
+ self.num_heads = model.num_heads
71
+ self.head_dim = getattr(model, "head_dim", model.proj.in_features // model.num_heads)
72
+ self.qkv = model.qkv
73
+ self.proj = model.proj
74
+
75
+ def forward(
76
+ self,
77
+ hidden_states: torch.Tensor,
78
+ attn_masks: torch.Tensor,
79
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
80
+ ) -> torch.Tensor:
81
+ seq_length = hidden_states.shape[0]
82
+ hidden_states = hidden_states.unsqueeze(0)
83
+ q, k, v = (
84
+ self.qkv(hidden_states).reshape(1, seq_length, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4).unbind(0)
85
+ )
86
+
87
+ cos, sin = position_embeddings
88
+ q, k = apply_rotary_pos_emb(q, k, cos, sin)
89
+
90
+ attn_weights = torch.matmul(q, k.transpose(2, 3)) / math.sqrt(self.head_dim)
91
+ attn_weights = attn_weights + attn_masks
92
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32)
93
+ attn_output = torch.matmul(attn_weights, v)
94
+ attn_output = attn_output.transpose(1, 2)
95
+ attn_output = attn_output.reshape(1, seq_length, -1)
96
+ attn_output = self.proj(attn_output).squeeze(0)
97
+
98
+ return attn_output
99
+
100
+
101
+ class Qwen2VL_LanguageModelWrapper(DecoderOnlyWrapper):
102
+ def prepare_forward_args(self, *args):
103
+ args = list(args)
104
+ input_ids = None if self.rbln_config.use_inputs_embeds else args.pop(0)
105
+ inputs_embeds = args.pop(0) if self.rbln_config.use_inputs_embeds else None
106
+ cache_position = args.pop(0)
107
+ global_block_tables = args.pop(0)
108
+ local_block_tables = None
109
+ position_embeds = args.pop(0)
110
+ query_position = args.pop(0) if self.phase == "prefill" else None
111
+ position_ids = None
112
+ attention_mask = args.pop(0) if self.rbln_config.use_attention_mask else None
113
+ past_key_values = args
114
+
115
+ if len(past_key_values) != 2 * self.num_hidden_layers:
116
+ raise ValueError(
117
+ f"Different past_key_values to model's config. {len(past_key_values)} != {2 * self.num_hidden_layers}"
118
+ )
119
+
120
+ # [key, value] * n_layer -> ( (key, value) ) * n_layer
121
+ # cache shape : batch, n_heads, 1, max_seq_len, head_dim
122
+ _past_key_values = []
123
+ for i in range(self.config.num_hidden_layers):
124
+ key_states = past_key_values[i * 2]
125
+ value_states = past_key_values[i * 2 + 1]
126
+ past_key_value = [key_states, value_states]
127
+ _past_key_values.append(past_key_value)
128
+ past_key_values = _past_key_values
129
+
130
+ return (
131
+ input_ids,
132
+ inputs_embeds,
133
+ cache_position,
134
+ global_block_tables,
135
+ local_block_tables,
136
+ query_position,
137
+ attention_mask,
138
+ position_ids,
139
+ past_key_values,
140
+ position_embeds,
141
+ )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: optimum-rbln
3
- Version: 0.8.4a1
3
+ Version: 0.8.4a2
4
4
  Summary: Optimum RBLN is the interface between the HuggingFace Transformers and Diffusers libraries and RBLN accelerators. It provides a set of tools enabling easy model loading and inference on single and multiple rbln device settings for different downstream tasks.
5
5
  Project-URL: Homepage, https://rebellions.ai
6
6
  Project-URL: Documentation, https://docs.rbln.ai
@@ -1,5 +1,5 @@
1
- optimum/rbln/__init__.py,sha256=32ouGKDGus9k5_kD27CxP8jIQOw66zpDTfS0xs1XlfE,18298
2
- optimum/rbln/__version__.py,sha256=Xldcu_i01nl8cPxjp-cO8CxxNYyVzFEpw4QQPEW-cj4,712
1
+ optimum/rbln/__init__.py,sha256=DAJM5PWAYFiWVlyxVXUvj3CaFOEhX1yhEfhIt1LxL-A,18714
2
+ optimum/rbln/__version__.py,sha256=6hrMyGZLwiE6FQKcZWu0sAdnavT4qOGFRA8YsAHksXI,712
3
3
  optimum/rbln/configuration_utils.py,sha256=WNubd8EJIrdBkLOGT2UJJorgNL3lzhjg3a4bihAIptY,34761
4
4
  optimum/rbln/modeling.py,sha256=cAIPWEw5DGzUWeqjCbocRhU6OO3jyhVGW60AmBLh1Nw,14134
5
5
  optimum/rbln/modeling_base.py,sha256=97ju0uHJXB7PaorKaspf-FbLfsaHy0HwRVLJqtVscXA,27574
@@ -72,13 +72,13 @@ optimum/rbln/ops/flash_attn.py,sha256=yTCdYQVqm_1rHMHWjrMQaIR8WTuG_xA6t033x1IVvT
72
72
  optimum/rbln/ops/kv_cache_update.py,sha256=aIvK2Sp7M3EfJzJgNvIvAJv4emoN6QOhmgaWj-VboLs,1440
73
73
  optimum/rbln/ops/linear.py,sha256=5K3pcrrUHu_p8LrMIU-jX2TnafksveFjjZSCsYSp_yw,1328
74
74
  optimum/rbln/ops/sliding_window_attn.py,sha256=EQrV_yRGc5z6kvwEsAcLP028bJWkQg2UPI3xubt9skU,3487
75
- optimum/rbln/transformers/__init__.py,sha256=6s-VhsqwptqwUuq7vb847bJlfFgBGshOoK3vaN9i_lI,12043
75
+ optimum/rbln/transformers/__init__.py,sha256=g5G6Eqk80NzS0tMmwghFI2DMKgPaOpoafv1m0Euhw6A,12459
76
76
  optimum/rbln/transformers/configuration_generic.py,sha256=jrehv1oONOS-iBTY5gj2TKUfWjDTnukNJt6cZfNMylU,5213
77
77
  optimum/rbln/transformers/modeling_attention_utils.py,sha256=aLyOaq4me1m-JMmnKbuyNQageDxNU2jjEhGE_ew2P5o,11465
78
78
  optimum/rbln/transformers/modeling_generic.py,sha256=82Wi2K6zAp5tjef05lzYIEqbK93h0_OkPDbElB-VMMs,12568
79
79
  optimum/rbln/transformers/modeling_outputs.py,sha256=cd8ZlhHAGq7S6i5-QK6TJCxgORvoPMnZpqPBlUc_pMY,1177
80
80
  optimum/rbln/transformers/modeling_rope_utils.py,sha256=6Zg3r-TeUk4WQAlr95pqfhuoAD_RQ4njT1rbO9uPL0Q,14379
81
- optimum/rbln/transformers/models/__init__.py,sha256=V36KWN0fTL0MvfDduUfjIiwXvWmwDKm43G-g5Y773-I,12943
81
+ optimum/rbln/transformers/models/__init__.py,sha256=9gAXrYeYPdLbQH8KlRG4eSOFQ8h4kyWzXPM1grHvpDQ,13418
82
82
  optimum/rbln/transformers/models/audio_spectrogram_transformer/__init__.py,sha256=I2vL4lrzbT5p4eJcH-EKHzEfcPkj_XVsie7jb9q6yic,775
83
83
  optimum/rbln/transformers/models/audio_spectrogram_transformer/configuration_audio_spectrogram_transformer.py,sha256=z7LJiVJPmnlCM3mcyhPJP8AufSrxO_dsPeJ51onq-Nc,833
84
84
  optimum/rbln/transformers/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.py,sha256=FIKEVWpIt6-JQX9B_rAfCrAPqdUHtR2i8D_X2k7639E,1498
@@ -105,7 +105,7 @@ optimum/rbln/transformers/models/colpali/configuration_colpali.py,sha256=eDWPVlo
105
105
  optimum/rbln/transformers/models/colpali/modeling_colpali.py,sha256=v9rPLmNx-BQZhDFhKnr2kmARElTtKdFZCgFIU4m-HPw,15703
106
106
  optimum/rbln/transformers/models/decoderonly/__init__.py,sha256=w3VZOIBYaHXVdnuhK4y0zWAj0IAv7_5LGTJYaz9oYmI,1056
107
107
  optimum/rbln/transformers/models/decoderonly/configuration_decoderonly.py,sha256=H2i9Iefy-q5X-0BLWQ-CrxK8ZoT3p9t0lt_3r4TFSCY,15182
108
- optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py,sha256=L5LArhjN36fTdiwrUABgn3cnS7hh4SVCF4FMHBbiLZU,42760
108
+ optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py,sha256=ySsiU0Acj5enJW-SqtFMAfBeH0HeqlhCd78QlpKJNQw,42780
109
109
  optimum/rbln/transformers/models/decoderonly/decoderonly_runtime_utils.py,sha256=v3mfIlQImQkYYr-rPn7rQR3GYdVUhALRttEduLI7H9c,20012
110
110
  optimum/rbln/transformers/models/decoderonly/generation_decoderonly.py,sha256=4D89IF0yQju_Dp_vLJN_dBkpe2U_LMWaUciYx57D-0M,3379
111
111
  optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py,sha256=dAHV9NgdpXHyTJGT0lieXOB3Pzi_NPlR4rqmRtmAWzM,32412
@@ -137,7 +137,7 @@ optimum/rbln/transformers/models/gpt2/gpt2_architecture.py,sha256=MyAWReXmyuHnDp
137
137
  optimum/rbln/transformers/models/gpt2/modeling_gpt2.py,sha256=DhF6hU3oCYGbZ7UijKCsRfTx-VCkTqqqNwqqMSrjqRE,2230
138
138
  optimum/rbln/transformers/models/grounding_dino/__init__.py,sha256=DE7DipZGvrKC6b1T77k4I4X3G70ss8mlr-PrZCaohto,307
139
139
  optimum/rbln/transformers/models/grounding_dino/configuration_grounding_dino.py,sha256=b6aeAlAMf0aOoTKAqe5nnBfontu_H3zvIHgOiCNMJ1I,3127
140
- optimum/rbln/transformers/models/grounding_dino/grounding_dino_architecture.py,sha256=E6HReXGwvSV7YDeetSBuds1rAVSzEeL0AGHYgBOQW6o,23097
140
+ optimum/rbln/transformers/models/grounding_dino/grounding_dino_architecture.py,sha256=2BGhyKa7x6fiiZPaLy_S7zKr2NOdJnMLFMf6CEcegGE,26674
141
141
  optimum/rbln/transformers/models/grounding_dino/modeling_grounding_dino.py,sha256=bXAOs2QH4sy2UFoFLUSM6u1_VHouUT5COERLQX20F6Y,46897
142
142
  optimum/rbln/transformers/models/idefics3/__init__.py,sha256=ulxE7HEfXsNJhd25J9Fvi6vggo9aZH9sLKJjWB6LlzQ,814
143
143
  optimum/rbln/transformers/models/idefics3/configuration_idefics3.py,sha256=8BhPLkfE1_ZU0eSm2iTbWQOnVe1q0g99srYHWZM6VJ4,2373
@@ -184,6 +184,10 @@ optimum/rbln/transformers/models/qwen2_5_vl/__init__.py,sha256=rAW3DKQUzGL6EMwa5
184
184
  optimum/rbln/transformers/models/qwen2_5_vl/configuration_qwen2_5_vl.py,sha256=1yyMFxh1SKsKR7rOjuotPvpSneN2_4a89bYfNk42370,4735
185
185
  optimum/rbln/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py,sha256=hRvA37sPFC9xH1FqnFbtHS9rQOPwAvLYg4zl4oEyK-w,26639
186
186
  optimum/rbln/transformers/models/qwen2_5_vl/qwen2_5_vl_architecture.py,sha256=i_UUWhKoFjJ5CCpgeWicqABM23TxMEKPQ354LoZ6iUU,7445
187
+ optimum/rbln/transformers/models/qwen2_vl/__init__.py,sha256=O3t6zKda92CnZDzEnz_dcisMOQ71-OOJxElXzKCH5e0,849
188
+ optimum/rbln/transformers/models/qwen2_vl/configuration_qwen2_vl.py,sha256=OGIlUHWNymBTOxnwit-1gm2Gpl8bbGV0i076Sa4RgCw,4718
189
+ optimum/rbln/transformers/models/qwen2_vl/modeling_qwen2_vl.py,sha256=OKjhwWe0UDczmauCNQA838BF3n1BIz8c7oM5gaBVUz8,20286
190
+ optimum/rbln/transformers/models/qwen2_vl/qwen2_vl_architecture.py,sha256=EZlCuSRTIpSAGEjtDi4SY1V9RRdtgg76ie5jqec1UuI,4833
187
191
  optimum/rbln/transformers/models/qwen3/__init__.py,sha256=tI4KwvXpD35dUUaa8aLUXpWoU9gJGcmKXeywOlH14ZE,746
188
192
  optimum/rbln/transformers/models/qwen3/configuration_qwen3.py,sha256=BFRPggnH4VlsXlOa19C6KAID-bPgQ8ooQ29dvogh5zk,2102
189
193
  optimum/rbln/transformers/models/qwen3/modeling_qwen3.py,sha256=S05efusxjXJhMMYztstGes6ZbqkSr5I4fHFaLSYVG8c,5760
@@ -238,7 +242,7 @@ optimum/rbln/utils/model_utils.py,sha256=4k5879Kh75m3x_vS4-qOGfqsOiAvc2kdNFFfvsF
238
242
  optimum/rbln/utils/runtime_utils.py,sha256=R6uXDbeJP03-FWdd4vthNe2D4aCra5n12E3WB1ifiGM,7933
239
243
  optimum/rbln/utils/save_utils.py,sha256=hG5uOtYmecSXZuGTvCXsTM-SiyZpr5q3InUGCCq_jzQ,3619
240
244
  optimum/rbln/utils/submodule.py,sha256=60NGLFvnhjP1DJg1opdb-FVQDsthcLCwWjW_1WQaasU,5280
241
- optimum_rbln-0.8.4a1.dist-info/METADATA,sha256=cs0rmwPfLMefC6PHPHGw7XYrZIQVGPP3ax09PhmeUB8,5299
242
- optimum_rbln-0.8.4a1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
243
- optimum_rbln-0.8.4a1.dist-info/licenses/LICENSE,sha256=QwcOLU5TJoTeUhuIXzhdCEEDDvorGiC6-3YTOl4TecE,11356
244
- optimum_rbln-0.8.4a1.dist-info/RECORD,,
245
+ optimum_rbln-0.8.4a2.dist-info/METADATA,sha256=edliyp3YVFP4epCAMZjuPPSxo4LZyyLtux9uAa7EJH4,5299
246
+ optimum_rbln-0.8.4a2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
247
+ optimum_rbln-0.8.4a2.dist-info/licenses/LICENSE,sha256=QwcOLU5TJoTeUhuIXzhdCEEDDvorGiC6-3YTOl4TecE,11356
248
+ optimum_rbln-0.8.4a2.dist-info/RECORD,,