optimum-rbln 0.1.9__py3-none-any.whl → 0.1.12__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.
Files changed (73) hide show
  1. optimum/rbln/__init__.py +47 -9
  2. optimum/rbln/__version__.py +1 -1
  3. optimum/rbln/diffusers/models/autoencoder_kl.py +36 -31
  4. optimum/rbln/diffusers/models/controlnet.py +53 -43
  5. optimum/rbln/diffusers/models/unet_2d_condition.py +40 -31
  6. optimum/rbln/diffusers/pipelines/controlnet/multicontrolnet.py +4 -0
  7. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet.py +28 -23
  8. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +28 -23
  9. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +28 -37
  10. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +30 -39
  11. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +24 -14
  12. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +24 -15
  13. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +26 -17
  14. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +26 -17
  15. optimum/rbln/modeling_alias.py +6 -11
  16. optimum/rbln/modeling_base.py +467 -261
  17. optimum/rbln/modeling_config.py +199 -73
  18. optimum/rbln/transformers/__init__.py +43 -1
  19. optimum/rbln/transformers/models/__init__.py +23 -1
  20. optimum/rbln/transformers/models/auto/__init__.py +14 -0
  21. optimum/rbln/transformers/models/auto/auto_factory.py +84 -0
  22. optimum/rbln/transformers/models/auto/modeling_auto.py +95 -0
  23. optimum/rbln/transformers/models/bart/__init__.py +1 -0
  24. optimum/rbln/transformers/models/bart/bart_architecture.py +203 -58
  25. optimum/rbln/transformers/models/bart/modeling_bart.py +125 -0
  26. optimum/rbln/transformers/models/bert/__init__.py +24 -0
  27. optimum/rbln/transformers/models/bert/modeling_bert.py +101 -0
  28. optimum/rbln/transformers/models/clip/__init__.py +1 -1
  29. optimum/rbln/transformers/models/clip/modeling_clip.py +127 -26
  30. optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py +28 -4
  31. optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py +409 -150
  32. optimum/rbln/transformers/models/dpt/modeling_dpt.py +21 -8
  33. optimum/rbln/transformers/models/exaone/__init__.py +32 -0
  34. optimum/rbln/transformers/models/exaone/exaone_architecture.py +72 -0
  35. optimum/rbln/transformers/models/exaone/hf_hub_cached/configuration_exaone.py +181 -0
  36. optimum/rbln/transformers/models/exaone/hf_hub_cached/modeling_exaone.py +1725 -0
  37. optimum/rbln/transformers/models/exaone/modeling_exaone.py +78 -0
  38. optimum/rbln/transformers/models/gemma/modeling_gemma.py +1 -1
  39. optimum/rbln/transformers/models/gpt2/gpt2_architecture.py +4 -1
  40. optimum/rbln/transformers/models/gpt2/modeling_gpt2.py +1 -1
  41. optimum/rbln/transformers/models/llama/modeling_llama.py +1 -1
  42. optimum/rbln/transformers/models/llava_next/__init__.py +24 -0
  43. optimum/rbln/transformers/models/llava_next/modeling_llava_next.py +662 -0
  44. optimum/rbln/transformers/models/midm/midm_architecture.py +5 -1
  45. optimum/rbln/transformers/models/midm/modeling_midm.py +6 -1
  46. optimum/rbln/transformers/models/mistral/modeling_mistral.py +1 -1
  47. optimum/rbln/transformers/models/phi/__init__.py +24 -0
  48. optimum/rbln/transformers/models/phi/modeling_phi.py +69 -0
  49. optimum/rbln/transformers/models/phi/phi_architecture.py +406 -0
  50. optimum/rbln/transformers/models/qwen2/__init__.py +24 -0
  51. optimum/rbln/transformers/models/qwen2/modeling_qwen2.py +67 -0
  52. optimum/rbln/transformers/models/qwen2/qwen2_architecture.py +29 -0
  53. optimum/rbln/transformers/models/seq2seq/__init__.py +24 -0
  54. optimum/rbln/{modeling_seq2seq.py → transformers/models/seq2seq/modeling_seq2seq.py} +198 -168
  55. optimum/rbln/transformers/models/t5/__init__.py +1 -0
  56. optimum/rbln/transformers/models/t5/modeling_t5.py +55 -0
  57. optimum/rbln/transformers/models/t5/t5_architecture.py +122 -47
  58. optimum/rbln/transformers/models/wav2vec2/modeling_wav2vec2.py +17 -12
  59. optimum/rbln/transformers/models/whisper/generation_whisper.py +68 -0
  60. optimum/rbln/transformers/models/whisper/modeling_whisper.py +172 -111
  61. optimum/rbln/transformers/models/whisper/whisper_architecture.py +44 -17
  62. optimum/rbln/transformers/models/xlm_roberta/modeling_xlm_roberta.py +18 -16
  63. optimum/rbln/transformers/utils/rbln_quantization.py +48 -60
  64. optimum/rbln/utils/import_utils.py +50 -1
  65. optimum/rbln/utils/logging.py +82 -0
  66. optimum/rbln/utils/runtime_utils.py +33 -0
  67. optimum/rbln/utils/timer_utils.py +43 -0
  68. {optimum_rbln-0.1.9.dist-info → optimum_rbln-0.1.12.dist-info}/METADATA +9 -7
  69. optimum_rbln-0.1.12.dist-info/RECORD +103 -0
  70. {optimum_rbln-0.1.9.dist-info → optimum_rbln-0.1.12.dist-info}/WHEEL +1 -1
  71. optimum_rbln-0.1.12.dist-info/entry_points.txt +4 -0
  72. optimum_rbln-0.1.9.dist-info/RECORD +0 -78
  73. {optimum_rbln-0.1.9.dist-info → optimum_rbln-0.1.12.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,662 @@
1
+ # Copyright 2024 Rebellions Inc.
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
+ # Portions of this software are licensed under the Apache License,
16
+ # Version 2.0. See the NOTICE file distributed with this work for
17
+ # additional information regarding copyright ownership.
18
+
19
+ # All other portions of this software, including proprietary code,
20
+ # are the intellectual property of Rebellions Inc. and may not be
21
+ # copied, modified, or distributed without prior written permission
22
+ # from Rebellions Inc.
23
+ import inspect
24
+ import logging
25
+ from pathlib import Path
26
+ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
27
+
28
+ import numpy as np
29
+ import torch
30
+ from transformers import (
31
+ AutoModelForVision2Seq,
32
+ LlavaNextForConditionalGeneration,
33
+ PretrainedConfig,
34
+ PreTrainedModel,
35
+ )
36
+ from transformers.modeling_outputs import BaseModelOutputWithPooling
37
+ from transformers.models.llava_next.modeling_llava_next import LlavaNextCausalLMOutputWithPast
38
+
39
+ from ....modeling_base import RBLNModel
40
+ from ....modeling_config import RBLNCompileConfig, RBLNConfig
41
+ from ..decoderonly.modeling_decoderonly import RBLNDecoderOnlyOutput
42
+
43
+
44
+ logger = logging.getLogger(__name__)
45
+
46
+ if TYPE_CHECKING:
47
+ from transformers import (
48
+ AutoFeatureExtractor,
49
+ AutoProcessor,
50
+ AutoTokenizer,
51
+ PretrainedConfig,
52
+ )
53
+
54
+
55
+ class LoopVisionTower:
56
+ def __init__(self, vision_tower: RBLNModel) -> None:
57
+ self.vision_tower = vision_tower
58
+
59
+ def forward(self, *args, **kwargs):
60
+ # Loop instead of batch
61
+ # shape of pixel_values : [batch, num_patches, num_channel, height, width]
62
+ pixel_values = args[0]
63
+
64
+ batch_size = pixel_values.shape[0]
65
+ outputs = []
66
+ for i in range(batch_size):
67
+ outputs.append(self.vision_tower.model[0](pixel_values[i : i + 1]))
68
+
69
+ last_hidden_states = [output[0] for output in outputs]
70
+ pooler_output = [output[1] for output in outputs]
71
+
72
+ # FIXME:: This can be optimized using out= API of rbln runtime.
73
+ last_hidden_states = torch.cat(last_hidden_states, dim=0)
74
+ pooler_output = torch.cat(pooler_output, dim=0)
75
+
76
+ hidden_states = [output[2:] for output in outputs] # batch x (hidden x 1)
77
+
78
+ hidden_states = tuple(
79
+ torch.cat(tuple((hidden_states[n][i] for n in range(batch_size))), dim=0)
80
+ for i in range(len(hidden_states[0]))
81
+ ) # hidden x (batch,)
82
+
83
+ return BaseModelOutputWithPooling(
84
+ last_hidden_state=last_hidden_states,
85
+ pooler_output=pooler_output,
86
+ hidden_states=hidden_states,
87
+ )
88
+
89
+ def __call__(self, *args: Any, **kwds: Any) -> Any:
90
+ return self.forward(*args, **kwds)
91
+
92
+ def __repr__(self) -> str:
93
+ return repr(self.vision_tower)
94
+
95
+
96
+ class LoopProjector:
97
+ def __init__(self, multi_modal_projector) -> None:
98
+ self.multi_modal_projector = multi_modal_projector
99
+
100
+ def forward(self, *args, **kwargs):
101
+ # Loop instead of batch
102
+ image_feature = args[0]
103
+
104
+ batch_size = image_feature.shape[0]
105
+ outputs = []
106
+ for i in range(batch_size):
107
+ outputs.append(self.multi_modal_projector(image_feature[i : i + 1]))
108
+
109
+ # FIXME:: This can be optimized using out= API of rbln runtime.
110
+ outputs = torch.cat(outputs, dim=0)
111
+ return outputs
112
+
113
+ def __call__(self, *args: Any, **kwds: Any) -> Any:
114
+ return self.forward(*args, **kwds)
115
+
116
+ def __repr__(self) -> str:
117
+ return repr(self.multi_modal_projector)
118
+
119
+
120
+ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
121
+ auto_model_class = AutoModelForVision2Seq
122
+ _rbln_submodules = [
123
+ {"name": "vision_tower"},
124
+ {"name": "language_model"},
125
+ ]
126
+
127
+ def __getattr__(self, __name: str) -> Any:
128
+ def redirect(func):
129
+ return lambda *pargs, **kwargs: func(self, *pargs, **kwargs)
130
+
131
+ val = getattr(LlavaNextForConditionalGeneration, __name)
132
+
133
+ if isinstance(val, Callable) and "self" in set(inspect.signature(val).parameters):
134
+ return redirect(val)
135
+ return val
136
+
137
+ def can_generate(self):
138
+ return True
139
+
140
+ @classmethod
141
+ def save_torch_artifacts(
142
+ cls,
143
+ model: "LlavaNextForConditionalGeneration",
144
+ save_dir_path: Path,
145
+ subfolder: str,
146
+ rbln_config: RBLNConfig,
147
+ ):
148
+ """
149
+ If you are unavoidably running on a CPU rather than an RBLN device,
150
+ store the torch tensor, weight, etc. in this function.
151
+ """
152
+ save_dict = {}
153
+ save_dict["image_newline"] = model.image_newline
154
+ torch.save(save_dict, save_dir_path / subfolder / "torch_artifacts.pth")
155
+
156
+ def __post_init__(self, **kwargs):
157
+ self.vision_tower = LoopVisionTower(self.rbln_submodules[0])
158
+ self.language_model = self.rbln_submodules[1]
159
+ self.multi_modal_projector = LoopProjector(self.model[0])
160
+
161
+ artifacts = torch.load(self.model_save_dir / self.subfolder / "torch_artifacts.pth", weights_only=False)
162
+ self.image_newline = artifacts["image_newline"]
163
+
164
+ # Copied from the original class
165
+ self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
166
+ self._padding_side = "left" # set it to left by default, user can use setter to change padding_sides
167
+ return super().__post_init__(**kwargs)
168
+
169
+ @classmethod
170
+ def get_pytorch_model(
171
+ cls,
172
+ model_id: str,
173
+ *args,
174
+ rbln_kwargs: Optional[Dict[str, Any]] = None,
175
+ **kwargs,
176
+ ) -> "PreTrainedModel":
177
+ # Optimum's TasksManager does not handle Llava.
178
+ kwargs = cls.update_kwargs(kwargs)
179
+ model = LlavaNextForConditionalGeneration.from_pretrained(model_id, *args, **kwargs)
180
+ return model
181
+
182
+ def get_input_embeddings(self):
183
+ return self.language_model.get_input_embeddings()
184
+
185
+ @classmethod
186
+ def wrap_model_if_needed(cls, model: "PreTrainedModel", rbln_config: RBLNConfig):
187
+ return model.multi_modal_projector
188
+
189
+ @classmethod
190
+ def _get_rbln_config(
191
+ cls,
192
+ preprocessors: Optional[Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"]],
193
+ model_config: Optional["PretrainedConfig"] = None,
194
+ rbln_kwargs={},
195
+ ) -> RBLNConfig:
196
+ vision_feature_select_strategy = rbln_kwargs.get("vision_feature_select_strategy", None)
197
+
198
+ # 1. Multi-modal projection layer
199
+ batch_size = rbln_kwargs.get("rbln_batch_size", None)
200
+ if batch_size is None:
201
+ batch_size = 1
202
+
203
+ feature_size = model_config.vision_config.hidden_size
204
+
205
+ # See forward function to see more details.
206
+ vision_feature_select_strategy = (
207
+ vision_feature_select_strategy
208
+ if vision_feature_select_strategy is not None
209
+ else model_config.vision_feature_select_strategy
210
+ )
211
+
212
+ # Calculating `num_positions` : See CLIPVisionEmbeddings of transformers for more details.
213
+ num_positions = (model_config.vision_config.image_size // model_config.vision_config.patch_size) ** 2 + 1
214
+ if vision_feature_select_strategy == "default":
215
+ selected_image_feature_dim = num_positions - 1
216
+ else:
217
+ selected_image_feature_dim = num_positions
218
+
219
+ input_info = [("image_features", [batch_size, selected_image_feature_dim, feature_size], "float32")]
220
+ rbln_compile_config = RBLNCompileConfig(input_info=input_info)
221
+ rbln_config = RBLNConfig(rbln_cls=cls.__name__, compile_cfgs=[rbln_compile_config], rbln_kwargs=rbln_kwargs)
222
+ return rbln_config
223
+
224
+ def prepare_inputs_for_generation(
225
+ self,
226
+ input_ids,
227
+ inputs_embeds=None,
228
+ pixel_values=None,
229
+ image_sizes=None,
230
+ attention_mask=None,
231
+ generate_idx=None,
232
+ **kwargs,
233
+ ):
234
+ # Prepare HF generation
235
+ is_prefill_phase = generate_idx is None
236
+ batch_size = input_ids.shape[0]
237
+
238
+ model_inputs = self.language_model.prepare_inputs_for_generation(
239
+ input_ids=input_ids,
240
+ inputs_embeds=inputs_embeds,
241
+ generate_idx=generate_idx, # Not affect
242
+ attention_mask=attention_mask,
243
+ **kwargs,
244
+ )
245
+
246
+ if is_prefill_phase:
247
+ model_inputs["generate_idx"] = torch.zeros((batch_size, 1), dtype=torch.int32)
248
+
249
+ model_inputs.update(
250
+ {
251
+ "pixel_values": pixel_values,
252
+ "image_sizes": image_sizes,
253
+ "attention_mask": attention_mask,
254
+ }
255
+ )
256
+ return model_inputs
257
+
258
+ def _update_model_kwargs_for_generation(
259
+ self,
260
+ outputs: RBLNDecoderOnlyOutput,
261
+ model_kwargs: Dict[str, Any],
262
+ **kwargs,
263
+ ) -> Dict[str, Any]:
264
+ # update generate_idx
265
+ model_kwargs["generate_idx"] = outputs.generate_idx
266
+
267
+ return model_kwargs
268
+
269
+ def text_embedding(
270
+ self,
271
+ input_ids: torch.LongTensor,
272
+ ) -> torch.Tensor:
273
+ for_inputs_embeds_ids = input_ids.clone()
274
+ for_inputs_embeds_ids[(input_ids == self.config.image_token_index)] = 0
275
+ inputs_embeds = self.get_input_embeddings()(for_inputs_embeds_ids)
276
+
277
+ return inputs_embeds
278
+
279
+ def image_embedding(
280
+ self,
281
+ image_sizes: torch.LongTensor,
282
+ pixel_values: torch.FloatTensor,
283
+ vision_feature_layer: int,
284
+ vision_feature_select_strategy: str,
285
+ ) -> torch.Tensor:
286
+ vision_feature_layer = (
287
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
288
+ )
289
+ vision_feature_select_strategy = (
290
+ vision_feature_select_strategy
291
+ if vision_feature_select_strategy is not None
292
+ else self.config.vision_feature_select_strategy
293
+ )
294
+
295
+ # ! infer image_num_patches from image_sizes
296
+ image_num_patches = [
297
+ image_size_to_num_patches(
298
+ image_size=imsize,
299
+ grid_pinpoints=self.config.image_grid_pinpoints,
300
+ patch_size=self.config.vision_config.image_size,
301
+ )
302
+ for imsize in image_sizes
303
+ ]
304
+
305
+ # figure out if pixel_values is concatenated or stacked
306
+ if pixel_values.dim() == 5:
307
+ # stacking when input is (batch_size, num_patches, num_channels, height, width)
308
+ _pixel_values_list = [pix_val[:num_patch] for pix_val, num_patch in zip(pixel_values, image_num_patches)]
309
+ pixel_values = torch.cat(_pixel_values_list, dim=0)
310
+ elif pixel_values.dim() != 4:
311
+ # otherwise has to be stacked from list of (num_patches, num_channels, height, width)
312
+ raise ValueError(f"pixel_values of shape {pixel_values.shape}, expect to be of 4 or 5 dimensions")
313
+
314
+ image_features = self.vision_tower(pixel_values, output_hidden_states=True)
315
+ selected_image_feature = image_features.hidden_states[vision_feature_layer]
316
+
317
+ if vision_feature_select_strategy == "default":
318
+ selected_image_feature = selected_image_feature[:, 1:]
319
+ elif vision_feature_select_strategy == "full":
320
+ selected_image_feature = selected_image_feature
321
+
322
+ image_features = self.multi_modal_projector(selected_image_feature)
323
+ image_features = torch.split(image_features, image_num_patches, dim=0)
324
+
325
+ # NOTE we only support multimodal_patch_merge_type == "spatial_unpad"
326
+ image_features, feature_lens = self.pack_image_features(
327
+ image_features,
328
+ image_sizes,
329
+ image_newline=self.image_newline,
330
+ )
331
+
332
+ return image_features, feature_lens
333
+
334
+ def forward(
335
+ self,
336
+ input_ids: torch.LongTensor = None,
337
+ attention_mask: torch.LongTensor = None,
338
+ pixel_values: torch.FloatTensor = None,
339
+ image_sizes: Optional[torch.LongTensor] = None,
340
+ inputs_embeds: Optional[torch.FloatTensor] = None,
341
+ vision_feature_layer: Optional[int] = None,
342
+ vision_feature_select_strategy: Optional[str] = None,
343
+ cache_position: torch.Tensor = None,
344
+ generate_idx: Optional[torch.Tensor] = None,
345
+ **kwargs,
346
+ ) -> Union[Tuple, LlavaNextCausalLMOutputWithPast]:
347
+ if inputs_embeds is not None:
348
+ raise NotImplementedError("Specifying inputs_embeds is not supported.")
349
+
350
+ is_prefill_phase = not generate_idx.bool().all()
351
+
352
+ if is_prefill_phase:
353
+ # Get the number of images in the prompt
354
+ special_image_token_masks = [input_id == self.config.image_token_index for input_id in input_ids]
355
+ num_special_image_tokens = [torch.sum(mask, dim=-1) for mask in special_image_token_masks]
356
+
357
+ # Split images for each prompt
358
+ if pixel_values is not None and pixel_values.size(0) > 0:
359
+ pixel_values = pixel_values.split(num_special_image_tokens, dim=0)
360
+ image_sizes = image_sizes.split(num_special_image_tokens, dim=0)
361
+
362
+ logits = []
363
+ for b_idx in range(input_ids.shape[0]):
364
+ # Get text_embeds from input_id
365
+ input_id = input_ids[b_idx : b_idx + 1, attention_mask[b_idx].bool()]
366
+ inputs_embed = self.text_embedding(input_id)
367
+
368
+ # If any images in the prompt, get image_embeds and merge with text
369
+ if num_special_image_tokens[b_idx] > 0:
370
+ image_features, feature_lens = self.image_embedding(
371
+ image_sizes[b_idx], pixel_values[b_idx], vision_feature_layer, vision_feature_select_strategy
372
+ )
373
+ inputs_embed, _, _, _, _ = self._merge_input_ids_with_image_features(
374
+ image_features,
375
+ feature_lens,
376
+ inputs_embed.to(image_features.dtype),
377
+ input_id,
378
+ torch.ones_like(input_id, dtype=torch.long),
379
+ )
380
+
381
+ # Update generate_idx according to inputs_embed
382
+ generate_idx[b_idx] = inputs_embed.shape[1]
383
+
384
+ logit = self.language_model._forward_prefill(
385
+ inputs_embeds=inputs_embed,
386
+ batch_idx=b_idx,
387
+ cache_position=torch.arange(0, generate_idx[b_idx].item(), dtype=torch.int32).unsqueeze(0),
388
+ )
389
+
390
+ logits.append(logit)
391
+
392
+ logits = torch.cat(logits, dim=0)
393
+ outputs = RBLNDecoderOnlyOutput(logits=logits, generate_idx=generate_idx)
394
+
395
+ else:
396
+ inputs_embeds = self.text_embedding(input_ids)
397
+
398
+ outputs: RBLNDecoderOnlyOutput = self.language_model(
399
+ inputs_embeds=inputs_embeds,
400
+ cache_position=cache_position,
401
+ generate_idx=generate_idx,
402
+ )
403
+
404
+ return outputs
405
+
406
+ def vllm_forward(
407
+ self,
408
+ input_ids: torch.LongTensor = None,
409
+ pixel_values: torch.FloatTensor = None,
410
+ image_sizes: Optional[torch.LongTensor] = None,
411
+ inputs_embeds: Optional[torch.FloatTensor] = None,
412
+ vision_feature_layer: Optional[int] = None,
413
+ vision_feature_select_strategy: Optional[str] = None,
414
+ cache_position: Union[List[torch.Tensor], torch.Tensor] = None, # vllm keyword argument
415
+ batch_idx: Optional[int] = None,
416
+ **kwargs,
417
+ ) -> Union[Tuple, LlavaNextCausalLMOutputWithPast]:
418
+ is_prefill = cache_position.shape[-1] > 1
419
+
420
+ if inputs_embeds is not None:
421
+ raise NotImplementedError("Specifying inputs_embeds is not supported.")
422
+
423
+ if is_prefill:
424
+ # Get text_embeds
425
+ inputs_embeds = self.text_embedding(input_ids)
426
+
427
+ # If any images in the prompt, get image_embeds and merge with text
428
+ if pixel_values is not None and input_ids.shape[1] != 1 and pixel_values.size(0) > 0:
429
+ image_features, _ = self.image_embedding(
430
+ image_sizes, pixel_values, vision_feature_layer, vision_feature_select_strategy
431
+ )
432
+
433
+ def merge_vllm_multimodal_embeddings(
434
+ input_ids: torch.Tensor,
435
+ inputs_embeds: torch.Tensor,
436
+ multimodal_embeddings: torch.Tensor,
437
+ placeholder_token_id: int,
438
+ ) -> torch.Tensor:
439
+ mask = input_ids == placeholder_token_id
440
+ num_expected_tokens = mask.sum().item()
441
+
442
+ if multimodal_embeddings.shape[0] != num_expected_tokens:
443
+ raise ValueError(
444
+ f"Attempted to assign {inputs_embeds[mask].shape} = {multimodal_embeddings.shape} "
445
+ f"multimodal tokens to {num_expected_tokens} placeholders"
446
+ )
447
+
448
+ inputs_embeds[mask] = multimodal_embeddings
449
+ return inputs_embeds
450
+
451
+ inputs_embeds = merge_vllm_multimodal_embeddings(
452
+ input_ids, inputs_embeds, image_features, self.config.image_token_index
453
+ )
454
+
455
+ else:
456
+ inputs_embeds = self.text_embedding(input_ids=input_ids)
457
+
458
+ outputs: RBLNDecoderOnlyOutput = self.language_model.vllm_forward(
459
+ inputs_embeds=inputs_embeds,
460
+ batch_idx=batch_idx,
461
+ cache_position=cache_position,
462
+ )
463
+
464
+ return outputs
465
+
466
+ # Almost copied from : https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/llava_next/modeling_llava_next.py
467
+ def pack_image_features(self, image_features, image_sizes, image_newline=None):
468
+ """
469
+ Reshape, unpad and then pack each image_feature into a single image_features tensor containing all visual vectors.
470
+
471
+ Args:
472
+ image_features (`List[torch.Tensor]` of length num_images, each of shape `(num_patches, image_length, embed_dim)`)
473
+ List of image feature tensor, each contains all the visual feature of all patches.
474
+ image_sizes (`torch.Tensor` of shape `(num_images, 2)`)
475
+ Actual image size of each images (H, W).
476
+ image_newline (`torch.Tensor` of shape `(embed_dim)`)
477
+ New line embedding vector.
478
+ Returns:
479
+ image_features (`torch.Tensor` of shape `(all_feat_len, embed_dim)`)
480
+ feature_lens (`List[int]`)
481
+ token length of each image in image_features
482
+ """
483
+ new_image_features = []
484
+ feature_lens = []
485
+ for image_idx, image_feature in enumerate(image_features):
486
+ if image_feature.shape[0] > 1:
487
+ base_image_feature = image_feature[0]
488
+ image_feature = image_feature[1:]
489
+ height = width = self.config.vision_config.image_size // self.config.vision_config.patch_size
490
+ if height * width != base_image_feature.shape[0]:
491
+ raise ValueError("The number of patches is not consistent with the image size.")
492
+ num_patch_width, num_patch_height = get_anyres_image_grid_shape(
493
+ image_sizes[image_idx],
494
+ self.config.image_grid_pinpoints,
495
+ self.config.vision_config.image_size,
496
+ )
497
+ image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
498
+ image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
499
+ image_feature = image_feature.flatten(1, 2).flatten(2, 3)
500
+ image_feature = unpad_image(image_feature, image_sizes[image_idx])
501
+ if image_newline is not None:
502
+ image_feature = torch.cat(
503
+ (
504
+ image_feature,
505
+ image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.dtype),
506
+ ),
507
+ dim=-1,
508
+ )
509
+ image_feature = image_feature.flatten(1, 2).transpose(0, 1)
510
+ image_feature = torch.cat((base_image_feature, image_feature), dim=0)
511
+ else:
512
+ image_feature = image_feature[0]
513
+ if image_newline is not None:
514
+ image_feature = torch.cat((image_feature, image_newline[None].to(image_feature)), dim=0)
515
+ new_image_features.append(image_feature)
516
+ feature_lens.append(image_feature.size(0))
517
+ image_features = torch.cat(new_image_features, dim=0)
518
+ feature_lens = torch.tensor(feature_lens, dtype=torch.long, device=image_features.device)
519
+ return image_features, feature_lens
520
+
521
+
522
+ # Almost copied from : https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/llava_next/modeling_llava_next.py
523
+ def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size):
524
+ """
525
+ Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
526
+
527
+ Args:
528
+ image_size (`tuple`):
529
+ The size of the input image in the format (width, height).
530
+ grid_pinpoints (`List`):
531
+ A list containing possible resolutions. Each item in the list should be a tuple or list
532
+ of the form `(height, width)`.
533
+ patch_size (`int`):
534
+ The size of each image patch.
535
+
536
+ Returns:
537
+ tuple: The shape of the image patch grid in the format (width, height).
538
+ """
539
+ if not isinstance(grid_pinpoints, list):
540
+ raise TypeError("grid_pinpoints should be a list of tuples or lists")
541
+
542
+ # ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate
543
+ if not isinstance(image_size, (list, tuple)):
544
+ if not isinstance(image_size, (torch.Tensor, np.ndarray)):
545
+ raise TypeError(
546
+ f"image_size invalid type: {type(image_size)} not valid, should be either list, tuple, np.ndarray or tensor"
547
+ )
548
+ image_size = image_size.tolist()
549
+
550
+ height, width = select_best_resolution(image_size, grid_pinpoints)
551
+ return height // patch_size, width // patch_size
552
+
553
+
554
+ # Almost copied from : https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/llava_next/modeling_llava_next.py
555
+ def unpad_image(tensor, original_size):
556
+ """
557
+ Unpads a PyTorch tensor of a padded and resized image.
558
+
559
+ Args:
560
+ tensor (`torch.Tensor`):
561
+ The image tensor, assumed to be of shape (num_channels, height, width).
562
+ original_size (`tuple`):
563
+ The original size of the image (height, width).
564
+
565
+ Returns:
566
+ `torch.Tensor`: The unpadded image tensor.
567
+ """
568
+ original_height, original_width = original_size
569
+ current_height, current_width = tensor.shape[1:]
570
+
571
+ original_aspect_ratio = original_width / original_height
572
+ current_aspect_ratio = current_width / current_height
573
+
574
+ if original_aspect_ratio > current_aspect_ratio:
575
+ scale_factor = current_width / original_width
576
+ new_height = int(original_height * scale_factor)
577
+ padding = (current_height - new_height) // 2
578
+ unpadded_tensor = tensor[:, padding : current_height - padding, :]
579
+ else:
580
+ scale_factor = current_height / original_height
581
+ new_width = int(original_width * scale_factor)
582
+ padding = (current_width - new_width) // 2
583
+ unpadded_tensor = tensor[:, :, padding : current_width - padding]
584
+
585
+ return unpadded_tensor
586
+
587
+
588
+ # Almost copied from : https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/llava_next/modeling_llava_next.py
589
+ def select_best_resolution(original_size: tuple, possible_resolutions: list) -> tuple:
590
+ """
591
+ Selects the best resolution from a list of possible resolutions based on the original size.
592
+
593
+ This is done by calculating the effective and wasted resolution for each possible resolution.
594
+
595
+ The best fit resolution is the one that maximizes the effective resolution and minimizes the wasted resolution.
596
+
597
+ Args:
598
+ original_size (tuple):
599
+ The original size of the image in the format (height, width).
600
+ possible_resolutions (list):
601
+ A list of possible resolutions in the format [(height1, width1), (height2, width2), ...].
602
+
603
+ Returns:
604
+ tuple: The best fit resolution in the format (height, width).
605
+ """
606
+ original_height, original_width = original_size
607
+ best_fit = None
608
+ max_effective_resolution = 0
609
+ min_wasted_resolution = float("inf")
610
+
611
+ for height, width in possible_resolutions:
612
+ scale = min(width / original_width, height / original_height)
613
+ downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
614
+ effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
615
+ wasted_resolution = (width * height) - effective_resolution
616
+
617
+ if effective_resolution > max_effective_resolution or (
618
+ effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution
619
+ ):
620
+ max_effective_resolution = effective_resolution
621
+ min_wasted_resolution = wasted_resolution
622
+ best_fit = (height, width)
623
+
624
+ return best_fit
625
+
626
+
627
+ # Almost copied from : https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/llava_next/modeling_llava_next.py
628
+ def image_size_to_num_patches(image_size, grid_pinpoints, patch_size: int):
629
+ """
630
+ Calculate the number of patches after the preprocessing for images of any resolution.
631
+
632
+ Args:
633
+ image_size (`Union[torch.LongTensor, np.ndarray, Tuple[int, int]):
634
+ The size of the input image in the format (height, width). ?
635
+ grid_pinpoints (`List`):
636
+ A list containing possible resolutions. Each item in the list should be a tuple or list
637
+ of the form `(height, width)`.
638
+ patch_size (`int`):
639
+ The size of each image patch.
640
+
641
+ Returns:
642
+ int: the number of patches
643
+ """
644
+ if not isinstance(grid_pinpoints, list):
645
+ raise TypeError("grid_pinpoints should be a list of tuples or lists")
646
+
647
+ # ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate
648
+ if not isinstance(image_size, (list, tuple)):
649
+ if not isinstance(image_size, (torch.Tensor, np.ndarray)):
650
+ raise TypeError(f"image_size invalid type {type(image_size)} with value {image_size}")
651
+ image_size = image_size.tolist()
652
+
653
+ best_resolution = select_best_resolution(image_size, grid_pinpoints)
654
+ height, width = best_resolution
655
+ num_patches = 0
656
+ # consider change to ceil(height/patch_size)*ceil(width/patch_size) + 1
657
+ for i in range(0, height, patch_size):
658
+ for j in range(0, width, patch_size):
659
+ num_patches += 1
660
+ # add the base patch
661
+ num_patches += 1
662
+ return num_patches
@@ -82,6 +82,7 @@ class MidmLMHeadModelWrapper(torch.nn.Module):
82
82
  attention_mask: torch.Tensor,
83
83
  cache_position: torch.LongTensor,
84
84
  batch_position: int,
85
+ query_idx: int,
85
86
  *past_key_values,
86
87
  ):
87
88
  """Defines the forward pass for the wrapper model."""
@@ -107,10 +108,13 @@ class MidmLMHeadModelWrapper(torch.nn.Module):
107
108
  )
108
109
 
109
110
  hidden_states = outputs[0]
111
+ if batch_position >= 0:
112
+ hidden_states = hidden_states[:, query_idx].unsqueeze(1)
113
+
110
114
  logits = self.lm_head(hidden_states)
111
115
  output = (logits,) + outputs[1:]
112
116
 
113
- return output, batch_position
117
+ return output, batch_position + query_idx
114
118
 
115
119
 
116
120
  def layernorm1p(module, input):