optimum-rbln 0.7.4a6__py3-none-any.whl → 0.7.4a8__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.
- optimum/rbln/__init__.py +8 -0
- optimum/rbln/__version__.py +2 -2
- optimum/rbln/configuration_utils.py +18 -1
- optimum/rbln/diffusers/modeling_diffusers.py +41 -15
- optimum/rbln/modeling_base.py +4 -3
- optimum/rbln/transformers/__init__.py +8 -0
- optimum/rbln/transformers/models/__init__.py +12 -0
- optimum/rbln/transformers/models/auto/auto_factory.py +3 -3
- optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py +2 -0
- optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py +6 -0
- optimum/rbln/transformers/models/idefics3/__init__.py +16 -0
- optimum/rbln/transformers/models/idefics3/configuration_idefics3.py +51 -0
- optimum/rbln/transformers/models/idefics3/modeling_idefics3.py +459 -0
- optimum/rbln/transformers/models/llava_next/modeling_llava_next.py +6 -0
- optimum/rbln/utils/hub.py +2 -2
- optimum/rbln/utils/model_utils.py +4 -4
- optimum/rbln/utils/submodule.py +10 -1
- {optimum_rbln-0.7.4a6.dist-info → optimum_rbln-0.7.4a8.dist-info}/METADATA +2 -2
- {optimum_rbln-0.7.4a6.dist-info → optimum_rbln-0.7.4a8.dist-info}/RECORD +21 -18
- {optimum_rbln-0.7.4a6.dist-info → optimum_rbln-0.7.4a8.dist-info}/WHEEL +0 -0
- {optimum_rbln-0.7.4a6.dist-info → optimum_rbln-0.7.4a8.dist-info}/licenses/LICENSE +0 -0
optimum/rbln/__init__.py
CHANGED
@@ -74,6 +74,10 @@ _import_structure = {
|
|
74
74
|
"RBLNGemmaForCausalLMConfig",
|
75
75
|
"RBLNGPT2LMHeadModel",
|
76
76
|
"RBLNGPT2LMHeadModelConfig",
|
77
|
+
"RBLNIdefics3VisionTransformer",
|
78
|
+
"RBLNIdefics3ForConditionalGeneration",
|
79
|
+
"RBLNIdefics3ForConditionalGenerationConfig",
|
80
|
+
"RBLNIdefics3VisionTransformerConfig",
|
77
81
|
"RBLNLlamaForCausalLM",
|
78
82
|
"RBLNLlamaForCausalLMConfig",
|
79
83
|
"RBLNLlavaNextForConditionalGeneration",
|
@@ -281,6 +285,10 @@ if TYPE_CHECKING:
|
|
281
285
|
RBLNGemmaForCausalLMConfig,
|
282
286
|
RBLNGPT2LMHeadModel,
|
283
287
|
RBLNGPT2LMHeadModelConfig,
|
288
|
+
RBLNIdefics3ForConditionalGeneration,
|
289
|
+
RBLNIdefics3ForConditionalGenerationConfig,
|
290
|
+
RBLNIdefics3VisionTransformer,
|
291
|
+
RBLNIdefics3VisionTransformerConfig,
|
284
292
|
RBLNLlamaForCausalLM,
|
285
293
|
RBLNLlamaForCausalLMConfig,
|
286
294
|
RBLNLlavaNextForConditionalGeneration,
|
optimum/rbln/__version__.py
CHANGED
@@ -17,5 +17,5 @@ __version__: str
|
|
17
17
|
__version_tuple__: VERSION_TUPLE
|
18
18
|
version_tuple: VERSION_TUPLE
|
19
19
|
|
20
|
-
__version__ = version = '0.7.
|
21
|
-
__version_tuple__ = version_tuple = (0, 7, 4, '
|
20
|
+
__version__ = version = '0.7.4a8'
|
21
|
+
__version_tuple__ = version_tuple = (0, 7, 4, 'a8')
|
@@ -174,6 +174,14 @@ class RBLNAutoConfig:
|
|
174
174
|
cls = getattr(importlib.import_module("optimum.rbln"), cls_name)
|
175
175
|
return cls(**kwargs)
|
176
176
|
|
177
|
+
@staticmethod
|
178
|
+
def load_from_dict(config_dict: Dict[str, Any]) -> "RBLNModelConfig":
|
179
|
+
cls_name = config_dict.get("cls_name")
|
180
|
+
if cls_name is None:
|
181
|
+
raise ValueError("`cls_name` is required.")
|
182
|
+
cls = getattr(importlib.import_module("optimum.rbln"), cls_name)
|
183
|
+
return cls(**config_dict)
|
184
|
+
|
177
185
|
@staticmethod
|
178
186
|
def load(
|
179
187
|
path: str,
|
@@ -195,8 +203,9 @@ class RBLNAutoConfig:
|
|
195
203
|
cls, config_file = load_config(path)
|
196
204
|
|
197
205
|
rbln_keys = [key for key in kwargs.keys() if key.startswith("rbln_")]
|
198
|
-
|
199
206
|
rbln_runtime_kwargs = {key[5:]: kwargs.pop(key) for key in rbln_keys if key[5:] in RUNTIME_KEYWORDS}
|
207
|
+
rbln_submodule_kwargs = {key[5:]: kwargs.pop(key) for key in rbln_keys if key[5:] in cls.submodules}
|
208
|
+
|
200
209
|
rbln_kwargs = {
|
201
210
|
key[5:]: kwargs.pop(key)
|
202
211
|
for key in rbln_keys
|
@@ -206,6 +215,14 @@ class RBLNAutoConfig:
|
|
206
215
|
if len(rbln_kwargs) > 0:
|
207
216
|
raise ValueError(f"Cannot set the following arguments: {list(rbln_kwargs.keys())}")
|
208
217
|
|
218
|
+
# Process submodule's rbln_config
|
219
|
+
for submodule in cls.submodules:
|
220
|
+
if submodule not in config_file:
|
221
|
+
raise ValueError(f"Submodule {submodule} not found in rbln_config.json.")
|
222
|
+
submodule_config = config_file[submodule]
|
223
|
+
submodule_config.update(rbln_submodule_kwargs.pop(submodule, {}))
|
224
|
+
config_file[submodule] = RBLNAutoConfig.load_from_dict(submodule_config)
|
225
|
+
|
209
226
|
if passed_rbln_config is not None:
|
210
227
|
config_file.update(passed_rbln_config._runtime_options)
|
211
228
|
# TODO(jongho): Reject if the passed_rbln_config has different attributes from the config_file
|
@@ -47,17 +47,11 @@ class RBLNDiffusionMixin:
|
|
47
47
|
|
48
48
|
1. Create a new pipeline class that inherits from both this mixin and the original StableDiffusionPipeline.
|
49
49
|
2. Define the required _submodules class variable listing the components to be compiled.
|
50
|
-
3. If needed, implement get_default_rbln_config for custom configuration of submodules.
|
51
50
|
|
52
51
|
Example:
|
53
52
|
```python
|
54
53
|
class RBLNStableDiffusionPipeline(RBLNDiffusionMixin, StableDiffusionPipeline):
|
55
54
|
_submodules = ["text_encoder", "unet", "vae"]
|
56
|
-
|
57
|
-
@classmethod
|
58
|
-
def get_default_rbln_config(cls, model, submodule_name, rbln_config):
|
59
|
-
# Configuration for other submodules...
|
60
|
-
pass
|
61
55
|
```
|
62
56
|
|
63
57
|
Class Variables:
|
@@ -77,14 +71,6 @@ class RBLNDiffusionMixin:
|
|
77
71
|
_prefix = {}
|
78
72
|
_rbln_config_class = None
|
79
73
|
|
80
|
-
@classmethod
|
81
|
-
def is_img2img_pipeline(cls):
|
82
|
-
return "Img2Img" in cls.__name__
|
83
|
-
|
84
|
-
@classmethod
|
85
|
-
def is_inpaint_pipeline(cls):
|
86
|
-
return "Inpaint" in cls.__name__
|
87
|
-
|
88
74
|
@staticmethod
|
89
75
|
def _maybe_apply_and_fuse_lora(
|
90
76
|
model: torch.nn.Module,
|
@@ -151,7 +137,47 @@ class RBLNDiffusionMixin:
|
|
151
137
|
lora_weights_names: Optional[Union[str, List[str]]] = None,
|
152
138
|
lora_scales: Optional[Union[float, List[float]]] = None,
|
153
139
|
**kwargs,
|
154
|
-
) ->
|
140
|
+
) -> "RBLNDiffusionMixin":
|
141
|
+
"""
|
142
|
+
Load a pretrained diffusion pipeline from a model checkpoint, with optional compilation for RBLN NPUs.
|
143
|
+
|
144
|
+
This method has two distinct operating modes:
|
145
|
+
- When `export=True`: Takes a PyTorch-based diffusion model, compiles it for RBLN NPUs, and loads the compiled model
|
146
|
+
- When `export=False`: Loads an already compiled RBLN model from `model_id` without recompilation
|
147
|
+
|
148
|
+
It supports various diffusion pipelines including Stable Diffusion, Kandinsky, ControlNet, and other diffusers-based models.
|
149
|
+
|
150
|
+
Args:
|
151
|
+
model_id (`str`):
|
152
|
+
The model ID or path to the pretrained model to load. Can be either:
|
153
|
+
- A model ID from the HuggingFace Hub
|
154
|
+
- A local path to a saved model directory
|
155
|
+
export (`bool`, *optional*, defaults to `False`):
|
156
|
+
If True, takes a PyTorch model from `model_id` and compiles it for RBLN NPU execution.
|
157
|
+
If False, loads an already compiled RBLN model from `model_id` without recompilation.
|
158
|
+
model_save_dir (`os.PathLike`, *optional*):
|
159
|
+
Directory to save the compiled model artifacts. Only used when `export=True`.
|
160
|
+
If not provided and `export=True`, a temporary directory is used.
|
161
|
+
rbln_config (`Dict[str, Any]`, *optional*, defaults to `{}`):
|
162
|
+
Configuration options for RBLN compilation. Can include settings for specific submodules
|
163
|
+
such as `text_encoder`, `unet`, and `vae`. Configuration can be tailored to the specific
|
164
|
+
pipeline being compiled.
|
165
|
+
lora_ids (`str` or `List[str]`, *optional*):
|
166
|
+
LoRA adapter ID(s) to load and apply before compilation. LoRA weights are fused
|
167
|
+
into the model weights during compilation. Only used when `export=True`.
|
168
|
+
lora_weights_names (`str` or `List[str]`, *optional*):
|
169
|
+
Names of specific LoRA weight files to load, corresponding to lora_ids. Only used when `export=True`.
|
170
|
+
lora_scales (`float` or `List[float]`, *optional*):
|
171
|
+
Scaling factor(s) to apply to the LoRA adapter(s). Only used when `export=True`.
|
172
|
+
**kwargs:
|
173
|
+
Additional arguments to pass to the underlying diffusion pipeline constructor or the
|
174
|
+
RBLN compilation process. These may include parameters specific to individual submodules
|
175
|
+
or the particular diffusion pipeline being used.
|
176
|
+
|
177
|
+
Returns:
|
178
|
+
`RBLNDiffusionMixin`: A compiled or loaded diffusion pipeline that can be used for inference on RBLN NPU.
|
179
|
+
The returned object is an instance of the class that called this method, inheriting from RBLNDiffusionMixin.
|
180
|
+
"""
|
155
181
|
rbln_config, kwargs = cls.get_rbln_config_class().initialize_from_kwargs(rbln_config, **kwargs)
|
156
182
|
|
157
183
|
if export:
|
optimum/rbln/modeling_base.py
CHANGED
@@ -216,6 +216,7 @@ class RBLNBaseModel(SubModulesMixin, PushToHubMixin, PreTrainedModel):
|
|
216
216
|
if isinstance(rbln_config, dict):
|
217
217
|
rbln_config_as_kwargs = {f"rbln_{key}": value for key, value in rbln_config.items()}
|
218
218
|
kwargs.update(rbln_config_as_kwargs)
|
219
|
+
rbln_config = None
|
219
220
|
elif isinstance(rbln_config, RBLNModelConfig) and rbln_config.rbln_model_cls_name != cls.__name__:
|
220
221
|
raise ValueError(
|
221
222
|
f"Cannot use the passed rbln_config. Its model class name ({rbln_config.rbln_model_cls_name}) "
|
@@ -392,13 +393,13 @@ class RBLNBaseModel(SubModulesMixin, PushToHubMixin, PreTrainedModel):
|
|
392
393
|
@classmethod
|
393
394
|
def get_hf_class(cls):
|
394
395
|
"""
|
395
|
-
Lazily loads and caches the corresponding
|
396
|
+
Lazily loads and caches the corresponding HuggingFace model class.
|
396
397
|
Removes 'RBLN' prefix from the class name to get the original class name
|
397
398
|
(e.g., RBLNLlamaForCausalLM -> LlamaForCausalLM) and imports it from
|
398
399
|
the transformers/diffusers module.
|
399
400
|
|
400
401
|
Returns:
|
401
|
-
type: The original
|
402
|
+
type: The original HuggingFace model class
|
402
403
|
"""
|
403
404
|
if cls._hf_class is None:
|
404
405
|
hf_cls_name = cls.__name__[4:]
|
@@ -478,7 +479,7 @@ class RBLNBaseModel(SubModulesMixin, PushToHubMixin, PreTrainedModel):
|
|
478
479
|
save_directory (`Union[str, Path]`):
|
479
480
|
Directory where to save the model file.
|
480
481
|
push_to_hub (`bool`, *optional*, defaults to `False`):
|
481
|
-
Whether or not to push your model to the
|
482
|
+
Whether or not to push your model to the HuggingFace model hub after saving it.
|
482
483
|
|
483
484
|
"""
|
484
485
|
if os.path.isfile(save_directory):
|
@@ -68,6 +68,10 @@ _import_structure = {
|
|
68
68
|
"RBLNGemmaForCausalLMConfig",
|
69
69
|
"RBLNGPT2LMHeadModel",
|
70
70
|
"RBLNGPT2LMHeadModelConfig",
|
71
|
+
"RBLNIdefics3VisionTransformer",
|
72
|
+
"RBLNIdefics3ForConditionalGeneration",
|
73
|
+
"RBLNIdefics3ForConditionalGenerationConfig",
|
74
|
+
"RBLNIdefics3VisionTransformerConfig",
|
71
75
|
"RBLNLlamaForCausalLM",
|
72
76
|
"RBLNLlamaForCausalLMConfig",
|
73
77
|
"RBLNLlavaNextForConditionalGeneration",
|
@@ -169,6 +173,10 @@ if TYPE_CHECKING:
|
|
169
173
|
RBLNGemmaForCausalLMConfig,
|
170
174
|
RBLNGPT2LMHeadModel,
|
171
175
|
RBLNGPT2LMHeadModelConfig,
|
176
|
+
RBLNIdefics3ForConditionalGeneration,
|
177
|
+
RBLNIdefics3ForConditionalGenerationConfig,
|
178
|
+
RBLNIdefics3VisionTransformer,
|
179
|
+
RBLNIdefics3VisionTransformerConfig,
|
172
180
|
RBLNLlamaForCausalLM,
|
173
181
|
RBLNLlamaForCausalLMConfig,
|
174
182
|
RBLNLlavaNextForConditionalGeneration,
|
@@ -73,6 +73,12 @@ _import_structure = {
|
|
73
73
|
"exaone": ["RBLNExaoneForCausalLM", "RBLNExaoneForCausalLMConfig"],
|
74
74
|
"gemma": ["RBLNGemmaForCausalLM", "RBLNGemmaForCausalLMConfig"],
|
75
75
|
"gpt2": ["RBLNGPT2LMHeadModel", "RBLNGPT2LMHeadModelConfig"],
|
76
|
+
"idefics3": [
|
77
|
+
"RBLNIdefics3VisionTransformer",
|
78
|
+
"RBLNIdefics3ForConditionalGeneration",
|
79
|
+
"RBLNIdefics3ForConditionalGenerationConfig",
|
80
|
+
"RBLNIdefics3VisionTransformerConfig",
|
81
|
+
],
|
76
82
|
"llama": ["RBLNLlamaForCausalLM", "RBLNLlamaForCausalLMConfig"],
|
77
83
|
"llava_next": ["RBLNLlavaNextForConditionalGeneration", "RBLNLlavaNextForConditionalGenerationConfig"],
|
78
84
|
"midm": ["RBLNMidmLMHeadModel", "RBLNMidmLMHeadModelConfig"],
|
@@ -144,6 +150,12 @@ if TYPE_CHECKING:
|
|
144
150
|
from .exaone import RBLNExaoneForCausalLM, RBLNExaoneForCausalLMConfig
|
145
151
|
from .gemma import RBLNGemmaForCausalLM, RBLNGemmaForCausalLMConfig
|
146
152
|
from .gpt2 import RBLNGPT2LMHeadModel, RBLNGPT2LMHeadModelConfig
|
153
|
+
from .idefics3 import (
|
154
|
+
RBLNIdefics3ForConditionalGeneration,
|
155
|
+
RBLNIdefics3ForConditionalGenerationConfig,
|
156
|
+
RBLNIdefics3VisionTransformer,
|
157
|
+
RBLNIdefics3VisionTransformerConfig,
|
158
|
+
)
|
147
159
|
from .llama import RBLNLlamaForCausalLM, RBLNLlamaForCausalLMConfig
|
148
160
|
from .llava_next import RBLNLlavaNextForConditionalGeneration, RBLNLlavaNextForConditionalGenerationConfig
|
149
161
|
from .midm import RBLNMidmLMHeadModel, RBLNMidmLMHeadModelConfig
|
@@ -48,7 +48,7 @@ class _BaseAutoModelClass:
|
|
48
48
|
|
49
49
|
Args:
|
50
50
|
pretrained_model_name_or_path (str): Identifier or path to the pretrained model.
|
51
|
-
export (bool): Whether to infer the class based on
|
51
|
+
export (bool): Whether to infer the class based on HuggingFace (HF) architecture.
|
52
52
|
kwargs: Additional arguments for configuration and loading.
|
53
53
|
|
54
54
|
Returns:
|
@@ -86,14 +86,14 @@ class _BaseAutoModelClass:
|
|
86
86
|
**kwargs,
|
87
87
|
):
|
88
88
|
"""
|
89
|
-
Infer the
|
89
|
+
Infer the HuggingFace model class based on the configuration or model name.
|
90
90
|
|
91
91
|
Args:
|
92
92
|
pretrained_model_name_or_path (str): Identifier or path to the pretrained model.
|
93
93
|
kwargs: Additional arguments for configuration and loading.
|
94
94
|
|
95
95
|
Returns:
|
96
|
-
PretrainedModel: The inferred
|
96
|
+
PretrainedModel: The inferred HuggingFace model class.
|
97
97
|
"""
|
98
98
|
|
99
99
|
# Try to load configuration if provided or retrieve it from the model ID
|
@@ -184,6 +184,7 @@ class DecoderOnlyWrapper(nn.Module):
|
|
184
184
|
|
185
185
|
def convert_to_rbln_causal_lm(self, causal_lm: PreTrainedModel, max_seq_len: int):
|
186
186
|
new_layers = []
|
187
|
+
|
187
188
|
for layer in causal_lm.model.layers:
|
188
189
|
if self.attn_impl == "eager":
|
189
190
|
new_self_attn = DecoderOnlyAttention(
|
@@ -201,6 +202,7 @@ class DecoderOnlyWrapper(nn.Module):
|
|
201
202
|
|
202
203
|
new_layer = DecoderOnlyLayer(layer, new_self_attn)
|
203
204
|
new_layers.append(new_layer)
|
205
|
+
|
204
206
|
new_model = DecoderOnlyModel(
|
205
207
|
causal_lm.model,
|
206
208
|
new_layers,
|
@@ -451,6 +451,12 @@ class RBLNDecoderOnlyModelForCausalLM(RBLNModel):
|
|
451
451
|
def get_input_embeddings(self):
|
452
452
|
return self.embed_tokens
|
453
453
|
|
454
|
+
def get_attn_impl(self) -> str:
|
455
|
+
return self.rbln_config.attn_impl
|
456
|
+
|
457
|
+
def get_kvcache_num_blocks(self) -> int:
|
458
|
+
return self.rbln_config.kvcache_num_blocks
|
459
|
+
|
454
460
|
@classmethod
|
455
461
|
def get_quantized_model(
|
456
462
|
cls,
|
@@ -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_idefics3 import RBLNIdefics3ForConditionalGenerationConfig, RBLNIdefics3VisionTransformerConfig
|
16
|
+
from .modeling_idefics3 import RBLNIdefics3ForConditionalGeneration, RBLNIdefics3VisionTransformer
|
@@ -0,0 +1,51 @@
|
|
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
|
16
|
+
|
17
|
+
from ....configuration_utils import RBLNModelConfig
|
18
|
+
|
19
|
+
|
20
|
+
class RBLNIdefics3VisionTransformerConfig(RBLNModelConfig):
|
21
|
+
pass
|
22
|
+
|
23
|
+
|
24
|
+
class RBLNIdefics3ForConditionalGenerationConfig(RBLNModelConfig):
|
25
|
+
submodules = ["vision_model", "text_model"]
|
26
|
+
|
27
|
+
def __init__(
|
28
|
+
self,
|
29
|
+
batch_size: Optional[int] = None,
|
30
|
+
vision_model: Optional[RBLNModelConfig] = None,
|
31
|
+
text_model: Optional[RBLNModelConfig] = None,
|
32
|
+
**kwargs,
|
33
|
+
):
|
34
|
+
"""
|
35
|
+
Args:
|
36
|
+
batch_size (Optional[int]): The batch size for inference. Defaults to 1.
|
37
|
+
vision_model (Optional[RBLNModelConfig]): Configuration for the vision transformer component.
|
38
|
+
text_model (Optional[RBLNModelConfig]): Configuration for the text model component.
|
39
|
+
**kwargs: Additional arguments passed to the parent RBLNModelConfig.
|
40
|
+
|
41
|
+
Raises:
|
42
|
+
ValueError: If batch_size is not a positive integer.
|
43
|
+
"""
|
44
|
+
|
45
|
+
super().__init__(**kwargs)
|
46
|
+
self.batch_size = batch_size or 1
|
47
|
+
if not isinstance(self.batch_size, int) or self.batch_size < 0:
|
48
|
+
raise ValueError(f"batch_size must be a positive integer, got {self.batch_size}")
|
49
|
+
|
50
|
+
self.vision_model = vision_model
|
51
|
+
self.text_model = text_model
|
@@ -0,0 +1,459 @@
|
|
1
|
+
# Copyright 2025 Rebellions Inc. All rights reserved.
|
2
|
+
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at:
|
6
|
+
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
|
15
|
+
import importlib
|
16
|
+
import inspect
|
17
|
+
from pathlib import Path
|
18
|
+
from typing import TYPE_CHECKING, Any, Callable, Optional, Tuple, Union
|
19
|
+
|
20
|
+
import rebel
|
21
|
+
import torch
|
22
|
+
from transformers import (
|
23
|
+
AutoModelForVision2Seq,
|
24
|
+
Idefics3ForConditionalGeneration,
|
25
|
+
Idefics3VisionConfig,
|
26
|
+
Idefics3VisionTransformer,
|
27
|
+
PretrainedConfig,
|
28
|
+
PreTrainedModel,
|
29
|
+
)
|
30
|
+
from transformers.modeling_outputs import BaseModelOutput
|
31
|
+
from transformers.modeling_utils import no_init_weights
|
32
|
+
from transformers.models.idefics3.modeling_idefics3 import Idefics3CausalLMOutputWithPast, Idefics3VisionEmbeddings
|
33
|
+
|
34
|
+
from ....configuration_utils import RBLNCompileConfig, RBLNModelConfig
|
35
|
+
from ....modeling import RBLNModel
|
36
|
+
from ....utils.runtime_utils import RBLNPytorchRuntime
|
37
|
+
from ..decoderonly.modeling_decoderonly import (
|
38
|
+
RBLNDecoderOnlyOutput,
|
39
|
+
)
|
40
|
+
|
41
|
+
|
42
|
+
if TYPE_CHECKING:
|
43
|
+
from transformers import (
|
44
|
+
AutoFeatureExtractor,
|
45
|
+
AutoProcessor,
|
46
|
+
AutoTokenizer,
|
47
|
+
)
|
48
|
+
|
49
|
+
|
50
|
+
class RBLNRuntimeVisionModel(RBLNPytorchRuntime):
|
51
|
+
mandatory_members = ["main_input_name"]
|
52
|
+
|
53
|
+
def __init__(
|
54
|
+
self,
|
55
|
+
runtime: rebel.Runtime,
|
56
|
+
config: Idefics3VisionConfig,
|
57
|
+
**kwargs: Any,
|
58
|
+
) -> None:
|
59
|
+
super().__init__(runtime, **kwargs)
|
60
|
+
self.patch_size = config.patch_size
|
61
|
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
62
|
+
|
63
|
+
def forward(
|
64
|
+
self,
|
65
|
+
pixel_values,
|
66
|
+
patch_attention_mask: Optional[torch.BoolTensor] = None,
|
67
|
+
return_dict: Optional[bool] = None,
|
68
|
+
**kwargs,
|
69
|
+
):
|
70
|
+
batch_size = pixel_values.size(0)
|
71
|
+
if patch_attention_mask is None:
|
72
|
+
patch_size = self.patch_size
|
73
|
+
patch_attention_mask = torch.ones(
|
74
|
+
(
|
75
|
+
batch_size,
|
76
|
+
pixel_values.size(2) // patch_size,
|
77
|
+
pixel_values.size(3) // patch_size,
|
78
|
+
)
|
79
|
+
)
|
80
|
+
patch_attention_mask = patch_attention_mask.to(dtype=torch.bool, device=pixel_values.device)
|
81
|
+
|
82
|
+
hidden_states = self.embeddings(pixel_values=pixel_values, patch_attention_mask=patch_attention_mask)
|
83
|
+
|
84
|
+
return super().forward(hidden_states.contiguous())
|
85
|
+
|
86
|
+
|
87
|
+
class RBLNIdefics3VisionTransformer(RBLNModel):
|
88
|
+
def __post_init__(self, **kwargs):
|
89
|
+
artifacts = torch.load(self.model_save_dir / self.subfolder / "torch_artifacts.pth", weights_only=False)
|
90
|
+
with no_init_weights():
|
91
|
+
self.embeddings = Idefics3VisionEmbeddings(self.config)
|
92
|
+
self.embeddings.load_state_dict(artifacts["embeddings"])
|
93
|
+
self.model = RBLNRuntimeVisionModel(
|
94
|
+
self.model[0], main_input_name="pixel_values", config=self.config, embeddings=self.embeddings
|
95
|
+
)
|
96
|
+
|
97
|
+
@classmethod
|
98
|
+
def save_torch_artifacts(
|
99
|
+
cls,
|
100
|
+
model: "PreTrainedModel",
|
101
|
+
save_dir_path: Path,
|
102
|
+
subfolder: str,
|
103
|
+
rbln_config: RBLNModelConfig,
|
104
|
+
):
|
105
|
+
"""
|
106
|
+
If you are unavoidably running on a CPU rather than an RBLN device,
|
107
|
+
store the torch tensor, weight, etc. in this function.
|
108
|
+
"""
|
109
|
+
save_dict = {}
|
110
|
+
save_dict["embeddings"] = model.get_input_embeddings().state_dict()
|
111
|
+
torch.save(save_dict, save_dir_path / subfolder / "torch_artifacts.pth")
|
112
|
+
|
113
|
+
def get_input_embeddings(self):
|
114
|
+
return self.embeddings
|
115
|
+
|
116
|
+
@classmethod
|
117
|
+
def wrap_model_if_needed(cls, model: torch.nn.Module, rbln_config: RBLNModelConfig) -> torch.nn.Module:
|
118
|
+
class Idefics3VisionTransformerWrapper(torch.nn.Module):
|
119
|
+
def __init__(self, model: "Idefics3VisionTransformer"):
|
120
|
+
super().__init__()
|
121
|
+
self.encoder = model.encoder
|
122
|
+
self.post_layernorm = model.post_layernorm
|
123
|
+
|
124
|
+
def forward(self, hidden_states, patch_attention_mask: Optional[torch.BoolTensor] = None):
|
125
|
+
encoder_outputs = self.encoder(
|
126
|
+
inputs_embeds=hidden_states,
|
127
|
+
attention_mask=patch_attention_mask,
|
128
|
+
output_attentions=None,
|
129
|
+
output_hidden_states=None,
|
130
|
+
return_dict=False,
|
131
|
+
)
|
132
|
+
last_hidden_state = encoder_outputs[0]
|
133
|
+
last_hidden_state = self.post_layernorm(last_hidden_state)
|
134
|
+
return last_hidden_state
|
135
|
+
|
136
|
+
return Idefics3VisionTransformerWrapper(model).eval()
|
137
|
+
|
138
|
+
@classmethod
|
139
|
+
def _update_rbln_config(
|
140
|
+
cls,
|
141
|
+
preprocessors: Optional[Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"]],
|
142
|
+
model: Optional["PreTrainedModel"] = None,
|
143
|
+
model_config: Optional["PretrainedConfig"] = None,
|
144
|
+
rbln_config: Optional[RBLNModelConfig] = None,
|
145
|
+
) -> RBLNModelConfig:
|
146
|
+
input_info = [
|
147
|
+
(
|
148
|
+
"hidden_states",
|
149
|
+
[
|
150
|
+
# batch_size * num_patches (dependent on image size) -> compile with 1 and use for loop
|
151
|
+
1,
|
152
|
+
(model_config.image_size // model_config.patch_size) ** 2,
|
153
|
+
model_config.hidden_size,
|
154
|
+
],
|
155
|
+
"float32",
|
156
|
+
),
|
157
|
+
]
|
158
|
+
|
159
|
+
rbln_compile_config = RBLNCompileConfig(input_info=input_info)
|
160
|
+
rbln_config.set_compile_cfgs([rbln_compile_config])
|
161
|
+
return rbln_config
|
162
|
+
|
163
|
+
def forward(
|
164
|
+
self,
|
165
|
+
pixel_values,
|
166
|
+
patch_attention_mask: Optional[torch.BoolTensor] = None,
|
167
|
+
return_dict: Optional[bool] = None,
|
168
|
+
**kwargs,
|
169
|
+
) -> Union[Tuple, BaseModelOutput]:
|
170
|
+
batch_size = pixel_values.shape[0]
|
171
|
+
last_hidden_state = []
|
172
|
+
for i in range(batch_size):
|
173
|
+
if patch_attention_mask is not None:
|
174
|
+
batch_attention_mask = patch_attention_mask[i : i + 1,]
|
175
|
+
else:
|
176
|
+
batch_attention_mask = None
|
177
|
+
|
178
|
+
batch_hidden_state = self.model(
|
179
|
+
pixel_values[i : i + 1,],
|
180
|
+
batch_attention_mask,
|
181
|
+
return_dict=False,
|
182
|
+
)
|
183
|
+
last_hidden_state.append(batch_hidden_state)
|
184
|
+
last_hidden_state = torch.cat(last_hidden_state, dim=0)
|
185
|
+
|
186
|
+
if not return_dict:
|
187
|
+
return (last_hidden_state,)
|
188
|
+
else:
|
189
|
+
return BaseModelOutput(last_hidden_state=last_hidden_state)
|
190
|
+
|
191
|
+
|
192
|
+
class RBLNIdefics3ForConditionalGeneration(RBLNModel):
|
193
|
+
auto_model_class = AutoModelForVision2Seq
|
194
|
+
_rbln_submodules = [{"name": "vision_model"}, {"name": "text_model"}]
|
195
|
+
_rbln_submodule_prefix = "model"
|
196
|
+
|
197
|
+
def __getattr__(self, __name: str) -> Any:
|
198
|
+
def redirect(func):
|
199
|
+
return lambda *pargs, **kwargs: func(self, *pargs, **kwargs)
|
200
|
+
|
201
|
+
val = getattr(Idefics3ForConditionalGeneration, __name)
|
202
|
+
|
203
|
+
if isinstance(val, Callable) and "self" in set(inspect.signature(val).parameters):
|
204
|
+
return redirect(val)
|
205
|
+
return val
|
206
|
+
|
207
|
+
def can_generate(self):
|
208
|
+
return True
|
209
|
+
|
210
|
+
@classmethod
|
211
|
+
def get_pytorch_model(cls, *args, **kwargs):
|
212
|
+
model = super().get_pytorch_model(*args, **kwargs)
|
213
|
+
|
214
|
+
with no_init_weights():
|
215
|
+
model_cls_name = model.model.text_model.__class__.__name__
|
216
|
+
causal_model_cls_name = model_cls_name.replace("Model", "ForCausalLM")
|
217
|
+
causal_model_cls = getattr(importlib.import_module("transformers"), causal_model_cls_name)
|
218
|
+
new_text_model = causal_model_cls(model.model.text_model.config)
|
219
|
+
|
220
|
+
new_text_model.lm_head = model.lm_head
|
221
|
+
new_text_model.model = model.model.text_model
|
222
|
+
model.model.text_model = new_text_model
|
223
|
+
model.lm_head = None
|
224
|
+
del model.lm_head
|
225
|
+
return model
|
226
|
+
|
227
|
+
def __post_init__(self, **kwargs):
|
228
|
+
self.vision_model = self.rbln_submodules[0]
|
229
|
+
self.connector = self.model[0]
|
230
|
+
self.text_model = self.rbln_submodules[1]
|
231
|
+
|
232
|
+
def get_attn_impl(self) -> str:
|
233
|
+
return self.rbln_config.text_model.attn_impl
|
234
|
+
|
235
|
+
def get_kvcache_num_blocks(self) -> int:
|
236
|
+
return self.rbln_config.text_model.kvcache_num_blocks
|
237
|
+
|
238
|
+
def get_input_embeddings(self):
|
239
|
+
return self.text_model.get_input_embeddings()
|
240
|
+
|
241
|
+
@classmethod
|
242
|
+
def wrap_model_if_needed(cls, model, rbln_config):
|
243
|
+
return model.model.connector
|
244
|
+
|
245
|
+
@classmethod
|
246
|
+
def _update_rbln_config(
|
247
|
+
cls,
|
248
|
+
preprocessors: Optional[Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"]],
|
249
|
+
model: Optional["PreTrainedModel"] = None,
|
250
|
+
model_config: Optional["PretrainedConfig"] = None,
|
251
|
+
rbln_config: Optional[RBLNModelConfig] = None,
|
252
|
+
) -> RBLNModelConfig:
|
253
|
+
input_info = [
|
254
|
+
(
|
255
|
+
"image_hidden_states",
|
256
|
+
[
|
257
|
+
# batch_size * num_patches (dependent on image size) -> compile with 1 and use for loop
|
258
|
+
1,
|
259
|
+
(model_config.vision_config.image_size // model_config.vision_config.patch_size) ** 2,
|
260
|
+
model_config.vision_config.hidden_size,
|
261
|
+
],
|
262
|
+
"float32",
|
263
|
+
),
|
264
|
+
]
|
265
|
+
|
266
|
+
rbln_compile_config = RBLNCompileConfig(input_info=input_info)
|
267
|
+
rbln_config.set_compile_cfgs([rbln_compile_config])
|
268
|
+
|
269
|
+
return rbln_config
|
270
|
+
|
271
|
+
def prepare_inputs_for_generation(
|
272
|
+
self,
|
273
|
+
input_ids,
|
274
|
+
attention_mask=None,
|
275
|
+
inputs_embeds=None,
|
276
|
+
cache_position=None,
|
277
|
+
pixel_values=None,
|
278
|
+
pixel_attention_mask=None,
|
279
|
+
image_hidden_states=None,
|
280
|
+
generate_idx=None,
|
281
|
+
**kwargs,
|
282
|
+
):
|
283
|
+
is_prefill_phase = generate_idx is None
|
284
|
+
model_inputs = {}
|
285
|
+
|
286
|
+
if is_prefill_phase:
|
287
|
+
generate_idx = attention_mask.sum(dim=-1, keepdim=True).int()
|
288
|
+
cache_position = None
|
289
|
+
pixel_values = pixel_values
|
290
|
+
pixel_attention_mask = pixel_attention_mask
|
291
|
+
else:
|
292
|
+
if inputs_embeds is not None:
|
293
|
+
raise NotImplementedError("Specifying inputs_embeds in decoder phase is not supported.")
|
294
|
+
|
295
|
+
pixel_values = None
|
296
|
+
pixel_attention_mask = None
|
297
|
+
input_ids = input_ids[:, -1:]
|
298
|
+
cache_position = generate_idx
|
299
|
+
generate_idx = generate_idx + 1
|
300
|
+
model_inputs.update({"input_ids": input_ids})
|
301
|
+
|
302
|
+
if inputs_embeds is not None:
|
303
|
+
if self.rbln_config.use_inputs_embeds:
|
304
|
+
model_inputs.update({"inputs_embeds": inputs_embeds})
|
305
|
+
else:
|
306
|
+
raise ValueError(
|
307
|
+
"The specifying inputs_embeds is only supported when using a compiled RBLN model with 'rbln_use_inputs_embeds' set to True."
|
308
|
+
)
|
309
|
+
else:
|
310
|
+
model_inputs.update({"input_ids": input_ids})
|
311
|
+
|
312
|
+
model_inputs.update(
|
313
|
+
{
|
314
|
+
"attention_mask": attention_mask,
|
315
|
+
"pixel_values": pixel_values,
|
316
|
+
"pixel_attention_mask": pixel_attention_mask,
|
317
|
+
"image_hidden_states": image_hidden_states,
|
318
|
+
"cache_position": cache_position,
|
319
|
+
"generate_idx": generate_idx,
|
320
|
+
}
|
321
|
+
)
|
322
|
+
return model_inputs
|
323
|
+
|
324
|
+
def _update_model_kwargs_for_generation(self, outputs, model_kwargs, is_encoder_decoder, **kwargs):
|
325
|
+
model_kwargs["generate_idx"] = outputs.generate_idx
|
326
|
+
return model_kwargs
|
327
|
+
|
328
|
+
def inputs_merger(
|
329
|
+
self,
|
330
|
+
input_ids: torch.LongTensor,
|
331
|
+
inputs_embeds: Optional[torch.Tensor],
|
332
|
+
image_hidden_states: Optional[torch.Tensor],
|
333
|
+
):
|
334
|
+
num_images, _, vision_hidden_size = image_hidden_states.shape
|
335
|
+
special_image_token_mask = input_ids == self.config.image_token_id
|
336
|
+
new_inputs_embeds = inputs_embeds.clone()
|
337
|
+
reshaped_image_hidden_states = image_hidden_states.view(-1, vision_hidden_size)
|
338
|
+
reshaped_image_hidden_states = reshaped_image_hidden_states.to(inputs_embeds.device, inputs_embeds.dtype)
|
339
|
+
new_inputs_embeds[special_image_token_mask] = reshaped_image_hidden_states
|
340
|
+
return new_inputs_embeds
|
341
|
+
|
342
|
+
def _preprocess_prefill(
|
343
|
+
self,
|
344
|
+
input_ids: torch.LongTensor = None,
|
345
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
346
|
+
pixel_values: Optional[torch.FloatTensor] = None,
|
347
|
+
pixel_attention_mask: Optional[torch.BoolTensor] = None,
|
348
|
+
image_hidden_states: Optional[torch.FloatTensor] = None,
|
349
|
+
**kwargs,
|
350
|
+
):
|
351
|
+
if input_ids is not None:
|
352
|
+
batch_size, _ = input_ids.shape
|
353
|
+
elif inputs_embeds is not None:
|
354
|
+
batch_size, _, _ = inputs_embeds.shape
|
355
|
+
else:
|
356
|
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
357
|
+
|
358
|
+
if inputs_embeds is not None and input_ids is None:
|
359
|
+
raise ValueError("When first calling the model, if input_embeds are passed, input_ids should not be None.")
|
360
|
+
|
361
|
+
if inputs_embeds is None:
|
362
|
+
inputs_embeds = self.get_input_embeddings()(input_ids).to(self.device)
|
363
|
+
|
364
|
+
if pixel_values is not None and image_hidden_states is not None:
|
365
|
+
raise ValueError("You cannot specify both pixel_values and image_hidden_states at the same time")
|
366
|
+
|
367
|
+
elif pixel_values is not None:
|
368
|
+
batch_size, num_images, num_channels, height, width = pixel_values.shape
|
369
|
+
pixel_values = pixel_values.to(dtype=self.dtype)
|
370
|
+
pixel_values = pixel_values.view(batch_size * num_images, *pixel_values.shape[2:])
|
371
|
+
|
372
|
+
nb_values_per_image = pixel_values.shape[1:].numel()
|
373
|
+
real_images_inds = (pixel_values == 0.0).sum(dim=(-1, -2, -3)) != nb_values_per_image
|
374
|
+
pixel_values = pixel_values[real_images_inds].contiguous()
|
375
|
+
|
376
|
+
if pixel_attention_mask is None:
|
377
|
+
pixel_attention_mask = torch.ones(
|
378
|
+
size=(pixel_values.size(0), pixel_values.size(2), pixel_values.size(3)),
|
379
|
+
dtype=torch.bool,
|
380
|
+
device=pixel_values.device,
|
381
|
+
)
|
382
|
+
else:
|
383
|
+
pixel_attention_mask = pixel_attention_mask.view(
|
384
|
+
batch_size * num_images, *pixel_attention_mask.shape[2:]
|
385
|
+
)
|
386
|
+
pixel_attention_mask = pixel_attention_mask[real_images_inds].contiguous()
|
387
|
+
|
388
|
+
patch_size = self.config.vision_config.patch_size
|
389
|
+
patches_subgrid = pixel_attention_mask.unfold(dimension=1, size=patch_size, step=patch_size)
|
390
|
+
patches_subgrid = patches_subgrid.unfold(dimension=2, size=patch_size, step=patch_size)
|
391
|
+
patch_attention_mask = (patches_subgrid.sum(dim=(-1, -2)) > 0).bool()
|
392
|
+
|
393
|
+
image_hidden_states = self.vision_model(
|
394
|
+
pixel_values=pixel_values, patch_attention_mask=patch_attention_mask, return_dict=True
|
395
|
+
).last_hidden_state
|
396
|
+
|
397
|
+
connector_outputs = []
|
398
|
+
for i in range(image_hidden_states.shape[0]):
|
399
|
+
connector_outputs.append(self.connector(image_hidden_states[i : i + 1,]))
|
400
|
+
image_hidden_states = torch.cat(connector_outputs, dim=0)
|
401
|
+
|
402
|
+
elif image_hidden_states is not None:
|
403
|
+
image_hidden_states = image_hidden_states.to(dtype=self.dtype, device=input_ids.device)
|
404
|
+
|
405
|
+
if inputs_embeds is not None and image_hidden_states is not None:
|
406
|
+
inputs_embeds = self.inputs_merger(
|
407
|
+
input_ids=input_ids,
|
408
|
+
inputs_embeds=inputs_embeds,
|
409
|
+
image_hidden_states=image_hidden_states,
|
410
|
+
)
|
411
|
+
|
412
|
+
return inputs_embeds
|
413
|
+
|
414
|
+
def forward(
|
415
|
+
self,
|
416
|
+
input_ids: torch.LongTensor = None,
|
417
|
+
attention_mask: Optional[torch.Tensor] = None,
|
418
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
419
|
+
pixel_values: Optional[torch.FloatTensor] = None,
|
420
|
+
pixel_attention_mask: Optional[torch.BoolTensor] = None,
|
421
|
+
image_hidden_states: Optional[torch.FloatTensor] = None,
|
422
|
+
cache_position: torch.Tensor = None,
|
423
|
+
generate_idx: Optional[torch.Tensor] = None,
|
424
|
+
**kwargs,
|
425
|
+
) -> Union[Tuple, Idefics3CausalLMOutputWithPast]:
|
426
|
+
# Prefill
|
427
|
+
if cache_position is None:
|
428
|
+
inputs_embeds = self._preprocess_prefill(
|
429
|
+
input_ids, inputs_embeds, pixel_values, pixel_attention_mask, image_hidden_states
|
430
|
+
)
|
431
|
+
logits = []
|
432
|
+
inputs = inputs_embeds if inputs_embeds is not None else input_ids
|
433
|
+
batch_size = inputs.shape[0]
|
434
|
+
|
435
|
+
for b_idx in range(batch_size):
|
436
|
+
cache_position = torch.arange(0, generate_idx[b_idx].item(), dtype=torch.int32).unsqueeze(0)
|
437
|
+
logit = self.text_model.prefill_decoder(
|
438
|
+
input_ids=inputs[b_idx : b_idx + 1] if inputs_embeds is None else None,
|
439
|
+
inputs_embeds=inputs[b_idx : b_idx + 1] if inputs_embeds is not None else None,
|
440
|
+
attention_mask=attention_mask[b_idx] if attention_mask is not None else None,
|
441
|
+
cache_position=cache_position,
|
442
|
+
batch_idx=b_idx,
|
443
|
+
)
|
444
|
+
logits.append(logit)
|
445
|
+
|
446
|
+
logits = torch.cat(logits, dim=0)
|
447
|
+
|
448
|
+
# Decoder
|
449
|
+
else:
|
450
|
+
logits = self.text_model.decoder(
|
451
|
+
input_ids=input_ids,
|
452
|
+
inputs_embeds=inputs_embeds,
|
453
|
+
cache_position=cache_position,
|
454
|
+
)
|
455
|
+
|
456
|
+
return RBLNDecoderOnlyOutput(
|
457
|
+
logits=logits,
|
458
|
+
generate_idx=generate_idx,
|
459
|
+
)
|
@@ -157,6 +157,12 @@ class RBLNLlavaNextForConditionalGeneration(RBLNModel):
|
|
157
157
|
self._padding_side = "left" # set it to left by default, user can use setter to change padding_sides
|
158
158
|
return super().__post_init__(**kwargs)
|
159
159
|
|
160
|
+
def get_attn_impl(self) -> str:
|
161
|
+
return self.rbln_config.language_model.attn_impl
|
162
|
+
|
163
|
+
def get_kvcache_num_blocks(self) -> int:
|
164
|
+
return self.rbln_config.language_model.kvcache_num_blocks
|
165
|
+
|
160
166
|
def get_input_embeddings(self):
|
161
167
|
return self.language_model.get_input_embeddings()
|
162
168
|
|
optimum/rbln/utils/hub.py
CHANGED
@@ -63,7 +63,7 @@ def pull_compiled_model_from_hub(
|
|
63
63
|
force_download: bool,
|
64
64
|
local_files_only: bool,
|
65
65
|
) -> Path:
|
66
|
-
"""Pull model files from the
|
66
|
+
"""Pull model files from the HuggingFace Hub."""
|
67
67
|
huggingface_token = _get_huggingface_token(use_auth_token)
|
68
68
|
repo_files = list(
|
69
69
|
map(
|
@@ -119,4 +119,4 @@ def _get_huggingface_token(use_auth_token: Union[bool, str]) -> str:
|
|
119
119
|
elif use_auth_token:
|
120
120
|
return HfFolder.get_token()
|
121
121
|
else:
|
122
|
-
raise ValueError("`use_auth_token` must be provided to interact with the
|
122
|
+
raise ValueError("`use_auth_token` must be provided to interact with the HuggingFace Hub.")
|
@@ -18,10 +18,10 @@ RBLN_PREFIX = "RBLN"
|
|
18
18
|
|
19
19
|
def convert_hf_to_rbln_model_name(hf_model_name: str):
|
20
20
|
"""
|
21
|
-
Convert
|
21
|
+
Convert HuggingFace model name to RBLN model name.
|
22
22
|
|
23
23
|
Args:
|
24
|
-
hf_model_name (str): The
|
24
|
+
hf_model_name (str): The HuggingFace model name.
|
25
25
|
|
26
26
|
Returns:
|
27
27
|
str: The corresponding RBLN model name.
|
@@ -31,13 +31,13 @@ def convert_hf_to_rbln_model_name(hf_model_name: str):
|
|
31
31
|
|
32
32
|
def convert_rbln_to_hf_model_name(rbln_model_name: str):
|
33
33
|
"""
|
34
|
-
Convert RBLN model name to
|
34
|
+
Convert RBLN model name to HuggingFace model name.
|
35
35
|
|
36
36
|
Args:
|
37
37
|
rbln_model_name (str): The RBLN model name.
|
38
38
|
|
39
39
|
Returns:
|
40
|
-
str: The corresponding
|
40
|
+
str: The corresponding HuggingFace model name.
|
41
41
|
"""
|
42
42
|
|
43
43
|
return rbln_model_name.removeprefix(RBLN_PREFIX)
|
optimum/rbln/utils/submodule.py
CHANGED
@@ -43,9 +43,16 @@ class SubModulesMixin:
|
|
43
43
|
cls, model: "PreTrainedModel", model_save_dir: str, rbln_config: RBLNModelConfig, **kwargs
|
44
44
|
) -> List["RBLNBaseModel"]:
|
45
45
|
rbln_submodules = []
|
46
|
+
submodule_prefix = getattr(cls, "_rbln_submodule_prefix", None)
|
47
|
+
|
46
48
|
for submodule in cls._rbln_submodules:
|
47
49
|
submodule_name = submodule["name"]
|
48
|
-
|
50
|
+
if submodule_prefix is not None:
|
51
|
+
torch_submodule: PreTrainedModel = getattr(model, submodule_prefix)
|
52
|
+
torch_submodule = getattr(torch_submodule, submodule_name)
|
53
|
+
else:
|
54
|
+
torch_submodule: PreTrainedModel = getattr(model, submodule_name)
|
55
|
+
|
49
56
|
cls_name = torch_submodule.__class__.__name__
|
50
57
|
submodule_cls: Type["RBLNBaseModel"] = getattr(importlib.import_module("optimum.rbln"), f"RBLN{cls_name}")
|
51
58
|
submodule_rbln_config = getattr(rbln_config, submodule_name) or {}
|
@@ -57,6 +64,7 @@ class SubModulesMixin:
|
|
57
64
|
|
58
65
|
rbln_submodule = submodule_cls.from_model(
|
59
66
|
model=torch_submodule,
|
67
|
+
config=torch_submodule.config,
|
60
68
|
subfolder=submodule_name,
|
61
69
|
model_save_dir=model_save_dir,
|
62
70
|
rbln_config=submodule_rbln_config,
|
@@ -70,6 +78,7 @@ class SubModulesMixin:
|
|
70
78
|
@classmethod
|
71
79
|
def _load_submodules_from_compiled_models(cls, model_save_dir: str, rbln_config: RBLNModelConfig, **kwargs):
|
72
80
|
rbln_submodules = []
|
81
|
+
|
73
82
|
for submodule in cls._rbln_submodules:
|
74
83
|
submodule_name = submodule["name"]
|
75
84
|
|
@@ -1,7 +1,7 @@
|
|
1
1
|
Metadata-Version: 2.4
|
2
2
|
Name: optimum-rbln
|
3
|
-
Version: 0.7.
|
4
|
-
Summary: Optimum RBLN is the interface between the
|
3
|
+
Version: 0.7.4a8
|
4
|
+
Summary: Optimum RBLN is the interface between the HuggingFace Transformers and Diffusers libraries and RBLN accelerators. It provides a set of tools enabling easy model loading and inference on single and multiple rbln device settings for different downstream tasks.
|
5
5
|
Project-URL: Homepage, https://rebellions.ai
|
6
6
|
Project-URL: Documentation, https://docs.rbln.ai
|
7
7
|
Project-URL: Repository, https://github.com/rebellions-sw/optimum-rbln
|
@@ -1,10 +1,10 @@
|
|
1
|
-
optimum/rbln/__init__.py,sha256=
|
2
|
-
optimum/rbln/__version__.py,sha256=
|
3
|
-
optimum/rbln/configuration_utils.py,sha256=
|
1
|
+
optimum/rbln/__init__.py,sha256=c2whRR6XkelNLlH1MwAKYMoaBEhmGxSQFrhfKS1JC-I,13186
|
2
|
+
optimum/rbln/__version__.py,sha256=QL0a_B-kCttMpg_RwbPMs7mYzsY06SEmJHJVDUYponM,519
|
3
|
+
optimum/rbln/configuration_utils.py,sha256=S2RGzl-gdE5evUd5ZsO9i8LXgPGCrQEOGZJTa6t1A9Y,30044
|
4
4
|
optimum/rbln/modeling.py,sha256=qDXB69Oq0jx9hfONebDiSNe2_DgKYhnAGLTbGAtwYVw,9677
|
5
|
-
optimum/rbln/modeling_base.py,sha256=
|
5
|
+
optimum/rbln/modeling_base.py,sha256=iQKw2IORu1cN6sOK0xeBVrhatt-ZPeinT_v6l2FnGRw,24173
|
6
6
|
optimum/rbln/diffusers/__init__.py,sha256=XL6oKPHbPCV6IVCw3fu0-M9mD2KO_x6unx5kJdAtpVY,6180
|
7
|
-
optimum/rbln/diffusers/modeling_diffusers.py,sha256=
|
7
|
+
optimum/rbln/diffusers/modeling_diffusers.py,sha256=DrB-UZbNYXGQYyY5DXOeH88_AfSg35JPEQ3AXnkrCP4,19294
|
8
8
|
optimum/rbln/diffusers/configurations/__init__.py,sha256=Sk_sQVTuTl01RVgYViWknQSLmulxKaISS0w-oPdNoBQ,1164
|
9
9
|
optimum/rbln/diffusers/configurations/models/__init__.py,sha256=P3vif5I4wYeol50jzHCZ1ttujuEFZSYJPzUdSF6_jsU,407
|
10
10
|
optimum/rbln/diffusers/configurations/models/configuration_autoencoder_kl.py,sha256=61QHgb_tVF6lxvy6vBxst2TjnebeKQy3rKHOOOc6e68,2952
|
@@ -60,15 +60,15 @@ optimum/rbln/ops/attn.py,sha256=x02yFLk7FcONFqfow0ROmVy9fmxo5Pw0SPCiDY3AZNg,9012
|
|
60
60
|
optimum/rbln/ops/flash_attn.py,sha256=NmCqUdMTzgJ4sbYGj8IWXJEsLWvbuCMponR01w5DK6w,4121
|
61
61
|
optimum/rbln/ops/kv_cache_update.py,sha256=HjnHBR-oFrJQibsVnkYb0P5_-wEma8jl0mkjkylwakU,1270
|
62
62
|
optimum/rbln/ops/linear.py,sha256=1_7Hg-9wXxhu97fqPobotLQx17k7VPeSSL91_9Z7EDg,1018
|
63
|
-
optimum/rbln/transformers/__init__.py,sha256=
|
63
|
+
optimum/rbln/transformers/__init__.py,sha256=P89UOclQWiLgNkH90GXdnwWD2492O2tusM-fZApfBNg,8084
|
64
64
|
optimum/rbln/transformers/configuration_alias.py,sha256=qFVfg6ohsR7a6b-CBgxjBUPDrk9MyiJwtO8AQah_RTU,1505
|
65
65
|
optimum/rbln/transformers/configuration_generic.py,sha256=XIiZ1-5p1CMHhG7Sr2qR4SLYKcYw9aph7eGlga3Opx0,5056
|
66
66
|
optimum/rbln/transformers/modeling_alias.py,sha256=yx7FnZQWAnrWzivaO5hI7T6i-fyLzt2tMIXG2oDNbPo,1657
|
67
67
|
optimum/rbln/transformers/modeling_generic.py,sha256=nT_lytAILkYtwBVJKxXg0dxmh0UpjGYO6zOdLoMs1uU,12891
|
68
68
|
optimum/rbln/transformers/modeling_rope_utils.py,sha256=3zwkhYUyTZhxCJUSmwCc88iiY1TppRWEY9ShwUqNB2k,14293
|
69
|
-
optimum/rbln/transformers/models/__init__.py,sha256=
|
69
|
+
optimum/rbln/transformers/models/__init__.py,sha256=72eMPN5UYGJ9P5gnJ2yi25cGdX1jV7viTOKmsX2OqBg,7221
|
70
70
|
optimum/rbln/transformers/models/auto/__init__.py,sha256=GvGbb3ZpMv-h6euXeZ42jSizoOfrL2O1uvpAnfKxYEo,1034
|
71
|
-
optimum/rbln/transformers/models/auto/auto_factory.py,sha256=
|
71
|
+
optimum/rbln/transformers/models/auto/auto_factory.py,sha256=Uf5rCUoxec2qhIAwbAeZNZN4NIMFaLurSB1EdI79lwA,7044
|
72
72
|
optimum/rbln/transformers/models/auto/modeling_auto.py,sha256=Un9qoqdy3dO8JBza_bTJF_6_fRVNM9QisihSgTRFI-o,3933
|
73
73
|
optimum/rbln/transformers/models/bart/__init__.py,sha256=fVo-gZEmJ0yxkIxEX6ciuRAGgXNyuvaXE2s88bhbjAE,830
|
74
74
|
optimum/rbln/transformers/models/bart/bart_architecture.py,sha256=Oo-Cdne7igKEex8wwP-gztKJHgs5GLHQjK1oc3IZIDE,5801
|
@@ -82,8 +82,8 @@ optimum/rbln/transformers/models/clip/configuration_clip.py,sha256=wgfZeVvcVdSzr
|
|
82
82
|
optimum/rbln/transformers/models/clip/modeling_clip.py,sha256=UslcDN6otyQ_psou7F_YcdK5vCImEtgIdcbwmexSfOM,7256
|
83
83
|
optimum/rbln/transformers/models/decoderonly/__init__.py,sha256=vQYZDDdoddwA7yKc5zzrq2Zs9sax-0p8rNF_aYfF4bk,1006
|
84
84
|
optimum/rbln/transformers/models/decoderonly/configuration_decoderonly.py,sha256=b1W7zS0MUmeDd048bLp5AkZMrWd3LIhHaVy8NvlwdCw,4116
|
85
|
-
optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py,sha256=
|
86
|
-
optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py,sha256=
|
85
|
+
optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py,sha256=NG2tKC3gT57r34PYKgU0evZHctEHzJGRrk2FOjLyK7Q,41748
|
86
|
+
optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py,sha256=5o2m_xPVjfCovP_jcW8E17sSKkLqcVblr4mFLbv-VDU,42991
|
87
87
|
optimum/rbln/transformers/models/dpt/__init__.py,sha256=Nzep9mlzKyL1kV726IBqY8DnLp1DkH9JzFeknWSRhok,714
|
88
88
|
optimum/rbln/transformers/models/dpt/configuration_dpt.py,sha256=4fW6bzVhaAxym4wGV3F785rvUOoWPyw_gdEMqB08Leg,755
|
89
89
|
optimum/rbln/transformers/models/dpt/modeling_dpt.py,sha256=oKLX7MQZvfk1QB8wOtcdi7AmZH2fOIVbypa9A3RA9MI,733
|
@@ -99,13 +99,16 @@ optimum/rbln/transformers/models/gpt2/__init__.py,sha256=socBMIBZSiLbrVN12rQ4nL9
|
|
99
99
|
optimum/rbln/transformers/models/gpt2/configuration_gpt2.py,sha256=vKvJD8P9Li4W9wdVoQcqMEr1MwEXojPBnF2NE85VXAo,772
|
100
100
|
optimum/rbln/transformers/models/gpt2/gpt2_architecture.py,sha256=1IxqHmB-GlH2Dv2Yk4z0rMxL9CpxMGHhSu_x8_4cxvs,3008
|
101
101
|
optimum/rbln/transformers/models/gpt2/modeling_gpt2.py,sha256=qBDanUk_O-HtOIVCA4IE3FYyCsnL9xIDK00vft-0caw,1490
|
102
|
+
optimum/rbln/transformers/models/idefics3/__init__.py,sha256=ulxE7HEfXsNJhd25J9Fvi6vggo9aZH9sLKJjWB6LlzQ,814
|
103
|
+
optimum/rbln/transformers/models/idefics3/configuration_idefics3.py,sha256=sM0pXsvkxcpDXagoKlqwKdBAcNdayB9KlWdYC9xlyDU,1889
|
104
|
+
optimum/rbln/transformers/models/idefics3/modeling_idefics3.py,sha256=Rr9BJDyoOqJFQ8dJV78QU4Tjjhhj3aqRk05JcDqFv6Y,17904
|
102
105
|
optimum/rbln/transformers/models/llama/__init__.py,sha256=knxvRkPx8x6-WOxqSq_PlaKYD-9F9Q8dh7r095Esey0,708
|
103
106
|
optimum/rbln/transformers/models/llama/configuration_llama.py,sha256=B9gr4pTn9yiv3-8DIk0P7_AQdIHEc7SuLaH9gZAmP8E,773
|
104
107
|
optimum/rbln/transformers/models/llama/llama_architecture.py,sha256=S7MCPfyjG5eUqgaS-QNBB0ApUD6wnb5fR0RHq7k7-pA,728
|
105
108
|
optimum/rbln/transformers/models/llama/modeling_llama.py,sha256=Z3iony7icoFhRQ11MAuFx9UF03uJCsvJQZ6bxHXlrgk,1530
|
106
109
|
optimum/rbln/transformers/models/llava_next/__init__.py,sha256=kDXKr7wMkp1XqE__DER2B8kQF_NYMxhzsQS5ytGg56I,752
|
107
110
|
optimum/rbln/transformers/models/llava_next/configuration_llava_next.py,sha256=QPreWZyohwRL23GOyvoAfKtk5UNg7IJ_Y_pNfUDe7cU,1838
|
108
|
-
optimum/rbln/transformers/models/llava_next/modeling_llava_next.py,sha256
|
111
|
+
optimum/rbln/transformers/models/llava_next/modeling_llava_next.py,sha256=xOXc1XUIK4oLSFvAq7Q0lxiOLlDFMbFdOcg5JvLnVkI,25979
|
109
112
|
optimum/rbln/transformers/models/midm/__init__.py,sha256=IC3FETwgYinbp3wDj7tp4zIHJhbqM-c6GfTRdYcMNj8,913
|
110
113
|
optimum/rbln/transformers/models/midm/configuration_midm.py,sha256=Kv5g5dIsBrhGcZ2_pFUOPNB80np4Xiw0wPH1IZm1PHI,772
|
111
114
|
optimum/rbln/transformers/models/midm/midm_architecture.py,sha256=357iviqQkzI0s_lU_teH1sVOChNRDUABe3GA0HuhZZY,5444
|
@@ -153,14 +156,14 @@ optimum/rbln/transformers/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm
|
|
153
156
|
optimum/rbln/transformers/utils/rbln_quantization.py,sha256=gwBVHf97sQgPNmGa0wq87E8mPyrtXYhMnO4X4sKp3c8,7639
|
154
157
|
optimum/rbln/utils/__init__.py,sha256=ieDBT2VFTt2E0M4v_POLBpuGW9LxSydpb_DuPd6PQqc,712
|
155
158
|
optimum/rbln/utils/decorator_utils.py,sha256=xu-TrsNi33SRC2a7DBsyoo6-pEQxWKZPZSmM9QlDe2Y,3745
|
156
|
-
optimum/rbln/utils/hub.py,sha256=
|
159
|
+
optimum/rbln/utils/hub.py,sha256=Z_R9Ic9VAew8bUmlaAlxZf5JGMDBivHvvFRI557pILY,4196
|
157
160
|
optimum/rbln/utils/import_utils.py,sha256=uMldLJmDVMj5uHvxBfb96uV29bfGEDvlksLY26GOHAs,4389
|
158
161
|
optimum/rbln/utils/logging.py,sha256=VKKBmlQSdg6iZCGmAXaWYiW67K84jyp1QJhLQSSjPPE,3453
|
159
|
-
optimum/rbln/utils/model_utils.py,sha256=
|
162
|
+
optimum/rbln/utils/model_utils.py,sha256=V2kFpUe2aqVzLwbpztD8JOVFQqRHncvIWwJbgnUPr4E,1274
|
160
163
|
optimum/rbln/utils/runtime_utils.py,sha256=LoKNK3AQNV_BSScstIZWjICkJf265MnUgy360BOocVI,5454
|
161
164
|
optimum/rbln/utils/save_utils.py,sha256=hG5uOtYmecSXZuGTvCXsTM-SiyZpr5q3InUGCCq_jzQ,3619
|
162
|
-
optimum/rbln/utils/submodule.py,sha256=
|
163
|
-
optimum_rbln-0.7.
|
164
|
-
optimum_rbln-0.7.
|
165
|
-
optimum_rbln-0.7.
|
166
|
-
optimum_rbln-0.7.
|
165
|
+
optimum/rbln/utils/submodule.py,sha256=TtcH3OLctFd2Dosc-zNMGZ8xOXKKUfE91dLQ1v09E8Q,4636
|
166
|
+
optimum_rbln-0.7.4a8.dist-info/METADATA,sha256=jkrw5KRSdUkdaY3ZJYv0A4HHNhUDdOB59D_tNSMa7Ss,5299
|
167
|
+
optimum_rbln-0.7.4a8.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
168
|
+
optimum_rbln-0.7.4a8.dist-info/licenses/LICENSE,sha256=QwcOLU5TJoTeUhuIXzhdCEEDDvorGiC6-3YTOl4TecE,11356
|
169
|
+
optimum_rbln-0.7.4a8.dist-info/RECORD,,
|
File without changes
|
File without changes
|