optimum-rbln 0.8.1a4__py3-none-any.whl → 0.8.1a6__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 (37) hide show
  1. optimum/rbln/__init__.py +22 -0
  2. optimum/rbln/__version__.py +2 -2
  3. optimum/rbln/diffusers/__init__.py +21 -1
  4. optimum/rbln/diffusers/configurations/__init__.py +4 -0
  5. optimum/rbln/diffusers/configurations/models/__init__.py +2 -0
  6. optimum/rbln/diffusers/configurations/models/configuration_autoencoder_kl_cosmos.py +82 -0
  7. optimum/rbln/diffusers/configurations/models/configuration_cosmos_transformer.py +68 -0
  8. optimum/rbln/diffusers/configurations/pipelines/__init__.py +1 -0
  9. optimum/rbln/diffusers/configurations/pipelines/configuration_cosmos.py +110 -0
  10. optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion_3.py +1 -0
  11. optimum/rbln/diffusers/modeling_diffusers.py +41 -22
  12. optimum/rbln/diffusers/models/__init__.py +4 -0
  13. optimum/rbln/diffusers/models/autoencoders/__init__.py +1 -0
  14. optimum/rbln/diffusers/models/autoencoders/autoencoder_kl_cosmos.py +209 -0
  15. optimum/rbln/diffusers/models/autoencoders/vae.py +49 -5
  16. optimum/rbln/diffusers/models/controlnet.py +1 -1
  17. optimum/rbln/diffusers/models/transformers/__init__.py +1 -0
  18. optimum/rbln/diffusers/models/transformers/transformer_cosmos.py +321 -0
  19. optimum/rbln/diffusers/pipelines/__init__.py +10 -0
  20. optimum/rbln/diffusers/pipelines/cosmos/__init__.py +17 -0
  21. optimum/rbln/diffusers/pipelines/cosmos/configuration_cosmos_guardrail.py +102 -0
  22. optimum/rbln/diffusers/pipelines/cosmos/cosmos_guardrail.py +395 -0
  23. optimum/rbln/diffusers/pipelines/cosmos/pipeline_cosmos_text2world.py +98 -0
  24. optimum/rbln/diffusers/pipelines/cosmos/pipeline_cosmos_video2world.py +98 -0
  25. optimum/rbln/transformers/__init__.py +2 -0
  26. optimum/rbln/transformers/models/__init__.py +8 -0
  27. optimum/rbln/transformers/models/colpali/__init__.py +2 -0
  28. optimum/rbln/transformers/models/colpali/colpali_architecture.py +221 -0
  29. optimum/rbln/transformers/models/colpali/configuration_colpali.py +68 -0
  30. optimum/rbln/transformers/models/colpali/modeling_colpali.py +383 -0
  31. optimum/rbln/transformers/models/qwen2_5_vl/qwen2_5_vl_architecture.py +2 -2
  32. optimum/rbln/transformers/models/t5/modeling_t5.py +10 -4
  33. optimum/rbln/utils/runtime_utils.py +3 -0
  34. {optimum_rbln-0.8.1a4.dist-info → optimum_rbln-0.8.1a6.dist-info}/METADATA +4 -4
  35. {optimum_rbln-0.8.1a4.dist-info → optimum_rbln-0.8.1a6.dist-info}/RECORD +37 -23
  36. {optimum_rbln-0.8.1a4.dist-info → optimum_rbln-0.8.1a6.dist-info}/WHEEL +0 -0
  37. {optimum_rbln-0.8.1a4.dist-info → optimum_rbln-0.8.1a6.dist-info}/licenses/LICENSE +0 -0
@@ -50,6 +50,8 @@ _import_structure = {
50
50
  "RBLNBlip2QFormerModelConfig",
51
51
  "RBLNBlip2VisionModel",
52
52
  "RBLNBlip2VisionModelConfig",
53
+ "RBLNColPaliForRetrieval",
54
+ "RBLNColPaliForRetrievalConfig",
53
55
  "RBLNCLIPTextModel",
54
56
  "RBLNCLIPTextModelConfig",
55
57
  "RBLNCLIPTextModelWithProjection",
@@ -69,6 +69,10 @@ _import_structure = {
69
69
  "RBLNCLIPVisionModelWithProjection",
70
70
  "RBLNCLIPVisionModelWithProjectionConfig",
71
71
  ],
72
+ "colpali": [
73
+ "RBLNColPaliForRetrieval",
74
+ "RBLNColPaliForRetrievalConfig",
75
+ ],
72
76
  "distilbert": [
73
77
  "RBLNDistilBertForQuestionAnswering",
74
78
  "RBLNDistilBertForQuestionAnsweringConfig",
@@ -193,6 +197,10 @@ if TYPE_CHECKING:
193
197
  RBLNCLIPVisionModelWithProjection,
194
198
  RBLNCLIPVisionModelWithProjectionConfig,
195
199
  )
200
+ from .colpali import (
201
+ RBLNColPaliForRetrieval,
202
+ RBLNColPaliForRetrievalConfig,
203
+ )
196
204
  from .decoderonly import (
197
205
  RBLNDecoderOnlyModelForCausalLM,
198
206
  RBLNDecoderOnlyModelForCausalLMConfig,
@@ -0,0 +1,2 @@
1
+ from .configuration_colpali import RBLNColPaliForRetrievalConfig
2
+ from .modeling_colpali import RBLNColPaliForRetrieval
@@ -0,0 +1,221 @@
1
+ from typing import List, Optional, Tuple, Union
2
+
3
+ import torch
4
+ from torch import nn
5
+ from transformers import GemmaForCausalLM, GemmaModel
6
+
7
+ from ..decoderonly.decoderonly_architecture import (
8
+ RotaryEmbedding,
9
+ apply_rotary_pos_emb,
10
+ )
11
+
12
+
13
+ def slice_and_unsqueeze_cos_sin(cos, sin, position_ids):
14
+ """Slice cos[cache_position], sin[cache_position] vector for the query."""
15
+ cos = cos[position_ids[0]][None, None, None, :, :]
16
+ sin = sin[position_ids[0]][None, None, None, :, :]
17
+
18
+ return cos, sin
19
+
20
+
21
+ class RBLNColPaliForRetrievalWrapper(nn.Module):
22
+ def __init__(
23
+ self,
24
+ causal_lm: GemmaForCausalLM,
25
+ embedding_proj_layer: nn.Module,
26
+ max_seq_len: int,
27
+ output_hidden_states: bool = False,
28
+ ):
29
+ super().__init__()
30
+ self.text_config = causal_lm.config
31
+ self.rotary_emb = self.get_rotary_emb(max_seq_len=max_seq_len)
32
+
33
+ self.output_hidden_states = output_hidden_states
34
+ self.language_model = self.convert_to_rbln_language_model(causal_lm.model, max_seq_len)
35
+
36
+ self.num_hidden_layers = getattr(self.text_config, "num_hidden_layers", None)
37
+ self.embedding_proj_layer = embedding_proj_layer
38
+
39
+ def get_rotary_emb(self, max_seq_len):
40
+ return RotaryEmbedding(config=self.text_config, max_seq_len_cached=max_seq_len)
41
+
42
+ def convert_to_rbln_language_model(self, gemma_model: GemmaModel, max_seq_len: int):
43
+ new_layers = []
44
+ for layer in gemma_model.layers:
45
+ new_self_attn = ColPaliAttention(
46
+ layer.self_attn,
47
+ )
48
+ new_layer = ColPaliLayer(layer, new_self_attn)
49
+ new_layers.append(new_layer)
50
+
51
+ new_model = ColPaliModel(
52
+ gemma_model,
53
+ new_layers,
54
+ output_hidden_states=self.output_hidden_states,
55
+ max_seq_len=max_seq_len,
56
+ )
57
+
58
+ return new_model
59
+
60
+ def forward(self, inputs_embeds: torch.Tensor, attention_mask: torch.Tensor, position_ids: torch.Tensor):
61
+ attention_mask = (1.0 - attention_mask) * torch.finfo(torch.float32).min
62
+ attention_mask = attention_mask[:, None, None, None, :]
63
+
64
+ hidden_states, all_hidden_states = self.language_model(
65
+ inputs_embeds=inputs_embeds,
66
+ attention_mask=attention_mask,
67
+ rotary_emb=self.rotary_emb,
68
+ position_ids=position_ids,
69
+ )
70
+ embeddings = self.embedding_proj_layer(hidden_states)
71
+
72
+ if self.output_hidden_states:
73
+ return embeddings, all_hidden_states
74
+ else:
75
+ return embeddings
76
+
77
+
78
+ class ColPaliModel(nn.Module):
79
+ def __init__(
80
+ self, model, layers: List["ColPaliLayer"], output_hidden_states: bool = False, max_seq_len: int = 2048
81
+ ):
82
+ super().__init__()
83
+ self._original_mod = model
84
+ self.layers = nn.ModuleList(layers)
85
+ self.output_hidden_states = output_hidden_states
86
+ self.norm = self._original_mod.norm
87
+ self.hidden_size = self._original_mod.config.hidden_size
88
+ self.max_seq_len = max_seq_len
89
+
90
+ def forward(
91
+ self,
92
+ inputs_embeds: Optional[torch.Tensor] = None,
93
+ attention_mask: torch.Tensor = None,
94
+ rotary_emb: Optional[Union[nn.Module, torch.Tensor]] = None,
95
+ position_ids: Optional[torch.Tensor] = None,
96
+ ):
97
+ hidden_states = inputs_embeds * self.hidden_size**0.5
98
+
99
+ cos, sin = rotary_emb(hidden_states, self.max_seq_len) # dtype carrier, max_seq_len
100
+ cos, sin = slice_and_unsqueeze_cos_sin(cos, sin, position_ids)
101
+
102
+ all_hidden_states = () if self.output_hidden_states else None
103
+ for layer in self.layers:
104
+ if self.output_hidden_states:
105
+ all_hidden_states += (hidden_states,)
106
+
107
+ hidden_states = layer(
108
+ hidden_states=hidden_states,
109
+ attention_mask=attention_mask,
110
+ cos=cos,
111
+ sin=sin,
112
+ )
113
+ hidden_states = self.norm(hidden_states)
114
+
115
+ if self.output_hidden_states:
116
+ all_hidden_states += (hidden_states,)
117
+
118
+ return hidden_states, all_hidden_states
119
+
120
+
121
+ class ColPaliLayer(nn.Module):
122
+ def __init__(self, layer, self_attn: "ColPaliAttention"):
123
+ super().__init__()
124
+ self._original_mod = layer
125
+ self.self_attn = self_attn
126
+ self.mlp = layer.mlp
127
+ self.input_layernorm = layer.input_layernorm
128
+ self.post_attention_layernorm = layer.post_attention_layernorm
129
+
130
+ def forward(
131
+ self,
132
+ hidden_states: torch.Tensor,
133
+ attention_mask: Optional[torch.Tensor] = None,
134
+ cos: Optional[torch.Tensor] = None,
135
+ sin: Optional[torch.Tensor] = None,
136
+ ) -> Tuple[torch.FloatTensor]:
137
+ residual = hidden_states
138
+ hidden_states = self.input_layernorm(hidden_states)
139
+
140
+ # Self Attention
141
+ hidden_states = self.self_attn(
142
+ hidden_states=hidden_states,
143
+ attention_mask=attention_mask,
144
+ cos=cos,
145
+ sin=sin,
146
+ )
147
+ hidden_states = residual + hidden_states
148
+
149
+ # Fully Connected
150
+ residual = hidden_states
151
+ hidden_states = self.post_attention_layernorm(hidden_states)
152
+ hidden_states = self.mlp(hidden_states)
153
+ hidden_states = residual + hidden_states
154
+
155
+ return hidden_states
156
+
157
+
158
+ class ColPaliAttention(nn.Module):
159
+ def __init__(self, self_attn):
160
+ super().__init__()
161
+ self._original_mod = self_attn
162
+ self.num_heads = getattr(self._original_mod, "num_heads", None) or getattr(
163
+ self._original_mod.config, "num_attention_heads"
164
+ )
165
+ self.head_dim = self._original_mod.head_dim
166
+ self.scaling = self.head_dim**-0.5
167
+
168
+ if hasattr(self._original_mod, "num_key_value_heads"):
169
+ self.num_key_value_heads = self._original_mod.num_key_value_heads
170
+ elif hasattr(self._original_mod, "config") and hasattr(self._original_mod.config, "num_key_value_heads"):
171
+ self.num_key_value_heads = self._original_mod.config.num_key_value_heads
172
+ else:
173
+ self.num_key_value_heads = self.num_heads
174
+
175
+ self.__post_init__()
176
+
177
+ def __post_init__(self):
178
+ self.q_proj = self._original_mod.q_proj
179
+ self.k_proj = self._original_mod.k_proj
180
+ self.v_proj = self._original_mod.v_proj
181
+ self.o_proj = self._original_mod.o_proj
182
+
183
+ def projection(self, hidden_states) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
184
+ query_states = self.q_proj(hidden_states)
185
+ key_states = self.k_proj(hidden_states)
186
+ value_states = self.v_proj(hidden_states)
187
+
188
+ return query_states, key_states, value_states
189
+
190
+ def forward(
191
+ self,
192
+ hidden_states: torch.Tensor,
193
+ attention_mask: torch.Tensor,
194
+ cos: Optional[torch.Tensor] = None,
195
+ sin: Optional[torch.Tensor] = None,
196
+ ):
197
+ batch_size, query_length, _ = hidden_states.size()
198
+
199
+ query_states, key_states, value_states = self.projection(hidden_states=hidden_states)
200
+
201
+ query_states = query_states.view(batch_size, query_length, 1, self.num_heads, self.head_dim).transpose(1, 3)
202
+ key_states = key_states.view(batch_size, query_length, 1, self.num_key_value_heads, self.head_dim).transpose(
203
+ 1, 3
204
+ )
205
+ value_states = value_states.view(
206
+ batch_size, query_length, 1, self.num_key_value_heads, self.head_dim
207
+ ).transpose(1, 3)
208
+
209
+ if cos is not None and sin is not None:
210
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
211
+
212
+ attn_weights = torch.matmul(query_states, key_states.transpose(3, 4)) * self.scaling
213
+ attn_weights = attn_weights + attention_mask
214
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32)
215
+ attn_output = torch.matmul(attn_weights, value_states)
216
+ attn_output = attn_output.transpose(1, 3)
217
+
218
+ attn_output = attn_output.reshape(batch_size, query_length, -1)
219
+ attn_output = self.o_proj(attn_output)
220
+
221
+ return attn_output
@@ -0,0 +1,68 @@
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 List, Optional, Union
15
+
16
+ from ....configuration_utils import RBLNModelConfig
17
+
18
+
19
+ class RBLNColPaliForRetrievalConfig(RBLNModelConfig):
20
+ """
21
+ Configuration class for RBLN ColPali models for document retrieval.
22
+
23
+ This class extends RBLNModelConfig with specific configurations for ColPali models,
24
+ including vision tower settings and multi-sequence length support.
25
+
26
+ Example usage:
27
+ ```python
28
+ from optimum.rbln import RBLNColPaliForRetrieval, RBLNColPaliForRetrievalConfig
29
+
30
+ # Create a configuration object
31
+ config = RBLNColPaliForRetrievalConfig(
32
+ max_seq_lens=1152,
33
+ output_hidden_states=False,
34
+ tensor_parallel_size=4
35
+ )
36
+
37
+ # Use the configuration with from_pretrained
38
+ model = RBLNColPaliForRetrieval.from_pretrained(
39
+ "vidore/colpali-v1.3-hf",
40
+ export=True,
41
+ rbln_config=config
42
+ )
43
+ ```
44
+ """
45
+
46
+ submodules = ["vision_tower"]
47
+
48
+ def __init__(
49
+ self,
50
+ max_seq_lens: Union[int, List[int]] = None,
51
+ output_hidden_states: Optional[bool] = None,
52
+ vision_tower: Optional[RBLNModelConfig] = None,
53
+ **kwargs,
54
+ ):
55
+ """
56
+ Args:
57
+ vision_tower (Optional[RBLNModelConfig]): Configuration for the vision encoder component.
58
+ max_seq_lens (Union[int, List[int]]): The maximum sequence lengths for the language model.
59
+ This can be multiple values, and the model will be compiled for each max_seq_len, allowing selection of the most appropriate max_seq_len at inference time.
60
+ output_hidden_states (Optional[bool]): Whether to output the hidden states of the language model.
61
+ **kwargs: Additional arguments passed to the parent RBLNModelConfig.
62
+ Raises:
63
+ ValueError: If batch_size is not a positive integer.
64
+ """
65
+ super().__init__(**kwargs)
66
+ self.vision_tower = vision_tower
67
+ self.max_seq_lens = max_seq_lens
68
+ self.output_hidden_states = output_hidden_states