optimum-rbln 0.7.4a6__py3-none-any.whl → 0.7.4a7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
optimum/rbln/__init__.py CHANGED
@@ -74,6 +74,10 @@ _import_structure = {
74
74
  "RBLNGemmaForCausalLMConfig",
75
75
  "RBLNGPT2LMHeadModel",
76
76
  "RBLNGPT2LMHeadModelConfig",
77
+ "RBLNIdefics3VisionTransformer",
78
+ "RBLNIdefics3ForConditionalGeneration",
79
+ "RBLNIdefics3ForConditionalGenerationConfig",
80
+ "RBLNIdefics3VisionTransformerConfig",
77
81
  "RBLNLlamaForCausalLM",
78
82
  "RBLNLlamaForCausalLMConfig",
79
83
  "RBLNLlavaNextForConditionalGeneration",
@@ -281,6 +285,10 @@ if TYPE_CHECKING:
281
285
  RBLNGemmaForCausalLMConfig,
282
286
  RBLNGPT2LMHeadModel,
283
287
  RBLNGPT2LMHeadModelConfig,
288
+ RBLNIdefics3ForConditionalGeneration,
289
+ RBLNIdefics3ForConditionalGenerationConfig,
290
+ RBLNIdefics3VisionTransformer,
291
+ RBLNIdefics3VisionTransformerConfig,
284
292
  RBLNLlamaForCausalLM,
285
293
  RBLNLlamaForCausalLMConfig,
286
294
  RBLNLlavaNextForConditionalGeneration,
@@ -17,5 +17,5 @@ __version__: str
17
17
  __version_tuple__: VERSION_TUPLE
18
18
  version_tuple: VERSION_TUPLE
19
19
 
20
- __version__ = version = '0.7.4a6'
21
- __version_tuple__ = version_tuple = (0, 7, 4, 'a6')
20
+ __version__ = version = '0.7.4a7'
21
+ __version_tuple__ = version_tuple = (0, 7, 4, 'a7')
@@ -68,6 +68,10 @@ _import_structure = {
68
68
  "RBLNGemmaForCausalLMConfig",
69
69
  "RBLNGPT2LMHeadModel",
70
70
  "RBLNGPT2LMHeadModelConfig",
71
+ "RBLNIdefics3VisionTransformer",
72
+ "RBLNIdefics3ForConditionalGeneration",
73
+ "RBLNIdefics3ForConditionalGenerationConfig",
74
+ "RBLNIdefics3VisionTransformerConfig",
71
75
  "RBLNLlamaForCausalLM",
72
76
  "RBLNLlamaForCausalLMConfig",
73
77
  "RBLNLlavaNextForConditionalGeneration",
@@ -169,6 +173,10 @@ if TYPE_CHECKING:
169
173
  RBLNGemmaForCausalLMConfig,
170
174
  RBLNGPT2LMHeadModel,
171
175
  RBLNGPT2LMHeadModelConfig,
176
+ RBLNIdefics3ForConditionalGeneration,
177
+ RBLNIdefics3ForConditionalGenerationConfig,
178
+ RBLNIdefics3VisionTransformer,
179
+ RBLNIdefics3VisionTransformerConfig,
172
180
  RBLNLlamaForCausalLM,
173
181
  RBLNLlamaForCausalLMConfig,
174
182
  RBLNLlavaNextForConditionalGeneration,
@@ -73,6 +73,12 @@ _import_structure = {
73
73
  "exaone": ["RBLNExaoneForCausalLM", "RBLNExaoneForCausalLMConfig"],
74
74
  "gemma": ["RBLNGemmaForCausalLM", "RBLNGemmaForCausalLMConfig"],
75
75
  "gpt2": ["RBLNGPT2LMHeadModel", "RBLNGPT2LMHeadModelConfig"],
76
+ "idefics3": [
77
+ "RBLNIdefics3VisionTransformer",
78
+ "RBLNIdefics3ForConditionalGeneration",
79
+ "RBLNIdefics3ForConditionalGenerationConfig",
80
+ "RBLNIdefics3VisionTransformerConfig",
81
+ ],
76
82
  "llama": ["RBLNLlamaForCausalLM", "RBLNLlamaForCausalLMConfig"],
77
83
  "llava_next": ["RBLNLlavaNextForConditionalGeneration", "RBLNLlavaNextForConditionalGenerationConfig"],
78
84
  "midm": ["RBLNMidmLMHeadModel", "RBLNMidmLMHeadModelConfig"],
@@ -144,6 +150,12 @@ if TYPE_CHECKING:
144
150
  from .exaone import RBLNExaoneForCausalLM, RBLNExaoneForCausalLMConfig
145
151
  from .gemma import RBLNGemmaForCausalLM, RBLNGemmaForCausalLMConfig
146
152
  from .gpt2 import RBLNGPT2LMHeadModel, RBLNGPT2LMHeadModelConfig
153
+ from .idefics3 import (
154
+ RBLNIdefics3ForConditionalGeneration,
155
+ RBLNIdefics3ForConditionalGenerationConfig,
156
+ RBLNIdefics3VisionTransformer,
157
+ RBLNIdefics3VisionTransformerConfig,
158
+ )
147
159
  from .llama import RBLNLlamaForCausalLM, RBLNLlamaForCausalLMConfig
148
160
  from .llava_next import RBLNLlavaNextForConditionalGeneration, RBLNLlavaNextForConditionalGenerationConfig
149
161
  from .midm import RBLNMidmLMHeadModel, RBLNMidmLMHeadModelConfig
@@ -184,6 +184,7 @@ class DecoderOnlyWrapper(nn.Module):
184
184
 
185
185
  def convert_to_rbln_causal_lm(self, causal_lm: PreTrainedModel, max_seq_len: int):
186
186
  new_layers = []
187
+
187
188
  for layer in causal_lm.model.layers:
188
189
  if self.attn_impl == "eager":
189
190
  new_self_attn = DecoderOnlyAttention(
@@ -201,6 +202,7 @@ class DecoderOnlyWrapper(nn.Module):
201
202
 
202
203
  new_layer = DecoderOnlyLayer(layer, new_self_attn)
203
204
  new_layers.append(new_layer)
205
+
204
206
  new_model = DecoderOnlyModel(
205
207
  causal_lm.model,
206
208
  new_layers,
@@ -451,6 +451,12 @@ class RBLNDecoderOnlyModelForCausalLM(RBLNModel):
451
451
  def get_input_embeddings(self):
452
452
  return self.embed_tokens
453
453
 
454
+ def get_attn_impl(self) -> str:
455
+ return self.rbln_config.attn_impl
456
+
457
+ def get_kvcache_num_blocks(self) -> int:
458
+ return self.rbln_config.kvcache_num_blocks
459
+
454
460
  @classmethod
455
461
  def get_quantized_model(
456
462
  cls,
@@ -0,0 +1,16 @@
1
+ # Copyright 2025 Rebellions Inc. All rights reserved.
2
+
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at:
6
+
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .configuration_idefics3 import RBLNIdefics3ForConditionalGenerationConfig, RBLNIdefics3VisionTransformerConfig
16
+ from .modeling_idefics3 import RBLNIdefics3ForConditionalGeneration, RBLNIdefics3VisionTransformer
@@ -0,0 +1,51 @@
1
+ # Copyright 2025 Rebellions Inc. All rights reserved.
2
+
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at:
6
+
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Optional
16
+
17
+ from ....configuration_utils import RBLNModelConfig
18
+
19
+
20
+ class RBLNIdefics3VisionTransformerConfig(RBLNModelConfig):
21
+ pass
22
+
23
+
24
+ class RBLNIdefics3ForConditionalGenerationConfig(RBLNModelConfig):
25
+ submodules = ["vision_model", "text_model"]
26
+
27
+ def __init__(
28
+ self,
29
+ batch_size: Optional[int] = None,
30
+ vision_model: Optional[RBLNModelConfig] = None,
31
+ text_model: Optional[RBLNModelConfig] = None,
32
+ **kwargs,
33
+ ):
34
+ """
35
+ Args:
36
+ batch_size (Optional[int]): The batch size for inference. Defaults to 1.
37
+ vision_model (Optional[RBLNModelConfig]): Configuration for the vision transformer component.
38
+ text_model (Optional[RBLNModelConfig]): Configuration for the text model component.
39
+ **kwargs: Additional arguments passed to the parent RBLNModelConfig.
40
+
41
+ Raises:
42
+ ValueError: If batch_size is not a positive integer.
43
+ """
44
+
45
+ super().__init__(**kwargs)
46
+ self.batch_size = batch_size or 1
47
+ if not isinstance(self.batch_size, int) or self.batch_size < 0:
48
+ raise ValueError(f"batch_size must be a positive integer, got {self.batch_size}")
49
+
50
+ self.vision_model = vision_model
51
+ self.text_model = text_model
@@ -0,0 +1,459 @@
1
+ # Copyright 2025 Rebellions Inc. All rights reserved.
2
+
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at:
6
+
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import importlib
16
+ import inspect
17
+ from pathlib import Path
18
+ from typing import TYPE_CHECKING, Any, Callable, Optional, Tuple, Union
19
+
20
+ import rebel
21
+ import torch
22
+ from transformers import (
23
+ AutoModelForVision2Seq,
24
+ Idefics3ForConditionalGeneration,
25
+ Idefics3VisionConfig,
26
+ Idefics3VisionTransformer,
27
+ PretrainedConfig,
28
+ PreTrainedModel,
29
+ )
30
+ from transformers.modeling_outputs import BaseModelOutput
31
+ from transformers.modeling_utils import no_init_weights
32
+ from transformers.models.idefics3.modeling_idefics3 import Idefics3CausalLMOutputWithPast, Idefics3VisionEmbeddings
33
+
34
+ from ....configuration_utils import RBLNCompileConfig, RBLNModelConfig
35
+ from ....modeling import RBLNModel
36
+ from ....utils.runtime_utils import RBLNPytorchRuntime
37
+ from ..decoderonly.modeling_decoderonly import (
38
+ RBLNDecoderOnlyOutput,
39
+ )
40
+
41
+
42
+ if TYPE_CHECKING:
43
+ from transformers import (
44
+ AutoFeatureExtractor,
45
+ AutoProcessor,
46
+ AutoTokenizer,
47
+ )
48
+
49
+
50
+ class RBLNRuntimeVisionModel(RBLNPytorchRuntime):
51
+ mandatory_members = ["main_input_name"]
52
+
53
+ def __init__(
54
+ self,
55
+ runtime: rebel.Runtime,
56
+ config: Idefics3VisionConfig,
57
+ **kwargs: Any,
58
+ ) -> None:
59
+ super().__init__(runtime, **kwargs)
60
+ self.patch_size = config.patch_size
61
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
62
+
63
+ def forward(
64
+ self,
65
+ pixel_values,
66
+ patch_attention_mask: Optional[torch.BoolTensor] = None,
67
+ return_dict: Optional[bool] = None,
68
+ **kwargs,
69
+ ):
70
+ batch_size = pixel_values.size(0)
71
+ if patch_attention_mask is None:
72
+ patch_size = self.patch_size
73
+ patch_attention_mask = torch.ones(
74
+ (
75
+ batch_size,
76
+ pixel_values.size(2) // patch_size,
77
+ pixel_values.size(3) // patch_size,
78
+ )
79
+ )
80
+ patch_attention_mask = patch_attention_mask.to(dtype=torch.bool, device=pixel_values.device)
81
+
82
+ hidden_states = self.embeddings(pixel_values=pixel_values, patch_attention_mask=patch_attention_mask)
83
+
84
+ return super().forward(hidden_states.contiguous())
85
+
86
+
87
+ class RBLNIdefics3VisionTransformer(RBLNModel):
88
+ def __post_init__(self, **kwargs):
89
+ artifacts = torch.load(self.model_save_dir / self.subfolder / "torch_artifacts.pth", weights_only=False)
90
+ with no_init_weights():
91
+ self.embeddings = Idefics3VisionEmbeddings(self.config)
92
+ self.embeddings.load_state_dict(artifacts["embeddings"])
93
+ self.model = RBLNRuntimeVisionModel(
94
+ self.model[0], main_input_name="pixel_values", config=self.config, embeddings=self.embeddings
95
+ )
96
+
97
+ @classmethod
98
+ def save_torch_artifacts(
99
+ cls,
100
+ model: "PreTrainedModel",
101
+ save_dir_path: Path,
102
+ subfolder: str,
103
+ rbln_config: RBLNModelConfig,
104
+ ):
105
+ """
106
+ If you are unavoidably running on a CPU rather than an RBLN device,
107
+ store the torch tensor, weight, etc. in this function.
108
+ """
109
+ save_dict = {}
110
+ save_dict["embeddings"] = model.get_input_embeddings().state_dict()
111
+ torch.save(save_dict, save_dir_path / subfolder / "torch_artifacts.pth")
112
+
113
+ def get_input_embeddings(self):
114
+ return self.embeddings
115
+
116
+ @classmethod
117
+ def wrap_model_if_needed(cls, model: torch.nn.Module, rbln_config: RBLNModelConfig) -> torch.nn.Module:
118
+ class Idefics3VisionTransformerWrapper(torch.nn.Module):
119
+ def __init__(self, model: "Idefics3VisionTransformer"):
120
+ super().__init__()
121
+ self.encoder = model.encoder
122
+ self.post_layernorm = model.post_layernorm
123
+
124
+ def forward(self, hidden_states, patch_attention_mask: Optional[torch.BoolTensor] = None):
125
+ encoder_outputs = self.encoder(
126
+ inputs_embeds=hidden_states,
127
+ attention_mask=patch_attention_mask,
128
+ output_attentions=None,
129
+ output_hidden_states=None,
130
+ return_dict=False,
131
+ )
132
+ last_hidden_state = encoder_outputs[0]
133
+ last_hidden_state = self.post_layernorm(last_hidden_state)
134
+ return last_hidden_state
135
+
136
+ return Idefics3VisionTransformerWrapper(model).eval()
137
+
138
+ @classmethod
139
+ def _update_rbln_config(
140
+ cls,
141
+ preprocessors: Optional[Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"]],
142
+ model: Optional["PreTrainedModel"] = None,
143
+ model_config: Optional["PretrainedConfig"] = None,
144
+ rbln_config: Optional[RBLNModelConfig] = None,
145
+ ) -> RBLNModelConfig:
146
+ input_info = [
147
+ (
148
+ "hidden_states",
149
+ [
150
+ # batch_size * num_patches (dependent on image size) -> compile with 1 and use for loop
151
+ 1,
152
+ (model_config.image_size // model_config.patch_size) ** 2,
153
+ model_config.hidden_size,
154
+ ],
155
+ "float32",
156
+ ),
157
+ ]
158
+
159
+ rbln_compile_config = RBLNCompileConfig(input_info=input_info)
160
+ rbln_config.set_compile_cfgs([rbln_compile_config])
161
+ return rbln_config
162
+
163
+ def forward(
164
+ self,
165
+ pixel_values,
166
+ patch_attention_mask: Optional[torch.BoolTensor] = None,
167
+ return_dict: Optional[bool] = None,
168
+ **kwargs,
169
+ ) -> Union[Tuple, BaseModelOutput]:
170
+ batch_size = pixel_values.shape[0]
171
+ last_hidden_state = []
172
+ for i in range(batch_size):
173
+ if patch_attention_mask is not None:
174
+ batch_attention_mask = patch_attention_mask[i : i + 1,]
175
+ else:
176
+ batch_attention_mask = None
177
+
178
+ batch_hidden_state = self.model(
179
+ pixel_values[i : i + 1,],
180
+ batch_attention_mask,
181
+ return_dict=False,
182
+ )
183
+ last_hidden_state.append(batch_hidden_state)
184
+ last_hidden_state = torch.cat(last_hidden_state, dim=0)
185
+
186
+ if not return_dict:
187
+ return (last_hidden_state,)
188
+ else:
189
+ return BaseModelOutput(last_hidden_state=last_hidden_state)
190
+
191
+
192
+ class RBLNIdefics3ForConditionalGeneration(RBLNModel):
193
+ auto_model_class = AutoModelForVision2Seq
194
+ _rbln_submodules = [{"name": "vision_model"}, {"name": "text_model"}]
195
+ _rbln_submodule_prefix = "model"
196
+
197
+ def __getattr__(self, __name: str) -> Any:
198
+ def redirect(func):
199
+ return lambda *pargs, **kwargs: func(self, *pargs, **kwargs)
200
+
201
+ val = getattr(Idefics3ForConditionalGeneration, __name)
202
+
203
+ if isinstance(val, Callable) and "self" in set(inspect.signature(val).parameters):
204
+ return redirect(val)
205
+ return val
206
+
207
+ def can_generate(self):
208
+ return True
209
+
210
+ @classmethod
211
+ def get_pytorch_model(cls, *args, **kwargs):
212
+ model = super().get_pytorch_model(*args, **kwargs)
213
+
214
+ with no_init_weights():
215
+ model_cls_name = model.model.text_model.__class__.__name__
216
+ causal_model_cls_name = model_cls_name.replace("Model", "ForCausalLM")
217
+ causal_model_cls = getattr(importlib.import_module("transformers"), causal_model_cls_name)
218
+ new_text_model = causal_model_cls(model.model.text_model.config)
219
+
220
+ new_text_model.lm_head = model.lm_head
221
+ new_text_model.model = model.model.text_model
222
+ model.model.text_model = new_text_model
223
+ model.lm_head = None
224
+ del model.lm_head
225
+ return model
226
+
227
+ def __post_init__(self, **kwargs):
228
+ self.vision_model = self.rbln_submodules[0]
229
+ self.connector = self.model[0]
230
+ self.text_model = self.rbln_submodules[1]
231
+
232
+ def get_attn_impl(self) -> str:
233
+ return self.rbln_config.text_model.attn_impl
234
+
235
+ def get_kvcache_num_blocks(self) -> int:
236
+ return self.rbln_config.text_model.kvcache_num_blocks
237
+
238
+ def get_input_embeddings(self):
239
+ return self.text_model.get_input_embeddings()
240
+
241
+ @classmethod
242
+ def wrap_model_if_needed(cls, model, rbln_config):
243
+ return model.model.connector
244
+
245
+ @classmethod
246
+ def _update_rbln_config(
247
+ cls,
248
+ preprocessors: Optional[Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"]],
249
+ model: Optional["PreTrainedModel"] = None,
250
+ model_config: Optional["PretrainedConfig"] = None,
251
+ rbln_config: Optional[RBLNModelConfig] = None,
252
+ ) -> RBLNModelConfig:
253
+ input_info = [
254
+ (
255
+ "image_hidden_states",
256
+ [
257
+ # batch_size * num_patches (dependent on image size) -> compile with 1 and use for loop
258
+ 1,
259
+ (model_config.vision_config.image_size // model_config.vision_config.patch_size) ** 2,
260
+ model_config.vision_config.hidden_size,
261
+ ],
262
+ "float32",
263
+ ),
264
+ ]
265
+
266
+ rbln_compile_config = RBLNCompileConfig(input_info=input_info)
267
+ rbln_config.set_compile_cfgs([rbln_compile_config])
268
+
269
+ return rbln_config
270
+
271
+ def prepare_inputs_for_generation(
272
+ self,
273
+ input_ids,
274
+ attention_mask=None,
275
+ inputs_embeds=None,
276
+ cache_position=None,
277
+ pixel_values=None,
278
+ pixel_attention_mask=None,
279
+ image_hidden_states=None,
280
+ generate_idx=None,
281
+ **kwargs,
282
+ ):
283
+ is_prefill_phase = generate_idx is None
284
+ model_inputs = {}
285
+
286
+ if is_prefill_phase:
287
+ generate_idx = attention_mask.sum(dim=-1, keepdim=True).int()
288
+ cache_position = None
289
+ pixel_values = pixel_values
290
+ pixel_attention_mask = pixel_attention_mask
291
+ else:
292
+ if inputs_embeds is not None:
293
+ raise NotImplementedError("Specifying inputs_embeds in decoder phase is not supported.")
294
+
295
+ pixel_values = None
296
+ pixel_attention_mask = None
297
+ input_ids = input_ids[:, -1:]
298
+ cache_position = generate_idx
299
+ generate_idx = generate_idx + 1
300
+ model_inputs.update({"input_ids": input_ids})
301
+
302
+ if inputs_embeds is not None:
303
+ if self.rbln_config.use_inputs_embeds:
304
+ model_inputs.update({"inputs_embeds": inputs_embeds})
305
+ else:
306
+ raise ValueError(
307
+ "The specifying inputs_embeds is only supported when using a compiled RBLN model with 'rbln_use_inputs_embeds' set to True."
308
+ )
309
+ else:
310
+ model_inputs.update({"input_ids": input_ids})
311
+
312
+ model_inputs.update(
313
+ {
314
+ "attention_mask": attention_mask,
315
+ "pixel_values": pixel_values,
316
+ "pixel_attention_mask": pixel_attention_mask,
317
+ "image_hidden_states": image_hidden_states,
318
+ "cache_position": cache_position,
319
+ "generate_idx": generate_idx,
320
+ }
321
+ )
322
+ return model_inputs
323
+
324
+ def _update_model_kwargs_for_generation(self, outputs, model_kwargs, is_encoder_decoder, **kwargs):
325
+ model_kwargs["generate_idx"] = outputs.generate_idx
326
+ return model_kwargs
327
+
328
+ def inputs_merger(
329
+ self,
330
+ input_ids: torch.LongTensor,
331
+ inputs_embeds: Optional[torch.Tensor],
332
+ image_hidden_states: Optional[torch.Tensor],
333
+ ):
334
+ num_images, _, vision_hidden_size = image_hidden_states.shape
335
+ special_image_token_mask = input_ids == self.config.image_token_id
336
+ new_inputs_embeds = inputs_embeds.clone()
337
+ reshaped_image_hidden_states = image_hidden_states.view(-1, vision_hidden_size)
338
+ reshaped_image_hidden_states = reshaped_image_hidden_states.to(inputs_embeds.device, inputs_embeds.dtype)
339
+ new_inputs_embeds[special_image_token_mask] = reshaped_image_hidden_states
340
+ return new_inputs_embeds
341
+
342
+ def _preprocess_prefill(
343
+ self,
344
+ input_ids: torch.LongTensor = None,
345
+ inputs_embeds: Optional[torch.FloatTensor] = None,
346
+ pixel_values: Optional[torch.FloatTensor] = None,
347
+ pixel_attention_mask: Optional[torch.BoolTensor] = None,
348
+ image_hidden_states: Optional[torch.FloatTensor] = None,
349
+ **kwargs,
350
+ ):
351
+ if input_ids is not None:
352
+ batch_size, _ = input_ids.shape
353
+ elif inputs_embeds is not None:
354
+ batch_size, _, _ = inputs_embeds.shape
355
+ else:
356
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
357
+
358
+ if inputs_embeds is not None and input_ids is None:
359
+ raise ValueError("When first calling the model, if input_embeds are passed, input_ids should not be None.")
360
+
361
+ if inputs_embeds is None:
362
+ inputs_embeds = self.get_input_embeddings()(input_ids).to(self.device)
363
+
364
+ if pixel_values is not None and image_hidden_states is not None:
365
+ raise ValueError("You cannot specify both pixel_values and image_hidden_states at the same time")
366
+
367
+ elif pixel_values is not None:
368
+ batch_size, num_images, num_channels, height, width = pixel_values.shape
369
+ pixel_values = pixel_values.to(dtype=self.dtype)
370
+ pixel_values = pixel_values.view(batch_size * num_images, *pixel_values.shape[2:])
371
+
372
+ nb_values_per_image = pixel_values.shape[1:].numel()
373
+ real_images_inds = (pixel_values == 0.0).sum(dim=(-1, -2, -3)) != nb_values_per_image
374
+ pixel_values = pixel_values[real_images_inds].contiguous()
375
+
376
+ if pixel_attention_mask is None:
377
+ pixel_attention_mask = torch.ones(
378
+ size=(pixel_values.size(0), pixel_values.size(2), pixel_values.size(3)),
379
+ dtype=torch.bool,
380
+ device=pixel_values.device,
381
+ )
382
+ else:
383
+ pixel_attention_mask = pixel_attention_mask.view(
384
+ batch_size * num_images, *pixel_attention_mask.shape[2:]
385
+ )
386
+ pixel_attention_mask = pixel_attention_mask[real_images_inds].contiguous()
387
+
388
+ patch_size = self.config.vision_config.patch_size
389
+ patches_subgrid = pixel_attention_mask.unfold(dimension=1, size=patch_size, step=patch_size)
390
+ patches_subgrid = patches_subgrid.unfold(dimension=2, size=patch_size, step=patch_size)
391
+ patch_attention_mask = (patches_subgrid.sum(dim=(-1, -2)) > 0).bool()
392
+
393
+ image_hidden_states = self.vision_model(
394
+ pixel_values=pixel_values, patch_attention_mask=patch_attention_mask, return_dict=True
395
+ ).last_hidden_state
396
+
397
+ connector_outputs = []
398
+ for i in range(image_hidden_states.shape[0]):
399
+ connector_outputs.append(self.connector(image_hidden_states[i : i + 1,]))
400
+ image_hidden_states = torch.cat(connector_outputs, dim=0)
401
+
402
+ elif image_hidden_states is not None:
403
+ image_hidden_states = image_hidden_states.to(dtype=self.dtype, device=input_ids.device)
404
+
405
+ if inputs_embeds is not None and image_hidden_states is not None:
406
+ inputs_embeds = self.inputs_merger(
407
+ input_ids=input_ids,
408
+ inputs_embeds=inputs_embeds,
409
+ image_hidden_states=image_hidden_states,
410
+ )
411
+
412
+ return inputs_embeds
413
+
414
+ def forward(
415
+ self,
416
+ input_ids: torch.LongTensor = None,
417
+ attention_mask: Optional[torch.Tensor] = None,
418
+ inputs_embeds: Optional[torch.FloatTensor] = None,
419
+ pixel_values: Optional[torch.FloatTensor] = None,
420
+ pixel_attention_mask: Optional[torch.BoolTensor] = None,
421
+ image_hidden_states: Optional[torch.FloatTensor] = None,
422
+ cache_position: torch.Tensor = None,
423
+ generate_idx: Optional[torch.Tensor] = None,
424
+ **kwargs,
425
+ ) -> Union[Tuple, Idefics3CausalLMOutputWithPast]:
426
+ # Prefill
427
+ if cache_position is None:
428
+ inputs_embeds = self._preprocess_prefill(
429
+ input_ids, inputs_embeds, pixel_values, pixel_attention_mask, image_hidden_states
430
+ )
431
+ logits = []
432
+ inputs = inputs_embeds if inputs_embeds is not None else input_ids
433
+ batch_size = inputs.shape[0]
434
+
435
+ for b_idx in range(batch_size):
436
+ cache_position = torch.arange(0, generate_idx[b_idx].item(), dtype=torch.int32).unsqueeze(0)
437
+ logit = self.text_model.prefill_decoder(
438
+ input_ids=inputs[b_idx : b_idx + 1] if inputs_embeds is None else None,
439
+ inputs_embeds=inputs[b_idx : b_idx + 1] if inputs_embeds is not None else None,
440
+ attention_mask=attention_mask[b_idx] if attention_mask is not None else None,
441
+ cache_position=cache_position,
442
+ batch_idx=b_idx,
443
+ )
444
+ logits.append(logit)
445
+
446
+ logits = torch.cat(logits, dim=0)
447
+
448
+ # Decoder
449
+ else:
450
+ logits = self.text_model.decoder(
451
+ input_ids=input_ids,
452
+ inputs_embeds=inputs_embeds,
453
+ cache_position=cache_position,
454
+ )
455
+
456
+ return RBLNDecoderOnlyOutput(
457
+ logits=logits,
458
+ generate_idx=generate_idx,
459
+ )
@@ -157,6 +157,12 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
157
157
  self._padding_side = "left" # set it to left by default, user can use setter to change padding_sides
158
158
  return super().__post_init__(**kwargs)
159
159
 
160
+ def get_attn_impl(self) -> str:
161
+ return self.rbln_config.language_model.attn_impl
162
+
163
+ def get_kvcache_num_blocks(self) -> int:
164
+ return self.rbln_config.language_model.kvcache_num_blocks
165
+
160
166
  def get_input_embeddings(self):
161
167
  return self.language_model.get_input_embeddings()
162
168
 
@@ -43,9 +43,16 @@ class SubModulesMixin:
43
43
  cls, model: "PreTrainedModel", model_save_dir: str, rbln_config: RBLNModelConfig, **kwargs
44
44
  ) -> List["RBLNBaseModel"]:
45
45
  rbln_submodules = []
46
+ submodule_prefix = getattr(cls, "_rbln_submodule_prefix", None)
47
+
46
48
  for submodule in cls._rbln_submodules:
47
49
  submodule_name = submodule["name"]
48
- torch_submodule: "PreTrainedModel" = getattr(model, submodule["name"])
50
+ if submodule_prefix is not None:
51
+ torch_submodule: PreTrainedModel = getattr(model, submodule_prefix)
52
+ torch_submodule = getattr(torch_submodule, submodule_name)
53
+ else:
54
+ torch_submodule: PreTrainedModel = getattr(model, submodule_name)
55
+
49
56
  cls_name = torch_submodule.__class__.__name__
50
57
  submodule_cls: Type["RBLNBaseModel"] = getattr(importlib.import_module("optimum.rbln"), f"RBLN{cls_name}")
51
58
  submodule_rbln_config = getattr(rbln_config, submodule_name) or {}
@@ -57,6 +64,7 @@ class SubModulesMixin:
57
64
 
58
65
  rbln_submodule = submodule_cls.from_model(
59
66
  model=torch_submodule,
67
+ config=torch_submodule.config,
60
68
  subfolder=submodule_name,
61
69
  model_save_dir=model_save_dir,
62
70
  rbln_config=submodule_rbln_config,
@@ -70,6 +78,7 @@ class SubModulesMixin:
70
78
  @classmethod
71
79
  def _load_submodules_from_compiled_models(cls, model_save_dir: str, rbln_config: RBLNModelConfig, **kwargs):
72
80
  rbln_submodules = []
81
+
73
82
  for submodule in cls._rbln_submodules:
74
83
  submodule_name = submodule["name"]
75
84
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: optimum-rbln
3
- Version: 0.7.4a6
3
+ Version: 0.7.4a7
4
4
  Summary: Optimum RBLN is the interface between the Hugging Face Transformers and Diffusers libraries and RBLN accelerators. It provides a set of tools enabling easy model loading and inference on single and multiple rbln device settings for different downstream tasks.
5
5
  Project-URL: Homepage, https://rebellions.ai
6
6
  Project-URL: Documentation, https://docs.rbln.ai
@@ -1,5 +1,5 @@
1
- optimum/rbln/__init__.py,sha256=gwlRrI10tkLlpXt-N3FbmMeVqEJRVExtfVrxsqdcCpM,12814
2
- optimum/rbln/__version__.py,sha256=BD2gZveYjqvIGZe_xk184XdKxoYxjbIrrR0xZAj20HQ,519
1
+ optimum/rbln/__init__.py,sha256=c2whRR6XkelNLlH1MwAKYMoaBEhmGxSQFrhfKS1JC-I,13186
2
+ optimum/rbln/__version__.py,sha256=ExpymO8GOd28EzUaHV6rNr0B3jcFOOGB0YXiUm3i25Y,519
3
3
  optimum/rbln/configuration_utils.py,sha256=1IX8AHmQbnJvhNm3yD6ZJABP7Oi40WvVSNlThty-ASk,29167
4
4
  optimum/rbln/modeling.py,sha256=qDXB69Oq0jx9hfONebDiSNe2_DgKYhnAGLTbGAtwYVw,9677
5
5
  optimum/rbln/modeling_base.py,sha256=3JQhXDh_Rz1f6bMNxgFk-Xd-lQcAVeh-q1KVO0ijSaA,24141
@@ -60,13 +60,13 @@ optimum/rbln/ops/attn.py,sha256=x02yFLk7FcONFqfow0ROmVy9fmxo5Pw0SPCiDY3AZNg,9012
60
60
  optimum/rbln/ops/flash_attn.py,sha256=NmCqUdMTzgJ4sbYGj8IWXJEsLWvbuCMponR01w5DK6w,4121
61
61
  optimum/rbln/ops/kv_cache_update.py,sha256=HjnHBR-oFrJQibsVnkYb0P5_-wEma8jl0mkjkylwakU,1270
62
62
  optimum/rbln/ops/linear.py,sha256=1_7Hg-9wXxhu97fqPobotLQx17k7VPeSSL91_9Z7EDg,1018
63
- optimum/rbln/transformers/__init__.py,sha256=9IzUXwbMZ1cGFNa25wvoBs42UkQrvZNgvlbZ8zjOTOs,7712
63
+ optimum/rbln/transformers/__init__.py,sha256=P89UOclQWiLgNkH90GXdnwWD2492O2tusM-fZApfBNg,8084
64
64
  optimum/rbln/transformers/configuration_alias.py,sha256=qFVfg6ohsR7a6b-CBgxjBUPDrk9MyiJwtO8AQah_RTU,1505
65
65
  optimum/rbln/transformers/configuration_generic.py,sha256=XIiZ1-5p1CMHhG7Sr2qR4SLYKcYw9aph7eGlga3Opx0,5056
66
66
  optimum/rbln/transformers/modeling_alias.py,sha256=yx7FnZQWAnrWzivaO5hI7T6i-fyLzt2tMIXG2oDNbPo,1657
67
67
  optimum/rbln/transformers/modeling_generic.py,sha256=nT_lytAILkYtwBVJKxXg0dxmh0UpjGYO6zOdLoMs1uU,12891
68
68
  optimum/rbln/transformers/modeling_rope_utils.py,sha256=3zwkhYUyTZhxCJUSmwCc88iiY1TppRWEY9ShwUqNB2k,14293
69
- optimum/rbln/transformers/models/__init__.py,sha256=9f2fJgdchqM_CJbx5BogQQ_xvCVtgYQ8bgyARt4lFu4,6790
69
+ optimum/rbln/transformers/models/__init__.py,sha256=72eMPN5UYGJ9P5gnJ2yi25cGdX1jV7viTOKmsX2OqBg,7221
70
70
  optimum/rbln/transformers/models/auto/__init__.py,sha256=GvGbb3ZpMv-h6euXeZ42jSizoOfrL2O1uvpAnfKxYEo,1034
71
71
  optimum/rbln/transformers/models/auto/auto_factory.py,sha256=jS33v5H6AY7yHZMAQPq94MBLer2wpb33IVMYcb1w57A,7047
72
72
  optimum/rbln/transformers/models/auto/modeling_auto.py,sha256=Un9qoqdy3dO8JBza_bTJF_6_fRVNM9QisihSgTRFI-o,3933
@@ -82,8 +82,8 @@ optimum/rbln/transformers/models/clip/configuration_clip.py,sha256=wgfZeVvcVdSzr
82
82
  optimum/rbln/transformers/models/clip/modeling_clip.py,sha256=UslcDN6otyQ_psou7F_YcdK5vCImEtgIdcbwmexSfOM,7256
83
83
  optimum/rbln/transformers/models/decoderonly/__init__.py,sha256=vQYZDDdoddwA7yKc5zzrq2Zs9sax-0p8rNF_aYfF4bk,1006
84
84
  optimum/rbln/transformers/models/decoderonly/configuration_decoderonly.py,sha256=b1W7zS0MUmeDd048bLp5AkZMrWd3LIhHaVy8NvlwdCw,4116
85
- optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py,sha256=BDATZTGF0J2zfc3u-zHXPKbkvsVHOwkNR10smB9Zuo8,41746
86
- optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py,sha256=uzw1nOz_jdi3lrBiLkkHy8QiOn-M5bCwNtyNs01a-d8,42815
85
+ optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py,sha256=NG2tKC3gT57r34PYKgU0evZHctEHzJGRrk2FOjLyK7Q,41748
86
+ optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py,sha256=5o2m_xPVjfCovP_jcW8E17sSKkLqcVblr4mFLbv-VDU,42991
87
87
  optimum/rbln/transformers/models/dpt/__init__.py,sha256=Nzep9mlzKyL1kV726IBqY8DnLp1DkH9JzFeknWSRhok,714
88
88
  optimum/rbln/transformers/models/dpt/configuration_dpt.py,sha256=4fW6bzVhaAxym4wGV3F785rvUOoWPyw_gdEMqB08Leg,755
89
89
  optimum/rbln/transformers/models/dpt/modeling_dpt.py,sha256=oKLX7MQZvfk1QB8wOtcdi7AmZH2fOIVbypa9A3RA9MI,733
@@ -99,13 +99,16 @@ optimum/rbln/transformers/models/gpt2/__init__.py,sha256=socBMIBZSiLbrVN12rQ4nL9
99
99
  optimum/rbln/transformers/models/gpt2/configuration_gpt2.py,sha256=vKvJD8P9Li4W9wdVoQcqMEr1MwEXojPBnF2NE85VXAo,772
100
100
  optimum/rbln/transformers/models/gpt2/gpt2_architecture.py,sha256=1IxqHmB-GlH2Dv2Yk4z0rMxL9CpxMGHhSu_x8_4cxvs,3008
101
101
  optimum/rbln/transformers/models/gpt2/modeling_gpt2.py,sha256=qBDanUk_O-HtOIVCA4IE3FYyCsnL9xIDK00vft-0caw,1490
102
+ optimum/rbln/transformers/models/idefics3/__init__.py,sha256=ulxE7HEfXsNJhd25J9Fvi6vggo9aZH9sLKJjWB6LlzQ,814
103
+ optimum/rbln/transformers/models/idefics3/configuration_idefics3.py,sha256=sM0pXsvkxcpDXagoKlqwKdBAcNdayB9KlWdYC9xlyDU,1889
104
+ optimum/rbln/transformers/models/idefics3/modeling_idefics3.py,sha256=Rr9BJDyoOqJFQ8dJV78QU4Tjjhhj3aqRk05JcDqFv6Y,17904
102
105
  optimum/rbln/transformers/models/llama/__init__.py,sha256=knxvRkPx8x6-WOxqSq_PlaKYD-9F9Q8dh7r095Esey0,708
103
106
  optimum/rbln/transformers/models/llama/configuration_llama.py,sha256=B9gr4pTn9yiv3-8DIk0P7_AQdIHEc7SuLaH9gZAmP8E,773
104
107
  optimum/rbln/transformers/models/llama/llama_architecture.py,sha256=S7MCPfyjG5eUqgaS-QNBB0ApUD6wnb5fR0RHq7k7-pA,728
105
108
  optimum/rbln/transformers/models/llama/modeling_llama.py,sha256=Z3iony7icoFhRQ11MAuFx9UF03uJCsvJQZ6bxHXlrgk,1530
106
109
  optimum/rbln/transformers/models/llava_next/__init__.py,sha256=kDXKr7wMkp1XqE__DER2B8kQF_NYMxhzsQS5ytGg56I,752
107
110
  optimum/rbln/transformers/models/llava_next/configuration_llava_next.py,sha256=QPreWZyohwRL23GOyvoAfKtk5UNg7IJ_Y_pNfUDe7cU,1838
108
- optimum/rbln/transformers/models/llava_next/modeling_llava_next.py,sha256=-NvLf9ixzEbVqUKlkyZW94n0tmnsIQ7CvP1Y7U1JEPU,25773
111
+ optimum/rbln/transformers/models/llava_next/modeling_llava_next.py,sha256=xOXc1XUIK4oLSFvAq7Q0lxiOLlDFMbFdOcg5JvLnVkI,25979
109
112
  optimum/rbln/transformers/models/midm/__init__.py,sha256=IC3FETwgYinbp3wDj7tp4zIHJhbqM-c6GfTRdYcMNj8,913
110
113
  optimum/rbln/transformers/models/midm/configuration_midm.py,sha256=Kv5g5dIsBrhGcZ2_pFUOPNB80np4Xiw0wPH1IZm1PHI,772
111
114
  optimum/rbln/transformers/models/midm/midm_architecture.py,sha256=357iviqQkzI0s_lU_teH1sVOChNRDUABe3GA0HuhZZY,5444
@@ -159,8 +162,8 @@ optimum/rbln/utils/logging.py,sha256=VKKBmlQSdg6iZCGmAXaWYiW67K84jyp1QJhLQSSjPPE
159
162
  optimum/rbln/utils/model_utils.py,sha256=DfD_Z2qvZHqcddXqnzTM1AN8khanj3-DXK2lJvVxDvs,1278
160
163
  optimum/rbln/utils/runtime_utils.py,sha256=LoKNK3AQNV_BSScstIZWjICkJf265MnUgy360BOocVI,5454
161
164
  optimum/rbln/utils/save_utils.py,sha256=hG5uOtYmecSXZuGTvCXsTM-SiyZpr5q3InUGCCq_jzQ,3619
162
- optimum/rbln/utils/submodule.py,sha256=_qX15LE2nHzOFVUp5U5DqdJx11RzPBR848PR0nsjQBc,4293
163
- optimum_rbln-0.7.4a6.dist-info/METADATA,sha256=m4NMptBdyrOQ746DO16TCGBCSHeidkLBpXQQC8_EEhY,5300
164
- optimum_rbln-0.7.4a6.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
165
- optimum_rbln-0.7.4a6.dist-info/licenses/LICENSE,sha256=QwcOLU5TJoTeUhuIXzhdCEEDDvorGiC6-3YTOl4TecE,11356
166
- optimum_rbln-0.7.4a6.dist-info/RECORD,,
165
+ optimum/rbln/utils/submodule.py,sha256=TtcH3OLctFd2Dosc-zNMGZ8xOXKKUfE91dLQ1v09E8Q,4636
166
+ optimum_rbln-0.7.4a7.dist-info/METADATA,sha256=QEd-nMYyV2VO40XhrSwZwApvFaWXp9MZ3RI_MFBX8z8,5300
167
+ optimum_rbln-0.7.4a7.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
168
+ optimum_rbln-0.7.4a7.dist-info/licenses/LICENSE,sha256=QwcOLU5TJoTeUhuIXzhdCEEDDvorGiC6-3YTOl4TecE,11356
169
+ optimum_rbln-0.7.4a7.dist-info/RECORD,,