optimum-rbln 0.1.13__py3-none-any.whl → 0.2.0__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 (103) hide show
  1. optimum/rbln/__init__.py +41 -38
  2. optimum/rbln/__version__.py +16 -1
  3. optimum/rbln/diffusers/__init__.py +26 -2
  4. optimum/rbln/{modeling_diffusers.py → diffusers/modeling_diffusers.py} +97 -126
  5. optimum/rbln/diffusers/models/__init__.py +36 -3
  6. optimum/rbln/{transformers/generation → diffusers/models/autoencoders}/__init__.py +1 -2
  7. optimum/rbln/diffusers/models/{autoencoder_kl.py → autoencoders/autoencoder_kl.py} +73 -61
  8. optimum/rbln/diffusers/models/autoencoders/vae.py +83 -0
  9. optimum/rbln/diffusers/models/controlnet.py +54 -14
  10. optimum/rbln/diffusers/models/transformers/__init__.py +24 -0
  11. optimum/rbln/diffusers/models/transformers/transformer_sd3.py +203 -0
  12. optimum/rbln/diffusers/models/unets/__init__.py +24 -0
  13. optimum/rbln/diffusers/models/{unet_2d_condition.py → unets/unet_2d_condition.py} +82 -22
  14. optimum/rbln/diffusers/pipelines/__init__.py +23 -2
  15. optimum/rbln/diffusers/pipelines/controlnet/multicontrolnet.py +13 -33
  16. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet.py +17 -2
  17. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +18 -2
  18. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +18 -2
  19. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +18 -2
  20. optimum/rbln/diffusers/pipelines/stable_diffusion/__init__.py +1 -0
  21. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +2 -2
  22. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +1 -13
  23. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +31 -0
  24. optimum/rbln/diffusers/pipelines/stable_diffusion_3/__init__.py +26 -0
  25. optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +31 -0
  26. optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +31 -0
  27. optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +31 -0
  28. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/__init__.py +24 -0
  29. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +15 -8
  30. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +15 -8
  31. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +31 -0
  32. optimum/rbln/modeling.py +238 -0
  33. optimum/rbln/modeling_base.py +186 -760
  34. optimum/rbln/modeling_config.py +31 -7
  35. optimum/rbln/ops/__init__.py +26 -0
  36. optimum/rbln/ops/attn.py +221 -0
  37. optimum/rbln/ops/flash_attn.py +70 -0
  38. optimum/rbln/ops/kv_cache_update.py +69 -0
  39. optimum/rbln/transformers/__init__.py +20 -2
  40. optimum/rbln/{modeling_alias.py → transformers/modeling_alias.py} +5 -1
  41. optimum/rbln/transformers/modeling_generic.py +385 -0
  42. optimum/rbln/transformers/models/auto/__init__.py +23 -0
  43. optimum/rbln/transformers/models/auto/auto_factory.py +117 -23
  44. optimum/rbln/transformers/models/auto/modeling_auto.py +36 -12
  45. optimum/rbln/transformers/models/bart/__init__.py +0 -1
  46. optimum/rbln/transformers/models/bart/bart_architecture.py +107 -464
  47. optimum/rbln/transformers/models/bart/modeling_bart.py +10 -9
  48. optimum/rbln/transformers/models/bert/modeling_bert.py +3 -6
  49. optimum/rbln/transformers/models/clip/modeling_clip.py +8 -25
  50. optimum/rbln/transformers/models/decoderonly/__init__.py +0 -10
  51. optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py +775 -514
  52. optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py +128 -260
  53. optimum/rbln/transformers/models/dpt/modeling_dpt.py +1 -1
  54. optimum/rbln/transformers/models/exaone/exaone_architecture.py +60 -45
  55. optimum/rbln/transformers/models/exaone/modeling_exaone.py +4 -2
  56. optimum/rbln/transformers/models/gemma/gemma_architecture.py +33 -104
  57. optimum/rbln/transformers/models/gpt2/gpt2_architecture.py +50 -238
  58. optimum/rbln/transformers/models/gpt2/modeling_gpt2.py +3 -2
  59. optimum/rbln/transformers/models/llama/llama_architecture.py +0 -1
  60. optimum/rbln/transformers/models/llava_next/modeling_llava_next.py +3 -75
  61. optimum/rbln/transformers/models/midm/midm_architecture.py +84 -238
  62. optimum/rbln/transformers/models/midm/modeling_midm.py +5 -6
  63. optimum/rbln/transformers/models/mistral/mistral_architecture.py +0 -1
  64. optimum/rbln/transformers/models/phi/phi_architecture.py +60 -261
  65. optimum/rbln/transformers/models/qwen2/qwen2_architecture.py +0 -1
  66. optimum/rbln/transformers/models/seq2seq/modeling_seq2seq.py +58 -103
  67. optimum/rbln/transformers/models/seq2seq/seq2seq_architecture.py +498 -0
  68. optimum/rbln/transformers/models/t5/__init__.py +0 -1
  69. optimum/rbln/transformers/models/t5/modeling_t5.py +106 -5
  70. optimum/rbln/transformers/models/t5/t5_architecture.py +106 -448
  71. optimum/rbln/transformers/models/wav2vec2/modeling_wav2vec2.py +1 -1
  72. optimum/rbln/transformers/models/whisper/generation_whisper.py +42 -0
  73. optimum/rbln/transformers/models/whisper/modeling_whisper.py +78 -55
  74. optimum/rbln/transformers/models/whisper/whisper_architecture.py +219 -312
  75. optimum/rbln/transformers/models/xlm_roberta/modeling_xlm_roberta.py +3 -35
  76. optimum/rbln/transformers/utils/rbln_quantization.py +120 -4
  77. optimum/rbln/utils/decorator_utils.py +51 -11
  78. optimum/rbln/utils/hub.py +131 -0
  79. optimum/rbln/utils/import_utils.py +22 -1
  80. optimum/rbln/utils/logging.py +37 -0
  81. optimum/rbln/utils/model_utils.py +52 -0
  82. optimum/rbln/utils/runtime_utils.py +10 -4
  83. optimum/rbln/utils/save_utils.py +17 -0
  84. optimum/rbln/utils/submodule.py +137 -0
  85. optimum_rbln-0.2.0.dist-info/METADATA +117 -0
  86. optimum_rbln-0.2.0.dist-info/RECORD +114 -0
  87. {optimum_rbln-0.1.13.dist-info → optimum_rbln-0.2.0.dist-info}/WHEEL +1 -1
  88. optimum_rbln-0.2.0.dist-info/licenses/LICENSE +288 -0
  89. optimum/rbln/transformers/cache_utils.py +0 -107
  90. optimum/rbln/transformers/generation/streamers.py +0 -139
  91. optimum/rbln/transformers/generation/utils.py +0 -397
  92. optimum/rbln/transformers/models/exaone/hf_hub_cached/configuration_exaone.py +0 -181
  93. optimum/rbln/transformers/models/exaone/hf_hub_cached/modeling_exaone.py +0 -1725
  94. optimum/rbln/transformers/models/midm/hf_hub_cached/configuration_midm.py +0 -22
  95. optimum/rbln/transformers/models/midm/hf_hub_cached/midm_bitext_tokenization.py +0 -304
  96. optimum/rbln/transformers/models/midm/hf_hub_cached/modeling_midm.py +0 -1469
  97. optimum/rbln/transformers/models/midm/hf_hub_cached/rotary_position_embedding.py +0 -98
  98. optimum/rbln/utils/context.py +0 -58
  99. optimum/rbln/utils/timer_utils.py +0 -43
  100. optimum_rbln-0.1.13.dist-info/METADATA +0 -120
  101. optimum_rbln-0.1.13.dist-info/RECORD +0 -107
  102. optimum_rbln-0.1.13.dist-info/entry_points.txt +0 -4
  103. optimum_rbln-0.1.13.dist-info/licenses/LICENSE +0 -201
@@ -0,0 +1,385 @@
1
+ # Copyright 2024 Rebellions Inc.
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
+ # Portions of this software are licensed under the Apache License,
16
+ # Version 2.0. See the NOTICE file distributed with this work for
17
+ # additional information regarding copyright ownership.
18
+
19
+ # All other portions of this software, including proprietary code,
20
+ # are the intellectual property of Rebellions Inc. and may not be
21
+ # copied, modified, or distributed without prior written permission
22
+ # from Rebellions Inc.
23
+
24
+ """
25
+ This file defines generic base classes for various RBLN models,
26
+ such as Question Answering, Image Classification, Audio Classification,
27
+ Sequence Classification, and Masked Language Modeling. These classes
28
+ implement common functionalities and configurations to be used across
29
+ different model architectures.
30
+ """
31
+
32
+ import inspect
33
+ from typing import TYPE_CHECKING, Any, Dict, Optional, Union
34
+
35
+ import transformers
36
+ from transformers import (
37
+ AutoModelForAudioClassification,
38
+ AutoModelForImageClassification,
39
+ AutoModelForMaskedLM,
40
+ AutoModelForQuestionAnswering,
41
+ AutoModelForSequenceClassification,
42
+ PretrainedConfig,
43
+ )
44
+
45
+ from ..modeling import RBLNModel
46
+ from ..modeling_config import RBLNCompileConfig, RBLNConfig
47
+ from ..utils.logging import get_logger
48
+
49
+
50
+ if TYPE_CHECKING:
51
+ from transformers import (
52
+ AutoFeatureExtractor,
53
+ AutoProcessor,
54
+ AutoTokenizer,
55
+ )
56
+
57
+ logger = get_logger()
58
+
59
+
60
+ class RBLNModelForQuestionAnswering(RBLNModel):
61
+ auto_model_class = AutoModelForQuestionAnswering
62
+ rbln_model_input_names = ["input_ids", "attention_mask", "token_type_ids"]
63
+
64
+ @classmethod
65
+ def _get_rbln_config(
66
+ cls,
67
+ preprocessors: Optional[Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"]],
68
+ model_config: Optional["PretrainedConfig"] = None,
69
+ rbln_kwargs: Dict[str, Any] = {},
70
+ ) -> RBLNConfig:
71
+ rbln_max_seq_len = rbln_kwargs.get("max_seq_len", None)
72
+ rbln_batch_size = rbln_kwargs.get("batch_size", None)
73
+ rbln_model_input_names = rbln_kwargs.get("model_input_names", None)
74
+
75
+ if rbln_max_seq_len is None:
76
+ for tokenizer in preprocessors:
77
+ if hasattr(tokenizer, "model_max_length"):
78
+ rbln_max_seq_len = tokenizer.model_max_length
79
+ break
80
+ if rbln_max_seq_len is None:
81
+ raise ValueError("`rbln_max_seq_len` should be specified!")
82
+
83
+ if rbln_batch_size is None:
84
+ rbln_batch_size = 1
85
+
86
+ if rbln_model_input_names is None:
87
+ for tokenizer in preprocessors:
88
+ if hasattr(tokenizer, "model_input_names"):
89
+ rbln_model_input_names = tokenizer.model_input_names
90
+ break
91
+ if rbln_model_input_names is None and hasattr(cls, "rbln_model_input_names"):
92
+ rbln_model_input_names = cls.rbln_model_input_names
93
+ elif rbln_model_input_names is None and hasattr(cls, "rbln_model_input_names") is False:
94
+ input_names_order = inspect.signature(cls.hf_class.forward).parameters.keys()
95
+ raise ValueError(
96
+ "Specify the model input names obtained by the tokenizer via `rbln_model_input_names`, "
97
+ f"and be sure to make the order of the inputs same as QuestionAnswering forward() arguments like ({list(input_names_order)})"
98
+ )
99
+
100
+ input_info = [
101
+ (model_input_name, [rbln_batch_size, rbln_max_seq_len], "int64")
102
+ for model_input_name in rbln_model_input_names
103
+ ]
104
+
105
+ rbln_compile_config = RBLNCompileConfig(input_info=input_info)
106
+ rbln_config = RBLNConfig(
107
+ rbln_cls=cls.__name__,
108
+ compile_cfgs=[rbln_compile_config],
109
+ rbln_kwargs=rbln_kwargs,
110
+ )
111
+ rbln_config.model_cfg.update({"max_seq_len": rbln_max_seq_len})
112
+ return rbln_config
113
+
114
+
115
+ class RBLNModelForImageClassification(RBLNModel):
116
+ """
117
+ This is a generic model class that will be instantiated as one of the model classes of the library (with a image classification head) when created with the from_pretrained() class method
118
+ """
119
+
120
+ auto_model_class = AutoModelForImageClassification
121
+
122
+ @classmethod
123
+ def _get_rbln_config(
124
+ cls,
125
+ preprocessors: Optional[Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"]],
126
+ model_config: Optional["PretrainedConfig"] = None,
127
+ rbln_kwargs: Dict[str, Any] = {},
128
+ ) -> RBLNConfig:
129
+ rbln_image_size = rbln_kwargs.get("image_size", None)
130
+ rbln_batch_size = rbln_kwargs.get("batch_size", None)
131
+
132
+ if rbln_image_size is None:
133
+ for processor in preprocessors:
134
+ if hasattr(processor, "size"):
135
+ if all(required_key in processor.size.keys() for required_key in ["height", "width"]):
136
+ rbln_image_size = (processor.size["height"], processor.size["width"])
137
+ elif "shortest_edge" in processor.size.keys():
138
+ rbln_image_size = (processor.size["shortest_edge"], processor.size["shortest_edge"])
139
+ elif "longest_edge" in processor.size.keys():
140
+ rbln_image_size = (processor.size["longest_edge"], processor.size["longest_edge"])
141
+ break
142
+
143
+ if rbln_image_size is None:
144
+ rbln_image_size = model_config.image_size
145
+
146
+ if rbln_image_size is None:
147
+ raise ValueError("`rbln_image_size` should be specified!")
148
+
149
+ if rbln_batch_size is None:
150
+ rbln_batch_size = 1
151
+
152
+ if isinstance(rbln_image_size, int):
153
+ rbln_image_height, rbln_image_width = rbln_image_size, rbln_image_size
154
+ elif isinstance(rbln_image_size, (list, tuple)):
155
+ rbln_image_height, rbln_image_width = rbln_image_size[0], rbln_image_size[1]
156
+ elif isinstance(rbln_image_size, dict):
157
+ rbln_image_height, rbln_image_width = rbln_image_size["height"], rbln_image_size["width"]
158
+ else:
159
+ raise ValueError(
160
+ "`rbln_image_size` should be `int` (ex. 224), `tuple` (ex. 224, 224), `dict` (ex. {'height': 224, 'width': 224}) format"
161
+ )
162
+
163
+ input_info = [
164
+ (
165
+ "pixel_values",
166
+ [rbln_batch_size, 3, rbln_image_height, rbln_image_width],
167
+ "float32",
168
+ )
169
+ ]
170
+
171
+ rbln_compile_config = RBLNCompileConfig(input_info=input_info)
172
+ return RBLNConfig(rbln_cls=cls.__name__, compile_cfgs=[rbln_compile_config], rbln_kwargs=rbln_kwargs)
173
+
174
+
175
+ class RBLNModelForAudioClassification(RBLNModel):
176
+ """
177
+ This is a generic model class that will be instantiated as one of the model classes of the library (with a audio classification head) when created with the from_pretrained() class method
178
+ This model inherits from [`RBLNModel`]. Check the superclass documentation for the generic methods the library implements for all its models.
179
+
180
+ A class to convert and run pre-trained transformers based AudioClassification models on RBLN devices.
181
+ It implements the methods to convert a pre-trained transformers AudioClassification model into a RBLN transformer model by:
182
+ - transferring the checkpoint weights of the original into an optimized RBLN graph,
183
+ - compiling the resulting graph using the RBLN compiler.
184
+
185
+ Currently, this model class only supports the 'AST' model from the transformers library. Future updates may include support for additional model types.
186
+ """
187
+
188
+ auto_model_class = AutoModelForAudioClassification
189
+
190
+ @classmethod
191
+ def _get_rbln_config(
192
+ cls,
193
+ preprocessors: "AutoFeatureExtractor",
194
+ model_config: "PretrainedConfig",
195
+ rbln_kwargs: Dict[str, Any] = {},
196
+ ) -> RBLNConfig:
197
+ rbln_batch_size = rbln_kwargs.get("batch_size", None)
198
+ rbln_max_length = rbln_kwargs.get("max_length", None)
199
+ rbln_num_mel_bins = rbln_kwargs.get("num_mel_bins", None)
200
+
201
+ if rbln_batch_size is None:
202
+ rbln_batch_size = 1
203
+
204
+ if rbln_num_mel_bins is None:
205
+ rbln_num_mel_bins = getattr(model_config, "num_mel_bins", None)
206
+ if rbln_num_mel_bins is None:
207
+ for feature_extractor in preprocessors:
208
+ if hasattr(feature_extractor, "num_mel_bins"):
209
+ rbln_num_mel_bins = feature_extractor.num_mel_bins
210
+ break
211
+
212
+ if rbln_num_mel_bins is None:
213
+ raise ValueError("`rbln_num_mel_bins` should be specified!")
214
+
215
+ if rbln_max_length is None:
216
+ rbln_max_length = getattr(model_config, "max_length", None)
217
+ for feature_extractor in preprocessors:
218
+ if hasattr(feature_extractor, "max_length"):
219
+ rbln_max_length = feature_extractor.max_length
220
+ break
221
+
222
+ if rbln_max_length is None:
223
+ raise ValueError("`rbln_max_length` should be specified!")
224
+
225
+ input_info = [
226
+ (
227
+ "input_values",
228
+ [rbln_batch_size, rbln_max_length, rbln_num_mel_bins],
229
+ "float32",
230
+ ),
231
+ ]
232
+
233
+ rbln_compile_config = RBLNCompileConfig(input_info=input_info)
234
+ rbln_config = RBLNConfig(
235
+ rbln_cls=cls.__name__,
236
+ compile_cfgs=[rbln_compile_config],
237
+ rbln_kwargs=rbln_kwargs,
238
+ )
239
+ rbln_config.model_cfg.update(
240
+ {
241
+ "batch_size": rbln_batch_size,
242
+ "max_length": rbln_max_length,
243
+ "num_mel_bins": rbln_num_mel_bins,
244
+ }
245
+ )
246
+ return rbln_config
247
+
248
+
249
+ class RBLNModelForSequenceClassification(RBLNModel):
250
+ """
251
+ This is a generic model class that will be instantiated as one of the model classes of the library (with a sequence classification head) when created with the from_pretrained() class method
252
+ This model inherits from [`RBLNModel`]. Check the superclass documentation for the generic methods the library implements for all its models.
253
+
254
+ A class to convert and run pre-trained transformers based SequenceClassification models on RBLN devices.
255
+ It implements the methods to convert a pre-trained transformers SequenceClassification model into a RBLN transformer model by:
256
+ - transferring the checkpoint weights of the original into an optimized RBLN graph,
257
+ - compiling the resulting graph using the RBLN compiler.
258
+
259
+ Currently, this model class supports the 'XLMRoberta' and 'Roberta' model from the transformers library. Future updates may include support for additional model types.
260
+ """
261
+
262
+ auto_model_class = AutoModelForSequenceClassification
263
+
264
+ @classmethod
265
+ def _get_rbln_config(
266
+ cls,
267
+ preprocessors: Optional[Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"]],
268
+ model_config: Optional["PretrainedConfig"] = None,
269
+ rbln_kwargs: Dict[str, Any] = {},
270
+ ) -> RBLNConfig:
271
+ rbln_max_seq_len = rbln_kwargs.get("max_seq_len", None)
272
+ rbln_model_input_names = rbln_kwargs.get("model_input_names", None)
273
+ rbln_batch_size = rbln_kwargs.get("batch_size", None)
274
+
275
+ max_position_embeddings = getattr(model_config, "n_positions", None) or getattr(
276
+ model_config, "max_position_embeddings", None
277
+ )
278
+
279
+ if rbln_max_seq_len is None:
280
+ rbln_max_seq_len = max_position_embeddings
281
+ if rbln_max_seq_len is None:
282
+ for tokenizer in preprocessors:
283
+ if hasattr(tokenizer, "model_max_length"):
284
+ rbln_max_seq_len = tokenizer.model_max_length
285
+ break
286
+ if rbln_max_seq_len is None:
287
+ raise ValueError("`rbln_max_seq_len` should be specified!")
288
+
289
+ if max_position_embeddings is not None and rbln_max_seq_len > max_position_embeddings:
290
+ raise ValueError("`rbln_enc_max_seq_len` should be less or equal than max_position_embeddings!")
291
+
292
+ if rbln_model_input_names is None:
293
+ for tokenizer in preprocessors:
294
+ if hasattr(tokenizer, "model_input_names"):
295
+ rbln_model_input_names = tokenizer.model_input_names
296
+ break
297
+ if rbln_model_input_names is None and hasattr(cls, "rbln_model_input_names"):
298
+ rbln_model_input_names = cls.rbln_model_input_names
299
+ elif rbln_model_input_names is None and hasattr(cls, "rbln_model_input_names") is False:
300
+ original_model_class = getattr(transformers, model_config.architectures[0])
301
+ input_names_order = inspect.signature(original_model_class.forward).parameters.keys()
302
+ raise ValueError(
303
+ "Specify the model input names obtained by the tokenizer via `rbln_model_input_names`, "
304
+ f"and be sure to make the order of the inputs same as SequenceClassification forward() arguments like ({list(input_names_order)})"
305
+ )
306
+
307
+ if rbln_batch_size is None:
308
+ rbln_batch_size = 1
309
+
310
+ input_info = [
311
+ (model_input_name, [rbln_batch_size, rbln_max_seq_len], "int64")
312
+ for model_input_name in rbln_model_input_names
313
+ ]
314
+
315
+ rbln_compile_config = RBLNCompileConfig(input_info=input_info)
316
+ rbln_config = RBLNConfig(
317
+ rbln_cls=cls.__name__,
318
+ compile_cfgs=[rbln_compile_config],
319
+ rbln_kwargs=rbln_kwargs,
320
+ )
321
+ rbln_config.model_cfg.update({"max_seq_len": rbln_max_seq_len})
322
+ return rbln_config
323
+
324
+
325
+ class RBLNModelForMaskedLM(RBLNModel):
326
+ auto_model_class = AutoModelForMaskedLM
327
+
328
+ @classmethod
329
+ def _get_rbln_config(
330
+ cls,
331
+ preprocessors: Optional[Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"]],
332
+ model_config: Optional["PretrainedConfig"] = None,
333
+ rbln_kwargs: Dict[str, Any] = {},
334
+ ) -> RBLNConfig:
335
+ rbln_max_seq_len = rbln_kwargs.get("max_seq_len", None)
336
+ rbln_model_input_names = rbln_kwargs.get("model_input_names", None)
337
+ rbln_batch_size = rbln_kwargs.get("batch_size", None)
338
+
339
+ max_position_embeddings = getattr(model_config, "n_positions", None) or getattr(
340
+ model_config, "max_position_embeddings", None
341
+ )
342
+
343
+ if rbln_max_seq_len is None:
344
+ rbln_max_seq_len = max_position_embeddings
345
+ if rbln_max_seq_len is None:
346
+ for tokenizer in preprocessors:
347
+ if hasattr(tokenizer, "model_max_length"):
348
+ rbln_max_seq_len = tokenizer.model_max_length
349
+ break
350
+ if rbln_max_seq_len is None:
351
+ raise ValueError("`rbln_max_seq_len` should be specified!")
352
+
353
+ if max_position_embeddings is not None and rbln_max_seq_len > max_position_embeddings:
354
+ raise ValueError("`rbln_enc_max_seq_len` should be less or equal than max_position_embeddings!")
355
+
356
+ if rbln_model_input_names is None:
357
+ for tokenizer in preprocessors:
358
+ if hasattr(tokenizer, "model_input_names"):
359
+ rbln_model_input_names = tokenizer.model_input_names
360
+ break
361
+ if rbln_model_input_names is None and hasattr(cls, "rbln_model_input_names"):
362
+ rbln_model_input_names = cls.rbln_model_input_names
363
+ elif rbln_model_input_names is None and hasattr(cls, "rbln_model_input_names") is False:
364
+ input_names_order = inspect.signature(cls.hf_class.forward).parameters.keys()
365
+ raise ValueError(
366
+ "Specify the model input names obtained by the tokenizer via `rbln_model_input_names`, "
367
+ f"and be sure to make the order of the inputs same as MaskedLM forward() arguments like ({list(input_names_order)})"
368
+ )
369
+
370
+ if rbln_batch_size is None:
371
+ rbln_batch_size = 1
372
+
373
+ input_info = [
374
+ (model_input_name, [rbln_batch_size, rbln_max_seq_len], "int64")
375
+ for model_input_name in rbln_model_input_names
376
+ ]
377
+
378
+ rbln_compile_config = RBLNCompileConfig(input_info=input_info)
379
+ rbln_config = RBLNConfig(
380
+ rbln_cls=cls.__name__,
381
+ compile_cfgs=[rbln_compile_config],
382
+ rbln_kwargs=rbln_kwargs,
383
+ )
384
+ rbln_config.model_cfg.update({"max_seq_len": rbln_max_seq_len})
385
+ return rbln_config
@@ -1,3 +1,26 @@
1
+ # Copyright 2024 Rebellions Inc.
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
+ # Portions of this software are licensed under the Apache License,
16
+ # Version 2.0. See the NOTICE file distributed with this work for
17
+ # additional information regarding copyright ownership.
18
+
19
+ # All other portions of this software, including proprietary code,
20
+ # are the intellectual property of Rebellions Inc. and may not be
21
+ # copied, modified, or distributed without prior written permission
22
+ # from Rebellions Inc.
23
+
1
24
  from .modeling_auto import (
2
25
  RBLNAutoModel,
3
26
  RBLNAutoModelForAudioClassification,
@@ -22,8 +22,16 @@
22
22
  # from Rebellions Inc.
23
23
 
24
24
  import importlib
25
+ import inspect
26
+ import warnings
25
27
 
26
- from transformers import AutoConfig
28
+ from transformers import AutoConfig, PretrainedConfig
29
+ from transformers.dynamic_module_utils import get_class_from_dynamic_module
30
+ from transformers.models.auto.auto_factory import _get_model_class
31
+
32
+ from optimum.rbln.modeling_base import RBLNBaseModel
33
+ from optimum.rbln.modeling_config import RBLNConfig
34
+ from optimum.rbln.utils.model_utils import convert_hf_to_rbln_model_name, convert_rbln_to_hf_model_name
27
35
 
28
36
 
29
37
  class _BaseAutoModelClass:
@@ -33,46 +41,132 @@ class _BaseAutoModelClass:
33
41
  def __init__(self, *args, **kwargs):
34
42
  raise EnvironmentError(
35
43
  f"{self.__class__.__name__} is designed to be instantiated "
36
- f"using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)` or "
37
- f"`{self.__class__.__name__}.from_config(config)` methods."
44
+ f"using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)`"
38
45
  )
39
46
 
40
47
  @classmethod
41
48
  def get_rbln_cls(
42
49
  cls,
43
- model_id,
50
+ pretrained_model_name_or_path,
44
51
  *args,
52
+ export=True,
45
53
  **kwargs,
46
54
  ):
47
- # kwargs.update({"return_unused_kwargs": True})
48
- config = AutoConfig.from_pretrained(model_id, return_unused_kwargs=True, **kwargs)[0]
49
-
50
- if len(config.architectures) > 1:
51
- raise ValueError(
52
- f"Model with ID '{model_id}' has multiple architectures defined in the configuration: "
53
- f"{config.architectures}. `_BaseAutoModelClass` require exactly one architecture. "
54
- )
55
-
56
- architecture_name = config.architectures[0]
57
- if architecture_name not in cls._model_mapping.values():
58
- raise ValueError(
59
- f"The 'RBLN{architecture_name}' architecture is not supported by `{cls.__name__}.from_pretrained()`."
60
- "Please use the appropriate class's `from_pretrained()` method to load this model."
61
- )
62
-
63
- rbln_class_name = "RBLN" + architecture_name
64
- module = importlib.import_module("optimum.rbln")
55
+ """
56
+ Determine the appropriate RBLN model class based on the given model ID and configuration.
57
+
58
+ Args:
59
+ pretrained_model_name_or_path (str): Identifier or path to the pretrained model.
60
+ export (bool): Whether to infer the class based on Hugging Face (HF) architecture.
61
+ kwargs: Additional arguments for configuration and loading.
62
+
63
+ Returns:
64
+ RBLNBaseModel: The corresponding RBLN model class.
65
+ """
66
+ if export:
67
+ hf_model_class = cls.infer_hf_model_class(pretrained_model_name_or_path, **kwargs)
68
+ rbln_class_name = convert_hf_to_rbln_model_name(hf_model_class.__name__)
69
+ else:
70
+ rbln_class_name = cls.get_rbln_model_class_name(pretrained_model_name_or_path, **kwargs)
71
+
72
+ if convert_rbln_to_hf_model_name(rbln_class_name) not in cls._model_mapping_names.values():
73
+ raise ValueError(
74
+ f"The architecture '{rbln_class_name}' is not supported by the `{cls.__name__}.from_pretrained()` method. "
75
+ "Please use the `from_pretrained()` method of the appropriate class to load this model, "
76
+ f"or directly use '{rbln_class_name}.from_pretrained()`."
77
+ )
65
78
 
66
79
  try:
80
+ module = importlib.import_module("optimum.rbln")
67
81
  rbln_cls = getattr(module, rbln_class_name)
68
82
  except AttributeError as e:
69
83
  raise AttributeError(
70
- f"Class '{rbln_class_name}' not found in 'optimum.rbln' module for model ID '{model_id}'. "
84
+ f"Class '{rbln_class_name}' not found in 'optimum.rbln' module for model ID '{pretrained_model_name_or_path}'. "
71
85
  "Ensure that the class name is correctly mapped and available in the 'optimum.rbln' module."
72
86
  ) from e
73
87
 
74
88
  return rbln_cls
75
89
 
90
+ @classmethod
91
+ def infer_hf_model_class(
92
+ cls,
93
+ pretrained_model_name_or_path,
94
+ *args,
95
+ **kwargs,
96
+ ):
97
+ """
98
+ Infer the Hugging Face model class based on the configuration or model name.
99
+
100
+ Args:
101
+ pretrained_model_name_or_path (str): Identifier or path to the pretrained model.
102
+ kwargs: Additional arguments for configuration and loading.
103
+
104
+ Returns:
105
+ PretrainedModel: The inferred Hugging Face model class.
106
+ """
107
+
108
+ # Try to load configuration if provided or retrieve it from the model ID
109
+ config = kwargs.pop("config", None)
110
+ kwargs.update({"trust_remote_code": True})
111
+ kwargs["_from_auto"] = True
112
+
113
+ # Load configuration if not already provided
114
+ if not isinstance(config, PretrainedConfig):
115
+ config, kwargs = AutoConfig.from_pretrained(
116
+ pretrained_model_name_or_path,
117
+ return_unused_kwargs=True,
118
+ **kwargs,
119
+ )
120
+
121
+ # Get hf_model_class from Config
122
+ has_remote_code = (
123
+ hasattr(config, "auto_map") and convert_rbln_to_hf_model_name(cls.__name__) in config.auto_map
124
+ )
125
+ if has_remote_code:
126
+ class_ref = config.auto_map[convert_rbln_to_hf_model_name(cls.__name__)]
127
+ model_class = get_class_from_dynamic_module(class_ref, pretrained_model_name_or_path, **kwargs)
128
+ elif type(config) in cls._model_mapping.keys():
129
+ model_class = _get_model_class(config, cls._model_mapping)
130
+ else:
131
+ raise ValueError(
132
+ f"Unrecognized configuration class {config.__class__} for this kind of AutoModel: {cls.__name__}.\n"
133
+ f"Model type should be one of {', '.join(c.__name__ for c in cls._model_mapping.keys())}."
134
+ )
135
+
136
+ if model_class.__name__ != config.architectures[0]:
137
+ warnings.warn(
138
+ f"`{cls.__name__}.from_pretrained()` is invoking `{convert_hf_to_rbln_model_name(model_class.__name__)}.from_pretrained()`, which does not match the "
139
+ f"expected architecture `RBLN{config.architectures[0]}` from config. This mismatch could cause some operations to not be properly loaded "
140
+ f"from the checkpoint, leading to potential unintended behavior. If this is not intentional, consider calling the "
141
+ f"`from_pretrained()` method directly from the `RBLN{config.architectures[0]}` class instead.",
142
+ UserWarning,
143
+ )
144
+
145
+ return model_class
146
+
147
+ @classmethod
148
+ def get_rbln_model_class_name(cls, pretrained_model_name_or_path, **kwargs):
149
+ """
150
+ Retrieve the path to the compiled model directory for a given RBLN model.
151
+
152
+ Args:
153
+ pretrained_model_name_or_path (str): Identifier of the model.
154
+ kwargs: Additional arguments that match the parameters of `_load_compiled_model_dir`.
155
+
156
+ Returns:
157
+ str: Path to the compiled model directory.
158
+ """
159
+ sig = inspect.signature(RBLNBaseModel._load_compiled_model_dir)
160
+ valid_params = sig.parameters.keys()
161
+ filtered_kwargs = {k: v for k, v in kwargs.items() if k in valid_params}
162
+
163
+ model_path_subfolder = RBLNBaseModel._load_compiled_model_dir(
164
+ model_id=pretrained_model_name_or_path, **filtered_kwargs
165
+ )
166
+ rbln_config = RBLNConfig.load(model_path_subfolder)
167
+
168
+ return rbln_config.meta["cls"]
169
+
76
170
  @classmethod
77
171
  def from_pretrained(
78
172
  cls,