optimum-rbln 0.9.1__py3-none-any.whl → 0.9.2__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.

Files changed (64) hide show
  1. optimum/rbln/__init__.py +8 -0
  2. optimum/rbln/__version__.py +2 -2
  3. optimum/rbln/cli.py +660 -0
  4. optimum/rbln/configuration_utils.py +63 -32
  5. optimum/rbln/diffusers/configurations/pipelines/configuration_controlnet.py +30 -14
  6. optimum/rbln/diffusers/configurations/pipelines/configuration_cosmos.py +11 -8
  7. optimum/rbln/diffusers/configurations/pipelines/configuration_kandinsky2_2.py +23 -13
  8. optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion.py +10 -6
  9. optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion_3.py +14 -10
  10. optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion_xl.py +14 -7
  11. optimum/rbln/diffusers/modeling_diffusers.py +5 -7
  12. optimum/rbln/diffusers/pipelines/cosmos/configuration_cosmos_guardrail.py +9 -11
  13. optimum/rbln/modeling.py +50 -0
  14. optimum/rbln/modeling_base.py +1 -2
  15. optimum/rbln/transformers/__init__.py +8 -0
  16. optimum/rbln/transformers/modeling_generic.py +37 -1
  17. optimum/rbln/transformers/models/__init__.py +9 -0
  18. optimum/rbln/transformers/models/blip_2/configuration_blip_2.py +35 -3
  19. optimum/rbln/transformers/models/blip_2/modeling_blip_2.py +86 -23
  20. optimum/rbln/transformers/models/clip/modeling_clip.py +4 -0
  21. optimum/rbln/transformers/models/colpali/colpali_architecture.py +2 -2
  22. optimum/rbln/transformers/models/colpali/configuration_colpali.py +34 -18
  23. optimum/rbln/transformers/models/colpali/modeling_colpali.py +73 -80
  24. optimum/rbln/transformers/models/colqwen2/__init__.py +2 -0
  25. optimum/rbln/transformers/models/colqwen2/colqwen2_architecture.py +233 -0
  26. optimum/rbln/transformers/models/colqwen2/configuration_colqwen2.py +74 -0
  27. optimum/rbln/transformers/models/colqwen2/modeling_colqwen2.py +446 -0
  28. optimum/rbln/transformers/models/decoderonly/__init__.py +1 -0
  29. optimum/rbln/transformers/models/decoderonly/configuration_decoderonly.py +34 -0
  30. optimum/rbln/transformers/models/decoderonly/configuration_lora.py +411 -0
  31. optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py +100 -20
  32. optimum/rbln/transformers/models/decoderonly/decoderonly_runtime_utils.py +50 -2
  33. optimum/rbln/transformers/models/decoderonly/lora_architecture.py +204 -0
  34. optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py +65 -3
  35. optimum/rbln/transformers/models/gemma3/configuration_gemma3.py +11 -3
  36. optimum/rbln/transformers/models/gemma3/gemma3_architecture.py +12 -2
  37. optimum/rbln/transformers/models/gemma3/gemma3_runtime_utils.py +31 -3
  38. optimum/rbln/transformers/models/gemma3/modeling_gemma3.py +67 -44
  39. optimum/rbln/transformers/models/gpt2/gpt2_architecture.py +4 -1
  40. optimum/rbln/transformers/models/idefics3/configuration_idefics3.py +27 -3
  41. optimum/rbln/transformers/models/idefics3/modeling_idefics3.py +24 -19
  42. optimum/rbln/transformers/models/llava/configuration_llava.py +16 -2
  43. optimum/rbln/transformers/models/llava/modeling_llava.py +108 -50
  44. optimum/rbln/transformers/models/llava_next/configuration_llava_next.py +11 -13
  45. optimum/rbln/transformers/models/llava_next/modeling_llava_next.py +234 -343
  46. optimum/rbln/transformers/models/midm/midm_architecture.py +4 -1
  47. optimum/rbln/transformers/models/phi/phi_architecture.py +5 -1
  48. optimum/rbln/transformers/models/pixtral/modeling_pixtral.py +6 -11
  49. optimum/rbln/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py +9 -8
  50. optimum/rbln/transformers/models/qwen2_5_vl/qwen2_5_vl_architecture.py +24 -0
  51. optimum/rbln/transformers/models/qwen2_vl/modeling_qwen2_vl.py +11 -1
  52. optimum/rbln/transformers/models/qwen2_vl/qwen2_vl_architecture.py +24 -0
  53. optimum/rbln/transformers/models/seq2seq/modeling_seq2seq.py +3 -1
  54. optimum/rbln/transformers/models/siglip/modeling_siglip.py +3 -14
  55. optimum/rbln/transformers/models/whisper/generation_whisper.py +28 -6
  56. optimum/rbln/transformers/models/whisper/modeling_whisper.py +2 -1
  57. optimum/rbln/transformers/utils/rbln_runtime_wrapper.py +79 -0
  58. optimum/rbln/utils/runtime_utils.py +25 -15
  59. optimum/rbln/utils/submodule.py +21 -5
  60. {optimum_rbln-0.9.1.dist-info → optimum_rbln-0.9.2.dist-info}/METADATA +5 -5
  61. {optimum_rbln-0.9.1.dist-info → optimum_rbln-0.9.2.dist-info}/RECORD +64 -55
  62. optimum_rbln-0.9.2.dist-info/entry_points.txt +2 -0
  63. {optimum_rbln-0.9.1.dist-info → optimum_rbln-0.9.2.dist-info}/WHEEL +0 -0
  64. {optimum_rbln-0.9.1.dist-info → optimum_rbln-0.9.2.dist-info}/licenses/LICENSE +0 -0
@@ -12,18 +12,27 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
+ import importlib
15
16
  import inspect
16
17
  from pathlib import Path
17
- from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Tuple, Union
18
+ from typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple, Union
18
19
 
19
20
  import numpy as np
20
21
  import torch
21
22
  from transformers import AutoModelForVision2Seq, LlavaNextForConditionalGeneration, PretrainedConfig, PreTrainedModel
22
23
  from transformers.modeling_outputs import BaseModelOutputWithPooling
24
+ from transformers.modeling_utils import no_init_weights
25
+ from transformers.models.llava_next.modeling_llava_next import (
26
+ get_anyres_image_grid_shape,
27
+ image_size_to_num_patches,
28
+ unpad_image,
29
+ )
23
30
 
24
31
  from ....configuration_utils import RBLNCompileConfig, RBLNModelConfig
25
32
  from ....modeling import RBLNModel
26
33
  from ....utils.logging import get_logger
34
+ from ...utils.rbln_runtime_wrapper import LoopProcessor
35
+ from ..decoderonly.generation_decoderonly import RBLNDecoderOnlyGenerationMixin
27
36
  from ..decoderonly.modeling_decoderonly import RBLNDecoderOnlyOutput
28
37
 
29
38
 
@@ -33,33 +42,27 @@ if TYPE_CHECKING:
33
42
  from transformers import AutoFeatureExtractor, AutoProcessor, AutoTokenizer, PretrainedConfig
34
43
 
35
44
 
36
- class LoopVisionTower:
37
- def __init__(self, vision_tower: RBLNModel) -> None:
38
- self.vision_tower = vision_tower
45
+ class LoopVisionTower(LoopProcessor):
46
+ def __init__(self, vision_tower: "RBLNModel"):
47
+ super().__init__(model=vision_tower.model[0])
39
48
 
40
- def forward(self, *args, **kwargs):
41
- # Loop instead of batch
42
- # shape of pixel_values : [batch, num_patches, num_channel, height, width]
43
- pixel_values = args[0]
49
+ def _get_batch_size(self, pixel_values, **kwargs):
50
+ return pixel_values.shape[0]
44
51
 
45
- batch_size = pixel_values.shape[0]
46
- outputs = []
47
- for i in range(batch_size):
48
- outputs.append(self.vision_tower.model[0](pixel_values[i : i + 1]))
52
+ def _prepare_inputs_for_iteration(self, index, common_inputs, pixel_values, **kwargs):
53
+ pixel_values_item = pixel_values[index : index + 1]
54
+ out_buffer = [tensor[index : index + 1] for tensor in kwargs["out"]]
55
+ return ([pixel_values_item], {"out": out_buffer})
49
56
 
50
- last_hidden_states = [output[0] for output in outputs]
51
- pooler_output = [output[1] for output in outputs]
57
+ def _process_outputs(self, outputs: list, **kwargs) -> "BaseModelOutputWithPooling":
58
+ output = kwargs["out"]
59
+ last_hidden_states = output[0]
60
+ pooler_output = output[1]
52
61
 
53
- # FIXME:: This can be optimized using out= API of rbln runtime.
54
- last_hidden_states = torch.cat(last_hidden_states, dim=0)
55
- pooler_output = torch.cat(pooler_output, dim=0)
56
-
57
- hidden_states = [output[2:] for output in outputs] # batch x (hidden x 1)
58
-
59
- hidden_states = tuple(
60
- torch.cat(tuple((hidden_states[n][i] for n in range(batch_size))), dim=0)
61
- for i in range(len(hidden_states[0]))
62
- ) # hidden x (batch,)
62
+ if not output[2:]:
63
+ hidden_states = None
64
+ else:
65
+ hidden_states = tuple(output[2:])
63
66
 
64
67
  return BaseModelOutputWithPooling(
65
68
  last_hidden_state=last_hidden_states,
@@ -67,38 +70,25 @@ class LoopVisionTower:
67
70
  hidden_states=hidden_states,
68
71
  )
69
72
 
70
- def __call__(self, *args: Any, **kwds: Any) -> Any:
71
- return self.forward(*args, **kwds)
72
-
73
- def __repr__(self) -> str:
74
- return repr(self.vision_tower)
75
-
76
73
 
77
- class LoopProjector:
78
- def __init__(self, multi_modal_projector) -> None:
79
- self.multi_modal_projector = multi_modal_projector
74
+ class LoopProjector(LoopProcessor):
75
+ def __init__(self, multi_modal_projector: "RBLNModel"):
76
+ super().__init__(model=multi_modal_projector)
80
77
 
81
- def forward(self, *args, **kwargs):
82
- # Loop instead of batch
83
- image_feature = args[0]
78
+ def _get_batch_size(self, image_feature, **kwargs):
79
+ return image_feature.shape[0]
84
80
 
85
- batch_size = image_feature.shape[0]
86
- outputs = []
87
- for i in range(batch_size):
88
- outputs.append(self.multi_modal_projector(image_feature[i : i + 1]))
81
+ def _prepare_inputs_for_iteration(self, index, common_inputs, image_feature, **kwargs):
82
+ image_feature_item = image_feature[index : index + 1]
83
+ out_buffer = [tensor[index : index + 1] for tensor in kwargs["out"]]
84
+ return ([image_feature_item], {"out": out_buffer})
89
85
 
90
- # FIXME:: This can be optimized using out= API of rbln runtime.
91
- outputs = torch.cat(outputs, dim=0)
92
- return outputs
86
+ def _process_outputs(self, outputs: list, **kwargs):
87
+ output = kwargs["out"]
88
+ return output[0]
93
89
 
94
- def __call__(self, *args: Any, **kwds: Any) -> Any:
95
- return self.forward(*args, **kwds)
96
90
 
97
- def __repr__(self) -> str:
98
- return repr(self.multi_modal_projector)
99
-
100
-
101
- class RBLNLlavaNextForConditionalGeneration(RBLNModel):
91
+ class RBLNLlavaNextForConditionalGeneration(RBLNModel, RBLNDecoderOnlyGenerationMixin):
102
92
  """
103
93
  RBLNLlavaNextForConditionalGeneration is a multi-modal model that combines vision and language processing capabilities,
104
94
  optimized for RBLN NPUs. It is designed for conditional generation tasks that involve both image and text inputs.
@@ -148,6 +138,23 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
148
138
  def can_generate(self):
149
139
  return True
150
140
 
141
+ @classmethod
142
+ def get_pytorch_model(cls, *args, **kwargs):
143
+ model = super().get_pytorch_model(*args, **kwargs)
144
+
145
+ with no_init_weights():
146
+ model_cls_name = model.model.language_model.__class__.__name__
147
+ causal_model_cls_name = model_cls_name.replace("Model", "ForCausalLM")
148
+ causal_model_cls = getattr(importlib.import_module("transformers"), causal_model_cls_name)
149
+ new_language_model = causal_model_cls(model.model.language_model.config)
150
+
151
+ new_language_model.lm_head = model.lm_head
152
+ new_language_model.model = model.model.language_model
153
+ model.model.language_model = new_language_model
154
+ model.lm_head = None
155
+ del model.lm_head
156
+ return model
157
+
151
158
  @classmethod
152
159
  def save_torch_artifacts(
153
160
  cls,
@@ -159,7 +166,7 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
159
166
  # If you are unavoidably running on a CPU rather than an RBLN device,
160
167
  # store the torch tensor, weight, etc. in this function.
161
168
  save_dict = {}
162
- save_dict["image_newline"] = model.image_newline
169
+ save_dict["image_newline"] = model.model.image_newline
163
170
  torch.save(save_dict, save_dir_path / subfolder / "torch_artifacts.pth")
164
171
 
165
172
  def __post_init__(self, **kwargs):
@@ -206,7 +213,11 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
206
213
  selected_image_feature_dim = num_positions
207
214
 
208
215
  input_info = [
209
- ("image_features", [rbln_config.batch_size, selected_image_feature_dim, feature_size], "float32")
216
+ (
217
+ "image_features",
218
+ [rbln_config.vision_tower.batch_size, selected_image_feature_dim, feature_size],
219
+ "float32",
220
+ )
210
221
  ]
211
222
  rbln_compile_config = RBLNCompileConfig(input_info=input_info)
212
223
  rbln_config.set_compile_cfgs([rbln_compile_config])
@@ -217,86 +228,62 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
217
228
  input_ids,
218
229
  inputs_embeds=None,
219
230
  pixel_values=None,
220
- image_sizes=None,
221
231
  attention_mask=None,
232
+ cache_position=None,
233
+ image_sizes=None,
222
234
  generate_idx=None,
223
235
  **kwargs,
224
236
  ):
225
- # Prepare HF generation
226
237
  is_prefill_phase = generate_idx is None
227
- batch_size = input_ids.shape[0]
228
-
229
- model_inputs = self.language_model.prepare_inputs_for_generation(
230
- input_ids=input_ids,
231
- inputs_embeds=inputs_embeds,
232
- generate_idx=generate_idx, # Not affect
233
- attention_mask=attention_mask,
234
- **kwargs,
235
- )
238
+ model_inputs = {}
236
239
 
237
240
  if is_prefill_phase:
238
- model_inputs["generate_idx"] = torch.zeros((batch_size, 1), dtype=torch.int32)
239
- model_inputs.update(
240
- {
241
- "pixel_values": pixel_values,
242
- "image_sizes": image_sizes,
243
- }
244
- )
241
+ generate_idx = attention_mask.sum(dim=-1, keepdim=True).int()
242
+ cache_position = None
243
+ pixel_values = pixel_values
244
+ model_inputs.update({"image_sizes": image_sizes})
245
+ else:
246
+ if inputs_embeds is not None:
247
+ raise NotImplementedError("Specifying inputs_embeds in decoder phase is not supported.")
245
248
 
246
- model_inputs["attention_mask"] = attention_mask
249
+ pixel_values = None
250
+ input_ids = input_ids[:, -1:]
251
+ cache_position = generate_idx
252
+ generate_idx = generate_idx + 1
253
+ model_inputs.update({"input_ids": input_ids})
254
+
255
+ if inputs_embeds is not None:
256
+ if self.rbln_config.use_inputs_embeds:
257
+ model_inputs.update({"inputs_embeds": inputs_embeds})
258
+ else:
259
+ raise ValueError(
260
+ "The specifying inputs_embeds is only supported when using a compiled RBLN model with 'rbln_use_inputs_embeds' set to True."
261
+ )
262
+ else:
263
+ model_inputs.update({"input_ids": input_ids})
264
+
265
+ model_inputs.update(
266
+ {
267
+ "attention_mask": attention_mask,
268
+ "pixel_values": pixel_values,
269
+ "cache_position": cache_position,
270
+ "generate_idx": generate_idx,
271
+ }
272
+ )
247
273
  return model_inputs
248
274
 
249
- def _update_model_kwargs_for_generation(
250
- self,
251
- outputs: RBLNDecoderOnlyOutput,
252
- model_kwargs: Dict[str, Any],
253
- **kwargs,
254
- ) -> Dict[str, Any]:
275
+ def _update_model_kwargs_for_generation(self, outputs, model_kwargs, is_encoder_decoder, **kwargs):
255
276
  # update generate_idx
256
277
  model_kwargs["generate_idx"] = outputs.generate_idx
257
-
258
278
  return model_kwargs
259
279
 
260
- def text_embedding(
280
+ def get_image_features(
261
281
  self,
262
- input_ids: torch.LongTensor,
263
- ) -> torch.Tensor:
264
- for_inputs_embeds_ids = input_ids.clone()
265
- for_inputs_embeds_ids[(input_ids == self.config.image_token_index)] = 0
266
- inputs_embeds = self.get_input_embeddings()(for_inputs_embeds_ids)
267
-
268
- return inputs_embeds
269
-
270
- def image_embedding(
271
- self,
272
- image_sizes: torch.Tensor,
273
282
  pixel_values: torch.FloatTensor,
274
- vision_feature_layer: int,
283
+ image_sizes: torch.Tensor,
284
+ vision_feature_layer: Union[int, List[int]],
275
285
  vision_feature_select_strategy: str,
276
286
  ):
277
- vision_feature_layer = (
278
- vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
279
- )
280
- vision_feature_select_strategy = (
281
- vision_feature_select_strategy
282
- if vision_feature_select_strategy is not None
283
- else self.config.vision_feature_select_strategy
284
- )
285
-
286
- """
287
- Obtains image last hidden states from the vision tower and apply multimodal projection.
288
-
289
- Args:
290
- pixel_values (torch.FloatTensor): The tensors corresponding to the input images
291
- whose shape is `(batch_size, num_patches, channels, height, width)`.
292
- image_sizes (torch.Tensor): Actual image size of each images (H, W).
293
- vision_feature_layer (int): The index of the layer to select the vision feature.
294
- vision_feature_select_strategy (str): The feature selection strategy used to select the vision feature from the vision backbone.
295
- Can be one of `"default"` or `"full"`
296
- Returns:
297
- image_features (List[torch.Tensor]): List of image feature tensor, each contains all the visual feature of all patches
298
- and are of shape `(num_patches, image_length, embed_dim)`).
299
- """
300
287
  # ! infer image_num_patches from image_sizes
301
288
  image_num_patches = [
302
289
  image_size_to_num_patches(
@@ -306,6 +293,26 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
306
293
  )
307
294
  for imsize in image_sizes
308
295
  ]
296
+
297
+ # prepare out buffer for pre-allocation
298
+ vision_out_size = [
299
+ pixel_values.shape[0] * pixel_values.shape[1],
300
+ (self.config.vision_config.image_size // self.config.vision_config.patch_size) ** 2 + 1,
301
+ self.config.vision_config.hidden_size,
302
+ ]
303
+ pooler_out_size = [pixel_values.shape[0] * pixel_values.shape[1], self.config.vision_config.hidden_size]
304
+ vision_out_buffer = []
305
+ for i in range(self.config.vision_config.num_hidden_layers + 2):
306
+ vision_out_buffer.append(torch.empty(size=vision_out_size, dtype=torch.float32, device="cpu"))
307
+ vision_out_buffer.insert(1, torch.empty(size=pooler_out_size, dtype=torch.float32, device="cpu"))
308
+
309
+ projector_out_size = [
310
+ pixel_values.shape[0] * pixel_values.shape[1],
311
+ (self.config.vision_config.image_size // self.config.vision_config.patch_size) ** 2,
312
+ self.config.text_config.hidden_size,
313
+ ]
314
+ projector_out_buffer = [torch.empty(size=projector_out_size, dtype=torch.float32, device="cpu")]
315
+
309
316
  if pixel_values.dim() == 5:
310
317
  # stacked if input is (batch_size, num_patches, num_channels, height, width)
311
318
  _pixel_values_list = [pix_val[:num_patch] for pix_val, num_patch in zip(pixel_values, image_num_patches)]
@@ -314,114 +321,25 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
314
321
  # otherwise has to be stacked from list of (num_patches, num_channels, height, width)
315
322
  raise ValueError(f"pixel_values of shape {pixel_values.shape}, expect to be of 4 or 5 dimensions")
316
323
 
317
- image_features = self.vision_tower(pixel_values, output_hidden_states=True)
318
- selected_image_feature = image_features.hidden_states[vision_feature_layer]
324
+ image_features = self.vision_tower(pixel_values, output_hidden_states=True, out=vision_out_buffer)
325
+ # If we have one vision feature layer, return the corresponding hidden states,
326
+ # otherwise, select the hidden states of each feature layer and concatenate them
327
+ if isinstance(vision_feature_layer, int):
328
+ selected_image_feature = image_features.hidden_states[vision_feature_layer]
329
+ else:
330
+ hs_pool = [image_features.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
331
+ selected_image_feature = torch.cat(hs_pool, dim=-1)
332
+
319
333
  if vision_feature_select_strategy == "default":
320
334
  selected_image_feature = selected_image_feature[:, 1:]
321
335
  elif vision_feature_select_strategy == "full":
322
336
  selected_image_feature = selected_image_feature
323
- image_features = self.multi_modal_projector(selected_image_feature)
324
- image_features = torch.split(image_features, image_num_patches, dim=0)
325
-
326
- # NOTE we only support multimodal_patch_merge_type == "spatial_unpad"
327
- image_features, feature_lens = self.pack_image_features(
328
- image_features,
329
- image_sizes,
330
- vision_feature_select_strategy=vision_feature_select_strategy,
331
- image_newline=self.image_newline,
332
- )
333
-
334
- return image_features, feature_lens
335
-
336
- def forward(
337
- self,
338
- input_ids: torch.LongTensor = None,
339
- attention_mask: torch.LongTensor = None,
340
- pixel_values: torch.FloatTensor = None,
341
- image_sizes: Optional[torch.LongTensor] = None,
342
- inputs_embeds: Optional[torch.FloatTensor] = None,
343
- vision_feature_layer: Optional[int] = None,
344
- vision_feature_select_strategy: Optional[str] = None,
345
- cache_position: torch.Tensor = None,
346
- generate_idx: Optional[torch.Tensor] = None,
347
- batch_idx: Optional[int] = None,
348
- **kwargs,
349
- ) -> Union[Tuple, RBLNDecoderOnlyOutput]:
350
- vision_feature_layer = (
351
- vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
352
- )
353
- vision_feature_select_strategy = (
354
- vision_feature_select_strategy
355
- if vision_feature_select_strategy is not None
356
- else self.config.vision_feature_select_strategy
357
- )
358
-
359
- if inputs_embeds is not None:
360
- raise NotImplementedError("Specifying inputs_embeds is not supported.")
361
- inputs_embeds = self.get_input_embeddings()(input_ids)
362
-
363
- if pixel_values is not None and pixel_values.size(0) > 0:
364
- image_features, _ = self.image_embedding(
365
- pixel_values=pixel_values,
366
- image_sizes=image_sizes,
367
- vision_feature_layer=vision_feature_layer,
368
- vision_feature_select_strategy=vision_feature_select_strategy,
369
- )
370
-
371
- n_image_tokens = (input_ids == self.config.image_token_index).sum().item()
372
- n_image_features = image_features.shape[0]
373
- if n_image_tokens != n_image_features:
374
- raise ValueError(
375
- f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
376
- )
377
- special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
378
- special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
379
- image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
380
- inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
381
-
382
- is_prefill_phase = not generate_idx.bool().all()
383
-
384
- if is_prefill_phase:
385
- logits = []
386
- batch_size = input_ids.shape[0]
387
- inputs_embeds = [inputs_embeds[i : i + 1, attention_mask[i].bool()] for i in range(batch_size)]
388
- for batch_idx in range(batch_size):
389
- generate_idx[batch_idx] = inputs_embeds[batch_idx].shape[-2]
390
- output = self.language_model.prefill_decoder(
391
- inputs_embeds=inputs_embeds[batch_idx],
392
- batch_idx=batch_idx,
393
- cache_position=torch.arange(
394
- 0,
395
- generate_idx[batch_idx].item(),
396
- dtype=torch.int32,
397
- ).unsqueeze(0),
398
- )
399
337
 
400
- logits.append(output.logits)
401
- logits = torch.cat(logits, dim=0)
402
- else:
403
- output = self.language_model.decoder(
404
- inputs_embeds=inputs_embeds,
405
- cache_position=cache_position,
406
- )
407
- logits = output.logits
408
- return RBLNDecoderOnlyOutput(logits=logits, generate_idx=generate_idx)
338
+ image_features = self.multi_modal_projector(selected_image_feature, out=projector_out_buffer)
339
+ image_features = torch.split(image_features, image_num_patches, dim=0)
340
+ return image_features
409
341
 
410
- # Almost copied from : https://github.com/huggingface/transformers/blob/6b550462139655d488d4c663086a63e98713c6b9/src/transformers/models/llava_next/modeling_llava_next.py
411
342
  def pack_image_features(self, image_features, image_sizes, vision_feature_select_strategy, image_newline=None):
412
- # Reshape, unpad and then pack each image_feature into a single image_features tensor containing all visual vectors.
413
-
414
- # Args:
415
- # image_features (List[torch.Tensor]): List of image feature tensor, each contains all the visual feature of all patches.
416
- # Its length is num_images, and each of shape is `(num_patches, image_length, embed_dim)`
417
- # image_sizes (torch.Tensor): Actual image size of each images (H, W).
418
- # vision_feature_select_strategy (str): The feature selection strategy used to select the vision feature from the vision backbone.
419
- # image_newline (torch.Tensor): New line embedding vector whose shape is `embed_dim`.
420
-
421
- # Returns:
422
- # image_features (torch.Tensor): A torch.Tensor of shape `(all_feat_len, embed_dim)`)
423
- # feature_lens (List[int]): A token length of each image in image_features
424
-
425
343
  new_image_features = []
426
344
  feature_lens = []
427
345
  for image_idx, image_feature in enumerate(image_features):
@@ -430,18 +348,22 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
430
348
  image_feature = image_feature[1:]
431
349
  height = width = self.config.vision_config.image_size // self.config.vision_config.patch_size
432
350
 
433
- if vision_feature_select_strategy == "default":
434
- expected_num_patches = height * width
435
- elif vision_feature_select_strategy == "full":
436
- expected_num_patches = height * width + 1
437
- if expected_num_patches != base_image_feature.shape[0]:
438
- raise ValueError("The number of patches is not consistent with the image size.")
439
-
440
351
  num_patch_height, num_patch_width = get_anyres_image_grid_shape(
441
352
  image_sizes[image_idx],
442
353
  self.config.image_grid_pinpoints,
443
354
  self.config.vision_config.image_size,
444
355
  )
356
+
357
+ if (
358
+ np.prod(image_feature.shape) % (num_patch_height * num_patch_width * height * width) != 0
359
+ and vision_feature_select_strategy == "default"
360
+ ):
361
+ logger.warning_once(
362
+ "Image feature shape does not line up with the provided patch size. "
363
+ "You may be using the `default` vision_feature_select_strategy with a"
364
+ " visual encoder that does not have CLS."
365
+ )
366
+
445
367
  image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
446
368
  image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
447
369
  image_feature = image_feature.flatten(1, 2).flatten(2, 3)
@@ -468,137 +390,106 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
468
390
  feature_lens = torch.tensor(feature_lens, dtype=torch.long, device=image_features.device)
469
391
  return image_features, feature_lens
470
392
 
393
+ def _preprocess_prefill(
394
+ self,
395
+ input_ids: torch.LongTensor = None,
396
+ pixel_values: torch.FloatTensor = None,
397
+ image_sizes: Optional[torch.LongTensor] = None,
398
+ inputs_embeds: Optional[torch.FloatTensor] = None,
399
+ vision_feature_layer: Optional[int] = None,
400
+ vision_feature_select_strategy: Optional[str] = None,
401
+ **kwargs,
402
+ ):
403
+ vision_feature_layer = (
404
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
405
+ )
471
406
 
472
- # Almost copied from : https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/llava_next/modeling_llava_next.py
473
- def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size):
474
- # Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
407
+ vision_feature_select_strategy = (
408
+ vision_feature_select_strategy
409
+ if vision_feature_select_strategy is not None
410
+ else self.config.vision_feature_select_strategy
411
+ )
475
412
 
476
- # Args:
477
- # image_size (tuple): The size of the input image in the format (width, height).
478
- # grid_pinpoints (list): A list containing possible resolutions.
479
- # Each item in the list should be a tuple or list of the form `(height, width)`.
480
- # patch_size (int): The size of each image patch.
413
+ if (input_ids is None) ^ (inputs_embeds is not None):
414
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
481
415
 
482
- # Returns:
483
- # tuple: The shape of the image patch grid in the format (width, height).
416
+ if pixel_values is not None and inputs_embeds is not None:
417
+ raise ValueError(
418
+ "You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
419
+ )
484
420
 
485
- if not isinstance(grid_pinpoints, list):
486
- raise TypeError("grid_pinpoints should be a list of tuples or lists")
421
+ if inputs_embeds is None:
422
+ inputs_embeds = self.get_input_embeddings()(input_ids)
487
423
 
488
- # ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate
489
- if not isinstance(image_size, (list, tuple)):
490
- if not isinstance(image_size, (torch.Tensor, np.ndarray)):
491
- raise TypeError(
492
- f"image_size invalid type: {type(image_size)} not valid, should be either list, tuple, np.ndarray or tensor"
424
+ if pixel_values is not None and pixel_values.size(0) > 0:
425
+ image_features = self.get_image_features(
426
+ pixel_values,
427
+ image_sizes,
428
+ vision_feature_layer=vision_feature_layer,
429
+ vision_feature_select_strategy=vision_feature_select_strategy,
493
430
  )
494
- image_size = image_size.tolist()
495
431
 
496
- height, width = select_best_resolution(image_size, grid_pinpoints)
497
- return height // patch_size, width // patch_size
432
+ # NOTE we only support multimodal_patch_merge_type == "spatial_unpad"
433
+ image_features, feature_lens = self.pack_image_features(
434
+ image_features,
435
+ image_sizes,
436
+ vision_feature_select_strategy=vision_feature_select_strategy,
437
+ image_newline=self.image_newline,
438
+ )
498
439
 
440
+ special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
441
+ special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
442
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
443
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
499
444
 
500
- # Almost copied from : https://github.com/huggingface/transformers/blob/1feebb5b4150882deabddd190a541f336f3be817/src/transformers/models/llava_next/modeling_llava_next.py#L115C1-L152C1
501
- def unpad_image(tensor, original_size):
502
- # Unpads a PyTorch tensor of a padded and resized image.
445
+ return inputs_embeds
503
446
 
504
- # Args:
505
- # tensor (torch.Tensor): The image tensor, assumed to be of shape (num_channels, height, width).
506
- # original_size (tuple): The original size of the image (height, width).
447
+ def forward(
448
+ self,
449
+ input_ids: torch.LongTensor = None,
450
+ attention_mask: torch.LongTensor = None,
451
+ pixel_values: torch.FloatTensor = None,
452
+ image_sizes: Optional[torch.LongTensor] = None,
453
+ inputs_embeds: Optional[torch.FloatTensor] = None,
454
+ cache_position: torch.Tensor = None,
455
+ generate_idx: Optional[torch.Tensor] = None,
456
+ return_dict: Optional[bool] = None,
457
+ **kwargs,
458
+ ) -> Union[Tuple, RBLNDecoderOnlyOutput]:
459
+ # Prefill
460
+ if cache_position is None:
461
+ inputs_embeds = self._preprocess_prefill(
462
+ input_ids=input_ids, inputs_embeds=inputs_embeds, pixel_values=pixel_values, image_sizes=image_sizes
463
+ )
464
+ logits = []
465
+ inputs = inputs_embeds if inputs_embeds is not None else input_ids
466
+ batch_size = inputs.shape[0]
507
467
 
508
- # Returns:
509
- # (torch.Tensor): The unpadded image tensor.
468
+ for b_idx in range(batch_size):
469
+ cache_position = torch.arange(0, generate_idx[b_idx].item(), dtype=torch.int32).unsqueeze(0)
470
+ output = self.language_model.prefill_decoder(
471
+ input_ids=inputs[b_idx : b_idx + 1] if inputs_embeds is None else None,
472
+ inputs_embeds=inputs[b_idx : b_idx + 1] if inputs_embeds is not None else None,
473
+ attention_mask=attention_mask[b_idx] if attention_mask is not None else None,
474
+ cache_position=cache_position,
475
+ batch_idx=b_idx,
476
+ )
477
+ logits.append(output.logits)
510
478
 
511
- if not isinstance(original_size, (list, tuple)):
512
- if not isinstance(original_size, (torch.Tensor, np.ndarray)):
513
- raise TypeError(
514
- f"image_size invalid type: {type(original_size)} not valid, should be either list, tuple, np.ndarray or tensor"
479
+ logits = torch.cat(logits, dim=0)
480
+
481
+ # Decoder
482
+ else:
483
+ logits = self.language_model.decoder(
484
+ input_ids=input_ids,
485
+ inputs_embeds=inputs_embeds,
486
+ cache_position=cache_position,
487
+ ).logits
488
+
489
+ if not return_dict:
490
+ return logits, generate_idx
491
+ else:
492
+ return RBLNDecoderOnlyOutput(
493
+ logits=logits,
494
+ generate_idx=generate_idx,
515
495
  )
516
- original_size = original_size.tolist()
517
- original_height, original_width = original_size
518
- current_height, current_width = tensor.shape[1:]
519
-
520
- original_aspect_ratio = original_width / original_height
521
- current_aspect_ratio = current_width / current_height
522
-
523
- if original_aspect_ratio > current_aspect_ratio:
524
- scale_factor = current_width / original_width
525
- new_height = int(round(original_height * scale_factor, 7))
526
- padding = (current_height - new_height) // 2
527
- unpadded_tensor = tensor[:, padding : current_height - padding, :]
528
- else:
529
- scale_factor = current_height / original_height
530
- new_width = int(round(original_width * scale_factor, 7))
531
- padding = (current_width - new_width) // 2
532
- unpadded_tensor = tensor[:, :, padding : current_width - padding]
533
-
534
- return unpadded_tensor
535
-
536
-
537
- # Almost copied from : https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/llava_next/modeling_llava_next.py
538
- def select_best_resolution(original_size: tuple, possible_resolutions: list) -> tuple:
539
- # Selects the best resolution from a list of possible resolutions based on the original size.
540
-
541
- # This is done by calculating the effective and wasted resolution for each possible resolution.
542
-
543
- # The best fit resolution is the one that maximizes the effective resolution and minimizes the wasted resolution.
544
-
545
- # Args:
546
- # original_size (tuple): The original size of the image in the format (height, width).
547
- # possible_resolutions (List(tuple)): A list of possible resolutions in the format [(height1, width1), (height2, width2), ...].
548
-
549
- # Returns:
550
- # (tuple): The best fit resolution in the format (height, width).
551
-
552
- original_height, original_width = original_size
553
- best_fit = None
554
- max_effective_resolution = 0
555
- min_wasted_resolution = float("inf")
556
-
557
- for height, width in possible_resolutions:
558
- scale = min(width / original_width, height / original_height)
559
- downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
560
- effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
561
- wasted_resolution = (width * height) - effective_resolution
562
-
563
- if effective_resolution > max_effective_resolution or (
564
- effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution
565
- ):
566
- max_effective_resolution = effective_resolution
567
- min_wasted_resolution = wasted_resolution
568
- best_fit = (height, width)
569
-
570
- return best_fit
571
-
572
-
573
- # Almost copied from : https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/llava_next/modeling_llava_next.py
574
- def image_size_to_num_patches(image_size, grid_pinpoints, patch_size: int):
575
- # Calculate the number of patches after the preprocessing for images of any resolution.
576
-
577
- # Args:
578
- # image_size (Union[torch.LongTensor, np.ndarray, Tuple[int, int]): The size of the input image in the format (height, width).
579
- # grid_pinpoints (list): A list containing possible resolutions.
580
- # Each item in the list should be a tuple or list of the form `(height, width)`.
581
- # patch_size (int): The size of each image patch.
582
-
583
- # Returns:
584
- # (int): the number of patches.
585
-
586
- if not isinstance(grid_pinpoints, list):
587
- raise TypeError("grid_pinpoints should be a list of tuples or lists")
588
-
589
- # ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate
590
- if not isinstance(image_size, (list, tuple)):
591
- if not isinstance(image_size, (torch.Tensor, np.ndarray)):
592
- raise TypeError(f"image_size invalid type {type(image_size)} with value {image_size}")
593
- image_size = image_size.tolist()
594
-
595
- best_resolution = select_best_resolution(image_size, grid_pinpoints)
596
- height, width = best_resolution
597
- num_patches = 0
598
- # consider change to ceil(height/patch_size)*ceil(width/patch_size) + 1
599
- for i in range(0, height, patch_size):
600
- for j in range(0, width, patch_size):
601
- num_patches += 1
602
- # add the base patch
603
- num_patches += 1
604
- return num_patches