optimum-rbln 0.8.2a4__py3-none-any.whl → 0.9.3rc0__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 (167) hide show
  1. optimum/rbln/__init__.py +96 -9
  2. optimum/rbln/__version__.py +16 -3
  3. optimum/rbln/cli.py +660 -0
  4. optimum/rbln/configuration_utils.py +153 -42
  5. optimum/rbln/diffusers/__init__.py +7 -0
  6. optimum/rbln/diffusers/configurations/models/configuration_autoencoder_kl.py +3 -3
  7. optimum/rbln/diffusers/configurations/models/configuration_autoencoder_kl_cosmos.py +1 -1
  8. optimum/rbln/diffusers/configurations/models/configuration_controlnet.py +3 -3
  9. optimum/rbln/diffusers/configurations/models/configuration_prior_transformer.py +4 -4
  10. optimum/rbln/diffusers/configurations/models/configuration_transformer_cosmos.py +9 -4
  11. optimum/rbln/diffusers/configurations/models/configuration_transformer_sd3.py +9 -4
  12. optimum/rbln/diffusers/configurations/models/configuration_unet_2d_condition.py +3 -3
  13. optimum/rbln/diffusers/configurations/models/configuration_vq_model.py +3 -3
  14. optimum/rbln/diffusers/configurations/pipelines/configuration_controlnet.py +35 -19
  15. optimum/rbln/diffusers/configurations/pipelines/configuration_cosmos.py +14 -11
  16. optimum/rbln/diffusers/configurations/pipelines/configuration_kandinsky2_2.py +30 -20
  17. optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion.py +13 -9
  18. optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion_3.py +17 -13
  19. optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion_xl.py +17 -10
  20. optimum/rbln/diffusers/modeling_diffusers.py +30 -14
  21. optimum/rbln/diffusers/models/__init__.py +3 -13
  22. optimum/rbln/diffusers/models/autoencoders/autoencoder_kl.py +31 -3
  23. optimum/rbln/diffusers/models/autoencoders/autoencoder_kl_cosmos.py +28 -3
  24. optimum/rbln/diffusers/models/autoencoders/vq_model.py +31 -3
  25. optimum/rbln/diffusers/models/transformers/prior_transformer.py +1 -1
  26. optimum/rbln/diffusers/models/transformers/transformer_cosmos.py +9 -1
  27. optimum/rbln/diffusers/models/transformers/transformer_sd3.py +9 -1
  28. optimum/rbln/diffusers/models/unets/unet_2d_condition.py +6 -3
  29. optimum/rbln/diffusers/pipelines/__init__.py +11 -5
  30. optimum/rbln/diffusers/pipelines/auto_pipeline.py +307 -0
  31. optimum/rbln/diffusers/pipelines/cosmos/configuration_cosmos_guardrail.py +19 -16
  32. optimum/rbln/diffusers/pipelines/cosmos/cosmos_guardrail.py +14 -18
  33. optimum/rbln/diffusers/pipelines/cosmos/pipeline_cosmos_text2world.py +31 -1
  34. optimum/rbln/diffusers/pipelines/cosmos/pipeline_cosmos_video2world.py +31 -1
  35. optimum/rbln/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +1 -6
  36. optimum/rbln/modeling.py +71 -19
  37. optimum/rbln/modeling_base.py +99 -21
  38. optimum/rbln/ops/attn.py +158 -0
  39. optimum/rbln/ops/flash_attn.py +166 -0
  40. optimum/rbln/ops/kv_cache_update.py +5 -0
  41. optimum/rbln/ops/linear.py +7 -0
  42. optimum/rbln/transformers/__init__.py +92 -0
  43. optimum/rbln/transformers/configuration_generic.py +9 -7
  44. optimum/rbln/transformers/modeling_attention_utils.py +252 -0
  45. optimum/rbln/transformers/modeling_generic.py +51 -9
  46. optimum/rbln/transformers/modeling_outputs.py +37 -0
  47. optimum/rbln/transformers/models/__init__.py +91 -30
  48. optimum/rbln/transformers/models/auto/__init__.py +2 -0
  49. optimum/rbln/transformers/models/auto/auto_factory.py +92 -17
  50. optimum/rbln/transformers/models/auto/modeling_auto.py +45 -0
  51. optimum/rbln/transformers/models/bart/bart_architecture.py +1 -3
  52. optimum/rbln/transformers/models/bart/configuration_bart.py +2 -0
  53. optimum/rbln/transformers/models/bert/bert_architecture.py +16 -0
  54. optimum/rbln/transformers/models/bert/modeling_bert.py +8 -4
  55. optimum/rbln/transformers/models/blip_2/configuration_blip_2.py +42 -11
  56. optimum/rbln/transformers/models/blip_2/modeling_blip_2.py +94 -30
  57. optimum/rbln/transformers/models/clip/configuration_clip.py +10 -7
  58. optimum/rbln/transformers/models/clip/modeling_clip.py +27 -4
  59. optimum/rbln/transformers/models/colpali/colpali_architecture.py +3 -6
  60. optimum/rbln/transformers/models/colpali/configuration_colpali.py +37 -21
  61. optimum/rbln/transformers/models/colpali/modeling_colpali.py +113 -96
  62. optimum/rbln/transformers/models/colqwen2/__init__.py +2 -0
  63. optimum/rbln/transformers/models/colqwen2/colqwen2_architecture.py +233 -0
  64. optimum/rbln/transformers/models/colqwen2/configuration_colqwen2.py +74 -0
  65. optimum/rbln/transformers/models/colqwen2/modeling_colqwen2.py +446 -0
  66. optimum/rbln/transformers/models/decoderonly/__init__.py +3 -2
  67. optimum/rbln/transformers/models/decoderonly/configuration_decoderonly.py +109 -37
  68. optimum/rbln/transformers/models/decoderonly/configuration_lora.py +411 -0
  69. optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py +318 -309
  70. optimum/rbln/transformers/models/decoderonly/decoderonly_runtime_utils.py +504 -0
  71. optimum/rbln/transformers/models/decoderonly/generation_decoderonly.py +111 -0
  72. optimum/rbln/transformers/models/decoderonly/lora_architecture.py +204 -0
  73. optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py +453 -897
  74. optimum/rbln/transformers/models/depth_anything/__init__.py +16 -0
  75. optimum/rbln/transformers/models/depth_anything/configuration_depth_anything.py +24 -0
  76. optimum/rbln/transformers/models/depth_anything/modeling_depth_anything.py +25 -0
  77. optimum/rbln/transformers/models/exaone/modeling_exaone.py +42 -4
  78. optimum/rbln/transformers/models/gemma/__init__.py +2 -2
  79. optimum/rbln/transformers/models/gemma/configuration_gemma.py +9 -1
  80. optimum/rbln/transformers/models/gemma/gemma_architecture.py +1 -4
  81. optimum/rbln/transformers/models/gemma/modeling_gemma.py +22 -1
  82. optimum/rbln/transformers/models/gemma3/configuration_gemma3.py +49 -13
  83. optimum/rbln/transformers/models/gemma3/gemma3_architecture.py +12 -2
  84. optimum/rbln/transformers/models/gemma3/gemma3_runtime_utils.py +245 -0
  85. optimum/rbln/transformers/models/gemma3/modeling_gemma3.py +201 -349
  86. optimum/rbln/transformers/models/gpt2/__init__.py +2 -2
  87. optimum/rbln/transformers/models/gpt2/configuration_gpt2.py +31 -3
  88. optimum/rbln/transformers/models/gpt2/gpt2_architecture.py +10 -8
  89. optimum/rbln/transformers/models/gpt2/modeling_gpt2.py +18 -1
  90. optimum/rbln/transformers/models/grounding_dino/__init__.py +10 -0
  91. optimum/rbln/transformers/models/grounding_dino/configuration_grounding_dino.py +92 -0
  92. optimum/rbln/transformers/models/grounding_dino/grounding_dino_architecture.py +599 -0
  93. optimum/rbln/transformers/models/grounding_dino/modeling_grounding_dino.py +1032 -0
  94. optimum/rbln/transformers/models/idefics3/configuration_idefics3.py +35 -7
  95. optimum/rbln/transformers/models/idefics3/modeling_idefics3.py +26 -27
  96. optimum/rbln/transformers/models/llama/__init__.py +2 -2
  97. optimum/rbln/transformers/models/llama/configuration_llama.py +9 -1
  98. optimum/rbln/transformers/models/llama/modeling_llama.py +22 -1
  99. optimum/rbln/transformers/models/llava/__init__.py +16 -0
  100. optimum/rbln/transformers/models/llava/configuration_llava.py +72 -0
  101. optimum/rbln/transformers/models/llava/modeling_llava.py +478 -0
  102. optimum/rbln/transformers/models/llava_next/configuration_llava_next.py +15 -17
  103. optimum/rbln/transformers/models/llava_next/modeling_llava_next.py +235 -375
  104. optimum/rbln/transformers/models/midm/midm_architecture.py +4 -1
  105. optimum/rbln/transformers/models/midm/modeling_midm.py +42 -4
  106. optimum/rbln/transformers/models/mistral/__init__.py +2 -2
  107. optimum/rbln/transformers/models/mistral/configuration_mistral.py +9 -1
  108. optimum/rbln/transformers/models/mistral/mistral_architecture.py +1 -1
  109. optimum/rbln/transformers/models/mistral/modeling_mistral.py +26 -3
  110. optimum/rbln/transformers/models/opt/__init__.py +2 -2
  111. optimum/rbln/transformers/models/opt/configuration_opt.py +8 -1
  112. optimum/rbln/transformers/models/opt/modeling_opt.py +28 -16
  113. optimum/rbln/transformers/models/opt/opt_architecture.py +4 -4
  114. optimum/rbln/transformers/models/pegasus/__init__.py +17 -0
  115. optimum/rbln/transformers/models/pegasus/configuration_pegasus.py +38 -0
  116. optimum/rbln/transformers/models/pegasus/modeling_pegasus.py +71 -0
  117. optimum/rbln/transformers/models/pegasus/pegasus_architecture.py +161 -0
  118. optimum/rbln/transformers/models/phi/__init__.py +2 -2
  119. optimum/rbln/transformers/models/phi/configuration_phi.py +9 -1
  120. optimum/rbln/transformers/models/phi/modeling_phi.py +10 -1
  121. optimum/rbln/transformers/models/phi/phi_architecture.py +11 -7
  122. optimum/rbln/transformers/models/pixtral/__init__.py +16 -0
  123. optimum/rbln/transformers/models/pixtral/configuration_pixtral.py +43 -0
  124. optimum/rbln/transformers/models/pixtral/modeling_pixtral.py +310 -0
  125. optimum/rbln/transformers/models/pixtral/pixtral_architecture.py +73 -0
  126. optimum/rbln/transformers/models/qwen2/__init__.py +2 -2
  127. optimum/rbln/transformers/models/qwen2/configuration_qwen2.py +9 -1
  128. optimum/rbln/transformers/models/qwen2/modeling_qwen2.py +27 -1
  129. optimum/rbln/transformers/models/qwen2_5_vl/configuration_qwen2_5_vl.py +21 -6
  130. optimum/rbln/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py +15 -21
  131. optimum/rbln/transformers/models/qwen2_5_vl/qwen2_5_vl_architecture.py +28 -7
  132. optimum/rbln/transformers/models/qwen2_vl/__init__.py +19 -0
  133. optimum/rbln/transformers/models/qwen2_vl/configuration_qwen2_vl.py +88 -0
  134. optimum/rbln/transformers/models/qwen2_vl/modeling_qwen2_vl.py +514 -0
  135. optimum/rbln/transformers/models/qwen2_vl/qwen2_vl_architecture.py +165 -0
  136. optimum/rbln/transformers/models/qwen3/configuration_qwen3.py +2 -2
  137. optimum/rbln/transformers/models/qwen3/modeling_qwen3.py +86 -330
  138. optimum/rbln/transformers/models/qwen3/qwen3_architecture.py +1 -245
  139. optimum/rbln/transformers/models/seq2seq/configuration_seq2seq.py +20 -13
  140. optimum/rbln/transformers/models/seq2seq/modeling_seq2seq.py +24 -3
  141. optimum/rbln/transformers/models/seq2seq/seq2seq_architecture.py +2 -2
  142. optimum/rbln/transformers/models/siglip/__init__.py +2 -6
  143. optimum/rbln/transformers/models/siglip/configuration_siglip.py +1 -1
  144. optimum/rbln/transformers/models/siglip/modeling_siglip.py +5 -16
  145. optimum/rbln/transformers/models/swin/__init__.py +16 -0
  146. optimum/rbln/transformers/models/swin/configuration_swin.py +42 -0
  147. optimum/rbln/transformers/models/swin/modeling_swin.py +341 -0
  148. optimum/rbln/transformers/models/t5/configuration_t5.py +2 -0
  149. optimum/rbln/transformers/models/t5/t5_architecture.py +8 -1
  150. optimum/rbln/transformers/models/time_series_transformer/configuration_time_series_transformer.py +3 -3
  151. optimum/rbln/transformers/models/time_series_transformer/modeling_time_series_transformer.py +4 -14
  152. optimum/rbln/transformers/models/time_series_transformer/time_series_transformers_architecture.py +7 -1
  153. optimum/rbln/transformers/models/wav2vec2/modeling_wav2vec2.py +1 -0
  154. optimum/rbln/transformers/models/whisper/configuration_whisper.py +12 -13
  155. optimum/rbln/transformers/models/whisper/generation_whisper.py +28 -6
  156. optimum/rbln/transformers/models/whisper/modeling_whisper.py +28 -3
  157. optimum/rbln/transformers/models/xlm_roberta/__init__.py +2 -8
  158. optimum/rbln/transformers/utils/rbln_quantization.py +391 -75
  159. optimum/rbln/transformers/utils/rbln_runtime_wrapper.py +79 -0
  160. optimum/rbln/utils/depreacate_utils.py +16 -0
  161. optimum/rbln/utils/runtime_utils.py +28 -18
  162. optimum/rbln/utils/submodule.py +31 -9
  163. {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.9.3rc0.dist-info}/METADATA +8 -7
  164. {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.9.3rc0.dist-info}/RECORD +167 -125
  165. optimum_rbln-0.9.3rc0.dist-info/entry_points.txt +2 -0
  166. {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.9.3rc0.dist-info}/WHEEL +0 -0
  167. {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.9.3rc0.dist-info}/licenses/LICENSE +0 -0
@@ -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_depth_anything import RBLNDepthAnythingForDepthEstimationConfig
16
+ from .modeling_depth_anything import RBLNDepthAnythingForDepthEstimation
@@ -0,0 +1,24 @@
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_generic import RBLNModelForDepthEstimationConfig
16
+
17
+
18
+ class RBLNDepthAnythingForDepthEstimationConfig(RBLNModelForDepthEstimationConfig):
19
+ """
20
+ Configuration class for DepthAnythingForDepthEstimation.
21
+
22
+ This configuration class stores the configuration parameters specific to
23
+ RBLN-optimized Depth Anything V2 Small models for depth estimation tasks.
24
+ """
@@ -0,0 +1,25 @@
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
+
16
+ from ...modeling_generic import RBLNModelForDepthEstimation
17
+
18
+
19
+ class RBLNDepthAnythingForDepthEstimation(RBLNModelForDepthEstimation):
20
+ """
21
+ RBLN optimized DepthAnythingForDepthEstimation model for depth estimation tasks.
22
+
23
+ This class provides hardware-accelerated inference for Depth Anything V2
24
+ models on RBLN devices, providing the most capable monocular depth estimation (MDE) model.
25
+ """
@@ -14,11 +14,13 @@
14
14
 
15
15
 
16
16
  import inspect
17
- from typing import Any, Callable
17
+ from pathlib import Path
18
+ from typing import Any, Callable, Dict, Optional, Union
18
19
 
19
20
  from transformers import AutoModelForCausalLM
20
21
  from transformers.generation.utils import GenerationMixin
21
22
 
23
+ from ....configuration_utils import RBLNModelConfig
22
24
  from ....utils import logging
23
25
  from ..decoderonly import RBLNDecoderOnlyModelForCausalLM
24
26
  from .exaone_architecture import ExaoneForCausalLMWrapper
@@ -92,9 +94,45 @@ class RBLNExaoneForCausalLM(RBLNDecoderOnlyModelForCausalLM):
92
94
  _supports_cache_class = True
93
95
 
94
96
  @classmethod
95
- def from_pretrained(cls, *args, **kwargs):
96
- kwargs.setdefault("trust_remote_code", True)
97
- return super().from_pretrained(*args, **kwargs)
97
+ def from_pretrained(
98
+ cls,
99
+ model_id: Union[str, Path],
100
+ *,
101
+ export: Optional[bool] = None,
102
+ rbln_config: Optional[Union[Dict, RBLNModelConfig]] = None,
103
+ trust_remote_code: Optional[bool] = None,
104
+ **kwargs: Any,
105
+ ):
106
+ """
107
+ The `from_pretrained()` function is utilized in its standard form as in the HuggingFace transformers library.
108
+ User can use this function to load a pre-trained model from the HuggingFace library and convert it to a RBLN model to be run on RBLN NPUs.
109
+
110
+ Args:
111
+ model_id (Union[str, Path]): The model id of the pre-trained model to be loaded.
112
+ It can be downloaded from the HuggingFace model hub or a local path, or a model id of a compiled model using the RBLN Compiler.
113
+ export (Optional[bool]): A boolean flag to indicate whether the model should be compiled.
114
+ If None, it will be determined based on the existence of the compiled model files in the model_id.
115
+ rbln_config (Optional[Union[Dict, RBLNModelConfig]]): Configuration for RBLN model compilation and runtime.
116
+ This can be provided as a dictionary or an instance of the model's configuration class (e.g., `RBLNExaoneForCausalLMConfig` for EXAONE models).
117
+ For detailed configuration options, see the specific model's configuration class documentation.
118
+ trust_remote_code (bool): Whether or not to trust the remote code when loading a model from the Hub.
119
+ kwargs: Additional keyword arguments. Arguments with the prefix `rbln_` are passed to rbln_config, while the remaining arguments are passed to the HuggingFace library.
120
+
121
+ Returns:
122
+ (RBLNModel): A RBLN model instance ready for inference on RBLN NPU devices.
123
+ """
124
+
125
+ if trust_remote_code is not None:
126
+ kwargs["trust_remote_code"] = trust_remote_code
127
+ elif "trust_remote_code" not in kwargs:
128
+ kwargs["trust_remote_code"] = True
129
+
130
+ return super().from_pretrained(
131
+ model_id=model_id,
132
+ export=export,
133
+ rbln_config=rbln_config,
134
+ **kwargs,
135
+ )
98
136
 
99
137
  def __getattr__(self, __name: str) -> Any:
100
138
  def redirect(func):
@@ -12,5 +12,5 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
- from .configuration_gemma import RBLNGemmaForCausalLMConfig
16
- from .modeling_gemma import RBLNGemmaForCausalLM
15
+ from .configuration_gemma import RBLNGemmaForCausalLMConfig, RBLNGemmaModelConfig
16
+ from .modeling_gemma import RBLNGemmaForCausalLM, RBLNGemmaModel
@@ -12,7 +12,7 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
- from ..decoderonly.configuration_decoderonly import RBLNDecoderOnlyModelForCausalLMConfig
15
+ from ..decoderonly.configuration_decoderonly import RBLNDecoderOnlyModelConfig, RBLNDecoderOnlyModelForCausalLMConfig
16
16
 
17
17
 
18
18
  class RBLNGemmaForCausalLMConfig(RBLNDecoderOnlyModelForCausalLMConfig):
@@ -40,3 +40,11 @@ class RBLNGemmaForCausalLMConfig(RBLNDecoderOnlyModelForCausalLMConfig):
40
40
  )
41
41
  ```
42
42
  """
43
+
44
+
45
+ class RBLNGemmaModelConfig(RBLNDecoderOnlyModelConfig):
46
+ """
47
+ Configuration class for RBLN Gemma models.
48
+
49
+ This class is an alias of RBLNDecoderOnlyModelConfig.
50
+ """
@@ -13,10 +13,7 @@
13
13
  # limitations under the License.
14
14
 
15
15
 
16
- from ...models.decoderonly.decoderonly_architecture import (
17
- DecoderOnlyModel,
18
- DecoderOnlyWrapper,
19
- )
16
+ from ...models.decoderonly.decoderonly_architecture import DecoderOnlyModel, DecoderOnlyWrapper
20
17
 
21
18
 
22
19
  class GemmaWrapper(DecoderOnlyWrapper):
@@ -13,7 +13,7 @@
13
13
  # limitations under the License.
14
14
 
15
15
  from ....utils import logging
16
- from ...models.decoderonly import RBLNDecoderOnlyModelForCausalLM
16
+ from ...models.decoderonly import RBLNDecoderOnlyModel, RBLNDecoderOnlyModelForCausalLM
17
17
  from .gemma_architecture import GemmaWrapper
18
18
 
19
19
 
@@ -81,3 +81,24 @@ class RBLNGemmaForCausalLM(RBLNDecoderOnlyModelForCausalLM):
81
81
  """
82
82
 
83
83
  _decoder_wrapper_cls = GemmaWrapper
84
+
85
+
86
+ class RBLNGemmaModel(RBLNDecoderOnlyModel):
87
+ """
88
+ The Gemma Model transformer without a language modeling head.
89
+ This model inherits from [`RBLNDecoderOnlyModel`]. Check the superclass documentation for the generic methods the library implements for all its models.
90
+
91
+ A class to convert and run pre-trained transformers based GemmaModel model on RBLN devices.
92
+ It implements the methods to convert a pre-trained transformers GemmaModel model into a RBLN transformer model by:
93
+
94
+ - transferring the checkpoint weights of the original into an optimized RBLN graph,
95
+ - compiling the resulting graph using the RBLN compiler.
96
+
97
+ **Configuration:**
98
+ This model uses [`RBLNGemmaModelConfig`] for configuration. When calling methods like `from_pretrained` or `from_model`,
99
+ the `rbln_config` parameter should be an instance of [`RBLNGemmaModelConfig`] or a dictionary conforming to its structure.
100
+
101
+ See the [`RBLNGemmaModelConfig`] class for all available configuration options.
102
+ """
103
+
104
+ _decoder_wrapper_cls = GemmaWrapper
@@ -11,13 +11,14 @@
11
11
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
- from typing import Any, Dict, Optional
15
-
16
- import rebel
14
+ from typing import Any, Optional
17
15
 
18
16
  from ....configuration_utils import RBLNModelConfig
17
+ from ....utils.logging import get_logger
19
18
  from ..decoderonly.configuration_decoderonly import RBLNDecoderOnlyModelForCausalLMConfig
20
- from ..siglip.configuration_siglip import RBLNSiglipVisionModelConfig
19
+
20
+
21
+ logger = get_logger(__name__)
21
22
 
22
23
 
23
24
  class RBLNGemma3ForCausalLMConfig(RBLNDecoderOnlyModelForCausalLMConfig):
@@ -25,23 +26,45 @@ class RBLNGemma3ForCausalLMConfig(RBLNDecoderOnlyModelForCausalLMConfig):
25
26
  self,
26
27
  use_position_ids: Optional[bool] = None,
27
28
  use_attention_mask: Optional[bool] = None,
29
+ prefill_chunk_size: Optional[int] = None,
28
30
  image_prefill_chunk_size: Optional[int] = None,
29
- **kwargs: Dict[str, Any],
31
+ **kwargs: Any,
30
32
  ):
33
+ """
34
+ Args:
35
+ use_position_ids (Optional[bool]): Whether or not to use `position_ids`, which is indices of positions of each input sequence tokens in the position embeddings.
36
+ use_attention_mask (Optional[bool]): Whether or not to use `attention_mask` to to avoid performing attention on padding token indices.
37
+ prefill_chunk_size (Optional[int]): The chunk size used during the prefill phase for
38
+ processing input sequences. Defaults to 256. Must be a positive integer
39
+ divisible by 64. Affects prefill performance and memory usage.
40
+ image_prefill_chunk_size (Optional[int]): The chunk size used during the prefill phase for
41
+ processing images. This config is used when `use_image_prefill` is True.
42
+ Currently, the `prefill_chunk_size` and `image_prefill_chunk_size` should be the same value.
43
+ kwargs: Additional arguments passed to the parent `RBLNDecoderOnlyModelForCausalLMConfig`.
44
+
45
+ Raises:
46
+ ValueError: If `use_attention_mask` or `use_position_ids` are False.
47
+ """
31
48
  # use_attention_mask and use_position_ids are always True for Gemma3
32
49
  use_attention_mask = use_attention_mask or True
33
50
  use_position_ids = use_position_ids or True
51
+ prefill_chunk_size = prefill_chunk_size or 256
34
52
 
35
53
  super().__init__(
54
+ prefill_chunk_size=prefill_chunk_size,
36
55
  use_attention_mask=use_attention_mask,
37
56
  use_position_ids=use_position_ids,
38
57
  **kwargs,
39
58
  )
40
59
  self.image_prefill_chunk_size = image_prefill_chunk_size
41
60
 
42
- npu = self.npu or rebel.get_npu_name()
43
- if npu == "RBLN-CA02":
44
- raise NotImplementedError("Gemma3 is currently not supported on RBLN-CA02")
61
+ @property
62
+ def use_image_prefill(self):
63
+ return self.image_prefill_chunk_size is not None
64
+
65
+ @property
66
+ def decoder_runtime_idx(self):
67
+ return 2 if self.use_image_prefill else 1
45
68
 
46
69
 
47
70
  class RBLNGemma3ForConditionalGenerationConfig(RBLNModelConfig):
@@ -52,22 +75,35 @@ class RBLNGemma3ForConditionalGenerationConfig(RBLNModelConfig):
52
75
  batch_size: Optional[int] = None,
53
76
  vision_tower: Optional[RBLNModelConfig] = None,
54
77
  language_model: Optional[RBLNModelConfig] = None,
55
- **kwargs: Dict[str, Any],
78
+ **kwargs: Any,
56
79
  ):
57
80
  """
58
81
  Args:
59
82
  batch_size (Optional[int]): The batch size for inference. Defaults to 1.
60
83
  vision_tower (Optional[RBLNModelConfig]): Configuration for the vision encoder component.
61
84
  language_model (Optional[RBLNModelConfig]): Configuration for the language model component.
62
- **kwargs: Additional arguments passed to the parent RBLNModelConfig.
85
+ kwargs: Additional arguments passed to the parent RBLNModelConfig.
63
86
 
64
87
  Raises:
65
- ValueError: If batch_size is not a positive integer.
88
+ ValueError: If `batch_size` is not a positive integer.
66
89
  """
67
90
  super().__init__(**kwargs)
68
91
  self.batch_size = batch_size or 1
69
92
  if not isinstance(self.batch_size, int) or self.batch_size < 0:
70
93
  raise ValueError(f"batch_size must be a positive integer, got {self.batch_size}")
71
94
 
72
- self.vision_tower = self.init_submodule_config(RBLNSiglipVisionModelConfig, vision_tower)
73
- self.language_model = self.init_submodule_config(RBLNGemma3ForCausalLMConfig, language_model)
95
+ if self.batch_size != 1:
96
+ logger.warning("Ignore batch_size for Gemma3 vision tower. It will be set to 1.")
97
+
98
+ self.vision_tower = self.initialize_submodule_config(
99
+ submodule_config=vision_tower, batch_size=1, force_kwargs=True
100
+ )
101
+ self.language_model = self.initialize_submodule_config(submodule_config=language_model)
102
+
103
+ @property
104
+ def image_prefill_chunk_size(self):
105
+ return self.language_model.image_prefill_chunk_size
106
+
107
+ @property
108
+ def prefill_chunk_size(self):
109
+ return self.language_model.prefill_chunk_size
@@ -63,6 +63,7 @@ class Gemma3TextModel(DecoderOnlyModel):
63
63
  rotary_emb: torch.nn.Module = None,
64
64
  global_block_tables: Optional[torch.Tensor] = None,
65
65
  local_block_tables: Optional[torch.Tensor] = None,
66
+ lora_int_id: Optional[torch.Tensor] = None,
66
67
  ):
67
68
  # retrieve input_ids and inputs_embeds
68
69
  if (input_ids is None) ^ (inputs_embeds is not None):
@@ -105,6 +106,7 @@ class Gemma3TextModel(DecoderOnlyModel):
105
106
  cos=cos_local if is_sliding else cos_global,
106
107
  sin=sin_local if is_sliding else sin_global,
107
108
  block_tables=local_block_tables if is_sliding else global_block_tables,
109
+ lora_int_id=lora_int_id,
108
110
  )
109
111
 
110
112
  hidden_states = self.get_last_layernorm()(hidden_states)
@@ -127,12 +129,20 @@ class Gemma3DecoderLayer(DecoderOnlyLayer):
127
129
  cos: Optional[torch.Tensor] = None,
128
130
  sin: Optional[torch.Tensor] = None,
129
131
  block_tables: Optional[torch.Tensor] = None,
132
+ lora_int_id: Optional[torch.Tensor] = None,
130
133
  ):
131
134
  residual = hidden_states
132
135
  hidden_states = self.get_pre_attention_layernorm()(hidden_states)
133
136
 
134
137
  hidden_states = self.self_attn(
135
- hidden_states, attention_mask, seq_positions, past_key_values, cos, sin, block_tables
138
+ hidden_states=hidden_states,
139
+ attention_mask=attention_mask,
140
+ seq_positions=seq_positions,
141
+ past_key_values=past_key_values,
142
+ cos=cos,
143
+ sin=sin,
144
+ block_tables=block_tables,
145
+ lora_int_id=lora_int_id,
136
146
  )
137
147
  hidden_states = self.get_post_attention_layernorm()(hidden_states)
138
148
  hidden_states = residual + hidden_states
@@ -140,7 +150,7 @@ class Gemma3DecoderLayer(DecoderOnlyLayer):
140
150
  # Fully Connected
141
151
  residual = hidden_states
142
152
  hidden_states = self.get_pre_feedforward_layernorm()(hidden_states)
143
- hidden_states = self._original_mod.mlp(hidden_states)
153
+ hidden_states = self.forward_mlp(hidden_states, lora_int_id)
144
154
  hidden_states = self.get_post_feedforward_layernorm()(hidden_states)
145
155
  hidden_states = residual + hidden_states
146
156
 
@@ -0,0 +1,245 @@
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
+ from typing import Optional
15
+
16
+ import rebel
17
+ import torch
18
+
19
+ from ...modeling_outputs import RBLNDecoderOnlyOutput, RBLNGemma3ForCausalLMOutput
20
+ from ..decoderonly.decoderonly_runtime_utils import RBLNPytorchRuntime
21
+ from ..decoderonly.modeling_decoderonly import RBLNRuntimeModel
22
+
23
+
24
+ class RBLNGemma3RuntimeModel(RBLNRuntimeModel):
25
+ def __init__(self, *args, image_prefill: Optional[rebel.Runtime] = None, **kwargs):
26
+ super().__init__(*args, **kwargs)
27
+ self.image_prefill = RBLNPytorchRuntime(image_prefill) # FIXME(taehoon)
28
+ self.prefill = RBLNPytorchRuntime(self.runtime) if self.phase == "prefill" else None # FIXME
29
+ self.decode = RBLNPytorchRuntime(self.runtime) if self.phase == "decode" else None
30
+
31
+ def _prepare_prefill_inputs(self, *args, **kwargs):
32
+ (
33
+ inputs,
34
+ cache_position,
35
+ chunked_attention_mask,
36
+ position_ids,
37
+ position_embed,
38
+ padded_cache_lengths,
39
+ query_length,
40
+ token_type_ids,
41
+ ) = super()._prepare_prefill_inputs(*args, **kwargs)
42
+
43
+ # chunked_attention_mask shape
44
+ chunked_attention_mask = torch.zeros(1, chunked_attention_mask.shape[-1], dtype=torch.float32)
45
+
46
+ # In case of Gemma3ForConditionalGeneration, the loop counter may not be a prefill_chunk_size,
47
+ # so we cannot guarantee that the last chunk starts at a position that is a multiple of prefill_chunk_size.
48
+ if self.rbln_config.use_image_prefill:
49
+ padding_size = self.rbln_config.image_prefill_chunk_size
50
+ inputs = torch.nn.functional.pad(inputs, (0, 0, 0, padding_size))
51
+ cache_position = torch.nn.functional.pad(cache_position, (0, padding_size))
52
+ position_ids = torch.nn.functional.pad(position_ids, (0, padding_size))
53
+ token_type_ids = torch.nn.functional.pad(token_type_ids, (0, padding_size), value=-1)
54
+
55
+ return (
56
+ inputs,
57
+ cache_position,
58
+ chunked_attention_mask,
59
+ position_ids,
60
+ position_embed,
61
+ padded_cache_lengths,
62
+ query_length,
63
+ token_type_ids,
64
+ )
65
+
66
+ def prefill_forward(
67
+ self,
68
+ inputs: torch.Tensor,
69
+ cache_position: torch.Tensor = None,
70
+ attention_mask: Optional[torch.Tensor] = None,
71
+ batch_idx: int = None,
72
+ block_tables: torch.Tensor = None,
73
+ is_external_block_tables: bool = None,
74
+ position_embed: Optional[torch.Tensor] = None,
75
+ token_type_ids: Optional[torch.Tensor] = None,
76
+ local_block_tables: Optional[torch.Tensor] = None,
77
+ lora_int_ids: Optional[torch.Tensor] = None,
78
+ ) -> torch.FloatTensor:
79
+ """
80
+ Performs chunked prefill for efficient KV-cache updates and memory optimization.
81
+ Instead of processing the entire sequence at once, the input is divided into chunks of size `prefill_chunk_size`,
82
+ and each chunk is processed sequentially. This allows for better memory utilization and compatibility with continuous batching.
83
+ """
84
+ if self.rbln_config.use_lora and lora_int_ids is None:
85
+ if self.lora_int_ids is None:
86
+ raise ValueError(
87
+ "lora_int_id is required when using LoRA. "
88
+ "You should call set_lora_int_ids() before forward() or pass lora_int_id to forward()."
89
+ )
90
+ if batch_idx is not None:
91
+ lora_int_ids = self.lora_int_ids[batch_idx : batch_idx + 1].clone()
92
+ else:
93
+ lora_int_ids = self.lora_int_ids.clone()
94
+
95
+ (
96
+ inputs,
97
+ cache_position,
98
+ chunked_attention_mask,
99
+ position_ids,
100
+ position_embed,
101
+ padded_cache_lengths,
102
+ query_length,
103
+ token_type_ids,
104
+ ) = self._prepare_prefill_inputs(
105
+ inputs, cache_position, attention_mask, position_embed, token_type_ids=token_type_ids
106
+ )
107
+
108
+ step = 0
109
+ while step < query_length:
110
+ if self.rbln_config.use_image_prefill:
111
+ # Check if the prefill chunk is an image prefill
112
+ is_image_prefill = torch.all(
113
+ token_type_ids[:, step : step + self.rbln_config.image_prefill_chunk_size] == 1
114
+ )
115
+ # Check if the prefill chunk is a text prefill which have image_tokens in it.
116
+ is_text_prefill_with_image_tokens = not is_image_prefill and torch.any(
117
+ token_type_ids[:, step : step + self.rbln_config.prefill_chunk_size] == 1
118
+ )
119
+ else:
120
+ is_image_prefill, is_text_prefill_with_image_tokens = False, False
121
+
122
+ # Check if the prefill chunk is the last chunk
123
+ is_last_chunk = step + self.rbln_config.prefill_chunk_size >= query_length
124
+
125
+ input_chunk = inputs[:, step : step + self.rbln_config.prefill_chunk_size]
126
+ cache_pos_chunk = (
127
+ cache_position[:, step : step + self.rbln_config.prefill_chunk_size] + padded_cache_lengths
128
+ )
129
+ position_ids_chunk = position_ids[:, step : step + self.rbln_config.prefill_chunk_size]
130
+
131
+ # if text_prefill end with image_tokens, we only treat the text part.
132
+ num_processed_tokens = self.rbln_config.prefill_chunk_size
133
+ current_padded_cache_lengths = 0
134
+ if is_text_prefill_with_image_tokens:
135
+ first_image_token_idx = torch.where(
136
+ token_type_ids[:, step : step + self.rbln_config.prefill_chunk_size] == 1
137
+ )[1][0]
138
+ num_processed_tokens = first_image_token_idx.item()
139
+ current_padded_cache_lengths = self.rbln_config.prefill_chunk_size - num_processed_tokens
140
+ if is_last_chunk:
141
+ num_processed_tokens = query_length - step
142
+
143
+ chunked_attention_mask[
144
+ :, step + padded_cache_lengths : step + num_processed_tokens + padded_cache_lengths
145
+ ] = 1
146
+ query_position = torch.tensor(num_processed_tokens - 1, dtype=torch.int16)
147
+
148
+ if is_image_prefill:
149
+ logits = self.image_prefill(
150
+ input_chunk,
151
+ cache_pos_chunk,
152
+ block_tables,
153
+ local_block_tables,
154
+ query_position,
155
+ chunked_attention_mask,
156
+ position_ids_chunk,
157
+ lora_int_ids if self.rbln_config.use_lora else None,
158
+ )
159
+ else:
160
+ logits = self.prefill(
161
+ input_chunk,
162
+ cache_pos_chunk,
163
+ block_tables,
164
+ local_block_tables,
165
+ query_position,
166
+ chunked_attention_mask,
167
+ position_ids_chunk,
168
+ lora_int_ids if self.rbln_config.use_lora else None,
169
+ )
170
+
171
+ padded_cache_lengths += current_padded_cache_lengths
172
+ step += num_processed_tokens
173
+
174
+ if not is_external_block_tables:
175
+ self.dec_attn_mask[batch_idx : batch_idx + 1] = chunked_attention_mask
176
+
177
+ return RBLNGemma3ForCausalLMOutput(
178
+ logits=logits, padded_cache_lengths=padded_cache_lengths, attention_mask=chunked_attention_mask
179
+ )
180
+
181
+ def decode_forward(
182
+ self,
183
+ inputs: torch.Tensor,
184
+ cache_position: torch.Tensor = None,
185
+ block_tables: torch.Tensor = None,
186
+ is_external_block_tables: bool = None,
187
+ attention_mask: Optional[torch.Tensor] = None,
188
+ position_embed: Optional[torch.Tensor] = None,
189
+ position_ids: Optional[torch.Tensor] = None,
190
+ local_block_tables: Optional[torch.Tensor] = None,
191
+ lora_int_ids: Optional[torch.Tensor] = None,
192
+ ) -> torch.FloatTensor:
193
+ if self.rbln_config.use_lora and lora_int_ids is None:
194
+ if self.lora_int_ids is None:
195
+ raise ValueError(
196
+ "lora_int_id is required when using LoRA. "
197
+ "You should call set_lora_int_ids() before forward() or pass lora_int_id to forward()."
198
+ )
199
+
200
+ lora_int_ids = self.lora_int_ids
201
+
202
+ if lora_int_ids is not None and lora_int_ids.shape[0] != self.batch_size:
203
+ raise ValueError(f"lora_int_ids size mismatch: got {lora_int_ids.shape[0]}, expected {self.batch_size}.")
204
+
205
+ batch_size = inputs.shape[0]
206
+ if batch_size != self.batch_size:
207
+ raise RuntimeError(
208
+ f"Batch size mismatch: got {batch_size}, expected {self.batch_size} (compiled batch size)."
209
+ )
210
+
211
+ if batch_size != cache_position.shape[0]:
212
+ raise RuntimeError(f"Cache position size mismatch: got {cache_position.shape[0]}, expected {batch_size}.")
213
+
214
+ # FIXME(taehoon): how to handle pos_attn_mask with external block tables
215
+ if is_external_block_tables:
216
+ if attention_mask is None:
217
+ raise ValueError("attention_mask should be provided with external block tables.")
218
+ if local_block_tables is None:
219
+ raise ValueError("local_block_tables should be provided with external block tables.")
220
+ else:
221
+ local_block_tables = (
222
+ local_block_tables
223
+ if local_block_tables is not None
224
+ else torch.arange(0, self.batch_size, dtype=torch.int16).view(self.batch_size, -1)
225
+ )
226
+ if self.rbln_config.use_attention_mask and attention_mask is None:
227
+ for b_idx in range(batch_size):
228
+ decoding_step = cache_position[b_idx].item()
229
+ if not (0 <= decoding_step < self.dec_attn_mask.shape[-1]):
230
+ raise ValueError(
231
+ f"Decoding step {decoding_step} out of bounds for attention mask with shape {self.dec_attn_mask.shape}."
232
+ )
233
+ self.dec_attn_mask[b_idx, decoding_step] = 1
234
+
235
+ attention_mask = self.dec_attn_mask
236
+
237
+ if self.batch_size < block_tables.shape[0]:
238
+ block_tables = block_tables[: self.batch_size]
239
+
240
+ if attention_mask is not None and self.batch_size < attention_mask.shape[0]:
241
+ attention_mask = attention_mask[: self.batch_size]
242
+
243
+ logits = self.decode(inputs, cache_position, block_tables, local_block_tables, attention_mask, position_ids)
244
+
245
+ return RBLNDecoderOnlyOutput(logits=logits)