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.
- optimum/rbln/__init__.py +27 -13
- optimum/rbln/__version__.py +16 -1
- optimum/rbln/diffusers/__init__.py +22 -2
- optimum/rbln/diffusers/models/__init__.py +34 -3
- optimum/rbln/{transformers/generation → diffusers/models/autoencoders}/__init__.py +1 -2
- optimum/rbln/diffusers/models/{autoencoder_kl.py → autoencoders/autoencoder_kl.py} +66 -111
- optimum/rbln/diffusers/models/autoencoders/vae.py +84 -0
- optimum/rbln/diffusers/models/controlnet.py +85 -65
- optimum/rbln/diffusers/models/transformers/__init__.py +24 -0
- optimum/rbln/diffusers/models/transformers/transformer_sd3.py +203 -0
- optimum/rbln/diffusers/models/unets/__init__.py +24 -0
- optimum/rbln/diffusers/models/{unet_2d_condition.py → unets/unet_2d_condition.py} +129 -163
- optimum/rbln/diffusers/pipelines/__init__.py +60 -12
- optimum/rbln/diffusers/pipelines/controlnet/multicontrolnet.py +11 -25
- optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet.py +9 -185
- optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +9 -190
- optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +9 -191
- optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +9 -192
- optimum/rbln/diffusers/pipelines/stable_diffusion/__init__.py +1 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +4 -110
- optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +4 -118
- optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +32 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion_3/__init__.py +26 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +32 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +32 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +32 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion_xl/__init__.py +1 -0
- optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +18 -128
- optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +18 -131
- optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +32 -0
- optimum/rbln/modeling.py +572 -0
- optimum/rbln/modeling_alias.py +1 -1
- optimum/rbln/modeling_base.py +176 -763
- optimum/rbln/modeling_diffusers.py +329 -0
- optimum/rbln/transformers/__init__.py +2 -2
- optimum/rbln/transformers/cache_utils.py +5 -9
- optimum/rbln/transformers/modeling_rope_utils.py +283 -0
- optimum/rbln/transformers/models/__init__.py +80 -31
- optimum/rbln/transformers/models/auto/auto_factory.py +117 -23
- optimum/rbln/transformers/models/auto/modeling_auto.py +37 -12
- optimum/rbln/transformers/models/bart/modeling_bart.py +3 -6
- optimum/rbln/transformers/models/bert/modeling_bert.py +3 -6
- optimum/rbln/transformers/models/clip/modeling_clip.py +8 -34
- optimum/rbln/transformers/models/decoderonly/__init__.py +0 -5
- optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py +779 -361
- optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py +83 -142
- optimum/rbln/transformers/models/dpt/modeling_dpt.py +1 -1
- optimum/rbln/transformers/models/exaone/exaone_architecture.py +64 -39
- optimum/rbln/transformers/models/exaone/modeling_exaone.py +6 -29
- optimum/rbln/transformers/models/gemma/gemma_architecture.py +31 -92
- optimum/rbln/transformers/models/gemma/modeling_gemma.py +4 -28
- optimum/rbln/transformers/models/gpt2/gpt2_architecture.py +50 -238
- optimum/rbln/transformers/models/gpt2/modeling_gpt2.py +6 -31
- optimum/rbln/transformers/models/llama/modeling_llama.py +4 -28
- optimum/rbln/transformers/models/llava_next/modeling_llava_next.py +29 -83
- optimum/rbln/transformers/models/midm/midm_architecture.py +88 -253
- optimum/rbln/transformers/models/midm/modeling_midm.py +8 -33
- optimum/rbln/transformers/models/mistral/modeling_mistral.py +4 -29
- optimum/rbln/transformers/models/phi/modeling_phi.py +5 -31
- optimum/rbln/transformers/models/phi/phi_architecture.py +61 -345
- optimum/rbln/transformers/models/qwen2/modeling_qwen2.py +5 -29
- optimum/rbln/transformers/models/seq2seq/modeling_seq2seq.py +1 -46
- optimum/rbln/transformers/models/t5/__init__.py +1 -1
- optimum/rbln/transformers/models/t5/modeling_t5.py +157 -6
- optimum/rbln/transformers/models/wav2vec2/modeling_wav2vec2.py +1 -1
- optimum/rbln/transformers/models/whisper/modeling_whisper.py +2 -2
- optimum/rbln/transformers/models/xlm_roberta/modeling_xlm_roberta.py +3 -35
- optimum/rbln/transformers/utils/rbln_quantization.py +128 -5
- optimum/rbln/utils/decorator_utils.py +59 -0
- optimum/rbln/utils/hub.py +131 -0
- optimum/rbln/utils/import_utils.py +21 -0
- optimum/rbln/utils/model_utils.py +53 -0
- optimum/rbln/utils/runtime_utils.py +5 -5
- optimum/rbln/utils/submodule.py +114 -0
- optimum/rbln/utils/timer_utils.py +2 -2
- optimum_rbln-0.1.15.dist-info/METADATA +106 -0
- optimum_rbln-0.1.15.dist-info/RECORD +110 -0
- {optimum_rbln-0.1.12.dist-info → optimum_rbln-0.1.15.dist-info}/WHEEL +1 -1
- optimum/rbln/transformers/generation/streamers.py +0 -139
- optimum/rbln/transformers/generation/utils.py +0 -397
- optimum/rbln/transformers/models/exaone/hf_hub_cached/configuration_exaone.py +0 -181
- optimum/rbln/transformers/models/exaone/hf_hub_cached/modeling_exaone.py +0 -1725
- optimum/rbln/transformers/models/midm/hf_hub_cached/configuration_midm.py +0 -22
- optimum/rbln/transformers/models/midm/hf_hub_cached/midm_bitext_tokenization.py +0 -304
- optimum/rbln/transformers/models/midm/hf_hub_cached/modeling_midm.py +0 -1469
- optimum/rbln/transformers/models/midm/hf_hub_cached/rotary_position_embedding.py +0 -98
- optimum_rbln-0.1.12.dist-info/METADATA +0 -119
- optimum_rbln-0.1.12.dist-info/RECORD +0 -103
- optimum_rbln-0.1.12.dist-info/entry_points.txt +0 -4
- {optimum_rbln-0.1.12.dist-info → optimum_rbln-0.1.15.dist-info}/licenses/LICENSE +0 -0
@@ -1,397 +0,0 @@
|
|
1
|
-
import traceback
|
2
|
-
import warnings
|
3
|
-
from typing import List, Optional, Union
|
4
|
-
|
5
|
-
import torch
|
6
|
-
from transformers.generation import GenerationConfig
|
7
|
-
from transformers.generation.logits_process import LogitsProcessorList
|
8
|
-
from transformers.generation.stopping_criteria import (
|
9
|
-
StoppingCriteriaList,
|
10
|
-
validate_stopping_criteria,
|
11
|
-
)
|
12
|
-
from transformers.generation.streamers import BaseStreamer
|
13
|
-
from transformers.generation.utils import SampleDecoderOnlyOutput
|
14
|
-
|
15
|
-
|
16
|
-
class RBLNGenerationMixin:
|
17
|
-
# call 'greedy_search` directly is deprecated and removed in v4.41.
|
18
|
-
def greedy_search(self, *args, **kwargs):
|
19
|
-
return self._greedy_search(*args, **kwargs)
|
20
|
-
|
21
|
-
def _greedy_search(
|
22
|
-
self,
|
23
|
-
input_ids: torch.LongTensor,
|
24
|
-
logits_processor: Optional[LogitsProcessorList] = None,
|
25
|
-
stopping_criteria: Optional[StoppingCriteriaList] = None,
|
26
|
-
max_length: Optional[int] = None,
|
27
|
-
pad_token_id: Optional[int] = None,
|
28
|
-
eos_token_id: Optional[Union[int, List[int]]] = None,
|
29
|
-
output_logits: Optional[bool] = None,
|
30
|
-
return_dict_in_generate: Optional[bool] = None,
|
31
|
-
streamer: Optional["BaseStreamer"] = None,
|
32
|
-
generation_config: Optional[GenerationConfig] = None, # thkim change for 4.41.0
|
33
|
-
**model_kwargs,
|
34
|
-
) -> Union[SampleDecoderOnlyOutput, torch.LongTensor]:
|
35
|
-
###################### thkim change for 4.41.0 ############################
|
36
|
-
if generation_config is not None:
|
37
|
-
pad_token_id = generation_config.pad_token_id
|
38
|
-
output_logits = generation_config.output_logits
|
39
|
-
return_dict_in_generate = generation_config.return_dict_in_generate
|
40
|
-
##########################################################################
|
41
|
-
# init values
|
42
|
-
logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
|
43
|
-
stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
|
44
|
-
|
45
|
-
if max_length is not None:
|
46
|
-
warnings.warn(
|
47
|
-
"`max_length` is deprecated in this function, use"
|
48
|
-
" `stopping_criteria=StoppingCriteriaList([MaxLengthCriteria(max_length=max_length)])` instead.",
|
49
|
-
UserWarning,
|
50
|
-
)
|
51
|
-
stopping_criteria = validate_stopping_criteria(stopping_criteria, max_length)
|
52
|
-
|
53
|
-
pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
|
54
|
-
eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
|
55
|
-
if isinstance(eos_token_id, int):
|
56
|
-
eos_token_id = [eos_token_id]
|
57
|
-
eos_token_id_tensor = torch.tensor(eos_token_id).to(input_ids.device) if eos_token_id is not None else None
|
58
|
-
|
59
|
-
return_dict_in_generate = (
|
60
|
-
return_dict_in_generate
|
61
|
-
if return_dict_in_generate is not None
|
62
|
-
else self.generation_config.return_dict_in_generate
|
63
|
-
)
|
64
|
-
|
65
|
-
# init attention / hidden states / scores tuples
|
66
|
-
raw_logits = () if (return_dict_in_generate and output_logits) else None
|
67
|
-
|
68
|
-
# keep track of which sequences are already finished
|
69
|
-
unfinished_sequences = torch.ones(input_ids.shape[0], dtype=torch.long, device=input_ids.device)
|
70
|
-
|
71
|
-
this_peer_finished = False # used by synced_gpus only
|
72
|
-
|
73
|
-
while True:
|
74
|
-
# prepare model inputs
|
75
|
-
model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
|
76
|
-
# forward pass to get next token
|
77
|
-
try:
|
78
|
-
outputs = self(
|
79
|
-
**model_inputs,
|
80
|
-
return_dict=True,
|
81
|
-
)
|
82
|
-
next_token_logits = outputs.logits[:, -1, :]
|
83
|
-
except Exception:
|
84
|
-
traceback.print_exc()
|
85
|
-
break
|
86
|
-
|
87
|
-
# pre-process distribution
|
88
|
-
next_tokens_scores = logits_processor(input_ids, next_token_logits)
|
89
|
-
|
90
|
-
# Store scores, attentions and hidden_states when required
|
91
|
-
if return_dict_in_generate:
|
92
|
-
if output_logits:
|
93
|
-
raw_logits += (next_token_logits,)
|
94
|
-
|
95
|
-
# argmax
|
96
|
-
next_tokens = torch.argmax(next_tokens_scores, dim=-1)
|
97
|
-
|
98
|
-
# finished sentences should have their next token be a padding token
|
99
|
-
if eos_token_id is not None:
|
100
|
-
if pad_token_id is None:
|
101
|
-
raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.")
|
102
|
-
next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
|
103
|
-
|
104
|
-
########################################################################################################
|
105
|
-
# thkim change for right-padding batch
|
106
|
-
# if min_input_len <= update_idx < max_input_len
|
107
|
-
# update validate input_ids[:,update_idx]
|
108
|
-
# TODO : raw_logits contains dummy next_token's logits
|
109
|
-
if hasattr(self, "rightpad_max_len"):
|
110
|
-
update_idx = model_inputs["cache_position"] + model_inputs["query_length"]
|
111
|
-
if update_idx < self.rightpad_max_len:
|
112
|
-
# update exist input_ids rather than concat
|
113
|
-
valid_indices = model_kwargs["attention_mask"][:, update_idx] == 0
|
114
|
-
dummy_indices = model_kwargs["attention_mask"][:, update_idx] == 1
|
115
|
-
|
116
|
-
input_ids[valid_indices, update_idx] = next_tokens[valid_indices]
|
117
|
-
model_kwargs["attention_mask"][valid_indices, update_idx] = 1
|
118
|
-
model_kwargs["past_key_values"] = outputs["past_key_values"]
|
119
|
-
|
120
|
-
# dummy next_token -> pad_token_id for streamer
|
121
|
-
# in order to skip by 'skip_special_tokens = True"
|
122
|
-
if streamer is not None:
|
123
|
-
next_tokens[dummy_indices] = pad_token_id
|
124
|
-
else:
|
125
|
-
input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
|
126
|
-
model_kwargs = self._update_model_kwargs_for_generation(
|
127
|
-
outputs,
|
128
|
-
model_kwargs,
|
129
|
-
is_encoder_decoder=self.config.is_encoder_decoder,
|
130
|
-
)
|
131
|
-
else:
|
132
|
-
############################################END#########################################################
|
133
|
-
# update generated ids, model inputs, and length for next step
|
134
|
-
input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
|
135
|
-
model_kwargs = self._update_model_kwargs_for_generation(
|
136
|
-
outputs,
|
137
|
-
model_kwargs,
|
138
|
-
is_encoder_decoder=self.config.is_encoder_decoder,
|
139
|
-
)
|
140
|
-
|
141
|
-
if streamer is not None:
|
142
|
-
streamer.put(next_tokens.cpu())
|
143
|
-
if streamer.is_blocked():
|
144
|
-
this_peer_finished = True
|
145
|
-
|
146
|
-
# if eos_token was found in one sentence, set sentence to finished
|
147
|
-
if eos_token_id_tensor is not None:
|
148
|
-
####################################################################
|
149
|
-
# thkim : to do not finish sequence of dummy_decoder of right_padding
|
150
|
-
if hasattr(self, "rightpad_max_len"):
|
151
|
-
update_idx = model_inputs["cache_position"] + model_inputs["query_length"]
|
152
|
-
if update_idx < self.rightpad_max_len:
|
153
|
-
next_tokens += (
|
154
|
-
model_kwargs["attention_mask"][:, update_idx] * self.generation_config.eos_token_id
|
155
|
-
)
|
156
|
-
######################################################################
|
157
|
-
unfinished_sequences = unfinished_sequences.mul(
|
158
|
-
next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0)
|
159
|
-
)
|
160
|
-
|
161
|
-
# stop when each sentence is finished
|
162
|
-
if unfinished_sequences.max() == 0:
|
163
|
-
this_peer_finished = True
|
164
|
-
|
165
|
-
# stop if we exceed the maximum length
|
166
|
-
# thkim : backward compatibility bool vs torch.BoolTensor
|
167
|
-
is_stop = stopping_criteria(input_ids, None)
|
168
|
-
if isinstance(is_stop, torch.BoolTensor):
|
169
|
-
is_stop = torch.all(is_stop)
|
170
|
-
if is_stop:
|
171
|
-
this_peer_finished = True
|
172
|
-
|
173
|
-
if this_peer_finished:
|
174
|
-
break
|
175
|
-
|
176
|
-
if streamer is not None:
|
177
|
-
streamer.end()
|
178
|
-
|
179
|
-
if return_dict_in_generate:
|
180
|
-
############## thkim : roate raw_logits when right_padding#####################
|
181
|
-
if hasattr(self, "rightpad_max_len"):
|
182
|
-
raw_logits = torch.stack(raw_logits).transpose(0, 1)
|
183
|
-
for i in range(input_ids.shape[0]):
|
184
|
-
raw_logits[i] = torch.cat((raw_logits[i][self.dummy_len[i] :], raw_logits[i][: self.dummy_len[i]]))
|
185
|
-
raw_logits = raw_logits.transpose(1, 0)
|
186
|
-
##################################################################################
|
187
|
-
return SampleDecoderOnlyOutput(
|
188
|
-
sequences=input_ids,
|
189
|
-
logits=raw_logits,
|
190
|
-
)
|
191
|
-
else:
|
192
|
-
return input_ids
|
193
|
-
|
194
|
-
# call 'sample` directly is deprecated and removed in v4.41.
|
195
|
-
def sample(self, *args, **kwargs):
|
196
|
-
return self._sample(*args, **kwargs)
|
197
|
-
|
198
|
-
def _sample(
|
199
|
-
self,
|
200
|
-
input_ids: torch.LongTensor,
|
201
|
-
logits_processor: Optional[LogitsProcessorList] = None,
|
202
|
-
stopping_criteria: Optional[StoppingCriteriaList] = None,
|
203
|
-
logits_warper: Optional[LogitsProcessorList] = None,
|
204
|
-
max_length: Optional[int] = None,
|
205
|
-
pad_token_id: Optional[int] = None,
|
206
|
-
eos_token_id: Optional[Union[int, List[int]]] = None,
|
207
|
-
output_attentions: Optional[bool] = None,
|
208
|
-
output_hidden_states: Optional[bool] = None,
|
209
|
-
output_scores: Optional[bool] = None,
|
210
|
-
output_logits: Optional[bool] = None,
|
211
|
-
return_dict_in_generate: Optional[bool] = None,
|
212
|
-
synced_gpus: bool = False,
|
213
|
-
streamer: Optional["BaseStreamer"] = None,
|
214
|
-
generation_config: Optional[GenerationConfig] = None,
|
215
|
-
do_sample: Optional[bool] = True,
|
216
|
-
**model_kwargs,
|
217
|
-
) -> Union[SampleDecoderOnlyOutput, torch.LongTensor]:
|
218
|
-
###################### thkim change for 4.41.0 ############################
|
219
|
-
if generation_config is not None:
|
220
|
-
pad_token_id = generation_config.pad_token_id
|
221
|
-
output_logits = generation_config.output_logits
|
222
|
-
return_dict_in_generate = generation_config.return_dict_in_generate
|
223
|
-
do_sample = generation_config.do_sample
|
224
|
-
###########################################################################
|
225
|
-
|
226
|
-
# init values
|
227
|
-
logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
|
228
|
-
stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
|
229
|
-
|
230
|
-
if max_length is not None:
|
231
|
-
warnings.warn(
|
232
|
-
"`max_length` is deprecated in this function, use"
|
233
|
-
" `stopping_criteria=StoppingCriteriaList([MaxLengthCriteria(max_length=max_length)])` instead.",
|
234
|
-
UserWarning,
|
235
|
-
)
|
236
|
-
stopping_criteria = validate_stopping_criteria(stopping_criteria, max_length)
|
237
|
-
|
238
|
-
logits_warper = logits_warper if logits_warper is not None else LogitsProcessorList()
|
239
|
-
pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
|
240
|
-
eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
|
241
|
-
|
242
|
-
if isinstance(eos_token_id, int):
|
243
|
-
eos_token_id = [eos_token_id]
|
244
|
-
eos_token_id_tensor = torch.tensor(eos_token_id).to(input_ids.device) if eos_token_id is not None else None
|
245
|
-
|
246
|
-
output_scores = output_scores if output_scores is not None else self.generation_config.output_scores
|
247
|
-
output_logits = output_logits if output_logits is not None else False
|
248
|
-
|
249
|
-
# init attention / hidden states / scores tuples
|
250
|
-
scores = () if (return_dict_in_generate and output_scores) else None
|
251
|
-
raw_logits = () if (return_dict_in_generate and output_logits) else None
|
252
|
-
|
253
|
-
# keep track of which sequences are already finished
|
254
|
-
batch_size, cur_len = input_ids.shape
|
255
|
-
unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
|
256
|
-
this_peer_finished = False
|
257
|
-
|
258
|
-
# model_kwargs["cache_position"] = torch.arange(cur_len, device=input_ids.device)
|
259
|
-
|
260
|
-
while True:
|
261
|
-
# prepare model inputs
|
262
|
-
model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
|
263
|
-
|
264
|
-
# forward pass to get next token
|
265
|
-
try:
|
266
|
-
outputs = self(
|
267
|
-
**model_inputs,
|
268
|
-
return_dict=True,
|
269
|
-
output_attentions=output_attentions,
|
270
|
-
output_hidden_states=output_hidden_states,
|
271
|
-
)
|
272
|
-
next_token_logits = outputs.logits[:, -1, :]
|
273
|
-
except Exception:
|
274
|
-
traceback.print_exc()
|
275
|
-
break
|
276
|
-
|
277
|
-
# pre-process distribution
|
278
|
-
next_token_scores = logits_processor(input_ids, next_token_logits)
|
279
|
-
|
280
|
-
###################### thkim change for 4.41.0 ############################
|
281
|
-
if do_sample:
|
282
|
-
next_token_scores = logits_warper(input_ids, next_token_scores)
|
283
|
-
###########################################################################
|
284
|
-
|
285
|
-
# Store scores, attentions and hidden_states when required
|
286
|
-
if return_dict_in_generate:
|
287
|
-
if output_scores:
|
288
|
-
scores += (next_token_scores,)
|
289
|
-
if output_logits:
|
290
|
-
raw_logits += (next_token_logits,)
|
291
|
-
|
292
|
-
# sample
|
293
|
-
###################### thkim change for 4.41.0 ############################
|
294
|
-
if do_sample:
|
295
|
-
probs = torch.nn.functional.softmax(next_token_scores, dim=-1)
|
296
|
-
next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
|
297
|
-
else:
|
298
|
-
next_tokens = torch.argmax(next_token_scores, dim=-1)
|
299
|
-
###########################################################################
|
300
|
-
|
301
|
-
# finished sentences should have their next token be a padding token
|
302
|
-
if eos_token_id is not None:
|
303
|
-
if pad_token_id is None:
|
304
|
-
raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.")
|
305
|
-
next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
|
306
|
-
|
307
|
-
###############################thkim change for right-padding batch#################################
|
308
|
-
# if min_input_len <= update_idx < max_input_len
|
309
|
-
# update validate input_ids[:,update_idx]
|
310
|
-
# TODO : raw_logits contains dummy next_token's logits
|
311
|
-
|
312
|
-
if hasattr(self, "rightpad_max_len"):
|
313
|
-
update_idx = model_inputs["cache_position"] + model_inputs["query_length"]
|
314
|
-
if update_idx < self.rightpad_max_len:
|
315
|
-
# update exist input_ids rather than concat
|
316
|
-
valid_indices = model_kwargs["attention_mask"][:, update_idx] == 0
|
317
|
-
dummy_indices = model_kwargs["attention_mask"][:, update_idx] == 1
|
318
|
-
|
319
|
-
input_ids[valid_indices, update_idx] = next_tokens[valid_indices]
|
320
|
-
model_kwargs["attention_mask"][valid_indices, update_idx] = 1
|
321
|
-
model_kwargs["past_key_values"] = outputs["past_key_values"]
|
322
|
-
# dummy next_token -> pad_token_id for streamer
|
323
|
-
# in order to skip by 'skip_special_tokens = True"
|
324
|
-
if streamer is not None:
|
325
|
-
next_tokens[dummy_indices] = pad_token_id
|
326
|
-
else:
|
327
|
-
input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
|
328
|
-
model_kwargs = self._update_model_kwargs_for_generation(
|
329
|
-
outputs,
|
330
|
-
model_kwargs,
|
331
|
-
is_encoder_decoder=self.config.is_encoder_decoder,
|
332
|
-
)
|
333
|
-
else:
|
334
|
-
############################################END#########################################################
|
335
|
-
# update generated ids, model inputs, and length for next step
|
336
|
-
input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
|
337
|
-
|
338
|
-
model_kwargs = self._update_model_kwargs_for_generation(
|
339
|
-
outputs,
|
340
|
-
model_kwargs,
|
341
|
-
is_encoder_decoder=self.config.is_encoder_decoder,
|
342
|
-
)
|
343
|
-
|
344
|
-
if streamer is not None:
|
345
|
-
streamer.put(next_tokens.cpu())
|
346
|
-
if streamer.is_blocked():
|
347
|
-
this_peer_finished = True
|
348
|
-
|
349
|
-
# if eos_token was found in one sentence, set sentence to finished
|
350
|
-
if eos_token_id_tensor is not None:
|
351
|
-
####################################################################
|
352
|
-
# thkim : to do not finish sequence of dummy_decoder of right_padding
|
353
|
-
if hasattr(self, "rightpad_max_len"):
|
354
|
-
update_idx = model_inputs["cache_position"] + model_inputs["query_length"]
|
355
|
-
if update_idx < self.rightpad_max_len:
|
356
|
-
next_tokens += (
|
357
|
-
model_kwargs["attention_mask"][:, update_idx] * self.generation_config.eos_token_id
|
358
|
-
)
|
359
|
-
|
360
|
-
######################################################################
|
361
|
-
unfinished_sequences = unfinished_sequences.mul(
|
362
|
-
next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0)
|
363
|
-
)
|
364
|
-
|
365
|
-
# stop when each sentence is finished
|
366
|
-
if unfinished_sequences.max() == 0:
|
367
|
-
this_peer_finished = True
|
368
|
-
|
369
|
-
# stop if we exceed the maximum length
|
370
|
-
# thkim : backward compatibility bool vs list[bool]
|
371
|
-
is_stop = stopping_criteria(input_ids, None)
|
372
|
-
if isinstance(is_stop, torch.BoolTensor):
|
373
|
-
is_stop = torch.all(is_stop)
|
374
|
-
if is_stop:
|
375
|
-
this_peer_finished = True
|
376
|
-
|
377
|
-
if this_peer_finished:
|
378
|
-
break
|
379
|
-
|
380
|
-
if streamer is not None:
|
381
|
-
streamer.end()
|
382
|
-
|
383
|
-
if return_dict_in_generate:
|
384
|
-
############## thkim : roate raw_logits when right_padding#####################
|
385
|
-
if hasattr(self, "rightpad_max_len"):
|
386
|
-
raw_logits = torch.stack(raw_logits).transpose(0, 1)
|
387
|
-
for i in range(input_ids.shape[0]):
|
388
|
-
raw_logits[i] = torch.cat((raw_logits[i][self.dummy_len[i] :], raw_logits[i][: self.dummy_len[i]]))
|
389
|
-
raw_logits = raw_logits.transpose(1, 0)
|
390
|
-
##################################################################################
|
391
|
-
return SampleDecoderOnlyOutput(
|
392
|
-
sequences=input_ids,
|
393
|
-
scores=scores,
|
394
|
-
logits=raw_logits,
|
395
|
-
)
|
396
|
-
else:
|
397
|
-
return input_ids
|
@@ -1,181 +0,0 @@
|
|
1
|
-
# coding=utf-8
|
2
|
-
# Copyright 2021 The LG AI Research EXAONE Lab. All rights reserved.
|
3
|
-
#
|
4
|
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
5
|
-
# you may not use this file except in compliance with the License.
|
6
|
-
# You may obtain a copy of the License at
|
7
|
-
#
|
8
|
-
# http://www.apache.org/licenses/LICENSE-2.0
|
9
|
-
#
|
10
|
-
# Unless required by applicable law or agreed to in writing, software
|
11
|
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
12
|
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13
|
-
# See the License for the specific language governing permissions and
|
14
|
-
# limitations under the License.
|
15
|
-
"""EXAONE model configuration"""
|
16
|
-
|
17
|
-
from transformers.configuration_utils import PretrainedConfig
|
18
|
-
from transformers.utils import logging
|
19
|
-
|
20
|
-
|
21
|
-
logger = logging.get_logger(__name__)
|
22
|
-
|
23
|
-
EXAONE_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
24
|
-
|
25
|
-
|
26
|
-
class ExaoneConfig(PretrainedConfig):
|
27
|
-
r"""
|
28
|
-
This is the configuration class to store the configuration of a :class:`~transformers.ExaoneModel`. It is used to
|
29
|
-
instantiate a EXAONE model according to the specified arguments, defining the model architecture. Instantiating a
|
30
|
-
configuration with the defaults will yield a similar configuration to that of the Exaone
|
31
|
-
Configuration objects inherit from :class:`~transformers.PretrainedConfig` and can be used to control the model
|
32
|
-
outputs. Read the documentation from :class:`~transformers.PretrainedConfig` for more information.
|
33
|
-
Args:
|
34
|
-
vocab_size (:obj:`int`, `optional`, defaults to 102400):
|
35
|
-
Vocabulary size of the EXAONE model. Defines the number of different tokens that can be represented by the
|
36
|
-
:obj:`inputs_ids` passed when calling :class:`~transformers.ExaoneModel`. Vocabulary size of the model.
|
37
|
-
Defines the different tokens that can be represented by the `inputs_ids` passed to the forward method of
|
38
|
-
:class:`~transformers.EXAONEModel`.
|
39
|
-
max_position_embeddings (:obj:`int`, `optional`, defaults to 2048):
|
40
|
-
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
41
|
-
just in case (e.g., 512 or 1024 or 2048).
|
42
|
-
hidden_size (:obj:`int`, `optional`, defaults to 2048):
|
43
|
-
Dimensionality of the encoder layers and the pooler layer.
|
44
|
-
num_layers (:obj:`int`, `optional`, defaults to 32):
|
45
|
-
Number of hidden layers in the Transformer encoder.
|
46
|
-
num_attention_heads (:obj:`int`, `optional`, defaults to 32):
|
47
|
-
Number of attention heads for each attention layer in the Transformer decoder.
|
48
|
-
num_key_value_heads (:obj:`int`, `optional`):
|
49
|
-
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
50
|
-
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
51
|
-
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
52
|
-
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
53
|
-
by meanpooling all the original heads within that group. For more details checkout [this
|
54
|
-
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
55
|
-
`num_attention_heads`.
|
56
|
-
intermediate_size (:obj:`int`, `optional`, defaults to `hidden_size * 4`):
|
57
|
-
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
58
|
-
activation_function (:obj:`str` or :obj:`function`, `optional`, defaults to :obj:`"silu"`):
|
59
|
-
The non-linear activation function (function or string) in the decoder.
|
60
|
-
rope_theta (:obj:`float`, `optional`, defaults to 10000.0):
|
61
|
-
The base period of the RoPE embeddings.
|
62
|
-
rope_scaling (:obj:`Dict`, `optional`):
|
63
|
-
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
64
|
-
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
65
|
-
accordingly.
|
66
|
-
Expected contents:
|
67
|
-
`rope_type` (:obj:`str`):
|
68
|
-
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
69
|
-
'llama3'], with 'default' being the original RoPE implementation.
|
70
|
-
`factor` (:obj:`float`, `optional`):
|
71
|
-
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
72
|
-
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
73
|
-
original maximum pre-trained length.
|
74
|
-
`original_max_position_embeddings` (:obj:`int`, `optional`):
|
75
|
-
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
76
|
-
pretraining.
|
77
|
-
`attention_factor` (:obj:`float`, `optional`):
|
78
|
-
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
79
|
-
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
80
|
-
`factor` field to infer the suggested value.
|
81
|
-
`beta_fast` (:obj:`float`, `optional`):
|
82
|
-
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
83
|
-
ramp function. If unspecified, it defaults to 32.
|
84
|
-
`beta_slow` (:obj:`float`, `optional`):
|
85
|
-
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
86
|
-
ramp function. If unspecified, it defaults to 1.
|
87
|
-
`short_factor` (:obj:`List[float]`, `optional`):
|
88
|
-
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
89
|
-
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
90
|
-
size divided by the number of attention heads divided by 2
|
91
|
-
`long_factor` (:obj:`List[float]`, `optional`):
|
92
|
-
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
93
|
-
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
94
|
-
size divided by the number of attention heads divided by 2
|
95
|
-
`low_freq_factor` (:obj:`float`, `optional`):
|
96
|
-
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
97
|
-
`high_freq_factor` (:obj:`float`, `optional`):
|
98
|
-
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
99
|
-
embed_dropout (:obj:`float`, `optional`, defaults to 0.0):
|
100
|
-
The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.
|
101
|
-
attention_dropout (:obj:`float`, `optional`, defaults to 0.0):
|
102
|
-
The dropout ratio for the attention probabilities.
|
103
|
-
layer_norm_epsilon (:obj:`float`, `optional`, defaults to 1e-5):
|
104
|
-
The epsilon used by the layer normalization layers.
|
105
|
-
initializer_range (:obj:`float`, `optional`, defaults to 0.02):
|
106
|
-
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
107
|
-
use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`):
|
108
|
-
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
109
|
-
relevant if ``config.is_decoder=True``.
|
110
|
-
bos_token_id (:obj:`int`, `optional`, defaults to 0):
|
111
|
-
Beginning of stream token id.
|
112
|
-
eos_token_id (:obj:`int`, `optional`, defaults to 2):
|
113
|
-
End of stream token id.
|
114
|
-
tie_word_embeddings (:obj:`bool`, `optional`, defaults to :obj:`True`):
|
115
|
-
Whether to tie weight embeddings
|
116
|
-
gradient_checkpointing (:obj:`bool`, `optional`, defaults to :obj:`False`):
|
117
|
-
If True, use gradient checkpointing to save memory at the expense of slower backward pass.
|
118
|
-
Example::
|
119
|
-
>>> from transformers import EXAONEModel, ExaoneConfig
|
120
|
-
>>> # Initializing a EXAONE configuration
|
121
|
-
>>> configuration = ExaoneConfig()
|
122
|
-
>>> # Initializing a model from configuration
|
123
|
-
>>> model = EXAONEModel(configuration)
|
124
|
-
>>> # Accessing the model configuration
|
125
|
-
>>> configuration = model.config
|
126
|
-
"""
|
127
|
-
|
128
|
-
model_type = "exaone"
|
129
|
-
keys_to_ignore_at_inference = ["past_key_values"]
|
130
|
-
attribute_map = {"num_hidden_layers": "num_layers"}
|
131
|
-
|
132
|
-
def __init__(
|
133
|
-
self,
|
134
|
-
vocab_size=102400,
|
135
|
-
max_position_embeddings=2048,
|
136
|
-
hidden_size=2048,
|
137
|
-
num_layers=32,
|
138
|
-
num_attention_heads=32,
|
139
|
-
num_key_value_heads=None,
|
140
|
-
intermediate_size=None,
|
141
|
-
activation_function="silu",
|
142
|
-
rope_theta=10000.0,
|
143
|
-
rope_scaling=None,
|
144
|
-
embed_dropout=0.0,
|
145
|
-
attention_dropout=0.0,
|
146
|
-
layer_norm_epsilon=1e-5,
|
147
|
-
initializer_range=0.02,
|
148
|
-
use_cache=True,
|
149
|
-
bos_token_id=0,
|
150
|
-
eos_token_id=2,
|
151
|
-
tie_word_embeddings=True,
|
152
|
-
**kwargs,
|
153
|
-
):
|
154
|
-
self.vocab_size = vocab_size
|
155
|
-
self.max_position_embeddings = max_position_embeddings
|
156
|
-
self.hidden_size = hidden_size
|
157
|
-
self.num_layers = num_layers
|
158
|
-
self.num_attention_heads = num_attention_heads
|
159
|
-
self.num_hidden_layers = num_layers
|
160
|
-
if num_key_value_heads is None:
|
161
|
-
num_key_value_heads = num_attention_heads
|
162
|
-
self.num_key_value_heads = num_key_value_heads
|
163
|
-
if intermediate_size:
|
164
|
-
self.intermediate_size = intermediate_size
|
165
|
-
else:
|
166
|
-
self.intermediate_size = hidden_size * 4
|
167
|
-
self.activation_function = activation_function
|
168
|
-
self.embed_dropout = embed_dropout
|
169
|
-
self.attention_dropout = attention_dropout
|
170
|
-
self.layer_norm_epsilon = layer_norm_epsilon
|
171
|
-
self.initializer_range = initializer_range
|
172
|
-
self.use_cache = use_cache
|
173
|
-
self.rope_theta = rope_theta
|
174
|
-
self.rope_scaling = rope_scaling
|
175
|
-
|
176
|
-
self.bos_token_id = bos_token_id
|
177
|
-
self.eos_token_id = eos_token_id
|
178
|
-
|
179
|
-
super().__init__(
|
180
|
-
bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs
|
181
|
-
)
|