optimum-rbln 0.1.9__py3-none-any.whl → 0.1.11__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 (61) hide show
  1. optimum/rbln/__init__.py +37 -2
  2. optimum/rbln/__version__.py +1 -1
  3. optimum/rbln/diffusers/models/autoencoder_kl.py +36 -29
  4. optimum/rbln/diffusers/models/controlnet.py +56 -40
  5. optimum/rbln/diffusers/models/unet_2d_condition.py +40 -28
  6. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet.py +22 -15
  7. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +22 -15
  8. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +23 -17
  9. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +24 -18
  10. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +22 -11
  11. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +22 -11
  12. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +24 -14
  13. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +24 -14
  14. optimum/rbln/modeling_alias.py +3 -3
  15. optimum/rbln/modeling_base.py +471 -231
  16. optimum/rbln/modeling_config.py +152 -77
  17. optimum/rbln/modeling_seq2seq.py +166 -77
  18. optimum/rbln/transformers/__init__.py +35 -1
  19. optimum/rbln/transformers/models/__init__.py +20 -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 +94 -0
  23. optimum/rbln/transformers/models/bart/__init__.py +1 -0
  24. optimum/rbln/transformers/models/bart/bart_architecture.py +189 -50
  25. optimum/rbln/transformers/models/bart/modeling_bart.py +106 -0
  26. optimum/rbln/transformers/models/bert/__init__.py +24 -0
  27. optimum/rbln/transformers/models/bert/modeling_bert.py +102 -0
  28. optimum/rbln/transformers/models/clip/__init__.py +1 -1
  29. optimum/rbln/transformers/models/clip/modeling_clip.py +127 -25
  30. optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py +28 -4
  31. optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py +302 -115
  32. optimum/rbln/transformers/models/dpt/modeling_dpt.py +21 -7
  33. optimum/rbln/transformers/models/gemma/modeling_gemma.py +1 -1
  34. optimum/rbln/transformers/models/gpt2/gpt2_architecture.py +4 -1
  35. optimum/rbln/transformers/models/gpt2/modeling_gpt2.py +1 -1
  36. optimum/rbln/transformers/models/llama/modeling_llama.py +1 -1
  37. optimum/rbln/transformers/models/llava_next/__init__.py +24 -0
  38. optimum/rbln/transformers/models/llava_next/modeling_llava_next.py +666 -0
  39. optimum/rbln/transformers/models/midm/midm_architecture.py +5 -1
  40. optimum/rbln/transformers/models/midm/modeling_midm.py +1 -1
  41. optimum/rbln/transformers/models/mistral/modeling_mistral.py +1 -1
  42. optimum/rbln/transformers/models/phi/__init__.py +24 -0
  43. optimum/rbln/transformers/models/phi/modeling_phi.py +69 -0
  44. optimum/rbln/transformers/models/phi/phi_architecture.py +406 -0
  45. optimum/rbln/transformers/models/t5/t5_architecture.py +92 -31
  46. optimum/rbln/transformers/models/wav2vec2/modeling_wav2vec2.py +17 -11
  47. optimum/rbln/transformers/models/whisper/generation_whisper.py +68 -0
  48. optimum/rbln/transformers/models/whisper/modeling_whisper.py +141 -105
  49. optimum/rbln/transformers/models/whisper/whisper_architecture.py +44 -17
  50. optimum/rbln/transformers/models/xlm_roberta/modeling_xlm_roberta.py +17 -14
  51. optimum/rbln/transformers/utils/rbln_quantization.py +48 -60
  52. optimum/rbln/utils/import_utils.py +36 -1
  53. optimum/rbln/utils/logging.py +82 -0
  54. optimum/rbln/utils/runtime_utils.py +33 -0
  55. optimum/rbln/utils/timer_utils.py +19 -0
  56. {optimum_rbln-0.1.9.dist-info → optimum_rbln-0.1.11.dist-info}/METADATA +8 -7
  57. optimum_rbln-0.1.11.dist-info/RECORD +93 -0
  58. {optimum_rbln-0.1.9.dist-info → optimum_rbln-0.1.11.dist-info}/WHEEL +1 -1
  59. optimum_rbln-0.1.11.dist-info/entry_points.txt +4 -0
  60. optimum_rbln-0.1.9.dist-info/RECORD +0 -78
  61. {optimum_rbln-0.1.9.dist-info → optimum_rbln-0.1.11.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,666 @@
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.vision_tower)
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
+ past_cached_length=None,
232
+ **kwargs,
233
+ ):
234
+ # Prepare HF generation
235
+ is_prefill_phase = past_cached_length 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
+ past_cached_length=past_cached_length, # Not affect
242
+ attention_mask=attention_mask,
243
+ **kwargs,
244
+ )
245
+
246
+ if is_prefill_phase:
247
+ model_inputs["past_cached_length"] = torch.zeros((batch_size, 1), dtype=torch.int32)
248
+ else:
249
+ model_inputs["past_cached_length"] = past_cached_length + 1
250
+
251
+ model_inputs.update(
252
+ {
253
+ # "position_ids": position_ids or cache_positions,
254
+ "pixel_values": pixel_values,
255
+ "image_sizes": image_sizes,
256
+ "attention_mask": attention_mask,
257
+ }
258
+ )
259
+ return model_inputs
260
+
261
+ def _update_model_kwargs_for_generation(
262
+ self,
263
+ outputs: RBLNDecoderOnlyOutput,
264
+ model_kwargs: Dict[str, Any],
265
+ **kwargs,
266
+ ) -> Dict[str, Any]:
267
+ # update past_cached_length
268
+ model_kwargs["past_cached_length"] = outputs.past_cached_length
269
+
270
+ return model_kwargs
271
+
272
+ def _merge_vllm_multimodal_embeddings(
273
+ self,
274
+ input_ids: torch.Tensor,
275
+ inputs_embeds: torch.Tensor,
276
+ multimodal_embeddings: torch.Tensor,
277
+ placeholder_token_id: int,
278
+ ) -> torch.Tensor:
279
+ mask = input_ids == placeholder_token_id
280
+ num_expected_tokens = mask.sum().item()
281
+ assert isinstance(num_expected_tokens, int)
282
+
283
+ if multimodal_embeddings.shape[0] != num_expected_tokens:
284
+ raise ValueError(
285
+ f"Attempted to assign {inputs_embeds[mask].shape} = {multimodal_embeddings.shape} "
286
+ f"multimodal tokens to {num_expected_tokens} placeholders"
287
+ )
288
+
289
+ inputs_embeds[mask] = multimodal_embeddings
290
+ return inputs_embeds
291
+
292
+ def _embed(
293
+ self,
294
+ input_ids: torch.LongTensor,
295
+ image_sizes: torch.LongTensor,
296
+ attention_mask: torch.Tensor,
297
+ pixel_values: torch.FloatTensor,
298
+ vision_feature_layer: int,
299
+ vision_feature_select_strategy: str,
300
+ cache_position: torch.Tensor,
301
+ past_cached_length: torch.Tensor,
302
+ from_vllm_prefill: bool = False,
303
+ ) -> List[torch.Tensor]:
304
+ vision_feature_layer = (
305
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
306
+ )
307
+ vision_feature_select_strategy = (
308
+ vision_feature_select_strategy
309
+ if vision_feature_select_strategy is not None
310
+ else self.config.vision_feature_select_strategy
311
+ )
312
+
313
+ # 1. Extract the input embeddings
314
+ # In case image_token_index is not in the embeddings (extra token but embedding don't have it)
315
+ for_inputs_embeds_ids = input_ids.clone()
316
+ for_inputs_embeds_ids[(input_ids == self.config.image_token_index)] = 0
317
+
318
+ inputs_embeds = self.get_input_embeddings()(for_inputs_embeds_ids)
319
+
320
+ # 2. Merge text and images
321
+ if pixel_values is not None and input_ids.shape[1] != 1 and pixel_values.size(0) > 0:
322
+ # ! infer image_num_patches from image_sizes
323
+ image_num_patches = [
324
+ image_size_to_num_patches(
325
+ image_size=imsize,
326
+ grid_pinpoints=self.config.image_grid_pinpoints,
327
+ patch_size=self.config.vision_config.image_size,
328
+ )
329
+ for imsize in image_sizes
330
+ ]
331
+ # figure out if pixel_values is concatenated or stacked
332
+ if pixel_values.dim() == 5:
333
+ # stacking when input is (batch_size, num_patches, num_channels, height, width)
334
+ _pixel_values_list = [
335
+ pix_val[:num_patch] for pix_val, num_patch in zip(pixel_values, image_num_patches)
336
+ ]
337
+ pixel_values = torch.cat(_pixel_values_list, dim=0)
338
+ elif pixel_values.dim() != 4:
339
+ # otherwise has to be stacked from list of (num_patches, num_channels, height, width)
340
+ raise ValueError(f"pixel_values of shape {pixel_values.shape}, expect to be of 4 or 5 dimensions")
341
+
342
+ image_features = self.vision_tower(pixel_values, output_hidden_states=True)
343
+ selected_image_feature = image_features.hidden_states[vision_feature_layer]
344
+
345
+ if vision_feature_select_strategy == "default":
346
+ selected_image_feature = selected_image_feature[:, 1:]
347
+ elif vision_feature_select_strategy == "full":
348
+ selected_image_feature = selected_image_feature
349
+
350
+ image_features = self.multi_modal_projector(selected_image_feature)
351
+ image_features = torch.split(image_features, image_num_patches, dim=0)
352
+
353
+ # NOTE we only support multimodal_patch_merge_type == "spatial_unpad"
354
+ image_features, feature_lens = self.pack_image_features(
355
+ image_features,
356
+ image_sizes,
357
+ image_newline=self.image_newline,
358
+ )
359
+
360
+ inputs_embeds = inputs_embeds.to(image_features.dtype)
361
+
362
+ if from_vllm_prefill:
363
+ self._merge_vllm_multimodal_embeddings(
364
+ input_ids, inputs_embeds, image_features, self.config.image_token_index
365
+ )
366
+ else:
367
+ inputs_embeds, attention_mask, position_ids, labels, _ = self._merge_input_ids_with_image_features(
368
+ image_features,
369
+ feature_lens,
370
+ inputs_embeds,
371
+ input_ids,
372
+ attention_mask,
373
+ )
374
+
375
+ cache_position = torch.arange(0, inputs_embeds.shape[1], dtype=torch.int32).unsqueeze_(0)
376
+
377
+ # pixel_values is not None but is empty ---> text only cases
378
+ elif (
379
+ pixel_values is not None and input_ids.shape[1] != 1 and pixel_values.size(0) == 0 or pixel_values is None
380
+ ):
381
+ pass
382
+
383
+ # In case input_ids.shape[1] == 1 & pixel_values==None & past_key_values != None, we are in the case of
384
+ # generation with cache
385
+ elif pixel_values is not None and input_ids.shape[1] == 1 and past_cached_length is not None:
386
+ cache_position = past_cached_length
387
+
388
+ return inputs_embeds, cache_position
389
+
390
+ def forward(
391
+ self,
392
+ input_ids: torch.LongTensor = None,
393
+ pixel_values: torch.FloatTensor = None,
394
+ image_sizes: Optional[torch.LongTensor] = None,
395
+ inputs_embeds: Optional[torch.FloatTensor] = None,
396
+ vision_feature_layer: Optional[int] = None,
397
+ vision_feature_select_strategy: Optional[str] = None,
398
+ cache_position: Union[List[torch.Tensor], torch.Tensor] = None, # vllm keyword argument
399
+ batch_idx: Optional[int] = None,
400
+ past_cached_length: Optional[torch.Tensor] = None,
401
+ **kwargs,
402
+ ) -> Union[Tuple, LlavaNextCausalLMOutputWithPast]:
403
+ from_vllm_prefill = isinstance(cache_position, torch.Tensor) and cache_position.shape[-1] > 1
404
+ from_hf_generate_prefill = isinstance(input_ids, list)
405
+
406
+ if inputs_embeds is not None:
407
+ raise NotImplementedError("Specifying inputs_embeds is not supported.")
408
+
409
+ if from_hf_generate_prefill:
410
+ inputs_embeds = []
411
+ batch_size = len(input_ids)
412
+
413
+ # Get the number of images in the prompt
414
+ special_image_token_masks = [input_id == self.config.image_token_index for input_id in input_ids]
415
+ num_special_image_tokens = [torch.sum(mask, dim=-1) for mask in special_image_token_masks]
416
+
417
+ # Split images for each prompt
418
+ pixel_values = pixel_values.split(num_special_image_tokens, dim=0)
419
+ image_sizes = image_sizes.split(num_special_image_tokens, dim=0)
420
+
421
+ for b_idx in range(batch_size):
422
+ embed, cache_pos = self._embed(
423
+ input_ids=input_ids[b_idx],
424
+ image_sizes=image_sizes[b_idx] if image_sizes is not None else None,
425
+ attention_mask=torch.ones_like(input_ids[b_idx]),
426
+ pixel_values=pixel_values[b_idx] if pixel_values is not None else None,
427
+ vision_feature_layer=vision_feature_layer,
428
+ vision_feature_select_strategy=vision_feature_select_strategy,
429
+ cache_position=cache_position[b_idx],
430
+ past_cached_length=past_cached_length[b_idx : b_idx + 1],
431
+ )
432
+ inputs_embeds.append(embed)
433
+ cache_position[b_idx] = cache_pos
434
+ past_cached_length[b_idx] += embed.shape[1]
435
+
436
+ elif from_vllm_prefill:
437
+ inputs_embeds, cache_position = self._embed(
438
+ input_ids=input_ids,
439
+ image_sizes=image_sizes,
440
+ attention_mask=torch.ones_like(input_ids),
441
+ pixel_values=pixel_values,
442
+ vision_feature_layer=vision_feature_layer,
443
+ vision_feature_select_strategy=vision_feature_select_strategy,
444
+ cache_position=cache_position,
445
+ past_cached_length=past_cached_length,
446
+ from_vllm_prefill=from_vllm_prefill,
447
+ )
448
+ else:
449
+ # Decoding step
450
+ inputs_embeds, cache_position = self._embed(
451
+ input_ids=input_ids,
452
+ image_sizes=image_sizes,
453
+ attention_mask=torch.ones_like(input_ids),
454
+ pixel_values=pixel_values,
455
+ vision_feature_layer=vision_feature_layer,
456
+ vision_feature_select_strategy=vision_feature_select_strategy,
457
+ cache_position=cache_position,
458
+ past_cached_length=past_cached_length,
459
+ )
460
+
461
+ outputs: RBLNDecoderOnlyOutput = self.language_model(
462
+ inputs_embeds=inputs_embeds,
463
+ batch_idx=batch_idx,
464
+ cache_position=cache_position,
465
+ past_cached_length=past_cached_length,
466
+ )
467
+
468
+ return outputs
469
+
470
+ # Almost copied from : https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/llava_next/modeling_llava_next.py
471
+ def pack_image_features(self, image_features, image_sizes, image_newline=None):
472
+ """
473
+ Reshape, unpad and then pack each image_feature into a single image_features tensor containing all visual vectors.
474
+
475
+ Args:
476
+ image_features (`List[torch.Tensor]` of length num_images, each of shape `(num_patches, image_length, embed_dim)`)
477
+ List of image feature tensor, each contains all the visual feature of all patches.
478
+ image_sizes (`torch.Tensor` of shape `(num_images, 2)`)
479
+ Actual image size of each images (H, W).
480
+ image_newline (`torch.Tensor` of shape `(embed_dim)`)
481
+ New line embedding vector.
482
+ Returns:
483
+ image_features (`torch.Tensor` of shape `(all_feat_len, embed_dim)`)
484
+ feature_lens (`List[int]`)
485
+ token length of each image in image_features
486
+ """
487
+ new_image_features = []
488
+ feature_lens = []
489
+ for image_idx, image_feature in enumerate(image_features):
490
+ if image_feature.shape[0] > 1:
491
+ base_image_feature = image_feature[0]
492
+ image_feature = image_feature[1:]
493
+ height = width = self.config.vision_config.image_size // self.config.vision_config.patch_size
494
+ if height * width != base_image_feature.shape[0]:
495
+ raise ValueError("The number of patches is not consistent with the image size.")
496
+ num_patch_width, num_patch_height = get_anyres_image_grid_shape(
497
+ image_sizes[image_idx],
498
+ self.config.image_grid_pinpoints,
499
+ self.config.vision_config.image_size,
500
+ )
501
+ image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
502
+ image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
503
+ image_feature = image_feature.flatten(1, 2).flatten(2, 3)
504
+ image_feature = unpad_image(image_feature, image_sizes[image_idx])
505
+ if image_newline is not None:
506
+ image_feature = torch.cat(
507
+ (
508
+ image_feature,
509
+ image_newline[:, None, None].expand(*image_feature.shape[:-1], 1).to(image_feature.dtype),
510
+ ),
511
+ dim=-1,
512
+ )
513
+ image_feature = image_feature.flatten(1, 2).transpose(0, 1)
514
+ image_feature = torch.cat((base_image_feature, image_feature), dim=0)
515
+ else:
516
+ image_feature = image_feature[0]
517
+ if image_newline is not None:
518
+ image_feature = torch.cat((image_feature, image_newline[None].to(image_feature)), dim=0)
519
+ new_image_features.append(image_feature)
520
+ feature_lens.append(image_feature.size(0))
521
+ image_features = torch.cat(new_image_features, dim=0)
522
+ feature_lens = torch.tensor(feature_lens, dtype=torch.long, device=image_features.device)
523
+ return image_features, feature_lens
524
+
525
+
526
+ # Almost copied from : https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/llava_next/modeling_llava_next.py
527
+ def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size):
528
+ """
529
+ Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
530
+
531
+ Args:
532
+ image_size (`tuple`):
533
+ The size of the input image in the format (width, height).
534
+ grid_pinpoints (`List`):
535
+ A list containing possible resolutions. Each item in the list should be a tuple or list
536
+ of the form `(height, width)`.
537
+ patch_size (`int`):
538
+ The size of each image patch.
539
+
540
+ Returns:
541
+ tuple: The shape of the image patch grid in the format (width, height).
542
+ """
543
+ if not isinstance(grid_pinpoints, list):
544
+ raise TypeError("grid_pinpoints should be a list of tuples or lists")
545
+
546
+ # ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate
547
+ if not isinstance(image_size, (list, tuple)):
548
+ if not isinstance(image_size, (torch.Tensor, np.ndarray)):
549
+ raise TypeError(
550
+ f"image_size invalid type: {type(image_size)} not valid, should be either list, tuple, np.ndarray or tensor"
551
+ )
552
+ image_size = image_size.tolist()
553
+
554
+ height, width = select_best_resolution(image_size, grid_pinpoints)
555
+ return height // patch_size, width // patch_size
556
+
557
+
558
+ # Almost copied from : https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/llava_next/modeling_llava_next.py
559
+ def unpad_image(tensor, original_size):
560
+ """
561
+ Unpads a PyTorch tensor of a padded and resized image.
562
+
563
+ Args:
564
+ tensor (`torch.Tensor`):
565
+ The image tensor, assumed to be of shape (num_channels, height, width).
566
+ original_size (`tuple`):
567
+ The original size of the image (height, width).
568
+
569
+ Returns:
570
+ `torch.Tensor`: The unpadded image tensor.
571
+ """
572
+ original_height, original_width = original_size
573
+ current_height, current_width = tensor.shape[1:]
574
+
575
+ original_aspect_ratio = original_width / original_height
576
+ current_aspect_ratio = current_width / current_height
577
+
578
+ if original_aspect_ratio > current_aspect_ratio:
579
+ scale_factor = current_width / original_width
580
+ new_height = int(original_height * scale_factor)
581
+ padding = (current_height - new_height) // 2
582
+ unpadded_tensor = tensor[:, padding : current_height - padding, :]
583
+ else:
584
+ scale_factor = current_height / original_height
585
+ new_width = int(original_width * scale_factor)
586
+ padding = (current_width - new_width) // 2
587
+ unpadded_tensor = tensor[:, :, padding : current_width - padding]
588
+
589
+ return unpadded_tensor
590
+
591
+
592
+ # Almost copied from : https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/llava_next/modeling_llava_next.py
593
+ def select_best_resolution(original_size: tuple, possible_resolutions: list) -> tuple:
594
+ """
595
+ Selects the best resolution from a list of possible resolutions based on the original size.
596
+
597
+ This is done by calculating the effective and wasted resolution for each possible resolution.
598
+
599
+ The best fit resolution is the one that maximizes the effective resolution and minimizes the wasted resolution.
600
+
601
+ Args:
602
+ original_size (tuple):
603
+ The original size of the image in the format (height, width).
604
+ possible_resolutions (list):
605
+ A list of possible resolutions in the format [(height1, width1), (height2, width2), ...].
606
+
607
+ Returns:
608
+ tuple: The best fit resolution in the format (height, width).
609
+ """
610
+ original_height, original_width = original_size
611
+ best_fit = None
612
+ max_effective_resolution = 0
613
+ min_wasted_resolution = float("inf")
614
+
615
+ for height, width in possible_resolutions:
616
+ scale = min(width / original_width, height / original_height)
617
+ downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
618
+ effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
619
+ wasted_resolution = (width * height) - effective_resolution
620
+
621
+ if effective_resolution > max_effective_resolution or (
622
+ effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution
623
+ ):
624
+ max_effective_resolution = effective_resolution
625
+ min_wasted_resolution = wasted_resolution
626
+ best_fit = (height, width)
627
+
628
+ return best_fit
629
+
630
+
631
+ # Almost copied from : https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/llava_next/modeling_llava_next.py
632
+ def image_size_to_num_patches(image_size, grid_pinpoints, patch_size: int):
633
+ """
634
+ Calculate the number of patches after the preprocessing for images of any resolution.
635
+
636
+ Args:
637
+ image_size (`Union[torch.LongTensor, np.ndarray, Tuple[int, int]):
638
+ The size of the input image in the format (height, width). ?
639
+ grid_pinpoints (`List`):
640
+ A list containing possible resolutions. Each item in the list should be a tuple or list
641
+ of the form `(height, width)`.
642
+ patch_size (`int`):
643
+ The size of each image patch.
644
+
645
+ Returns:
646
+ int: the number of patches
647
+ """
648
+ if not isinstance(grid_pinpoints, list):
649
+ raise TypeError("grid_pinpoints should be a list of tuples or lists")
650
+
651
+ # ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate
652
+ if not isinstance(image_size, (list, tuple)):
653
+ if not isinstance(image_size, (torch.Tensor, np.ndarray)):
654
+ raise TypeError(f"image_size invalid type {type(image_size)} with value {image_size}")
655
+ image_size = image_size.tolist()
656
+
657
+ best_resolution = select_best_resolution(image_size, grid_pinpoints)
658
+ height, width = best_resolution
659
+ num_patches = 0
660
+ # consider change to ceil(height/patch_size)*ceil(width/patch_size) + 1
661
+ for i in range(0, height, patch_size):
662
+ for j in range(0, width, patch_size):
663
+ num_patches += 1
664
+ # add the base patch
665
+ num_patches += 1
666
+ 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):
@@ -56,7 +56,7 @@ class RBLNMidmLMHeadModel(RBLNDecoderOnlyModelForCausalLM):
56
56
 
57
57
  @classmethod
58
58
  def wrap_model_if_needed(self, model: "PreTrainedModel", rbln_config: "RBLNConfig"):
59
- rbln_max_seq_len = rbln_config.meta["rbln_max_seq_len"]
59
+ rbln_max_seq_len = rbln_config.model_cfg["max_seq_len"]
60
60
  return MidmLMHeadModelWrapper(model, rbln_max_seq_len).eval()
61
61
 
62
62
  def __getattr__(self, __name: str) -> Any: