optimum-rbln 0.1.15__py3-none-any.whl → 0.2.1a0__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 (80) hide show
  1. optimum/rbln/__init__.py +26 -33
  2. optimum/rbln/__version__.py +2 -2
  3. optimum/rbln/diffusers/__init__.py +4 -0
  4. optimum/rbln/{modeling_diffusers.py → diffusers/modeling_diffusers.py} +66 -24
  5. optimum/rbln/diffusers/models/__init__.py +2 -0
  6. optimum/rbln/diffusers/models/autoencoders/autoencoder_kl.py +38 -12
  7. optimum/rbln/diffusers/models/autoencoders/vae.py +0 -1
  8. optimum/rbln/diffusers/models/controlnet.py +1 -1
  9. optimum/rbln/diffusers/models/transformers/transformer_sd3.py +1 -1
  10. optimum/rbln/diffusers/models/unets/unet_2d_condition.py +5 -7
  11. optimum/rbln/diffusers/pipelines/__init__.py +1 -0
  12. optimum/rbln/diffusers/pipelines/controlnet/multicontrolnet.py +8 -7
  13. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet.py +17 -2
  14. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +17 -2
  15. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +17 -2
  16. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +17 -2
  17. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +1 -2
  18. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +1 -2
  19. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +1 -2
  20. optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +1 -2
  21. optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +1 -2
  22. optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +1 -2
  23. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/__init__.py +23 -0
  24. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +1 -2
  25. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +1 -2
  26. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +1 -2
  27. optimum/rbln/modeling.py +13 -347
  28. optimum/rbln/modeling_base.py +24 -4
  29. optimum/rbln/modeling_config.py +31 -7
  30. optimum/rbln/ops/__init__.py +26 -0
  31. optimum/rbln/ops/attn.py +221 -0
  32. optimum/rbln/ops/flash_attn.py +70 -0
  33. optimum/rbln/ops/kv_cache_update.py +69 -0
  34. optimum/rbln/transformers/__init__.py +20 -0
  35. optimum/rbln/{modeling_alias.py → transformers/modeling_alias.py} +5 -1
  36. optimum/rbln/transformers/modeling_generic.py +385 -0
  37. optimum/rbln/transformers/models/auto/__init__.py +23 -0
  38. optimum/rbln/transformers/models/auto/modeling_auto.py +0 -1
  39. optimum/rbln/transformers/models/bart/__init__.py +0 -1
  40. optimum/rbln/transformers/models/bart/bart_architecture.py +107 -464
  41. optimum/rbln/transformers/models/bart/modeling_bart.py +8 -4
  42. optimum/rbln/transformers/models/clip/modeling_clip.py +1 -1
  43. optimum/rbln/transformers/models/decoderonly/__init__.py +0 -7
  44. optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py +329 -328
  45. optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py +92 -107
  46. optimum/rbln/transformers/models/exaone/exaone_architecture.py +2 -3
  47. optimum/rbln/transformers/models/gemma/gemma_architecture.py +1 -1
  48. optimum/rbln/transformers/models/gpt2/gpt2_architecture.py +10 -10
  49. optimum/rbln/transformers/models/gpt2/modeling_gpt2.py +1 -1
  50. optimum/rbln/transformers/models/llama/llama_architecture.py +0 -1
  51. optimum/rbln/transformers/models/llava_next/modeling_llava_next.py +1 -0
  52. optimum/rbln/transformers/models/midm/midm_architecture.py +11 -11
  53. optimum/rbln/transformers/models/midm/modeling_midm.py +0 -1
  54. optimum/rbln/transformers/models/mistral/mistral_architecture.py +0 -1
  55. optimum/rbln/transformers/models/phi/phi_architecture.py +2 -3
  56. optimum/rbln/transformers/models/qwen2/qwen2_architecture.py +0 -1
  57. optimum/rbln/transformers/models/seq2seq/modeling_seq2seq.py +57 -57
  58. optimum/rbln/transformers/models/seq2seq/seq2seq_architecture.py +498 -0
  59. optimum/rbln/transformers/models/t5/__init__.py +0 -1
  60. optimum/rbln/transformers/models/t5/modeling_t5.py +5 -2
  61. optimum/rbln/transformers/models/t5/t5_architecture.py +106 -448
  62. optimum/rbln/transformers/models/whisper/generation_whisper.py +42 -0
  63. optimum/rbln/transformers/models/whisper/modeling_whisper.py +77 -54
  64. optimum/rbln/transformers/models/whisper/whisper_architecture.py +219 -312
  65. optimum/rbln/transformers/utils/rbln_quantization.py +1 -2
  66. optimum/rbln/utils/decorator_utils.py +51 -15
  67. optimum/rbln/utils/import_utils.py +8 -1
  68. optimum/rbln/utils/logging.py +38 -1
  69. optimum/rbln/utils/model_utils.py +0 -1
  70. optimum/rbln/utils/runtime_utils.py +9 -3
  71. optimum/rbln/utils/save_utils.py +17 -0
  72. optimum/rbln/utils/submodule.py +23 -0
  73. optimum_rbln-0.2.1a0.dist-info/METADATA +121 -0
  74. {optimum_rbln-0.1.15.dist-info → optimum_rbln-0.2.1a0.dist-info}/RECORD +76 -72
  75. optimum_rbln-0.2.1a0.dist-info/licenses/LICENSE +288 -0
  76. optimum/rbln/transformers/cache_utils.py +0 -107
  77. optimum/rbln/utils/timer_utils.py +0 -43
  78. optimum_rbln-0.1.15.dist-info/METADATA +0 -106
  79. optimum_rbln-0.1.15.dist-info/licenses/LICENSE +0 -201
  80. {optimum_rbln-0.1.15.dist-info → optimum_rbln-0.2.1a0.dist-info}/WHEEL +0 -0
@@ -1,3 +1,17 @@
1
+ # Copyright 2024 The HuggingFace Team. 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
+
1
15
  # Copyright 2024 Rebellions Inc.
2
16
 
3
17
  # Licensed under the Apache License, Version 2.0 (the "License");
@@ -20,7 +34,6 @@
20
34
  # are the intellectual property of Rebellions Inc. and may not be
21
35
  # copied, modified, or distributed without prior written permission
22
36
  # from Rebellions Inc.
23
- """RBLNStableDiffusionXLPipeline class for inference of diffusion models on rbln devices."""
24
37
 
25
38
  from typing import Any, Callable, Dict, List, Optional, Tuple, Union
26
39
 
@@ -32,8 +45,8 @@ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffus
32
45
  from diffusers.utils import deprecate, logging
33
46
  from diffusers.utils.torch_utils import is_compiled_module
34
47
 
35
- from ....modeling_diffusers import RBLNDiffusionMixin
36
48
  from ....utils.decorator_utils import remove_compile_time_kwargs
49
+ from ...modeling_diffusers import RBLNDiffusionMixin
37
50
  from ...models import RBLNControlNetModel
38
51
  from ...pipelines.controlnet.multicontrolnet import RBLNMultiControlNetModel
39
52
 
@@ -45,6 +58,7 @@ class RBLNStableDiffusionXLControlNetImg2ImgPipeline(RBLNDiffusionMixin, StableD
45
58
  original_class = StableDiffusionXLControlNetImg2ImgPipeline
46
59
  _submodules = ["text_encoder", "text_encoder_2", "unet", "vae", "controlnet"]
47
60
 
61
+ # Almost copied from diffusers.pipelines.controlnet.pipeline_controlnet_sd_xl_img2img.py
48
62
  def check_inputs(
49
63
  self,
50
64
  prompt,
@@ -246,6 +260,7 @@ class RBLNStableDiffusionXLControlNetImg2ImgPipeline(RBLNDiffusionMixin, StableD
246
260
  f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
247
261
  )
248
262
 
263
+ # Almost copied from diffusers.pipelines.controlnet.pipeline_controlnet_sd_xl_img2img.py
249
264
  @torch.no_grad()
250
265
  @remove_compile_time_kwargs
251
266
  def __call__(
@@ -20,11 +20,10 @@
20
20
  # are the intellectual property of Rebellions Inc. and may not be
21
21
  # copied, modified, or distributed without prior written permission
22
22
  # from Rebellions Inc.
23
- """RBLNStableDiffusionPipeline class for inference of diffusion models on rbln devices."""
24
23
 
25
24
  from diffusers import StableDiffusionPipeline
26
25
 
27
- from ....modeling_diffusers import RBLNDiffusionMixin
26
+ from ...modeling_diffusers import RBLNDiffusionMixin
28
27
 
29
28
 
30
29
  class RBLNStableDiffusionPipeline(RBLNDiffusionMixin, StableDiffusionPipeline):
@@ -20,11 +20,10 @@
20
20
  # are the intellectual property of Rebellions Inc. and may not be
21
21
  # copied, modified, or distributed without prior written permission
22
22
  # from Rebellions Inc.
23
- """RBLNStableDiffusionPipeline class for inference of diffusion models on rbln devices."""
24
23
 
25
24
  from diffusers import StableDiffusionImg2ImgPipeline
26
25
 
27
- from ....modeling_diffusers import RBLNDiffusionMixin
26
+ from ...modeling_diffusers import RBLNDiffusionMixin
28
27
 
29
28
 
30
29
  class RBLNStableDiffusionImg2ImgPipeline(RBLNDiffusionMixin, StableDiffusionImg2ImgPipeline):
@@ -20,11 +20,10 @@
20
20
  # are the intellectual property of Rebellions Inc. and may not be
21
21
  # copied, modified, or distributed without prior written permission
22
22
  # from Rebellions Inc.
23
- """RBLNStableDiffusionInpaintPipeline class for inference of diffusion models on rbln devices."""
24
23
 
25
24
  from diffusers import StableDiffusionInpaintPipeline
26
25
 
27
- from ....modeling_diffusers import RBLNDiffusionMixin
26
+ from ...modeling_diffusers import RBLNDiffusionMixin
28
27
 
29
28
 
30
29
  class RBLNStableDiffusionInpaintPipeline(RBLNDiffusionMixin, StableDiffusionInpaintPipeline):
@@ -20,11 +20,10 @@
20
20
  # are the intellectual property of Rebellions Inc. and may not be
21
21
  # copied, modified, or distributed without prior written permission
22
22
  # from Rebellions Inc.
23
- """RBLNStableDiffusion3Pipeline class for inference of diffusion models on rbln devices."""
24
23
 
25
24
  from diffusers import StableDiffusion3Pipeline
26
25
 
27
- from ....modeling_diffusers import RBLNDiffusionMixin
26
+ from ...modeling_diffusers import RBLNDiffusionMixin
28
27
 
29
28
 
30
29
  class RBLNStableDiffusion3Pipeline(RBLNDiffusionMixin, StableDiffusion3Pipeline):
@@ -20,11 +20,10 @@
20
20
  # are the intellectual property of Rebellions Inc. and may not be
21
21
  # copied, modified, or distributed without prior written permission
22
22
  # from Rebellions Inc.
23
- """RBLNStableDiffusion3Img2ImgPipeline class for inference of diffusion models on rbln devices."""
24
23
 
25
24
  from diffusers import StableDiffusion3Img2ImgPipeline
26
25
 
27
- from ....modeling_diffusers import RBLNDiffusionMixin
26
+ from ...modeling_diffusers import RBLNDiffusionMixin
28
27
 
29
28
 
30
29
  class RBLNStableDiffusion3Img2ImgPipeline(RBLNDiffusionMixin, StableDiffusion3Img2ImgPipeline):
@@ -20,11 +20,10 @@
20
20
  # are the intellectual property of Rebellions Inc. and may not be
21
21
  # copied, modified, or distributed without prior written permission
22
22
  # from Rebellions Inc.
23
- """RBLNStableDiffusion3InpaintPipeline class for inference of diffusion models on rbln devices."""
24
23
 
25
24
  from diffusers import StableDiffusion3InpaintPipeline
26
25
 
27
- from ....modeling_diffusers import RBLNDiffusionMixin
26
+ from ...modeling_diffusers import RBLNDiffusionMixin
28
27
 
29
28
 
30
29
  class RBLNStableDiffusion3InpaintPipeline(RBLNDiffusionMixin, StableDiffusion3InpaintPipeline):
@@ -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 .pipeline_stable_diffusion_xl import RBLNStableDiffusionXLPipeline
2
25
  from .pipeline_stable_diffusion_xl_img2img import RBLNStableDiffusionXLImg2ImgPipeline
3
26
  from .pipeline_stable_diffusion_xl_inpaint import RBLNStableDiffusionXLInpaintPipeline
@@ -20,11 +20,10 @@
20
20
  # are the intellectual property of Rebellions Inc. and may not be
21
21
  # copied, modified, or distributed without prior written permission
22
22
  # from Rebellions Inc.
23
- """RBLNStableDiffusionXLPipeline class for inference of diffusion models on rbln devices."""
24
23
 
25
24
  from diffusers import StableDiffusionXLPipeline
26
25
 
27
- from ....modeling_diffusers import RBLNDiffusionMixin
26
+ from ...modeling_diffusers import RBLNDiffusionMixin
28
27
 
29
28
 
30
29
  class RBLNStableDiffusionXLPipeline(RBLNDiffusionMixin, StableDiffusionXLPipeline):
@@ -20,11 +20,10 @@
20
20
  # are the intellectual property of Rebellions Inc. and may not be
21
21
  # copied, modified, or distributed without prior written permission
22
22
  # from Rebellions Inc.
23
- """RBLNStableDiffusionXLPipeline class for inference of diffusion models on rbln devices."""
24
23
 
25
24
  from diffusers import StableDiffusionXLImg2ImgPipeline
26
25
 
27
- from ....modeling_diffusers import RBLNDiffusionMixin
26
+ from ...modeling_diffusers import RBLNDiffusionMixin
28
27
 
29
28
 
30
29
  class RBLNStableDiffusionXLImg2ImgPipeline(RBLNDiffusionMixin, StableDiffusionXLImg2ImgPipeline):
@@ -20,11 +20,10 @@
20
20
  # are the intellectual property of Rebellions Inc. and may not be
21
21
  # copied, modified, or distributed without prior written permission
22
22
  # from Rebellions Inc.
23
- """RBLNStableDiffusionXLInpaintPipeline class for inference of diffusion models on rbln devices."""
24
23
 
25
24
  from diffusers import StableDiffusionXLInpaintPipeline
26
25
 
27
- from ....modeling_diffusers import RBLNDiffusionMixin
26
+ from ...modeling_diffusers import RBLNDiffusionMixin
28
27
 
29
28
 
30
29
  class RBLNStableDiffusionXLInpaintPipeline(RBLNDiffusionMixin, StableDiffusionXLInpaintPipeline):
optimum/rbln/modeling.py CHANGED
@@ -20,7 +20,7 @@
20
20
  # are the intellectual property of Rebellions Inc. and may not be
21
21
  # copied, modified, or distributed without prior written permission
22
22
  # from Rebellions Inc.
23
- import inspect
23
+
24
24
  import logging
25
25
  from pathlib import Path
26
26
  from tempfile import TemporaryDirectory
@@ -28,29 +28,16 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
28
28
 
29
29
  import rebel
30
30
  import torch
31
- import transformers
32
31
  from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE
33
- from transformers import (
34
- AutoConfig,
35
- AutoModelForAudioClassification,
36
- AutoModelForImageClassification,
37
- AutoModelForMaskedLM,
38
- AutoModelForQuestionAnswering,
39
- AutoModelForSequenceClassification,
40
- PretrainedConfig,
41
- )
32
+ from transformers import AutoConfig, PretrainedConfig
42
33
 
43
34
  from .modeling_base import RBLNBaseModel
44
- from .modeling_config import DEFAULT_COMPILED_MODEL_NAME, RBLNCompileConfig, RBLNConfig, use_rbln_config
35
+ from .modeling_config import DEFAULT_COMPILED_MODEL_NAME, RBLNConfig, use_rbln_config
45
36
 
46
37
 
47
38
  if TYPE_CHECKING:
48
- from transformers import (
49
- AutoFeatureExtractor,
50
- AutoProcessor,
51
- AutoTokenizer,
52
- PreTrainedModel,
53
- )
39
+ from transformers import PreTrainedModel
40
+
54
41
 
55
42
  logger = logging.getLogger(__name__)
56
43
 
@@ -235,338 +222,17 @@ class RBLNModel(RBLNBaseModel):
235
222
  cls,
236
223
  compiled_models: List[rebel.RBLNCompiledModel],
237
224
  rbln_device_map: Dict[str, int],
225
+ activate_profiler: Optional[bool] = None,
238
226
  ) -> List[rebel.Runtime]:
227
+ if DEFAULT_COMPILED_MODEL_NAME not in rbln_device_map:
228
+ cls._raise_missing_compiled_file_error([DEFAULT_COMPILED_MODEL_NAME])
229
+
239
230
  device = rbln_device_map[DEFAULT_COMPILED_MODEL_NAME]
240
- return [compiled_model.create_runtime(tensor_type="pt", device=device) for compiled_model in compiled_models]
231
+ return [
232
+ compiled_model.create_runtime(tensor_type="pt", device=device, activate_profiler=activate_profiler)
233
+ for compiled_model in compiled_models
234
+ ]
241
235
 
242
236
  def forward(self, *args: List[torch.Tensor], **kwargs: Dict[str, torch.Tensor]):
243
237
  output = self.model[0](*args, **kwargs)
244
238
  return output
245
-
246
-
247
- class RBLNModelForQuestionAnswering(RBLNModel):
248
- auto_model_class = AutoModelForQuestionAnswering
249
- rbln_model_input_names = ["input_ids", "attention_mask", "token_type_ids"]
250
-
251
- @classmethod
252
- def _get_rbln_config(
253
- cls,
254
- preprocessors: Optional[Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"]],
255
- model_config: Optional["PretrainedConfig"] = None,
256
- rbln_kwargs: Dict[str, Any] = {},
257
- ) -> RBLNConfig:
258
- rbln_max_seq_len = rbln_kwargs.get("max_seq_len", None)
259
- rbln_batch_size = rbln_kwargs.get("batch_size", None)
260
- rbln_model_input_names = rbln_kwargs.get("model_input_names", None)
261
-
262
- if rbln_max_seq_len is None:
263
- for tokenizer in preprocessors:
264
- if hasattr(tokenizer, "model_max_length"):
265
- rbln_max_seq_len = tokenizer.model_max_length
266
- break
267
- if rbln_max_seq_len is None:
268
- raise ValueError("`rbln_max_seq_len` should be specified!")
269
-
270
- if rbln_batch_size is None:
271
- rbln_batch_size = 1
272
-
273
- if rbln_model_input_names is None:
274
- for tokenizer in preprocessors:
275
- if hasattr(tokenizer, "model_input_names"):
276
- rbln_model_input_names = tokenizer.model_input_names
277
- break
278
- if rbln_model_input_names is None and hasattr(cls, "rbln_model_input_names"):
279
- rbln_model_input_names = cls.rbln_model_input_names
280
- elif rbln_model_input_names is None and hasattr(cls, "rbln_model_input_names") is False:
281
- input_names_order = inspect.signature(cls.hf_class.forward).parameters.keys()
282
- raise ValueError(
283
- "Specify the model input names obtained by the tokenizer via `rbln_model_input_names`, "
284
- f"and be sure to make the order of the inputs same as QuestionAnswering forward() arguments like ({list(input_names_order)})"
285
- )
286
-
287
- input_info = [
288
- (model_input_name, [rbln_batch_size, rbln_max_seq_len], "int64")
289
- for model_input_name in rbln_model_input_names
290
- ]
291
-
292
- rbln_compile_config = RBLNCompileConfig(input_info=input_info)
293
- rbln_config = RBLNConfig(
294
- rbln_cls=cls.__name__,
295
- compile_cfgs=[rbln_compile_config],
296
- rbln_kwargs=rbln_kwargs,
297
- )
298
- rbln_config.model_cfg.update({"max_seq_len": rbln_max_seq_len})
299
- return rbln_config
300
-
301
-
302
- class RBLNModelForImageClassification(RBLNModel):
303
- """
304
- 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
305
- """
306
-
307
- auto_model_class = AutoModelForImageClassification
308
-
309
- @classmethod
310
- def _get_rbln_config(
311
- cls,
312
- preprocessors: Optional[Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"]],
313
- model_config: Optional["PretrainedConfig"] = None,
314
- rbln_kwargs: Dict[str, Any] = {},
315
- ) -> RBLNConfig:
316
- rbln_image_size = rbln_kwargs.get("image_size", None)
317
- rbln_batch_size = rbln_kwargs.get("batch_size", None)
318
-
319
- if rbln_image_size is None:
320
- for processor in preprocessors:
321
- if hasattr(processor, "size"):
322
- if all(required_key in processor.size.keys() for required_key in ["height", "width"]):
323
- rbln_image_size = (processor.size["height"], processor.size["width"])
324
- elif "shortest_edge" in processor.size.keys():
325
- rbln_image_size = (processor.size["shortest_edge"], processor.size["shortest_edge"])
326
- elif "longest_edge" in processor.size.keys():
327
- rbln_image_size = (processor.size["longest_edge"], processor.size["longest_edge"])
328
- break
329
-
330
- if rbln_image_size is None:
331
- rbln_image_size = model_config.image_size
332
-
333
- if rbln_image_size is None:
334
- raise ValueError("`rbln_image_size` should be specified!")
335
-
336
- if rbln_batch_size is None:
337
- rbln_batch_size = 1
338
-
339
- if isinstance(rbln_image_size, int):
340
- rbln_image_height, rbln_image_width = rbln_image_size, rbln_image_size
341
- elif isinstance(rbln_image_size, (list, tuple)):
342
- rbln_image_height, rbln_image_width = rbln_image_size[0], rbln_image_size[1]
343
- elif isinstance(rbln_image_size, dict):
344
- rbln_image_height, rbln_image_width = rbln_image_size["height"], rbln_image_size["width"]
345
- else:
346
- raise ValueError(
347
- "`rbln_image_size` should be `int` (ex. 224), `tuple` (ex. 224, 224), `dict` (ex. {'height': 224, 'width': 224}) format"
348
- )
349
-
350
- input_info = [
351
- (
352
- "pixel_values",
353
- [rbln_batch_size, 3, rbln_image_height, rbln_image_width],
354
- "float32",
355
- )
356
- ]
357
-
358
- rbln_compile_config = RBLNCompileConfig(input_info=input_info)
359
- return RBLNConfig(rbln_cls=cls.__name__, compile_cfgs=[rbln_compile_config], rbln_kwargs=rbln_kwargs)
360
-
361
-
362
- class RBLNModelForAudioClassification(RBLNModel):
363
- """
364
- 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
365
- This model inherits from [`RBLNModel`]. Check the superclass documentation for the generic methods the library implements for all its models.
366
-
367
- A class to convert and run pre-trained transformers based AudioClassification models on RBLN devices.
368
- It implements the methods to convert a pre-trained transformers AudioClassification model into a RBLN transformer model by:
369
- - transferring the checkpoint weights of the original into an optimized RBLN graph,
370
- - compiling the resulting graph using the RBLN compiler.
371
-
372
- Currently, this model class only supports the 'AST' model from the transformers library. Future updates may include support for additional model types.
373
- """
374
-
375
- auto_model_class = AutoModelForAudioClassification
376
-
377
- @classmethod
378
- def _get_rbln_config(
379
- cls,
380
- preprocessors: "AutoFeatureExtractor",
381
- model_config: "PretrainedConfig",
382
- rbln_kwargs: Dict[str, Any] = {},
383
- ) -> RBLNConfig:
384
- rbln_batch_size = rbln_kwargs.get("batch_size", None)
385
- rbln_max_length = rbln_kwargs.get("max_length", None)
386
- rbln_num_mel_bins = rbln_kwargs.get("num_mel_bins", None)
387
-
388
- if rbln_batch_size is None:
389
- rbln_batch_size = 1
390
-
391
- if rbln_num_mel_bins is None:
392
- rbln_num_mel_bins = getattr(model_config, "num_mel_bins", None)
393
- if rbln_num_mel_bins is None:
394
- for feature_extractor in preprocessors:
395
- if hasattr(feature_extractor, "num_mel_bins"):
396
- rbln_num_mel_bins = feature_extractor.num_mel_bins
397
- break
398
-
399
- if rbln_num_mel_bins is None:
400
- raise ValueError("`rbln_num_mel_bins` should be specified!")
401
-
402
- if rbln_max_length is None:
403
- rbln_max_length = getattr(model_config, "max_length", None)
404
- for feature_extractor in preprocessors:
405
- if hasattr(feature_extractor, "max_length"):
406
- rbln_max_length = feature_extractor.max_length
407
- break
408
-
409
- if rbln_max_length is None:
410
- raise ValueError("`rbln_max_length` should be specified!")
411
-
412
- input_info = [
413
- (
414
- "input_values",
415
- [rbln_batch_size, rbln_max_length, rbln_num_mel_bins],
416
- "float32",
417
- ),
418
- ]
419
-
420
- rbln_compile_config = RBLNCompileConfig(input_info=input_info)
421
- rbln_config = RBLNConfig(
422
- rbln_cls=cls.__name__,
423
- compile_cfgs=[rbln_compile_config],
424
- rbln_kwargs=rbln_kwargs,
425
- )
426
- rbln_config.model_cfg.update(
427
- {
428
- "batch_size": rbln_batch_size,
429
- "max_length": rbln_max_length,
430
- "num_mel_bins": rbln_num_mel_bins,
431
- }
432
- )
433
- return rbln_config
434
-
435
-
436
- class RBLNModelForSequenceClassification(RBLNModel):
437
- """
438
- 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
439
- This model inherits from [`RBLNModel`]. Check the superclass documentation for the generic methods the library implements for all its models.
440
-
441
- A class to convert and run pre-trained transformers based SequenceClassification models on RBLN devices.
442
- It implements the methods to convert a pre-trained transformers SequenceClassification model into a RBLN transformer model by:
443
- - transferring the checkpoint weights of the original into an optimized RBLN graph,
444
- - compiling the resulting graph using the RBLN compiler.
445
-
446
- Currently, this model class supports the 'XLMRoberta' and 'Roberta' model from the transformers library. Future updates may include support for additional model types.
447
- """
448
-
449
- auto_model_class = AutoModelForSequenceClassification
450
-
451
- @classmethod
452
- def _get_rbln_config(
453
- cls,
454
- preprocessors: Optional[Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"]],
455
- model_config: Optional["PretrainedConfig"] = None,
456
- rbln_kwargs: Dict[str, Any] = {},
457
- ) -> RBLNConfig:
458
- rbln_max_seq_len = rbln_kwargs.get("max_seq_len", None)
459
- rbln_model_input_names = rbln_kwargs.get("model_input_names", None)
460
- rbln_batch_size = rbln_kwargs.get("batch_size", None)
461
-
462
- max_position_embeddings = getattr(model_config, "n_positions", None) or getattr(
463
- model_config, "max_position_embeddings", None
464
- )
465
-
466
- if rbln_max_seq_len is None:
467
- rbln_max_seq_len = max_position_embeddings
468
- if rbln_max_seq_len is None:
469
- for tokenizer in preprocessors:
470
- if hasattr(tokenizer, "model_max_length"):
471
- rbln_max_seq_len = tokenizer.model_max_length
472
- break
473
- if rbln_max_seq_len is None:
474
- raise ValueError("`rbln_max_seq_len` should be specified!")
475
-
476
- if max_position_embeddings is not None and rbln_max_seq_len > max_position_embeddings:
477
- raise ValueError("`rbln_enc_max_seq_len` should be less or equal than max_position_embeddings!")
478
-
479
- if rbln_model_input_names is None:
480
- for tokenizer in preprocessors:
481
- if hasattr(tokenizer, "model_input_names"):
482
- rbln_model_input_names = tokenizer.model_input_names
483
- break
484
- if rbln_model_input_names is None and hasattr(cls, "rbln_model_input_names"):
485
- rbln_model_input_names = cls.rbln_model_input_names
486
- elif rbln_model_input_names is None and hasattr(cls, "rbln_model_input_names") is False:
487
- original_model_class = getattr(transformers, model_config.architectures[0])
488
- input_names_order = inspect.signature(original_model_class.forward).parameters.keys()
489
- raise ValueError(
490
- "Specify the model input names obtained by the tokenizer via `rbln_model_input_names`, "
491
- f"and be sure to make the order of the inputs same as SequenceClassification forward() arguments like ({list(input_names_order)})"
492
- )
493
-
494
- if rbln_batch_size is None:
495
- rbln_batch_size = 1
496
-
497
- input_info = [
498
- (model_input_name, [rbln_batch_size, rbln_max_seq_len], "int64")
499
- for model_input_name in rbln_model_input_names
500
- ]
501
-
502
- rbln_compile_config = RBLNCompileConfig(input_info=input_info)
503
- rbln_config = RBLNConfig(
504
- rbln_cls=cls.__name__,
505
- compile_cfgs=[rbln_compile_config],
506
- rbln_kwargs=rbln_kwargs,
507
- )
508
- rbln_config.model_cfg.update({"max_seq_len": rbln_max_seq_len})
509
- return rbln_config
510
-
511
-
512
- class RBLNModelForMaskedLM(RBLNModel):
513
- auto_model_class = AutoModelForMaskedLM
514
-
515
- @classmethod
516
- def _get_rbln_config(
517
- cls,
518
- preprocessors: Optional[Union["AutoFeatureExtractor", "AutoProcessor", "AutoTokenizer"]],
519
- model_config: Optional["PretrainedConfig"] = None,
520
- rbln_kwargs: Dict[str, Any] = {},
521
- ) -> RBLNConfig:
522
- rbln_max_seq_len = rbln_kwargs.get("max_seq_len", None)
523
- rbln_model_input_names = rbln_kwargs.get("model_input_names", None)
524
- rbln_batch_size = rbln_kwargs.get("batch_size", None)
525
-
526
- max_position_embeddings = getattr(model_config, "n_positions", None) or getattr(
527
- model_config, "max_position_embeddings", None
528
- )
529
-
530
- if rbln_max_seq_len is None:
531
- rbln_max_seq_len = max_position_embeddings
532
- if rbln_max_seq_len is None:
533
- for tokenizer in preprocessors:
534
- if hasattr(tokenizer, "model_max_length"):
535
- rbln_max_seq_len = tokenizer.model_max_length
536
- break
537
- if rbln_max_seq_len is None:
538
- raise ValueError("`rbln_max_seq_len` should be specified!")
539
-
540
- if max_position_embeddings is not None and rbln_max_seq_len > max_position_embeddings:
541
- raise ValueError("`rbln_enc_max_seq_len` should be less or equal than max_position_embeddings!")
542
-
543
- if rbln_model_input_names is None:
544
- for tokenizer in preprocessors:
545
- if hasattr(tokenizer, "model_input_names"):
546
- rbln_model_input_names = tokenizer.model_input_names
547
- break
548
- if rbln_model_input_names is None and hasattr(cls, "rbln_model_input_names"):
549
- rbln_model_input_names = cls.rbln_model_input_names
550
- elif rbln_model_input_names is None and hasattr(cls, "rbln_model_input_names") is False:
551
- input_names_order = inspect.signature(cls.hf_class.forward).parameters.keys()
552
- raise ValueError(
553
- "Specify the model input names obtained by the tokenizer via `rbln_model_input_names`, "
554
- f"and be sure to make the order of the inputs same as MaskedLM forward() arguments like ({list(input_names_order)})"
555
- )
556
-
557
- if rbln_batch_size is None:
558
- rbln_batch_size = 1
559
-
560
- input_info = [
561
- (model_input_name, [rbln_batch_size, rbln_max_seq_len], "int64")
562
- for model_input_name in rbln_model_input_names
563
- ]
564
-
565
- rbln_compile_config = RBLNCompileConfig(input_info=input_info)
566
- rbln_config = RBLNConfig(
567
- rbln_cls=cls.__name__,
568
- compile_cfgs=[rbln_compile_config],
569
- rbln_kwargs=rbln_kwargs,
570
- )
571
- rbln_config.model_cfg.update({"max_seq_len": rbln_max_seq_len})
572
- return rbln_config
@@ -21,7 +21,6 @@
21
21
  # copied, modified, or distributed without prior written permission
22
22
  # from Rebellions Inc.
23
23
 
24
-
25
24
  import importlib
26
25
  import logging
27
26
  import os
@@ -211,6 +210,7 @@ class RBLNBaseModel(SubModulesMixin, PushToHubMixin, PreTrainedModel):
211
210
  **kwargs,
212
211
  ) -> "RBLNBaseModel":
213
212
  from_export_method = isinstance(rbln_config, RBLNConfig) and rbln_compiled_models is not None
213
+
214
214
  if not from_export_method:
215
215
  # from compiled dir
216
216
  rbln_kwargs = rbln_config or {}
@@ -304,7 +304,6 @@ class RBLNBaseModel(SubModulesMixin, PushToHubMixin, PreTrainedModel):
304
304
  ):
305
305
  if isinstance(model_save_dir, str):
306
306
  model_save_dir = Path(model_save_dir)
307
-
308
307
  # FIXME:: Should we convert it?
309
308
  compiled_model_names = [cfg.compiled_model_name for cfg in rbln_config.compile_cfgs]
310
309
  rbln_compiled_models = [rbln_compiled_models[cm_name] for cm_name in compiled_model_names]
@@ -312,7 +311,7 @@ class RBLNBaseModel(SubModulesMixin, PushToHubMixin, PreTrainedModel):
312
311
  # create runtimes only if `rbln_create_runtimes` is enabled
313
312
  try:
314
313
  models = (
315
- cls._create_runtimes(rbln_compiled_models, rbln_config.device_map)
314
+ cls._create_runtimes(rbln_compiled_models, rbln_config.device_map, rbln_config.activate_profiler)
316
315
  if rbln_config.create_runtimes
317
316
  else UnavailableRuntime()
318
317
  )
@@ -373,13 +372,14 @@ class RBLNBaseModel(SubModulesMixin, PushToHubMixin, PreTrainedModel):
373
372
  return from_pretrained_method(model_id=model_id, **kwargs)
374
373
 
375
374
  @classmethod
376
- def compile(cls, model, rbln_compile_config: Optional[RBLNCompileConfig] = None):
375
+ def compile(cls, model, rbln_compile_config: Optional[RBLNCompileConfig] = None, **kwargs):
377
376
  compiled_model = rebel.compile_from_torch(
378
377
  model,
379
378
  input_info=rbln_compile_config.input_info,
380
379
  fusion=rbln_compile_config.fusion,
381
380
  npu=rbln_compile_config.npu,
382
381
  tensor_parallel_size=rbln_compile_config.tensor_parallel_size,
382
+ **kwargs,
383
383
  )
384
384
  return compiled_model
385
385
 
@@ -475,6 +475,25 @@ class RBLNBaseModel(SubModulesMixin, PushToHubMixin, PreTrainedModel):
475
475
  if push_to_hub:
476
476
  return super().push_to_hub(save_directory, **kwargs)
477
477
 
478
+ @staticmethod
479
+ def _raise_missing_compiled_file_error(missing_files: List[str]):
480
+ """Raises a KeyError with a message indicating missing compiled model files."""
481
+
482
+ if len(missing_files) == 1:
483
+ message = f"The rbln model folder is missing the required '{missing_files[0]}.rbln' file. "
484
+ else:
485
+ files_str = ", ".join([f"'{f}.rbln'" for f in missing_files])
486
+ message = (
487
+ "The rbln model folder is missing required files. "
488
+ f"Ensure that {files_str} files are present in the folder. "
489
+ )
490
+ message += (
491
+ "These files are necessary for loading the rbln model. "
492
+ "If these files are missing, please recompile the model using the latest optimum-rbln "
493
+ "and ensure the compilation completes successfully."
494
+ )
495
+ raise KeyError(message)
496
+
478
497
  @classmethod
479
498
  @abstractmethod
480
499
  def _get_rbln_config(cls, **rbln_config_kwargs) -> RBLNConfig:
@@ -486,6 +505,7 @@ class RBLNBaseModel(SubModulesMixin, PushToHubMixin, PreTrainedModel):
486
505
  cls,
487
506
  compiled_models: List[rebel.RBLNCompiledModel],
488
507
  rbln_device_map: Dict[str, int],
508
+ activate_profiler: Optional[bool] = None,
489
509
  ) -> List[rebel.Runtime]:
490
510
  # compiled_models -> runtimes
491
511
  pass