optimum-rbln 0.8.2a4__py3-none-any.whl → 0.8.2a6__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of optimum-rbln might be problematic. Click here for more details.
- optimum/rbln/__init__.py +44 -0
- optimum/rbln/__version__.py +2 -2
- optimum/rbln/configuration_utils.py +4 -0
- optimum/rbln/ops/kv_cache_update.py +5 -0
- optimum/rbln/ops/linear.py +7 -0
- optimum/rbln/transformers/__init__.py +48 -0
- optimum/rbln/transformers/modeling_attention_utils.py +252 -0
- optimum/rbln/transformers/models/__init__.py +35 -14
- optimum/rbln/transformers/models/decoderonly/__init__.py +2 -2
- optimum/rbln/transformers/models/decoderonly/configuration_decoderonly.py +214 -45
- optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py +122 -205
- optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py +569 -366
- optimum/rbln/transformers/models/gemma/__init__.py +2 -2
- optimum/rbln/transformers/models/gemma/configuration_gemma.py +9 -1
- optimum/rbln/transformers/models/gemma/modeling_gemma.py +13 -1
- optimum/rbln/transformers/models/gemma3/configuration_gemma3.py +7 -5
- optimum/rbln/transformers/models/gemma3/modeling_gemma3.py +82 -59
- optimum/rbln/transformers/models/gpt2/__init__.py +2 -2
- optimum/rbln/transformers/models/gpt2/configuration_gpt2.py +31 -3
- optimum/rbln/transformers/models/gpt2/gpt2_architecture.py +6 -7
- optimum/rbln/transformers/models/gpt2/modeling_gpt2.py +16 -1
- optimum/rbln/transformers/models/idefics3/modeling_idefics3.py +2 -2
- optimum/rbln/transformers/models/llama/__init__.py +2 -2
- optimum/rbln/transformers/models/llama/configuration_llama.py +9 -1
- optimum/rbln/transformers/models/llama/modeling_llama.py +13 -1
- optimum/rbln/transformers/models/llava/__init__.py +16 -0
- optimum/rbln/transformers/models/llava/configuration_llava.py +54 -0
- optimum/rbln/transformers/models/llava/modeling_llava.py +379 -0
- optimum/rbln/transformers/models/llava_next/modeling_llava_next.py +4 -4
- optimum/rbln/transformers/models/mistral/__init__.py +2 -2
- optimum/rbln/transformers/models/mistral/configuration_mistral.py +9 -1
- optimum/rbln/transformers/models/mistral/mistral_architecture.py +1 -1
- optimum/rbln/transformers/models/mistral/modeling_mistral.py +26 -3
- optimum/rbln/transformers/models/opt/__init__.py +2 -2
- optimum/rbln/transformers/models/opt/configuration_opt.py +8 -1
- optimum/rbln/transformers/models/opt/modeling_opt.py +41 -1
- optimum/rbln/transformers/models/opt/opt_architecture.py +4 -4
- optimum/rbln/transformers/models/pegasus/__init__.py +17 -0
- optimum/rbln/transformers/models/pegasus/configuration_pegasus.py +34 -0
- optimum/rbln/transformers/models/pegasus/modeling_pegasus.py +69 -0
- optimum/rbln/transformers/models/pegasus/pegasus_architecture.py +163 -0
- optimum/rbln/transformers/models/phi/__init__.py +2 -2
- optimum/rbln/transformers/models/phi/configuration_phi.py +9 -1
- optimum/rbln/transformers/models/phi/modeling_phi.py +10 -1
- optimum/rbln/transformers/models/phi/phi_architecture.py +6 -6
- optimum/rbln/transformers/models/pixtral/__init__.py +16 -0
- optimum/rbln/transformers/models/pixtral/configuration_pixtral.py +43 -0
- optimum/rbln/transformers/models/pixtral/modeling_pixtral.py +318 -0
- optimum/rbln/transformers/models/pixtral/pixtral_architecture.py +73 -0
- optimum/rbln/transformers/models/qwen2/__init__.py +2 -2
- optimum/rbln/transformers/models/qwen2/configuration_qwen2.py +9 -1
- optimum/rbln/transformers/models/qwen2/modeling_qwen2.py +27 -1
- optimum/rbln/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py +3 -3
- optimum/rbln/transformers/models/qwen3/configuration_qwen3.py +2 -2
- optimum/rbln/transformers/models/qwen3/modeling_qwen3.py +10 -328
- optimum/rbln/transformers/models/qwen3/qwen3_architecture.py +0 -241
- optimum/rbln/transformers/models/seq2seq/configuration_seq2seq.py +0 -10
- optimum/rbln/transformers/models/whisper/configuration_whisper.py +1 -10
- optimum/rbln/transformers/models/whisper/modeling_whisper.py +5 -1
- optimum/rbln/utils/depreacate_utils.py +16 -0
- {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.8.2a6.dist-info}/METADATA +1 -1
- {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.8.2a6.dist-info}/RECORD +64 -51
- {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.8.2a6.dist-info}/WHEEL +0 -0
- {optimum_rbln-0.8.2a4.dist-info → optimum_rbln-0.8.2a6.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,318 @@
|
|
|
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 pathlib import Path
|
|
16
|
+
from typing import TYPE_CHECKING, Any, Optional, Tuple, Union
|
|
17
|
+
|
|
18
|
+
import rebel
|
|
19
|
+
import torch
|
|
20
|
+
import torch.nn as nn
|
|
21
|
+
from transformers import PixtralVisionConfig, PixtralVisionModel
|
|
22
|
+
from transformers.modeling_outputs import BaseModelOutput
|
|
23
|
+
from transformers.modeling_utils import no_init_weights
|
|
24
|
+
from transformers.models.pixtral.modeling_pixtral import (
|
|
25
|
+
PixtralRMSNorm,
|
|
26
|
+
PixtralRotaryEmbedding,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
from ....configuration_utils import RBLNCompileConfig, RBLNModelConfig
|
|
30
|
+
from ....modeling import RBLNModel
|
|
31
|
+
from ....utils.logging import get_logger
|
|
32
|
+
from ....utils.runtime_utils import RBLNPytorchRuntime
|
|
33
|
+
from .configuration_pixtral import RBLNPixtralVisionModelConfig
|
|
34
|
+
from .pixtral_architecture import PixtralAttention
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
logger = get_logger(__name__)
|
|
38
|
+
|
|
39
|
+
if TYPE_CHECKING:
|
|
40
|
+
from transformers import AutoFeatureExtractor, AutoProcessor, AutoTokenizer, PreTrainedModel
|
|
41
|
+
|
|
42
|
+
from ....diffusers.modeling_diffusers import RBLNDiffusionMixin, RBLNDiffusionMixinConfig
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class RBLNRuntimePixtralVisionModel(RBLNPytorchRuntime):
|
|
46
|
+
mandatory_members = ["main_input_name"]
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
runtime: rebel.Runtime,
|
|
51
|
+
config: PixtralVisionConfig,
|
|
52
|
+
rbln_config: RBLNPixtralVisionModelConfig,
|
|
53
|
+
**kwargs: Any,
|
|
54
|
+
) -> None:
|
|
55
|
+
super().__init__(runtime, **kwargs)
|
|
56
|
+
self.patch_positional_embedding = PixtralRotaryEmbedding(config)
|
|
57
|
+
self.patch_size = config.patch_size
|
|
58
|
+
self.image_size = config.image_size
|
|
59
|
+
self.hidden_size = config.hidden_size
|
|
60
|
+
self.max_image_size = rbln_config.max_image_size
|
|
61
|
+
|
|
62
|
+
def forward(
|
|
63
|
+
self,
|
|
64
|
+
pixel_values: torch.Tensor,
|
|
65
|
+
image_sizes: torch.Tensor,
|
|
66
|
+
output_hidden_states: Optional[bool] = None,
|
|
67
|
+
return_dict: Optional[bool] = None,
|
|
68
|
+
**kwargs,
|
|
69
|
+
):
|
|
70
|
+
if pixel_values.shape[2] > self.max_image_size[0] or pixel_values.shape[3] > self.max_image_size[1]:
|
|
71
|
+
raise ValueError("The height() and width of pixel_values can't be larger than max_image_size.")
|
|
72
|
+
|
|
73
|
+
if pixel_values.shape[2] != self.max_image_size[0] or pixel_values.shape[3] != self.max_image_size[1]:
|
|
74
|
+
padded_pixel_values = [
|
|
75
|
+
torch.nn.functional.pad(
|
|
76
|
+
image,
|
|
77
|
+
pad=(
|
|
78
|
+
0,
|
|
79
|
+
self.max_image_size[1] - pixel_values.shape[3],
|
|
80
|
+
0,
|
|
81
|
+
self.max_image_size[0] - pixel_values.shape[2],
|
|
82
|
+
),
|
|
83
|
+
)
|
|
84
|
+
for image in pixel_values
|
|
85
|
+
]
|
|
86
|
+
pixel_values = torch.stack(padded_pixel_values)
|
|
87
|
+
|
|
88
|
+
batch_size, _, H_max, W_max = pixel_values.shape
|
|
89
|
+
H_max_p = H_max // self.patch_size
|
|
90
|
+
W_max_p = W_max // self.patch_size
|
|
91
|
+
|
|
92
|
+
final_hidden_states = None
|
|
93
|
+
|
|
94
|
+
last_hidden_state_list = []
|
|
95
|
+
if output_hidden_states:
|
|
96
|
+
batch_hidden_states_list = []
|
|
97
|
+
|
|
98
|
+
for i in range(batch_size):
|
|
99
|
+
h_patched_original = image_sizes[i, 0] // self.patch_size
|
|
100
|
+
w_patched_original = image_sizes[i, 1] // self.patch_size
|
|
101
|
+
|
|
102
|
+
single_pixel_values = pixel_values[i : i + 1]
|
|
103
|
+
patch_embed = self.patch_conv(single_pixel_values)
|
|
104
|
+
patch_embed_seq = patch_embed[:, :, :h_patched_original, :w_patched_original].flatten(2).transpose(1, 2)
|
|
105
|
+
patch_embed_seq = self.ln_pre(patch_embed_seq)
|
|
106
|
+
patch_embed_seq = nn.functional.pad(
|
|
107
|
+
patch_embed_seq, (0, 0, 0, H_max_p * W_max_p - patch_embed_seq.shape[1]), "constant", value=0
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
max_w_from_config = self.image_size // self.patch_size
|
|
111
|
+
mesh = torch.meshgrid(torch.arange(h_patched_original), torch.arange(w_patched_original), indexing="ij")
|
|
112
|
+
h_grid, v_grid = torch.stack(mesh, dim=-1).reshape(-1, 2).chunk(2, -1)
|
|
113
|
+
ids = h_grid * max_w_from_config + v_grid
|
|
114
|
+
position_ids = ids[:, 0]
|
|
115
|
+
|
|
116
|
+
position_embeddings = self.patch_positional_embedding(patch_embed_seq, position_ids)
|
|
117
|
+
cos = nn.functional.pad(
|
|
118
|
+
position_embeddings[0],
|
|
119
|
+
(0, 0, 0, H_max_p * W_max_p - position_embeddings[0].shape[0]),
|
|
120
|
+
"constant",
|
|
121
|
+
value=0,
|
|
122
|
+
)
|
|
123
|
+
sin = nn.functional.pad(
|
|
124
|
+
position_embeddings[1],
|
|
125
|
+
(0, 0, 0, H_max_p * W_max_p - position_embeddings[1].shape[0]),
|
|
126
|
+
"constant",
|
|
127
|
+
value=0,
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
attention_mask = torch.full(
|
|
131
|
+
(1, patch_embed_seq.shape[-2]), fill_value=torch.finfo(patch_embed_seq.dtype).min
|
|
132
|
+
)
|
|
133
|
+
attention_mask[:, : h_patched_original * w_patched_original] = 0
|
|
134
|
+
|
|
135
|
+
transformer_output = super().forward(patch_embed_seq, attention_mask, cos, sin)
|
|
136
|
+
|
|
137
|
+
last_hidden_state_list.append(transformer_output[0][:, : h_patched_original * w_patched_original, :])
|
|
138
|
+
hidden_states = transformer_output[1:]
|
|
139
|
+
|
|
140
|
+
if output_hidden_states:
|
|
141
|
+
batch_hidden_states_list.append(
|
|
142
|
+
[hidden_state[:, : h_patched_original * w_patched_original, :] for hidden_state in hidden_states]
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
final_last_hidden_state = torch.cat(last_hidden_state_list, dim=1)
|
|
146
|
+
|
|
147
|
+
if output_hidden_states:
|
|
148
|
+
hidden_states = [
|
|
149
|
+
torch.cat(
|
|
150
|
+
[batch_hidden_states[layer_idx] for batch_hidden_states in batch_hidden_states_list],
|
|
151
|
+
dim=1,
|
|
152
|
+
)
|
|
153
|
+
for layer_idx in range(len(batch_hidden_states_list[0]))
|
|
154
|
+
]
|
|
155
|
+
|
|
156
|
+
final_hidden_states = tuple(hidden_states)
|
|
157
|
+
|
|
158
|
+
if not return_dict:
|
|
159
|
+
return tuple(v for v in (final_last_hidden_state, final_hidden_states) if v is not None)
|
|
160
|
+
|
|
161
|
+
# TODO: output_attentions
|
|
162
|
+
return BaseModelOutput(
|
|
163
|
+
last_hidden_state=final_last_hidden_state,
|
|
164
|
+
hidden_states=final_hidden_states,
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class _PixtralVisionModel(torch.nn.Module):
|
|
169
|
+
def __init__(self, model: PixtralVisionModel, output_hidden_states: bool):
|
|
170
|
+
super().__init__()
|
|
171
|
+
self.transformer = self.convert_to_rbln_pixtral_vision_model(model)
|
|
172
|
+
self.output_hidden_states = output_hidden_states
|
|
173
|
+
|
|
174
|
+
def convert_to_rbln_pixtral_vision_model(self, model: nn.Module):
|
|
175
|
+
for layer in model.transformer.layers:
|
|
176
|
+
layer.attention = PixtralAttention(layer.attention)
|
|
177
|
+
return model.transformer
|
|
178
|
+
|
|
179
|
+
def forward(self, patch_embeds, attention_mask, position_embeddings_1, position_embeddings_2):
|
|
180
|
+
output = self.transformer(
|
|
181
|
+
inputs_embeds=patch_embeds,
|
|
182
|
+
attention_mask=attention_mask,
|
|
183
|
+
position_embeddings=(position_embeddings_1, position_embeddings_2),
|
|
184
|
+
output_hidden_states=self.output_hidden_states,
|
|
185
|
+
return_dict=False,
|
|
186
|
+
)
|
|
187
|
+
return output
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class RBLNPixtralVisionModel(RBLNModel):
|
|
191
|
+
"""
|
|
192
|
+
RBLN optimized Pixtral vision encoder model.
|
|
193
|
+
|
|
194
|
+
This class provides hardware-accelerated inference for Pixtral vision encoders
|
|
195
|
+
on RBLN devices, supporting image encoding for multimodal tasks.
|
|
196
|
+
"""
|
|
197
|
+
|
|
198
|
+
def __post_init__(self, **kwargs):
|
|
199
|
+
artifacts = torch.load(self.model_save_dir / self.subfolder / "torch_artifacts.pth", weights_only=False)
|
|
200
|
+
with no_init_weights():
|
|
201
|
+
self.patch_conv = nn.Conv2d(
|
|
202
|
+
in_channels=self.config.num_channels,
|
|
203
|
+
out_channels=self.config.hidden_size,
|
|
204
|
+
kernel_size=self.config.patch_size,
|
|
205
|
+
stride=self.config.patch_size,
|
|
206
|
+
bias=False,
|
|
207
|
+
)
|
|
208
|
+
self.ln_pre = PixtralRMSNorm(self.config.hidden_size, eps=1e-5)
|
|
209
|
+
self.patch_conv.load_state_dict(artifacts["patch_conv"])
|
|
210
|
+
self.ln_pre.load_state_dict(artifacts["ln_pre"])
|
|
211
|
+
self.model = RBLNRuntimePixtralVisionModel(
|
|
212
|
+
self.model[0],
|
|
213
|
+
main_input_name="pixel_values",
|
|
214
|
+
config=self.config,
|
|
215
|
+
rbln_config=self.rbln_config,
|
|
216
|
+
patch_conv=self.patch_conv,
|
|
217
|
+
ln_pre=self.ln_pre,
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
@classmethod
|
|
221
|
+
def save_torch_artifacts(
|
|
222
|
+
cls,
|
|
223
|
+
model: "PreTrainedModel",
|
|
224
|
+
save_dir_path: Path,
|
|
225
|
+
subfolder: str,
|
|
226
|
+
rbln_config: RBLNModelConfig,
|
|
227
|
+
):
|
|
228
|
+
save_dict = {}
|
|
229
|
+
save_dict["patch_conv"] = model.get_input_embeddings().state_dict()
|
|
230
|
+
save_dict["ln_pre"] = model.ln_pre.state_dict()
|
|
231
|
+
torch.save(save_dict, save_dir_path / subfolder / "torch_artifacts.pth")
|
|
232
|
+
|
|
233
|
+
@classmethod
|
|
234
|
+
def wrap_model_if_needed(
|
|
235
|
+
cls, model: torch.nn.Module, rbln_config: RBLNPixtralVisionModelConfig
|
|
236
|
+
) -> torch.nn.Module:
|
|
237
|
+
wrapper_cfg = {
|
|
238
|
+
"output_hidden_states": rbln_config.output_hidden_states,
|
|
239
|
+
}
|
|
240
|
+
return _PixtralVisionModel(model, **wrapper_cfg).eval()
|
|
241
|
+
|
|
242
|
+
@classmethod
|
|
243
|
+
def update_rbln_config_using_pipe(
|
|
244
|
+
cls, pipe: "RBLNDiffusionMixin", rbln_config: "RBLNDiffusionMixinConfig", submodule_name: str
|
|
245
|
+
) -> "RBLNDiffusionMixinConfig":
|
|
246
|
+
return rbln_config
|
|
247
|
+
|
|
248
|
+
@classmethod
|
|
249
|
+
def _update_rbln_config(
|
|
250
|
+
cls,
|
|
251
|
+
preprocessors: Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"],
|
|
252
|
+
model: Optional["PreTrainedModel"] = None,
|
|
253
|
+
model_config: "PixtralVisionConfig" = None,
|
|
254
|
+
rbln_config: Optional[RBLNPixtralVisionModelConfig] = None,
|
|
255
|
+
) -> RBLNPixtralVisionModelConfig:
|
|
256
|
+
if rbln_config.max_image_size is None:
|
|
257
|
+
rbln_config.max_image_size = (model_config.image_size, model_config.image_size)
|
|
258
|
+
|
|
259
|
+
if rbln_config.output_hidden_states is None:
|
|
260
|
+
rbln_config.output_hidden_states = getattr(model_config, "output_hidden_states", False)
|
|
261
|
+
|
|
262
|
+
num_total_patches = (rbln_config.max_image_size[0] // model_config.patch_size) * (
|
|
263
|
+
rbln_config.max_image_size[1] // model_config.patch_size
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
rbln_compile_config = RBLNCompileConfig(
|
|
267
|
+
input_info=[
|
|
268
|
+
(
|
|
269
|
+
"patch_embeds",
|
|
270
|
+
[1, num_total_patches, model_config.hidden_size],
|
|
271
|
+
"float32",
|
|
272
|
+
),
|
|
273
|
+
("attention_mask", [1, num_total_patches], "float32"),
|
|
274
|
+
(
|
|
275
|
+
"position_embeddings_1",
|
|
276
|
+
[
|
|
277
|
+
num_total_patches,
|
|
278
|
+
model_config.head_dim,
|
|
279
|
+
],
|
|
280
|
+
"float32",
|
|
281
|
+
),
|
|
282
|
+
(
|
|
283
|
+
"position_embeddings_2",
|
|
284
|
+
[
|
|
285
|
+
num_total_patches,
|
|
286
|
+
model_config.head_dim,
|
|
287
|
+
],
|
|
288
|
+
"float32",
|
|
289
|
+
),
|
|
290
|
+
]
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
rbln_config.set_compile_cfgs([rbln_compile_config])
|
|
294
|
+
return rbln_config
|
|
295
|
+
|
|
296
|
+
def forward(
|
|
297
|
+
self,
|
|
298
|
+
pixel_values: Optional[torch.FloatTensor] = None,
|
|
299
|
+
image_sizes: Optional[torch.FloatTensor] = None,
|
|
300
|
+
output_hidden_states: Optional[bool] = None,
|
|
301
|
+
return_dict: bool = True,
|
|
302
|
+
**kwargs,
|
|
303
|
+
) -> Union[Tuple, BaseModelOutput]:
|
|
304
|
+
output_hidden_states = (
|
|
305
|
+
output_hidden_states if output_hidden_states is not None else self.rbln_config.output_hidden_states
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
if output_hidden_states != self.rbln_config.output_hidden_states:
|
|
309
|
+
raise ValueError(
|
|
310
|
+
f"Variable output_hidden_states {output_hidden_states} is not equal to rbln_config.output_hidden_states {self.rbln_config.output_hidden_states} "
|
|
311
|
+
f"Please compile again with the correct argument."
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
output = self.model(
|
|
315
|
+
pixel_values, image_sizes, output_hidden_states=output_hidden_states, return_dict=return_dict
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
return output
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# Copyright 2025 Rebellions Inc. All rights reserved.
|
|
2
|
+
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at:
|
|
6
|
+
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
from typing import Optional, Tuple
|
|
16
|
+
|
|
17
|
+
import torch
|
|
18
|
+
import torch.nn as nn
|
|
19
|
+
|
|
20
|
+
from ..decoderonly.decoderonly_architecture import apply_rotary_pos_emb
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class PixtralAttention(nn.Module):
|
|
24
|
+
def __init__(self, self_attention):
|
|
25
|
+
super().__init__()
|
|
26
|
+
self.original_model = self_attention
|
|
27
|
+
self.num_heads = getattr(self.original_model, "num_heads", None) or getattr(
|
|
28
|
+
self.original_model.config, "num_attention_heads"
|
|
29
|
+
)
|
|
30
|
+
self.head_dim = self.original_model.head_dim
|
|
31
|
+
self.scaling = self.head_dim**-0.5
|
|
32
|
+
|
|
33
|
+
self.__post_init__()
|
|
34
|
+
|
|
35
|
+
def __post_init__(self):
|
|
36
|
+
self.q_proj = self.original_model.q_proj
|
|
37
|
+
self.k_proj = self.original_model.k_proj
|
|
38
|
+
self.v_proj = self.original_model.v_proj
|
|
39
|
+
self.o_proj = self.original_model.o_proj
|
|
40
|
+
|
|
41
|
+
def forward(
|
|
42
|
+
self,
|
|
43
|
+
hidden_states: torch.Tensor,
|
|
44
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
45
|
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
|
46
|
+
output_attentions: Optional[bool] = False,
|
|
47
|
+
):
|
|
48
|
+
batch_size, patches, _ = hidden_states.size()
|
|
49
|
+
|
|
50
|
+
query_states = self.q_proj(hidden_states)
|
|
51
|
+
key_states = self.k_proj(hidden_states)
|
|
52
|
+
value_states = self.v_proj(hidden_states)
|
|
53
|
+
|
|
54
|
+
# TODO: return output attention
|
|
55
|
+
query_states = query_states.view(batch_size, patches, 1, self.num_heads, self.head_dim).transpose(1, 3)
|
|
56
|
+
key_states = key_states.view(batch_size, patches, 1, self.num_heads, self.head_dim).transpose(1, 3)
|
|
57
|
+
value_states = value_states.view(batch_size, patches, 1, self.num_heads, self.head_dim).transpose(1, 3)
|
|
58
|
+
|
|
59
|
+
cos, sin = position_embeddings
|
|
60
|
+
cos = cos[None, None, None, :, :]
|
|
61
|
+
sin = sin[None, None, None, :, :]
|
|
62
|
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
|
63
|
+
|
|
64
|
+
attn_weights = torch.matmul(query_states, key_states.transpose(3, 4)) * self.scaling
|
|
65
|
+
attn_weights = attn_weights + attention_mask
|
|
66
|
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32)
|
|
67
|
+
attn_output = torch.matmul(attn_weights, value_states)
|
|
68
|
+
attn_output = attn_output.transpose(1, 3)
|
|
69
|
+
|
|
70
|
+
attn_output = attn_output.reshape(batch_size, patches, -1)
|
|
71
|
+
attn_output = self.o_proj(attn_output)
|
|
72
|
+
|
|
73
|
+
return attn_output, _
|
|
@@ -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_qwen2 import RBLNQwen2ForCausalLMConfig
|
|
16
|
-
from .modeling_qwen2 import RBLNQwen2ForCausalLM
|
|
15
|
+
from .configuration_qwen2 import RBLNQwen2ForCausalLMConfig, RBLNQwen2ModelConfig
|
|
16
|
+
from .modeling_qwen2 import RBLNQwen2ForCausalLM, RBLNQwen2Model
|
|
@@ -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 RBLNQwen2ForCausalLMConfig(RBLNDecoderOnlyModelForCausalLMConfig):
|
|
@@ -40,3 +40,11 @@ class RBLNQwen2ForCausalLMConfig(RBLNDecoderOnlyModelForCausalLMConfig):
|
|
|
40
40
|
)
|
|
41
41
|
```
|
|
42
42
|
"""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class RBLNQwen2ModelConfig(RBLNDecoderOnlyModelConfig):
|
|
46
|
+
"""
|
|
47
|
+
Configuration class for RBLN Qwen2 models.
|
|
48
|
+
|
|
49
|
+
This class is an alias of RBLNDecoderOnlyModelConfig.
|
|
50
|
+
"""
|
|
@@ -15,7 +15,11 @@
|
|
|
15
15
|
from transformers import PretrainedConfig
|
|
16
16
|
|
|
17
17
|
from ....utils import logging
|
|
18
|
-
from ...models.decoderonly import
|
|
18
|
+
from ...models.decoderonly import (
|
|
19
|
+
RBLNDecoderOnlyModel,
|
|
20
|
+
RBLNDecoderOnlyModelForCausalLM,
|
|
21
|
+
RBLNDecoderOnlyModelForCausalLMConfig,
|
|
22
|
+
)
|
|
19
23
|
from .qwen2_architecture import QWEN2Wrapper
|
|
20
24
|
|
|
21
25
|
|
|
@@ -95,3 +99,25 @@ class RBLNQwen2ForCausalLM(RBLNDecoderOnlyModelForCausalLM):
|
|
|
95
99
|
rbln_config.sliding_window = model_config.sliding_window
|
|
96
100
|
rbln_config.sliding_window_layers = list(range(model_config.num_hidden_layers))
|
|
97
101
|
return rbln_config
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class RBLNQwen2Model(RBLNDecoderOnlyModel):
|
|
105
|
+
"""
|
|
106
|
+
The Qwen2 Model transformer without a language modeling head.
|
|
107
|
+
This model inherits from [`RBLNDecoderOnlyModel`]. Check the superclass documentation for the generic methods the library implements for all its models.
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
_decoder_wrapper_cls = QWEN2Wrapper
|
|
111
|
+
|
|
112
|
+
@classmethod
|
|
113
|
+
def _update_sliding_window_config(
|
|
114
|
+
cls, model_config: PretrainedConfig, rbln_config: RBLNDecoderOnlyModelForCausalLMConfig
|
|
115
|
+
):
|
|
116
|
+
# https://github.com/huggingface/transformers/issues/35896
|
|
117
|
+
# There seems to be a bug in transformers(v4.52.4). Therefore, similar to when attn_implementation is eager,
|
|
118
|
+
# we set all layers to use sliding window in this version. This should be updated once the bug is fixed.
|
|
119
|
+
|
|
120
|
+
rbln_config.cache_impl = "sliding_window"
|
|
121
|
+
rbln_config.sliding_window = model_config.sliding_window
|
|
122
|
+
rbln_config.sliding_window_layers = list(range(model_config.num_hidden_layers))
|
|
123
|
+
return rbln_config
|
|
@@ -34,7 +34,7 @@ from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import (
|
|
|
34
34
|
from ....configuration_utils import RBLNCompileConfig
|
|
35
35
|
from ....modeling import RBLNModel
|
|
36
36
|
from ....utils.logging import get_logger
|
|
37
|
-
from ..decoderonly.modeling_decoderonly import
|
|
37
|
+
from ..decoderonly.modeling_decoderonly import RBLNDecoderOnlyForCausalLMOutput, RBLNDecoderOnlyModelForCausalLM
|
|
38
38
|
from .configuration_qwen2_5_vl import (
|
|
39
39
|
RBLNQwen2_5_VisionTransformerPretrainedModelConfig,
|
|
40
40
|
RBLNQwen2_5_VLForConditionalGenerationConfig,
|
|
@@ -595,7 +595,7 @@ class RBLNQwen2_5_VLForConditionalGeneration(RBLNDecoderOnlyModelForCausalLM):
|
|
|
595
595
|
generate_idx: Optional[torch.Tensor] = None,
|
|
596
596
|
return_dict: Optional[bool] = None,
|
|
597
597
|
**kwargs,
|
|
598
|
-
) ->
|
|
598
|
+
) -> RBLNDecoderOnlyForCausalLMOutput:
|
|
599
599
|
# Prefill
|
|
600
600
|
if cache_position is None:
|
|
601
601
|
inputs_embeds, position_embed, rope_deltas = self._preprocess_prefill(
|
|
@@ -637,7 +637,7 @@ class RBLNQwen2_5_VLForConditionalGeneration(RBLNDecoderOnlyModelForCausalLM):
|
|
|
637
637
|
if not return_dict:
|
|
638
638
|
return logits, generate_idx
|
|
639
639
|
else:
|
|
640
|
-
return
|
|
640
|
+
return RBLNDecoderOnlyForCausalLMOutput(
|
|
641
641
|
logits=logits,
|
|
642
642
|
generate_idx=generate_idx,
|
|
643
643
|
)
|
|
@@ -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 RBLNQwen3ForCausalLMConfig(RBLNDecoderOnlyModelForCausalLMConfig):
|
|
@@ -43,7 +43,7 @@ class RBLNQwen3ForCausalLMConfig(RBLNDecoderOnlyModelForCausalLMConfig):
|
|
|
43
43
|
"""
|
|
44
44
|
|
|
45
45
|
|
|
46
|
-
class RBLNQwen3ModelConfig(
|
|
46
|
+
class RBLNQwen3ModelConfig(RBLNDecoderOnlyModelConfig):
|
|
47
47
|
"""
|
|
48
48
|
Configuration class for RBLN Qwen3 models.
|
|
49
49
|
|