optimum-rbln 0.7.5a1__py3-none-any.whl → 0.7.5rc0__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 (24) hide show
  1. optimum/rbln/__init__.py +10 -0
  2. optimum/rbln/__version__.py +2 -2
  3. optimum/rbln/transformers/__init__.py +10 -0
  4. optimum/rbln/transformers/models/__init__.py +14 -0
  5. optimum/rbln/transformers/models/auto/__init__.py +1 -0
  6. optimum/rbln/transformers/models/auto/modeling_auto.py +7 -0
  7. optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py +114 -19
  8. optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py +29 -10
  9. optimum/rbln/transformers/models/exaone/exaone_architecture.py +5 -1
  10. optimum/rbln/transformers/models/gemma/gemma_architecture.py +5 -1
  11. optimum/rbln/transformers/models/gemma3/__init__.py +16 -0
  12. optimum/rbln/transformers/models/gemma3/configuration_gemma3.py +69 -0
  13. optimum/rbln/transformers/models/gemma3/gemma3_architecture.py +446 -0
  14. optimum/rbln/transformers/models/gemma3/modeling_gemma3.py +1057 -0
  15. optimum/rbln/transformers/models/gpt2/gpt2_architecture.py +4 -1
  16. optimum/rbln/transformers/models/midm/midm_architecture.py +4 -1
  17. optimum/rbln/transformers/models/opt/modeling_opt.py +2 -0
  18. optimum/rbln/transformers/models/opt/opt_architecture.py +4 -1
  19. optimum/rbln/transformers/models/phi/phi_architecture.py +4 -1
  20. optimum/rbln/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py +3 -2
  21. {optimum_rbln-0.7.5a1.dist-info → optimum_rbln-0.7.5rc0.dist-info}/METADATA +1 -1
  22. {optimum_rbln-0.7.5a1.dist-info → optimum_rbln-0.7.5rc0.dist-info}/RECORD +24 -20
  23. {optimum_rbln-0.7.5a1.dist-info → optimum_rbln-0.7.5rc0.dist-info}/WHEEL +0 -0
  24. {optimum_rbln-0.7.5a1.dist-info → optimum_rbln-0.7.5rc0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,1057 @@
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
+ import inspect
15
+ from collections import deque
16
+ from dataclasses import dataclass
17
+ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
18
+
19
+ import rebel
20
+ import torch
21
+ from rebel.compile_context import CompileContext
22
+ from transformers import (
23
+ AutoModelForImageTextToText,
24
+ Gemma3ForConditionalGeneration,
25
+ PretrainedConfig,
26
+ PreTrainedModel,
27
+ )
28
+ from transformers.modeling_outputs import BaseModelOutputWithPooling
29
+ from transformers.modeling_utils import no_init_weights
30
+ from transformers.models.gemma3.modeling_gemma3 import Gemma3TextScaledWordEmbedding
31
+
32
+ from ....configuration_utils import RBLNCompileConfig, RBLNModelConfig
33
+ from ....modeling import RBLNModel
34
+ from ....utils.logging import get_logger
35
+ from ..decoderonly.decoderonly_architecture import (
36
+ set_default_values,
37
+ validate_attention_method,
38
+ )
39
+ from ..decoderonly.modeling_decoderonly import RBLNDecoderOnlyModelForCausalLM, RBLNDecoderOnlyOutput, RBLNRuntimeModel
40
+ from .configuration_gemma3 import RBLNGemma3ForCausalLMConfig
41
+ from .gemma3_architecture import Gemma3ForCausalLMWrapper
42
+
43
+
44
+ logger = get_logger()
45
+
46
+
47
+ if TYPE_CHECKING:
48
+ from transformers import AutoFeatureExtractor, AutoProcessor, AutoTokenizer, Gemma3ForConditionalGeneration
49
+
50
+
51
+ @dataclass
52
+ class RBLNGemma3ForCausalLMOutput(RBLNDecoderOnlyOutput):
53
+ attention_mask: Optional[torch.Tensor] = None
54
+
55
+
56
+ class LoopVisionTower:
57
+ def __init__(self, vision_tower: RBLNModel) -> None:
58
+ self.vision_tower = vision_tower
59
+
60
+ def forward(self, *args, **kwargs):
61
+ # Loop instead of batch
62
+ # shape of pixel_values : [batch, num_channel, height, width]
63
+ pixel_values = args[0]
64
+
65
+ batch_size = pixel_values.shape[0]
66
+ outputs = []
67
+ for i in range(batch_size):
68
+ outputs.append(self.vision_tower(pixel_values=pixel_values[i : i + 1], return_dict=True))
69
+
70
+ last_hidden_states = [output.last_hidden_state 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
+
75
+ return BaseModelOutputWithPooling(
76
+ last_hidden_state=last_hidden_states,
77
+ )
78
+
79
+ def __call__(self, *args: Any, **kwds: Any) -> Any:
80
+ return self.forward(*args, **kwds)
81
+
82
+ def __repr__(self) -> str:
83
+ return repr(self.vision_tower)
84
+
85
+
86
+ class LoopProjector:
87
+ def __init__(self, multi_modal_projector) -> None:
88
+ self.multi_modal_projector = multi_modal_projector
89
+
90
+ def forward(self, *args, **kwargs):
91
+ # Loop instead of batch
92
+ image_feature = args[0]
93
+
94
+ batch_size = image_feature.shape[0]
95
+ outputs = []
96
+ for i in range(batch_size):
97
+ outputs.append(self.multi_modal_projector(image_feature[i : i + 1]))
98
+
99
+ # FIXME:: This can be optimized using out= API of rbln runtime.
100
+ outputs = torch.cat(outputs, dim=0)
101
+ return outputs
102
+
103
+ def __call__(self, *args: Any, **kwds: Any) -> Any:
104
+ return self.forward(*args, **kwds)
105
+
106
+ def __repr__(self) -> str:
107
+ return repr(self.multi_modal_projector)
108
+
109
+
110
+ class RBLNGemma3ForConditionalGeneration(RBLNModel):
111
+ auto_model_class = AutoModelForImageTextToText
112
+ _rbln_submodules = [
113
+ {"name": "vision_tower"},
114
+ {"name": "language_model"},
115
+ ]
116
+
117
+ def __getattr__(self, __name: str) -> Any:
118
+ def redirect(func):
119
+ return lambda *pargs, **kwargs: func(self, *pargs, **kwargs)
120
+
121
+ val = getattr(Gemma3ForConditionalGeneration, __name)
122
+
123
+ if isinstance(val, Callable) and "self" in set(inspect.signature(val).parameters):
124
+ return redirect(val)
125
+ return val
126
+
127
+ def can_generate(self):
128
+ return True
129
+
130
+ def __post_init__(self, **kwargs):
131
+ self.vision_tower = LoopVisionTower(self.rbln_submodules[0])
132
+ self.language_model = self.rbln_submodules[1]
133
+ self.multi_modal_projector = LoopProjector(self.model[0])
134
+ self.vocab_size = self.config.text_config.vocab_size
135
+
136
+ # Copied from the original class
137
+ self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
138
+ return super().__post_init__(**kwargs)
139
+
140
+ def get_attn_impl(self) -> str:
141
+ return self.rbln_config.language_model.attn_impl
142
+
143
+ def get_kvcache_num_blocks(self) -> int:
144
+ return self.rbln_config.language_model.kvcache_num_blocks
145
+
146
+ def get_input_embeddings(self):
147
+ return self.language_model.get_input_embeddings()
148
+
149
+ @classmethod
150
+ def wrap_model_if_needed(cls, model: "PreTrainedModel", rbln_config: RBLNModelConfig):
151
+ return model.multi_modal_projector
152
+
153
+ @classmethod
154
+ def _update_rbln_config(
155
+ cls,
156
+ preprocessors: Optional[Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"]],
157
+ model: Optional["PreTrainedModel"] = None,
158
+ model_config: Optional["PretrainedConfig"] = None,
159
+ rbln_config: Optional[RBLNModelConfig] = None,
160
+ ) -> RBLNModelConfig:
161
+ image_feature_dim = (model_config.vision_config.image_size // model_config.vision_config.patch_size) ** 2
162
+ feature_size = model_config.vision_config.hidden_size
163
+
164
+ input_info = [("image_features", [rbln_config.batch_size, image_feature_dim, feature_size], "float32")]
165
+ rbln_compile_config = RBLNCompileConfig(input_info=input_info)
166
+ rbln_config.set_compile_cfgs([rbln_compile_config])
167
+ return rbln_config
168
+
169
+ def prepare_inputs_for_generation(
170
+ self,
171
+ input_ids,
172
+ inputs_embeds=None,
173
+ pixel_values=None,
174
+ image_sizes=None,
175
+ attention_mask=None,
176
+ generate_idx=None,
177
+ padded_cache_lengths=None,
178
+ token_type_ids=None,
179
+ **kwargs,
180
+ ):
181
+ # Prepare HF generation
182
+ is_prefill_phase = generate_idx is None
183
+
184
+ model_inputs = self.language_model.prepare_inputs_for_generation(
185
+ input_ids=input_ids,
186
+ inputs_embeds=inputs_embeds,
187
+ generate_idx=generate_idx, # Not affect
188
+ attention_mask=attention_mask,
189
+ padded_cache_lengths=padded_cache_lengths,
190
+ **kwargs,
191
+ )
192
+
193
+ if is_prefill_phase:
194
+ model_inputs.update(
195
+ {
196
+ "pixel_values": pixel_values,
197
+ "image_sizes": image_sizes,
198
+ "token_type_ids": token_type_ids,
199
+ }
200
+ )
201
+
202
+ model_inputs["attention_mask"] = attention_mask
203
+
204
+ return model_inputs
205
+
206
+ def _update_model_kwargs_for_generation(
207
+ self,
208
+ outputs: RBLNDecoderOnlyOutput,
209
+ model_kwargs: Dict[str, Any],
210
+ **kwargs,
211
+ ) -> Dict[str, Any]:
212
+ # update generate_idx
213
+ model_kwargs["generate_idx"] = outputs.generate_idx
214
+ model_kwargs["padded_cache_lengths"] = outputs.padded_cache_lengths
215
+
216
+ return model_kwargs
217
+
218
+ def get_image_features(self, pixel_values: torch.Tensor):
219
+ """
220
+ Projects the last hidden state from the vision model into language model space.
221
+
222
+ Args:
223
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
224
+ The tensors corresponding to the input images.
225
+ Returns:
226
+ image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
227
+ """
228
+ vision_outputs = self.vision_tower(pixel_values).last_hidden_state
229
+ image_features = self.multi_modal_projector(vision_outputs)
230
+ return image_features
231
+
232
+ def _preprocess_prefill(
233
+ self,
234
+ input_ids: Optional[torch.LongTensor] = None,
235
+ inputs_embeds: Optional[torch.FloatTensor] = None,
236
+ pixel_values: Optional[torch.FloatTensor] = None,
237
+ **kwargs,
238
+ ):
239
+ if (input_ids is None) ^ (inputs_embeds is not None):
240
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
241
+
242
+ # Replace image id woth PAD if the image token if OOV, to avoid index-errors
243
+ if input_ids is not None and self.config.image_token_index >= self.vocab_size:
244
+ special_image_mask = input_ids == self.config.image_token_index
245
+ llm_input_ids = input_ids.clone()
246
+ llm_input_ids[special_image_mask] = 0
247
+ else:
248
+ llm_input_ids = input_ids
249
+
250
+ if inputs_embeds is None:
251
+ inputs_embeds = self.get_input_embeddings()(llm_input_ids)
252
+
253
+ # Merge text and images
254
+ if pixel_values is not None:
255
+ image_features = self.get_image_features(pixel_values)
256
+ special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
257
+ special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
258
+
259
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
260
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
261
+
262
+ return inputs_embeds
263
+
264
+ def forward(
265
+ self,
266
+ input_ids: torch.LongTensor = None,
267
+ pixel_values: torch.FloatTensor = None,
268
+ attention_mask: Optional[torch.Tensor] = None,
269
+ cache_position: Optional[torch.LongTensor] = None,
270
+ inputs_embeds: Optional[torch.FloatTensor] = None,
271
+ generate_idx: Optional[torch.Tensor] = None,
272
+ padded_cache_lengths: Optional[torch.Tensor] = None,
273
+ position_ids: Optional[torch.Tensor] = None,
274
+ token_type_ids: Optional[torch.Tensor] = None,
275
+ **lm_kwargs,
276
+ ) -> Union[Tuple, RBLNDecoderOnlyOutput]:
277
+ # prefill
278
+ if cache_position is None:
279
+ logits = []
280
+ inputs_embeds = self._preprocess_prefill(input_ids, inputs_embeds, pixel_values)
281
+ batch_size = inputs_embeds.shape[0]
282
+
283
+ for b_idx in range(batch_size):
284
+ cache_position = torch.arange(0, generate_idx[b_idx].item(), dtype=torch.int32).unsqueeze(0)
285
+ output = self.language_model.prefill_decoder(
286
+ inputs_embeds=inputs_embeds[b_idx : b_idx + 1],
287
+ attention_mask=attention_mask[b_idx],
288
+ cache_position=cache_position,
289
+ batch_idx=b_idx,
290
+ token_type_ids=token_type_ids[b_idx : b_idx + 1] if token_type_ids is not None else None,
291
+ )
292
+ padded_cache_lengths[b_idx] += output.padded_cache_lengths
293
+ logits.append(output.logits)
294
+
295
+ logits = torch.cat(logits, dim=0)
296
+ # decoder
297
+ else:
298
+ inputs = inputs_embeds if inputs_embeds is not None else input_ids
299
+ batch_size = inputs.shape[0]
300
+ if batch_size not in self.language_model.decoders:
301
+ raise ValueError(
302
+ f"No decoder runtime available for batch size {batch_size}. "
303
+ f"Available batch sizes are: {list(self.decoders.keys())}. "
304
+ f"Please run your model with one of these batch sizes or add support for batch size {batch_size}."
305
+ )
306
+
307
+ logits = self.language_model.decoders[batch_size](
308
+ input_ids=input_ids,
309
+ inputs_embeds=inputs_embeds,
310
+ cache_position=cache_position,
311
+ position_ids=position_ids if self.rbln_config.language_model.use_position_ids else None,
312
+ ).logits
313
+
314
+ return RBLNDecoderOnlyOutput(
315
+ logits=logits, generate_idx=generate_idx, padded_cache_lengths=padded_cache_lengths
316
+ )
317
+
318
+
319
+ class RBLNGemma3RuntimeModel(RBLNRuntimeModel):
320
+ def __init__(self, *args, image_prefill: Optional[rebel.Runtime] = None, **kwargs):
321
+ super().__init__(*args, **kwargs)
322
+ self.image_prefill = image_prefill # FIXME(taehoon)
323
+ self.prefill = self.runtime if self.phase == "prefill" else None # FIXME
324
+ self.decode = self.runtime if self.phase == "decode" else None
325
+
326
+ def pad_for_chunked_images(
327
+ self,
328
+ inputs: torch.Tensor,
329
+ attention_mask: torch.Tensor,
330
+ position_ids: torch.Tensor,
331
+ token_type_ids: Optional[torch.Tensor] = None,
332
+ ):
333
+ """
334
+ Pads inputs, attention_mask, and position_ids so image token groups (256 tokens with token_type_ids == 1)
335
+ start at multiples of prefill_chunk_size (256). Returns padded tensors and total padded length.
336
+
337
+ Args:
338
+ inputs: (1, seq_len, hidden_size) tensor.
339
+ attention_mask: (1, seq_len) tensor, 1 for valid, 0 for masked.
340
+ position_ids: (1, seq_len) tensor for RoPE.
341
+ token_type_ids: (1, seq_len) tensor, 0 for text, 1 for image.
342
+
343
+ Returns:
344
+ Tuple: (inputs_padded, attention_mask_padded, position_ids_padded, padded_len, token_type_ids_padded).
345
+ """
346
+
347
+ if token_type_ids is None:
348
+ return inputs, attention_mask, position_ids, 0, torch.zeros(inputs.shape[:2], dtype=torch.long)
349
+
350
+ seq_len = inputs.shape[1]
351
+
352
+ # Find image start positions
353
+ image_starts = [
354
+ s
355
+ for s in range(seq_len - self.prefill_chunk_size + 1)
356
+ if torch.all(token_type_ids[:, s : s + self.prefill_chunk_size] == 1)
357
+ ]
358
+
359
+ # Initialize padded tensors
360
+ padded_input_len = seq_len
361
+ for image_start in image_starts:
362
+ pad_needed = (
363
+ self.prefill_chunk_size - (image_start + padded_input_len - seq_len) % self.prefill_chunk_size
364
+ ) % self.prefill_chunk_size
365
+ padded_input_len += pad_needed
366
+ total_padding = padded_input_len - seq_len
367
+
368
+ if inputs.dim() == 3:
369
+ inputs_padded = torch.zeros(1, padded_input_len, inputs.shape[2], dtype=inputs.dtype)
370
+ else:
371
+ inputs_padded = torch.zeros(1, padded_input_len, dtype=inputs.dtype)
372
+ attention_mask_padded = torch.zeros(1, padded_input_len, dtype=attention_mask.dtype)
373
+ position_ids_padded = torch.zeros(1, padded_input_len, dtype=position_ids.dtype)
374
+ token_type_ids_padded = torch.zeros(1, padded_input_len, dtype=token_type_ids.dtype)
375
+
376
+ # Fill padded tensors
377
+ dest_pos = 0
378
+ src_pos = 0
379
+ last_pos_id = -1
380
+ for image_start in image_starts + [seq_len]:
381
+ # Text segment
382
+ if src_pos < image_start:
383
+ length = image_start - src_pos
384
+ inputs_padded[:, dest_pos : dest_pos + length] = inputs[:, src_pos:image_start]
385
+ attention_mask_padded[:, dest_pos : dest_pos + length] = attention_mask[:, src_pos:image_start]
386
+ position_ids_padded[:, dest_pos : dest_pos + length] = position_ids[:, src_pos:image_start]
387
+ token_type_ids_padded[:, dest_pos : dest_pos + length] = token_type_ids[:, src_pos:image_start]
388
+ dest_pos += length
389
+ last_pos_id = position_ids[0, image_start - 1].item()
390
+ src_pos = image_start
391
+
392
+ # Padding
393
+ pad_needed = (self.prefill_chunk_size - dest_pos % self.prefill_chunk_size) % self.prefill_chunk_size
394
+ if pad_needed and dest_pos < padded_input_len:
395
+ position_ids_padded[:, dest_pos : dest_pos + pad_needed] = torch.arange(
396
+ last_pos_id + 1, last_pos_id + pad_needed + 1, dtype=position_ids.dtype
397
+ ).unsqueeze(0)
398
+ dest_pos += pad_needed
399
+
400
+ # Image segment
401
+ if src_pos < seq_len and src_pos == image_start:
402
+ inputs_padded[:, dest_pos : dest_pos + self.prefill_chunk_size] = inputs[
403
+ :, src_pos : src_pos + self.prefill_chunk_size
404
+ ]
405
+ attention_mask_padded[:, dest_pos : dest_pos + self.prefill_chunk_size] = attention_mask[
406
+ :, src_pos : src_pos + self.prefill_chunk_size
407
+ ]
408
+ position_ids_padded[:, dest_pos : dest_pos + self.prefill_chunk_size] = position_ids[
409
+ :, src_pos : src_pos + self.prefill_chunk_size
410
+ ]
411
+ token_type_ids_padded[:, dest_pos : dest_pos + self.prefill_chunk_size] = token_type_ids[
412
+ :, src_pos : src_pos + self.prefill_chunk_size
413
+ ]
414
+ dest_pos += self.prefill_chunk_size
415
+ src_pos += self.prefill_chunk_size
416
+ last_pos_id = position_ids[0, image_start + self.prefill_chunk_size - 1].item()
417
+
418
+ return inputs_padded, attention_mask_padded, position_ids_padded, total_padding, token_type_ids_padded
419
+
420
+ def _prepare_prefill_inputs(
421
+ self,
422
+ inputs: torch.Tensor,
423
+ cache_position: torch.Tensor,
424
+ attention_mask: Optional[torch.Tensor] = None,
425
+ position_embed: Optional[torch.Tensor] = None,
426
+ token_type_ids: Optional[torch.Tensor] = None,
427
+ ):
428
+ """
429
+ Prepare inputs for prefill phase.
430
+ """
431
+ # Handle continuous batching in a compiled graph by extracting valid inputs
432
+ # If an attention mask is provided, select only the valid (non-masked) inputs
433
+ inputs = inputs[:, attention_mask.bool()] if attention_mask is not None else inputs
434
+ token_type_ids = (
435
+ token_type_ids[:, attention_mask.bool()]
436
+ if attention_mask is not None and token_type_ids is not None
437
+ else token_type_ids
438
+ )
439
+
440
+ if position_embed is not None:
441
+ position_embed = (
442
+ position_embed[:, :, :, attention_mask.bool(), :] if attention_mask is not None else position_embed
443
+ )
444
+
445
+ seq_len = inputs.shape[1]
446
+ # Initialize attention mask for chunked processing
447
+ if self.use_attention_mask:
448
+ chunked_attention_mask = (
449
+ torch.ones(1, seq_len, dtype=torch.float32)
450
+ if self.use_position_ids
451
+ else torch.zeros(1, 1, self.prefill_chunk_size, self.max_seq_len, dtype=torch.float32)
452
+ )
453
+ else:
454
+ chunked_attention_mask = None
455
+
456
+ # Buffer for storing output logits
457
+ out_buffers = [
458
+ torch.empty(
459
+ size=self.output_size,
460
+ dtype=torch.float32,
461
+ device="cpu",
462
+ )
463
+ ]
464
+
465
+ inputs, chunked_attention_mask, position_ids, padded_cache_lengths, token_type_ids_padded = (
466
+ self.pad_for_chunked_images(inputs, chunked_attention_mask, cache_position, token_type_ids)
467
+ )
468
+
469
+ query_length = inputs.shape[1]
470
+ if query_length > self.max_seq_len:
471
+ raise ValueError(
472
+ f"Input length ({query_length}) exceeds the maximum allowed sequence length ({self.max_seq_len})."
473
+ )
474
+
475
+ # Align attention_mask to compiled shape
476
+ if self.use_position_ids:
477
+ chunked_attention_mask = torch.nn.functional.pad(
478
+ chunked_attention_mask, (0, self.max_seq_len - query_length)
479
+ )
480
+
481
+ # Pad input and cache_position if the last chunk is smaller than `prefill_chunk_size`
482
+ if query_length % self.prefill_chunk_size != 0:
483
+ padding_size = self.prefill_chunk_size - query_length % self.prefill_chunk_size
484
+ # inputs_embeds
485
+ if inputs.dim() == 3:
486
+ inputs = torch.nn.functional.pad(inputs, (0, 0, 0, padding_size))
487
+ # inputs_ids
488
+ else:
489
+ inputs = torch.nn.functional.pad(inputs, (0, padding_size))
490
+
491
+ position_ids = torch.cat(
492
+ [
493
+ position_ids,
494
+ torch.arange(
495
+ query_length,
496
+ query_length + padding_size,
497
+ dtype=torch.int32,
498
+ ).unsqueeze(0),
499
+ ],
500
+ dim=-1,
501
+ )
502
+ token_type_ids_padded = torch.nn.functional.pad(token_type_ids_padded, (0, padding_size))
503
+
504
+ if position_embed is not None:
505
+ position_embed = torch.nn.functional.pad(position_embed, (0, 0, 0, padding_size))
506
+
507
+ cache_position = torch.arange(0, query_length + padding_size, dtype=torch.int32).unsqueeze(0)
508
+
509
+ return (
510
+ inputs,
511
+ cache_position,
512
+ chunked_attention_mask,
513
+ out_buffers,
514
+ position_ids,
515
+ position_embed,
516
+ padded_cache_lengths,
517
+ query_length,
518
+ token_type_ids_padded,
519
+ )
520
+
521
+ def prefill_forward(
522
+ self,
523
+ inputs: torch.Tensor,
524
+ cache_position: torch.Tensor = None,
525
+ attention_mask: Optional[torch.Tensor] = None,
526
+ batch_idx: int = None,
527
+ block_tables: torch.Tensor = None,
528
+ is_external_block_tables: bool = None,
529
+ position_embed: Optional[torch.Tensor] = None,
530
+ token_type_ids: Optional[torch.Tensor] = None,
531
+ local_block_tables: Optional[torch.Tensor] = None,
532
+ ) -> torch.FloatTensor:
533
+ """
534
+ Performs chunked prefill for efficient KV-cache updates and memory optimization.
535
+ Instead of processing the entire sequence at once, the input is divided into chunks of size `prefill_chunk_size`,
536
+ and each chunk is processed sequentially. This allows for better memory utilization and compatibility with continuous batching.
537
+ """
538
+ (
539
+ inputs,
540
+ cache_position,
541
+ chunked_attention_mask,
542
+ out_buffers,
543
+ position_ids,
544
+ position_embed,
545
+ padded_cache_lengths,
546
+ query_length,
547
+ token_type_ids_padded,
548
+ ) = self._prepare_prefill_inputs(
549
+ inputs, cache_position, attention_mask, position_embed, token_type_ids=token_type_ids
550
+ )
551
+ self.dec_attn_mask[batch_idx : batch_idx + 1] = chunked_attention_mask[:1]
552
+ if not is_external_block_tables:
553
+ local_block_tables = torch.tensor([batch_idx], dtype=torch.int16)
554
+
555
+ if self.use_attention_mask and self.use_position_ids:
556
+ chunked_attention_mask = torch.zeros(1, self.max_seq_len, dtype=torch.float32)
557
+
558
+ # Process input in chunks of size `prefill_chunk_size`
559
+ for step in range(0, query_length, self.prefill_chunk_size):
560
+ # Extract the current chunk of inputs and cache positions
561
+ input_chunk = inputs[:, step : step + self.prefill_chunk_size]
562
+ cache_pos_chunk = cache_position[:, step : step + self.prefill_chunk_size]
563
+ position_ids_chunk = (
564
+ position_ids[:, step : step + self.prefill_chunk_size] if position_ids is not None else None
565
+ )
566
+
567
+ # Not used in Gemma3 yet.
568
+ if self.use_attention_mask:
569
+ if self.use_position_ids:
570
+ chunked_attention_mask[0, step : step + self.prefill_chunk_size] = self.dec_attn_mask[
571
+ batch_idx, step : step + self.prefill_chunk_size
572
+ ]
573
+ else:
574
+ # Update attention mask to ensure proper causal behavior
575
+ if step >= self.prefill_chunk_size:
576
+ chunked_attention_mask[:, :, :, step - self.prefill_chunk_size : step] = 1
577
+ chunked_attention_mask[:, :, :, step : step + self.prefill_chunk_size] = self.causal_mask
578
+
579
+ # Define query position
580
+ query_position = (
581
+ torch.sum(
582
+ chunked_attention_mask[0][step : step + self.prefill_chunk_size], dim=-1, dtype=torch.int16
583
+ ).squeeze(0)
584
+ - 1
585
+ )
586
+ if token_type_ids_padded[:, step] == 1:
587
+ if torch.any(token_type_ids_padded[:, step : step + self.prefill_chunk_size] == 0):
588
+ raise ValueError("All tokens of image_prefill should be the same image.")
589
+ else:
590
+ logits = self.image_prefill(
591
+ input_chunk,
592
+ chunked_attention_mask,
593
+ cache_pos_chunk,
594
+ position_ids_chunk,
595
+ query_position,
596
+ block_tables,
597
+ local_block_tables,
598
+ out=out_buffers,
599
+ )
600
+ else:
601
+ # Forward pass for the current chunk
602
+ logits = self.prefill(
603
+ input_chunk,
604
+ chunked_attention_mask,
605
+ cache_pos_chunk,
606
+ position_ids_chunk,
607
+ query_position,
608
+ block_tables,
609
+ local_block_tables,
610
+ out=out_buffers,
611
+ )
612
+
613
+ return RBLNGemma3ForCausalLMOutput(
614
+ logits=logits, padded_cache_lengths=padded_cache_lengths, attention_mask=chunked_attention_mask
615
+ )
616
+
617
+ def decode_forward(
618
+ self,
619
+ inputs: torch.Tensor,
620
+ cache_position: torch.Tensor = None,
621
+ block_tables: torch.Tensor = None,
622
+ is_external_block_tables: bool = None,
623
+ attention_mask: Optional[torch.Tensor] = None,
624
+ position_embed: Optional[torch.Tensor] = None,
625
+ position_ids: Optional[torch.Tensor] = None,
626
+ local_block_tables: Optional[torch.Tensor] = None,
627
+ ) -> torch.FloatTensor:
628
+ batch_size = inputs.shape[0]
629
+ if batch_size != self.batch_size:
630
+ raise RuntimeError(
631
+ f"Batch size mismatch: got {batch_size}, expected {self.batch_size} (compiled batch size)."
632
+ )
633
+
634
+ if batch_size != cache_position.shape[0]:
635
+ raise RuntimeError(f"Cache position size mismatch: got {cache_position.shape[0]}, expected {batch_size}.")
636
+
637
+ # FIXME(taehoon): how to handle pos_attn_mask with external block tables
638
+ if is_external_block_tables:
639
+ if attention_mask is None:
640
+ raise ValueError("attention_mask should be provided with external block tables.")
641
+ if local_block_tables is None:
642
+ raise ValueError("local_block_tables should be provided with external block tables.")
643
+ else:
644
+ local_block_tables = (
645
+ local_block_tables
646
+ if local_block_tables is not None
647
+ else torch.arange(0, self.batch_size, dtype=torch.int16).view(self.batch_size, -1)
648
+ )
649
+ if self.use_attention_mask and attention_mask is None:
650
+ for b_idx in range(batch_size):
651
+ decoding_step = cache_position[b_idx].item()
652
+ if not (0 <= decoding_step < self.dec_attn_mask.shape[-1]):
653
+ raise ValueError(
654
+ f"Decoding step {decoding_step} out of bounds for attention mask with shape {self.dec_attn_mask.shape}."
655
+ )
656
+ self.dec_attn_mask[b_idx, decoding_step] = 1
657
+
658
+ attention_mask = self.dec_attn_mask
659
+
660
+ if self.batch_size < block_tables.shape[0]:
661
+ block_tables = block_tables[: self.batch_size]
662
+
663
+ if attention_mask is not None and self.batch_size < attention_mask.shape[0]:
664
+ attention_mask = attention_mask[: self.batch_size]
665
+
666
+ logits = self.decode(inputs, attention_mask, cache_position, position_ids, block_tables, local_block_tables)
667
+
668
+ return RBLNDecoderOnlyOutput(logits=logits)
669
+
670
+
671
+ class RBLNGemma3ForCausalLM(RBLNDecoderOnlyModelForCausalLM):
672
+ """
673
+ The Gemma3 Model transformer with a language modeling head (linear layer) on top.
674
+ This model inherits from [`RBLNDecoderOnlyModelForCausalLM`]. Check the superclass documentation for the generic methods the library implements for all its models.
675
+
676
+ A class to convert and run pre-trained transformers based Gemma3ForCausalLM model on RBLN devices.
677
+ It implements the methods to convert a pre-trained transformers Gemma3ForCausalLM model into a RBLN transformer model by:
678
+ - transferring the checkpoint weights of the original into an optimized RBLN graph,
679
+ - compiling the resulting graph using the RBLN compiler.
680
+ """
681
+
682
+ _decoder_wrapper_cls = Gemma3ForCausalLMWrapper
683
+
684
+ def __post_init__(self, **kwargs):
685
+ main_input_name = self.main_input_name
686
+
687
+ if self.rbln_config.use_inputs_embeds:
688
+ main_input_name = "inputs_embeds"
689
+ artifacts = torch.load(self.model_save_dir / self.subfolder / "torch_artifacts.pth", weights_only=False)
690
+ self.embed_tokens = self._create_embedding_layer()
691
+ self.embed_tokens.load_state_dict(artifacts["embed_tokens"])
692
+ else:
693
+ self.embed_tokens = None
694
+
695
+ # Initialize shared resources to be used across Runtime instances (prefill and decode phases)
696
+ dec_attn_mask = torch.zeros(self.rbln_config.batch_size, self.rbln_config.max_seq_len, dtype=torch.float32)
697
+ block_tables = torch.zeros(
698
+ self.rbln_config.batch_size,
699
+ self.rbln_config.max_seq_len // self.rbln_config.kvcache_block_size,
700
+ dtype=torch.int16,
701
+ ).fill_(-1)
702
+ free_block_pool = deque(x for x in range(self.rbln_config.kvcache_num_blocks))
703
+
704
+ self.prefill_decoder = RBLNGemma3RuntimeModel(
705
+ runtime=self.model[0],
706
+ image_prefill=self.model[1],
707
+ main_input_name=main_input_name,
708
+ embed_tokens=self.embed_tokens,
709
+ phase="prefill",
710
+ batch_size=self.rbln_config.batch_size,
711
+ dec_attn_mask=dec_attn_mask,
712
+ block_tables=block_tables,
713
+ free_block_pool=free_block_pool,
714
+ kvcache_block_size=self.rbln_config.kvcache_block_size,
715
+ vocab_size=self.config.vocab_size,
716
+ prefill_chunk_size=self.rbln_config.prefill_chunk_size,
717
+ max_seq_len=self.rbln_config.max_seq_len,
718
+ use_attention_mask=self.rbln_config.use_attention_mask,
719
+ attn_impl=self.rbln_config.attn_impl,
720
+ use_position_ids=self.rbln_config.use_position_ids,
721
+ )
722
+
723
+ self.decoders = {}
724
+ for i, batch_size in enumerate(self.rbln_config.decoder_batch_sizes):
725
+ self.decoders[batch_size] = RBLNGemma3RuntimeModel(
726
+ runtime=self.model[i + 2],
727
+ main_input_name=main_input_name,
728
+ embed_tokens=self.embed_tokens,
729
+ phase="decode",
730
+ batch_size=batch_size,
731
+ dec_attn_mask=dec_attn_mask,
732
+ block_tables=block_tables,
733
+ free_block_pool=free_block_pool,
734
+ kvcache_block_size=self.rbln_config.kvcache_block_size,
735
+ use_attention_mask=self.rbln_config.use_attention_mask,
736
+ attn_impl=self.rbln_config.attn_impl,
737
+ use_position_ids=self.rbln_config.use_position_ids,
738
+ )
739
+
740
+ # NOTE(eunji): Use a decoder whose batch size matches the model's main batch size for compatibility.
741
+ self.decoder = self.decoders[self.rbln_config.batch_size]
742
+
743
+ def _create_embedding_layer(self):
744
+ with no_init_weights():
745
+ embed_tokens = Gemma3TextScaledWordEmbedding(
746
+ self.config.vocab_size,
747
+ self.config.hidden_size,
748
+ self.config.pad_token_id,
749
+ embed_scale=self.config.hidden_size**0.5,
750
+ )
751
+ return embed_tokens
752
+
753
+ @classmethod
754
+ def get_input_info(
755
+ cls,
756
+ batch_size: int,
757
+ query_length: int,
758
+ use_inputs_embeds: bool,
759
+ use_attention_mask: bool,
760
+ use_position_ids: bool,
761
+ max_seq_len: int,
762
+ kvcache_block_size: int,
763
+ kvcache_num_blocks: int,
764
+ num_key_value_heads: int,
765
+ num_hidden_layers: int,
766
+ hidden_size: int,
767
+ head_dim: int,
768
+ sliding_window: int,
769
+ sliding_window_pattern: int,
770
+ dec_batch_size: int,
771
+ ):
772
+ if use_inputs_embeds:
773
+ main_input = ("inputs_embeds", [batch_size, query_length, hidden_size], "float32")
774
+ else:
775
+ main_input = ("input_ids", [batch_size, query_length], "int64")
776
+
777
+ input_info = [
778
+ main_input,
779
+ (
780
+ "attention_mask",
781
+ [batch_size, 1, query_length, max_seq_len] if not use_position_ids else [batch_size, max_seq_len],
782
+ "float32",
783
+ ),
784
+ (
785
+ "cache_position",
786
+ [batch_size, query_length],
787
+ "int32",
788
+ ),
789
+ (
790
+ "position_ids",
791
+ [batch_size, query_length],
792
+ "int32",
793
+ ),
794
+ ]
795
+
796
+ if query_length > 1:
797
+ input_info.extend(
798
+ [
799
+ ("query_position", [], "int16"),
800
+ ]
801
+ )
802
+
803
+ max_block_cnt = max_seq_len // kvcache_block_size
804
+
805
+ if query_length > 1:
806
+ input_info.extend([("global_block_tables", [max_block_cnt], "int16")])
807
+ input_info.extend([("local_block_tables", [1], "int16")])
808
+ else:
809
+ input_info.extend([("global_block_tables", [batch_size, max_block_cnt], "int16")])
810
+ input_info.extend([("local_block_tables", [batch_size, 1], "int16")])
811
+
812
+ def is_sliding(layer_idx: int) -> bool:
813
+ return bool((layer_idx + 1) % sliding_window_pattern)
814
+
815
+ local_kvcache_shape = [dec_batch_size, num_key_value_heads, sliding_window, head_dim]
816
+ global_kvcache_shape = [kvcache_num_blocks, num_key_value_heads, kvcache_block_size, head_dim]
817
+ input_info.extend(
818
+ [
819
+ (
820
+ f"past_key_values_{i}",
821
+ local_kvcache_shape if is_sliding(i // 2) else global_kvcache_shape,
822
+ "float32",
823
+ )
824
+ for i in range(num_hidden_layers * 2)
825
+ ]
826
+ )
827
+
828
+ return input_info
829
+
830
+ @classmethod
831
+ def _update_submodule_config(cls, model: "PreTrainedModel", rbln_config: RBLNModelConfig):
832
+ if rbln_config.prefill_chunk_size is None:
833
+ rbln_config.prefill_chunk_size = model.config.mm_tokens_per_image
834
+
835
+ if rbln_config.prefill_chunk_size != model.config.mm_tokens_per_image:
836
+ logger.warning(
837
+ f"Prefill chunk size is different from mm_tokens_per_image: {rbln_config.prefill_chunk_size} != {model.config.mm_tokens_per_image}"
838
+ )
839
+ return rbln_config
840
+
841
+ @classmethod
842
+ def _update_rbln_config(
843
+ cls,
844
+ preprocessors: Optional[Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"]] = None,
845
+ model: Optional["PreTrainedModel"] = None,
846
+ model_config: Optional["PretrainedConfig"] = None,
847
+ rbln_config: Optional[RBLNGemma3ForCausalLMConfig] = None,
848
+ ) -> RBLNGemma3ForCausalLMConfig:
849
+ if rbln_config.max_seq_len is None:
850
+ rbln_config.max_seq_len = getattr(model_config, "max_position_embeddings", None)
851
+ if rbln_config.max_seq_len is None:
852
+ raise ValueError("`max_seq_len` should be specified.")
853
+
854
+ rbln_config.attn_impl, rbln_config.kvcache_partition_len, rbln_config.kvcache_block_size = set_default_values(
855
+ attn_impl=rbln_config.attn_impl,
856
+ kvcache_partition_len=rbln_config.kvcache_partition_len,
857
+ kvcache_block_size=rbln_config.kvcache_block_size,
858
+ max_seq_len=rbln_config.max_seq_len,
859
+ )
860
+
861
+ validate_attention_method(
862
+ attn_impl=rbln_config.attn_impl,
863
+ kvcache_partition_len=rbln_config.kvcache_partition_len,
864
+ kvcache_block_size=rbln_config.kvcache_block_size,
865
+ max_seq_len=rbln_config.max_seq_len,
866
+ )
867
+
868
+ required_num_blocks = (rbln_config.max_seq_len // rbln_config.kvcache_block_size) * rbln_config.batch_size
869
+ max_num_blocks = required_num_blocks
870
+
871
+ if rbln_config.attn_impl == "flash_attn":
872
+ flash_min_blocks = rbln_config.max_seq_len // rbln_config.kvcache_block_size + 1
873
+ if max_num_blocks < flash_min_blocks:
874
+ max_num_blocks = flash_min_blocks
875
+
876
+ if max_num_blocks < rbln_config.batch_size:
877
+ raise RuntimeError(
878
+ f"Batch size ({rbln_config.batch_size}) exceeds available KV cache blocks ({max_num_blocks}). "
879
+ "Ensure the number of blocks is at least equal to the batch size."
880
+ )
881
+
882
+ if rbln_config.kvcache_num_blocks is None:
883
+ rbln_config.kvcache_num_blocks = max_num_blocks
884
+ elif rbln_config.kvcache_num_blocks > max_num_blocks:
885
+ logger.warning(
886
+ f"The set `kvcache_num_blocks` ({rbln_config.kvcache_num_blocks}) is greater"
887
+ f" than the estimated maximum number of blocks ({max_num_blocks})."
888
+ "This can cause a failure during model compilation."
889
+ )
890
+ logger.info(f"[KVCache] Compiling with num_blocks: {rbln_config.kvcache_num_blocks}")
891
+
892
+ num_attention_heads = getattr(model_config, "n_head", None) or getattr(model_config, "num_attention_heads")
893
+ num_key_value_heads = getattr(model_config, "num_key_value_heads", None) or num_attention_heads
894
+ num_hidden_layers = getattr(model_config, "n_layer", None) or getattr(model_config, "num_hidden_layers")
895
+ hidden_size = getattr(model_config, "n_embd", None) or getattr(model_config, "hidden_size")
896
+ head_dim = getattr(model_config, "head_dim", None) or hidden_size // num_attention_heads
897
+ sliding_window = getattr(model_config, "sliding_window", None)
898
+ sliding_window_pattern = getattr(model_config, "sliding_window_pattern", None)
899
+
900
+ prefill_input_info = cls.get_input_info(
901
+ batch_size=1,
902
+ query_length=rbln_config.prefill_chunk_size,
903
+ use_inputs_embeds=rbln_config.use_inputs_embeds,
904
+ use_attention_mask=rbln_config.use_attention_mask,
905
+ use_position_ids=rbln_config.use_position_ids,
906
+ max_seq_len=rbln_config.max_seq_len,
907
+ kvcache_block_size=rbln_config.kvcache_block_size,
908
+ kvcache_num_blocks=rbln_config.kvcache_num_blocks,
909
+ num_key_value_heads=num_key_value_heads,
910
+ num_hidden_layers=num_hidden_layers,
911
+ hidden_size=hidden_size,
912
+ head_dim=head_dim,
913
+ sliding_window=sliding_window,
914
+ sliding_window_pattern=sliding_window_pattern,
915
+ dec_batch_size=max(rbln_config.decoder_batch_sizes),
916
+ )
917
+ prefill_compile_config = RBLNCompileConfig(compiled_model_name="prefill", input_info=prefill_input_info)
918
+ image_prefill_compile_config = RBLNCompileConfig(
919
+ compiled_model_name="image_prefill", input_info=prefill_input_info
920
+ )
921
+
922
+ dec_compile_configs = []
923
+ for batch_size in rbln_config.decoder_batch_sizes:
924
+ dec_input_info = cls.get_input_info(
925
+ batch_size=batch_size,
926
+ query_length=1,
927
+ use_inputs_embeds=rbln_config.use_inputs_embeds,
928
+ use_attention_mask=rbln_config.use_attention_mask,
929
+ use_position_ids=rbln_config.use_position_ids,
930
+ max_seq_len=rbln_config.max_seq_len,
931
+ kvcache_block_size=rbln_config.kvcache_block_size,
932
+ kvcache_num_blocks=rbln_config.kvcache_num_blocks,
933
+ num_key_value_heads=num_key_value_heads,
934
+ num_hidden_layers=num_hidden_layers,
935
+ hidden_size=hidden_size,
936
+ head_dim=head_dim,
937
+ sliding_window=sliding_window,
938
+ sliding_window_pattern=sliding_window_pattern,
939
+ dec_batch_size=batch_size,
940
+ )
941
+ dec_compile_configs.append(
942
+ RBLNCompileConfig(compiled_model_name=f"decoder_batch_{batch_size}", input_info=dec_input_info)
943
+ )
944
+ rbln_config.set_compile_cfgs([prefill_compile_config, image_prefill_compile_config, *dec_compile_configs])
945
+
946
+ return rbln_config
947
+
948
+ @classmethod
949
+ @torch.inference_mode()
950
+ def get_compiled_model(cls, model: "PreTrainedModel", rbln_config: RBLNGemma3ForCausalLMConfig):
951
+ wrapped_model = cls.wrap_model_if_needed(model, rbln_config)
952
+
953
+ rbln_compile_configs = rbln_config.compile_cfgs
954
+ prefill_compile_config = rbln_compile_configs[0]
955
+
956
+ context = CompileContext(use_weight_sharing=True)
957
+
958
+ # Here we use meta tensor, for the memory efficiency.
959
+ meta_tensor_names = [name for name, _, _ in prefill_compile_config.input_info if "past_key_values" in name]
960
+ prefill_example_inputs = prefill_compile_config.get_dummy_inputs(fill=0, meta_tensor_names=meta_tensor_names)
961
+
962
+ # Mark static tensors (self kv states)
963
+ static_tensors = {}
964
+ for (name, _, _), tensor in zip(prefill_compile_config.input_info, prefill_example_inputs):
965
+ if "past_key_values" in name:
966
+ static_tensors[name] = tensor
967
+ context.mark_static_address(tensor)
968
+
969
+ def compile_model(wrapped_model, compile_config, example_inputs, compile_context, quantization):
970
+ try:
971
+ if quantization:
972
+ quantization.maybe_set_quantization_env()
973
+ original_linear = torch.nn.functional.linear
974
+ torch.nn.functional.linear = torch.ops.rbln_custom_ops.linear
975
+ compiled_model = RBLNModel.compile(
976
+ wrapped_model,
977
+ compile_config,
978
+ example_inputs=example_inputs,
979
+ compile_context=compile_context,
980
+ )
981
+ return compiled_model
982
+ finally:
983
+ torch.nn.functional.linear = original_linear
984
+ if quantization:
985
+ quantization.maybe_reset_quantization_env()
986
+
987
+ wrapped_model.phase = "prefill"
988
+ compiled_prefill = compile_model(
989
+ wrapped_model,
990
+ prefill_compile_config,
991
+ prefill_example_inputs,
992
+ context,
993
+ rbln_config.quantization,
994
+ )
995
+
996
+ image_prefill_compile_config = rbln_compile_configs[1]
997
+ wrapped_model.phase = "image_prefill"
998
+ compiled_image_prefill = compile_model(
999
+ wrapped_model,
1000
+ image_prefill_compile_config,
1001
+ prefill_example_inputs,
1002
+ context,
1003
+ rbln_config.quantization,
1004
+ )
1005
+
1006
+ compiled_models = {"prefill": compiled_prefill, "image_prefill": compiled_image_prefill}
1007
+ wrapped_model.phase = "decode"
1008
+ for batch_size, dec_compile_config in zip(rbln_config.decoder_batch_sizes, rbln_compile_configs[2:]):
1009
+ dec_example_inputs = dec_compile_config.get_dummy_inputs(fill=0, static_tensors=static_tensors)
1010
+ compiled_decoder = compile_model(
1011
+ wrapped_model,
1012
+ dec_compile_config,
1013
+ dec_example_inputs,
1014
+ context,
1015
+ rbln_config.quantization,
1016
+ )
1017
+ compiled_models[f"decoder_batch_{batch_size}"] = compiled_decoder
1018
+
1019
+ return compiled_models
1020
+
1021
+ @classmethod
1022
+ def _create_runtimes(
1023
+ cls,
1024
+ compiled_models: List[rebel.RBLNCompiledModel],
1025
+ rbln_config: RBLNGemma3ForCausalLMConfig,
1026
+ ) -> List[rebel.Runtime]:
1027
+ expected_model_names = [
1028
+ "prefill",
1029
+ "image_prefill",
1030
+ *[f"decoder_batch_{batch_size}" for batch_size in rbln_config.decoder_batch_sizes],
1031
+ ]
1032
+ if any(model_name not in rbln_config.device_map for model_name in expected_model_names):
1033
+ cls._raise_missing_compiled_file_error(expected_model_names)
1034
+
1035
+ return [
1036
+ rebel.Runtime(
1037
+ compiled_models[0],
1038
+ tensor_type="pt",
1039
+ device=rbln_config.device_map["prefill"],
1040
+ activate_profiler=rbln_config.activate_profiler,
1041
+ ),
1042
+ rebel.Runtime(
1043
+ compiled_models[1],
1044
+ tensor_type="pt",
1045
+ device=rbln_config.device_map["image_prefill"],
1046
+ activate_profiler=rbln_config.activate_profiler,
1047
+ ),
1048
+ *[
1049
+ rebel.Runtime(
1050
+ compiled_models[i + 2],
1051
+ tensor_type="pt",
1052
+ device=rbln_config.device_map[f"decoder_batch_{batch_size}"],
1053
+ activate_profiler=rbln_config.activate_profiler,
1054
+ )
1055
+ for i, batch_size in enumerate(rbln_config.decoder_batch_sizes)
1056
+ ],
1057
+ ]