optimum-rbln 0.8.2a5__py3-none-any.whl → 0.8.2a6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


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

@@ -0,0 +1,379 @@
1
+ # Copyright 2025 Rebellions Inc. All rights reserved.
2
+
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at:
6
+
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ from transformers import (
20
+ AutoModelForImageTextToText,
21
+ LlavaForConditionalGeneration,
22
+ PretrainedConfig,
23
+ PreTrainedModel,
24
+ )
25
+ from transformers.modeling_outputs import BaseModelOutputWithPooling
26
+ from transformers.models.llava.modeling_llava import LlavaCausalLMOutputWithPast
27
+
28
+ from ....configuration_utils import RBLNCompileConfig, RBLNModelConfig
29
+ from ....modeling import RBLNModel
30
+ from ....utils.logging import get_logger
31
+ from ..decoderonly.modeling_decoderonly import RBLNDecoderOnlyForCausalLMOutput
32
+
33
+
34
+ logger = get_logger(__name__)
35
+
36
+ if TYPE_CHECKING:
37
+ from transformers import (
38
+ AutoFeatureExtractor,
39
+ AutoProcessor,
40
+ AutoTokenizer,
41
+ PretrainedConfig,
42
+ )
43
+
44
+
45
+ class LoopVisionTower:
46
+ def __init__(self, vision_tower: RBLNModel) -> None:
47
+ self.vision_tower = vision_tower
48
+
49
+ def forward(self, *args, **kwargs):
50
+ pixel_values = args[0]
51
+ image_sizes = kwargs.pop("image_sizes", None)
52
+
53
+ outputs = []
54
+ for i in range(pixel_values.shape[0]):
55
+ outputs.append(
56
+ self.vision_tower(
57
+ pixel_values[i : i + 1], image_sizes[i : i + 1] if image_sizes is not None else None, **kwargs
58
+ )
59
+ )
60
+
61
+ if hasattr(self.vision_tower.rbln_config, "max_image_size"):
62
+ last_hidden_states = [output.last_hidden_state for output in outputs]
63
+ last_hidden_states = torch.cat(last_hidden_states, dim=1)
64
+ hidden_states = tuple(
65
+ torch.cat(
66
+ [output.hidden_states[layer_idx] for output in outputs],
67
+ dim=1,
68
+ )
69
+ for layer_idx in range(len(outputs[0].hidden_states))
70
+ )
71
+
72
+ else:
73
+ last_hidden_states = [output.last_hidden_state for output in outputs]
74
+ last_hidden_states = torch.cat(last_hidden_states, dim=0)
75
+ hidden_states = [output.hidden_states for output in outputs]
76
+ hidden_states = tuple(
77
+ torch.cat(tuple((hidden_states[n][i] for n in range(pixel_values.shape[0]))), dim=0)
78
+ for i in range(len(hidden_states[0]))
79
+ )
80
+
81
+ return BaseModelOutputWithPooling(
82
+ last_hidden_state=last_hidden_states,
83
+ hidden_states=hidden_states,
84
+ )
85
+
86
+ def __call__(self, *args: Any, **kwds: Any) -> Any:
87
+ return self.forward(*args, **kwds)
88
+
89
+ def __repr__(self) -> str:
90
+ return repr(self.vision_tower)
91
+
92
+
93
+ class LoopProjector:
94
+ def __init__(self, multi_modal_projector) -> None:
95
+ self.multi_modal_projector = multi_modal_projector
96
+
97
+ def forward(self, *args, **kwargs):
98
+ # Loop instead of batch
99
+ image_feature = args[0]
100
+
101
+ outputs = []
102
+ for i in range(image_feature.shape[0]):
103
+ outputs.append(self.multi_modal_projector(image_feature[i : i + 1]))
104
+
105
+ # FIXME:: This can be optimized using out= API of rbln runtime.
106
+ outputs = torch.cat(outputs, dim=0)
107
+ return outputs
108
+
109
+ def __call__(self, *args: Any, **kwds: Any) -> Any:
110
+ return self.forward(*args, **kwds)
111
+
112
+ def __repr__(self) -> str:
113
+ return repr(self.multi_modal_projector)
114
+
115
+
116
+ class RBLNLlavaForConditionalGeneration(RBLNModel):
117
+ auto_model_class = AutoModelForImageTextToText
118
+ _rbln_submodules = [
119
+ {"name": "vision_tower"},
120
+ {"name": "language_model"},
121
+ ]
122
+
123
+ def __getattr__(self, __name: str) -> Any:
124
+ def redirect(func):
125
+ return lambda *pargs, **kwargs: func(self, *pargs, **kwargs)
126
+
127
+ val = getattr(LlavaForConditionalGeneration, __name)
128
+
129
+ if isinstance(val, Callable) and "self" in set(inspect.signature(val).parameters):
130
+ return redirect(val)
131
+ return val
132
+
133
+ def can_generate(self):
134
+ return True
135
+
136
+ def __post_init__(self, **kwargs):
137
+ self.vision_tower = LoopVisionTower(self.rbln_submodules[0])
138
+ self.language_model = self.rbln_submodules[1]
139
+ self.multi_modal_projector = LoopProjector(self.model[0])
140
+ self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
141
+ return super().__post_init__(**kwargs)
142
+
143
+ def get_attn_impl(self) -> str:
144
+ return self.rbln_config.language_model.attn_impl
145
+
146
+ def get_kvcache_num_blocks(self) -> int:
147
+ return self.rbln_config.language_model.kvcache_num_blocks
148
+
149
+ def get_input_embeddings(self):
150
+ return self.language_model.get_input_embeddings()
151
+
152
+ @classmethod
153
+ def wrap_model_if_needed(cls, model: "PreTrainedModel", rbln_config: RBLNModelConfig):
154
+ return model.multi_modal_projector
155
+
156
+ @classmethod
157
+ def _update_rbln_config(
158
+ cls,
159
+ preprocessors: Optional[Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"]],
160
+ model: Optional["PreTrainedModel"] = None,
161
+ model_config: Optional["PretrainedConfig"] = None,
162
+ rbln_config: Optional[RBLNModelConfig] = None,
163
+ ) -> RBLNModelConfig:
164
+ if hasattr(rbln_config.vision_tower, "max_image_size"):
165
+ num_positions = (
166
+ rbln_config.vision_tower.batch_size
167
+ * (rbln_config.vision_tower.max_image_size[0] // model_config.vision_config.patch_size)
168
+ * (rbln_config.vision_tower.max_image_size[1] // model_config.vision_config.patch_size)
169
+ )
170
+ selected_image_feature_dim = num_positions
171
+
172
+ else:
173
+ num_positions = (model_config.vision_config.image_size // model_config.vision_config.patch_size) ** 2 + 1
174
+ selected_image_feature_dim = num_positions - 1
175
+
176
+ input_info = [
177
+ (
178
+ "image_features",
179
+ [rbln_config.batch_size, selected_image_feature_dim, model_config.vision_config.hidden_size],
180
+ "float32",
181
+ )
182
+ ]
183
+
184
+ rbln_compile_config = RBLNCompileConfig(input_info=input_info)
185
+ rbln_config.set_compile_cfgs([rbln_compile_config])
186
+ return rbln_config
187
+
188
+ def prepare_inputs_for_generation(
189
+ self,
190
+ input_ids,
191
+ inputs_embeds=None,
192
+ pixel_values=None,
193
+ attention_mask=None,
194
+ cache_position=None,
195
+ image_sizes=None,
196
+ generate_idx=None,
197
+ **kwargs,
198
+ ):
199
+ is_prefill_phase = generate_idx is None
200
+ model_inputs = {}
201
+
202
+ if is_prefill_phase:
203
+ generate_idx = attention_mask.sum(dim=-1, keepdim=True).int()
204
+ cache_position = None
205
+ pixel_values = pixel_values
206
+ model_inputs.update({"image_sizes": image_sizes})
207
+ else:
208
+ if inputs_embeds is not None:
209
+ raise NotImplementedError("Specifying inputs_embeds in decoder phase is not supported.")
210
+
211
+ pixel_values = None
212
+ input_ids = input_ids[:, -1:]
213
+ cache_position = generate_idx
214
+ generate_idx = generate_idx + 1
215
+ model_inputs.update({"input_ids": input_ids})
216
+
217
+ if inputs_embeds is not None:
218
+ if self.rbln_config.use_inputs_embeds:
219
+ model_inputs.update({"inputs_embeds": inputs_embeds})
220
+ else:
221
+ raise ValueError(
222
+ "The specifying inputs_embeds is only supported when using a compiled RBLN model with 'rbln_use_inputs_embeds' set to True."
223
+ )
224
+ else:
225
+ model_inputs.update({"input_ids": input_ids})
226
+
227
+ model_inputs.update(
228
+ {
229
+ "attention_mask": attention_mask,
230
+ "pixel_values": pixel_values,
231
+ "cache_position": cache_position,
232
+ "generate_idx": generate_idx,
233
+ }
234
+ )
235
+ return model_inputs
236
+
237
+ def _update_model_kwargs_for_generation(self, outputs, model_kwargs, is_encoder_decoder, **kwargs):
238
+ model_kwargs["generate_idx"] = outputs.generate_idx
239
+ return model_kwargs
240
+
241
+ def get_image_features(
242
+ self,
243
+ pixel_values: torch.FloatTensor,
244
+ vision_feature_layer: Union[int, List[int]],
245
+ vision_feature_select_strategy: str,
246
+ **kwargs,
247
+ ):
248
+ if vision_feature_select_strategy not in ["default", "full"]:
249
+ raise ValueError(f"Unexpected select feature strategy: {self.config.vision_feature_select_strategy}")
250
+
251
+ kwargs = {k: v for k, v in kwargs.items() if v is not None}
252
+ image_outputs = self.vision_tower(pixel_values, output_hidden_states=True, **kwargs)
253
+
254
+ if isinstance(vision_feature_layer, int):
255
+ selected_image_feature = image_outputs.hidden_states[vision_feature_layer]
256
+ if vision_feature_select_strategy == "default":
257
+ selected_image_feature = selected_image_feature[:, 1:]
258
+ else:
259
+ hs_pool = [image_outputs.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
260
+ if vision_feature_select_strategy == "default":
261
+ hs_pool = [hs[:, 1:] for hs in hs_pool]
262
+ selected_image_feature = torch.cat(hs_pool, dim=-1)
263
+
264
+ if hasattr(self.rbln_config.vision_tower, "max_image_size"):
265
+ num_real_patches = selected_image_feature.shape[1]
266
+ max_patches = (
267
+ (self.rbln_config.vision_tower.max_image_size[0] // self.config.vision_config.patch_size)
268
+ * (self.rbln_config.vision_tower.max_image_size[1] // self.config.vision_config.patch_size)
269
+ * pixel_values.shape[0]
270
+ )
271
+ num_padding_patches = max_patches - num_real_patches
272
+
273
+ padding_tensor = torch.zeros(
274
+ (selected_image_feature.shape[0], num_padding_patches, selected_image_feature.shape[2]),
275
+ dtype=selected_image_feature.dtype,
276
+ )
277
+ padded_feature = torch.cat([selected_image_feature, padding_tensor], dim=1)
278
+ padded_projected_feature = self.multi_modal_projector(padded_feature)
279
+ image_features = padded_projected_feature[:, :num_real_patches, :]
280
+ else:
281
+ image_features = self.multi_modal_projector(selected_image_feature)
282
+
283
+ return image_features
284
+
285
+ def _preprocess_prefill(
286
+ self,
287
+ input_ids: Optional[torch.LongTensor] = None,
288
+ pixel_values: Optional[torch.FloatTensor] = None,
289
+ inputs_embeds: Optional[torch.FloatTensor] = None,
290
+ vision_feature_layer: Optional[Union[int, List[int]]] = None,
291
+ vision_feature_select_strategy: Optional[str] = None,
292
+ return_dict: Optional[bool] = None,
293
+ image_sizes: Optional[torch.Tensor] = None,
294
+ **lm_kwargs,
295
+ ):
296
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
297
+ vision_feature_layer = (
298
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
299
+ )
300
+ vision_feature_select_strategy = (
301
+ vision_feature_select_strategy
302
+ if vision_feature_select_strategy is not None
303
+ else self.config.vision_feature_select_strategy
304
+ )
305
+
306
+ if (input_ids is None) ^ (inputs_embeds is not None):
307
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
308
+
309
+ if pixel_values is not None and inputs_embeds is not None:
310
+ raise ValueError(
311
+ "You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
312
+ )
313
+
314
+ if inputs_embeds is None:
315
+ inputs_embeds = self.get_input_embeddings()(input_ids)
316
+
317
+ if pixel_values is not None:
318
+ image_features = self.get_image_features(
319
+ pixel_values=pixel_values,
320
+ vision_feature_layer=vision_feature_layer,
321
+ vision_feature_select_strategy=vision_feature_select_strategy,
322
+ image_sizes=image_sizes,
323
+ )
324
+
325
+ special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
326
+ special_image_mask = special_image_mask.expand_as(inputs_embeds)
327
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
328
+
329
+ return inputs_embeds
330
+
331
+ def forward(
332
+ self,
333
+ input_ids: Optional[torch.LongTensor] = None,
334
+ pixel_values: Optional[torch.FloatTensor] = None,
335
+ attention_mask: Optional[torch.Tensor] = None,
336
+ inputs_embeds: Optional[torch.FloatTensor] = None,
337
+ return_dict: Optional[bool] = None,
338
+ cache_position: Optional[torch.LongTensor] = None,
339
+ image_sizes: Optional[torch.Tensor] = None,
340
+ generate_idx: Optional[torch.Tensor] = None,
341
+ **kwargs,
342
+ ) -> Union[Tuple, LlavaCausalLMOutputWithPast]:
343
+ # Prefill
344
+ if cache_position is None:
345
+ inputs_embeds = self._preprocess_prefill(
346
+ input_ids=input_ids, inputs_embeds=inputs_embeds, pixel_values=pixel_values, image_sizes=image_sizes
347
+ )
348
+ logits = []
349
+ inputs = inputs_embeds if inputs_embeds is not None else input_ids
350
+ batch_size = inputs.shape[0]
351
+
352
+ for b_idx in range(batch_size):
353
+ cache_position = torch.arange(0, generate_idx[b_idx].item(), dtype=torch.int32).unsqueeze(0)
354
+ output = self.language_model.prefill_decoder(
355
+ input_ids=inputs[b_idx : b_idx + 1] if inputs_embeds is None else None,
356
+ inputs_embeds=inputs[b_idx : b_idx + 1] if inputs_embeds is not None else None,
357
+ attention_mask=attention_mask[b_idx] if attention_mask is not None else None,
358
+ cache_position=cache_position,
359
+ batch_idx=b_idx,
360
+ )
361
+ logits.append(output.logits)
362
+
363
+ logits = torch.cat(logits, dim=0)
364
+
365
+ # Decoder
366
+ else:
367
+ logits = self.language_model.decoder(
368
+ input_ids=input_ids,
369
+ inputs_embeds=inputs_embeds,
370
+ cache_position=cache_position,
371
+ ).logits
372
+
373
+ if not return_dict:
374
+ return logits, generate_idx
375
+ else:
376
+ return RBLNDecoderOnlyForCausalLMOutput(
377
+ logits=logits,
378
+ generate_idx=generate_idx,
379
+ )
@@ -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_pixtral import RBLNPixtralVisionModelConfig
16
+ from .modeling_pixtral import RBLNPixtralVisionModel
@@ -0,0 +1,43 @@
1
+ # Copyright 2025 Rebellions Inc. All rights reserved.
2
+
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at:
6
+
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Any, Dict, Optional, Tuple
16
+
17
+ from ....configuration_utils import RBLNModelConfig
18
+
19
+
20
+ class RBLNPixtralVisionModelConfig(RBLNModelConfig):
21
+ def __init__(
22
+ self,
23
+ max_image_size: Tuple = None,
24
+ batch_size: Optional[int] = None,
25
+ output_hidden_states: Optional[bool] = None,
26
+ **kwargs: Dict[str, Any],
27
+ ):
28
+ """
29
+ Args:
30
+ max_image_size (Tuple): The size of max input images. A tuple (max_height, max_width)
31
+ batch_size (Optional[int]): The batch size for image processing. Defaults to 1.
32
+ **kwargs: Additional arguments passed to the parent RBLNModelConfig.
33
+
34
+ Raises:
35
+ ValueError: If batch_size is not a positive integer.
36
+ """
37
+ super().__init__(**kwargs)
38
+ self.batch_size = batch_size or 1
39
+ if not isinstance(self.batch_size, int) or self.batch_size < 0:
40
+ raise ValueError(f"batch_size must be a positive integer, got {self.batch_size}")
41
+
42
+ self.max_image_size = max_image_size
43
+ self.output_hidden_states = output_hidden_states