optimum-rbln 0.8.4a0__py3-none-any.whl → 0.8.4a2__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,88 @@
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, List, Optional, Union
16
+
17
+ from ....configuration_utils import RBLNModelConfig
18
+ from ..decoderonly.configuration_decoderonly import RBLNDecoderOnlyModelForCausalLMConfig
19
+
20
+
21
+ class RBLNQwen2VLForConditionalGenerationConfig(RBLNDecoderOnlyModelForCausalLMConfig):
22
+ submodules = ["visual"]
23
+
24
+ def __init__(
25
+ self,
26
+ use_inputs_embeds: bool = True,
27
+ visual: Optional[RBLNModelConfig] = None,
28
+ **kwargs: Dict[str, Any],
29
+ ):
30
+ """
31
+ Args:
32
+ use_inputs_embeds (bool): Whether or not to use `inputs_embeds` as input. Defaults to `True`.
33
+ visual (Optional[RBLNModelConfig]): Configuration for the vision encoder component.
34
+ **kwargs: Additional arguments passed to the parent `RBLNDecoderOnlyModelForCausalLMConfig`.
35
+
36
+ Raises:
37
+ ValueError: If `use_inputs_embeds` is False.
38
+ ValueError: If the visual configuration is provided but contains invalid settings, such as an invalid max_seq_lens (e.g., not a positive integer or insufficient for the expected resolution).
39
+ ValueError: If visual is None and no default vision configuration can be inferred for the model architecture.
40
+ ValueError: If any inherited parameters violate constraints defined in the parent class, such as batch_size not being a positive integer, prefill_chunk_size not being divisible by 64, or max_seq_len not meeting requirements for Flash Attention.
41
+ """
42
+ super().__init__(use_inputs_embeds=use_inputs_embeds, **kwargs)
43
+ if not self.use_inputs_embeds:
44
+ raise ValueError(
45
+ "RBLNQwen2VLForConditionalGenerationConfig does not allow `use_inputs_embeds` to be set to False, "
46
+ "as RBLNQwen2VLForConditionalGeneration accepts only `inputs_embeds` as input."
47
+ )
48
+ self.visual = visual
49
+
50
+
51
+ class RBLNQwen2VisionTransformerPretrainedModelConfig(RBLNModelConfig):
52
+ def __init__(self, max_seq_lens: Union[int, List[int]] = None, **kwargs: Dict[str, Any]):
53
+ """
54
+ Args:
55
+ max_seq_lens (Optional[Union[int, List[int]]]): Maximum sequence lengths for Vision
56
+ Transformer attention. Can be an integer or list of integers, each indicating
57
+ the number of patches in a sequence for an image or video. For example, an image
58
+ of 224x224 pixels with patch size 14 results in (224/14) * (224/14) = 256 patches,
59
+ so `max_seq_lens` must be at least 256. RBLN optimization runs inference per image
60
+ or video frame, so set `max_seq_lens` to match the maximum expected resolution to
61
+ optimize computation. If not provided, a `ValueError` is raised.
62
+ **kwargs: Additional arguments passed to the parent RBLNModelConfig.
63
+
64
+ Raises:
65
+ ValueError: If batch_size is not a positive integer.
66
+ ValueError: If `max_seq_lens` (or any value in the list) is not a positive integer.
67
+ ValueError: If `max_seq_lens` is insufficient for the expected image/video resolution.
68
+ ValueError: If `batch_size` (inherited from RBLNModelConfig) is not a positive integer.
69
+
70
+ Max Seq Lens:
71
+ Since `Qwen2VLForConditionalGeneration` performs inference on a per-image or per-frame basis,
72
+ `max_seq_lens` should be set based on the maximum expected resolution of the input images or video frames.
73
+
74
+ The value must be greater than or equal to the number of patches generated from the input image.
75
+ For example, a 224x224 image with a patch size of 14 results in (224 / 14) * (224 / 14) = 256 patches.
76
+ Therefore, `max_seq_lens` must be at least 256.
77
+ """
78
+ super().__init__(**kwargs)
79
+
80
+ if max_seq_lens is not None:
81
+ if isinstance(max_seq_lens, int):
82
+ max_seq_lens = [max_seq_lens]
83
+ elif isinstance(max_seq_lens, list):
84
+ max_seq_lens.sort(reverse=True)
85
+ else:
86
+ raise ValueError("'max_seq_lens' must be specified.")
87
+
88
+ self.max_seq_lens = max_seq_lens
@@ -0,0 +1,506 @@
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 pathlib import Path
17
+ from typing import TYPE_CHECKING, Any, Callable, Optional, Union
18
+
19
+ import torch
20
+ from transformers import (
21
+ AutoModelForVision2Seq,
22
+ PretrainedConfig,
23
+ PreTrainedModel,
24
+ Qwen2VLForConditionalGeneration,
25
+ )
26
+ from transformers.modeling_utils import no_init_weights
27
+ from transformers.models.qwen2_vl.modeling_qwen2_vl import (
28
+ PatchEmbed,
29
+ Qwen2VisionTransformerPretrainedModel,
30
+ Qwen2VLRotaryEmbedding,
31
+ VisionRotaryEmbedding,
32
+ )
33
+
34
+ from ....configuration_utils import RBLNCompileConfig
35
+ from ....modeling import RBLNModel
36
+ from ....utils.logging import get_logger
37
+ from ..decoderonly.modeling_decoderonly import RBLNDecoderOnlyModelForCausalLM, RBLNDecoderOnlyOutput
38
+ from .configuration_qwen2_vl import (
39
+ RBLNQwen2VisionTransformerPretrainedModelConfig,
40
+ RBLNQwen2VLForConditionalGenerationConfig,
41
+ )
42
+ from .qwen2_vl_architecture import Qwen2VisionTransformerWrapper, Qwen2VL_LanguageModelWrapper
43
+
44
+
45
+ logger = get_logger(__name__)
46
+
47
+ if TYPE_CHECKING:
48
+ from transformers import (
49
+ AutoFeatureExtractor,
50
+ AutoProcessor,
51
+ AutoTokenizer,
52
+ PretrainedConfig,
53
+ )
54
+
55
+
56
+ class RBLNQwen2VisionTransformerPretrainedModel(RBLNModel):
57
+ auto_model_class = None
58
+
59
+ def __post_init__(self, **kwargs):
60
+ self.transformer = self.model[0]
61
+ self.max_seq_lens = torch.tensor(sorted(self.rbln_config.max_seq_lens, reverse=False))
62
+ config = self.config
63
+
64
+ self.patch_size = config.spatial_patch_size
65
+ self.spatial_merge_size = config.spatial_merge_size
66
+ self.spatial_merge_unit = config.spatial_merge_size * config.spatial_merge_size
67
+ self.rotary_pos_emb = VisionRotaryEmbedding((config.embed_dim // config.num_heads) // 2)
68
+ with no_init_weights():
69
+ self.patch_embed = PatchEmbed(
70
+ patch_size=config.patch_size,
71
+ temporal_patch_size=config.temporal_patch_size,
72
+ in_channels=config.in_channels,
73
+ embed_dim=config.embed_dim,
74
+ ).eval()
75
+ artifacts = torch.load(self.model_save_dir / self.subfolder / "torch_artifacts.pth", weights_only=False)
76
+ self.patch_embed.load_state_dict(artifacts["patch_embed"])
77
+
78
+ @classmethod
79
+ def save_torch_artifacts(
80
+ cls,
81
+ model: "Qwen2VLForConditionalGeneration",
82
+ save_dir_path: Path,
83
+ subfolder: str,
84
+ rbln_config: RBLNQwen2VisionTransformerPretrainedModelConfig,
85
+ ):
86
+ save_dict = {}
87
+ save_dict["patch_embed"] = model.patch_embed.state_dict()
88
+ torch.save(save_dict, save_dir_path / subfolder / "torch_artifacts.pth")
89
+
90
+ @classmethod
91
+ def wrap_model_if_needed(
92
+ cls, model: "PreTrainedModel", rbln_config: RBLNQwen2VisionTransformerPretrainedModelConfig
93
+ ):
94
+ return Qwen2VisionTransformerWrapper(model).eval()
95
+
96
+ def __getattr__(self, __name: str) -> Any:
97
+ def redirect(func):
98
+ return lambda *pargs, **kwargs: func(self, *pargs, **kwargs)
99
+
100
+ val = getattr(Qwen2VisionTransformerPretrainedModel, __name)
101
+
102
+ if isinstance(val, Callable) and "self" in set(inspect.signature(val).parameters):
103
+ return redirect(val)
104
+ return val
105
+
106
+ @classmethod
107
+ def _update_rbln_config(
108
+ cls,
109
+ preprocessors: Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"],
110
+ model: Optional["PreTrainedModel"] = None,
111
+ model_config: "PretrainedConfig" = None,
112
+ rbln_config: Optional[RBLNQwen2VisionTransformerPretrainedModelConfig] = None,
113
+ ) -> RBLNQwen2VisionTransformerPretrainedModelConfig:
114
+ hidden_size = getattr(model_config, "embed_dim")
115
+ num_heads = getattr(model_config, "num_heads")
116
+ head_dim = hidden_size // num_heads
117
+
118
+ input_infos = []
119
+ for max_seq_len in rbln_config.max_seq_lens:
120
+ input_info = [
121
+ ("hidden_states", [max_seq_len, hidden_size], "float32"),
122
+ ("full_attn_masks", [1, 1, max_seq_len, max_seq_len], "float32"),
123
+ (
124
+ "cos",
125
+ [1, 1, max_seq_len, head_dim],
126
+ "float32",
127
+ ),
128
+ (
129
+ "sin",
130
+ [1, 1, max_seq_len, head_dim],
131
+ "float32",
132
+ ),
133
+ ]
134
+ input_infos.append(input_info)
135
+
136
+ rbln_compile_config = RBLNCompileConfig(input_info=input_infos)
137
+ rbln_config.set_compile_cfgs([rbln_compile_config])
138
+
139
+ return rbln_config
140
+
141
+ @staticmethod
142
+ def _pad_for_full_attn_layers(hidden_state, cos, sin, max_seq_len):
143
+ if hidden_state.shape[0] < max_seq_len:
144
+ full_padding_size = max_seq_len - hidden_state.shape[0]
145
+ full_padding_hidden = torch.zeros(
146
+ full_padding_size,
147
+ hidden_state.shape[-1],
148
+ dtype=hidden_state.dtype,
149
+ )
150
+ hidden_state_full_padded = torch.cat([hidden_state, full_padding_hidden], dim=0)
151
+ full_padding_pos = torch.zeros(
152
+ full_padding_size,
153
+ cos.shape[-1],
154
+ dtype=cos.dtype,
155
+ )
156
+ cos_full_padded = torch.cat([cos, full_padding_pos], dim=0)
157
+ sin_full_padded = torch.cat([sin, full_padding_pos], dim=0)
158
+ else:
159
+ hidden_state_full_padded = hidden_state
160
+ cos_full_padded = cos
161
+ sin_full_padded = sin
162
+
163
+ full_attn_masks = torch.ones(
164
+ 1,
165
+ 1,
166
+ max_seq_len,
167
+ max_seq_len,
168
+ dtype=torch.float32,
169
+ )
170
+
171
+ full_attn_masks[:, :, hidden_state.shape[0] : max_seq_len, :] = 0
172
+ full_attn_masks[:, :, :, hidden_state.shape[0] : max_seq_len] = 0
173
+ return hidden_state_full_padded, cos_full_padded, sin_full_padded, full_attn_masks
174
+
175
+ def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor) -> torch.Tensor:
176
+ # Processes a batch of images (or frames) through the vision transformer.
177
+ # Each image is handled independently for padding and attention mask generation.
178
+
179
+ hidden_states = self.patch_embed(hidden_states)
180
+ rotary_pos_emb = self.rot_pos_emb(grid_thw)
181
+ emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
182
+ position_embeddings = (emb.cos(), emb.sin())
183
+
184
+ cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum(
185
+ dim=0,
186
+ dtype=torch.int32,
187
+ )
188
+ cu_seqlens = torch.nn.functional.pad(cu_seqlens, (1, 0), value=0)
189
+
190
+ num_images = len(cu_seqlens) - 1
191
+ output_hidden_states = []
192
+
193
+ # Process each image in the sequence
194
+ for i in range(num_images):
195
+ image_s, image_e = cu_seqlens[i], cu_seqlens[i + 1]
196
+
197
+ # Select the nearest higher max_seq_len from the available compiled models.
198
+ cu_seq_len = image_e - image_s
199
+ try:
200
+ cu_index = torch.searchsorted(self.max_seq_lens, cu_seq_len).item()
201
+ max_seq_len = self.max_seq_lens[cu_index]
202
+ except Exception:
203
+ raise ValueError(
204
+ f"Required seq_len({cu_seq_len}) is larger than available max_seq_lens({self.max_seq_lens.tolist()})."
205
+ )
206
+
207
+ # Padding for Full Attention Layers
208
+ hidden_state_full_padded, cos_full_padded, sin_full_padded, full_attn_masks = (
209
+ self._pad_for_full_attn_layers(
210
+ hidden_states[image_s:image_e],
211
+ position_embeddings[0][image_s:image_e],
212
+ position_embeddings[1][image_s:image_e],
213
+ max_seq_len,
214
+ )
215
+ )
216
+
217
+ # RBLN run with the compiled model
218
+ output = self.transformer(
219
+ hidden_state_full_padded,
220
+ full_attn_masks,
221
+ cos_full_padded[None, None, :, :],
222
+ sin_full_padded[None, None, :, :],
223
+ )
224
+ # Depadding
225
+ depadded_output = output[: cu_seq_len // self.spatial_merge_unit]
226
+ output_hidden_states.append(depadded_output)
227
+
228
+ hidden_states = torch.cat(output_hidden_states)
229
+ return hidden_states
230
+
231
+
232
+ class RBLNQwen2VLForConditionalGeneration(RBLNDecoderOnlyModelForCausalLM):
233
+ """
234
+ RBLNQwen2VLForConditionalGeneration is a multi-modal model that integrates vision and language processing capabilities,
235
+ optimized for RBLN NPUs. It is designed for conditional generation tasks that involve both image and text inputs.
236
+
237
+ This model inherits from [`RBLNDecoderOnlyModelForCausalLM`]. Check the superclass documentation for the generic methods the library implements for all its models.
238
+
239
+ Important Note:
240
+ This model includes a Large Language Model (LLM). For optimal performance, it is highly recommended to use
241
+ tensor parallelism for the language model. This can be achieved by using the `rbln_config` parameter in the
242
+ `from_pretrained` method. Refer to the `from_pretrained` documentation and the RBLNQwen2VLForConditionalGenerationConfig class for details.
243
+
244
+ Examples:
245
+ ```python
246
+ from optimum.rbln import RBLNQwen2VLForConditionalGeneration
247
+
248
+ model = RBLNQwen2VLForConditionalGeneration.from_pretrained(
249
+ "Qwen/Qwen2-VL-7B-Instruct",
250
+ export=True,
251
+ rbln_config={
252
+ "visual": {
253
+ "max_seq_lens": 6400,
254
+ "device": 0,
255
+ },
256
+ "tensor_parallel_size": 8,
257
+ "kvcache_partition_len": 16_384,
258
+ "max_seq_len": 114_688,
259
+ "device": [0, 1, 2, 3, 4, 5, 6, 7],
260
+ },
261
+ )
262
+
263
+ model.save_pretrained("compiled-qwen2-vl-7b-instruct")
264
+ ```
265
+ """
266
+
267
+ auto_model_class = AutoModelForVision2Seq
268
+ _rbln_submodules = [
269
+ {"name": "visual"},
270
+ ]
271
+ _decoder_wrapper_cls = Qwen2VL_LanguageModelWrapper
272
+ _use_rotary_emb = False
273
+
274
+ def __post_init__(self, **kwargs):
275
+ super().__post_init__(**kwargs)
276
+ self.visual = self.rbln_submodules[0]
277
+ self.mrope_section = self.config.rope_scaling["mrope_section"]
278
+ self.rotary_emb = Qwen2VLRotaryEmbedding(self.config)
279
+ self.rope_deltas = torch.zeros(self.rbln_config.batch_size)
280
+
281
+ def can_generate(self):
282
+ return True
283
+
284
+ @classmethod
285
+ def get_input_info(
286
+ cls,
287
+ batch_size: int,
288
+ query_length: int,
289
+ rbln_config: RBLNQwen2VLForConditionalGenerationConfig,
290
+ model_config: PretrainedConfig,
291
+ ):
292
+ input_info = super().get_input_info(batch_size, query_length, rbln_config, model_config)
293
+ pos_idx = 3
294
+ input_info.insert(
295
+ pos_idx,
296
+ (
297
+ "position_emb",
298
+ [2, batch_size, 1, query_length, model_config.hidden_size // model_config.num_attention_heads],
299
+ "float32",
300
+ ),
301
+ )
302
+
303
+ return input_info
304
+
305
+ def prepare_inputs_for_generation(
306
+ self,
307
+ input_ids: torch.LongTensor,
308
+ generate_idx: Optional[torch.Tensor] = None,
309
+ attention_mask: Optional[torch.LongTensor] = None,
310
+ inputs_embeds: Optional[torch.Tensor] = None,
311
+ pixel_values=None,
312
+ pixel_values_videos=None,
313
+ image_grid_thw=None,
314
+ video_grid_thw=None,
315
+ **kwargs,
316
+ ):
317
+ model_inputs = super().prepare_inputs_for_generation(
318
+ input_ids,
319
+ generate_idx,
320
+ attention_mask,
321
+ inputs_embeds,
322
+ **kwargs,
323
+ )
324
+
325
+ is_prefill_phase = generate_idx is None
326
+ if is_prefill_phase:
327
+ model_inputs.update({"input_ids": input_ids})
328
+
329
+ model_inputs.update(
330
+ {
331
+ "pixel_values": pixel_values,
332
+ "pixel_values_videos": pixel_values_videos,
333
+ "image_grid_thw": image_grid_thw,
334
+ "video_grid_thw": video_grid_thw,
335
+ }
336
+ )
337
+
338
+ return model_inputs
339
+
340
+ def _get_position_embeddings(self, hidden_states, position_ids):
341
+ cos, sin = self.rotary_emb(hidden_states, position_ids)
342
+ mrope_section = self.mrope_section * 2
343
+ cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze(1)
344
+ sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze(1)
345
+ return torch.stack([cos, sin])
346
+
347
+ def _preprocess_prefill(
348
+ self,
349
+ input_ids: torch.LongTensor = None,
350
+ attention_mask: torch.Tensor = None,
351
+ pixel_values: torch.Tensor = None,
352
+ pixel_values_videos: torch.FloatTensor = None,
353
+ image_grid_thw: torch.LongTensor = None,
354
+ video_grid_thw: torch.LongTensor = None,
355
+ ):
356
+ batch_size = input_ids.shape[0]
357
+ inputs_embeds = self.embed_tokens(input_ids)
358
+
359
+ if pixel_values is not None:
360
+ image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw)
361
+ n_image_tokens = (input_ids == self.config.image_token_id).sum().item()
362
+ n_image_features = image_embeds.shape[0]
363
+ if n_image_tokens != n_image_features:
364
+ raise ValueError(
365
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
366
+ )
367
+
368
+ mask = input_ids == self.config.image_token_id
369
+ mask_unsqueezed = mask.unsqueeze(-1)
370
+ mask_expanded = mask_unsqueezed.expand_as(inputs_embeds)
371
+
372
+ image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
373
+ inputs_embeds = inputs_embeds.masked_scatter(mask_expanded, image_embeds)
374
+
375
+ if pixel_values_videos is not None:
376
+ video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw)
377
+ n_video_tokens = (input_ids == self.config.video_token_id).sum().item()
378
+ n_video_features = video_embeds.shape[0]
379
+ if n_video_tokens != n_video_features:
380
+ raise ValueError(
381
+ f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}"
382
+ )
383
+
384
+ mask = input_ids == self.config.video_token_id
385
+ mask_unsqueezed = mask.unsqueeze(-1)
386
+ mask_expanded = mask_unsqueezed.expand_as(inputs_embeds)
387
+ inputs_embeds = inputs_embeds.masked_scatter(mask_expanded, video_embeds)
388
+
389
+ max_inputs_len = input_ids.shape[1]
390
+
391
+ head_dim = getattr(self.config, "head_dim", None) or self.config.hidden_size // self.config.num_attention_heads
392
+ all_position_embeds = torch.zeros(2, batch_size, 1, max_inputs_len, head_dim)
393
+ all_rope_deltas = []
394
+
395
+ image_token_id = self.config.image_token_id
396
+ video_token_id = self.config.video_token_id
397
+ vision_start_token_id = self.config.vision_start_token_id
398
+ image_idx, video_idx = 0, 0
399
+
400
+ for b_idx in range(batch_size):
401
+ input_id = input_ids[b_idx : b_idx + 1][:, attention_mask[b_idx].bool()]
402
+ vision_start_indices = torch.argwhere(input_id == vision_start_token_id).squeeze(1)
403
+ vision_tokens = input_id[0][vision_start_indices + 1]
404
+ image_nums = (vision_tokens == image_token_id).sum()
405
+ video_nums = (vision_tokens == video_token_id).sum()
406
+ position_ids, rope_deltas = self.get_rope_index(
407
+ input_id,
408
+ image_grid_thw[image_idx : image_idx + image_nums] if image_grid_thw is not None else None,
409
+ video_grid_thw[video_idx : video_idx + video_nums] if video_grid_thw is not None else None,
410
+ attention_mask=attention_mask[b_idx : b_idx + 1] if attention_mask is not None else None,
411
+ )
412
+ image_idx += image_nums
413
+ video_idx += video_nums
414
+
415
+ position_embed = self._get_position_embeddings(inputs_embeds, position_ids)
416
+ mask_indices = torch.nonzero(attention_mask[b_idx], as_tuple=True)[0]
417
+ all_position_embeds[:, b_idx : b_idx + 1].index_copy_(dim=-2, index=mask_indices, source=position_embed)
418
+ all_rope_deltas.append(rope_deltas)
419
+
420
+ rope_deltas = torch.stack(all_rope_deltas)
421
+
422
+ return inputs_embeds, all_position_embeds, rope_deltas
423
+
424
+ def _preprocess_decoder(
425
+ self,
426
+ input_ids: torch.LongTensor = None,
427
+ cache_position: torch.LongTensor = None,
428
+ ):
429
+ if self.rbln_config.batch_size != cache_position.shape[0]:
430
+ raise RuntimeError(
431
+ f"Cache position size mismatch: got {cache_position.shape[0]}, expected {self.rbln_config.batch_size}."
432
+ )
433
+
434
+ inputs_embeds = self.embed_tokens(input_ids)
435
+ position_embeds = []
436
+ for b_idx in range(self.rbln_config.batch_size):
437
+ delta = cache_position[b_idx] + self.rope_deltas[b_idx]
438
+ position_ids = torch.arange(1).view(1, -1)
439
+ position_ids = position_ids.add(delta)
440
+ position_ids = position_ids.unsqueeze(0).expand(3, -1, -1)
441
+ position_embed = self._get_position_embeddings(torch.zeros(1, dtype=torch.float32), position_ids)
442
+ position_embeds.append(position_embed)
443
+
444
+ position_embeds = torch.cat(position_embeds, dim=1)
445
+
446
+ return inputs_embeds, position_embeds
447
+
448
+ def forward(
449
+ self,
450
+ input_ids: Optional[torch.LongTensor] = None,
451
+ inputs_embeds: Optional[torch.FloatTensor] = None,
452
+ attention_mask: Optional[torch.Tensor] = None,
453
+ pixel_values: Optional[torch.Tensor] = None,
454
+ pixel_values_videos: Optional[torch.FloatTensor] = None,
455
+ image_grid_thw: Optional[torch.LongTensor] = None,
456
+ video_grid_thw: Optional[torch.LongTensor] = None,
457
+ cache_position: Optional[torch.LongTensor] = None,
458
+ generate_idx: Optional[torch.Tensor] = None,
459
+ return_dict: Optional[bool] = None,
460
+ **kwargs,
461
+ ) -> RBLNDecoderOnlyOutput:
462
+ # Prefill
463
+ if cache_position is None:
464
+ inputs_embeds, position_embed, rope_deltas = self._preprocess_prefill(
465
+ input_ids,
466
+ attention_mask,
467
+ pixel_values,
468
+ pixel_values_videos,
469
+ image_grid_thw,
470
+ video_grid_thw,
471
+ )
472
+
473
+ self.rope_deltas = rope_deltas
474
+ batch_size = inputs_embeds.shape[0]
475
+
476
+ logits = []
477
+ for b_idx in range(batch_size):
478
+ cache_position = torch.arange(0, generate_idx[b_idx].item(), dtype=torch.int32).unsqueeze(0)
479
+
480
+ output = self.prefill_decoder(
481
+ inputs_embeds=inputs_embeds[b_idx : b_idx + 1],
482
+ attention_mask=attention_mask[b_idx] if attention_mask is not None else None,
483
+ cache_position=cache_position,
484
+ batch_idx=b_idx,
485
+ position_embed=position_embed[:, b_idx : b_idx + 1],
486
+ )
487
+ logits.append(output.logits)
488
+ logits = torch.cat(logits, dim=0)
489
+
490
+ # Decoder
491
+ else:
492
+ inputs_embeds, position_embed = self._preprocess_decoder(input_ids, cache_position)
493
+ output = self.decoder(
494
+ inputs_embeds=inputs_embeds,
495
+ cache_position=cache_position,
496
+ position_embed=position_embed,
497
+ )
498
+ logits = output.logits
499
+
500
+ if not return_dict:
501
+ return logits, generate_idx
502
+ else:
503
+ return RBLNDecoderOnlyOutput(
504
+ logits=logits,
505
+ generate_idx=generate_idx,
506
+ )