Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- lib/python3.12/site-packages/transformers/models/__init__.py +325 -0
- lib/python3.12/site-packages/transformers/models/albert/__init__.py +31 -0
- lib/python3.12/site-packages/transformers/models/albert/__pycache__/__init__.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/albert/__pycache__/configuration_albert.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/albert/__pycache__/modeling_albert.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/albert/__pycache__/modeling_flax_albert.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/albert/__pycache__/modeling_tf_albert.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/albert/__pycache__/tokenization_albert.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/albert/__pycache__/tokenization_albert_fast.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/albert/configuration_albert.py +170 -0
- lib/python3.12/site-packages/transformers/models/albert/modeling_albert.py +1483 -0
- lib/python3.12/site-packages/transformers/models/albert/modeling_flax_albert.py +1132 -0
- lib/python3.12/site-packages/transformers/models/albert/modeling_tf_albert.py +1573 -0
- lib/python3.12/site-packages/transformers/models/albert/tokenization_albert.py +350 -0
- lib/python3.12/site-packages/transformers/models/albert/tokenization_albert_fast.py +212 -0
- lib/python3.12/site-packages/transformers/models/bertweet/__init__.py +26 -0
- lib/python3.12/site-packages/transformers/models/bertweet/__pycache__/__init__.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/bertweet/__pycache__/tokenization_bertweet.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/bertweet/tokenization_bertweet.py +769 -0
- lib/python3.12/site-packages/transformers/models/biogpt/__init__.py +28 -0
- lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/__init__.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/configuration_biogpt.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/modeling_biogpt.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/tokenization_biogpt.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/biogpt/configuration_biogpt.py +134 -0
- lib/python3.12/site-packages/transformers/models/biogpt/modeling_biogpt.py +1042 -0
- lib/python3.12/site-packages/transformers/models/biogpt/tokenization_biogpt.py +361 -0
- lib/python3.12/site-packages/transformers/models/blenderbot/__init__.py +31 -0
- lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/__init__.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/configuration_blenderbot.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/modeling_blenderbot.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/modeling_flax_blenderbot.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/modeling_tf_blenderbot.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/tokenization_blenderbot.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/tokenization_blenderbot_fast.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/blenderbot/configuration_blenderbot.py +395 -0
- lib/python3.12/site-packages/transformers/models/blenderbot/modeling_blenderbot.py +1557 -0
- lib/python3.12/site-packages/transformers/models/blenderbot/modeling_flax_blenderbot.py +1508 -0
- lib/python3.12/site-packages/transformers/models/blenderbot/modeling_tf_blenderbot.py +1558 -0
- lib/python3.12/site-packages/transformers/models/blenderbot/tokenization_blenderbot.py +410 -0
- lib/python3.12/site-packages/transformers/models/blenderbot/tokenization_blenderbot_fast.py +284 -0
- lib/python3.12/site-packages/transformers/models/code_llama/__init__.py +27 -0
- lib/python3.12/site-packages/transformers/models/code_llama/__pycache__/__init__.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/code_llama/__pycache__/tokenization_code_llama.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/code_llama/__pycache__/tokenization_code_llama_fast.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/code_llama/tokenization_code_llama.py +452 -0
- lib/python3.12/site-packages/transformers/models/code_llama/tokenization_code_llama_fast.py +381 -0
- lib/python3.12/site-packages/transformers/models/dbrx/__init__.py +27 -0
- lib/python3.12/site-packages/transformers/models/dbrx/__pycache__/__init__.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/dbrx/__pycache__/configuration_dbrx.cpython-312.pyc +0 -0
lib/python3.12/site-packages/transformers/models/__init__.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 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 |
+
|
| 15 |
+
from . import (
|
| 16 |
+
albert,
|
| 17 |
+
align,
|
| 18 |
+
altclip,
|
| 19 |
+
aria,
|
| 20 |
+
audio_spectrogram_transformer,
|
| 21 |
+
auto,
|
| 22 |
+
autoformer,
|
| 23 |
+
aya_vision,
|
| 24 |
+
bamba,
|
| 25 |
+
bark,
|
| 26 |
+
bart,
|
| 27 |
+
barthez,
|
| 28 |
+
bartpho,
|
| 29 |
+
beit,
|
| 30 |
+
bert,
|
| 31 |
+
bert_generation,
|
| 32 |
+
bert_japanese,
|
| 33 |
+
bertweet,
|
| 34 |
+
big_bird,
|
| 35 |
+
bigbird_pegasus,
|
| 36 |
+
biogpt,
|
| 37 |
+
bit,
|
| 38 |
+
blenderbot,
|
| 39 |
+
blenderbot_small,
|
| 40 |
+
blip,
|
| 41 |
+
blip_2,
|
| 42 |
+
bloom,
|
| 43 |
+
bridgetower,
|
| 44 |
+
bros,
|
| 45 |
+
byt5,
|
| 46 |
+
camembert,
|
| 47 |
+
canine,
|
| 48 |
+
chameleon,
|
| 49 |
+
chinese_clip,
|
| 50 |
+
clap,
|
| 51 |
+
clip,
|
| 52 |
+
clipseg,
|
| 53 |
+
clvp,
|
| 54 |
+
code_llama,
|
| 55 |
+
codegen,
|
| 56 |
+
cohere,
|
| 57 |
+
cohere2,
|
| 58 |
+
colpali,
|
| 59 |
+
conditional_detr,
|
| 60 |
+
convbert,
|
| 61 |
+
convnext,
|
| 62 |
+
convnextv2,
|
| 63 |
+
cpm,
|
| 64 |
+
cpmant,
|
| 65 |
+
ctrl,
|
| 66 |
+
cvt,
|
| 67 |
+
dab_detr,
|
| 68 |
+
dac,
|
| 69 |
+
data2vec,
|
| 70 |
+
dbrx,
|
| 71 |
+
deberta,
|
| 72 |
+
deberta_v2,
|
| 73 |
+
decision_transformer,
|
| 74 |
+
deepseek_v3,
|
| 75 |
+
deformable_detr,
|
| 76 |
+
deit,
|
| 77 |
+
deprecated,
|
| 78 |
+
depth_anything,
|
| 79 |
+
depth_pro,
|
| 80 |
+
detr,
|
| 81 |
+
dialogpt,
|
| 82 |
+
diffllama,
|
| 83 |
+
dinat,
|
| 84 |
+
dinov2,
|
| 85 |
+
dinov2_with_registers,
|
| 86 |
+
distilbert,
|
| 87 |
+
dit,
|
| 88 |
+
donut,
|
| 89 |
+
dpr,
|
| 90 |
+
dpt,
|
| 91 |
+
efficientnet,
|
| 92 |
+
electra,
|
| 93 |
+
emu3,
|
| 94 |
+
encodec,
|
| 95 |
+
encoder_decoder,
|
| 96 |
+
ernie,
|
| 97 |
+
esm,
|
| 98 |
+
falcon,
|
| 99 |
+
falcon_mamba,
|
| 100 |
+
fastspeech2_conformer,
|
| 101 |
+
flaubert,
|
| 102 |
+
flava,
|
| 103 |
+
fnet,
|
| 104 |
+
focalnet,
|
| 105 |
+
fsmt,
|
| 106 |
+
funnel,
|
| 107 |
+
fuyu,
|
| 108 |
+
gemma,
|
| 109 |
+
gemma2,
|
| 110 |
+
gemma3,
|
| 111 |
+
git,
|
| 112 |
+
glm,
|
| 113 |
+
glpn,
|
| 114 |
+
got_ocr2,
|
| 115 |
+
gpt2,
|
| 116 |
+
gpt_bigcode,
|
| 117 |
+
gpt_neo,
|
| 118 |
+
gpt_neox,
|
| 119 |
+
gpt_neox_japanese,
|
| 120 |
+
gpt_sw3,
|
| 121 |
+
gptj,
|
| 122 |
+
granite,
|
| 123 |
+
granitemoe,
|
| 124 |
+
granitemoeshared,
|
| 125 |
+
grounding_dino,
|
| 126 |
+
groupvit,
|
| 127 |
+
helium,
|
| 128 |
+
herbert,
|
| 129 |
+
hiera,
|
| 130 |
+
hubert,
|
| 131 |
+
ibert,
|
| 132 |
+
idefics,
|
| 133 |
+
idefics2,
|
| 134 |
+
idefics3,
|
| 135 |
+
ijepa,
|
| 136 |
+
imagegpt,
|
| 137 |
+
informer,
|
| 138 |
+
instructblip,
|
| 139 |
+
instructblipvideo,
|
| 140 |
+
jamba,
|
| 141 |
+
jetmoe,
|
| 142 |
+
kosmos2,
|
| 143 |
+
layoutlm,
|
| 144 |
+
layoutlmv2,
|
| 145 |
+
layoutlmv3,
|
| 146 |
+
layoutxlm,
|
| 147 |
+
led,
|
| 148 |
+
levit,
|
| 149 |
+
lilt,
|
| 150 |
+
llama,
|
| 151 |
+
llama4,
|
| 152 |
+
llava,
|
| 153 |
+
llava_next,
|
| 154 |
+
llava_next_video,
|
| 155 |
+
llava_onevision,
|
| 156 |
+
longformer,
|
| 157 |
+
longt5,
|
| 158 |
+
luke,
|
| 159 |
+
lxmert,
|
| 160 |
+
m2m_100,
|
| 161 |
+
mamba,
|
| 162 |
+
mamba2,
|
| 163 |
+
marian,
|
| 164 |
+
markuplm,
|
| 165 |
+
mask2former,
|
| 166 |
+
maskformer,
|
| 167 |
+
mbart,
|
| 168 |
+
mbart50,
|
| 169 |
+
megatron_bert,
|
| 170 |
+
megatron_gpt2,
|
| 171 |
+
mgp_str,
|
| 172 |
+
mimi,
|
| 173 |
+
mistral,
|
| 174 |
+
mistral3,
|
| 175 |
+
mixtral,
|
| 176 |
+
mllama,
|
| 177 |
+
mluke,
|
| 178 |
+
mobilebert,
|
| 179 |
+
mobilenet_v1,
|
| 180 |
+
mobilenet_v2,
|
| 181 |
+
mobilevit,
|
| 182 |
+
mobilevitv2,
|
| 183 |
+
modernbert,
|
| 184 |
+
moonshine,
|
| 185 |
+
moshi,
|
| 186 |
+
mpnet,
|
| 187 |
+
mpt,
|
| 188 |
+
mra,
|
| 189 |
+
mt5,
|
| 190 |
+
musicgen,
|
| 191 |
+
musicgen_melody,
|
| 192 |
+
mvp,
|
| 193 |
+
myt5,
|
| 194 |
+
nemotron,
|
| 195 |
+
nllb,
|
| 196 |
+
nllb_moe,
|
| 197 |
+
nougat,
|
| 198 |
+
nystromformer,
|
| 199 |
+
olmo,
|
| 200 |
+
olmo2,
|
| 201 |
+
olmoe,
|
| 202 |
+
omdet_turbo,
|
| 203 |
+
oneformer,
|
| 204 |
+
openai,
|
| 205 |
+
opt,
|
| 206 |
+
owlv2,
|
| 207 |
+
owlvit,
|
| 208 |
+
paligemma,
|
| 209 |
+
patchtsmixer,
|
| 210 |
+
patchtst,
|
| 211 |
+
pegasus,
|
| 212 |
+
pegasus_x,
|
| 213 |
+
perceiver,
|
| 214 |
+
persimmon,
|
| 215 |
+
phi,
|
| 216 |
+
phi3,
|
| 217 |
+
phi4_multimodal,
|
| 218 |
+
phimoe,
|
| 219 |
+
phobert,
|
| 220 |
+
pix2struct,
|
| 221 |
+
pixtral,
|
| 222 |
+
plbart,
|
| 223 |
+
poolformer,
|
| 224 |
+
pop2piano,
|
| 225 |
+
prompt_depth_anything,
|
| 226 |
+
prophetnet,
|
| 227 |
+
pvt,
|
| 228 |
+
pvt_v2,
|
| 229 |
+
qwen2,
|
| 230 |
+
qwen2_5_vl,
|
| 231 |
+
qwen2_audio,
|
| 232 |
+
qwen2_moe,
|
| 233 |
+
qwen2_vl,
|
| 234 |
+
qwen3,
|
| 235 |
+
qwen3_moe,
|
| 236 |
+
rag,
|
| 237 |
+
recurrent_gemma,
|
| 238 |
+
reformer,
|
| 239 |
+
regnet,
|
| 240 |
+
rembert,
|
| 241 |
+
resnet,
|
| 242 |
+
roberta,
|
| 243 |
+
roberta_prelayernorm,
|
| 244 |
+
roc_bert,
|
| 245 |
+
roformer,
|
| 246 |
+
rt_detr,
|
| 247 |
+
rt_detr_v2,
|
| 248 |
+
rwkv,
|
| 249 |
+
sam,
|
| 250 |
+
seamless_m4t,
|
| 251 |
+
seamless_m4t_v2,
|
| 252 |
+
segformer,
|
| 253 |
+
seggpt,
|
| 254 |
+
sew,
|
| 255 |
+
sew_d,
|
| 256 |
+
shieldgemma2,
|
| 257 |
+
siglip,
|
| 258 |
+
siglip2,
|
| 259 |
+
smolvlm,
|
| 260 |
+
speech_encoder_decoder,
|
| 261 |
+
speech_to_text,
|
| 262 |
+
speecht5,
|
| 263 |
+
splinter,
|
| 264 |
+
squeezebert,
|
| 265 |
+
stablelm,
|
| 266 |
+
starcoder2,
|
| 267 |
+
superglue,
|
| 268 |
+
superpoint,
|
| 269 |
+
swiftformer,
|
| 270 |
+
swin,
|
| 271 |
+
swin2sr,
|
| 272 |
+
swinv2,
|
| 273 |
+
switch_transformers,
|
| 274 |
+
t5,
|
| 275 |
+
table_transformer,
|
| 276 |
+
tapas,
|
| 277 |
+
textnet,
|
| 278 |
+
time_series_transformer,
|
| 279 |
+
timesformer,
|
| 280 |
+
timm_backbone,
|
| 281 |
+
timm_wrapper,
|
| 282 |
+
trocr,
|
| 283 |
+
tvp,
|
| 284 |
+
udop,
|
| 285 |
+
umt5,
|
| 286 |
+
unispeech,
|
| 287 |
+
unispeech_sat,
|
| 288 |
+
univnet,
|
| 289 |
+
upernet,
|
| 290 |
+
video_llava,
|
| 291 |
+
videomae,
|
| 292 |
+
vilt,
|
| 293 |
+
vipllava,
|
| 294 |
+
vision_encoder_decoder,
|
| 295 |
+
vision_text_dual_encoder,
|
| 296 |
+
visual_bert,
|
| 297 |
+
vit,
|
| 298 |
+
vit_mae,
|
| 299 |
+
vit_msn,
|
| 300 |
+
vitdet,
|
| 301 |
+
vitmatte,
|
| 302 |
+
vitpose,
|
| 303 |
+
vitpose_backbone,
|
| 304 |
+
vits,
|
| 305 |
+
vivit,
|
| 306 |
+
wav2vec2,
|
| 307 |
+
wav2vec2_bert,
|
| 308 |
+
wav2vec2_conformer,
|
| 309 |
+
wav2vec2_phoneme,
|
| 310 |
+
wav2vec2_with_lm,
|
| 311 |
+
wavlm,
|
| 312 |
+
whisper,
|
| 313 |
+
x_clip,
|
| 314 |
+
xglm,
|
| 315 |
+
xlm,
|
| 316 |
+
xlm_roberta,
|
| 317 |
+
xlm_roberta_xl,
|
| 318 |
+
xlnet,
|
| 319 |
+
xmod,
|
| 320 |
+
yolos,
|
| 321 |
+
yoso,
|
| 322 |
+
zamba,
|
| 323 |
+
zamba2,
|
| 324 |
+
zoedepth,
|
| 325 |
+
)
|
lib/python3.12/site-packages/transformers/models/albert/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 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 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_albert import *
|
| 22 |
+
from .modeling_albert import *
|
| 23 |
+
from .modeling_flax_albert import *
|
| 24 |
+
from .modeling_tf_albert import *
|
| 25 |
+
from .tokenization_albert import *
|
| 26 |
+
from .tokenization_albert_fast import *
|
| 27 |
+
else:
|
| 28 |
+
import sys
|
| 29 |
+
|
| 30 |
+
_file = globals()["__file__"]
|
| 31 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.12/site-packages/transformers/models/albert/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (808 Bytes). View file
|
|
|
lib/python3.12/site-packages/transformers/models/albert/__pycache__/configuration_albert.cpython-312.pyc
ADDED
|
Binary file (7.64 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/albert/__pycache__/modeling_albert.cpython-312.pyc
ADDED
|
Binary file (72.2 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/albert/__pycache__/modeling_flax_albert.cpython-312.pyc
ADDED
|
Binary file (48 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/albert/__pycache__/modeling_tf_albert.cpython-312.pyc
ADDED
|
Binary file (75 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/albert/__pycache__/tokenization_albert.cpython-312.pyc
ADDED
|
Binary file (16.7 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/albert/__pycache__/tokenization_albert_fast.cpython-312.pyc
ADDED
|
Binary file (9.18 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/albert/configuration_albert.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""ALBERT model configuration"""
|
| 17 |
+
|
| 18 |
+
from collections import OrderedDict
|
| 19 |
+
from typing import Mapping
|
| 20 |
+
|
| 21 |
+
from ...configuration_utils import PretrainedConfig
|
| 22 |
+
from ...onnx import OnnxConfig
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class AlbertConfig(PretrainedConfig):
|
| 26 |
+
r"""
|
| 27 |
+
This is the configuration class to store the configuration of a [`AlbertModel`] or a [`TFAlbertModel`]. It is used
|
| 28 |
+
to instantiate an ALBERT model according to the specified arguments, defining the model architecture. Instantiating
|
| 29 |
+
a configuration with the defaults will yield a similar configuration to that of the ALBERT
|
| 30 |
+
[albert/albert-xxlarge-v2](https://huggingface.co/albert/albert-xxlarge-v2) architecture.
|
| 31 |
+
|
| 32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 33 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
vocab_size (`int`, *optional*, defaults to 30000):
|
| 37 |
+
Vocabulary size of the ALBERT model. Defines the number of different tokens that can be represented by the
|
| 38 |
+
`inputs_ids` passed when calling [`AlbertModel`] or [`TFAlbertModel`].
|
| 39 |
+
embedding_size (`int`, *optional*, defaults to 128):
|
| 40 |
+
Dimensionality of vocabulary embeddings.
|
| 41 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
| 42 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 43 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 44 |
+
Number of hidden layers in the Transformer encoder.
|
| 45 |
+
num_hidden_groups (`int`, *optional*, defaults to 1):
|
| 46 |
+
Number of groups for the hidden layers, parameters in the same group are shared.
|
| 47 |
+
num_attention_heads (`int`, *optional*, defaults to 64):
|
| 48 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 49 |
+
intermediate_size (`int`, *optional*, defaults to 16384):
|
| 50 |
+
The dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
| 51 |
+
inner_group_num (`int`, *optional*, defaults to 1):
|
| 52 |
+
The number of inner repetition of attention and ffn.
|
| 53 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu_new"`):
|
| 54 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 55 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 56 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0):
|
| 57 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 58 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0):
|
| 59 |
+
The dropout ratio for the attention probabilities.
|
| 60 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 61 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 62 |
+
(e.g., 512 or 1024 or 2048).
|
| 63 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
| 64 |
+
The vocabulary size of the `token_type_ids` passed when calling [`AlbertModel`] or [`TFAlbertModel`].
|
| 65 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 66 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 67 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 68 |
+
The epsilon used by the layer normalization layers.
|
| 69 |
+
classifier_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 70 |
+
The dropout ratio for attached classifiers.
|
| 71 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
| 72 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
| 73 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
| 74 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
| 75 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
| 76 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
| 77 |
+
pad_token_id (`int`, *optional*, defaults to 0):
|
| 78 |
+
Padding token id.
|
| 79 |
+
bos_token_id (`int`, *optional*, defaults to 2):
|
| 80 |
+
Beginning of stream token id.
|
| 81 |
+
eos_token_id (`int`, *optional*, defaults to 3):
|
| 82 |
+
End of stream token id.
|
| 83 |
+
|
| 84 |
+
Examples:
|
| 85 |
+
|
| 86 |
+
```python
|
| 87 |
+
>>> from transformers import AlbertConfig, AlbertModel
|
| 88 |
+
|
| 89 |
+
>>> # Initializing an ALBERT-xxlarge style configuration
|
| 90 |
+
>>> albert_xxlarge_configuration = AlbertConfig()
|
| 91 |
+
|
| 92 |
+
>>> # Initializing an ALBERT-base style configuration
|
| 93 |
+
>>> albert_base_configuration = AlbertConfig(
|
| 94 |
+
... hidden_size=768,
|
| 95 |
+
... num_attention_heads=12,
|
| 96 |
+
... intermediate_size=3072,
|
| 97 |
+
... )
|
| 98 |
+
|
| 99 |
+
>>> # Initializing a model (with random weights) from the ALBERT-base style configuration
|
| 100 |
+
>>> model = AlbertModel(albert_xxlarge_configuration)
|
| 101 |
+
|
| 102 |
+
>>> # Accessing the model configuration
|
| 103 |
+
>>> configuration = model.config
|
| 104 |
+
```"""
|
| 105 |
+
|
| 106 |
+
model_type = "albert"
|
| 107 |
+
|
| 108 |
+
def __init__(
|
| 109 |
+
self,
|
| 110 |
+
vocab_size=30000,
|
| 111 |
+
embedding_size=128,
|
| 112 |
+
hidden_size=4096,
|
| 113 |
+
num_hidden_layers=12,
|
| 114 |
+
num_hidden_groups=1,
|
| 115 |
+
num_attention_heads=64,
|
| 116 |
+
intermediate_size=16384,
|
| 117 |
+
inner_group_num=1,
|
| 118 |
+
hidden_act="gelu_new",
|
| 119 |
+
hidden_dropout_prob=0,
|
| 120 |
+
attention_probs_dropout_prob=0,
|
| 121 |
+
max_position_embeddings=512,
|
| 122 |
+
type_vocab_size=2,
|
| 123 |
+
initializer_range=0.02,
|
| 124 |
+
layer_norm_eps=1e-12,
|
| 125 |
+
classifier_dropout_prob=0.1,
|
| 126 |
+
position_embedding_type="absolute",
|
| 127 |
+
pad_token_id=0,
|
| 128 |
+
bos_token_id=2,
|
| 129 |
+
eos_token_id=3,
|
| 130 |
+
**kwargs,
|
| 131 |
+
):
|
| 132 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 133 |
+
|
| 134 |
+
self.vocab_size = vocab_size
|
| 135 |
+
self.embedding_size = embedding_size
|
| 136 |
+
self.hidden_size = hidden_size
|
| 137 |
+
self.num_hidden_layers = num_hidden_layers
|
| 138 |
+
self.num_hidden_groups = num_hidden_groups
|
| 139 |
+
self.num_attention_heads = num_attention_heads
|
| 140 |
+
self.inner_group_num = inner_group_num
|
| 141 |
+
self.hidden_act = hidden_act
|
| 142 |
+
self.intermediate_size = intermediate_size
|
| 143 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 144 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 145 |
+
self.max_position_embeddings = max_position_embeddings
|
| 146 |
+
self.type_vocab_size = type_vocab_size
|
| 147 |
+
self.initializer_range = initializer_range
|
| 148 |
+
self.layer_norm_eps = layer_norm_eps
|
| 149 |
+
self.classifier_dropout_prob = classifier_dropout_prob
|
| 150 |
+
self.position_embedding_type = position_embedding_type
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# Copied from transformers.models.bert.configuration_bert.BertOnnxConfig with Roberta->Albert
|
| 154 |
+
class AlbertOnnxConfig(OnnxConfig):
|
| 155 |
+
@property
|
| 156 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 157 |
+
if self.task == "multiple-choice":
|
| 158 |
+
dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
|
| 159 |
+
else:
|
| 160 |
+
dynamic_axis = {0: "batch", 1: "sequence"}
|
| 161 |
+
return OrderedDict(
|
| 162 |
+
[
|
| 163 |
+
("input_ids", dynamic_axis),
|
| 164 |
+
("attention_mask", dynamic_axis),
|
| 165 |
+
("token_type_ids", dynamic_axis),
|
| 166 |
+
]
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
__all__ = ["AlbertConfig", "AlbertOnnxConfig"]
|
lib/python3.12/site-packages/transformers/models/albert/modeling_albert.py
ADDED
|
@@ -0,0 +1,1483 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and the HuggingFace Inc. team.
|
| 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 |
+
"""PyTorch ALBERT model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
import os
|
| 19 |
+
from dataclasses import dataclass
|
| 20 |
+
from typing import Dict, List, Optional, Tuple, Union
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
from torch import nn
|
| 24 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 25 |
+
|
| 26 |
+
from ...activations import ACT2FN
|
| 27 |
+
from ...modeling_attn_mask_utils import _prepare_4d_attention_mask_for_sdpa
|
| 28 |
+
from ...modeling_outputs import (
|
| 29 |
+
BaseModelOutput,
|
| 30 |
+
BaseModelOutputWithPooling,
|
| 31 |
+
MaskedLMOutput,
|
| 32 |
+
MultipleChoiceModelOutput,
|
| 33 |
+
QuestionAnsweringModelOutput,
|
| 34 |
+
SequenceClassifierOutput,
|
| 35 |
+
TokenClassifierOutput,
|
| 36 |
+
)
|
| 37 |
+
from ...modeling_utils import PreTrainedModel
|
| 38 |
+
from ...pytorch_utils import (
|
| 39 |
+
apply_chunking_to_forward,
|
| 40 |
+
find_pruneable_heads_and_indices,
|
| 41 |
+
is_torch_greater_or_equal_than_2_2,
|
| 42 |
+
prune_linear_layer,
|
| 43 |
+
)
|
| 44 |
+
from ...utils import (
|
| 45 |
+
ModelOutput,
|
| 46 |
+
add_code_sample_docstrings,
|
| 47 |
+
add_start_docstrings,
|
| 48 |
+
add_start_docstrings_to_model_forward,
|
| 49 |
+
logging,
|
| 50 |
+
replace_return_docstrings,
|
| 51 |
+
)
|
| 52 |
+
from .configuration_albert import AlbertConfig
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
logger = logging.get_logger(__name__)
|
| 56 |
+
|
| 57 |
+
_CHECKPOINT_FOR_DOC = "albert/albert-base-v2"
|
| 58 |
+
_CONFIG_FOR_DOC = "AlbertConfig"
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def load_tf_weights_in_albert(model, config, tf_checkpoint_path):
|
| 62 |
+
"""Load tf checkpoints in a pytorch model."""
|
| 63 |
+
try:
|
| 64 |
+
import re
|
| 65 |
+
|
| 66 |
+
import numpy as np
|
| 67 |
+
import tensorflow as tf
|
| 68 |
+
except ImportError:
|
| 69 |
+
logger.error(
|
| 70 |
+
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
|
| 71 |
+
"https://www.tensorflow.org/install/ for installation instructions."
|
| 72 |
+
)
|
| 73 |
+
raise
|
| 74 |
+
tf_path = os.path.abspath(tf_checkpoint_path)
|
| 75 |
+
logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
|
| 76 |
+
# Load weights from TF model
|
| 77 |
+
init_vars = tf.train.list_variables(tf_path)
|
| 78 |
+
names = []
|
| 79 |
+
arrays = []
|
| 80 |
+
for name, shape in init_vars:
|
| 81 |
+
logger.info(f"Loading TF weight {name} with shape {shape}")
|
| 82 |
+
array = tf.train.load_variable(tf_path, name)
|
| 83 |
+
names.append(name)
|
| 84 |
+
arrays.append(array)
|
| 85 |
+
|
| 86 |
+
for name, array in zip(names, arrays):
|
| 87 |
+
print(name)
|
| 88 |
+
|
| 89 |
+
for name, array in zip(names, arrays):
|
| 90 |
+
original_name = name
|
| 91 |
+
|
| 92 |
+
# If saved from the TF HUB module
|
| 93 |
+
name = name.replace("module/", "")
|
| 94 |
+
|
| 95 |
+
# Renaming and simplifying
|
| 96 |
+
name = name.replace("ffn_1", "ffn")
|
| 97 |
+
name = name.replace("bert/", "albert/")
|
| 98 |
+
name = name.replace("attention_1", "attention")
|
| 99 |
+
name = name.replace("transform/", "")
|
| 100 |
+
name = name.replace("LayerNorm_1", "full_layer_layer_norm")
|
| 101 |
+
name = name.replace("LayerNorm", "attention/LayerNorm")
|
| 102 |
+
name = name.replace("transformer/", "")
|
| 103 |
+
|
| 104 |
+
# The feed forward layer had an 'intermediate' step which has been abstracted away
|
| 105 |
+
name = name.replace("intermediate/dense/", "")
|
| 106 |
+
name = name.replace("ffn/intermediate/output/dense/", "ffn_output/")
|
| 107 |
+
|
| 108 |
+
# ALBERT attention was split between self and output which have been abstracted away
|
| 109 |
+
name = name.replace("/output/", "/")
|
| 110 |
+
name = name.replace("/self/", "/")
|
| 111 |
+
|
| 112 |
+
# The pooler is a linear layer
|
| 113 |
+
name = name.replace("pooler/dense", "pooler")
|
| 114 |
+
|
| 115 |
+
# The classifier was simplified to predictions from cls/predictions
|
| 116 |
+
name = name.replace("cls/predictions", "predictions")
|
| 117 |
+
name = name.replace("predictions/attention", "predictions")
|
| 118 |
+
|
| 119 |
+
# Naming was changed to be more explicit
|
| 120 |
+
name = name.replace("embeddings/attention", "embeddings")
|
| 121 |
+
name = name.replace("inner_group_", "albert_layers/")
|
| 122 |
+
name = name.replace("group_", "albert_layer_groups/")
|
| 123 |
+
|
| 124 |
+
# Classifier
|
| 125 |
+
if len(name.split("/")) == 1 and ("output_bias" in name or "output_weights" in name):
|
| 126 |
+
name = "classifier/" + name
|
| 127 |
+
|
| 128 |
+
# No ALBERT model currently handles the next sentence prediction task
|
| 129 |
+
if "seq_relationship" in name:
|
| 130 |
+
name = name.replace("seq_relationship/output_", "sop_classifier/classifier/")
|
| 131 |
+
name = name.replace("weights", "weight")
|
| 132 |
+
|
| 133 |
+
name = name.split("/")
|
| 134 |
+
|
| 135 |
+
# Ignore the gradients applied by the LAMB/ADAM optimizers.
|
| 136 |
+
if (
|
| 137 |
+
"adam_m" in name
|
| 138 |
+
or "adam_v" in name
|
| 139 |
+
or "AdamWeightDecayOptimizer" in name
|
| 140 |
+
or "AdamWeightDecayOptimizer_1" in name
|
| 141 |
+
or "global_step" in name
|
| 142 |
+
):
|
| 143 |
+
logger.info(f"Skipping {'/'.join(name)}")
|
| 144 |
+
continue
|
| 145 |
+
|
| 146 |
+
pointer = model
|
| 147 |
+
for m_name in name:
|
| 148 |
+
if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
|
| 149 |
+
scope_names = re.split(r"_(\d+)", m_name)
|
| 150 |
+
else:
|
| 151 |
+
scope_names = [m_name]
|
| 152 |
+
|
| 153 |
+
if scope_names[0] == "kernel" or scope_names[0] == "gamma":
|
| 154 |
+
pointer = getattr(pointer, "weight")
|
| 155 |
+
elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
|
| 156 |
+
pointer = getattr(pointer, "bias")
|
| 157 |
+
elif scope_names[0] == "output_weights":
|
| 158 |
+
pointer = getattr(pointer, "weight")
|
| 159 |
+
elif scope_names[0] == "squad":
|
| 160 |
+
pointer = getattr(pointer, "classifier")
|
| 161 |
+
else:
|
| 162 |
+
try:
|
| 163 |
+
pointer = getattr(pointer, scope_names[0])
|
| 164 |
+
except AttributeError:
|
| 165 |
+
logger.info(f"Skipping {'/'.join(name)}")
|
| 166 |
+
continue
|
| 167 |
+
if len(scope_names) >= 2:
|
| 168 |
+
num = int(scope_names[1])
|
| 169 |
+
pointer = pointer[num]
|
| 170 |
+
|
| 171 |
+
if m_name[-11:] == "_embeddings":
|
| 172 |
+
pointer = getattr(pointer, "weight")
|
| 173 |
+
elif m_name == "kernel":
|
| 174 |
+
array = np.transpose(array)
|
| 175 |
+
try:
|
| 176 |
+
if pointer.shape != array.shape:
|
| 177 |
+
raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
|
| 178 |
+
except ValueError as e:
|
| 179 |
+
e.args += (pointer.shape, array.shape)
|
| 180 |
+
raise
|
| 181 |
+
print(f"Initialize PyTorch weight {name} from {original_name}")
|
| 182 |
+
pointer.data = torch.from_numpy(array)
|
| 183 |
+
|
| 184 |
+
return model
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class AlbertEmbeddings(nn.Module):
|
| 188 |
+
"""
|
| 189 |
+
Construct the embeddings from word, position and token_type embeddings.
|
| 190 |
+
"""
|
| 191 |
+
|
| 192 |
+
def __init__(self, config: AlbertConfig):
|
| 193 |
+
super().__init__()
|
| 194 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id)
|
| 195 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.embedding_size)
|
| 196 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.embedding_size)
|
| 197 |
+
|
| 198 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
| 199 |
+
# any TensorFlow checkpoint file
|
| 200 |
+
self.LayerNorm = nn.LayerNorm(config.embedding_size, eps=config.layer_norm_eps)
|
| 201 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 202 |
+
|
| 203 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 204 |
+
self.register_buffer(
|
| 205 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 206 |
+
)
|
| 207 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
| 208 |
+
self.register_buffer(
|
| 209 |
+
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
# Copied from transformers.models.bert.modeling_bert.BertEmbeddings.forward
|
| 213 |
+
def forward(
|
| 214 |
+
self,
|
| 215 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 216 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 217 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 218 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 219 |
+
past_key_values_length: int = 0,
|
| 220 |
+
) -> torch.Tensor:
|
| 221 |
+
if input_ids is not None:
|
| 222 |
+
input_shape = input_ids.size()
|
| 223 |
+
else:
|
| 224 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 225 |
+
|
| 226 |
+
seq_length = input_shape[1]
|
| 227 |
+
|
| 228 |
+
if position_ids is None:
|
| 229 |
+
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
|
| 230 |
+
|
| 231 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
| 232 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
| 233 |
+
# issue #5664
|
| 234 |
+
if token_type_ids is None:
|
| 235 |
+
if hasattr(self, "token_type_ids"):
|
| 236 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
| 237 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
| 238 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 239 |
+
else:
|
| 240 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
| 241 |
+
|
| 242 |
+
if inputs_embeds is None:
|
| 243 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 244 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 245 |
+
|
| 246 |
+
embeddings = inputs_embeds + token_type_embeddings
|
| 247 |
+
if self.position_embedding_type == "absolute":
|
| 248 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 249 |
+
embeddings += position_embeddings
|
| 250 |
+
embeddings = self.LayerNorm(embeddings)
|
| 251 |
+
embeddings = self.dropout(embeddings)
|
| 252 |
+
return embeddings
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
class AlbertAttention(nn.Module):
|
| 256 |
+
def __init__(self, config: AlbertConfig):
|
| 257 |
+
super().__init__()
|
| 258 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 259 |
+
raise ValueError(
|
| 260 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 261 |
+
f"heads ({config.num_attention_heads}"
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
self.num_attention_heads = config.num_attention_heads
|
| 265 |
+
self.hidden_size = config.hidden_size
|
| 266 |
+
self.attention_head_size = config.hidden_size // config.num_attention_heads
|
| 267 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 268 |
+
|
| 269 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 270 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 271 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 272 |
+
|
| 273 |
+
self.attention_dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 274 |
+
self.output_dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 275 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 276 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 277 |
+
self.pruned_heads = set()
|
| 278 |
+
|
| 279 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
| 280 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 281 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 282 |
+
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
|
| 283 |
+
|
| 284 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfAttention.transpose_for_scores
|
| 285 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
| 286 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 287 |
+
x = x.view(new_x_shape)
|
| 288 |
+
return x.permute(0, 2, 1, 3)
|
| 289 |
+
|
| 290 |
+
def prune_heads(self, heads: List[int]) -> None:
|
| 291 |
+
if len(heads) == 0:
|
| 292 |
+
return
|
| 293 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 294 |
+
heads, self.num_attention_heads, self.attention_head_size, self.pruned_heads
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
# Prune linear layers
|
| 298 |
+
self.query = prune_linear_layer(self.query, index)
|
| 299 |
+
self.key = prune_linear_layer(self.key, index)
|
| 300 |
+
self.value = prune_linear_layer(self.value, index)
|
| 301 |
+
self.dense = prune_linear_layer(self.dense, index, dim=1)
|
| 302 |
+
|
| 303 |
+
# Update hyper params and store pruned heads
|
| 304 |
+
self.num_attention_heads = self.num_attention_heads - len(heads)
|
| 305 |
+
self.all_head_size = self.attention_head_size * self.num_attention_heads
|
| 306 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 307 |
+
|
| 308 |
+
def forward(
|
| 309 |
+
self,
|
| 310 |
+
hidden_states: torch.Tensor,
|
| 311 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 312 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 313 |
+
output_attentions: bool = False,
|
| 314 |
+
) -> Union[Tuple[torch.Tensor], Tuple[torch.Tensor, torch.Tensor]]:
|
| 315 |
+
mixed_query_layer = self.query(hidden_states)
|
| 316 |
+
mixed_key_layer = self.key(hidden_states)
|
| 317 |
+
mixed_value_layer = self.value(hidden_states)
|
| 318 |
+
|
| 319 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 320 |
+
key_layer = self.transpose_for_scores(mixed_key_layer)
|
| 321 |
+
value_layer = self.transpose_for_scores(mixed_value_layer)
|
| 322 |
+
|
| 323 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 324 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 325 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 326 |
+
|
| 327 |
+
if attention_mask is not None:
|
| 328 |
+
# Apply the attention mask is (precomputed for all layers in BertModel forward() function)
|
| 329 |
+
attention_scores = attention_scores + attention_mask
|
| 330 |
+
|
| 331 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 332 |
+
seq_length = hidden_states.size()[1]
|
| 333 |
+
position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
|
| 334 |
+
position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
|
| 335 |
+
distance = position_ids_l - position_ids_r
|
| 336 |
+
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
|
| 337 |
+
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
|
| 338 |
+
|
| 339 |
+
if self.position_embedding_type == "relative_key":
|
| 340 |
+
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 341 |
+
attention_scores = attention_scores + relative_position_scores
|
| 342 |
+
elif self.position_embedding_type == "relative_key_query":
|
| 343 |
+
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 344 |
+
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
|
| 345 |
+
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
|
| 346 |
+
|
| 347 |
+
# Normalize the attention scores to probabilities.
|
| 348 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 349 |
+
|
| 350 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 351 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 352 |
+
attention_probs = self.attention_dropout(attention_probs)
|
| 353 |
+
|
| 354 |
+
# Mask heads if we want to
|
| 355 |
+
if head_mask is not None:
|
| 356 |
+
attention_probs = attention_probs * head_mask
|
| 357 |
+
|
| 358 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 359 |
+
context_layer = context_layer.transpose(2, 1).flatten(2)
|
| 360 |
+
|
| 361 |
+
projected_context_layer = self.dense(context_layer)
|
| 362 |
+
projected_context_layer_dropout = self.output_dropout(projected_context_layer)
|
| 363 |
+
layernormed_context_layer = self.LayerNorm(hidden_states + projected_context_layer_dropout)
|
| 364 |
+
return (layernormed_context_layer, attention_probs) if output_attentions else (layernormed_context_layer,)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
class AlbertSdpaAttention(AlbertAttention):
|
| 368 |
+
def __init__(self, config):
|
| 369 |
+
super().__init__(config)
|
| 370 |
+
self.dropout_prob = config.attention_probs_dropout_prob
|
| 371 |
+
self.require_contiguous_qkv = not is_torch_greater_or_equal_than_2_2
|
| 372 |
+
|
| 373 |
+
def forward(
|
| 374 |
+
self,
|
| 375 |
+
hidden_states: torch.Tensor,
|
| 376 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 377 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 378 |
+
output_attentions: bool = False,
|
| 379 |
+
) -> Union[Tuple[torch.Tensor], Tuple[torch.Tensor, torch.Tensor]]:
|
| 380 |
+
if self.position_embedding_type != "absolute" or output_attentions or head_mask is not None:
|
| 381 |
+
logger.warning(
|
| 382 |
+
"AlbertSdpaAttention is used but `torch.nn.functional.scaled_dot_product_attention` does not support "
|
| 383 |
+
"non-absolute `position_embedding_type` or `output_attentions=True` or `head_mask`. Falling back to "
|
| 384 |
+
"the eager attention implementation, but specifying the eager implementation will be required from "
|
| 385 |
+
"Transformers version v5.0.0 onwards. This warning can be removed using the argument "
|
| 386 |
+
'`attn_implementation="eager"` when loading the model.'
|
| 387 |
+
)
|
| 388 |
+
return super().forward(hidden_states, attention_mask, head_mask, output_attentions)
|
| 389 |
+
|
| 390 |
+
batch_size, seq_len, _ = hidden_states.size()
|
| 391 |
+
query_layer = self.transpose_for_scores(self.query(hidden_states))
|
| 392 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 393 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 394 |
+
|
| 395 |
+
# SDPA with memory-efficient backend is broken in torch==2.1.2 when using non-contiguous inputs and a custom
|
| 396 |
+
# attn_mask, so we need to call `.contiguous()` here. This was fixed in torch==2.2.0.
|
| 397 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577
|
| 398 |
+
if self.require_contiguous_qkv and query_layer.device.type == "cuda" and attention_mask is not None:
|
| 399 |
+
query_layer = query_layer.contiguous()
|
| 400 |
+
key_layer = key_layer.contiguous()
|
| 401 |
+
value_layer = value_layer.contiguous()
|
| 402 |
+
|
| 403 |
+
attention_output = torch.nn.functional.scaled_dot_product_attention(
|
| 404 |
+
query=query_layer,
|
| 405 |
+
key=key_layer,
|
| 406 |
+
value=value_layer,
|
| 407 |
+
attn_mask=attention_mask,
|
| 408 |
+
dropout_p=self.dropout_prob if self.training else 0.0,
|
| 409 |
+
is_causal=False,
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
attention_output = attention_output.transpose(1, 2)
|
| 413 |
+
attention_output = attention_output.reshape(batch_size, seq_len, self.all_head_size)
|
| 414 |
+
|
| 415 |
+
projected_context_layer = self.dense(attention_output)
|
| 416 |
+
projected_context_layer_dropout = self.output_dropout(projected_context_layer)
|
| 417 |
+
layernormed_context_layer = self.LayerNorm(hidden_states + projected_context_layer_dropout)
|
| 418 |
+
return (layernormed_context_layer,)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
ALBERT_ATTENTION_CLASSES = {
|
| 422 |
+
"eager": AlbertAttention,
|
| 423 |
+
"sdpa": AlbertSdpaAttention,
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
class AlbertLayer(nn.Module):
|
| 428 |
+
def __init__(self, config: AlbertConfig):
|
| 429 |
+
super().__init__()
|
| 430 |
+
|
| 431 |
+
self.config = config
|
| 432 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 433 |
+
self.seq_len_dim = 1
|
| 434 |
+
self.full_layer_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 435 |
+
self.attention = ALBERT_ATTENTION_CLASSES[config._attn_implementation](config)
|
| 436 |
+
self.ffn = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 437 |
+
self.ffn_output = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 438 |
+
self.activation = ACT2FN[config.hidden_act]
|
| 439 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 440 |
+
|
| 441 |
+
def forward(
|
| 442 |
+
self,
|
| 443 |
+
hidden_states: torch.Tensor,
|
| 444 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 445 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 446 |
+
output_attentions: bool = False,
|
| 447 |
+
output_hidden_states: bool = False,
|
| 448 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 449 |
+
attention_output = self.attention(hidden_states, attention_mask, head_mask, output_attentions)
|
| 450 |
+
|
| 451 |
+
ffn_output = apply_chunking_to_forward(
|
| 452 |
+
self.ff_chunk,
|
| 453 |
+
self.chunk_size_feed_forward,
|
| 454 |
+
self.seq_len_dim,
|
| 455 |
+
attention_output[0],
|
| 456 |
+
)
|
| 457 |
+
hidden_states = self.full_layer_layer_norm(ffn_output + attention_output[0])
|
| 458 |
+
|
| 459 |
+
return (hidden_states,) + attention_output[1:] # add attentions if we output them
|
| 460 |
+
|
| 461 |
+
def ff_chunk(self, attention_output: torch.Tensor) -> torch.Tensor:
|
| 462 |
+
ffn_output = self.ffn(attention_output)
|
| 463 |
+
ffn_output = self.activation(ffn_output)
|
| 464 |
+
ffn_output = self.ffn_output(ffn_output)
|
| 465 |
+
return ffn_output
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
class AlbertLayerGroup(nn.Module):
|
| 469 |
+
def __init__(self, config: AlbertConfig):
|
| 470 |
+
super().__init__()
|
| 471 |
+
|
| 472 |
+
self.albert_layers = nn.ModuleList([AlbertLayer(config) for _ in range(config.inner_group_num)])
|
| 473 |
+
|
| 474 |
+
def forward(
|
| 475 |
+
self,
|
| 476 |
+
hidden_states: torch.Tensor,
|
| 477 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 478 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 479 |
+
output_attentions: bool = False,
|
| 480 |
+
output_hidden_states: bool = False,
|
| 481 |
+
) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
|
| 482 |
+
layer_hidden_states = ()
|
| 483 |
+
layer_attentions = ()
|
| 484 |
+
|
| 485 |
+
for layer_index, albert_layer in enumerate(self.albert_layers):
|
| 486 |
+
layer_output = albert_layer(hidden_states, attention_mask, head_mask[layer_index], output_attentions)
|
| 487 |
+
hidden_states = layer_output[0]
|
| 488 |
+
|
| 489 |
+
if output_attentions:
|
| 490 |
+
layer_attentions = layer_attentions + (layer_output[1],)
|
| 491 |
+
|
| 492 |
+
if output_hidden_states:
|
| 493 |
+
layer_hidden_states = layer_hidden_states + (hidden_states,)
|
| 494 |
+
|
| 495 |
+
outputs = (hidden_states,)
|
| 496 |
+
if output_hidden_states:
|
| 497 |
+
outputs = outputs + (layer_hidden_states,)
|
| 498 |
+
if output_attentions:
|
| 499 |
+
outputs = outputs + (layer_attentions,)
|
| 500 |
+
return outputs # last-layer hidden state, (layer hidden states), (layer attentions)
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
class AlbertTransformer(nn.Module):
|
| 504 |
+
def __init__(self, config: AlbertConfig):
|
| 505 |
+
super().__init__()
|
| 506 |
+
|
| 507 |
+
self.config = config
|
| 508 |
+
self.embedding_hidden_mapping_in = nn.Linear(config.embedding_size, config.hidden_size)
|
| 509 |
+
self.albert_layer_groups = nn.ModuleList([AlbertLayerGroup(config) for _ in range(config.num_hidden_groups)])
|
| 510 |
+
|
| 511 |
+
def forward(
|
| 512 |
+
self,
|
| 513 |
+
hidden_states: torch.Tensor,
|
| 514 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 515 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 516 |
+
output_attentions: bool = False,
|
| 517 |
+
output_hidden_states: bool = False,
|
| 518 |
+
return_dict: bool = True,
|
| 519 |
+
) -> Union[BaseModelOutput, Tuple]:
|
| 520 |
+
hidden_states = self.embedding_hidden_mapping_in(hidden_states)
|
| 521 |
+
|
| 522 |
+
all_hidden_states = (hidden_states,) if output_hidden_states else None
|
| 523 |
+
all_attentions = () if output_attentions else None
|
| 524 |
+
|
| 525 |
+
head_mask = [None] * self.config.num_hidden_layers if head_mask is None else head_mask
|
| 526 |
+
|
| 527 |
+
for i in range(self.config.num_hidden_layers):
|
| 528 |
+
# Number of layers in a hidden group
|
| 529 |
+
layers_per_group = int(self.config.num_hidden_layers / self.config.num_hidden_groups)
|
| 530 |
+
|
| 531 |
+
# Index of the hidden group
|
| 532 |
+
group_idx = int(i / (self.config.num_hidden_layers / self.config.num_hidden_groups))
|
| 533 |
+
|
| 534 |
+
layer_group_output = self.albert_layer_groups[group_idx](
|
| 535 |
+
hidden_states,
|
| 536 |
+
attention_mask,
|
| 537 |
+
head_mask[group_idx * layers_per_group : (group_idx + 1) * layers_per_group],
|
| 538 |
+
output_attentions,
|
| 539 |
+
output_hidden_states,
|
| 540 |
+
)
|
| 541 |
+
hidden_states = layer_group_output[0]
|
| 542 |
+
|
| 543 |
+
if output_attentions:
|
| 544 |
+
all_attentions = all_attentions + layer_group_output[-1]
|
| 545 |
+
|
| 546 |
+
if output_hidden_states:
|
| 547 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 548 |
+
|
| 549 |
+
if not return_dict:
|
| 550 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
|
| 551 |
+
return BaseModelOutput(
|
| 552 |
+
last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
|
| 553 |
+
)
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
class AlbertPreTrainedModel(PreTrainedModel):
|
| 557 |
+
"""
|
| 558 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 559 |
+
models.
|
| 560 |
+
"""
|
| 561 |
+
|
| 562 |
+
config_class = AlbertConfig
|
| 563 |
+
load_tf_weights = load_tf_weights_in_albert
|
| 564 |
+
base_model_prefix = "albert"
|
| 565 |
+
_supports_sdpa = True
|
| 566 |
+
|
| 567 |
+
def _init_weights(self, module):
|
| 568 |
+
"""Initialize the weights."""
|
| 569 |
+
if isinstance(module, nn.Linear):
|
| 570 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 571 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 572 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 573 |
+
if module.bias is not None:
|
| 574 |
+
module.bias.data.zero_()
|
| 575 |
+
elif isinstance(module, nn.Embedding):
|
| 576 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 577 |
+
if module.padding_idx is not None:
|
| 578 |
+
module.weight.data[module.padding_idx].zero_()
|
| 579 |
+
elif isinstance(module, nn.LayerNorm):
|
| 580 |
+
module.bias.data.zero_()
|
| 581 |
+
module.weight.data.fill_(1.0)
|
| 582 |
+
elif isinstance(module, AlbertMLMHead):
|
| 583 |
+
module.bias.data.zero_()
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
@dataclass
|
| 587 |
+
class AlbertForPreTrainingOutput(ModelOutput):
|
| 588 |
+
"""
|
| 589 |
+
Output type of [`AlbertForPreTraining`].
|
| 590 |
+
|
| 591 |
+
Args:
|
| 592 |
+
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
|
| 593 |
+
Total loss as the sum of the masked language modeling loss and the next sequence prediction
|
| 594 |
+
(classification) loss.
|
| 595 |
+
prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 596 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 597 |
+
sop_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
|
| 598 |
+
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
|
| 599 |
+
before SoftMax).
|
| 600 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 601 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 602 |
+
shape `(batch_size, sequence_length, hidden_size)`.
|
| 603 |
+
|
| 604 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 605 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 606 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 607 |
+
sequence_length)`.
|
| 608 |
+
|
| 609 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 610 |
+
heads.
|
| 611 |
+
"""
|
| 612 |
+
|
| 613 |
+
loss: Optional[torch.FloatTensor] = None
|
| 614 |
+
prediction_logits: Optional[torch.FloatTensor] = None
|
| 615 |
+
sop_logits: Optional[torch.FloatTensor] = None
|
| 616 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 617 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
ALBERT_START_DOCSTRING = r"""
|
| 621 |
+
|
| 622 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 623 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 624 |
+
etc.)
|
| 625 |
+
|
| 626 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 627 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 628 |
+
and behavior.
|
| 629 |
+
|
| 630 |
+
Args:
|
| 631 |
+
config ([`AlbertConfig`]): Model configuration class with all the parameters of the model.
|
| 632 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 633 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 634 |
+
"""
|
| 635 |
+
|
| 636 |
+
ALBERT_INPUTS_DOCSTRING = r"""
|
| 637 |
+
Args:
|
| 638 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
| 639 |
+
Indices of input sequence tokens in the vocabulary.
|
| 640 |
+
|
| 641 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
|
| 642 |
+
[`PreTrainedTokenizer.encode`] for details.
|
| 643 |
+
|
| 644 |
+
[What are input IDs?](../glossary#input-ids)
|
| 645 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
| 646 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 647 |
+
|
| 648 |
+
- 1 for tokens that are **not masked**,
|
| 649 |
+
- 0 for tokens that are **masked**.
|
| 650 |
+
|
| 651 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 652 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 653 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 654 |
+
1]`:
|
| 655 |
+
|
| 656 |
+
- 0 corresponds to a *sentence A* token,
|
| 657 |
+
- 1 corresponds to a *sentence B* token.
|
| 658 |
+
|
| 659 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 660 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 661 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 662 |
+
config.max_position_embeddings - 1]`.
|
| 663 |
+
|
| 664 |
+
[What are position IDs?](../glossary#position-ids)
|
| 665 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 666 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 667 |
+
|
| 668 |
+
- 1 indicates the head is **not masked**,
|
| 669 |
+
- 0 indicates the head is **masked**.
|
| 670 |
+
|
| 671 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
| 672 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 673 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 674 |
+
model's internal embedding lookup matrix.
|
| 675 |
+
output_attentions (`bool`, *optional*):
|
| 676 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 677 |
+
tensors for more detail.
|
| 678 |
+
output_hidden_states (`bool`, *optional*):
|
| 679 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 680 |
+
more detail.
|
| 681 |
+
return_dict (`bool`, *optional*):
|
| 682 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 683 |
+
"""
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
@add_start_docstrings(
|
| 687 |
+
"The bare ALBERT Model transformer outputting raw hidden-states without any specific head on top.",
|
| 688 |
+
ALBERT_START_DOCSTRING,
|
| 689 |
+
)
|
| 690 |
+
class AlbertModel(AlbertPreTrainedModel):
|
| 691 |
+
config_class = AlbertConfig
|
| 692 |
+
base_model_prefix = "albert"
|
| 693 |
+
|
| 694 |
+
def __init__(self, config: AlbertConfig, add_pooling_layer: bool = True):
|
| 695 |
+
super().__init__(config)
|
| 696 |
+
|
| 697 |
+
self.config = config
|
| 698 |
+
self.embeddings = AlbertEmbeddings(config)
|
| 699 |
+
self.encoder = AlbertTransformer(config)
|
| 700 |
+
if add_pooling_layer:
|
| 701 |
+
self.pooler = nn.Linear(config.hidden_size, config.hidden_size)
|
| 702 |
+
self.pooler_activation = nn.Tanh()
|
| 703 |
+
else:
|
| 704 |
+
self.pooler = None
|
| 705 |
+
self.pooler_activation = None
|
| 706 |
+
|
| 707 |
+
self.attn_implementation = config._attn_implementation
|
| 708 |
+
self.position_embedding_type = config.position_embedding_type
|
| 709 |
+
|
| 710 |
+
# Initialize weights and apply final processing
|
| 711 |
+
self.post_init()
|
| 712 |
+
|
| 713 |
+
def get_input_embeddings(self) -> nn.Embedding:
|
| 714 |
+
return self.embeddings.word_embeddings
|
| 715 |
+
|
| 716 |
+
def set_input_embeddings(self, value: nn.Embedding) -> None:
|
| 717 |
+
self.embeddings.word_embeddings = value
|
| 718 |
+
|
| 719 |
+
def _prune_heads(self, heads_to_prune: Dict[int, List[int]]) -> None:
|
| 720 |
+
"""
|
| 721 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} ALBERT has
|
| 722 |
+
a different architecture in that its layers are shared across groups, which then has inner groups. If an ALBERT
|
| 723 |
+
model has 12 hidden layers and 2 hidden groups, with two inner groups, there is a total of 4 different layers.
|
| 724 |
+
|
| 725 |
+
These layers are flattened: the indices [0,1] correspond to the two inner groups of the first hidden layer,
|
| 726 |
+
while [2,3] correspond to the two inner groups of the second hidden layer.
|
| 727 |
+
|
| 728 |
+
Any layer with in index other than [0,1,2,3] will result in an error. See base class PreTrainedModel for more
|
| 729 |
+
information about head pruning
|
| 730 |
+
"""
|
| 731 |
+
for layer, heads in heads_to_prune.items():
|
| 732 |
+
group_idx = int(layer / self.config.inner_group_num)
|
| 733 |
+
inner_group_idx = int(layer - group_idx * self.config.inner_group_num)
|
| 734 |
+
self.encoder.albert_layer_groups[group_idx].albert_layers[inner_group_idx].attention.prune_heads(heads)
|
| 735 |
+
|
| 736 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 737 |
+
@add_code_sample_docstrings(
|
| 738 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 739 |
+
output_type=BaseModelOutputWithPooling,
|
| 740 |
+
config_class=_CONFIG_FOR_DOC,
|
| 741 |
+
)
|
| 742 |
+
def forward(
|
| 743 |
+
self,
|
| 744 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 745 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 746 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 747 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 748 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 749 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 750 |
+
output_attentions: Optional[bool] = None,
|
| 751 |
+
output_hidden_states: Optional[bool] = None,
|
| 752 |
+
return_dict: Optional[bool] = None,
|
| 753 |
+
) -> Union[BaseModelOutputWithPooling, Tuple]:
|
| 754 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 755 |
+
output_hidden_states = (
|
| 756 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 757 |
+
)
|
| 758 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 759 |
+
|
| 760 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 761 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 762 |
+
elif input_ids is not None:
|
| 763 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 764 |
+
input_shape = input_ids.size()
|
| 765 |
+
elif inputs_embeds is not None:
|
| 766 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 767 |
+
else:
|
| 768 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 769 |
+
|
| 770 |
+
batch_size, seq_length = input_shape
|
| 771 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 772 |
+
|
| 773 |
+
if attention_mask is None:
|
| 774 |
+
attention_mask = torch.ones(input_shape, device=device)
|
| 775 |
+
if token_type_ids is None:
|
| 776 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
| 777 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
| 778 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
|
| 779 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 780 |
+
else:
|
| 781 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 782 |
+
|
| 783 |
+
embedding_output = self.embeddings(
|
| 784 |
+
input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
|
| 785 |
+
)
|
| 786 |
+
|
| 787 |
+
use_sdpa_attention_mask = (
|
| 788 |
+
self.attn_implementation == "sdpa"
|
| 789 |
+
and self.position_embedding_type == "absolute"
|
| 790 |
+
and head_mask is None
|
| 791 |
+
and not output_attentions
|
| 792 |
+
)
|
| 793 |
+
|
| 794 |
+
if use_sdpa_attention_mask:
|
| 795 |
+
extended_attention_mask = _prepare_4d_attention_mask_for_sdpa(
|
| 796 |
+
attention_mask, embedding_output.dtype, tgt_len=seq_length
|
| 797 |
+
)
|
| 798 |
+
else:
|
| 799 |
+
extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
| 800 |
+
extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
|
| 801 |
+
extended_attention_mask = (1.0 - extended_attention_mask) * torch.finfo(self.dtype).min
|
| 802 |
+
|
| 803 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 804 |
+
|
| 805 |
+
encoder_outputs = self.encoder(
|
| 806 |
+
embedding_output,
|
| 807 |
+
extended_attention_mask,
|
| 808 |
+
head_mask=head_mask,
|
| 809 |
+
output_attentions=output_attentions,
|
| 810 |
+
output_hidden_states=output_hidden_states,
|
| 811 |
+
return_dict=return_dict,
|
| 812 |
+
)
|
| 813 |
+
|
| 814 |
+
sequence_output = encoder_outputs[0]
|
| 815 |
+
|
| 816 |
+
pooled_output = self.pooler_activation(self.pooler(sequence_output[:, 0])) if self.pooler is not None else None
|
| 817 |
+
|
| 818 |
+
if not return_dict:
|
| 819 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
| 820 |
+
|
| 821 |
+
return BaseModelOutputWithPooling(
|
| 822 |
+
last_hidden_state=sequence_output,
|
| 823 |
+
pooler_output=pooled_output,
|
| 824 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 825 |
+
attentions=encoder_outputs.attentions,
|
| 826 |
+
)
|
| 827 |
+
|
| 828 |
+
|
| 829 |
+
@add_start_docstrings(
|
| 830 |
+
"""
|
| 831 |
+
Albert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a
|
| 832 |
+
`sentence order prediction (classification)` head.
|
| 833 |
+
""",
|
| 834 |
+
ALBERT_START_DOCSTRING,
|
| 835 |
+
)
|
| 836 |
+
class AlbertForPreTraining(AlbertPreTrainedModel):
|
| 837 |
+
_tied_weights_keys = ["predictions.decoder.bias", "predictions.decoder.weight"]
|
| 838 |
+
|
| 839 |
+
def __init__(self, config: AlbertConfig):
|
| 840 |
+
super().__init__(config)
|
| 841 |
+
|
| 842 |
+
self.albert = AlbertModel(config)
|
| 843 |
+
self.predictions = AlbertMLMHead(config)
|
| 844 |
+
self.sop_classifier = AlbertSOPHead(config)
|
| 845 |
+
|
| 846 |
+
# Initialize weights and apply final processing
|
| 847 |
+
self.post_init()
|
| 848 |
+
|
| 849 |
+
def get_output_embeddings(self) -> nn.Linear:
|
| 850 |
+
return self.predictions.decoder
|
| 851 |
+
|
| 852 |
+
def set_output_embeddings(self, new_embeddings: nn.Linear) -> None:
|
| 853 |
+
self.predictions.decoder = new_embeddings
|
| 854 |
+
|
| 855 |
+
def get_input_embeddings(self) -> nn.Embedding:
|
| 856 |
+
return self.albert.embeddings.word_embeddings
|
| 857 |
+
|
| 858 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 859 |
+
@replace_return_docstrings(output_type=AlbertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
|
| 860 |
+
def forward(
|
| 861 |
+
self,
|
| 862 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 863 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 864 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 865 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 866 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 867 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 868 |
+
labels: Optional[torch.LongTensor] = None,
|
| 869 |
+
sentence_order_label: Optional[torch.LongTensor] = None,
|
| 870 |
+
output_attentions: Optional[bool] = None,
|
| 871 |
+
output_hidden_states: Optional[bool] = None,
|
| 872 |
+
return_dict: Optional[bool] = None,
|
| 873 |
+
) -> Union[AlbertForPreTrainingOutput, Tuple]:
|
| 874 |
+
r"""
|
| 875 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 876 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 877 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 878 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 879 |
+
sentence_order_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 880 |
+
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
|
| 881 |
+
(see `input_ids` docstring) Indices should be in `[0, 1]`. `0` indicates original order (sequence A, then
|
| 882 |
+
sequence B), `1` indicates switched order (sequence B, then sequence A).
|
| 883 |
+
|
| 884 |
+
Returns:
|
| 885 |
+
|
| 886 |
+
Example:
|
| 887 |
+
|
| 888 |
+
```python
|
| 889 |
+
>>> from transformers import AutoTokenizer, AlbertForPreTraining
|
| 890 |
+
>>> import torch
|
| 891 |
+
|
| 892 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
|
| 893 |
+
>>> model = AlbertForPreTraining.from_pretrained("albert/albert-base-v2")
|
| 894 |
+
|
| 895 |
+
>>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0)
|
| 896 |
+
>>> # Batch size 1
|
| 897 |
+
>>> outputs = model(input_ids)
|
| 898 |
+
|
| 899 |
+
>>> prediction_logits = outputs.prediction_logits
|
| 900 |
+
>>> sop_logits = outputs.sop_logits
|
| 901 |
+
```"""
|
| 902 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 903 |
+
|
| 904 |
+
outputs = self.albert(
|
| 905 |
+
input_ids,
|
| 906 |
+
attention_mask=attention_mask,
|
| 907 |
+
token_type_ids=token_type_ids,
|
| 908 |
+
position_ids=position_ids,
|
| 909 |
+
head_mask=head_mask,
|
| 910 |
+
inputs_embeds=inputs_embeds,
|
| 911 |
+
output_attentions=output_attentions,
|
| 912 |
+
output_hidden_states=output_hidden_states,
|
| 913 |
+
return_dict=return_dict,
|
| 914 |
+
)
|
| 915 |
+
|
| 916 |
+
sequence_output, pooled_output = outputs[:2]
|
| 917 |
+
|
| 918 |
+
prediction_scores = self.predictions(sequence_output)
|
| 919 |
+
sop_scores = self.sop_classifier(pooled_output)
|
| 920 |
+
|
| 921 |
+
total_loss = None
|
| 922 |
+
if labels is not None and sentence_order_label is not None:
|
| 923 |
+
loss_fct = CrossEntropyLoss()
|
| 924 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 925 |
+
sentence_order_loss = loss_fct(sop_scores.view(-1, 2), sentence_order_label.view(-1))
|
| 926 |
+
total_loss = masked_lm_loss + sentence_order_loss
|
| 927 |
+
|
| 928 |
+
if not return_dict:
|
| 929 |
+
output = (prediction_scores, sop_scores) + outputs[2:]
|
| 930 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 931 |
+
|
| 932 |
+
return AlbertForPreTrainingOutput(
|
| 933 |
+
loss=total_loss,
|
| 934 |
+
prediction_logits=prediction_scores,
|
| 935 |
+
sop_logits=sop_scores,
|
| 936 |
+
hidden_states=outputs.hidden_states,
|
| 937 |
+
attentions=outputs.attentions,
|
| 938 |
+
)
|
| 939 |
+
|
| 940 |
+
|
| 941 |
+
class AlbertMLMHead(nn.Module):
|
| 942 |
+
def __init__(self, config: AlbertConfig):
|
| 943 |
+
super().__init__()
|
| 944 |
+
|
| 945 |
+
self.LayerNorm = nn.LayerNorm(config.embedding_size, eps=config.layer_norm_eps)
|
| 946 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 947 |
+
self.dense = nn.Linear(config.hidden_size, config.embedding_size)
|
| 948 |
+
self.decoder = nn.Linear(config.embedding_size, config.vocab_size)
|
| 949 |
+
self.activation = ACT2FN[config.hidden_act]
|
| 950 |
+
self.decoder.bias = self.bias
|
| 951 |
+
|
| 952 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 953 |
+
hidden_states = self.dense(hidden_states)
|
| 954 |
+
hidden_states = self.activation(hidden_states)
|
| 955 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 956 |
+
hidden_states = self.decoder(hidden_states)
|
| 957 |
+
|
| 958 |
+
prediction_scores = hidden_states
|
| 959 |
+
|
| 960 |
+
return prediction_scores
|
| 961 |
+
|
| 962 |
+
def _tie_weights(self) -> None:
|
| 963 |
+
# For accelerate compatibility and to not break backward compatibility
|
| 964 |
+
if self.decoder.bias.device.type == "meta":
|
| 965 |
+
self.decoder.bias = self.bias
|
| 966 |
+
else:
|
| 967 |
+
# To tie those two weights if they get disconnected (on TPU or when the bias is resized)
|
| 968 |
+
self.bias = self.decoder.bias
|
| 969 |
+
|
| 970 |
+
|
| 971 |
+
class AlbertSOPHead(nn.Module):
|
| 972 |
+
def __init__(self, config: AlbertConfig):
|
| 973 |
+
super().__init__()
|
| 974 |
+
|
| 975 |
+
self.dropout = nn.Dropout(config.classifier_dropout_prob)
|
| 976 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 977 |
+
|
| 978 |
+
def forward(self, pooled_output: torch.Tensor) -> torch.Tensor:
|
| 979 |
+
dropout_pooled_output = self.dropout(pooled_output)
|
| 980 |
+
logits = self.classifier(dropout_pooled_output)
|
| 981 |
+
return logits
|
| 982 |
+
|
| 983 |
+
|
| 984 |
+
@add_start_docstrings(
|
| 985 |
+
"Albert Model with a `language modeling` head on top.",
|
| 986 |
+
ALBERT_START_DOCSTRING,
|
| 987 |
+
)
|
| 988 |
+
class AlbertForMaskedLM(AlbertPreTrainedModel):
|
| 989 |
+
_tied_weights_keys = ["predictions.decoder.bias", "predictions.decoder.weight"]
|
| 990 |
+
|
| 991 |
+
def __init__(self, config):
|
| 992 |
+
super().__init__(config)
|
| 993 |
+
|
| 994 |
+
self.albert = AlbertModel(config, add_pooling_layer=False)
|
| 995 |
+
self.predictions = AlbertMLMHead(config)
|
| 996 |
+
|
| 997 |
+
# Initialize weights and apply final processing
|
| 998 |
+
self.post_init()
|
| 999 |
+
|
| 1000 |
+
def get_output_embeddings(self) -> nn.Linear:
|
| 1001 |
+
return self.predictions.decoder
|
| 1002 |
+
|
| 1003 |
+
def set_output_embeddings(self, new_embeddings: nn.Linear) -> None:
|
| 1004 |
+
self.predictions.decoder = new_embeddings
|
| 1005 |
+
self.predictions.bias = new_embeddings.bias
|
| 1006 |
+
|
| 1007 |
+
def get_input_embeddings(self) -> nn.Embedding:
|
| 1008 |
+
return self.albert.embeddings.word_embeddings
|
| 1009 |
+
|
| 1010 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1011 |
+
@replace_return_docstrings(output_type=MaskedLMOutput, config_class=_CONFIG_FOR_DOC)
|
| 1012 |
+
def forward(
|
| 1013 |
+
self,
|
| 1014 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1015 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1016 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1017 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1018 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1019 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1020 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1021 |
+
output_attentions: Optional[bool] = None,
|
| 1022 |
+
output_hidden_states: Optional[bool] = None,
|
| 1023 |
+
return_dict: Optional[bool] = None,
|
| 1024 |
+
) -> Union[MaskedLMOutput, Tuple]:
|
| 1025 |
+
r"""
|
| 1026 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1027 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 1028 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 1029 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 1030 |
+
|
| 1031 |
+
Returns:
|
| 1032 |
+
|
| 1033 |
+
Example:
|
| 1034 |
+
|
| 1035 |
+
```python
|
| 1036 |
+
>>> import torch
|
| 1037 |
+
>>> from transformers import AutoTokenizer, AlbertForMaskedLM
|
| 1038 |
+
|
| 1039 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
|
| 1040 |
+
>>> model = AlbertForMaskedLM.from_pretrained("albert/albert-base-v2")
|
| 1041 |
+
|
| 1042 |
+
>>> # add mask_token
|
| 1043 |
+
>>> inputs = tokenizer("The capital of [MASK] is Paris.", return_tensors="pt")
|
| 1044 |
+
>>> with torch.no_grad():
|
| 1045 |
+
... logits = model(**inputs).logits
|
| 1046 |
+
|
| 1047 |
+
>>> # retrieve index of [MASK]
|
| 1048 |
+
>>> mask_token_index = (inputs.input_ids == tokenizer.mask_token_id)[0].nonzero(as_tuple=True)[0]
|
| 1049 |
+
>>> predicted_token_id = logits[0, mask_token_index].argmax(axis=-1)
|
| 1050 |
+
>>> tokenizer.decode(predicted_token_id)
|
| 1051 |
+
'france'
|
| 1052 |
+
```
|
| 1053 |
+
|
| 1054 |
+
```python
|
| 1055 |
+
>>> labels = tokenizer("The capital of France is Paris.", return_tensors="pt")["input_ids"]
|
| 1056 |
+
>>> labels = torch.where(inputs.input_ids == tokenizer.mask_token_id, labels, -100)
|
| 1057 |
+
>>> outputs = model(**inputs, labels=labels)
|
| 1058 |
+
>>> round(outputs.loss.item(), 2)
|
| 1059 |
+
0.81
|
| 1060 |
+
```
|
| 1061 |
+
"""
|
| 1062 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1063 |
+
|
| 1064 |
+
outputs = self.albert(
|
| 1065 |
+
input_ids=input_ids,
|
| 1066 |
+
attention_mask=attention_mask,
|
| 1067 |
+
token_type_ids=token_type_ids,
|
| 1068 |
+
position_ids=position_ids,
|
| 1069 |
+
head_mask=head_mask,
|
| 1070 |
+
inputs_embeds=inputs_embeds,
|
| 1071 |
+
output_attentions=output_attentions,
|
| 1072 |
+
output_hidden_states=output_hidden_states,
|
| 1073 |
+
return_dict=return_dict,
|
| 1074 |
+
)
|
| 1075 |
+
sequence_outputs = outputs[0]
|
| 1076 |
+
|
| 1077 |
+
prediction_scores = self.predictions(sequence_outputs)
|
| 1078 |
+
|
| 1079 |
+
masked_lm_loss = None
|
| 1080 |
+
if labels is not None:
|
| 1081 |
+
loss_fct = CrossEntropyLoss()
|
| 1082 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1083 |
+
|
| 1084 |
+
if not return_dict:
|
| 1085 |
+
output = (prediction_scores,) + outputs[2:]
|
| 1086 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 1087 |
+
|
| 1088 |
+
return MaskedLMOutput(
|
| 1089 |
+
loss=masked_lm_loss,
|
| 1090 |
+
logits=prediction_scores,
|
| 1091 |
+
hidden_states=outputs.hidden_states,
|
| 1092 |
+
attentions=outputs.attentions,
|
| 1093 |
+
)
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
@add_start_docstrings(
|
| 1097 |
+
"""
|
| 1098 |
+
Albert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
|
| 1099 |
+
output) e.g. for GLUE tasks.
|
| 1100 |
+
""",
|
| 1101 |
+
ALBERT_START_DOCSTRING,
|
| 1102 |
+
)
|
| 1103 |
+
class AlbertForSequenceClassification(AlbertPreTrainedModel):
|
| 1104 |
+
def __init__(self, config: AlbertConfig):
|
| 1105 |
+
super().__init__(config)
|
| 1106 |
+
self.num_labels = config.num_labels
|
| 1107 |
+
self.config = config
|
| 1108 |
+
|
| 1109 |
+
self.albert = AlbertModel(config)
|
| 1110 |
+
self.dropout = nn.Dropout(config.classifier_dropout_prob)
|
| 1111 |
+
self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)
|
| 1112 |
+
|
| 1113 |
+
# Initialize weights and apply final processing
|
| 1114 |
+
self.post_init()
|
| 1115 |
+
|
| 1116 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1117 |
+
@add_code_sample_docstrings(
|
| 1118 |
+
checkpoint="textattack/albert-base-v2-imdb",
|
| 1119 |
+
output_type=SequenceClassifierOutput,
|
| 1120 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1121 |
+
expected_output="'LABEL_1'",
|
| 1122 |
+
expected_loss=0.12,
|
| 1123 |
+
)
|
| 1124 |
+
def forward(
|
| 1125 |
+
self,
|
| 1126 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1127 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1128 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1129 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1130 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1131 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1132 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1133 |
+
output_attentions: Optional[bool] = None,
|
| 1134 |
+
output_hidden_states: Optional[bool] = None,
|
| 1135 |
+
return_dict: Optional[bool] = None,
|
| 1136 |
+
) -> Union[SequenceClassifierOutput, Tuple]:
|
| 1137 |
+
r"""
|
| 1138 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1139 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1140 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1141 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1142 |
+
"""
|
| 1143 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1144 |
+
|
| 1145 |
+
outputs = self.albert(
|
| 1146 |
+
input_ids=input_ids,
|
| 1147 |
+
attention_mask=attention_mask,
|
| 1148 |
+
token_type_ids=token_type_ids,
|
| 1149 |
+
position_ids=position_ids,
|
| 1150 |
+
head_mask=head_mask,
|
| 1151 |
+
inputs_embeds=inputs_embeds,
|
| 1152 |
+
output_attentions=output_attentions,
|
| 1153 |
+
output_hidden_states=output_hidden_states,
|
| 1154 |
+
return_dict=return_dict,
|
| 1155 |
+
)
|
| 1156 |
+
|
| 1157 |
+
pooled_output = outputs[1]
|
| 1158 |
+
|
| 1159 |
+
pooled_output = self.dropout(pooled_output)
|
| 1160 |
+
logits = self.classifier(pooled_output)
|
| 1161 |
+
|
| 1162 |
+
loss = None
|
| 1163 |
+
if labels is not None:
|
| 1164 |
+
if self.config.problem_type is None:
|
| 1165 |
+
if self.num_labels == 1:
|
| 1166 |
+
self.config.problem_type = "regression"
|
| 1167 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1168 |
+
self.config.problem_type = "single_label_classification"
|
| 1169 |
+
else:
|
| 1170 |
+
self.config.problem_type = "multi_label_classification"
|
| 1171 |
+
|
| 1172 |
+
if self.config.problem_type == "regression":
|
| 1173 |
+
loss_fct = MSELoss()
|
| 1174 |
+
if self.num_labels == 1:
|
| 1175 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 1176 |
+
else:
|
| 1177 |
+
loss = loss_fct(logits, labels)
|
| 1178 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1179 |
+
loss_fct = CrossEntropyLoss()
|
| 1180 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1181 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1182 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1183 |
+
loss = loss_fct(logits, labels)
|
| 1184 |
+
|
| 1185 |
+
if not return_dict:
|
| 1186 |
+
output = (logits,) + outputs[2:]
|
| 1187 |
+
return ((loss,) + output) if loss is not None else output
|
| 1188 |
+
|
| 1189 |
+
return SequenceClassifierOutput(
|
| 1190 |
+
loss=loss,
|
| 1191 |
+
logits=logits,
|
| 1192 |
+
hidden_states=outputs.hidden_states,
|
| 1193 |
+
attentions=outputs.attentions,
|
| 1194 |
+
)
|
| 1195 |
+
|
| 1196 |
+
|
| 1197 |
+
@add_start_docstrings(
|
| 1198 |
+
"""
|
| 1199 |
+
Albert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
| 1200 |
+
Named-Entity-Recognition (NER) tasks.
|
| 1201 |
+
""",
|
| 1202 |
+
ALBERT_START_DOCSTRING,
|
| 1203 |
+
)
|
| 1204 |
+
class AlbertForTokenClassification(AlbertPreTrainedModel):
|
| 1205 |
+
def __init__(self, config: AlbertConfig):
|
| 1206 |
+
super().__init__(config)
|
| 1207 |
+
self.num_labels = config.num_labels
|
| 1208 |
+
|
| 1209 |
+
self.albert = AlbertModel(config, add_pooling_layer=False)
|
| 1210 |
+
classifier_dropout_prob = (
|
| 1211 |
+
config.classifier_dropout_prob
|
| 1212 |
+
if config.classifier_dropout_prob is not None
|
| 1213 |
+
else config.hidden_dropout_prob
|
| 1214 |
+
)
|
| 1215 |
+
self.dropout = nn.Dropout(classifier_dropout_prob)
|
| 1216 |
+
self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)
|
| 1217 |
+
|
| 1218 |
+
# Initialize weights and apply final processing
|
| 1219 |
+
self.post_init()
|
| 1220 |
+
|
| 1221 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1222 |
+
@add_code_sample_docstrings(
|
| 1223 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1224 |
+
output_type=TokenClassifierOutput,
|
| 1225 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1226 |
+
)
|
| 1227 |
+
def forward(
|
| 1228 |
+
self,
|
| 1229 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1230 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1231 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1232 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1233 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1234 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1235 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1236 |
+
output_attentions: Optional[bool] = None,
|
| 1237 |
+
output_hidden_states: Optional[bool] = None,
|
| 1238 |
+
return_dict: Optional[bool] = None,
|
| 1239 |
+
) -> Union[TokenClassifierOutput, Tuple]:
|
| 1240 |
+
r"""
|
| 1241 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1242 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 1243 |
+
"""
|
| 1244 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1245 |
+
|
| 1246 |
+
outputs = self.albert(
|
| 1247 |
+
input_ids,
|
| 1248 |
+
attention_mask=attention_mask,
|
| 1249 |
+
token_type_ids=token_type_ids,
|
| 1250 |
+
position_ids=position_ids,
|
| 1251 |
+
head_mask=head_mask,
|
| 1252 |
+
inputs_embeds=inputs_embeds,
|
| 1253 |
+
output_attentions=output_attentions,
|
| 1254 |
+
output_hidden_states=output_hidden_states,
|
| 1255 |
+
return_dict=return_dict,
|
| 1256 |
+
)
|
| 1257 |
+
|
| 1258 |
+
sequence_output = outputs[0]
|
| 1259 |
+
|
| 1260 |
+
sequence_output = self.dropout(sequence_output)
|
| 1261 |
+
logits = self.classifier(sequence_output)
|
| 1262 |
+
|
| 1263 |
+
loss = None
|
| 1264 |
+
if labels is not None:
|
| 1265 |
+
loss_fct = CrossEntropyLoss()
|
| 1266 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1267 |
+
|
| 1268 |
+
if not return_dict:
|
| 1269 |
+
output = (logits,) + outputs[2:]
|
| 1270 |
+
return ((loss,) + output) if loss is not None else output
|
| 1271 |
+
|
| 1272 |
+
return TokenClassifierOutput(
|
| 1273 |
+
loss=loss,
|
| 1274 |
+
logits=logits,
|
| 1275 |
+
hidden_states=outputs.hidden_states,
|
| 1276 |
+
attentions=outputs.attentions,
|
| 1277 |
+
)
|
| 1278 |
+
|
| 1279 |
+
|
| 1280 |
+
@add_start_docstrings(
|
| 1281 |
+
"""
|
| 1282 |
+
Albert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
|
| 1283 |
+
layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 1284 |
+
""",
|
| 1285 |
+
ALBERT_START_DOCSTRING,
|
| 1286 |
+
)
|
| 1287 |
+
class AlbertForQuestionAnswering(AlbertPreTrainedModel):
|
| 1288 |
+
def __init__(self, config: AlbertConfig):
|
| 1289 |
+
super().__init__(config)
|
| 1290 |
+
self.num_labels = config.num_labels
|
| 1291 |
+
|
| 1292 |
+
self.albert = AlbertModel(config, add_pooling_layer=False)
|
| 1293 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
| 1294 |
+
|
| 1295 |
+
# Initialize weights and apply final processing
|
| 1296 |
+
self.post_init()
|
| 1297 |
+
|
| 1298 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1299 |
+
@add_code_sample_docstrings(
|
| 1300 |
+
checkpoint="twmkn9/albert-base-v2-squad2",
|
| 1301 |
+
output_type=QuestionAnsweringModelOutput,
|
| 1302 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1303 |
+
qa_target_start_index=12,
|
| 1304 |
+
qa_target_end_index=13,
|
| 1305 |
+
expected_output="'a nice puppet'",
|
| 1306 |
+
expected_loss=7.36,
|
| 1307 |
+
)
|
| 1308 |
+
def forward(
|
| 1309 |
+
self,
|
| 1310 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1311 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1312 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1313 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1314 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1315 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1316 |
+
start_positions: Optional[torch.LongTensor] = None,
|
| 1317 |
+
end_positions: Optional[torch.LongTensor] = None,
|
| 1318 |
+
output_attentions: Optional[bool] = None,
|
| 1319 |
+
output_hidden_states: Optional[bool] = None,
|
| 1320 |
+
return_dict: Optional[bool] = None,
|
| 1321 |
+
) -> Union[AlbertForPreTrainingOutput, Tuple]:
|
| 1322 |
+
r"""
|
| 1323 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1324 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 1325 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1326 |
+
are not taken into account for computing the loss.
|
| 1327 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1328 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 1329 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1330 |
+
are not taken into account for computing the loss.
|
| 1331 |
+
"""
|
| 1332 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1333 |
+
|
| 1334 |
+
outputs = self.albert(
|
| 1335 |
+
input_ids=input_ids,
|
| 1336 |
+
attention_mask=attention_mask,
|
| 1337 |
+
token_type_ids=token_type_ids,
|
| 1338 |
+
position_ids=position_ids,
|
| 1339 |
+
head_mask=head_mask,
|
| 1340 |
+
inputs_embeds=inputs_embeds,
|
| 1341 |
+
output_attentions=output_attentions,
|
| 1342 |
+
output_hidden_states=output_hidden_states,
|
| 1343 |
+
return_dict=return_dict,
|
| 1344 |
+
)
|
| 1345 |
+
|
| 1346 |
+
sequence_output = outputs[0]
|
| 1347 |
+
|
| 1348 |
+
logits: torch.Tensor = self.qa_outputs(sequence_output)
|
| 1349 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1350 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 1351 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 1352 |
+
|
| 1353 |
+
total_loss = None
|
| 1354 |
+
if start_positions is not None and end_positions is not None:
|
| 1355 |
+
# If we are on multi-GPU, split add a dimension
|
| 1356 |
+
if len(start_positions.size()) > 1:
|
| 1357 |
+
start_positions = start_positions.squeeze(-1)
|
| 1358 |
+
if len(end_positions.size()) > 1:
|
| 1359 |
+
end_positions = end_positions.squeeze(-1)
|
| 1360 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 1361 |
+
ignored_index = start_logits.size(1)
|
| 1362 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 1363 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 1364 |
+
|
| 1365 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
| 1366 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 1367 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 1368 |
+
total_loss = (start_loss + end_loss) / 2
|
| 1369 |
+
|
| 1370 |
+
if not return_dict:
|
| 1371 |
+
output = (start_logits, end_logits) + outputs[2:]
|
| 1372 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 1373 |
+
|
| 1374 |
+
return QuestionAnsweringModelOutput(
|
| 1375 |
+
loss=total_loss,
|
| 1376 |
+
start_logits=start_logits,
|
| 1377 |
+
end_logits=end_logits,
|
| 1378 |
+
hidden_states=outputs.hidden_states,
|
| 1379 |
+
attentions=outputs.attentions,
|
| 1380 |
+
)
|
| 1381 |
+
|
| 1382 |
+
|
| 1383 |
+
@add_start_docstrings(
|
| 1384 |
+
"""
|
| 1385 |
+
Albert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
|
| 1386 |
+
softmax) e.g. for RocStories/SWAG tasks.
|
| 1387 |
+
""",
|
| 1388 |
+
ALBERT_START_DOCSTRING,
|
| 1389 |
+
)
|
| 1390 |
+
class AlbertForMultipleChoice(AlbertPreTrainedModel):
|
| 1391 |
+
def __init__(self, config: AlbertConfig):
|
| 1392 |
+
super().__init__(config)
|
| 1393 |
+
|
| 1394 |
+
self.albert = AlbertModel(config)
|
| 1395 |
+
self.dropout = nn.Dropout(config.classifier_dropout_prob)
|
| 1396 |
+
self.classifier = nn.Linear(config.hidden_size, 1)
|
| 1397 |
+
|
| 1398 |
+
# Initialize weights and apply final processing
|
| 1399 |
+
self.post_init()
|
| 1400 |
+
|
| 1401 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
|
| 1402 |
+
@add_code_sample_docstrings(
|
| 1403 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1404 |
+
output_type=MultipleChoiceModelOutput,
|
| 1405 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1406 |
+
)
|
| 1407 |
+
def forward(
|
| 1408 |
+
self,
|
| 1409 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1410 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1411 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1412 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1413 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1414 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1415 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1416 |
+
output_attentions: Optional[bool] = None,
|
| 1417 |
+
output_hidden_states: Optional[bool] = None,
|
| 1418 |
+
return_dict: Optional[bool] = None,
|
| 1419 |
+
) -> Union[AlbertForPreTrainingOutput, Tuple]:
|
| 1420 |
+
r"""
|
| 1421 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1422 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
|
| 1423 |
+
num_choices-1]` where *num_choices* is the size of the second dimension of the input tensors. (see
|
| 1424 |
+
*input_ids* above)
|
| 1425 |
+
"""
|
| 1426 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1427 |
+
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
|
| 1428 |
+
|
| 1429 |
+
input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
|
| 1430 |
+
attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
|
| 1431 |
+
token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
|
| 1432 |
+
position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
|
| 1433 |
+
inputs_embeds = (
|
| 1434 |
+
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
|
| 1435 |
+
if inputs_embeds is not None
|
| 1436 |
+
else None
|
| 1437 |
+
)
|
| 1438 |
+
outputs = self.albert(
|
| 1439 |
+
input_ids,
|
| 1440 |
+
attention_mask=attention_mask,
|
| 1441 |
+
token_type_ids=token_type_ids,
|
| 1442 |
+
position_ids=position_ids,
|
| 1443 |
+
head_mask=head_mask,
|
| 1444 |
+
inputs_embeds=inputs_embeds,
|
| 1445 |
+
output_attentions=output_attentions,
|
| 1446 |
+
output_hidden_states=output_hidden_states,
|
| 1447 |
+
return_dict=return_dict,
|
| 1448 |
+
)
|
| 1449 |
+
|
| 1450 |
+
pooled_output = outputs[1]
|
| 1451 |
+
|
| 1452 |
+
pooled_output = self.dropout(pooled_output)
|
| 1453 |
+
logits: torch.Tensor = self.classifier(pooled_output)
|
| 1454 |
+
reshaped_logits = logits.view(-1, num_choices)
|
| 1455 |
+
|
| 1456 |
+
loss = None
|
| 1457 |
+
if labels is not None:
|
| 1458 |
+
loss_fct = CrossEntropyLoss()
|
| 1459 |
+
loss = loss_fct(reshaped_logits, labels)
|
| 1460 |
+
|
| 1461 |
+
if not return_dict:
|
| 1462 |
+
output = (reshaped_logits,) + outputs[2:]
|
| 1463 |
+
return ((loss,) + output) if loss is not None else output
|
| 1464 |
+
|
| 1465 |
+
return MultipleChoiceModelOutput(
|
| 1466 |
+
loss=loss,
|
| 1467 |
+
logits=reshaped_logits,
|
| 1468 |
+
hidden_states=outputs.hidden_states,
|
| 1469 |
+
attentions=outputs.attentions,
|
| 1470 |
+
)
|
| 1471 |
+
|
| 1472 |
+
|
| 1473 |
+
__all__ = [
|
| 1474 |
+
"load_tf_weights_in_albert",
|
| 1475 |
+
"AlbertPreTrainedModel",
|
| 1476 |
+
"AlbertModel",
|
| 1477 |
+
"AlbertForPreTraining",
|
| 1478 |
+
"AlbertForMaskedLM",
|
| 1479 |
+
"AlbertForSequenceClassification",
|
| 1480 |
+
"AlbertForTokenClassification",
|
| 1481 |
+
"AlbertForQuestionAnswering",
|
| 1482 |
+
"AlbertForMultipleChoice",
|
| 1483 |
+
]
|
lib/python3.12/site-packages/transformers/models/albert/modeling_flax_albert.py
ADDED
|
@@ -0,0 +1,1132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 Google AI, Google Brain and the HuggingFace Inc. team.
|
| 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 |
+
|
| 16 |
+
from typing import Callable, Optional, Tuple
|
| 17 |
+
|
| 18 |
+
import flax
|
| 19 |
+
import flax.linen as nn
|
| 20 |
+
import jax
|
| 21 |
+
import jax.numpy as jnp
|
| 22 |
+
import numpy as np
|
| 23 |
+
from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
|
| 24 |
+
from flax.linen.attention import dot_product_attention_weights
|
| 25 |
+
from flax.traverse_util import flatten_dict, unflatten_dict
|
| 26 |
+
from jax import lax
|
| 27 |
+
|
| 28 |
+
from ...modeling_flax_outputs import (
|
| 29 |
+
FlaxBaseModelOutput,
|
| 30 |
+
FlaxBaseModelOutputWithPooling,
|
| 31 |
+
FlaxMaskedLMOutput,
|
| 32 |
+
FlaxMultipleChoiceModelOutput,
|
| 33 |
+
FlaxQuestionAnsweringModelOutput,
|
| 34 |
+
FlaxSequenceClassifierOutput,
|
| 35 |
+
FlaxTokenClassifierOutput,
|
| 36 |
+
)
|
| 37 |
+
from ...modeling_flax_utils import (
|
| 38 |
+
ACT2FN,
|
| 39 |
+
FlaxPreTrainedModel,
|
| 40 |
+
append_call_sample_docstring,
|
| 41 |
+
append_replace_return_docstrings,
|
| 42 |
+
overwrite_call_docstring,
|
| 43 |
+
)
|
| 44 |
+
from ...utils import ModelOutput, add_start_docstrings, add_start_docstrings_to_model_forward, logging
|
| 45 |
+
from .configuration_albert import AlbertConfig
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
logger = logging.get_logger(__name__)
|
| 49 |
+
|
| 50 |
+
_CHECKPOINT_FOR_DOC = "albert/albert-base-v2"
|
| 51 |
+
_CONFIG_FOR_DOC = "AlbertConfig"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@flax.struct.dataclass
|
| 55 |
+
class FlaxAlbertForPreTrainingOutput(ModelOutput):
|
| 56 |
+
"""
|
| 57 |
+
Output type of [`FlaxAlbertForPreTraining`].
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
prediction_logits (`jnp.ndarray` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 61 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 62 |
+
sop_logits (`jnp.ndarray` of shape `(batch_size, 2)`):
|
| 63 |
+
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
|
| 64 |
+
before SoftMax).
|
| 65 |
+
hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 66 |
+
Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 67 |
+
`(batch_size, sequence_length, hidden_size)`.
|
| 68 |
+
|
| 69 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 70 |
+
attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 71 |
+
Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 72 |
+
sequence_length)`.
|
| 73 |
+
|
| 74 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 75 |
+
heads.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
prediction_logits: jnp.ndarray = None
|
| 79 |
+
sop_logits: jnp.ndarray = None
|
| 80 |
+
hidden_states: Optional[Tuple[jnp.ndarray]] = None
|
| 81 |
+
attentions: Optional[Tuple[jnp.ndarray]] = None
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
ALBERT_START_DOCSTRING = r"""
|
| 85 |
+
|
| 86 |
+
This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 87 |
+
library implements for all its model (such as downloading, saving and converting weights from PyTorch models)
|
| 88 |
+
|
| 89 |
+
This model is also a
|
| 90 |
+
[flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html) subclass. Use it as
|
| 91 |
+
a regular Flax linen Module and refer to the Flax documentation for all matter related to general usage and
|
| 92 |
+
behavior.
|
| 93 |
+
|
| 94 |
+
Finally, this model supports inherent JAX features such as:
|
| 95 |
+
|
| 96 |
+
- [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
|
| 97 |
+
- [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
|
| 98 |
+
- [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
|
| 99 |
+
- [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
|
| 100 |
+
|
| 101 |
+
Parameters:
|
| 102 |
+
config ([`AlbertConfig`]): Model configuration class with all the parameters of the model.
|
| 103 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 104 |
+
configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 105 |
+
dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
|
| 106 |
+
The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
|
| 107 |
+
`jax.numpy.bfloat16` (on TPUs).
|
| 108 |
+
|
| 109 |
+
This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
|
| 110 |
+
specified all the computation will be performed with the given `dtype`.
|
| 111 |
+
|
| 112 |
+
**Note that this only specifies the dtype of the computation and does not influence the dtype of model
|
| 113 |
+
parameters.**
|
| 114 |
+
|
| 115 |
+
If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
|
| 116 |
+
[`~FlaxPreTrainedModel.to_bf16`].
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
ALBERT_INPUTS_DOCSTRING = r"""
|
| 120 |
+
Args:
|
| 121 |
+
input_ids (`numpy.ndarray` of shape `({0})`):
|
| 122 |
+
Indices of input sequence tokens in the vocabulary.
|
| 123 |
+
|
| 124 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 125 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 126 |
+
|
| 127 |
+
[What are input IDs?](../glossary#input-ids)
|
| 128 |
+
attention_mask (`numpy.ndarray` of shape `({0})`, *optional*):
|
| 129 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 130 |
+
|
| 131 |
+
- 1 for tokens that are **not masked**,
|
| 132 |
+
- 0 for tokens that are **masked**.
|
| 133 |
+
|
| 134 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 135 |
+
token_type_ids (`numpy.ndarray` of shape `({0})`, *optional*):
|
| 136 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 137 |
+
1]`:
|
| 138 |
+
|
| 139 |
+
- 0 corresponds to a *sentence A* token,
|
| 140 |
+
- 1 corresponds to a *sentence B* token.
|
| 141 |
+
|
| 142 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 143 |
+
position_ids (`numpy.ndarray` of shape `({0})`, *optional*):
|
| 144 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 145 |
+
config.max_position_embeddings - 1]`.
|
| 146 |
+
return_dict (`bool`, *optional*):
|
| 147 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 148 |
+
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class FlaxAlbertEmbeddings(nn.Module):
|
| 153 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 154 |
+
|
| 155 |
+
config: AlbertConfig
|
| 156 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 157 |
+
|
| 158 |
+
def setup(self):
|
| 159 |
+
self.word_embeddings = nn.Embed(
|
| 160 |
+
self.config.vocab_size,
|
| 161 |
+
self.config.embedding_size,
|
| 162 |
+
embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 163 |
+
)
|
| 164 |
+
self.position_embeddings = nn.Embed(
|
| 165 |
+
self.config.max_position_embeddings,
|
| 166 |
+
self.config.embedding_size,
|
| 167 |
+
embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 168 |
+
)
|
| 169 |
+
self.token_type_embeddings = nn.Embed(
|
| 170 |
+
self.config.type_vocab_size,
|
| 171 |
+
self.config.embedding_size,
|
| 172 |
+
embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 173 |
+
)
|
| 174 |
+
self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 175 |
+
self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
|
| 176 |
+
|
| 177 |
+
def __call__(self, input_ids, token_type_ids, position_ids, deterministic: bool = True):
|
| 178 |
+
# Embed
|
| 179 |
+
inputs_embeds = self.word_embeddings(input_ids.astype("i4"))
|
| 180 |
+
position_embeds = self.position_embeddings(position_ids.astype("i4"))
|
| 181 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids.astype("i4"))
|
| 182 |
+
|
| 183 |
+
# Sum all embeddings
|
| 184 |
+
hidden_states = inputs_embeds + token_type_embeddings + position_embeds
|
| 185 |
+
|
| 186 |
+
# Layer Norm
|
| 187 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 188 |
+
hidden_states = self.dropout(hidden_states, deterministic=deterministic)
|
| 189 |
+
return hidden_states
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class FlaxAlbertSelfAttention(nn.Module):
|
| 193 |
+
config: AlbertConfig
|
| 194 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 195 |
+
|
| 196 |
+
def setup(self):
|
| 197 |
+
if self.config.hidden_size % self.config.num_attention_heads != 0:
|
| 198 |
+
raise ValueError(
|
| 199 |
+
"`config.hidden_size`: {self.config.hidden_size} has to be a multiple of `config.num_attention_heads` "
|
| 200 |
+
" : {self.config.num_attention_heads}"
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
self.query = nn.Dense(
|
| 204 |
+
self.config.hidden_size,
|
| 205 |
+
dtype=self.dtype,
|
| 206 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 207 |
+
)
|
| 208 |
+
self.key = nn.Dense(
|
| 209 |
+
self.config.hidden_size,
|
| 210 |
+
dtype=self.dtype,
|
| 211 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 212 |
+
)
|
| 213 |
+
self.value = nn.Dense(
|
| 214 |
+
self.config.hidden_size,
|
| 215 |
+
dtype=self.dtype,
|
| 216 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 217 |
+
)
|
| 218 |
+
self.dense = nn.Dense(
|
| 219 |
+
self.config.hidden_size,
|
| 220 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 221 |
+
dtype=self.dtype,
|
| 222 |
+
)
|
| 223 |
+
self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 224 |
+
self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
|
| 225 |
+
|
| 226 |
+
def __call__(self, hidden_states, attention_mask, deterministic=True, output_attentions: bool = False):
|
| 227 |
+
head_dim = self.config.hidden_size // self.config.num_attention_heads
|
| 228 |
+
|
| 229 |
+
query_states = self.query(hidden_states).reshape(
|
| 230 |
+
hidden_states.shape[:2] + (self.config.num_attention_heads, head_dim)
|
| 231 |
+
)
|
| 232 |
+
value_states = self.value(hidden_states).reshape(
|
| 233 |
+
hidden_states.shape[:2] + (self.config.num_attention_heads, head_dim)
|
| 234 |
+
)
|
| 235 |
+
key_states = self.key(hidden_states).reshape(
|
| 236 |
+
hidden_states.shape[:2] + (self.config.num_attention_heads, head_dim)
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
# Convert the boolean attention mask to an attention bias.
|
| 240 |
+
if attention_mask is not None:
|
| 241 |
+
# attention mask in the form of attention bias
|
| 242 |
+
attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))
|
| 243 |
+
attention_bias = lax.select(
|
| 244 |
+
attention_mask > 0,
|
| 245 |
+
jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
|
| 246 |
+
jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
|
| 247 |
+
)
|
| 248 |
+
else:
|
| 249 |
+
attention_bias = None
|
| 250 |
+
|
| 251 |
+
dropout_rng = None
|
| 252 |
+
if not deterministic and self.config.attention_probs_dropout_prob > 0.0:
|
| 253 |
+
dropout_rng = self.make_rng("dropout")
|
| 254 |
+
|
| 255 |
+
attn_weights = dot_product_attention_weights(
|
| 256 |
+
query_states,
|
| 257 |
+
key_states,
|
| 258 |
+
bias=attention_bias,
|
| 259 |
+
dropout_rng=dropout_rng,
|
| 260 |
+
dropout_rate=self.config.attention_probs_dropout_prob,
|
| 261 |
+
broadcast_dropout=True,
|
| 262 |
+
deterministic=deterministic,
|
| 263 |
+
dtype=self.dtype,
|
| 264 |
+
precision=None,
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value_states)
|
| 268 |
+
attn_output = attn_output.reshape(attn_output.shape[:2] + (-1,))
|
| 269 |
+
|
| 270 |
+
projected_attn_output = self.dense(attn_output)
|
| 271 |
+
projected_attn_output = self.dropout(projected_attn_output, deterministic=deterministic)
|
| 272 |
+
layernormed_attn_output = self.LayerNorm(projected_attn_output + hidden_states)
|
| 273 |
+
outputs = (layernormed_attn_output, attn_weights) if output_attentions else (layernormed_attn_output,)
|
| 274 |
+
return outputs
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
class FlaxAlbertLayer(nn.Module):
|
| 278 |
+
config: AlbertConfig
|
| 279 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 280 |
+
|
| 281 |
+
def setup(self):
|
| 282 |
+
self.attention = FlaxAlbertSelfAttention(self.config, dtype=self.dtype)
|
| 283 |
+
self.ffn = nn.Dense(
|
| 284 |
+
self.config.intermediate_size,
|
| 285 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 286 |
+
dtype=self.dtype,
|
| 287 |
+
)
|
| 288 |
+
self.activation = ACT2FN[self.config.hidden_act]
|
| 289 |
+
self.ffn_output = nn.Dense(
|
| 290 |
+
self.config.hidden_size,
|
| 291 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 292 |
+
dtype=self.dtype,
|
| 293 |
+
)
|
| 294 |
+
self.full_layer_layer_norm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 295 |
+
self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
|
| 296 |
+
|
| 297 |
+
def __call__(
|
| 298 |
+
self,
|
| 299 |
+
hidden_states,
|
| 300 |
+
attention_mask,
|
| 301 |
+
deterministic: bool = True,
|
| 302 |
+
output_attentions: bool = False,
|
| 303 |
+
):
|
| 304 |
+
attention_outputs = self.attention(
|
| 305 |
+
hidden_states, attention_mask, deterministic=deterministic, output_attentions=output_attentions
|
| 306 |
+
)
|
| 307 |
+
attention_output = attention_outputs[0]
|
| 308 |
+
ffn_output = self.ffn(attention_output)
|
| 309 |
+
ffn_output = self.activation(ffn_output)
|
| 310 |
+
ffn_output = self.ffn_output(ffn_output)
|
| 311 |
+
ffn_output = self.dropout(ffn_output, deterministic=deterministic)
|
| 312 |
+
hidden_states = self.full_layer_layer_norm(ffn_output + attention_output)
|
| 313 |
+
|
| 314 |
+
outputs = (hidden_states,)
|
| 315 |
+
|
| 316 |
+
if output_attentions:
|
| 317 |
+
outputs += (attention_outputs[1],)
|
| 318 |
+
return outputs
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
class FlaxAlbertLayerCollection(nn.Module):
|
| 322 |
+
config: AlbertConfig
|
| 323 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 324 |
+
|
| 325 |
+
def setup(self):
|
| 326 |
+
self.layers = [
|
| 327 |
+
FlaxAlbertLayer(self.config, name=str(i), dtype=self.dtype) for i in range(self.config.inner_group_num)
|
| 328 |
+
]
|
| 329 |
+
|
| 330 |
+
def __call__(
|
| 331 |
+
self,
|
| 332 |
+
hidden_states,
|
| 333 |
+
attention_mask,
|
| 334 |
+
deterministic: bool = True,
|
| 335 |
+
output_attentions: bool = False,
|
| 336 |
+
output_hidden_states: bool = False,
|
| 337 |
+
):
|
| 338 |
+
layer_hidden_states = ()
|
| 339 |
+
layer_attentions = ()
|
| 340 |
+
|
| 341 |
+
for layer_index, albert_layer in enumerate(self.layers):
|
| 342 |
+
layer_output = albert_layer(
|
| 343 |
+
hidden_states,
|
| 344 |
+
attention_mask,
|
| 345 |
+
deterministic=deterministic,
|
| 346 |
+
output_attentions=output_attentions,
|
| 347 |
+
)
|
| 348 |
+
hidden_states = layer_output[0]
|
| 349 |
+
|
| 350 |
+
if output_attentions:
|
| 351 |
+
layer_attentions = layer_attentions + (layer_output[1],)
|
| 352 |
+
|
| 353 |
+
if output_hidden_states:
|
| 354 |
+
layer_hidden_states = layer_hidden_states + (hidden_states,)
|
| 355 |
+
|
| 356 |
+
outputs = (hidden_states,)
|
| 357 |
+
if output_hidden_states:
|
| 358 |
+
outputs = outputs + (layer_hidden_states,)
|
| 359 |
+
if output_attentions:
|
| 360 |
+
outputs = outputs + (layer_attentions,)
|
| 361 |
+
return outputs # last-layer hidden state, (layer hidden states), (layer attentions)
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
class FlaxAlbertLayerCollections(nn.Module):
|
| 365 |
+
config: AlbertConfig
|
| 366 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 367 |
+
layer_index: Optional[str] = None
|
| 368 |
+
|
| 369 |
+
def setup(self):
|
| 370 |
+
self.albert_layers = FlaxAlbertLayerCollection(self.config, dtype=self.dtype)
|
| 371 |
+
|
| 372 |
+
def __call__(
|
| 373 |
+
self,
|
| 374 |
+
hidden_states,
|
| 375 |
+
attention_mask,
|
| 376 |
+
deterministic: bool = True,
|
| 377 |
+
output_attentions: bool = False,
|
| 378 |
+
output_hidden_states: bool = False,
|
| 379 |
+
):
|
| 380 |
+
outputs = self.albert_layers(
|
| 381 |
+
hidden_states,
|
| 382 |
+
attention_mask,
|
| 383 |
+
deterministic=deterministic,
|
| 384 |
+
output_attentions=output_attentions,
|
| 385 |
+
output_hidden_states=output_hidden_states,
|
| 386 |
+
)
|
| 387 |
+
return outputs
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
class FlaxAlbertLayerGroups(nn.Module):
|
| 391 |
+
config: AlbertConfig
|
| 392 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 393 |
+
|
| 394 |
+
def setup(self):
|
| 395 |
+
self.layers = [
|
| 396 |
+
FlaxAlbertLayerCollections(self.config, name=str(i), layer_index=str(i), dtype=self.dtype)
|
| 397 |
+
for i in range(self.config.num_hidden_groups)
|
| 398 |
+
]
|
| 399 |
+
|
| 400 |
+
def __call__(
|
| 401 |
+
self,
|
| 402 |
+
hidden_states,
|
| 403 |
+
attention_mask,
|
| 404 |
+
deterministic: bool = True,
|
| 405 |
+
output_attentions: bool = False,
|
| 406 |
+
output_hidden_states: bool = False,
|
| 407 |
+
return_dict: bool = True,
|
| 408 |
+
):
|
| 409 |
+
all_attentions = () if output_attentions else None
|
| 410 |
+
all_hidden_states = (hidden_states,) if output_hidden_states else None
|
| 411 |
+
|
| 412 |
+
for i in range(self.config.num_hidden_layers):
|
| 413 |
+
# Index of the hidden group
|
| 414 |
+
group_idx = int(i / (self.config.num_hidden_layers / self.config.num_hidden_groups))
|
| 415 |
+
layer_group_output = self.layers[group_idx](
|
| 416 |
+
hidden_states,
|
| 417 |
+
attention_mask,
|
| 418 |
+
deterministic=deterministic,
|
| 419 |
+
output_attentions=output_attentions,
|
| 420 |
+
output_hidden_states=output_hidden_states,
|
| 421 |
+
)
|
| 422 |
+
hidden_states = layer_group_output[0]
|
| 423 |
+
|
| 424 |
+
if output_attentions:
|
| 425 |
+
all_attentions = all_attentions + layer_group_output[-1]
|
| 426 |
+
|
| 427 |
+
if output_hidden_states:
|
| 428 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 429 |
+
|
| 430 |
+
if not return_dict:
|
| 431 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
|
| 432 |
+
return FlaxBaseModelOutput(
|
| 433 |
+
last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
class FlaxAlbertEncoder(nn.Module):
|
| 438 |
+
config: AlbertConfig
|
| 439 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 440 |
+
|
| 441 |
+
def setup(self):
|
| 442 |
+
self.embedding_hidden_mapping_in = nn.Dense(
|
| 443 |
+
self.config.hidden_size,
|
| 444 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 445 |
+
dtype=self.dtype,
|
| 446 |
+
)
|
| 447 |
+
self.albert_layer_groups = FlaxAlbertLayerGroups(self.config, dtype=self.dtype)
|
| 448 |
+
|
| 449 |
+
def __call__(
|
| 450 |
+
self,
|
| 451 |
+
hidden_states,
|
| 452 |
+
attention_mask,
|
| 453 |
+
deterministic: bool = True,
|
| 454 |
+
output_attentions: bool = False,
|
| 455 |
+
output_hidden_states: bool = False,
|
| 456 |
+
return_dict: bool = True,
|
| 457 |
+
):
|
| 458 |
+
hidden_states = self.embedding_hidden_mapping_in(hidden_states)
|
| 459 |
+
return self.albert_layer_groups(
|
| 460 |
+
hidden_states,
|
| 461 |
+
attention_mask,
|
| 462 |
+
deterministic=deterministic,
|
| 463 |
+
output_attentions=output_attentions,
|
| 464 |
+
output_hidden_states=output_hidden_states,
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
class FlaxAlbertOnlyMLMHead(nn.Module):
|
| 469 |
+
config: AlbertConfig
|
| 470 |
+
dtype: jnp.dtype = jnp.float32
|
| 471 |
+
bias_init: Callable[..., np.ndarray] = jax.nn.initializers.zeros
|
| 472 |
+
|
| 473 |
+
def setup(self):
|
| 474 |
+
self.dense = nn.Dense(self.config.embedding_size, dtype=self.dtype)
|
| 475 |
+
self.activation = ACT2FN[self.config.hidden_act]
|
| 476 |
+
self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 477 |
+
self.decoder = nn.Dense(self.config.vocab_size, dtype=self.dtype, use_bias=False)
|
| 478 |
+
self.bias = self.param("bias", self.bias_init, (self.config.vocab_size,))
|
| 479 |
+
|
| 480 |
+
def __call__(self, hidden_states, shared_embedding=None):
|
| 481 |
+
hidden_states = self.dense(hidden_states)
|
| 482 |
+
hidden_states = self.activation(hidden_states)
|
| 483 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 484 |
+
|
| 485 |
+
if shared_embedding is not None:
|
| 486 |
+
hidden_states = self.decoder.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
|
| 487 |
+
else:
|
| 488 |
+
hidden_states = self.decoder(hidden_states)
|
| 489 |
+
|
| 490 |
+
hidden_states += self.bias
|
| 491 |
+
return hidden_states
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
class FlaxAlbertSOPHead(nn.Module):
|
| 495 |
+
config: AlbertConfig
|
| 496 |
+
dtype: jnp.dtype = jnp.float32
|
| 497 |
+
|
| 498 |
+
def setup(self):
|
| 499 |
+
self.dropout = nn.Dropout(self.config.classifier_dropout_prob)
|
| 500 |
+
self.classifier = nn.Dense(2, dtype=self.dtype)
|
| 501 |
+
|
| 502 |
+
def __call__(self, pooled_output, deterministic=True):
|
| 503 |
+
pooled_output = self.dropout(pooled_output, deterministic=deterministic)
|
| 504 |
+
logits = self.classifier(pooled_output)
|
| 505 |
+
return logits
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
class FlaxAlbertPreTrainedModel(FlaxPreTrainedModel):
|
| 509 |
+
"""
|
| 510 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 511 |
+
models.
|
| 512 |
+
"""
|
| 513 |
+
|
| 514 |
+
config_class = AlbertConfig
|
| 515 |
+
base_model_prefix = "albert"
|
| 516 |
+
module_class: nn.Module = None
|
| 517 |
+
|
| 518 |
+
def __init__(
|
| 519 |
+
self,
|
| 520 |
+
config: AlbertConfig,
|
| 521 |
+
input_shape: Tuple = (1, 1),
|
| 522 |
+
seed: int = 0,
|
| 523 |
+
dtype: jnp.dtype = jnp.float32,
|
| 524 |
+
_do_init: bool = True,
|
| 525 |
+
**kwargs,
|
| 526 |
+
):
|
| 527 |
+
module = self.module_class(config=config, dtype=dtype, **kwargs)
|
| 528 |
+
super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
|
| 529 |
+
|
| 530 |
+
def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
|
| 531 |
+
# init input tensors
|
| 532 |
+
input_ids = jnp.zeros(input_shape, dtype="i4")
|
| 533 |
+
token_type_ids = jnp.zeros_like(input_ids)
|
| 534 |
+
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_shape)
|
| 535 |
+
attention_mask = jnp.ones_like(input_ids)
|
| 536 |
+
|
| 537 |
+
params_rng, dropout_rng = jax.random.split(rng)
|
| 538 |
+
rngs = {"params": params_rng, "dropout": dropout_rng}
|
| 539 |
+
|
| 540 |
+
random_params = self.module.init(
|
| 541 |
+
rngs, input_ids, attention_mask, token_type_ids, position_ids, return_dict=False
|
| 542 |
+
)["params"]
|
| 543 |
+
|
| 544 |
+
if params is not None:
|
| 545 |
+
random_params = flatten_dict(unfreeze(random_params))
|
| 546 |
+
params = flatten_dict(unfreeze(params))
|
| 547 |
+
for missing_key in self._missing_keys:
|
| 548 |
+
params[missing_key] = random_params[missing_key]
|
| 549 |
+
self._missing_keys = set()
|
| 550 |
+
return freeze(unflatten_dict(params))
|
| 551 |
+
else:
|
| 552 |
+
return random_params
|
| 553 |
+
|
| 554 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 555 |
+
def __call__(
|
| 556 |
+
self,
|
| 557 |
+
input_ids,
|
| 558 |
+
attention_mask=None,
|
| 559 |
+
token_type_ids=None,
|
| 560 |
+
position_ids=None,
|
| 561 |
+
params: dict = None,
|
| 562 |
+
dropout_rng: jax.random.PRNGKey = None,
|
| 563 |
+
train: bool = False,
|
| 564 |
+
output_attentions: Optional[bool] = None,
|
| 565 |
+
output_hidden_states: Optional[bool] = None,
|
| 566 |
+
return_dict: Optional[bool] = None,
|
| 567 |
+
):
|
| 568 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 569 |
+
output_hidden_states = (
|
| 570 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 571 |
+
)
|
| 572 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 573 |
+
|
| 574 |
+
# init input tensors if not passed
|
| 575 |
+
if token_type_ids is None:
|
| 576 |
+
token_type_ids = jnp.zeros_like(input_ids)
|
| 577 |
+
|
| 578 |
+
if position_ids is None:
|
| 579 |
+
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
|
| 580 |
+
|
| 581 |
+
if attention_mask is None:
|
| 582 |
+
attention_mask = jnp.ones_like(input_ids)
|
| 583 |
+
|
| 584 |
+
# Handle any PRNG if needed
|
| 585 |
+
rngs = {}
|
| 586 |
+
if dropout_rng is not None:
|
| 587 |
+
rngs["dropout"] = dropout_rng
|
| 588 |
+
|
| 589 |
+
return self.module.apply(
|
| 590 |
+
{"params": params or self.params},
|
| 591 |
+
jnp.array(input_ids, dtype="i4"),
|
| 592 |
+
jnp.array(attention_mask, dtype="i4"),
|
| 593 |
+
jnp.array(token_type_ids, dtype="i4"),
|
| 594 |
+
jnp.array(position_ids, dtype="i4"),
|
| 595 |
+
not train,
|
| 596 |
+
output_attentions,
|
| 597 |
+
output_hidden_states,
|
| 598 |
+
return_dict,
|
| 599 |
+
rngs=rngs,
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
class FlaxAlbertModule(nn.Module):
|
| 604 |
+
config: AlbertConfig
|
| 605 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 606 |
+
add_pooling_layer: bool = True
|
| 607 |
+
|
| 608 |
+
def setup(self):
|
| 609 |
+
self.embeddings = FlaxAlbertEmbeddings(self.config, dtype=self.dtype)
|
| 610 |
+
self.encoder = FlaxAlbertEncoder(self.config, dtype=self.dtype)
|
| 611 |
+
if self.add_pooling_layer:
|
| 612 |
+
self.pooler = nn.Dense(
|
| 613 |
+
self.config.hidden_size,
|
| 614 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 615 |
+
dtype=self.dtype,
|
| 616 |
+
name="pooler",
|
| 617 |
+
)
|
| 618 |
+
self.pooler_activation = nn.tanh
|
| 619 |
+
else:
|
| 620 |
+
self.pooler = None
|
| 621 |
+
self.pooler_activation = None
|
| 622 |
+
|
| 623 |
+
def __call__(
|
| 624 |
+
self,
|
| 625 |
+
input_ids,
|
| 626 |
+
attention_mask,
|
| 627 |
+
token_type_ids: Optional[np.ndarray] = None,
|
| 628 |
+
position_ids: Optional[np.ndarray] = None,
|
| 629 |
+
deterministic: bool = True,
|
| 630 |
+
output_attentions: bool = False,
|
| 631 |
+
output_hidden_states: bool = False,
|
| 632 |
+
return_dict: bool = True,
|
| 633 |
+
):
|
| 634 |
+
# make sure `token_type_ids` is correctly initialized when not passed
|
| 635 |
+
if token_type_ids is None:
|
| 636 |
+
token_type_ids = jnp.zeros_like(input_ids)
|
| 637 |
+
|
| 638 |
+
# make sure `position_ids` is correctly initialized when not passed
|
| 639 |
+
if position_ids is None:
|
| 640 |
+
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
|
| 641 |
+
|
| 642 |
+
hidden_states = self.embeddings(input_ids, token_type_ids, position_ids, deterministic=deterministic)
|
| 643 |
+
|
| 644 |
+
outputs = self.encoder(
|
| 645 |
+
hidden_states,
|
| 646 |
+
attention_mask,
|
| 647 |
+
deterministic=deterministic,
|
| 648 |
+
output_attentions=output_attentions,
|
| 649 |
+
output_hidden_states=output_hidden_states,
|
| 650 |
+
return_dict=return_dict,
|
| 651 |
+
)
|
| 652 |
+
hidden_states = outputs[0]
|
| 653 |
+
if self.add_pooling_layer:
|
| 654 |
+
pooled = self.pooler(hidden_states[:, 0])
|
| 655 |
+
pooled = self.pooler_activation(pooled)
|
| 656 |
+
else:
|
| 657 |
+
pooled = None
|
| 658 |
+
|
| 659 |
+
if not return_dict:
|
| 660 |
+
# if pooled is None, don't return it
|
| 661 |
+
if pooled is None:
|
| 662 |
+
return (hidden_states,) + outputs[1:]
|
| 663 |
+
return (hidden_states, pooled) + outputs[1:]
|
| 664 |
+
|
| 665 |
+
return FlaxBaseModelOutputWithPooling(
|
| 666 |
+
last_hidden_state=hidden_states,
|
| 667 |
+
pooler_output=pooled,
|
| 668 |
+
hidden_states=outputs.hidden_states,
|
| 669 |
+
attentions=outputs.attentions,
|
| 670 |
+
)
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
@add_start_docstrings(
|
| 674 |
+
"The bare Albert Model transformer outputting raw hidden-states without any specific head on top.",
|
| 675 |
+
ALBERT_START_DOCSTRING,
|
| 676 |
+
)
|
| 677 |
+
class FlaxAlbertModel(FlaxAlbertPreTrainedModel):
|
| 678 |
+
module_class = FlaxAlbertModule
|
| 679 |
+
|
| 680 |
+
|
| 681 |
+
append_call_sample_docstring(FlaxAlbertModel, _CHECKPOINT_FOR_DOC, FlaxBaseModelOutputWithPooling, _CONFIG_FOR_DOC)
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
class FlaxAlbertForPreTrainingModule(nn.Module):
|
| 685 |
+
config: AlbertConfig
|
| 686 |
+
dtype: jnp.dtype = jnp.float32
|
| 687 |
+
|
| 688 |
+
def setup(self):
|
| 689 |
+
self.albert = FlaxAlbertModule(config=self.config, dtype=self.dtype)
|
| 690 |
+
self.predictions = FlaxAlbertOnlyMLMHead(config=self.config, dtype=self.dtype)
|
| 691 |
+
self.sop_classifier = FlaxAlbertSOPHead(config=self.config, dtype=self.dtype)
|
| 692 |
+
|
| 693 |
+
def __call__(
|
| 694 |
+
self,
|
| 695 |
+
input_ids,
|
| 696 |
+
attention_mask,
|
| 697 |
+
token_type_ids,
|
| 698 |
+
position_ids,
|
| 699 |
+
deterministic: bool = True,
|
| 700 |
+
output_attentions: bool = False,
|
| 701 |
+
output_hidden_states: bool = False,
|
| 702 |
+
return_dict: bool = True,
|
| 703 |
+
):
|
| 704 |
+
# Model
|
| 705 |
+
outputs = self.albert(
|
| 706 |
+
input_ids,
|
| 707 |
+
attention_mask,
|
| 708 |
+
token_type_ids,
|
| 709 |
+
position_ids,
|
| 710 |
+
deterministic=deterministic,
|
| 711 |
+
output_attentions=output_attentions,
|
| 712 |
+
output_hidden_states=output_hidden_states,
|
| 713 |
+
return_dict=return_dict,
|
| 714 |
+
)
|
| 715 |
+
|
| 716 |
+
if self.config.tie_word_embeddings:
|
| 717 |
+
shared_embedding = self.albert.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
|
| 718 |
+
else:
|
| 719 |
+
shared_embedding = None
|
| 720 |
+
|
| 721 |
+
hidden_states = outputs[0]
|
| 722 |
+
pooled_output = outputs[1]
|
| 723 |
+
|
| 724 |
+
prediction_scores = self.predictions(hidden_states, shared_embedding=shared_embedding)
|
| 725 |
+
sop_scores = self.sop_classifier(pooled_output, deterministic=deterministic)
|
| 726 |
+
|
| 727 |
+
if not return_dict:
|
| 728 |
+
return (prediction_scores, sop_scores) + outputs[2:]
|
| 729 |
+
|
| 730 |
+
return FlaxAlbertForPreTrainingOutput(
|
| 731 |
+
prediction_logits=prediction_scores,
|
| 732 |
+
sop_logits=sop_scores,
|
| 733 |
+
hidden_states=outputs.hidden_states,
|
| 734 |
+
attentions=outputs.attentions,
|
| 735 |
+
)
|
| 736 |
+
|
| 737 |
+
|
| 738 |
+
@add_start_docstrings(
|
| 739 |
+
"""
|
| 740 |
+
Albert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a
|
| 741 |
+
`sentence order prediction (classification)` head.
|
| 742 |
+
""",
|
| 743 |
+
ALBERT_START_DOCSTRING,
|
| 744 |
+
)
|
| 745 |
+
class FlaxAlbertForPreTraining(FlaxAlbertPreTrainedModel):
|
| 746 |
+
module_class = FlaxAlbertForPreTrainingModule
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
FLAX_ALBERT_FOR_PRETRAINING_DOCSTRING = """
|
| 750 |
+
Returns:
|
| 751 |
+
|
| 752 |
+
Example:
|
| 753 |
+
|
| 754 |
+
```python
|
| 755 |
+
>>> from transformers import AutoTokenizer, FlaxAlbertForPreTraining
|
| 756 |
+
|
| 757 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
|
| 758 |
+
>>> model = FlaxAlbertForPreTraining.from_pretrained("albert/albert-base-v2")
|
| 759 |
+
|
| 760 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="np")
|
| 761 |
+
>>> outputs = model(**inputs)
|
| 762 |
+
|
| 763 |
+
>>> prediction_logits = outputs.prediction_logits
|
| 764 |
+
>>> seq_relationship_logits = outputs.sop_logits
|
| 765 |
+
```
|
| 766 |
+
"""
|
| 767 |
+
|
| 768 |
+
overwrite_call_docstring(
|
| 769 |
+
FlaxAlbertForPreTraining,
|
| 770 |
+
ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length") + FLAX_ALBERT_FOR_PRETRAINING_DOCSTRING,
|
| 771 |
+
)
|
| 772 |
+
append_replace_return_docstrings(
|
| 773 |
+
FlaxAlbertForPreTraining, output_type=FlaxAlbertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC
|
| 774 |
+
)
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
class FlaxAlbertForMaskedLMModule(nn.Module):
|
| 778 |
+
config: AlbertConfig
|
| 779 |
+
dtype: jnp.dtype = jnp.float32
|
| 780 |
+
|
| 781 |
+
def setup(self):
|
| 782 |
+
self.albert = FlaxAlbertModule(config=self.config, add_pooling_layer=False, dtype=self.dtype)
|
| 783 |
+
self.predictions = FlaxAlbertOnlyMLMHead(config=self.config, dtype=self.dtype)
|
| 784 |
+
|
| 785 |
+
def __call__(
|
| 786 |
+
self,
|
| 787 |
+
input_ids,
|
| 788 |
+
attention_mask,
|
| 789 |
+
token_type_ids,
|
| 790 |
+
position_ids,
|
| 791 |
+
deterministic: bool = True,
|
| 792 |
+
output_attentions: bool = False,
|
| 793 |
+
output_hidden_states: bool = False,
|
| 794 |
+
return_dict: bool = True,
|
| 795 |
+
):
|
| 796 |
+
# Model
|
| 797 |
+
outputs = self.albert(
|
| 798 |
+
input_ids,
|
| 799 |
+
attention_mask,
|
| 800 |
+
token_type_ids,
|
| 801 |
+
position_ids,
|
| 802 |
+
deterministic=deterministic,
|
| 803 |
+
output_attentions=output_attentions,
|
| 804 |
+
output_hidden_states=output_hidden_states,
|
| 805 |
+
return_dict=return_dict,
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
hidden_states = outputs[0]
|
| 809 |
+
if self.config.tie_word_embeddings:
|
| 810 |
+
shared_embedding = self.albert.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
|
| 811 |
+
else:
|
| 812 |
+
shared_embedding = None
|
| 813 |
+
|
| 814 |
+
# Compute the prediction scores
|
| 815 |
+
logits = self.predictions(hidden_states, shared_embedding=shared_embedding)
|
| 816 |
+
|
| 817 |
+
if not return_dict:
|
| 818 |
+
return (logits,) + outputs[1:]
|
| 819 |
+
|
| 820 |
+
return FlaxMaskedLMOutput(
|
| 821 |
+
logits=logits,
|
| 822 |
+
hidden_states=outputs.hidden_states,
|
| 823 |
+
attentions=outputs.attentions,
|
| 824 |
+
)
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
@add_start_docstrings("""Albert Model with a `language modeling` head on top.""", ALBERT_START_DOCSTRING)
|
| 828 |
+
class FlaxAlbertForMaskedLM(FlaxAlbertPreTrainedModel):
|
| 829 |
+
module_class = FlaxAlbertForMaskedLMModule
|
| 830 |
+
|
| 831 |
+
|
| 832 |
+
append_call_sample_docstring(
|
| 833 |
+
FlaxAlbertForMaskedLM, _CHECKPOINT_FOR_DOC, FlaxMaskedLMOutput, _CONFIG_FOR_DOC, revision="refs/pr/11"
|
| 834 |
+
)
|
| 835 |
+
|
| 836 |
+
|
| 837 |
+
class FlaxAlbertForSequenceClassificationModule(nn.Module):
|
| 838 |
+
config: AlbertConfig
|
| 839 |
+
dtype: jnp.dtype = jnp.float32
|
| 840 |
+
|
| 841 |
+
def setup(self):
|
| 842 |
+
self.albert = FlaxAlbertModule(config=self.config, dtype=self.dtype)
|
| 843 |
+
classifier_dropout = (
|
| 844 |
+
self.config.classifier_dropout_prob
|
| 845 |
+
if self.config.classifier_dropout_prob is not None
|
| 846 |
+
else self.config.hidden_dropout_prob
|
| 847 |
+
)
|
| 848 |
+
self.dropout = nn.Dropout(rate=classifier_dropout)
|
| 849 |
+
self.classifier = nn.Dense(
|
| 850 |
+
self.config.num_labels,
|
| 851 |
+
dtype=self.dtype,
|
| 852 |
+
)
|
| 853 |
+
|
| 854 |
+
def __call__(
|
| 855 |
+
self,
|
| 856 |
+
input_ids,
|
| 857 |
+
attention_mask,
|
| 858 |
+
token_type_ids,
|
| 859 |
+
position_ids,
|
| 860 |
+
deterministic: bool = True,
|
| 861 |
+
output_attentions: bool = False,
|
| 862 |
+
output_hidden_states: bool = False,
|
| 863 |
+
return_dict: bool = True,
|
| 864 |
+
):
|
| 865 |
+
# Model
|
| 866 |
+
outputs = self.albert(
|
| 867 |
+
input_ids,
|
| 868 |
+
attention_mask,
|
| 869 |
+
token_type_ids,
|
| 870 |
+
position_ids,
|
| 871 |
+
deterministic=deterministic,
|
| 872 |
+
output_attentions=output_attentions,
|
| 873 |
+
output_hidden_states=output_hidden_states,
|
| 874 |
+
return_dict=return_dict,
|
| 875 |
+
)
|
| 876 |
+
|
| 877 |
+
pooled_output = outputs[1]
|
| 878 |
+
pooled_output = self.dropout(pooled_output, deterministic=deterministic)
|
| 879 |
+
logits = self.classifier(pooled_output)
|
| 880 |
+
|
| 881 |
+
if not return_dict:
|
| 882 |
+
return (logits,) + outputs[2:]
|
| 883 |
+
|
| 884 |
+
return FlaxSequenceClassifierOutput(
|
| 885 |
+
logits=logits,
|
| 886 |
+
hidden_states=outputs.hidden_states,
|
| 887 |
+
attentions=outputs.attentions,
|
| 888 |
+
)
|
| 889 |
+
|
| 890 |
+
|
| 891 |
+
@add_start_docstrings(
|
| 892 |
+
"""
|
| 893 |
+
Albert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
|
| 894 |
+
output) e.g. for GLUE tasks.
|
| 895 |
+
""",
|
| 896 |
+
ALBERT_START_DOCSTRING,
|
| 897 |
+
)
|
| 898 |
+
class FlaxAlbertForSequenceClassification(FlaxAlbertPreTrainedModel):
|
| 899 |
+
module_class = FlaxAlbertForSequenceClassificationModule
|
| 900 |
+
|
| 901 |
+
|
| 902 |
+
append_call_sample_docstring(
|
| 903 |
+
FlaxAlbertForSequenceClassification,
|
| 904 |
+
_CHECKPOINT_FOR_DOC,
|
| 905 |
+
FlaxSequenceClassifierOutput,
|
| 906 |
+
_CONFIG_FOR_DOC,
|
| 907 |
+
)
|
| 908 |
+
|
| 909 |
+
|
| 910 |
+
class FlaxAlbertForMultipleChoiceModule(nn.Module):
|
| 911 |
+
config: AlbertConfig
|
| 912 |
+
dtype: jnp.dtype = jnp.float32
|
| 913 |
+
|
| 914 |
+
def setup(self):
|
| 915 |
+
self.albert = FlaxAlbertModule(config=self.config, dtype=self.dtype)
|
| 916 |
+
self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
|
| 917 |
+
self.classifier = nn.Dense(1, dtype=self.dtype)
|
| 918 |
+
|
| 919 |
+
def __call__(
|
| 920 |
+
self,
|
| 921 |
+
input_ids,
|
| 922 |
+
attention_mask,
|
| 923 |
+
token_type_ids,
|
| 924 |
+
position_ids,
|
| 925 |
+
deterministic: bool = True,
|
| 926 |
+
output_attentions: bool = False,
|
| 927 |
+
output_hidden_states: bool = False,
|
| 928 |
+
return_dict: bool = True,
|
| 929 |
+
):
|
| 930 |
+
num_choices = input_ids.shape[1]
|
| 931 |
+
input_ids = input_ids.reshape(-1, input_ids.shape[-1]) if input_ids is not None else None
|
| 932 |
+
attention_mask = attention_mask.reshape(-1, attention_mask.shape[-1]) if attention_mask is not None else None
|
| 933 |
+
token_type_ids = token_type_ids.reshape(-1, token_type_ids.shape[-1]) if token_type_ids is not None else None
|
| 934 |
+
position_ids = position_ids.reshape(-1, position_ids.shape[-1]) if position_ids is not None else None
|
| 935 |
+
|
| 936 |
+
# Model
|
| 937 |
+
outputs = self.albert(
|
| 938 |
+
input_ids,
|
| 939 |
+
attention_mask,
|
| 940 |
+
token_type_ids,
|
| 941 |
+
position_ids,
|
| 942 |
+
deterministic=deterministic,
|
| 943 |
+
output_attentions=output_attentions,
|
| 944 |
+
output_hidden_states=output_hidden_states,
|
| 945 |
+
return_dict=return_dict,
|
| 946 |
+
)
|
| 947 |
+
|
| 948 |
+
pooled_output = outputs[1]
|
| 949 |
+
pooled_output = self.dropout(pooled_output, deterministic=deterministic)
|
| 950 |
+
logits = self.classifier(pooled_output)
|
| 951 |
+
|
| 952 |
+
reshaped_logits = logits.reshape(-1, num_choices)
|
| 953 |
+
|
| 954 |
+
if not return_dict:
|
| 955 |
+
return (reshaped_logits,) + outputs[2:]
|
| 956 |
+
|
| 957 |
+
return FlaxMultipleChoiceModelOutput(
|
| 958 |
+
logits=reshaped_logits,
|
| 959 |
+
hidden_states=outputs.hidden_states,
|
| 960 |
+
attentions=outputs.attentions,
|
| 961 |
+
)
|
| 962 |
+
|
| 963 |
+
|
| 964 |
+
@add_start_docstrings(
|
| 965 |
+
"""
|
| 966 |
+
Albert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
|
| 967 |
+
softmax) e.g. for RocStories/SWAG tasks.
|
| 968 |
+
""",
|
| 969 |
+
ALBERT_START_DOCSTRING,
|
| 970 |
+
)
|
| 971 |
+
class FlaxAlbertForMultipleChoice(FlaxAlbertPreTrainedModel):
|
| 972 |
+
module_class = FlaxAlbertForMultipleChoiceModule
|
| 973 |
+
|
| 974 |
+
|
| 975 |
+
overwrite_call_docstring(
|
| 976 |
+
FlaxAlbertForMultipleChoice, ALBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
|
| 977 |
+
)
|
| 978 |
+
append_call_sample_docstring(
|
| 979 |
+
FlaxAlbertForMultipleChoice,
|
| 980 |
+
_CHECKPOINT_FOR_DOC,
|
| 981 |
+
FlaxMultipleChoiceModelOutput,
|
| 982 |
+
_CONFIG_FOR_DOC,
|
| 983 |
+
)
|
| 984 |
+
|
| 985 |
+
|
| 986 |
+
class FlaxAlbertForTokenClassificationModule(nn.Module):
|
| 987 |
+
config: AlbertConfig
|
| 988 |
+
dtype: jnp.dtype = jnp.float32
|
| 989 |
+
|
| 990 |
+
def setup(self):
|
| 991 |
+
self.albert = FlaxAlbertModule(config=self.config, dtype=self.dtype, add_pooling_layer=False)
|
| 992 |
+
classifier_dropout = (
|
| 993 |
+
self.config.classifier_dropout_prob
|
| 994 |
+
if self.config.classifier_dropout_prob is not None
|
| 995 |
+
else self.config.hidden_dropout_prob
|
| 996 |
+
)
|
| 997 |
+
self.dropout = nn.Dropout(rate=classifier_dropout)
|
| 998 |
+
self.classifier = nn.Dense(self.config.num_labels, dtype=self.dtype)
|
| 999 |
+
|
| 1000 |
+
def __call__(
|
| 1001 |
+
self,
|
| 1002 |
+
input_ids,
|
| 1003 |
+
attention_mask,
|
| 1004 |
+
token_type_ids,
|
| 1005 |
+
position_ids,
|
| 1006 |
+
deterministic: bool = True,
|
| 1007 |
+
output_attentions: bool = False,
|
| 1008 |
+
output_hidden_states: bool = False,
|
| 1009 |
+
return_dict: bool = True,
|
| 1010 |
+
):
|
| 1011 |
+
# Model
|
| 1012 |
+
outputs = self.albert(
|
| 1013 |
+
input_ids,
|
| 1014 |
+
attention_mask,
|
| 1015 |
+
token_type_ids,
|
| 1016 |
+
position_ids,
|
| 1017 |
+
deterministic=deterministic,
|
| 1018 |
+
output_attentions=output_attentions,
|
| 1019 |
+
output_hidden_states=output_hidden_states,
|
| 1020 |
+
return_dict=return_dict,
|
| 1021 |
+
)
|
| 1022 |
+
|
| 1023 |
+
hidden_states = outputs[0]
|
| 1024 |
+
hidden_states = self.dropout(hidden_states, deterministic=deterministic)
|
| 1025 |
+
logits = self.classifier(hidden_states)
|
| 1026 |
+
|
| 1027 |
+
if not return_dict:
|
| 1028 |
+
return (logits,) + outputs[1:]
|
| 1029 |
+
|
| 1030 |
+
return FlaxTokenClassifierOutput(
|
| 1031 |
+
logits=logits,
|
| 1032 |
+
hidden_states=outputs.hidden_states,
|
| 1033 |
+
attentions=outputs.attentions,
|
| 1034 |
+
)
|
| 1035 |
+
|
| 1036 |
+
|
| 1037 |
+
@add_start_docstrings(
|
| 1038 |
+
"""
|
| 1039 |
+
Albert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
| 1040 |
+
Named-Entity-Recognition (NER) tasks.
|
| 1041 |
+
""",
|
| 1042 |
+
ALBERT_START_DOCSTRING,
|
| 1043 |
+
)
|
| 1044 |
+
class FlaxAlbertForTokenClassification(FlaxAlbertPreTrainedModel):
|
| 1045 |
+
module_class = FlaxAlbertForTokenClassificationModule
|
| 1046 |
+
|
| 1047 |
+
|
| 1048 |
+
append_call_sample_docstring(
|
| 1049 |
+
FlaxAlbertForTokenClassification,
|
| 1050 |
+
_CHECKPOINT_FOR_DOC,
|
| 1051 |
+
FlaxTokenClassifierOutput,
|
| 1052 |
+
_CONFIG_FOR_DOC,
|
| 1053 |
+
)
|
| 1054 |
+
|
| 1055 |
+
|
| 1056 |
+
class FlaxAlbertForQuestionAnsweringModule(nn.Module):
|
| 1057 |
+
config: AlbertConfig
|
| 1058 |
+
dtype: jnp.dtype = jnp.float32
|
| 1059 |
+
|
| 1060 |
+
def setup(self):
|
| 1061 |
+
self.albert = FlaxAlbertModule(config=self.config, dtype=self.dtype, add_pooling_layer=False)
|
| 1062 |
+
self.qa_outputs = nn.Dense(self.config.num_labels, dtype=self.dtype)
|
| 1063 |
+
|
| 1064 |
+
def __call__(
|
| 1065 |
+
self,
|
| 1066 |
+
input_ids,
|
| 1067 |
+
attention_mask,
|
| 1068 |
+
token_type_ids,
|
| 1069 |
+
position_ids,
|
| 1070 |
+
deterministic: bool = True,
|
| 1071 |
+
output_attentions: bool = False,
|
| 1072 |
+
output_hidden_states: bool = False,
|
| 1073 |
+
return_dict: bool = True,
|
| 1074 |
+
):
|
| 1075 |
+
# Model
|
| 1076 |
+
outputs = self.albert(
|
| 1077 |
+
input_ids,
|
| 1078 |
+
attention_mask,
|
| 1079 |
+
token_type_ids,
|
| 1080 |
+
position_ids,
|
| 1081 |
+
deterministic=deterministic,
|
| 1082 |
+
output_attentions=output_attentions,
|
| 1083 |
+
output_hidden_states=output_hidden_states,
|
| 1084 |
+
return_dict=return_dict,
|
| 1085 |
+
)
|
| 1086 |
+
|
| 1087 |
+
hidden_states = outputs[0]
|
| 1088 |
+
|
| 1089 |
+
logits = self.qa_outputs(hidden_states)
|
| 1090 |
+
start_logits, end_logits = jnp.split(logits, self.config.num_labels, axis=-1)
|
| 1091 |
+
start_logits = start_logits.squeeze(-1)
|
| 1092 |
+
end_logits = end_logits.squeeze(-1)
|
| 1093 |
+
|
| 1094 |
+
if not return_dict:
|
| 1095 |
+
return (start_logits, end_logits) + outputs[1:]
|
| 1096 |
+
|
| 1097 |
+
return FlaxQuestionAnsweringModelOutput(
|
| 1098 |
+
start_logits=start_logits,
|
| 1099 |
+
end_logits=end_logits,
|
| 1100 |
+
hidden_states=outputs.hidden_states,
|
| 1101 |
+
attentions=outputs.attentions,
|
| 1102 |
+
)
|
| 1103 |
+
|
| 1104 |
+
|
| 1105 |
+
@add_start_docstrings(
|
| 1106 |
+
"""
|
| 1107 |
+
Albert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
|
| 1108 |
+
layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 1109 |
+
""",
|
| 1110 |
+
ALBERT_START_DOCSTRING,
|
| 1111 |
+
)
|
| 1112 |
+
class FlaxAlbertForQuestionAnswering(FlaxAlbertPreTrainedModel):
|
| 1113 |
+
module_class = FlaxAlbertForQuestionAnsweringModule
|
| 1114 |
+
|
| 1115 |
+
|
| 1116 |
+
append_call_sample_docstring(
|
| 1117 |
+
FlaxAlbertForQuestionAnswering,
|
| 1118 |
+
_CHECKPOINT_FOR_DOC,
|
| 1119 |
+
FlaxQuestionAnsweringModelOutput,
|
| 1120 |
+
_CONFIG_FOR_DOC,
|
| 1121 |
+
)
|
| 1122 |
+
|
| 1123 |
+
__all__ = [
|
| 1124 |
+
"FlaxAlbertPreTrainedModel",
|
| 1125 |
+
"FlaxAlbertModel",
|
| 1126 |
+
"FlaxAlbertForPreTraining",
|
| 1127 |
+
"FlaxAlbertForMaskedLM",
|
| 1128 |
+
"FlaxAlbertForSequenceClassification",
|
| 1129 |
+
"FlaxAlbertForMultipleChoice",
|
| 1130 |
+
"FlaxAlbertForTokenClassification",
|
| 1131 |
+
"FlaxAlbertForQuestionAnswering",
|
| 1132 |
+
]
|
lib/python3.12/site-packages/transformers/models/albert/modeling_tf_albert.py
ADDED
|
@@ -0,0 +1,1573 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""TF 2.0 ALBERT model."""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import math
|
| 21 |
+
from dataclasses import dataclass
|
| 22 |
+
from typing import Dict, Optional, Tuple, Union
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
import tensorflow as tf
|
| 26 |
+
|
| 27 |
+
from ...activations_tf import get_tf_activation
|
| 28 |
+
from ...modeling_tf_outputs import (
|
| 29 |
+
TFBaseModelOutput,
|
| 30 |
+
TFBaseModelOutputWithPooling,
|
| 31 |
+
TFMaskedLMOutput,
|
| 32 |
+
TFMultipleChoiceModelOutput,
|
| 33 |
+
TFQuestionAnsweringModelOutput,
|
| 34 |
+
TFSequenceClassifierOutput,
|
| 35 |
+
TFTokenClassifierOutput,
|
| 36 |
+
)
|
| 37 |
+
from ...modeling_tf_utils import (
|
| 38 |
+
TFMaskedLanguageModelingLoss,
|
| 39 |
+
TFModelInputType,
|
| 40 |
+
TFMultipleChoiceLoss,
|
| 41 |
+
TFPreTrainedModel,
|
| 42 |
+
TFQuestionAnsweringLoss,
|
| 43 |
+
TFSequenceClassificationLoss,
|
| 44 |
+
TFTokenClassificationLoss,
|
| 45 |
+
get_initializer,
|
| 46 |
+
keras,
|
| 47 |
+
keras_serializable,
|
| 48 |
+
unpack_inputs,
|
| 49 |
+
)
|
| 50 |
+
from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
|
| 51 |
+
from ...utils import (
|
| 52 |
+
ModelOutput,
|
| 53 |
+
add_code_sample_docstrings,
|
| 54 |
+
add_start_docstrings,
|
| 55 |
+
add_start_docstrings_to_model_forward,
|
| 56 |
+
logging,
|
| 57 |
+
replace_return_docstrings,
|
| 58 |
+
)
|
| 59 |
+
from .configuration_albert import AlbertConfig
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
logger = logging.get_logger(__name__)
|
| 63 |
+
|
| 64 |
+
_CHECKPOINT_FOR_DOC = "albert/albert-base-v2"
|
| 65 |
+
_CONFIG_FOR_DOC = "AlbertConfig"
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class TFAlbertPreTrainingLoss:
|
| 69 |
+
"""
|
| 70 |
+
Loss function suitable for ALBERT pretraining, that is, the task of pretraining a language model by combining SOP +
|
| 71 |
+
MLM. .. note:: Any label of -100 will be ignored (along with the corresponding logits) in the loss computation.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def hf_compute_loss(self, labels: tf.Tensor, logits: tf.Tensor) -> tf.Tensor:
|
| 75 |
+
loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True, reduction=keras.losses.Reduction.NONE)
|
| 76 |
+
if self.config.tf_legacy_loss:
|
| 77 |
+
# make sure only labels that are not equal to -100
|
| 78 |
+
# are taken into account as loss
|
| 79 |
+
masked_lm_active_loss = tf.not_equal(tf.reshape(tensor=labels["labels"], shape=(-1,)), -100)
|
| 80 |
+
masked_lm_reduced_logits = tf.boolean_mask(
|
| 81 |
+
tensor=tf.reshape(tensor=logits[0], shape=(-1, shape_list(logits[0])[2])),
|
| 82 |
+
mask=masked_lm_active_loss,
|
| 83 |
+
)
|
| 84 |
+
masked_lm_labels = tf.boolean_mask(
|
| 85 |
+
tensor=tf.reshape(tensor=labels["labels"], shape=(-1,)), mask=masked_lm_active_loss
|
| 86 |
+
)
|
| 87 |
+
sentence_order_active_loss = tf.not_equal(
|
| 88 |
+
tf.reshape(tensor=labels["sentence_order_label"], shape=(-1,)), -100
|
| 89 |
+
)
|
| 90 |
+
sentence_order_reduced_logits = tf.boolean_mask(
|
| 91 |
+
tensor=tf.reshape(tensor=logits[1], shape=(-1, 2)), mask=sentence_order_active_loss
|
| 92 |
+
)
|
| 93 |
+
sentence_order_label = tf.boolean_mask(
|
| 94 |
+
tensor=tf.reshape(tensor=labels["sentence_order_label"], shape=(-1,)), mask=sentence_order_active_loss
|
| 95 |
+
)
|
| 96 |
+
masked_lm_loss = loss_fn(y_true=masked_lm_labels, y_pred=masked_lm_reduced_logits)
|
| 97 |
+
sentence_order_loss = loss_fn(y_true=sentence_order_label, y_pred=sentence_order_reduced_logits)
|
| 98 |
+
masked_lm_loss = tf.reshape(tensor=masked_lm_loss, shape=(-1, shape_list(sentence_order_loss)[0]))
|
| 99 |
+
masked_lm_loss = tf.reduce_mean(input_tensor=masked_lm_loss, axis=0)
|
| 100 |
+
|
| 101 |
+
return masked_lm_loss + sentence_order_loss
|
| 102 |
+
|
| 103 |
+
# Clip negative labels to zero here to avoid NaNs and errors - those positions will get masked later anyway
|
| 104 |
+
unmasked_lm_losses = loss_fn(y_true=tf.nn.relu(labels["labels"]), y_pred=logits[0])
|
| 105 |
+
# make sure only labels that are not equal to -100
|
| 106 |
+
# are taken into account for the loss computation
|
| 107 |
+
lm_loss_mask = tf.cast(labels["labels"] != -100, dtype=unmasked_lm_losses.dtype)
|
| 108 |
+
masked_lm_losses = unmasked_lm_losses * lm_loss_mask
|
| 109 |
+
reduced_masked_lm_loss = tf.reduce_sum(masked_lm_losses) / tf.reduce_sum(lm_loss_mask)
|
| 110 |
+
|
| 111 |
+
sop_logits = tf.reshape(logits[1], (-1, 2))
|
| 112 |
+
# Clip negative labels to zero here to avoid NaNs and errors - those positions will get masked later anyway
|
| 113 |
+
unmasked_sop_loss = loss_fn(y_true=tf.nn.relu(labels["sentence_order_label"]), y_pred=sop_logits)
|
| 114 |
+
sop_loss_mask = tf.cast(labels["sentence_order_label"] != -100, dtype=unmasked_sop_loss.dtype)
|
| 115 |
+
|
| 116 |
+
masked_sop_loss = unmasked_sop_loss * sop_loss_mask
|
| 117 |
+
reduced_masked_sop_loss = tf.reduce_sum(masked_sop_loss) / tf.reduce_sum(sop_loss_mask)
|
| 118 |
+
|
| 119 |
+
return tf.reshape(reduced_masked_lm_loss + reduced_masked_sop_loss, (1,))
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class TFAlbertEmbeddings(keras.layers.Layer):
|
| 123 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 124 |
+
|
| 125 |
+
def __init__(self, config: AlbertConfig, **kwargs):
|
| 126 |
+
super().__init__(**kwargs)
|
| 127 |
+
|
| 128 |
+
self.config = config
|
| 129 |
+
self.embedding_size = config.embedding_size
|
| 130 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 131 |
+
self.initializer_range = config.initializer_range
|
| 132 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 133 |
+
self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
| 134 |
+
|
| 135 |
+
def build(self, input_shape=None):
|
| 136 |
+
with tf.name_scope("word_embeddings"):
|
| 137 |
+
self.weight = self.add_weight(
|
| 138 |
+
name="weight",
|
| 139 |
+
shape=[self.config.vocab_size, self.embedding_size],
|
| 140 |
+
initializer=get_initializer(self.initializer_range),
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
with tf.name_scope("token_type_embeddings"):
|
| 144 |
+
self.token_type_embeddings = self.add_weight(
|
| 145 |
+
name="embeddings",
|
| 146 |
+
shape=[self.config.type_vocab_size, self.embedding_size],
|
| 147 |
+
initializer=get_initializer(self.initializer_range),
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
with tf.name_scope("position_embeddings"):
|
| 151 |
+
self.position_embeddings = self.add_weight(
|
| 152 |
+
name="embeddings",
|
| 153 |
+
shape=[self.max_position_embeddings, self.embedding_size],
|
| 154 |
+
initializer=get_initializer(self.initializer_range),
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
if self.built:
|
| 158 |
+
return
|
| 159 |
+
self.built = True
|
| 160 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 161 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 162 |
+
self.LayerNorm.build([None, None, self.config.embedding_size])
|
| 163 |
+
|
| 164 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertEmbeddings.call
|
| 165 |
+
def call(
|
| 166 |
+
self,
|
| 167 |
+
input_ids: Optional[tf.Tensor] = None,
|
| 168 |
+
position_ids: Optional[tf.Tensor] = None,
|
| 169 |
+
token_type_ids: Optional[tf.Tensor] = None,
|
| 170 |
+
inputs_embeds: Optional[tf.Tensor] = None,
|
| 171 |
+
past_key_values_length=0,
|
| 172 |
+
training: bool = False,
|
| 173 |
+
) -> tf.Tensor:
|
| 174 |
+
"""
|
| 175 |
+
Applies embedding based on inputs tensor.
|
| 176 |
+
|
| 177 |
+
Returns:
|
| 178 |
+
final_embeddings (`tf.Tensor`): output embedding tensor.
|
| 179 |
+
"""
|
| 180 |
+
if input_ids is None and inputs_embeds is None:
|
| 181 |
+
raise ValueError("Need to provide either `input_ids` or `input_embeds`.")
|
| 182 |
+
|
| 183 |
+
if input_ids is not None:
|
| 184 |
+
check_embeddings_within_bounds(input_ids, self.config.vocab_size)
|
| 185 |
+
inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
|
| 186 |
+
|
| 187 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 188 |
+
|
| 189 |
+
if token_type_ids is None:
|
| 190 |
+
token_type_ids = tf.fill(dims=input_shape, value=0)
|
| 191 |
+
|
| 192 |
+
if position_ids is None:
|
| 193 |
+
position_ids = tf.expand_dims(
|
| 194 |
+
tf.range(start=past_key_values_length, limit=input_shape[1] + past_key_values_length), axis=0
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
|
| 198 |
+
token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)
|
| 199 |
+
final_embeddings = inputs_embeds + position_embeds + token_type_embeds
|
| 200 |
+
final_embeddings = self.LayerNorm(inputs=final_embeddings)
|
| 201 |
+
final_embeddings = self.dropout(inputs=final_embeddings, training=training)
|
| 202 |
+
|
| 203 |
+
return final_embeddings
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
class TFAlbertAttention(keras.layers.Layer):
|
| 207 |
+
"""Contains the complete attention sublayer, including both dropouts and layer norm."""
|
| 208 |
+
|
| 209 |
+
def __init__(self, config: AlbertConfig, **kwargs):
|
| 210 |
+
super().__init__(**kwargs)
|
| 211 |
+
|
| 212 |
+
if config.hidden_size % config.num_attention_heads != 0:
|
| 213 |
+
raise ValueError(
|
| 214 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number "
|
| 215 |
+
f"of attention heads ({config.num_attention_heads})"
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
self.num_attention_heads = config.num_attention_heads
|
| 219 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 220 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 221 |
+
self.sqrt_att_head_size = math.sqrt(self.attention_head_size)
|
| 222 |
+
self.output_attentions = config.output_attentions
|
| 223 |
+
|
| 224 |
+
self.query = keras.layers.Dense(
|
| 225 |
+
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
|
| 226 |
+
)
|
| 227 |
+
self.key = keras.layers.Dense(
|
| 228 |
+
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
|
| 229 |
+
)
|
| 230 |
+
self.value = keras.layers.Dense(
|
| 231 |
+
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
|
| 232 |
+
)
|
| 233 |
+
self.dense = keras.layers.Dense(
|
| 234 |
+
units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 235 |
+
)
|
| 236 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 237 |
+
# Two different dropout probabilities; see https://github.com/google-research/albert/blob/master/modeling.py#L971-L993
|
| 238 |
+
self.attention_dropout = keras.layers.Dropout(rate=config.attention_probs_dropout_prob)
|
| 239 |
+
self.output_dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
| 240 |
+
self.config = config
|
| 241 |
+
|
| 242 |
+
def transpose_for_scores(self, tensor: tf.Tensor, batch_size: int) -> tf.Tensor:
|
| 243 |
+
# Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
|
| 244 |
+
tensor = tf.reshape(tensor=tensor, shape=(batch_size, -1, self.num_attention_heads, self.attention_head_size))
|
| 245 |
+
|
| 246 |
+
# Transpose the tensor from [batch_size, seq_length, num_attention_heads, attention_head_size] to [batch_size, num_attention_heads, seq_length, attention_head_size]
|
| 247 |
+
return tf.transpose(tensor, perm=[0, 2, 1, 3])
|
| 248 |
+
|
| 249 |
+
def call(
|
| 250 |
+
self,
|
| 251 |
+
input_tensor: tf.Tensor,
|
| 252 |
+
attention_mask: tf.Tensor,
|
| 253 |
+
head_mask: tf.Tensor,
|
| 254 |
+
output_attentions: bool,
|
| 255 |
+
training: bool = False,
|
| 256 |
+
) -> Tuple[tf.Tensor]:
|
| 257 |
+
batch_size = shape_list(input_tensor)[0]
|
| 258 |
+
mixed_query_layer = self.query(inputs=input_tensor)
|
| 259 |
+
mixed_key_layer = self.key(inputs=input_tensor)
|
| 260 |
+
mixed_value_layer = self.value(inputs=input_tensor)
|
| 261 |
+
query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)
|
| 262 |
+
key_layer = self.transpose_for_scores(mixed_key_layer, batch_size)
|
| 263 |
+
value_layer = self.transpose_for_scores(mixed_value_layer, batch_size)
|
| 264 |
+
|
| 265 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 266 |
+
# (batch size, num_heads, seq_len_q, seq_len_k)
|
| 267 |
+
attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
|
| 268 |
+
dk = tf.cast(self.sqrt_att_head_size, dtype=attention_scores.dtype)
|
| 269 |
+
attention_scores = tf.divide(attention_scores, dk)
|
| 270 |
+
|
| 271 |
+
if attention_mask is not None:
|
| 272 |
+
# Apply the attention mask is (precomputed for all layers in TFAlbertModel call() function)
|
| 273 |
+
attention_scores = tf.add(attention_scores, attention_mask)
|
| 274 |
+
|
| 275 |
+
# Normalize the attention scores to probabilities.
|
| 276 |
+
attention_probs = stable_softmax(logits=attention_scores, axis=-1)
|
| 277 |
+
|
| 278 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 279 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 280 |
+
attention_probs = self.attention_dropout(inputs=attention_probs, training=training)
|
| 281 |
+
|
| 282 |
+
# Mask heads if we want to
|
| 283 |
+
if head_mask is not None:
|
| 284 |
+
attention_probs = tf.multiply(attention_probs, head_mask)
|
| 285 |
+
|
| 286 |
+
context_layer = tf.matmul(attention_probs, value_layer)
|
| 287 |
+
context_layer = tf.transpose(context_layer, perm=[0, 2, 1, 3])
|
| 288 |
+
|
| 289 |
+
# (batch_size, seq_len_q, all_head_size)
|
| 290 |
+
context_layer = tf.reshape(tensor=context_layer, shape=(batch_size, -1, self.all_head_size))
|
| 291 |
+
self_outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 292 |
+
hidden_states = self_outputs[0]
|
| 293 |
+
hidden_states = self.dense(inputs=hidden_states)
|
| 294 |
+
hidden_states = self.output_dropout(inputs=hidden_states, training=training)
|
| 295 |
+
attention_output = self.LayerNorm(inputs=hidden_states + input_tensor)
|
| 296 |
+
|
| 297 |
+
# add attentions if we output them
|
| 298 |
+
outputs = (attention_output,) + self_outputs[1:]
|
| 299 |
+
|
| 300 |
+
return outputs
|
| 301 |
+
|
| 302 |
+
def build(self, input_shape=None):
|
| 303 |
+
if self.built:
|
| 304 |
+
return
|
| 305 |
+
self.built = True
|
| 306 |
+
if getattr(self, "query", None) is not None:
|
| 307 |
+
with tf.name_scope(self.query.name):
|
| 308 |
+
self.query.build([None, None, self.config.hidden_size])
|
| 309 |
+
if getattr(self, "key", None) is not None:
|
| 310 |
+
with tf.name_scope(self.key.name):
|
| 311 |
+
self.key.build([None, None, self.config.hidden_size])
|
| 312 |
+
if getattr(self, "value", None) is not None:
|
| 313 |
+
with tf.name_scope(self.value.name):
|
| 314 |
+
self.value.build([None, None, self.config.hidden_size])
|
| 315 |
+
if getattr(self, "dense", None) is not None:
|
| 316 |
+
with tf.name_scope(self.dense.name):
|
| 317 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 318 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 319 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 320 |
+
self.LayerNorm.build([None, None, self.config.hidden_size])
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
class TFAlbertLayer(keras.layers.Layer):
|
| 324 |
+
def __init__(self, config: AlbertConfig, **kwargs):
|
| 325 |
+
super().__init__(**kwargs)
|
| 326 |
+
|
| 327 |
+
self.attention = TFAlbertAttention(config, name="attention")
|
| 328 |
+
self.ffn = keras.layers.Dense(
|
| 329 |
+
units=config.intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name="ffn"
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
if isinstance(config.hidden_act, str):
|
| 333 |
+
self.activation = get_tf_activation(config.hidden_act)
|
| 334 |
+
else:
|
| 335 |
+
self.activation = config.hidden_act
|
| 336 |
+
|
| 337 |
+
self.ffn_output = keras.layers.Dense(
|
| 338 |
+
units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="ffn_output"
|
| 339 |
+
)
|
| 340 |
+
self.full_layer_layer_norm = keras.layers.LayerNormalization(
|
| 341 |
+
epsilon=config.layer_norm_eps, name="full_layer_layer_norm"
|
| 342 |
+
)
|
| 343 |
+
self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
| 344 |
+
self.config = config
|
| 345 |
+
|
| 346 |
+
def call(
|
| 347 |
+
self,
|
| 348 |
+
hidden_states: tf.Tensor,
|
| 349 |
+
attention_mask: tf.Tensor,
|
| 350 |
+
head_mask: tf.Tensor,
|
| 351 |
+
output_attentions: bool,
|
| 352 |
+
training: bool = False,
|
| 353 |
+
) -> Tuple[tf.Tensor]:
|
| 354 |
+
attention_outputs = self.attention(
|
| 355 |
+
input_tensor=hidden_states,
|
| 356 |
+
attention_mask=attention_mask,
|
| 357 |
+
head_mask=head_mask,
|
| 358 |
+
output_attentions=output_attentions,
|
| 359 |
+
training=training,
|
| 360 |
+
)
|
| 361 |
+
ffn_output = self.ffn(inputs=attention_outputs[0])
|
| 362 |
+
ffn_output = self.activation(ffn_output)
|
| 363 |
+
ffn_output = self.ffn_output(inputs=ffn_output)
|
| 364 |
+
ffn_output = self.dropout(inputs=ffn_output, training=training)
|
| 365 |
+
hidden_states = self.full_layer_layer_norm(inputs=ffn_output + attention_outputs[0])
|
| 366 |
+
|
| 367 |
+
# add attentions if we output them
|
| 368 |
+
outputs = (hidden_states,) + attention_outputs[1:]
|
| 369 |
+
|
| 370 |
+
return outputs
|
| 371 |
+
|
| 372 |
+
def build(self, input_shape=None):
|
| 373 |
+
if self.built:
|
| 374 |
+
return
|
| 375 |
+
self.built = True
|
| 376 |
+
if getattr(self, "attention", None) is not None:
|
| 377 |
+
with tf.name_scope(self.attention.name):
|
| 378 |
+
self.attention.build(None)
|
| 379 |
+
if getattr(self, "ffn", None) is not None:
|
| 380 |
+
with tf.name_scope(self.ffn.name):
|
| 381 |
+
self.ffn.build([None, None, self.config.hidden_size])
|
| 382 |
+
if getattr(self, "ffn_output", None) is not None:
|
| 383 |
+
with tf.name_scope(self.ffn_output.name):
|
| 384 |
+
self.ffn_output.build([None, None, self.config.intermediate_size])
|
| 385 |
+
if getattr(self, "full_layer_layer_norm", None) is not None:
|
| 386 |
+
with tf.name_scope(self.full_layer_layer_norm.name):
|
| 387 |
+
self.full_layer_layer_norm.build([None, None, self.config.hidden_size])
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
class TFAlbertLayerGroup(keras.layers.Layer):
|
| 391 |
+
def __init__(self, config: AlbertConfig, **kwargs):
|
| 392 |
+
super().__init__(**kwargs)
|
| 393 |
+
|
| 394 |
+
self.albert_layers = [
|
| 395 |
+
TFAlbertLayer(config, name=f"albert_layers_._{i}") for i in range(config.inner_group_num)
|
| 396 |
+
]
|
| 397 |
+
|
| 398 |
+
def call(
|
| 399 |
+
self,
|
| 400 |
+
hidden_states: tf.Tensor,
|
| 401 |
+
attention_mask: tf.Tensor,
|
| 402 |
+
head_mask: tf.Tensor,
|
| 403 |
+
output_attentions: bool,
|
| 404 |
+
output_hidden_states: bool,
|
| 405 |
+
training: bool = False,
|
| 406 |
+
) -> Union[TFBaseModelOutput, Tuple[tf.Tensor]]:
|
| 407 |
+
layer_hidden_states = () if output_hidden_states else None
|
| 408 |
+
layer_attentions = () if output_attentions else None
|
| 409 |
+
|
| 410 |
+
for layer_index, albert_layer in enumerate(self.albert_layers):
|
| 411 |
+
if output_hidden_states:
|
| 412 |
+
layer_hidden_states = layer_hidden_states + (hidden_states,)
|
| 413 |
+
|
| 414 |
+
layer_output = albert_layer(
|
| 415 |
+
hidden_states=hidden_states,
|
| 416 |
+
attention_mask=attention_mask,
|
| 417 |
+
head_mask=head_mask[layer_index],
|
| 418 |
+
output_attentions=output_attentions,
|
| 419 |
+
training=training,
|
| 420 |
+
)
|
| 421 |
+
hidden_states = layer_output[0]
|
| 422 |
+
|
| 423 |
+
if output_attentions:
|
| 424 |
+
layer_attentions = layer_attentions + (layer_output[1],)
|
| 425 |
+
|
| 426 |
+
# Add last layer
|
| 427 |
+
if output_hidden_states:
|
| 428 |
+
layer_hidden_states = layer_hidden_states + (hidden_states,)
|
| 429 |
+
|
| 430 |
+
return tuple(v for v in [hidden_states, layer_hidden_states, layer_attentions] if v is not None)
|
| 431 |
+
|
| 432 |
+
def build(self, input_shape=None):
|
| 433 |
+
if self.built:
|
| 434 |
+
return
|
| 435 |
+
self.built = True
|
| 436 |
+
if getattr(self, "albert_layers", None) is not None:
|
| 437 |
+
for layer in self.albert_layers:
|
| 438 |
+
with tf.name_scope(layer.name):
|
| 439 |
+
layer.build(None)
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
class TFAlbertTransformer(keras.layers.Layer):
|
| 443 |
+
def __init__(self, config: AlbertConfig, **kwargs):
|
| 444 |
+
super().__init__(**kwargs)
|
| 445 |
+
|
| 446 |
+
self.num_hidden_layers = config.num_hidden_layers
|
| 447 |
+
self.num_hidden_groups = config.num_hidden_groups
|
| 448 |
+
# Number of layers in a hidden group
|
| 449 |
+
self.layers_per_group = int(config.num_hidden_layers / config.num_hidden_groups)
|
| 450 |
+
self.embedding_hidden_mapping_in = keras.layers.Dense(
|
| 451 |
+
units=config.hidden_size,
|
| 452 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 453 |
+
name="embedding_hidden_mapping_in",
|
| 454 |
+
)
|
| 455 |
+
self.albert_layer_groups = [
|
| 456 |
+
TFAlbertLayerGroup(config, name=f"albert_layer_groups_._{i}") for i in range(config.num_hidden_groups)
|
| 457 |
+
]
|
| 458 |
+
self.config = config
|
| 459 |
+
|
| 460 |
+
def call(
|
| 461 |
+
self,
|
| 462 |
+
hidden_states: tf.Tensor,
|
| 463 |
+
attention_mask: tf.Tensor,
|
| 464 |
+
head_mask: tf.Tensor,
|
| 465 |
+
output_attentions: bool,
|
| 466 |
+
output_hidden_states: bool,
|
| 467 |
+
return_dict: bool,
|
| 468 |
+
training: bool = False,
|
| 469 |
+
) -> Union[TFBaseModelOutput, Tuple[tf.Tensor]]:
|
| 470 |
+
hidden_states = self.embedding_hidden_mapping_in(inputs=hidden_states)
|
| 471 |
+
all_attentions = () if output_attentions else None
|
| 472 |
+
all_hidden_states = (hidden_states,) if output_hidden_states else None
|
| 473 |
+
|
| 474 |
+
for i in range(self.num_hidden_layers):
|
| 475 |
+
# Index of the hidden group
|
| 476 |
+
group_idx = int(i / (self.num_hidden_layers / self.num_hidden_groups))
|
| 477 |
+
layer_group_output = self.albert_layer_groups[group_idx](
|
| 478 |
+
hidden_states=hidden_states,
|
| 479 |
+
attention_mask=attention_mask,
|
| 480 |
+
head_mask=head_mask[group_idx * self.layers_per_group : (group_idx + 1) * self.layers_per_group],
|
| 481 |
+
output_attentions=output_attentions,
|
| 482 |
+
output_hidden_states=output_hidden_states,
|
| 483 |
+
training=training,
|
| 484 |
+
)
|
| 485 |
+
hidden_states = layer_group_output[0]
|
| 486 |
+
|
| 487 |
+
if output_attentions:
|
| 488 |
+
all_attentions = all_attentions + layer_group_output[-1]
|
| 489 |
+
|
| 490 |
+
if output_hidden_states:
|
| 491 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 492 |
+
|
| 493 |
+
if not return_dict:
|
| 494 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
|
| 495 |
+
|
| 496 |
+
return TFBaseModelOutput(
|
| 497 |
+
last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
def build(self, input_shape=None):
|
| 501 |
+
if self.built:
|
| 502 |
+
return
|
| 503 |
+
self.built = True
|
| 504 |
+
if getattr(self, "embedding_hidden_mapping_in", None) is not None:
|
| 505 |
+
with tf.name_scope(self.embedding_hidden_mapping_in.name):
|
| 506 |
+
self.embedding_hidden_mapping_in.build([None, None, self.config.embedding_size])
|
| 507 |
+
if getattr(self, "albert_layer_groups", None) is not None:
|
| 508 |
+
for layer in self.albert_layer_groups:
|
| 509 |
+
with tf.name_scope(layer.name):
|
| 510 |
+
layer.build(None)
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
class TFAlbertPreTrainedModel(TFPreTrainedModel):
|
| 514 |
+
"""
|
| 515 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 516 |
+
models.
|
| 517 |
+
"""
|
| 518 |
+
|
| 519 |
+
config_class = AlbertConfig
|
| 520 |
+
base_model_prefix = "albert"
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
class TFAlbertMLMHead(keras.layers.Layer):
|
| 524 |
+
def __init__(self, config: AlbertConfig, input_embeddings: keras.layers.Layer, **kwargs):
|
| 525 |
+
super().__init__(**kwargs)
|
| 526 |
+
|
| 527 |
+
self.config = config
|
| 528 |
+
self.embedding_size = config.embedding_size
|
| 529 |
+
self.dense = keras.layers.Dense(
|
| 530 |
+
config.embedding_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 531 |
+
)
|
| 532 |
+
if isinstance(config.hidden_act, str):
|
| 533 |
+
self.activation = get_tf_activation(config.hidden_act)
|
| 534 |
+
else:
|
| 535 |
+
self.activation = config.hidden_act
|
| 536 |
+
|
| 537 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 538 |
+
|
| 539 |
+
# The output weights are the same as the input embeddings, but there is
|
| 540 |
+
# an output-only bias for each token.
|
| 541 |
+
self.decoder = input_embeddings
|
| 542 |
+
|
| 543 |
+
def build(self, input_shape=None):
|
| 544 |
+
self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
|
| 545 |
+
self.decoder_bias = self.add_weight(
|
| 546 |
+
shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="decoder/bias"
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
if self.built:
|
| 550 |
+
return
|
| 551 |
+
self.built = True
|
| 552 |
+
if getattr(self, "dense", None) is not None:
|
| 553 |
+
with tf.name_scope(self.dense.name):
|
| 554 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 555 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 556 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 557 |
+
self.LayerNorm.build([None, None, self.config.embedding_size])
|
| 558 |
+
|
| 559 |
+
def get_output_embeddings(self) -> keras.layers.Layer:
|
| 560 |
+
return self.decoder
|
| 561 |
+
|
| 562 |
+
def set_output_embeddings(self, value: tf.Variable):
|
| 563 |
+
self.decoder.weight = value
|
| 564 |
+
self.decoder.vocab_size = shape_list(value)[0]
|
| 565 |
+
|
| 566 |
+
def get_bias(self) -> Dict[str, tf.Variable]:
|
| 567 |
+
return {"bias": self.bias, "decoder_bias": self.decoder_bias}
|
| 568 |
+
|
| 569 |
+
def set_bias(self, value: tf.Variable):
|
| 570 |
+
self.bias = value["bias"]
|
| 571 |
+
self.decoder_bias = value["decoder_bias"]
|
| 572 |
+
self.config.vocab_size = shape_list(value["bias"])[0]
|
| 573 |
+
|
| 574 |
+
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
|
| 575 |
+
hidden_states = self.dense(inputs=hidden_states)
|
| 576 |
+
hidden_states = self.activation(hidden_states)
|
| 577 |
+
hidden_states = self.LayerNorm(inputs=hidden_states)
|
| 578 |
+
seq_length = shape_list(tensor=hidden_states)[1]
|
| 579 |
+
hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.embedding_size])
|
| 580 |
+
hidden_states = tf.matmul(a=hidden_states, b=self.decoder.weight, transpose_b=True)
|
| 581 |
+
hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.config.vocab_size])
|
| 582 |
+
hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.decoder_bias)
|
| 583 |
+
|
| 584 |
+
return hidden_states
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
@keras_serializable
|
| 588 |
+
class TFAlbertMainLayer(keras.layers.Layer):
|
| 589 |
+
config_class = AlbertConfig
|
| 590 |
+
|
| 591 |
+
def __init__(self, config: AlbertConfig, add_pooling_layer: bool = True, **kwargs):
|
| 592 |
+
super().__init__(**kwargs)
|
| 593 |
+
|
| 594 |
+
self.config = config
|
| 595 |
+
|
| 596 |
+
self.embeddings = TFAlbertEmbeddings(config, name="embeddings")
|
| 597 |
+
self.encoder = TFAlbertTransformer(config, name="encoder")
|
| 598 |
+
self.pooler = (
|
| 599 |
+
keras.layers.Dense(
|
| 600 |
+
units=config.hidden_size,
|
| 601 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 602 |
+
activation="tanh",
|
| 603 |
+
name="pooler",
|
| 604 |
+
)
|
| 605 |
+
if add_pooling_layer
|
| 606 |
+
else None
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
def get_input_embeddings(self) -> keras.layers.Layer:
|
| 610 |
+
return self.embeddings
|
| 611 |
+
|
| 612 |
+
def set_input_embeddings(self, value: tf.Variable):
|
| 613 |
+
self.embeddings.weight = value
|
| 614 |
+
self.embeddings.vocab_size = shape_list(value)[0]
|
| 615 |
+
|
| 616 |
+
def _prune_heads(self, heads_to_prune):
|
| 617 |
+
"""
|
| 618 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 619 |
+
class PreTrainedModel
|
| 620 |
+
"""
|
| 621 |
+
raise NotImplementedError
|
| 622 |
+
|
| 623 |
+
@unpack_inputs
|
| 624 |
+
def call(
|
| 625 |
+
self,
|
| 626 |
+
input_ids: TFModelInputType | None = None,
|
| 627 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 628 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 629 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 630 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 631 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 632 |
+
output_attentions: Optional[bool] = None,
|
| 633 |
+
output_hidden_states: Optional[bool] = None,
|
| 634 |
+
return_dict: Optional[bool] = None,
|
| 635 |
+
training: bool = False,
|
| 636 |
+
) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]:
|
| 637 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 638 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 639 |
+
elif input_ids is not None:
|
| 640 |
+
input_shape = shape_list(input_ids)
|
| 641 |
+
elif inputs_embeds is not None:
|
| 642 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 643 |
+
else:
|
| 644 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 645 |
+
|
| 646 |
+
if attention_mask is None:
|
| 647 |
+
attention_mask = tf.fill(dims=input_shape, value=1)
|
| 648 |
+
|
| 649 |
+
if token_type_ids is None:
|
| 650 |
+
token_type_ids = tf.fill(dims=input_shape, value=0)
|
| 651 |
+
|
| 652 |
+
embedding_output = self.embeddings(
|
| 653 |
+
input_ids=input_ids,
|
| 654 |
+
position_ids=position_ids,
|
| 655 |
+
token_type_ids=token_type_ids,
|
| 656 |
+
inputs_embeds=inputs_embeds,
|
| 657 |
+
training=training,
|
| 658 |
+
)
|
| 659 |
+
|
| 660 |
+
# We create a 3D attention mask from a 2D tensor mask.
|
| 661 |
+
# Sizes are [batch_size, 1, 1, to_seq_length]
|
| 662 |
+
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
|
| 663 |
+
# this attention mask is more simple than the triangular masking of causal attention
|
| 664 |
+
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
|
| 665 |
+
extended_attention_mask = tf.reshape(attention_mask, (input_shape[0], 1, 1, input_shape[1]))
|
| 666 |
+
|
| 667 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
| 668 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
| 669 |
+
# positions we want to attend and -10000.0 for masked positions.
|
| 670 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
| 671 |
+
# effectively the same as removing these entirely.
|
| 672 |
+
extended_attention_mask = tf.cast(extended_attention_mask, dtype=embedding_output.dtype)
|
| 673 |
+
one_cst = tf.constant(1.0, dtype=embedding_output.dtype)
|
| 674 |
+
ten_thousand_cst = tf.constant(-10000.0, dtype=embedding_output.dtype)
|
| 675 |
+
extended_attention_mask = tf.multiply(tf.subtract(one_cst, extended_attention_mask), ten_thousand_cst)
|
| 676 |
+
|
| 677 |
+
# Prepare head mask if needed
|
| 678 |
+
# 1.0 in head_mask indicate we keep the head
|
| 679 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 680 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 681 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 682 |
+
if head_mask is not None:
|
| 683 |
+
raise NotImplementedError
|
| 684 |
+
else:
|
| 685 |
+
head_mask = [None] * self.config.num_hidden_layers
|
| 686 |
+
|
| 687 |
+
encoder_outputs = self.encoder(
|
| 688 |
+
hidden_states=embedding_output,
|
| 689 |
+
attention_mask=extended_attention_mask,
|
| 690 |
+
head_mask=head_mask,
|
| 691 |
+
output_attentions=output_attentions,
|
| 692 |
+
output_hidden_states=output_hidden_states,
|
| 693 |
+
return_dict=return_dict,
|
| 694 |
+
training=training,
|
| 695 |
+
)
|
| 696 |
+
|
| 697 |
+
sequence_output = encoder_outputs[0]
|
| 698 |
+
pooled_output = self.pooler(inputs=sequence_output[:, 0]) if self.pooler is not None else None
|
| 699 |
+
|
| 700 |
+
if not return_dict:
|
| 701 |
+
return (
|
| 702 |
+
sequence_output,
|
| 703 |
+
pooled_output,
|
| 704 |
+
) + encoder_outputs[1:]
|
| 705 |
+
|
| 706 |
+
return TFBaseModelOutputWithPooling(
|
| 707 |
+
last_hidden_state=sequence_output,
|
| 708 |
+
pooler_output=pooled_output,
|
| 709 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 710 |
+
attentions=encoder_outputs.attentions,
|
| 711 |
+
)
|
| 712 |
+
|
| 713 |
+
def build(self, input_shape=None):
|
| 714 |
+
if self.built:
|
| 715 |
+
return
|
| 716 |
+
self.built = True
|
| 717 |
+
if getattr(self, "embeddings", None) is not None:
|
| 718 |
+
with tf.name_scope(self.embeddings.name):
|
| 719 |
+
self.embeddings.build(None)
|
| 720 |
+
if getattr(self, "encoder", None) is not None:
|
| 721 |
+
with tf.name_scope(self.encoder.name):
|
| 722 |
+
self.encoder.build(None)
|
| 723 |
+
if getattr(self, "pooler", None) is not None:
|
| 724 |
+
with tf.name_scope(self.pooler.name):
|
| 725 |
+
self.pooler.build([None, None, self.config.hidden_size])
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
@dataclass
|
| 729 |
+
class TFAlbertForPreTrainingOutput(ModelOutput):
|
| 730 |
+
"""
|
| 731 |
+
Output type of [`TFAlbertForPreTraining`].
|
| 732 |
+
|
| 733 |
+
Args:
|
| 734 |
+
prediction_logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 735 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 736 |
+
sop_logits (`tf.Tensor` of shape `(batch_size, 2)`):
|
| 737 |
+
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
|
| 738 |
+
before SoftMax).
|
| 739 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 740 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 741 |
+
`(batch_size, sequence_length, hidden_size)`.
|
| 742 |
+
|
| 743 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 744 |
+
attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 745 |
+
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 746 |
+
sequence_length)`.
|
| 747 |
+
|
| 748 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 749 |
+
heads.
|
| 750 |
+
"""
|
| 751 |
+
|
| 752 |
+
loss: Optional[tf.Tensor] = None
|
| 753 |
+
prediction_logits: Optional[tf.Tensor] = None
|
| 754 |
+
sop_logits: Optional[tf.Tensor] = None
|
| 755 |
+
hidden_states: Tuple[tf.Tensor] | None = None
|
| 756 |
+
attentions: Tuple[tf.Tensor] | None = None
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
ALBERT_START_DOCSTRING = r"""
|
| 760 |
+
|
| 761 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 762 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 763 |
+
etc.)
|
| 764 |
+
|
| 765 |
+
This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
| 766 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
| 767 |
+
behavior.
|
| 768 |
+
|
| 769 |
+
<Tip>
|
| 770 |
+
|
| 771 |
+
TensorFlow models and layers in `transformers` accept two formats as input:
|
| 772 |
+
|
| 773 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
| 774 |
+
- having all inputs as a list, tuple or dict in the first positional argument.
|
| 775 |
+
|
| 776 |
+
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
|
| 777 |
+
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
|
| 778 |
+
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
|
| 779 |
+
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
|
| 780 |
+
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
|
| 781 |
+
positional argument:
|
| 782 |
+
|
| 783 |
+
- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
|
| 784 |
+
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
|
| 785 |
+
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
|
| 786 |
+
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
|
| 787 |
+
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
|
| 788 |
+
|
| 789 |
+
Note that when creating models and layers with
|
| 790 |
+
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
|
| 791 |
+
about any of this, as you can just pass inputs like you would to any other Python function!
|
| 792 |
+
|
| 793 |
+
</Tip>
|
| 794 |
+
|
| 795 |
+
Args:
|
| 796 |
+
config ([`AlbertConfig`]): Model configuration class with all the parameters of the model.
|
| 797 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 798 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 799 |
+
"""
|
| 800 |
+
|
| 801 |
+
ALBERT_INPUTS_DOCSTRING = r"""
|
| 802 |
+
Args:
|
| 803 |
+
input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
|
| 804 |
+
Indices of input sequence tokens in the vocabulary.
|
| 805 |
+
|
| 806 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
|
| 807 |
+
[`PreTrainedTokenizer.encode`] for details.
|
| 808 |
+
|
| 809 |
+
[What are input IDs?](../glossary#input-ids)
|
| 810 |
+
attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
|
| 811 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 812 |
+
|
| 813 |
+
- 1 for tokens that are **not masked**,
|
| 814 |
+
- 0 for tokens that are **masked**.
|
| 815 |
+
|
| 816 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 817 |
+
token_type_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
|
| 818 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 819 |
+
1]`:
|
| 820 |
+
|
| 821 |
+
- 0 corresponds to a *sentence A* token,
|
| 822 |
+
- 1 corresponds to a *sentence B* token.
|
| 823 |
+
|
| 824 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 825 |
+
position_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
|
| 826 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 827 |
+
config.max_position_embeddings - 1]`.
|
| 828 |
+
|
| 829 |
+
[What are position IDs?](../glossary#position-ids)
|
| 830 |
+
head_mask (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 831 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 832 |
+
|
| 833 |
+
- 1 indicates the head is **not masked**,
|
| 834 |
+
- 0 indicates the head is **masked**.
|
| 835 |
+
|
| 836 |
+
inputs_embeds (`tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
|
| 837 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 838 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 839 |
+
model's internal embedding lookup matrix.
|
| 840 |
+
output_attentions (`bool`, *optional*):
|
| 841 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 842 |
+
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
|
| 843 |
+
config will be used instead.
|
| 844 |
+
output_hidden_states (`bool`, *optional*):
|
| 845 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 846 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 847 |
+
used instead.
|
| 848 |
+
return_dict (`bool`, *optional*):
|
| 849 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 850 |
+
eager mode, in graph mode the value will always be set to True.
|
| 851 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 852 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 853 |
+
behaviors between training and evaluation).
|
| 854 |
+
"""
|
| 855 |
+
|
| 856 |
+
|
| 857 |
+
@add_start_docstrings(
|
| 858 |
+
"The bare Albert Model transformer outputting raw hidden-states without any specific head on top.",
|
| 859 |
+
ALBERT_START_DOCSTRING,
|
| 860 |
+
)
|
| 861 |
+
class TFAlbertModel(TFAlbertPreTrainedModel):
|
| 862 |
+
def __init__(self, config: AlbertConfig, *inputs, **kwargs):
|
| 863 |
+
super().__init__(config, *inputs, **kwargs)
|
| 864 |
+
|
| 865 |
+
self.albert = TFAlbertMainLayer(config, name="albert")
|
| 866 |
+
|
| 867 |
+
@unpack_inputs
|
| 868 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 869 |
+
@add_code_sample_docstrings(
|
| 870 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 871 |
+
output_type=TFBaseModelOutputWithPooling,
|
| 872 |
+
config_class=_CONFIG_FOR_DOC,
|
| 873 |
+
)
|
| 874 |
+
def call(
|
| 875 |
+
self,
|
| 876 |
+
input_ids: TFModelInputType | None = None,
|
| 877 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 878 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 879 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 880 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 881 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 882 |
+
output_attentions: Optional[bool] = None,
|
| 883 |
+
output_hidden_states: Optional[bool] = None,
|
| 884 |
+
return_dict: Optional[bool] = None,
|
| 885 |
+
training: Optional[bool] = False,
|
| 886 |
+
) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]:
|
| 887 |
+
outputs = self.albert(
|
| 888 |
+
input_ids=input_ids,
|
| 889 |
+
attention_mask=attention_mask,
|
| 890 |
+
token_type_ids=token_type_ids,
|
| 891 |
+
position_ids=position_ids,
|
| 892 |
+
head_mask=head_mask,
|
| 893 |
+
inputs_embeds=inputs_embeds,
|
| 894 |
+
output_attentions=output_attentions,
|
| 895 |
+
output_hidden_states=output_hidden_states,
|
| 896 |
+
return_dict=return_dict,
|
| 897 |
+
training=training,
|
| 898 |
+
)
|
| 899 |
+
|
| 900 |
+
return outputs
|
| 901 |
+
|
| 902 |
+
def build(self, input_shape=None):
|
| 903 |
+
if self.built:
|
| 904 |
+
return
|
| 905 |
+
self.built = True
|
| 906 |
+
if getattr(self, "albert", None) is not None:
|
| 907 |
+
with tf.name_scope(self.albert.name):
|
| 908 |
+
self.albert.build(None)
|
| 909 |
+
|
| 910 |
+
|
| 911 |
+
@add_start_docstrings(
|
| 912 |
+
"""
|
| 913 |
+
Albert Model with two heads on top for pretraining: a `masked language modeling` head and a `sentence order
|
| 914 |
+
prediction` (classification) head.
|
| 915 |
+
""",
|
| 916 |
+
ALBERT_START_DOCSTRING,
|
| 917 |
+
)
|
| 918 |
+
class TFAlbertForPreTraining(TFAlbertPreTrainedModel, TFAlbertPreTrainingLoss):
|
| 919 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 920 |
+
_keys_to_ignore_on_load_unexpected = [r"predictions.decoder.weight"]
|
| 921 |
+
|
| 922 |
+
def __init__(self, config: AlbertConfig, *inputs, **kwargs):
|
| 923 |
+
super().__init__(config, *inputs, **kwargs)
|
| 924 |
+
|
| 925 |
+
self.num_labels = config.num_labels
|
| 926 |
+
|
| 927 |
+
self.albert = TFAlbertMainLayer(config, name="albert")
|
| 928 |
+
self.predictions = TFAlbertMLMHead(config, input_embeddings=self.albert.embeddings, name="predictions")
|
| 929 |
+
self.sop_classifier = TFAlbertSOPHead(config, name="sop_classifier")
|
| 930 |
+
|
| 931 |
+
def get_lm_head(self) -> keras.layers.Layer:
|
| 932 |
+
return self.predictions
|
| 933 |
+
|
| 934 |
+
@unpack_inputs
|
| 935 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 936 |
+
@replace_return_docstrings(output_type=TFAlbertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
|
| 937 |
+
def call(
|
| 938 |
+
self,
|
| 939 |
+
input_ids: TFModelInputType | None = None,
|
| 940 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 941 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 942 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 943 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 944 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 945 |
+
output_attentions: Optional[bool] = None,
|
| 946 |
+
output_hidden_states: Optional[bool] = None,
|
| 947 |
+
return_dict: Optional[bool] = None,
|
| 948 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 949 |
+
sentence_order_label: np.ndarray | tf.Tensor | None = None,
|
| 950 |
+
training: Optional[bool] = False,
|
| 951 |
+
) -> Union[TFAlbertForPreTrainingOutput, Tuple[tf.Tensor]]:
|
| 952 |
+
r"""
|
| 953 |
+
Return:
|
| 954 |
+
|
| 955 |
+
Example:
|
| 956 |
+
|
| 957 |
+
```python
|
| 958 |
+
>>> import tensorflow as tf
|
| 959 |
+
>>> from transformers import AutoTokenizer, TFAlbertForPreTraining
|
| 960 |
+
|
| 961 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
|
| 962 |
+
>>> model = TFAlbertForPreTraining.from_pretrained("albert/albert-base-v2")
|
| 963 |
+
|
| 964 |
+
>>> input_ids = tf.constant(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True))[None, :]
|
| 965 |
+
>>> # Batch size 1
|
| 966 |
+
>>> outputs = model(input_ids)
|
| 967 |
+
|
| 968 |
+
>>> prediction_logits = outputs.prediction_logits
|
| 969 |
+
>>> sop_logits = outputs.sop_logits
|
| 970 |
+
```"""
|
| 971 |
+
|
| 972 |
+
outputs = self.albert(
|
| 973 |
+
input_ids=input_ids,
|
| 974 |
+
attention_mask=attention_mask,
|
| 975 |
+
token_type_ids=token_type_ids,
|
| 976 |
+
position_ids=position_ids,
|
| 977 |
+
head_mask=head_mask,
|
| 978 |
+
inputs_embeds=inputs_embeds,
|
| 979 |
+
output_attentions=output_attentions,
|
| 980 |
+
output_hidden_states=output_hidden_states,
|
| 981 |
+
return_dict=return_dict,
|
| 982 |
+
training=training,
|
| 983 |
+
)
|
| 984 |
+
sequence_output, pooled_output = outputs[:2]
|
| 985 |
+
prediction_scores = self.predictions(hidden_states=sequence_output)
|
| 986 |
+
sop_scores = self.sop_classifier(pooled_output=pooled_output, training=training)
|
| 987 |
+
total_loss = None
|
| 988 |
+
|
| 989 |
+
if labels is not None and sentence_order_label is not None:
|
| 990 |
+
d_labels = {"labels": labels}
|
| 991 |
+
d_labels["sentence_order_label"] = sentence_order_label
|
| 992 |
+
total_loss = self.hf_compute_loss(labels=d_labels, logits=(prediction_scores, sop_scores))
|
| 993 |
+
|
| 994 |
+
if not return_dict:
|
| 995 |
+
output = (prediction_scores, sop_scores) + outputs[2:]
|
| 996 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 997 |
+
|
| 998 |
+
return TFAlbertForPreTrainingOutput(
|
| 999 |
+
loss=total_loss,
|
| 1000 |
+
prediction_logits=prediction_scores,
|
| 1001 |
+
sop_logits=sop_scores,
|
| 1002 |
+
hidden_states=outputs.hidden_states,
|
| 1003 |
+
attentions=outputs.attentions,
|
| 1004 |
+
)
|
| 1005 |
+
|
| 1006 |
+
def build(self, input_shape=None):
|
| 1007 |
+
if self.built:
|
| 1008 |
+
return
|
| 1009 |
+
self.built = True
|
| 1010 |
+
if getattr(self, "albert", None) is not None:
|
| 1011 |
+
with tf.name_scope(self.albert.name):
|
| 1012 |
+
self.albert.build(None)
|
| 1013 |
+
if getattr(self, "predictions", None) is not None:
|
| 1014 |
+
with tf.name_scope(self.predictions.name):
|
| 1015 |
+
self.predictions.build(None)
|
| 1016 |
+
if getattr(self, "sop_classifier", None) is not None:
|
| 1017 |
+
with tf.name_scope(self.sop_classifier.name):
|
| 1018 |
+
self.sop_classifier.build(None)
|
| 1019 |
+
|
| 1020 |
+
|
| 1021 |
+
class TFAlbertSOPHead(keras.layers.Layer):
|
| 1022 |
+
def __init__(self, config: AlbertConfig, **kwargs):
|
| 1023 |
+
super().__init__(**kwargs)
|
| 1024 |
+
|
| 1025 |
+
self.dropout = keras.layers.Dropout(rate=config.classifier_dropout_prob)
|
| 1026 |
+
self.classifier = keras.layers.Dense(
|
| 1027 |
+
units=config.num_labels,
|
| 1028 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 1029 |
+
name="classifier",
|
| 1030 |
+
)
|
| 1031 |
+
self.config = config
|
| 1032 |
+
|
| 1033 |
+
def call(self, pooled_output: tf.Tensor, training: bool) -> tf.Tensor:
|
| 1034 |
+
dropout_pooled_output = self.dropout(inputs=pooled_output, training=training)
|
| 1035 |
+
logits = self.classifier(inputs=dropout_pooled_output)
|
| 1036 |
+
|
| 1037 |
+
return logits
|
| 1038 |
+
|
| 1039 |
+
def build(self, input_shape=None):
|
| 1040 |
+
if self.built:
|
| 1041 |
+
return
|
| 1042 |
+
self.built = True
|
| 1043 |
+
if getattr(self, "classifier", None) is not None:
|
| 1044 |
+
with tf.name_scope(self.classifier.name):
|
| 1045 |
+
self.classifier.build([None, None, self.config.hidden_size])
|
| 1046 |
+
|
| 1047 |
+
|
| 1048 |
+
@add_start_docstrings("""Albert Model with a `language modeling` head on top.""", ALBERT_START_DOCSTRING)
|
| 1049 |
+
class TFAlbertForMaskedLM(TFAlbertPreTrainedModel, TFMaskedLanguageModelingLoss):
|
| 1050 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1051 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler", r"predictions.decoder.weight"]
|
| 1052 |
+
|
| 1053 |
+
def __init__(self, config: AlbertConfig, *inputs, **kwargs):
|
| 1054 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1055 |
+
|
| 1056 |
+
self.albert = TFAlbertMainLayer(config, add_pooling_layer=False, name="albert")
|
| 1057 |
+
self.predictions = TFAlbertMLMHead(config, input_embeddings=self.albert.embeddings, name="predictions")
|
| 1058 |
+
|
| 1059 |
+
def get_lm_head(self) -> keras.layers.Layer:
|
| 1060 |
+
return self.predictions
|
| 1061 |
+
|
| 1062 |
+
@unpack_inputs
|
| 1063 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1064 |
+
@replace_return_docstrings(output_type=TFMaskedLMOutput, config_class=_CONFIG_FOR_DOC)
|
| 1065 |
+
def call(
|
| 1066 |
+
self,
|
| 1067 |
+
input_ids: TFModelInputType | None = None,
|
| 1068 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1069 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1070 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1071 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1072 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1073 |
+
output_attentions: Optional[bool] = None,
|
| 1074 |
+
output_hidden_states: Optional[bool] = None,
|
| 1075 |
+
return_dict: Optional[bool] = None,
|
| 1076 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 1077 |
+
training: Optional[bool] = False,
|
| 1078 |
+
) -> Union[TFMaskedLMOutput, Tuple[tf.Tensor]]:
|
| 1079 |
+
r"""
|
| 1080 |
+
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1081 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 1082 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 1083 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 1084 |
+
|
| 1085 |
+
Returns:
|
| 1086 |
+
|
| 1087 |
+
Example:
|
| 1088 |
+
|
| 1089 |
+
```python
|
| 1090 |
+
>>> import tensorflow as tf
|
| 1091 |
+
>>> from transformers import AutoTokenizer, TFAlbertForMaskedLM
|
| 1092 |
+
|
| 1093 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("albert/albert-base-v2")
|
| 1094 |
+
>>> model = TFAlbertForMaskedLM.from_pretrained("albert/albert-base-v2")
|
| 1095 |
+
|
| 1096 |
+
>>> # add mask_token
|
| 1097 |
+
>>> inputs = tokenizer(f"The capital of [MASK] is Paris.", return_tensors="tf")
|
| 1098 |
+
>>> logits = model(**inputs).logits
|
| 1099 |
+
|
| 1100 |
+
>>> # retrieve index of [MASK]
|
| 1101 |
+
>>> mask_token_index = tf.where(inputs.input_ids == tokenizer.mask_token_id)[0][1]
|
| 1102 |
+
>>> predicted_token_id = tf.math.argmax(logits[0, mask_token_index], axis=-1)
|
| 1103 |
+
>>> tokenizer.decode(predicted_token_id)
|
| 1104 |
+
'france'
|
| 1105 |
+
```
|
| 1106 |
+
|
| 1107 |
+
```python
|
| 1108 |
+
>>> labels = tokenizer("The capital of France is Paris.", return_tensors="tf")["input_ids"]
|
| 1109 |
+
>>> labels = tf.where(inputs.input_ids == tokenizer.mask_token_id, labels, -100)
|
| 1110 |
+
>>> outputs = model(**inputs, labels=labels)
|
| 1111 |
+
>>> round(float(outputs.loss), 2)
|
| 1112 |
+
0.81
|
| 1113 |
+
```
|
| 1114 |
+
"""
|
| 1115 |
+
outputs = self.albert(
|
| 1116 |
+
input_ids=input_ids,
|
| 1117 |
+
attention_mask=attention_mask,
|
| 1118 |
+
token_type_ids=token_type_ids,
|
| 1119 |
+
position_ids=position_ids,
|
| 1120 |
+
head_mask=head_mask,
|
| 1121 |
+
inputs_embeds=inputs_embeds,
|
| 1122 |
+
output_attentions=output_attentions,
|
| 1123 |
+
output_hidden_states=output_hidden_states,
|
| 1124 |
+
return_dict=return_dict,
|
| 1125 |
+
training=training,
|
| 1126 |
+
)
|
| 1127 |
+
sequence_output = outputs[0]
|
| 1128 |
+
prediction_scores = self.predictions(hidden_states=sequence_output, training=training)
|
| 1129 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=prediction_scores)
|
| 1130 |
+
|
| 1131 |
+
if not return_dict:
|
| 1132 |
+
output = (prediction_scores,) + outputs[2:]
|
| 1133 |
+
|
| 1134 |
+
return ((loss,) + output) if loss is not None else output
|
| 1135 |
+
|
| 1136 |
+
return TFMaskedLMOutput(
|
| 1137 |
+
loss=loss,
|
| 1138 |
+
logits=prediction_scores,
|
| 1139 |
+
hidden_states=outputs.hidden_states,
|
| 1140 |
+
attentions=outputs.attentions,
|
| 1141 |
+
)
|
| 1142 |
+
|
| 1143 |
+
def build(self, input_shape=None):
|
| 1144 |
+
if self.built:
|
| 1145 |
+
return
|
| 1146 |
+
self.built = True
|
| 1147 |
+
if getattr(self, "albert", None) is not None:
|
| 1148 |
+
with tf.name_scope(self.albert.name):
|
| 1149 |
+
self.albert.build(None)
|
| 1150 |
+
if getattr(self, "predictions", None) is not None:
|
| 1151 |
+
with tf.name_scope(self.predictions.name):
|
| 1152 |
+
self.predictions.build(None)
|
| 1153 |
+
|
| 1154 |
+
|
| 1155 |
+
@add_start_docstrings(
|
| 1156 |
+
"""
|
| 1157 |
+
Albert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
|
| 1158 |
+
output) e.g. for GLUE tasks.
|
| 1159 |
+
""",
|
| 1160 |
+
ALBERT_START_DOCSTRING,
|
| 1161 |
+
)
|
| 1162 |
+
class TFAlbertForSequenceClassification(TFAlbertPreTrainedModel, TFSequenceClassificationLoss):
|
| 1163 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1164 |
+
_keys_to_ignore_on_load_unexpected = [r"predictions"]
|
| 1165 |
+
_keys_to_ignore_on_load_missing = [r"dropout"]
|
| 1166 |
+
|
| 1167 |
+
def __init__(self, config: AlbertConfig, *inputs, **kwargs):
|
| 1168 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1169 |
+
|
| 1170 |
+
self.num_labels = config.num_labels
|
| 1171 |
+
|
| 1172 |
+
self.albert = TFAlbertMainLayer(config, name="albert")
|
| 1173 |
+
self.dropout = keras.layers.Dropout(rate=config.classifier_dropout_prob)
|
| 1174 |
+
self.classifier = keras.layers.Dense(
|
| 1175 |
+
units=config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
|
| 1176 |
+
)
|
| 1177 |
+
self.config = config
|
| 1178 |
+
|
| 1179 |
+
@unpack_inputs
|
| 1180 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1181 |
+
@add_code_sample_docstrings(
|
| 1182 |
+
checkpoint="vumichien/albert-base-v2-imdb",
|
| 1183 |
+
output_type=TFSequenceClassifierOutput,
|
| 1184 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1185 |
+
expected_output="'LABEL_1'",
|
| 1186 |
+
expected_loss=0.12,
|
| 1187 |
+
)
|
| 1188 |
+
def call(
|
| 1189 |
+
self,
|
| 1190 |
+
input_ids: TFModelInputType | None = None,
|
| 1191 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1192 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1193 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1194 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1195 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1196 |
+
output_attentions: Optional[bool] = None,
|
| 1197 |
+
output_hidden_states: Optional[bool] = None,
|
| 1198 |
+
return_dict: Optional[bool] = None,
|
| 1199 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 1200 |
+
training: Optional[bool] = False,
|
| 1201 |
+
) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
|
| 1202 |
+
r"""
|
| 1203 |
+
labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1204 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1205 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1206 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1207 |
+
"""
|
| 1208 |
+
outputs = self.albert(
|
| 1209 |
+
input_ids=input_ids,
|
| 1210 |
+
attention_mask=attention_mask,
|
| 1211 |
+
token_type_ids=token_type_ids,
|
| 1212 |
+
position_ids=position_ids,
|
| 1213 |
+
head_mask=head_mask,
|
| 1214 |
+
inputs_embeds=inputs_embeds,
|
| 1215 |
+
output_attentions=output_attentions,
|
| 1216 |
+
output_hidden_states=output_hidden_states,
|
| 1217 |
+
return_dict=return_dict,
|
| 1218 |
+
training=training,
|
| 1219 |
+
)
|
| 1220 |
+
pooled_output = outputs[1]
|
| 1221 |
+
pooled_output = self.dropout(inputs=pooled_output, training=training)
|
| 1222 |
+
logits = self.classifier(inputs=pooled_output)
|
| 1223 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
|
| 1224 |
+
|
| 1225 |
+
if not return_dict:
|
| 1226 |
+
output = (logits,) + outputs[2:]
|
| 1227 |
+
|
| 1228 |
+
return ((loss,) + output) if loss is not None else output
|
| 1229 |
+
|
| 1230 |
+
return TFSequenceClassifierOutput(
|
| 1231 |
+
loss=loss,
|
| 1232 |
+
logits=logits,
|
| 1233 |
+
hidden_states=outputs.hidden_states,
|
| 1234 |
+
attentions=outputs.attentions,
|
| 1235 |
+
)
|
| 1236 |
+
|
| 1237 |
+
def build(self, input_shape=None):
|
| 1238 |
+
if self.built:
|
| 1239 |
+
return
|
| 1240 |
+
self.built = True
|
| 1241 |
+
if getattr(self, "albert", None) is not None:
|
| 1242 |
+
with tf.name_scope(self.albert.name):
|
| 1243 |
+
self.albert.build(None)
|
| 1244 |
+
if getattr(self, "classifier", None) is not None:
|
| 1245 |
+
with tf.name_scope(self.classifier.name):
|
| 1246 |
+
self.classifier.build([None, None, self.config.hidden_size])
|
| 1247 |
+
|
| 1248 |
+
|
| 1249 |
+
@add_start_docstrings(
|
| 1250 |
+
"""
|
| 1251 |
+
Albert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
| 1252 |
+
Named-Entity-Recognition (NER) tasks.
|
| 1253 |
+
""",
|
| 1254 |
+
ALBERT_START_DOCSTRING,
|
| 1255 |
+
)
|
| 1256 |
+
class TFAlbertForTokenClassification(TFAlbertPreTrainedModel, TFTokenClassificationLoss):
|
| 1257 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1258 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler", r"predictions"]
|
| 1259 |
+
_keys_to_ignore_on_load_missing = [r"dropout"]
|
| 1260 |
+
|
| 1261 |
+
def __init__(self, config: AlbertConfig, *inputs, **kwargs):
|
| 1262 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1263 |
+
|
| 1264 |
+
self.num_labels = config.num_labels
|
| 1265 |
+
|
| 1266 |
+
self.albert = TFAlbertMainLayer(config, add_pooling_layer=False, name="albert")
|
| 1267 |
+
classifier_dropout_prob = (
|
| 1268 |
+
config.classifier_dropout_prob
|
| 1269 |
+
if config.classifier_dropout_prob is not None
|
| 1270 |
+
else config.hidden_dropout_prob
|
| 1271 |
+
)
|
| 1272 |
+
self.dropout = keras.layers.Dropout(rate=classifier_dropout_prob)
|
| 1273 |
+
self.classifier = keras.layers.Dense(
|
| 1274 |
+
units=config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
|
| 1275 |
+
)
|
| 1276 |
+
self.config = config
|
| 1277 |
+
|
| 1278 |
+
@unpack_inputs
|
| 1279 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1280 |
+
@add_code_sample_docstrings(
|
| 1281 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1282 |
+
output_type=TFTokenClassifierOutput,
|
| 1283 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1284 |
+
)
|
| 1285 |
+
def call(
|
| 1286 |
+
self,
|
| 1287 |
+
input_ids: TFModelInputType | None = None,
|
| 1288 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1289 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1290 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1291 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1292 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1293 |
+
output_attentions: Optional[bool] = None,
|
| 1294 |
+
output_hidden_states: Optional[bool] = None,
|
| 1295 |
+
return_dict: Optional[bool] = None,
|
| 1296 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 1297 |
+
training: Optional[bool] = False,
|
| 1298 |
+
) -> Union[TFTokenClassifierOutput, Tuple[tf.Tensor]]:
|
| 1299 |
+
r"""
|
| 1300 |
+
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1301 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 1302 |
+
"""
|
| 1303 |
+
outputs = self.albert(
|
| 1304 |
+
input_ids=input_ids,
|
| 1305 |
+
attention_mask=attention_mask,
|
| 1306 |
+
token_type_ids=token_type_ids,
|
| 1307 |
+
position_ids=position_ids,
|
| 1308 |
+
head_mask=head_mask,
|
| 1309 |
+
inputs_embeds=inputs_embeds,
|
| 1310 |
+
output_attentions=output_attentions,
|
| 1311 |
+
output_hidden_states=output_hidden_states,
|
| 1312 |
+
return_dict=return_dict,
|
| 1313 |
+
training=training,
|
| 1314 |
+
)
|
| 1315 |
+
sequence_output = outputs[0]
|
| 1316 |
+
sequence_output = self.dropout(inputs=sequence_output, training=training)
|
| 1317 |
+
logits = self.classifier(inputs=sequence_output)
|
| 1318 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
|
| 1319 |
+
|
| 1320 |
+
if not return_dict:
|
| 1321 |
+
output = (logits,) + outputs[2:]
|
| 1322 |
+
|
| 1323 |
+
return ((loss,) + output) if loss is not None else output
|
| 1324 |
+
|
| 1325 |
+
return TFTokenClassifierOutput(
|
| 1326 |
+
loss=loss,
|
| 1327 |
+
logits=logits,
|
| 1328 |
+
hidden_states=outputs.hidden_states,
|
| 1329 |
+
attentions=outputs.attentions,
|
| 1330 |
+
)
|
| 1331 |
+
|
| 1332 |
+
def build(self, input_shape=None):
|
| 1333 |
+
if self.built:
|
| 1334 |
+
return
|
| 1335 |
+
self.built = True
|
| 1336 |
+
if getattr(self, "albert", None) is not None:
|
| 1337 |
+
with tf.name_scope(self.albert.name):
|
| 1338 |
+
self.albert.build(None)
|
| 1339 |
+
if getattr(self, "classifier", None) is not None:
|
| 1340 |
+
with tf.name_scope(self.classifier.name):
|
| 1341 |
+
self.classifier.build([None, None, self.config.hidden_size])
|
| 1342 |
+
|
| 1343 |
+
|
| 1344 |
+
@add_start_docstrings(
|
| 1345 |
+
"""
|
| 1346 |
+
Albert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
|
| 1347 |
+
layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 1348 |
+
""",
|
| 1349 |
+
ALBERT_START_DOCSTRING,
|
| 1350 |
+
)
|
| 1351 |
+
class TFAlbertForQuestionAnswering(TFAlbertPreTrainedModel, TFQuestionAnsweringLoss):
|
| 1352 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1353 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler", r"predictions"]
|
| 1354 |
+
|
| 1355 |
+
def __init__(self, config: AlbertConfig, *inputs, **kwargs):
|
| 1356 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1357 |
+
|
| 1358 |
+
self.num_labels = config.num_labels
|
| 1359 |
+
|
| 1360 |
+
self.albert = TFAlbertMainLayer(config, add_pooling_layer=False, name="albert")
|
| 1361 |
+
self.qa_outputs = keras.layers.Dense(
|
| 1362 |
+
units=config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
|
| 1363 |
+
)
|
| 1364 |
+
self.config = config
|
| 1365 |
+
|
| 1366 |
+
@unpack_inputs
|
| 1367 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1368 |
+
@add_code_sample_docstrings(
|
| 1369 |
+
checkpoint="vumichien/albert-base-v2-squad2",
|
| 1370 |
+
output_type=TFQuestionAnsweringModelOutput,
|
| 1371 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1372 |
+
qa_target_start_index=12,
|
| 1373 |
+
qa_target_end_index=13,
|
| 1374 |
+
expected_output="'a nice puppet'",
|
| 1375 |
+
expected_loss=7.36,
|
| 1376 |
+
)
|
| 1377 |
+
def call(
|
| 1378 |
+
self,
|
| 1379 |
+
input_ids: TFModelInputType | None = None,
|
| 1380 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1381 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1382 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1383 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1384 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1385 |
+
output_attentions: Optional[bool] = None,
|
| 1386 |
+
output_hidden_states: Optional[bool] = None,
|
| 1387 |
+
return_dict: Optional[bool] = None,
|
| 1388 |
+
start_positions: np.ndarray | tf.Tensor | None = None,
|
| 1389 |
+
end_positions: np.ndarray | tf.Tensor | None = None,
|
| 1390 |
+
training: Optional[bool] = False,
|
| 1391 |
+
) -> Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]]:
|
| 1392 |
+
r"""
|
| 1393 |
+
start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1394 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 1395 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1396 |
+
are not taken into account for computing the loss.
|
| 1397 |
+
end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1398 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 1399 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1400 |
+
are not taken into account for computing the loss.
|
| 1401 |
+
"""
|
| 1402 |
+
outputs = self.albert(
|
| 1403 |
+
input_ids=input_ids,
|
| 1404 |
+
attention_mask=attention_mask,
|
| 1405 |
+
token_type_ids=token_type_ids,
|
| 1406 |
+
position_ids=position_ids,
|
| 1407 |
+
head_mask=head_mask,
|
| 1408 |
+
inputs_embeds=inputs_embeds,
|
| 1409 |
+
output_attentions=output_attentions,
|
| 1410 |
+
output_hidden_states=output_hidden_states,
|
| 1411 |
+
return_dict=return_dict,
|
| 1412 |
+
training=training,
|
| 1413 |
+
)
|
| 1414 |
+
sequence_output = outputs[0]
|
| 1415 |
+
logits = self.qa_outputs(inputs=sequence_output)
|
| 1416 |
+
start_logits, end_logits = tf.split(value=logits, num_or_size_splits=2, axis=-1)
|
| 1417 |
+
start_logits = tf.squeeze(input=start_logits, axis=-1)
|
| 1418 |
+
end_logits = tf.squeeze(input=end_logits, axis=-1)
|
| 1419 |
+
loss = None
|
| 1420 |
+
|
| 1421 |
+
if start_positions is not None and end_positions is not None:
|
| 1422 |
+
labels = {"start_position": start_positions}
|
| 1423 |
+
labels["end_position"] = end_positions
|
| 1424 |
+
loss = self.hf_compute_loss(labels=labels, logits=(start_logits, end_logits))
|
| 1425 |
+
|
| 1426 |
+
if not return_dict:
|
| 1427 |
+
output = (start_logits, end_logits) + outputs[2:]
|
| 1428 |
+
|
| 1429 |
+
return ((loss,) + output) if loss is not None else output
|
| 1430 |
+
|
| 1431 |
+
return TFQuestionAnsweringModelOutput(
|
| 1432 |
+
loss=loss,
|
| 1433 |
+
start_logits=start_logits,
|
| 1434 |
+
end_logits=end_logits,
|
| 1435 |
+
hidden_states=outputs.hidden_states,
|
| 1436 |
+
attentions=outputs.attentions,
|
| 1437 |
+
)
|
| 1438 |
+
|
| 1439 |
+
def build(self, input_shape=None):
|
| 1440 |
+
if self.built:
|
| 1441 |
+
return
|
| 1442 |
+
self.built = True
|
| 1443 |
+
if getattr(self, "albert", None) is not None:
|
| 1444 |
+
with tf.name_scope(self.albert.name):
|
| 1445 |
+
self.albert.build(None)
|
| 1446 |
+
if getattr(self, "qa_outputs", None) is not None:
|
| 1447 |
+
with tf.name_scope(self.qa_outputs.name):
|
| 1448 |
+
self.qa_outputs.build([None, None, self.config.hidden_size])
|
| 1449 |
+
|
| 1450 |
+
|
| 1451 |
+
@add_start_docstrings(
|
| 1452 |
+
"""
|
| 1453 |
+
Albert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
|
| 1454 |
+
softmax) e.g. for RocStories/SWAG tasks.
|
| 1455 |
+
""",
|
| 1456 |
+
ALBERT_START_DOCSTRING,
|
| 1457 |
+
)
|
| 1458 |
+
class TFAlbertForMultipleChoice(TFAlbertPreTrainedModel, TFMultipleChoiceLoss):
|
| 1459 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1460 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler", r"predictions"]
|
| 1461 |
+
_keys_to_ignore_on_load_missing = [r"dropout"]
|
| 1462 |
+
|
| 1463 |
+
def __init__(self, config: AlbertConfig, *inputs, **kwargs):
|
| 1464 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1465 |
+
|
| 1466 |
+
self.albert = TFAlbertMainLayer(config, name="albert")
|
| 1467 |
+
self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
| 1468 |
+
self.classifier = keras.layers.Dense(
|
| 1469 |
+
units=1, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
|
| 1470 |
+
)
|
| 1471 |
+
self.config = config
|
| 1472 |
+
|
| 1473 |
+
@unpack_inputs
|
| 1474 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
|
| 1475 |
+
@add_code_sample_docstrings(
|
| 1476 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1477 |
+
output_type=TFMultipleChoiceModelOutput,
|
| 1478 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1479 |
+
)
|
| 1480 |
+
def call(
|
| 1481 |
+
self,
|
| 1482 |
+
input_ids: TFModelInputType | None = None,
|
| 1483 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1484 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1485 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1486 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1487 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1488 |
+
output_attentions: Optional[bool] = None,
|
| 1489 |
+
output_hidden_states: Optional[bool] = None,
|
| 1490 |
+
return_dict: Optional[bool] = None,
|
| 1491 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 1492 |
+
training: Optional[bool] = False,
|
| 1493 |
+
) -> Union[TFMultipleChoiceModelOutput, Tuple[tf.Tensor]]:
|
| 1494 |
+
r"""
|
| 1495 |
+
labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1496 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
|
| 1497 |
+
where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
|
| 1498 |
+
"""
|
| 1499 |
+
|
| 1500 |
+
if input_ids is not None:
|
| 1501 |
+
num_choices = shape_list(input_ids)[1]
|
| 1502 |
+
seq_length = shape_list(input_ids)[2]
|
| 1503 |
+
else:
|
| 1504 |
+
num_choices = shape_list(inputs_embeds)[1]
|
| 1505 |
+
seq_length = shape_list(inputs_embeds)[2]
|
| 1506 |
+
|
| 1507 |
+
flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None
|
| 1508 |
+
flat_attention_mask = (
|
| 1509 |
+
tf.reshape(tensor=attention_mask, shape=(-1, seq_length)) if attention_mask is not None else None
|
| 1510 |
+
)
|
| 1511 |
+
flat_token_type_ids = (
|
| 1512 |
+
tf.reshape(tensor=token_type_ids, shape=(-1, seq_length)) if token_type_ids is not None else None
|
| 1513 |
+
)
|
| 1514 |
+
flat_position_ids = (
|
| 1515 |
+
tf.reshape(tensor=position_ids, shape=(-1, seq_length)) if position_ids is not None else None
|
| 1516 |
+
)
|
| 1517 |
+
flat_inputs_embeds = (
|
| 1518 |
+
tf.reshape(tensor=inputs_embeds, shape=(-1, seq_length, shape_list(inputs_embeds)[3]))
|
| 1519 |
+
if inputs_embeds is not None
|
| 1520 |
+
else None
|
| 1521 |
+
)
|
| 1522 |
+
outputs = self.albert(
|
| 1523 |
+
input_ids=flat_input_ids,
|
| 1524 |
+
attention_mask=flat_attention_mask,
|
| 1525 |
+
token_type_ids=flat_token_type_ids,
|
| 1526 |
+
position_ids=flat_position_ids,
|
| 1527 |
+
head_mask=head_mask,
|
| 1528 |
+
inputs_embeds=flat_inputs_embeds,
|
| 1529 |
+
output_attentions=output_attentions,
|
| 1530 |
+
output_hidden_states=output_hidden_states,
|
| 1531 |
+
return_dict=return_dict,
|
| 1532 |
+
training=training,
|
| 1533 |
+
)
|
| 1534 |
+
pooled_output = outputs[1]
|
| 1535 |
+
pooled_output = self.dropout(inputs=pooled_output, training=training)
|
| 1536 |
+
logits = self.classifier(inputs=pooled_output)
|
| 1537 |
+
reshaped_logits = tf.reshape(tensor=logits, shape=(-1, num_choices))
|
| 1538 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=reshaped_logits)
|
| 1539 |
+
|
| 1540 |
+
if not return_dict:
|
| 1541 |
+
output = (reshaped_logits,) + outputs[2:]
|
| 1542 |
+
return ((loss,) + output) if loss is not None else output
|
| 1543 |
+
|
| 1544 |
+
return TFMultipleChoiceModelOutput(
|
| 1545 |
+
loss=loss,
|
| 1546 |
+
logits=reshaped_logits,
|
| 1547 |
+
hidden_states=outputs.hidden_states,
|
| 1548 |
+
attentions=outputs.attentions,
|
| 1549 |
+
)
|
| 1550 |
+
|
| 1551 |
+
def build(self, input_shape=None):
|
| 1552 |
+
if self.built:
|
| 1553 |
+
return
|
| 1554 |
+
self.built = True
|
| 1555 |
+
if getattr(self, "albert", None) is not None:
|
| 1556 |
+
with tf.name_scope(self.albert.name):
|
| 1557 |
+
self.albert.build(None)
|
| 1558 |
+
if getattr(self, "classifier", None) is not None:
|
| 1559 |
+
with tf.name_scope(self.classifier.name):
|
| 1560 |
+
self.classifier.build([None, None, self.config.hidden_size])
|
| 1561 |
+
|
| 1562 |
+
|
| 1563 |
+
__all__ = [
|
| 1564 |
+
"TFAlbertPreTrainedModel",
|
| 1565 |
+
"TFAlbertModel",
|
| 1566 |
+
"TFAlbertForPreTraining",
|
| 1567 |
+
"TFAlbertForMaskedLM",
|
| 1568 |
+
"TFAlbertForSequenceClassification",
|
| 1569 |
+
"TFAlbertForTokenClassification",
|
| 1570 |
+
"TFAlbertForQuestionAnswering",
|
| 1571 |
+
"TFAlbertForMultipleChoice",
|
| 1572 |
+
"TFAlbertMainLayer",
|
| 1573 |
+
]
|
lib/python3.12/site-packages/transformers/models/albert/tokenization_albert.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and the HuggingFace Inc. team.
|
| 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 |
+
"""Tokenization classes for ALBERT model."""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
import unicodedata
|
| 19 |
+
from shutil import copyfile
|
| 20 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 21 |
+
|
| 22 |
+
import sentencepiece as spm
|
| 23 |
+
|
| 24 |
+
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
|
| 25 |
+
from ...utils import logging
|
| 26 |
+
from ...utils.import_utils import export
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
logger = logging.get_logger(__name__)
|
| 30 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
SPIECE_UNDERLINE = "▁"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@export(backends=("sentencepiece",))
|
| 37 |
+
class AlbertTokenizer(PreTrainedTokenizer):
|
| 38 |
+
"""
|
| 39 |
+
Construct an ALBERT tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
|
| 40 |
+
|
| 41 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 42 |
+
this superclass for more information regarding those methods.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
vocab_file (`str`):
|
| 46 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
| 47 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 48 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 49 |
+
Whether or not to lowercase the input when tokenizing.
|
| 50 |
+
remove_space (`bool`, *optional*, defaults to `True`):
|
| 51 |
+
Whether or not to strip the text when tokenizing (removing excess spaces before and after the string).
|
| 52 |
+
keep_accents (`bool`, *optional*, defaults to `False`):
|
| 53 |
+
Whether or not to keep accents when tokenizing.
|
| 54 |
+
bos_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 55 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
| 56 |
+
|
| 57 |
+
<Tip>
|
| 58 |
+
|
| 59 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 60 |
+
sequence. The token used is the `cls_token`.
|
| 61 |
+
|
| 62 |
+
</Tip>
|
| 63 |
+
|
| 64 |
+
eos_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 65 |
+
The end of sequence token.
|
| 66 |
+
|
| 67 |
+
<Tip>
|
| 68 |
+
|
| 69 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
| 70 |
+
The token used is the `sep_token`.
|
| 71 |
+
|
| 72 |
+
</Tip>
|
| 73 |
+
|
| 74 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 75 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 76 |
+
token instead.
|
| 77 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 78 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 79 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 80 |
+
token of a sequence built with special tokens.
|
| 81 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 82 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 83 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 84 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 85 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 86 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 87 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 88 |
+
modeling. This is the token which the model will try to predict.
|
| 89 |
+
sp_model_kwargs (`dict`, *optional*):
|
| 90 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
| 91 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
| 92 |
+
to set:
|
| 93 |
+
|
| 94 |
+
- `enable_sampling`: Enable subword regularization.
|
| 95 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
| 96 |
+
|
| 97 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
| 98 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
| 99 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
| 100 |
+
using forward-filtering-and-backward-sampling algorithm.
|
| 101 |
+
|
| 102 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
| 103 |
+
BPE-dropout.
|
| 104 |
+
|
| 105 |
+
Attributes:
|
| 106 |
+
sp_model (`SentencePieceProcessor`):
|
| 107 |
+
The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 111 |
+
|
| 112 |
+
def __init__(
|
| 113 |
+
self,
|
| 114 |
+
vocab_file,
|
| 115 |
+
do_lower_case=True,
|
| 116 |
+
remove_space=True,
|
| 117 |
+
keep_accents=False,
|
| 118 |
+
bos_token="[CLS]",
|
| 119 |
+
eos_token="[SEP]",
|
| 120 |
+
unk_token="<unk>",
|
| 121 |
+
sep_token="[SEP]",
|
| 122 |
+
pad_token="<pad>",
|
| 123 |
+
cls_token="[CLS]",
|
| 124 |
+
mask_token="[MASK]",
|
| 125 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
| 126 |
+
**kwargs,
|
| 127 |
+
) -> None:
|
| 128 |
+
# Mask token behave like a normal word, i.e. include the space before it and
|
| 129 |
+
# is included in the raw text, there should be a match in a non-normalized sentence.
|
| 130 |
+
mask_token = (
|
| 131 |
+
AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False)
|
| 132 |
+
if isinstance(mask_token, str)
|
| 133 |
+
else mask_token
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 137 |
+
|
| 138 |
+
self.do_lower_case = do_lower_case
|
| 139 |
+
self.remove_space = remove_space
|
| 140 |
+
self.keep_accents = keep_accents
|
| 141 |
+
self.vocab_file = vocab_file
|
| 142 |
+
|
| 143 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 144 |
+
self.sp_model.Load(vocab_file)
|
| 145 |
+
|
| 146 |
+
super().__init__(
|
| 147 |
+
do_lower_case=do_lower_case,
|
| 148 |
+
remove_space=remove_space,
|
| 149 |
+
keep_accents=keep_accents,
|
| 150 |
+
bos_token=bos_token,
|
| 151 |
+
eos_token=eos_token,
|
| 152 |
+
unk_token=unk_token,
|
| 153 |
+
sep_token=sep_token,
|
| 154 |
+
pad_token=pad_token,
|
| 155 |
+
cls_token=cls_token,
|
| 156 |
+
mask_token=mask_token,
|
| 157 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
| 158 |
+
**kwargs,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
@property
|
| 162 |
+
def vocab_size(self) -> int:
|
| 163 |
+
return len(self.sp_model)
|
| 164 |
+
|
| 165 |
+
def get_vocab(self) -> Dict[str, int]:
|
| 166 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
| 167 |
+
vocab.update(self.added_tokens_encoder)
|
| 168 |
+
return vocab
|
| 169 |
+
|
| 170 |
+
def __getstate__(self):
|
| 171 |
+
state = self.__dict__.copy()
|
| 172 |
+
state["sp_model"] = None
|
| 173 |
+
return state
|
| 174 |
+
|
| 175 |
+
def __setstate__(self, d):
|
| 176 |
+
self.__dict__ = d
|
| 177 |
+
|
| 178 |
+
# for backward compatibility
|
| 179 |
+
if not hasattr(self, "sp_model_kwargs"):
|
| 180 |
+
self.sp_model_kwargs = {}
|
| 181 |
+
|
| 182 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 183 |
+
self.sp_model.Load(self.vocab_file)
|
| 184 |
+
|
| 185 |
+
def preprocess_text(self, inputs):
|
| 186 |
+
if self.remove_space:
|
| 187 |
+
outputs = " ".join(inputs.strip().split())
|
| 188 |
+
else:
|
| 189 |
+
outputs = inputs
|
| 190 |
+
outputs = outputs.replace("``", '"').replace("''", '"')
|
| 191 |
+
|
| 192 |
+
if not self.keep_accents:
|
| 193 |
+
outputs = unicodedata.normalize("NFKD", outputs)
|
| 194 |
+
outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
|
| 195 |
+
if self.do_lower_case:
|
| 196 |
+
outputs = outputs.lower()
|
| 197 |
+
|
| 198 |
+
return outputs
|
| 199 |
+
|
| 200 |
+
def _tokenize(self, text: str) -> List[str]:
|
| 201 |
+
"""Tokenize a string."""
|
| 202 |
+
text = self.preprocess_text(text)
|
| 203 |
+
pieces = self.sp_model.encode(text, out_type=str)
|
| 204 |
+
new_pieces = []
|
| 205 |
+
for piece in pieces:
|
| 206 |
+
if len(piece) > 1 and piece[-1] == str(",") and piece[-2].isdigit():
|
| 207 |
+
# Logic to handle special cases see https://github.com/google-research/bert/blob/master/README.md#tokenization
|
| 208 |
+
# `9,9` -> ['▁9', ',', '9'] instead of [`_9,`, '9']
|
| 209 |
+
cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
|
| 210 |
+
if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
|
| 211 |
+
if len(cur_pieces[0]) == 1:
|
| 212 |
+
cur_pieces = cur_pieces[1:]
|
| 213 |
+
else:
|
| 214 |
+
cur_pieces[0] = cur_pieces[0][1:]
|
| 215 |
+
cur_pieces.append(piece[-1])
|
| 216 |
+
new_pieces.extend(cur_pieces)
|
| 217 |
+
else:
|
| 218 |
+
new_pieces.append(piece)
|
| 219 |
+
|
| 220 |
+
return new_pieces
|
| 221 |
+
|
| 222 |
+
def _convert_token_to_id(self, token):
|
| 223 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 224 |
+
return self.sp_model.PieceToId(token)
|
| 225 |
+
|
| 226 |
+
def _convert_id_to_token(self, index):
|
| 227 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 228 |
+
return self.sp_model.IdToPiece(index)
|
| 229 |
+
|
| 230 |
+
def convert_tokens_to_string(self, tokens):
|
| 231 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 232 |
+
current_sub_tokens = []
|
| 233 |
+
out_string = ""
|
| 234 |
+
prev_is_special = False
|
| 235 |
+
for token in tokens:
|
| 236 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
| 237 |
+
if token in self.all_special_tokens:
|
| 238 |
+
if not prev_is_special:
|
| 239 |
+
out_string += " "
|
| 240 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
| 241 |
+
prev_is_special = True
|
| 242 |
+
current_sub_tokens = []
|
| 243 |
+
else:
|
| 244 |
+
current_sub_tokens.append(token)
|
| 245 |
+
prev_is_special = False
|
| 246 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
| 247 |
+
return out_string.strip()
|
| 248 |
+
|
| 249 |
+
def build_inputs_with_special_tokens(
|
| 250 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 251 |
+
) -> List[int]:
|
| 252 |
+
"""
|
| 253 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 254 |
+
adding special tokens. An ALBERT sequence has the following format:
|
| 255 |
+
|
| 256 |
+
- single sequence: `[CLS] X [SEP]`
|
| 257 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 258 |
+
|
| 259 |
+
Args:
|
| 260 |
+
token_ids_0 (`List[int]`):
|
| 261 |
+
List of IDs to which the special tokens will be added.
|
| 262 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 263 |
+
Optional second list of IDs for sequence pairs.
|
| 264 |
+
|
| 265 |
+
Returns:
|
| 266 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 267 |
+
"""
|
| 268 |
+
sep = [self.sep_token_id]
|
| 269 |
+
cls = [self.cls_token_id]
|
| 270 |
+
if token_ids_1 is None:
|
| 271 |
+
return cls + token_ids_0 + sep
|
| 272 |
+
return cls + token_ids_0 + sep + token_ids_1 + sep
|
| 273 |
+
|
| 274 |
+
def get_special_tokens_mask(
|
| 275 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
| 276 |
+
) -> List[int]:
|
| 277 |
+
"""
|
| 278 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 279 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 280 |
+
|
| 281 |
+
Args:
|
| 282 |
+
token_ids_0 (`List[int]`):
|
| 283 |
+
List of IDs.
|
| 284 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 285 |
+
Optional second list of IDs for sequence pairs.
|
| 286 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 287 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 288 |
+
|
| 289 |
+
Returns:
|
| 290 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 291 |
+
"""
|
| 292 |
+
|
| 293 |
+
if already_has_special_tokens:
|
| 294 |
+
return super().get_special_tokens_mask(
|
| 295 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
if token_ids_1 is not None:
|
| 299 |
+
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
|
| 300 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
| 301 |
+
|
| 302 |
+
def create_token_type_ids_from_sequences(
|
| 303 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 304 |
+
) -> List[int]:
|
| 305 |
+
"""
|
| 306 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
|
| 307 |
+
sequence pair mask has the following format:
|
| 308 |
+
|
| 309 |
+
```
|
| 310 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
| 311 |
+
| first sequence | second sequence |
|
| 312 |
+
```
|
| 313 |
+
|
| 314 |
+
If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
|
| 315 |
+
|
| 316 |
+
Args:
|
| 317 |
+
token_ids_0 (`List[int]`):
|
| 318 |
+
List of IDs.
|
| 319 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 320 |
+
Optional second list of IDs for sequence pairs.
|
| 321 |
+
|
| 322 |
+
Returns:
|
| 323 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
| 324 |
+
"""
|
| 325 |
+
sep = [self.sep_token_id]
|
| 326 |
+
cls = [self.cls_token_id]
|
| 327 |
+
|
| 328 |
+
if token_ids_1 is None:
|
| 329 |
+
return len(cls + token_ids_0 + sep) * [0]
|
| 330 |
+
return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
|
| 331 |
+
|
| 332 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 333 |
+
if not os.path.isdir(save_directory):
|
| 334 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 335 |
+
return
|
| 336 |
+
out_vocab_file = os.path.join(
|
| 337 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
| 341 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 342 |
+
elif not os.path.isfile(self.vocab_file):
|
| 343 |
+
with open(out_vocab_file, "wb") as fi:
|
| 344 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
| 345 |
+
fi.write(content_spiece_model)
|
| 346 |
+
|
| 347 |
+
return (out_vocab_file,)
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
__all__ = ["AlbertTokenizer"]
|
lib/python3.12/site-packages/transformers/models/albert/tokenization_albert_fast.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and the HuggingFace Inc. team.
|
| 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 |
+
"""Tokenization classes for ALBERT model."""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
from shutil import copyfile
|
| 19 |
+
from typing import List, Optional, Tuple
|
| 20 |
+
|
| 21 |
+
from ...tokenization_utils import AddedToken
|
| 22 |
+
from ...tokenization_utils_fast import PreTrainedTokenizerFast
|
| 23 |
+
from ...utils import is_sentencepiece_available, logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if is_sentencepiece_available():
|
| 27 |
+
from .tokenization_albert import AlbertTokenizer
|
| 28 |
+
else:
|
| 29 |
+
AlbertTokenizer = None
|
| 30 |
+
|
| 31 |
+
logger = logging.get_logger(__name__)
|
| 32 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
SPIECE_UNDERLINE = "▁"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class AlbertTokenizerFast(PreTrainedTokenizerFast):
|
| 39 |
+
"""
|
| 40 |
+
Construct a "fast" ALBERT tokenizer (backed by HuggingFace's *tokenizers* library). Based on
|
| 41 |
+
[Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models). This
|
| 42 |
+
tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should refer to
|
| 43 |
+
this superclass for more information regarding those methods
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
vocab_file (`str`):
|
| 47 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
| 48 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 49 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 50 |
+
Whether or not to lowercase the input when tokenizing.
|
| 51 |
+
remove_space (`bool`, *optional*, defaults to `True`):
|
| 52 |
+
Whether or not to strip the text when tokenizing (removing excess spaces before and after the string).
|
| 53 |
+
keep_accents (`bool`, *optional*, defaults to `False`):
|
| 54 |
+
Whether or not to keep accents when tokenizing.
|
| 55 |
+
bos_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 56 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
| 57 |
+
|
| 58 |
+
<Tip>
|
| 59 |
+
|
| 60 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 61 |
+
sequence. The token used is the `cls_token`.
|
| 62 |
+
|
| 63 |
+
</Tip>
|
| 64 |
+
|
| 65 |
+
eos_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 66 |
+
The end of sequence token. .. note:: When building a sequence using special tokens, this is not the token
|
| 67 |
+
that is used for the end of sequence. The token used is the `sep_token`.
|
| 68 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 69 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 70 |
+
token instead.
|
| 71 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 72 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 73 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 74 |
+
token of a sequence built with special tokens.
|
| 75 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 76 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 77 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 78 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 79 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 80 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 81 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 82 |
+
modeling. This is the token which the model will try to predict.
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 86 |
+
slow_tokenizer_class = AlbertTokenizer
|
| 87 |
+
|
| 88 |
+
def __init__(
|
| 89 |
+
self,
|
| 90 |
+
vocab_file=None,
|
| 91 |
+
tokenizer_file=None,
|
| 92 |
+
do_lower_case=True,
|
| 93 |
+
remove_space=True,
|
| 94 |
+
keep_accents=False,
|
| 95 |
+
bos_token="[CLS]",
|
| 96 |
+
eos_token="[SEP]",
|
| 97 |
+
unk_token="<unk>",
|
| 98 |
+
sep_token="[SEP]",
|
| 99 |
+
pad_token="<pad>",
|
| 100 |
+
cls_token="[CLS]",
|
| 101 |
+
mask_token="[MASK]",
|
| 102 |
+
**kwargs,
|
| 103 |
+
):
|
| 104 |
+
# Mask token behave like a normal word, i.e. include the space before it and
|
| 105 |
+
# is included in the raw text, there should be a match in a non-normalized sentence.
|
| 106 |
+
mask_token = (
|
| 107 |
+
AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False)
|
| 108 |
+
if isinstance(mask_token, str)
|
| 109 |
+
else mask_token
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
super().__init__(
|
| 113 |
+
vocab_file,
|
| 114 |
+
tokenizer_file=tokenizer_file,
|
| 115 |
+
do_lower_case=do_lower_case,
|
| 116 |
+
remove_space=remove_space,
|
| 117 |
+
keep_accents=keep_accents,
|
| 118 |
+
bos_token=bos_token,
|
| 119 |
+
eos_token=eos_token,
|
| 120 |
+
unk_token=unk_token,
|
| 121 |
+
sep_token=sep_token,
|
| 122 |
+
pad_token=pad_token,
|
| 123 |
+
cls_token=cls_token,
|
| 124 |
+
mask_token=mask_token,
|
| 125 |
+
**kwargs,
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
self.do_lower_case = do_lower_case
|
| 129 |
+
self.remove_space = remove_space
|
| 130 |
+
self.keep_accents = keep_accents
|
| 131 |
+
self.vocab_file = vocab_file
|
| 132 |
+
|
| 133 |
+
@property
|
| 134 |
+
def can_save_slow_tokenizer(self) -> bool:
|
| 135 |
+
return os.path.isfile(self.vocab_file) if self.vocab_file else False
|
| 136 |
+
|
| 137 |
+
def build_inputs_with_special_tokens(
|
| 138 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 139 |
+
) -> List[int]:
|
| 140 |
+
"""
|
| 141 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 142 |
+
adding special tokens. An ALBERT sequence has the following format:
|
| 143 |
+
|
| 144 |
+
- single sequence: `[CLS] X [SEP]`
|
| 145 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 146 |
+
|
| 147 |
+
Args:
|
| 148 |
+
token_ids_0 (`List[int]`):
|
| 149 |
+
List of IDs to which the special tokens will be added
|
| 150 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 151 |
+
Optional second list of IDs for sequence pairs.
|
| 152 |
+
|
| 153 |
+
Returns:
|
| 154 |
+
`List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 155 |
+
"""
|
| 156 |
+
sep = [self.sep_token_id]
|
| 157 |
+
cls = [self.cls_token_id]
|
| 158 |
+
if token_ids_1 is None:
|
| 159 |
+
return cls + token_ids_0 + sep
|
| 160 |
+
return cls + token_ids_0 + sep + token_ids_1 + sep
|
| 161 |
+
|
| 162 |
+
def create_token_type_ids_from_sequences(
|
| 163 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 164 |
+
) -> List[int]:
|
| 165 |
+
"""
|
| 166 |
+
Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
|
| 167 |
+
sequence pair mask has the following format:
|
| 168 |
+
|
| 169 |
+
```
|
| 170 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
| 171 |
+
| first sequence | second sequence |
|
| 172 |
+
```
|
| 173 |
+
|
| 174 |
+
if token_ids_1 is None, only returns the first portion of the mask (0s).
|
| 175 |
+
|
| 176 |
+
Args:
|
| 177 |
+
token_ids_0 (`List[int]`):
|
| 178 |
+
List of ids.
|
| 179 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 180 |
+
Optional second list of IDs for sequence pairs.
|
| 181 |
+
|
| 182 |
+
Returns:
|
| 183 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
| 184 |
+
"""
|
| 185 |
+
sep = [self.sep_token_id]
|
| 186 |
+
cls = [self.cls_token_id]
|
| 187 |
+
|
| 188 |
+
if token_ids_1 is None:
|
| 189 |
+
return len(cls + token_ids_0 + sep) * [0]
|
| 190 |
+
return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
|
| 191 |
+
|
| 192 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 193 |
+
if not self.can_save_slow_tokenizer:
|
| 194 |
+
raise ValueError(
|
| 195 |
+
"Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
|
| 196 |
+
"tokenizer."
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
if not os.path.isdir(save_directory):
|
| 200 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 201 |
+
return
|
| 202 |
+
out_vocab_file = os.path.join(
|
| 203 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
|
| 207 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 208 |
+
|
| 209 |
+
return (out_vocab_file,)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
__all__ = ["AlbertTokenizerFast"]
|
lib/python3.12/site-packages/transformers/models/bertweet/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .tokenization_bertweet import *
|
| 22 |
+
else:
|
| 23 |
+
import sys
|
| 24 |
+
|
| 25 |
+
_file = globals()["__file__"]
|
| 26 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.12/site-packages/transformers/models/bertweet/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (640 Bytes). View file
|
|
|
lib/python3.12/site-packages/transformers/models/bertweet/__pycache__/tokenization_bertweet.cpython-312.pyc
ADDED
|
Binary file (28.3 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/bertweet/tokenization_bertweet.py
ADDED
|
@@ -0,0 +1,769 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright (c) 2020, VinAI Research and the HuggingFace Inc. team.
|
| 3 |
+
# Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""Tokenization classes for BERTweet"""
|
| 17 |
+
|
| 18 |
+
import html
|
| 19 |
+
import os
|
| 20 |
+
import re
|
| 21 |
+
from shutil import copyfile
|
| 22 |
+
from typing import List, Optional, Tuple
|
| 23 |
+
|
| 24 |
+
import regex
|
| 25 |
+
|
| 26 |
+
from ...tokenization_utils import PreTrainedTokenizer
|
| 27 |
+
from ...utils import logging
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
VOCAB_FILES_NAMES = {
|
| 33 |
+
"vocab_file": "vocab.txt",
|
| 34 |
+
"merges_file": "bpe.codes",
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def get_pairs(word):
|
| 39 |
+
"""
|
| 40 |
+
Return set of symbol pairs in a word.
|
| 41 |
+
|
| 42 |
+
Word is represented as tuple of symbols (symbols being variable-length strings).
|
| 43 |
+
"""
|
| 44 |
+
pairs = set()
|
| 45 |
+
prev_char = word[0]
|
| 46 |
+
for char in word[1:]:
|
| 47 |
+
pairs.add((prev_char, char))
|
| 48 |
+
prev_char = char
|
| 49 |
+
|
| 50 |
+
pairs = set(pairs)
|
| 51 |
+
return pairs
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class BertweetTokenizer(PreTrainedTokenizer):
|
| 55 |
+
"""
|
| 56 |
+
Constructs a BERTweet tokenizer, using Byte-Pair-Encoding.
|
| 57 |
+
|
| 58 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 59 |
+
this superclass for more information regarding those methods.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
vocab_file (`str`):
|
| 63 |
+
Path to the vocabulary file.
|
| 64 |
+
merges_file (`str`):
|
| 65 |
+
Path to the merges file.
|
| 66 |
+
normalization (`bool`, *optional*, defaults to `False`):
|
| 67 |
+
Whether or not to apply a normalization preprocess.
|
| 68 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 69 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
| 70 |
+
|
| 71 |
+
<Tip>
|
| 72 |
+
|
| 73 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 74 |
+
sequence. The token used is the `cls_token`.
|
| 75 |
+
|
| 76 |
+
</Tip>
|
| 77 |
+
|
| 78 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 79 |
+
The end of sequence token.
|
| 80 |
+
|
| 81 |
+
<Tip>
|
| 82 |
+
|
| 83 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
| 84 |
+
The token used is the `sep_token`.
|
| 85 |
+
|
| 86 |
+
</Tip>
|
| 87 |
+
|
| 88 |
+
sep_token (`str`, *optional*, defaults to `"</s>"`):
|
| 89 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 90 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 91 |
+
token of a sequence built with special tokens.
|
| 92 |
+
cls_token (`str`, *optional*, defaults to `"<s>"`):
|
| 93 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 94 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 95 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 96 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 97 |
+
token instead.
|
| 98 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 99 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 100 |
+
mask_token (`str`, *optional*, defaults to `"<mask>"`):
|
| 101 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 102 |
+
modeling. This is the token which the model will try to predict.
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 106 |
+
|
| 107 |
+
def __init__(
|
| 108 |
+
self,
|
| 109 |
+
vocab_file,
|
| 110 |
+
merges_file,
|
| 111 |
+
normalization=False,
|
| 112 |
+
bos_token="<s>",
|
| 113 |
+
eos_token="</s>",
|
| 114 |
+
sep_token="</s>",
|
| 115 |
+
cls_token="<s>",
|
| 116 |
+
unk_token="<unk>",
|
| 117 |
+
pad_token="<pad>",
|
| 118 |
+
mask_token="<mask>",
|
| 119 |
+
**kwargs,
|
| 120 |
+
):
|
| 121 |
+
try:
|
| 122 |
+
from emoji import demojize
|
| 123 |
+
|
| 124 |
+
self.demojizer = demojize
|
| 125 |
+
except ImportError:
|
| 126 |
+
logger.warning(
|
| 127 |
+
"emoji is not installed, thus not converting emoticons or emojis into text. Install emoji: pip3"
|
| 128 |
+
" install emoji==0.6.0"
|
| 129 |
+
)
|
| 130 |
+
self.demojizer = None
|
| 131 |
+
|
| 132 |
+
self.vocab_file = vocab_file
|
| 133 |
+
self.merges_file = merges_file
|
| 134 |
+
|
| 135 |
+
self.encoder = {}
|
| 136 |
+
self.encoder[str(bos_token)] = 0
|
| 137 |
+
self.encoder[str(pad_token)] = 1
|
| 138 |
+
self.encoder[str(eos_token)] = 2
|
| 139 |
+
self.encoder[str(unk_token)] = 3
|
| 140 |
+
|
| 141 |
+
self.add_from_file(vocab_file)
|
| 142 |
+
|
| 143 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
| 144 |
+
|
| 145 |
+
with open(merges_file, encoding="utf-8") as merges_handle:
|
| 146 |
+
merges = merges_handle.read().split("\n")[:-1]
|
| 147 |
+
merges = [tuple(merge.split()[:-1]) for merge in merges]
|
| 148 |
+
self.bpe_ranks = dict(zip(merges, range(len(merges))))
|
| 149 |
+
self.cache = {}
|
| 150 |
+
|
| 151 |
+
self.normalization = normalization
|
| 152 |
+
self.tweetPreprocessor = TweetTokenizer()
|
| 153 |
+
self.special_puncts = {"’": "'", "…": "..."}
|
| 154 |
+
|
| 155 |
+
super().__init__(
|
| 156 |
+
normalization=normalization,
|
| 157 |
+
bos_token=bos_token,
|
| 158 |
+
eos_token=eos_token,
|
| 159 |
+
sep_token=sep_token,
|
| 160 |
+
cls_token=cls_token,
|
| 161 |
+
unk_token=unk_token,
|
| 162 |
+
pad_token=pad_token,
|
| 163 |
+
mask_token=mask_token,
|
| 164 |
+
**kwargs,
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
def build_inputs_with_special_tokens(
|
| 168 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 169 |
+
) -> List[int]:
|
| 170 |
+
"""
|
| 171 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 172 |
+
adding special tokens. A BERTweet sequence has the following format:
|
| 173 |
+
|
| 174 |
+
- single sequence: `<s> X </s>`
|
| 175 |
+
- pair of sequences: `<s> A </s></s> B </s>`
|
| 176 |
+
|
| 177 |
+
Args:
|
| 178 |
+
token_ids_0 (`List[int]`):
|
| 179 |
+
List of IDs to which the special tokens will be added.
|
| 180 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 181 |
+
Optional second list of IDs for sequence pairs.
|
| 182 |
+
|
| 183 |
+
Returns:
|
| 184 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 185 |
+
"""
|
| 186 |
+
|
| 187 |
+
if token_ids_1 is None:
|
| 188 |
+
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
| 189 |
+
cls = [self.cls_token_id]
|
| 190 |
+
sep = [self.sep_token_id]
|
| 191 |
+
return cls + token_ids_0 + sep + sep + token_ids_1 + sep
|
| 192 |
+
|
| 193 |
+
def get_special_tokens_mask(
|
| 194 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
| 195 |
+
) -> List[int]:
|
| 196 |
+
"""
|
| 197 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 198 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 199 |
+
|
| 200 |
+
Args:
|
| 201 |
+
token_ids_0 (`List[int]`):
|
| 202 |
+
List of IDs.
|
| 203 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 204 |
+
Optional second list of IDs for sequence pairs.
|
| 205 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 206 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 207 |
+
|
| 208 |
+
Returns:
|
| 209 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 210 |
+
"""
|
| 211 |
+
|
| 212 |
+
if already_has_special_tokens:
|
| 213 |
+
return super().get_special_tokens_mask(
|
| 214 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
if token_ids_1 is None:
|
| 218 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
| 219 |
+
return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
|
| 220 |
+
|
| 221 |
+
def create_token_type_ids_from_sequences(
|
| 222 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 223 |
+
) -> List[int]:
|
| 224 |
+
"""
|
| 225 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. BERTweet does
|
| 226 |
+
not make use of token type ids, therefore a list of zeros is returned.
|
| 227 |
+
|
| 228 |
+
Args:
|
| 229 |
+
token_ids_0 (`List[int]`):
|
| 230 |
+
List of IDs.
|
| 231 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 232 |
+
Optional second list of IDs for sequence pairs.
|
| 233 |
+
|
| 234 |
+
Returns:
|
| 235 |
+
`List[int]`: List of zeros.
|
| 236 |
+
"""
|
| 237 |
+
|
| 238 |
+
sep = [self.sep_token_id]
|
| 239 |
+
cls = [self.cls_token_id]
|
| 240 |
+
|
| 241 |
+
if token_ids_1 is None:
|
| 242 |
+
return len(cls + token_ids_0 + sep) * [0]
|
| 243 |
+
return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
|
| 244 |
+
|
| 245 |
+
@property
|
| 246 |
+
def vocab_size(self):
|
| 247 |
+
return len(self.encoder)
|
| 248 |
+
|
| 249 |
+
def get_vocab(self):
|
| 250 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
| 251 |
+
|
| 252 |
+
def bpe(self, token):
|
| 253 |
+
if token in self.cache:
|
| 254 |
+
return self.cache[token]
|
| 255 |
+
word = tuple(token)
|
| 256 |
+
word = tuple(list(word[:-1]) + [word[-1] + "</w>"])
|
| 257 |
+
pairs = get_pairs(word)
|
| 258 |
+
|
| 259 |
+
if not pairs:
|
| 260 |
+
return token
|
| 261 |
+
|
| 262 |
+
while True:
|
| 263 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
| 264 |
+
if bigram not in self.bpe_ranks:
|
| 265 |
+
break
|
| 266 |
+
first, second = bigram
|
| 267 |
+
new_word = []
|
| 268 |
+
i = 0
|
| 269 |
+
while i < len(word):
|
| 270 |
+
try:
|
| 271 |
+
j = word.index(first, i)
|
| 272 |
+
except ValueError:
|
| 273 |
+
new_word.extend(word[i:])
|
| 274 |
+
break
|
| 275 |
+
else:
|
| 276 |
+
new_word.extend(word[i:j])
|
| 277 |
+
i = j
|
| 278 |
+
|
| 279 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
| 280 |
+
new_word.append(first + second)
|
| 281 |
+
i += 2
|
| 282 |
+
else:
|
| 283 |
+
new_word.append(word[i])
|
| 284 |
+
i += 1
|
| 285 |
+
new_word = tuple(new_word)
|
| 286 |
+
word = new_word
|
| 287 |
+
if len(word) == 1:
|
| 288 |
+
break
|
| 289 |
+
else:
|
| 290 |
+
pairs = get_pairs(word)
|
| 291 |
+
word = "@@ ".join(word)
|
| 292 |
+
word = word[:-4]
|
| 293 |
+
self.cache[token] = word
|
| 294 |
+
return word
|
| 295 |
+
|
| 296 |
+
def _tokenize(self, text):
|
| 297 |
+
"""Tokenize a string."""
|
| 298 |
+
if self.normalization: # Perform Tweet normalization before performing BPE
|
| 299 |
+
text = self.normalizeTweet(text)
|
| 300 |
+
|
| 301 |
+
split_tokens = []
|
| 302 |
+
words = re.findall(r"\S+\n?", text)
|
| 303 |
+
for token in words:
|
| 304 |
+
split_tokens.extend(list(self.bpe(token).split(" ")))
|
| 305 |
+
return split_tokens
|
| 306 |
+
|
| 307 |
+
def normalizeTweet(self, tweet):
|
| 308 |
+
"""
|
| 309 |
+
Normalize a raw Tweet
|
| 310 |
+
"""
|
| 311 |
+
for punct in self.special_puncts:
|
| 312 |
+
tweet = tweet.replace(punct, self.special_puncts[punct])
|
| 313 |
+
|
| 314 |
+
tokens = self.tweetPreprocessor.tokenize(tweet)
|
| 315 |
+
normTweet = " ".join([self.normalizeToken(token) for token in tokens])
|
| 316 |
+
|
| 317 |
+
normTweet = (
|
| 318 |
+
normTweet.replace("cannot ", "can not ")
|
| 319 |
+
.replace("n't ", " n't ")
|
| 320 |
+
.replace("n 't ", " n't ")
|
| 321 |
+
.replace("ca n't", "can't")
|
| 322 |
+
.replace("ai n't", "ain't")
|
| 323 |
+
)
|
| 324 |
+
normTweet = (
|
| 325 |
+
normTweet.replace("'m ", " 'm ")
|
| 326 |
+
.replace("'re ", " 're ")
|
| 327 |
+
.replace("'s ", " 's ")
|
| 328 |
+
.replace("'ll ", " 'll ")
|
| 329 |
+
.replace("'d ", " 'd ")
|
| 330 |
+
.replace("'ve ", " 've ")
|
| 331 |
+
)
|
| 332 |
+
normTweet = (
|
| 333 |
+
normTweet.replace(" p . m .", " p.m.")
|
| 334 |
+
.replace(" p . m ", " p.m ")
|
| 335 |
+
.replace(" a . m .", " a.m.")
|
| 336 |
+
.replace(" a . m ", " a.m ")
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
return " ".join(normTweet.split())
|
| 340 |
+
|
| 341 |
+
def normalizeToken(self, token):
|
| 342 |
+
"""
|
| 343 |
+
Normalize tokens in a Tweet
|
| 344 |
+
"""
|
| 345 |
+
lowercased_token = token.lower()
|
| 346 |
+
if token.startswith("@"):
|
| 347 |
+
return "@USER"
|
| 348 |
+
elif lowercased_token.startswith("http") or lowercased_token.startswith("www"):
|
| 349 |
+
return "HTTPURL"
|
| 350 |
+
elif len(token) == 1:
|
| 351 |
+
if token in self.special_puncts:
|
| 352 |
+
return self.special_puncts[token]
|
| 353 |
+
if self.demojizer is not None:
|
| 354 |
+
return self.demojizer(token)
|
| 355 |
+
else:
|
| 356 |
+
return token
|
| 357 |
+
else:
|
| 358 |
+
return token
|
| 359 |
+
|
| 360 |
+
def _convert_token_to_id(self, token):
|
| 361 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 362 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
| 363 |
+
|
| 364 |
+
def _convert_id_to_token(self, index):
|
| 365 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 366 |
+
return self.decoder.get(index, self.unk_token)
|
| 367 |
+
|
| 368 |
+
def convert_tokens_to_string(self, tokens):
|
| 369 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 370 |
+
out_string = " ".join(tokens).replace("@@ ", "").strip()
|
| 371 |
+
return out_string
|
| 372 |
+
|
| 373 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 374 |
+
if not os.path.isdir(save_directory):
|
| 375 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 376 |
+
return
|
| 377 |
+
out_vocab_file = os.path.join(
|
| 378 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 379 |
+
)
|
| 380 |
+
out_merge_file = os.path.join(
|
| 381 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
| 385 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 386 |
+
elif not os.path.isfile(self.vocab_file):
|
| 387 |
+
with open(out_vocab_file, "wb") as fi:
|
| 388 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
| 389 |
+
fi.write(content_spiece_model)
|
| 390 |
+
|
| 391 |
+
if os.path.abspath(self.merges_file) != os.path.abspath(out_merge_file):
|
| 392 |
+
copyfile(self.merges_file, out_merge_file)
|
| 393 |
+
|
| 394 |
+
return out_vocab_file, out_merge_file
|
| 395 |
+
|
| 396 |
+
# def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
|
| 397 |
+
# filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))
|
| 398 |
+
# tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)
|
| 399 |
+
# tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)
|
| 400 |
+
# return ''.join(tokens_generated_so_far)
|
| 401 |
+
|
| 402 |
+
def add_from_file(self, f):
|
| 403 |
+
"""
|
| 404 |
+
Loads a pre-existing dictionary from a text file and adds its symbols to this instance.
|
| 405 |
+
"""
|
| 406 |
+
if isinstance(f, str):
|
| 407 |
+
try:
|
| 408 |
+
with open(f, "r", encoding="utf-8") as fd:
|
| 409 |
+
self.add_from_file(fd)
|
| 410 |
+
except FileNotFoundError as fnfe:
|
| 411 |
+
raise fnfe
|
| 412 |
+
except UnicodeError:
|
| 413 |
+
raise Exception(f"Incorrect encoding detected in {f}, please rebuild the dataset")
|
| 414 |
+
return
|
| 415 |
+
|
| 416 |
+
lines = f.readlines()
|
| 417 |
+
for lineTmp in lines:
|
| 418 |
+
line = lineTmp.strip()
|
| 419 |
+
idx = line.rfind(" ")
|
| 420 |
+
if idx == -1:
|
| 421 |
+
raise ValueError("Incorrect dictionary format, expected '<token> <cnt>'")
|
| 422 |
+
word = line[:idx]
|
| 423 |
+
self.encoder[word] = len(self.encoder)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
# Natural Language Toolkit: Twitter Tokenizer
|
| 427 |
+
#
|
| 428 |
+
# Copyright (C) 2001-2020 NLTK Project
|
| 429 |
+
# Author: Christopher Potts <cgpotts@stanford.edu>
|
| 430 |
+
# Ewan Klein <ewan@inf.ed.ac.uk> (modifications)
|
| 431 |
+
# Pierpaolo Pantone <> (modifications)
|
| 432 |
+
# URL: http://nltk.org/
|
| 433 |
+
# For license information, see LICENSE.TXT
|
| 434 |
+
#
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
"""
|
| 438 |
+
Twitter-aware tokenizer, designed to be flexible and easy to adapt to new domains and tasks. The basic logic is this:
|
| 439 |
+
|
| 440 |
+
1. The tuple regex_strings defines a list of regular expression strings.
|
| 441 |
+
|
| 442 |
+
2. The regex_strings strings are put, in order, into a compiled regular expression object called word_re.
|
| 443 |
+
|
| 444 |
+
3. The tokenization is done by word_re.findall(s), where s is the user-supplied string, inside the tokenize() method of
|
| 445 |
+
the class Tokenizer.
|
| 446 |
+
|
| 447 |
+
4. When instantiating Tokenizer objects, there is a single option: preserve_case. By default, it is set to True. If it
|
| 448 |
+
is set to False, then the tokenizer will lowercase everything except for emoticons.
|
| 449 |
+
|
| 450 |
+
"""
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
######################################################################
|
| 454 |
+
#
|
| 455 |
+
# import regex # https://github.com/nltk/nltk/issues/2409
|
| 456 |
+
# import html
|
| 457 |
+
#
|
| 458 |
+
######################################################################
|
| 459 |
+
# The following strings are components in the regular expression
|
| 460 |
+
# that is used for tokenizing. It's important that phone_number
|
| 461 |
+
# appears first in the final regex (since it can contain whitespace).
|
| 462 |
+
# It also could matter that tags comes after emoticons, due to the
|
| 463 |
+
# possibility of having text like
|
| 464 |
+
#
|
| 465 |
+
# <:| and some text >:)
|
| 466 |
+
#
|
| 467 |
+
# Most importantly, the final element should always be last, since it
|
| 468 |
+
# does a last ditch whitespace-based tokenization of whatever is left.
|
| 469 |
+
|
| 470 |
+
# ToDo: Update with http://en.wikipedia.org/wiki/List_of_emoticons ?
|
| 471 |
+
|
| 472 |
+
# This particular element is used in a couple ways, so we define it
|
| 473 |
+
# with a name:
|
| 474 |
+
# docstyle-ignore
|
| 475 |
+
EMOTICONS = r"""
|
| 476 |
+
(?:
|
| 477 |
+
[<>]?
|
| 478 |
+
[:;=8] # eyes
|
| 479 |
+
[\-o\*\']? # optional nose
|
| 480 |
+
[\)\]\(\[dDpP/\:\}\{@\|\\] # mouth
|
| 481 |
+
|
|
| 482 |
+
[\)\]\(\[dDpP/\:\}\{@\|\\] # mouth
|
| 483 |
+
[\-o\*\']? # optional nose
|
| 484 |
+
[:;=8] # eyes
|
| 485 |
+
[<>]?
|
| 486 |
+
|
|
| 487 |
+
<3 # heart
|
| 488 |
+
)"""
|
| 489 |
+
|
| 490 |
+
# URL pattern due to John Gruber, modified by Tom Winzig. See
|
| 491 |
+
# https://gist.github.com/winzig/8894715
|
| 492 |
+
# docstyle-ignore
|
| 493 |
+
URLS = r""" # Capture 1: entire matched URL
|
| 494 |
+
(?:
|
| 495 |
+
https?: # URL protocol and colon
|
| 496 |
+
(?:
|
| 497 |
+
/{1,3} # 1-3 slashes
|
| 498 |
+
| # or
|
| 499 |
+
[a-z0-9%] # Single letter or digit or '%'
|
| 500 |
+
# (Trying not to match e.g. "URI::Escape")
|
| 501 |
+
)
|
| 502 |
+
| # or
|
| 503 |
+
# looks like domain name followed by a slash:
|
| 504 |
+
[a-z0-9.\-]+[.]
|
| 505 |
+
(?:[a-z]{2,13})
|
| 506 |
+
/
|
| 507 |
+
)
|
| 508 |
+
(?: # One or more:
|
| 509 |
+
[^\s()<>{}\[\]]+ # Run of non-space, non-()<>{}[]
|
| 510 |
+
| # or
|
| 511 |
+
\([^\s()]*?\([^\s()]+\)[^\s()]*?\) # balanced parens, one level deep: (...(...)...)
|
| 512 |
+
|
|
| 513 |
+
\([^\s]+?\) # balanced parens, non-recursive: (...)
|
| 514 |
+
)+
|
| 515 |
+
(?: # End with:
|
| 516 |
+
\([^\s()]*?\([^\s()]+\)[^\s()]*?\) # balanced parens, one level deep: (...(...)...)
|
| 517 |
+
|
|
| 518 |
+
\([^\s]+?\) # balanced parens, non-recursive: (...)
|
| 519 |
+
| # or
|
| 520 |
+
[^\s`!()\[\]{};:'".,<>?«»“”‘’] # not a space or one of these punct chars
|
| 521 |
+
)
|
| 522 |
+
| # OR, the following to match naked domains:
|
| 523 |
+
(?:
|
| 524 |
+
(?<!@) # not preceded by a @, avoid matching foo@_gmail.com_
|
| 525 |
+
[a-z0-9]+
|
| 526 |
+
(?:[.\-][a-z0-9]+)*
|
| 527 |
+
[.]
|
| 528 |
+
(?:[a-z]{2,13})
|
| 529 |
+
\b
|
| 530 |
+
/?
|
| 531 |
+
(?!@) # not succeeded by a @,
|
| 532 |
+
# avoid matching "foo.na" in "foo.na@example.com"
|
| 533 |
+
)
|
| 534 |
+
"""
|
| 535 |
+
|
| 536 |
+
# docstyle-ignore
|
| 537 |
+
# The components of the tokenizer:
|
| 538 |
+
REGEXPS = (
|
| 539 |
+
URLS,
|
| 540 |
+
# Phone numbers:
|
| 541 |
+
r"""
|
| 542 |
+
(?:
|
| 543 |
+
(?: # (international)
|
| 544 |
+
\+?[01]
|
| 545 |
+
[ *\-.\)]*
|
| 546 |
+
)?
|
| 547 |
+
(?: # (area code)
|
| 548 |
+
[\(]?
|
| 549 |
+
\d{3}
|
| 550 |
+
[ *\-.\)]*
|
| 551 |
+
)?
|
| 552 |
+
\d{3} # exchange
|
| 553 |
+
[ *\-.\)]*
|
| 554 |
+
\d{4} # base
|
| 555 |
+
)""",
|
| 556 |
+
# ASCII Emoticons
|
| 557 |
+
EMOTICONS,
|
| 558 |
+
# HTML tags:
|
| 559 |
+
r"""<[^>\s]+>""",
|
| 560 |
+
# ASCII Arrows
|
| 561 |
+
r"""[\-]+>|<[\-]+""",
|
| 562 |
+
# Twitter username:
|
| 563 |
+
r"""(?:@[\w_]+)""",
|
| 564 |
+
# Twitter hashtags:
|
| 565 |
+
r"""(?:\#+[\w_]+[\w\'_\-]*[\w_]+)""",
|
| 566 |
+
# email addresses
|
| 567 |
+
r"""[\w.+-]+@[\w-]+\.(?:[\w-]\.?)+[\w-]""",
|
| 568 |
+
# docstyle-ignore
|
| 569 |
+
# Remaining word types:
|
| 570 |
+
r"""
|
| 571 |
+
(?:[^\W\d_](?:[^\W\d_]|['\-_])+[^\W\d_]) # Words with apostrophes or dashes.
|
| 572 |
+
|
|
| 573 |
+
(?:[+\-]?\d+[,/.:-]\d+[+\-]?) # Numbers, including fractions, decimals.
|
| 574 |
+
|
|
| 575 |
+
(?:[\w_]+) # Words without apostrophes or dashes.
|
| 576 |
+
|
|
| 577 |
+
(?:\.(?:\s*\.){1,}) # Ellipsis dots.
|
| 578 |
+
|
|
| 579 |
+
(?:\S) # Everything else that isn't whitespace.
|
| 580 |
+
""",
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
######################################################################
|
| 584 |
+
# This is the core tokenizing regex:
|
| 585 |
+
|
| 586 |
+
WORD_RE = regex.compile(r"""(%s)""" % "|".join(REGEXPS), regex.VERBOSE | regex.I | regex.UNICODE)
|
| 587 |
+
|
| 588 |
+
# WORD_RE performs poorly on these patterns:
|
| 589 |
+
HANG_RE = regex.compile(r"([^a-zA-Z0-9])\1{3,}")
|
| 590 |
+
|
| 591 |
+
# The emoticon string gets its own regex so that we can preserve case for
|
| 592 |
+
# them as needed:
|
| 593 |
+
EMOTICON_RE = regex.compile(EMOTICONS, regex.VERBOSE | regex.I | regex.UNICODE)
|
| 594 |
+
|
| 595 |
+
# These are for regularizing HTML entities to Unicode:
|
| 596 |
+
ENT_RE = regex.compile(r"&(#?(x?))([^&;\s]+);")
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
######################################################################
|
| 600 |
+
# Functions for converting html entities
|
| 601 |
+
######################################################################
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def _str_to_unicode(text, encoding=None, errors="strict"):
|
| 605 |
+
if encoding is None:
|
| 606 |
+
encoding = "utf-8"
|
| 607 |
+
if isinstance(text, bytes):
|
| 608 |
+
return text.decode(encoding, errors)
|
| 609 |
+
return text
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
def _replace_html_entities(text, keep=(), remove_illegal=True, encoding="utf-8"):
|
| 613 |
+
"""
|
| 614 |
+
Remove entities from text by converting them to their corresponding unicode character.
|
| 615 |
+
|
| 616 |
+
Args:
|
| 617 |
+
text:
|
| 618 |
+
A unicode string or a byte string encoded in the given *encoding* (which defaults to 'utf-8').
|
| 619 |
+
keep (list):
|
| 620 |
+
List of entity names which should not be replaced. This supports both numeric entities (`&#nnnn;` and
|
| 621 |
+
`&#hhhh;`) and named entities (such as ` ` or `>`).
|
| 622 |
+
remove_illegal (bool):
|
| 623 |
+
If `True`, entities that can't be converted are removed. Otherwise, entities that can't be converted are
|
| 624 |
+
kept "as is".
|
| 625 |
+
|
| 626 |
+
Returns: A unicode string with the entities removed.
|
| 627 |
+
|
| 628 |
+
See https://github.com/scrapy/w3lib/blob/master/w3lib/html.py
|
| 629 |
+
|
| 630 |
+
Examples:
|
| 631 |
+
|
| 632 |
+
```python
|
| 633 |
+
>>> from nltk.tokenize.casual import _replace_html_entities
|
| 634 |
+
|
| 635 |
+
>>> _replace_html_entities(b"Price: £100")
|
| 636 |
+
'Price: \\xa3100'
|
| 637 |
+
|
| 638 |
+
>>> print(_replace_html_entities(b"Price: £100"))
|
| 639 |
+
Price: £100
|
| 640 |
+
```"""
|
| 641 |
+
|
| 642 |
+
def _convert_entity(match):
|
| 643 |
+
entity_body = match.group(3)
|
| 644 |
+
if match.group(1):
|
| 645 |
+
try:
|
| 646 |
+
if match.group(2):
|
| 647 |
+
number = int(entity_body, 16)
|
| 648 |
+
else:
|
| 649 |
+
number = int(entity_body, 10)
|
| 650 |
+
# Numeric character references in the 80-9F range are typically
|
| 651 |
+
# interpreted by browsers as representing the characters mapped
|
| 652 |
+
# to bytes 80-9F in the Windows-1252 encoding. For more info
|
| 653 |
+
# see: https://en.wikipedia.org/wiki/ISO/IEC_8859-1#Similar_character_sets
|
| 654 |
+
if 0x80 <= number <= 0x9F:
|
| 655 |
+
return bytes((number,)).decode("cp1252")
|
| 656 |
+
except ValueError:
|
| 657 |
+
number = None
|
| 658 |
+
else:
|
| 659 |
+
if entity_body in keep:
|
| 660 |
+
return match.group(0)
|
| 661 |
+
else:
|
| 662 |
+
number = html.entities.name2codepoint.get(entity_body)
|
| 663 |
+
if number is not None:
|
| 664 |
+
try:
|
| 665 |
+
return chr(number)
|
| 666 |
+
except (ValueError, OverflowError):
|
| 667 |
+
pass
|
| 668 |
+
|
| 669 |
+
return "" if remove_illegal else match.group(0)
|
| 670 |
+
|
| 671 |
+
return ENT_RE.sub(_convert_entity, _str_to_unicode(text, encoding))
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
######################################################################
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
class TweetTokenizer:
|
| 678 |
+
r"""
|
| 679 |
+
Examples:
|
| 680 |
+
|
| 681 |
+
```python
|
| 682 |
+
>>> # Tokenizer for tweets.
|
| 683 |
+
>>> from nltk.tokenize import TweetTokenizer
|
| 684 |
+
|
| 685 |
+
>>> tknzr = TweetTokenizer()
|
| 686 |
+
>>> s0 = "This is a cooool #dummysmiley: :-) :-P <3 and some arrows < > -> <--"
|
| 687 |
+
>>> tknzr.tokenize(s0)
|
| 688 |
+
['This', 'is', 'a', 'cooool', '#dummysmiley', ':', ':-)', ':-P', '<3', 'and', 'some', 'arrows', '<', '>', '->', '<--']
|
| 689 |
+
|
| 690 |
+
>>> # Examples using *strip_handles* and *reduce_len parameters*:
|
| 691 |
+
>>> tknzr = TweetTokenizer(strip_handles=True, reduce_len=True)
|
| 692 |
+
>>> s1 = "@remy: This is waaaaayyyy too much for you!!!!!!"
|
| 693 |
+
>>> tknzr.tokenize(s1)
|
| 694 |
+
[':', 'This', 'is', 'waaayyy', 'too', 'much', 'for', 'you', '!', '!', '!']
|
| 695 |
+
```"""
|
| 696 |
+
|
| 697 |
+
def __init__(self, preserve_case=True, reduce_len=False, strip_handles=False):
|
| 698 |
+
self.preserve_case = preserve_case
|
| 699 |
+
self.reduce_len = reduce_len
|
| 700 |
+
self.strip_handles = strip_handles
|
| 701 |
+
|
| 702 |
+
def tokenize(self, text):
|
| 703 |
+
"""
|
| 704 |
+
Args:
|
| 705 |
+
text: str
|
| 706 |
+
|
| 707 |
+
Returns: list(str) A tokenized list of strings; concatenating this list returns the original string if
|
| 708 |
+
`preserve_case=False`
|
| 709 |
+
"""
|
| 710 |
+
# Fix HTML character entities:
|
| 711 |
+
text = _replace_html_entities(text)
|
| 712 |
+
# Remove username handles
|
| 713 |
+
if self.strip_handles:
|
| 714 |
+
text = remove_handles(text)
|
| 715 |
+
# Normalize word lengthening
|
| 716 |
+
if self.reduce_len:
|
| 717 |
+
text = reduce_lengthening(text)
|
| 718 |
+
# Shorten problematic sequences of characters
|
| 719 |
+
safe_text = HANG_RE.sub(r"\1\1\1", text)
|
| 720 |
+
# Tokenize:
|
| 721 |
+
words = WORD_RE.findall(safe_text)
|
| 722 |
+
# Possibly alter the case, but avoid changing emoticons like :D into :d:
|
| 723 |
+
if not self.preserve_case:
|
| 724 |
+
words = [x if EMOTICON_RE.search(x) else x.lower() for x in words]
|
| 725 |
+
return words
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
######################################################################
|
| 729 |
+
# Normalization Functions
|
| 730 |
+
######################################################################
|
| 731 |
+
|
| 732 |
+
|
| 733 |
+
def reduce_lengthening(text):
|
| 734 |
+
"""
|
| 735 |
+
Replace repeated character sequences of length 3 or greater with sequences of length 3.
|
| 736 |
+
"""
|
| 737 |
+
pattern = regex.compile(r"(.)\1{2,}")
|
| 738 |
+
return pattern.sub(r"\1\1\1", text)
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
def remove_handles(text):
|
| 742 |
+
"""
|
| 743 |
+
Remove Twitter username handles from text.
|
| 744 |
+
"""
|
| 745 |
+
pattern = regex.compile(
|
| 746 |
+
r"(?<![A-Za-z0-9_!@#\$%&*])@(([A-Za-z0-9_]){20}(?!@))|(?<![A-Za-z0-9_!@#\$%&*])@(([A-Za-z0-9_]){1,19})(?![A-Za-z0-9_]*@)"
|
| 747 |
+
)
|
| 748 |
+
# Substitute handles with ' ' to ensure that text on either side of removed handles are tokenized correctly
|
| 749 |
+
return pattern.sub(" ", text)
|
| 750 |
+
|
| 751 |
+
|
| 752 |
+
######################################################################
|
| 753 |
+
# Tokenization Function
|
| 754 |
+
######################################################################
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
def casual_tokenize(text, preserve_case=True, reduce_len=False, strip_handles=False):
|
| 758 |
+
"""
|
| 759 |
+
Convenience function for wrapping the tokenizer.
|
| 760 |
+
"""
|
| 761 |
+
return TweetTokenizer(preserve_case=preserve_case, reduce_len=reduce_len, strip_handles=strip_handles).tokenize(
|
| 762 |
+
text
|
| 763 |
+
)
|
| 764 |
+
|
| 765 |
+
|
| 766 |
+
###############################################################################
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
__all__ = ["BertweetTokenizer"]
|
lib/python3.12/site-packages/transformers/models/biogpt/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_biogpt import *
|
| 22 |
+
from .modeling_biogpt import *
|
| 23 |
+
from .tokenization_biogpt import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (701 Bytes). View file
|
|
|
lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/configuration_biogpt.cpython-312.pyc
ADDED
|
Binary file (5.77 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/modeling_biogpt.cpython-312.pyc
ADDED
|
Binary file (46.1 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/tokenization_biogpt.cpython-312.pyc
ADDED
|
Binary file (16.8 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/biogpt/configuration_biogpt.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Team and Microsoft Research AI4Science 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 |
+
"""BioGPT model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class BioGptConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`BioGptModel`]. It is used to instantiate an
|
| 27 |
+
BioGPT model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 28 |
+
with the defaults will yield a similar configuration to that of the BioGPT
|
| 29 |
+
[microsoft/biogpt](https://huggingface.co/microsoft/biogpt) architecture.
|
| 30 |
+
|
| 31 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 32 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
vocab_size (`int`, *optional*, defaults to 42384):
|
| 37 |
+
Vocabulary size of the BioGPT model. Defines the number of different tokens that can be represented by the
|
| 38 |
+
`inputs_ids` passed when calling [`BioGptModel`].
|
| 39 |
+
hidden_size (`int`, *optional*, defaults to 1024):
|
| 40 |
+
Dimension of the encoder layers and the pooler layer.
|
| 41 |
+
num_hidden_layers (`int`, *optional*, defaults to 24):
|
| 42 |
+
Number of hidden layers in the Transformer encoder.
|
| 43 |
+
num_attention_heads (`int`, *optional*, defaults to 16):
|
| 44 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 45 |
+
intermediate_size (`int`, *optional*, defaults to 4096):
|
| 46 |
+
Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 47 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 48 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 49 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 50 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 51 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 52 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 53 |
+
The dropout ratio for the attention probabilities.
|
| 54 |
+
max_position_embeddings (`int`, *optional*, defaults to 1024):
|
| 55 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 56 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 57 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 58 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 59 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 60 |
+
The epsilon used by the layer normalization layers.
|
| 61 |
+
scale_embedding (`bool`, *optional*, defaults to `True`):
|
| 62 |
+
Scale embeddings by diving by sqrt(d_model).
|
| 63 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 64 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 65 |
+
relevant if `config.is_decoder=True`.
|
| 66 |
+
layerdrop (`float`, *optional*, defaults to 0.0):
|
| 67 |
+
Please refer to the paper about LayerDrop: https://arxiv.org/abs/1909.11556 for further details
|
| 68 |
+
activation_dropout (`float`, *optional*, defaults to 0.0):
|
| 69 |
+
The dropout ratio for activations inside the fully connected layer.
|
| 70 |
+
pad_token_id (`int`, *optional*, defaults to 1):
|
| 71 |
+
Padding token id.
|
| 72 |
+
bos_token_id (`int`, *optional*, defaults to 0):
|
| 73 |
+
Beginning of stream token id.
|
| 74 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
| 75 |
+
End of stream token id.
|
| 76 |
+
|
| 77 |
+
Example:
|
| 78 |
+
|
| 79 |
+
```python
|
| 80 |
+
>>> from transformers import BioGptModel, BioGptConfig
|
| 81 |
+
|
| 82 |
+
>>> # Initializing a BioGPT microsoft/biogpt style configuration
|
| 83 |
+
>>> configuration = BioGptConfig()
|
| 84 |
+
|
| 85 |
+
>>> # Initializing a model from the microsoft/biogpt style configuration
|
| 86 |
+
>>> model = BioGptModel(configuration)
|
| 87 |
+
|
| 88 |
+
>>> # Accessing the model configuration
|
| 89 |
+
>>> configuration = model.config
|
| 90 |
+
```"""
|
| 91 |
+
|
| 92 |
+
model_type = "biogpt"
|
| 93 |
+
|
| 94 |
+
def __init__(
|
| 95 |
+
self,
|
| 96 |
+
vocab_size=42384,
|
| 97 |
+
hidden_size=1024,
|
| 98 |
+
num_hidden_layers=24,
|
| 99 |
+
num_attention_heads=16,
|
| 100 |
+
intermediate_size=4096,
|
| 101 |
+
hidden_act="gelu",
|
| 102 |
+
hidden_dropout_prob=0.1,
|
| 103 |
+
attention_probs_dropout_prob=0.1,
|
| 104 |
+
max_position_embeddings=1024,
|
| 105 |
+
initializer_range=0.02,
|
| 106 |
+
layer_norm_eps=1e-12,
|
| 107 |
+
scale_embedding=True,
|
| 108 |
+
use_cache=True,
|
| 109 |
+
layerdrop=0.0,
|
| 110 |
+
activation_dropout=0.0,
|
| 111 |
+
pad_token_id=1,
|
| 112 |
+
bos_token_id=0,
|
| 113 |
+
eos_token_id=2,
|
| 114 |
+
**kwargs,
|
| 115 |
+
):
|
| 116 |
+
self.vocab_size = vocab_size
|
| 117 |
+
self.max_position_embeddings = max_position_embeddings
|
| 118 |
+
self.hidden_size = hidden_size
|
| 119 |
+
self.num_hidden_layers = num_hidden_layers
|
| 120 |
+
self.num_attention_heads = num_attention_heads
|
| 121 |
+
self.intermediate_size = intermediate_size
|
| 122 |
+
self.hidden_act = hidden_act
|
| 123 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 124 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 125 |
+
self.initializer_range = initializer_range
|
| 126 |
+
self.layer_norm_eps = layer_norm_eps
|
| 127 |
+
self.scale_embedding = scale_embedding
|
| 128 |
+
self.use_cache = use_cache
|
| 129 |
+
self.layerdrop = layerdrop
|
| 130 |
+
self.activation_dropout = activation_dropout
|
| 131 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
__all__ = ["BioGptConfig"]
|
lib/python3.12/site-packages/transformers/models/biogpt/modeling_biogpt.py
ADDED
|
@@ -0,0 +1,1042 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Team and Microsoft Research AI4Science 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 |
+
"""PyTorch BioGPT model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from typing import Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.utils.checkpoint
|
| 22 |
+
from torch import nn
|
| 23 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 24 |
+
|
| 25 |
+
from ...activations import ACT2FN
|
| 26 |
+
from ...generation import GenerationMixin
|
| 27 |
+
from ...modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
|
| 28 |
+
from ...modeling_outputs import (
|
| 29 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 30 |
+
CausalLMOutputWithCrossAttentions,
|
| 31 |
+
SequenceClassifierOutputWithPast,
|
| 32 |
+
TokenClassifierOutput,
|
| 33 |
+
)
|
| 34 |
+
from ...modeling_utils import PreTrainedModel
|
| 35 |
+
from ...utils import (
|
| 36 |
+
add_code_sample_docstrings,
|
| 37 |
+
add_start_docstrings,
|
| 38 |
+
add_start_docstrings_to_model_forward,
|
| 39 |
+
logging,
|
| 40 |
+
)
|
| 41 |
+
from .configuration_biogpt import BioGptConfig
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
logger = logging.get_logger(__name__)
|
| 45 |
+
|
| 46 |
+
_CHECKPOINT_FOR_DOC = "microsoft/biogpt"
|
| 47 |
+
_CONFIG_FOR_DOC = "BioGptConfig"
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# copied from transformers.models.opt.modeling_opt.OPTLearnedPositionalEmbedding with OPT->BioGpt
|
| 51 |
+
# TODO @ArthurZucker bring copied from back
|
| 52 |
+
class BioGptLearnedPositionalEmbedding(nn.Embedding):
|
| 53 |
+
"""
|
| 54 |
+
This module learns positional embeddings up to a fixed maximum size.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
def __init__(self, num_embeddings: int, embedding_dim: int):
|
| 58 |
+
# BioGpt is set up so that if padding_idx is specified then offset the embedding ids by 2
|
| 59 |
+
# and adjust num_embeddings appropriately. Other models don't have this hack
|
| 60 |
+
self.offset = 2
|
| 61 |
+
super().__init__(num_embeddings + self.offset, embedding_dim)
|
| 62 |
+
|
| 63 |
+
def forward(self, attention_mask: torch.LongTensor, past_key_values_length: int = 0):
|
| 64 |
+
"""`input_ids_shape` is expected to be [bsz x seqlen]."""
|
| 65 |
+
attention_mask = attention_mask.long()
|
| 66 |
+
|
| 67 |
+
# create positions depending on attention_mask
|
| 68 |
+
positions = (torch.cumsum(attention_mask, dim=1).type_as(attention_mask) * attention_mask).long() - 1
|
| 69 |
+
|
| 70 |
+
# cut positions if `past_key_values_length` is > 0
|
| 71 |
+
positions = positions[:, past_key_values_length:]
|
| 72 |
+
|
| 73 |
+
return super().forward(positions + self.offset)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# Copied from transformers.models.bart.modeling_bart.BartScaledWordEmbedding with Bart->BioGpt
|
| 77 |
+
class BioGptScaledWordEmbedding(nn.Embedding):
|
| 78 |
+
"""
|
| 79 |
+
This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: Optional[float] = 1.0):
|
| 83 |
+
super().__init__(num_embeddings, embedding_dim, padding_idx)
|
| 84 |
+
self.embed_scale = embed_scale
|
| 85 |
+
|
| 86 |
+
def forward(self, input_ids: torch.Tensor):
|
| 87 |
+
return super().forward(input_ids) * self.embed_scale
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
# Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->BioGpt
|
| 91 |
+
class BioGptAttention(nn.Module):
|
| 92 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 93 |
+
|
| 94 |
+
def __init__(
|
| 95 |
+
self,
|
| 96 |
+
embed_dim: int,
|
| 97 |
+
num_heads: int,
|
| 98 |
+
dropout: float = 0.0,
|
| 99 |
+
is_decoder: bool = False,
|
| 100 |
+
bias: bool = True,
|
| 101 |
+
is_causal: bool = False,
|
| 102 |
+
config: Optional[BioGptConfig] = None,
|
| 103 |
+
):
|
| 104 |
+
super().__init__()
|
| 105 |
+
self.embed_dim = embed_dim
|
| 106 |
+
self.num_heads = num_heads
|
| 107 |
+
self.dropout = dropout
|
| 108 |
+
self.head_dim = embed_dim // num_heads
|
| 109 |
+
self.config = config
|
| 110 |
+
|
| 111 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 112 |
+
raise ValueError(
|
| 113 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 114 |
+
f" and `num_heads`: {num_heads})."
|
| 115 |
+
)
|
| 116 |
+
self.scaling = self.head_dim**-0.5
|
| 117 |
+
self.is_decoder = is_decoder
|
| 118 |
+
self.is_causal = is_causal
|
| 119 |
+
|
| 120 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 121 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 122 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 123 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 124 |
+
|
| 125 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 126 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 127 |
+
|
| 128 |
+
def forward(
|
| 129 |
+
self,
|
| 130 |
+
hidden_states: torch.Tensor,
|
| 131 |
+
key_value_states: Optional[torch.Tensor] = None,
|
| 132 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 133 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 134 |
+
layer_head_mask: Optional[torch.Tensor] = None,
|
| 135 |
+
output_attentions: bool = False,
|
| 136 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 137 |
+
"""Input shape: Batch x Time x Channel"""
|
| 138 |
+
|
| 139 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 140 |
+
# for the decoder
|
| 141 |
+
is_cross_attention = key_value_states is not None
|
| 142 |
+
|
| 143 |
+
bsz, tgt_len, _ = hidden_states.size()
|
| 144 |
+
|
| 145 |
+
# get query proj
|
| 146 |
+
query_states = self.q_proj(hidden_states) * self.scaling
|
| 147 |
+
# get key, value proj
|
| 148 |
+
# `past_key_value[0].shape[2] == key_value_states.shape[1]`
|
| 149 |
+
# is checking that the `sequence_length` of the `past_key_value` is the same as
|
| 150 |
+
# the provided `key_value_states` to support prefix tuning
|
| 151 |
+
if (
|
| 152 |
+
is_cross_attention
|
| 153 |
+
and past_key_value is not None
|
| 154 |
+
and past_key_value[0].shape[2] == key_value_states.shape[1]
|
| 155 |
+
):
|
| 156 |
+
# reuse k,v, cross_attentions
|
| 157 |
+
key_states = past_key_value[0]
|
| 158 |
+
value_states = past_key_value[1]
|
| 159 |
+
elif is_cross_attention:
|
| 160 |
+
# cross_attentions
|
| 161 |
+
key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
|
| 162 |
+
value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
|
| 163 |
+
elif past_key_value is not None:
|
| 164 |
+
# reuse k, v, self_attention
|
| 165 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 166 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 167 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
| 168 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
| 169 |
+
else:
|
| 170 |
+
# self_attention
|
| 171 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 172 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 173 |
+
|
| 174 |
+
if self.is_decoder:
|
| 175 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 176 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 177 |
+
# key/value_states (first "if" case)
|
| 178 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 179 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 180 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 181 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 182 |
+
past_key_value = (key_states, value_states)
|
| 183 |
+
|
| 184 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 185 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
| 186 |
+
key_states = key_states.reshape(*proj_shape)
|
| 187 |
+
value_states = value_states.reshape(*proj_shape)
|
| 188 |
+
|
| 189 |
+
src_len = key_states.size(1)
|
| 190 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
| 191 |
+
|
| 192 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
| 193 |
+
raise ValueError(
|
| 194 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 195 |
+
f" {attn_weights.size()}"
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
if attention_mask is not None:
|
| 199 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 200 |
+
raise ValueError(
|
| 201 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
| 202 |
+
)
|
| 203 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
| 204 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 205 |
+
|
| 206 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 207 |
+
|
| 208 |
+
if layer_head_mask is not None:
|
| 209 |
+
if layer_head_mask.size() != (self.num_heads,):
|
| 210 |
+
raise ValueError(
|
| 211 |
+
f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
|
| 212 |
+
f" {layer_head_mask.size()}"
|
| 213 |
+
)
|
| 214 |
+
attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 215 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 216 |
+
|
| 217 |
+
if output_attentions:
|
| 218 |
+
# this operation is a bit awkward, but it's required to
|
| 219 |
+
# make sure that attn_weights keeps its gradient.
|
| 220 |
+
# In order to do so, attn_weights have to be reshaped
|
| 221 |
+
# twice and have to be reused in the following
|
| 222 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 223 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
| 224 |
+
else:
|
| 225 |
+
attn_weights_reshaped = None
|
| 226 |
+
|
| 227 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 228 |
+
|
| 229 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
| 230 |
+
|
| 231 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
| 232 |
+
raise ValueError(
|
| 233 |
+
f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 234 |
+
f" {attn_output.size()}"
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
| 238 |
+
attn_output = attn_output.transpose(1, 2)
|
| 239 |
+
|
| 240 |
+
# Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
|
| 241 |
+
# partitioned across GPUs when using tensor-parallelism.
|
| 242 |
+
attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
|
| 243 |
+
|
| 244 |
+
attn_output = self.out_proj(attn_output)
|
| 245 |
+
|
| 246 |
+
return attn_output, attn_weights_reshaped, past_key_value
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
# Copied from transformers.models.bart.modeling_bart.BartSdpaAttention with Bart->BioGpt
|
| 250 |
+
class BioGptSdpaAttention(BioGptAttention):
|
| 251 |
+
def forward(
|
| 252 |
+
self,
|
| 253 |
+
hidden_states: torch.Tensor,
|
| 254 |
+
key_value_states: Optional[torch.Tensor] = None,
|
| 255 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 256 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 257 |
+
layer_head_mask: Optional[torch.Tensor] = None,
|
| 258 |
+
output_attentions: bool = False,
|
| 259 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 260 |
+
"""Input shape: Batch x Time x Channel"""
|
| 261 |
+
if output_attentions or layer_head_mask is not None:
|
| 262 |
+
# TODO: Improve this warning with e.g. `model.config._attn_implementation = "manual"` once this is implemented.
|
| 263 |
+
logger.warning_once(
|
| 264 |
+
"BioGptModel is using BioGptSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True` or `layer_head_mask` not None. Falling back to the manual attention"
|
| 265 |
+
' implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 266 |
+
)
|
| 267 |
+
return super().forward(
|
| 268 |
+
hidden_states,
|
| 269 |
+
key_value_states=key_value_states,
|
| 270 |
+
past_key_value=past_key_value,
|
| 271 |
+
attention_mask=attention_mask,
|
| 272 |
+
layer_head_mask=layer_head_mask,
|
| 273 |
+
output_attentions=output_attentions,
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 277 |
+
# for the decoder
|
| 278 |
+
is_cross_attention = key_value_states is not None
|
| 279 |
+
|
| 280 |
+
bsz, tgt_len, _ = hidden_states.size()
|
| 281 |
+
|
| 282 |
+
# get query proj
|
| 283 |
+
query_states = self.q_proj(hidden_states)
|
| 284 |
+
# get key, value proj
|
| 285 |
+
# `past_key_value[0].shape[2] == key_value_states.shape[1]`
|
| 286 |
+
# is checking that the `sequence_length` of the `past_key_value` is the same as
|
| 287 |
+
# the provided `key_value_states` to support prefix tuning
|
| 288 |
+
if (
|
| 289 |
+
is_cross_attention
|
| 290 |
+
and past_key_value is not None
|
| 291 |
+
and past_key_value[0].shape[2] == key_value_states.shape[1]
|
| 292 |
+
):
|
| 293 |
+
# reuse k,v, cross_attentions
|
| 294 |
+
key_states = past_key_value[0]
|
| 295 |
+
value_states = past_key_value[1]
|
| 296 |
+
elif is_cross_attention:
|
| 297 |
+
# cross_attentions
|
| 298 |
+
key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
|
| 299 |
+
value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
|
| 300 |
+
elif past_key_value is not None:
|
| 301 |
+
# reuse k, v, self_attention
|
| 302 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 303 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 304 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
| 305 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
| 306 |
+
else:
|
| 307 |
+
# self_attention
|
| 308 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 309 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 310 |
+
|
| 311 |
+
if self.is_decoder:
|
| 312 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 313 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 314 |
+
# key/value_states (first "if" case)
|
| 315 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 316 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 317 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 318 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 319 |
+
past_key_value = (key_states, value_states)
|
| 320 |
+
|
| 321 |
+
query_states = self._shape(query_states, tgt_len, bsz)
|
| 322 |
+
|
| 323 |
+
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
|
| 324 |
+
# in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
|
| 325 |
+
# The tgt_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case tgt_len == 1.
|
| 326 |
+
is_causal = True if self.is_causal and attention_mask is None and tgt_len > 1 else False
|
| 327 |
+
|
| 328 |
+
# NOTE: SDPA with memory-efficient backend is currently (torch==2.1.2) bugged when using non-contiguous inputs and a custom attn_mask,
|
| 329 |
+
# but we are fine here as `_shape` do call `.contiguous()`. Reference: https://github.com/pytorch/pytorch/issues/112577
|
| 330 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
| 331 |
+
query_states,
|
| 332 |
+
key_states,
|
| 333 |
+
value_states,
|
| 334 |
+
attn_mask=attention_mask,
|
| 335 |
+
dropout_p=self.dropout if self.training else 0.0,
|
| 336 |
+
is_causal=is_causal,
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
if attn_output.size() != (bsz, self.num_heads, tgt_len, self.head_dim):
|
| 340 |
+
raise ValueError(
|
| 341 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 342 |
+
f" {attn_output.size()}"
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
attn_output = attn_output.transpose(1, 2)
|
| 346 |
+
|
| 347 |
+
# Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
|
| 348 |
+
# partitioned across GPUs when using tensor-parallelism.
|
| 349 |
+
attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
|
| 350 |
+
|
| 351 |
+
attn_output = self.out_proj(attn_output)
|
| 352 |
+
|
| 353 |
+
return attn_output, None, past_key_value
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
BIOGPT_ATTENTION_CLASSES = {
|
| 357 |
+
"eager": BioGptAttention,
|
| 358 |
+
"sdpa": BioGptSdpaAttention,
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
class BioGptDecoderLayer(nn.Module):
|
| 363 |
+
def __init__(self, config: BioGptConfig):
|
| 364 |
+
super().__init__()
|
| 365 |
+
self.embed_dim = config.hidden_size
|
| 366 |
+
|
| 367 |
+
self.self_attn = BIOGPT_ATTENTION_CLASSES[config._attn_implementation](
|
| 368 |
+
embed_dim=self.embed_dim,
|
| 369 |
+
num_heads=config.num_attention_heads,
|
| 370 |
+
dropout=config.attention_probs_dropout_prob,
|
| 371 |
+
is_decoder=True,
|
| 372 |
+
is_causal=True,
|
| 373 |
+
)
|
| 374 |
+
self.dropout = config.hidden_dropout_prob
|
| 375 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 376 |
+
self.activation_dropout = config.activation_dropout
|
| 377 |
+
|
| 378 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 379 |
+
|
| 380 |
+
self.fc1 = nn.Linear(self.embed_dim, config.intermediate_size)
|
| 381 |
+
self.fc2 = nn.Linear(config.intermediate_size, self.embed_dim)
|
| 382 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 383 |
+
|
| 384 |
+
def forward(
|
| 385 |
+
self,
|
| 386 |
+
hidden_states: torch.Tensor,
|
| 387 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 388 |
+
layer_head_mask: Optional[torch.Tensor] = None,
|
| 389 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 390 |
+
output_attentions: Optional[bool] = False,
|
| 391 |
+
use_cache: Optional[bool] = True,
|
| 392 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 393 |
+
"""
|
| 394 |
+
Args:
|
| 395 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 396 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 397 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 398 |
+
layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
|
| 399 |
+
`(encoder_attention_heads,)`.
|
| 400 |
+
past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
|
| 401 |
+
output_attentions (`bool`, *optional*):
|
| 402 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 403 |
+
returned tensors for more detail.
|
| 404 |
+
use_cache (`bool`, *optional*):
|
| 405 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 406 |
+
(see `past_key_values`).
|
| 407 |
+
"""
|
| 408 |
+
residual = hidden_states
|
| 409 |
+
|
| 410 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 411 |
+
|
| 412 |
+
# Self Attention
|
| 413 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 414 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 415 |
+
# add present self-attn cache to positions 1,2 of present_key_value tuple
|
| 416 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 417 |
+
hidden_states=hidden_states,
|
| 418 |
+
past_key_value=self_attn_past_key_value,
|
| 419 |
+
attention_mask=attention_mask,
|
| 420 |
+
layer_head_mask=layer_head_mask,
|
| 421 |
+
output_attentions=output_attentions,
|
| 422 |
+
)
|
| 423 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 424 |
+
hidden_states = residual + hidden_states
|
| 425 |
+
|
| 426 |
+
# Fully Connected
|
| 427 |
+
residual = hidden_states
|
| 428 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 429 |
+
hidden_states = self.fc1(hidden_states)
|
| 430 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 431 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 432 |
+
hidden_states = self.fc2(hidden_states)
|
| 433 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 434 |
+
hidden_states = residual + hidden_states
|
| 435 |
+
|
| 436 |
+
outputs = (hidden_states,)
|
| 437 |
+
|
| 438 |
+
if output_attentions:
|
| 439 |
+
outputs += (self_attn_weights,)
|
| 440 |
+
|
| 441 |
+
if use_cache:
|
| 442 |
+
outputs += (present_key_value,)
|
| 443 |
+
|
| 444 |
+
return outputs
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
class BioGptPreTrainedModel(PreTrainedModel):
|
| 448 |
+
"""
|
| 449 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 450 |
+
models.
|
| 451 |
+
"""
|
| 452 |
+
|
| 453 |
+
config_class = BioGptConfig
|
| 454 |
+
base_model_prefix = "biogpt"
|
| 455 |
+
supports_gradient_checkpointing = True
|
| 456 |
+
_supports_sdpa = True
|
| 457 |
+
|
| 458 |
+
def _init_weights(self, module):
|
| 459 |
+
"""Initialize the weights"""
|
| 460 |
+
if isinstance(module, nn.Linear):
|
| 461 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 462 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 463 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 464 |
+
if module.bias is not None:
|
| 465 |
+
module.bias.data.zero_()
|
| 466 |
+
elif isinstance(module, nn.Embedding):
|
| 467 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 468 |
+
if module.padding_idx is not None:
|
| 469 |
+
module.weight.data[module.padding_idx].zero_()
|
| 470 |
+
elif isinstance(module, nn.LayerNorm):
|
| 471 |
+
module.bias.data.zero_()
|
| 472 |
+
module.weight.data.fill_(1.0)
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
BIOGPT_START_DOCSTRING = r"""
|
| 476 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
|
| 477 |
+
it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 478 |
+
behavior.
|
| 479 |
+
|
| 480 |
+
Parameters:
|
| 481 |
+
config ([`~BioGptConfig`]): Model configuration class with all the parameters of the model.
|
| 482 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 483 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 484 |
+
"""
|
| 485 |
+
|
| 486 |
+
BIOGPT_INPUTS_DOCSTRING = r"""
|
| 487 |
+
Args:
|
| 488 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
| 489 |
+
Indices of input sequence tokens in the vocabulary.
|
| 490 |
+
|
| 491 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 492 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 493 |
+
|
| 494 |
+
[What are input IDs?](../glossary#input-ids)
|
| 495 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
| 496 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 497 |
+
|
| 498 |
+
- 1 for tokens that are **not masked**,
|
| 499 |
+
- 0 for tokens that are **masked**.
|
| 500 |
+
|
| 501 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 502 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 503 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 504 |
+
|
| 505 |
+
- 1 indicates the head is **not masked**,
|
| 506 |
+
- 0 indicates the head is **masked**.
|
| 507 |
+
|
| 508 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
| 509 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 510 |
+
is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
|
| 511 |
+
model's internal embedding lookup matrix.
|
| 512 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 513 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
| 514 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
|
| 515 |
+
`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
|
| 516 |
+
|
| 517 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
| 518 |
+
blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 519 |
+
|
| 520 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 521 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 522 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 523 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 524 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 525 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 526 |
+
than the model's internal embedding lookup matrix.
|
| 527 |
+
use_cache (`bool`, *optional*):
|
| 528 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 529 |
+
`past_key_values`).
|
| 530 |
+
output_attentions (`bool`, *optional*):
|
| 531 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 532 |
+
tensors for more detail.
|
| 533 |
+
output_hidden_states (`bool`, *optional*):
|
| 534 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 535 |
+
more detail.
|
| 536 |
+
return_dict (`bool`, *optional*):
|
| 537 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 538 |
+
"""
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
@add_start_docstrings(
|
| 542 |
+
"The bare BioGPT Model transformer outputting raw hidden-states without any specific head on top.",
|
| 543 |
+
BIOGPT_START_DOCSTRING,
|
| 544 |
+
)
|
| 545 |
+
class BioGptModel(BioGptPreTrainedModel):
|
| 546 |
+
def __init__(self, config: BioGptConfig):
|
| 547 |
+
super().__init__(config)
|
| 548 |
+
self.config = config
|
| 549 |
+
self.layerdrop = config.layerdrop
|
| 550 |
+
self.dropout = config.hidden_dropout_prob
|
| 551 |
+
self.embed_dim = config.hidden_size
|
| 552 |
+
self.padding_idx = config.pad_token_id
|
| 553 |
+
embed_scale = math.sqrt(config.hidden_size) if config.scale_embedding else 1.0
|
| 554 |
+
|
| 555 |
+
self.embed_tokens = BioGptScaledWordEmbedding(
|
| 556 |
+
config.vocab_size, self.embed_dim, self.padding_idx, embed_scale=embed_scale
|
| 557 |
+
)
|
| 558 |
+
self.embed_positions = BioGptLearnedPositionalEmbedding(config.max_position_embeddings, self.embed_dim)
|
| 559 |
+
|
| 560 |
+
self.layers = nn.ModuleList([BioGptDecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
| 561 |
+
self.layer_norm = nn.LayerNorm(self.embed_dim)
|
| 562 |
+
|
| 563 |
+
self.gradient_checkpointing = False
|
| 564 |
+
self._use_sdpa = config._attn_implementation == "sdpa"
|
| 565 |
+
# Initialize weights and apply final processing
|
| 566 |
+
self.post_init()
|
| 567 |
+
|
| 568 |
+
def get_input_embeddings(self):
|
| 569 |
+
return self.embed_tokens
|
| 570 |
+
|
| 571 |
+
def set_input_embeddings(self, value):
|
| 572 |
+
self.embed_tokens = value
|
| 573 |
+
|
| 574 |
+
@add_start_docstrings_to_model_forward(BIOGPT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 575 |
+
@add_code_sample_docstrings(
|
| 576 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 577 |
+
output_type=BaseModelOutputWithPastAndCrossAttentions,
|
| 578 |
+
config_class=_CONFIG_FOR_DOC,
|
| 579 |
+
)
|
| 580 |
+
def forward(
|
| 581 |
+
self,
|
| 582 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 583 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 584 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 585 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 586 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
| 587 |
+
use_cache: Optional[bool] = None,
|
| 588 |
+
output_attentions: Optional[bool] = None,
|
| 589 |
+
output_hidden_states: Optional[bool] = None,
|
| 590 |
+
return_dict: Optional[bool] = None,
|
| 591 |
+
**kwargs, # NOOP kwargs, for now
|
| 592 |
+
) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
|
| 593 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 594 |
+
output_hidden_states = (
|
| 595 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 596 |
+
)
|
| 597 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 598 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 599 |
+
|
| 600 |
+
# retrieve input_ids and inputs_embeds
|
| 601 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 602 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 603 |
+
elif input_ids is not None:
|
| 604 |
+
input = input_ids
|
| 605 |
+
input_shape = input.size()
|
| 606 |
+
elif inputs_embeds is not None:
|
| 607 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 608 |
+
input = inputs_embeds[:, :, -1]
|
| 609 |
+
else:
|
| 610 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 611 |
+
|
| 612 |
+
# past_key_values_length
|
| 613 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
| 614 |
+
|
| 615 |
+
if inputs_embeds is None:
|
| 616 |
+
inputs_embeds = self.embed_tokens(input)
|
| 617 |
+
|
| 618 |
+
if attention_mask is None:
|
| 619 |
+
attention_mask = torch.ones(
|
| 620 |
+
(inputs_embeds.shape[0], inputs_embeds.shape[1] + past_key_values_length),
|
| 621 |
+
dtype=torch.bool,
|
| 622 |
+
device=inputs_embeds.device,
|
| 623 |
+
)
|
| 624 |
+
elif attention_mask.shape[1] != past_key_values_length + input_shape[1]:
|
| 625 |
+
raise ValueError(
|
| 626 |
+
f"The provided attention mask has length {attention_mask.shape[1]}, but its length should be "
|
| 627 |
+
f"{past_key_values_length + input_shape[1]} (sum of the lengths of current and past inputs)"
|
| 628 |
+
)
|
| 629 |
+
|
| 630 |
+
# embed positions
|
| 631 |
+
positions = self.embed_positions(attention_mask, past_key_values_length)
|
| 632 |
+
|
| 633 |
+
if self._use_sdpa and not output_attentions and head_mask is None:
|
| 634 |
+
# output_attentions=True & head_mask can not be supported when using SDPA, fall back to
|
| 635 |
+
# the manual implementation that requires a 4D causal mask in all cases.
|
| 636 |
+
attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
|
| 637 |
+
attention_mask, input_shape, inputs_embeds, past_key_values_length
|
| 638 |
+
)
|
| 639 |
+
else:
|
| 640 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
| 641 |
+
attention_mask, input_shape, inputs_embeds, past_key_values_length
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
hidden_states = inputs_embeds + positions
|
| 645 |
+
|
| 646 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 647 |
+
|
| 648 |
+
if self.gradient_checkpointing and self.training:
|
| 649 |
+
if use_cache:
|
| 650 |
+
logger.warning_once(
|
| 651 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 652 |
+
)
|
| 653 |
+
use_cache = False
|
| 654 |
+
|
| 655 |
+
all_hidden_states = () if output_hidden_states else None
|
| 656 |
+
all_self_attns = () if output_attentions else None
|
| 657 |
+
all_cross_attentions = None
|
| 658 |
+
next_decoder_cache = () if use_cache else None
|
| 659 |
+
|
| 660 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 661 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 662 |
+
if output_hidden_states:
|
| 663 |
+
all_hidden_states += (hidden_states,)
|
| 664 |
+
if self.training:
|
| 665 |
+
dropout_probability = torch.rand([])
|
| 666 |
+
if dropout_probability < self.layerdrop:
|
| 667 |
+
continue
|
| 668 |
+
|
| 669 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
| 670 |
+
|
| 671 |
+
if self.gradient_checkpointing and self.training:
|
| 672 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 673 |
+
decoder_layer.__call__,
|
| 674 |
+
hidden_states,
|
| 675 |
+
attention_mask,
|
| 676 |
+
head_mask[idx] if head_mask is not None else None,
|
| 677 |
+
None,
|
| 678 |
+
output_attentions,
|
| 679 |
+
use_cache,
|
| 680 |
+
)
|
| 681 |
+
else:
|
| 682 |
+
layer_outputs = decoder_layer(
|
| 683 |
+
hidden_states,
|
| 684 |
+
attention_mask=attention_mask,
|
| 685 |
+
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
|
| 686 |
+
past_key_value=past_key_value,
|
| 687 |
+
output_attentions=output_attentions,
|
| 688 |
+
use_cache=use_cache,
|
| 689 |
+
)
|
| 690 |
+
|
| 691 |
+
hidden_states = layer_outputs[0]
|
| 692 |
+
|
| 693 |
+
if use_cache:
|
| 694 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
| 695 |
+
|
| 696 |
+
if output_attentions:
|
| 697 |
+
all_self_attns += (layer_outputs[1],)
|
| 698 |
+
|
| 699 |
+
# add hidden states from the last decoder layer
|
| 700 |
+
if output_hidden_states:
|
| 701 |
+
all_hidden_states += (hidden_states,)
|
| 702 |
+
|
| 703 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 704 |
+
|
| 705 |
+
next_cache = next_decoder_cache if use_cache else None
|
| 706 |
+
|
| 707 |
+
if not return_dict:
|
| 708 |
+
return tuple(
|
| 709 |
+
v
|
| 710 |
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
|
| 711 |
+
if v is not None
|
| 712 |
+
)
|
| 713 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 714 |
+
last_hidden_state=hidden_states,
|
| 715 |
+
past_key_values=next_cache,
|
| 716 |
+
hidden_states=all_hidden_states,
|
| 717 |
+
attentions=all_self_attns,
|
| 718 |
+
cross_attentions=all_cross_attentions,
|
| 719 |
+
)
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
@add_start_docstrings(
|
| 723 |
+
"""BioGPT Model with a `language modeling` head on top for CLM fine-tuning.""", BIOGPT_START_DOCSTRING
|
| 724 |
+
)
|
| 725 |
+
class BioGptForCausalLM(BioGptPreTrainedModel, GenerationMixin):
|
| 726 |
+
_tied_weights_keys = ["output_projection.weight"]
|
| 727 |
+
|
| 728 |
+
def __init__(self, config):
|
| 729 |
+
super().__init__(config)
|
| 730 |
+
|
| 731 |
+
self.biogpt = BioGptModel(config)
|
| 732 |
+
self.output_projection = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 733 |
+
|
| 734 |
+
# Initialize weights and apply final processing
|
| 735 |
+
self.post_init()
|
| 736 |
+
|
| 737 |
+
def get_output_embeddings(self):
|
| 738 |
+
return self.output_projection
|
| 739 |
+
|
| 740 |
+
def set_output_embeddings(self, new_embeddings):
|
| 741 |
+
self.output_projection = new_embeddings
|
| 742 |
+
|
| 743 |
+
@add_start_docstrings_to_model_forward(BIOGPT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 744 |
+
@add_code_sample_docstrings(
|
| 745 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 746 |
+
output_type=CausalLMOutputWithCrossAttentions,
|
| 747 |
+
config_class=_CONFIG_FOR_DOC,
|
| 748 |
+
)
|
| 749 |
+
def forward(
|
| 750 |
+
self,
|
| 751 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 752 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 753 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 754 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 755 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
| 756 |
+
labels: Optional[torch.LongTensor] = None,
|
| 757 |
+
use_cache: Optional[bool] = None,
|
| 758 |
+
output_attentions: Optional[bool] = None,
|
| 759 |
+
output_hidden_states: Optional[bool] = None,
|
| 760 |
+
return_dict: Optional[bool] = None,
|
| 761 |
+
**kwargs,
|
| 762 |
+
) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
|
| 763 |
+
r"""
|
| 764 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 765 |
+
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
|
| 766 |
+
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
|
| 767 |
+
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
|
| 768 |
+
"""
|
| 769 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 770 |
+
|
| 771 |
+
outputs = self.biogpt(
|
| 772 |
+
input_ids,
|
| 773 |
+
attention_mask=attention_mask,
|
| 774 |
+
head_mask=head_mask,
|
| 775 |
+
inputs_embeds=inputs_embeds,
|
| 776 |
+
past_key_values=past_key_values,
|
| 777 |
+
use_cache=use_cache,
|
| 778 |
+
output_attentions=output_attentions,
|
| 779 |
+
output_hidden_states=output_hidden_states,
|
| 780 |
+
return_dict=return_dict,
|
| 781 |
+
)
|
| 782 |
+
|
| 783 |
+
sequence_output = outputs[0]
|
| 784 |
+
prediction_scores = self.output_projection(sequence_output)
|
| 785 |
+
|
| 786 |
+
lm_loss = None
|
| 787 |
+
if labels is not None:
|
| 788 |
+
lm_loss = self.loss_function(
|
| 789 |
+
prediction_scores,
|
| 790 |
+
labels,
|
| 791 |
+
vocab_size=self.config.vocab_size,
|
| 792 |
+
**kwargs,
|
| 793 |
+
)
|
| 794 |
+
|
| 795 |
+
if not return_dict:
|
| 796 |
+
output = (prediction_scores,) + outputs[1:]
|
| 797 |
+
return ((lm_loss,) + output) if lm_loss is not None else output
|
| 798 |
+
|
| 799 |
+
return CausalLMOutputWithCrossAttentions(
|
| 800 |
+
loss=lm_loss,
|
| 801 |
+
logits=prediction_scores,
|
| 802 |
+
past_key_values=outputs.past_key_values,
|
| 803 |
+
hidden_states=outputs.hidden_states,
|
| 804 |
+
attentions=outputs.attentions,
|
| 805 |
+
cross_attentions=outputs.cross_attentions,
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
@staticmethod
|
| 809 |
+
def _reorder_cache(past_key_values, beam_idx):
|
| 810 |
+
reordered_past = ()
|
| 811 |
+
for layer_past in past_key_values:
|
| 812 |
+
reordered_past += (
|
| 813 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
| 814 |
+
)
|
| 815 |
+
return reordered_past
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
@add_start_docstrings(
|
| 819 |
+
"""
|
| 820 |
+
BioGPT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
| 821 |
+
Named-Entity-Recognition (NER) tasks.
|
| 822 |
+
""",
|
| 823 |
+
BIOGPT_START_DOCSTRING,
|
| 824 |
+
)
|
| 825 |
+
class BioGptForTokenClassification(BioGptPreTrainedModel):
|
| 826 |
+
def __init__(self, config):
|
| 827 |
+
super().__init__(config)
|
| 828 |
+
self.num_labels = config.num_labels
|
| 829 |
+
|
| 830 |
+
self.biogpt = BioGptModel(config)
|
| 831 |
+
if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
|
| 832 |
+
classifier_dropout = config.classifier_dropout
|
| 833 |
+
else:
|
| 834 |
+
classifier_dropout = config.hidden_dropout_prob
|
| 835 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 836 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 837 |
+
|
| 838 |
+
self.post_init()
|
| 839 |
+
|
| 840 |
+
@add_start_docstrings_to_model_forward(BIOGPT_INPUTS_DOCSTRING)
|
| 841 |
+
@add_code_sample_docstrings(
|
| 842 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 843 |
+
output_type=TokenClassifierOutput,
|
| 844 |
+
config_class=_CONFIG_FOR_DOC,
|
| 845 |
+
)
|
| 846 |
+
def forward(
|
| 847 |
+
self,
|
| 848 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 849 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 850 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 851 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 852 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
| 853 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 854 |
+
labels: Optional[torch.LongTensor] = None,
|
| 855 |
+
use_cache: Optional[bool] = None,
|
| 856 |
+
output_attentions: Optional[bool] = None,
|
| 857 |
+
output_hidden_states: Optional[bool] = None,
|
| 858 |
+
return_dict: Optional[bool] = None,
|
| 859 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
| 860 |
+
r"""
|
| 861 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 862 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 863 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 864 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 865 |
+
"""
|
| 866 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 867 |
+
|
| 868 |
+
transformer_outputs = self.biogpt(
|
| 869 |
+
input_ids,
|
| 870 |
+
past_key_values=past_key_values,
|
| 871 |
+
attention_mask=attention_mask,
|
| 872 |
+
head_mask=head_mask,
|
| 873 |
+
inputs_embeds=inputs_embeds,
|
| 874 |
+
use_cache=use_cache,
|
| 875 |
+
output_attentions=output_attentions,
|
| 876 |
+
output_hidden_states=output_hidden_states,
|
| 877 |
+
return_dict=return_dict,
|
| 878 |
+
)
|
| 879 |
+
|
| 880 |
+
hidden_states = transformer_outputs[0]
|
| 881 |
+
hidden_states = self.dropout(hidden_states)
|
| 882 |
+
logits = self.classifier(hidden_states)
|
| 883 |
+
|
| 884 |
+
loss = None
|
| 885 |
+
if labels is not None:
|
| 886 |
+
loss_fct = CrossEntropyLoss()
|
| 887 |
+
# Only keep active parts of the loss
|
| 888 |
+
if attention_mask is not None:
|
| 889 |
+
active_loss = attention_mask.view(-1) == 1
|
| 890 |
+
active_logits = logits.view(-1, self.num_labels)
|
| 891 |
+
active_labels = torch.where(
|
| 892 |
+
active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
|
| 893 |
+
)
|
| 894 |
+
loss = loss_fct(active_logits, active_labels)
|
| 895 |
+
else:
|
| 896 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 897 |
+
|
| 898 |
+
if not return_dict:
|
| 899 |
+
output = (logits,) + transformer_outputs[2:]
|
| 900 |
+
return ((loss,) + output) if loss is not None else output
|
| 901 |
+
|
| 902 |
+
return TokenClassifierOutput(
|
| 903 |
+
loss=loss,
|
| 904 |
+
logits=logits,
|
| 905 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 906 |
+
attentions=transformer_outputs.attentions,
|
| 907 |
+
)
|
| 908 |
+
|
| 909 |
+
|
| 910 |
+
@add_start_docstrings(
|
| 911 |
+
"""
|
| 912 |
+
The BioGpt Model transformer with a sequence classification head on top (linear layer).
|
| 913 |
+
|
| 914 |
+
[`BioGptForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
| 915 |
+
(e.g. GPT-2) do.
|
| 916 |
+
|
| 917 |
+
Since it does classification on the last token, it is required to know the position of the last token. If a
|
| 918 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
| 919 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
| 920 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
| 921 |
+
each row of the batch).
|
| 922 |
+
""",
|
| 923 |
+
BIOGPT_START_DOCSTRING,
|
| 924 |
+
)
|
| 925 |
+
class BioGptForSequenceClassification(BioGptPreTrainedModel):
|
| 926 |
+
def __init__(self, config: BioGptConfig):
|
| 927 |
+
super().__init__(config)
|
| 928 |
+
self.num_labels = config.num_labels
|
| 929 |
+
self.biogpt = BioGptModel(config)
|
| 930 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
| 931 |
+
|
| 932 |
+
# Initialize weights and apply final processing
|
| 933 |
+
self.post_init()
|
| 934 |
+
|
| 935 |
+
@add_start_docstrings_to_model_forward(BIOGPT_INPUTS_DOCSTRING)
|
| 936 |
+
@add_code_sample_docstrings(
|
| 937 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 938 |
+
output_type=SequenceClassifierOutputWithPast,
|
| 939 |
+
config_class=_CONFIG_FOR_DOC,
|
| 940 |
+
)
|
| 941 |
+
def forward(
|
| 942 |
+
self,
|
| 943 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 944 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 945 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 946 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
| 947 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 948 |
+
labels: Optional[torch.LongTensor] = None,
|
| 949 |
+
use_cache: Optional[bool] = None,
|
| 950 |
+
output_attentions: Optional[bool] = None,
|
| 951 |
+
output_hidden_states: Optional[bool] = None,
|
| 952 |
+
return_dict: Optional[bool] = None,
|
| 953 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
| 954 |
+
r"""
|
| 955 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 956 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 957 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 958 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 959 |
+
"""
|
| 960 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 961 |
+
|
| 962 |
+
transformer_outputs = self.biogpt(
|
| 963 |
+
input_ids,
|
| 964 |
+
past_key_values=past_key_values,
|
| 965 |
+
attention_mask=attention_mask,
|
| 966 |
+
head_mask=head_mask,
|
| 967 |
+
inputs_embeds=inputs_embeds,
|
| 968 |
+
use_cache=use_cache,
|
| 969 |
+
output_attentions=output_attentions,
|
| 970 |
+
output_hidden_states=output_hidden_states,
|
| 971 |
+
return_dict=return_dict,
|
| 972 |
+
)
|
| 973 |
+
hidden_states = transformer_outputs[0]
|
| 974 |
+
logits = self.score(hidden_states)
|
| 975 |
+
|
| 976 |
+
if input_ids is not None:
|
| 977 |
+
batch_size, sequence_length = input_ids.shape[:2]
|
| 978 |
+
else:
|
| 979 |
+
batch_size, sequence_length = inputs_embeds.shape[:2]
|
| 980 |
+
|
| 981 |
+
if self.config.pad_token_id is None:
|
| 982 |
+
sequence_length = -1
|
| 983 |
+
else:
|
| 984 |
+
if input_ids is not None:
|
| 985 |
+
sequence_length = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
|
| 986 |
+
else:
|
| 987 |
+
sequence_length = -1
|
| 988 |
+
logger.warning_once(
|
| 989 |
+
f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
|
| 990 |
+
"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
|
| 991 |
+
)
|
| 992 |
+
|
| 993 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_length]
|
| 994 |
+
|
| 995 |
+
loss = None
|
| 996 |
+
if labels is not None:
|
| 997 |
+
if self.config.problem_type is None:
|
| 998 |
+
if self.num_labels == 1:
|
| 999 |
+
self.config.problem_type = "regression"
|
| 1000 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1001 |
+
self.config.problem_type = "single_label_classification"
|
| 1002 |
+
else:
|
| 1003 |
+
self.config.problem_type = "multi_label_classification"
|
| 1004 |
+
|
| 1005 |
+
if self.config.problem_type == "regression":
|
| 1006 |
+
loss_fct = MSELoss()
|
| 1007 |
+
if self.num_labels == 1:
|
| 1008 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
| 1009 |
+
else:
|
| 1010 |
+
loss = loss_fct(pooled_logits, labels)
|
| 1011 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1012 |
+
loss_fct = CrossEntropyLoss()
|
| 1013 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
| 1014 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1015 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1016 |
+
loss = loss_fct(pooled_logits, labels)
|
| 1017 |
+
if not return_dict:
|
| 1018 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
| 1019 |
+
return ((loss,) + output) if loss is not None else output
|
| 1020 |
+
|
| 1021 |
+
return SequenceClassifierOutputWithPast(
|
| 1022 |
+
loss=loss,
|
| 1023 |
+
logits=pooled_logits,
|
| 1024 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 1025 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 1026 |
+
attentions=transformer_outputs.attentions,
|
| 1027 |
+
)
|
| 1028 |
+
|
| 1029 |
+
def get_input_embeddings(self):
|
| 1030 |
+
return self.biogpt.embed_tokens
|
| 1031 |
+
|
| 1032 |
+
def set_input_embeddings(self, value):
|
| 1033 |
+
self.biogpt.embed_tokens = value
|
| 1034 |
+
|
| 1035 |
+
|
| 1036 |
+
__all__ = [
|
| 1037 |
+
"BioGptForCausalLM",
|
| 1038 |
+
"BioGptForTokenClassification",
|
| 1039 |
+
"BioGptForSequenceClassification",
|
| 1040 |
+
"BioGptModel",
|
| 1041 |
+
"BioGptPreTrainedModel",
|
| 1042 |
+
]
|
lib/python3.12/site-packages/transformers/models/biogpt/tokenization_biogpt.py
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Team and Microsoft Research AI4Science. 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 |
+
"""Tokenization classes for BioGPT."""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
from typing import List, Optional, Tuple
|
| 20 |
+
|
| 21 |
+
from ...tokenization_utils import PreTrainedTokenizer
|
| 22 |
+
from ...utils import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
VOCAB_FILES_NAMES = {
|
| 28 |
+
"vocab_file": "vocab.json",
|
| 29 |
+
"merges_file": "merges.txt",
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def get_pairs(word):
|
| 34 |
+
"""
|
| 35 |
+
Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length
|
| 36 |
+
strings)
|
| 37 |
+
"""
|
| 38 |
+
pairs = set()
|
| 39 |
+
prev_char = word[0]
|
| 40 |
+
for char in word[1:]:
|
| 41 |
+
pairs.add((prev_char, char))
|
| 42 |
+
prev_char = char
|
| 43 |
+
return pairs
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class BioGptTokenizer(PreTrainedTokenizer):
|
| 47 |
+
"""
|
| 48 |
+
Construct an FAIRSEQ Transformer tokenizer. Moses tokenization followed by Byte-Pair Encoding.
|
| 49 |
+
|
| 50 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 51 |
+
this superclass for more information regarding those methods.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
vocab_file (`str`):
|
| 55 |
+
Path to the vocabulary file.
|
| 56 |
+
merges_file (`str`):
|
| 57 |
+
Merges file.
|
| 58 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 59 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 60 |
+
token instead.
|
| 61 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 62 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
| 63 |
+
|
| 64 |
+
<Tip>
|
| 65 |
+
|
| 66 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 67 |
+
sequence. The token used is the `cls_token`.
|
| 68 |
+
|
| 69 |
+
</Tip>
|
| 70 |
+
|
| 71 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 72 |
+
The end of sequence token.
|
| 73 |
+
|
| 74 |
+
<Tip>
|
| 75 |
+
|
| 76 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
| 77 |
+
The token used is the `sep_token`.
|
| 78 |
+
|
| 79 |
+
</Tip>
|
| 80 |
+
|
| 81 |
+
sep_token (`str`, *optional*, defaults to `"</s>"`):
|
| 82 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 83 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 84 |
+
token of a sequence built with special tokens.
|
| 85 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 86 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 90 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 91 |
+
|
| 92 |
+
def __init__(
|
| 93 |
+
self,
|
| 94 |
+
vocab_file,
|
| 95 |
+
merges_file,
|
| 96 |
+
unk_token="<unk>",
|
| 97 |
+
bos_token="<s>",
|
| 98 |
+
eos_token="</s>",
|
| 99 |
+
sep_token="</s>",
|
| 100 |
+
pad_token="<pad>",
|
| 101 |
+
**kwargs,
|
| 102 |
+
):
|
| 103 |
+
try:
|
| 104 |
+
import sacremoses
|
| 105 |
+
except ImportError:
|
| 106 |
+
raise ImportError(
|
| 107 |
+
"You need to install sacremoses to use BioGptTokenizer. "
|
| 108 |
+
"See https://pypi.org/project/sacremoses/ for installation."
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
self.lang = "en"
|
| 112 |
+
self.sm = sacremoses
|
| 113 |
+
# cache of sm.MosesTokenizer instance
|
| 114 |
+
self.cache_moses_tokenizer = {}
|
| 115 |
+
self.cache_moses_detokenizer = {}
|
| 116 |
+
|
| 117 |
+
""" Initialisation"""
|
| 118 |
+
with open(vocab_file, encoding="utf-8") as vocab_handle:
|
| 119 |
+
self.encoder = json.load(vocab_handle)
|
| 120 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
| 121 |
+
with open(merges_file, encoding="utf-8") as merges_handle:
|
| 122 |
+
merges = merges_handle.read().split("\n")[:-1]
|
| 123 |
+
merges = [tuple(merge.split()[:2]) for merge in merges]
|
| 124 |
+
self.bpe_ranks = dict(zip(merges, range(len(merges))))
|
| 125 |
+
self.cache = {}
|
| 126 |
+
|
| 127 |
+
super().__init__(
|
| 128 |
+
bos_token=bos_token,
|
| 129 |
+
eos_token=eos_token,
|
| 130 |
+
sep_token=sep_token,
|
| 131 |
+
unk_token=unk_token,
|
| 132 |
+
pad_token=pad_token,
|
| 133 |
+
**kwargs,
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
@property
|
| 137 |
+
def vocab_size(self):
|
| 138 |
+
"""Returns vocab size"""
|
| 139 |
+
return len(self.encoder)
|
| 140 |
+
|
| 141 |
+
def get_vocab(self):
|
| 142 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
| 143 |
+
|
| 144 |
+
def moses_tokenize(self, text, lang):
|
| 145 |
+
if lang not in self.cache_moses_tokenizer:
|
| 146 |
+
moses_tokenizer = self.sm.MosesTokenizer(lang=lang)
|
| 147 |
+
self.cache_moses_tokenizer[lang] = moses_tokenizer
|
| 148 |
+
return self.cache_moses_tokenizer[lang].tokenize(
|
| 149 |
+
text, aggressive_dash_splits=True, return_str=False, escape=True
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
def moses_detokenize(self, tokens, lang):
|
| 153 |
+
if lang not in self.cache_moses_detokenizer:
|
| 154 |
+
moses_detokenizer = self.sm.MosesDetokenizer(lang=lang)
|
| 155 |
+
self.cache_moses_detokenizer[lang] = moses_detokenizer
|
| 156 |
+
return self.cache_moses_detokenizer[lang].detokenize(tokens)
|
| 157 |
+
|
| 158 |
+
def bpe(self, token):
|
| 159 |
+
word = tuple(token[:-1]) + (token[-1] + "</w>",)
|
| 160 |
+
if token in self.cache:
|
| 161 |
+
return self.cache[token]
|
| 162 |
+
pairs = get_pairs(word)
|
| 163 |
+
|
| 164 |
+
if not pairs:
|
| 165 |
+
return token + "</w>"
|
| 166 |
+
|
| 167 |
+
while True:
|
| 168 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
| 169 |
+
if bigram not in self.bpe_ranks:
|
| 170 |
+
break
|
| 171 |
+
first, second = bigram
|
| 172 |
+
new_word = []
|
| 173 |
+
i = 0
|
| 174 |
+
while i < len(word):
|
| 175 |
+
try:
|
| 176 |
+
j = word.index(first, i)
|
| 177 |
+
except ValueError:
|
| 178 |
+
new_word.extend(word[i:])
|
| 179 |
+
break
|
| 180 |
+
else:
|
| 181 |
+
new_word.extend(word[i:j])
|
| 182 |
+
i = j
|
| 183 |
+
|
| 184 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
| 185 |
+
new_word.append(first + second)
|
| 186 |
+
i += 2
|
| 187 |
+
else:
|
| 188 |
+
new_word.append(word[i])
|
| 189 |
+
i += 1
|
| 190 |
+
new_word = tuple(new_word)
|
| 191 |
+
word = new_word
|
| 192 |
+
if len(word) == 1:
|
| 193 |
+
break
|
| 194 |
+
else:
|
| 195 |
+
pairs = get_pairs(word)
|
| 196 |
+
word = " ".join(word)
|
| 197 |
+
if word == "\n </w>":
|
| 198 |
+
word = "\n</w>"
|
| 199 |
+
self.cache[token] = word
|
| 200 |
+
return word
|
| 201 |
+
|
| 202 |
+
def _tokenize(self, text, bypass_tokenizer=False):
|
| 203 |
+
"""Returns a tokenized string."""
|
| 204 |
+
if bypass_tokenizer:
|
| 205 |
+
text = text.split()
|
| 206 |
+
else:
|
| 207 |
+
text = self.moses_tokenize(text, self.lang)
|
| 208 |
+
|
| 209 |
+
split_tokens = []
|
| 210 |
+
for token in text:
|
| 211 |
+
if token:
|
| 212 |
+
split_tokens.extend(list(self.bpe(token).split(" ")))
|
| 213 |
+
|
| 214 |
+
return split_tokens
|
| 215 |
+
|
| 216 |
+
def _convert_token_to_id(self, token):
|
| 217 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 218 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
| 219 |
+
|
| 220 |
+
def _convert_id_to_token(self, index):
|
| 221 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 222 |
+
return self.decoder.get(index, self.unk_token)
|
| 223 |
+
|
| 224 |
+
def convert_tokens_to_string(self, tokens):
|
| 225 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 226 |
+
# remove BPE
|
| 227 |
+
tokens = [t.replace(" ", "").replace("</w>", " ") for t in tokens]
|
| 228 |
+
tokens = "".join(tokens).split()
|
| 229 |
+
# detokenize
|
| 230 |
+
text = self.moses_detokenize(tokens, self.lang)
|
| 231 |
+
return text
|
| 232 |
+
|
| 233 |
+
def build_inputs_with_special_tokens(
|
| 234 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 235 |
+
) -> List[int]:
|
| 236 |
+
"""
|
| 237 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 238 |
+
adding special tokens. A BioGPT sequence has the following format:
|
| 239 |
+
|
| 240 |
+
- single sequence: `</s> X `
|
| 241 |
+
- pair of sequences: `</s> A </s> B `
|
| 242 |
+
|
| 243 |
+
Args:
|
| 244 |
+
token_ids_0 (`List[int]`):
|
| 245 |
+
List of IDs to which the special tokens will be added.
|
| 246 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 247 |
+
Optional second list of IDs for sequence pairs.
|
| 248 |
+
|
| 249 |
+
Returns:
|
| 250 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 251 |
+
"""
|
| 252 |
+
if token_ids_1 is None:
|
| 253 |
+
return [self.sep_token_id] + token_ids_0
|
| 254 |
+
sep = [self.sep_token_id]
|
| 255 |
+
return sep + token_ids_0 + sep + token_ids_1
|
| 256 |
+
|
| 257 |
+
def get_special_tokens_mask(
|
| 258 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
| 259 |
+
) -> List[int]:
|
| 260 |
+
"""
|
| 261 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 262 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 263 |
+
|
| 264 |
+
Args:
|
| 265 |
+
token_ids_0 (`List[int]`):
|
| 266 |
+
List of IDs.
|
| 267 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 268 |
+
Optional second list of IDs for sequence pairs.
|
| 269 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 270 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 271 |
+
|
| 272 |
+
Returns:
|
| 273 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 274 |
+
"""
|
| 275 |
+
if already_has_special_tokens:
|
| 276 |
+
return super().get_special_tokens_mask(
|
| 277 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 278 |
+
)
|
| 279 |
+
# no bos used in fairseq
|
| 280 |
+
if token_ids_1 is not None:
|
| 281 |
+
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
|
| 282 |
+
return [1] + ([0] * len(token_ids_0))
|
| 283 |
+
|
| 284 |
+
def create_token_type_ids_from_sequences(
|
| 285 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 286 |
+
) -> List[int]:
|
| 287 |
+
"""
|
| 288 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A FAIRSEQ
|
| 289 |
+
Transformer sequence pair mask has the following format:
|
| 290 |
+
|
| 291 |
+
```
|
| 292 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
| 293 |
+
| first sequence | second sequence |
|
| 294 |
+
```
|
| 295 |
+
|
| 296 |
+
If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
|
| 297 |
+
|
| 298 |
+
Args:
|
| 299 |
+
token_ids_0 (`List[int]`):
|
| 300 |
+
List of IDs.
|
| 301 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 302 |
+
Optional second list of IDs for sequence pairs.
|
| 303 |
+
|
| 304 |
+
Returns:
|
| 305 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
| 306 |
+
"""
|
| 307 |
+
sep = [self.sep_token_id]
|
| 308 |
+
|
| 309 |
+
# no bos used in fairseq
|
| 310 |
+
if token_ids_1 is None:
|
| 311 |
+
return len(token_ids_0 + sep) * [0]
|
| 312 |
+
return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
|
| 313 |
+
|
| 314 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 315 |
+
if not os.path.isdir(save_directory):
|
| 316 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 317 |
+
return
|
| 318 |
+
vocab_file = os.path.join(
|
| 319 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 320 |
+
)
|
| 321 |
+
merge_file = os.path.join(
|
| 322 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
| 326 |
+
f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
|
| 327 |
+
|
| 328 |
+
index = 0
|
| 329 |
+
with open(merge_file, "w", encoding="utf-8") as writer:
|
| 330 |
+
for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
|
| 331 |
+
if index != token_index:
|
| 332 |
+
logger.warning(
|
| 333 |
+
f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
|
| 334 |
+
" Please check that the tokenizer is not corrupted!"
|
| 335 |
+
)
|
| 336 |
+
index = token_index
|
| 337 |
+
writer.write(" ".join(bpe_tokens) + "\n")
|
| 338 |
+
index += 1
|
| 339 |
+
|
| 340 |
+
return vocab_file, merge_file
|
| 341 |
+
|
| 342 |
+
def __getstate__(self):
|
| 343 |
+
state = self.__dict__.copy()
|
| 344 |
+
state["sm"] = None
|
| 345 |
+
return state
|
| 346 |
+
|
| 347 |
+
def __setstate__(self, d):
|
| 348 |
+
self.__dict__ = d
|
| 349 |
+
|
| 350 |
+
try:
|
| 351 |
+
import sacremoses
|
| 352 |
+
except ImportError:
|
| 353 |
+
raise ImportError(
|
| 354 |
+
"You need to install sacremoses to use XLMTokenizer. "
|
| 355 |
+
"See https://pypi.org/project/sacremoses/ for installation."
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
self.sm = sacremoses
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
__all__ = ["BioGptTokenizer"]
|
lib/python3.12/site-packages/transformers/models/blenderbot/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_blenderbot import *
|
| 22 |
+
from .modeling_blenderbot import *
|
| 23 |
+
from .modeling_flax_blenderbot import *
|
| 24 |
+
from .modeling_tf_blenderbot import *
|
| 25 |
+
from .tokenization_blenderbot import *
|
| 26 |
+
from .tokenization_blenderbot_fast import *
|
| 27 |
+
else:
|
| 28 |
+
import sys
|
| 29 |
+
|
| 30 |
+
_file = globals()["__file__"]
|
| 31 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (836 Bytes). View file
|
|
|
lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/configuration_blenderbot.cpython-312.pyc
ADDED
|
Binary file (16.5 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/modeling_blenderbot.cpython-312.pyc
ADDED
|
Binary file (75.4 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/modeling_flax_blenderbot.cpython-312.pyc
ADDED
|
Binary file (65.6 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/modeling_tf_blenderbot.cpython-312.pyc
ADDED
|
Binary file (75 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/tokenization_blenderbot.cpython-312.pyc
ADDED
|
Binary file (20.3 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/tokenization_blenderbot_fast.cpython-312.pyc
ADDED
|
Binary file (12 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/blenderbot/configuration_blenderbot.py
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The Facebook, Inc. and The HuggingFace Inc. team. 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 |
+
"""Blenderbot model configuration"""
|
| 16 |
+
|
| 17 |
+
from collections import OrderedDict
|
| 18 |
+
from typing import Any, Mapping, Optional
|
| 19 |
+
|
| 20 |
+
from ... import PreTrainedTokenizer
|
| 21 |
+
from ...configuration_utils import PretrainedConfig
|
| 22 |
+
from ...file_utils import TensorType, is_torch_available
|
| 23 |
+
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeq2SeqConfigWithPast
|
| 24 |
+
from ...onnx.utils import compute_effective_axis_dimension
|
| 25 |
+
from ...utils import logging
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class BlenderbotConfig(PretrainedConfig):
|
| 32 |
+
r"""
|
| 33 |
+
This is the configuration class to store the configuration of a [`BlenderbotModel`]. It is used to instantiate an
|
| 34 |
+
Blenderbot model according to the specified arguments, defining the model architecture. Instantiating a
|
| 35 |
+
configuration with the defaults will yield a similar configuration to that of the Blenderbot
|
| 36 |
+
[facebook/blenderbot-3B](https://huggingface.co/facebook/blenderbot-3B) architecture.
|
| 37 |
+
|
| 38 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 39 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
vocab_size (`int`, *optional*, defaults to 50265):
|
| 44 |
+
Vocabulary size of the Blenderbot model. Defines the number of different tokens that can be represented by
|
| 45 |
+
the `inputs_ids` passed when calling [`BlenderbotModel`] or [`TFBlenderbotModel`].
|
| 46 |
+
d_model (`int`, *optional*, defaults to 1024):
|
| 47 |
+
Dimensionality of the layers and the pooler layer.
|
| 48 |
+
encoder_layers (`int`, *optional*, defaults to 12):
|
| 49 |
+
Number of encoder layers.
|
| 50 |
+
decoder_layers (`int`, *optional*, defaults to 12):
|
| 51 |
+
Number of decoder layers.
|
| 52 |
+
encoder_attention_heads (`int`, *optional*, defaults to 16):
|
| 53 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 54 |
+
decoder_attention_heads (`int`, *optional*, defaults to 16):
|
| 55 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 56 |
+
decoder_ffn_dim (`int`, *optional*, defaults to 4096):
|
| 57 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
|
| 58 |
+
encoder_ffn_dim (`int`, *optional*, defaults to 4096):
|
| 59 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
|
| 60 |
+
activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 61 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 62 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 63 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 64 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 65 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 66 |
+
The dropout ratio for the attention probabilities.
|
| 67 |
+
activation_dropout (`float`, *optional*, defaults to 0.0):
|
| 68 |
+
The dropout ratio for activations inside the fully connected layer.
|
| 69 |
+
max_position_embeddings (`int`, *optional*, defaults to 128):
|
| 70 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 71 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 72 |
+
init_std (`float`, *optional*, defaults to 0.02):
|
| 73 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 74 |
+
encoder_layerdrop (`float`, *optional*, defaults to 0.0):
|
| 75 |
+
The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
|
| 76 |
+
for more details.
|
| 77 |
+
decoder_layerdrop (`float`, *optional*, defaults to 0.0):
|
| 78 |
+
The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
|
| 79 |
+
for more details.
|
| 80 |
+
scale_embedding (`bool`, *optional*, defaults to `False`):
|
| 81 |
+
Scale embeddings by diving by sqrt(d_model).
|
| 82 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 83 |
+
Whether or not the model should return the last key/values attentions (not used by all models)
|
| 84 |
+
forced_eos_token_id (`int`, *optional*, defaults to 2):
|
| 85 |
+
The id of the token to force as the last generated token when `max_length` is reached. Usually set to
|
| 86 |
+
`eos_token_id`.
|
| 87 |
+
|
| 88 |
+
Example:
|
| 89 |
+
|
| 90 |
+
```python
|
| 91 |
+
>>> from transformers import BlenderbotConfig, BlenderbotModel
|
| 92 |
+
|
| 93 |
+
>>> # Initializing a Blenderbot facebook/blenderbot-3B style configuration
|
| 94 |
+
>>> configuration = BlenderbotConfig()
|
| 95 |
+
|
| 96 |
+
>>> # Initializing a model (with random weights) from the facebook/blenderbot-3B style configuration
|
| 97 |
+
>>> model = BlenderbotModel(configuration)
|
| 98 |
+
|
| 99 |
+
>>> # Accessing the model configuration
|
| 100 |
+
>>> configuration = model.config
|
| 101 |
+
```"""
|
| 102 |
+
|
| 103 |
+
model_type = "blenderbot"
|
| 104 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 105 |
+
attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
|
| 106 |
+
|
| 107 |
+
def __init__(
|
| 108 |
+
self,
|
| 109 |
+
vocab_size=8008,
|
| 110 |
+
max_position_embeddings=128,
|
| 111 |
+
encoder_layers=2,
|
| 112 |
+
encoder_ffn_dim=10240,
|
| 113 |
+
encoder_attention_heads=32,
|
| 114 |
+
decoder_layers=24,
|
| 115 |
+
decoder_ffn_dim=10240,
|
| 116 |
+
decoder_attention_heads=32,
|
| 117 |
+
encoder_layerdrop=0.0,
|
| 118 |
+
decoder_layerdrop=0.0,
|
| 119 |
+
use_cache=True,
|
| 120 |
+
is_encoder_decoder=True,
|
| 121 |
+
activation_function="gelu",
|
| 122 |
+
d_model=2560,
|
| 123 |
+
dropout=0.1,
|
| 124 |
+
attention_dropout=0.0,
|
| 125 |
+
activation_dropout=0.0,
|
| 126 |
+
init_std=0.02,
|
| 127 |
+
decoder_start_token_id=1,
|
| 128 |
+
scale_embedding=False,
|
| 129 |
+
pad_token_id=0,
|
| 130 |
+
bos_token_id=1,
|
| 131 |
+
eos_token_id=2,
|
| 132 |
+
encoder_no_repeat_ngram_size=3,
|
| 133 |
+
forced_eos_token_id=2,
|
| 134 |
+
**kwargs,
|
| 135 |
+
):
|
| 136 |
+
self.vocab_size = vocab_size
|
| 137 |
+
self.max_position_embeddings = max_position_embeddings
|
| 138 |
+
self.d_model = d_model
|
| 139 |
+
self.encoder_ffn_dim = encoder_ffn_dim
|
| 140 |
+
self.encoder_layers = encoder_layers
|
| 141 |
+
self.encoder_attention_heads = encoder_attention_heads
|
| 142 |
+
self.decoder_ffn_dim = decoder_ffn_dim
|
| 143 |
+
self.decoder_layers = decoder_layers
|
| 144 |
+
self.decoder_attention_heads = decoder_attention_heads
|
| 145 |
+
self.dropout = dropout
|
| 146 |
+
self.attention_dropout = attention_dropout
|
| 147 |
+
self.activation_dropout = activation_dropout
|
| 148 |
+
self.activation_function = activation_function
|
| 149 |
+
self.init_std = init_std
|
| 150 |
+
self.encoder_layerdrop = encoder_layerdrop
|
| 151 |
+
self.decoder_layerdrop = decoder_layerdrop
|
| 152 |
+
self.use_cache = use_cache
|
| 153 |
+
self.num_hidden_layers = encoder_layers
|
| 154 |
+
self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
|
| 155 |
+
|
| 156 |
+
super().__init__(
|
| 157 |
+
pad_token_id=pad_token_id,
|
| 158 |
+
bos_token_id=bos_token_id,
|
| 159 |
+
eos_token_id=eos_token_id,
|
| 160 |
+
is_encoder_decoder=is_encoder_decoder,
|
| 161 |
+
decoder_start_token_id=decoder_start_token_id,
|
| 162 |
+
encoder_no_repeat_ngram_size=encoder_no_repeat_ngram_size,
|
| 163 |
+
forced_eos_token_id=forced_eos_token_id,
|
| 164 |
+
**kwargs,
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class BlenderbotOnnxConfig(OnnxSeq2SeqConfigWithPast):
|
| 169 |
+
@property
|
| 170 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 171 |
+
if self.task in ["default", "seq2seq-lm"]:
|
| 172 |
+
common_inputs = OrderedDict(
|
| 173 |
+
[
|
| 174 |
+
("input_ids", {0: "batch", 1: "encoder_sequence"}),
|
| 175 |
+
("attention_mask", {0: "batch", 1: "encoder_sequence"}),
|
| 176 |
+
]
|
| 177 |
+
)
|
| 178 |
+
if self.use_past:
|
| 179 |
+
common_inputs["decoder_input_ids"] = {0: "batch"}
|
| 180 |
+
common_inputs["decoder_attention_mask"] = {0: "batch", 1: "past_decoder_sequence + sequence"}
|
| 181 |
+
else:
|
| 182 |
+
common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"}
|
| 183 |
+
common_inputs["decoder_attention_mask"] = {0: "batch", 1: "decoder_sequence"}
|
| 184 |
+
if self.use_past:
|
| 185 |
+
self.fill_with_past_key_values_(common_inputs, direction="inputs")
|
| 186 |
+
elif self.task == "causal-lm":
|
| 187 |
+
common_inputs = OrderedDict(
|
| 188 |
+
[
|
| 189 |
+
("input_ids", {0: "batch", 1: "encoder_sequence"}),
|
| 190 |
+
("attention_mask", {0: "batch", 1: "encoder_sequence"}),
|
| 191 |
+
]
|
| 192 |
+
)
|
| 193 |
+
if self.use_past:
|
| 194 |
+
_, num_decoder_layers = self.num_layers
|
| 195 |
+
for i in range(num_decoder_layers):
|
| 196 |
+
common_inputs[f"past_key_values.{i}.key"] = {0: "batch", 2: "past_sequence + sequence"}
|
| 197 |
+
common_inputs[f"past_key_values.{i}.value"] = {0: "batch", 2: "past_sequence + sequence"}
|
| 198 |
+
else:
|
| 199 |
+
common_inputs = OrderedDict(
|
| 200 |
+
[
|
| 201 |
+
("input_ids", {0: "batch", 1: "encoder_sequence"}),
|
| 202 |
+
("attention_mask", {0: "batch", 1: "encoder_sequence"}),
|
| 203 |
+
("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}),
|
| 204 |
+
("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}),
|
| 205 |
+
]
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
return common_inputs
|
| 209 |
+
|
| 210 |
+
@property
|
| 211 |
+
# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
|
| 212 |
+
def outputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 213 |
+
if self.task in ["default", "seq2seq-lm"]:
|
| 214 |
+
common_outputs = super().outputs
|
| 215 |
+
else:
|
| 216 |
+
common_outputs = super(OnnxConfigWithPast, self).outputs
|
| 217 |
+
if self.use_past:
|
| 218 |
+
num_encoder_layers, _ = self.num_layers
|
| 219 |
+
for i in range(num_encoder_layers):
|
| 220 |
+
common_outputs[f"present.{i}.key"] = {0: "batch", 2: "past_sequence + sequence"}
|
| 221 |
+
common_outputs[f"present.{i}.value"] = {0: "batch", 2: "past_sequence + sequence"}
|
| 222 |
+
return common_outputs
|
| 223 |
+
|
| 224 |
+
def _generate_dummy_inputs_for_default_and_seq2seq_lm(
|
| 225 |
+
self,
|
| 226 |
+
tokenizer: PreTrainedTokenizer,
|
| 227 |
+
batch_size: int = -1,
|
| 228 |
+
seq_length: int = -1,
|
| 229 |
+
is_pair: bool = False,
|
| 230 |
+
framework: Optional[TensorType] = None,
|
| 231 |
+
) -> Mapping[str, Any]:
|
| 232 |
+
encoder_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
|
| 233 |
+
tokenizer, batch_size, seq_length, is_pair, framework
|
| 234 |
+
)
|
| 235 |
+
# Generate decoder inputs
|
| 236 |
+
decoder_seq_length = seq_length if not self.use_past else 1
|
| 237 |
+
decoder_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
|
| 238 |
+
tokenizer, batch_size, decoder_seq_length, is_pair, framework
|
| 239 |
+
)
|
| 240 |
+
decoder_inputs = {f"decoder_{name}": tensor for name, tensor in decoder_inputs.items()}
|
| 241 |
+
common_inputs = dict(**encoder_inputs, **decoder_inputs)
|
| 242 |
+
|
| 243 |
+
if self.use_past:
|
| 244 |
+
if not is_torch_available():
|
| 245 |
+
raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
|
| 246 |
+
else:
|
| 247 |
+
import torch
|
| 248 |
+
batch, encoder_seq_length = common_inputs["input_ids"].shape
|
| 249 |
+
decoder_seq_length = common_inputs["decoder_input_ids"].shape[1]
|
| 250 |
+
num_encoder_attention_heads, num_decoder_attention_heads = self.num_attention_heads
|
| 251 |
+
encoder_shape = (
|
| 252 |
+
batch,
|
| 253 |
+
num_encoder_attention_heads,
|
| 254 |
+
encoder_seq_length,
|
| 255 |
+
self._config.hidden_size // num_encoder_attention_heads,
|
| 256 |
+
)
|
| 257 |
+
decoder_past_length = decoder_seq_length
|
| 258 |
+
decoder_shape = (
|
| 259 |
+
batch,
|
| 260 |
+
num_decoder_attention_heads,
|
| 261 |
+
decoder_past_length,
|
| 262 |
+
self._config.hidden_size // num_decoder_attention_heads,
|
| 263 |
+
)
|
| 264 |
+
common_inputs["decoder_attention_mask"] = torch.cat(
|
| 265 |
+
[common_inputs["decoder_attention_mask"], torch.ones(batch, decoder_past_length)], dim=1
|
| 266 |
+
)
|
| 267 |
+
common_inputs["past_key_values"] = []
|
| 268 |
+
_, num_decoder_layers = self.num_layers
|
| 269 |
+
|
| 270 |
+
for _ in range(num_decoder_layers):
|
| 271 |
+
common_inputs["past_key_values"].append(
|
| 272 |
+
(
|
| 273 |
+
torch.zeros(decoder_shape),
|
| 274 |
+
torch.zeros(decoder_shape),
|
| 275 |
+
torch.zeros(encoder_shape),
|
| 276 |
+
torch.zeros(encoder_shape),
|
| 277 |
+
)
|
| 278 |
+
)
|
| 279 |
+
return common_inputs
|
| 280 |
+
|
| 281 |
+
def _generate_dummy_inputs_for_causal_lm(
|
| 282 |
+
self,
|
| 283 |
+
tokenizer: PreTrainedTokenizer,
|
| 284 |
+
batch_size: int = -1,
|
| 285 |
+
seq_length: int = -1,
|
| 286 |
+
is_pair: bool = False,
|
| 287 |
+
framework: Optional[TensorType] = None,
|
| 288 |
+
) -> Mapping[str, Any]:
|
| 289 |
+
common_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
|
| 290 |
+
tokenizer, batch_size, seq_length, is_pair, framework
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
if self.use_past:
|
| 294 |
+
if not is_torch_available():
|
| 295 |
+
raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
|
| 296 |
+
else:
|
| 297 |
+
import torch
|
| 298 |
+
batch, seqlen = common_inputs["input_ids"].shape
|
| 299 |
+
past_key_values_length = seqlen
|
| 300 |
+
_, num_decoder_layers = self.num_layers
|
| 301 |
+
num_encoder_attention_heads, _ = self.num_attention_heads
|
| 302 |
+
past_shape = (
|
| 303 |
+
batch,
|
| 304 |
+
num_encoder_attention_heads,
|
| 305 |
+
past_key_values_length,
|
| 306 |
+
self._config.hidden_size // num_encoder_attention_heads,
|
| 307 |
+
)
|
| 308 |
+
mask_dtype = common_inputs["attention_mask"].dtype
|
| 309 |
+
common_inputs["attention_mask"] = torch.cat(
|
| 310 |
+
[common_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
|
| 311 |
+
)
|
| 312 |
+
common_inputs["past_key_values"] = [
|
| 313 |
+
(torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(num_decoder_layers)
|
| 314 |
+
]
|
| 315 |
+
return common_inputs
|
| 316 |
+
|
| 317 |
+
# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig._generate_dummy_inputs_for_sequence_classification_and_question_answering
|
| 318 |
+
def _generate_dummy_inputs_for_sequence_classification_and_question_answering(
|
| 319 |
+
self,
|
| 320 |
+
tokenizer: PreTrainedTokenizer,
|
| 321 |
+
batch_size: int = -1,
|
| 322 |
+
seq_length: int = -1,
|
| 323 |
+
is_pair: bool = False,
|
| 324 |
+
framework: Optional[TensorType] = None,
|
| 325 |
+
) -> Mapping[str, Any]:
|
| 326 |
+
# Copied from OnnxConfig.generate_dummy_inputs
|
| 327 |
+
# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
|
| 328 |
+
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
|
| 329 |
+
batch_size = compute_effective_axis_dimension(
|
| 330 |
+
batch_size, fixed_dimension=OnnxConfig.default_fixed_batch, num_token_to_add=0
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
|
| 334 |
+
token_to_add = tokenizer.num_special_tokens_to_add(is_pair)
|
| 335 |
+
seq_length = compute_effective_axis_dimension(
|
| 336 |
+
seq_length, fixed_dimension=OnnxConfig.default_fixed_sequence, num_token_to_add=token_to_add
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
# Generate dummy inputs according to compute batch and sequence
|
| 340 |
+
dummy_input = [" ".join([tokenizer.unk_token]) * seq_length] * batch_size
|
| 341 |
+
common_inputs = dict(tokenizer(dummy_input, return_tensors=framework))
|
| 342 |
+
return common_inputs
|
| 343 |
+
|
| 344 |
+
# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.generate_dummy_inputs
|
| 345 |
+
def generate_dummy_inputs(
|
| 346 |
+
self,
|
| 347 |
+
tokenizer: PreTrainedTokenizer,
|
| 348 |
+
batch_size: int = -1,
|
| 349 |
+
seq_length: int = -1,
|
| 350 |
+
is_pair: bool = False,
|
| 351 |
+
framework: Optional[TensorType] = None,
|
| 352 |
+
) -> Mapping[str, Any]:
|
| 353 |
+
if self.task in ["default", "seq2seq-lm"]:
|
| 354 |
+
common_inputs = self._generate_dummy_inputs_for_default_and_seq2seq_lm(
|
| 355 |
+
tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
elif self.task == "causal-lm":
|
| 359 |
+
common_inputs = self._generate_dummy_inputs_for_causal_lm(
|
| 360 |
+
tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
|
| 361 |
+
)
|
| 362 |
+
else:
|
| 363 |
+
common_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
|
| 364 |
+
tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
return common_inputs
|
| 368 |
+
|
| 369 |
+
# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig._flatten_past_key_values_
|
| 370 |
+
def _flatten_past_key_values_(self, flattened_output, name, idx, t):
|
| 371 |
+
if self.task in ["default", "seq2seq-lm"]:
|
| 372 |
+
flattened_output = super()._flatten_past_key_values_(flattened_output, name, idx, t)
|
| 373 |
+
else:
|
| 374 |
+
flattened_output = super(OnnxSeq2SeqConfigWithPast, self)._flatten_past_key_values_(
|
| 375 |
+
flattened_output, name, idx, t
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
def fill_with_past_key_values_(self, inputs_or_outputs: Mapping[str, Mapping[int, str]], direction: str):
|
| 379 |
+
if direction not in ["inputs", "outputs"]:
|
| 380 |
+
raise ValueError(f'direction must either be "inputs" or "outputs", but {direction} was given')
|
| 381 |
+
|
| 382 |
+
name = "past_key_values" if direction == "inputs" else "present"
|
| 383 |
+
_, num_decoder_layers = self.num_layers
|
| 384 |
+
|
| 385 |
+
encoder_sequence = "past_encoder_sequence"
|
| 386 |
+
decoder_sequence = "past_decoder_sequence" if direction == "inputs" else "past_decoder_sequence + sequence"
|
| 387 |
+
|
| 388 |
+
for i in range(num_decoder_layers):
|
| 389 |
+
inputs_or_outputs[f"{name}.{i}.decoder.key"] = {0: "batch", 2: decoder_sequence}
|
| 390 |
+
inputs_or_outputs[f"{name}.{i}.decoder.value"] = {0: "batch", 2: decoder_sequence}
|
| 391 |
+
inputs_or_outputs[f"{name}.{i}.encoder.key"] = {0: "batch", 2: encoder_sequence}
|
| 392 |
+
inputs_or_outputs[f"{name}.{i}.encoder.value"] = {0: "batch", 2: encoder_sequence}
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
__all__ = ["BlenderbotConfig", "BlenderbotOnnxConfig"]
|
lib/python3.12/site-packages/transformers/models/blender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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The Facebook, Inc. and The HuggingFace Inc. team. 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 |
+
"""PyTorch Blenderbot model."""
|
| 16 |
+
|
| 17 |
+
import copy
|
| 18 |
+
import math
|
| 19 |
+
import os
|
| 20 |
+
import warnings
|
| 21 |
+
from typing import List, Optional, Tuple, Union
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
import torch.utils.checkpoint
|
| 25 |
+
from torch import nn
|
| 26 |
+
from torch.nn import CrossEntropyLoss
|
| 27 |
+
|
| 28 |
+
from ...activations import ACT2FN
|
| 29 |
+
from ...generation import GenerationMixin
|
| 30 |
+
from ...modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask
|
| 31 |
+
from ...modeling_outputs import (
|
| 32 |
+
BaseModelOutput,
|
| 33 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 34 |
+
CausalLMOutputWithCrossAttentions,
|
| 35 |
+
Seq2SeqLMOutput,
|
| 36 |
+
Seq2SeqModelOutput,
|
| 37 |
+
)
|
| 38 |
+
from ...modeling_utils import PreTrainedModel
|
| 39 |
+
from ...utils import (
|
| 40 |
+
add_end_docstrings,
|
| 41 |
+
add_start_docstrings,
|
| 42 |
+
add_start_docstrings_to_model_forward,
|
| 43 |
+
logging,
|
| 44 |
+
replace_return_docstrings,
|
| 45 |
+
)
|
| 46 |
+
from ..blenderbot_small import BlenderbotSmallForConditionalGeneration, BlenderbotSmallModel
|
| 47 |
+
from .configuration_blenderbot import BlenderbotConfig
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
logger = logging.get_logger(__name__)
|
| 51 |
+
|
| 52 |
+
_CONFIG_FOR_DOC = "BlenderbotConfig"
|
| 53 |
+
_CHECKPOINT_FOR_DOC = "facebook/blenderbot-400M-distill"
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# Copied from transformers.models.bart.modeling_bart.shift_tokens_right
|
| 57 |
+
def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
|
| 58 |
+
"""
|
| 59 |
+
Shift input ids one token to the right.
|
| 60 |
+
"""
|
| 61 |
+
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
|
| 62 |
+
shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
|
| 63 |
+
shifted_input_ids[:, 0] = decoder_start_token_id
|
| 64 |
+
|
| 65 |
+
if pad_token_id is None:
|
| 66 |
+
raise ValueError("self.model.config.pad_token_id has to be defined.")
|
| 67 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 68 |
+
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
|
| 69 |
+
|
| 70 |
+
return shifted_input_ids
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class BlenderbotLearnedPositionalEmbedding(nn.Embedding):
|
| 74 |
+
"""
|
| 75 |
+
This module learns positional embeddings up to a fixed maximum size.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
def __init__(self, num_embeddings: int, embedding_dim: int):
|
| 79 |
+
super().__init__(num_embeddings, embedding_dim)
|
| 80 |
+
|
| 81 |
+
def forward(self, input_ids_shape: torch.Size, past_key_values_length: int = 0):
|
| 82 |
+
"""`input_ids_shape` is expected to be [bsz x seqlen]."""
|
| 83 |
+
bsz, seq_len = input_ids_shape[:2]
|
| 84 |
+
positions = torch.arange(
|
| 85 |
+
past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
|
| 86 |
+
)
|
| 87 |
+
return super().forward(positions)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
# Copied from transformers.models.bart.modeling_bart.BartScaledWordEmbedding with Bart->Blenderbot
|
| 91 |
+
class BlenderbotScaledWordEmbedding(nn.Embedding):
|
| 92 |
+
"""
|
| 93 |
+
This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: Optional[float] = 1.0):
|
| 97 |
+
super().__init__(num_embeddings, embedding_dim, padding_idx)
|
| 98 |
+
self.embed_scale = embed_scale
|
| 99 |
+
|
| 100 |
+
def forward(self, input_ids: torch.Tensor):
|
| 101 |
+
return super().forward(input_ids) * self.embed_scale
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
# Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->Blenderbot
|
| 105 |
+
class BlenderbotAttention(nn.Module):
|
| 106 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 107 |
+
|
| 108 |
+
def __init__(
|
| 109 |
+
self,
|
| 110 |
+
embed_dim: int,
|
| 111 |
+
num_heads: int,
|
| 112 |
+
dropout: float = 0.0,
|
| 113 |
+
is_decoder: bool = False,
|
| 114 |
+
bias: bool = True,
|
| 115 |
+
is_causal: bool = False,
|
| 116 |
+
config: Optional[BlenderbotConfig] = None,
|
| 117 |
+
):
|
| 118 |
+
super().__init__()
|
| 119 |
+
self.embed_dim = embed_dim
|
| 120 |
+
self.num_heads = num_heads
|
| 121 |
+
self.dropout = dropout
|
| 122 |
+
self.head_dim = embed_dim // num_heads
|
| 123 |
+
self.config = config
|
| 124 |
+
|
| 125 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 126 |
+
raise ValueError(
|
| 127 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 128 |
+
f" and `num_heads`: {num_heads})."
|
| 129 |
+
)
|
| 130 |
+
self.scaling = self.head_dim**-0.5
|
| 131 |
+
self.is_decoder = is_decoder
|
| 132 |
+
self.is_causal = is_causal
|
| 133 |
+
|
| 134 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 135 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 136 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 137 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 138 |
+
|
| 139 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 140 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 141 |
+
|
| 142 |
+
def forward(
|
| 143 |
+
self,
|
| 144 |
+
hidden_states: torch.Tensor,
|
| 145 |
+
key_value_states: Optional[torch.Tensor] = None,
|
| 146 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 147 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 148 |
+
layer_head_mask: Optional[torch.Tensor] = None,
|
| 149 |
+
output_attentions: bool = False,
|
| 150 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 151 |
+
"""Input shape: Batch x Time x Channel"""
|
| 152 |
+
|
| 153 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 154 |
+
# for the decoder
|
| 155 |
+
is_cross_attention = key_value_states is not None
|
| 156 |
+
|
| 157 |
+
bsz, tgt_len, _ = hidden_states.size()
|
| 158 |
+
|
| 159 |
+
# get query proj
|
| 160 |
+
query_states = self.q_proj(hidden_states) * self.scaling
|
| 161 |
+
# get key, value proj
|
| 162 |
+
# `past_key_value[0].shape[2] == key_value_states.shape[1]`
|
| 163 |
+
# is checking that the `sequence_length` of the `past_key_value` is the same as
|
| 164 |
+
# the provided `key_value_states` to support prefix tuning
|
| 165 |
+
if (
|
| 166 |
+
is_cross_attention
|
| 167 |
+
and past_key_value is not None
|
| 168 |
+
and past_key_value[0].shape[2] == key_value_states.shape[1]
|
| 169 |
+
):
|
| 170 |
+
# reuse k,v, cross_attentions
|
| 171 |
+
key_states = past_key_value[0]
|
| 172 |
+
value_states = past_key_value[1]
|
| 173 |
+
elif is_cross_attention:
|
| 174 |
+
# cross_attentions
|
| 175 |
+
key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
|
| 176 |
+
value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
|
| 177 |
+
elif past_key_value is not None:
|
| 178 |
+
# reuse k, v, self_attention
|
| 179 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 180 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 181 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
| 182 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
| 183 |
+
else:
|
| 184 |
+
# self_attention
|
| 185 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 186 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 187 |
+
|
| 188 |
+
if self.is_decoder:
|
| 189 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 190 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 191 |
+
# key/value_states (first "if" case)
|
| 192 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 193 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 194 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 195 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 196 |
+
past_key_value = (key_states, value_states)
|
| 197 |
+
|
| 198 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 199 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
| 200 |
+
key_states = key_states.reshape(*proj_shape)
|
| 201 |
+
value_states = value_states.reshape(*proj_shape)
|
| 202 |
+
|
| 203 |
+
src_len = key_states.size(1)
|
| 204 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
| 205 |
+
|
| 206 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
| 207 |
+
raise ValueError(
|
| 208 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 209 |
+
f" {attn_weights.size()}"
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
if attention_mask is not None:
|
| 213 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 214 |
+
raise ValueError(
|
| 215 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
| 216 |
+
)
|
| 217 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
| 218 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 219 |
+
|
| 220 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 221 |
+
|
| 222 |
+
if layer_head_mask is not None:
|
| 223 |
+
if layer_head_mask.size() != (self.num_heads,):
|
| 224 |
+
raise ValueError(
|
| 225 |
+
f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
|
| 226 |
+
f" {layer_head_mask.size()}"
|
| 227 |
+
)
|
| 228 |
+
attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 229 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 230 |
+
|
| 231 |
+
if output_attentions:
|
| 232 |
+
# this operation is a bit awkward, but it's required to
|
| 233 |
+
# make sure that attn_weights keeps its gradient.
|
| 234 |
+
# In order to do so, attn_weights have to be reshaped
|
| 235 |
+
# twice and have to be reused in the following
|
| 236 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 237 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
| 238 |
+
else:
|
| 239 |
+
attn_weights_reshaped = None
|
| 240 |
+
|
| 241 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 242 |
+
|
| 243 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
| 244 |
+
|
| 245 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
| 246 |
+
raise ValueError(
|
| 247 |
+
f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 248 |
+
f" {attn_output.size()}"
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
| 252 |
+
attn_output = attn_output.transpose(1, 2)
|
| 253 |
+
|
| 254 |
+
# Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
|
| 255 |
+
# partitioned across GPUs when using tensor-parallelism.
|
| 256 |
+
attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
|
| 257 |
+
|
| 258 |
+
attn_output = self.out_proj(attn_output)
|
| 259 |
+
|
| 260 |
+
return attn_output, attn_weights_reshaped, past_key_value
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
BLENDERBOT_ATTENTION_CLASSES = {"eager": BlenderbotAttention}
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
# Copied from transformers.models.mbart.modeling_mbart.MBartEncoderLayer with MBart->Blenderbot, MBART->BLENDERBOT
|
| 267 |
+
class BlenderbotEncoderLayer(nn.Module):
|
| 268 |
+
def __init__(self, config: BlenderbotConfig):
|
| 269 |
+
super().__init__()
|
| 270 |
+
self.embed_dim = config.d_model
|
| 271 |
+
|
| 272 |
+
self.self_attn = BLENDERBOT_ATTENTION_CLASSES[config._attn_implementation](
|
| 273 |
+
embed_dim=self.embed_dim,
|
| 274 |
+
num_heads=config.encoder_attention_heads,
|
| 275 |
+
dropout=config.attention_dropout,
|
| 276 |
+
config=config,
|
| 277 |
+
)
|
| 278 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 279 |
+
self.dropout = config.dropout
|
| 280 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 281 |
+
self.activation_dropout = config.activation_dropout
|
| 282 |
+
self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
|
| 283 |
+
self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
|
| 284 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 285 |
+
|
| 286 |
+
def forward(
|
| 287 |
+
self,
|
| 288 |
+
hidden_states: torch.Tensor,
|
| 289 |
+
attention_mask: torch.Tensor,
|
| 290 |
+
layer_head_mask: torch.Tensor,
|
| 291 |
+
output_attentions: bool = False,
|
| 292 |
+
) -> torch.Tensor:
|
| 293 |
+
"""
|
| 294 |
+
Args:
|
| 295 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 296 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 297 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 298 |
+
layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
|
| 299 |
+
`(encoder_attention_heads,)`.
|
| 300 |
+
output_attentions (`bool`, *optional*):
|
| 301 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 302 |
+
returned tensors for more detail.
|
| 303 |
+
"""
|
| 304 |
+
residual = hidden_states
|
| 305 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 306 |
+
hidden_states, attn_weights, _ = self.self_attn(
|
| 307 |
+
hidden_states=hidden_states,
|
| 308 |
+
attention_mask=attention_mask,
|
| 309 |
+
layer_head_mask=layer_head_mask,
|
| 310 |
+
output_attentions=output_attentions,
|
| 311 |
+
)
|
| 312 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 313 |
+
hidden_states = residual + hidden_states
|
| 314 |
+
|
| 315 |
+
residual = hidden_states
|
| 316 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 317 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 318 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 319 |
+
hidden_states = self.fc2(hidden_states)
|
| 320 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 321 |
+
hidden_states = residual + hidden_states
|
| 322 |
+
|
| 323 |
+
if hidden_states.dtype == torch.float16:
|
| 324 |
+
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
|
| 325 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
| 326 |
+
|
| 327 |
+
outputs = (hidden_states,)
|
| 328 |
+
|
| 329 |
+
if output_attentions:
|
| 330 |
+
outputs += (attn_weights,)
|
| 331 |
+
|
| 332 |
+
return outputs
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
# Copied from transformers.models.mbart.modeling_mbart.MBartDecoderLayer with MBart->Blenderbot, MBART->BLENDERBOT
|
| 336 |
+
class BlenderbotDecoderLayer(nn.Module):
|
| 337 |
+
def __init__(self, config: BlenderbotConfig):
|
| 338 |
+
super().__init__()
|
| 339 |
+
self.embed_dim = config.d_model
|
| 340 |
+
|
| 341 |
+
self.self_attn = BLENDERBOT_ATTENTION_CLASSES[config._attn_implementation](
|
| 342 |
+
embed_dim=self.embed_dim,
|
| 343 |
+
num_heads=config.decoder_attention_heads,
|
| 344 |
+
dropout=config.attention_dropout,
|
| 345 |
+
is_decoder=True,
|
| 346 |
+
is_causal=True,
|
| 347 |
+
config=config,
|
| 348 |
+
)
|
| 349 |
+
self.dropout = config.dropout
|
| 350 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 351 |
+
self.activation_dropout = config.activation_dropout
|
| 352 |
+
|
| 353 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 354 |
+
self.encoder_attn = BLENDERBOT_ATTENTION_CLASSES[config._attn_implementation](
|
| 355 |
+
self.embed_dim,
|
| 356 |
+
config.decoder_attention_heads,
|
| 357 |
+
dropout=config.attention_dropout,
|
| 358 |
+
is_decoder=True,
|
| 359 |
+
config=config,
|
| 360 |
+
)
|
| 361 |
+
self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 362 |
+
self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
|
| 363 |
+
self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
|
| 364 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 365 |
+
|
| 366 |
+
def forward(
|
| 367 |
+
self,
|
| 368 |
+
hidden_states: torch.Tensor,
|
| 369 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 370 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 371 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 372 |
+
layer_head_mask: Optional[torch.Tensor] = None,
|
| 373 |
+
cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
|
| 374 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 375 |
+
output_attentions: Optional[bool] = False,
|
| 376 |
+
use_cache: Optional[bool] = True,
|
| 377 |
+
) -> torch.Tensor:
|
| 378 |
+
"""
|
| 379 |
+
Args:
|
| 380 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 381 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 382 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 383 |
+
encoder_hidden_states (`torch.FloatTensor`):
|
| 384 |
+
cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 385 |
+
encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
|
| 386 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 387 |
+
layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
|
| 388 |
+
`(encoder_attention_heads,)`.
|
| 389 |
+
cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
|
| 390 |
+
size `(decoder_attention_heads,)`.
|
| 391 |
+
past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
|
| 392 |
+
output_attentions (`bool`, *optional*):
|
| 393 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 394 |
+
returned tensors for more detail.
|
| 395 |
+
"""
|
| 396 |
+
residual = hidden_states
|
| 397 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 398 |
+
|
| 399 |
+
# Self Attention
|
| 400 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 401 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 402 |
+
# add present self-attn cache to positions 1,2 of present_key_value tuple
|
| 403 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 404 |
+
hidden_states=hidden_states,
|
| 405 |
+
past_key_value=self_attn_past_key_value,
|
| 406 |
+
attention_mask=attention_mask,
|
| 407 |
+
layer_head_mask=layer_head_mask,
|
| 408 |
+
output_attentions=output_attentions,
|
| 409 |
+
)
|
| 410 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 411 |
+
hidden_states = residual + hidden_states
|
| 412 |
+
|
| 413 |
+
# Cross-Attention Block
|
| 414 |
+
cross_attn_present_key_value = None
|
| 415 |
+
cross_attn_weights = None
|
| 416 |
+
if encoder_hidden_states is not None:
|
| 417 |
+
residual = hidden_states
|
| 418 |
+
hidden_states = self.encoder_attn_layer_norm(hidden_states)
|
| 419 |
+
|
| 420 |
+
# cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
|
| 421 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 422 |
+
hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
|
| 423 |
+
hidden_states=hidden_states,
|
| 424 |
+
key_value_states=encoder_hidden_states,
|
| 425 |
+
attention_mask=encoder_attention_mask,
|
| 426 |
+
layer_head_mask=cross_attn_layer_head_mask,
|
| 427 |
+
past_key_value=cross_attn_past_key_value,
|
| 428 |
+
output_attentions=output_attentions,
|
| 429 |
+
)
|
| 430 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 431 |
+
hidden_states = residual + hidden_states
|
| 432 |
+
|
| 433 |
+
# add cross-attn to positions 3,4 of present_key_value tuple
|
| 434 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 435 |
+
|
| 436 |
+
# Fully Connected
|
| 437 |
+
residual = hidden_states
|
| 438 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 439 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 440 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 441 |
+
hidden_states = self.fc2(hidden_states)
|
| 442 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 443 |
+
hidden_states = residual + hidden_states
|
| 444 |
+
|
| 445 |
+
outputs = (hidden_states,)
|
| 446 |
+
|
| 447 |
+
if output_attentions:
|
| 448 |
+
outputs += (self_attn_weights, cross_attn_weights)
|
| 449 |
+
|
| 450 |
+
if use_cache:
|
| 451 |
+
outputs += (present_key_value,)
|
| 452 |
+
|
| 453 |
+
return outputs
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
class BlenderbotPreTrainedModel(PreTrainedModel):
|
| 457 |
+
config_class = BlenderbotConfig
|
| 458 |
+
base_model_prefix = "model"
|
| 459 |
+
supports_gradient_checkpointing = True
|
| 460 |
+
|
| 461 |
+
def _init_weights(self, module):
|
| 462 |
+
std = self.config.init_std
|
| 463 |
+
if isinstance(module, nn.Linear):
|
| 464 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 465 |
+
if module.bias is not None:
|
| 466 |
+
module.bias.data.zero_()
|
| 467 |
+
elif isinstance(module, nn.Embedding):
|
| 468 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 469 |
+
if module.padding_idx is not None:
|
| 470 |
+
module.weight.data[module.padding_idx].zero_()
|
| 471 |
+
|
| 472 |
+
@property
|
| 473 |
+
def dummy_inputs(self):
|
| 474 |
+
pad_token = self.config.pad_token_id
|
| 475 |
+
input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
|
| 476 |
+
dummy_inputs = {
|
| 477 |
+
"attention_mask": input_ids.ne(pad_token),
|
| 478 |
+
"input_ids": input_ids,
|
| 479 |
+
"decoder_input_ids": input_ids,
|
| 480 |
+
}
|
| 481 |
+
return dummy_inputs
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
BLENDERBOT_START_DOCSTRING = r"""
|
| 485 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 486 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 487 |
+
etc.)
|
| 488 |
+
|
| 489 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 490 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 491 |
+
and behavior.
|
| 492 |
+
|
| 493 |
+
Parameters:
|
| 494 |
+
config ([`BlenderbotConfig`]):
|
| 495 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 496 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 497 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 498 |
+
"""
|
| 499 |
+
|
| 500 |
+
BLENDERBOT_GENERATION_EXAMPLE = r"""
|
| 501 |
+
Conversation example:
|
| 502 |
+
|
| 503 |
+
```python
|
| 504 |
+
>>> from transformers import AutoTokenizer, BlenderbotForConditionalGeneration
|
| 505 |
+
|
| 506 |
+
>>> mname = "facebook/blenderbot-400M-distill"
|
| 507 |
+
>>> model = BlenderbotForConditionalGeneration.from_pretrained(mname)
|
| 508 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(mname)
|
| 509 |
+
>>> UTTERANCE = "My friends are cool but they eat too many carbs."
|
| 510 |
+
>>> print("Human: ", UTTERANCE)
|
| 511 |
+
Human: My friends are cool but they eat too many carbs.
|
| 512 |
+
|
| 513 |
+
>>> inputs = tokenizer([UTTERANCE], return_tensors="pt")
|
| 514 |
+
>>> reply_ids = model.generate(**inputs)
|
| 515 |
+
>>> print("Bot: ", tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0])
|
| 516 |
+
Bot: That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?
|
| 517 |
+
|
| 518 |
+
>>> REPLY = "I'm not sure"
|
| 519 |
+
>>> print("Human: ", REPLY)
|
| 520 |
+
Human: I'm not sure
|
| 521 |
+
|
| 522 |
+
>>> NEXT_UTTERANCE = (
|
| 523 |
+
... "My friends are cool but they eat too many carbs.</s> <s>That's unfortunate. "
|
| 524 |
+
... "Are they trying to lose weight or are they just trying to be healthier?</s> "
|
| 525 |
+
... "<s> I'm not sure."
|
| 526 |
+
... )
|
| 527 |
+
>>> inputs = tokenizer([NEXT_UTTERANCE], return_tensors="pt")
|
| 528 |
+
>>> next_reply_ids = model.generate(**inputs)
|
| 529 |
+
>>> print("Bot: ", tokenizer.batch_decode(next_reply_ids, skip_special_tokens=True)[0])
|
| 530 |
+
Bot: I see. Well, it's good that they're trying to change their eating habits.
|
| 531 |
+
```
|
| 532 |
+
"""
|
| 533 |
+
|
| 534 |
+
BLENDERBOT_INPUTS_DOCSTRING = r"""
|
| 535 |
+
Args:
|
| 536 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 537 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 538 |
+
it.
|
| 539 |
+
|
| 540 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 541 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 542 |
+
|
| 543 |
+
[What are input IDs?](../glossary#input-ids)
|
| 544 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 545 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 546 |
+
|
| 547 |
+
- 1 for tokens that are **not masked**,
|
| 548 |
+
- 0 for tokens that are **masked**.
|
| 549 |
+
|
| 550 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 551 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 552 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 553 |
+
|
| 554 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 555 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 556 |
+
|
| 557 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 558 |
+
|
| 559 |
+
Blenderbot uses the `bos_token_id` as the starting token for `decoder_input_ids` generation. If
|
| 560 |
+
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 561 |
+
`past_key_values`).
|
| 562 |
+
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 563 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 564 |
+
be used by default.
|
| 565 |
+
head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
|
| 566 |
+
Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
|
| 567 |
+
|
| 568 |
+
- 1 indicates the head is **not masked**,
|
| 569 |
+
- 0 indicates the head is **masked**.
|
| 570 |
+
|
| 571 |
+
decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 572 |
+
Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
|
| 573 |
+
|
| 574 |
+
- 1 indicates the head is **not masked**,
|
| 575 |
+
- 0 indicates the head is **masked**.
|
| 576 |
+
|
| 577 |
+
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 578 |
+
Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
|
| 579 |
+
1]`:
|
| 580 |
+
|
| 581 |
+
- 1 indicates the head is **not masked**,
|
| 582 |
+
- 0 indicates the head is **masked**.
|
| 583 |
+
|
| 584 |
+
encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
|
| 585 |
+
Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
|
| 586 |
+
`last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
|
| 587 |
+
hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
|
| 588 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 589 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
| 590 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
|
| 591 |
+
`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
|
| 592 |
+
|
| 593 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
| 594 |
+
blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 595 |
+
|
| 596 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 597 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 598 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 599 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 600 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 601 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 602 |
+
than the model's internal embedding lookup matrix.
|
| 603 |
+
decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
|
| 604 |
+
Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
|
| 605 |
+
representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
|
| 606 |
+
input (see `past_key_values`). This is useful if you want more control over how to convert
|
| 607 |
+
`decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
|
| 608 |
+
|
| 609 |
+
If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
|
| 610 |
+
of `inputs_embeds`.
|
| 611 |
+
use_cache (`bool`, *optional*):
|
| 612 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 613 |
+
`past_key_values`).
|
| 614 |
+
output_attentions (`bool`, *optional*):
|
| 615 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 616 |
+
tensors for more detail.
|
| 617 |
+
output_hidden_states (`bool`, *optional*):
|
| 618 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 619 |
+
more detail.
|
| 620 |
+
return_dict (`bool`, *optional*):
|
| 621 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 622 |
+
"""
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
class BlenderbotEncoder(BlenderbotPreTrainedModel):
|
| 626 |
+
"""
|
| 627 |
+
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
|
| 628 |
+
[`BlenderbotEncoderLayer`].
|
| 629 |
+
|
| 630 |
+
Args:
|
| 631 |
+
config: BlenderbotConfig
|
| 632 |
+
embed_tokens (nn.Embedding): output embedding
|
| 633 |
+
"""
|
| 634 |
+
|
| 635 |
+
def __init__(self, config: BlenderbotConfig, embed_tokens: Optional[nn.Embedding] = None):
|
| 636 |
+
super().__init__(config)
|
| 637 |
+
|
| 638 |
+
self.dropout = config.dropout
|
| 639 |
+
self.layerdrop = config.encoder_layerdrop
|
| 640 |
+
|
| 641 |
+
embed_dim = config.d_model
|
| 642 |
+
self.padding_idx = config.pad_token_id
|
| 643 |
+
self.max_source_positions = config.max_position_embeddings
|
| 644 |
+
embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
|
| 645 |
+
|
| 646 |
+
if embed_tokens is not None:
|
| 647 |
+
self.embed_tokens = embed_tokens
|
| 648 |
+
else:
|
| 649 |
+
self.embed_tokens = BlenderbotScaledWordEmbedding(
|
| 650 |
+
config.vocab_size, embed_dim, self.padding_idx, embed_scale=embed_scale
|
| 651 |
+
)
|
| 652 |
+
|
| 653 |
+
self.embed_positions = BlenderbotLearnedPositionalEmbedding(
|
| 654 |
+
config.max_position_embeddings,
|
| 655 |
+
embed_dim,
|
| 656 |
+
)
|
| 657 |
+
self.layers = nn.ModuleList([BlenderbotEncoderLayer(config) for _ in range(config.encoder_layers)])
|
| 658 |
+
self.layer_norm = nn.LayerNorm(config.d_model)
|
| 659 |
+
|
| 660 |
+
self.gradient_checkpointing = False
|
| 661 |
+
# Initialize weights and apply final processing
|
| 662 |
+
self.post_init()
|
| 663 |
+
|
| 664 |
+
def forward(
|
| 665 |
+
self,
|
| 666 |
+
input_ids=None,
|
| 667 |
+
attention_mask=None,
|
| 668 |
+
head_mask=None,
|
| 669 |
+
inputs_embeds=None,
|
| 670 |
+
output_attentions=None,
|
| 671 |
+
output_hidden_states=None,
|
| 672 |
+
return_dict=None,
|
| 673 |
+
):
|
| 674 |
+
r"""
|
| 675 |
+
Args:
|
| 676 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 677 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 678 |
+
provide it.
|
| 679 |
+
|
| 680 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 681 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 682 |
+
|
| 683 |
+
[What are input IDs?](../glossary#input-ids)
|
| 684 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 685 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 686 |
+
|
| 687 |
+
- 1 for tokens that are **not masked**,
|
| 688 |
+
- 0 for tokens that are **masked**.
|
| 689 |
+
|
| 690 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 691 |
+
head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
|
| 692 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 693 |
+
|
| 694 |
+
- 1 indicates the head is **not masked**,
|
| 695 |
+
- 0 indicates the head is **masked**.
|
| 696 |
+
|
| 697 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 698 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 699 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 700 |
+
than the model's internal embedding lookup matrix.
|
| 701 |
+
output_attentions (`bool`, *optional*):
|
| 702 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 703 |
+
returned tensors for more detail.
|
| 704 |
+
output_hidden_states (`bool`, *optional*):
|
| 705 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 706 |
+
for more detail.
|
| 707 |
+
return_dict (`bool`, *optional*):
|
| 708 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 709 |
+
"""
|
| 710 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 711 |
+
output_hidden_states = (
|
| 712 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 713 |
+
)
|
| 714 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 715 |
+
|
| 716 |
+
# retrieve input_ids and inputs_embeds
|
| 717 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 718 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 719 |
+
elif input_ids is not None:
|
| 720 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 721 |
+
input_shape = input_ids.size()
|
| 722 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 723 |
+
elif inputs_embeds is not None:
|
| 724 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 725 |
+
else:
|
| 726 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 727 |
+
|
| 728 |
+
if inputs_embeds is None:
|
| 729 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 730 |
+
|
| 731 |
+
embed_pos = self.embed_positions(input_shape)
|
| 732 |
+
|
| 733 |
+
hidden_states = inputs_embeds + embed_pos
|
| 734 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 735 |
+
|
| 736 |
+
# expand attention_mask
|
| 737 |
+
if attention_mask is not None:
|
| 738 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 739 |
+
attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
|
| 740 |
+
|
| 741 |
+
encoder_states = () if output_hidden_states else None
|
| 742 |
+
all_attentions = () if output_attentions else None
|
| 743 |
+
|
| 744 |
+
# check if head_mask has a correct number of layers specified if desired
|
| 745 |
+
if head_mask is not None:
|
| 746 |
+
if head_mask.size()[0] != len(self.layers):
|
| 747 |
+
raise ValueError(
|
| 748 |
+
f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
|
| 749 |
+
f" {head_mask.size()[0]}."
|
| 750 |
+
)
|
| 751 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 752 |
+
if output_hidden_states:
|
| 753 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 754 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 755 |
+
to_drop = False
|
| 756 |
+
if self.training:
|
| 757 |
+
dropout_probability = torch.rand([])
|
| 758 |
+
if dropout_probability < self.layerdrop: # skip the layer
|
| 759 |
+
to_drop = True
|
| 760 |
+
|
| 761 |
+
if to_drop:
|
| 762 |
+
layer_outputs = (None, None)
|
| 763 |
+
else:
|
| 764 |
+
if self.gradient_checkpointing and self.training:
|
| 765 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 766 |
+
encoder_layer.__call__,
|
| 767 |
+
hidden_states,
|
| 768 |
+
attention_mask,
|
| 769 |
+
(head_mask[idx] if head_mask is not None else None),
|
| 770 |
+
output_attentions,
|
| 771 |
+
)
|
| 772 |
+
else:
|
| 773 |
+
layer_outputs = encoder_layer(
|
| 774 |
+
hidden_states,
|
| 775 |
+
attention_mask,
|
| 776 |
+
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
|
| 777 |
+
output_attentions=output_attentions,
|
| 778 |
+
)
|
| 779 |
+
|
| 780 |
+
hidden_states = layer_outputs[0]
|
| 781 |
+
|
| 782 |
+
if output_attentions:
|
| 783 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 784 |
+
|
| 785 |
+
# add final layer norm
|
| 786 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 787 |
+
|
| 788 |
+
if output_hidden_states:
|
| 789 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 790 |
+
|
| 791 |
+
if not return_dict:
|
| 792 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 793 |
+
return BaseModelOutput(
|
| 794 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 795 |
+
)
|
| 796 |
+
|
| 797 |
+
|
| 798 |
+
class BlenderbotDecoder(BlenderbotPreTrainedModel):
|
| 799 |
+
"""
|
| 800 |
+
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`BlenderbotDecoderLayer`]
|
| 801 |
+
|
| 802 |
+
Args:
|
| 803 |
+
config: BlenderbotConfig
|
| 804 |
+
embed_tokens (nn.Embedding): output embedding
|
| 805 |
+
"""
|
| 806 |
+
|
| 807 |
+
def __init__(self, config: BlenderbotConfig, embed_tokens: Optional[nn.Embedding] = None):
|
| 808 |
+
super().__init__(config)
|
| 809 |
+
self.dropout = config.dropout
|
| 810 |
+
self.layerdrop = config.decoder_layerdrop
|
| 811 |
+
self.padding_idx = config.pad_token_id
|
| 812 |
+
self.max_target_positions = config.max_position_embeddings
|
| 813 |
+
embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
|
| 814 |
+
|
| 815 |
+
if embed_tokens is not None:
|
| 816 |
+
self.embed_tokens = embed_tokens
|
| 817 |
+
else:
|
| 818 |
+
self.embed_tokens = BlenderbotScaledWordEmbedding(
|
| 819 |
+
config.vocab_size, config.d_model, self.padding_idx, embed_scale=embed_scale
|
| 820 |
+
)
|
| 821 |
+
|
| 822 |
+
self.embed_positions = BlenderbotLearnedPositionalEmbedding(
|
| 823 |
+
config.max_position_embeddings,
|
| 824 |
+
config.d_model,
|
| 825 |
+
)
|
| 826 |
+
self.layers = nn.ModuleList([BlenderbotDecoderLayer(config) for _ in range(config.decoder_layers)])
|
| 827 |
+
self.layer_norm = nn.LayerNorm(config.d_model)
|
| 828 |
+
|
| 829 |
+
self.gradient_checkpointing = False
|
| 830 |
+
# Initialize weights and apply final processing
|
| 831 |
+
self.post_init()
|
| 832 |
+
|
| 833 |
+
def get_input_embeddings(self):
|
| 834 |
+
return self.embed_tokens
|
| 835 |
+
|
| 836 |
+
def set_input_embeddings(self, value):
|
| 837 |
+
self.embed_tokens = value
|
| 838 |
+
|
| 839 |
+
def forward(
|
| 840 |
+
self,
|
| 841 |
+
input_ids=None,
|
| 842 |
+
attention_mask=None,
|
| 843 |
+
encoder_hidden_states=None,
|
| 844 |
+
encoder_attention_mask=None,
|
| 845 |
+
head_mask=None,
|
| 846 |
+
cross_attn_head_mask=None,
|
| 847 |
+
past_key_values=None,
|
| 848 |
+
inputs_embeds=None,
|
| 849 |
+
use_cache=None,
|
| 850 |
+
output_attentions=None,
|
| 851 |
+
output_hidden_states=None,
|
| 852 |
+
return_dict=None,
|
| 853 |
+
):
|
| 854 |
+
r"""
|
| 855 |
+
Args:
|
| 856 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 857 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 858 |
+
provide it.
|
| 859 |
+
|
| 860 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 861 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 862 |
+
|
| 863 |
+
[What are input IDs?](../glossary#input-ids)
|
| 864 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 865 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 866 |
+
|
| 867 |
+
- 1 for tokens that are **not masked**,
|
| 868 |
+
- 0 for tokens that are **masked**.
|
| 869 |
+
|
| 870 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 871 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
|
| 872 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 873 |
+
of the decoder.
|
| 874 |
+
encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
|
| 875 |
+
Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
|
| 876 |
+
selected in `[0, 1]`:
|
| 877 |
+
|
| 878 |
+
- 1 for tokens that are **not masked**,
|
| 879 |
+
- 0 for tokens that are **masked**.
|
| 880 |
+
|
| 881 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 882 |
+
head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
|
| 883 |
+
Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0,
|
| 884 |
+
1]`:
|
| 885 |
+
|
| 886 |
+
- 1 indicates the head is **not masked**,
|
| 887 |
+
- 0 indicates the head is **masked**.
|
| 888 |
+
|
| 889 |
+
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 890 |
+
Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing
|
| 891 |
+
cross-attention on hidden heads. Mask values selected in `[0, 1]`:
|
| 892 |
+
|
| 893 |
+
- 1 indicates the head is **not masked**,
|
| 894 |
+
- 0 indicates the head is **masked**.
|
| 895 |
+
|
| 896 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 897 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
| 898 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
|
| 899 |
+
shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
|
| 900 |
+
|
| 901 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
|
| 902 |
+
cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 903 |
+
|
| 904 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
|
| 905 |
+
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
|
| 906 |
+
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 907 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 908 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 909 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 910 |
+
than the model's internal embedding lookup matrix.
|
| 911 |
+
output_attentions (`bool`, *optional*):
|
| 912 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 913 |
+
returned tensors for more detail.
|
| 914 |
+
output_hidden_states (`bool`, *optional*):
|
| 915 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 916 |
+
for more detail.
|
| 917 |
+
return_dict (`bool`, *optional*):
|
| 918 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 919 |
+
"""
|
| 920 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 921 |
+
output_hidden_states = (
|
| 922 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 923 |
+
)
|
| 924 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 925 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 926 |
+
|
| 927 |
+
# retrieve input_ids and inputs_embeds
|
| 928 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 929 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
| 930 |
+
elif input_ids is not None:
|
| 931 |
+
input_shape = input_ids.size()
|
| 932 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 933 |
+
elif inputs_embeds is not None:
|
| 934 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 935 |
+
else:
|
| 936 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
| 937 |
+
|
| 938 |
+
# past_key_values_length
|
| 939 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
| 940 |
+
|
| 941 |
+
if inputs_embeds is None:
|
| 942 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 943 |
+
|
| 944 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
| 945 |
+
attention_mask, input_shape, inputs_embeds, past_key_values_length
|
| 946 |
+
)
|
| 947 |
+
|
| 948 |
+
# expand encoder attention mask
|
| 949 |
+
if encoder_hidden_states is not None and encoder_attention_mask is not None:
|
| 950 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 951 |
+
encoder_attention_mask = _prepare_4d_attention_mask(
|
| 952 |
+
encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
|
| 953 |
+
)
|
| 954 |
+
|
| 955 |
+
# embed positions
|
| 956 |
+
positions = self.embed_positions(input_shape, past_key_values_length)
|
| 957 |
+
|
| 958 |
+
hidden_states = inputs_embeds + positions
|
| 959 |
+
|
| 960 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 961 |
+
|
| 962 |
+
if self.gradient_checkpointing and self.training:
|
| 963 |
+
if use_cache:
|
| 964 |
+
logger.warning(
|
| 965 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 966 |
+
)
|
| 967 |
+
use_cache = False
|
| 968 |
+
# decoder layers
|
| 969 |
+
all_hidden_states = () if output_hidden_states else None
|
| 970 |
+
all_self_attns = () if output_attentions else None
|
| 971 |
+
all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
|
| 972 |
+
next_decoder_cache = () if use_cache else None
|
| 973 |
+
|
| 974 |
+
# check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
|
| 975 |
+
for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
|
| 976 |
+
if attn_mask is not None:
|
| 977 |
+
if attn_mask.size()[0] != len(self.layers):
|
| 978 |
+
raise ValueError(
|
| 979 |
+
f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
|
| 980 |
+
f" {head_mask.size()[0]}."
|
| 981 |
+
)
|
| 982 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 983 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 984 |
+
if output_hidden_states:
|
| 985 |
+
all_hidden_states += (hidden_states,)
|
| 986 |
+
if self.training:
|
| 987 |
+
dropout_probability = torch.rand([])
|
| 988 |
+
if dropout_probability < self.layerdrop:
|
| 989 |
+
continue
|
| 990 |
+
|
| 991 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
| 992 |
+
|
| 993 |
+
if self.gradient_checkpointing and self.training:
|
| 994 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 995 |
+
decoder_layer.__call__,
|
| 996 |
+
hidden_states,
|
| 997 |
+
attention_mask,
|
| 998 |
+
encoder_hidden_states,
|
| 999 |
+
encoder_attention_mask,
|
| 1000 |
+
head_mask[idx] if head_mask is not None else None,
|
| 1001 |
+
cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
|
| 1002 |
+
None,
|
| 1003 |
+
output_attentions,
|
| 1004 |
+
use_cache,
|
| 1005 |
+
)
|
| 1006 |
+
else:
|
| 1007 |
+
layer_outputs = decoder_layer(
|
| 1008 |
+
hidden_states,
|
| 1009 |
+
attention_mask=attention_mask,
|
| 1010 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1011 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1012 |
+
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
|
| 1013 |
+
cross_attn_layer_head_mask=(
|
| 1014 |
+
cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
|
| 1015 |
+
),
|
| 1016 |
+
past_key_value=past_key_value,
|
| 1017 |
+
output_attentions=output_attentions,
|
| 1018 |
+
use_cache=use_cache,
|
| 1019 |
+
)
|
| 1020 |
+
hidden_states = layer_outputs[0]
|
| 1021 |
+
|
| 1022 |
+
if use_cache:
|
| 1023 |
+
next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
|
| 1024 |
+
|
| 1025 |
+
if output_attentions:
|
| 1026 |
+
all_self_attns += (layer_outputs[1],)
|
| 1027 |
+
|
| 1028 |
+
if encoder_hidden_states is not None:
|
| 1029 |
+
all_cross_attentions += (layer_outputs[2],)
|
| 1030 |
+
|
| 1031 |
+
# add final layer norm
|
| 1032 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 1033 |
+
|
| 1034 |
+
# add hidden states from the last decoder layer
|
| 1035 |
+
if output_hidden_states:
|
| 1036 |
+
all_hidden_states += (hidden_states,)
|
| 1037 |
+
|
| 1038 |
+
next_cache = next_decoder_cache if use_cache else None
|
| 1039 |
+
if not return_dict:
|
| 1040 |
+
return tuple(
|
| 1041 |
+
v
|
| 1042 |
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
|
| 1043 |
+
if v is not None
|
| 1044 |
+
)
|
| 1045 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 1046 |
+
last_hidden_state=hidden_states,
|
| 1047 |
+
past_key_values=next_cache,
|
| 1048 |
+
hidden_states=all_hidden_states,
|
| 1049 |
+
attentions=all_self_attns,
|
| 1050 |
+
cross_attentions=all_cross_attentions,
|
| 1051 |
+
)
|
| 1052 |
+
|
| 1053 |
+
|
| 1054 |
+
@add_start_docstrings(
|
| 1055 |
+
"The bare Blenderbot Model outputting raw hidden-states without any specific head on top.",
|
| 1056 |
+
BLENDERBOT_START_DOCSTRING,
|
| 1057 |
+
)
|
| 1058 |
+
class BlenderbotModel(BlenderbotPreTrainedModel):
|
| 1059 |
+
_tied_weights_keys = ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight"]
|
| 1060 |
+
|
| 1061 |
+
def __init__(self, config: BlenderbotConfig):
|
| 1062 |
+
super().__init__(config)
|
| 1063 |
+
|
| 1064 |
+
padding_idx, vocab_size = config.pad_token_id, config.vocab_size
|
| 1065 |
+
embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
|
| 1066 |
+
self.shared = BlenderbotScaledWordEmbedding(vocab_size, config.d_model, padding_idx, embed_scale=embed_scale)
|
| 1067 |
+
self.encoder = BlenderbotEncoder(config, self.shared)
|
| 1068 |
+
self.decoder = BlenderbotDecoder(config, self.shared)
|
| 1069 |
+
|
| 1070 |
+
# Initialize weights and apply final processing
|
| 1071 |
+
self.post_init()
|
| 1072 |
+
|
| 1073 |
+
@classmethod
|
| 1074 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *model_args, **kwargs):
|
| 1075 |
+
if pretrained_model_name_or_path == "facebook/blenderbot-90M":
|
| 1076 |
+
warnings.warn(
|
| 1077 |
+
"The checkpoint `facebook/blenderbot-90M` is deprecated. In the future, please use the identical"
|
| 1078 |
+
" checkpoint `facebook/small_blenderbot-90M` with"
|
| 1079 |
+
" `BlenderbotSmallModel.from_pretrained('facebook/small_blenderbot-90M')` instead.",
|
| 1080 |
+
FutureWarning,
|
| 1081 |
+
)
|
| 1082 |
+
return BlenderbotSmallModel.from_pretrained(pretrained_model_name_or_path)
|
| 1083 |
+
|
| 1084 |
+
return super(BlenderbotModel, cls).from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
|
| 1085 |
+
|
| 1086 |
+
def get_input_embeddings(self):
|
| 1087 |
+
return self.shared
|
| 1088 |
+
|
| 1089 |
+
def set_input_embeddings(self, value):
|
| 1090 |
+
self.shared = value
|
| 1091 |
+
self.encoder.embed_tokens = self.shared
|
| 1092 |
+
self.decoder.embed_tokens = self.shared
|
| 1093 |
+
|
| 1094 |
+
def get_encoder(self):
|
| 1095 |
+
return self.encoder
|
| 1096 |
+
|
| 1097 |
+
def get_decoder(self):
|
| 1098 |
+
return self.decoder
|
| 1099 |
+
|
| 1100 |
+
@add_start_docstrings_to_model_forward(BLENDERBOT_INPUTS_DOCSTRING)
|
| 1101 |
+
@replace_return_docstrings(output_type=Seq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)
|
| 1102 |
+
def forward(
|
| 1103 |
+
self,
|
| 1104 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1105 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1106 |
+
decoder_input_ids: Optional[torch.LongTensor] = None,
|
| 1107 |
+
decoder_attention_mask: Optional[torch.LongTensor] = None,
|
| 1108 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1109 |
+
decoder_head_mask: Optional[torch.Tensor] = None,
|
| 1110 |
+
cross_attn_head_mask: Optional[torch.Tensor] = None,
|
| 1111 |
+
encoder_outputs: Optional[Union[Tuple, BaseModelOutput]] = None,
|
| 1112 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1113 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1114 |
+
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1115 |
+
use_cache: Optional[bool] = None,
|
| 1116 |
+
output_attentions: Optional[bool] = None,
|
| 1117 |
+
output_hidden_states: Optional[bool] = None,
|
| 1118 |
+
return_dict: Optional[bool] = None,
|
| 1119 |
+
) -> Union[Tuple[torch.FloatTensor], Seq2SeqModelOutput]:
|
| 1120 |
+
r"""
|
| 1121 |
+
Returns:
|
| 1122 |
+
|
| 1123 |
+
Example:
|
| 1124 |
+
|
| 1125 |
+
```python
|
| 1126 |
+
>>> from transformers import AutoTokenizer, BlenderbotModel
|
| 1127 |
+
|
| 1128 |
+
>>> model = BlenderbotModel.from_pretrained("facebook/blenderbot-400M-distill")
|
| 1129 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
|
| 1130 |
+
|
| 1131 |
+
>>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
|
| 1132 |
+
>>> decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids # Batch size 1
|
| 1133 |
+
>>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_input_ids)
|
| 1134 |
+
|
| 1135 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 1136 |
+
>>> list(last_hidden_states.shape)
|
| 1137 |
+
[1, 6, 1280]
|
| 1138 |
+
```"""
|
| 1139 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1140 |
+
output_hidden_states = (
|
| 1141 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1142 |
+
)
|
| 1143 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1144 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1145 |
+
|
| 1146 |
+
if encoder_outputs is None:
|
| 1147 |
+
encoder_outputs = self.encoder(
|
| 1148 |
+
input_ids=input_ids,
|
| 1149 |
+
attention_mask=attention_mask,
|
| 1150 |
+
head_mask=head_mask,
|
| 1151 |
+
inputs_embeds=inputs_embeds,
|
| 1152 |
+
output_attentions=output_attentions,
|
| 1153 |
+
output_hidden_states=output_hidden_states,
|
| 1154 |
+
return_dict=return_dict,
|
| 1155 |
+
)
|
| 1156 |
+
# If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
|
| 1157 |
+
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
|
| 1158 |
+
encoder_outputs = BaseModelOutput(
|
| 1159 |
+
last_hidden_state=encoder_outputs[0],
|
| 1160 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
| 1161 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
| 1162 |
+
)
|
| 1163 |
+
|
| 1164 |
+
# decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
|
| 1165 |
+
decoder_outputs = self.decoder(
|
| 1166 |
+
input_ids=decoder_input_ids,
|
| 1167 |
+
attention_mask=decoder_attention_mask,
|
| 1168 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 1169 |
+
encoder_attention_mask=attention_mask,
|
| 1170 |
+
head_mask=decoder_head_mask,
|
| 1171 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1172 |
+
past_key_values=past_key_values,
|
| 1173 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 1174 |
+
use_cache=use_cache,
|
| 1175 |
+
output_attentions=output_attentions,
|
| 1176 |
+
output_hidden_states=output_hidden_states,
|
| 1177 |
+
return_dict=return_dict,
|
| 1178 |
+
)
|
| 1179 |
+
|
| 1180 |
+
if not return_dict:
|
| 1181 |
+
return decoder_outputs + encoder_outputs
|
| 1182 |
+
|
| 1183 |
+
return Seq2SeqModelOutput(
|
| 1184 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 1185 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 1186 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 1187 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 1188 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 1189 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 1190 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 1191 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 1192 |
+
)
|
| 1193 |
+
|
| 1194 |
+
|
| 1195 |
+
@add_start_docstrings(
|
| 1196 |
+
"The Blenderbot Model with a language modeling head. Can be used for summarization.", BLENDERBOT_START_DOCSTRING
|
| 1197 |
+
)
|
| 1198 |
+
class BlenderbotForConditionalGeneration(BlenderbotPreTrainedModel, GenerationMixin):
|
| 1199 |
+
base_model_prefix = "model"
|
| 1200 |
+
_keys_to_ignore_on_load_missing = ["final_logits_bias"]
|
| 1201 |
+
_tied_weights_keys = ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight", "lm_head.weight"]
|
| 1202 |
+
|
| 1203 |
+
def __init__(self, config: BlenderbotConfig):
|
| 1204 |
+
super().__init__(config)
|
| 1205 |
+
self.model = BlenderbotModel(config)
|
| 1206 |
+
self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings)))
|
| 1207 |
+
self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
|
| 1208 |
+
|
| 1209 |
+
# Initialize weights and apply final processing
|
| 1210 |
+
self.post_init()
|
| 1211 |
+
|
| 1212 |
+
@classmethod
|
| 1213 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *model_args, **kwargs):
|
| 1214 |
+
if pretrained_model_name_or_path == "facebook/blenderbot-90M":
|
| 1215 |
+
warnings.warn(
|
| 1216 |
+
"The checkpoint `facebook/blenderbot-90M` is deprecated. In the future, please use the identical"
|
| 1217 |
+
" checkpoint `facebook/small_blenderbot-90M` with"
|
| 1218 |
+
" `BlenderbotSmallForConditionalGeneration.from_pretrained('facebook/small_blenderbot-90M')` instead.",
|
| 1219 |
+
FutureWarning,
|
| 1220 |
+
)
|
| 1221 |
+
return BlenderbotSmallForConditionalGeneration.from_pretrained(pretrained_model_name_or_path)
|
| 1222 |
+
|
| 1223 |
+
return super(BlenderbotForConditionalGeneration, cls).from_pretrained(
|
| 1224 |
+
pretrained_model_name_or_path, *model_args, **kwargs
|
| 1225 |
+
)
|
| 1226 |
+
|
| 1227 |
+
def get_encoder(self):
|
| 1228 |
+
return self.model.get_encoder()
|
| 1229 |
+
|
| 1230 |
+
def get_decoder(self):
|
| 1231 |
+
return self.model.get_decoder()
|
| 1232 |
+
|
| 1233 |
+
def resize_token_embeddings(
|
| 1234 |
+
self, new_num_tokens: int, pad_to_multiple_of: Optional[int] = None, mean_resizing: bool = True
|
| 1235 |
+
) -> nn.Embedding:
|
| 1236 |
+
new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of, mean_resizing)
|
| 1237 |
+
self._resize_final_logits_bias(new_embeddings.weight.shape[0])
|
| 1238 |
+
return new_embeddings
|
| 1239 |
+
|
| 1240 |
+
def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
|
| 1241 |
+
old_num_tokens = self.final_logits_bias.shape[-1]
|
| 1242 |
+
if new_num_tokens <= old_num_tokens:
|
| 1243 |
+
new_bias = self.final_logits_bias[:, :new_num_tokens]
|
| 1244 |
+
else:
|
| 1245 |
+
extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
|
| 1246 |
+
new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
|
| 1247 |
+
self.register_buffer("final_logits_bias", new_bias)
|
| 1248 |
+
|
| 1249 |
+
def get_output_embeddings(self):
|
| 1250 |
+
return self.lm_head
|
| 1251 |
+
|
| 1252 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1253 |
+
self.lm_head = new_embeddings
|
| 1254 |
+
|
| 1255 |
+
@add_start_docstrings_to_model_forward(BLENDERBOT_INPUTS_DOCSTRING)
|
| 1256 |
+
@replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
|
| 1257 |
+
@add_end_docstrings(BLENDERBOT_GENERATION_EXAMPLE)
|
| 1258 |
+
def forward(
|
| 1259 |
+
self,
|
| 1260 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1261 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1262 |
+
decoder_input_ids: Optional[torch.LongTensor] = None,
|
| 1263 |
+
decoder_attention_mask: Optional[torch.LongTensor] = None,
|
| 1264 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1265 |
+
decoder_head_mask: Optional[torch.Tensor] = None,
|
| 1266 |
+
cross_attn_head_mask: Optional[torch.Tensor] = None,
|
| 1267 |
+
encoder_outputs: Optional[Union[Tuple, BaseModelOutput]] = None,
|
| 1268 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1269 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1270 |
+
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1271 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1272 |
+
use_cache: Optional[bool] = None,
|
| 1273 |
+
output_attentions: Optional[bool] = None,
|
| 1274 |
+
output_hidden_states: Optional[bool] = None,
|
| 1275 |
+
return_dict: Optional[bool] = None,
|
| 1276 |
+
) -> Union[Tuple[torch.FloatTensor], Seq2SeqLMOutput]:
|
| 1277 |
+
r"""
|
| 1278 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1279 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1280 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1281 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1282 |
+
|
| 1283 |
+
Returns:
|
| 1284 |
+
"""
|
| 1285 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1286 |
+
|
| 1287 |
+
if labels is not None:
|
| 1288 |
+
if use_cache:
|
| 1289 |
+
logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
|
| 1290 |
+
use_cache = False
|
| 1291 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 1292 |
+
decoder_input_ids = shift_tokens_right(
|
| 1293 |
+
labels, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 1294 |
+
)
|
| 1295 |
+
|
| 1296 |
+
outputs = self.model(
|
| 1297 |
+
input_ids,
|
| 1298 |
+
attention_mask=attention_mask,
|
| 1299 |
+
decoder_input_ids=decoder_input_ids,
|
| 1300 |
+
encoder_outputs=encoder_outputs,
|
| 1301 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1302 |
+
head_mask=head_mask,
|
| 1303 |
+
decoder_head_mask=decoder_head_mask,
|
| 1304 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1305 |
+
past_key_values=past_key_values,
|
| 1306 |
+
inputs_embeds=inputs_embeds,
|
| 1307 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1308 |
+
use_cache=use_cache,
|
| 1309 |
+
output_attentions=output_attentions,
|
| 1310 |
+
output_hidden_states=output_hidden_states,
|
| 1311 |
+
return_dict=return_dict,
|
| 1312 |
+
)
|
| 1313 |
+
lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias
|
| 1314 |
+
|
| 1315 |
+
masked_lm_loss = None
|
| 1316 |
+
if labels is not None:
|
| 1317 |
+
loss_fct = CrossEntropyLoss()
|
| 1318 |
+
masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1319 |
+
|
| 1320 |
+
if not return_dict:
|
| 1321 |
+
output = (lm_logits,) + outputs[1:]
|
| 1322 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 1323 |
+
|
| 1324 |
+
return Seq2SeqLMOutput(
|
| 1325 |
+
loss=masked_lm_loss,
|
| 1326 |
+
logits=lm_logits,
|
| 1327 |
+
past_key_values=outputs.past_key_values,
|
| 1328 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 1329 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 1330 |
+
cross_attentions=outputs.cross_attentions,
|
| 1331 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 1332 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 1333 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 1334 |
+
)
|
| 1335 |
+
|
| 1336 |
+
@staticmethod
|
| 1337 |
+
def _reorder_cache(past_key_values, beam_idx):
|
| 1338 |
+
reordered_past = ()
|
| 1339 |
+
for layer_past in past_key_values:
|
| 1340 |
+
# cached cross_attention states don't have to be reordered -> they are always the same
|
| 1341 |
+
reordered_past += (
|
| 1342 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past[:2])
|
| 1343 |
+
+ layer_past[2:],
|
| 1344 |
+
)
|
| 1345 |
+
return reordered_past
|
| 1346 |
+
|
| 1347 |
+
|
| 1348 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoderWrapper with Bart->Blenderbot
|
| 1349 |
+
class BlenderbotDecoderWrapper(BlenderbotPreTrainedModel):
|
| 1350 |
+
"""
|
| 1351 |
+
This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
|
| 1352 |
+
used in combination with the [`EncoderDecoderModel`] framework.
|
| 1353 |
+
"""
|
| 1354 |
+
|
| 1355 |
+
def __init__(self, config):
|
| 1356 |
+
super().__init__(config)
|
| 1357 |
+
self.decoder = BlenderbotDecoder(config)
|
| 1358 |
+
|
| 1359 |
+
def forward(self, *args, **kwargs):
|
| 1360 |
+
return self.decoder(*args, **kwargs)
|
| 1361 |
+
|
| 1362 |
+
|
| 1363 |
+
# Copied from transformers.models.bart.modeling_bart.BartForCausalLM with Bart->Blenderbot, facebook/bart-base->facebook/blenderbot-400M-distill
|
| 1364 |
+
class BlenderbotForCausalLM(BlenderbotPreTrainedModel, GenerationMixin):
|
| 1365 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 1366 |
+
|
| 1367 |
+
def __init__(self, config):
|
| 1368 |
+
config = copy.deepcopy(config)
|
| 1369 |
+
config.is_decoder = True
|
| 1370 |
+
config.is_encoder_decoder = False
|
| 1371 |
+
super().__init__(config)
|
| 1372 |
+
self.model = BlenderbotDecoderWrapper(config)
|
| 1373 |
+
|
| 1374 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1375 |
+
|
| 1376 |
+
# Initialize weights and apply final processing
|
| 1377 |
+
self.post_init()
|
| 1378 |
+
|
| 1379 |
+
def get_input_embeddings(self):
|
| 1380 |
+
return self.model.decoder.embed_tokens
|
| 1381 |
+
|
| 1382 |
+
def set_input_embeddings(self, value):
|
| 1383 |
+
self.model.decoder.embed_tokens = value
|
| 1384 |
+
|
| 1385 |
+
def get_output_embeddings(self):
|
| 1386 |
+
return self.lm_head
|
| 1387 |
+
|
| 1388 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1389 |
+
self.lm_head = new_embeddings
|
| 1390 |
+
|
| 1391 |
+
def set_decoder(self, decoder):
|
| 1392 |
+
self.model.decoder = decoder
|
| 1393 |
+
|
| 1394 |
+
def get_decoder(self):
|
| 1395 |
+
return self.model.decoder
|
| 1396 |
+
|
| 1397 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
|
| 1398 |
+
def forward(
|
| 1399 |
+
self,
|
| 1400 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1401 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1402 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 1403 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 1404 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1405 |
+
cross_attn_head_mask: Optional[torch.Tensor] = None,
|
| 1406 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1407 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1408 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1409 |
+
use_cache: Optional[bool] = None,
|
| 1410 |
+
output_attentions: Optional[bool] = None,
|
| 1411 |
+
output_hidden_states: Optional[bool] = None,
|
| 1412 |
+
return_dict: Optional[bool] = None,
|
| 1413 |
+
) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
|
| 1414 |
+
r"""
|
| 1415 |
+
Args:
|
| 1416 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 1417 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 1418 |
+
provide it.
|
| 1419 |
+
|
| 1420 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1421 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1422 |
+
|
| 1423 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1424 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1425 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 1426 |
+
|
| 1427 |
+
- 1 for tokens that are **not masked**,
|
| 1428 |
+
- 0 for tokens that are **masked**.
|
| 1429 |
+
|
| 1430 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 1431 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 1432 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 1433 |
+
if the model is configured as a decoder.
|
| 1434 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1435 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
|
| 1436 |
+
in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 1437 |
+
head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 1438 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 1439 |
+
|
| 1440 |
+
- 1 indicates the head is **not masked**,
|
| 1441 |
+
- 0 indicates the head is **masked**.
|
| 1442 |
+
|
| 1443 |
+
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 1444 |
+
Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
|
| 1445 |
+
|
| 1446 |
+
- 1 indicates the head is **not masked**,
|
| 1447 |
+
- 0 indicates the head is **masked**.
|
| 1448 |
+
|
| 1449 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 1450 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
| 1451 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
|
| 1452 |
+
shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
|
| 1453 |
+
tensors are only required when the model is used as a decoder in a Sequence to Sequence model.
|
| 1454 |
+
|
| 1455 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
|
| 1456 |
+
cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 1457 |
+
|
| 1458 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
|
| 1459 |
+
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
|
| 1460 |
+
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 1461 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1462 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1463 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1464 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1465 |
+
use_cache (`bool`, *optional*):
|
| 1466 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 1467 |
+
(see `past_key_values`).
|
| 1468 |
+
|
| 1469 |
+
- 1 for tokens that are **not masked**,
|
| 1470 |
+
- 0 for tokens that are **masked**.
|
| 1471 |
+
output_attentions (`bool`, *optional*):
|
| 1472 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 1473 |
+
returned tensors for more detail.
|
| 1474 |
+
output_hidden_states (`bool`, *optional*):
|
| 1475 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 1476 |
+
for more detail.
|
| 1477 |
+
return_dict (`bool`, *optional*):
|
| 1478 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 1479 |
+
|
| 1480 |
+
Returns:
|
| 1481 |
+
|
| 1482 |
+
Example:
|
| 1483 |
+
|
| 1484 |
+
```python
|
| 1485 |
+
>>> from transformers import AutoTokenizer, BlenderbotForCausalLM
|
| 1486 |
+
|
| 1487 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
|
| 1488 |
+
>>> model = BlenderbotForCausalLM.from_pretrained("facebook/blenderbot-400M-distill", add_cross_attention=False)
|
| 1489 |
+
>>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
|
| 1490 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
| 1491 |
+
>>> outputs = model(**inputs)
|
| 1492 |
+
|
| 1493 |
+
>>> logits = outputs.logits
|
| 1494 |
+
>>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
|
| 1495 |
+
>>> list(logits.shape) == expected_shape
|
| 1496 |
+
True
|
| 1497 |
+
```"""
|
| 1498 |
+
|
| 1499 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1500 |
+
output_hidden_states = (
|
| 1501 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1502 |
+
)
|
| 1503 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1504 |
+
|
| 1505 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 1506 |
+
outputs = self.model.decoder(
|
| 1507 |
+
input_ids=input_ids,
|
| 1508 |
+
attention_mask=attention_mask,
|
| 1509 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1510 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1511 |
+
head_mask=head_mask,
|
| 1512 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1513 |
+
past_key_values=past_key_values,
|
| 1514 |
+
inputs_embeds=inputs_embeds,
|
| 1515 |
+
use_cache=use_cache,
|
| 1516 |
+
output_attentions=output_attentions,
|
| 1517 |
+
output_hidden_states=output_hidden_states,
|
| 1518 |
+
return_dict=return_dict,
|
| 1519 |
+
)
|
| 1520 |
+
|
| 1521 |
+
logits = self.lm_head(outputs[0])
|
| 1522 |
+
|
| 1523 |
+
loss = None
|
| 1524 |
+
if labels is not None:
|
| 1525 |
+
labels = labels.to(logits.device)
|
| 1526 |
+
loss_fct = CrossEntropyLoss()
|
| 1527 |
+
loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1528 |
+
|
| 1529 |
+
if not return_dict:
|
| 1530 |
+
output = (logits,) + outputs[1:]
|
| 1531 |
+
return (loss,) + output if loss is not None else output
|
| 1532 |
+
|
| 1533 |
+
return CausalLMOutputWithCrossAttentions(
|
| 1534 |
+
loss=loss,
|
| 1535 |
+
logits=logits,
|
| 1536 |
+
past_key_values=outputs.past_key_values,
|
| 1537 |
+
hidden_states=outputs.hidden_states,
|
| 1538 |
+
attentions=outputs.attentions,
|
| 1539 |
+
cross_attentions=outputs.cross_attentions,
|
| 1540 |
+
)
|
| 1541 |
+
|
| 1542 |
+
@staticmethod
|
| 1543 |
+
def _reorder_cache(past_key_values, beam_idx):
|
| 1544 |
+
reordered_past = ()
|
| 1545 |
+
for layer_past in past_key_values:
|
| 1546 |
+
reordered_past += (
|
| 1547 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
| 1548 |
+
)
|
| 1549 |
+
return reordered_past
|
| 1550 |
+
|
| 1551 |
+
|
| 1552 |
+
__all__ = [
|
| 1553 |
+
"BlenderbotForCausalLM",
|
| 1554 |
+
"BlenderbotForConditionalGeneration",
|
| 1555 |
+
"BlenderbotModel",
|
| 1556 |
+
"BlenderbotPreTrainedModel",
|
| 1557 |
+
]
|
lib/python3.12/site-packages/transformers/models/blenderbot/modeling_flax_blenderbot.py
ADDED
|
@@ -0,0 +1,1508 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The Fairseq Authors and The Google Flax Team Authors And The HuggingFace Inc. team. 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 |
+
"""Flax Blenderbot model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
import random
|
| 19 |
+
from functools import partial
|
| 20 |
+
from typing import Callable, Optional, Tuple
|
| 21 |
+
|
| 22 |
+
import flax.linen as nn
|
| 23 |
+
import jax
|
| 24 |
+
import jax.numpy as jnp
|
| 25 |
+
from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
|
| 26 |
+
from flax.linen import combine_masks, make_causal_mask
|
| 27 |
+
from flax.linen.attention import dot_product_attention_weights
|
| 28 |
+
from flax.traverse_util import flatten_dict, unflatten_dict
|
| 29 |
+
from jax import lax
|
| 30 |
+
from jax.random import PRNGKey
|
| 31 |
+
|
| 32 |
+
from ...modeling_flax_outputs import (
|
| 33 |
+
FlaxBaseModelOutput,
|
| 34 |
+
FlaxBaseModelOutputWithPastAndCrossAttentions,
|
| 35 |
+
FlaxCausalLMOutputWithCrossAttentions,
|
| 36 |
+
FlaxSeq2SeqLMOutput,
|
| 37 |
+
FlaxSeq2SeqModelOutput,
|
| 38 |
+
)
|
| 39 |
+
from ...modeling_flax_utils import (
|
| 40 |
+
ACT2FN,
|
| 41 |
+
FlaxPreTrainedModel,
|
| 42 |
+
append_call_sample_docstring,
|
| 43 |
+
append_replace_return_docstrings,
|
| 44 |
+
overwrite_call_docstring,
|
| 45 |
+
)
|
| 46 |
+
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
|
| 47 |
+
from .configuration_blenderbot import BlenderbotConfig
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
logger = logging.get_logger(__name__)
|
| 51 |
+
|
| 52 |
+
_CONFIG_FOR_DOC = "BlenderbotConfig"
|
| 53 |
+
_CHECKPOINT_FOR_DOC = "facebook/blenderbot-400M-distill"
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
BLENDERBOT_START_DOCSTRING = r"""
|
| 57 |
+
This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 58 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 59 |
+
etc.)
|
| 60 |
+
|
| 61 |
+
This model is also a Flax Linen
|
| 62 |
+
[flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
|
| 63 |
+
regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.
|
| 64 |
+
|
| 65 |
+
Finally, this model supports inherent JAX features such as:
|
| 66 |
+
|
| 67 |
+
- [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
|
| 68 |
+
- [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
|
| 69 |
+
- [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
|
| 70 |
+
- [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
|
| 71 |
+
|
| 72 |
+
Parameters:
|
| 73 |
+
config ([`BlenderbotConfig`]): Model configuration class with all the parameters of the model.
|
| 74 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 75 |
+
configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
BLENDERBOT_INPUTS_DOCSTRING = r"""
|
| 79 |
+
Args:
|
| 80 |
+
input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
|
| 81 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 82 |
+
it.
|
| 83 |
+
|
| 84 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 85 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 86 |
+
|
| 87 |
+
[What are input IDs?](../glossary#input-ids)
|
| 88 |
+
attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 89 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 90 |
+
|
| 91 |
+
- 1 for tokens that are **not masked**,
|
| 92 |
+
- 0 for tokens that are **masked**.
|
| 93 |
+
|
| 94 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 95 |
+
decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 96 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 97 |
+
|
| 98 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 99 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 100 |
+
|
| 101 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 102 |
+
|
| 103 |
+
For translation and summarization training, `decoder_input_ids` should be provided. If no
|
| 104 |
+
`decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
|
| 105 |
+
for denoising pre-training following the paper.
|
| 106 |
+
decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 107 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 108 |
+
be used by default.
|
| 109 |
+
|
| 110 |
+
If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the
|
| 111 |
+
paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
|
| 112 |
+
position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 113 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 114 |
+
config.max_position_embeddings - 1]`.
|
| 115 |
+
decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 116 |
+
Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
|
| 117 |
+
range `[0, config.max_position_embeddings - 1]`.
|
| 118 |
+
output_attentions (`bool`, *optional*):
|
| 119 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 120 |
+
tensors for more detail.
|
| 121 |
+
output_hidden_states (`bool`, *optional*):
|
| 122 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 123 |
+
more detail.
|
| 124 |
+
return_dict (`bool`, *optional*):
|
| 125 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
BLENDERBOT_ENCODE_INPUTS_DOCSTRING = r"""
|
| 130 |
+
Args:
|
| 131 |
+
input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
|
| 132 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 133 |
+
it.
|
| 134 |
+
|
| 135 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 136 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 137 |
+
|
| 138 |
+
[What are input IDs?](../glossary#input-ids)
|
| 139 |
+
attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 140 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 141 |
+
|
| 142 |
+
- 1 for tokens that are **not masked**,
|
| 143 |
+
- 0 for tokens that are **masked**.
|
| 144 |
+
|
| 145 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 146 |
+
position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 147 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 148 |
+
config.max_position_embeddings - 1]`.
|
| 149 |
+
output_attentions (`bool`, *optional*):
|
| 150 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 151 |
+
tensors for more detail.
|
| 152 |
+
output_hidden_states (`bool`, *optional*):
|
| 153 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 154 |
+
more detail.
|
| 155 |
+
return_dict (`bool`, *optional*):
|
| 156 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 157 |
+
"""
|
| 158 |
+
|
| 159 |
+
BLENDERBOT_DECODE_INPUTS_DOCSTRING = r"""
|
| 160 |
+
Args:
|
| 161 |
+
decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`):
|
| 162 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 163 |
+
|
| 164 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 165 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 166 |
+
|
| 167 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 168 |
+
|
| 169 |
+
For translation and summarization training, `decoder_input_ids` should be provided. If no
|
| 170 |
+
`decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
|
| 171 |
+
for denoising pre-training following the paper.
|
| 172 |
+
encoder_outputs (`tuple(tuple(jnp.ndarray)`):
|
| 173 |
+
Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
|
| 174 |
+
`last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
|
| 175 |
+
hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
|
| 176 |
+
encoder_attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 177 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 178 |
+
|
| 179 |
+
- 1 for tokens that are **not masked**,
|
| 180 |
+
- 0 for tokens that are **masked**.
|
| 181 |
+
|
| 182 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 183 |
+
decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 184 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 185 |
+
be used by default.
|
| 186 |
+
|
| 187 |
+
If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the
|
| 188 |
+
paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
|
| 189 |
+
decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 190 |
+
Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
|
| 191 |
+
range `[0, config.max_position_embeddings - 1]`.
|
| 192 |
+
past_key_values (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`):
|
| 193 |
+
Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
|
| 194 |
+
auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
|
| 195 |
+
output_attentions (`bool`, *optional*):
|
| 196 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 197 |
+
tensors for more detail.
|
| 198 |
+
output_hidden_states (`bool`, *optional*):
|
| 199 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 200 |
+
more detail.
|
| 201 |
+
return_dict (`bool`, *optional*):
|
| 202 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# Copied from transformers.models.bart.modeling_flax_bart.shift_tokens_right
|
| 207 |
+
def shift_tokens_right(input_ids: jnp.ndarray, pad_token_id: int, decoder_start_token_id: int) -> jnp.ndarray:
|
| 208 |
+
"""
|
| 209 |
+
Shift input ids one token to the right.
|
| 210 |
+
"""
|
| 211 |
+
shifted_input_ids = jnp.zeros_like(input_ids)
|
| 212 |
+
shifted_input_ids = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1])
|
| 213 |
+
shifted_input_ids = shifted_input_ids.at[:, 0].set(decoder_start_token_id)
|
| 214 |
+
|
| 215 |
+
shifted_input_ids = jnp.where(shifted_input_ids == -100, pad_token_id, shifted_input_ids)
|
| 216 |
+
return shifted_input_ids
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartAttention with Bart->Blenderbot
|
| 220 |
+
class FlaxBlenderbotAttention(nn.Module):
|
| 221 |
+
config: BlenderbotConfig
|
| 222 |
+
embed_dim: int
|
| 223 |
+
num_heads: int
|
| 224 |
+
dropout: float = 0.0
|
| 225 |
+
causal: bool = False
|
| 226 |
+
bias: bool = True
|
| 227 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 228 |
+
|
| 229 |
+
def setup(self) -> None:
|
| 230 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 231 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 232 |
+
raise ValueError(
|
| 233 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 234 |
+
f" and `num_heads`: {self.num_heads})."
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
dense = partial(
|
| 238 |
+
nn.Dense,
|
| 239 |
+
self.embed_dim,
|
| 240 |
+
use_bias=self.bias,
|
| 241 |
+
dtype=self.dtype,
|
| 242 |
+
kernel_init=jax.nn.initializers.normal(self.config.init_std),
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
self.q_proj, self.k_proj, self.v_proj = dense(), dense(), dense()
|
| 246 |
+
self.out_proj = dense()
|
| 247 |
+
|
| 248 |
+
self.dropout_layer = nn.Dropout(rate=self.dropout)
|
| 249 |
+
|
| 250 |
+
if self.causal:
|
| 251 |
+
self.causal_mask = make_causal_mask(
|
| 252 |
+
jnp.ones((1, self.config.max_position_embeddings), dtype="bool"), dtype="bool"
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
def _split_heads(self, hidden_states):
|
| 256 |
+
return hidden_states.reshape(hidden_states.shape[:2] + (self.num_heads, self.head_dim))
|
| 257 |
+
|
| 258 |
+
def _merge_heads(self, hidden_states):
|
| 259 |
+
return hidden_states.reshape(hidden_states.shape[:2] + (self.embed_dim,))
|
| 260 |
+
|
| 261 |
+
@nn.compact
|
| 262 |
+
def _concatenate_to_cache(self, key, value, query, attention_mask):
|
| 263 |
+
"""
|
| 264 |
+
This function takes projected key, value states from a single input token and concatenates the states to cached
|
| 265 |
+
states from previous steps. This function is slightly adapted from the official Flax repository:
|
| 266 |
+
https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
|
| 267 |
+
"""
|
| 268 |
+
# detect if we're initializing by absence of existing cache data.
|
| 269 |
+
is_initialized = self.has_variable("cache", "cached_key")
|
| 270 |
+
cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
|
| 271 |
+
cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
|
| 272 |
+
cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
|
| 273 |
+
|
| 274 |
+
if is_initialized:
|
| 275 |
+
*batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
|
| 276 |
+
# update key, value caches with our new 1d spatial slices
|
| 277 |
+
cur_index = cache_index.value
|
| 278 |
+
indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
|
| 279 |
+
key = lax.dynamic_update_slice(cached_key.value, key, indices)
|
| 280 |
+
value = lax.dynamic_update_slice(cached_value.value, value, indices)
|
| 281 |
+
cached_key.value = key
|
| 282 |
+
cached_value.value = value
|
| 283 |
+
num_updated_cache_vectors = query.shape[1]
|
| 284 |
+
cache_index.value = cache_index.value + num_updated_cache_vectors
|
| 285 |
+
# causal mask for cached decoder self-attention: our single query position should only attend to those key positions that have already been generated and cached, not the remaining zero elements.
|
| 286 |
+
pad_mask = jnp.broadcast_to(
|
| 287 |
+
jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
|
| 288 |
+
tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
|
| 289 |
+
)
|
| 290 |
+
attention_mask = combine_masks(pad_mask, attention_mask)
|
| 291 |
+
return key, value, attention_mask
|
| 292 |
+
|
| 293 |
+
def __call__(
|
| 294 |
+
self,
|
| 295 |
+
hidden_states: jnp.ndarray,
|
| 296 |
+
key_value_states: Optional[jnp.ndarray] = None,
|
| 297 |
+
attention_mask: Optional[jnp.ndarray] = None,
|
| 298 |
+
init_cache: bool = False,
|
| 299 |
+
deterministic: bool = True,
|
| 300 |
+
) -> Tuple[jnp.ndarray]:
|
| 301 |
+
"""Input shape: Batch x Time x Channel"""
|
| 302 |
+
|
| 303 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 304 |
+
# for the decoder
|
| 305 |
+
is_cross_attention = key_value_states is not None
|
| 306 |
+
batch_size = hidden_states.shape[0]
|
| 307 |
+
|
| 308 |
+
# get query proj
|
| 309 |
+
query_states = self.q_proj(hidden_states)
|
| 310 |
+
# get key, value proj
|
| 311 |
+
if is_cross_attention:
|
| 312 |
+
# cross_attentions
|
| 313 |
+
key_states = self.k_proj(key_value_states)
|
| 314 |
+
value_states = self.v_proj(key_value_states)
|
| 315 |
+
else:
|
| 316 |
+
# self_attention
|
| 317 |
+
key_states = self.k_proj(hidden_states)
|
| 318 |
+
value_states = self.v_proj(hidden_states)
|
| 319 |
+
|
| 320 |
+
query_states = self._split_heads(query_states)
|
| 321 |
+
key_states = self._split_heads(key_states)
|
| 322 |
+
value_states = self._split_heads(value_states)
|
| 323 |
+
|
| 324 |
+
# handle cache prepare causal attention mask
|
| 325 |
+
if self.causal:
|
| 326 |
+
query_length, key_length = query_states.shape[1], key_states.shape[1]
|
| 327 |
+
if self.has_variable("cache", "cached_key"):
|
| 328 |
+
mask_shift = self.variables["cache"]["cache_index"]
|
| 329 |
+
max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
|
| 330 |
+
causal_mask = lax.dynamic_slice(
|
| 331 |
+
self.causal_mask, (0, 0, mask_shift, 0), (1, 1, query_length, max_decoder_length)
|
| 332 |
+
)
|
| 333 |
+
else:
|
| 334 |
+
causal_mask = self.causal_mask[:, :, :query_length, :key_length]
|
| 335 |
+
causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])
|
| 336 |
+
|
| 337 |
+
# combine masks if needed
|
| 338 |
+
if attention_mask is not None and self.causal:
|
| 339 |
+
attention_mask = jnp.broadcast_to(jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_mask.shape)
|
| 340 |
+
attention_mask = combine_masks(attention_mask, causal_mask)
|
| 341 |
+
elif self.causal:
|
| 342 |
+
attention_mask = causal_mask
|
| 343 |
+
elif attention_mask is not None:
|
| 344 |
+
attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))
|
| 345 |
+
|
| 346 |
+
# During fast autoregressive decoding, we feed one position at a time,
|
| 347 |
+
# and cache the keys and values step by step.
|
| 348 |
+
if self.causal and (self.has_variable("cache", "cached_key") or init_cache):
|
| 349 |
+
key_states, value_states, attention_mask = self._concatenate_to_cache(
|
| 350 |
+
key_states, value_states, query_states, attention_mask
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
# Convert the boolean attention mask to an attention bias.
|
| 354 |
+
if attention_mask is not None:
|
| 355 |
+
# attention mask in the form of attention bias
|
| 356 |
+
attention_bias = lax.select(
|
| 357 |
+
attention_mask > 0,
|
| 358 |
+
jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
|
| 359 |
+
jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
|
| 360 |
+
)
|
| 361 |
+
else:
|
| 362 |
+
attention_bias = None
|
| 363 |
+
|
| 364 |
+
dropout_rng = None
|
| 365 |
+
if not deterministic and self.dropout > 0.0:
|
| 366 |
+
dropout_rng = self.make_rng("dropout")
|
| 367 |
+
|
| 368 |
+
attn_weights = dot_product_attention_weights(
|
| 369 |
+
query_states,
|
| 370 |
+
key_states,
|
| 371 |
+
bias=attention_bias,
|
| 372 |
+
dropout_rng=dropout_rng,
|
| 373 |
+
dropout_rate=self.dropout,
|
| 374 |
+
broadcast_dropout=True,
|
| 375 |
+
deterministic=deterministic,
|
| 376 |
+
dtype=self.dtype,
|
| 377 |
+
precision=None,
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value_states)
|
| 381 |
+
attn_output = self._merge_heads(attn_output)
|
| 382 |
+
attn_output = self.out_proj(attn_output)
|
| 383 |
+
|
| 384 |
+
return attn_output, attn_weights
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
# Copied from transformers.models.mbart.modeling_flax_mbart.FlaxMBartEncoderLayer with MBart->Blenderbot
|
| 388 |
+
class FlaxBlenderbotEncoderLayer(nn.Module):
|
| 389 |
+
config: BlenderbotConfig
|
| 390 |
+
dtype: jnp.dtype = jnp.float32
|
| 391 |
+
|
| 392 |
+
def setup(self) -> None:
|
| 393 |
+
self.embed_dim = self.config.d_model
|
| 394 |
+
self.self_attn = FlaxBlenderbotAttention(
|
| 395 |
+
config=self.config,
|
| 396 |
+
embed_dim=self.embed_dim,
|
| 397 |
+
num_heads=self.config.encoder_attention_heads,
|
| 398 |
+
dropout=self.config.attention_dropout,
|
| 399 |
+
dtype=self.dtype,
|
| 400 |
+
)
|
| 401 |
+
self.self_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
|
| 402 |
+
self.dropout_layer = nn.Dropout(rate=self.config.dropout)
|
| 403 |
+
self.activation_fn = ACT2FN[self.config.activation_function]
|
| 404 |
+
self.activation_dropout_layer = nn.Dropout(rate=self.config.activation_dropout)
|
| 405 |
+
self.fc1 = nn.Dense(
|
| 406 |
+
self.config.encoder_ffn_dim,
|
| 407 |
+
dtype=self.dtype,
|
| 408 |
+
kernel_init=jax.nn.initializers.normal(self.config.init_std),
|
| 409 |
+
)
|
| 410 |
+
self.fc2 = nn.Dense(
|
| 411 |
+
self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(self.config.init_std)
|
| 412 |
+
)
|
| 413 |
+
self.final_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
|
| 414 |
+
|
| 415 |
+
def __call__(
|
| 416 |
+
self,
|
| 417 |
+
hidden_states: jnp.ndarray,
|
| 418 |
+
attention_mask: jnp.ndarray,
|
| 419 |
+
output_attentions: bool = True,
|
| 420 |
+
deterministic: bool = True,
|
| 421 |
+
) -> Tuple[jnp.ndarray]:
|
| 422 |
+
residual = hidden_states
|
| 423 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 424 |
+
hidden_states, attn_weights = self.self_attn(hidden_states=hidden_states, attention_mask=attention_mask)
|
| 425 |
+
hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
|
| 426 |
+
hidden_states = residual + hidden_states
|
| 427 |
+
|
| 428 |
+
residual = hidden_states
|
| 429 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 430 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 431 |
+
hidden_states = self.activation_dropout_layer(hidden_states, deterministic=deterministic)
|
| 432 |
+
hidden_states = self.fc2(hidden_states)
|
| 433 |
+
hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
|
| 434 |
+
hidden_states = residual + hidden_states
|
| 435 |
+
|
| 436 |
+
outputs = (hidden_states,)
|
| 437 |
+
|
| 438 |
+
if output_attentions:
|
| 439 |
+
outputs += (attn_weights,)
|
| 440 |
+
|
| 441 |
+
return outputs
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartEncoderLayerCollection with Bart->Blenderbot
|
| 445 |
+
class FlaxBlenderbotEncoderLayerCollection(nn.Module):
|
| 446 |
+
config: BlenderbotConfig
|
| 447 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 448 |
+
|
| 449 |
+
def setup(self):
|
| 450 |
+
self.layers = [
|
| 451 |
+
FlaxBlenderbotEncoderLayer(self.config, name=str(i), dtype=self.dtype)
|
| 452 |
+
for i in range(self.config.encoder_layers)
|
| 453 |
+
]
|
| 454 |
+
self.layerdrop = self.config.encoder_layerdrop
|
| 455 |
+
|
| 456 |
+
def __call__(
|
| 457 |
+
self,
|
| 458 |
+
hidden_states,
|
| 459 |
+
attention_mask,
|
| 460 |
+
deterministic: bool = True,
|
| 461 |
+
output_attentions: bool = False,
|
| 462 |
+
output_hidden_states: bool = False,
|
| 463 |
+
return_dict: bool = True,
|
| 464 |
+
):
|
| 465 |
+
all_attentions = () if output_attentions else None
|
| 466 |
+
all_hidden_states = () if output_hidden_states else None
|
| 467 |
+
|
| 468 |
+
for encoder_layer in self.layers:
|
| 469 |
+
if output_hidden_states:
|
| 470 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 471 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 472 |
+
dropout_probability = random.uniform(0, 1)
|
| 473 |
+
if not deterministic and (dropout_probability < self.layerdrop): # skip the layer
|
| 474 |
+
layer_outputs = (None, None)
|
| 475 |
+
else:
|
| 476 |
+
layer_outputs = encoder_layer(
|
| 477 |
+
hidden_states,
|
| 478 |
+
attention_mask,
|
| 479 |
+
output_attentions,
|
| 480 |
+
deterministic,
|
| 481 |
+
)
|
| 482 |
+
hidden_states = layer_outputs[0]
|
| 483 |
+
if output_attentions:
|
| 484 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 485 |
+
|
| 486 |
+
if output_hidden_states:
|
| 487 |
+
all_hidden_states += (hidden_states,)
|
| 488 |
+
|
| 489 |
+
outputs = (hidden_states, all_hidden_states, all_attentions)
|
| 490 |
+
|
| 491 |
+
if not return_dict:
|
| 492 |
+
return tuple(v for v in outputs if v is not None)
|
| 493 |
+
|
| 494 |
+
return FlaxBaseModelOutput(
|
| 495 |
+
last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
# Copied from transformers.models.mbart.modeling_flax_mbart.FlaxMBartDecoderLayer with MBart->Blenderbot
|
| 500 |
+
class FlaxBlenderbotDecoderLayer(nn.Module):
|
| 501 |
+
config: BlenderbotConfig
|
| 502 |
+
dtype: jnp.dtype = jnp.float32
|
| 503 |
+
|
| 504 |
+
def setup(self) -> None:
|
| 505 |
+
self.embed_dim = self.config.d_model
|
| 506 |
+
self.self_attn = FlaxBlenderbotAttention(
|
| 507 |
+
config=self.config,
|
| 508 |
+
embed_dim=self.embed_dim,
|
| 509 |
+
num_heads=self.config.decoder_attention_heads,
|
| 510 |
+
dropout=self.config.attention_dropout,
|
| 511 |
+
causal=True,
|
| 512 |
+
dtype=self.dtype,
|
| 513 |
+
)
|
| 514 |
+
self.dropout_layer = nn.Dropout(rate=self.config.dropout)
|
| 515 |
+
self.activation_fn = ACT2FN[self.config.activation_function]
|
| 516 |
+
self.activation_dropout_layer = nn.Dropout(rate=self.config.activation_dropout)
|
| 517 |
+
|
| 518 |
+
self.self_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
|
| 519 |
+
self.encoder_attn = FlaxBlenderbotAttention(
|
| 520 |
+
config=self.config,
|
| 521 |
+
embed_dim=self.embed_dim,
|
| 522 |
+
num_heads=self.config.decoder_attention_heads,
|
| 523 |
+
dropout=self.config.attention_dropout,
|
| 524 |
+
dtype=self.dtype,
|
| 525 |
+
)
|
| 526 |
+
self.encoder_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
|
| 527 |
+
self.fc1 = nn.Dense(
|
| 528 |
+
self.config.decoder_ffn_dim,
|
| 529 |
+
dtype=self.dtype,
|
| 530 |
+
kernel_init=jax.nn.initializers.normal(self.config.init_std),
|
| 531 |
+
)
|
| 532 |
+
self.fc2 = nn.Dense(
|
| 533 |
+
self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(self.config.init_std)
|
| 534 |
+
)
|
| 535 |
+
self.final_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
|
| 536 |
+
|
| 537 |
+
def __call__(
|
| 538 |
+
self,
|
| 539 |
+
hidden_states: jnp.ndarray,
|
| 540 |
+
attention_mask: jnp.ndarray,
|
| 541 |
+
encoder_hidden_states: Optional[jnp.ndarray] = None,
|
| 542 |
+
encoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 543 |
+
init_cache: bool = False,
|
| 544 |
+
output_attentions: bool = True,
|
| 545 |
+
deterministic: bool = True,
|
| 546 |
+
) -> Tuple[jnp.ndarray]:
|
| 547 |
+
residual = hidden_states
|
| 548 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 549 |
+
|
| 550 |
+
# Self Attention
|
| 551 |
+
hidden_states, self_attn_weights = self.self_attn(
|
| 552 |
+
hidden_states=hidden_states, attention_mask=attention_mask, init_cache=init_cache
|
| 553 |
+
)
|
| 554 |
+
hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
|
| 555 |
+
hidden_states = residual + hidden_states
|
| 556 |
+
|
| 557 |
+
# Cross-Attention Block
|
| 558 |
+
cross_attn_weights = None
|
| 559 |
+
if encoder_hidden_states is not None:
|
| 560 |
+
residual = hidden_states
|
| 561 |
+
|
| 562 |
+
hidden_states = self.encoder_attn_layer_norm(hidden_states)
|
| 563 |
+
hidden_states, cross_attn_weights = self.encoder_attn(
|
| 564 |
+
hidden_states=hidden_states,
|
| 565 |
+
key_value_states=encoder_hidden_states,
|
| 566 |
+
attention_mask=encoder_attention_mask,
|
| 567 |
+
)
|
| 568 |
+
hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
|
| 569 |
+
hidden_states = residual + hidden_states
|
| 570 |
+
|
| 571 |
+
# Fully Connected
|
| 572 |
+
residual = hidden_states
|
| 573 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 574 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 575 |
+
hidden_states = self.activation_dropout_layer(hidden_states, deterministic=deterministic)
|
| 576 |
+
hidden_states = self.fc2(hidden_states)
|
| 577 |
+
hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
|
| 578 |
+
hidden_states = residual + hidden_states
|
| 579 |
+
|
| 580 |
+
outputs = (hidden_states,)
|
| 581 |
+
|
| 582 |
+
if output_attentions:
|
| 583 |
+
outputs += (self_attn_weights, cross_attn_weights)
|
| 584 |
+
|
| 585 |
+
return outputs
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartDecoderLayerCollection with Bart->Blenderbot
|
| 589 |
+
class FlaxBlenderbotDecoderLayerCollection(nn.Module):
|
| 590 |
+
config: BlenderbotConfig
|
| 591 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 592 |
+
|
| 593 |
+
def setup(self):
|
| 594 |
+
self.layers = [
|
| 595 |
+
FlaxBlenderbotDecoderLayer(self.config, name=str(i), dtype=self.dtype)
|
| 596 |
+
for i in range(self.config.decoder_layers)
|
| 597 |
+
]
|
| 598 |
+
self.layerdrop = self.config.decoder_layerdrop
|
| 599 |
+
|
| 600 |
+
def __call__(
|
| 601 |
+
self,
|
| 602 |
+
hidden_states,
|
| 603 |
+
attention_mask,
|
| 604 |
+
encoder_hidden_states: Optional[jnp.ndarray] = None,
|
| 605 |
+
encoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 606 |
+
deterministic: bool = True,
|
| 607 |
+
init_cache: bool = False,
|
| 608 |
+
output_attentions: bool = False,
|
| 609 |
+
output_hidden_states: bool = False,
|
| 610 |
+
return_dict: bool = True,
|
| 611 |
+
):
|
| 612 |
+
# decoder layers
|
| 613 |
+
all_hidden_states = () if output_hidden_states else None
|
| 614 |
+
all_self_attns = () if output_attentions else None
|
| 615 |
+
all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
|
| 616 |
+
|
| 617 |
+
for decoder_layer in self.layers:
|
| 618 |
+
if output_hidden_states:
|
| 619 |
+
all_hidden_states += (hidden_states,)
|
| 620 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 621 |
+
dropout_probability = random.uniform(0, 1)
|
| 622 |
+
if not deterministic and (dropout_probability < self.layerdrop):
|
| 623 |
+
layer_outputs = (None, None, None)
|
| 624 |
+
else:
|
| 625 |
+
layer_outputs = decoder_layer(
|
| 626 |
+
hidden_states,
|
| 627 |
+
attention_mask=attention_mask,
|
| 628 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 629 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 630 |
+
init_cache=init_cache,
|
| 631 |
+
output_attentions=output_attentions,
|
| 632 |
+
deterministic=deterministic,
|
| 633 |
+
)
|
| 634 |
+
|
| 635 |
+
hidden_states = layer_outputs[0]
|
| 636 |
+
if output_attentions:
|
| 637 |
+
all_self_attns += (layer_outputs[1],)
|
| 638 |
+
|
| 639 |
+
if encoder_hidden_states is not None:
|
| 640 |
+
all_cross_attentions += (layer_outputs[2],)
|
| 641 |
+
|
| 642 |
+
# add hidden states from the last decoder layer
|
| 643 |
+
if output_hidden_states:
|
| 644 |
+
all_hidden_states += (hidden_states,)
|
| 645 |
+
|
| 646 |
+
outputs = [hidden_states, all_hidden_states, all_self_attns, all_cross_attentions]
|
| 647 |
+
|
| 648 |
+
if not return_dict:
|
| 649 |
+
return tuple(v for v in outputs if v is not None)
|
| 650 |
+
|
| 651 |
+
return FlaxBaseModelOutputWithPastAndCrossAttentions(
|
| 652 |
+
last_hidden_state=hidden_states,
|
| 653 |
+
hidden_states=all_hidden_states,
|
| 654 |
+
attentions=all_self_attns,
|
| 655 |
+
cross_attentions=all_cross_attentions,
|
| 656 |
+
)
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
class FlaxBlenderbotEncoder(nn.Module):
|
| 660 |
+
config: BlenderbotConfig
|
| 661 |
+
embed_tokens: nn.Embed
|
| 662 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 663 |
+
|
| 664 |
+
def setup(self):
|
| 665 |
+
self.dropout_layer = nn.Dropout(rate=self.config.dropout)
|
| 666 |
+
|
| 667 |
+
embed_dim = self.config.d_model
|
| 668 |
+
self.padding_idx = self.config.pad_token_id
|
| 669 |
+
self.max_source_positions = self.config.max_position_embeddings
|
| 670 |
+
self.embed_scale = math.sqrt(embed_dim) if self.config.scale_embedding else 1.0
|
| 671 |
+
|
| 672 |
+
self.embed_positions = nn.Embed(
|
| 673 |
+
self.config.max_position_embeddings,
|
| 674 |
+
embed_dim,
|
| 675 |
+
embedding_init=jax.nn.initializers.normal(self.config.init_std),
|
| 676 |
+
)
|
| 677 |
+
self.layers = FlaxBlenderbotEncoderLayerCollection(self.config, self.dtype)
|
| 678 |
+
self.layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
|
| 679 |
+
|
| 680 |
+
def __call__(
|
| 681 |
+
self,
|
| 682 |
+
input_ids,
|
| 683 |
+
attention_mask,
|
| 684 |
+
position_ids,
|
| 685 |
+
output_attentions: bool = False,
|
| 686 |
+
output_hidden_states: bool = False,
|
| 687 |
+
return_dict: bool = True,
|
| 688 |
+
deterministic: bool = True,
|
| 689 |
+
):
|
| 690 |
+
input_shape = input_ids.shape
|
| 691 |
+
input_ids = input_ids.reshape(-1, input_shape[-1])
|
| 692 |
+
|
| 693 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 694 |
+
|
| 695 |
+
embed_pos = self.embed_positions(position_ids)
|
| 696 |
+
|
| 697 |
+
hidden_states = inputs_embeds + embed_pos
|
| 698 |
+
hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
|
| 699 |
+
|
| 700 |
+
outputs = self.layers(
|
| 701 |
+
hidden_states,
|
| 702 |
+
attention_mask,
|
| 703 |
+
deterministic=deterministic,
|
| 704 |
+
output_attentions=output_attentions,
|
| 705 |
+
output_hidden_states=output_hidden_states,
|
| 706 |
+
return_dict=return_dict,
|
| 707 |
+
)
|
| 708 |
+
last_hidden_states = outputs[0]
|
| 709 |
+
last_hidden_states = self.layer_norm(last_hidden_states)
|
| 710 |
+
|
| 711 |
+
# update the last element in `hidden_states` after applying `layernorm` above
|
| 712 |
+
hidden_states = None
|
| 713 |
+
if output_hidden_states:
|
| 714 |
+
hidden_states = outputs[1]
|
| 715 |
+
hidden_states = hidden_states[:-1] + (last_hidden_states,)
|
| 716 |
+
|
| 717 |
+
if not return_dict:
|
| 718 |
+
outputs = (last_hidden_states, hidden_states) + (outputs[2:] if output_hidden_states else outputs[1:])
|
| 719 |
+
return tuple(v for v in outputs if v is not None)
|
| 720 |
+
|
| 721 |
+
return FlaxBaseModelOutput(
|
| 722 |
+
last_hidden_state=last_hidden_states,
|
| 723 |
+
hidden_states=hidden_states,
|
| 724 |
+
attentions=outputs.attentions,
|
| 725 |
+
)
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
class FlaxBlenderbotDecoder(nn.Module):
|
| 729 |
+
config: BlenderbotConfig
|
| 730 |
+
embed_tokens: nn.Embed
|
| 731 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 732 |
+
|
| 733 |
+
def setup(self):
|
| 734 |
+
self.dropout_layer = nn.Dropout(rate=self.config.dropout)
|
| 735 |
+
|
| 736 |
+
embed_dim = self.config.d_model
|
| 737 |
+
self.padding_idx = self.config.pad_token_id
|
| 738 |
+
self.max_target_positions = self.config.max_position_embeddings
|
| 739 |
+
self.embed_scale = math.sqrt(self.config.d_model) if self.config.scale_embedding else 1.0
|
| 740 |
+
|
| 741 |
+
self.embed_positions = nn.Embed(
|
| 742 |
+
self.config.max_position_embeddings,
|
| 743 |
+
embed_dim,
|
| 744 |
+
embedding_init=jax.nn.initializers.normal(self.config.init_std),
|
| 745 |
+
)
|
| 746 |
+
|
| 747 |
+
self.layers = FlaxBlenderbotDecoderLayerCollection(self.config, self.dtype)
|
| 748 |
+
self.layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
|
| 749 |
+
|
| 750 |
+
def __call__(
|
| 751 |
+
self,
|
| 752 |
+
input_ids,
|
| 753 |
+
attention_mask,
|
| 754 |
+
position_ids,
|
| 755 |
+
encoder_hidden_states: Optional[jnp.ndarray] = None,
|
| 756 |
+
encoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 757 |
+
init_cache: bool = False,
|
| 758 |
+
output_attentions: bool = False,
|
| 759 |
+
output_hidden_states: bool = False,
|
| 760 |
+
return_dict: bool = True,
|
| 761 |
+
deterministic: bool = True,
|
| 762 |
+
):
|
| 763 |
+
input_shape = input_ids.shape
|
| 764 |
+
input_ids = input_ids.reshape(-1, input_shape[-1])
|
| 765 |
+
|
| 766 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 767 |
+
|
| 768 |
+
# embed positions
|
| 769 |
+
positions = self.embed_positions(position_ids)
|
| 770 |
+
|
| 771 |
+
hidden_states = inputs_embeds + positions
|
| 772 |
+
hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
|
| 773 |
+
|
| 774 |
+
outputs = self.layers(
|
| 775 |
+
hidden_states,
|
| 776 |
+
attention_mask,
|
| 777 |
+
encoder_hidden_states,
|
| 778 |
+
encoder_attention_mask,
|
| 779 |
+
deterministic=deterministic,
|
| 780 |
+
init_cache=init_cache,
|
| 781 |
+
output_attentions=output_attentions,
|
| 782 |
+
output_hidden_states=output_hidden_states,
|
| 783 |
+
return_dict=return_dict,
|
| 784 |
+
)
|
| 785 |
+
|
| 786 |
+
last_hidden_states = outputs[0]
|
| 787 |
+
last_hidden_states = self.layer_norm(last_hidden_states)
|
| 788 |
+
|
| 789 |
+
# update the last element in `hidden_states` after applying `layernorm` above
|
| 790 |
+
hidden_states = None
|
| 791 |
+
if output_hidden_states:
|
| 792 |
+
hidden_states = outputs[1]
|
| 793 |
+
hidden_states = hidden_states[:-1] + (last_hidden_states,)
|
| 794 |
+
|
| 795 |
+
if not return_dict:
|
| 796 |
+
outputs = (last_hidden_states, hidden_states) + (outputs[2:] if output_hidden_states else outputs[1:])
|
| 797 |
+
return tuple(v for v in outputs if v is not None)
|
| 798 |
+
|
| 799 |
+
return FlaxBaseModelOutputWithPastAndCrossAttentions(
|
| 800 |
+
last_hidden_state=last_hidden_states,
|
| 801 |
+
hidden_states=hidden_states,
|
| 802 |
+
attentions=outputs.attentions,
|
| 803 |
+
cross_attentions=outputs.cross_attentions,
|
| 804 |
+
)
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartModule with Bart->Blenderbot
|
| 808 |
+
class FlaxBlenderbotModule(nn.Module):
|
| 809 |
+
config: BlenderbotConfig
|
| 810 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 811 |
+
|
| 812 |
+
def setup(self):
|
| 813 |
+
self.shared = nn.Embed(
|
| 814 |
+
self.config.vocab_size,
|
| 815 |
+
self.config.d_model,
|
| 816 |
+
embedding_init=jax.nn.initializers.normal(self.config.init_std),
|
| 817 |
+
dtype=self.dtype,
|
| 818 |
+
)
|
| 819 |
+
|
| 820 |
+
self.encoder = FlaxBlenderbotEncoder(self.config, dtype=self.dtype, embed_tokens=self.shared)
|
| 821 |
+
self.decoder = FlaxBlenderbotDecoder(self.config, dtype=self.dtype, embed_tokens=self.shared)
|
| 822 |
+
|
| 823 |
+
def _get_encoder_module(self):
|
| 824 |
+
return self.encoder
|
| 825 |
+
|
| 826 |
+
def _get_decoder_module(self):
|
| 827 |
+
return self.decoder
|
| 828 |
+
|
| 829 |
+
def __call__(
|
| 830 |
+
self,
|
| 831 |
+
input_ids,
|
| 832 |
+
attention_mask,
|
| 833 |
+
decoder_input_ids,
|
| 834 |
+
decoder_attention_mask,
|
| 835 |
+
position_ids,
|
| 836 |
+
decoder_position_ids,
|
| 837 |
+
output_attentions: bool = False,
|
| 838 |
+
output_hidden_states: bool = False,
|
| 839 |
+
return_dict: bool = True,
|
| 840 |
+
deterministic: bool = True,
|
| 841 |
+
):
|
| 842 |
+
encoder_outputs = self.encoder(
|
| 843 |
+
input_ids=input_ids,
|
| 844 |
+
attention_mask=attention_mask,
|
| 845 |
+
position_ids=position_ids,
|
| 846 |
+
output_attentions=output_attentions,
|
| 847 |
+
output_hidden_states=output_hidden_states,
|
| 848 |
+
return_dict=return_dict,
|
| 849 |
+
deterministic=deterministic,
|
| 850 |
+
)
|
| 851 |
+
|
| 852 |
+
decoder_outputs = self.decoder(
|
| 853 |
+
input_ids=decoder_input_ids,
|
| 854 |
+
attention_mask=decoder_attention_mask,
|
| 855 |
+
position_ids=decoder_position_ids,
|
| 856 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 857 |
+
encoder_attention_mask=attention_mask,
|
| 858 |
+
output_attentions=output_attentions,
|
| 859 |
+
output_hidden_states=output_hidden_states,
|
| 860 |
+
return_dict=return_dict,
|
| 861 |
+
deterministic=deterministic,
|
| 862 |
+
)
|
| 863 |
+
|
| 864 |
+
if not return_dict:
|
| 865 |
+
return decoder_outputs + encoder_outputs
|
| 866 |
+
|
| 867 |
+
return FlaxSeq2SeqModelOutput(
|
| 868 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 869 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 870 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 871 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 872 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 873 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 874 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 875 |
+
)
|
| 876 |
+
|
| 877 |
+
|
| 878 |
+
class FlaxBlenderbotPreTrainedModel(FlaxPreTrainedModel):
|
| 879 |
+
config_class = BlenderbotConfig
|
| 880 |
+
base_model_prefix: str = "model"
|
| 881 |
+
module_class: nn.Module = None
|
| 882 |
+
|
| 883 |
+
def __init__(
|
| 884 |
+
self,
|
| 885 |
+
config: BlenderbotConfig,
|
| 886 |
+
input_shape: Tuple[int] = (1, 1),
|
| 887 |
+
seed: int = 0,
|
| 888 |
+
dtype: jnp.dtype = jnp.float32,
|
| 889 |
+
_do_init: bool = True,
|
| 890 |
+
**kwargs,
|
| 891 |
+
):
|
| 892 |
+
module = self.module_class(config=config, dtype=dtype, **kwargs)
|
| 893 |
+
super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
|
| 894 |
+
|
| 895 |
+
def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
|
| 896 |
+
# init input tensors
|
| 897 |
+
input_ids = jnp.zeros(input_shape, dtype="i4")
|
| 898 |
+
# make sure initialization pass will work for FlaxBlenderbotForSequenceClassificationModule
|
| 899 |
+
input_ids = input_ids.at[(..., -1)].set(self.config.eos_token_id)
|
| 900 |
+
attention_mask = jnp.ones_like(input_ids)
|
| 901 |
+
decoder_input_ids = input_ids
|
| 902 |
+
decoder_attention_mask = jnp.ones_like(input_ids)
|
| 903 |
+
|
| 904 |
+
batch_size, sequence_length = input_ids.shape
|
| 905 |
+
position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
|
| 906 |
+
decoder_position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
|
| 907 |
+
|
| 908 |
+
params_rng, dropout_rng = jax.random.split(rng)
|
| 909 |
+
rngs = {"params": params_rng, "dropout": dropout_rng}
|
| 910 |
+
|
| 911 |
+
random_params = self.module.init(
|
| 912 |
+
rngs,
|
| 913 |
+
input_ids,
|
| 914 |
+
attention_mask,
|
| 915 |
+
decoder_input_ids,
|
| 916 |
+
decoder_attention_mask,
|
| 917 |
+
position_ids,
|
| 918 |
+
decoder_position_ids,
|
| 919 |
+
)["params"]
|
| 920 |
+
|
| 921 |
+
if params is not None:
|
| 922 |
+
random_params = flatten_dict(unfreeze(random_params))
|
| 923 |
+
params = flatten_dict(unfreeze(params))
|
| 924 |
+
for missing_key in self._missing_keys:
|
| 925 |
+
params[missing_key] = random_params[missing_key]
|
| 926 |
+
self._missing_keys = set()
|
| 927 |
+
return freeze(unflatten_dict(params))
|
| 928 |
+
else:
|
| 929 |
+
return random_params
|
| 930 |
+
|
| 931 |
+
def init_cache(self, batch_size, max_length, encoder_outputs):
|
| 932 |
+
r"""
|
| 933 |
+
Args:
|
| 934 |
+
batch_size (`int`):
|
| 935 |
+
batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
|
| 936 |
+
max_length (`int`):
|
| 937 |
+
maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
|
| 938 |
+
cache.
|
| 939 |
+
encoder_outputs (`Union[FlaxBaseModelOutput, tuple(tuple(jnp.ndarray)]`):
|
| 940 |
+
`encoder_outputs` consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*:
|
| 941 |
+
`attentions`). `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*)
|
| 942 |
+
is a sequence of hidden-states at the output of the last layer of the encoder. Used in the
|
| 943 |
+
cross-attention of the decoder.
|
| 944 |
+
"""
|
| 945 |
+
# init input variables to retrieve cache
|
| 946 |
+
decoder_input_ids = jnp.ones((batch_size, max_length), dtype="i4")
|
| 947 |
+
decoder_attention_mask = jnp.ones_like(decoder_input_ids)
|
| 948 |
+
decoder_position_ids = jnp.broadcast_to(
|
| 949 |
+
jnp.arange(jnp.atleast_2d(decoder_input_ids).shape[-1]), decoder_input_ids.shape
|
| 950 |
+
)
|
| 951 |
+
|
| 952 |
+
def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
|
| 953 |
+
decoder_module = module._get_decoder_module()
|
| 954 |
+
return decoder_module(
|
| 955 |
+
decoder_input_ids,
|
| 956 |
+
decoder_attention_mask,
|
| 957 |
+
decoder_position_ids,
|
| 958 |
+
**kwargs,
|
| 959 |
+
)
|
| 960 |
+
|
| 961 |
+
init_variables = self.module.init(
|
| 962 |
+
jax.random.PRNGKey(0),
|
| 963 |
+
decoder_input_ids=decoder_input_ids,
|
| 964 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 965 |
+
decoder_position_ids=decoder_position_ids,
|
| 966 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 967 |
+
init_cache=True,
|
| 968 |
+
method=_decoder_forward, # we only need to call the decoder to init the cache
|
| 969 |
+
)
|
| 970 |
+
return unfreeze(init_variables["cache"])
|
| 971 |
+
|
| 972 |
+
@add_start_docstrings(BLENDERBOT_ENCODE_INPUTS_DOCSTRING)
|
| 973 |
+
@replace_return_docstrings(output_type=FlaxBaseModelOutput, config_class=BlenderbotConfig)
|
| 974 |
+
def encode(
|
| 975 |
+
self,
|
| 976 |
+
input_ids: jnp.ndarray,
|
| 977 |
+
attention_mask: Optional[jnp.ndarray] = None,
|
| 978 |
+
position_ids: Optional[jnp.ndarray] = None,
|
| 979 |
+
output_attentions: Optional[bool] = None,
|
| 980 |
+
output_hidden_states: Optional[bool] = None,
|
| 981 |
+
return_dict: Optional[bool] = None,
|
| 982 |
+
train: bool = False,
|
| 983 |
+
params: dict = None,
|
| 984 |
+
dropout_rng: PRNGKey = None,
|
| 985 |
+
):
|
| 986 |
+
r"""
|
| 987 |
+
Returns:
|
| 988 |
+
|
| 989 |
+
Example:
|
| 990 |
+
|
| 991 |
+
```python
|
| 992 |
+
>>> from transformers import AutoTokenizer, FlaxBlenderbotForConditionalGeneration
|
| 993 |
+
|
| 994 |
+
>>> model = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-400M-distill")
|
| 995 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
|
| 996 |
+
|
| 997 |
+
>>> text = "My friends are cool but they eat too many carbs."
|
| 998 |
+
>>> inputs = tokenizer(text, max_length=1024, return_tensors="jax")
|
| 999 |
+
>>> encoder_outputs = model.encode(**inputs)
|
| 1000 |
+
```"""
|
| 1001 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1002 |
+
output_hidden_states = (
|
| 1003 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1004 |
+
)
|
| 1005 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1006 |
+
|
| 1007 |
+
if attention_mask is None:
|
| 1008 |
+
attention_mask = jnp.ones_like(input_ids)
|
| 1009 |
+
if position_ids is None:
|
| 1010 |
+
batch_size, sequence_length = input_ids.shape
|
| 1011 |
+
position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
|
| 1012 |
+
|
| 1013 |
+
# Handle any PRNG if needed
|
| 1014 |
+
rngs = {}
|
| 1015 |
+
if dropout_rng is not None:
|
| 1016 |
+
rngs["dropout"] = dropout_rng
|
| 1017 |
+
|
| 1018 |
+
def _encoder_forward(module, input_ids, attention_mask, position_ids, **kwargs):
|
| 1019 |
+
encode_module = module._get_encoder_module()
|
| 1020 |
+
return encode_module(input_ids, attention_mask, position_ids, **kwargs)
|
| 1021 |
+
|
| 1022 |
+
return self.module.apply(
|
| 1023 |
+
{"params": params or self.params},
|
| 1024 |
+
input_ids=jnp.array(input_ids, dtype="i4"),
|
| 1025 |
+
attention_mask=jnp.array(attention_mask, dtype="i4"),
|
| 1026 |
+
position_ids=jnp.array(position_ids, dtype="i4"),
|
| 1027 |
+
output_attentions=output_attentions,
|
| 1028 |
+
output_hidden_states=output_hidden_states,
|
| 1029 |
+
return_dict=return_dict,
|
| 1030 |
+
deterministic=not train,
|
| 1031 |
+
rngs=rngs,
|
| 1032 |
+
method=_encoder_forward,
|
| 1033 |
+
)
|
| 1034 |
+
|
| 1035 |
+
@add_start_docstrings(BLENDERBOT_DECODE_INPUTS_DOCSTRING)
|
| 1036 |
+
@replace_return_docstrings(
|
| 1037 |
+
output_type=FlaxBaseModelOutputWithPastAndCrossAttentions, config_class=BlenderbotConfig
|
| 1038 |
+
)
|
| 1039 |
+
def decode(
|
| 1040 |
+
self,
|
| 1041 |
+
decoder_input_ids,
|
| 1042 |
+
encoder_outputs,
|
| 1043 |
+
encoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 1044 |
+
decoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 1045 |
+
decoder_position_ids: Optional[jnp.ndarray] = None,
|
| 1046 |
+
past_key_values: dict = None,
|
| 1047 |
+
output_attentions: Optional[bool] = None,
|
| 1048 |
+
output_hidden_states: Optional[bool] = None,
|
| 1049 |
+
return_dict: Optional[bool] = None,
|
| 1050 |
+
train: bool = False,
|
| 1051 |
+
params: dict = None,
|
| 1052 |
+
dropout_rng: PRNGKey = None,
|
| 1053 |
+
):
|
| 1054 |
+
r"""
|
| 1055 |
+
Returns:
|
| 1056 |
+
|
| 1057 |
+
Example:
|
| 1058 |
+
|
| 1059 |
+
```python
|
| 1060 |
+
>>> import jax.numpy as jnp
|
| 1061 |
+
>>> from transformers import AutoTokenizer, FlaxBlenderbotForConditionalGeneration
|
| 1062 |
+
|
| 1063 |
+
>>> model = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-400M-distill")
|
| 1064 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
|
| 1065 |
+
|
| 1066 |
+
>>> text = "My friends are cool but they eat too many carbs."
|
| 1067 |
+
>>> inputs = tokenizer(text, max_length=1024, return_tensors="jax")
|
| 1068 |
+
>>> encoder_outputs = model.encode(**inputs)
|
| 1069 |
+
|
| 1070 |
+
>>> decoder_start_token_id = model.config.decoder_start_token_id
|
| 1071 |
+
>>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id
|
| 1072 |
+
|
| 1073 |
+
>>> outputs = model.decode(decoder_input_ids, encoder_outputs)
|
| 1074 |
+
>>> last_decoder_hidden_states = outputs.last_hidden_state
|
| 1075 |
+
```"""
|
| 1076 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1077 |
+
output_hidden_states = (
|
| 1078 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1079 |
+
)
|
| 1080 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1081 |
+
|
| 1082 |
+
encoder_hidden_states = encoder_outputs[0]
|
| 1083 |
+
if encoder_attention_mask is None:
|
| 1084 |
+
batch_size, sequence_length = encoder_hidden_states.shape[:2]
|
| 1085 |
+
encoder_attention_mask = jnp.ones((batch_size, sequence_length))
|
| 1086 |
+
|
| 1087 |
+
batch_size, sequence_length = decoder_input_ids.shape
|
| 1088 |
+
if decoder_attention_mask is None:
|
| 1089 |
+
decoder_attention_mask = jnp.ones((batch_size, sequence_length))
|
| 1090 |
+
|
| 1091 |
+
if decoder_position_ids is None:
|
| 1092 |
+
if past_key_values is not None:
|
| 1093 |
+
raise ValueError("Make sure to provide `decoder_position_ids` when passing `past_key_values`.")
|
| 1094 |
+
|
| 1095 |
+
decoder_position_ids = jnp.broadcast_to(
|
| 1096 |
+
jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
|
| 1097 |
+
)
|
| 1098 |
+
|
| 1099 |
+
# Handle any PRNG if needed
|
| 1100 |
+
rngs = {}
|
| 1101 |
+
if dropout_rng is not None:
|
| 1102 |
+
rngs["dropout"] = dropout_rng
|
| 1103 |
+
|
| 1104 |
+
inputs = {"params": params or self.params}
|
| 1105 |
+
|
| 1106 |
+
# if past_key_values are passed then cache is already initialized a private flag init_cache has to be
|
| 1107 |
+
# passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that
|
| 1108 |
+
# it can be changed by FlaxBlenderbotAttention module
|
| 1109 |
+
if past_key_values:
|
| 1110 |
+
inputs["cache"] = past_key_values
|
| 1111 |
+
mutable = ["cache"]
|
| 1112 |
+
else:
|
| 1113 |
+
mutable = False
|
| 1114 |
+
|
| 1115 |
+
def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
|
| 1116 |
+
decoder_module = module._get_decoder_module()
|
| 1117 |
+
return decoder_module(
|
| 1118 |
+
decoder_input_ids,
|
| 1119 |
+
decoder_attention_mask,
|
| 1120 |
+
decoder_position_ids,
|
| 1121 |
+
**kwargs,
|
| 1122 |
+
)
|
| 1123 |
+
|
| 1124 |
+
outputs = self.module.apply(
|
| 1125 |
+
inputs,
|
| 1126 |
+
decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
|
| 1127 |
+
decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
|
| 1128 |
+
decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
|
| 1129 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1130 |
+
encoder_attention_mask=jnp.array(encoder_attention_mask, dtype="i4"),
|
| 1131 |
+
output_attentions=output_attentions,
|
| 1132 |
+
output_hidden_states=output_hidden_states,
|
| 1133 |
+
return_dict=return_dict,
|
| 1134 |
+
deterministic=not train,
|
| 1135 |
+
rngs=rngs,
|
| 1136 |
+
mutable=mutable,
|
| 1137 |
+
method=_decoder_forward,
|
| 1138 |
+
)
|
| 1139 |
+
|
| 1140 |
+
# add updated cache to model output
|
| 1141 |
+
if past_key_values is not None and return_dict:
|
| 1142 |
+
outputs, past = outputs
|
| 1143 |
+
outputs["past_key_values"] = unfreeze(past["cache"])
|
| 1144 |
+
return outputs
|
| 1145 |
+
elif past_key_values is not None and not return_dict:
|
| 1146 |
+
outputs, past = outputs
|
| 1147 |
+
outputs = outputs[:1] + (unfreeze(past["cache"]),) + outputs[1:]
|
| 1148 |
+
|
| 1149 |
+
return outputs
|
| 1150 |
+
|
| 1151 |
+
@add_start_docstrings_to_model_forward(BLENDERBOT_INPUTS_DOCSTRING)
|
| 1152 |
+
def __call__(
|
| 1153 |
+
self,
|
| 1154 |
+
input_ids: jnp.ndarray,
|
| 1155 |
+
attention_mask: Optional[jnp.ndarray] = None,
|
| 1156 |
+
decoder_input_ids: Optional[jnp.ndarray] = None,
|
| 1157 |
+
decoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 1158 |
+
position_ids: Optional[jnp.ndarray] = None,
|
| 1159 |
+
decoder_position_ids: Optional[jnp.ndarray] = None,
|
| 1160 |
+
output_attentions: Optional[bool] = None,
|
| 1161 |
+
output_hidden_states: Optional[bool] = None,
|
| 1162 |
+
return_dict: Optional[bool] = None,
|
| 1163 |
+
train: bool = False,
|
| 1164 |
+
params: dict = None,
|
| 1165 |
+
dropout_rng: PRNGKey = None,
|
| 1166 |
+
):
|
| 1167 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1168 |
+
output_hidden_states = (
|
| 1169 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1170 |
+
)
|
| 1171 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1172 |
+
|
| 1173 |
+
# prepare encoder inputs
|
| 1174 |
+
if attention_mask is None:
|
| 1175 |
+
attention_mask = jnp.ones_like(input_ids)
|
| 1176 |
+
if position_ids is None:
|
| 1177 |
+
batch_size, sequence_length = input_ids.shape
|
| 1178 |
+
position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
|
| 1179 |
+
|
| 1180 |
+
# prepare decoder inputs
|
| 1181 |
+
if decoder_input_ids is None:
|
| 1182 |
+
decoder_input_ids = shift_tokens_right(
|
| 1183 |
+
input_ids, self.config.pad_token_id, decoder_start_token_id=self.config.decoder_start_token_id
|
| 1184 |
+
)
|
| 1185 |
+
if decoder_attention_mask is None:
|
| 1186 |
+
decoder_attention_mask = jnp.ones_like(decoder_input_ids)
|
| 1187 |
+
if decoder_position_ids is None:
|
| 1188 |
+
batch_size, sequence_length = decoder_input_ids.shape
|
| 1189 |
+
decoder_position_ids = jnp.broadcast_to(
|
| 1190 |
+
jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
|
| 1191 |
+
)
|
| 1192 |
+
|
| 1193 |
+
# Handle any PRNG if needed
|
| 1194 |
+
rngs = {"dropout": dropout_rng} if dropout_rng is not None else {}
|
| 1195 |
+
|
| 1196 |
+
return self.module.apply(
|
| 1197 |
+
{"params": params or self.params},
|
| 1198 |
+
input_ids=jnp.array(input_ids, dtype="i4"),
|
| 1199 |
+
attention_mask=jnp.array(attention_mask, dtype="i4"),
|
| 1200 |
+
position_ids=jnp.array(position_ids, dtype="i4"),
|
| 1201 |
+
decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
|
| 1202 |
+
decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
|
| 1203 |
+
decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
|
| 1204 |
+
output_attentions=output_attentions,
|
| 1205 |
+
output_hidden_states=output_hidden_states,
|
| 1206 |
+
return_dict=return_dict,
|
| 1207 |
+
deterministic=not train,
|
| 1208 |
+
rngs=rngs,
|
| 1209 |
+
)
|
| 1210 |
+
|
| 1211 |
+
|
| 1212 |
+
@add_start_docstrings(
|
| 1213 |
+
"The bare MBart Model transformer outputting raw hidden-states without any specific head on top.",
|
| 1214 |
+
BLENDERBOT_START_DOCSTRING,
|
| 1215 |
+
)
|
| 1216 |
+
class FlaxBlenderbotModel(FlaxBlenderbotPreTrainedModel):
|
| 1217 |
+
config: BlenderbotConfig
|
| 1218 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 1219 |
+
module_class = FlaxBlenderbotModule
|
| 1220 |
+
|
| 1221 |
+
|
| 1222 |
+
append_call_sample_docstring(FlaxBlenderbotModel, _CHECKPOINT_FOR_DOC, FlaxSeq2SeqModelOutput, _CONFIG_FOR_DOC)
|
| 1223 |
+
|
| 1224 |
+
|
| 1225 |
+
# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartForConditionalGenerationModule with Bart->Blenderbot
|
| 1226 |
+
class FlaxBlenderbotForConditionalGenerationModule(nn.Module):
|
| 1227 |
+
config: BlenderbotConfig
|
| 1228 |
+
dtype: jnp.dtype = jnp.float32
|
| 1229 |
+
bias_init: Callable[..., jnp.ndarray] = jax.nn.initializers.zeros
|
| 1230 |
+
|
| 1231 |
+
def setup(self):
|
| 1232 |
+
self.model = FlaxBlenderbotModule(config=self.config, dtype=self.dtype)
|
| 1233 |
+
self.lm_head = nn.Dense(
|
| 1234 |
+
self.model.shared.num_embeddings,
|
| 1235 |
+
use_bias=False,
|
| 1236 |
+
dtype=self.dtype,
|
| 1237 |
+
kernel_init=jax.nn.initializers.normal(self.config.init_std),
|
| 1238 |
+
)
|
| 1239 |
+
self.final_logits_bias = self.param("final_logits_bias", self.bias_init, (1, self.model.shared.num_embeddings))
|
| 1240 |
+
|
| 1241 |
+
def _get_encoder_module(self):
|
| 1242 |
+
return self.model.encoder
|
| 1243 |
+
|
| 1244 |
+
def _get_decoder_module(self):
|
| 1245 |
+
return self.model.decoder
|
| 1246 |
+
|
| 1247 |
+
def __call__(
|
| 1248 |
+
self,
|
| 1249 |
+
input_ids,
|
| 1250 |
+
attention_mask,
|
| 1251 |
+
decoder_input_ids,
|
| 1252 |
+
decoder_attention_mask,
|
| 1253 |
+
position_ids,
|
| 1254 |
+
decoder_position_ids,
|
| 1255 |
+
output_attentions: bool = False,
|
| 1256 |
+
output_hidden_states: bool = False,
|
| 1257 |
+
return_dict: bool = True,
|
| 1258 |
+
deterministic: bool = True,
|
| 1259 |
+
):
|
| 1260 |
+
outputs = self.model(
|
| 1261 |
+
input_ids=input_ids,
|
| 1262 |
+
attention_mask=attention_mask,
|
| 1263 |
+
decoder_input_ids=decoder_input_ids,
|
| 1264 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1265 |
+
position_ids=position_ids,
|
| 1266 |
+
decoder_position_ids=decoder_position_ids,
|
| 1267 |
+
output_attentions=output_attentions,
|
| 1268 |
+
output_hidden_states=output_hidden_states,
|
| 1269 |
+
return_dict=return_dict,
|
| 1270 |
+
deterministic=deterministic,
|
| 1271 |
+
)
|
| 1272 |
+
|
| 1273 |
+
hidden_states = outputs[0]
|
| 1274 |
+
|
| 1275 |
+
if self.config.tie_word_embeddings:
|
| 1276 |
+
shared_embedding = self.model.variables["params"]["shared"]["embedding"]
|
| 1277 |
+
lm_logits = self.lm_head.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
|
| 1278 |
+
else:
|
| 1279 |
+
lm_logits = self.lm_head(hidden_states)
|
| 1280 |
+
|
| 1281 |
+
lm_logits += jax.lax.stop_gradient(self.final_logits_bias.astype(self.dtype))
|
| 1282 |
+
|
| 1283 |
+
if not return_dict:
|
| 1284 |
+
output = (lm_logits,) + outputs[1:]
|
| 1285 |
+
return output
|
| 1286 |
+
|
| 1287 |
+
return FlaxSeq2SeqLMOutput(
|
| 1288 |
+
logits=lm_logits,
|
| 1289 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 1290 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 1291 |
+
cross_attentions=outputs.cross_attentions,
|
| 1292 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 1293 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 1294 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 1295 |
+
)
|
| 1296 |
+
|
| 1297 |
+
|
| 1298 |
+
@add_start_docstrings(
|
| 1299 |
+
"The Blenderbot Model with a language modeling head. Can be used for summarization.", BLENDERBOT_START_DOCSTRING
|
| 1300 |
+
)
|
| 1301 |
+
class FlaxBlenderbotForConditionalGeneration(FlaxBlenderbotPreTrainedModel):
|
| 1302 |
+
module_class = FlaxBlenderbotForConditionalGenerationModule
|
| 1303 |
+
dtype: jnp.dtype = jnp.float32
|
| 1304 |
+
|
| 1305 |
+
@add_start_docstrings(BLENDERBOT_DECODE_INPUTS_DOCSTRING)
|
| 1306 |
+
@replace_return_docstrings(output_type=FlaxCausalLMOutputWithCrossAttentions, config_class=BlenderbotConfig)
|
| 1307 |
+
def decode(
|
| 1308 |
+
self,
|
| 1309 |
+
decoder_input_ids,
|
| 1310 |
+
encoder_outputs,
|
| 1311 |
+
encoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 1312 |
+
decoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 1313 |
+
decoder_position_ids: Optional[jnp.ndarray] = None,
|
| 1314 |
+
past_key_values: dict = None,
|
| 1315 |
+
output_attentions: Optional[bool] = None,
|
| 1316 |
+
output_hidden_states: Optional[bool] = None,
|
| 1317 |
+
return_dict: Optional[bool] = None,
|
| 1318 |
+
train: bool = False,
|
| 1319 |
+
params: dict = None,
|
| 1320 |
+
dropout_rng: PRNGKey = None,
|
| 1321 |
+
):
|
| 1322 |
+
r"""
|
| 1323 |
+
Returns:
|
| 1324 |
+
|
| 1325 |
+
Example:
|
| 1326 |
+
|
| 1327 |
+
```python
|
| 1328 |
+
>>> import jax.numpy as jnp
|
| 1329 |
+
>>> from transformers import AutoTokenizer, FlaxBlenderbotForConditionalGeneration
|
| 1330 |
+
|
| 1331 |
+
>>> model = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-400M-distill")
|
| 1332 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
|
| 1333 |
+
|
| 1334 |
+
>>> text = "My friends are cool but they eat too many carbs."
|
| 1335 |
+
>>> inputs = tokenizer(text, max_length=1024, return_tensors="jax")
|
| 1336 |
+
>>> encoder_outputs = model.encode(**inputs)
|
| 1337 |
+
|
| 1338 |
+
>>> decoder_start_token_id = model.config.decoder_start_token_id
|
| 1339 |
+
>>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id
|
| 1340 |
+
|
| 1341 |
+
>>> outputs = model.decode(decoder_input_ids, encoder_outputs)
|
| 1342 |
+
>>> logits = outputs.logits
|
| 1343 |
+
```"""
|
| 1344 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1345 |
+
output_hidden_states = (
|
| 1346 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1347 |
+
)
|
| 1348 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1349 |
+
|
| 1350 |
+
encoder_hidden_states = encoder_outputs[0]
|
| 1351 |
+
if encoder_attention_mask is None:
|
| 1352 |
+
batch_size, sequence_length = encoder_hidden_states.shape[:2]
|
| 1353 |
+
encoder_attention_mask = jnp.ones((batch_size, sequence_length))
|
| 1354 |
+
|
| 1355 |
+
batch_size, sequence_length = decoder_input_ids.shape
|
| 1356 |
+
if decoder_attention_mask is None:
|
| 1357 |
+
decoder_attention_mask = jnp.ones((batch_size, sequence_length))
|
| 1358 |
+
|
| 1359 |
+
if decoder_position_ids is None:
|
| 1360 |
+
if past_key_values is not None:
|
| 1361 |
+
raise ValueError("Make sure to provide `decoder_position_ids` when passing `past_key_values`.")
|
| 1362 |
+
|
| 1363 |
+
decoder_position_ids = jnp.broadcast_to(
|
| 1364 |
+
jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
|
| 1365 |
+
)
|
| 1366 |
+
|
| 1367 |
+
# Handle any PRNG if needed
|
| 1368 |
+
rngs = {}
|
| 1369 |
+
if dropout_rng is not None:
|
| 1370 |
+
rngs["dropout"] = dropout_rng
|
| 1371 |
+
|
| 1372 |
+
inputs = {"params": params or self.params}
|
| 1373 |
+
|
| 1374 |
+
# if past_key_values are passed then cache is already initialized a private flag init_cache has to be
|
| 1375 |
+
# passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that
|
| 1376 |
+
# it can be changed by FlaxBlenderbotAttention module
|
| 1377 |
+
if past_key_values:
|
| 1378 |
+
inputs["cache"] = past_key_values
|
| 1379 |
+
mutable = ["cache"]
|
| 1380 |
+
else:
|
| 1381 |
+
mutable = False
|
| 1382 |
+
|
| 1383 |
+
def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
|
| 1384 |
+
decoder_module = module._get_decoder_module()
|
| 1385 |
+
outputs = decoder_module(
|
| 1386 |
+
decoder_input_ids,
|
| 1387 |
+
decoder_attention_mask,
|
| 1388 |
+
decoder_position_ids,
|
| 1389 |
+
**kwargs,
|
| 1390 |
+
)
|
| 1391 |
+
hidden_states = outputs[0]
|
| 1392 |
+
|
| 1393 |
+
if self.config.tie_word_embeddings:
|
| 1394 |
+
shared_embedding = module.model.variables["params"]["shared"]["embedding"]
|
| 1395 |
+
lm_logits = module.lm_head.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
|
| 1396 |
+
else:
|
| 1397 |
+
lm_logits = module.lm_head(hidden_states)
|
| 1398 |
+
|
| 1399 |
+
lm_logits += module.final_logits_bias
|
| 1400 |
+
return lm_logits, outputs
|
| 1401 |
+
|
| 1402 |
+
outputs = self.module.apply(
|
| 1403 |
+
inputs,
|
| 1404 |
+
decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
|
| 1405 |
+
decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
|
| 1406 |
+
decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
|
| 1407 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1408 |
+
encoder_attention_mask=jnp.array(encoder_attention_mask, dtype="i4"),
|
| 1409 |
+
output_attentions=output_attentions,
|
| 1410 |
+
output_hidden_states=output_hidden_states,
|
| 1411 |
+
return_dict=return_dict,
|
| 1412 |
+
deterministic=not train,
|
| 1413 |
+
rngs=rngs,
|
| 1414 |
+
mutable=mutable,
|
| 1415 |
+
method=_decoder_forward,
|
| 1416 |
+
)
|
| 1417 |
+
|
| 1418 |
+
if past_key_values is None:
|
| 1419 |
+
lm_logits, decoder_outputs = outputs
|
| 1420 |
+
else:
|
| 1421 |
+
(lm_logits, decoder_outputs), past = outputs
|
| 1422 |
+
|
| 1423 |
+
if return_dict:
|
| 1424 |
+
outputs = FlaxCausalLMOutputWithCrossAttentions(
|
| 1425 |
+
logits=lm_logits,
|
| 1426 |
+
hidden_states=decoder_outputs.hidden_states,
|
| 1427 |
+
attentions=decoder_outputs.attentions,
|
| 1428 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 1429 |
+
)
|
| 1430 |
+
else:
|
| 1431 |
+
outputs = (lm_logits,) + decoder_outputs[1:]
|
| 1432 |
+
|
| 1433 |
+
# add updated cache to model output
|
| 1434 |
+
if past_key_values is not None and return_dict:
|
| 1435 |
+
outputs["past_key_values"] = unfreeze(past["cache"])
|
| 1436 |
+
return outputs
|
| 1437 |
+
elif past_key_values is not None and not return_dict:
|
| 1438 |
+
outputs = outputs[:1] + (unfreeze(past["cache"]),) + outputs[1:]
|
| 1439 |
+
|
| 1440 |
+
return outputs
|
| 1441 |
+
|
| 1442 |
+
def prepare_inputs_for_generation(
|
| 1443 |
+
self,
|
| 1444 |
+
decoder_input_ids,
|
| 1445 |
+
max_length,
|
| 1446 |
+
attention_mask: Optional[jax.Array] = None,
|
| 1447 |
+
decoder_attention_mask: Optional[jax.Array] = None,
|
| 1448 |
+
encoder_outputs=None,
|
| 1449 |
+
**kwargs,
|
| 1450 |
+
):
|
| 1451 |
+
# initializing the cache
|
| 1452 |
+
batch_size, seq_length = decoder_input_ids.shape
|
| 1453 |
+
|
| 1454 |
+
past_key_values = self.init_cache(batch_size, max_length, encoder_outputs)
|
| 1455 |
+
# Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
|
| 1456 |
+
# But since the decoder uses a causal mask, those positions are masked anyways.
|
| 1457 |
+
# Thus we can create a single static attention_mask here, which is more efficient for compilation
|
| 1458 |
+
extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
|
| 1459 |
+
if decoder_attention_mask is not None:
|
| 1460 |
+
position_ids = decoder_attention_mask.cumsum(axis=-1) - 1
|
| 1461 |
+
extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, decoder_attention_mask, (0, 0))
|
| 1462 |
+
else:
|
| 1463 |
+
position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length))
|
| 1464 |
+
|
| 1465 |
+
return {
|
| 1466 |
+
"past_key_values": past_key_values,
|
| 1467 |
+
"encoder_outputs": encoder_outputs,
|
| 1468 |
+
"encoder_attention_mask": attention_mask,
|
| 1469 |
+
"decoder_attention_mask": extended_attention_mask,
|
| 1470 |
+
"decoder_position_ids": position_ids,
|
| 1471 |
+
}
|
| 1472 |
+
|
| 1473 |
+
def update_inputs_for_generation(self, model_outputs, model_kwargs):
|
| 1474 |
+
model_kwargs["past_key_values"] = model_outputs.past_key_values
|
| 1475 |
+
model_kwargs["decoder_position_ids"] = model_kwargs["decoder_position_ids"][:, -1:] + 1
|
| 1476 |
+
return model_kwargs
|
| 1477 |
+
|
| 1478 |
+
|
| 1479 |
+
FLAX_BLENDERBOT_CONDITIONAL_GENERATION_DOCSTRING = r"""
|
| 1480 |
+
Returns:
|
| 1481 |
+
|
| 1482 |
+
Conversation example::
|
| 1483 |
+
|
| 1484 |
+
```py
|
| 1485 |
+
>>> from transformers import AutoTokenizer, FlaxBlenderbotForConditionalGeneration
|
| 1486 |
+
|
| 1487 |
+
>>> model = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-400M-distill")
|
| 1488 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
|
| 1489 |
+
|
| 1490 |
+
>>> UTTERANCE = "My friends are cool but they eat too many carbs."
|
| 1491 |
+
>>> inputs = tokenizer([UTTERANCE], max_length=1024, return_tensors="np")
|
| 1492 |
+
|
| 1493 |
+
>>> # Generate Reply
|
| 1494 |
+
>>> reply_ids = model.generate(inputs["input_ids"], num_beams=4, max_length=5, early_stopping=True).sequences
|
| 1495 |
+
>>> print([tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=False) for g in reply_ids])
|
| 1496 |
+
```
|
| 1497 |
+
"""
|
| 1498 |
+
|
| 1499 |
+
overwrite_call_docstring(
|
| 1500 |
+
FlaxBlenderbotForConditionalGeneration,
|
| 1501 |
+
BLENDERBOT_INPUTS_DOCSTRING + FLAX_BLENDERBOT_CONDITIONAL_GENERATION_DOCSTRING,
|
| 1502 |
+
)
|
| 1503 |
+
append_replace_return_docstrings(
|
| 1504 |
+
FlaxBlenderbotForConditionalGeneration, output_type=FlaxSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC
|
| 1505 |
+
)
|
| 1506 |
+
|
| 1507 |
+
|
| 1508 |
+
__all__ = ["FlaxBlenderbotForConditionalGeneration", "FlaxBlenderbotModel", "FlaxBlenderbotPreTrainedModel"]
|
lib/python3.12/site-packages/transformers/models/blenderbot/modeling_tf_blenderbot.py
ADDED
|
@@ -0,0 +1,1558 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The Facebook, Inc and The HuggingFace Inc. team. 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 |
+
"""TF 2.0 Blenderbot model."""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import os
|
| 20 |
+
import random
|
| 21 |
+
import warnings
|
| 22 |
+
from typing import List, Optional, Tuple, Union
|
| 23 |
+
|
| 24 |
+
import tensorflow as tf
|
| 25 |
+
|
| 26 |
+
from ...activations_tf import get_tf_activation
|
| 27 |
+
from ...modeling_tf_outputs import (
|
| 28 |
+
TFBaseModelOutput,
|
| 29 |
+
TFBaseModelOutputWithPastAndCrossAttentions,
|
| 30 |
+
TFSeq2SeqLMOutput,
|
| 31 |
+
TFSeq2SeqModelOutput,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
# Public API
|
| 35 |
+
from ...modeling_tf_utils import (
|
| 36 |
+
TFCausalLanguageModelingLoss,
|
| 37 |
+
TFPreTrainedModel,
|
| 38 |
+
keras,
|
| 39 |
+
keras_serializable,
|
| 40 |
+
unpack_inputs,
|
| 41 |
+
)
|
| 42 |
+
from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
|
| 43 |
+
from ...utils import (
|
| 44 |
+
add_code_sample_docstrings,
|
| 45 |
+
add_end_docstrings,
|
| 46 |
+
add_start_docstrings,
|
| 47 |
+
add_start_docstrings_to_model_forward,
|
| 48 |
+
logging,
|
| 49 |
+
replace_return_docstrings,
|
| 50 |
+
)
|
| 51 |
+
from .configuration_blenderbot import BlenderbotConfig
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
logger = logging.get_logger(__name__)
|
| 55 |
+
|
| 56 |
+
_CHECKPOINT_FOR_DOC = "facebook/blenderbot-400M-distill"
|
| 57 |
+
_CONFIG_FOR_DOC = "BlenderbotConfig"
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
LARGE_NEGATIVE = -1e8
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# Copied from transformers.models.bart.modeling_tf_bart.shift_tokens_right
|
| 64 |
+
def shift_tokens_right(input_ids: tf.Tensor, pad_token_id: int, decoder_start_token_id: int):
|
| 65 |
+
pad_token_id = tf.cast(pad_token_id, input_ids.dtype)
|
| 66 |
+
decoder_start_token_id = tf.cast(decoder_start_token_id, input_ids.dtype)
|
| 67 |
+
start_tokens = tf.fill(
|
| 68 |
+
(shape_list(input_ids)[0], 1), tf.convert_to_tensor(decoder_start_token_id, input_ids.dtype)
|
| 69 |
+
)
|
| 70 |
+
shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1)
|
| 71 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 72 |
+
shifted_input_ids = tf.where(
|
| 73 |
+
shifted_input_ids == -100,
|
| 74 |
+
tf.fill(shape_list(shifted_input_ids), tf.convert_to_tensor(pad_token_id, input_ids.dtype)),
|
| 75 |
+
shifted_input_ids,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
# "Verify that `labels` has only positive values and -100"
|
| 79 |
+
assert_gte0 = tf.debugging.assert_greater_equal(shifted_input_ids, tf.constant(0, dtype=input_ids.dtype))
|
| 80 |
+
|
| 81 |
+
# Make sure the assertion op is called by wrapping the result in an identity no-op
|
| 82 |
+
with tf.control_dependencies([assert_gte0]):
|
| 83 |
+
shifted_input_ids = tf.identity(shifted_input_ids)
|
| 84 |
+
|
| 85 |
+
return shifted_input_ids
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# Copied from transformers.models.bart.modeling_tf_bart._make_causal_mask
|
| 89 |
+
def _make_causal_mask(input_ids_shape: tf.TensorShape, past_key_values_length: int = 0):
|
| 90 |
+
"""
|
| 91 |
+
Make causal mask used for bi-directional self-attention.
|
| 92 |
+
"""
|
| 93 |
+
bsz = input_ids_shape[0]
|
| 94 |
+
tgt_len = input_ids_shape[1]
|
| 95 |
+
mask = tf.ones((tgt_len, tgt_len)) * LARGE_NEGATIVE
|
| 96 |
+
mask_cond = tf.range(shape_list(mask)[-1])
|
| 97 |
+
|
| 98 |
+
mask = tf.where(mask_cond < tf.reshape(mask_cond + 1, (shape_list(mask)[-1], 1)), 0.0, mask)
|
| 99 |
+
|
| 100 |
+
if past_key_values_length > 0:
|
| 101 |
+
mask = tf.concat([tf.zeros((tgt_len, past_key_values_length)), mask], axis=-1)
|
| 102 |
+
|
| 103 |
+
return tf.tile(mask[None, None, :, :], (bsz, 1, 1, 1))
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
# Copied from transformers.models.bart.modeling_tf_bart._expand_mask
|
| 107 |
+
def _expand_mask(mask: tf.Tensor, tgt_len: Optional[int] = None):
|
| 108 |
+
"""
|
| 109 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
| 110 |
+
"""
|
| 111 |
+
src_len = shape_list(mask)[1]
|
| 112 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
| 113 |
+
one_cst = tf.constant(1.0)
|
| 114 |
+
mask = tf.cast(mask, dtype=one_cst.dtype)
|
| 115 |
+
expanded_mask = tf.tile(mask[:, None, None, :], (1, 1, tgt_len, 1))
|
| 116 |
+
|
| 117 |
+
return (one_cst - expanded_mask) * LARGE_NEGATIVE
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class TFBlenderbotLearnedPositionalEmbedding(keras.layers.Embedding):
|
| 121 |
+
"""
|
| 122 |
+
This module learns positional embeddings up to a fixed maximum size.
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
def __init__(self, num_embeddings: int, embedding_dim: int, **kwargs):
|
| 126 |
+
super().__init__(num_embeddings, embedding_dim, **kwargs)
|
| 127 |
+
|
| 128 |
+
def call(
|
| 129 |
+
self, input_shape: tf.TensorShape, past_key_values_length: int = 0, position_ids: tf.Tensor | None = None
|
| 130 |
+
):
|
| 131 |
+
"""Input is expected to be of size [bsz x seqlen]."""
|
| 132 |
+
if position_ids is None:
|
| 133 |
+
seq_len = input_shape[1]
|
| 134 |
+
position_ids = tf.range(seq_len, delta=1, name="range")
|
| 135 |
+
position_ids += past_key_values_length
|
| 136 |
+
|
| 137 |
+
return super().call(tf.cast(position_ids, dtype=tf.int32))
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# Copied from transformers.models.bart.modeling_tf_bart.TFBartAttention with Bart->Blenderbot
|
| 141 |
+
class TFBlenderbotAttention(keras.layers.Layer):
|
| 142 |
+
"""Multi-headed attention from "Attention Is All You Need"""
|
| 143 |
+
|
| 144 |
+
def __init__(
|
| 145 |
+
self,
|
| 146 |
+
embed_dim: int,
|
| 147 |
+
num_heads: int,
|
| 148 |
+
dropout: float = 0.0,
|
| 149 |
+
is_decoder: bool = False,
|
| 150 |
+
bias: bool = True,
|
| 151 |
+
**kwargs,
|
| 152 |
+
):
|
| 153 |
+
super().__init__(**kwargs)
|
| 154 |
+
self.embed_dim = embed_dim
|
| 155 |
+
|
| 156 |
+
self.num_heads = num_heads
|
| 157 |
+
self.dropout = keras.layers.Dropout(dropout)
|
| 158 |
+
self.head_dim = embed_dim // num_heads
|
| 159 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 160 |
+
raise ValueError(
|
| 161 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 162 |
+
f" and `num_heads`: {num_heads})."
|
| 163 |
+
)
|
| 164 |
+
self.scaling = self.head_dim**-0.5
|
| 165 |
+
self.is_decoder = is_decoder
|
| 166 |
+
|
| 167 |
+
self.k_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="k_proj")
|
| 168 |
+
self.q_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="q_proj")
|
| 169 |
+
self.v_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="v_proj")
|
| 170 |
+
self.out_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="out_proj")
|
| 171 |
+
|
| 172 |
+
def _shape(self, tensor: tf.Tensor, seq_len: int, bsz: int):
|
| 173 |
+
return tf.transpose(tf.reshape(tensor, (bsz, seq_len, self.num_heads, self.head_dim)), (0, 2, 1, 3))
|
| 174 |
+
|
| 175 |
+
def call(
|
| 176 |
+
self,
|
| 177 |
+
hidden_states: tf.Tensor,
|
| 178 |
+
key_value_states: tf.Tensor | None = None,
|
| 179 |
+
past_key_value: Tuple[Tuple[tf.Tensor]] | None = None,
|
| 180 |
+
attention_mask: tf.Tensor | None = None,
|
| 181 |
+
layer_head_mask: tf.Tensor | None = None,
|
| 182 |
+
training: Optional[bool] = False,
|
| 183 |
+
) -> Tuple[tf.Tensor, tf.Tensor | None]:
|
| 184 |
+
"""Input shape: Batch x Time x Channel"""
|
| 185 |
+
|
| 186 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 187 |
+
# for the decoder
|
| 188 |
+
is_cross_attention = key_value_states is not None
|
| 189 |
+
bsz, tgt_len, embed_dim = shape_list(hidden_states)
|
| 190 |
+
|
| 191 |
+
# get query proj
|
| 192 |
+
query_states = self.q_proj(hidden_states) * self.scaling
|
| 193 |
+
# get key, value proj
|
| 194 |
+
if is_cross_attention and past_key_value is not None:
|
| 195 |
+
# reuse k,v, cross_attentions
|
| 196 |
+
key_states = past_key_value[0]
|
| 197 |
+
value_states = past_key_value[1]
|
| 198 |
+
elif is_cross_attention:
|
| 199 |
+
# cross_attentions
|
| 200 |
+
key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
|
| 201 |
+
value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
|
| 202 |
+
elif past_key_value is not None:
|
| 203 |
+
# reuse k, v, self_attention
|
| 204 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 205 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 206 |
+
key_states = tf.concat([past_key_value[0], key_states], axis=2)
|
| 207 |
+
value_states = tf.concat([past_key_value[1], value_states], axis=2)
|
| 208 |
+
else:
|
| 209 |
+
# self_attention
|
| 210 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 211 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 212 |
+
|
| 213 |
+
if self.is_decoder:
|
| 214 |
+
# if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.
|
| 215 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 216 |
+
# key/value_states (first "if" case)
|
| 217 |
+
# if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of
|
| 218 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 219 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 220 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 221 |
+
past_key_value = (key_states, value_states)
|
| 222 |
+
|
| 223 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 224 |
+
query_states = tf.reshape(self._shape(query_states, tgt_len, bsz), proj_shape)
|
| 225 |
+
key_states = tf.reshape(key_states, proj_shape)
|
| 226 |
+
value_states = tf.reshape(value_states, proj_shape)
|
| 227 |
+
|
| 228 |
+
src_len = shape_list(key_states)[1]
|
| 229 |
+
attn_weights = tf.matmul(query_states, key_states, transpose_b=True)
|
| 230 |
+
|
| 231 |
+
tf.debugging.assert_equal(
|
| 232 |
+
shape_list(attn_weights),
|
| 233 |
+
[bsz * self.num_heads, tgt_len, src_len],
|
| 234 |
+
message=(
|
| 235 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 236 |
+
f" {shape_list(attn_weights)}"
|
| 237 |
+
),
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
if attention_mask is not None:
|
| 241 |
+
tf.debugging.assert_equal(
|
| 242 |
+
shape_list(attention_mask),
|
| 243 |
+
[bsz, 1, tgt_len, src_len],
|
| 244 |
+
message=(
|
| 245 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
|
| 246 |
+
f" {shape_list(attention_mask)}"
|
| 247 |
+
),
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
attention_mask = tf.cast(attention_mask, dtype=attn_weights.dtype)
|
| 251 |
+
attn_weights = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len)) + attention_mask
|
| 252 |
+
attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
|
| 253 |
+
|
| 254 |
+
attn_weights = stable_softmax(attn_weights, axis=-1)
|
| 255 |
+
|
| 256 |
+
if layer_head_mask is not None:
|
| 257 |
+
tf.debugging.assert_equal(
|
| 258 |
+
shape_list(layer_head_mask),
|
| 259 |
+
[self.num_heads],
|
| 260 |
+
message=(
|
| 261 |
+
f"Head mask for a single layer should be of size {(self.num_heads)}, but is"
|
| 262 |
+
f" {shape_list(layer_head_mask)}"
|
| 263 |
+
),
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape(
|
| 267 |
+
attn_weights, (bsz, self.num_heads, tgt_len, src_len)
|
| 268 |
+
)
|
| 269 |
+
attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
|
| 270 |
+
|
| 271 |
+
attn_probs = self.dropout(attn_weights, training=training)
|
| 272 |
+
attn_output = tf.matmul(attn_probs, value_states)
|
| 273 |
+
|
| 274 |
+
tf.debugging.assert_equal(
|
| 275 |
+
shape_list(attn_output),
|
| 276 |
+
[bsz * self.num_heads, tgt_len, self.head_dim],
|
| 277 |
+
message=(
|
| 278 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 279 |
+
f" {shape_list(attn_output)}"
|
| 280 |
+
),
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
attn_output = tf.transpose(
|
| 284 |
+
tf.reshape(attn_output, (bsz, self.num_heads, tgt_len, self.head_dim)), (0, 2, 1, 3)
|
| 285 |
+
)
|
| 286 |
+
attn_output = tf.reshape(attn_output, (bsz, tgt_len, embed_dim))
|
| 287 |
+
|
| 288 |
+
attn_output = self.out_proj(attn_output)
|
| 289 |
+
attn_weights: tf.Tensor = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len))
|
| 290 |
+
|
| 291 |
+
return attn_output, attn_weights, past_key_value
|
| 292 |
+
|
| 293 |
+
def build(self, input_shape=None):
|
| 294 |
+
if self.built:
|
| 295 |
+
return
|
| 296 |
+
self.built = True
|
| 297 |
+
if getattr(self, "k_proj", None) is not None:
|
| 298 |
+
with tf.name_scope(self.k_proj.name):
|
| 299 |
+
self.k_proj.build([None, None, self.embed_dim])
|
| 300 |
+
if getattr(self, "q_proj", None) is not None:
|
| 301 |
+
with tf.name_scope(self.q_proj.name):
|
| 302 |
+
self.q_proj.build([None, None, self.embed_dim])
|
| 303 |
+
if getattr(self, "v_proj", None) is not None:
|
| 304 |
+
with tf.name_scope(self.v_proj.name):
|
| 305 |
+
self.v_proj.build([None, None, self.embed_dim])
|
| 306 |
+
if getattr(self, "out_proj", None) is not None:
|
| 307 |
+
with tf.name_scope(self.out_proj.name):
|
| 308 |
+
self.out_proj.build([None, None, self.embed_dim])
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
# Copied from transformers.models.mbart.modeling_tf_mbart.TFMBartEncoderLayer with MBart->Blenderbot
|
| 312 |
+
class TFBlenderbotEncoderLayer(keras.layers.Layer):
|
| 313 |
+
def __init__(self, config: BlenderbotConfig, **kwargs):
|
| 314 |
+
super().__init__(**kwargs)
|
| 315 |
+
self.embed_dim = config.d_model
|
| 316 |
+
self.self_attn = TFBlenderbotAttention(
|
| 317 |
+
self.embed_dim, config.encoder_attention_heads, dropout=config.attention_dropout, name="self_attn"
|
| 318 |
+
)
|
| 319 |
+
self.self_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm")
|
| 320 |
+
self.dropout = keras.layers.Dropout(config.dropout)
|
| 321 |
+
self.activation_fn = get_tf_activation(config.activation_function)
|
| 322 |
+
self.activation_dropout = keras.layers.Dropout(config.activation_dropout)
|
| 323 |
+
self.fc1 = keras.layers.Dense(config.encoder_ffn_dim, name="fc1")
|
| 324 |
+
self.fc2 = keras.layers.Dense(self.embed_dim, name="fc2")
|
| 325 |
+
self.final_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
|
| 326 |
+
self.config = config
|
| 327 |
+
|
| 328 |
+
def call(
|
| 329 |
+
self,
|
| 330 |
+
hidden_states: tf.Tensor,
|
| 331 |
+
attention_mask: tf.Tensor,
|
| 332 |
+
layer_head_mask: tf.Tensor,
|
| 333 |
+
training: Optional[bool] = False,
|
| 334 |
+
):
|
| 335 |
+
"""
|
| 336 |
+
Args:
|
| 337 |
+
hidden_states (`tf.Tensor`): input to the layer of shape *(batch, seq_len, embed_dim)*
|
| 338 |
+
attention_mask (`tf.Tensor`): attention mask of size
|
| 339 |
+
*(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
|
| 340 |
+
layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size
|
| 341 |
+
*(encoder_attention_heads,)*
|
| 342 |
+
"""
|
| 343 |
+
residual = hidden_states
|
| 344 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 345 |
+
hidden_states, self_attn_weights, _ = self.self_attn(
|
| 346 |
+
hidden_states=hidden_states, attention_mask=attention_mask, layer_head_mask=layer_head_mask
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
tf.debugging.assert_equal(
|
| 350 |
+
shape_list(hidden_states),
|
| 351 |
+
shape_list(residual),
|
| 352 |
+
message=f"Self attn modified the shape of query {shape_list(residual)} to {shape_list(hidden_states)}",
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 356 |
+
hidden_states = residual + hidden_states
|
| 357 |
+
|
| 358 |
+
residual = hidden_states
|
| 359 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 360 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 361 |
+
hidden_states = self.activation_dropout(hidden_states, training=training)
|
| 362 |
+
hidden_states = self.fc2(hidden_states)
|
| 363 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 364 |
+
hidden_states = residual + hidden_states
|
| 365 |
+
|
| 366 |
+
return hidden_states, self_attn_weights
|
| 367 |
+
|
| 368 |
+
def build(self, input_shape=None):
|
| 369 |
+
if self.built:
|
| 370 |
+
return
|
| 371 |
+
self.built = True
|
| 372 |
+
if getattr(self, "self_attn", None) is not None:
|
| 373 |
+
with tf.name_scope(self.self_attn.name):
|
| 374 |
+
self.self_attn.build(None)
|
| 375 |
+
if getattr(self, "self_attn_layer_norm", None) is not None:
|
| 376 |
+
with tf.name_scope(self.self_attn_layer_norm.name):
|
| 377 |
+
self.self_attn_layer_norm.build([None, None, self.embed_dim])
|
| 378 |
+
if getattr(self, "fc1", None) is not None:
|
| 379 |
+
with tf.name_scope(self.fc1.name):
|
| 380 |
+
self.fc1.build([None, None, self.embed_dim])
|
| 381 |
+
if getattr(self, "fc2", None) is not None:
|
| 382 |
+
with tf.name_scope(self.fc2.name):
|
| 383 |
+
self.fc2.build([None, None, self.config.encoder_ffn_dim])
|
| 384 |
+
if getattr(self, "final_layer_norm", None) is not None:
|
| 385 |
+
with tf.name_scope(self.final_layer_norm.name):
|
| 386 |
+
self.final_layer_norm.build([None, None, self.embed_dim])
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
# Copied from transformers.models.mbart.modeling_tf_mbart.TFMBartDecoderLayer with MBart->Blenderbot
|
| 390 |
+
class TFBlenderbotDecoderLayer(keras.layers.Layer):
|
| 391 |
+
def __init__(self, config: BlenderbotConfig, **kwargs):
|
| 392 |
+
super().__init__(**kwargs)
|
| 393 |
+
self.embed_dim = config.d_model
|
| 394 |
+
self.self_attn = TFBlenderbotAttention(
|
| 395 |
+
embed_dim=self.embed_dim,
|
| 396 |
+
num_heads=config.decoder_attention_heads,
|
| 397 |
+
dropout=config.attention_dropout,
|
| 398 |
+
name="self_attn",
|
| 399 |
+
is_decoder=True,
|
| 400 |
+
)
|
| 401 |
+
self.dropout = keras.layers.Dropout(config.dropout)
|
| 402 |
+
self.activation_fn = get_tf_activation(config.activation_function)
|
| 403 |
+
self.activation_dropout = keras.layers.Dropout(config.activation_dropout)
|
| 404 |
+
|
| 405 |
+
self.self_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm")
|
| 406 |
+
self.encoder_attn = TFBlenderbotAttention(
|
| 407 |
+
self.embed_dim,
|
| 408 |
+
config.decoder_attention_heads,
|
| 409 |
+
dropout=config.attention_dropout,
|
| 410 |
+
name="encoder_attn",
|
| 411 |
+
is_decoder=True,
|
| 412 |
+
)
|
| 413 |
+
self.encoder_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="encoder_attn_layer_norm")
|
| 414 |
+
self.fc1 = keras.layers.Dense(config.decoder_ffn_dim, name="fc1")
|
| 415 |
+
self.fc2 = keras.layers.Dense(self.embed_dim, name="fc2")
|
| 416 |
+
self.final_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
|
| 417 |
+
self.config = config
|
| 418 |
+
|
| 419 |
+
def call(
|
| 420 |
+
self,
|
| 421 |
+
hidden_states: tf.Tensor,
|
| 422 |
+
attention_mask: tf.Tensor | None = None,
|
| 423 |
+
encoder_hidden_states: tf.Tensor | None = None,
|
| 424 |
+
encoder_attention_mask: tf.Tensor | None = None,
|
| 425 |
+
layer_head_mask: tf.Tensor | None = None,
|
| 426 |
+
cross_attn_layer_head_mask: tf.Tensor | None = None,
|
| 427 |
+
past_key_value: Tuple[tf.Tensor] | None = None,
|
| 428 |
+
training: Optional[bool] = False,
|
| 429 |
+
) -> Tuple[tf.Tensor, tf.Tensor, Tuple[Tuple[tf.Tensor]]]:
|
| 430 |
+
"""
|
| 431 |
+
Args:
|
| 432 |
+
hidden_states (`tf.Tensor`): input to the layer of shape *(batch, seq_len, embed_dim)*
|
| 433 |
+
attention_mask (`tf.Tensor`): attention mask of size
|
| 434 |
+
*(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
|
| 435 |
+
encoder_hidden_states (`tf.Tensor`):
|
| 436 |
+
cross attention input to the layer of shape *(batch, seq_len, embed_dim)*
|
| 437 |
+
encoder_attention_mask (`tf.Tensor`): encoder attention mask of size
|
| 438 |
+
*(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
|
| 439 |
+
layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size
|
| 440 |
+
*(decoder_attention_heads,)*
|
| 441 |
+
cross_attn_layer_head_mask (`tf.Tensor`): mask for heads of the cross-attention module.
|
| 442 |
+
*(decoder_attention_heads,)*
|
| 443 |
+
past_key_value (`Tuple(tf.Tensor)`): cached past key and value projection states
|
| 444 |
+
"""
|
| 445 |
+
residual = hidden_states
|
| 446 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 447 |
+
|
| 448 |
+
# Self Attention
|
| 449 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 450 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 451 |
+
# add present self-attn cache to positions 1,2 of present_key_value tuple
|
| 452 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 453 |
+
hidden_states=hidden_states,
|
| 454 |
+
past_key_value=self_attn_past_key_value,
|
| 455 |
+
attention_mask=attention_mask,
|
| 456 |
+
layer_head_mask=layer_head_mask,
|
| 457 |
+
)
|
| 458 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 459 |
+
hidden_states = residual + hidden_states
|
| 460 |
+
|
| 461 |
+
# Cross-Attention Block
|
| 462 |
+
cross_attn_present_key_value = None
|
| 463 |
+
cross_attn_weights = None
|
| 464 |
+
if encoder_hidden_states is not None:
|
| 465 |
+
residual = hidden_states
|
| 466 |
+
hidden_states = self.encoder_attn_layer_norm(hidden_states)
|
| 467 |
+
|
| 468 |
+
# cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
|
| 469 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 470 |
+
hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
|
| 471 |
+
hidden_states=hidden_states,
|
| 472 |
+
key_value_states=encoder_hidden_states,
|
| 473 |
+
attention_mask=encoder_attention_mask,
|
| 474 |
+
layer_head_mask=cross_attn_layer_head_mask,
|
| 475 |
+
past_key_value=cross_attn_past_key_value,
|
| 476 |
+
)
|
| 477 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 478 |
+
hidden_states = residual + hidden_states
|
| 479 |
+
|
| 480 |
+
# add cross-attn to positions 3,4 of present_key_value tuple
|
| 481 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 482 |
+
|
| 483 |
+
# Fully Connected
|
| 484 |
+
residual = hidden_states
|
| 485 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 486 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 487 |
+
hidden_states = self.activation_dropout(hidden_states, training=training)
|
| 488 |
+
hidden_states = self.fc2(hidden_states)
|
| 489 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 490 |
+
hidden_states = residual + hidden_states
|
| 491 |
+
|
| 492 |
+
return (
|
| 493 |
+
hidden_states,
|
| 494 |
+
self_attn_weights,
|
| 495 |
+
cross_attn_weights,
|
| 496 |
+
present_key_value,
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
def build(self, input_shape=None):
|
| 500 |
+
if self.built:
|
| 501 |
+
return
|
| 502 |
+
self.built = True
|
| 503 |
+
if getattr(self, "self_attn", None) is not None:
|
| 504 |
+
with tf.name_scope(self.self_attn.name):
|
| 505 |
+
self.self_attn.build(None)
|
| 506 |
+
if getattr(self, "self_attn_layer_norm", None) is not None:
|
| 507 |
+
with tf.name_scope(self.self_attn_layer_norm.name):
|
| 508 |
+
self.self_attn_layer_norm.build([None, None, self.embed_dim])
|
| 509 |
+
if getattr(self, "encoder_attn", None) is not None:
|
| 510 |
+
with tf.name_scope(self.encoder_attn.name):
|
| 511 |
+
self.encoder_attn.build(None)
|
| 512 |
+
if getattr(self, "encoder_attn_layer_norm", None) is not None:
|
| 513 |
+
with tf.name_scope(self.encoder_attn_layer_norm.name):
|
| 514 |
+
self.encoder_attn_layer_norm.build([None, None, self.embed_dim])
|
| 515 |
+
if getattr(self, "fc1", None) is not None:
|
| 516 |
+
with tf.name_scope(self.fc1.name):
|
| 517 |
+
self.fc1.build([None, None, self.embed_dim])
|
| 518 |
+
if getattr(self, "fc2", None) is not None:
|
| 519 |
+
with tf.name_scope(self.fc2.name):
|
| 520 |
+
self.fc2.build([None, None, self.config.decoder_ffn_dim])
|
| 521 |
+
if getattr(self, "final_layer_norm", None) is not None:
|
| 522 |
+
with tf.name_scope(self.final_layer_norm.name):
|
| 523 |
+
self.final_layer_norm.build([None, None, self.embed_dim])
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
class TFBlenderbotPreTrainedModel(TFPreTrainedModel):
|
| 527 |
+
config_class = BlenderbotConfig
|
| 528 |
+
base_model_prefix = "model"
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
BLENDERBOT_START_DOCSTRING = r"""
|
| 532 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 533 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 534 |
+
etc.)
|
| 535 |
+
|
| 536 |
+
This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
| 537 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
| 538 |
+
behavior.
|
| 539 |
+
|
| 540 |
+
<Tip>
|
| 541 |
+
|
| 542 |
+
TensorFlow models and layers in `transformers` accept two formats as input:
|
| 543 |
+
|
| 544 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
| 545 |
+
- having all inputs as a list, tuple or dict in the first positional argument.
|
| 546 |
+
|
| 547 |
+
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
|
| 548 |
+
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
|
| 549 |
+
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
|
| 550 |
+
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
|
| 551 |
+
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
|
| 552 |
+
positional argument:
|
| 553 |
+
|
| 554 |
+
- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
|
| 555 |
+
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
|
| 556 |
+
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
|
| 557 |
+
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
|
| 558 |
+
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
|
| 559 |
+
|
| 560 |
+
Note that when creating models and layers with
|
| 561 |
+
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
|
| 562 |
+
about any of this, as you can just pass inputs like you would to any other Python function!
|
| 563 |
+
|
| 564 |
+
</Tip>
|
| 565 |
+
|
| 566 |
+
Args:
|
| 567 |
+
config ([`BlenderbotConfig`]): Model configuration class with all the parameters of the model.
|
| 568 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 569 |
+
configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 570 |
+
"""
|
| 571 |
+
|
| 572 |
+
BLENDERBOT_GENERATION_EXAMPLE = r"""
|
| 573 |
+
Conversation example::
|
| 574 |
+
|
| 575 |
+
```py
|
| 576 |
+
>>> from transformers import AutoTokenizer, TFBlenderbotForConditionalGeneration
|
| 577 |
+
|
| 578 |
+
>>> mname = "facebook/blenderbot-400M-distill"
|
| 579 |
+
>>> model = TFBlenderbotForConditionalGeneration.from_pretrained(mname)
|
| 580 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(mname)
|
| 581 |
+
>>> UTTERANCE = "My friends are cool but they eat too many carbs."
|
| 582 |
+
>>> print("Human: ", UTTERANCE)
|
| 583 |
+
|
| 584 |
+
>>> inputs = tokenizer([UTTERANCE], return_tensors="tf")
|
| 585 |
+
>>> reply_ids = model.generate(**inputs)
|
| 586 |
+
>>> print("Bot: ", tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0])
|
| 587 |
+
|
| 588 |
+
>>> REPLY = "I'm not sure"
|
| 589 |
+
>>> print("Human: ", REPLY)
|
| 590 |
+
>>> NEXT_UTTERANCE = (
|
| 591 |
+
... "My friends are cool but they eat too many carbs.</s> <s>That's unfortunate. "
|
| 592 |
+
... "Are they trying to lose weight or are they just trying to be healthier?</s> "
|
| 593 |
+
... "<s> I'm not sure."
|
| 594 |
+
... )
|
| 595 |
+
>>> inputs = tokenizer([NEXT_UTTERANCE], return_tensors="tf")
|
| 596 |
+
>>> next_reply_ids = model.generate(**inputs)
|
| 597 |
+
>>> print("Bot: ", tokenizer.batch_decode(next_reply_ids, skip_special_tokens=True)[0])
|
| 598 |
+
```
|
| 599 |
+
"""
|
| 600 |
+
|
| 601 |
+
BLENDERBOT_INPUTS_DOCSTRING = r"""
|
| 602 |
+
Args:
|
| 603 |
+
input_ids (`tf.Tensor` of shape `({0})`):
|
| 604 |
+
Indices of input sequence tokens in the vocabulary.
|
| 605 |
+
|
| 606 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 607 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 608 |
+
|
| 609 |
+
[What are input IDs?](../glossary#input-ids)
|
| 610 |
+
attention_mask (`tf.Tensor` of shape `({0})`, *optional*):
|
| 611 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 612 |
+
|
| 613 |
+
- 1 for tokens that are **not masked**,
|
| 614 |
+
- 0 for tokens that are **masked**.
|
| 615 |
+
|
| 616 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 617 |
+
decoder_input_ids (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 618 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 619 |
+
|
| 620 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 621 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 622 |
+
|
| 623 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 624 |
+
|
| 625 |
+
Blenderbot uses the `bos_token_id` as the starting token for `decoder_input_ids` generation. If
|
| 626 |
+
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 627 |
+
`past_key_values`).
|
| 628 |
+
decoder_attention_mask (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 629 |
+
will be made by default and ignore pad tokens. It is not recommended to set this for most use cases.
|
| 630 |
+
decoder_position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 631 |
+
Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
|
| 632 |
+
range `[0, config.max_position_embeddings - 1]`.
|
| 633 |
+
head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
|
| 634 |
+
Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
|
| 635 |
+
|
| 636 |
+
- 1 indicates the head is **not masked**,
|
| 637 |
+
- 0 indicates the head is **masked**.
|
| 638 |
+
|
| 639 |
+
decoder_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 640 |
+
Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
|
| 641 |
+
|
| 642 |
+
- 1 indicates the head is **not masked**,
|
| 643 |
+
- 0 indicates the head is **masked**.
|
| 644 |
+
|
| 645 |
+
cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 646 |
+
Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
|
| 647 |
+
|
| 648 |
+
- 1 indicates the head is **not masked**,
|
| 649 |
+
- 0 indicates the head is **masked**.
|
| 650 |
+
|
| 651 |
+
encoder_outputs (`tf.FloatTensor`, *optional*):
|
| 652 |
+
hidden states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
|
| 653 |
+
of shape `(batch_size, sequence_length, hidden_size)` is a sequence of
|
| 654 |
+
past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)
|
| 655 |
+
contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 656 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 657 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 658 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 659 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 660 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 661 |
+
`past_key_values`). Set to `False` during training, `True` during generation
|
| 662 |
+
output_attentions (`bool`, *optional*):
|
| 663 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 664 |
+
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
|
| 665 |
+
config will be used instead.
|
| 666 |
+
output_hidden_states (`bool`, *optional*):
|
| 667 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 668 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 669 |
+
used instead.
|
| 670 |
+
return_dict (`bool`, *optional*):
|
| 671 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 672 |
+
eager mode, in graph mode the value will always be set to True.
|
| 673 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 674 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 675 |
+
behaviors between training and evaluation).
|
| 676 |
+
"""
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
@keras_serializable
|
| 680 |
+
class TFBlenderbotEncoder(keras.layers.Layer):
|
| 681 |
+
config_class = BlenderbotConfig
|
| 682 |
+
"""
|
| 683 |
+
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
|
| 684 |
+
[`TFBlenderbotEncoderLayer`].
|
| 685 |
+
|
| 686 |
+
Args:
|
| 687 |
+
config: BlenderbotConfig
|
| 688 |
+
"""
|
| 689 |
+
|
| 690 |
+
def __init__(self, config: BlenderbotConfig, embed_tokens: Optional[keras.layers.Embedding] = None, **kwargs):
|
| 691 |
+
super().__init__(**kwargs)
|
| 692 |
+
self.config = config
|
| 693 |
+
self.dropout = keras.layers.Dropout(config.dropout)
|
| 694 |
+
self.layerdrop = config.encoder_layerdrop
|
| 695 |
+
self.padding_idx = config.pad_token_id
|
| 696 |
+
self.max_source_positions = config.max_position_embeddings
|
| 697 |
+
self.embed_scale = tf.math.sqrt(float(config.d_model)) if config.scale_embedding else 1.0
|
| 698 |
+
|
| 699 |
+
self.embed_tokens = embed_tokens
|
| 700 |
+
self.embed_positions = TFBlenderbotLearnedPositionalEmbedding(
|
| 701 |
+
config.max_position_embeddings,
|
| 702 |
+
config.d_model,
|
| 703 |
+
name="embed_positions",
|
| 704 |
+
)
|
| 705 |
+
self.layers = [TFBlenderbotEncoderLayer(config, name=f"layers.{i}") for i in range(config.encoder_layers)]
|
| 706 |
+
self.layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="layer_norm")
|
| 707 |
+
|
| 708 |
+
def get_embed_tokens(self):
|
| 709 |
+
return self.embed_tokens
|
| 710 |
+
|
| 711 |
+
def set_embed_tokens(self, embed_tokens):
|
| 712 |
+
self.embed_tokens = embed_tokens
|
| 713 |
+
|
| 714 |
+
@unpack_inputs
|
| 715 |
+
def call(
|
| 716 |
+
self,
|
| 717 |
+
input_ids=None,
|
| 718 |
+
inputs_embeds=None,
|
| 719 |
+
attention_mask=None,
|
| 720 |
+
head_mask=None,
|
| 721 |
+
output_attentions=None,
|
| 722 |
+
output_hidden_states=None,
|
| 723 |
+
return_dict=None,
|
| 724 |
+
training=False,
|
| 725 |
+
):
|
| 726 |
+
"""
|
| 727 |
+
Args:
|
| 728 |
+
input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
|
| 729 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 730 |
+
provide it.
|
| 731 |
+
|
| 732 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 733 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 734 |
+
|
| 735 |
+
[What are input IDs?](../glossary#input-ids)
|
| 736 |
+
attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 737 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 738 |
+
|
| 739 |
+
- 1 for tokens that are **not masked**,
|
| 740 |
+
- 0 for tokens that are **masked**.
|
| 741 |
+
|
| 742 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 743 |
+
head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, `optional):
|
| 744 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 745 |
+
|
| 746 |
+
- 1 indicates the head is **not masked**,
|
| 747 |
+
- 0 indicates the head is **masked**.
|
| 748 |
+
|
| 749 |
+
inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 750 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 751 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 752 |
+
than the model's internal embedding lookup matrix.
|
| 753 |
+
output_attentions (`bool`, *optional*):
|
| 754 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 755 |
+
returned tensors for more detail. This argument can be used only in eager mode, in graph mode the value
|
| 756 |
+
in the config will be used instead.
|
| 757 |
+
output_hidden_states (`bool`, *optional*):
|
| 758 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 759 |
+
for more detail. This argument can be used only in eager mode, in graph mode the value in the config
|
| 760 |
+
will be used instead.
|
| 761 |
+
return_dict (`bool`, *optional*):
|
| 762 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used
|
| 763 |
+
in eager mode, in graph mode the value will always be set to True.
|
| 764 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 765 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 766 |
+
behaviors between training and evaluation).
|
| 767 |
+
"""
|
| 768 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 769 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 770 |
+
elif input_ids is not None:
|
| 771 |
+
input_shape = shape_list(input_ids)
|
| 772 |
+
elif inputs_embeds is not None:
|
| 773 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 774 |
+
else:
|
| 775 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 776 |
+
|
| 777 |
+
if inputs_embeds is None:
|
| 778 |
+
check_embeddings_within_bounds(input_ids, self.embed_tokens.input_dim)
|
| 779 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 780 |
+
|
| 781 |
+
embed_pos = self.embed_positions(input_shape)
|
| 782 |
+
hidden_states = inputs_embeds + embed_pos
|
| 783 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 784 |
+
|
| 785 |
+
# check attention mask and invert
|
| 786 |
+
if attention_mask is not None:
|
| 787 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 788 |
+
attention_mask = _expand_mask(attention_mask)
|
| 789 |
+
else:
|
| 790 |
+
attention_mask = None
|
| 791 |
+
|
| 792 |
+
encoder_states = () if output_hidden_states else None
|
| 793 |
+
all_attentions = () if output_attentions else None
|
| 794 |
+
|
| 795 |
+
# check if head_mask has a correct number of layers specified if desired
|
| 796 |
+
if head_mask is not None:
|
| 797 |
+
tf.debugging.assert_equal(
|
| 798 |
+
shape_list(head_mask)[0],
|
| 799 |
+
len(self.layers),
|
| 800 |
+
message=(
|
| 801 |
+
f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
|
| 802 |
+
f" {shape_list(head_mask)[0]}."
|
| 803 |
+
),
|
| 804 |
+
)
|
| 805 |
+
|
| 806 |
+
# encoder layers
|
| 807 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 808 |
+
if output_hidden_states:
|
| 809 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 810 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 811 |
+
dropout_probability = random.uniform(0, 1)
|
| 812 |
+
if training and (dropout_probability < self.layerdrop): # skip the layer
|
| 813 |
+
continue
|
| 814 |
+
|
| 815 |
+
hidden_states, attn = encoder_layer(
|
| 816 |
+
hidden_states,
|
| 817 |
+
attention_mask,
|
| 818 |
+
head_mask[idx] if head_mask is not None else None,
|
| 819 |
+
)
|
| 820 |
+
|
| 821 |
+
if output_attentions:
|
| 822 |
+
all_attentions += (attn,)
|
| 823 |
+
|
| 824 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 825 |
+
|
| 826 |
+
if output_hidden_states:
|
| 827 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 828 |
+
|
| 829 |
+
if not return_dict:
|
| 830 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 831 |
+
return TFBaseModelOutput(
|
| 832 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 833 |
+
)
|
| 834 |
+
|
| 835 |
+
def build(self, input_shape=None):
|
| 836 |
+
if self.built:
|
| 837 |
+
return
|
| 838 |
+
self.built = True
|
| 839 |
+
if getattr(self, "embed_positions", None) is not None:
|
| 840 |
+
with tf.name_scope(self.embed_positions.name):
|
| 841 |
+
self.embed_positions.build(None)
|
| 842 |
+
if getattr(self, "layer_norm", None) is not None:
|
| 843 |
+
with tf.name_scope(self.layer_norm.name):
|
| 844 |
+
self.layer_norm.build([None, None, self.config.d_model])
|
| 845 |
+
if getattr(self, "layers", None) is not None:
|
| 846 |
+
for layer in self.layers:
|
| 847 |
+
with tf.name_scope(layer.name):
|
| 848 |
+
layer.build(None)
|
| 849 |
+
|
| 850 |
+
|
| 851 |
+
@keras_serializable
|
| 852 |
+
class TFBlenderbotDecoder(keras.layers.Layer):
|
| 853 |
+
config_class = BlenderbotConfig
|
| 854 |
+
"""
|
| 855 |
+
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`TFBlenderbotDecoderLayer`]
|
| 856 |
+
|
| 857 |
+
Args:
|
| 858 |
+
config: BlenderbotConfig
|
| 859 |
+
embed_tokens: output embedding
|
| 860 |
+
"""
|
| 861 |
+
|
| 862 |
+
def __init__(self, config: BlenderbotConfig, embed_tokens: Optional[keras.layers.Embedding] = None, **kwargs):
|
| 863 |
+
super().__init__(**kwargs)
|
| 864 |
+
self.config = config
|
| 865 |
+
self.padding_idx = config.pad_token_id
|
| 866 |
+
self.embed_tokens = embed_tokens
|
| 867 |
+
self.layerdrop = config.decoder_layerdrop
|
| 868 |
+
self.embed_positions = TFBlenderbotLearnedPositionalEmbedding(
|
| 869 |
+
config.max_position_embeddings,
|
| 870 |
+
config.d_model,
|
| 871 |
+
name="embed_positions",
|
| 872 |
+
)
|
| 873 |
+
self.embed_scale = tf.math.sqrt(float(config.d_model)) if config.scale_embedding else 1.0
|
| 874 |
+
self.layers = [TFBlenderbotDecoderLayer(config, name=f"layers.{i}") for i in range(config.decoder_layers)]
|
| 875 |
+
self.layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="layer_norm")
|
| 876 |
+
|
| 877 |
+
self.dropout = keras.layers.Dropout(config.dropout)
|
| 878 |
+
|
| 879 |
+
def get_embed_tokens(self):
|
| 880 |
+
return self.embed_tokens
|
| 881 |
+
|
| 882 |
+
def set_embed_tokens(self, embed_tokens):
|
| 883 |
+
self.embed_tokens = embed_tokens
|
| 884 |
+
|
| 885 |
+
@unpack_inputs
|
| 886 |
+
def call(
|
| 887 |
+
self,
|
| 888 |
+
input_ids=None,
|
| 889 |
+
inputs_embeds=None,
|
| 890 |
+
attention_mask=None,
|
| 891 |
+
position_ids=None,
|
| 892 |
+
encoder_hidden_states=None,
|
| 893 |
+
encoder_attention_mask=None,
|
| 894 |
+
head_mask=None,
|
| 895 |
+
cross_attn_head_mask=None,
|
| 896 |
+
past_key_values=None,
|
| 897 |
+
use_cache=None,
|
| 898 |
+
output_attentions=None,
|
| 899 |
+
output_hidden_states=None,
|
| 900 |
+
return_dict=None,
|
| 901 |
+
training=False,
|
| 902 |
+
):
|
| 903 |
+
r"""
|
| 904 |
+
Args:
|
| 905 |
+
input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
|
| 906 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 907 |
+
provide it.
|
| 908 |
+
|
| 909 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 910 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 911 |
+
|
| 912 |
+
[What are input IDs?](../glossary#input-ids)
|
| 913 |
+
attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 914 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 915 |
+
|
| 916 |
+
- 1 for tokens that are **not masked**,
|
| 917 |
+
- 0 for tokens that are **masked**.
|
| 918 |
+
|
| 919 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 920 |
+
position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 921 |
+
Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
|
| 922 |
+
range `[0, config.max_position_embeddings - 1]`.
|
| 923 |
+
encoder_hidden_states (`tf.Tensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
|
| 924 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 925 |
+
of the decoder.
|
| 926 |
+
encoder_attention_mask (`tf.Tensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
|
| 927 |
+
Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
|
| 928 |
+
selected in `[0, 1]`:
|
| 929 |
+
|
| 930 |
+
- 1 for tokens that are **not masked**,
|
| 931 |
+
- 0 for tokens that are **masked**.
|
| 932 |
+
|
| 933 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 934 |
+
head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 935 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 936 |
+
|
| 937 |
+
- 1 indicates the head is **not masked**,
|
| 938 |
+
- 0 indicates the head is **masked**.
|
| 939 |
+
|
| 940 |
+
cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 941 |
+
Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
|
| 942 |
+
|
| 943 |
+
- 1 indicates the head is **not masked**,
|
| 944 |
+
- 0 indicates the head is **masked**.
|
| 945 |
+
|
| 946 |
+
past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
| 947 |
+
Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up
|
| 948 |
+
decoding.
|
| 949 |
+
|
| 950 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
|
| 951 |
+
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
|
| 952 |
+
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 953 |
+
inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 954 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 955 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 956 |
+
than the model's internal embedding lookup matrix.
|
| 957 |
+
output_attentions (`bool`, *optional*):
|
| 958 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 959 |
+
returned tensors for more detail. This argument can be used only in eager mode, in graph mode the value
|
| 960 |
+
in the config will be used instead.
|
| 961 |
+
output_hidden_states (`bool`, *optional*):
|
| 962 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 963 |
+
for more detail. This argument can be used only in eager mode, in graph mode the value in the config
|
| 964 |
+
will be used instead.
|
| 965 |
+
return_dict (`bool`, *optional*):
|
| 966 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used
|
| 967 |
+
in eager mode, in graph mode the value will always be set to True.
|
| 968 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 969 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 970 |
+
behaviors between training and evaluation).
|
| 971 |
+
"""
|
| 972 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 973 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
| 974 |
+
elif input_ids is not None:
|
| 975 |
+
input_shape = shape_list(input_ids)
|
| 976 |
+
elif inputs_embeds is not None:
|
| 977 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 978 |
+
else:
|
| 979 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
| 980 |
+
|
| 981 |
+
past_key_values_length = shape_list(past_key_values[0][0])[2] if past_key_values is not None else 0
|
| 982 |
+
|
| 983 |
+
# embed positions
|
| 984 |
+
if position_ids is None:
|
| 985 |
+
positions = self.embed_positions(input_shape, past_key_values_length)
|
| 986 |
+
else:
|
| 987 |
+
positions = self.embed_positions(input_shape, position_ids=position_ids)
|
| 988 |
+
|
| 989 |
+
if inputs_embeds is None:
|
| 990 |
+
check_embeddings_within_bounds(input_ids, self.embed_tokens.input_dim)
|
| 991 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 992 |
+
|
| 993 |
+
hidden_states = inputs_embeds
|
| 994 |
+
|
| 995 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 996 |
+
if input_shape[-1] > 1:
|
| 997 |
+
combined_attention_mask = _make_causal_mask(input_shape, past_key_values_length=past_key_values_length)
|
| 998 |
+
else:
|
| 999 |
+
combined_attention_mask = _expand_mask(
|
| 1000 |
+
tf.ones((input_shape[0], input_shape[1] + past_key_values_length)), tgt_len=input_shape[-1]
|
| 1001 |
+
)
|
| 1002 |
+
|
| 1003 |
+
if attention_mask is not None:
|
| 1004 |
+
combined_attention_mask = combined_attention_mask + _expand_mask(attention_mask, tgt_len=input_shape[-1])
|
| 1005 |
+
|
| 1006 |
+
if encoder_hidden_states is not None and encoder_attention_mask is not None:
|
| 1007 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 1008 |
+
encoder_attention_mask = _expand_mask(encoder_attention_mask, tgt_len=input_shape[-1])
|
| 1009 |
+
|
| 1010 |
+
hidden_states = hidden_states + positions
|
| 1011 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 1012 |
+
|
| 1013 |
+
# decoder layers
|
| 1014 |
+
all_hidden_states = () if output_hidden_states else None
|
| 1015 |
+
all_self_attns = () if output_attentions else None
|
| 1016 |
+
all_cross_attns = () if (output_attentions and encoder_hidden_states is not None) else None
|
| 1017 |
+
present_key_values = () if use_cache else None
|
| 1018 |
+
|
| 1019 |
+
# check if head_mask and cross_attn_head_mask have a correct number of layers specified if desired
|
| 1020 |
+
for attn_mask_name, attn_mask in [("head_mask", head_mask), ("cross_attn_head_mask", cross_attn_head_mask)]:
|
| 1021 |
+
if attn_mask is not None:
|
| 1022 |
+
tf.debugging.assert_equal(
|
| 1023 |
+
shape_list(attn_mask)[0],
|
| 1024 |
+
len(self.layers),
|
| 1025 |
+
message=(
|
| 1026 |
+
f"The {attn_mask_name} should be specified for {len(self.layers)} layers, but it is for"
|
| 1027 |
+
f" {shape_list(attn_mask)[0]}."
|
| 1028 |
+
),
|
| 1029 |
+
)
|
| 1030 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 1031 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 1032 |
+
if output_hidden_states:
|
| 1033 |
+
all_hidden_states += (hidden_states,)
|
| 1034 |
+
dropout_probability = random.uniform(0, 1)
|
| 1035 |
+
|
| 1036 |
+
if training and (dropout_probability < self.layerdrop):
|
| 1037 |
+
continue
|
| 1038 |
+
|
| 1039 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
| 1040 |
+
|
| 1041 |
+
hidden_states, layer_self_attn, layer_cross_attn, present_key_value = decoder_layer(
|
| 1042 |
+
hidden_states,
|
| 1043 |
+
attention_mask=combined_attention_mask,
|
| 1044 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1045 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1046 |
+
layer_head_mask=head_mask[idx] if head_mask is not None else None,
|
| 1047 |
+
cross_attn_layer_head_mask=cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
|
| 1048 |
+
past_key_value=past_key_value,
|
| 1049 |
+
)
|
| 1050 |
+
|
| 1051 |
+
if use_cache:
|
| 1052 |
+
present_key_values += (present_key_value,)
|
| 1053 |
+
|
| 1054 |
+
if output_attentions:
|
| 1055 |
+
all_self_attns += (layer_self_attn,)
|
| 1056 |
+
|
| 1057 |
+
if encoder_hidden_states is not None:
|
| 1058 |
+
all_cross_attns += (layer_cross_attn,)
|
| 1059 |
+
|
| 1060 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 1061 |
+
|
| 1062 |
+
if output_hidden_states:
|
| 1063 |
+
all_hidden_states += (hidden_states,)
|
| 1064 |
+
|
| 1065 |
+
if not return_dict:
|
| 1066 |
+
return hidden_states, present_key_values, all_hidden_states, all_self_attns, all_cross_attns
|
| 1067 |
+
else:
|
| 1068 |
+
return TFBaseModelOutputWithPastAndCrossAttentions(
|
| 1069 |
+
last_hidden_state=hidden_states,
|
| 1070 |
+
past_key_values=present_key_values,
|
| 1071 |
+
hidden_states=all_hidden_states,
|
| 1072 |
+
attentions=all_self_attns,
|
| 1073 |
+
cross_attentions=all_cross_attns,
|
| 1074 |
+
)
|
| 1075 |
+
|
| 1076 |
+
def build(self, input_shape=None):
|
| 1077 |
+
if self.built:
|
| 1078 |
+
return
|
| 1079 |
+
self.built = True
|
| 1080 |
+
if getattr(self, "embed_positions", None) is not None:
|
| 1081 |
+
with tf.name_scope(self.embed_positions.name):
|
| 1082 |
+
self.embed_positions.build(None)
|
| 1083 |
+
if getattr(self, "layer_norm", None) is not None:
|
| 1084 |
+
with tf.name_scope(self.layer_norm.name):
|
| 1085 |
+
self.layer_norm.build([None, None, self.config.d_model])
|
| 1086 |
+
if getattr(self, "layers", None) is not None:
|
| 1087 |
+
for layer in self.layers:
|
| 1088 |
+
with tf.name_scope(layer.name):
|
| 1089 |
+
layer.build(None)
|
| 1090 |
+
|
| 1091 |
+
|
| 1092 |
+
@keras_serializable
|
| 1093 |
+
class TFBlenderbotMainLayer(keras.layers.Layer):
|
| 1094 |
+
config_class = BlenderbotConfig
|
| 1095 |
+
|
| 1096 |
+
def __init__(self, config: BlenderbotConfig, **kwargs):
|
| 1097 |
+
super().__init__(**kwargs)
|
| 1098 |
+
|
| 1099 |
+
self.config = config
|
| 1100 |
+
self.shared = keras.layers.Embedding(
|
| 1101 |
+
input_dim=config.vocab_size,
|
| 1102 |
+
output_dim=config.d_model,
|
| 1103 |
+
embeddings_initializer=keras.initializers.TruncatedNormal(stddev=self.config.init_std),
|
| 1104 |
+
name="model.shared",
|
| 1105 |
+
)
|
| 1106 |
+
# Additional attribute to specify the expected name scope of the layer (for loading/storing weights)
|
| 1107 |
+
self.shared.load_weight_prefix = "model.shared"
|
| 1108 |
+
|
| 1109 |
+
self.encoder = TFBlenderbotEncoder(config, self.shared, name="encoder")
|
| 1110 |
+
self.decoder = TFBlenderbotDecoder(config, self.shared, name="decoder")
|
| 1111 |
+
|
| 1112 |
+
def get_input_embeddings(self):
|
| 1113 |
+
return self.shared
|
| 1114 |
+
|
| 1115 |
+
def set_input_embeddings(self, new_embeddings):
|
| 1116 |
+
self.shared = new_embeddings
|
| 1117 |
+
self.encoder.embed_tokens = self.shared
|
| 1118 |
+
self.decoder.embed_tokens = self.shared
|
| 1119 |
+
|
| 1120 |
+
@unpack_inputs
|
| 1121 |
+
def call(
|
| 1122 |
+
self,
|
| 1123 |
+
input_ids=None,
|
| 1124 |
+
attention_mask=None,
|
| 1125 |
+
decoder_input_ids=None,
|
| 1126 |
+
decoder_attention_mask=None,
|
| 1127 |
+
decoder_position_ids=None,
|
| 1128 |
+
head_mask=None,
|
| 1129 |
+
decoder_head_mask=None,
|
| 1130 |
+
cross_attn_head_mask=None,
|
| 1131 |
+
encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,
|
| 1132 |
+
past_key_values=None,
|
| 1133 |
+
inputs_embeds=None,
|
| 1134 |
+
decoder_inputs_embeds=None,
|
| 1135 |
+
use_cache=None,
|
| 1136 |
+
output_attentions=None,
|
| 1137 |
+
output_hidden_states=None,
|
| 1138 |
+
return_dict=None,
|
| 1139 |
+
training=False,
|
| 1140 |
+
**kwargs,
|
| 1141 |
+
):
|
| 1142 |
+
output_hidden_states = (
|
| 1143 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1144 |
+
)
|
| 1145 |
+
|
| 1146 |
+
if encoder_outputs is None:
|
| 1147 |
+
encoder_outputs = self.encoder(
|
| 1148 |
+
input_ids=input_ids,
|
| 1149 |
+
attention_mask=attention_mask,
|
| 1150 |
+
head_mask=head_mask,
|
| 1151 |
+
inputs_embeds=inputs_embeds,
|
| 1152 |
+
output_attentions=output_attentions,
|
| 1153 |
+
output_hidden_states=output_hidden_states,
|
| 1154 |
+
return_dict=return_dict,
|
| 1155 |
+
training=training,
|
| 1156 |
+
)
|
| 1157 |
+
# If the user passed a tuple for encoder_outputs, we wrap it in a TFBaseModelOutput when return_dict=True
|
| 1158 |
+
elif return_dict and not isinstance(encoder_outputs, TFBaseModelOutput):
|
| 1159 |
+
encoder_outputs = TFBaseModelOutput(
|
| 1160 |
+
last_hidden_state=encoder_outputs[0],
|
| 1161 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
| 1162 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
| 1163 |
+
)
|
| 1164 |
+
# If the user passed a TFBaseModelOutput for encoder_outputs, we wrap it in a tuple when return_dict=False
|
| 1165 |
+
elif not return_dict and not isinstance(encoder_outputs, tuple):
|
| 1166 |
+
encoder_outputs = encoder_outputs.to_tuple()
|
| 1167 |
+
|
| 1168 |
+
decoder_outputs = self.decoder(
|
| 1169 |
+
decoder_input_ids,
|
| 1170 |
+
attention_mask=decoder_attention_mask,
|
| 1171 |
+
position_ids=decoder_position_ids,
|
| 1172 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 1173 |
+
encoder_attention_mask=attention_mask,
|
| 1174 |
+
head_mask=decoder_head_mask,
|
| 1175 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1176 |
+
past_key_values=past_key_values,
|
| 1177 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 1178 |
+
use_cache=use_cache,
|
| 1179 |
+
output_attentions=output_attentions,
|
| 1180 |
+
output_hidden_states=output_hidden_states,
|
| 1181 |
+
return_dict=return_dict,
|
| 1182 |
+
training=training,
|
| 1183 |
+
)
|
| 1184 |
+
|
| 1185 |
+
if not return_dict:
|
| 1186 |
+
return decoder_outputs + encoder_outputs
|
| 1187 |
+
|
| 1188 |
+
return TFSeq2SeqModelOutput(
|
| 1189 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 1190 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 1191 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 1192 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 1193 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 1194 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 1195 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 1196 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 1197 |
+
)
|
| 1198 |
+
|
| 1199 |
+
def build(self, input_shape=None):
|
| 1200 |
+
if self.built:
|
| 1201 |
+
return
|
| 1202 |
+
self.built = True
|
| 1203 |
+
# The shared/tied weights expect to be in the model base namespace
|
| 1204 |
+
# Adding "/" to the end (not the start!) of a tf.name_scope puts it in the root namespace rather than
|
| 1205 |
+
# the current one.
|
| 1206 |
+
with tf.name_scope(self.shared.load_weight_prefix + "/" + self.shared.name + "/"):
|
| 1207 |
+
self.shared.build(None)
|
| 1208 |
+
if getattr(self, "encoder", None) is not None:
|
| 1209 |
+
with tf.name_scope(self.encoder.name):
|
| 1210 |
+
self.encoder.build(None)
|
| 1211 |
+
if getattr(self, "decoder", None) is not None:
|
| 1212 |
+
with tf.name_scope(self.decoder.name):
|
| 1213 |
+
self.decoder.build(None)
|
| 1214 |
+
|
| 1215 |
+
|
| 1216 |
+
@add_start_docstrings(
|
| 1217 |
+
"The bare BLENDERBOT Model outputting raw hidden-states without any specific head on top.",
|
| 1218 |
+
BLENDERBOT_START_DOCSTRING,
|
| 1219 |
+
)
|
| 1220 |
+
class TFBlenderbotModel(TFBlenderbotPreTrainedModel):
|
| 1221 |
+
def __init__(self, config: BlenderbotConfig, *inputs, **kwargs):
|
| 1222 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1223 |
+
|
| 1224 |
+
self.model = TFBlenderbotMainLayer(config, name="model")
|
| 1225 |
+
|
| 1226 |
+
def get_encoder(self):
|
| 1227 |
+
return self.model.encoder
|
| 1228 |
+
|
| 1229 |
+
def get_decoder(self):
|
| 1230 |
+
return self.model.decoder
|
| 1231 |
+
|
| 1232 |
+
@classmethod
|
| 1233 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *model_args, **kwargs):
|
| 1234 |
+
if pretrained_model_name_or_path == "facebook/blenderbot-90M":
|
| 1235 |
+
from ..blenderbot_small import TFBlenderbotSmallModel
|
| 1236 |
+
|
| 1237 |
+
warnings.warn(
|
| 1238 |
+
"The checkpoint `facebook/blenderbot-90M` is deprecated. In the future, please use the identical"
|
| 1239 |
+
" checkpoint `facebook/small_blenderbot-90M` with"
|
| 1240 |
+
" `TFBlenderbotSmallForConditionalGeneration.from_pretrained('facebook/small_blenderbot-90M')`"
|
| 1241 |
+
" instead.",
|
| 1242 |
+
FutureWarning,
|
| 1243 |
+
)
|
| 1244 |
+
return TFBlenderbotSmallModel.from_pretrained(pretrained_model_name_or_path)
|
| 1245 |
+
|
| 1246 |
+
return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
|
| 1247 |
+
|
| 1248 |
+
@unpack_inputs
|
| 1249 |
+
@add_start_docstrings_to_model_forward(BLENDERBOT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1250 |
+
@add_code_sample_docstrings(
|
| 1251 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1252 |
+
output_type=TFSeq2SeqModelOutput,
|
| 1253 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1254 |
+
)
|
| 1255 |
+
def call(
|
| 1256 |
+
self,
|
| 1257 |
+
input_ids: tf.Tensor | None = None,
|
| 1258 |
+
attention_mask: tf.Tensor | None = None,
|
| 1259 |
+
decoder_input_ids: tf.Tensor | None = None,
|
| 1260 |
+
decoder_attention_mask: tf.Tensor | None = None,
|
| 1261 |
+
decoder_position_ids: tf.Tensor | None = None,
|
| 1262 |
+
head_mask: tf.Tensor | None = None,
|
| 1263 |
+
decoder_head_mask: tf.Tensor | None = None,
|
| 1264 |
+
cross_attn_head_mask: tf.Tensor | None = None,
|
| 1265 |
+
encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,
|
| 1266 |
+
past_key_values: List[tf.Tensor] | None = None,
|
| 1267 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 1268 |
+
decoder_inputs_embeds: tf.Tensor | None = None,
|
| 1269 |
+
use_cache: Optional[bool] = None,
|
| 1270 |
+
output_attentions: Optional[bool] = None,
|
| 1271 |
+
output_hidden_states: Optional[bool] = None,
|
| 1272 |
+
return_dict: Optional[bool] = None,
|
| 1273 |
+
training: Optional[bool] = False,
|
| 1274 |
+
**kwargs,
|
| 1275 |
+
) -> Union[Tuple[tf.Tensor], TFSeq2SeqModelOutput]:
|
| 1276 |
+
outputs = self.model(
|
| 1277 |
+
input_ids=input_ids,
|
| 1278 |
+
attention_mask=attention_mask,
|
| 1279 |
+
decoder_input_ids=decoder_input_ids,
|
| 1280 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1281 |
+
decoder_position_ids=decoder_position_ids,
|
| 1282 |
+
head_mask=head_mask,
|
| 1283 |
+
decoder_head_mask=decoder_head_mask,
|
| 1284 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1285 |
+
encoder_outputs=encoder_outputs,
|
| 1286 |
+
past_key_values=past_key_values,
|
| 1287 |
+
inputs_embeds=inputs_embeds,
|
| 1288 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1289 |
+
use_cache=use_cache,
|
| 1290 |
+
output_attentions=output_attentions,
|
| 1291 |
+
output_hidden_states=output_hidden_states,
|
| 1292 |
+
return_dict=return_dict,
|
| 1293 |
+
training=training,
|
| 1294 |
+
)
|
| 1295 |
+
|
| 1296 |
+
return outputs
|
| 1297 |
+
|
| 1298 |
+
# Copied from transformers.models.bart.modeling_tf_bart.TFBartModel.serving_output
|
| 1299 |
+
def serving_output(self, output):
|
| 1300 |
+
pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
|
| 1301 |
+
dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
|
| 1302 |
+
dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
|
| 1303 |
+
cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
|
| 1304 |
+
enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
|
| 1305 |
+
enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
|
| 1306 |
+
|
| 1307 |
+
return TFSeq2SeqModelOutput(
|
| 1308 |
+
last_hidden_state=output.last_hidden_state,
|
| 1309 |
+
past_key_values=pkv,
|
| 1310 |
+
decoder_hidden_states=dec_hs,
|
| 1311 |
+
decoder_attentions=dec_attns,
|
| 1312 |
+
cross_attentions=cross_attns,
|
| 1313 |
+
encoder_last_hidden_state=output.encoder_last_hidden_state,
|
| 1314 |
+
encoder_hidden_states=enc_hs,
|
| 1315 |
+
encoder_attentions=enc_attns,
|
| 1316 |
+
)
|
| 1317 |
+
|
| 1318 |
+
def build(self, input_shape=None):
|
| 1319 |
+
if self.built:
|
| 1320 |
+
return
|
| 1321 |
+
self.built = True
|
| 1322 |
+
if getattr(self, "model", None) is not None:
|
| 1323 |
+
with tf.name_scope(self.model.name):
|
| 1324 |
+
self.model.build(None)
|
| 1325 |
+
|
| 1326 |
+
|
| 1327 |
+
# Copied from transformers.models.bart.modeling_tf_bart.BiasLayer
|
| 1328 |
+
class BiasLayer(keras.layers.Layer):
|
| 1329 |
+
"""
|
| 1330 |
+
Bias as a layer. It is used for serialization purposes: `keras.Model.save_weights` stores on a per-layer basis,
|
| 1331 |
+
so all weights have to be registered in a layer.
|
| 1332 |
+
"""
|
| 1333 |
+
|
| 1334 |
+
def __init__(self, shape, initializer, trainable, name, **kwargs):
|
| 1335 |
+
super().__init__(name=name, **kwargs)
|
| 1336 |
+
# Note: the name of this variable will NOT be scoped when serialized, i.e. it will not be in the format of
|
| 1337 |
+
# "outer_layer/inner_layer/.../name:0". Instead, it will be "name:0". For further details, see:
|
| 1338 |
+
# https://github.com/huggingface/transformers/pull/18833#issuecomment-1233090214
|
| 1339 |
+
self.bias = self.add_weight(name=name, shape=shape, initializer=initializer, trainable=trainable)
|
| 1340 |
+
|
| 1341 |
+
def call(self, x):
|
| 1342 |
+
return x + self.bias
|
| 1343 |
+
|
| 1344 |
+
|
| 1345 |
+
@add_start_docstrings(
|
| 1346 |
+
"The BLENDERBOT Model with a language modeling head. Can be used for summarization.",
|
| 1347 |
+
BLENDERBOT_START_DOCSTRING,
|
| 1348 |
+
)
|
| 1349 |
+
class TFBlenderbotForConditionalGeneration(TFBlenderbotPreTrainedModel, TFCausalLanguageModelingLoss):
|
| 1350 |
+
_keys_to_ignore_on_load_unexpected = [
|
| 1351 |
+
r"model.encoder.embed_tokens.weight",
|
| 1352 |
+
r"model.decoder.embed_tokens.weight",
|
| 1353 |
+
]
|
| 1354 |
+
|
| 1355 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 1356 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1357 |
+
self.model = TFBlenderbotMainLayer(config, name="model")
|
| 1358 |
+
self.use_cache = config.use_cache
|
| 1359 |
+
# final_bias_logits is registered as a buffer in pytorch, so not trainable for the sake of consistency.
|
| 1360 |
+
self.bias_layer = BiasLayer(
|
| 1361 |
+
name="final_logits_bias", shape=[1, config.vocab_size], initializer="zeros", trainable=False
|
| 1362 |
+
)
|
| 1363 |
+
|
| 1364 |
+
def get_decoder(self):
|
| 1365 |
+
return self.model.decoder
|
| 1366 |
+
|
| 1367 |
+
def get_encoder(self):
|
| 1368 |
+
return self.model.encoder
|
| 1369 |
+
|
| 1370 |
+
def get_output_embeddings(self):
|
| 1371 |
+
return self.get_input_embeddings()
|
| 1372 |
+
|
| 1373 |
+
def set_output_embeddings(self, value):
|
| 1374 |
+
self.set_input_embeddings(value)
|
| 1375 |
+
|
| 1376 |
+
def get_bias(self):
|
| 1377 |
+
return {"final_logits_bias": self.bias_layer.bias}
|
| 1378 |
+
|
| 1379 |
+
def set_bias(self, value):
|
| 1380 |
+
# Replaces the existing layers containing bias for correct (de)serialization.
|
| 1381 |
+
vocab_size = value["final_logits_bias"].shape[-1]
|
| 1382 |
+
self.bias_layer = BiasLayer(
|
| 1383 |
+
name="final_logits_bias", shape=[1, vocab_size], initializer="zeros", trainable=False
|
| 1384 |
+
)
|
| 1385 |
+
self.bias_layer.bias.assign(value["final_logits_bias"])
|
| 1386 |
+
|
| 1387 |
+
@classmethod
|
| 1388 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *model_args, **kwargs):
|
| 1389 |
+
if pretrained_model_name_or_path == "facebook/blenderbot-90M":
|
| 1390 |
+
from ..blenderbot_small import TFBlenderbotSmallForConditionalGeneration
|
| 1391 |
+
|
| 1392 |
+
warnings.warn(
|
| 1393 |
+
"The checkpoint `facebook/blenderbot-90M` is deprecated. In the future, please use the identical"
|
| 1394 |
+
" checkpoint `facebook/small_blenderbot-90M` with"
|
| 1395 |
+
" `TFBlenderbotSmallForConditionalGeneration.from_pretrained('facebook/small_blenderbot-90M')`"
|
| 1396 |
+
" instead.",
|
| 1397 |
+
FutureWarning,
|
| 1398 |
+
)
|
| 1399 |
+
return TFBlenderbotSmallForConditionalGeneration.from_pretrained(pretrained_model_name_or_path)
|
| 1400 |
+
|
| 1401 |
+
return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
|
| 1402 |
+
|
| 1403 |
+
@unpack_inputs
|
| 1404 |
+
@add_start_docstrings_to_model_forward(BLENDERBOT_INPUTS_DOCSTRING)
|
| 1405 |
+
@replace_return_docstrings(output_type=TFSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
|
| 1406 |
+
@add_end_docstrings(BLENDERBOT_GENERATION_EXAMPLE)
|
| 1407 |
+
def call(
|
| 1408 |
+
self,
|
| 1409 |
+
input_ids: tf.Tensor | None = None,
|
| 1410 |
+
attention_mask: tf.Tensor | None = None,
|
| 1411 |
+
decoder_input_ids: tf.Tensor | None = None,
|
| 1412 |
+
decoder_attention_mask: tf.Tensor | None = None,
|
| 1413 |
+
decoder_position_ids: tf.Tensor | None = None,
|
| 1414 |
+
head_mask: tf.Tensor | None = None,
|
| 1415 |
+
decoder_head_mask: tf.Tensor | None = None,
|
| 1416 |
+
cross_attn_head_mask: tf.Tensor | None = None,
|
| 1417 |
+
encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,
|
| 1418 |
+
past_key_values: List[tf.Tensor] | None = None,
|
| 1419 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 1420 |
+
decoder_inputs_embeds: tf.Tensor | None = None,
|
| 1421 |
+
use_cache: Optional[bool] = None,
|
| 1422 |
+
output_attentions: Optional[bool] = None,
|
| 1423 |
+
output_hidden_states: Optional[bool] = None,
|
| 1424 |
+
return_dict: Optional[bool] = None,
|
| 1425 |
+
labels: tf.Tensor | None = None,
|
| 1426 |
+
training: Optional[bool] = False,
|
| 1427 |
+
) -> Union[Tuple[tf.Tensor], TFSeq2SeqLMOutput]:
|
| 1428 |
+
r"""
|
| 1429 |
+
labels (`tf.tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1430 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1431 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1432 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1433 |
+
|
| 1434 |
+
Returns:
|
| 1435 |
+
|
| 1436 |
+
"""
|
| 1437 |
+
if labels is not None:
|
| 1438 |
+
labels = tf.where(
|
| 1439 |
+
labels == self.config.pad_token_id,
|
| 1440 |
+
tf.cast(tf.fill(shape_list(labels), -100), labels.dtype),
|
| 1441 |
+
labels,
|
| 1442 |
+
)
|
| 1443 |
+
use_cache = False
|
| 1444 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 1445 |
+
decoder_input_ids = shift_tokens_right(
|
| 1446 |
+
labels, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 1447 |
+
)
|
| 1448 |
+
|
| 1449 |
+
outputs = self.model(
|
| 1450 |
+
input_ids,
|
| 1451 |
+
attention_mask=attention_mask,
|
| 1452 |
+
decoder_input_ids=decoder_input_ids,
|
| 1453 |
+
encoder_outputs=encoder_outputs,
|
| 1454 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1455 |
+
decoder_position_ids=decoder_position_ids,
|
| 1456 |
+
head_mask=head_mask,
|
| 1457 |
+
decoder_head_mask=decoder_head_mask,
|
| 1458 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1459 |
+
past_key_values=past_key_values,
|
| 1460 |
+
inputs_embeds=inputs_embeds,
|
| 1461 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1462 |
+
use_cache=use_cache,
|
| 1463 |
+
output_attentions=output_attentions,
|
| 1464 |
+
output_hidden_states=output_hidden_states,
|
| 1465 |
+
return_dict=return_dict,
|
| 1466 |
+
training=training,
|
| 1467 |
+
)
|
| 1468 |
+
lm_logits = tf.matmul(outputs[0], self.model.shared.weights, transpose_b=True)
|
| 1469 |
+
lm_logits = self.bias_layer(lm_logits)
|
| 1470 |
+
masked_lm_loss = None if labels is None else self.hf_compute_loss(labels, lm_logits)
|
| 1471 |
+
|
| 1472 |
+
if not return_dict:
|
| 1473 |
+
output = (lm_logits,) + outputs[1:]
|
| 1474 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 1475 |
+
return TFSeq2SeqLMOutput(
|
| 1476 |
+
loss=masked_lm_loss,
|
| 1477 |
+
logits=lm_logits,
|
| 1478 |
+
past_key_values=outputs.past_key_values, # index 1 of d outputs
|
| 1479 |
+
decoder_hidden_states=outputs.decoder_hidden_states, # index 2 of d outputs
|
| 1480 |
+
decoder_attentions=outputs.decoder_attentions, # index 3 of d outputs
|
| 1481 |
+
cross_attentions=outputs.cross_attentions, # index 4 of d outputs
|
| 1482 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state, # index 0 of encoder outputs
|
| 1483 |
+
encoder_hidden_states=outputs.encoder_hidden_states, # 1 of e out
|
| 1484 |
+
encoder_attentions=outputs.encoder_attentions, # 2 of e out
|
| 1485 |
+
)
|
| 1486 |
+
|
| 1487 |
+
# Copied from transformers.models.bart.modeling_tf_bart.TFBartForConditionalGeneration.serving_output
|
| 1488 |
+
def serving_output(self, output):
|
| 1489 |
+
pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
|
| 1490 |
+
dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
|
| 1491 |
+
dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
|
| 1492 |
+
cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
|
| 1493 |
+
enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
|
| 1494 |
+
enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
|
| 1495 |
+
|
| 1496 |
+
return TFSeq2SeqLMOutput(
|
| 1497 |
+
logits=output.logits,
|
| 1498 |
+
past_key_values=pkv,
|
| 1499 |
+
decoder_hidden_states=dec_hs,
|
| 1500 |
+
decoder_attentions=dec_attns,
|
| 1501 |
+
cross_attentions=cross_attns,
|
| 1502 |
+
encoder_last_hidden_state=output.encoder_last_hidden_state,
|
| 1503 |
+
encoder_hidden_states=enc_hs,
|
| 1504 |
+
encoder_attentions=enc_attns,
|
| 1505 |
+
)
|
| 1506 |
+
|
| 1507 |
+
# Copied from transformers.models.bart.modeling_tf_bart.TFBartForConditionalGeneration.prepare_inputs_for_generation
|
| 1508 |
+
def prepare_inputs_for_generation(
|
| 1509 |
+
self,
|
| 1510 |
+
decoder_input_ids,
|
| 1511 |
+
past_key_values=None,
|
| 1512 |
+
attention_mask=None,
|
| 1513 |
+
decoder_attention_mask=None,
|
| 1514 |
+
head_mask=None,
|
| 1515 |
+
decoder_head_mask=None,
|
| 1516 |
+
cross_attn_head_mask=None,
|
| 1517 |
+
use_cache=None,
|
| 1518 |
+
encoder_outputs=None,
|
| 1519 |
+
**kwargs,
|
| 1520 |
+
):
|
| 1521 |
+
# cut decoder_input_ids if past_key_values is used
|
| 1522 |
+
if past_key_values is not None:
|
| 1523 |
+
decoder_input_ids = decoder_input_ids[:, -1:]
|
| 1524 |
+
|
| 1525 |
+
if decoder_attention_mask is not None: # xla
|
| 1526 |
+
decoder_position_ids = tf.math.cumsum(decoder_attention_mask, axis=-1, exclusive=True)[:, -1:]
|
| 1527 |
+
elif past_key_values is not None: # no xla + past_key_values
|
| 1528 |
+
decoder_position_ids = past_key_values[0][0].shape[2]
|
| 1529 |
+
else: # no xla + no past_key_values
|
| 1530 |
+
decoder_position_ids = tf.range(decoder_input_ids.shape[1])
|
| 1531 |
+
|
| 1532 |
+
return {
|
| 1533 |
+
"input_ids": None, # encoder_outputs is defined. input_ids not needed
|
| 1534 |
+
"encoder_outputs": encoder_outputs,
|
| 1535 |
+
"past_key_values": past_key_values,
|
| 1536 |
+
"decoder_input_ids": decoder_input_ids,
|
| 1537 |
+
"attention_mask": attention_mask,
|
| 1538 |
+
"decoder_attention_mask": decoder_attention_mask,
|
| 1539 |
+
"decoder_position_ids": decoder_position_ids,
|
| 1540 |
+
"head_mask": head_mask,
|
| 1541 |
+
"decoder_head_mask": decoder_head_mask,
|
| 1542 |
+
"cross_attn_head_mask": cross_attn_head_mask,
|
| 1543 |
+
"use_cache": use_cache, # change this to avoid caching (presumably for debugging)
|
| 1544 |
+
}
|
| 1545 |
+
|
| 1546 |
+
def build(self, input_shape=None):
|
| 1547 |
+
if self.built:
|
| 1548 |
+
return
|
| 1549 |
+
self.built = True
|
| 1550 |
+
if getattr(self, "model", None) is not None:
|
| 1551 |
+
with tf.name_scope(self.model.name):
|
| 1552 |
+
self.model.build(None)
|
| 1553 |
+
if getattr(self, "bias_layer", None) is not None:
|
| 1554 |
+
with tf.name_scope(self.bias_layer.name):
|
| 1555 |
+
self.bias_layer.build(None)
|
| 1556 |
+
|
| 1557 |
+
|
| 1558 |
+
__all__ = ["TFBlenderbotForConditionalGeneration", "TFBlenderbotModel", "TFBlenderbotPreTrainedModel"]
|
lib/python3.12/site-packages/transformers/models/blenderbot/tokenization_blenderbot.py
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 The Facebook Inc. and The HuggingFace Inc. team. 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 |
+
"""Tokenization class for Blenderbot."""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
from functools import lru_cache
|
| 20 |
+
from typing import List, Optional, Tuple
|
| 21 |
+
|
| 22 |
+
import regex as re
|
| 23 |
+
|
| 24 |
+
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
|
| 25 |
+
from ...utils import logging
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
VOCAB_FILES_NAMES = {
|
| 32 |
+
"vocab_file": "vocab.json",
|
| 33 |
+
"merges_file": "merges.txt",
|
| 34 |
+
"tokenizer_config_file": "tokenizer_config.json",
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@lru_cache()
|
| 39 |
+
# Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode
|
| 40 |
+
def bytes_to_unicode():
|
| 41 |
+
"""
|
| 42 |
+
Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
|
| 43 |
+
characters the bpe code barfs on.
|
| 44 |
+
|
| 45 |
+
The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
|
| 46 |
+
if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
|
| 47 |
+
decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
|
| 48 |
+
tables between utf-8 bytes and unicode strings.
|
| 49 |
+
"""
|
| 50 |
+
bs = (
|
| 51 |
+
list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
|
| 52 |
+
)
|
| 53 |
+
cs = bs[:]
|
| 54 |
+
n = 0
|
| 55 |
+
for b in range(2**8):
|
| 56 |
+
if b not in bs:
|
| 57 |
+
bs.append(b)
|
| 58 |
+
cs.append(2**8 + n)
|
| 59 |
+
n += 1
|
| 60 |
+
cs = [chr(n) for n in cs]
|
| 61 |
+
return dict(zip(bs, cs))
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# Copied from transformers.models.roberta.tokenization_roberta.get_pairs
|
| 65 |
+
def get_pairs(word):
|
| 66 |
+
"""
|
| 67 |
+
Return set of symbol pairs in a word.
|
| 68 |
+
|
| 69 |
+
Word is represented as tuple of symbols (symbols being variable-length strings).
|
| 70 |
+
"""
|
| 71 |
+
pairs = set()
|
| 72 |
+
prev_char = word[0]
|
| 73 |
+
for char in word[1:]:
|
| 74 |
+
pairs.add((prev_char, char))
|
| 75 |
+
prev_char = char
|
| 76 |
+
return pairs
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class BlenderbotTokenizer(PreTrainedTokenizer):
|
| 80 |
+
"""
|
| 81 |
+
Constructs a Blenderbot tokenizer, derived from the GPT-2 tokenizer, using byte-level Byte-Pair-Encoding.
|
| 82 |
+
|
| 83 |
+
This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
|
| 84 |
+
be encoded differently whether it is at the beginning of the sentence (without space) or not:
|
| 85 |
+
|
| 86 |
+
```python
|
| 87 |
+
>>> from transformers import BlenderbotTokenizer
|
| 88 |
+
|
| 89 |
+
>>> tokenizer = BlenderbotTokenizer.from_pretrained("facebook/blenderbot-3B")
|
| 90 |
+
>>> tokenizer.add_prefix_space = False
|
| 91 |
+
>>> tokenizer("Hello world")["input_ids"]
|
| 92 |
+
[47, 921, 86, 1085, 2]
|
| 93 |
+
|
| 94 |
+
>>> tokenizer(" Hello world")["input_ids"]
|
| 95 |
+
[6950, 1085, 2]
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
|
| 99 |
+
call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
|
| 100 |
+
|
| 101 |
+
<Tip>
|
| 102 |
+
|
| 103 |
+
When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
|
| 104 |
+
|
| 105 |
+
</Tip>
|
| 106 |
+
|
| 107 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 108 |
+
this superclass for more information regarding those methods.
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
vocab_file (`str`):
|
| 112 |
+
Path to the vocabulary file.
|
| 113 |
+
merges_file (`str`):
|
| 114 |
+
Path to the merges file.
|
| 115 |
+
errors (`str`, *optional*, defaults to `"replace"`):
|
| 116 |
+
Paradigm to follow when decoding bytes to UTF-8. See
|
| 117 |
+
[bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
|
| 118 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 119 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
| 120 |
+
|
| 121 |
+
<Tip>
|
| 122 |
+
|
| 123 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 124 |
+
sequence. The token used is the `cls_token`.
|
| 125 |
+
|
| 126 |
+
</Tip>
|
| 127 |
+
|
| 128 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 129 |
+
The end of sequence token.
|
| 130 |
+
|
| 131 |
+
<Tip>
|
| 132 |
+
|
| 133 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
| 134 |
+
The token used is the `sep_token`.
|
| 135 |
+
|
| 136 |
+
</Tip>
|
| 137 |
+
|
| 138 |
+
sep_token (`str`, *optional*, defaults to `"</s>"`):
|
| 139 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 140 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 141 |
+
token of a sequence built with special tokens.
|
| 142 |
+
cls_token (`str`, *optional*, defaults to `"<s>"`):
|
| 143 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 144 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 145 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 146 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 147 |
+
token instead.
|
| 148 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 149 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 150 |
+
mask_token (`str`, *optional*, defaults to `"<mask>"`):
|
| 151 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 152 |
+
modeling. This is the token which the model will try to predict.
|
| 153 |
+
add_prefix_space (`bool`, *optional*, defaults to `False`):
|
| 154 |
+
Whether or not to add an initial space to the input. This allows to treat the leading word just as any
|
| 155 |
+
other word. (Blenderbot tokenizer detect beginning of words by the preceding space).
|
| 156 |
+
"""
|
| 157 |
+
|
| 158 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 159 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 160 |
+
|
| 161 |
+
# Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.__init__ with Roberta->Blenderbot, RoBERTa->Blenderbot
|
| 162 |
+
def __init__(
|
| 163 |
+
self,
|
| 164 |
+
vocab_file,
|
| 165 |
+
merges_file,
|
| 166 |
+
errors="replace",
|
| 167 |
+
bos_token="<s>",
|
| 168 |
+
eos_token="</s>",
|
| 169 |
+
sep_token="</s>",
|
| 170 |
+
cls_token="<s>",
|
| 171 |
+
unk_token="<unk>",
|
| 172 |
+
pad_token="<pad>",
|
| 173 |
+
mask_token="<mask>",
|
| 174 |
+
add_prefix_space=False,
|
| 175 |
+
**kwargs,
|
| 176 |
+
):
|
| 177 |
+
bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
|
| 178 |
+
pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
|
| 179 |
+
eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
|
| 180 |
+
unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
|
| 181 |
+
sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
|
| 182 |
+
cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
|
| 183 |
+
|
| 184 |
+
# Mask token behave like a normal word, i.e. include the space before it
|
| 185 |
+
mask_token = (
|
| 186 |
+
AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False)
|
| 187 |
+
if isinstance(mask_token, str)
|
| 188 |
+
else mask_token
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
# these special tokens are not part of the vocab.json, let's add them in the correct order
|
| 192 |
+
|
| 193 |
+
with open(vocab_file, encoding="utf-8") as vocab_handle:
|
| 194 |
+
self.encoder = json.load(vocab_handle)
|
| 195 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
| 196 |
+
self.errors = errors # how to handle errors in decoding
|
| 197 |
+
self.byte_encoder = bytes_to_unicode()
|
| 198 |
+
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
|
| 199 |
+
with open(merges_file, encoding="utf-8") as merges_handle:
|
| 200 |
+
bpe_merges = merges_handle.read().split("\n")[1:-1]
|
| 201 |
+
bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
|
| 202 |
+
self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
|
| 203 |
+
self.cache = {}
|
| 204 |
+
self.add_prefix_space = add_prefix_space
|
| 205 |
+
|
| 206 |
+
# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
|
| 207 |
+
self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
|
| 208 |
+
|
| 209 |
+
super().__init__(
|
| 210 |
+
errors=errors,
|
| 211 |
+
bos_token=bos_token,
|
| 212 |
+
eos_token=eos_token,
|
| 213 |
+
unk_token=unk_token,
|
| 214 |
+
sep_token=sep_token,
|
| 215 |
+
cls_token=cls_token,
|
| 216 |
+
pad_token=pad_token,
|
| 217 |
+
mask_token=mask_token,
|
| 218 |
+
add_prefix_space=add_prefix_space,
|
| 219 |
+
**kwargs,
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
@property
|
| 223 |
+
# Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot
|
| 224 |
+
def vocab_size(self):
|
| 225 |
+
return len(self.encoder)
|
| 226 |
+
|
| 227 |
+
# Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.get_vocab with Roberta->Blenderbot, RoBERTa->Blenderbot
|
| 228 |
+
def get_vocab(self):
|
| 229 |
+
vocab = dict(self.encoder).copy()
|
| 230 |
+
vocab.update(self.added_tokens_encoder)
|
| 231 |
+
return vocab
|
| 232 |
+
|
| 233 |
+
# Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.bpe with Roberta->Blenderbot, RoBERTa->Blenderbot
|
| 234 |
+
def bpe(self, token):
|
| 235 |
+
if token in self.cache:
|
| 236 |
+
return self.cache[token]
|
| 237 |
+
word = tuple(token)
|
| 238 |
+
pairs = get_pairs(word)
|
| 239 |
+
|
| 240 |
+
if not pairs:
|
| 241 |
+
return token
|
| 242 |
+
|
| 243 |
+
while True:
|
| 244 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
| 245 |
+
if bigram not in self.bpe_ranks:
|
| 246 |
+
break
|
| 247 |
+
first, second = bigram
|
| 248 |
+
new_word = []
|
| 249 |
+
i = 0
|
| 250 |
+
while i < len(word):
|
| 251 |
+
try:
|
| 252 |
+
j = word.index(first, i)
|
| 253 |
+
except ValueError:
|
| 254 |
+
new_word.extend(word[i:])
|
| 255 |
+
break
|
| 256 |
+
else:
|
| 257 |
+
new_word.extend(word[i:j])
|
| 258 |
+
i = j
|
| 259 |
+
|
| 260 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
| 261 |
+
new_word.append(first + second)
|
| 262 |
+
i += 2
|
| 263 |
+
else:
|
| 264 |
+
new_word.append(word[i])
|
| 265 |
+
i += 1
|
| 266 |
+
new_word = tuple(new_word)
|
| 267 |
+
word = new_word
|
| 268 |
+
if len(word) == 1:
|
| 269 |
+
break
|
| 270 |
+
else:
|
| 271 |
+
pairs = get_pairs(word)
|
| 272 |
+
word = " ".join(word)
|
| 273 |
+
self.cache[token] = word
|
| 274 |
+
return word
|
| 275 |
+
|
| 276 |
+
# Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer._tokenize with Roberta->Blenderbot, RoBERTa->Blenderbot
|
| 277 |
+
def _tokenize(self, text):
|
| 278 |
+
"""Tokenize a string."""
|
| 279 |
+
bpe_tokens = []
|
| 280 |
+
for token in re.findall(self.pat, text):
|
| 281 |
+
token = "".join(
|
| 282 |
+
self.byte_encoder[b] for b in token.encode("utf-8")
|
| 283 |
+
) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
|
| 284 |
+
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
|
| 285 |
+
return bpe_tokens
|
| 286 |
+
|
| 287 |
+
# Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer._convert_token_to_id with Roberta->Blenderbot, RoBERTa->Blenderbot
|
| 288 |
+
def _convert_token_to_id(self, token):
|
| 289 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 290 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
| 291 |
+
|
| 292 |
+
# Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer._convert_id_to_token with Roberta->Blenderbot, RoBERTa->Blenderbot
|
| 293 |
+
def _convert_id_to_token(self, index):
|
| 294 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 295 |
+
return self.decoder.get(index)
|
| 296 |
+
|
| 297 |
+
# Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.convert_tokens_to_string with Roberta->Blenderbot, RoBERTa->Blenderbot
|
| 298 |
+
def convert_tokens_to_string(self, tokens):
|
| 299 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 300 |
+
text = "".join(tokens)
|
| 301 |
+
text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
|
| 302 |
+
return text
|
| 303 |
+
|
| 304 |
+
# Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.save_vocabulary with Roberta->Blenderbot, RoBERTa->Blenderbot
|
| 305 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 306 |
+
if not os.path.isdir(save_directory):
|
| 307 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 308 |
+
return
|
| 309 |
+
vocab_file = os.path.join(
|
| 310 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 311 |
+
)
|
| 312 |
+
merge_file = os.path.join(
|
| 313 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
| 317 |
+
f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
|
| 318 |
+
|
| 319 |
+
index = 0
|
| 320 |
+
with open(merge_file, "w", encoding="utf-8") as writer:
|
| 321 |
+
writer.write("#version: 0.2\n")
|
| 322 |
+
for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
|
| 323 |
+
if index != token_index:
|
| 324 |
+
logger.warning(
|
| 325 |
+
f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
|
| 326 |
+
" Please check that the tokenizer is not corrupted!"
|
| 327 |
+
)
|
| 328 |
+
index = token_index
|
| 329 |
+
writer.write(" ".join(bpe_tokens) + "\n")
|
| 330 |
+
index += 1
|
| 331 |
+
|
| 332 |
+
return vocab_file, merge_file
|
| 333 |
+
|
| 334 |
+
# Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.get_special_tokens_mask with Roberta->Blenderbot, RoBERTa->Blenderbot
|
| 335 |
+
def get_special_tokens_mask(
|
| 336 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
| 337 |
+
) -> List[int]:
|
| 338 |
+
"""
|
| 339 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 340 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 341 |
+
|
| 342 |
+
Args:
|
| 343 |
+
token_ids_0 (`List[int]`):
|
| 344 |
+
List of IDs.
|
| 345 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 346 |
+
Optional second list of IDs for sequence pairs.
|
| 347 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 348 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 349 |
+
|
| 350 |
+
Returns:
|
| 351 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 352 |
+
"""
|
| 353 |
+
if already_has_special_tokens:
|
| 354 |
+
return super().get_special_tokens_mask(
|
| 355 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
if token_ids_1 is None:
|
| 359 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
| 360 |
+
return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
|
| 361 |
+
|
| 362 |
+
# Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.create_token_type_ids_from_sequences with Roberta->Blenderbot, RoBERTa->Blenderbot
|
| 363 |
+
def create_token_type_ids_from_sequences(
|
| 364 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 365 |
+
) -> List[int]:
|
| 366 |
+
"""
|
| 367 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. Blenderbot does not
|
| 368 |
+
make use of token type ids, therefore a list of zeros is returned.
|
| 369 |
+
|
| 370 |
+
Args:
|
| 371 |
+
token_ids_0 (`List[int]`):
|
| 372 |
+
List of IDs.
|
| 373 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 374 |
+
Optional second list of IDs for sequence pairs.
|
| 375 |
+
|
| 376 |
+
Returns:
|
| 377 |
+
`List[int]`: List of zeros.
|
| 378 |
+
"""
|
| 379 |
+
sep = [self.sep_token_id]
|
| 380 |
+
cls = [self.cls_token_id]
|
| 381 |
+
|
| 382 |
+
if token_ids_1 is None:
|
| 383 |
+
return len(cls + token_ids_0 + sep) * [0]
|
| 384 |
+
return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
|
| 385 |
+
|
| 386 |
+
# Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.prepare_for_tokenization with Roberta->Blenderbot, RoBERTa->Blenderbot
|
| 387 |
+
def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
|
| 388 |
+
add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
|
| 389 |
+
if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
|
| 390 |
+
text = " " + text
|
| 391 |
+
return (text, kwargs)
|
| 392 |
+
|
| 393 |
+
def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None):
|
| 394 |
+
"""
|
| 395 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 396 |
+
adding special tokens. A Blenderbot sequence has the following format:
|
| 397 |
+
- single sequence: ` X </s>`
|
| 398 |
+
|
| 399 |
+
Args:
|
| 400 |
+
token_ids_0 (`List[int]`):
|
| 401 |
+
List of IDs to which the special tokens will be added
|
| 402 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 403 |
+
Will be ignored
|
| 404 |
+
Returns:
|
| 405 |
+
`List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 406 |
+
"""
|
| 407 |
+
return token_ids_0 + [self.eos_token_id]
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
__all__ = ["BlenderbotTokenizer"]
|
lib/python3.12/site-packages/transformers/models/blenderbot/tokenization_blenderbot_fast.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The Facebook Inc. and The HuggingFace Inc. team. 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 |
+
"""Fast Tokenization class for Blenderbot."""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
from typing import List, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
from tokenizers import processors
|
| 21 |
+
|
| 22 |
+
from ...tokenization_utils_base import AddedToken, BatchEncoding
|
| 23 |
+
from ...tokenization_utils_fast import PreTrainedTokenizerFast
|
| 24 |
+
from ...utils import logging
|
| 25 |
+
from .tokenization_blenderbot import BlenderbotTokenizer
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
VOCAB_FILES_NAMES = {
|
| 32 |
+
"vocab_file": "vocab.json",
|
| 33 |
+
"merges_file": "merges.txt",
|
| 34 |
+
"tokenizer_config_file": "tokenizer_config.json",
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class BlenderbotTokenizerFast(PreTrainedTokenizerFast):
|
| 39 |
+
"""
|
| 40 |
+
Construct a "fast" Blenderbot tokenizer (backed by HuggingFace's *tokenizers* library), derived from the GPT-2
|
| 41 |
+
tokenizer, using byte-level Byte-Pair-Encoding.
|
| 42 |
+
|
| 43 |
+
This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
|
| 44 |
+
be encoded differently whether it is at the beginning of the sentence (without space) or not:
|
| 45 |
+
|
| 46 |
+
```python
|
| 47 |
+
>>> from transformers import BlenderbotTokenizerFast
|
| 48 |
+
|
| 49 |
+
>>> tokenizer = BlenderbotTokenizerFast.from_pretrained("facebook/blenderbot-3B")
|
| 50 |
+
>>> tokenizer("Hello world")["input_ids"]
|
| 51 |
+
[6950, 1085, 2]
|
| 52 |
+
|
| 53 |
+
>>> tokenizer(" Hello world")["input_ids"]
|
| 54 |
+
[6950, 1085, 2]
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
|
| 58 |
+
call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
|
| 59 |
+
|
| 60 |
+
<Tip>
|
| 61 |
+
|
| 62 |
+
When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
|
| 63 |
+
|
| 64 |
+
</Tip>
|
| 65 |
+
|
| 66 |
+
This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
|
| 67 |
+
refer to this superclass for more information regarding those methods.
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
vocab_file (`str`):
|
| 71 |
+
Path to the vocabulary file.
|
| 72 |
+
merges_file (`str`):
|
| 73 |
+
Path to the merges file.
|
| 74 |
+
errors (`str`, *optional*, defaults to `"replace"`):
|
| 75 |
+
Paradigm to follow when decoding bytes to UTF-8. See
|
| 76 |
+
[bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
|
| 77 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 78 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
| 79 |
+
|
| 80 |
+
<Tip>
|
| 81 |
+
|
| 82 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 83 |
+
sequence. The token used is the `cls_token`.
|
| 84 |
+
|
| 85 |
+
</Tip>
|
| 86 |
+
|
| 87 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 88 |
+
The end of sequence token.
|
| 89 |
+
|
| 90 |
+
<Tip>
|
| 91 |
+
|
| 92 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
| 93 |
+
The token used is the `sep_token`.
|
| 94 |
+
|
| 95 |
+
</Tip>
|
| 96 |
+
|
| 97 |
+
sep_token (`str`, *optional*, defaults to `"</s>"`):
|
| 98 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 99 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 100 |
+
token of a sequence built with special tokens.
|
| 101 |
+
cls_token (`str`, *optional*, defaults to `"<s>"`):
|
| 102 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 103 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 104 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 105 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 106 |
+
token instead.
|
| 107 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 108 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 109 |
+
mask_token (`str`, *optional*, defaults to `"<mask>"`):
|
| 110 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 111 |
+
modeling. This is the token which the model will try to predict.
|
| 112 |
+
add_prefix_space (`bool`, *optional*, defaults to `False`):
|
| 113 |
+
Whether or not to add an initial space to the input. This allows to treat the leading word just as any
|
| 114 |
+
other word. (Blenderbot tokenizer detect beginning of words by the preceding space).
|
| 115 |
+
trim_offsets (`bool`, *optional*, defaults to `True`):
|
| 116 |
+
Whether the post processing step should trim offsets to avoid including whitespaces.
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 120 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 121 |
+
slow_tokenizer_class = BlenderbotTokenizer
|
| 122 |
+
|
| 123 |
+
# Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.__init__ with Roberta->Blenderbot, RoBERTa->Blenderbot
|
| 124 |
+
def __init__(
|
| 125 |
+
self,
|
| 126 |
+
vocab_file=None,
|
| 127 |
+
merges_file=None,
|
| 128 |
+
tokenizer_file=None,
|
| 129 |
+
errors="replace",
|
| 130 |
+
bos_token="<s>",
|
| 131 |
+
eos_token="</s>",
|
| 132 |
+
sep_token="</s>",
|
| 133 |
+
cls_token="<s>",
|
| 134 |
+
unk_token="<unk>",
|
| 135 |
+
pad_token="<pad>",
|
| 136 |
+
mask_token="<mask>",
|
| 137 |
+
add_prefix_space=False,
|
| 138 |
+
trim_offsets=True,
|
| 139 |
+
**kwargs,
|
| 140 |
+
):
|
| 141 |
+
mask_token = (
|
| 142 |
+
AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False)
|
| 143 |
+
if isinstance(mask_token, str)
|
| 144 |
+
else mask_token
|
| 145 |
+
)
|
| 146 |
+
super().__init__(
|
| 147 |
+
vocab_file,
|
| 148 |
+
merges_file,
|
| 149 |
+
tokenizer_file=tokenizer_file,
|
| 150 |
+
errors=errors,
|
| 151 |
+
bos_token=bos_token,
|
| 152 |
+
eos_token=eos_token,
|
| 153 |
+
sep_token=sep_token,
|
| 154 |
+
cls_token=cls_token,
|
| 155 |
+
unk_token=unk_token,
|
| 156 |
+
pad_token=pad_token,
|
| 157 |
+
mask_token=mask_token,
|
| 158 |
+
add_prefix_space=add_prefix_space,
|
| 159 |
+
trim_offsets=trim_offsets,
|
| 160 |
+
**kwargs,
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
tokenizer_component = "post_processor"
|
| 164 |
+
tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None)
|
| 165 |
+
if tokenizer_component_instance:
|
| 166 |
+
state = json.loads(tokenizer_component_instance.__getstate__())
|
| 167 |
+
|
| 168 |
+
# The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
|
| 169 |
+
if "sep" in state:
|
| 170 |
+
state["sep"] = tuple(state["sep"])
|
| 171 |
+
if "cls" in state:
|
| 172 |
+
state["cls"] = tuple(state["cls"])
|
| 173 |
+
|
| 174 |
+
changes_to_apply = False
|
| 175 |
+
|
| 176 |
+
if state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
|
| 177 |
+
state["add_prefix_space"] = add_prefix_space
|
| 178 |
+
changes_to_apply = True
|
| 179 |
+
|
| 180 |
+
if state.get("trim_offsets", trim_offsets) != trim_offsets:
|
| 181 |
+
state["trim_offsets"] = trim_offsets
|
| 182 |
+
changes_to_apply = True
|
| 183 |
+
|
| 184 |
+
if changes_to_apply:
|
| 185 |
+
component_class = getattr(processors, state.pop("type"))
|
| 186 |
+
new_value = component_class(**state)
|
| 187 |
+
setattr(self.backend_tokenizer, tokenizer_component, new_value)
|
| 188 |
+
|
| 189 |
+
@property
|
| 190 |
+
# Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.mask_token with Roberta->Blenderbot, RoBERTa->Blenderbot
|
| 191 |
+
def mask_token(self) -> str:
|
| 192 |
+
"""
|
| 193 |
+
`str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
|
| 194 |
+
having been set.
|
| 195 |
+
|
| 196 |
+
Blenderbot tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily
|
| 197 |
+
comprise the space before the *<mask>*.
|
| 198 |
+
"""
|
| 199 |
+
if self._mask_token is None:
|
| 200 |
+
if self.verbose:
|
| 201 |
+
logger.error("Using mask_token, but it is not set yet.")
|
| 202 |
+
return None
|
| 203 |
+
return str(self._mask_token)
|
| 204 |
+
|
| 205 |
+
@mask_token.setter
|
| 206 |
+
def mask_token(self, value):
|
| 207 |
+
"""
|
| 208 |
+
Overriding the default behavior of the mask token to have it eat the space before it.
|
| 209 |
+
|
| 210 |
+
This is needed to preserve backward compatibility with all the previously used models based on Roberta.
|
| 211 |
+
"""
|
| 212 |
+
# Mask token behave like a normal word, i.e. include the space before it
|
| 213 |
+
# So we set lstrip to True
|
| 214 |
+
value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value
|
| 215 |
+
self._mask_token = value
|
| 216 |
+
|
| 217 |
+
# Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast._batch_encode_plus with Roberta->Blenderbot, RoBERTa->Blenderbot
|
| 218 |
+
def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
|
| 219 |
+
is_split_into_words = kwargs.get("is_split_into_words", False)
|
| 220 |
+
assert self.add_prefix_space or not is_split_into_words, (
|
| 221 |
+
f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
|
| 222 |
+
"to use it with pretokenized inputs."
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
return super()._batch_encode_plus(*args, **kwargs)
|
| 226 |
+
|
| 227 |
+
# Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast._encode_plus with Roberta->Blenderbot, RoBERTa->Blenderbot
|
| 228 |
+
def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
|
| 229 |
+
is_split_into_words = kwargs.get("is_split_into_words", False)
|
| 230 |
+
|
| 231 |
+
assert self.add_prefix_space or not is_split_into_words, (
|
| 232 |
+
f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
|
| 233 |
+
"to use it with pretokenized inputs."
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
return super()._encode_plus(*args, **kwargs)
|
| 237 |
+
|
| 238 |
+
# Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.save_vocabulary with Roberta->Blenderbot, RoBERTa->Blenderbot
|
| 239 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 240 |
+
files = self._tokenizer.model.save(save_directory, name=filename_prefix)
|
| 241 |
+
return tuple(files)
|
| 242 |
+
|
| 243 |
+
# Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.create_token_type_ids_from_sequences with Roberta->Blenderbot, RoBERTa->Blenderbot
|
| 244 |
+
def create_token_type_ids_from_sequences(
|
| 245 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 246 |
+
) -> List[int]:
|
| 247 |
+
"""
|
| 248 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. Blenderbot does not
|
| 249 |
+
make use of token type ids, therefore a list of zeros is returned.
|
| 250 |
+
|
| 251 |
+
Args:
|
| 252 |
+
token_ids_0 (`List[int]`):
|
| 253 |
+
List of IDs.
|
| 254 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 255 |
+
Optional second list of IDs for sequence pairs.
|
| 256 |
+
|
| 257 |
+
Returns:
|
| 258 |
+
`List[int]`: List of zeros.
|
| 259 |
+
"""
|
| 260 |
+
sep = [self.sep_token_id]
|
| 261 |
+
cls = [self.cls_token_id]
|
| 262 |
+
|
| 263 |
+
if token_ids_1 is None:
|
| 264 |
+
return len(cls + token_ids_0 + sep) * [0]
|
| 265 |
+
return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
|
| 266 |
+
|
| 267 |
+
def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None):
|
| 268 |
+
"""
|
| 269 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 270 |
+
adding special tokens. A Blenderbot sequence has the following format:
|
| 271 |
+
- single sequence: ` X </s>`
|
| 272 |
+
|
| 273 |
+
Args:
|
| 274 |
+
token_ids_0 (`List[int]`):
|
| 275 |
+
List of IDs to which the special tokens will be added
|
| 276 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 277 |
+
Will be ignored
|
| 278 |
+
Returns:
|
| 279 |
+
`List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 280 |
+
"""
|
| 281 |
+
return token_ids_0 + [self.eos_token_id]
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
__all__ = ["BlenderbotTokenizerFast"]
|
lib/python3.12/site-packages/transformers/models/code_llama/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .tokenization_code_llama import *
|
| 22 |
+
from .tokenization_code_llama_fast import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.12/site-packages/transformers/models/code_llama/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (687 Bytes). View file
|
|
|
lib/python3.12/site-packages/transformers/models/code_llama/__pycache__/tokenization_code_llama.cpython-312.pyc
ADDED
|
Binary file (21.4 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/code_llama/__pycache__/tokenization_code_llama_fast.cpython-312.pyc
ADDED
|
Binary file (17.8 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/code_llama/tokenization_code_llama.py
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 MetaAI and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
|
| 17 |
+
"""Tokenization classes for Code LLaMA."""
|
| 18 |
+
|
| 19 |
+
import os
|
| 20 |
+
from shutil import copyfile
|
| 21 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 22 |
+
|
| 23 |
+
import sentencepiece as spm
|
| 24 |
+
|
| 25 |
+
from ...convert_slow_tokenizer import import_protobuf
|
| 26 |
+
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
|
| 27 |
+
from ...utils import logging, requires_backends
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
|
| 33 |
+
|
| 34 |
+
SPIECE_UNDERLINE = "▁"
|
| 35 |
+
|
| 36 |
+
B_INST, E_INST = "[INST]", "[/INST]"
|
| 37 |
+
B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
|
| 38 |
+
|
| 39 |
+
# fmt: off
|
| 40 |
+
DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your \
|
| 41 |
+
answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
|
| 42 |
+
that your responses are socially unbiased and positive in nature.
|
| 43 |
+
|
| 44 |
+
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not \
|
| 45 |
+
correct. If you don't know the answer to a question, please don't share false information."""
|
| 46 |
+
# fmt: on
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class CodeLlamaTokenizer(PreTrainedTokenizer):
|
| 50 |
+
"""
|
| 51 |
+
Construct a CodeLlama tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as
|
| 52 |
+
there is no padding token in the original model.
|
| 53 |
+
|
| 54 |
+
The default configuration match that of
|
| 55 |
+
[codellama/CodeLlama-7b-Instruct-hf](https://huggingface.co/meta-llama/CodeLlama-7b-Instruct-hf/blob/main/tokenizer_config.json)
|
| 56 |
+
which supports prompt infilling.
|
| 57 |
+
|
| 58 |
+
Args:
|
| 59 |
+
vocab_file (`str`):
|
| 60 |
+
Path to the vocabulary file.
|
| 61 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 62 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 63 |
+
token instead.
|
| 64 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 65 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
| 66 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 67 |
+
The end of sequence token.
|
| 68 |
+
|
| 69 |
+
<Tip>
|
| 70 |
+
|
| 71 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
| 72 |
+
The token used is the `sep_token`.
|
| 73 |
+
|
| 74 |
+
</Tip>
|
| 75 |
+
|
| 76 |
+
prefix_token (`str`, *optional*, defaults to `"▁<PRE>"`):
|
| 77 |
+
Prefix token used for infilling.
|
| 78 |
+
middle_token (`str`, *optional*, defaults to `"▁<MID>"`):
|
| 79 |
+
Middle token used for infilling.
|
| 80 |
+
suffix_token (`str`, *optional*, defaults to `"▁<SUF>"`):
|
| 81 |
+
Suffix token used for infilling.
|
| 82 |
+
eot_token (`str`, *optional*, defaults to `"▁<EOT>"`):
|
| 83 |
+
End of text token used for infilling.
|
| 84 |
+
fill_token (`str`, *optional*, defaults to `"<FILL_ME>"`):
|
| 85 |
+
The token used to split the input between the prefix and suffix.
|
| 86 |
+
suffix_first (`bool`, *optional*, defaults to `False`):
|
| 87 |
+
Whether the input prompt and suffix should be formatted with the suffix first.
|
| 88 |
+
sp_model_kwargs (`dict`, *optional*):
|
| 89 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
| 90 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
| 91 |
+
to set:
|
| 92 |
+
|
| 93 |
+
- `enable_sampling`: Enable subword regularization.
|
| 94 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
| 95 |
+
|
| 96 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
| 97 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
| 98 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
| 99 |
+
using forward-filtering-and-backward-sampling algorithm.
|
| 100 |
+
|
| 101 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
| 102 |
+
BPE-dropout.
|
| 103 |
+
add_bos_token (`bool`, *optional*, defaults to `True`):
|
| 104 |
+
Whether to add a beginning of sequence token at the start of sequences.
|
| 105 |
+
add_eos_token (`bool`, *optional*, defaults to `False`):
|
| 106 |
+
Whether to add an end of sequence token at the end of sequences.
|
| 107 |
+
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
|
| 108 |
+
Whether or not to clean up the tokenization spaces.
|
| 109 |
+
additional_special_tokens (`List[str]`, *optional*):
|
| 110 |
+
Additional special tokens used by the tokenizer.
|
| 111 |
+
use_default_system_prompt (`bool`, *optional*, defaults to `False`):
|
| 112 |
+
Whether or not the default system prompt for Llama should be used.
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 116 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 117 |
+
|
| 118 |
+
def __init__(
|
| 119 |
+
self,
|
| 120 |
+
vocab_file,
|
| 121 |
+
unk_token="<unk>",
|
| 122 |
+
bos_token="<s>",
|
| 123 |
+
eos_token="</s>",
|
| 124 |
+
prefix_token="▁<PRE>",
|
| 125 |
+
middle_token="▁<MID>",
|
| 126 |
+
suffix_token="▁<SUF>",
|
| 127 |
+
eot_token="▁<EOT>",
|
| 128 |
+
fill_token="<FILL_ME>",
|
| 129 |
+
suffix_first=False,
|
| 130 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
| 131 |
+
add_bos_token=True,
|
| 132 |
+
add_eos_token=False,
|
| 133 |
+
clean_up_tokenization_spaces=False,
|
| 134 |
+
additional_special_tokens=None,
|
| 135 |
+
use_default_system_prompt=False,
|
| 136 |
+
**kwargs,
|
| 137 |
+
):
|
| 138 |
+
requires_backends(self, "protobuf")
|
| 139 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 140 |
+
bos_token = AddedToken(bos_token, normalized=False, special=True) if isinstance(bos_token, str) else bos_token
|
| 141 |
+
eos_token = AddedToken(eos_token, normalized=False, special=True) if isinstance(eos_token, str) else eos_token
|
| 142 |
+
unk_token = AddedToken(unk_token, normalized=False, special=True) if isinstance(unk_token, str) else unk_token
|
| 143 |
+
|
| 144 |
+
self.use_default_system_prompt = use_default_system_prompt
|
| 145 |
+
# mark tokens special to skip them
|
| 146 |
+
additional_special_tokens = additional_special_tokens or []
|
| 147 |
+
for token in [prefix_token, middle_token, suffix_token, eot_token]:
|
| 148 |
+
additional_special_tokens += [token] if token is not None else []
|
| 149 |
+
|
| 150 |
+
self.vocab_file = vocab_file
|
| 151 |
+
self.add_bos_token = add_bos_token
|
| 152 |
+
self.add_eos_token = add_eos_token
|
| 153 |
+
self._prefix_token = prefix_token
|
| 154 |
+
self._middle_token = middle_token
|
| 155 |
+
self._suffix_token = suffix_token
|
| 156 |
+
self._eot_token = eot_token
|
| 157 |
+
self.fill_token = fill_token
|
| 158 |
+
self.suffix_first = suffix_first
|
| 159 |
+
self.sp_model = self.get_spm_processor()
|
| 160 |
+
|
| 161 |
+
super().__init__(
|
| 162 |
+
bos_token=bos_token,
|
| 163 |
+
eos_token=eos_token,
|
| 164 |
+
unk_token=unk_token,
|
| 165 |
+
add_bos_token=add_bos_token,
|
| 166 |
+
add_eos_token=add_eos_token,
|
| 167 |
+
prefix_token=prefix_token,
|
| 168 |
+
middle_token=middle_token,
|
| 169 |
+
suffix_token=suffix_token,
|
| 170 |
+
eot_token=eot_token,
|
| 171 |
+
fill_token=fill_token,
|
| 172 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
| 173 |
+
suffix_first=suffix_first,
|
| 174 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
| 175 |
+
additional_special_tokens=additional_special_tokens,
|
| 176 |
+
use_default_system_prompt=use_default_system_prompt,
|
| 177 |
+
**kwargs,
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
@property
|
| 181 |
+
def unk_token_length(self):
|
| 182 |
+
return len(self.sp_model.encode(str(self.unk_token)))
|
| 183 |
+
|
| 184 |
+
def get_spm_processor(self):
|
| 185 |
+
tokenizer = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 186 |
+
with open(self.vocab_file, "rb") as f:
|
| 187 |
+
sp_model = f.read()
|
| 188 |
+
model_pb2 = import_protobuf()
|
| 189 |
+
model = model_pb2.ModelProto.FromString(sp_model)
|
| 190 |
+
normalizer_spec = model_pb2.NormalizerSpec()
|
| 191 |
+
normalizer_spec.add_dummy_prefix = False
|
| 192 |
+
model.normalizer_spec.MergeFrom(normalizer_spec)
|
| 193 |
+
sp_model = model.SerializeToString()
|
| 194 |
+
tokenizer.LoadFromSerializedProto(sp_model)
|
| 195 |
+
return tokenizer
|
| 196 |
+
|
| 197 |
+
@property
|
| 198 |
+
def prefix_token(self):
|
| 199 |
+
return self._prefix_token
|
| 200 |
+
|
| 201 |
+
@property
|
| 202 |
+
def prefix_id(self):
|
| 203 |
+
if self._prefix_token is None:
|
| 204 |
+
return None
|
| 205 |
+
return self.convert_tokens_to_ids(self.prefix_token)
|
| 206 |
+
|
| 207 |
+
@property
|
| 208 |
+
def middle_token(self):
|
| 209 |
+
return self._middle_token
|
| 210 |
+
|
| 211 |
+
@property
|
| 212 |
+
def middle_id(self):
|
| 213 |
+
if self._middle_token is None:
|
| 214 |
+
return None
|
| 215 |
+
return self.convert_tokens_to_ids(self.middle_token)
|
| 216 |
+
|
| 217 |
+
@property
|
| 218 |
+
def suffix_token(self):
|
| 219 |
+
return self._suffix_token
|
| 220 |
+
|
| 221 |
+
@property
|
| 222 |
+
def suffix_id(self):
|
| 223 |
+
if self._suffix_token is None:
|
| 224 |
+
return None
|
| 225 |
+
return self.convert_tokens_to_ids(self.suffix_token)
|
| 226 |
+
|
| 227 |
+
@property
|
| 228 |
+
def eot_token(self):
|
| 229 |
+
return self._eot_token
|
| 230 |
+
|
| 231 |
+
@property
|
| 232 |
+
def eot_id(self):
|
| 233 |
+
if self._eot_token is None:
|
| 234 |
+
return None
|
| 235 |
+
return self.convert_tokens_to_ids(self.eot_token)
|
| 236 |
+
|
| 237 |
+
@property
|
| 238 |
+
def vocab_size(self):
|
| 239 |
+
"""Returns vocab size"""
|
| 240 |
+
return self.sp_model.get_piece_size()
|
| 241 |
+
|
| 242 |
+
# Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.get_vocab
|
| 243 |
+
def get_vocab(self):
|
| 244 |
+
"""Returns vocab as a dict"""
|
| 245 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
| 246 |
+
vocab.update(self.added_tokens_encoder)
|
| 247 |
+
return vocab
|
| 248 |
+
|
| 249 |
+
def tokenize(self, prefix, suffix=None, suffix_first=False, **kwargs) -> List[int]:
|
| 250 |
+
# add a prefix space to `prefix`
|
| 251 |
+
if self.fill_token is not None and self.fill_token in prefix and suffix is None:
|
| 252 |
+
prefix, suffix = prefix.split(self.fill_token)
|
| 253 |
+
|
| 254 |
+
if len(prefix) > 0:
|
| 255 |
+
prefix = SPIECE_UNDERLINE + prefix.replace(SPIECE_UNDERLINE, " ")
|
| 256 |
+
|
| 257 |
+
if suffix is None or len(suffix) < 1:
|
| 258 |
+
tokens = super().tokenize(prefix, **kwargs)
|
| 259 |
+
if len(tokens) > 1 and tokens[0] == SPIECE_UNDERLINE and tokens[1] in self.all_special_tokens:
|
| 260 |
+
tokens = tokens[1:]
|
| 261 |
+
return tokens
|
| 262 |
+
|
| 263 |
+
prefix_tokens = self._tokenize(prefix) # prefix has an extra `SPIECE_UNDERLINE`
|
| 264 |
+
|
| 265 |
+
if None in (self.prefix_id, self.middle_id, self.suffix_id):
|
| 266 |
+
raise ValueError(
|
| 267 |
+
"The input either includes a `prefix` and a `suffix` used for the infilling task,"
|
| 268 |
+
f" or can be split on the {self.fill_token} token, creating a suffix and prefix,"
|
| 269 |
+
" but the model does not support `infilling`."
|
| 270 |
+
)
|
| 271 |
+
suffix_tokens = self._tokenize(suffix) # make sure CodeLlama sp model does not mess up
|
| 272 |
+
|
| 273 |
+
suffix_first = suffix_first if suffix_first is not None else self.suffix_first
|
| 274 |
+
if suffix_first:
|
| 275 |
+
# format as " <PRE> <SUF>{suf} <MID> {pre}"
|
| 276 |
+
return [self.prefix_token, self.suffix_token] + suffix_tokens + [self.middle_token] + prefix_tokens
|
| 277 |
+
else:
|
| 278 |
+
# format as " <PRE> {pre} <SUF>{suf} <MID>"
|
| 279 |
+
return [self.prefix_token] + prefix_tokens + [self.suffix_token] + suffix_tokens + [self.middle_token]
|
| 280 |
+
|
| 281 |
+
def _tokenize(self, text, **kwargs):
|
| 282 |
+
"""
|
| 283 |
+
Returns a tokenized string.
|
| 284 |
+
|
| 285 |
+
We de-activated the `add_dummy_prefix` option, thus the sentencepiece internals will always strip any
|
| 286 |
+
SPIECE_UNDERLINE. For example: `self.sp_model.encode(f"{SPIECE_UNDERLINE}Hey", out_type = str)` will give
|
| 287 |
+
`['H', 'e', 'y']` instead of `['▁He', 'y']`. Thus we always encode `f"{unk_token}text"` and strip the
|
| 288 |
+
`unk_token`. Here is an example with `unk_token = "<unk>"` and `unk_token_length = 4`.
|
| 289 |
+
`self.tokenizer.sp_model.encode("<unk> Hey", out_type = str)[4:]`.
|
| 290 |
+
"""
|
| 291 |
+
tokens = self.sp_model.encode(text, out_type=str)
|
| 292 |
+
if not text.startswith((SPIECE_UNDERLINE, " ")):
|
| 293 |
+
return tokens
|
| 294 |
+
# 1. Encode string + prefix ex: "<unk> Hey"
|
| 295 |
+
tokens = self.sp_model.encode(self.unk_token + text, out_type=str)
|
| 296 |
+
# 2. Remove self.unk_token from ['<','unk','>', '▁Hey']
|
| 297 |
+
return tokens[self.unk_token_length :] if len(tokens) >= self.unk_token_length else tokens
|
| 298 |
+
|
| 299 |
+
# Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer._convert_token_to_id
|
| 300 |
+
def _convert_token_to_id(self, token):
|
| 301 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 302 |
+
return self.sp_model.piece_to_id(token)
|
| 303 |
+
|
| 304 |
+
# Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer._convert_id_to_token
|
| 305 |
+
def _convert_id_to_token(self, index):
|
| 306 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 307 |
+
token = self.sp_model.IdToPiece(index)
|
| 308 |
+
return token
|
| 309 |
+
|
| 310 |
+
def convert_tokens_to_string(self, tokens):
|
| 311 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 312 |
+
# since we manually add the prefix space, we have to remove it when decoding
|
| 313 |
+
if tokens[0].startswith(SPIECE_UNDERLINE):
|
| 314 |
+
tokens[0] = tokens[0][1:]
|
| 315 |
+
|
| 316 |
+
current_sub_tokens = []
|
| 317 |
+
out_string = ""
|
| 318 |
+
for _, token in enumerate(tokens):
|
| 319 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
| 320 |
+
if token in self.all_special_tokens:
|
| 321 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
| 322 |
+
current_sub_tokens = []
|
| 323 |
+
else:
|
| 324 |
+
current_sub_tokens.append(token)
|
| 325 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
| 326 |
+
return out_string
|
| 327 |
+
|
| 328 |
+
# Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.save_vocabulary
|
| 329 |
+
def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 330 |
+
"""
|
| 331 |
+
Save the vocabulary and special tokens file to a directory.
|
| 332 |
+
|
| 333 |
+
Args:
|
| 334 |
+
save_directory (`str`):
|
| 335 |
+
The directory in which to save the vocabulary.
|
| 336 |
+
|
| 337 |
+
Returns:
|
| 338 |
+
`Tuple(str)`: Paths to the files saved.
|
| 339 |
+
"""
|
| 340 |
+
if not os.path.isdir(save_directory):
|
| 341 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 342 |
+
return
|
| 343 |
+
out_vocab_file = os.path.join(
|
| 344 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
| 348 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 349 |
+
elif not os.path.isfile(self.vocab_file):
|
| 350 |
+
with open(out_vocab_file, "wb") as fi:
|
| 351 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
| 352 |
+
fi.write(content_spiece_model)
|
| 353 |
+
|
| 354 |
+
return (out_vocab_file,)
|
| 355 |
+
|
| 356 |
+
# Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.build_inputs_with_special_tokens
|
| 357 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
| 358 |
+
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
|
| 359 |
+
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
|
| 360 |
+
|
| 361 |
+
output = bos_token_id + token_ids_0 + eos_token_id
|
| 362 |
+
|
| 363 |
+
if token_ids_1 is not None:
|
| 364 |
+
output = output + bos_token_id + token_ids_1 + eos_token_id
|
| 365 |
+
|
| 366 |
+
return output
|
| 367 |
+
|
| 368 |
+
# Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.get_special_tokens_mask
|
| 369 |
+
def get_special_tokens_mask(
|
| 370 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
| 371 |
+
) -> List[int]:
|
| 372 |
+
"""
|
| 373 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 374 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 375 |
+
|
| 376 |
+
Args:
|
| 377 |
+
token_ids_0 (`List[int]`):
|
| 378 |
+
List of IDs.
|
| 379 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 380 |
+
Optional second list of IDs for sequence pairs.
|
| 381 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 382 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 383 |
+
|
| 384 |
+
Returns:
|
| 385 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 386 |
+
"""
|
| 387 |
+
if already_has_special_tokens:
|
| 388 |
+
return super().get_special_tokens_mask(
|
| 389 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
bos_token_id = [1] if self.add_bos_token else []
|
| 393 |
+
eos_token_id = [1] if self.add_eos_token else []
|
| 394 |
+
|
| 395 |
+
if token_ids_1 is None:
|
| 396 |
+
return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
|
| 397 |
+
return (
|
| 398 |
+
bos_token_id
|
| 399 |
+
+ ([0] * len(token_ids_0))
|
| 400 |
+
+ eos_token_id
|
| 401 |
+
+ bos_token_id
|
| 402 |
+
+ ([0] * len(token_ids_1))
|
| 403 |
+
+ eos_token_id
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
# Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.create_token_type_ids_from_sequences
|
| 407 |
+
def create_token_type_ids_from_sequences(
|
| 408 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 409 |
+
) -> List[int]:
|
| 410 |
+
"""
|
| 411 |
+
Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
|
| 412 |
+
sequence pair mask has the following format:
|
| 413 |
+
|
| 414 |
+
```
|
| 415 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
| 416 |
+
| first sequence | second sequence |
|
| 417 |
+
```
|
| 418 |
+
|
| 419 |
+
if token_ids_1 is None, only returns the first portion of the mask (0s).
|
| 420 |
+
|
| 421 |
+
Args:
|
| 422 |
+
token_ids_0 (`List[int]`):
|
| 423 |
+
List of ids.
|
| 424 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 425 |
+
Optional second list of IDs for sequence pairs.
|
| 426 |
+
|
| 427 |
+
Returns:
|
| 428 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
| 429 |
+
"""
|
| 430 |
+
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
|
| 431 |
+
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
|
| 432 |
+
|
| 433 |
+
output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
|
| 434 |
+
|
| 435 |
+
if token_ids_1 is not None:
|
| 436 |
+
output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
|
| 437 |
+
|
| 438 |
+
return output
|
| 439 |
+
|
| 440 |
+
def __getstate__(self):
|
| 441 |
+
state = self.__dict__.copy()
|
| 442 |
+
state["sp_model"] = None
|
| 443 |
+
state["sp_model_proto"] = self.sp_model.serialized_model_proto()
|
| 444 |
+
return state
|
| 445 |
+
|
| 446 |
+
def __setstate__(self, d):
|
| 447 |
+
self.__dict__ = d
|
| 448 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 449 |
+
self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
__all__ = ["CodeLlamaTokenizer"]
|
lib/python3.12/site-packages/transformers/models/code_llama/tokenization_code_llama_fast.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team.
|
| 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 |
+
import os
|
| 16 |
+
from shutil import copyfile
|
| 17 |
+
from typing import List, Optional, Tuple
|
| 18 |
+
|
| 19 |
+
from tokenizers import normalizers, processors
|
| 20 |
+
|
| 21 |
+
from ...tokenization_utils_fast import PreTrainedTokenizerFast
|
| 22 |
+
from ...utils import is_sentencepiece_available, logging
|
| 23 |
+
from ...utils.versions import require_version
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
require_version("tokenizers>=0.13.3")
|
| 27 |
+
|
| 28 |
+
if is_sentencepiece_available():
|
| 29 |
+
from .tokenization_code_llama import CodeLlamaTokenizer
|
| 30 |
+
else:
|
| 31 |
+
CodeLlamaTokenizer = None
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model", "tokenizer_file": "tokenizer.json"}
|
| 35 |
+
|
| 36 |
+
SPIECE_UNDERLINE = "▁"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
B_INST, E_INST = "[INST]", "[/INST]"
|
| 40 |
+
B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
|
| 41 |
+
|
| 42 |
+
# fmt: off
|
| 43 |
+
DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your \
|
| 44 |
+
answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
|
| 45 |
+
that your responses are socially unbiased and positive in nature.
|
| 46 |
+
|
| 47 |
+
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not \
|
| 48 |
+
correct. If you don't know the answer to a question, please don't share false information."""
|
| 49 |
+
# fmt: on
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class CodeLlamaTokenizerFast(PreTrainedTokenizerFast):
|
| 53 |
+
"""
|
| 54 |
+
Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding.
|
| 55 |
+
|
| 56 |
+
This uses notably ByteFallback and no normalization.
|
| 57 |
+
|
| 58 |
+
```python
|
| 59 |
+
>>> from transformers import CodeLlamaTokenizerFast
|
| 60 |
+
|
| 61 |
+
>>> tokenizer = CodeLlamaTokenizerFast.from_pretrained("hf-internal-testing/llama-tokenizer")
|
| 62 |
+
>>> tokenizer.encode("Hello this is a test")
|
| 63 |
+
[1, 15043, 445, 338, 263, 1243]
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
If you want to change the `bos_token` or the `eos_token`, make sure to specify them when initializing the model, or
|
| 67 |
+
call `tokenizer.update_post_processor()` to make sure that the post-processing is correctly done (otherwise the
|
| 68 |
+
values of the first token and final token of an encoded sequence will not be correct). For more details, checkout
|
| 69 |
+
[post-processors] (https://huggingface.co/docs/tokenizers/api/post-processors) documentation.
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
|
| 73 |
+
refer to this superclass for more information regarding those methods. The default configuration match that of
|
| 74 |
+
[meta-llama/CodeLlama-7b-Instruct-hf](https://huggingface.co/meta-llama/CodeLlama-7b-Instruct-hf/blob/main/tokenizer_config.json)
|
| 75 |
+
which supports prompt infilling.
|
| 76 |
+
|
| 77 |
+
Args:
|
| 78 |
+
vocab_file (`str`, *optional*):
|
| 79 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a .model extension) that
|
| 80 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 81 |
+
tokenizer_file (`str`, *optional*):
|
| 82 |
+
[tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that
|
| 83 |
+
contains everything needed to load the tokenizer.
|
| 84 |
+
clean_up_tokenization_spaces (`str`, *optional*, defaults to `False`):
|
| 85 |
+
Whether to cleanup spaces after decoding, cleanup consists in removing potential artifacts like extra
|
| 86 |
+
spaces.
|
| 87 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 88 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 89 |
+
token instead.
|
| 90 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 91 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
| 92 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 93 |
+
The end of sequence token.
|
| 94 |
+
prefix_token (`str`, *optional*, defaults to `"▁<PRE>"`):
|
| 95 |
+
Prefix token used for infilling.
|
| 96 |
+
middle_token (`str`, *optional*, defaults to `"▁<MID>"`):
|
| 97 |
+
Middle token used for infilling.
|
| 98 |
+
suffix_token (`str`, *optional*, defaults to `"▁<SUF>"`):
|
| 99 |
+
Suffix token used for infilling.
|
| 100 |
+
eot_token (`str`, *optional*, defaults to `"▁<EOT>"`):
|
| 101 |
+
End of text token used for infilling.
|
| 102 |
+
fill_token (`str`, *optional*, defaults to `"<FILL_ME>"`):
|
| 103 |
+
The token used to split the input between the prefix and suffix.
|
| 104 |
+
additional_special_tokens (`List[str]`, *optional*):
|
| 105 |
+
Additional special tokens used by the tokenizer.
|
| 106 |
+
add_bos_token (`bool`, *optional*, defaults to `True`):
|
| 107 |
+
Whether to add a beginning of sequence token at the start of sequences.
|
| 108 |
+
add_eos_token (`bool`, *optional*, defaults to `False`):
|
| 109 |
+
Whether to add an end of sequence token at the end of sequences.
|
| 110 |
+
use_default_system_prompt (`bool`, *optional*, defaults to `False`):
|
| 111 |
+
Whether or not the default system prompt for Llama should be used.
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 115 |
+
slow_tokenizer_class = CodeLlamaTokenizer
|
| 116 |
+
padding_side = "left"
|
| 117 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 118 |
+
|
| 119 |
+
def __init__(
|
| 120 |
+
self,
|
| 121 |
+
vocab_file=None,
|
| 122 |
+
tokenizer_file=None,
|
| 123 |
+
clean_up_tokenization_spaces=False,
|
| 124 |
+
unk_token="<unk>",
|
| 125 |
+
bos_token="<s>",
|
| 126 |
+
eos_token="</s>",
|
| 127 |
+
prefix_token="▁<PRE>",
|
| 128 |
+
middle_token="▁<MID>",
|
| 129 |
+
suffix_token="▁<SUF>",
|
| 130 |
+
eot_token="▁<EOT>",
|
| 131 |
+
fill_token="<FILL_ME>",
|
| 132 |
+
additional_special_tokens=None,
|
| 133 |
+
add_bos_token=True,
|
| 134 |
+
add_eos_token=False,
|
| 135 |
+
use_default_system_prompt=False,
|
| 136 |
+
**kwargs,
|
| 137 |
+
):
|
| 138 |
+
# mark tokens special to skip them
|
| 139 |
+
additional_special_tokens = additional_special_tokens or []
|
| 140 |
+
for token in [prefix_token, middle_token, suffix_token, eot_token]:
|
| 141 |
+
additional_special_tokens += [token] if token is not None else []
|
| 142 |
+
self.use_default_system_prompt = use_default_system_prompt
|
| 143 |
+
|
| 144 |
+
super().__init__(
|
| 145 |
+
vocab_file=vocab_file,
|
| 146 |
+
tokenizer_file=tokenizer_file,
|
| 147 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
| 148 |
+
additional_special_tokens=additional_special_tokens,
|
| 149 |
+
unk_token=unk_token,
|
| 150 |
+
bos_token=bos_token,
|
| 151 |
+
eos_token=eos_token,
|
| 152 |
+
add_bos_token=add_bos_token,
|
| 153 |
+
add_eos_token=add_eos_token,
|
| 154 |
+
prefix_token=prefix_token,
|
| 155 |
+
middle_token=middle_token,
|
| 156 |
+
suffix_token=suffix_token,
|
| 157 |
+
eot_token=eot_token,
|
| 158 |
+
fill_token=fill_token,
|
| 159 |
+
use_default_system_prompt=use_default_system_prompt,
|
| 160 |
+
**kwargs,
|
| 161 |
+
)
|
| 162 |
+
self._add_bos_token = add_bos_token
|
| 163 |
+
self._add_eos_token = add_eos_token
|
| 164 |
+
self.update_post_processor()
|
| 165 |
+
|
| 166 |
+
self.vocab_file = vocab_file
|
| 167 |
+
|
| 168 |
+
self._prefix_token = prefix_token
|
| 169 |
+
self._middle_token = middle_token
|
| 170 |
+
self._suffix_token = suffix_token
|
| 171 |
+
self._eot_token = eot_token
|
| 172 |
+
self.fill_token = fill_token
|
| 173 |
+
|
| 174 |
+
@property
|
| 175 |
+
def can_save_slow_tokenizer(self) -> bool:
|
| 176 |
+
return os.path.isfile(self.vocab_file) if self.vocab_file else False
|
| 177 |
+
|
| 178 |
+
# Copied from transformers.models.llama.tokenization_llama_fast.LlamaTokenizerFast.update_post_processor
|
| 179 |
+
def update_post_processor(self):
|
| 180 |
+
"""
|
| 181 |
+
Updates the underlying post processor with the current `bos_token` and `eos_token`.
|
| 182 |
+
"""
|
| 183 |
+
bos = self.bos_token
|
| 184 |
+
bos_token_id = self.bos_token_id
|
| 185 |
+
if bos is None and self.add_bos_token:
|
| 186 |
+
raise ValueError("add_bos_token = True but bos_token = None")
|
| 187 |
+
|
| 188 |
+
eos = self.eos_token
|
| 189 |
+
eos_token_id = self.eos_token_id
|
| 190 |
+
if eos is None and self.add_eos_token:
|
| 191 |
+
raise ValueError("add_eos_token = True but eos_token = None")
|
| 192 |
+
|
| 193 |
+
single = f"{(bos + ':0 ') if self.add_bos_token else ''}$A:0{(' ' + eos + ':0') if self.add_eos_token else ''}"
|
| 194 |
+
pair = f"{single}{(' ' + bos + ':1') if self.add_bos_token else ''} $B:1{(' ' + eos + ':1') if self.add_eos_token else ''}"
|
| 195 |
+
|
| 196 |
+
special_tokens = []
|
| 197 |
+
if self.add_bos_token:
|
| 198 |
+
special_tokens.append((bos, bos_token_id))
|
| 199 |
+
if self.add_eos_token:
|
| 200 |
+
special_tokens.append((eos, eos_token_id))
|
| 201 |
+
self._tokenizer.post_processor = processors.TemplateProcessing(
|
| 202 |
+
single=single, pair=pair, special_tokens=special_tokens
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
@property
|
| 206 |
+
def prefix_token(self):
|
| 207 |
+
return self._prefix_token
|
| 208 |
+
|
| 209 |
+
@property
|
| 210 |
+
def prefix_id(self):
|
| 211 |
+
if self._prefix_token is None:
|
| 212 |
+
return None
|
| 213 |
+
return self.convert_tokens_to_ids(self.prefix_token)
|
| 214 |
+
|
| 215 |
+
@property
|
| 216 |
+
def middle_token(self):
|
| 217 |
+
return self._middle_token
|
| 218 |
+
|
| 219 |
+
@property
|
| 220 |
+
def middle_id(self):
|
| 221 |
+
if self._middle_token is None:
|
| 222 |
+
return None
|
| 223 |
+
return self.convert_tokens_to_ids(self.middle_token)
|
| 224 |
+
|
| 225 |
+
@property
|
| 226 |
+
def suffix_token(self):
|
| 227 |
+
return self._suffix_token
|
| 228 |
+
|
| 229 |
+
@property
|
| 230 |
+
def suffix_id(self):
|
| 231 |
+
if self._suffix_token is None:
|
| 232 |
+
return None
|
| 233 |
+
return self.convert_tokens_to_ids(self.suffix_token)
|
| 234 |
+
|
| 235 |
+
@property
|
| 236 |
+
def eot_id(self):
|
| 237 |
+
if self._eot_token is None:
|
| 238 |
+
return None
|
| 239 |
+
return self.convert_tokens_to_ids(self.eot_token)
|
| 240 |
+
|
| 241 |
+
@property
|
| 242 |
+
def eot_token(self):
|
| 243 |
+
return self._eot_token
|
| 244 |
+
|
| 245 |
+
@property
|
| 246 |
+
def add_eos_token(self):
|
| 247 |
+
return self._add_eos_token
|
| 248 |
+
|
| 249 |
+
@property
|
| 250 |
+
def add_bos_token(self):
|
| 251 |
+
return self._add_bos_token
|
| 252 |
+
|
| 253 |
+
@add_eos_token.setter
|
| 254 |
+
def add_eos_token(self, value):
|
| 255 |
+
self._add_eos_token = value
|
| 256 |
+
self.update_post_processor()
|
| 257 |
+
|
| 258 |
+
@add_bos_token.setter
|
| 259 |
+
def add_bos_token(self, value):
|
| 260 |
+
self._add_bos_token = value
|
| 261 |
+
self.update_post_processor()
|
| 262 |
+
|
| 263 |
+
def set_infilling_processor(self, reset, suffix_first=False, add_special_tokens=True):
|
| 264 |
+
"""
|
| 265 |
+
Updates the normalizer to make sure the prompt format for `infilling` is respected. The infilling format is the
|
| 266 |
+
following: if suffix_first
|
| 267 |
+
" <PRE> <SUF>{suf} <MID> {pre}"
|
| 268 |
+
else:
|
| 269 |
+
" <PRE> {pre} <SUF>{suf} <MID>"
|
| 270 |
+
|
| 271 |
+
If `reset` is set to `True`, the `normalizer` and `post_processor` are reset to their "normal" behaviour, which
|
| 272 |
+
is to add a prefix space for the normalizer, and add a `bos_token` to the input text for the `post_processor`.
|
| 273 |
+
"""
|
| 274 |
+
if reset:
|
| 275 |
+
self._tokenizer.normalizer = normalizers.Sequence(
|
| 276 |
+
[
|
| 277 |
+
normalizers.Prepend(prepend="▁"),
|
| 278 |
+
normalizers.Replace(pattern=" ", content="▁"),
|
| 279 |
+
]
|
| 280 |
+
)
|
| 281 |
+
self.update_post_processor()
|
| 282 |
+
return
|
| 283 |
+
|
| 284 |
+
self._tokenizer.normalizer = normalizers.Replace(pattern=" ", content="▁")
|
| 285 |
+
pair = [self.bos_token] if self.add_bos_token and add_special_tokens else []
|
| 286 |
+
special_tokens = [(self.bos_token, self.bos_token_id)] if self.add_bos_token and add_special_tokens else []
|
| 287 |
+
if suffix_first:
|
| 288 |
+
# format as " <PRE> <SUF>{suf} <MID> {pre}"
|
| 289 |
+
pair += [self.prefix_token, self.suffix_token, "$B", self.middle_token, "$A"]
|
| 290 |
+
special_tokens += [
|
| 291 |
+
(self.prefix_token, self.prefix_id),
|
| 292 |
+
(self.suffix_token, self.suffix_id),
|
| 293 |
+
(self.middle_token, self.middle_id),
|
| 294 |
+
]
|
| 295 |
+
else:
|
| 296 |
+
# format as " <PRE> {pre} <SUF>{suf} <MID>"
|
| 297 |
+
pair += [self.prefix_token, "$A", self.suffix_token, "$B", self.middle_token]
|
| 298 |
+
special_tokens += [
|
| 299 |
+
(self.prefix_token, self.prefix_id),
|
| 300 |
+
(self.suffix_token, self.suffix_id),
|
| 301 |
+
(self.middle_token, self.middle_id),
|
| 302 |
+
]
|
| 303 |
+
|
| 304 |
+
if self.add_eos_token and add_special_tokens:
|
| 305 |
+
pair += [self.eos_token]
|
| 306 |
+
special_tokens += [(self.eos_token, self.eos_token_id)]
|
| 307 |
+
self._tokenizer.post_processor = processors.TemplateProcessing(
|
| 308 |
+
single="$A", pair=pair, special_tokens=special_tokens
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
def encode_plus(self, text, text_pair=None, suffix_first=False, add_special_tokens=True, **kwargs):
|
| 312 |
+
# hack to make sure the input is pre-process but outside rust
|
| 313 |
+
text_pair = kwargs.pop("suffix", text_pair)
|
| 314 |
+
if self.fill_token is not None and self.fill_token in text and text_pair is None:
|
| 315 |
+
text, text_pair = text.split(self.fill_token)
|
| 316 |
+
|
| 317 |
+
if text_pair is None or len(text_pair) < 1:
|
| 318 |
+
return super().encode_plus(text, text_pair, add_special_tokens=add_special_tokens, **kwargs)
|
| 319 |
+
|
| 320 |
+
if None in (self.prefix_id, self.middle_id, self.suffix_id):
|
| 321 |
+
raise ValueError(
|
| 322 |
+
"Then input includes a `prefix` and a `suffix` used for the infilling task,"
|
| 323 |
+
" the `prefix_id, middle_id, suffix_id` must all be initialized. Current"
|
| 324 |
+
f" values : {self.prefix_id, self.middle_id, self.suffix_id}"
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
self.set_infilling_processor(False, suffix_first=suffix_first, add_special_tokens=add_special_tokens)
|
| 328 |
+
tokens = super().encode_plus(" " + text, text_pair=text_pair, add_special_tokens=True, **kwargs)
|
| 329 |
+
self.set_infilling_processor(True)
|
| 330 |
+
return tokens
|
| 331 |
+
|
| 332 |
+
# Copied from transformers.models.llama.tokenization_llama_fast.LlamaTokenizerFast.save_vocabulary
|
| 333 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 334 |
+
if not self.can_save_slow_tokenizer:
|
| 335 |
+
raise ValueError(
|
| 336 |
+
"Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
|
| 337 |
+
"tokenizer."
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
if not os.path.isdir(save_directory):
|
| 341 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 342 |
+
return
|
| 343 |
+
out_vocab_file = os.path.join(
|
| 344 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
|
| 348 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 349 |
+
|
| 350 |
+
return (out_vocab_file,)
|
| 351 |
+
|
| 352 |
+
def build_inputs_with_special_tokens(
|
| 353 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 354 |
+
) -> List[int]:
|
| 355 |
+
"""
|
| 356 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 357 |
+
adding special tokens. The special tokens depend on calling set_lang.
|
| 358 |
+
|
| 359 |
+
An NLLB sequence has the following format, where `X` represents the sequence:
|
| 360 |
+
|
| 361 |
+
- `input_ids` (for encoder) `X [eos, src_lang_code]`
|
| 362 |
+
- `decoder_input_ids`: (for decoder) `X [eos, tgt_lang_code]`
|
| 363 |
+
|
| 364 |
+
BOS is never used. Pairs of sequences are not the expected use case, but they will be handled without a
|
| 365 |
+
separator.
|
| 366 |
+
|
| 367 |
+
Args:
|
| 368 |
+
token_ids_0 (`List[int]`):
|
| 369 |
+
List of IDs to which the special tokens will be added.
|
| 370 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 371 |
+
Optional second list of IDs for sequence pairs.
|
| 372 |
+
|
| 373 |
+
Returns:
|
| 374 |
+
`List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 375 |
+
"""
|
| 376 |
+
if token_ids_1 is None:
|
| 377 |
+
return self.bos_token_id + token_ids_0 + self.eos_token_id
|
| 378 |
+
return self.bos_token_id + token_ids_0 + token_ids_1 + self.eos_token_id
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
__all__ = ["CodeLlamaTokenizerFast"]
|
lib/python3.12/site-packages/transformers/models/dbrx/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_dbrx import *
|
| 22 |
+
from .modeling_dbrx import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.12/site-packages/transformers/models/dbrx/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (661 Bytes). View file
|
|
|
lib/python3.12/site-packages/transformers/models/dbrx/__pycache__/configuration_dbrx.cpython-312.pyc
ADDED
|
Binary file (10.2 kB). View file
|
|
|