optimum-rbln 0.1.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.
- optimum/rbln/__init__.py +115 -0
- optimum/rbln/__version__.py +1 -0
- optimum/rbln/diffusers/__init__.py +64 -0
- optimum/rbln/diffusers/models/__init__.py +26 -0
- optimum/rbln/diffusers/models/autoencoder_kl.py +313 -0
- optimum/rbln/diffusers/models/controlnet.py +180 -0
- optimum/rbln/diffusers/models/unet_2d_condition.py +352 -0
- optimum/rbln/diffusers/pipelines/__init__.py +30 -0
- optimum/rbln/diffusers/pipelines/controlnet/__init__.py +24 -0
- optimum/rbln/diffusers/pipelines/controlnet/multicontrolnet.py +266 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion/__init__.py +26 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_controlnet_img2img.py +731 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +106 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +116 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion_xl/__init__.py +2 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +109 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +111 -0
- optimum/rbln/modeling.py +0 -0
- optimum/rbln/modeling_alias.py +49 -0
- optimum/rbln/modeling_base.py +645 -0
- optimum/rbln/modeling_config.py +169 -0
- optimum/rbln/modeling_seq2seq.py +469 -0
- optimum/rbln/transformers/__init__.py +59 -0
- optimum/rbln/transformers/generation/__init__.py +24 -0
- optimum/rbln/transformers/generation/streamers.py +122 -0
- optimum/rbln/transformers/models/__init__.py +28 -0
- optimum/rbln/transformers/models/bart/__init__.py +24 -0
- optimum/rbln/transformers/models/bart/bart_architecture.py +377 -0
- optimum/rbln/transformers/models/clip/__init__.py +24 -0
- optimum/rbln/transformers/models/clip/modeling_clip.py +116 -0
- optimum/rbln/transformers/models/gpt2/__init__.py +24 -0
- optimum/rbln/transformers/models/gpt2/gpt2_architecture.py +253 -0
- optimum/rbln/transformers/models/gpt2/modeling_gpt2.py +700 -0
- optimum/rbln/transformers/models/llama/__init__.py +24 -0
- optimum/rbln/transformers/models/llama/llama_architecture.py +607 -0
- optimum/rbln/transformers/models/llama/modeling_llama.py +409 -0
- optimum/rbln/transformers/models/t5/__init__.py +24 -0
- optimum/rbln/transformers/models/t5/t5_architecture.py +439 -0
- optimum/rbln/transformers/models/wav2vec2/__init__.py +24 -0
- optimum/rbln/transformers/models/wav2vec2/modeling_wav2vec2.py +121 -0
- optimum/rbln/transformers/models/whisper/__init__.py +24 -0
- optimum/rbln/transformers/models/whisper/modeling_whisper.py +374 -0
- optimum/rbln/transformers/models/whisper/whisper_architecture.py +406 -0
- optimum/rbln/utils/__init__.py +25 -0
- optimum/rbln/utils/import_utils.py +28 -0
- optimum/rbln/utils/runtime_utils.py +71 -0
- optimum/rbln/utils/save_utils.py +92 -0
- optimum_rbln-0.1.0.dist-info/METADATA +144 -0
- optimum_rbln-0.1.0.dist-info/RECORD +51 -0
- optimum_rbln-0.1.0.dist-info/WHEEL +4 -0
- optimum_rbln-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,374 @@
|
|
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
|
+
import inspect
|
25
|
+
import logging
|
26
|
+
from pathlib import Path
|
27
|
+
from tempfile import TemporaryDirectory
|
28
|
+
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
|
29
|
+
|
30
|
+
import rebel
|
31
|
+
import torch
|
32
|
+
from optimum.exporters import TasksManager
|
33
|
+
from transformers import (
|
34
|
+
AutoModelForSpeechSeq2Seq,
|
35
|
+
AutoProcessor,
|
36
|
+
GenerationMixin,
|
37
|
+
PretrainedConfig,
|
38
|
+
WhisperForConditionalGeneration,
|
39
|
+
WhisperModel,
|
40
|
+
)
|
41
|
+
from transformers.modeling_outputs import BaseModelOutput, Seq2SeqLMOutput
|
42
|
+
|
43
|
+
from ....modeling_base import RBLNBaseModel
|
44
|
+
from ....modeling_config import DEFAULT_COMPILED_MODEL_NAME, RBLNConfig, RBLNRuntimeConfig
|
45
|
+
from ....utils.runtime_utils import RBLNPytorchRuntime
|
46
|
+
from ....utils.save_utils import maybe_save_preprocessors
|
47
|
+
from .whisper_architecture import (
|
48
|
+
_WhisperDecoderWrapper,
|
49
|
+
_WhisperEncoderWrapper,
|
50
|
+
)
|
51
|
+
|
52
|
+
|
53
|
+
logger = logging.getLogger(__name__)
|
54
|
+
|
55
|
+
if TYPE_CHECKING:
|
56
|
+
from transformers import (
|
57
|
+
AutoFeatureExtractor,
|
58
|
+
AutoProcessor,
|
59
|
+
PretrainedConfig,
|
60
|
+
)
|
61
|
+
|
62
|
+
|
63
|
+
class RBLNRuntimeEncoder(RBLNPytorchRuntime):
|
64
|
+
mandatory_members = ["main_input_name"]
|
65
|
+
|
66
|
+
def forward(self, *args: List[torch.Tensor], **kwargs: Dict[str, torch.Tensor]):
|
67
|
+
_ = super().forward(input_features=kwargs["input_features"])
|
68
|
+
return BaseModelOutput(last_hidden_state=torch.tensor([1.0]))
|
69
|
+
|
70
|
+
|
71
|
+
class RBLNRuntimeDecoder(RBLNPytorchRuntime):
|
72
|
+
mandatory_members = ["main_input_name"]
|
73
|
+
|
74
|
+
def forward(self, *args: List[torch.Tensor], **kwargs: Dict[str, torch.Tensor]):
|
75
|
+
outputs = super().forward(*args, **kwargs)
|
76
|
+
return Seq2SeqLMOutput(logits=outputs)
|
77
|
+
|
78
|
+
|
79
|
+
class RBLNWhisperForConditionalGeneration(RBLNBaseModel, GenerationMixin):
|
80
|
+
"""
|
81
|
+
The Whisper Model with a language modeling head. Can be used for automatic speech recognition.
|
82
|
+
This model inherits from [`RBLNBaseModel`]. Check the superclass documentation for the generic methods the library implements for all its models.
|
83
|
+
|
84
|
+
A class to convert and run pre-trained transformers based LlamaForCausalLM model on RBLN devices.
|
85
|
+
It implements the methods to convert a pre-trained transformers LlamaForCausalLM model into a RBLN transformer model by:
|
86
|
+
- transferring the checkpoint weights of the original into an optimized RBLN graph,
|
87
|
+
- compiling the resulting graph using the RBLN compiler.
|
88
|
+
"""
|
89
|
+
|
90
|
+
model_type = "rbln_model"
|
91
|
+
auto_model_class = AutoModelForSpeechSeq2Seq
|
92
|
+
main_input_name = "input_ids"
|
93
|
+
|
94
|
+
def __post_init__(self, **kwargs):
|
95
|
+
self.batch_size = self.rbln_config[DEFAULT_COMPILED_MODEL_NAME][0].batch_size
|
96
|
+
self.enc_max_seq_len = self.rbln_config.meta["input_max_length"]
|
97
|
+
self.dec_max_seq_len = self.rbln_config.meta["rbln_dec_max_seq_len"]
|
98
|
+
|
99
|
+
self.encoder = RBLNRuntimeEncoder(runtime=self.runtimes[0], main_input_name="input_features")
|
100
|
+
self.decoder = RBLNRuntimeDecoder(runtime=self.runtimes[1], main_input_name="input_ids")
|
101
|
+
self.forced_decoder_ids = self.config.forced_decoder_ids
|
102
|
+
|
103
|
+
# used in GenerationMixin.generate()
|
104
|
+
self.model = WhisperModel(self.config)
|
105
|
+
self.pad_token_id = self.config.pad_token_id
|
106
|
+
|
107
|
+
def can_generate(self):
|
108
|
+
return True
|
109
|
+
|
110
|
+
def get_encoder(self):
|
111
|
+
return self.encoder
|
112
|
+
|
113
|
+
def get_decoder(self):
|
114
|
+
return self.decoder
|
115
|
+
|
116
|
+
def __getattr__(self, __name: str) -> Any:
|
117
|
+
"""This is the key method to implement RBLN-Whisper.
|
118
|
+
Returns:
|
119
|
+
Any: Whisper's corresponding method
|
120
|
+
"""
|
121
|
+
|
122
|
+
def redirect(func):
|
123
|
+
return lambda *pargs, **kwargs: func(self, *pargs, **kwargs)
|
124
|
+
|
125
|
+
val = getattr(WhisperForConditionalGeneration, __name)
|
126
|
+
if isinstance(val, Callable) and "self" in set(inspect.signature(val).parameters):
|
127
|
+
return redirect(val)
|
128
|
+
return val
|
129
|
+
|
130
|
+
def _reorder_cache(self, past_key_values, beam_idx):
|
131
|
+
# TODO(jongho): implement
|
132
|
+
raise NotImplementedError
|
133
|
+
|
134
|
+
def prepare_inputs_for_generation(
|
135
|
+
self,
|
136
|
+
input_ids,
|
137
|
+
decoder_attention_mask=None,
|
138
|
+
input_features=None, # Must be explicit
|
139
|
+
**kwargs,
|
140
|
+
):
|
141
|
+
max_seq_len = self.dec_max_seq_len
|
142
|
+
cur_seq_len = input_ids.shape[-1]
|
143
|
+
input_ids = input_ids[:, cur_seq_len - 1 : cur_seq_len].contiguous()
|
144
|
+
decoder_attention_mask = torch.zeros(self.batch_size, max_seq_len, dtype=torch.int64)
|
145
|
+
decoder_attention_mask[:, :cur_seq_len] = 1
|
146
|
+
cache_position = torch.tensor(cur_seq_len - 1, dtype=torch.int32)
|
147
|
+
|
148
|
+
return {
|
149
|
+
"decoder_input_ids": input_ids,
|
150
|
+
"decoder_attention_mask": decoder_attention_mask,
|
151
|
+
"cache_position": cache_position,
|
152
|
+
}
|
153
|
+
|
154
|
+
@classmethod
|
155
|
+
def _export(
|
156
|
+
cls,
|
157
|
+
model_id: str,
|
158
|
+
config: "PretrainedConfig",
|
159
|
+
use_auth_token: Optional[Union[bool, str]] = None,
|
160
|
+
revision: Optional[str] = None,
|
161
|
+
force_download: bool = False,
|
162
|
+
cache_dir: Optional[str] = None,
|
163
|
+
subfolder: str = "",
|
164
|
+
local_files_only: bool = False,
|
165
|
+
trust_remote_code: bool = False,
|
166
|
+
**kwargs,
|
167
|
+
) -> "RBLNWhisperForConditionalGeneration":
|
168
|
+
"""
|
169
|
+
Exports a vanilla Transformers model into a rbln-compiled Module.
|
170
|
+
"""
|
171
|
+
task = kwargs.pop("task", None)
|
172
|
+
if task is None:
|
173
|
+
task = TasksManager.infer_task_from_model(cls.auto_model_class)
|
174
|
+
|
175
|
+
save_dir = TemporaryDirectory()
|
176
|
+
save_dir_path = Path(save_dir.name)
|
177
|
+
|
178
|
+
kwargs.update(
|
179
|
+
{
|
180
|
+
"torchscript": True,
|
181
|
+
"return_dict": False,
|
182
|
+
"use_cache": False,
|
183
|
+
}
|
184
|
+
)
|
185
|
+
rbln_config_kwargs, rbln_constructor_kwargs = cls.pop_rbln_kwargs_from_kwargs(kwargs)
|
186
|
+
|
187
|
+
model: WhisperForConditionalGeneration = TasksManager.get_model_from_task(
|
188
|
+
task=task,
|
189
|
+
model_name_or_path=model_id,
|
190
|
+
subfolder=subfolder,
|
191
|
+
revision=revision,
|
192
|
+
framework="pt",
|
193
|
+
cache_dir=cache_dir,
|
194
|
+
use_auth_token=use_auth_token,
|
195
|
+
local_files_only=local_files_only,
|
196
|
+
force_download=force_download,
|
197
|
+
trust_remote_code=trust_remote_code,
|
198
|
+
**kwargs,
|
199
|
+
)
|
200
|
+
|
201
|
+
if config is None:
|
202
|
+
config = model.config
|
203
|
+
|
204
|
+
config.save_pretrained(save_dir_path)
|
205
|
+
preprocessors = maybe_save_preprocessors(model_id, save_dir_path, src_subfolder=subfolder)
|
206
|
+
|
207
|
+
# Get compilation arguments
|
208
|
+
if rbln_config_kwargs.get("rbln_config", None) is None:
|
209
|
+
rbln_config = cls.get_rbln_config(
|
210
|
+
preprocessors=preprocessors, model_config=model.config, **rbln_config_kwargs
|
211
|
+
)
|
212
|
+
|
213
|
+
def compile_whisper():
|
214
|
+
wrapped_encoder = _WhisperEncoderWrapper(model).eval()
|
215
|
+
wrapped_decoder = _WhisperDecoderWrapper(model).eval()
|
216
|
+
|
217
|
+
enc_rbln_runtime_config = rbln_config[DEFAULT_COMPILED_MODEL_NAME][0]
|
218
|
+
dec_rbln_runtime_config = rbln_config[DEFAULT_COMPILED_MODEL_NAME][1]
|
219
|
+
|
220
|
+
enc_example_inputs = enc_rbln_runtime_config.get_dummy_inputs(fill=1)
|
221
|
+
dec_example_inputs = dec_rbln_runtime_config.get_dummy_inputs(fill=1)
|
222
|
+
|
223
|
+
enc_scripted_model = torch.jit.trace(wrapped_encoder, enc_example_inputs[0]).eval()
|
224
|
+
dec_scripted_model = torch.jit.trace(wrapped_decoder, dec_example_inputs).eval()
|
225
|
+
|
226
|
+
enc_ir = rebel.torchscript_to_ir(
|
227
|
+
enc_scripted_model,
|
228
|
+
input_names=[v[0] for v in enc_rbln_runtime_config.input_info],
|
229
|
+
name=enc_rbln_runtime_config.rbln_mod_name,
|
230
|
+
)
|
231
|
+
dec_ir = rebel.torchscript_to_ir(
|
232
|
+
dec_scripted_model,
|
233
|
+
input_names=[v[0] for v in dec_rbln_runtime_config.input_info],
|
234
|
+
name=dec_rbln_runtime_config.rbln_mod_name,
|
235
|
+
)
|
236
|
+
dec_ir.batch_size = dec_rbln_runtime_config.batch_size
|
237
|
+
|
238
|
+
# Caching encoder/decoder I/O
|
239
|
+
connections = [
|
240
|
+
(enc_ir.outputs[0], dec_ir.inputs[4]),
|
241
|
+
(dec_ir.outputs[1], dec_ir.inputs[3]),
|
242
|
+
]
|
243
|
+
compiled_model = rebel.compile(
|
244
|
+
enc_ir,
|
245
|
+
dec_ir,
|
246
|
+
connections=connections,
|
247
|
+
fusion=enc_rbln_runtime_config.fusion,
|
248
|
+
npu=enc_rbln_runtime_config.npu,
|
249
|
+
tensor_parallel_size=enc_rbln_runtime_config.tensor_parallel_size,
|
250
|
+
)
|
251
|
+
compiled_model.save(save_dir_path / f"{DEFAULT_COMPILED_MODEL_NAME}.rbln")
|
252
|
+
|
253
|
+
compile_whisper()
|
254
|
+
rbln_config.save(save_dir_path)
|
255
|
+
|
256
|
+
return cls._from_pretrained(
|
257
|
+
model_id=save_dir_path,
|
258
|
+
config=config,
|
259
|
+
model_save_dir=save_dir,
|
260
|
+
**rbln_constructor_kwargs,
|
261
|
+
**kwargs,
|
262
|
+
)
|
263
|
+
|
264
|
+
@classmethod
|
265
|
+
def _get_rbln_config(
|
266
|
+
cls,
|
267
|
+
preprocessors: Union["AutoFeatureExtractor", "AutoProcessor"],
|
268
|
+
model_config: "PretrainedConfig",
|
269
|
+
rbln_batch_size: Optional[int] = 1,
|
270
|
+
) -> RBLNConfig:
|
271
|
+
meta = {}
|
272
|
+
|
273
|
+
input_max_length = 3000
|
274
|
+
rbln_enc_num_mel_bins = getattr(model_config, "num_mel_bins", None)
|
275
|
+
if rbln_enc_num_mel_bins is None:
|
276
|
+
for feature_extractor in preprocessors:
|
277
|
+
if hasattr(feature_extractor, "feature_size"):
|
278
|
+
rbln_enc_num_mel_bins = feature_extractor.feature_size
|
279
|
+
break
|
280
|
+
raise ValueError("`rbln_enc_num_mel_bins` should be specified!")
|
281
|
+
|
282
|
+
rbln_enc_max_seq_len = getattr(model_config, "max_source_positions", None)
|
283
|
+
if rbln_enc_max_seq_len is None:
|
284
|
+
raise ValueError("`rbln_enc_max_seq_len` should be specified!")
|
285
|
+
|
286
|
+
rbln_dec_max_seq_len = getattr(model_config, "max_length", None)
|
287
|
+
if rbln_dec_max_seq_len is None:
|
288
|
+
raise ValueError("`rbln_dec_max_seq_len` should be specified!")
|
289
|
+
|
290
|
+
decoder_batch_size = rbln_batch_size
|
291
|
+
|
292
|
+
meta["rbln_dec_max_seq_len"] = rbln_dec_max_seq_len
|
293
|
+
meta["rbln_enc_max_seq_len"] = rbln_enc_max_seq_len
|
294
|
+
meta["num_mel_bins"] = rbln_enc_num_mel_bins
|
295
|
+
meta["input_max_length"] = input_max_length
|
296
|
+
meta["decoder_batch_size"] = decoder_batch_size
|
297
|
+
meta["forced_decoder_ids"] = model_config.forced_decoder_ids
|
298
|
+
|
299
|
+
# model input info
|
300
|
+
enc_input_info = [("input_features", [rbln_batch_size, rbln_enc_num_mel_bins, input_max_length], "float32")]
|
301
|
+
dec_input_info = [
|
302
|
+
("decoder_input_ids", [decoder_batch_size, 1], "int64"),
|
303
|
+
("decoder_attention_mask", [decoder_batch_size, rbln_dec_max_seq_len], "int64"),
|
304
|
+
("cache_position", [], "int32"),
|
305
|
+
]
|
306
|
+
dec_input_info.extend(
|
307
|
+
[
|
308
|
+
(
|
309
|
+
"self_key_value_states",
|
310
|
+
[
|
311
|
+
model_config.decoder_layers * 2,
|
312
|
+
decoder_batch_size,
|
313
|
+
model_config.decoder_attention_heads,
|
314
|
+
rbln_dec_max_seq_len,
|
315
|
+
model_config.d_model // model_config.encoder_attention_heads,
|
316
|
+
],
|
317
|
+
"float32",
|
318
|
+
)
|
319
|
+
]
|
320
|
+
)
|
321
|
+
dec_input_info.extend(
|
322
|
+
[
|
323
|
+
(
|
324
|
+
"cross_key_value_states",
|
325
|
+
[
|
326
|
+
model_config.decoder_layers * 2,
|
327
|
+
rbln_batch_size,
|
328
|
+
model_config.decoder_attention_heads,
|
329
|
+
rbln_enc_max_seq_len,
|
330
|
+
model_config.d_model // model_config.encoder_attention_heads,
|
331
|
+
],
|
332
|
+
"float32",
|
333
|
+
)
|
334
|
+
]
|
335
|
+
)
|
336
|
+
|
337
|
+
enc_rbln_runtime_config = RBLNRuntimeConfig(rbln_mod_name="encoder", input_info=enc_input_info)
|
338
|
+
dec_rbln_runtime_config = RBLNRuntimeConfig(rbln_mod_name="decoder", input_info=dec_input_info)
|
339
|
+
|
340
|
+
enc_rbln_runtime_config.batch_size = rbln_batch_size
|
341
|
+
dec_rbln_runtime_config.batch_size = decoder_batch_size
|
342
|
+
|
343
|
+
rbln_config = RBLNConfig.from_rbln_runtime_configs(
|
344
|
+
[enc_rbln_runtime_config, dec_rbln_runtime_config],
|
345
|
+
_rbln_meta=meta,
|
346
|
+
)
|
347
|
+
|
348
|
+
return rbln_config
|
349
|
+
|
350
|
+
def _create_runtimes(self, rbln_device_map: Dict[str, int]) -> List[rebel.Runtime]:
|
351
|
+
device_val = rbln_device_map[DEFAULT_COMPILED_MODEL_NAME]
|
352
|
+
return [
|
353
|
+
self.compiled_models[0].create_runtime("encoder", tensor_type="pt", device=device_val),
|
354
|
+
self.compiled_models[0].create_runtime("decoder", tensor_type="pt", device=device_val),
|
355
|
+
]
|
356
|
+
|
357
|
+
def forward(
|
358
|
+
self,
|
359
|
+
decoder_input_ids: Optional[torch.LongTensor] = None,
|
360
|
+
decoder_attention_mask: Optional[torch.LongTensor] = None,
|
361
|
+
cache_position: Optional[torch.Tensor] = None,
|
362
|
+
**kwargs,
|
363
|
+
) -> Seq2SeqLMOutput:
|
364
|
+
decoder_output = self.decoder(
|
365
|
+
decoder_input_ids=decoder_input_ids,
|
366
|
+
decoder_attention_mask=decoder_attention_mask,
|
367
|
+
cache_position=cache_position,
|
368
|
+
)
|
369
|
+
lm_logits = decoder_output.logits
|
370
|
+
|
371
|
+
return Seq2SeqLMOutput(logits=lm_logits)
|
372
|
+
|
373
|
+
def __repr__(self):
|
374
|
+
return repr(self.runtimes[0]) + "\n" + repr(self.runtimes[1])
|