optimum-rbln 0.1.12__py3-none-any.whl → 0.1.15__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 (90) hide show
  1. optimum/rbln/__init__.py +27 -13
  2. optimum/rbln/__version__.py +16 -1
  3. optimum/rbln/diffusers/__init__.py +22 -2
  4. optimum/rbln/diffusers/models/__init__.py +34 -3
  5. optimum/rbln/{transformers/generation → diffusers/models/autoencoders}/__init__.py +1 -2
  6. optimum/rbln/diffusers/models/{autoencoder_kl.py → autoencoders/autoencoder_kl.py} +66 -111
  7. optimum/rbln/diffusers/models/autoencoders/vae.py +84 -0
  8. optimum/rbln/diffusers/models/controlnet.py +85 -65
  9. optimum/rbln/diffusers/models/transformers/__init__.py +24 -0
  10. optimum/rbln/diffusers/models/transformers/transformer_sd3.py +203 -0
  11. optimum/rbln/diffusers/models/unets/__init__.py +24 -0
  12. optimum/rbln/diffusers/models/{unet_2d_condition.py → unets/unet_2d_condition.py} +129 -163
  13. optimum/rbln/diffusers/pipelines/__init__.py +60 -12
  14. optimum/rbln/diffusers/pipelines/controlnet/multicontrolnet.py +11 -25
  15. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet.py +9 -185
  16. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +9 -190
  17. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +9 -191
  18. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +9 -192
  19. optimum/rbln/diffusers/pipelines/stable_diffusion/__init__.py +1 -0
  20. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +4 -110
  21. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +4 -118
  22. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +32 -0
  23. optimum/rbln/diffusers/pipelines/stable_diffusion_3/__init__.py +26 -0
  24. optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +32 -0
  25. optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +32 -0
  26. optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +32 -0
  27. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/__init__.py +1 -0
  28. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +18 -128
  29. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +18 -131
  30. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +32 -0
  31. optimum/rbln/modeling.py +572 -0
  32. optimum/rbln/modeling_alias.py +1 -1
  33. optimum/rbln/modeling_base.py +176 -763
  34. optimum/rbln/modeling_diffusers.py +329 -0
  35. optimum/rbln/transformers/__init__.py +2 -2
  36. optimum/rbln/transformers/cache_utils.py +5 -9
  37. optimum/rbln/transformers/modeling_rope_utils.py +283 -0
  38. optimum/rbln/transformers/models/__init__.py +80 -31
  39. optimum/rbln/transformers/models/auto/auto_factory.py +117 -23
  40. optimum/rbln/transformers/models/auto/modeling_auto.py +37 -12
  41. optimum/rbln/transformers/models/bart/modeling_bart.py +3 -6
  42. optimum/rbln/transformers/models/bert/modeling_bert.py +3 -6
  43. optimum/rbln/transformers/models/clip/modeling_clip.py +8 -34
  44. optimum/rbln/transformers/models/decoderonly/__init__.py +0 -5
  45. optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py +779 -361
  46. optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py +83 -142
  47. optimum/rbln/transformers/models/dpt/modeling_dpt.py +1 -1
  48. optimum/rbln/transformers/models/exaone/exaone_architecture.py +64 -39
  49. optimum/rbln/transformers/models/exaone/modeling_exaone.py +6 -29
  50. optimum/rbln/transformers/models/gemma/gemma_architecture.py +31 -92
  51. optimum/rbln/transformers/models/gemma/modeling_gemma.py +4 -28
  52. optimum/rbln/transformers/models/gpt2/gpt2_architecture.py +50 -238
  53. optimum/rbln/transformers/models/gpt2/modeling_gpt2.py +6 -31
  54. optimum/rbln/transformers/models/llama/modeling_llama.py +4 -28
  55. optimum/rbln/transformers/models/llava_next/modeling_llava_next.py +29 -83
  56. optimum/rbln/transformers/models/midm/midm_architecture.py +88 -253
  57. optimum/rbln/transformers/models/midm/modeling_midm.py +8 -33
  58. optimum/rbln/transformers/models/mistral/modeling_mistral.py +4 -29
  59. optimum/rbln/transformers/models/phi/modeling_phi.py +5 -31
  60. optimum/rbln/transformers/models/phi/phi_architecture.py +61 -345
  61. optimum/rbln/transformers/models/qwen2/modeling_qwen2.py +5 -29
  62. optimum/rbln/transformers/models/seq2seq/modeling_seq2seq.py +1 -46
  63. optimum/rbln/transformers/models/t5/__init__.py +1 -1
  64. optimum/rbln/transformers/models/t5/modeling_t5.py +157 -6
  65. optimum/rbln/transformers/models/wav2vec2/modeling_wav2vec2.py +1 -1
  66. optimum/rbln/transformers/models/whisper/modeling_whisper.py +2 -2
  67. optimum/rbln/transformers/models/xlm_roberta/modeling_xlm_roberta.py +3 -35
  68. optimum/rbln/transformers/utils/rbln_quantization.py +128 -5
  69. optimum/rbln/utils/decorator_utils.py +59 -0
  70. optimum/rbln/utils/hub.py +131 -0
  71. optimum/rbln/utils/import_utils.py +21 -0
  72. optimum/rbln/utils/model_utils.py +53 -0
  73. optimum/rbln/utils/runtime_utils.py +5 -5
  74. optimum/rbln/utils/submodule.py +114 -0
  75. optimum/rbln/utils/timer_utils.py +2 -2
  76. optimum_rbln-0.1.15.dist-info/METADATA +106 -0
  77. optimum_rbln-0.1.15.dist-info/RECORD +110 -0
  78. {optimum_rbln-0.1.12.dist-info → optimum_rbln-0.1.15.dist-info}/WHEEL +1 -1
  79. optimum/rbln/transformers/generation/streamers.py +0 -139
  80. optimum/rbln/transformers/generation/utils.py +0 -397
  81. optimum/rbln/transformers/models/exaone/hf_hub_cached/configuration_exaone.py +0 -181
  82. optimum/rbln/transformers/models/exaone/hf_hub_cached/modeling_exaone.py +0 -1725
  83. optimum/rbln/transformers/models/midm/hf_hub_cached/configuration_midm.py +0 -22
  84. optimum/rbln/transformers/models/midm/hf_hub_cached/midm_bitext_tokenization.py +0 -304
  85. optimum/rbln/transformers/models/midm/hf_hub_cached/modeling_midm.py +0 -1469
  86. optimum/rbln/transformers/models/midm/hf_hub_cached/rotary_position_embedding.py +0 -98
  87. optimum_rbln-0.1.12.dist-info/METADATA +0 -119
  88. optimum_rbln-0.1.12.dist-info/RECORD +0 -103
  89. optimum_rbln-0.1.12.dist-info/entry_points.txt +0 -4
  90. {optimum_rbln-0.1.12.dist-info → optimum_rbln-0.1.15.dist-info}/licenses/LICENSE +0 -0
@@ -1,22 +0,0 @@
1
- from transformers.models.gpt2.configuration_gpt2 import GPT2Config
2
-
3
-
4
- class MidmBitextConfig(GPT2Config):
5
- model_type = "midm-bitext-S"
6
-
7
- def __init__(
8
- self,
9
- use_absolute_position_embedding: bool = True,
10
- use_rotary_position_embedding: bool = False,
11
- rotary_percentage: float = 1.0,
12
- normalization_type: str = "layernorm",
13
- scale_qk_by_inverse_layer_idx: bool = False,
14
- *args,
15
- **kwargs,
16
- ):
17
- super().__init__(*args, **kwargs)
18
- self.use_absolute_position_embedding = use_absolute_position_embedding
19
- self.use_rotary_position_embedding = use_rotary_position_embedding
20
- self.rotary_percentage = rotary_percentage
21
- self.normalization_type = normalization_type
22
- self.scale_qk_by_inverse_layer_idx = scale_qk_by_inverse_layer_idx
@@ -1,304 +0,0 @@
1
- # coding=utf-8
2
- # Licensed under the Apache License, Version 2.0 (the "License");
3
- # you may not use this file except in compliance with the License.
4
- # You may obtain a copy of the License at
5
- #
6
- # http://www.apache.org/licenses/LICENSE-2.0
7
- #
8
- # Unless required by applicable law or agreed to in writing, software
9
- # distributed under the License is distributed on an "AS IS" BASIS,
10
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
- # See the License for the specific language governing permissions and
12
- # limitations under the License.
13
- """Tokenization class for model Midm_bitext_tonkenizer."""
14
-
15
- import os
16
- import re
17
- import warnings
18
- from shutil import copyfile
19
- from typing import Any, Dict, List, Optional, Tuple
20
-
21
- import sentencepiece as spm
22
- from transformers.tokenization_utils import PreTrainedTokenizer
23
- from transformers.utils import logging
24
-
25
-
26
- logger = logging.get_logger(__name__)
27
-
28
- VOCAB_FILES_NAMES = {"vocab_file": "midm_bitext_tokenizer.model"}
29
-
30
- PRETRAINED_VOCAB_FILES_MAP = {}
31
-
32
- PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
33
-
34
-
35
- class Midm_bitext_Tokenizer(PreTrainedTokenizer):
36
- """
37
- Construct a Midm bitext tonkenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
38
-
39
- This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
40
- this superclass for more information regarding those methods.
41
-
42
- Args:
43
- vocab_file (`str`):
44
- [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
45
- contains the vocabulary necessary to instantiate a tokenizer.
46
- eos_token (`str`, *optional*, defaults to `"</s>"`):
47
- The end of sequence token.
48
-
49
- <Tip>
50
-
51
- When building a sequence using special tokens, this is not the token that is used for the end of sequence.
52
- The token used is the `sep_token`.
53
-
54
- </Tip>
55
-
56
- unk_token (`str`, *optional*, defaults to `"<unk>"`):
57
- The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
58
- token instead.
59
- pad_token (`str`, *optional*, defaults to `"<pad>"`):
60
- The token used for padding, for example when batching sequences of different lengths.
61
- extra_ids (`int`, *optional*, defaults to 100):
62
- Add a number of extra ids added to the end of the vocabulary for use as sentinels. These tokens are
63
- accessible as "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. Extra tokens are
64
- indexed from the end of the vocabulary up to beginning.
65
- additional_special_tokens (`List[str]`, *optional*):
66
- Additional special tokens used by the tokenizer.
67
- sp_model_kwargs (`dict`, *optional*):
68
- Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
69
- SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
70
- to set:
71
-
72
- - `enable_sampling`: Enable subword regularization.
73
- - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
74
-
75
- - `nbest_size = {0,1}`: No sampling is performed.
76
- - `nbest_size > 1`: samples from the nbest_size results.
77
- - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
78
- using forward-filtering-and-backward-sampling algorithm.
79
-
80
- - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
81
- BPE-dropout.
82
-
83
- Attributes:
84
- sp_model (`SentencePieceProcessor`):
85
- The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
86
- """
87
-
88
- vocab_files_names = VOCAB_FILES_NAMES
89
- pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
90
- max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
91
- model_input_names = ["input_ids", "attention_mask"]
92
-
93
- def __init__(
94
- self,
95
- vocab_file,
96
- eos_token="</s>",
97
- unk_token="<unk>",
98
- pad_token="<pad>",
99
- extra_ids=100,
100
- additional_special_tokens=None,
101
- sp_model_kwargs: Optional[Dict[str, Any]] = None,
102
- **kwargs,
103
- ) -> None:
104
- # Add extra_ids to the special token list
105
- if extra_ids > 0 and additional_special_tokens is None:
106
- additional_special_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)]
107
- elif extra_ids > 0 and additional_special_tokens is not None:
108
- # Check that we have the right number of extra_id special tokens
109
- extra_tokens = len(set(filter(lambda x: bool("extra_id" in str(x)), additional_special_tokens)))
110
- if extra_tokens != extra_ids:
111
- raise ValueError(
112
- f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are provided to Midm_bitext_Tonkenizer. "
113
- "In this case the additional_special_tokens must include the extra_ids tokens"
114
- )
115
-
116
- self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
117
-
118
- # custom special tokens
119
- # convert \n, \t in input text -> <[!newline]>, <[!tab]>
120
- self.newline_token = "<[!newline]>"
121
- self.tab_token = "<[!tab]>"
122
-
123
- self.vocab_file = vocab_file
124
- self._extra_ids = extra_ids
125
-
126
- self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
127
- self.sp_model.Load(vocab_file)
128
- super().__init__(
129
- eos_token=eos_token,
130
- unk_token=unk_token,
131
- pad_token=pad_token,
132
- extra_ids=extra_ids,
133
- additional_special_tokens=additional_special_tokens,
134
- sp_model_kwargs=self.sp_model_kwargs,
135
- **kwargs,
136
- )
137
-
138
- @property
139
- def vocab_size(self):
140
- return self.sp_model.get_piece_size() + self._extra_ids
141
-
142
- def get_vocab(self):
143
- vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
144
- vocab.update(self.added_tokens_encoder)
145
- return vocab
146
-
147
- def get_special_tokens_mask(
148
- self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
149
- ) -> List[int]:
150
- """
151
- Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
152
- special tokens using the tokenizer `prepare_for_model` method.
153
-
154
- Args:
155
- token_ids_0 (`List[int]`):
156
- List of IDs.
157
- token_ids_1 (`List[int]`, *optional*):
158
- Optional second list of IDs for sequence pairs.
159
- already_has_special_tokens (`bool`, *optional*, defaults to `False`):
160
- Whether or not the token list is already formatted with special tokens for the model.
161
-
162
- Returns:
163
- `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
164
- """
165
- if already_has_special_tokens:
166
- return super().get_special_tokens_mask(
167
- token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
168
- )
169
-
170
- # normal case: some special tokens
171
- if token_ids_1 is None:
172
- return ([0] * len(token_ids_0)) + [1]
173
- return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
174
-
175
- def _add_eos_if_not_present(self, token_ids: List[int]) -> List[int]:
176
- """Do not add eos again if user already added it."""
177
- if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id:
178
- warnings.warn(
179
- f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated eos tokens being added."
180
- )
181
- return token_ids
182
- else:
183
- return token_ids + [self.eos_token_id]
184
-
185
- def create_token_type_ids_from_sequences(
186
- self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
187
- ) -> List[int]:
188
- """
189
- Create a mask from the two sequences passed to be used in a sequence-pair classification task. Midm does not make
190
- use of token type ids, therefore a list of zeros is returned.
191
-
192
- Args:
193
- token_ids_0 (`List[int]`):
194
- List of IDs.
195
- token_ids_1 (`List[int]`, *optional*):
196
- Optional second list of IDs for sequence pairs.
197
-
198
- Returns:
199
- `List[int]`: List of zeros.
200
- """
201
- eos = [self.eos_token_id]
202
-
203
- if token_ids_1 is None:
204
- return len(token_ids_0 + eos) * [0]
205
- return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
206
-
207
- def build_inputs_with_special_tokens(
208
- self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
209
- ) -> List[int]:
210
- """
211
- Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
212
- adding special tokens. A sequence has the following format:
213
-
214
- - single sequence: `X </s>`
215
- - pair of sequences: `A </s> B </s>`
216
-
217
- Args:
218
- token_ids_0 (`List[int]`):
219
- List of IDs to which the special tokens will be added.
220
- token_ids_1 (`List[int]`, *optional*):
221
- Optional second list of IDs for sequence pairs.
222
-
223
- Returns:
224
- `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
225
- """
226
- token_ids_0 = self._add_eos_if_not_present(token_ids_0)
227
- if token_ids_1 is None:
228
- return token_ids_0
229
- else:
230
- token_ids_1 = self._add_eos_if_not_present(token_ids_1)
231
- return token_ids_0 + token_ids_1
232
-
233
- def __getstate__(self):
234
- state = self.__dict__.copy()
235
- state["sp_model"] = None
236
- return state
237
-
238
- def __setstate__(self, d):
239
- self.__dict__ = d
240
-
241
- # for backward compatibility
242
- if not hasattr(self, "sp_model_kwargs"):
243
- self.sp_model_kwargs = {}
244
-
245
- self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
246
- self.sp_model.Load(self.vocab_file)
247
-
248
- def _tokenize(self, text: str) -> List[str]:
249
- """Take as input a string and return a list of strings (tokens) for words/sub-words"""
250
- text = text.replace("\n", self.newline_token)
251
- text = text.replace("\t", self.tab_token)
252
-
253
- return self.sp_model.encode(text, out_type=str)
254
-
255
- def _convert_token_to_id(self, token):
256
- """Converts a token (str) in an id using the vocab."""
257
- if token.startswith("<extra_id_"):
258
- match = re.match(r"<extra_id_(\d+)>", token)
259
- num = int(match.group(1))
260
- return self.vocab_size - num - 1
261
- return self.sp_model.piece_to_id(token)
262
-
263
- def _convert_id_to_token(self, index):
264
- """Converts an index (integer) in a token (str) using the vocab."""
265
- if index < self.sp_model.get_piece_size():
266
- token = self.sp_model.IdToPiece(index)
267
- else:
268
- token = f"<extra_id_{self.vocab_size - 1 - index}>"
269
- return token
270
-
271
- def convert_tokens_to_string(self, tokens):
272
- """Converts a sequence of tokens (string) in a single string."""
273
- current_sub_tokens = []
274
- out_string = ""
275
- for token in tokens:
276
- # make sure that special tokens are not decoded using sentencepiece model
277
- if token in self.all_special_tokens:
278
- out_string += self.sp_model.decode_pieces(current_sub_tokens) + token + " "
279
- current_sub_tokens = []
280
- else:
281
- current_sub_tokens.append(token)
282
- out_string += self.sp_model.decode_pieces(current_sub_tokens)
283
-
284
- out_string.replace(self.newline_token, "\n")
285
- out_string.replace(self.tab_token, "\t")
286
-
287
- return out_string.strip()
288
-
289
- def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
290
- if not os.path.isdir(save_directory):
291
- logger.error(f"Vocabulary path ({save_directory}) should be a directory")
292
- return
293
- out_vocab_file = os.path.join(
294
- save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
295
- )
296
-
297
- if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
298
- copyfile(self.vocab_file, out_vocab_file)
299
- elif not os.path.isfile(self.vocab_file):
300
- with open(out_vocab_file, "wb") as fi:
301
- content_spiece_model = self.sp_model.serialized_model_proto()
302
- fi.write(content_spiece_model)
303
-
304
- return (out_vocab_file,)