Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step20/zero/8.mlp.dense_4h_to_h.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step20/zero/9.attention.dense.weight/exp_avg_sq.pt +3 -0
- lm-evaluation-harness/wandb/run-20240522_184928-kt8p2r8k/files/config.yaml +43 -0
- lm-evaluation-harness/wandb/run-20240522_184928-kt8p2r8k/files/output.log +34 -0
- lm-evaluation-harness/wandb/run-20240522_184928-kt8p2r8k/files/requirements.txt +155 -0
- lm-evaluation-harness/wandb/run-20240522_184928-kt8p2r8k/files/wandb-metadata.json +850 -0
- lm-evaluation-harness/wandb/run-20240522_184928-kt8p2r8k/files/wandb-summary.json +1 -0
- lm-evaluation-harness/wandb/run-20240522_184928-kt8p2r8k/run-kt8p2r8k.wandb +0 -0
- lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/files/config.yaml +284 -0
- lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/files/media/table/evaluation/eval_results_1_9c87687b44ab0685fb7b.table.json +1 -0
- lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/files/output.log +592 -0
- lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/files/requirements.txt +153 -0
- lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/files/wandb-metadata.json +850 -0
- lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/files/wandb-summary.json +1 -0
- lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/logs/debug-internal.log +0 -0
- lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/logs/debug.log +36 -0
- lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/run-wg4623zd.wandb +0 -0
- venv/lib/python3.10/site-packages/transformers/models/align/__init__.py +73 -0
- venv/lib/python3.10/site-packages/transformers/models/align/convert_align_tf_to_hf.py +389 -0
- venv/lib/python3.10/site-packages/transformers/models/bridgetower/__init__.py +89 -0
- venv/lib/python3.10/site-packages/transformers/models/bridgetower/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/bridgetower/__pycache__/configuration_bridgetower.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/bridgetower/__pycache__/image_processing_bridgetower.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/bridgetower/__pycache__/modeling_bridgetower.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/bridgetower/__pycache__/processing_bridgetower.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/bridgetower/configuration_bridgetower.py +349 -0
- venv/lib/python3.10/site-packages/transformers/models/bridgetower/image_processing_bridgetower.py +561 -0
- venv/lib/python3.10/site-packages/transformers/models/bridgetower/modeling_bridgetower.py +1898 -0
- venv/lib/python3.10/site-packages/transformers/models/bridgetower/processing_bridgetower.py +119 -0
- venv/lib/python3.10/site-packages/transformers/models/conditional_detr/__init__.py +85 -0
- venv/lib/python3.10/site-packages/transformers/models/conditional_detr/modeling_conditional_detr.py +0 -0
- venv/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/__init__.py +62 -0
- venv/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/__pycache__/configuration_gpt_neox_japanese.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/__pycache__/modeling_gpt_neox_japanese.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/__pycache__/tokenization_gpt_neox_japanese.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/configuration_gpt_neox_japanese.py +120 -0
- venv/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/modeling_gpt_neox_japanese.py +729 -0
- venv/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/tokenization_gpt_neox_japanese.py +368 -0
- venv/lib/python3.10/site-packages/transformers/models/qwen2/__init__.py +80 -0
- venv/lib/python3.10/site-packages/transformers/models/qwen2/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/qwen2/__pycache__/configuration_qwen2.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/qwen2/__pycache__/modeling_qwen2.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/qwen2/__pycache__/tokenization_qwen2.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/qwen2/__pycache__/tokenization_qwen2_fast.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/qwen2/configuration_qwen2.py +143 -0
- venv/lib/python3.10/site-packages/transformers/models/qwen2/modeling_qwen2.py +1397 -0
- venv/lib/python3.10/site-packages/transformers/models/qwen2/tokenization_qwen2.py +339 -0
- venv/lib/python3.10/site-packages/transformers/models/qwen2/tokenization_qwen2_fast.py +134 -0
- venv/lib/python3.10/site-packages/transformers/models/rwkv/__init__.py +60 -0
ckpts/universal/global_step20/zero/8.mlp.dense_4h_to_h.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8fbeb14f061a13d56478cbd35cc6559ba3db71af4a967cccb7c57836a8c7bfb4
|
3 |
+
size 33555627
|
ckpts/universal/global_step20/zero/9.attention.dense.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:fe8bc781cef30250dca4fd0478bd1dbd45684da0731128585fefda573e190cc1
|
3 |
+
size 16778411
|
lm-evaluation-harness/wandb/run-20240522_184928-kt8p2r8k/files/config.yaml
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
wandb_version: 1
|
2 |
+
|
3 |
+
_wandb:
|
4 |
+
desc: null
|
5 |
+
value:
|
6 |
+
python_version: 3.10.12
|
7 |
+
cli_version: 0.17.0
|
8 |
+
framework: huggingface
|
9 |
+
huggingface_version: 4.41.0
|
10 |
+
is_jupyter_run: false
|
11 |
+
is_kaggle_kernel: false
|
12 |
+
start_time: 1716403768
|
13 |
+
t:
|
14 |
+
1:
|
15 |
+
- 1
|
16 |
+
- 5
|
17 |
+
- 11
|
18 |
+
- 49
|
19 |
+
- 51
|
20 |
+
- 53
|
21 |
+
- 55
|
22 |
+
- 71
|
23 |
+
- 98
|
24 |
+
- 100
|
25 |
+
2:
|
26 |
+
- 1
|
27 |
+
- 5
|
28 |
+
- 11
|
29 |
+
- 49
|
30 |
+
- 51
|
31 |
+
- 53
|
32 |
+
- 55
|
33 |
+
- 71
|
34 |
+
- 98
|
35 |
+
- 100
|
36 |
+
3:
|
37 |
+
- 23
|
38 |
+
4: 3.10.12
|
39 |
+
5: 0.17.0
|
40 |
+
6: 4.41.0
|
41 |
+
8:
|
42 |
+
- 5
|
43 |
+
13: linux-x86_64
|
lm-evaluation-harness/wandb/run-20240522_184928-kt8p2r8k/files/output.log
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
2024-05-22:18:49:28,921 INFO [__main__.py:251] Verbosity set to INFO
|
3 |
+
2024-05-22:18:49:37,334 INFO [__main__.py:335] Selected Tasks: ['arc_easy', 'hellaswag', 'mrpc', 'openbookqa', 'sst2', 'winogrande']
|
4 |
+
2024-05-22:18:49:37,335 INFO [evaluator.py:131] Setting random seed to 0 | Setting numpy seed to 1234 | Setting torch manual seed to 1234
|
5 |
+
2024-05-22:18:49:37,335 INFO [evaluator.py:177] Initializing hf model, with arguments: {'pretrained': '/mnt/weka/peacock/experiments/llama/checkpoint/llamav2-3b//hf_ckpt//global_step14000'}
|
6 |
+
2024-05-22:18:49:39,753 INFO [huggingface.py:164] Using device 'cuda'
|
7 |
+
Traceback (most recent call last):
|
8 |
+
File "/usr/lib/python3.10/runpy.py", line 196, in _run_module_as_main
|
9 |
+
return _run_code(code, main_globals, None,
|
10 |
+
File "/usr/lib/python3.10/runpy.py", line 86, in _run_code
|
11 |
+
exec(code, run_globals)
|
12 |
+
File "/mnt/weka/peacock/idc/cronscript/lm-evaluation-harness/lm_eval/__main__.py", line 417, in <module>
|
13 |
+
cli_evaluate()
|
14 |
+
File "/mnt/weka/peacock/idc/cronscript/lm-evaluation-harness/lm_eval/__main__.py", line 341, in cli_evaluate
|
15 |
+
results = evaluator.simple_evaluate(
|
16 |
+
File "/mnt/weka/peacock/idc/cronscript/lm-evaluation-harness/lm_eval/utils.py", line 288, in _wrapper
|
17 |
+
return fn(*args, **kwargs)
|
18 |
+
File "/mnt/weka/peacock/idc/cronscript/lm-evaluation-harness/lm_eval/evaluator.py", line 180, in simple_evaluate
|
19 |
+
lm = lm_eval.api.registry.get_model(model).create_from_arg_string(
|
20 |
+
File "/mnt/weka/peacock/idc/cronscript/lm-evaluation-harness/lm_eval/api/model.py", line 134, in create_from_arg_string
|
21 |
+
return cls(**args, **args2)
|
22 |
+
File "/mnt/weka/peacock/idc/cronscript/lm-evaluation-harness/lm_eval/models/huggingface.py", line 190, in __init__
|
23 |
+
self._get_config(
|
24 |
+
File "/mnt/weka/peacock/idc/cronscript/lm-evaluation-harness/lm_eval/models/huggingface.py", line 471, in _get_config
|
25 |
+
self._config = transformers.AutoConfig.from_pretrained(
|
26 |
+
File "/usr/local/lib/python3.10/dist-packages/transformers/models/auto/configuration_auto.py", line 934, in from_pretrained
|
27 |
+
config_dict, unused_kwargs = PretrainedConfig.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
28 |
+
File "/usr/local/lib/python3.10/dist-packages/transformers/configuration_utils.py", line 632, in get_config_dict
|
29 |
+
config_dict, kwargs = cls._get_config_dict(pretrained_model_name_or_path, **kwargs)
|
30 |
+
File "/usr/local/lib/python3.10/dist-packages/transformers/configuration_utils.py", line 689, in _get_config_dict
|
31 |
+
resolved_config_file = cached_file(
|
32 |
+
File "/usr/local/lib/python3.10/dist-packages/transformers/utils/hub.py", line 370, in cached_file
|
33 |
+
raise EnvironmentError(
|
34 |
+
OSError: /mnt/weka/peacock/experiments/llama/checkpoint/llamav2-3b//hf_ckpt//global_step14000 does not appear to have a file named config.json. Checkout 'https://huggingface.co//mnt/weka/peacock/experiments/llama/checkpoint/llamav2-3b//hf_ckpt//global_step14000/tree/main' for available files.
|
lm-evaluation-harness/wandb/run-20240522_184928-kt8p2r8k/files/requirements.txt
ADDED
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
DataProperty==1.0.1
|
2 |
+
GitPython==3.1.43
|
3 |
+
Jinja2==3.1.4
|
4 |
+
Markdown==3.6
|
5 |
+
MarkupSafe==2.1.5
|
6 |
+
Pillow-SIMD==7.0.0.post3
|
7 |
+
PyYAML==6.0
|
8 |
+
Werkzeug==3.0.3
|
9 |
+
absl-py==2.1.0
|
10 |
+
accelerate==0.30.1
|
11 |
+
aiohttp==3.9.5
|
12 |
+
aiosignal==1.3.1
|
13 |
+
async-timeout==4.0.3
|
14 |
+
attrs==23.2.0
|
15 |
+
av==9.2.0
|
16 |
+
cachetools==5.3.3
|
17 |
+
certifi==2024.2.2
|
18 |
+
cffi==1.15.1
|
19 |
+
cfgv==3.4.0
|
20 |
+
chardet==5.2.0
|
21 |
+
charset-normalizer==3.3.2
|
22 |
+
click==8.1.7
|
23 |
+
cmake==3.29.2
|
24 |
+
colorama==0.4.6
|
25 |
+
datasets==2.19.1
|
26 |
+
deepspeed==0.12.4+hpu.synapse.v1.15.1
|
27 |
+
dill==0.3.8
|
28 |
+
distlib==0.3.8
|
29 |
+
docker-pycreds==0.4.0
|
30 |
+
einops==0.8.0
|
31 |
+
evaluate==0.4.2
|
32 |
+
exceptiongroup==1.2.1
|
33 |
+
expecttest==0.2.1
|
34 |
+
filelock==3.14.0
|
35 |
+
frozenlist==1.4.1
|
36 |
+
fsspec==2024.3.1
|
37 |
+
gitdb==4.0.11
|
38 |
+
google-auth-oauthlib==0.4.6
|
39 |
+
google-auth==2.29.0
|
40 |
+
grpcio==1.63.0
|
41 |
+
habana-media-loader==1.15.1.15
|
42 |
+
habana-pyhlml==1.15.1.15
|
43 |
+
habana-torch-dataloader==1.15.1.15
|
44 |
+
habana-torch-plugin==1.15.1.15
|
45 |
+
habana_gpu_migration==1.15.1.15
|
46 |
+
habana_quantization_toolkit==1.15.1.15
|
47 |
+
hjson==3.1.0
|
48 |
+
huggingface-hub==0.23.1
|
49 |
+
identify==2.5.36
|
50 |
+
idna==3.7
|
51 |
+
iniconfig==2.0.0
|
52 |
+
joblib==1.4.2
|
53 |
+
jsonlines==4.0.0
|
54 |
+
lightning-habana==1.4.0
|
55 |
+
lightning-utilities==0.11.2
|
56 |
+
lightning==2.2.0.post0
|
57 |
+
lm_eval==0.4.2
|
58 |
+
lm_eval==0.4.2
|
59 |
+
lm_eval==0.4.2
|
60 |
+
lxml==5.2.2
|
61 |
+
mbstrdecoder==1.1.3
|
62 |
+
more-itertools==10.2.0
|
63 |
+
mpi4py==3.1.4
|
64 |
+
mpmath==1.3.0
|
65 |
+
multidict==6.0.5
|
66 |
+
multiprocess==0.70.16
|
67 |
+
networkx==3.3
|
68 |
+
ninja==1.11.1.1
|
69 |
+
nltk==3.8.1
|
70 |
+
nodeenv==1.8.0
|
71 |
+
numexpr==2.10.0
|
72 |
+
numpy==1.23.5
|
73 |
+
oauthlib==3.2.2
|
74 |
+
packaging==24.0
|
75 |
+
pandas==2.0.1
|
76 |
+
pathspec==0.12.1
|
77 |
+
pathvalidate==3.2.0
|
78 |
+
peft==0.11.1
|
79 |
+
perfetto==0.7.0
|
80 |
+
pillow==10.3.0
|
81 |
+
pip==22.0.2
|
82 |
+
pip==23.3.1
|
83 |
+
platformdirs==4.2.1
|
84 |
+
pluggy==1.5.0
|
85 |
+
portalocker==2.8.2
|
86 |
+
pre-commit==3.3.3
|
87 |
+
pretty-errors==1.2.25
|
88 |
+
protobuf==3.20.3
|
89 |
+
psutil==5.9.8
|
90 |
+
py-cpuinfo==9.0.0
|
91 |
+
pyarrow-hotfix==0.6
|
92 |
+
pyarrow==16.1.0
|
93 |
+
pyasn1==0.6.0
|
94 |
+
pyasn1_modules==0.4.0
|
95 |
+
pybind11==2.10.4
|
96 |
+
pycparser==2.22
|
97 |
+
pydantic==1.10.13
|
98 |
+
pynvml==8.0.4
|
99 |
+
pytablewriter==1.2.0
|
100 |
+
pytest==8.2.0
|
101 |
+
python-dateutil==2.9.0.post0
|
102 |
+
pytorch-lightning==2.2.4
|
103 |
+
pytz==2024.1
|
104 |
+
regex==2023.5.5
|
105 |
+
requests-oauthlib==2.0.0
|
106 |
+
requests==2.31.0
|
107 |
+
rouge_score==0.1.2
|
108 |
+
rsa==4.9
|
109 |
+
sacrebleu==2.4.2
|
110 |
+
safetensors==0.4.3
|
111 |
+
scikit-learn==1.5.0
|
112 |
+
scipy==1.13.0
|
113 |
+
sentencepiece==0.2.0
|
114 |
+
sentry-sdk==2.2.1
|
115 |
+
setproctitle==1.3.3
|
116 |
+
setuptools==59.6.0
|
117 |
+
setuptools==69.5.1
|
118 |
+
six==1.16.0
|
119 |
+
smmap==5.0.1
|
120 |
+
sqlitedict==2.1.0
|
121 |
+
symengine==0.11.0
|
122 |
+
sympy==1.12
|
123 |
+
tabledata==1.3.3
|
124 |
+
tabulate==0.9.0
|
125 |
+
tcolorpy==0.1.6
|
126 |
+
tdqm==0.0.1
|
127 |
+
tensorboard-data-server==0.6.1
|
128 |
+
tensorboard-plugin-wit==1.8.1
|
129 |
+
tensorboard==2.11.2
|
130 |
+
threadpoolctl==3.5.0
|
131 |
+
tokenizers==0.19.1
|
132 |
+
tomli==2.0.1
|
133 |
+
torch==2.2.0a0+git8964477
|
134 |
+
torch_tb_profiler==0.4.0
|
135 |
+
torchaudio==2.2.0+08901ad
|
136 |
+
torchdata==0.7.1+5e6f7b7
|
137 |
+
torchmetrics==1.4.0
|
138 |
+
torchtext==0.17.0+400da5c
|
139 |
+
torchvision==0.17.0+b2383d4
|
140 |
+
tqdm-multiprocess==0.0.11
|
141 |
+
tqdm==4.66.4
|
142 |
+
transformers==4.41.0
|
143 |
+
typepy==1.3.2
|
144 |
+
typing_extensions==4.11.0
|
145 |
+
tzdata==2024.1
|
146 |
+
urllib3==1.26.18
|
147 |
+
virtualenv==20.26.1
|
148 |
+
wandb==0.17.0
|
149 |
+
wheel==0.37.1
|
150 |
+
wheel==0.43.0
|
151 |
+
word2number==1.1
|
152 |
+
xxhash==3.4.1
|
153 |
+
yamllint==1.35.1
|
154 |
+
yarl==1.9.4
|
155 |
+
zstandard==0.22.0
|
lm-evaluation-harness/wandb/run-20240522_184928-kt8p2r8k/files/wandb-metadata.json
ADDED
@@ -0,0 +1,850 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"os": "Linux-5.15.0-92-generic-x86_64-with-glibc2.35",
|
3 |
+
"python": "3.10.12",
|
4 |
+
"heartbeatAt": "2024-05-22T18:49:28.717571",
|
5 |
+
"startedAt": "2024-05-22T18:49:28.186831",
|
6 |
+
"docker": null,
|
7 |
+
"cuda": null,
|
8 |
+
"args": [
|
9 |
+
"--model",
|
10 |
+
"hf",
|
11 |
+
"--model_args",
|
12 |
+
"pretrained=/mnt/weka/peacock/experiments/llama/checkpoint/llamav2-3b//hf_ckpt//global_step14000",
|
13 |
+
"--tasks",
|
14 |
+
"hellaswag,arc_easy,openbookqa,winogrande,sst2,mrpc",
|
15 |
+
"--batch_size",
|
16 |
+
"auto",
|
17 |
+
"--wandb_args",
|
18 |
+
"project=bharatgpt,group=trial_expt_2"
|
19 |
+
],
|
20 |
+
"state": "running",
|
21 |
+
"program": "-m lm_eval.__main__",
|
22 |
+
"codePathLocal": null,
|
23 |
+
"git": {
|
24 |
+
"remote": "https://github.com/EleutherAI/lm-evaluation-harness",
|
25 |
+
"commit": null
|
26 |
+
},
|
27 |
+
"email": null,
|
28 |
+
"root": "/mnt/weka/peacock/idc/cronscript/lm-evaluation-harness",
|
29 |
+
"host": "peacock-evaluation-worker-0",
|
30 |
+
"username": "root",
|
31 |
+
"executable": "/usr/bin/python3",
|
32 |
+
"cpu_count": 80,
|
33 |
+
"cpu_count_logical": 160,
|
34 |
+
"cpu_freq": {
|
35 |
+
"current": 2327.1428562499996,
|
36 |
+
"min": 800.0,
|
37 |
+
"max": 3400.0
|
38 |
+
},
|
39 |
+
"cpu_freq_per_core": [
|
40 |
+
{
|
41 |
+
"current": 3400.0,
|
42 |
+
"min": 800.0,
|
43 |
+
"max": 3400.0
|
44 |
+
},
|
45 |
+
{
|
46 |
+
"current": 3400.0,
|
47 |
+
"min": 800.0,
|
48 |
+
"max": 3400.0
|
49 |
+
},
|
50 |
+
{
|
51 |
+
"current": 2300.0,
|
52 |
+
"min": 800.0,
|
53 |
+
"max": 3400.0
|
54 |
+
},
|
55 |
+
{
|
56 |
+
"current": 2300.0,
|
57 |
+
"min": 800.0,
|
58 |
+
"max": 3400.0
|
59 |
+
},
|
60 |
+
{
|
61 |
+
"current": 2300.0,
|
62 |
+
"min": 800.0,
|
63 |
+
"max": 3400.0
|
64 |
+
},
|
65 |
+
{
|
66 |
+
"current": 2300.0,
|
67 |
+
"min": 800.0,
|
68 |
+
"max": 3400.0
|
69 |
+
},
|
70 |
+
{
|
71 |
+
"current": 2300.0,
|
72 |
+
"min": 800.0,
|
73 |
+
"max": 3400.0
|
74 |
+
},
|
75 |
+
{
|
76 |
+
"current": 2300.0,
|
77 |
+
"min": 800.0,
|
78 |
+
"max": 3400.0
|
79 |
+
},
|
80 |
+
{
|
81 |
+
"current": 2300.0,
|
82 |
+
"min": 800.0,
|
83 |
+
"max": 3400.0
|
84 |
+
},
|
85 |
+
{
|
86 |
+
"current": 2300.0,
|
87 |
+
"min": 800.0,
|
88 |
+
"max": 3400.0
|
89 |
+
},
|
90 |
+
{
|
91 |
+
"current": 2300.0,
|
92 |
+
"min": 800.0,
|
93 |
+
"max": 3400.0
|
94 |
+
},
|
95 |
+
{
|
96 |
+
"current": 2300.0,
|
97 |
+
"min": 800.0,
|
98 |
+
"max": 3400.0
|
99 |
+
},
|
100 |
+
{
|
101 |
+
"current": 2300.0,
|
102 |
+
"min": 800.0,
|
103 |
+
"max": 3400.0
|
104 |
+
},
|
105 |
+
{
|
106 |
+
"current": 2300.0,
|
107 |
+
"min": 800.0,
|
108 |
+
"max": 3400.0
|
109 |
+
},
|
110 |
+
{
|
111 |
+
"current": 2300.0,
|
112 |
+
"min": 800.0,
|
113 |
+
"max": 3400.0
|
114 |
+
},
|
115 |
+
{
|
116 |
+
"current": 2300.0,
|
117 |
+
"min": 800.0,
|
118 |
+
"max": 3400.0
|
119 |
+
},
|
120 |
+
{
|
121 |
+
"current": 2300.0,
|
122 |
+
"min": 800.0,
|
123 |
+
"max": 3400.0
|
124 |
+
},
|
125 |
+
{
|
126 |
+
"current": 2300.0,
|
127 |
+
"min": 800.0,
|
128 |
+
"max": 3400.0
|
129 |
+
},
|
130 |
+
{
|
131 |
+
"current": 2300.0,
|
132 |
+
"min": 800.0,
|
133 |
+
"max": 3400.0
|
134 |
+
},
|
135 |
+
{
|
136 |
+
"current": 2300.0,
|
137 |
+
"min": 800.0,
|
138 |
+
"max": 3400.0
|
139 |
+
},
|
140 |
+
{
|
141 |
+
"current": 2300.0,
|
142 |
+
"min": 800.0,
|
143 |
+
"max": 3400.0
|
144 |
+
},
|
145 |
+
{
|
146 |
+
"current": 2300.0,
|
147 |
+
"min": 800.0,
|
148 |
+
"max": 3400.0
|
149 |
+
},
|
150 |
+
{
|
151 |
+
"current": 2300.0,
|
152 |
+
"min": 800.0,
|
153 |
+
"max": 3400.0
|
154 |
+
},
|
155 |
+
{
|
156 |
+
"current": 2300.0,
|
157 |
+
"min": 800.0,
|
158 |
+
"max": 3400.0
|
159 |
+
},
|
160 |
+
{
|
161 |
+
"current": 2300.0,
|
162 |
+
"min": 800.0,
|
163 |
+
"max": 3400.0
|
164 |
+
},
|
165 |
+
{
|
166 |
+
"current": 2300.0,
|
167 |
+
"min": 800.0,
|
168 |
+
"max": 3400.0
|
169 |
+
},
|
170 |
+
{
|
171 |
+
"current": 2300.0,
|
172 |
+
"min": 800.0,
|
173 |
+
"max": 3400.0
|
174 |
+
},
|
175 |
+
{
|
176 |
+
"current": 2300.0,
|
177 |
+
"min": 800.0,
|
178 |
+
"max": 3400.0
|
179 |
+
},
|
180 |
+
{
|
181 |
+
"current": 2300.0,
|
182 |
+
"min": 800.0,
|
183 |
+
"max": 3400.0
|
184 |
+
},
|
185 |
+
{
|
186 |
+
"current": 2300.0,
|
187 |
+
"min": 800.0,
|
188 |
+
"max": 3400.0
|
189 |
+
},
|
190 |
+
{
|
191 |
+
"current": 2300.0,
|
192 |
+
"min": 800.0,
|
193 |
+
"max": 3400.0
|
194 |
+
},
|
195 |
+
{
|
196 |
+
"current": 2300.0,
|
197 |
+
"min": 800.0,
|
198 |
+
"max": 3400.0
|
199 |
+
},
|
200 |
+
{
|
201 |
+
"current": 2300.0,
|
202 |
+
"min": 800.0,
|
203 |
+
"max": 3400.0
|
204 |
+
},
|
205 |
+
{
|
206 |
+
"current": 2300.0,
|
207 |
+
"min": 800.0,
|
208 |
+
"max": 3400.0
|
209 |
+
},
|
210 |
+
{
|
211 |
+
"current": 2300.0,
|
212 |
+
"min": 800.0,
|
213 |
+
"max": 3400.0
|
214 |
+
},
|
215 |
+
{
|
216 |
+
"current": 2300.0,
|
217 |
+
"min": 800.0,
|
218 |
+
"max": 3400.0
|
219 |
+
},
|
220 |
+
{
|
221 |
+
"current": 2300.0,
|
222 |
+
"min": 800.0,
|
223 |
+
"max": 3400.0
|
224 |
+
},
|
225 |
+
{
|
226 |
+
"current": 2300.0,
|
227 |
+
"min": 800.0,
|
228 |
+
"max": 3400.0
|
229 |
+
},
|
230 |
+
{
|
231 |
+
"current": 2300.0,
|
232 |
+
"min": 800.0,
|
233 |
+
"max": 3400.0
|
234 |
+
},
|
235 |
+
{
|
236 |
+
"current": 2300.0,
|
237 |
+
"min": 800.0,
|
238 |
+
"max": 3400.0
|
239 |
+
},
|
240 |
+
{
|
241 |
+
"current": 3400.0,
|
242 |
+
"min": 800.0,
|
243 |
+
"max": 3400.0
|
244 |
+
},
|
245 |
+
{
|
246 |
+
"current": 2300.0,
|
247 |
+
"min": 800.0,
|
248 |
+
"max": 3400.0
|
249 |
+
},
|
250 |
+
{
|
251 |
+
"current": 2300.0,
|
252 |
+
"min": 800.0,
|
253 |
+
"max": 3400.0
|
254 |
+
},
|
255 |
+
{
|
256 |
+
"current": 2300.0,
|
257 |
+
"min": 800.0,
|
258 |
+
"max": 3400.0
|
259 |
+
},
|
260 |
+
{
|
261 |
+
"current": 2300.0,
|
262 |
+
"min": 800.0,
|
263 |
+
"max": 3400.0
|
264 |
+
},
|
265 |
+
{
|
266 |
+
"current": 2300.0,
|
267 |
+
"min": 800.0,
|
268 |
+
"max": 3400.0
|
269 |
+
},
|
270 |
+
{
|
271 |
+
"current": 2300.0,
|
272 |
+
"min": 800.0,
|
273 |
+
"max": 3400.0
|
274 |
+
},
|
275 |
+
{
|
276 |
+
"current": 2300.0,
|
277 |
+
"min": 800.0,
|
278 |
+
"max": 3400.0
|
279 |
+
},
|
280 |
+
{
|
281 |
+
"current": 2300.0,
|
282 |
+
"min": 800.0,
|
283 |
+
"max": 3400.0
|
284 |
+
},
|
285 |
+
{
|
286 |
+
"current": 2300.0,
|
287 |
+
"min": 800.0,
|
288 |
+
"max": 3400.0
|
289 |
+
},
|
290 |
+
{
|
291 |
+
"current": 2300.0,
|
292 |
+
"min": 800.0,
|
293 |
+
"max": 3400.0
|
294 |
+
},
|
295 |
+
{
|
296 |
+
"current": 2300.0,
|
297 |
+
"min": 800.0,
|
298 |
+
"max": 3400.0
|
299 |
+
},
|
300 |
+
{
|
301 |
+
"current": 2300.0,
|
302 |
+
"min": 800.0,
|
303 |
+
"max": 3400.0
|
304 |
+
},
|
305 |
+
{
|
306 |
+
"current": 2300.0,
|
307 |
+
"min": 800.0,
|
308 |
+
"max": 3400.0
|
309 |
+
},
|
310 |
+
{
|
311 |
+
"current": 2300.0,
|
312 |
+
"min": 800.0,
|
313 |
+
"max": 3400.0
|
314 |
+
},
|
315 |
+
{
|
316 |
+
"current": 2300.0,
|
317 |
+
"min": 800.0,
|
318 |
+
"max": 3400.0
|
319 |
+
},
|
320 |
+
{
|
321 |
+
"current": 2300.0,
|
322 |
+
"min": 800.0,
|
323 |
+
"max": 3400.0
|
324 |
+
},
|
325 |
+
{
|
326 |
+
"current": 2300.0,
|
327 |
+
"min": 800.0,
|
328 |
+
"max": 3400.0
|
329 |
+
},
|
330 |
+
{
|
331 |
+
"current": 2300.0,
|
332 |
+
"min": 800.0,
|
333 |
+
"max": 3400.0
|
334 |
+
},
|
335 |
+
{
|
336 |
+
"current": 2300.0,
|
337 |
+
"min": 800.0,
|
338 |
+
"max": 3400.0
|
339 |
+
},
|
340 |
+
{
|
341 |
+
"current": 2300.0,
|
342 |
+
"min": 800.0,
|
343 |
+
"max": 3400.0
|
344 |
+
},
|
345 |
+
{
|
346 |
+
"current": 2300.0,
|
347 |
+
"min": 800.0,
|
348 |
+
"max": 3400.0
|
349 |
+
},
|
350 |
+
{
|
351 |
+
"current": 2300.0,
|
352 |
+
"min": 800.0,
|
353 |
+
"max": 3400.0
|
354 |
+
},
|
355 |
+
{
|
356 |
+
"current": 2300.0,
|
357 |
+
"min": 800.0,
|
358 |
+
"max": 3400.0
|
359 |
+
},
|
360 |
+
{
|
361 |
+
"current": 2300.0,
|
362 |
+
"min": 800.0,
|
363 |
+
"max": 3400.0
|
364 |
+
},
|
365 |
+
{
|
366 |
+
"current": 2300.0,
|
367 |
+
"min": 800.0,
|
368 |
+
"max": 3400.0
|
369 |
+
},
|
370 |
+
{
|
371 |
+
"current": 2300.0,
|
372 |
+
"min": 800.0,
|
373 |
+
"max": 3400.0
|
374 |
+
},
|
375 |
+
{
|
376 |
+
"current": 2300.0,
|
377 |
+
"min": 800.0,
|
378 |
+
"max": 3400.0
|
379 |
+
},
|
380 |
+
{
|
381 |
+
"current": 2300.0,
|
382 |
+
"min": 800.0,
|
383 |
+
"max": 3400.0
|
384 |
+
},
|
385 |
+
{
|
386 |
+
"current": 2300.0,
|
387 |
+
"min": 800.0,
|
388 |
+
"max": 3400.0
|
389 |
+
},
|
390 |
+
{
|
391 |
+
"current": 2300.0,
|
392 |
+
"min": 800.0,
|
393 |
+
"max": 3400.0
|
394 |
+
},
|
395 |
+
{
|
396 |
+
"current": 2300.0,
|
397 |
+
"min": 800.0,
|
398 |
+
"max": 3400.0
|
399 |
+
},
|
400 |
+
{
|
401 |
+
"current": 2300.0,
|
402 |
+
"min": 800.0,
|
403 |
+
"max": 3400.0
|
404 |
+
},
|
405 |
+
{
|
406 |
+
"current": 2300.0,
|
407 |
+
"min": 800.0,
|
408 |
+
"max": 3400.0
|
409 |
+
},
|
410 |
+
{
|
411 |
+
"current": 2300.0,
|
412 |
+
"min": 800.0,
|
413 |
+
"max": 3400.0
|
414 |
+
},
|
415 |
+
{
|
416 |
+
"current": 2300.0,
|
417 |
+
"min": 800.0,
|
418 |
+
"max": 3400.0
|
419 |
+
},
|
420 |
+
{
|
421 |
+
"current": 2300.0,
|
422 |
+
"min": 800.0,
|
423 |
+
"max": 3400.0
|
424 |
+
},
|
425 |
+
{
|
426 |
+
"current": 2300.0,
|
427 |
+
"min": 800.0,
|
428 |
+
"max": 3400.0
|
429 |
+
},
|
430 |
+
{
|
431 |
+
"current": 2300.0,
|
432 |
+
"min": 800.0,
|
433 |
+
"max": 3400.0
|
434 |
+
},
|
435 |
+
{
|
436 |
+
"current": 2300.0,
|
437 |
+
"min": 800.0,
|
438 |
+
"max": 3400.0
|
439 |
+
},
|
440 |
+
{
|
441 |
+
"current": 3400.0,
|
442 |
+
"min": 800.0,
|
443 |
+
"max": 3400.0
|
444 |
+
},
|
445 |
+
{
|
446 |
+
"current": 2300.0,
|
447 |
+
"min": 800.0,
|
448 |
+
"max": 3400.0
|
449 |
+
},
|
450 |
+
{
|
451 |
+
"current": 2300.0,
|
452 |
+
"min": 800.0,
|
453 |
+
"max": 3400.0
|
454 |
+
},
|
455 |
+
{
|
456 |
+
"current": 2300.0,
|
457 |
+
"min": 800.0,
|
458 |
+
"max": 3400.0
|
459 |
+
},
|
460 |
+
{
|
461 |
+
"current": 2300.0,
|
462 |
+
"min": 800.0,
|
463 |
+
"max": 3400.0
|
464 |
+
},
|
465 |
+
{
|
466 |
+
"current": 2300.0,
|
467 |
+
"min": 800.0,
|
468 |
+
"max": 3400.0
|
469 |
+
},
|
470 |
+
{
|
471 |
+
"current": 2300.0,
|
472 |
+
"min": 800.0,
|
473 |
+
"max": 3400.0
|
474 |
+
},
|
475 |
+
{
|
476 |
+
"current": 2300.0,
|
477 |
+
"min": 800.0,
|
478 |
+
"max": 3400.0
|
479 |
+
},
|
480 |
+
{
|
481 |
+
"current": 2300.0,
|
482 |
+
"min": 800.0,
|
483 |
+
"max": 3400.0
|
484 |
+
},
|
485 |
+
{
|
486 |
+
"current": 2300.0,
|
487 |
+
"min": 800.0,
|
488 |
+
"max": 3400.0
|
489 |
+
},
|
490 |
+
{
|
491 |
+
"current": 2300.0,
|
492 |
+
"min": 800.0,
|
493 |
+
"max": 3400.0
|
494 |
+
},
|
495 |
+
{
|
496 |
+
"current": 2300.0,
|
497 |
+
"min": 800.0,
|
498 |
+
"max": 3400.0
|
499 |
+
},
|
500 |
+
{
|
501 |
+
"current": 2300.0,
|
502 |
+
"min": 800.0,
|
503 |
+
"max": 3400.0
|
504 |
+
},
|
505 |
+
{
|
506 |
+
"current": 2300.0,
|
507 |
+
"min": 800.0,
|
508 |
+
"max": 3400.0
|
509 |
+
},
|
510 |
+
{
|
511 |
+
"current": 2300.0,
|
512 |
+
"min": 800.0,
|
513 |
+
"max": 3400.0
|
514 |
+
},
|
515 |
+
{
|
516 |
+
"current": 2300.0,
|
517 |
+
"min": 800.0,
|
518 |
+
"max": 3400.0
|
519 |
+
},
|
520 |
+
{
|
521 |
+
"current": 2300.0,
|
522 |
+
"min": 800.0,
|
523 |
+
"max": 3400.0
|
524 |
+
},
|
525 |
+
{
|
526 |
+
"current": 2300.0,
|
527 |
+
"min": 800.0,
|
528 |
+
"max": 3400.0
|
529 |
+
},
|
530 |
+
{
|
531 |
+
"current": 2300.0,
|
532 |
+
"min": 800.0,
|
533 |
+
"max": 3400.0
|
534 |
+
},
|
535 |
+
{
|
536 |
+
"current": 2300.0,
|
537 |
+
"min": 800.0,
|
538 |
+
"max": 3400.0
|
539 |
+
},
|
540 |
+
{
|
541 |
+
"current": 2300.0,
|
542 |
+
"min": 800.0,
|
543 |
+
"max": 3400.0
|
544 |
+
},
|
545 |
+
{
|
546 |
+
"current": 2300.0,
|
547 |
+
"min": 800.0,
|
548 |
+
"max": 3400.0
|
549 |
+
},
|
550 |
+
{
|
551 |
+
"current": 2300.0,
|
552 |
+
"min": 800.0,
|
553 |
+
"max": 3400.0
|
554 |
+
},
|
555 |
+
{
|
556 |
+
"current": 2300.0,
|
557 |
+
"min": 800.0,
|
558 |
+
"max": 3400.0
|
559 |
+
},
|
560 |
+
{
|
561 |
+
"current": 2300.0,
|
562 |
+
"min": 800.0,
|
563 |
+
"max": 3400.0
|
564 |
+
},
|
565 |
+
{
|
566 |
+
"current": 2300.0,
|
567 |
+
"min": 800.0,
|
568 |
+
"max": 3400.0
|
569 |
+
},
|
570 |
+
{
|
571 |
+
"current": 2300.0,
|
572 |
+
"min": 800.0,
|
573 |
+
"max": 3400.0
|
574 |
+
},
|
575 |
+
{
|
576 |
+
"current": 2300.0,
|
577 |
+
"min": 800.0,
|
578 |
+
"max": 3400.0
|
579 |
+
},
|
580 |
+
{
|
581 |
+
"current": 2300.0,
|
582 |
+
"min": 800.0,
|
583 |
+
"max": 3400.0
|
584 |
+
},
|
585 |
+
{
|
586 |
+
"current": 2300.0,
|
587 |
+
"min": 800.0,
|
588 |
+
"max": 3400.0
|
589 |
+
},
|
590 |
+
{
|
591 |
+
"current": 2300.0,
|
592 |
+
"min": 800.0,
|
593 |
+
"max": 3400.0
|
594 |
+
},
|
595 |
+
{
|
596 |
+
"current": 2300.0,
|
597 |
+
"min": 800.0,
|
598 |
+
"max": 3400.0
|
599 |
+
},
|
600 |
+
{
|
601 |
+
"current": 2300.0,
|
602 |
+
"min": 800.0,
|
603 |
+
"max": 3400.0
|
604 |
+
},
|
605 |
+
{
|
606 |
+
"current": 2300.0,
|
607 |
+
"min": 800.0,
|
608 |
+
"max": 3400.0
|
609 |
+
},
|
610 |
+
{
|
611 |
+
"current": 2300.0,
|
612 |
+
"min": 800.0,
|
613 |
+
"max": 3400.0
|
614 |
+
},
|
615 |
+
{
|
616 |
+
"current": 2300.0,
|
617 |
+
"min": 800.0,
|
618 |
+
"max": 3400.0
|
619 |
+
},
|
620 |
+
{
|
621 |
+
"current": 2300.0,
|
622 |
+
"min": 800.0,
|
623 |
+
"max": 3400.0
|
624 |
+
},
|
625 |
+
{
|
626 |
+
"current": 2300.0,
|
627 |
+
"min": 800.0,
|
628 |
+
"max": 3400.0
|
629 |
+
},
|
630 |
+
{
|
631 |
+
"current": 2300.0,
|
632 |
+
"min": 800.0,
|
633 |
+
"max": 3400.0
|
634 |
+
},
|
635 |
+
{
|
636 |
+
"current": 2300.0,
|
637 |
+
"min": 800.0,
|
638 |
+
"max": 3400.0
|
639 |
+
},
|
640 |
+
{
|
641 |
+
"current": 2300.0,
|
642 |
+
"min": 800.0,
|
643 |
+
"max": 3400.0
|
644 |
+
},
|
645 |
+
{
|
646 |
+
"current": 2300.0,
|
647 |
+
"min": 800.0,
|
648 |
+
"max": 3400.0
|
649 |
+
},
|
650 |
+
{
|
651 |
+
"current": 2300.0,
|
652 |
+
"min": 800.0,
|
653 |
+
"max": 3400.0
|
654 |
+
},
|
655 |
+
{
|
656 |
+
"current": 2300.0,
|
657 |
+
"min": 800.0,
|
658 |
+
"max": 3400.0
|
659 |
+
},
|
660 |
+
{
|
661 |
+
"current": 2300.0,
|
662 |
+
"min": 800.0,
|
663 |
+
"max": 3400.0
|
664 |
+
},
|
665 |
+
{
|
666 |
+
"current": 2300.0,
|
667 |
+
"min": 800.0,
|
668 |
+
"max": 3400.0
|
669 |
+
},
|
670 |
+
{
|
671 |
+
"current": 2300.0,
|
672 |
+
"min": 800.0,
|
673 |
+
"max": 3400.0
|
674 |
+
},
|
675 |
+
{
|
676 |
+
"current": 2300.0,
|
677 |
+
"min": 800.0,
|
678 |
+
"max": 3400.0
|
679 |
+
},
|
680 |
+
{
|
681 |
+
"current": 2300.0,
|
682 |
+
"min": 800.0,
|
683 |
+
"max": 3400.0
|
684 |
+
},
|
685 |
+
{
|
686 |
+
"current": 2300.0,
|
687 |
+
"min": 800.0,
|
688 |
+
"max": 3400.0
|
689 |
+
},
|
690 |
+
{
|
691 |
+
"current": 2300.0,
|
692 |
+
"min": 800.0,
|
693 |
+
"max": 3400.0
|
694 |
+
},
|
695 |
+
{
|
696 |
+
"current": 2300.0,
|
697 |
+
"min": 800.0,
|
698 |
+
"max": 3400.0
|
699 |
+
},
|
700 |
+
{
|
701 |
+
"current": 2300.0,
|
702 |
+
"min": 800.0,
|
703 |
+
"max": 3400.0
|
704 |
+
},
|
705 |
+
{
|
706 |
+
"current": 2300.0,
|
707 |
+
"min": 800.0,
|
708 |
+
"max": 3400.0
|
709 |
+
},
|
710 |
+
{
|
711 |
+
"current": 2300.0,
|
712 |
+
"min": 800.0,
|
713 |
+
"max": 3400.0
|
714 |
+
},
|
715 |
+
{
|
716 |
+
"current": 2300.0,
|
717 |
+
"min": 800.0,
|
718 |
+
"max": 3400.0
|
719 |
+
},
|
720 |
+
{
|
721 |
+
"current": 2300.0,
|
722 |
+
"min": 800.0,
|
723 |
+
"max": 3400.0
|
724 |
+
},
|
725 |
+
{
|
726 |
+
"current": 2300.0,
|
727 |
+
"min": 800.0,
|
728 |
+
"max": 3400.0
|
729 |
+
},
|
730 |
+
{
|
731 |
+
"current": 2300.0,
|
732 |
+
"min": 800.0,
|
733 |
+
"max": 3400.0
|
734 |
+
},
|
735 |
+
{
|
736 |
+
"current": 2300.0,
|
737 |
+
"min": 800.0,
|
738 |
+
"max": 3400.0
|
739 |
+
},
|
740 |
+
{
|
741 |
+
"current": 2300.0,
|
742 |
+
"min": 800.0,
|
743 |
+
"max": 3400.0
|
744 |
+
},
|
745 |
+
{
|
746 |
+
"current": 2300.0,
|
747 |
+
"min": 800.0,
|
748 |
+
"max": 3400.0
|
749 |
+
},
|
750 |
+
{
|
751 |
+
"current": 2300.0,
|
752 |
+
"min": 800.0,
|
753 |
+
"max": 3400.0
|
754 |
+
},
|
755 |
+
{
|
756 |
+
"current": 2300.0,
|
757 |
+
"min": 800.0,
|
758 |
+
"max": 3400.0
|
759 |
+
},
|
760 |
+
{
|
761 |
+
"current": 2300.0,
|
762 |
+
"min": 800.0,
|
763 |
+
"max": 3400.0
|
764 |
+
},
|
765 |
+
{
|
766 |
+
"current": 2300.0,
|
767 |
+
"min": 800.0,
|
768 |
+
"max": 3400.0
|
769 |
+
},
|
770 |
+
{
|
771 |
+
"current": 2300.0,
|
772 |
+
"min": 800.0,
|
773 |
+
"max": 3400.0
|
774 |
+
},
|
775 |
+
{
|
776 |
+
"current": 2300.0,
|
777 |
+
"min": 800.0,
|
778 |
+
"max": 3400.0
|
779 |
+
},
|
780 |
+
{
|
781 |
+
"current": 2300.0,
|
782 |
+
"min": 800.0,
|
783 |
+
"max": 3400.0
|
784 |
+
},
|
785 |
+
{
|
786 |
+
"current": 2300.0,
|
787 |
+
"min": 800.0,
|
788 |
+
"max": 3400.0
|
789 |
+
},
|
790 |
+
{
|
791 |
+
"current": 2300.0,
|
792 |
+
"min": 800.0,
|
793 |
+
"max": 3400.0
|
794 |
+
},
|
795 |
+
{
|
796 |
+
"current": 2300.0,
|
797 |
+
"min": 800.0,
|
798 |
+
"max": 3400.0
|
799 |
+
},
|
800 |
+
{
|
801 |
+
"current": 2300.0,
|
802 |
+
"min": 800.0,
|
803 |
+
"max": 3400.0
|
804 |
+
},
|
805 |
+
{
|
806 |
+
"current": 2300.0,
|
807 |
+
"min": 800.0,
|
808 |
+
"max": 3400.0
|
809 |
+
},
|
810 |
+
{
|
811 |
+
"current": 2300.0,
|
812 |
+
"min": 800.0,
|
813 |
+
"max": 3400.0
|
814 |
+
},
|
815 |
+
{
|
816 |
+
"current": 2300.0,
|
817 |
+
"min": 800.0,
|
818 |
+
"max": 3400.0
|
819 |
+
},
|
820 |
+
{
|
821 |
+
"current": 2300.0,
|
822 |
+
"min": 800.0,
|
823 |
+
"max": 3400.0
|
824 |
+
},
|
825 |
+
{
|
826 |
+
"current": 2300.0,
|
827 |
+
"min": 800.0,
|
828 |
+
"max": 3400.0
|
829 |
+
},
|
830 |
+
{
|
831 |
+
"current": 2300.0,
|
832 |
+
"min": 800.0,
|
833 |
+
"max": 3400.0
|
834 |
+
},
|
835 |
+
{
|
836 |
+
"current": 2300.0,
|
837 |
+
"min": 800.0,
|
838 |
+
"max": 3400.0
|
839 |
+
}
|
840 |
+
],
|
841 |
+
"disk": {
|
842 |
+
"/": {
|
843 |
+
"total": 877.6341285705566,
|
844 |
+
"used": 211.64437866210938
|
845 |
+
}
|
846 |
+
},
|
847 |
+
"memory": {
|
848 |
+
"total": 1007.4379997253418
|
849 |
+
}
|
850 |
+
}
|
lm-evaluation-harness/wandb/run-20240522_184928-kt8p2r8k/files/wandb-summary.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"_wandb": {"runtime": 11}}
|
lm-evaluation-harness/wandb/run-20240522_184928-kt8p2r8k/run-kt8p2r8k.wandb
ADDED
Binary file (4.04 kB). View file
|
|
lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/files/config.yaml
ADDED
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
wandb_version: 1
|
2 |
+
|
3 |
+
_wandb:
|
4 |
+
desc: null
|
5 |
+
value:
|
6 |
+
python_version: 3.10.12
|
7 |
+
cli_version: 0.17.0
|
8 |
+
framework: huggingface
|
9 |
+
huggingface_version: 4.36.2
|
10 |
+
is_jupyter_run: false
|
11 |
+
is_kaggle_kernel: false
|
12 |
+
start_time: 1717073967
|
13 |
+
t:
|
14 |
+
1:
|
15 |
+
- 1
|
16 |
+
- 5
|
17 |
+
- 11
|
18 |
+
- 49
|
19 |
+
- 51
|
20 |
+
- 53
|
21 |
+
- 55
|
22 |
+
- 71
|
23 |
+
- 98
|
24 |
+
- 100
|
25 |
+
2:
|
26 |
+
- 1
|
27 |
+
- 5
|
28 |
+
- 11
|
29 |
+
- 49
|
30 |
+
- 51
|
31 |
+
- 53
|
32 |
+
- 55
|
33 |
+
- 71
|
34 |
+
- 98
|
35 |
+
- 100
|
36 |
+
3:
|
37 |
+
- 2
|
38 |
+
- 13
|
39 |
+
- 23
|
40 |
+
- 62
|
41 |
+
4: 3.10.12
|
42 |
+
5: 0.17.0
|
43 |
+
6: 4.36.2
|
44 |
+
8:
|
45 |
+
- 5
|
46 |
+
13: linux-x86_64
|
47 |
+
task_configs:
|
48 |
+
desc: null
|
49 |
+
value:
|
50 |
+
arc_easy:
|
51 |
+
task: arc_easy
|
52 |
+
group:
|
53 |
+
- ai2_arc
|
54 |
+
dataset_path: allenai/ai2_arc
|
55 |
+
dataset_name: ARC-Easy
|
56 |
+
training_split: train
|
57 |
+
validation_split: validation
|
58 |
+
test_split: test
|
59 |
+
doc_to_text: 'Question: {{question}}
|
60 |
+
|
61 |
+
Answer:'
|
62 |
+
doc_to_target: '{{choices.label.index(answerKey)}}'
|
63 |
+
doc_to_choice: '{{choices.text}}'
|
64 |
+
description: ''
|
65 |
+
target_delimiter: ' '
|
66 |
+
fewshot_delimiter: '
|
67 |
+
|
68 |
+
|
69 |
+
'
|
70 |
+
num_fewshot: 0
|
71 |
+
metric_list:
|
72 |
+
- metric: acc
|
73 |
+
aggregation: mean
|
74 |
+
higher_is_better: true
|
75 |
+
- metric: acc_norm
|
76 |
+
aggregation: mean
|
77 |
+
higher_is_better: true
|
78 |
+
output_type: multiple_choice
|
79 |
+
repeats: 1
|
80 |
+
should_decontaminate: true
|
81 |
+
doc_to_decontamination_query: 'Question: {{question}}
|
82 |
+
|
83 |
+
Answer:'
|
84 |
+
metadata:
|
85 |
+
version: 1.0
|
86 |
+
boolq:
|
87 |
+
task: boolq
|
88 |
+
group:
|
89 |
+
- super-glue-lm-eval-v1
|
90 |
+
dataset_path: super_glue
|
91 |
+
dataset_name: boolq
|
92 |
+
training_split: train
|
93 |
+
validation_split: validation
|
94 |
+
doc_to_text: '{{passage}}
|
95 |
+
|
96 |
+
Question: {{question}}?
|
97 |
+
|
98 |
+
Answer:'
|
99 |
+
doc_to_target: label
|
100 |
+
doc_to_choice:
|
101 |
+
- 'no'
|
102 |
+
- 'yes'
|
103 |
+
description: ''
|
104 |
+
target_delimiter: ' '
|
105 |
+
fewshot_delimiter: '
|
106 |
+
|
107 |
+
|
108 |
+
'
|
109 |
+
num_fewshot: 0
|
110 |
+
metric_list:
|
111 |
+
- metric: acc
|
112 |
+
output_type: multiple_choice
|
113 |
+
repeats: 1
|
114 |
+
should_decontaminate: true
|
115 |
+
doc_to_decontamination_query: passage
|
116 |
+
metadata:
|
117 |
+
version: 2.0
|
118 |
+
copa:
|
119 |
+
task: copa
|
120 |
+
group:
|
121 |
+
- super-glue-lm-eval-v1
|
122 |
+
dataset_path: super_glue
|
123 |
+
dataset_name: copa
|
124 |
+
training_split: train
|
125 |
+
validation_split: validation
|
126 |
+
doc_to_text: "def doc_to_text(doc):\n # Drop the period\n connector =\
|
127 |
+
\ {\n \"cause\": \"because\",\n \"effect\": \"therefore\",\n\
|
128 |
+
\ }[doc[\"question\"]]\n return doc[\"premise\"].strip()[:-1] + f\"\
|
129 |
+
\ {connector}\"\n"
|
130 |
+
doc_to_target: "def doc_to_target(doc):\n correct_choice = doc[\"choice1\"\
|
131 |
+
] if doc[\"label\"] == 0 else doc[\"choice2\"]\n # Connect the sentences\n\
|
132 |
+
\ return \" \" + convert_choice(correct_choice)\n"
|
133 |
+
doc_to_choice: "def doc_to_choice(doc):\n return [\" \" + convert_choice(doc[\"\
|
134 |
+
choice1\"]), \" \" + convert_choice(doc[\"choice2\"])]\n"
|
135 |
+
description: ''
|
136 |
+
target_delimiter: ' '
|
137 |
+
fewshot_delimiter: '
|
138 |
+
|
139 |
+
|
140 |
+
'
|
141 |
+
num_fewshot: 0
|
142 |
+
metric_list:
|
143 |
+
- metric: acc
|
144 |
+
output_type: multiple_choice
|
145 |
+
repeats: 1
|
146 |
+
should_decontaminate: false
|
147 |
+
metadata:
|
148 |
+
version: 1.0
|
149 |
+
mrpc:
|
150 |
+
task: mrpc
|
151 |
+
group: glue
|
152 |
+
dataset_path: glue
|
153 |
+
dataset_name: mrpc
|
154 |
+
training_split: train
|
155 |
+
validation_split: validation
|
156 |
+
doc_to_text: 'Sentence 1: {{sentence1}}
|
157 |
+
|
158 |
+
Sentence 2: {{sentence2}}
|
159 |
+
|
160 |
+
Question: Do both sentences mean the same thing?
|
161 |
+
|
162 |
+
Answer:'
|
163 |
+
doc_to_target: label
|
164 |
+
doc_to_choice:
|
165 |
+
- 'no'
|
166 |
+
- 'yes'
|
167 |
+
description: ''
|
168 |
+
target_delimiter: ' '
|
169 |
+
fewshot_delimiter: '
|
170 |
+
|
171 |
+
|
172 |
+
'
|
173 |
+
num_fewshot: 0
|
174 |
+
metric_list:
|
175 |
+
- metric: acc
|
176 |
+
- metric: f1
|
177 |
+
output_type: multiple_choice
|
178 |
+
repeats: 1
|
179 |
+
should_decontaminate: false
|
180 |
+
metadata:
|
181 |
+
version: 1.0
|
182 |
+
piqa:
|
183 |
+
task: piqa
|
184 |
+
dataset_path: piqa
|
185 |
+
training_split: train
|
186 |
+
validation_split: validation
|
187 |
+
doc_to_text: 'Question: {{goal}}
|
188 |
+
|
189 |
+
Answer:'
|
190 |
+
doc_to_target: label
|
191 |
+
doc_to_choice: '{{[sol1, sol2]}}'
|
192 |
+
description: ''
|
193 |
+
target_delimiter: ' '
|
194 |
+
fewshot_delimiter: '
|
195 |
+
|
196 |
+
|
197 |
+
'
|
198 |
+
num_fewshot: 0
|
199 |
+
metric_list:
|
200 |
+
- metric: acc
|
201 |
+
aggregation: mean
|
202 |
+
higher_is_better: true
|
203 |
+
- metric: acc_norm
|
204 |
+
aggregation: mean
|
205 |
+
higher_is_better: true
|
206 |
+
output_type: multiple_choice
|
207 |
+
repeats: 1
|
208 |
+
should_decontaminate: true
|
209 |
+
doc_to_decontamination_query: goal
|
210 |
+
metadata:
|
211 |
+
version: 1.0
|
212 |
+
sst2:
|
213 |
+
task: sst2
|
214 |
+
group: glue
|
215 |
+
dataset_path: glue
|
216 |
+
dataset_name: sst2
|
217 |
+
training_split: train
|
218 |
+
validation_split: validation
|
219 |
+
doc_to_text: '{{sentence}}
|
220 |
+
|
221 |
+
Question: Is this sentence positive or negative?
|
222 |
+
|
223 |
+
Answer:'
|
224 |
+
doc_to_target: label
|
225 |
+
doc_to_choice:
|
226 |
+
- negative
|
227 |
+
- positive
|
228 |
+
description: ''
|
229 |
+
target_delimiter: ' '
|
230 |
+
fewshot_delimiter: '
|
231 |
+
|
232 |
+
|
233 |
+
'
|
234 |
+
num_fewshot: 0
|
235 |
+
metric_list:
|
236 |
+
- metric: acc
|
237 |
+
output_type: multiple_choice
|
238 |
+
repeats: 1
|
239 |
+
should_decontaminate: false
|
240 |
+
metadata:
|
241 |
+
version: 1.0
|
242 |
+
winogrande:
|
243 |
+
task: winogrande
|
244 |
+
dataset_path: winogrande
|
245 |
+
dataset_name: winogrande_xl
|
246 |
+
training_split: train
|
247 |
+
validation_split: validation
|
248 |
+
doc_to_text: "def doc_to_text(doc):\n answer_to_num = {\"1\": 0, \"2\": 1}\n\
|
249 |
+
\ return answer_to_num[doc[\"answer\"]]\n"
|
250 |
+
doc_to_target: "def doc_to_target(doc):\n idx = doc[\"sentence\"].index(\"\
|
251 |
+
_\") + 1\n return doc[\"sentence\"][idx:].strip()\n"
|
252 |
+
doc_to_choice: "def doc_to_choice(doc):\n idx = doc[\"sentence\"].index(\"\
|
253 |
+
_\")\n options = [doc[\"option1\"], doc[\"option2\"]]\n return [doc[\"\
|
254 |
+
sentence\"][:idx] + opt for opt in options]\n"
|
255 |
+
description: ''
|
256 |
+
target_delimiter: ' '
|
257 |
+
fewshot_delimiter: '
|
258 |
+
|
259 |
+
|
260 |
+
'
|
261 |
+
num_fewshot: 0
|
262 |
+
metric_list:
|
263 |
+
- metric: acc
|
264 |
+
aggregation: mean
|
265 |
+
higher_is_better: true
|
266 |
+
output_type: multiple_choice
|
267 |
+
repeats: 1
|
268 |
+
should_decontaminate: true
|
269 |
+
doc_to_decontamination_query: sentence
|
270 |
+
metadata:
|
271 |
+
version: 1.0
|
272 |
+
cli_configs:
|
273 |
+
desc: null
|
274 |
+
value:
|
275 |
+
model: hf
|
276 |
+
model_args: pretrained=/mnt/weka/peacock/experiments/llama/eval/checkpoint-english/llamav2-3b/hf/global_step70000,tokenizer=/mnt/weka/peacock/tokenization/trained-tokenizer/enhiben_50k_hf/ConvertedTokenizer
|
277 |
+
batch_size: auto
|
278 |
+
batch_sizes:
|
279 |
+
- 64
|
280 |
+
device: null
|
281 |
+
use_cache: null
|
282 |
+
limit: null
|
283 |
+
bootstrap_iters: 100000
|
284 |
+
gen_kwargs: null
|
lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/files/media/table/evaluation/eval_results_1_9c87687b44ab0685fb7b.table.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"columns": ["Tasks", "Version", "Filter", "num_fewshot", "Metric", "Value", "Stderr"], "data": [["winogrande", 1.0, "none", 0, "acc", "0.4861878453038674", "0.0140"], ["sst2", 1.0, "none", 0, "acc", "0.49655963302752293", "0.0169"], ["piqa", 1.0, "none", 0, "acc", "0.5136017410228509", "0.0117"], ["piqa", 1.0, "none", 0, "acc_norm", "0.48258977149075083", "0.0117"], ["mrpc", 1.0, "none", 0, "acc", "0.3161764705882353", "0.0230"], ["mrpc", 1.0, "none", 0, "f1", "0.0", "0.0000"], ["copa", 1.0, "none", 0, "acc", "0.6", "0.0492"], ["boolq", 2.0, "none", 0, "acc", "0.37767584097859325", "0.0085"], ["arc_easy", 1.0, "none", 0, "acc", "0.2529461279461279", "0.0089"], ["arc_easy", 1.0, "none", 0, "acc_norm", "0.25336700336700335", "0.0089"]]}
|
lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/files/output.log
ADDED
@@ -0,0 +1,592 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
2024-05-30:12:59:28,500 INFO [__main__.py:251] Verbosity set to INFO
|
3 |
+
2024-05-30:12:59:37,836 INFO [__main__.py:335] Selected Tasks: ['arc_easy', 'boolq', 'copa', 'mrpc', 'piqa', 'sst2', 'winogrande']
|
4 |
+
2024-05-30:12:59:37,837 INFO [evaluator.py:131] Setting random seed to 0 | Setting numpy seed to 1234 | Setting torch manual seed to 1234
|
5 |
+
2024-05-30:12:59:37,837 INFO [evaluator.py:177] Initializing hf model, with arguments: {'pretrained': '/mnt/weka/peacock/experiments/llama/eval/checkpoint-english/llamav2-3b/hf/global_step70000', 'tokenizer': '/mnt/weka/peacock/tokenization/trained-tokenizer/enhiben_50k_hf/ConvertedTokenizer'}
|
6 |
+
2024-05-30:12:59:40,131 INFO [huggingface.py:164] Using device 'cuda'
|
7 |
+
/usr/local/lib/python3.10/dist-packages/habana_frameworks/torch/gpu_migration/torch/cuda/memory.py:36: UserWarning: No need to call empty_cache on HPU. It manages the memory internally in an effcient way.
|
8 |
+
warnings.warn(
|
9 |
+
Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.
|
10 |
+
Downloading readme: 100%|██████████| 9.00k/9.00k [00:00<00:00, 14.1MB/s]
|
11 |
+
Downloading data: 100%|██████████| 331k/331k [00:00<00:00, 1.86MB/s]
|
12 |
+
Downloading data: 100%|██████████| 346k/346k [00:00<00:00, 4.59MB/s]
|
13 |
+
Downloading data: 100%|██████████| 86.1k/86.1k [00:00<00:00, 1.14MB/s]
|
14 |
+
Generating train split: 100%|██████████| 2251/2251 [00:00<00:00, 42582.05 examples/s]
|
15 |
+
Generating test split: 100%|██████████| 2376/2376 [00:00<00:00, 331415.57 examples/s]
|
16 |
+
Generating validation split: 100%|██████████| 570/570 [00:00<00:00, 152861.46 examples/s]
|
17 |
+
2024-05-30:13:00:10,175 WARNING [task.py:763] [Task: boolq] metric acc is defined, but aggregation is not. using default aggregation=mean
|
18 |
+
2024-05-30:13:00:10,175 WARNING [task.py:775] [Task: boolq] metric acc is defined, but higher_is_better is not. using default higher_is_better=True
|
19 |
+
/usr/local/lib/python3.10/dist-packages/datasets/load.py:1486: FutureWarning: The repository for super_glue contains custom code which must be executed to correctly load the dataset. You can inspect the repository content at https://hf.co/datasets/super_glue
|
20 |
+
You can avoid this message in future by passing the argument `trust_remote_code=True`.
|
21 |
+
Passing `trust_remote_code=True` will be mandatory to load this dataset from the next major release of `datasets`.
|
22 |
+
warnings.warn(
|
23 |
+
Downloading builder script: 100%|██████████| 30.7k/30.7k [00:00<00:00, 41.1MB/s]
|
24 |
+
Downloading readme: 100%|██████████| 18.2k/18.2k [00:00<00:00, 30.5MB/s]
|
25 |
+
Downloading data: 100%|██████████| 4.12M/4.12M [00:00<00:00, 17.5MB/s]
|
26 |
+
Generating train split: 100%|██████████| 9427/9427 [00:00<00:00, 22302.36 examples/s]
|
27 |
+
Generating validation split: 100%|██████████| 3270/3270 [00:00<00:00, 19757.63 examples/s]
|
28 |
+
Generating test split: 100%|██████████| 3245/3245 [00:00<00:00, 22659.61 examples/s]
|
29 |
+
2024-05-30:13:00:14,119 WARNING [task.py:763] [Task: copa] metric acc is defined, but aggregation is not. using default aggregation=mean
|
30 |
+
2024-05-30:13:00:14,119 WARNING [task.py:775] [Task: copa] metric acc is defined, but higher_is_better is not. using default higher_is_better=True
|
31 |
+
Downloading data: 100%|██████████| 44.0k/44.0k [00:00<00:00, 48.8MB/s]
|
32 |
+
Generating train split: 100%|██████████| 400/400 [00:00<00:00, 16209.24 examples/s]
|
33 |
+
Generating validation split: 100%|██████████| 100/100 [00:00<00:00, 12743.22 examples/s]
|
34 |
+
Generating test split: 100%|██████████| 500/500 [00:00<00:00, 17484.13 examples/s]
|
35 |
+
2024-05-30:13:00:16,198 WARNING [task.py:763] [Task: mrpc] metric acc is defined, but aggregation is not. using default aggregation=mean
|
36 |
+
2024-05-30:13:00:16,198 WARNING [task.py:775] [Task: mrpc] metric acc is defined, but higher_is_better is not. using default higher_is_better=True
|
37 |
+
2024-05-30:13:00:16,198 WARNING [task.py:763] [Task: mrpc] metric f1 is defined, but aggregation is not. using default aggregation=f1
|
38 |
+
2024-05-30:13:00:16,198 WARNING [task.py:775] [Task: mrpc] metric f1 is defined, but higher_is_better is not. using default higher_is_better=True
|
39 |
+
Downloading readme: 100%|██████████| 35.3k/35.3k [00:00<00:00, 42.5MB/s]
|
40 |
+
Downloading data: 100%|██████████| 649k/649k [00:00<00:00, 4.44MB/s]
|
41 |
+
Downloading data: 100%|██████████| 75.7k/75.7k [00:00<00:00, 513kB/s]
|
42 |
+
Downloading data: 100%|██████████| 308k/308k [00:00<00:00, 1.43MB/s]
|
43 |
+
Generating train split: 100%|██████████| 3668/3668 [00:00<00:00, 409930.91 examples/s]
|
44 |
+
Generating validation split: 100%|██████████| 408/408 [00:00<00:00, 174655.65 examples/s]
|
45 |
+
Generating test split: 100%|██████████| 1725/1725 [00:00<00:00, 384440.72 examples/s]
|
46 |
+
/usr/local/lib/python3.10/dist-packages/datasets/load.py:1486: FutureWarning: The repository for piqa contains custom code which must be executed to correctly load the dataset. You can inspect the repository content at https://hf.co/datasets/piqa
|
47 |
+
You can avoid this message in future by passing the argument `trust_remote_code=True`.
|
48 |
+
Passing `trust_remote_code=True` will be mandatory to load this dataset from the next major release of `datasets`.
|
49 |
+
warnings.warn(
|
50 |
+
Downloading builder script: 100%|██████████| 5.36k/5.36k [00:00<00:00, 12.1MB/s]
|
51 |
+
Downloading readme: 100%|██████████| 8.41k/8.41k [00:00<00:00, 17.3MB/s]
|
52 |
+
Downloading data: 100%|██████████| 1.82M/1.82M [00:00<00:00, 4.17MB/s]
|
53 |
+
Downloading data: 100%|██████████| 815k/815k [00:00<00:00, 23.8MB/s]
|
54 |
+
Generating train split: 100%|██████████| 16113/16113 [00:00<00:00, 24119.62 examples/s]
|
55 |
+
Generating test split: 100%|██████████| 3084/3084 [00:00<00:00, 24246.44 examples/s]
|
56 |
+
Generating validation split: 100%|██████████| 1838/1838 [00:00<00:00, 24180.73 examples/s]
|
57 |
+
2024-05-30:13:00:26,733 WARNING [task.py:763] [Task: sst2] metric acc is defined, but aggregation is not. using default aggregation=mean
|
58 |
+
2024-05-30:13:00:26,733 WARNING [task.py:775] [Task: sst2] metric acc is defined, but higher_is_better is not. using default higher_is_better=True
|
59 |
+
Downloading data: 100%|██████████| 3.11M/3.11M [00:00<00:00, 21.0MB/s]
|
60 |
+
Downloading data: 100%|██████████| 72.8k/72.8k [00:00<00:00, 510kB/s]
|
61 |
+
Downloading data: 100%|██████████| 148k/148k [00:00<00:00, 1.02MB/s]
|
62 |
+
Generating train split: 100%|██████████| 67349/67349 [00:00<00:00, 1427196.66 examples/s]
|
63 |
+
Generating validation split: 100%|██████████| 872/872 [00:00<00:00, 378107.42 examples/s]
|
64 |
+
Generating test split: 100%|██████████| 1821/1821 [00:00<00:00, 413414.21 examples/s]
|
65 |
+
/usr/local/lib/python3.10/dist-packages/datasets/load.py:1486: FutureWarning: The repository for winogrande contains custom code which must be executed to correctly load the dataset. You can inspect the repository content at https://hf.co/datasets/winogrande
|
66 |
+
You can avoid this message in future by passing the argument `trust_remote_code=True`.
|
67 |
+
Passing `trust_remote_code=True` will be mandatory to load this dataset from the next major release of `datasets`.
|
68 |
+
warnings.warn(
|
69 |
+
Downloading builder script: 100%|██████████| 5.65k/5.65k [00:00<00:00, 12.4MB/s]
|
70 |
+
Downloading readme: 100%|██████████| 9.97k/9.97k [00:00<00:00, 20.5MB/s]
|
71 |
+
Downloading data: 100%|██████████| 3.40M/3.40M [00:00<00:00, 7.08MB/s]
|
72 |
+
Generating train split: 100%|██████████| 40398/40398 [00:01<00:00, 24456.13 examples/s]
|
73 |
+
Generating test split: 100%|██████████| 1767/1767 [00:00<00:00, 24232.17 examples/s]
|
74 |
+
Generating validation split: 100%|██████████| 1267/1267 [00:00<00:00, 23665.92 examples/s]
|
75 |
+
2024-05-30:13:00:39,614 INFO [task.py:395] Building contexts for winogrande on rank 0...
|
76 |
+
100%|██████████| 1267/1267 [00:00<00:00, 67713.85it/s]
|
77 |
+
2024-05-30:13:00:39,696 INFO [task.py:395] Building contexts for sst2 on rank 0...
|
78 |
+
100%|██████████| 872/872 [00:00<00:00, 2590.42it/s]
|
79 |
+
2024-05-30:13:00:40,061 INFO [task.py:395] Building contexts for piqa on rank 0...
|
80 |
+
100%|██████████| 1838/1838 [00:01<00:00, 1096.81it/s]
|
81 |
+
2024-05-30:13:00:41,812 INFO [task.py:395] Building contexts for mrpc on rank 0...
|
82 |
+
100%|██████████| 408/408 [00:00<00:00, 1914.16it/s]
|
83 |
+
2024-05-30:13:00:42,044 INFO [task.py:395] Building contexts for copa on rank 0...
|
84 |
+
100%|██████████| 100/100 [00:00<00:00, 60707.83it/s]
|
85 |
+
2024-05-30:13:00:42,052 INFO [task.py:395] Building contexts for boolq on rank 0...
|
86 |
+
100%|██████████| 3270/3270 [00:01<00:00, 1948.70it/s]
|
87 |
+
2024-05-30:13:00:43,861 INFO [task.py:395] Building contexts for arc_easy on rank 0...
|
88 |
+
100%|██████████| 2376/2376 [00:02<00:00, 1078.90it/s]
|
89 |
+
2024-05-30:13:00:46,207 INFO [evaluator.py:379] Running loglikelihood requests
|
90 |
+
Token indices sequence length is longer than the specified maximum sequence length for this model (1333 > 1024). Running this sequence through the model will result in indexing errors
|
91 |
+
Running loglikelihood requests: 0%| | 0/25011 [00:00<?, ?it/s]
|
92 |
+
Passed argument batch_size = auto:1. Detecting largest batch size
|
93 |
+
|
94 |
+
|
95 |
+
|
96 |
+
|
97 |
+
|
98 |
+
|
99 |
+
|
100 |
+
|
101 |
+
|
102 |
+
|
103 |
+
|
104 |
+
|
105 |
+
|
106 |
+
|
107 |
+
|
108 |
+
|
109 |
+
|
110 |
+
|
111 |
+
|
112 |
+
|
113 |
+
|
114 |
+
|
115 |
+
|
116 |
+
|
117 |
+
|
118 |
+
|
119 |
+
|
120 |
+
|
121 |
+
|
122 |
+
|
123 |
+
|
124 |
+
|
125 |
+
|
126 |
+
|
127 |
+
|
128 |
+
|
129 |
+
|
130 |
+
|
131 |
+
|
132 |
+
|
133 |
+
|
134 |
+
|
135 |
+
|
136 |
+
|
137 |
+
|
138 |
+
|
139 |
+
|
140 |
+
|
141 |
+
|
142 |
+
|
143 |
+
|
144 |
+
|
145 |
+
|
146 |
+
|
147 |
+
|
148 |
+
|
149 |
+
|
150 |
+
|
151 |
+
|
152 |
+
|
153 |
+
|
154 |
+
|
155 |
+
|
156 |
+
|
157 |
+
|
158 |
+
|
159 |
+
|
160 |
+
|
161 |
+
|
162 |
+
|
163 |
+
|
164 |
+
|
165 |
+
|
166 |
+
|
167 |
+
|
168 |
+
|
169 |
+
|
170 |
+
|
171 |
+
|
172 |
+
|
173 |
+
|
174 |
+
|
175 |
+
|
176 |
+
|
177 |
+
|
178 |
+
|
179 |
+
|
180 |
+
|
181 |
+
|
182 |
+
|
183 |
+
|
184 |
+
|
185 |
+
|
186 |
+
|
187 |
+
|
188 |
+
|
189 |
+
|
190 |
+
|
191 |
+
|
192 |
+
|
193 |
+
|
194 |
+
|
195 |
+
|
196 |
+
|
197 |
+
|
198 |
+
|
199 |
+
|
200 |
+
|
201 |
+
|
202 |
+
|
203 |
+
|
204 |
+
|
205 |
+
|
206 |
+
|
207 |
+
|
208 |
+
|
209 |
+
|
210 |
+
|
211 |
+
|
212 |
+
|
213 |
+
|
214 |
+
|
215 |
+
|
216 |
+
|
217 |
+
|
218 |
+
|
219 |
+
|
220 |
+
|
221 |
+
|
222 |
+
|
223 |
+
|
224 |
+
|
225 |
+
|
226 |
+
|
227 |
+
|
228 |
+
|
229 |
+
|
230 |
+
|
231 |
+
|
232 |
+
|
233 |
+
|
234 |
+
|
235 |
+
|
236 |
+
|
237 |
+
|
238 |
+
|
239 |
+
|
240 |
+
|
241 |
+
|
242 |
+
|
243 |
+
|
244 |
+
|
245 |
+
|
246 |
+
|
247 |
+
|
248 |
+
|
249 |
+
|
250 |
+
|
251 |
+
|
252 |
+
|
253 |
+
|
254 |
+
|
255 |
+
|
256 |
+
|
257 |
+
|
258 |
+
|
259 |
+
|
260 |
+
|
261 |
+
|
262 |
+
|
263 |
+
|
264 |
+
|
265 |
+
|
266 |
+
|
267 |
+
|
268 |
+
|
269 |
+
|
270 |
+
|
271 |
+
|
272 |
+
|
273 |
+
|
274 |
+
|
275 |
+
|
276 |
+
|
277 |
+
|
278 |
+
|
279 |
+
|
280 |
+
|
281 |
+
|
282 |
+
|
283 |
+
|
284 |
+
|
285 |
+
|
286 |
+
|
287 |
+
|
288 |
+
|
289 |
+
|
290 |
+
|
291 |
+
|
292 |
+
|
293 |
+
|
294 |
+
|
295 |
+
|
296 |
+
|
297 |
+
|
298 |
+
|
299 |
+
|
300 |
+
|
301 |
+
|
302 |
+
|
303 |
+
|
304 |
+
|
305 |
+
|
306 |
+
|
307 |
+
|
308 |
+
|
309 |
+
|
310 |
+
|
311 |
+
|
312 |
+
|
313 |
+
|
314 |
+
|
315 |
+
|
316 |
+
|
317 |
+
|
318 |
+
|
319 |
+
|
320 |
+
|
321 |
+
|
322 |
+
|
323 |
+
|
324 |
+
|
325 |
+
|
326 |
+
|
327 |
+
|
328 |
+
|
329 |
+
|
330 |
+
|
331 |
+
|
332 |
+
|
333 |
+
|
334 |
+
|
335 |
+
|
336 |
+
|
337 |
+
|
338 |
+
|
339 |
+
|
340 |
+
|
341 |
+
|
342 |
+
|
343 |
+
|
344 |
+
|
345 |
+
|
346 |
+
|
347 |
+
|
348 |
+
|
349 |
+
|
350 |
+
|
351 |
+
|
352 |
+
|
353 |
+
|
354 |
+
|
355 |
+
|
356 |
+
|
357 |
+
|
358 |
+
|
359 |
+
|
360 |
+
|
361 |
+
|
362 |
+
|
363 |
+
|
364 |
+
|
365 |
+
|
366 |
+
|
367 |
+
|
368 |
+
|
369 |
+
|
370 |
+
|
371 |
+
|
372 |
+
|
373 |
+
|
374 |
+
|
375 |
+
|
376 |
+
|
377 |
+
|
378 |
+
|
379 |
+
|
380 |
+
|
381 |
+
|
382 |
+
|
383 |
+
|
384 |
+
|
385 |
+
|
386 |
+
|
387 |
+
|
388 |
+
|
389 |
+
|
390 |
+
|
391 |
+
|
392 |
+
|
393 |
+
|
394 |
+
|
395 |
+
|
396 |
+
|
397 |
+
|
398 |
+
|
399 |
+
|
400 |
+
|
401 |
+
|
402 |
+
|
403 |
+
|
404 |
+
|
405 |
+
|
406 |
+
|
407 |
+
|
408 |
+
|
409 |
+
|
410 |
+
|
411 |
+
|
412 |
+
|
413 |
+
|
414 |
+
|
415 |
+
|
416 |
+
|
417 |
+
|
418 |
+
|
419 |
+
|
420 |
+
|
421 |
+
|
422 |
+
|
423 |
+
|
424 |
+
|
425 |
+
|
426 |
+
|
427 |
+
|
428 |
+
|
429 |
+
|
430 |
+
|
431 |
+
|
432 |
+
|
433 |
+
|
434 |
+
|
435 |
+
|
436 |
+
|
437 |
+
|
438 |
+
|
439 |
+
|
440 |
+
|
441 |
+
|
442 |
+
|
443 |
+
|
444 |
+
|
445 |
+
|
446 |
+
|
447 |
+
|
448 |
+
|
449 |
+
|
450 |
+
|
451 |
+
|
452 |
+
|
453 |
+
|
454 |
+
|
455 |
+
|
456 |
+
|
457 |
+
|
458 |
+
|
459 |
+
|
460 |
+
|
461 |
+
|
462 |
+
|
463 |
+
|
464 |
+
|
465 |
+
|
466 |
+
|
467 |
+
|
468 |
+
|
469 |
+
|
470 |
+
|
471 |
+
|
472 |
+
|
473 |
+
|
474 |
+
|
475 |
+
|
476 |
+
|
477 |
+
|
478 |
+
|
479 |
+
|
480 |
+
|
481 |
+
|
482 |
+
|
483 |
+
|
484 |
+
|
485 |
+
|
486 |
+
|
487 |
+
|
488 |
+
|
489 |
+
|
490 |
+
|
491 |
+
|
492 |
+
|
493 |
+
|
494 |
+
|
495 |
+
|
496 |
+
|
497 |
+
|
498 |
+
|
499 |
+
|
500 |
+
|
501 |
+
|
502 |
+
|
503 |
+
|
504 |
+
|
505 |
+
|
506 |
+
|
507 |
+
|
508 |
+
|
509 |
+
|
510 |
+
|
511 |
+
|
512 |
+
|
513 |
+
|
514 |
+
|
515 |
+
|
516 |
+
|
517 |
+
|
518 |
+
|
519 |
+
|
520 |
+
|
521 |
+
|
522 |
+
|
523 |
+
|
524 |
+
|
525 |
+
|
526 |
+
|
527 |
+
|
528 |
+
|
529 |
+
|
530 |
+
|
531 |
+
|
532 |
+
|
533 |
+
|
534 |
+
|
535 |
+
|
536 |
+
|
537 |
+
|
538 |
+
|
539 |
+
|
540 |
+
|
541 |
+
|
542 |
+
|
543 |
+
|
544 |
+
|
545 |
+
|
546 |
+
|
547 |
+
|
548 |
+
|
549 |
+
|
550 |
+
|
551 |
+
|
552 |
+
|
553 |
+
|
554 |
+
|
555 |
+
|
556 |
+
|
557 |
+
|
558 |
+
|
559 |
+
|
560 |
+
|
561 |
+
|
562 |
+
|
563 |
+
|
564 |
+
|
565 |
+
|
566 |
+
|
567 |
+
|
568 |
+
|
569 |
+
|
570 |
+
|
571 |
+
|
572 |
+
|
573 |
+
|
574 |
+
|
575 |
+
Running loglikelihood requests: 100%|██████████| 25011/25011 [55:51<00:00, 7.46it/s]
|
576 |
+
bootstrapping for stddev: f1_score
|
577 |
+
|
578 |
+
|
579 |
+
100%|██████████| 100/100 [02:10<00:00, 1.31s/it]
|
580 |
+
hf (pretrained=/mnt/weka/peacock/experiments/llama/eval/checkpoint-english/llamav2-3b/hf/global_step70000,tokenizer=/mnt/weka/peacock/tokenization/trained-tokenizer/enhiben_50k_hf/ConvertedTokenizer), gen_kwargs: (None), limit: None, num_fewshot: None, batch_size: auto (64)
|
581 |
+
| Tasks |Version|Filter|n-shot| Metric |Value | |Stderr|
|
582 |
+
|----------|------:|------|-----:|--------|-----:|---|-----:|
|
583 |
+
|winogrande| 1|none | 0|acc |0.4862|± |0.0140|
|
584 |
+
|sst2 | 1|none | 0|acc |0.4966|± |0.0169|
|
585 |
+
|piqa | 1|none | 0|acc |0.5136|± |0.0117|
|
586 |
+
| | |none | 0|acc_norm|0.4826|± |0.0117|
|
587 |
+
|mrpc | 1|none | 0|acc |0.3162|± |0.0230|
|
588 |
+
| | |none | 0|f1 |0.0000|± |0.0000|
|
589 |
+
|copa | 1|none | 0|acc |0.6000|± |0.0492|
|
590 |
+
|boolq | 2|none | 0|acc |0.3777|± |0.0085|
|
591 |
+
|arc_easy | 1|none | 0|acc |0.2529|± |0.0089|
|
592 |
+
| | |none | 0|acc_norm|0.2534|± |0.0089|
|
lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/files/requirements.txt
ADDED
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
DataProperty==1.0.1
|
2 |
+
GitPython==3.1.43
|
3 |
+
Jinja2==3.1.3
|
4 |
+
Markdown==3.6
|
5 |
+
MarkupSafe==2.1.5
|
6 |
+
Pillow-SIMD==7.0.0.post3
|
7 |
+
PyYAML==6.0
|
8 |
+
Werkzeug==3.0.2
|
9 |
+
absl-py==2.1.0
|
10 |
+
accelerate==0.30.1
|
11 |
+
aiohttp==3.9.4
|
12 |
+
aiosignal==1.3.1
|
13 |
+
async-timeout==4.0.3
|
14 |
+
attrs==23.2.0
|
15 |
+
av==9.2.0
|
16 |
+
cachetools==5.3.3
|
17 |
+
certifi==2024.2.2
|
18 |
+
cffi==1.15.1
|
19 |
+
cfgv==3.4.0
|
20 |
+
chardet==5.2.0
|
21 |
+
charset-normalizer==3.3.2
|
22 |
+
click==8.1.7
|
23 |
+
cmake==3.29.2
|
24 |
+
colorama==0.4.6
|
25 |
+
datasets==2.19.1
|
26 |
+
deepspeed==0.12.4+hpu.synapse.v1.15.1
|
27 |
+
dill==0.3.8
|
28 |
+
distlib==0.3.8
|
29 |
+
docker-pycreds==0.4.0
|
30 |
+
einops==0.8.0
|
31 |
+
evaluate==0.4.2
|
32 |
+
exceptiongroup==1.2.0
|
33 |
+
expecttest==0.2.1
|
34 |
+
filelock==3.13.4
|
35 |
+
frozenlist==1.4.1
|
36 |
+
fsspec==2024.3.1
|
37 |
+
gitdb==4.0.11
|
38 |
+
google-auth-oauthlib==0.4.6
|
39 |
+
google-auth==2.29.0
|
40 |
+
grpcio==1.62.1
|
41 |
+
habana-media-loader==1.15.1.15
|
42 |
+
habana-pyhlml==1.15.1.15
|
43 |
+
habana-torch-dataloader==1.15.1.15
|
44 |
+
habana-torch-plugin==1.15.1.15
|
45 |
+
habana_gpu_migration==1.15.1.15
|
46 |
+
habana_quantization_toolkit==1.15.1.15
|
47 |
+
hjson==3.1.0
|
48 |
+
huggingface-hub==0.23.2
|
49 |
+
identify==2.5.35
|
50 |
+
idna==3.7
|
51 |
+
iniconfig==2.0.0
|
52 |
+
joblib==1.4.2
|
53 |
+
jsonlines==4.0.0
|
54 |
+
lightning-habana==1.4.0
|
55 |
+
lightning-utilities==0.11.2
|
56 |
+
lightning==2.2.0.post0
|
57 |
+
lm_eval==0.4.2
|
58 |
+
lm_eval==0.4.2
|
59 |
+
lm_eval==0.4.2
|
60 |
+
lxml==5.2.2
|
61 |
+
mbstrdecoder==1.1.3
|
62 |
+
more-itertools==10.2.0
|
63 |
+
mpi4py==3.1.4
|
64 |
+
mpmath==1.3.0
|
65 |
+
multidict==6.0.5
|
66 |
+
multiprocess==0.70.16
|
67 |
+
networkx==3.3
|
68 |
+
ninja==1.11.1.1
|
69 |
+
nltk==3.8.1
|
70 |
+
nodeenv==1.8.0
|
71 |
+
numexpr==2.10.0
|
72 |
+
numpy==1.23.5
|
73 |
+
oauthlib==3.2.2
|
74 |
+
packaging==24.0
|
75 |
+
pandas==2.0.1
|
76 |
+
pathspec==0.12.1
|
77 |
+
pathvalidate==3.2.0
|
78 |
+
peft==0.11.1
|
79 |
+
perfetto==0.7.0
|
80 |
+
pip==22.0.2
|
81 |
+
pip==23.3.1
|
82 |
+
platformdirs==4.2.0
|
83 |
+
pluggy==1.4.0
|
84 |
+
portalocker==2.8.2
|
85 |
+
pre-commit==3.3.3
|
86 |
+
protobuf==3.20.3
|
87 |
+
psutil==5.9.8
|
88 |
+
py-cpuinfo==9.0.0
|
89 |
+
pyarrow-hotfix==0.6
|
90 |
+
pyarrow==16.1.0
|
91 |
+
pyasn1==0.6.0
|
92 |
+
pyasn1_modules==0.4.0
|
93 |
+
pybind11==2.10.4
|
94 |
+
pycparser==2.22
|
95 |
+
pydantic==1.10.13
|
96 |
+
pynvml==8.0.4
|
97 |
+
pytablewriter==1.2.0
|
98 |
+
pytest==8.1.1
|
99 |
+
python-dateutil==2.9.0.post0
|
100 |
+
pytorch-lightning==2.2.2
|
101 |
+
pytz==2024.1
|
102 |
+
regex==2023.5.5
|
103 |
+
requests-oauthlib==2.0.0
|
104 |
+
requests==2.31.0
|
105 |
+
rouge_score==0.1.2
|
106 |
+
rsa==4.9
|
107 |
+
sacrebleu==2.4.2
|
108 |
+
safetensors==0.4.3
|
109 |
+
scikit-learn==1.5.0
|
110 |
+
scipy==1.13.1
|
111 |
+
sentencepiece==0.2.0
|
112 |
+
sentry-sdk==2.3.1
|
113 |
+
setproctitle==1.3.3
|
114 |
+
setuptools==59.6.0
|
115 |
+
setuptools==69.5.1
|
116 |
+
six==1.16.0
|
117 |
+
smmap==5.0.1
|
118 |
+
sqlitedict==2.1.0
|
119 |
+
symengine==0.11.0
|
120 |
+
sympy==1.12
|
121 |
+
tabledata==1.3.3
|
122 |
+
tabulate==0.9.0
|
123 |
+
tcolorpy==0.1.6
|
124 |
+
tdqm==0.0.1
|
125 |
+
tensorboard-data-server==0.6.1
|
126 |
+
tensorboard-plugin-wit==1.8.1
|
127 |
+
tensorboard==2.11.2
|
128 |
+
threadpoolctl==3.5.0
|
129 |
+
tokenizers==0.15.2
|
130 |
+
tomli==2.0.1
|
131 |
+
torch==2.2.0a0+git8964477
|
132 |
+
torch_tb_profiler==0.4.0
|
133 |
+
torchaudio==2.2.0+08901ad
|
134 |
+
torchdata==0.7.1+5e6f7b7
|
135 |
+
torchmetrics==1.3.2
|
136 |
+
torchtext==0.17.0+400da5c
|
137 |
+
torchvision==0.17.0+b2383d4
|
138 |
+
tqdm-multiprocess==0.0.11
|
139 |
+
tqdm==4.66.2
|
140 |
+
transformers==4.36.2
|
141 |
+
typepy==1.3.2
|
142 |
+
typing_extensions==4.11.0
|
143 |
+
tzdata==2024.1
|
144 |
+
urllib3==1.26.18
|
145 |
+
virtualenv==20.25.1
|
146 |
+
wandb==0.17.0
|
147 |
+
wheel==0.37.1
|
148 |
+
wheel==0.43.0
|
149 |
+
word2number==1.1
|
150 |
+
xxhash==3.4.1
|
151 |
+
yamllint==1.35.1
|
152 |
+
yarl==1.9.4
|
153 |
+
zstandard==0.22.0
|
lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/files/wandb-metadata.json
ADDED
@@ -0,0 +1,850 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"os": "Linux-5.15.0-92-generic-x86_64-with-glibc2.35",
|
3 |
+
"python": "3.10.12",
|
4 |
+
"heartbeatAt": "2024-05-30T12:59:28.263936",
|
5 |
+
"startedAt": "2024-05-30T12:59:27.773552",
|
6 |
+
"docker": null,
|
7 |
+
"cuda": null,
|
8 |
+
"args": [
|
9 |
+
"--model",
|
10 |
+
"hf",
|
11 |
+
"--model_args",
|
12 |
+
"pretrained=/mnt/weka/peacock/experiments/llama/eval/checkpoint-english/llamav2-3b/hf/global_step70000,tokenizer=/mnt/weka/peacock/tokenization/trained-tokenizer/enhiben_50k_hf/ConvertedTokenizer",
|
13 |
+
"--tasks",
|
14 |
+
"winogrande,sst2,mrpc,arc_easy,copa,piqa,boolq",
|
15 |
+
"--batch_size",
|
16 |
+
"auto",
|
17 |
+
"--wandb_args",
|
18 |
+
"project=english-eval,group=exp2,name=global_step70000"
|
19 |
+
],
|
20 |
+
"state": "running",
|
21 |
+
"program": "-m lm_eval.__main__",
|
22 |
+
"codePathLocal": null,
|
23 |
+
"git": {
|
24 |
+
"remote": "https://github.com/EleutherAI/lm-evaluation-harness",
|
25 |
+
"commit": null
|
26 |
+
},
|
27 |
+
"email": null,
|
28 |
+
"root": "/mnt/weka/peacock/idc/cronscript/lm-evaluation-harness",
|
29 |
+
"host": "peacock-evaluation-debug-35-worker-0",
|
30 |
+
"username": "root",
|
31 |
+
"executable": "/usr/bin/python3",
|
32 |
+
"cpu_count": 80,
|
33 |
+
"cpu_count_logical": 160,
|
34 |
+
"cpu_freq": {
|
35 |
+
"current": 2366.7911937500003,
|
36 |
+
"min": 800.0,
|
37 |
+
"max": 3400.0
|
38 |
+
},
|
39 |
+
"cpu_freq_per_core": [
|
40 |
+
{
|
41 |
+
"current": 3400.0,
|
42 |
+
"min": 800.0,
|
43 |
+
"max": 3400.0
|
44 |
+
},
|
45 |
+
{
|
46 |
+
"current": 3400.0,
|
47 |
+
"min": 800.0,
|
48 |
+
"max": 3400.0
|
49 |
+
},
|
50 |
+
{
|
51 |
+
"current": 2300.0,
|
52 |
+
"min": 800.0,
|
53 |
+
"max": 3400.0
|
54 |
+
},
|
55 |
+
{
|
56 |
+
"current": 2300.0,
|
57 |
+
"min": 800.0,
|
58 |
+
"max": 3400.0
|
59 |
+
},
|
60 |
+
{
|
61 |
+
"current": 2300.0,
|
62 |
+
"min": 800.0,
|
63 |
+
"max": 3400.0
|
64 |
+
},
|
65 |
+
{
|
66 |
+
"current": 2300.0,
|
67 |
+
"min": 800.0,
|
68 |
+
"max": 3400.0
|
69 |
+
},
|
70 |
+
{
|
71 |
+
"current": 2300.0,
|
72 |
+
"min": 800.0,
|
73 |
+
"max": 3400.0
|
74 |
+
},
|
75 |
+
{
|
76 |
+
"current": 2300.0,
|
77 |
+
"min": 800.0,
|
78 |
+
"max": 3400.0
|
79 |
+
},
|
80 |
+
{
|
81 |
+
"current": 2300.0,
|
82 |
+
"min": 800.0,
|
83 |
+
"max": 3400.0
|
84 |
+
},
|
85 |
+
{
|
86 |
+
"current": 2300.0,
|
87 |
+
"min": 800.0,
|
88 |
+
"max": 3400.0
|
89 |
+
},
|
90 |
+
{
|
91 |
+
"current": 2300.0,
|
92 |
+
"min": 800.0,
|
93 |
+
"max": 3400.0
|
94 |
+
},
|
95 |
+
{
|
96 |
+
"current": 2300.0,
|
97 |
+
"min": 800.0,
|
98 |
+
"max": 3400.0
|
99 |
+
},
|
100 |
+
{
|
101 |
+
"current": 2300.0,
|
102 |
+
"min": 800.0,
|
103 |
+
"max": 3400.0
|
104 |
+
},
|
105 |
+
{
|
106 |
+
"current": 2300.0,
|
107 |
+
"min": 800.0,
|
108 |
+
"max": 3400.0
|
109 |
+
},
|
110 |
+
{
|
111 |
+
"current": 2300.0,
|
112 |
+
"min": 800.0,
|
113 |
+
"max": 3400.0
|
114 |
+
},
|
115 |
+
{
|
116 |
+
"current": 2300.0,
|
117 |
+
"min": 800.0,
|
118 |
+
"max": 3400.0
|
119 |
+
},
|
120 |
+
{
|
121 |
+
"current": 2300.0,
|
122 |
+
"min": 800.0,
|
123 |
+
"max": 3400.0
|
124 |
+
},
|
125 |
+
{
|
126 |
+
"current": 2300.0,
|
127 |
+
"min": 800.0,
|
128 |
+
"max": 3400.0
|
129 |
+
},
|
130 |
+
{
|
131 |
+
"current": 2300.0,
|
132 |
+
"min": 800.0,
|
133 |
+
"max": 3400.0
|
134 |
+
},
|
135 |
+
{
|
136 |
+
"current": 2300.0,
|
137 |
+
"min": 800.0,
|
138 |
+
"max": 3400.0
|
139 |
+
},
|
140 |
+
{
|
141 |
+
"current": 2300.0,
|
142 |
+
"min": 800.0,
|
143 |
+
"max": 3400.0
|
144 |
+
},
|
145 |
+
{
|
146 |
+
"current": 2300.0,
|
147 |
+
"min": 800.0,
|
148 |
+
"max": 3400.0
|
149 |
+
},
|
150 |
+
{
|
151 |
+
"current": 2300.0,
|
152 |
+
"min": 800.0,
|
153 |
+
"max": 3400.0
|
154 |
+
},
|
155 |
+
{
|
156 |
+
"current": 2300.0,
|
157 |
+
"min": 800.0,
|
158 |
+
"max": 3400.0
|
159 |
+
},
|
160 |
+
{
|
161 |
+
"current": 2300.0,
|
162 |
+
"min": 800.0,
|
163 |
+
"max": 3400.0
|
164 |
+
},
|
165 |
+
{
|
166 |
+
"current": 2300.0,
|
167 |
+
"min": 800.0,
|
168 |
+
"max": 3400.0
|
169 |
+
},
|
170 |
+
{
|
171 |
+
"current": 2300.0,
|
172 |
+
"min": 800.0,
|
173 |
+
"max": 3400.0
|
174 |
+
},
|
175 |
+
{
|
176 |
+
"current": 2300.0,
|
177 |
+
"min": 800.0,
|
178 |
+
"max": 3400.0
|
179 |
+
},
|
180 |
+
{
|
181 |
+
"current": 2300.0,
|
182 |
+
"min": 800.0,
|
183 |
+
"max": 3400.0
|
184 |
+
},
|
185 |
+
{
|
186 |
+
"current": 2300.0,
|
187 |
+
"min": 800.0,
|
188 |
+
"max": 3400.0
|
189 |
+
},
|
190 |
+
{
|
191 |
+
"current": 2300.0,
|
192 |
+
"min": 800.0,
|
193 |
+
"max": 3400.0
|
194 |
+
},
|
195 |
+
{
|
196 |
+
"current": 2300.0,
|
197 |
+
"min": 800.0,
|
198 |
+
"max": 3400.0
|
199 |
+
},
|
200 |
+
{
|
201 |
+
"current": 2300.0,
|
202 |
+
"min": 800.0,
|
203 |
+
"max": 3400.0
|
204 |
+
},
|
205 |
+
{
|
206 |
+
"current": 2300.0,
|
207 |
+
"min": 800.0,
|
208 |
+
"max": 3400.0
|
209 |
+
},
|
210 |
+
{
|
211 |
+
"current": 2300.0,
|
212 |
+
"min": 800.0,
|
213 |
+
"max": 3400.0
|
214 |
+
},
|
215 |
+
{
|
216 |
+
"current": 2300.0,
|
217 |
+
"min": 800.0,
|
218 |
+
"max": 3400.0
|
219 |
+
},
|
220 |
+
{
|
221 |
+
"current": 2300.0,
|
222 |
+
"min": 800.0,
|
223 |
+
"max": 3400.0
|
224 |
+
},
|
225 |
+
{
|
226 |
+
"current": 2300.0,
|
227 |
+
"min": 800.0,
|
228 |
+
"max": 3400.0
|
229 |
+
},
|
230 |
+
{
|
231 |
+
"current": 2300.0,
|
232 |
+
"min": 800.0,
|
233 |
+
"max": 3400.0
|
234 |
+
},
|
235 |
+
{
|
236 |
+
"current": 2300.0,
|
237 |
+
"min": 800.0,
|
238 |
+
"max": 3400.0
|
239 |
+
},
|
240 |
+
{
|
241 |
+
"current": 3400.0,
|
242 |
+
"min": 800.0,
|
243 |
+
"max": 3400.0
|
244 |
+
},
|
245 |
+
{
|
246 |
+
"current": 2300.0,
|
247 |
+
"min": 800.0,
|
248 |
+
"max": 3400.0
|
249 |
+
},
|
250 |
+
{
|
251 |
+
"current": 2300.0,
|
252 |
+
"min": 800.0,
|
253 |
+
"max": 3400.0
|
254 |
+
},
|
255 |
+
{
|
256 |
+
"current": 2300.0,
|
257 |
+
"min": 800.0,
|
258 |
+
"max": 3400.0
|
259 |
+
},
|
260 |
+
{
|
261 |
+
"current": 2300.0,
|
262 |
+
"min": 800.0,
|
263 |
+
"max": 3400.0
|
264 |
+
},
|
265 |
+
{
|
266 |
+
"current": 2300.0,
|
267 |
+
"min": 800.0,
|
268 |
+
"max": 3400.0
|
269 |
+
},
|
270 |
+
{
|
271 |
+
"current": 2300.0,
|
272 |
+
"min": 800.0,
|
273 |
+
"max": 3400.0
|
274 |
+
},
|
275 |
+
{
|
276 |
+
"current": 2300.0,
|
277 |
+
"min": 800.0,
|
278 |
+
"max": 3400.0
|
279 |
+
},
|
280 |
+
{
|
281 |
+
"current": 2300.0,
|
282 |
+
"min": 800.0,
|
283 |
+
"max": 3400.0
|
284 |
+
},
|
285 |
+
{
|
286 |
+
"current": 2300.0,
|
287 |
+
"min": 800.0,
|
288 |
+
"max": 3400.0
|
289 |
+
},
|
290 |
+
{
|
291 |
+
"current": 2300.0,
|
292 |
+
"min": 800.0,
|
293 |
+
"max": 3400.0
|
294 |
+
},
|
295 |
+
{
|
296 |
+
"current": 2300.0,
|
297 |
+
"min": 800.0,
|
298 |
+
"max": 3400.0
|
299 |
+
},
|
300 |
+
{
|
301 |
+
"current": 2300.0,
|
302 |
+
"min": 800.0,
|
303 |
+
"max": 3400.0
|
304 |
+
},
|
305 |
+
{
|
306 |
+
"current": 2300.0,
|
307 |
+
"min": 800.0,
|
308 |
+
"max": 3400.0
|
309 |
+
},
|
310 |
+
{
|
311 |
+
"current": 2300.0,
|
312 |
+
"min": 800.0,
|
313 |
+
"max": 3400.0
|
314 |
+
},
|
315 |
+
{
|
316 |
+
"current": 2300.0,
|
317 |
+
"min": 800.0,
|
318 |
+
"max": 3400.0
|
319 |
+
},
|
320 |
+
{
|
321 |
+
"current": 2300.0,
|
322 |
+
"min": 800.0,
|
323 |
+
"max": 3400.0
|
324 |
+
},
|
325 |
+
{
|
326 |
+
"current": 2300.0,
|
327 |
+
"min": 800.0,
|
328 |
+
"max": 3400.0
|
329 |
+
},
|
330 |
+
{
|
331 |
+
"current": 2300.0,
|
332 |
+
"min": 800.0,
|
333 |
+
"max": 3400.0
|
334 |
+
},
|
335 |
+
{
|
336 |
+
"current": 2300.0,
|
337 |
+
"min": 800.0,
|
338 |
+
"max": 3400.0
|
339 |
+
},
|
340 |
+
{
|
341 |
+
"current": 2300.0,
|
342 |
+
"min": 800.0,
|
343 |
+
"max": 3400.0
|
344 |
+
},
|
345 |
+
{
|
346 |
+
"current": 2300.0,
|
347 |
+
"min": 800.0,
|
348 |
+
"max": 3400.0
|
349 |
+
},
|
350 |
+
{
|
351 |
+
"current": 2300.0,
|
352 |
+
"min": 800.0,
|
353 |
+
"max": 3400.0
|
354 |
+
},
|
355 |
+
{
|
356 |
+
"current": 2300.0,
|
357 |
+
"min": 800.0,
|
358 |
+
"max": 3400.0
|
359 |
+
},
|
360 |
+
{
|
361 |
+
"current": 2300.0,
|
362 |
+
"min": 800.0,
|
363 |
+
"max": 3400.0
|
364 |
+
},
|
365 |
+
{
|
366 |
+
"current": 2300.0,
|
367 |
+
"min": 800.0,
|
368 |
+
"max": 3400.0
|
369 |
+
},
|
370 |
+
{
|
371 |
+
"current": 2300.0,
|
372 |
+
"min": 800.0,
|
373 |
+
"max": 3400.0
|
374 |
+
},
|
375 |
+
{
|
376 |
+
"current": 2300.0,
|
377 |
+
"min": 800.0,
|
378 |
+
"max": 3400.0
|
379 |
+
},
|
380 |
+
{
|
381 |
+
"current": 2300.0,
|
382 |
+
"min": 800.0,
|
383 |
+
"max": 3400.0
|
384 |
+
},
|
385 |
+
{
|
386 |
+
"current": 2300.0,
|
387 |
+
"min": 800.0,
|
388 |
+
"max": 3400.0
|
389 |
+
},
|
390 |
+
{
|
391 |
+
"current": 2300.0,
|
392 |
+
"min": 800.0,
|
393 |
+
"max": 3400.0
|
394 |
+
},
|
395 |
+
{
|
396 |
+
"current": 2300.0,
|
397 |
+
"min": 800.0,
|
398 |
+
"max": 3400.0
|
399 |
+
},
|
400 |
+
{
|
401 |
+
"current": 2300.0,
|
402 |
+
"min": 800.0,
|
403 |
+
"max": 3400.0
|
404 |
+
},
|
405 |
+
{
|
406 |
+
"current": 2300.0,
|
407 |
+
"min": 800.0,
|
408 |
+
"max": 3400.0
|
409 |
+
},
|
410 |
+
{
|
411 |
+
"current": 2300.0,
|
412 |
+
"min": 800.0,
|
413 |
+
"max": 3400.0
|
414 |
+
},
|
415 |
+
{
|
416 |
+
"current": 2300.0,
|
417 |
+
"min": 800.0,
|
418 |
+
"max": 3400.0
|
419 |
+
},
|
420 |
+
{
|
421 |
+
"current": 2300.0,
|
422 |
+
"min": 800.0,
|
423 |
+
"max": 3400.0
|
424 |
+
},
|
425 |
+
{
|
426 |
+
"current": 2300.0,
|
427 |
+
"min": 800.0,
|
428 |
+
"max": 3400.0
|
429 |
+
},
|
430 |
+
{
|
431 |
+
"current": 2300.0,
|
432 |
+
"min": 800.0,
|
433 |
+
"max": 3400.0
|
434 |
+
},
|
435 |
+
{
|
436 |
+
"current": 2300.0,
|
437 |
+
"min": 800.0,
|
438 |
+
"max": 3400.0
|
439 |
+
},
|
440 |
+
{
|
441 |
+
"current": 3400.0,
|
442 |
+
"min": 800.0,
|
443 |
+
"max": 3400.0
|
444 |
+
},
|
445 |
+
{
|
446 |
+
"current": 2300.0,
|
447 |
+
"min": 800.0,
|
448 |
+
"max": 3400.0
|
449 |
+
},
|
450 |
+
{
|
451 |
+
"current": 2300.0,
|
452 |
+
"min": 800.0,
|
453 |
+
"max": 3400.0
|
454 |
+
},
|
455 |
+
{
|
456 |
+
"current": 2300.0,
|
457 |
+
"min": 800.0,
|
458 |
+
"max": 3400.0
|
459 |
+
},
|
460 |
+
{
|
461 |
+
"current": 2300.0,
|
462 |
+
"min": 800.0,
|
463 |
+
"max": 3400.0
|
464 |
+
},
|
465 |
+
{
|
466 |
+
"current": 2300.0,
|
467 |
+
"min": 800.0,
|
468 |
+
"max": 3400.0
|
469 |
+
},
|
470 |
+
{
|
471 |
+
"current": 2300.0,
|
472 |
+
"min": 800.0,
|
473 |
+
"max": 3400.0
|
474 |
+
},
|
475 |
+
{
|
476 |
+
"current": 2300.0,
|
477 |
+
"min": 800.0,
|
478 |
+
"max": 3400.0
|
479 |
+
},
|
480 |
+
{
|
481 |
+
"current": 2300.0,
|
482 |
+
"min": 800.0,
|
483 |
+
"max": 3400.0
|
484 |
+
},
|
485 |
+
{
|
486 |
+
"current": 2300.0,
|
487 |
+
"min": 800.0,
|
488 |
+
"max": 3400.0
|
489 |
+
},
|
490 |
+
{
|
491 |
+
"current": 2300.0,
|
492 |
+
"min": 800.0,
|
493 |
+
"max": 3400.0
|
494 |
+
},
|
495 |
+
{
|
496 |
+
"current": 2300.0,
|
497 |
+
"min": 800.0,
|
498 |
+
"max": 3400.0
|
499 |
+
},
|
500 |
+
{
|
501 |
+
"current": 2300.0,
|
502 |
+
"min": 800.0,
|
503 |
+
"max": 3400.0
|
504 |
+
},
|
505 |
+
{
|
506 |
+
"current": 2300.0,
|
507 |
+
"min": 800.0,
|
508 |
+
"max": 3400.0
|
509 |
+
},
|
510 |
+
{
|
511 |
+
"current": 2300.0,
|
512 |
+
"min": 800.0,
|
513 |
+
"max": 3400.0
|
514 |
+
},
|
515 |
+
{
|
516 |
+
"current": 2300.0,
|
517 |
+
"min": 800.0,
|
518 |
+
"max": 3400.0
|
519 |
+
},
|
520 |
+
{
|
521 |
+
"current": 2300.0,
|
522 |
+
"min": 800.0,
|
523 |
+
"max": 3400.0
|
524 |
+
},
|
525 |
+
{
|
526 |
+
"current": 2300.0,
|
527 |
+
"min": 800.0,
|
528 |
+
"max": 3400.0
|
529 |
+
},
|
530 |
+
{
|
531 |
+
"current": 2300.0,
|
532 |
+
"min": 800.0,
|
533 |
+
"max": 3400.0
|
534 |
+
},
|
535 |
+
{
|
536 |
+
"current": 2300.0,
|
537 |
+
"min": 800.0,
|
538 |
+
"max": 3400.0
|
539 |
+
},
|
540 |
+
{
|
541 |
+
"current": 2300.0,
|
542 |
+
"min": 800.0,
|
543 |
+
"max": 3400.0
|
544 |
+
},
|
545 |
+
{
|
546 |
+
"current": 2300.0,
|
547 |
+
"min": 800.0,
|
548 |
+
"max": 3400.0
|
549 |
+
},
|
550 |
+
{
|
551 |
+
"current": 2300.0,
|
552 |
+
"min": 800.0,
|
553 |
+
"max": 3400.0
|
554 |
+
},
|
555 |
+
{
|
556 |
+
"current": 2300.0,
|
557 |
+
"min": 800.0,
|
558 |
+
"max": 3400.0
|
559 |
+
},
|
560 |
+
{
|
561 |
+
"current": 2300.0,
|
562 |
+
"min": 800.0,
|
563 |
+
"max": 3400.0
|
564 |
+
},
|
565 |
+
{
|
566 |
+
"current": 2300.0,
|
567 |
+
"min": 800.0,
|
568 |
+
"max": 3400.0
|
569 |
+
},
|
570 |
+
{
|
571 |
+
"current": 2300.0,
|
572 |
+
"min": 800.0,
|
573 |
+
"max": 3400.0
|
574 |
+
},
|
575 |
+
{
|
576 |
+
"current": 2300.0,
|
577 |
+
"min": 800.0,
|
578 |
+
"max": 3400.0
|
579 |
+
},
|
580 |
+
{
|
581 |
+
"current": 2300.0,
|
582 |
+
"min": 800.0,
|
583 |
+
"max": 3400.0
|
584 |
+
},
|
585 |
+
{
|
586 |
+
"current": 2300.0,
|
587 |
+
"min": 800.0,
|
588 |
+
"max": 3400.0
|
589 |
+
},
|
590 |
+
{
|
591 |
+
"current": 2300.0,
|
592 |
+
"min": 800.0,
|
593 |
+
"max": 3400.0
|
594 |
+
},
|
595 |
+
{
|
596 |
+
"current": 2300.0,
|
597 |
+
"min": 800.0,
|
598 |
+
"max": 3400.0
|
599 |
+
},
|
600 |
+
{
|
601 |
+
"current": 2300.0,
|
602 |
+
"min": 800.0,
|
603 |
+
"max": 3400.0
|
604 |
+
},
|
605 |
+
{
|
606 |
+
"current": 2300.0,
|
607 |
+
"min": 800.0,
|
608 |
+
"max": 3400.0
|
609 |
+
},
|
610 |
+
{
|
611 |
+
"current": 2300.0,
|
612 |
+
"min": 800.0,
|
613 |
+
"max": 3400.0
|
614 |
+
},
|
615 |
+
{
|
616 |
+
"current": 2300.0,
|
617 |
+
"min": 800.0,
|
618 |
+
"max": 3400.0
|
619 |
+
},
|
620 |
+
{
|
621 |
+
"current": 2300.0,
|
622 |
+
"min": 800.0,
|
623 |
+
"max": 3400.0
|
624 |
+
},
|
625 |
+
{
|
626 |
+
"current": 2300.0,
|
627 |
+
"min": 800.0,
|
628 |
+
"max": 3400.0
|
629 |
+
},
|
630 |
+
{
|
631 |
+
"current": 2300.0,
|
632 |
+
"min": 800.0,
|
633 |
+
"max": 3400.0
|
634 |
+
},
|
635 |
+
{
|
636 |
+
"current": 2300.0,
|
637 |
+
"min": 800.0,
|
638 |
+
"max": 3400.0
|
639 |
+
},
|
640 |
+
{
|
641 |
+
"current": 2300.0,
|
642 |
+
"min": 800.0,
|
643 |
+
"max": 3400.0
|
644 |
+
},
|
645 |
+
{
|
646 |
+
"current": 2300.0,
|
647 |
+
"min": 800.0,
|
648 |
+
"max": 3400.0
|
649 |
+
},
|
650 |
+
{
|
651 |
+
"current": 2300.0,
|
652 |
+
"min": 800.0,
|
653 |
+
"max": 3400.0
|
654 |
+
},
|
655 |
+
{
|
656 |
+
"current": 2300.0,
|
657 |
+
"min": 800.0,
|
658 |
+
"max": 3400.0
|
659 |
+
},
|
660 |
+
{
|
661 |
+
"current": 2300.0,
|
662 |
+
"min": 800.0,
|
663 |
+
"max": 3400.0
|
664 |
+
},
|
665 |
+
{
|
666 |
+
"current": 2300.0,
|
667 |
+
"min": 800.0,
|
668 |
+
"max": 3400.0
|
669 |
+
},
|
670 |
+
{
|
671 |
+
"current": 2300.0,
|
672 |
+
"min": 800.0,
|
673 |
+
"max": 3400.0
|
674 |
+
},
|
675 |
+
{
|
676 |
+
"current": 2300.0,
|
677 |
+
"min": 800.0,
|
678 |
+
"max": 3400.0
|
679 |
+
},
|
680 |
+
{
|
681 |
+
"current": 2300.0,
|
682 |
+
"min": 800.0,
|
683 |
+
"max": 3400.0
|
684 |
+
},
|
685 |
+
{
|
686 |
+
"current": 2300.0,
|
687 |
+
"min": 800.0,
|
688 |
+
"max": 3400.0
|
689 |
+
},
|
690 |
+
{
|
691 |
+
"current": 2300.0,
|
692 |
+
"min": 800.0,
|
693 |
+
"max": 3400.0
|
694 |
+
},
|
695 |
+
{
|
696 |
+
"current": 2300.0,
|
697 |
+
"min": 800.0,
|
698 |
+
"max": 3400.0
|
699 |
+
},
|
700 |
+
{
|
701 |
+
"current": 2300.0,
|
702 |
+
"min": 800.0,
|
703 |
+
"max": 3400.0
|
704 |
+
},
|
705 |
+
{
|
706 |
+
"current": 2300.0,
|
707 |
+
"min": 800.0,
|
708 |
+
"max": 3400.0
|
709 |
+
},
|
710 |
+
{
|
711 |
+
"current": 2300.0,
|
712 |
+
"min": 800.0,
|
713 |
+
"max": 3400.0
|
714 |
+
},
|
715 |
+
{
|
716 |
+
"current": 2300.0,
|
717 |
+
"min": 800.0,
|
718 |
+
"max": 3400.0
|
719 |
+
},
|
720 |
+
{
|
721 |
+
"current": 2300.0,
|
722 |
+
"min": 800.0,
|
723 |
+
"max": 3400.0
|
724 |
+
},
|
725 |
+
{
|
726 |
+
"current": 2300.0,
|
727 |
+
"min": 800.0,
|
728 |
+
"max": 3400.0
|
729 |
+
},
|
730 |
+
{
|
731 |
+
"current": 2300.0,
|
732 |
+
"min": 800.0,
|
733 |
+
"max": 3400.0
|
734 |
+
},
|
735 |
+
{
|
736 |
+
"current": 2300.0,
|
737 |
+
"min": 800.0,
|
738 |
+
"max": 3400.0
|
739 |
+
},
|
740 |
+
{
|
741 |
+
"current": 2300.0,
|
742 |
+
"min": 800.0,
|
743 |
+
"max": 3400.0
|
744 |
+
},
|
745 |
+
{
|
746 |
+
"current": 2300.0,
|
747 |
+
"min": 800.0,
|
748 |
+
"max": 3400.0
|
749 |
+
},
|
750 |
+
{
|
751 |
+
"current": 2300.0,
|
752 |
+
"min": 800.0,
|
753 |
+
"max": 3400.0
|
754 |
+
},
|
755 |
+
{
|
756 |
+
"current": 2300.0,
|
757 |
+
"min": 800.0,
|
758 |
+
"max": 3400.0
|
759 |
+
},
|
760 |
+
{
|
761 |
+
"current": 2300.0,
|
762 |
+
"min": 800.0,
|
763 |
+
"max": 3400.0
|
764 |
+
},
|
765 |
+
{
|
766 |
+
"current": 2300.0,
|
767 |
+
"min": 800.0,
|
768 |
+
"max": 3400.0
|
769 |
+
},
|
770 |
+
{
|
771 |
+
"current": 2300.0,
|
772 |
+
"min": 800.0,
|
773 |
+
"max": 3400.0
|
774 |
+
},
|
775 |
+
{
|
776 |
+
"current": 2300.0,
|
777 |
+
"min": 800.0,
|
778 |
+
"max": 3400.0
|
779 |
+
},
|
780 |
+
{
|
781 |
+
"current": 2300.0,
|
782 |
+
"min": 800.0,
|
783 |
+
"max": 3400.0
|
784 |
+
},
|
785 |
+
{
|
786 |
+
"current": 2300.0,
|
787 |
+
"min": 800.0,
|
788 |
+
"max": 3400.0
|
789 |
+
},
|
790 |
+
{
|
791 |
+
"current": 2300.0,
|
792 |
+
"min": 800.0,
|
793 |
+
"max": 3400.0
|
794 |
+
},
|
795 |
+
{
|
796 |
+
"current": 2300.0,
|
797 |
+
"min": 800.0,
|
798 |
+
"max": 3400.0
|
799 |
+
},
|
800 |
+
{
|
801 |
+
"current": 2300.0,
|
802 |
+
"min": 800.0,
|
803 |
+
"max": 3400.0
|
804 |
+
},
|
805 |
+
{
|
806 |
+
"current": 2300.0,
|
807 |
+
"min": 800.0,
|
808 |
+
"max": 3400.0
|
809 |
+
},
|
810 |
+
{
|
811 |
+
"current": 2300.0,
|
812 |
+
"min": 800.0,
|
813 |
+
"max": 3400.0
|
814 |
+
},
|
815 |
+
{
|
816 |
+
"current": 2300.0,
|
817 |
+
"min": 800.0,
|
818 |
+
"max": 3400.0
|
819 |
+
},
|
820 |
+
{
|
821 |
+
"current": 2300.0,
|
822 |
+
"min": 800.0,
|
823 |
+
"max": 3400.0
|
824 |
+
},
|
825 |
+
{
|
826 |
+
"current": 2300.0,
|
827 |
+
"min": 800.0,
|
828 |
+
"max": 3400.0
|
829 |
+
},
|
830 |
+
{
|
831 |
+
"current": 2300.0,
|
832 |
+
"min": 800.0,
|
833 |
+
"max": 3400.0
|
834 |
+
},
|
835 |
+
{
|
836 |
+
"current": 2300.0,
|
837 |
+
"min": 800.0,
|
838 |
+
"max": 3400.0
|
839 |
+
}
|
840 |
+
],
|
841 |
+
"disk": {
|
842 |
+
"/": {
|
843 |
+
"total": 877.6341285705566,
|
844 |
+
"used": 192.04769897460938
|
845 |
+
}
|
846 |
+
},
|
847 |
+
"memory": {
|
848 |
+
"total": 1007.4379920959473
|
849 |
+
}
|
850 |
+
}
|
lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/files/wandb-summary.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"winogrande/alias": "winogrande", "sst2/alias": "sst2", "piqa/alias": "piqa", "mrpc/alias": "mrpc", "copa/alias": "copa", "boolq/alias": "boolq", "arc_easy/alias": "arc_easy", "winogrande/acc": 0.4861878453038674, "winogrande/acc_stderr": 0.014047122916440422, "sst2/acc": 0.49655963302752293, "sst2/acc_stderr": 0.01694145263275272, "piqa/acc": 0.5136017410228509, "piqa/acc_stderr": 0.011661506839823784, "piqa/acc_norm": 0.48258977149075083, "piqa/acc_norm_stderr": 0.011658749823107691, "mrpc/acc": 0.3161764705882353, "mrpc/acc_stderr": 0.023048336668420193, "mrpc/f1": 0.0, "mrpc/f1_stderr": 0.0, "copa/acc": 0.6, "copa/acc_stderr": 0.04923659639173309, "boolq/acc": 0.37767584097859325, "boolq/acc_stderr": 0.008479309208281641, "arc_easy/acc": 0.2529461279461279, "arc_easy/acc_stderr": 0.008919862739165604, "arc_easy/acc_norm": 0.25336700336700335, "arc_easy/acc_norm_stderr": 0.008924765424529262, "_timestamp": 1717077579.812849, "_runtime": 3612.01855802536, "_step": 1, "evaluation/eval_results": {"_type": "table-file", "sha256": "9c87687b44ab0685fb7b82fd3443388298eab88292dc5e23c9e733bbb322fcf7", "size": 745, "artifact_path": "wandb-client-artifact://q2v1w3zvymy8k8uhe93sh5q1kn94qlo75741qs0gdb04jaxw3v7s6hsbks2131rq1h6xrs8d68kzir7yv1uaa3ngkqwebvmlsa8x6e5g2yqr8kiinzxbhs2f82ljl0z1/evaluation/eval_results.table.json", "_latest_artifact_path": "wandb-client-artifact://o4hc2so4usqygkby5rqx32e25cxz4719vlailyndzwfasbzvlvwgjwagn5u97f3crzvwj247srg4p977iahqwz9uj7pttf8o5so39ui7iwdgybxn8al5mp3hwsowe4wc:latest/evaluation/eval_results.table.json", "path": "media/table/evaluation/eval_results_1_9c87687b44ab0685fb7b.table.json", "ncols": 7, "nrows": 10}, "_wandb": {"runtime": 3611}}
|
lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/logs/debug-internal.log
ADDED
The diff for this file is too large to render.
See raw diff
|
|
lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/logs/debug.log
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
2024-05-30 12:59:27,788 INFO MainThread:744 [wandb_setup.py:_flush():76] Current SDK version is 0.17.0
|
2 |
+
2024-05-30 12:59:27,788 INFO MainThread:744 [wandb_setup.py:_flush():76] Configure stats pid to 744
|
3 |
+
2024-05-30 12:59:27,788 INFO MainThread:744 [wandb_setup.py:_flush():76] Loading settings from /root/.config/wandb/settings
|
4 |
+
2024-05-30 12:59:27,788 INFO MainThread:744 [wandb_setup.py:_flush():76] Loading settings from /mnt/weka/peacock/idc/cronscript/lm-evaluation-harness/wandb/settings
|
5 |
+
2024-05-30 12:59:27,788 INFO MainThread:744 [wandb_setup.py:_flush():76] Loading settings from environment variables: {}
|
6 |
+
2024-05-30 12:59:27,788 INFO MainThread:744 [wandb_setup.py:_flush():76] Applying setup settings: {'_disable_service': False}
|
7 |
+
2024-05-30 12:59:27,788 WARNING MainThread:744 [wandb_setup.py:_flush():76] Could not find program at -m lm_eval.__main__
|
8 |
+
2024-05-30 12:59:27,788 INFO MainThread:744 [wandb_setup.py:_flush():76] Inferring run settings from compute environment: {'program_relpath': None, 'program': '-m lm_eval.__main__'}
|
9 |
+
2024-05-30 12:59:27,788 INFO MainThread:744 [wandb_setup.py:_flush():76] Applying login settings: {}
|
10 |
+
2024-05-30 12:59:27,788 INFO MainThread:744 [wandb_init.py:_log_setup():520] Logging user logs to /mnt/weka/peacock/idc/cronscript/lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/logs/debug.log
|
11 |
+
2024-05-30 12:59:27,788 INFO MainThread:744 [wandb_init.py:_log_setup():521] Logging internal logs to /mnt/weka/peacock/idc/cronscript/lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/logs/debug-internal.log
|
12 |
+
2024-05-30 12:59:27,788 INFO MainThread:744 [wandb_init.py:init():560] calling init triggers
|
13 |
+
2024-05-30 12:59:27,788 INFO MainThread:744 [wandb_init.py:init():567] wandb.init called with sweep_config: {}
|
14 |
+
config: {}
|
15 |
+
2024-05-30 12:59:27,788 INFO MainThread:744 [wandb_init.py:init():610] starting backend
|
16 |
+
2024-05-30 12:59:27,788 INFO MainThread:744 [wandb_init.py:init():614] setting up manager
|
17 |
+
2024-05-30 12:59:27,792 INFO MainThread:744 [backend.py:_multiprocessing_setup():105] multiprocessing start_methods=fork,spawn,forkserver, using: spawn
|
18 |
+
2024-05-30 12:59:27,794 INFO MainThread:744 [wandb_init.py:init():622] backend started and connected
|
19 |
+
2024-05-30 12:59:27,797 INFO MainThread:744 [wandb_init.py:init():711] updated telemetry
|
20 |
+
2024-05-30 12:59:27,806 INFO MainThread:744 [wandb_init.py:init():744] communicating run to backend with 90.0 second timeout
|
21 |
+
2024-05-30 12:59:28,069 INFO MainThread:744 [wandb_run.py:_on_init():2396] communicating current version
|
22 |
+
2024-05-30 12:59:28,181 INFO MainThread:744 [wandb_run.py:_on_init():2405] got version response
|
23 |
+
2024-05-30 12:59:28,182 INFO MainThread:744 [wandb_init.py:init():795] starting run threads in backend
|
24 |
+
2024-05-30 12:59:28,496 INFO MainThread:744 [wandb_run.py:_console_start():2374] atexit reg
|
25 |
+
2024-05-30 12:59:28,496 INFO MainThread:744 [wandb_run.py:_redirect():2229] redirect: wrap_raw
|
26 |
+
2024-05-30 12:59:28,496 INFO MainThread:744 [wandb_run.py:_redirect():2294] Wrapping output streams.
|
27 |
+
2024-05-30 12:59:28,496 INFO MainThread:744 [wandb_run.py:_redirect():2319] Redirects installed.
|
28 |
+
2024-05-30 12:59:28,497 INFO MainThread:744 [wandb_init.py:init():838] run started, returning control to user process
|
29 |
+
2024-05-30 13:59:39,187 INFO MainThread:744 [wandb_run.py:_config_callback():1376] config_cb None None {'task_configs': {'arc_easy': {'task': 'arc_easy', 'group': ['ai2_arc'], 'dataset_path': 'allenai/ai2_arc', 'dataset_name': 'ARC-Easy', 'training_split': 'train', 'validation_split': 'validation', 'test_split': 'test', 'doc_to_text': 'Question: {{question}}\nAnswer:', 'doc_to_target': '{{choices.label.index(answerKey)}}', 'doc_to_choice': '{{choices.text}}', 'description': '', 'target_delimiter': ' ', 'fewshot_delimiter': '\n\n', 'num_fewshot': 0, 'metric_list': [{'metric': 'acc', 'aggregation': 'mean', 'higher_is_better': True}, {'metric': 'acc_norm', 'aggregation': 'mean', 'higher_is_better': True}], 'output_type': 'multiple_choice', 'repeats': 1, 'should_decontaminate': True, 'doc_to_decontamination_query': 'Question: {{question}}\nAnswer:', 'metadata': {'version': 1.0}}, 'boolq': {'task': 'boolq', 'group': ['super-glue-lm-eval-v1'], 'dataset_path': 'super_glue', 'dataset_name': 'boolq', 'training_split': 'train', 'validation_split': 'validation', 'doc_to_text': '{{passage}}\nQuestion: {{question}}?\nAnswer:', 'doc_to_target': 'label', 'doc_to_choice': ['no', 'yes'], 'description': '', 'target_delimiter': ' ', 'fewshot_delimiter': '\n\n', 'num_fewshot': 0, 'metric_list': [{'metric': 'acc'}], 'output_type': 'multiple_choice', 'repeats': 1, 'should_decontaminate': True, 'doc_to_decontamination_query': 'passage', 'metadata': {'version': 2.0}}, 'copa': {'task': 'copa', 'group': ['super-glue-lm-eval-v1'], 'dataset_path': 'super_glue', 'dataset_name': 'copa', 'training_split': 'train', 'validation_split': 'validation', 'doc_to_text': 'def doc_to_text(doc):\n # Drop the period\n connector = {\n "cause": "because",\n "effect": "therefore",\n }[doc["question"]]\n return doc["premise"].strip()[:-1] + f" {connector}"\n', 'doc_to_target': 'def doc_to_target(doc):\n correct_choice = doc["choice1"] if doc["label"] == 0 else doc["choice2"]\n # Connect the sentences\n return " " + convert_choice(correct_choice)\n', 'doc_to_choice': 'def doc_to_choice(doc):\n return [" " + convert_choice(doc["choice1"]), " " + convert_choice(doc["choice2"])]\n', 'description': '', 'target_delimiter': ' ', 'fewshot_delimiter': '\n\n', 'num_fewshot': 0, 'metric_list': [{'metric': 'acc'}], 'output_type': 'multiple_choice', 'repeats': 1, 'should_decontaminate': False, 'metadata': {'version': 1.0}}, 'mrpc': {'task': 'mrpc', 'group': 'glue', 'dataset_path': 'glue', 'dataset_name': 'mrpc', 'training_split': 'train', 'validation_split': 'validation', 'doc_to_text': 'Sentence 1: {{sentence1}}\nSentence 2: {{sentence2}}\nQuestion: Do both sentences mean the same thing?\nAnswer:', 'doc_to_target': 'label', 'doc_to_choice': ['no', 'yes'], 'description': '', 'target_delimiter': ' ', 'fewshot_delimiter': '\n\n', 'num_fewshot': 0, 'metric_list': [{'metric': 'acc'}, {'metric': 'f1'}], 'output_type': 'multiple_choice', 'repeats': 1, 'should_decontaminate': False, 'metadata': {'version': 1.0}}, 'piqa': {'task': 'piqa', 'dataset_path': 'piqa', 'training_split': 'train', 'validation_split': 'validation', 'doc_to_text': 'Question: {{goal}}\nAnswer:', 'doc_to_target': 'label', 'doc_to_choice': '{{[sol1, sol2]}}', 'description': '', 'target_delimiter': ' ', 'fewshot_delimiter': '\n\n', 'num_fewshot': 0, 'metric_list': [{'metric': 'acc', 'aggregation': 'mean', 'higher_is_better': True}, {'metric': 'acc_norm', 'aggregation': 'mean', 'higher_is_better': True}], 'output_type': 'multiple_choice', 'repeats': 1, 'should_decontaminate': True, 'doc_to_decontamination_query': 'goal', 'metadata': {'version': 1.0}}, 'sst2': {'task': 'sst2', 'group': 'glue', 'dataset_path': 'glue', 'dataset_name': 'sst2', 'training_split': 'train', 'validation_split': 'validation', 'doc_to_text': '{{sentence}}\nQuestion: Is this sentence positive or negative?\nAnswer:', 'doc_to_target': 'label', 'doc_to_choice': ['negative', 'positive'], 'description': '', 'target_delimiter': ' ', 'fewshot_delimiter': '\n\n', 'num_fewshot': 0, 'metric_list': [{'metric': 'acc'}], 'output_type': 'multiple_choice', 'repeats': 1, 'should_decontaminate': False, 'metadata': {'version': 1.0}}, 'winogrande': {'task': 'winogrande', 'dataset_path': 'winogrande', 'dataset_name': 'winogrande_xl', 'training_split': 'train', 'validation_split': 'validation', 'doc_to_text': 'def doc_to_text(doc):\n answer_to_num = {"1": 0, "2": 1}\n return answer_to_num[doc["answer"]]\n', 'doc_to_target': 'def doc_to_target(doc):\n idx = doc["sentence"].index("_") + 1\n return doc["sentence"][idx:].strip()\n', 'doc_to_choice': 'def doc_to_choice(doc):\n idx = doc["sentence"].index("_")\n options = [doc["option1"], doc["option2"]]\n return [doc["sentence"][:idx] + opt for opt in options]\n', 'description': '', 'target_delimiter': ' ', 'fewshot_delimiter': '\n\n', 'num_fewshot': 0, 'metric_list': [{'metric': 'acc', 'aggregation': 'mean', 'higher_is_better': True}], 'output_type': 'multiple_choice', 'repeats': 1, 'should_decontaminate': True, 'doc_to_decontamination_query': 'sentence', 'metadata': {'version': 1.0}}}, 'cli_configs': {'model': 'hf', 'model_args': 'pretrained=/mnt/weka/peacock/experiments/llama/eval/checkpoint-english/llamav2-3b/hf/global_step70000,tokenizer=/mnt/weka/peacock/tokenization/trained-tokenizer/enhiben_50k_hf/ConvertedTokenizer', 'batch_size': 'auto', 'batch_sizes': [64], 'device': None, 'use_cache': None, 'limit': None, 'bootstrap_iters': 100000, 'gen_kwargs': None}}
|
30 |
+
2024-05-30 13:59:40,118 INFO MainThread:744 [wandb_run.py:_finish():2103] finishing run smlgenai/english-eval/wg4623zd
|
31 |
+
2024-05-30 13:59:40,118 INFO MainThread:744 [wandb_run.py:_atexit_cleanup():2343] got exitcode: 0
|
32 |
+
2024-05-30 13:59:40,118 INFO MainThread:744 [wandb_run.py:_restore():2326] restore
|
33 |
+
2024-05-30 13:59:40,139 INFO MainThread:744 [wandb_run.py:_restore():2332] restore done
|
34 |
+
2024-05-30 13:59:46,205 INFO MainThread:744 [wandb_run.py:_footer_history_summary_info():3994] rendering history
|
35 |
+
2024-05-30 13:59:46,206 INFO MainThread:744 [wandb_run.py:_footer_history_summary_info():4026] rendering summary
|
36 |
+
2024-05-30 13:59:46,212 INFO MainThread:744 [wandb_run.py:_footer_sync_info():3953] logging synced files
|
lm-evaluation-harness/wandb/run-20240530_125927-wg4623zd/run-wg4623zd.wandb
ADDED
Binary file (966 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/align/__init__.py
ADDED
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 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 (
|
17 |
+
OptionalDependencyNotAvailable,
|
18 |
+
_LazyModule,
|
19 |
+
is_torch_available,
|
20 |
+
)
|
21 |
+
|
22 |
+
|
23 |
+
_import_structure = {
|
24 |
+
"configuration_align": [
|
25 |
+
"ALIGN_PRETRAINED_CONFIG_ARCHIVE_MAP",
|
26 |
+
"AlignConfig",
|
27 |
+
"AlignTextConfig",
|
28 |
+
"AlignVisionConfig",
|
29 |
+
],
|
30 |
+
"processing_align": ["AlignProcessor"],
|
31 |
+
}
|
32 |
+
|
33 |
+
try:
|
34 |
+
if not is_torch_available():
|
35 |
+
raise OptionalDependencyNotAvailable()
|
36 |
+
except OptionalDependencyNotAvailable:
|
37 |
+
pass
|
38 |
+
else:
|
39 |
+
_import_structure["modeling_align"] = [
|
40 |
+
"ALIGN_PRETRAINED_MODEL_ARCHIVE_LIST",
|
41 |
+
"AlignModel",
|
42 |
+
"AlignPreTrainedModel",
|
43 |
+
"AlignTextModel",
|
44 |
+
"AlignVisionModel",
|
45 |
+
]
|
46 |
+
|
47 |
+
if TYPE_CHECKING:
|
48 |
+
from .configuration_align import (
|
49 |
+
ALIGN_PRETRAINED_CONFIG_ARCHIVE_MAP,
|
50 |
+
AlignConfig,
|
51 |
+
AlignTextConfig,
|
52 |
+
AlignVisionConfig,
|
53 |
+
)
|
54 |
+
from .processing_align import AlignProcessor
|
55 |
+
|
56 |
+
try:
|
57 |
+
if not is_torch_available():
|
58 |
+
raise OptionalDependencyNotAvailable()
|
59 |
+
except OptionalDependencyNotAvailable:
|
60 |
+
pass
|
61 |
+
else:
|
62 |
+
from .modeling_align import (
|
63 |
+
ALIGN_PRETRAINED_MODEL_ARCHIVE_LIST,
|
64 |
+
AlignModel,
|
65 |
+
AlignPreTrainedModel,
|
66 |
+
AlignTextModel,
|
67 |
+
AlignVisionModel,
|
68 |
+
)
|
69 |
+
|
70 |
+
else:
|
71 |
+
import sys
|
72 |
+
|
73 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
venv/lib/python3.10/site-packages/transformers/models/align/convert_align_tf_to_hf.py
ADDED
@@ -0,0 +1,389 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
"""Convert ALIGN checkpoints from the original repository."""
|
16 |
+
|
17 |
+
import argparse
|
18 |
+
import os
|
19 |
+
|
20 |
+
import align
|
21 |
+
import numpy as np
|
22 |
+
import requests
|
23 |
+
import tensorflow as tf
|
24 |
+
import torch
|
25 |
+
from PIL import Image
|
26 |
+
from tokenizer import Tokenizer
|
27 |
+
|
28 |
+
from transformers import (
|
29 |
+
AlignConfig,
|
30 |
+
AlignModel,
|
31 |
+
AlignProcessor,
|
32 |
+
BertConfig,
|
33 |
+
BertTokenizer,
|
34 |
+
EfficientNetConfig,
|
35 |
+
EfficientNetImageProcessor,
|
36 |
+
)
|
37 |
+
from transformers.utils import logging
|
38 |
+
|
39 |
+
|
40 |
+
logging.set_verbosity_info()
|
41 |
+
logger = logging.get_logger(__name__)
|
42 |
+
|
43 |
+
|
44 |
+
def preprocess(image):
|
45 |
+
image = tf.image.resize(image, (346, 346))
|
46 |
+
image = tf.image.crop_to_bounding_box(image, (346 - 289) // 2, (346 - 289) // 2, 289, 289)
|
47 |
+
return image
|
48 |
+
|
49 |
+
|
50 |
+
def get_align_config():
|
51 |
+
vision_config = EfficientNetConfig.from_pretrained("google/efficientnet-b7")
|
52 |
+
vision_config.image_size = 289
|
53 |
+
vision_config.hidden_dim = 640
|
54 |
+
vision_config.id2label = {"0": "LABEL_0", "1": "LABEL_1"}
|
55 |
+
vision_config.label2id = {"LABEL_0": 0, "LABEL_1": 1}
|
56 |
+
vision_config.depthwise_padding = []
|
57 |
+
|
58 |
+
text_config = BertConfig()
|
59 |
+
config = AlignConfig.from_text_vision_configs(
|
60 |
+
text_config=text_config, vision_config=vision_config, projection_dim=640
|
61 |
+
)
|
62 |
+
return config
|
63 |
+
|
64 |
+
|
65 |
+
# We will verify our results on an image of cute cats
|
66 |
+
def prepare_img():
|
67 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
68 |
+
im = Image.open(requests.get(url, stream=True).raw)
|
69 |
+
return im
|
70 |
+
|
71 |
+
|
72 |
+
def get_processor():
|
73 |
+
image_processor = EfficientNetImageProcessor(
|
74 |
+
do_center_crop=True,
|
75 |
+
rescale_factor=1 / 127.5,
|
76 |
+
rescale_offset=True,
|
77 |
+
do_normalize=False,
|
78 |
+
include_top=False,
|
79 |
+
resample=Image.BILINEAR,
|
80 |
+
)
|
81 |
+
tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased")
|
82 |
+
tokenizer.model_max_length = 64
|
83 |
+
processor = AlignProcessor(image_processor=image_processor, tokenizer=tokenizer)
|
84 |
+
return processor
|
85 |
+
|
86 |
+
|
87 |
+
# here we list all keys to be renamed (original name on the left, our name on the right)
|
88 |
+
def rename_keys(original_param_names):
|
89 |
+
# EfficientNet image encoder
|
90 |
+
block_names = [v.split("_")[0].split("block")[1] for v in original_param_names if v.startswith("block")]
|
91 |
+
block_names = list(set(block_names))
|
92 |
+
block_names = sorted(block_names)
|
93 |
+
num_blocks = len(block_names)
|
94 |
+
block_name_mapping = {b: str(i) for b, i in zip(block_names, range(num_blocks))}
|
95 |
+
|
96 |
+
rename_keys = []
|
97 |
+
rename_keys.append(("stem_conv/kernel:0", "embeddings.convolution.weight"))
|
98 |
+
rename_keys.append(("stem_bn/gamma:0", "embeddings.batchnorm.weight"))
|
99 |
+
rename_keys.append(("stem_bn/beta:0", "embeddings.batchnorm.bias"))
|
100 |
+
rename_keys.append(("stem_bn/moving_mean:0", "embeddings.batchnorm.running_mean"))
|
101 |
+
rename_keys.append(("stem_bn/moving_variance:0", "embeddings.batchnorm.running_var"))
|
102 |
+
|
103 |
+
for b in block_names:
|
104 |
+
hf_b = block_name_mapping[b]
|
105 |
+
rename_keys.append((f"block{b}_expand_conv/kernel:0", f"encoder.blocks.{hf_b}.expansion.expand_conv.weight"))
|
106 |
+
rename_keys.append((f"block{b}_expand_bn/gamma:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.weight"))
|
107 |
+
rename_keys.append((f"block{b}_expand_bn/beta:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.bias"))
|
108 |
+
rename_keys.append(
|
109 |
+
(f"block{b}_expand_bn/moving_mean:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.running_mean")
|
110 |
+
)
|
111 |
+
rename_keys.append(
|
112 |
+
(f"block{b}_expand_bn/moving_variance:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.running_var")
|
113 |
+
)
|
114 |
+
rename_keys.append(
|
115 |
+
(f"block{b}_dwconv/depthwise_kernel:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight")
|
116 |
+
)
|
117 |
+
rename_keys.append((f"block{b}_bn/gamma:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight"))
|
118 |
+
rename_keys.append((f"block{b}_bn/beta:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias"))
|
119 |
+
rename_keys.append(
|
120 |
+
(f"block{b}_bn/moving_mean:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean")
|
121 |
+
)
|
122 |
+
rename_keys.append(
|
123 |
+
(f"block{b}_bn/moving_variance:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var")
|
124 |
+
)
|
125 |
+
|
126 |
+
rename_keys.append((f"block{b}_se_reduce/kernel:0", f"encoder.blocks.{hf_b}.squeeze_excite.reduce.weight"))
|
127 |
+
rename_keys.append((f"block{b}_se_reduce/bias:0", f"encoder.blocks.{hf_b}.squeeze_excite.reduce.bias"))
|
128 |
+
rename_keys.append((f"block{b}_se_expand/kernel:0", f"encoder.blocks.{hf_b}.squeeze_excite.expand.weight"))
|
129 |
+
rename_keys.append((f"block{b}_se_expand/bias:0", f"encoder.blocks.{hf_b}.squeeze_excite.expand.bias"))
|
130 |
+
rename_keys.append(
|
131 |
+
(f"block{b}_project_conv/kernel:0", f"encoder.blocks.{hf_b}.projection.project_conv.weight")
|
132 |
+
)
|
133 |
+
rename_keys.append((f"block{b}_project_bn/gamma:0", f"encoder.blocks.{hf_b}.projection.project_bn.weight"))
|
134 |
+
rename_keys.append((f"block{b}_project_bn/beta:0", f"encoder.blocks.{hf_b}.projection.project_bn.bias"))
|
135 |
+
rename_keys.append(
|
136 |
+
(f"block{b}_project_bn/moving_mean:0", f"encoder.blocks.{hf_b}.projection.project_bn.running_mean")
|
137 |
+
)
|
138 |
+
rename_keys.append(
|
139 |
+
(f"block{b}_project_bn/moving_variance:0", f"encoder.blocks.{hf_b}.projection.project_bn.running_var")
|
140 |
+
)
|
141 |
+
|
142 |
+
key_mapping = {}
|
143 |
+
for item in rename_keys:
|
144 |
+
if item[0] in original_param_names:
|
145 |
+
key_mapping[item[0]] = "vision_model." + item[1]
|
146 |
+
|
147 |
+
# BERT text encoder
|
148 |
+
rename_keys = []
|
149 |
+
old = "tf_bert_model/bert"
|
150 |
+
new = "text_model"
|
151 |
+
for i in range(12):
|
152 |
+
rename_keys.append(
|
153 |
+
(
|
154 |
+
f"{old}/encoder/layer_._{i}/attention/self/query/kernel:0",
|
155 |
+
f"{new}.encoder.layer.{i}.attention.self.query.weight",
|
156 |
+
)
|
157 |
+
)
|
158 |
+
rename_keys.append(
|
159 |
+
(
|
160 |
+
f"{old}/encoder/layer_._{i}/attention/self/query/bias:0",
|
161 |
+
f"{new}.encoder.layer.{i}.attention.self.query.bias",
|
162 |
+
)
|
163 |
+
)
|
164 |
+
rename_keys.append(
|
165 |
+
(
|
166 |
+
f"{old}/encoder/layer_._{i}/attention/self/key/kernel:0",
|
167 |
+
f"{new}.encoder.layer.{i}.attention.self.key.weight",
|
168 |
+
)
|
169 |
+
)
|
170 |
+
rename_keys.append(
|
171 |
+
(
|
172 |
+
f"{old}/encoder/layer_._{i}/attention/self/key/bias:0",
|
173 |
+
f"{new}.encoder.layer.{i}.attention.self.key.bias",
|
174 |
+
)
|
175 |
+
)
|
176 |
+
rename_keys.append(
|
177 |
+
(
|
178 |
+
f"{old}/encoder/layer_._{i}/attention/self/value/kernel:0",
|
179 |
+
f"{new}.encoder.layer.{i}.attention.self.value.weight",
|
180 |
+
)
|
181 |
+
)
|
182 |
+
rename_keys.append(
|
183 |
+
(
|
184 |
+
f"{old}/encoder/layer_._{i}/attention/self/value/bias:0",
|
185 |
+
f"{new}.encoder.layer.{i}.attention.self.value.bias",
|
186 |
+
)
|
187 |
+
)
|
188 |
+
rename_keys.append(
|
189 |
+
(
|
190 |
+
f"{old}/encoder/layer_._{i}/attention/output/dense/kernel:0",
|
191 |
+
f"{new}.encoder.layer.{i}.attention.output.dense.weight",
|
192 |
+
)
|
193 |
+
)
|
194 |
+
rename_keys.append(
|
195 |
+
(
|
196 |
+
f"{old}/encoder/layer_._{i}/attention/output/dense/bias:0",
|
197 |
+
f"{new}.encoder.layer.{i}.attention.output.dense.bias",
|
198 |
+
)
|
199 |
+
)
|
200 |
+
rename_keys.append(
|
201 |
+
(
|
202 |
+
f"{old}/encoder/layer_._{i}/attention/output/LayerNorm/gamma:0",
|
203 |
+
f"{new}.encoder.layer.{i}.attention.output.LayerNorm.weight",
|
204 |
+
)
|
205 |
+
)
|
206 |
+
rename_keys.append(
|
207 |
+
(
|
208 |
+
f"{old}/encoder/layer_._{i}/attention/output/LayerNorm/beta:0",
|
209 |
+
f"{new}.encoder.layer.{i}.attention.output.LayerNorm.bias",
|
210 |
+
)
|
211 |
+
)
|
212 |
+
rename_keys.append(
|
213 |
+
(
|
214 |
+
f"{old}/encoder/layer_._{i}/intermediate/dense/kernel:0",
|
215 |
+
f"{new}.encoder.layer.{i}.intermediate.dense.weight",
|
216 |
+
)
|
217 |
+
)
|
218 |
+
rename_keys.append(
|
219 |
+
(
|
220 |
+
f"{old}/encoder/layer_._{i}/intermediate/dense/bias:0",
|
221 |
+
f"{new}.encoder.layer.{i}.intermediate.dense.bias",
|
222 |
+
)
|
223 |
+
)
|
224 |
+
rename_keys.append(
|
225 |
+
(f"{old}/encoder/layer_._{i}/output/dense/kernel:0", f"{new}.encoder.layer.{i}.output.dense.weight")
|
226 |
+
)
|
227 |
+
rename_keys.append(
|
228 |
+
(f"{old}/encoder/layer_._{i}/output/dense/bias:0", f"{new}.encoder.layer.{i}.output.dense.bias")
|
229 |
+
)
|
230 |
+
rename_keys.append(
|
231 |
+
(f"{old}/encoder/layer_._{i}/output/LayerNorm/gamma:0", f"{new}.encoder.layer.{i}.output.LayerNorm.weight")
|
232 |
+
)
|
233 |
+
rename_keys.append(
|
234 |
+
(f"{old}/encoder/layer_._{i}/output/LayerNorm/beta:0", f"{new}.encoder.layer.{i}.output.LayerNorm.bias")
|
235 |
+
)
|
236 |
+
|
237 |
+
rename_keys.append((f"{old}/embeddings/word_embeddings/weight:0", f"{new}.embeddings.word_embeddings.weight"))
|
238 |
+
rename_keys.append(
|
239 |
+
(f"{old}/embeddings/position_embeddings/embeddings:0", f"{new}.embeddings.position_embeddings.weight")
|
240 |
+
)
|
241 |
+
rename_keys.append(
|
242 |
+
(f"{old}/embeddings/token_type_embeddings/embeddings:0", f"{new}.embeddings.token_type_embeddings.weight")
|
243 |
+
)
|
244 |
+
rename_keys.append((f"{old}/embeddings/LayerNorm/gamma:0", f"{new}.embeddings.LayerNorm.weight"))
|
245 |
+
rename_keys.append((f"{old}/embeddings/LayerNorm/beta:0", f"{new}.embeddings.LayerNorm.bias"))
|
246 |
+
|
247 |
+
rename_keys.append((f"{old}/pooler/dense/kernel:0", f"{new}.pooler.dense.weight"))
|
248 |
+
rename_keys.append((f"{old}/pooler/dense/bias:0", f"{new}.pooler.dense.bias"))
|
249 |
+
rename_keys.append(("dense/kernel:0", "text_projection.weight"))
|
250 |
+
rename_keys.append(("dense/bias:0", "text_projection.bias"))
|
251 |
+
rename_keys.append(("dense/bias:0", "text_projection.bias"))
|
252 |
+
rename_keys.append(("temperature:0", "temperature"))
|
253 |
+
|
254 |
+
for item in rename_keys:
|
255 |
+
if item[0] in original_param_names:
|
256 |
+
key_mapping[item[0]] = item[1]
|
257 |
+
return key_mapping
|
258 |
+
|
259 |
+
|
260 |
+
def replace_params(hf_params, tf_params, key_mapping):
|
261 |
+
list(hf_params.keys())
|
262 |
+
|
263 |
+
for key, value in tf_params.items():
|
264 |
+
if key not in key_mapping:
|
265 |
+
continue
|
266 |
+
|
267 |
+
hf_key = key_mapping[key]
|
268 |
+
if "_conv" in key and "kernel" in key:
|
269 |
+
new_hf_value = torch.from_numpy(value).permute(3, 2, 0, 1)
|
270 |
+
elif "embeddings" in key:
|
271 |
+
new_hf_value = torch.from_numpy(value)
|
272 |
+
elif "depthwise_kernel" in key:
|
273 |
+
new_hf_value = torch.from_numpy(value).permute(2, 3, 0, 1)
|
274 |
+
elif "kernel" in key:
|
275 |
+
new_hf_value = torch.from_numpy(np.transpose(value))
|
276 |
+
elif "temperature" in key:
|
277 |
+
new_hf_value = value
|
278 |
+
elif "bn/gamma" or "bn/beta" in key:
|
279 |
+
new_hf_value = torch.from_numpy(np.transpose(value)).squeeze()
|
280 |
+
else:
|
281 |
+
new_hf_value = torch.from_numpy(value)
|
282 |
+
|
283 |
+
# Replace HF parameters with original TF model parameters
|
284 |
+
hf_params[hf_key].copy_(new_hf_value)
|
285 |
+
|
286 |
+
|
287 |
+
@torch.no_grad()
|
288 |
+
def convert_align_checkpoint(checkpoint_path, pytorch_dump_folder_path, save_model, push_to_hub):
|
289 |
+
"""
|
290 |
+
Copy/paste/tweak model's weights to our ALIGN structure.
|
291 |
+
"""
|
292 |
+
# Load original model
|
293 |
+
seq_length = 64
|
294 |
+
tok = Tokenizer(seq_length)
|
295 |
+
original_model = align.Align("efficientnet-b7", "bert-base", 640, seq_length, tok.get_vocab_size())
|
296 |
+
original_model.compile()
|
297 |
+
original_model.load_weights(checkpoint_path)
|
298 |
+
|
299 |
+
tf_params = original_model.trainable_variables
|
300 |
+
tf_non_train_params = original_model.non_trainable_variables
|
301 |
+
tf_params = {param.name: param.numpy() for param in tf_params}
|
302 |
+
for param in tf_non_train_params:
|
303 |
+
tf_params[param.name] = param.numpy()
|
304 |
+
tf_param_names = list(tf_params.keys())
|
305 |
+
|
306 |
+
# Load HuggingFace model
|
307 |
+
config = get_align_config()
|
308 |
+
hf_model = AlignModel(config).eval()
|
309 |
+
hf_params = hf_model.state_dict()
|
310 |
+
|
311 |
+
# Create src-to-dst parameter name mapping dictionary
|
312 |
+
print("Converting parameters...")
|
313 |
+
key_mapping = rename_keys(tf_param_names)
|
314 |
+
replace_params(hf_params, tf_params, key_mapping)
|
315 |
+
|
316 |
+
# Initialize processor
|
317 |
+
processor = get_processor()
|
318 |
+
inputs = processor(
|
319 |
+
images=prepare_img(), text="A picture of a cat", padding="max_length", max_length=64, return_tensors="pt"
|
320 |
+
)
|
321 |
+
|
322 |
+
# HF model inference
|
323 |
+
hf_model.eval()
|
324 |
+
with torch.no_grad():
|
325 |
+
outputs = hf_model(**inputs)
|
326 |
+
|
327 |
+
hf_image_features = outputs.image_embeds.detach().numpy()
|
328 |
+
hf_text_features = outputs.text_embeds.detach().numpy()
|
329 |
+
|
330 |
+
# Original model inference
|
331 |
+
original_model.trainable = False
|
332 |
+
tf_image_processor = EfficientNetImageProcessor(
|
333 |
+
do_center_crop=True,
|
334 |
+
do_rescale=False,
|
335 |
+
do_normalize=False,
|
336 |
+
include_top=False,
|
337 |
+
resample=Image.BILINEAR,
|
338 |
+
)
|
339 |
+
image = tf_image_processor(images=prepare_img(), return_tensors="tf", data_format="channels_last")["pixel_values"]
|
340 |
+
text = tok(tf.constant(["A picture of a cat"]))
|
341 |
+
|
342 |
+
image_features = original_model.image_encoder(image, training=False)
|
343 |
+
text_features = original_model.text_encoder(text, training=False)
|
344 |
+
|
345 |
+
image_features = tf.nn.l2_normalize(image_features, axis=-1)
|
346 |
+
text_features = tf.nn.l2_normalize(text_features, axis=-1)
|
347 |
+
|
348 |
+
# Check whether original and HF model outputs match -> np.allclose
|
349 |
+
if not np.allclose(image_features, hf_image_features, atol=1e-3):
|
350 |
+
raise ValueError("The predicted image features are not the same.")
|
351 |
+
if not np.allclose(text_features, hf_text_features, atol=1e-3):
|
352 |
+
raise ValueError("The predicted text features are not the same.")
|
353 |
+
print("Model outputs match!")
|
354 |
+
|
355 |
+
if save_model:
|
356 |
+
# Create folder to save model
|
357 |
+
if not os.path.isdir(pytorch_dump_folder_path):
|
358 |
+
os.mkdir(pytorch_dump_folder_path)
|
359 |
+
# Save converted model and image processor
|
360 |
+
hf_model.save_pretrained(pytorch_dump_folder_path)
|
361 |
+
processor.save_pretrained(pytorch_dump_folder_path)
|
362 |
+
|
363 |
+
if push_to_hub:
|
364 |
+
# Push model and image processor to hub
|
365 |
+
print("Pushing converted ALIGN to the hub...")
|
366 |
+
processor.push_to_hub("align-base")
|
367 |
+
hf_model.push_to_hub("align-base")
|
368 |
+
|
369 |
+
|
370 |
+
if __name__ == "__main__":
|
371 |
+
parser = argparse.ArgumentParser()
|
372 |
+
# Required parameters
|
373 |
+
parser.add_argument(
|
374 |
+
"--checkpoint_path",
|
375 |
+
default="./weights/model-weights",
|
376 |
+
type=str,
|
377 |
+
help="Path to the pretrained TF ALIGN checkpoint.",
|
378 |
+
)
|
379 |
+
parser.add_argument(
|
380 |
+
"--pytorch_dump_folder_path",
|
381 |
+
default="hf_model",
|
382 |
+
type=str,
|
383 |
+
help="Path to the output PyTorch model directory.",
|
384 |
+
)
|
385 |
+
parser.add_argument("--save_model", action="store_true", help="Save model to local")
|
386 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Push model and image processor to the hub")
|
387 |
+
|
388 |
+
args = parser.parse_args()
|
389 |
+
convert_align_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)
|
venv/lib/python3.10/site-packages/transformers/models/bridgetower/__init__.py
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 The Intel Labs Team Authors, The Microsoft Research Team Authors and HuggingFace Inc. 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 OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
|
17 |
+
|
18 |
+
|
19 |
+
_import_structure = {
|
20 |
+
"configuration_bridgetower": [
|
21 |
+
"BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP",
|
22 |
+
"BridgeTowerConfig",
|
23 |
+
"BridgeTowerTextConfig",
|
24 |
+
"BridgeTowerVisionConfig",
|
25 |
+
],
|
26 |
+
"processing_bridgetower": ["BridgeTowerProcessor"],
|
27 |
+
}
|
28 |
+
|
29 |
+
try:
|
30 |
+
if not is_vision_available():
|
31 |
+
raise OptionalDependencyNotAvailable()
|
32 |
+
except OptionalDependencyNotAvailable:
|
33 |
+
pass
|
34 |
+
else:
|
35 |
+
_import_structure["image_processing_bridgetower"] = ["BridgeTowerImageProcessor"]
|
36 |
+
|
37 |
+
try:
|
38 |
+
if not is_torch_available():
|
39 |
+
raise OptionalDependencyNotAvailable()
|
40 |
+
except OptionalDependencyNotAvailable:
|
41 |
+
pass
|
42 |
+
else:
|
43 |
+
_import_structure["modeling_bridgetower"] = [
|
44 |
+
"BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST",
|
45 |
+
"BridgeTowerForContrastiveLearning",
|
46 |
+
"BridgeTowerForImageAndTextRetrieval",
|
47 |
+
"BridgeTowerForMaskedLM",
|
48 |
+
"BridgeTowerModel",
|
49 |
+
"BridgeTowerPreTrainedModel",
|
50 |
+
]
|
51 |
+
|
52 |
+
|
53 |
+
if TYPE_CHECKING:
|
54 |
+
from .configuration_bridgetower import (
|
55 |
+
BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP,
|
56 |
+
BridgeTowerConfig,
|
57 |
+
BridgeTowerTextConfig,
|
58 |
+
BridgeTowerVisionConfig,
|
59 |
+
)
|
60 |
+
from .processing_bridgetower import BridgeTowerProcessor
|
61 |
+
|
62 |
+
try:
|
63 |
+
if not is_vision_available():
|
64 |
+
raise OptionalDependencyNotAvailable()
|
65 |
+
except OptionalDependencyNotAvailable:
|
66 |
+
pass
|
67 |
+
else:
|
68 |
+
from .image_processing_bridgetower import BridgeTowerImageProcessor
|
69 |
+
|
70 |
+
try:
|
71 |
+
if not is_torch_available():
|
72 |
+
raise OptionalDependencyNotAvailable()
|
73 |
+
except OptionalDependencyNotAvailable:
|
74 |
+
pass
|
75 |
+
else:
|
76 |
+
from .modeling_bridgetower import (
|
77 |
+
BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST,
|
78 |
+
BridgeTowerForContrastiveLearning,
|
79 |
+
BridgeTowerForImageAndTextRetrieval,
|
80 |
+
BridgeTowerForMaskedLM,
|
81 |
+
BridgeTowerModel,
|
82 |
+
BridgeTowerPreTrainedModel,
|
83 |
+
)
|
84 |
+
|
85 |
+
|
86 |
+
else:
|
87 |
+
import sys
|
88 |
+
|
89 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure)
|
venv/lib/python3.10/site-packages/transformers/models/bridgetower/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.39 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/bridgetower/__pycache__/configuration_bridgetower.cpython-310.pyc
ADDED
Binary file (13.8 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/bridgetower/__pycache__/image_processing_bridgetower.cpython-310.pyc
ADDED
Binary file (21.7 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/bridgetower/__pycache__/modeling_bridgetower.cpython-310.pyc
ADDED
Binary file (58.5 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/bridgetower/__pycache__/processing_bridgetower.cpython-310.pyc
ADDED
Binary file (4.23 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/bridgetower/configuration_bridgetower.py
ADDED
@@ -0,0 +1,349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 The Intel Labs Team Authors, The Microsoft Research Team Authors and 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 |
+
""" BridgeTower model configuration"""
|
16 |
+
|
17 |
+
import os
|
18 |
+
from typing import Union
|
19 |
+
|
20 |
+
from ...configuration_utils import PretrainedConfig
|
21 |
+
from ...utils import logging
|
22 |
+
|
23 |
+
|
24 |
+
logger = logging.get_logger(__name__)
|
25 |
+
|
26 |
+
|
27 |
+
from ..deprecated._archive_maps import BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP # noqa: F401, E402
|
28 |
+
|
29 |
+
|
30 |
+
class BridgeTowerVisionConfig(PretrainedConfig):
|
31 |
+
r"""
|
32 |
+
This is the configuration class to store the vision configuration of a [`BridgeTowerModel`]. Instantiating a
|
33 |
+
configuration with the defaults will yield a similar configuration to that of the bridgetower-base
|
34 |
+
[BridgeTower/bridgetower-base](https://huggingface.co/BridgeTower/bridgetower-base/) architecture.
|
35 |
+
|
36 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
37 |
+
documentation from [`PretrainedConfig`] for more information.
|
38 |
+
|
39 |
+
Args:
|
40 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
41 |
+
Dimensionality of the encoder layers and the pooler layer.
|
42 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
43 |
+
Number of hidden layers in visual encoder model.
|
44 |
+
patch_size (`int`, *optional*, defaults to 16):
|
45 |
+
The size (resolution) of each patch.
|
46 |
+
image_size (`int`, *optional*, defaults to 288):
|
47 |
+
The size (resolution) of each image.
|
48 |
+
initializer_factor (`float`, *optional*, defaults to 1):
|
49 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
50 |
+
testing).
|
51 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
|
52 |
+
The epsilon used by the layer normalization layers.
|
53 |
+
stop_gradient (`bool`, *optional*, defaults to `False`):
|
54 |
+
Whether to stop gradient for training.
|
55 |
+
share_layernorm (`bool`, *optional*, defaults to `True`):
|
56 |
+
Whether LayerNorm layers are shared.
|
57 |
+
remove_last_layer (`bool`, *optional*, defaults to `False`):
|
58 |
+
Whether to remove the last layer from the vision encoder.
|
59 |
+
|
60 |
+
|
61 |
+
Example:
|
62 |
+
|
63 |
+
```python
|
64 |
+
>>> from transformers import BridgeTowerVisionConfig
|
65 |
+
|
66 |
+
>>> # Initializing a BridgeTower BridgeTower/bridgetower-base style configuration for the vision model
|
67 |
+
>>> configuration = BridgeTowerVisionConfig()
|
68 |
+
|
69 |
+
>>> # Accessing the configuration
|
70 |
+
>>> configuration
|
71 |
+
```"""
|
72 |
+
|
73 |
+
model_type = "bridgetower_vision_model"
|
74 |
+
|
75 |
+
def __init__(
|
76 |
+
self,
|
77 |
+
hidden_size=768,
|
78 |
+
num_hidden_layers=12,
|
79 |
+
num_channels=3,
|
80 |
+
patch_size=16,
|
81 |
+
image_size=288,
|
82 |
+
initializer_factor=1,
|
83 |
+
layer_norm_eps=1e-05,
|
84 |
+
stop_gradient=False,
|
85 |
+
share_layernorm=True,
|
86 |
+
remove_last_layer=False,
|
87 |
+
**kwargs,
|
88 |
+
):
|
89 |
+
super().__init__(**kwargs)
|
90 |
+
self.hidden_size = hidden_size
|
91 |
+
self.num_hidden_layers = num_hidden_layers
|
92 |
+
self.num_channels = num_channels
|
93 |
+
self.patch_size = patch_size
|
94 |
+
self.image_size = image_size
|
95 |
+
self.initializer_factor = initializer_factor
|
96 |
+
self.layer_norm_eps = layer_norm_eps
|
97 |
+
self.stop_gradient = stop_gradient
|
98 |
+
self.share_layernorm = share_layernorm
|
99 |
+
self.remove_last_layer = remove_last_layer
|
100 |
+
|
101 |
+
@classmethod
|
102 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
103 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
104 |
+
|
105 |
+
if config_dict.get("model_type") == "bridgetower":
|
106 |
+
config_dict = config_dict["text_config"]
|
107 |
+
|
108 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
109 |
+
logger.warning(
|
110 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
111 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
112 |
+
)
|
113 |
+
|
114 |
+
return cls.from_dict(config_dict, **kwargs)
|
115 |
+
|
116 |
+
|
117 |
+
class BridgeTowerTextConfig(PretrainedConfig):
|
118 |
+
r"""
|
119 |
+
This is the configuration class to store the text configuration of a [`BridgeTowerModel`]. The default values here
|
120 |
+
are copied from RoBERTa. Instantiating a configuration with the defaults will yield a similar configuration to that
|
121 |
+
of the bridgetower-base [BridegTower/bridgetower-base](https://huggingface.co/BridgeTower/bridgetower-base/)
|
122 |
+
architecture.
|
123 |
+
|
124 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
125 |
+
documentation from [`PretrainedConfig`] for more information.
|
126 |
+
|
127 |
+
Args:
|
128 |
+
vocab_size (`int`, *optional*, defaults to 50265):
|
129 |
+
Vocabulary size of the text part of the model. Defines the number of different tokens that can be
|
130 |
+
represented by the `inputs_ids` passed when calling [`BridgeTowerModel`].
|
131 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
132 |
+
Dimensionality of the encoder layers and the pooler layer.
|
133 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
134 |
+
Number of hidden layers in the Transformer encoder.
|
135 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
136 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
137 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
138 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
139 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
|
140 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
141 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
142 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
143 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
144 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
145 |
+
The dropout ratio for the attention probabilities.
|
146 |
+
max_position_embeddings (`int`, *optional*, defaults to 514):
|
147 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
148 |
+
just in case (e.g., 512 or 1024 or 2048).
|
149 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
150 |
+
The vocabulary size of the `token_type_ids`.
|
151 |
+
initializer_factor (`float`, *optional*, defaults to 1):
|
152 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
153 |
+
testing).
|
154 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
|
155 |
+
The epsilon used by the layer normalization layers.
|
156 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
157 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
158 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
159 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
160 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
161 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
162 |
+
is_decoder (`bool`, *optional*, defaults to `False`):
|
163 |
+
Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
|
164 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
165 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
166 |
+
relevant if `config.is_decoder=True`.
|
167 |
+
|
168 |
+
Example:
|
169 |
+
|
170 |
+
```python
|
171 |
+
>>> from transformers import BridgeTowerTextConfig
|
172 |
+
|
173 |
+
>>> # Initializing a BridgeTower BridgeTower/bridgetower-base style configuration for the text model
|
174 |
+
>>> configuration = BridgeTowerTextConfig()
|
175 |
+
|
176 |
+
>>> # Accessing the configuration
|
177 |
+
>>> configuration
|
178 |
+
```"""
|
179 |
+
|
180 |
+
model_type = "bridgetower_text_model"
|
181 |
+
|
182 |
+
def __init__(
|
183 |
+
self,
|
184 |
+
vocab_size=50265,
|
185 |
+
hidden_size=768,
|
186 |
+
num_hidden_layers=12,
|
187 |
+
num_attention_heads=12,
|
188 |
+
initializer_factor=1,
|
189 |
+
intermediate_size=3072,
|
190 |
+
hidden_act="gelu",
|
191 |
+
hidden_dropout_prob=0.1,
|
192 |
+
attention_probs_dropout_prob=0.1,
|
193 |
+
max_position_embeddings=514,
|
194 |
+
type_vocab_size=1,
|
195 |
+
layer_norm_eps=1e-05,
|
196 |
+
pad_token_id=1,
|
197 |
+
bos_token_id=0,
|
198 |
+
eos_token_id=2,
|
199 |
+
position_embedding_type="absolute",
|
200 |
+
use_cache=True,
|
201 |
+
**kwargs,
|
202 |
+
):
|
203 |
+
super().__init__(**kwargs)
|
204 |
+
|
205 |
+
self.vocab_size = vocab_size
|
206 |
+
self.hidden_size = hidden_size
|
207 |
+
self.num_hidden_layers = num_hidden_layers
|
208 |
+
self.num_attention_heads = num_attention_heads
|
209 |
+
self.hidden_act = hidden_act
|
210 |
+
self.initializer_factor = initializer_factor
|
211 |
+
self.intermediate_size = intermediate_size
|
212 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
213 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
214 |
+
self.max_position_embeddings = max_position_embeddings
|
215 |
+
self.type_vocab_size = type_vocab_size
|
216 |
+
self.layer_norm_eps = layer_norm_eps
|
217 |
+
self.position_embedding_type = position_embedding_type
|
218 |
+
self.use_cache = use_cache
|
219 |
+
self.pad_token_id = pad_token_id
|
220 |
+
self.bos_token_id = bos_token_id
|
221 |
+
self.eos_token_id = eos_token_id
|
222 |
+
|
223 |
+
@classmethod
|
224 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
225 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
226 |
+
|
227 |
+
if config_dict.get("model_type") == "bridgetower":
|
228 |
+
config_dict = config_dict["text_config"]
|
229 |
+
|
230 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
231 |
+
logger.warning(
|
232 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
233 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
234 |
+
)
|
235 |
+
|
236 |
+
return cls.from_dict(config_dict, **kwargs)
|
237 |
+
|
238 |
+
|
239 |
+
class BridgeTowerConfig(PretrainedConfig):
|
240 |
+
r"""
|
241 |
+
This is the configuration class to store the configuration of a [`BridgeTowerModel`]. It is used to instantiate a
|
242 |
+
BridgeTower model according to the specified arguments, defining the model architecture. Instantiating a
|
243 |
+
configuration with the defaults will yield a similar configuration to that of the bridgetower-base
|
244 |
+
[BridgeTower/bridgetower-base](https://huggingface.co/BridgeTower/bridgetower-base/) architecture.
|
245 |
+
|
246 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
247 |
+
documentation from [`PretrainedConfig`] for more information.
|
248 |
+
|
249 |
+
Args:
|
250 |
+
share_cross_modal_transformer_layers (`bool`, *optional*, defaults to `True`):
|
251 |
+
Whether cross modal transformer layers are shared.
|
252 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
253 |
+
The non-linear activation function (function or string) in the encoder and pooler.
|
254 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
255 |
+
Dimensionality of the encoder layers and the pooler layer.
|
256 |
+
initializer_factor (`float`, *optional*, defaults to 1):
|
257 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
258 |
+
testing).
|
259 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
|
260 |
+
The epsilon used by the layer normalization layers.
|
261 |
+
share_link_tower_layers (`bool`, *optional*, defaults to `False`):
|
262 |
+
Whether the bride/link tower layers are shared.
|
263 |
+
link_tower_type (`str`, *optional*, defaults to `"add"`):
|
264 |
+
Type of the bridge/link layer.
|
265 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
266 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
267 |
+
num_hidden_layers (`int`, *optional*, defaults to 6):
|
268 |
+
Number of hidden layers in the Transformer encoder.
|
269 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
270 |
+
Whether to tie input and output embeddings.
|
271 |
+
init_layernorm_from_vision_encoder (`bool`, *optional*, defaults to `False`):
|
272 |
+
Whether to init LayerNorm from the vision encoder.
|
273 |
+
text_config (`dict`, *optional*):
|
274 |
+
Dictionary of configuration options used to initialize [`BridgeTowerTextConfig`].
|
275 |
+
vision_config (`dict`, *optional*):
|
276 |
+
Dictionary of configuration options used to initialize [`BridgeTowerVisionConfig`].
|
277 |
+
|
278 |
+
Example:
|
279 |
+
|
280 |
+
```python
|
281 |
+
>>> from transformers import BridgeTowerModel, BridgeTowerConfig
|
282 |
+
|
283 |
+
>>> # Initializing a BridgeTower BridgeTower/bridgetower-base style configuration
|
284 |
+
>>> configuration = BridgeTowerConfig()
|
285 |
+
|
286 |
+
>>> # Initializing a model from the BridgeTower/bridgetower-base style configuration
|
287 |
+
>>> model = BridgeTowerModel(configuration)
|
288 |
+
|
289 |
+
>>> # Accessing the model configuration
|
290 |
+
>>> configuration = model.config
|
291 |
+
```"""
|
292 |
+
|
293 |
+
model_type = "bridgetower"
|
294 |
+
|
295 |
+
def __init__(
|
296 |
+
self,
|
297 |
+
share_cross_modal_transformer_layers=True,
|
298 |
+
hidden_act="gelu",
|
299 |
+
hidden_size=768,
|
300 |
+
initializer_factor=1,
|
301 |
+
layer_norm_eps=1e-05,
|
302 |
+
share_link_tower_layers=False,
|
303 |
+
link_tower_type="add",
|
304 |
+
num_attention_heads=12,
|
305 |
+
num_hidden_layers=6,
|
306 |
+
tie_word_embeddings=False,
|
307 |
+
init_layernorm_from_vision_encoder=False,
|
308 |
+
text_config=None,
|
309 |
+
vision_config=None,
|
310 |
+
**kwargs,
|
311 |
+
):
|
312 |
+
# TODO: remove this once the Hub files are updated.
|
313 |
+
_ = kwargs.pop("text_config_dict", None)
|
314 |
+
_ = kwargs.pop("vision_config_dict", None)
|
315 |
+
|
316 |
+
super().__init__(**kwargs)
|
317 |
+
self.share_cross_modal_transformer_layers = share_cross_modal_transformer_layers
|
318 |
+
self.hidden_act = hidden_act
|
319 |
+
self.hidden_size = hidden_size
|
320 |
+
self.initializer_factor = initializer_factor
|
321 |
+
self.layer_norm_eps = layer_norm_eps
|
322 |
+
self.share_link_tower_layers = share_link_tower_layers
|
323 |
+
self.link_tower_type = link_tower_type
|
324 |
+
self.num_attention_heads = num_attention_heads
|
325 |
+
self.num_hidden_layers = num_hidden_layers
|
326 |
+
self.tie_word_embeddings = tie_word_embeddings
|
327 |
+
self.init_layernorm_from_vision_encoder = init_layernorm_from_vision_encoder
|
328 |
+
|
329 |
+
if text_config is None:
|
330 |
+
text_config = {}
|
331 |
+
logger.info("`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.")
|
332 |
+
|
333 |
+
if vision_config is None:
|
334 |
+
vision_config = {}
|
335 |
+
logger.info("`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.")
|
336 |
+
|
337 |
+
self.text_config = BridgeTowerTextConfig(**text_config)
|
338 |
+
self.vision_config = BridgeTowerVisionConfig(**vision_config)
|
339 |
+
|
340 |
+
@classmethod
|
341 |
+
def from_text_vision_configs(
|
342 |
+
cls, text_config: BridgeTowerTextConfig, vision_config: BridgeTowerVisionConfig, **kwargs
|
343 |
+
):
|
344 |
+
r"""
|
345 |
+
Instantiate a [`BridgeTowerConfig`] (or a derived class) from BridgeTower text model configuration. Returns:
|
346 |
+
[`BridgeTowerConfig`]: An instance of a configuration object
|
347 |
+
"""
|
348 |
+
|
349 |
+
return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
|
venv/lib/python3.10/site-packages/transformers/models/bridgetower/image_processing_bridgetower.py
ADDED
@@ -0,0 +1,561 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 The Intel Labs Team Authors, The Microsoft Research Team Authors and 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 |
+
"""Image processor class for BridgeTower."""
|
16 |
+
|
17 |
+
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
|
18 |
+
|
19 |
+
import numpy as np
|
20 |
+
|
21 |
+
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
|
22 |
+
from ...image_transforms import PaddingMode, center_crop, pad, resize, to_channel_dimension_format
|
23 |
+
from ...image_utils import (
|
24 |
+
OPENAI_CLIP_MEAN,
|
25 |
+
OPENAI_CLIP_STD,
|
26 |
+
ChannelDimension,
|
27 |
+
ImageInput,
|
28 |
+
PILImageResampling,
|
29 |
+
get_image_size,
|
30 |
+
infer_channel_dimension_format,
|
31 |
+
is_batched,
|
32 |
+
is_scaled_image,
|
33 |
+
to_numpy_array,
|
34 |
+
valid_images,
|
35 |
+
validate_kwargs,
|
36 |
+
validate_preprocess_arguments,
|
37 |
+
)
|
38 |
+
from ...utils import TensorType, is_vision_available, logging
|
39 |
+
|
40 |
+
|
41 |
+
if is_vision_available():
|
42 |
+
import PIL
|
43 |
+
|
44 |
+
logger = logging.get_logger(__name__)
|
45 |
+
|
46 |
+
|
47 |
+
# Copied from transformers.models.vilt.image_processing_vilt.max_across_indices
|
48 |
+
def max_across_indices(values: Iterable[Any]) -> List[Any]:
|
49 |
+
"""
|
50 |
+
Return the maximum value across all indices of an iterable of values.
|
51 |
+
"""
|
52 |
+
return [max(values_i) for values_i in zip(*values)]
|
53 |
+
|
54 |
+
|
55 |
+
# Copied from transformers.models.vilt.image_processing_vilt.make_pixel_mask
|
56 |
+
def make_pixel_mask(
|
57 |
+
image: np.ndarray, output_size: Tuple[int, int], input_data_format: Optional[Union[str, ChannelDimension]] = None
|
58 |
+
) -> np.ndarray:
|
59 |
+
"""
|
60 |
+
Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
|
61 |
+
|
62 |
+
Args:
|
63 |
+
image (`np.ndarray`):
|
64 |
+
Image to make the pixel mask for.
|
65 |
+
output_size (`Tuple[int, int]`):
|
66 |
+
Output size of the mask.
|
67 |
+
"""
|
68 |
+
input_height, input_width = get_image_size(image, channel_dim=input_data_format)
|
69 |
+
mask = np.zeros(output_size, dtype=np.int64)
|
70 |
+
mask[:input_height, :input_width] = 1
|
71 |
+
return mask
|
72 |
+
|
73 |
+
|
74 |
+
# Copied from transformers.models.vilt.image_processing_vilt.get_max_height_width
|
75 |
+
def get_max_height_width(
|
76 |
+
images: List[np.ndarray], input_data_format: Optional[Union[str, ChannelDimension]] = None
|
77 |
+
) -> List[int]:
|
78 |
+
"""
|
79 |
+
Get the maximum height and width across all images in a batch.
|
80 |
+
"""
|
81 |
+
if input_data_format is None:
|
82 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
83 |
+
|
84 |
+
if input_data_format == ChannelDimension.FIRST:
|
85 |
+
_, max_height, max_width = max_across_indices([img.shape for img in images])
|
86 |
+
elif input_data_format == ChannelDimension.LAST:
|
87 |
+
max_height, max_width, _ = max_across_indices([img.shape for img in images])
|
88 |
+
else:
|
89 |
+
raise ValueError(f"Invalid channel dimension format: {input_data_format}")
|
90 |
+
return (max_height, max_width)
|
91 |
+
|
92 |
+
|
93 |
+
# Copied from transformers.models.vilt.image_processing_vilt.get_resize_output_image_size
|
94 |
+
def get_resize_output_image_size(
|
95 |
+
input_image: np.ndarray,
|
96 |
+
shorter: int = 800,
|
97 |
+
longer: int = 1333,
|
98 |
+
size_divisor: int = 32,
|
99 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
100 |
+
) -> Tuple[int, int]:
|
101 |
+
input_height, input_width = get_image_size(input_image, input_data_format)
|
102 |
+
min_size, max_size = shorter, longer
|
103 |
+
|
104 |
+
scale = min_size / min(input_height, input_width)
|
105 |
+
|
106 |
+
if input_height < input_width:
|
107 |
+
new_height = min_size
|
108 |
+
new_width = scale * input_width
|
109 |
+
else:
|
110 |
+
new_height = scale * input_height
|
111 |
+
new_width = min_size
|
112 |
+
|
113 |
+
if max(new_height, new_width) > max_size:
|
114 |
+
scale = max_size / max(new_height, new_width)
|
115 |
+
new_height = scale * new_height
|
116 |
+
new_width = scale * new_width
|
117 |
+
|
118 |
+
new_height, new_width = int(new_height + 0.5), int(new_width + 0.5)
|
119 |
+
new_height = new_height // size_divisor * size_divisor
|
120 |
+
new_width = new_width // size_divisor * size_divisor
|
121 |
+
|
122 |
+
return new_height, new_width
|
123 |
+
|
124 |
+
|
125 |
+
class BridgeTowerImageProcessor(BaseImageProcessor):
|
126 |
+
r"""
|
127 |
+
Constructs a BridgeTower image processor.
|
128 |
+
|
129 |
+
Args:
|
130 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
131 |
+
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
|
132 |
+
`do_resize` parameter in the `preprocess` method.
|
133 |
+
size (`Dict[str, int]` *optional*, defaults to `{'shortest_edge': 288}`):
|
134 |
+
Resize the shorter side of the input to `size["shortest_edge"]`. The longer side will be limited to under
|
135 |
+
`int((1333 / 800) * size["shortest_edge"])` while preserving the aspect ratio. Only has an effect if
|
136 |
+
`do_resize` is set to `True`. Can be overridden by the `size` parameter in the `preprocess` method.
|
137 |
+
size_divisor (`int`, *optional*, defaults to 32):
|
138 |
+
The size by which to make sure both the height and width can be divided. Only has an effect if `do_resize`
|
139 |
+
is set to `True`. Can be overridden by the `size_divisor` parameter in the `preprocess` method.
|
140 |
+
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
|
141 |
+
Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`. Can be
|
142 |
+
overridden by the `resample` parameter in the `preprocess` method.
|
143 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
144 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
|
145 |
+
parameter in the `preprocess` method.
|
146 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
147 |
+
Scale factor to use if rescaling the image. Only has an effect if `do_rescale` is set to `True`. Can be
|
148 |
+
overridden by the `rescale_factor` parameter in the `preprocess` method.
|
149 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
150 |
+
Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
|
151 |
+
method. Can be overridden by the `do_normalize` parameter in the `preprocess` method.
|
152 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
|
153 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
154 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be
|
155 |
+
overridden by the `image_mean` parameter in the `preprocess` method.
|
156 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
|
157 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
158 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
159 |
+
Can be overridden by the `image_std` parameter in the `preprocess` method.
|
160 |
+
do_center_crop (`bool`, *optional*, defaults to `True`):
|
161 |
+
Whether to center crop the image. Can be overridden by the `do_center_crop` parameter in the `preprocess`
|
162 |
+
method.
|
163 |
+
crop_size (`Dict[str, int]`, *optional*):
|
164 |
+
Desired output size when applying center-cropping. Only has an effect if `do_center_crop` is set to `True`.
|
165 |
+
Can be overridden by the `crop_size` parameter in the `preprocess` method. If unset defaults to `size`,
|
166 |
+
do_pad (`bool`, *optional*, defaults to `True`):
|
167 |
+
Whether to pad the image to the `(max_height, max_width)` of the images in the batch. Can be overridden by
|
168 |
+
the `do_pad` parameter in the `preprocess` method.
|
169 |
+
"""
|
170 |
+
|
171 |
+
model_input_names = ["pixel_values"]
|
172 |
+
|
173 |
+
def __init__(
|
174 |
+
self,
|
175 |
+
do_resize: bool = True,
|
176 |
+
size: Dict[str, int] = None,
|
177 |
+
size_divisor: int = 32,
|
178 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
179 |
+
do_rescale: bool = True,
|
180 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
181 |
+
do_normalize: bool = True,
|
182 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
183 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
184 |
+
do_center_crop: bool = True,
|
185 |
+
crop_size: Dict[str, int] = None,
|
186 |
+
do_pad: bool = True,
|
187 |
+
**kwargs,
|
188 |
+
) -> None:
|
189 |
+
if "pad_and_return_pixel_mask" in kwargs:
|
190 |
+
do_pad = kwargs.pop("pad_and_return_pixel_mask")
|
191 |
+
|
192 |
+
super().__init__(**kwargs)
|
193 |
+
size = size if size is not None else {"shortest_edge": 288}
|
194 |
+
size = get_size_dict(size, default_to_square=False)
|
195 |
+
|
196 |
+
self.do_resize = do_resize
|
197 |
+
self.size = size
|
198 |
+
self.size_divisor = size_divisor
|
199 |
+
self.resample = resample
|
200 |
+
self.do_rescale = do_rescale
|
201 |
+
self.rescale_factor = rescale_factor
|
202 |
+
self.do_normalize = do_normalize
|
203 |
+
self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
|
204 |
+
self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
|
205 |
+
self.do_pad = do_pad
|
206 |
+
self.do_center_crop = do_center_crop
|
207 |
+
self.crop_size = crop_size
|
208 |
+
self._valid_processor_keys = [
|
209 |
+
"images",
|
210 |
+
"do_resize",
|
211 |
+
"size",
|
212 |
+
"size_divisor",
|
213 |
+
"resample",
|
214 |
+
"do_rescale",
|
215 |
+
"rescale_factor",
|
216 |
+
"do_normalize",
|
217 |
+
"image_mean",
|
218 |
+
"image_std",
|
219 |
+
"do_pad",
|
220 |
+
"do_center_crop",
|
221 |
+
"crop_size",
|
222 |
+
"return_tensors",
|
223 |
+
"data_format",
|
224 |
+
"input_data_format",
|
225 |
+
]
|
226 |
+
|
227 |
+
# Copied from transformers.models.vilt.image_processing_vilt.ViltImageProcessor.resize
|
228 |
+
def resize(
|
229 |
+
self,
|
230 |
+
image: np.ndarray,
|
231 |
+
size: Dict[str, int],
|
232 |
+
size_divisor: int = 32,
|
233 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
234 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
235 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
236 |
+
**kwargs,
|
237 |
+
) -> np.ndarray:
|
238 |
+
"""
|
239 |
+
Resize an image.
|
240 |
+
|
241 |
+
Resizes the shorter side of the image to `size["shortest_edge"]` while preserving the aspect ratio. If the
|
242 |
+
longer side is larger than the max size `(int(`size["shortest_edge"]` * 1333 / 800))`, the longer side is then
|
243 |
+
resized to the max size while preserving the aspect ratio.
|
244 |
+
|
245 |
+
Args:
|
246 |
+
image (`np.ndarray`):
|
247 |
+
Image to resize.
|
248 |
+
size (`Dict[str, int]`):
|
249 |
+
Controls the size of the output image. Should be of the form `{"shortest_edge": int}`.
|
250 |
+
size_divisor (`int`, defaults to 32):
|
251 |
+
The image is resized to a size that is a multiple of this value.
|
252 |
+
resample (`PILImageResampling` filter, *optional*, defaults to `PILImageResampling.BICUBIC`):
|
253 |
+
Resampling filter to use when resiizing the image.
|
254 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
255 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
256 |
+
input_data_format (`str` or `ChannelDimension`, *optional*):
|
257 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
258 |
+
"""
|
259 |
+
size = get_size_dict(size, default_to_square=False)
|
260 |
+
if "shortest_edge" not in size:
|
261 |
+
raise ValueError(f"The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}")
|
262 |
+
shorter = size["shortest_edge"]
|
263 |
+
longer = int(1333 / 800 * shorter)
|
264 |
+
output_size = get_resize_output_image_size(
|
265 |
+
image, shorter=shorter, longer=longer, size_divisor=size_divisor, input_data_format=input_data_format
|
266 |
+
)
|
267 |
+
return resize(
|
268 |
+
image,
|
269 |
+
size=output_size,
|
270 |
+
resample=resample,
|
271 |
+
data_format=data_format,
|
272 |
+
input_data_format=input_data_format,
|
273 |
+
**kwargs,
|
274 |
+
)
|
275 |
+
|
276 |
+
def center_crop(
|
277 |
+
self,
|
278 |
+
image: np.ndarray,
|
279 |
+
size: Dict[str, int],
|
280 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
281 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
282 |
+
**kwargs,
|
283 |
+
) -> np.ndarray:
|
284 |
+
"""
|
285 |
+
Center crop an image to `(size["height"], size["width"])`. If the input size is smaller than `crop_size` along
|
286 |
+
any edge, the image is padded with 0's and then center cropped.
|
287 |
+
|
288 |
+
Args:
|
289 |
+
image (`np.ndarray`):
|
290 |
+
Image to center crop.
|
291 |
+
size (`Dict[str, int]`):
|
292 |
+
Size of the output image in the form `{"height": h, "width": w}`.
|
293 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
294 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
295 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
296 |
+
The channel dimension format of the input image. If not provided, it will be inferred from the input
|
297 |
+
image.
|
298 |
+
"""
|
299 |
+
output_size = size["shortest_edge"]
|
300 |
+
return center_crop(
|
301 |
+
image,
|
302 |
+
size=(output_size, output_size),
|
303 |
+
data_format=data_format,
|
304 |
+
input_data_format=input_data_format,
|
305 |
+
**kwargs,
|
306 |
+
)
|
307 |
+
|
308 |
+
# Copied from transformers.models.vilt.image_processing_vilt.ViltImageProcessor._pad_image
|
309 |
+
def _pad_image(
|
310 |
+
self,
|
311 |
+
image: np.ndarray,
|
312 |
+
output_size: Tuple[int, int],
|
313 |
+
constant_values: Union[float, Iterable[float]] = 0,
|
314 |
+
data_format: Optional[ChannelDimension] = None,
|
315 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
316 |
+
) -> np.ndarray:
|
317 |
+
"""
|
318 |
+
Pad an image with zeros to the given size.
|
319 |
+
"""
|
320 |
+
input_height, input_width = get_image_size(image, channel_dim=input_data_format)
|
321 |
+
output_height, output_width = output_size
|
322 |
+
|
323 |
+
pad_bottom = output_height - input_height
|
324 |
+
pad_right = output_width - input_width
|
325 |
+
padding = ((0, pad_bottom), (0, pad_right))
|
326 |
+
padded_image = pad(
|
327 |
+
image,
|
328 |
+
padding,
|
329 |
+
mode=PaddingMode.CONSTANT,
|
330 |
+
constant_values=constant_values,
|
331 |
+
data_format=data_format,
|
332 |
+
input_data_format=input_data_format,
|
333 |
+
)
|
334 |
+
return padded_image
|
335 |
+
|
336 |
+
# Copied from transformers.models.vilt.image_processing_vilt.ViltImageProcessor.pad
|
337 |
+
def pad(
|
338 |
+
self,
|
339 |
+
images: List[np.ndarray],
|
340 |
+
constant_values: Union[float, Iterable[float]] = 0,
|
341 |
+
return_pixel_mask: bool = True,
|
342 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
343 |
+
data_format: Optional[ChannelDimension] = None,
|
344 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
345 |
+
) -> BatchFeature:
|
346 |
+
"""
|
347 |
+
Pads a batch of images to the bottom and right of the image with zeros to the size of largest height and width
|
348 |
+
in the batch and optionally returns their corresponding pixel mask.
|
349 |
+
|
350 |
+
Args:
|
351 |
+
image (`np.ndarray`):
|
352 |
+
Image to pad.
|
353 |
+
constant_values (`float` or `Iterable[float]`, *optional*):
|
354 |
+
The value to use for the padding if `mode` is `"constant"`.
|
355 |
+
return_pixel_mask (`bool`, *optional*, defaults to `True`):
|
356 |
+
Whether to return a pixel mask.
|
357 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
358 |
+
The type of tensors to return. Can be one of:
|
359 |
+
- Unset: Return a list of `np.ndarray`.
|
360 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
361 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
362 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
363 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
364 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
365 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
366 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
367 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
368 |
+
"""
|
369 |
+
pad_size = get_max_height_width(images, input_data_format=input_data_format)
|
370 |
+
|
371 |
+
padded_images = [
|
372 |
+
self._pad_image(
|
373 |
+
image,
|
374 |
+
pad_size,
|
375 |
+
constant_values=constant_values,
|
376 |
+
data_format=data_format,
|
377 |
+
input_data_format=input_data_format,
|
378 |
+
)
|
379 |
+
for image in images
|
380 |
+
]
|
381 |
+
data = {"pixel_values": padded_images}
|
382 |
+
|
383 |
+
if return_pixel_mask:
|
384 |
+
masks = [
|
385 |
+
make_pixel_mask(image=image, output_size=pad_size, input_data_format=input_data_format)
|
386 |
+
for image in images
|
387 |
+
]
|
388 |
+
data["pixel_mask"] = masks
|
389 |
+
|
390 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
391 |
+
|
392 |
+
def preprocess(
|
393 |
+
self,
|
394 |
+
images: ImageInput,
|
395 |
+
do_resize: Optional[bool] = None,
|
396 |
+
size: Optional[Dict[str, int]] = None,
|
397 |
+
size_divisor: Optional[int] = None,
|
398 |
+
resample: PILImageResampling = None,
|
399 |
+
do_rescale: Optional[bool] = None,
|
400 |
+
rescale_factor: Optional[float] = None,
|
401 |
+
do_normalize: Optional[bool] = None,
|
402 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
403 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
404 |
+
do_pad: Optional[bool] = None,
|
405 |
+
do_center_crop: Optional[bool] = None,
|
406 |
+
crop_size: Dict[str, int] = None,
|
407 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
408 |
+
data_format: ChannelDimension = ChannelDimension.FIRST,
|
409 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
410 |
+
**kwargs,
|
411 |
+
) -> PIL.Image.Image:
|
412 |
+
"""
|
413 |
+
Preprocess an image or batch of images.
|
414 |
+
|
415 |
+
Args:
|
416 |
+
images (`ImageInput`):
|
417 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
418 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
419 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
420 |
+
Whether to resize the image.
|
421 |
+
size (`Dict[str, int]`, *optional*, defaults to `self.size`):
|
422 |
+
Controls the size of the image after `resize`. The shortest edge of the image is resized to
|
423 |
+
`size["shortest_edge"]` whilst preserving the aspect ratio. If the longest edge of this resized image
|
424 |
+
is > `int(size["shortest_edge"] * (1333 / 800))`, then the image is resized again to make the longest
|
425 |
+
edge equal to `int(size["shortest_edge"] * (1333 / 800))`.
|
426 |
+
size_divisor (`int`, *optional*, defaults to `self.size_divisor`):
|
427 |
+
The image is resized to a size that is a multiple of this value.
|
428 |
+
resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
|
429 |
+
Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`.
|
430 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
431 |
+
Whether to rescale the image values between [0 - 1].
|
432 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
433 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
434 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
435 |
+
Whether to normalize the image.
|
436 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
437 |
+
Image mean to normalize the image by if `do_normalize` is set to `True`.
|
438 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
439 |
+
Image standard deviation to normalize the image by if `do_normalize` is set to `True`.
|
440 |
+
do_pad (`bool`, *optional*, defaults to `self.do_pad`):
|
441 |
+
Whether to pad the image to the (max_height, max_width) in the batch. If `True`, a pixel mask is also
|
442 |
+
created and returned.
|
443 |
+
do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
|
444 |
+
Whether to center crop the image. If the input size is smaller than `crop_size` along any edge, the
|
445 |
+
image is padded with 0's and then center cropped.
|
446 |
+
crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
|
447 |
+
Size of the image after center crop. If one edge the image is smaller than `crop_size`, it will be
|
448 |
+
padded with zeros and then cropped
|
449 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
450 |
+
The type of tensors to return. Can be one of:
|
451 |
+
- Unset: Return a list of `np.ndarray`.
|
452 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
453 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
454 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
455 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
456 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
457 |
+
The channel dimension format for the output image. Can be one of:
|
458 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
459 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
460 |
+
- Unset: Use the channel dimension format of the input image.
|
461 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
462 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
463 |
+
from the input image. Can be one of:
|
464 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
465 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
466 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
467 |
+
"""
|
468 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
469 |
+
size_divisor = size_divisor if size_divisor is not None else self.size_divisor
|
470 |
+
resample = resample if resample is not None else self.resample
|
471 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
472 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
473 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
474 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
475 |
+
image_std = image_std if image_std is not None else self.image_std
|
476 |
+
do_pad = do_pad if do_pad is not None else self.do_pad
|
477 |
+
do_center_crop if do_center_crop is not None else self.do_center_crop
|
478 |
+
# For backwards compatibility. Initial version of this processor was cropping to the "size" argument, which
|
479 |
+
# it should default to if crop_size is undefined.
|
480 |
+
crop_size = (
|
481 |
+
crop_size if crop_size is not None else (self.crop_size if self.crop_size is not None else self.size)
|
482 |
+
)
|
483 |
+
|
484 |
+
size = size if size is not None else self.size
|
485 |
+
size = get_size_dict(size, default_to_square=False)
|
486 |
+
|
487 |
+
validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)
|
488 |
+
|
489 |
+
if not is_batched(images):
|
490 |
+
images = [images]
|
491 |
+
|
492 |
+
if not valid_images(images):
|
493 |
+
raise ValueError(
|
494 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
495 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
496 |
+
)
|
497 |
+
# Here, crop_size is used only if it is set, else size will be used.
|
498 |
+
validate_preprocess_arguments(
|
499 |
+
do_rescale=do_rescale,
|
500 |
+
rescale_factor=rescale_factor,
|
501 |
+
do_normalize=do_normalize,
|
502 |
+
image_mean=image_mean,
|
503 |
+
image_std=image_std,
|
504 |
+
do_pad=do_pad,
|
505 |
+
size_divisibility=size_divisor,
|
506 |
+
do_center_crop=do_center_crop,
|
507 |
+
crop_size=crop_size,
|
508 |
+
do_resize=do_resize,
|
509 |
+
size=size,
|
510 |
+
resample=resample,
|
511 |
+
)
|
512 |
+
# All transformations expect numpy arrays.
|
513 |
+
images = [to_numpy_array(image) for image in images]
|
514 |
+
|
515 |
+
if is_scaled_image(images[0]) and do_rescale:
|
516 |
+
logger.warning_once(
|
517 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
518 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
519 |
+
)
|
520 |
+
|
521 |
+
if do_resize:
|
522 |
+
images = [
|
523 |
+
self.resize(
|
524 |
+
image=image,
|
525 |
+
size=size,
|
526 |
+
size_divisor=size_divisor,
|
527 |
+
resample=resample,
|
528 |
+
input_data_format=input_data_format,
|
529 |
+
)
|
530 |
+
for image in images
|
531 |
+
]
|
532 |
+
|
533 |
+
if do_center_crop:
|
534 |
+
images = [
|
535 |
+
self.center_crop(image=image, size=crop_size, input_data_format=input_data_format) for image in images
|
536 |
+
]
|
537 |
+
|
538 |
+
if do_rescale:
|
539 |
+
images = [
|
540 |
+
self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
|
541 |
+
for image in images
|
542 |
+
]
|
543 |
+
|
544 |
+
if do_normalize:
|
545 |
+
images = [
|
546 |
+
self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
|
547 |
+
for image in images
|
548 |
+
]
|
549 |
+
|
550 |
+
images = [
|
551 |
+
to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
|
552 |
+
]
|
553 |
+
|
554 |
+
if do_pad:
|
555 |
+
encoded_outputs = self.pad(
|
556 |
+
images, return_pixel_mask=True, return_tensors=return_tensors, input_data_format=data_format
|
557 |
+
)
|
558 |
+
else:
|
559 |
+
encoded_outputs = BatchFeature(data={"pixel_values": images}, tensor_type=return_tensors)
|
560 |
+
|
561 |
+
return encoded_outputs
|
venv/lib/python3.10/site-packages/transformers/models/bridgetower/modeling_bridgetower.py
ADDED
@@ -0,0 +1,1898 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 The Intel Labs Team Authors, The Microsoft Research Team Authors and 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 BridgeTower Model"""
|
16 |
+
|
17 |
+
import math
|
18 |
+
from collections import OrderedDict
|
19 |
+
from dataclasses import dataclass
|
20 |
+
from typing import List, Optional, Tuple, Union
|
21 |
+
|
22 |
+
import torch
|
23 |
+
import torch.utils.checkpoint
|
24 |
+
from torch import nn
|
25 |
+
from torch.nn import CrossEntropyLoss
|
26 |
+
|
27 |
+
from ...activations import ACT2FN, QuickGELUActivation
|
28 |
+
from ...modeling_outputs import (
|
29 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
30 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
31 |
+
MaskedLMOutput,
|
32 |
+
ModelOutput,
|
33 |
+
SequenceClassifierOutput,
|
34 |
+
)
|
35 |
+
from ...modeling_utils import PreTrainedModel, apply_chunking_to_forward
|
36 |
+
from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
|
37 |
+
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
|
38 |
+
from .configuration_bridgetower import BridgeTowerConfig, BridgeTowerTextConfig, BridgeTowerVisionConfig
|
39 |
+
|
40 |
+
|
41 |
+
logger = logging.get_logger(__name__)
|
42 |
+
|
43 |
+
_CONFIG_FOR_DOC = "BridgeTowerConfig"
|
44 |
+
_CHECKPOINT_FOR_DOC = "BridgeTower/bridgetower-base"
|
45 |
+
_TOKENIZER_FOR_DOC = "RobertaTokenizer"
|
46 |
+
|
47 |
+
|
48 |
+
from ..deprecated._archive_maps import BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST # noqa: F401, E402
|
49 |
+
|
50 |
+
|
51 |
+
BRIDGETOWER_START_DOCSTRING = r"""
|
52 |
+
This model is a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`_ subclass. Use
|
53 |
+
it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
54 |
+
behavior.
|
55 |
+
|
56 |
+
Parameters:
|
57 |
+
config ([`BridgeTowerConfig`]): Model configuration class with all the parameters of the model.
|
58 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
59 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
60 |
+
"""
|
61 |
+
|
62 |
+
BRIDGETOWER_INPUTS_DOCSTRING = r"""
|
63 |
+
Args:
|
64 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
65 |
+
Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
|
66 |
+
[`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
|
67 |
+
IDs?](../glossary#input-ids)
|
68 |
+
|
69 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
70 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
71 |
+
- 1 for tokens that are **not masked**,
|
72 |
+
- 0 for tokens that are **masked**.
|
73 |
+
[What are attention masks?](../glossary#attention-mask)
|
74 |
+
|
75 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
76 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
77 |
+
1]`:
|
78 |
+
- 0 corresponds to a *sentence A* token,
|
79 |
+
- 1 corresponds to a *sentence B* token.
|
80 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
81 |
+
|
82 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
83 |
+
Pixel values. Pixel values can be obtained using [`BridgeTowerImageProcessor`]. See
|
84 |
+
[`BridgeTowerImageProcessor.__call__`] for details.
|
85 |
+
|
86 |
+
pixel_mask (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
|
87 |
+
Mask to avoid performing attention on padding pixel values. Mask values selected in `[0, 1]`:
|
88 |
+
|
89 |
+
- 1 for pixels that are real (i.e. **not masked**),
|
90 |
+
- 0 for pixels that are padding (i.e. **masked**).
|
91 |
+
`What are attention masks? <../glossary.html#attention-mask>`__
|
92 |
+
|
93 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
94 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
95 |
+
- 1 indicates the head is **not masked**,
|
96 |
+
- 0 indicates the head is **masked**.
|
97 |
+
|
98 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
99 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
100 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
101 |
+
model's internal embedding lookup matrix.
|
102 |
+
|
103 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`, *optional*):
|
104 |
+
Optionally, instead of passing `pixel_values`, you can choose to directly pass an embedded representation.
|
105 |
+
This is useful if you want more control over how to convert `pixel_values` into patch embeddings.
|
106 |
+
|
107 |
+
image_token_type_idx (`int`, *optional*):
|
108 |
+
- The token type ids for images.
|
109 |
+
|
110 |
+
output_attentions (`bool`, *optional*):
|
111 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
112 |
+
tensors for more detail.
|
113 |
+
|
114 |
+
output_hidden_states (`bool`, *optional*):
|
115 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
116 |
+
more detail.
|
117 |
+
return_dict (`bool`, *optional*):
|
118 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
119 |
+
"""
|
120 |
+
|
121 |
+
|
122 |
+
@dataclass
|
123 |
+
class BridgeTowerModelOutput(ModelOutput):
|
124 |
+
"""
|
125 |
+
Output type of [`BridgeTowerModel`].
|
126 |
+
|
127 |
+
Args:
|
128 |
+
text_features (`torch.FloatTensor` of shape `(batch_size, text_sequence_length, hidden_size)`):
|
129 |
+
Sequence of hidden-states at the text output of the last layer of the model.
|
130 |
+
image_features (`torch.FloatTensor` of shape `(batch_size, image_sequence_length, hidden_size)`):
|
131 |
+
Sequence of hidden-states at the image output of the last layer of the model.
|
132 |
+
pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size x 2)`):
|
133 |
+
Concatenation of last layer hidden-state of the first token of the text and image sequence (classification
|
134 |
+
token), respectively, after further processing through layers used for auxiliary pretraining tasks.
|
135 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
136 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
137 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of
|
138 |
+
the model at the output of each layer plus the optional initial embedding outputs.
|
139 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
140 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
141 |
+
sequence_length)`.
|
142 |
+
|
143 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
144 |
+
heads.
|
145 |
+
"""
|
146 |
+
|
147 |
+
text_features: torch.FloatTensor = None
|
148 |
+
image_features: torch.FloatTensor = None
|
149 |
+
pooler_output: torch.FloatTensor = None
|
150 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
151 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
152 |
+
|
153 |
+
|
154 |
+
@dataclass
|
155 |
+
class BridgeTowerContrastiveOutput(ModelOutput):
|
156 |
+
"""
|
157 |
+
Output type of ['BridgeTowerForContrastiveLearning']
|
158 |
+
|
159 |
+
Args:
|
160 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`:
|
161 |
+
Image-text contrastive loss.
|
162 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
163 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
164 |
+
text_embeds (`torch.FloatTensor)`, *optional*, returned when model is initialized with `with_projection=True`):
|
165 |
+
The text embeddings obtained by applying the projection layer to the pooler_output.
|
166 |
+
image_embeds (`torch.FloatTensor)`, *optional*, returned when model is initialized with `with_projection=True`):
|
167 |
+
The image embeddings obtained by applying the projection layer to the pooler_output.
|
168 |
+
cross_embeds (`torch.FloatTensor)`, *optional*, returned when model is initialized with `with_projection=True`):
|
169 |
+
The text-image cross-modal embeddings obtained by applying the projection layer to the pooler_output.
|
170 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
171 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
172 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of
|
173 |
+
the model at the output of each layer plus the optional initial embedding outputs.
|
174 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
175 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
176 |
+
sequence_length)`.
|
177 |
+
"""
|
178 |
+
|
179 |
+
loss: Optional[torch.FloatTensor] = None
|
180 |
+
logits: torch.FloatTensor = None
|
181 |
+
text_embeds: Optional[Tuple[torch.FloatTensor]] = None
|
182 |
+
image_embeds: Optional[Tuple[torch.FloatTensor]] = None
|
183 |
+
cross_embeds: Optional[Tuple[torch.FloatTensor]] = None
|
184 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
185 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
186 |
+
|
187 |
+
|
188 |
+
class BridgeTowerResidualAttention(nn.Module):
|
189 |
+
def __init__(self, config):
|
190 |
+
super().__init__()
|
191 |
+
|
192 |
+
self.attn = nn.MultiheadAttention(config.hidden_size, config.hidden_size // 64)
|
193 |
+
self.ln_1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
194 |
+
self.mlp = nn.ModuleDict(
|
195 |
+
OrderedDict(
|
196 |
+
[
|
197 |
+
("c_fc", nn.Linear(config.hidden_size, config.hidden_size * 4)),
|
198 |
+
("gelu", QuickGELUActivation()),
|
199 |
+
("c_proj", nn.Linear(config.hidden_size * 4, config.hidden_size)),
|
200 |
+
]
|
201 |
+
)
|
202 |
+
)
|
203 |
+
self.ln_2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
204 |
+
self.attn_mask = None
|
205 |
+
|
206 |
+
def attention(self, hidden_state: torch.Tensor, attention_mask: torch.Tensor):
|
207 |
+
if attention_mask is not None:
|
208 |
+
attention_mask = attention_mask.to(dtype=torch.bool, device=hidden_state.device)
|
209 |
+
self.attn_mask = (
|
210 |
+
self.attn_mask.to(dtype=hidden_state.dtype, device=hidden_state.device)
|
211 |
+
if self.attn_mask is not None
|
212 |
+
else None
|
213 |
+
)
|
214 |
+
return self.attn(
|
215 |
+
hidden_state,
|
216 |
+
hidden_state,
|
217 |
+
hidden_state,
|
218 |
+
need_weights=False,
|
219 |
+
attn_mask=self.attn_mask,
|
220 |
+
key_padding_mask=attention_mask,
|
221 |
+
)[0]
|
222 |
+
|
223 |
+
def forward(self, hidden_state: torch.Tensor, attention_mask: torch.Tensor = None):
|
224 |
+
residual_state = hidden_state + self.attention(self.ln_1(hidden_state), attention_mask)
|
225 |
+
hidden_state = self.ln_2(residual_state)
|
226 |
+
for _, layer in self.mlp.items():
|
227 |
+
hidden_state = layer(hidden_state)
|
228 |
+
hidden_state = residual_state + hidden_state
|
229 |
+
return hidden_state
|
230 |
+
|
231 |
+
|
232 |
+
class BridgeTowerTransformer(nn.Module):
|
233 |
+
def __init__(self, config):
|
234 |
+
super().__init__()
|
235 |
+
self.hidden_size = config.hidden_size
|
236 |
+
self.num_hidden_layers = config.num_hidden_layers
|
237 |
+
if config.remove_last_layer:
|
238 |
+
self.resblocks = nn.ModuleList(
|
239 |
+
[BridgeTowerResidualAttention(config) for _ in range(self.num_hidden_layers - 1)]
|
240 |
+
)
|
241 |
+
else:
|
242 |
+
self.resblocks = nn.ModuleList(
|
243 |
+
[BridgeTowerResidualAttention(config) for _ in range(self.num_hidden_layers)]
|
244 |
+
)
|
245 |
+
self.stop_gradient = config.stop_gradient
|
246 |
+
|
247 |
+
def forward(self, hidden_state: torch.Tensor, attention_mask: Optional[torch.Tensor] = None):
|
248 |
+
hidden_states = []
|
249 |
+
for block in self.resblocks:
|
250 |
+
hidden_state = block(hidden_state, attention_mask)
|
251 |
+
if self.stop_gradient:
|
252 |
+
hidden_states.append(hidden_state.detach())
|
253 |
+
else:
|
254 |
+
hidden_states.append(hidden_state)
|
255 |
+
return hidden_states
|
256 |
+
|
257 |
+
|
258 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPVisionEmbeddings with CLIP->BridgeTower
|
259 |
+
class BridgeTowerVisionEmbeddings(nn.Module):
|
260 |
+
def __init__(self, config: BridgeTowerVisionConfig):
|
261 |
+
super().__init__()
|
262 |
+
self.config = config
|
263 |
+
self.embed_dim = config.hidden_size
|
264 |
+
self.image_size = config.image_size
|
265 |
+
self.patch_size = config.patch_size
|
266 |
+
|
267 |
+
self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
|
268 |
+
|
269 |
+
self.patch_embedding = nn.Conv2d(
|
270 |
+
in_channels=config.num_channels,
|
271 |
+
out_channels=self.embed_dim,
|
272 |
+
kernel_size=self.patch_size,
|
273 |
+
stride=self.patch_size,
|
274 |
+
bias=False,
|
275 |
+
)
|
276 |
+
|
277 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
278 |
+
self.num_positions = self.num_patches + 1
|
279 |
+
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
|
280 |
+
self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
|
281 |
+
|
282 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
283 |
+
batch_size = pixel_values.shape[0]
|
284 |
+
target_dtype = self.patch_embedding.weight.dtype
|
285 |
+
patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
|
286 |
+
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
|
287 |
+
|
288 |
+
class_embeds = self.class_embedding.expand(batch_size, 1, -1)
|
289 |
+
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
290 |
+
embeddings = embeddings + self.position_embedding(self.position_ids)
|
291 |
+
return embeddings
|
292 |
+
|
293 |
+
|
294 |
+
class BridgeTowerVisionTransformer(nn.Module):
|
295 |
+
def __init__(self, config):
|
296 |
+
super().__init__()
|
297 |
+
|
298 |
+
self.embeddings = BridgeTowerVisionEmbeddings(config)
|
299 |
+
self.ln_pre = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
300 |
+
self.transformer = BridgeTowerTransformer(config)
|
301 |
+
self.ln_post = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
302 |
+
self.share_layernorm = config.share_layernorm
|
303 |
+
if not config.share_layernorm:
|
304 |
+
self.ln_separate = nn.ModuleList(
|
305 |
+
[nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) for _ in range(config.num_hidden_layers)]
|
306 |
+
)
|
307 |
+
|
308 |
+
def forward(self, pixel_values: torch.Tensor, attention_mask):
|
309 |
+
hidden_states = self.embeddings(pixel_values)
|
310 |
+
hidden_states = self.ln_pre(hidden_states)
|
311 |
+
# NLD -> LND
|
312 |
+
hidden_states = hidden_states.permute(1, 0, 2)
|
313 |
+
|
314 |
+
hidden_states = self.transformer(hidden_states, attention_mask)
|
315 |
+
# shape = [num_hidden_layers, hidden_size, *, grid ** 2]
|
316 |
+
hidden_states = torch.stack(hidden_states, dim=0)
|
317 |
+
# shape = [num_hidden_layers, *, hidden_size, grid ** 2]
|
318 |
+
hidden_states = hidden_states.permute(0, 2, 1, 3)
|
319 |
+
if self.share_layernorm:
|
320 |
+
hidden_states = self.ln_post(hidden_states)
|
321 |
+
else:
|
322 |
+
hidden_states_stack = []
|
323 |
+
for hidden_states, ln in zip(hidden_states, self.ln_separate):
|
324 |
+
hidden_states = ln(hidden_states)
|
325 |
+
hidden_states_stack.append(hidden_states)
|
326 |
+
# shape = [num_hidden_layers, *, hidden_size, grid ** 2]
|
327 |
+
hidden_states = torch.stack(hidden_states_stack, dim=0)
|
328 |
+
return hidden_states
|
329 |
+
|
330 |
+
def forward_pre(self, pixel_values: torch.Tensor):
|
331 |
+
hidden_states = self.embeddings(pixel_values)
|
332 |
+
hidden_states = self.ln_pre(hidden_states)
|
333 |
+
# NLD -> LND
|
334 |
+
hidden_states = hidden_states.permute(1, 0, 2)
|
335 |
+
return hidden_states
|
336 |
+
|
337 |
+
def forward_post(self, hidden_state: torch.Tensor):
|
338 |
+
visual_output_post = hidden_state.permute(1, 0, 2)
|
339 |
+
visual_output_post = self.ln_post(visual_output_post)
|
340 |
+
return visual_output_post
|
341 |
+
|
342 |
+
|
343 |
+
class BridgeTowerLinkTower(nn.Module):
|
344 |
+
def __init__(self, config):
|
345 |
+
super().__init__()
|
346 |
+
self.link_tower_type = config.link_tower_type
|
347 |
+
self.hidden_size = config.hidden_size
|
348 |
+
if config.link_tower_type in ["add", "scaled_add", "interpolate"]:
|
349 |
+
if config.link_tower_type == "scaled_add":
|
350 |
+
self.scaled_factor = nn.Parameter(torch.tensor(1.0))
|
351 |
+
elif config.link_tower_type == "interpolate":
|
352 |
+
self.beta = nn.Parameter(torch.tensor(0.5))
|
353 |
+
self.LayerNorm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps)
|
354 |
+
else:
|
355 |
+
raise NotImplementedError(f"link_tower_type {config.link_tower_type} is not implemented")
|
356 |
+
|
357 |
+
def forward(self, hidden_states, cross_modal_hidden_states, attention_mask):
|
358 |
+
if self.link_tower_type == "add":
|
359 |
+
return self.LayerNorm(hidden_states + cross_modal_hidden_states)
|
360 |
+
elif self.link_tower_type == "scaled_add":
|
361 |
+
return self.LayerNorm(hidden_states * self.scaled_factor + cross_modal_hidden_states)
|
362 |
+
elif self.link_tower_type == "interpolate":
|
363 |
+
return self.LayerNorm(hidden_states * (1 - self.beta) + cross_modal_hidden_states * self.beta)
|
364 |
+
else:
|
365 |
+
raise NotImplementedError(f"link_tower_type {self.link_tower_type} is not implemented")
|
366 |
+
|
367 |
+
|
368 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->BridgeTower
|
369 |
+
class BridgeTowerSelfOutput(nn.Module):
|
370 |
+
def __init__(self, config):
|
371 |
+
super().__init__()
|
372 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
373 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
374 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
375 |
+
|
376 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
377 |
+
hidden_states = self.dense(hidden_states)
|
378 |
+
hidden_states = self.dropout(hidden_states)
|
379 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
380 |
+
return hidden_states
|
381 |
+
|
382 |
+
|
383 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->BridgeTower
|
384 |
+
class BridgeTowerIntermediate(nn.Module):
|
385 |
+
def __init__(self, config):
|
386 |
+
super().__init__()
|
387 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
388 |
+
if isinstance(config.hidden_act, str):
|
389 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
390 |
+
else:
|
391 |
+
self.intermediate_act_fn = config.hidden_act
|
392 |
+
|
393 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
394 |
+
hidden_states = self.dense(hidden_states)
|
395 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
396 |
+
return hidden_states
|
397 |
+
|
398 |
+
|
399 |
+
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->BridgeTower
|
400 |
+
class BridgeTowerOutput(nn.Module):
|
401 |
+
def __init__(self, config):
|
402 |
+
super().__init__()
|
403 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
404 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
405 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
406 |
+
|
407 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
408 |
+
hidden_states = self.dense(hidden_states)
|
409 |
+
hidden_states = self.dropout(hidden_states)
|
410 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
411 |
+
return hidden_states
|
412 |
+
|
413 |
+
|
414 |
+
# Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->BridgeTower
|
415 |
+
class BridgeTowerPooler(nn.Module):
|
416 |
+
def __init__(self, config):
|
417 |
+
super().__init__()
|
418 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
419 |
+
self.activation = nn.Tanh()
|
420 |
+
|
421 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
422 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
423 |
+
# to the first token.
|
424 |
+
first_token_tensor = hidden_states[:, 0]
|
425 |
+
pooled_output = self.dense(first_token_tensor)
|
426 |
+
pooled_output = self.activation(pooled_output)
|
427 |
+
return pooled_output
|
428 |
+
|
429 |
+
|
430 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaSelfAttention with Roberta->BridgeTower
|
431 |
+
class BridgeTowerSelfAttention(nn.Module):
|
432 |
+
def __init__(self, config, position_embedding_type=None):
|
433 |
+
super().__init__()
|
434 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
435 |
+
raise ValueError(
|
436 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
437 |
+
f"heads ({config.num_attention_heads})"
|
438 |
+
)
|
439 |
+
|
440 |
+
self.num_attention_heads = config.num_attention_heads
|
441 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
442 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
443 |
+
|
444 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
445 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
446 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
447 |
+
|
448 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
449 |
+
self.position_embedding_type = position_embedding_type or getattr(
|
450 |
+
config, "position_embedding_type", "absolute"
|
451 |
+
)
|
452 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
453 |
+
self.max_position_embeddings = config.max_position_embeddings
|
454 |
+
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
|
455 |
+
|
456 |
+
self.is_decoder = config.is_decoder
|
457 |
+
|
458 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
459 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
460 |
+
x = x.view(new_x_shape)
|
461 |
+
return x.permute(0, 2, 1, 3)
|
462 |
+
|
463 |
+
def forward(
|
464 |
+
self,
|
465 |
+
hidden_states: torch.Tensor,
|
466 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
467 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
468 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
469 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
470 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
471 |
+
output_attentions: Optional[bool] = False,
|
472 |
+
) -> Tuple[torch.Tensor]:
|
473 |
+
mixed_query_layer = self.query(hidden_states)
|
474 |
+
|
475 |
+
# If this is instantiated as a cross-attention module, the keys
|
476 |
+
# and values come from an encoder; the attention mask needs to be
|
477 |
+
# such that the encoder's padding tokens are not attended to.
|
478 |
+
is_cross_attention = encoder_hidden_states is not None
|
479 |
+
|
480 |
+
if is_cross_attention and past_key_value is not None:
|
481 |
+
# reuse k,v, cross_attentions
|
482 |
+
key_layer = past_key_value[0]
|
483 |
+
value_layer = past_key_value[1]
|
484 |
+
attention_mask = encoder_attention_mask
|
485 |
+
elif is_cross_attention:
|
486 |
+
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
|
487 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
|
488 |
+
attention_mask = encoder_attention_mask
|
489 |
+
elif past_key_value is not None:
|
490 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
491 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
492 |
+
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
|
493 |
+
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
|
494 |
+
else:
|
495 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
496 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
497 |
+
|
498 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
499 |
+
|
500 |
+
use_cache = past_key_value is not None
|
501 |
+
if self.is_decoder:
|
502 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
503 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
504 |
+
# key/value_states (first "if" case)
|
505 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
506 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
507 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
508 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
509 |
+
past_key_value = (key_layer, value_layer)
|
510 |
+
|
511 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
512 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
513 |
+
|
514 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
515 |
+
query_length, key_length = query_layer.shape[2], key_layer.shape[2]
|
516 |
+
if use_cache:
|
517 |
+
position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
|
518 |
+
-1, 1
|
519 |
+
)
|
520 |
+
else:
|
521 |
+
position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
|
522 |
+
position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
|
523 |
+
distance = position_ids_l - position_ids_r
|
524 |
+
|
525 |
+
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
|
526 |
+
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
|
527 |
+
|
528 |
+
if self.position_embedding_type == "relative_key":
|
529 |
+
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
530 |
+
attention_scores = attention_scores + relative_position_scores
|
531 |
+
elif self.position_embedding_type == "relative_key_query":
|
532 |
+
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
533 |
+
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
|
534 |
+
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
|
535 |
+
|
536 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
537 |
+
if attention_mask is not None:
|
538 |
+
# Apply the attention mask is (precomputed for all layers in BridgeTowerModel forward() function)
|
539 |
+
attention_scores = attention_scores + attention_mask
|
540 |
+
|
541 |
+
# Normalize the attention scores to probabilities.
|
542 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
543 |
+
|
544 |
+
# This is actually dropping out entire tokens to attend to, which might
|
545 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
546 |
+
attention_probs = self.dropout(attention_probs)
|
547 |
+
|
548 |
+
# Mask heads if we want to
|
549 |
+
if head_mask is not None:
|
550 |
+
attention_probs = attention_probs * head_mask
|
551 |
+
|
552 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
553 |
+
|
554 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
555 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
556 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
557 |
+
|
558 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
559 |
+
|
560 |
+
if self.is_decoder:
|
561 |
+
outputs = outputs + (past_key_value,)
|
562 |
+
return outputs
|
563 |
+
|
564 |
+
|
565 |
+
# Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->BridgeTower
|
566 |
+
class BridgeTowerAttention(nn.Module):
|
567 |
+
def __init__(self, config, position_embedding_type=None):
|
568 |
+
super().__init__()
|
569 |
+
self.self = BridgeTowerSelfAttention(config, position_embedding_type=position_embedding_type)
|
570 |
+
self.output = BridgeTowerSelfOutput(config)
|
571 |
+
self.pruned_heads = set()
|
572 |
+
|
573 |
+
def prune_heads(self, heads):
|
574 |
+
if len(heads) == 0:
|
575 |
+
return
|
576 |
+
heads, index = find_pruneable_heads_and_indices(
|
577 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
578 |
+
)
|
579 |
+
|
580 |
+
# Prune linear layers
|
581 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
582 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
583 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
584 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
585 |
+
|
586 |
+
# Update hyper params and store pruned heads
|
587 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
588 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
589 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
590 |
+
|
591 |
+
def forward(
|
592 |
+
self,
|
593 |
+
hidden_states: torch.Tensor,
|
594 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
595 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
596 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
597 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
598 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
599 |
+
output_attentions: Optional[bool] = False,
|
600 |
+
) -> Tuple[torch.Tensor]:
|
601 |
+
self_outputs = self.self(
|
602 |
+
hidden_states,
|
603 |
+
attention_mask,
|
604 |
+
head_mask,
|
605 |
+
encoder_hidden_states,
|
606 |
+
encoder_attention_mask,
|
607 |
+
past_key_value,
|
608 |
+
output_attentions,
|
609 |
+
)
|
610 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
611 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
612 |
+
return outputs
|
613 |
+
|
614 |
+
|
615 |
+
class BridgeTowerBertCrossLayer(nn.Module):
|
616 |
+
def __init__(self, config):
|
617 |
+
super().__init__()
|
618 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
619 |
+
self.seq_len_dim = 1
|
620 |
+
self.attention = BridgeTowerAttention(config)
|
621 |
+
self.is_decoder = config.is_decoder
|
622 |
+
self.add_cross_attention = config.add_cross_attention
|
623 |
+
self.crossattention = BridgeTowerAttention(config)
|
624 |
+
self.intermediate = BridgeTowerIntermediate(config)
|
625 |
+
self.output = BridgeTowerOutput(config)
|
626 |
+
|
627 |
+
def forward(
|
628 |
+
self,
|
629 |
+
hidden_states,
|
630 |
+
encoder_hidden_states,
|
631 |
+
attention_mask=None,
|
632 |
+
head_mask=None,
|
633 |
+
encoder_attention_mask=None,
|
634 |
+
past_key_value=None,
|
635 |
+
output_attentions=False,
|
636 |
+
):
|
637 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
638 |
+
self_attention_outputs = self.attention(
|
639 |
+
hidden_states,
|
640 |
+
attention_mask=attention_mask,
|
641 |
+
head_mask=None,
|
642 |
+
output_attentions=output_attentions,
|
643 |
+
past_key_value=None,
|
644 |
+
)
|
645 |
+
attention_output = self_attention_outputs[0]
|
646 |
+
|
647 |
+
# if decoder, the last output is tuple of self-attn cache
|
648 |
+
# add self attentions if we output attention weights
|
649 |
+
outputs = self_attention_outputs[1:]
|
650 |
+
|
651 |
+
cross_attention_outputs = self.crossattention(
|
652 |
+
attention_output,
|
653 |
+
attention_mask=attention_mask,
|
654 |
+
head_mask=head_mask,
|
655 |
+
encoder_hidden_states=encoder_hidden_states,
|
656 |
+
encoder_attention_mask=encoder_attention_mask,
|
657 |
+
past_key_value=past_key_value,
|
658 |
+
output_attentions=output_attentions,
|
659 |
+
)
|
660 |
+
attention_output = cross_attention_outputs[0]
|
661 |
+
# add cross attentions if we output attention weights
|
662 |
+
outputs = outputs + cross_attention_outputs[1:-1]
|
663 |
+
|
664 |
+
layer_output = apply_chunking_to_forward(
|
665 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
666 |
+
)
|
667 |
+
outputs = (layer_output,) + outputs
|
668 |
+
|
669 |
+
return outputs
|
670 |
+
|
671 |
+
def feed_forward_chunk(self, attention_output):
|
672 |
+
intermediate_output = self.intermediate(attention_output)
|
673 |
+
layer_output = self.output(intermediate_output, attention_output)
|
674 |
+
return layer_output
|
675 |
+
|
676 |
+
|
677 |
+
class BridgeTowerTextLayer(nn.Module):
|
678 |
+
def __init__(self, config):
|
679 |
+
super().__init__()
|
680 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
681 |
+
self.seq_len_dim = 1
|
682 |
+
self.attention = BridgeTowerAttention(config)
|
683 |
+
self.is_decoder = config.is_decoder
|
684 |
+
self.add_cross_attention = config.add_cross_attention
|
685 |
+
if self.add_cross_attention:
|
686 |
+
if not self.is_decoder:
|
687 |
+
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
|
688 |
+
self.crossattention = BridgeTowerAttention(config, position_embedding_type="absolute")
|
689 |
+
self.intermediate = BridgeTowerIntermediate(config)
|
690 |
+
self.output = BridgeTowerOutput(config)
|
691 |
+
|
692 |
+
def forward(
|
693 |
+
self,
|
694 |
+
hidden_states: torch.Tensor,
|
695 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
696 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
697 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
698 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
699 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
700 |
+
output_attentions: Optional[bool] = False,
|
701 |
+
) -> Tuple[torch.Tensor]:
|
702 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
703 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
704 |
+
self_attention_outputs = self.attention(
|
705 |
+
hidden_states,
|
706 |
+
attention_mask,
|
707 |
+
head_mask,
|
708 |
+
output_attentions=output_attentions,
|
709 |
+
past_key_value=self_attn_past_key_value,
|
710 |
+
)
|
711 |
+
attention_output = self_attention_outputs[0]
|
712 |
+
|
713 |
+
# if decoder, the last output is tuple of self-attn cache
|
714 |
+
if self.is_decoder:
|
715 |
+
outputs = self_attention_outputs[1:-1]
|
716 |
+
present_key_value = self_attention_outputs[-1]
|
717 |
+
else:
|
718 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
719 |
+
|
720 |
+
cross_attn_present_key_value = None
|
721 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
722 |
+
if not hasattr(self, "crossattention"):
|
723 |
+
raise ValueError(
|
724 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
725 |
+
" by setting `config.add_cross_attention=True`"
|
726 |
+
)
|
727 |
+
|
728 |
+
# cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
|
729 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
730 |
+
cross_attention_outputs = self.crossattention(
|
731 |
+
attention_output,
|
732 |
+
attention_mask,
|
733 |
+
head_mask,
|
734 |
+
encoder_hidden_states,
|
735 |
+
encoder_attention_mask,
|
736 |
+
cross_attn_past_key_value,
|
737 |
+
output_attentions,
|
738 |
+
)
|
739 |
+
attention_output = cross_attention_outputs[0]
|
740 |
+
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
|
741 |
+
|
742 |
+
# add cross-attn cache to positions 3,4 of present_key_value tuple
|
743 |
+
cross_attn_present_key_value = cross_attention_outputs[-1]
|
744 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
745 |
+
|
746 |
+
layer_output = apply_chunking_to_forward(
|
747 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
748 |
+
)
|
749 |
+
outputs = (layer_output,) + outputs
|
750 |
+
|
751 |
+
# if decoder, return the attn key/values as the last output
|
752 |
+
if self.is_decoder:
|
753 |
+
outputs = outputs + (present_key_value,)
|
754 |
+
|
755 |
+
return outputs
|
756 |
+
|
757 |
+
def feed_forward_chunk(self, attention_output):
|
758 |
+
intermediate_output = self.intermediate(attention_output)
|
759 |
+
layer_output = self.output(intermediate_output, attention_output)
|
760 |
+
return layer_output
|
761 |
+
|
762 |
+
|
763 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaEncoder with Roberta->BridgeTowerText
|
764 |
+
class BridgeTowerTextEncoder(nn.Module):
|
765 |
+
def __init__(self, config):
|
766 |
+
super().__init__()
|
767 |
+
self.config = config
|
768 |
+
self.layer = nn.ModuleList([BridgeTowerTextLayer(config) for _ in range(config.num_hidden_layers)])
|
769 |
+
self.gradient_checkpointing = False
|
770 |
+
|
771 |
+
def forward(
|
772 |
+
self,
|
773 |
+
hidden_states: torch.Tensor,
|
774 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
775 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
776 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
777 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
778 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
779 |
+
use_cache: Optional[bool] = None,
|
780 |
+
output_attentions: Optional[bool] = False,
|
781 |
+
output_hidden_states: Optional[bool] = False,
|
782 |
+
return_dict: Optional[bool] = True,
|
783 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
|
784 |
+
all_hidden_states = () if output_hidden_states else None
|
785 |
+
all_self_attentions = () if output_attentions else None
|
786 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
787 |
+
|
788 |
+
if self.gradient_checkpointing and self.training:
|
789 |
+
if use_cache:
|
790 |
+
logger.warning_once(
|
791 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
792 |
+
)
|
793 |
+
use_cache = False
|
794 |
+
|
795 |
+
next_decoder_cache = () if use_cache else None
|
796 |
+
for i, layer_module in enumerate(self.layer):
|
797 |
+
if output_hidden_states:
|
798 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
799 |
+
|
800 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
801 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
802 |
+
|
803 |
+
if self.gradient_checkpointing and self.training:
|
804 |
+
layer_outputs = self._gradient_checkpointing_func(
|
805 |
+
layer_module.__call__,
|
806 |
+
hidden_states,
|
807 |
+
attention_mask,
|
808 |
+
layer_head_mask,
|
809 |
+
encoder_hidden_states,
|
810 |
+
encoder_attention_mask,
|
811 |
+
past_key_value,
|
812 |
+
output_attentions,
|
813 |
+
)
|
814 |
+
else:
|
815 |
+
layer_outputs = layer_module(
|
816 |
+
hidden_states,
|
817 |
+
attention_mask,
|
818 |
+
layer_head_mask,
|
819 |
+
encoder_hidden_states,
|
820 |
+
encoder_attention_mask,
|
821 |
+
past_key_value,
|
822 |
+
output_attentions,
|
823 |
+
)
|
824 |
+
|
825 |
+
hidden_states = layer_outputs[0]
|
826 |
+
if use_cache:
|
827 |
+
next_decoder_cache += (layer_outputs[-1],)
|
828 |
+
if output_attentions:
|
829 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
830 |
+
if self.config.add_cross_attention:
|
831 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
832 |
+
|
833 |
+
if output_hidden_states:
|
834 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
835 |
+
|
836 |
+
if not return_dict:
|
837 |
+
return tuple(
|
838 |
+
v
|
839 |
+
for v in [
|
840 |
+
hidden_states,
|
841 |
+
next_decoder_cache,
|
842 |
+
all_hidden_states,
|
843 |
+
all_self_attentions,
|
844 |
+
all_cross_attentions,
|
845 |
+
]
|
846 |
+
if v is not None
|
847 |
+
)
|
848 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
849 |
+
last_hidden_state=hidden_states,
|
850 |
+
past_key_values=next_decoder_cache,
|
851 |
+
hidden_states=all_hidden_states,
|
852 |
+
attentions=all_self_attentions,
|
853 |
+
cross_attentions=all_cross_attentions,
|
854 |
+
)
|
855 |
+
|
856 |
+
|
857 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings with Roberta->BridgeTowerText
|
858 |
+
class BridgeTowerTextEmbeddings(nn.Module):
|
859 |
+
"""
|
860 |
+
Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
|
861 |
+
"""
|
862 |
+
|
863 |
+
# Copied from transformers.models.bert.modeling_bert.BertEmbeddings.__init__
|
864 |
+
def __init__(self, config):
|
865 |
+
super().__init__()
|
866 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
867 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
868 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
869 |
+
|
870 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
871 |
+
# any TensorFlow checkpoint file
|
872 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
873 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
874 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
875 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
876 |
+
self.register_buffer(
|
877 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
878 |
+
)
|
879 |
+
self.register_buffer(
|
880 |
+
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
|
881 |
+
)
|
882 |
+
|
883 |
+
# End copy
|
884 |
+
self.padding_idx = config.pad_token_id
|
885 |
+
self.position_embeddings = nn.Embedding(
|
886 |
+
config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
|
887 |
+
)
|
888 |
+
|
889 |
+
def forward(
|
890 |
+
self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
|
891 |
+
):
|
892 |
+
if position_ids is None:
|
893 |
+
if input_ids is not None:
|
894 |
+
# Create the position ids from the input token ids. Any padded tokens remain padded.
|
895 |
+
position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length)
|
896 |
+
else:
|
897 |
+
position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
|
898 |
+
|
899 |
+
if input_ids is not None:
|
900 |
+
input_shape = input_ids.size()
|
901 |
+
else:
|
902 |
+
input_shape = inputs_embeds.size()[:-1]
|
903 |
+
|
904 |
+
seq_length = input_shape[1]
|
905 |
+
|
906 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
907 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
908 |
+
# issue #5664
|
909 |
+
if token_type_ids is None:
|
910 |
+
if hasattr(self, "token_type_ids"):
|
911 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
912 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
913 |
+
token_type_ids = buffered_token_type_ids_expanded
|
914 |
+
else:
|
915 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
916 |
+
|
917 |
+
if inputs_embeds is None:
|
918 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
919 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
920 |
+
|
921 |
+
embeddings = inputs_embeds + token_type_embeddings
|
922 |
+
if self.position_embedding_type == "absolute":
|
923 |
+
position_embeddings = self.position_embeddings(position_ids)
|
924 |
+
embeddings += position_embeddings
|
925 |
+
embeddings = self.LayerNorm(embeddings)
|
926 |
+
embeddings = self.dropout(embeddings)
|
927 |
+
return embeddings
|
928 |
+
|
929 |
+
def create_position_ids_from_inputs_embeds(self, inputs_embeds):
|
930 |
+
"""
|
931 |
+
We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
|
932 |
+
|
933 |
+
Args:
|
934 |
+
inputs_embeds: torch.Tensor
|
935 |
+
|
936 |
+
Returns: torch.Tensor
|
937 |
+
"""
|
938 |
+
input_shape = inputs_embeds.size()[:-1]
|
939 |
+
sequence_length = input_shape[1]
|
940 |
+
|
941 |
+
position_ids = torch.arange(
|
942 |
+
self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
|
943 |
+
)
|
944 |
+
return position_ids.unsqueeze(0).expand(input_shape)
|
945 |
+
|
946 |
+
|
947 |
+
# Copied from transformers.models.roberta.modeling_roberta.create_position_ids_from_input_ids
|
948 |
+
def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
|
949 |
+
"""
|
950 |
+
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
|
951 |
+
are ignored. This is modified from fairseq's `utils.make_positions`.
|
952 |
+
|
953 |
+
Args:
|
954 |
+
x: torch.Tensor x:
|
955 |
+
|
956 |
+
Returns: torch.Tensor
|
957 |
+
"""
|
958 |
+
# The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
|
959 |
+
mask = input_ids.ne(padding_idx).int()
|
960 |
+
incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
|
961 |
+
return incremental_indices.long() + padding_idx
|
962 |
+
|
963 |
+
|
964 |
+
class BridgeTowerPreTrainedModel(PreTrainedModel):
|
965 |
+
"""
|
966 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
967 |
+
models.
|
968 |
+
"""
|
969 |
+
|
970 |
+
config_class = BridgeTowerConfig
|
971 |
+
base_model_prefix = "bridgetower"
|
972 |
+
supports_gradient_checkpointing = False
|
973 |
+
_no_split_modules = ["BridgeTowerSelfAttention", "BridgeTowerResidualAttention"]
|
974 |
+
_skip_keys_device_placement = "past_key_values"
|
975 |
+
|
976 |
+
def _init_weights(self, module):
|
977 |
+
if isinstance(module, BridgeTowerVisionModel):
|
978 |
+
proj_std = (module.visual.transformer.hidden_size**-0.5) * (
|
979 |
+
(2 * module.visual.transformer.num_hidden_layers) ** -0.5
|
980 |
+
)
|
981 |
+
attn_std = module.visual.transformer.hidden_size**-0.5
|
982 |
+
fc_std = (2 * module.visual.transformer.hidden_size) ** -0.5
|
983 |
+
for block in module.visual.transformer.resblocks:
|
984 |
+
nn.init.normal_(block.attn.in_proj_weight, std=attn_std * self.config.initializer_factor)
|
985 |
+
nn.init.normal_(block.attn.out_proj.weight, std=proj_std * self.config.initializer_factor)
|
986 |
+
nn.init.normal_(block.mlp.c_fc.weight, std=fc_std * self.config.initializer_factor)
|
987 |
+
nn.init.normal_(block.mlp.c_proj.weight, std=proj_std * self.config.initializer_factor)
|
988 |
+
|
989 |
+
nn.init.normal_(module.visual.embeddings.class_embedding, std=attn_std * self.config.initializer_factor)
|
990 |
+
nn.init.normal_(
|
991 |
+
module.visual.embeddings.position_embedding.weight, std=attn_std * self.config.initializer_factor
|
992 |
+
)
|
993 |
+
elif isinstance(module, (nn.Linear, nn.Conv2d, nn.Embedding)):
|
994 |
+
module.weight.data.normal_(mean=0.0, std=0.05 * self.config.initializer_factor)
|
995 |
+
elif isinstance(module, nn.LayerNorm):
|
996 |
+
module.bias.data.zero_()
|
997 |
+
module.weight.data.fill_(1.0)
|
998 |
+
|
999 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
1000 |
+
module.bias.data.zero_()
|
1001 |
+
|
1002 |
+
|
1003 |
+
class BridgeTowerVisionModel(BridgeTowerPreTrainedModel):
|
1004 |
+
config_class = BridgeTowerVisionConfig
|
1005 |
+
|
1006 |
+
def __init__(self, config):
|
1007 |
+
super().__init__(config)
|
1008 |
+
self.visual = BridgeTowerVisionTransformer(config)
|
1009 |
+
|
1010 |
+
@property
|
1011 |
+
def dtype(self):
|
1012 |
+
return self.visual.embeddings.patch_embedding.weight.dtype
|
1013 |
+
|
1014 |
+
def forward(self, image, image_mask=None):
|
1015 |
+
return self.visual(image.type(self.dtype), image_mask)
|
1016 |
+
|
1017 |
+
|
1018 |
+
class BridgeTowerTextModel(BridgeTowerPreTrainedModel):
|
1019 |
+
"""
|
1020 |
+
|
1021 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
1022 |
+
cross-attention is added between the self-attention layers, following the architecture described in *Attention is
|
1023 |
+
all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz
|
1024 |
+
Kaiser and Illia Polosukhin.
|
1025 |
+
|
1026 |
+
To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
|
1027 |
+
to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
|
1028 |
+
`add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
|
1029 |
+
|
1030 |
+
.. _*Attention is all you need*: https://arxiv.org/abs/1706.03762
|
1031 |
+
|
1032 |
+
"""
|
1033 |
+
|
1034 |
+
config_class = BridgeTowerTextConfig
|
1035 |
+
|
1036 |
+
def __init__(self, config, add_pooling_layer=True):
|
1037 |
+
super().__init__(config)
|
1038 |
+
self.config = config
|
1039 |
+
|
1040 |
+
self.embeddings = BridgeTowerTextEmbeddings(config)
|
1041 |
+
self.encoder = BridgeTowerTextEncoder(config)
|
1042 |
+
|
1043 |
+
self.pooler = BridgeTowerPooler(config) if add_pooling_layer else None
|
1044 |
+
|
1045 |
+
# Initialize weights and apply final processing
|
1046 |
+
self.post_init()
|
1047 |
+
|
1048 |
+
def get_input_embeddings(self):
|
1049 |
+
return self.embeddings.word_embeddings
|
1050 |
+
|
1051 |
+
def set_input_embeddings(self, value):
|
1052 |
+
self.embeddings.word_embeddings = value
|
1053 |
+
|
1054 |
+
def _prune_heads(self, heads_to_prune):
|
1055 |
+
"""
|
1056 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
1057 |
+
class PreTrainedModel
|
1058 |
+
"""
|
1059 |
+
for layer, heads in heads_to_prune.items():
|
1060 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
1061 |
+
|
1062 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaModel.forward
|
1063 |
+
def forward(
|
1064 |
+
self,
|
1065 |
+
input_ids: Optional[torch.Tensor] = None,
|
1066 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1067 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
1068 |
+
position_ids: Optional[torch.Tensor] = None,
|
1069 |
+
head_mask: Optional[torch.Tensor] = None,
|
1070 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1071 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
1072 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
1073 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1074 |
+
use_cache: Optional[bool] = None,
|
1075 |
+
output_attentions: Optional[bool] = None,
|
1076 |
+
output_hidden_states: Optional[bool] = None,
|
1077 |
+
return_dict: Optional[bool] = None,
|
1078 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
|
1079 |
+
r"""
|
1080 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
1081 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
1082 |
+
the model is configured as a decoder.
|
1083 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1084 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
1085 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
1086 |
+
|
1087 |
+
- 1 for tokens that are **not masked**,
|
1088 |
+
- 0 for tokens that are **masked**.
|
1089 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
1090 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
1091 |
+
|
1092 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
1093 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
1094 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
1095 |
+
use_cache (`bool`, *optional*):
|
1096 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
1097 |
+
`past_key_values`).
|
1098 |
+
"""
|
1099 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1100 |
+
output_hidden_states = (
|
1101 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1102 |
+
)
|
1103 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1104 |
+
|
1105 |
+
if self.config.is_decoder:
|
1106 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1107 |
+
else:
|
1108 |
+
use_cache = False
|
1109 |
+
|
1110 |
+
if input_ids is not None and inputs_embeds is not None:
|
1111 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
1112 |
+
elif input_ids is not None:
|
1113 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
1114 |
+
input_shape = input_ids.size()
|
1115 |
+
elif inputs_embeds is not None:
|
1116 |
+
input_shape = inputs_embeds.size()[:-1]
|
1117 |
+
else:
|
1118 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
1119 |
+
|
1120 |
+
batch_size, seq_length = input_shape
|
1121 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
1122 |
+
|
1123 |
+
# past_key_values_length
|
1124 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
1125 |
+
|
1126 |
+
if attention_mask is None:
|
1127 |
+
attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
|
1128 |
+
|
1129 |
+
if token_type_ids is None:
|
1130 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
1131 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
1132 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
|
1133 |
+
token_type_ids = buffered_token_type_ids_expanded
|
1134 |
+
else:
|
1135 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
1136 |
+
|
1137 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
1138 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
1139 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
|
1140 |
+
|
1141 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
1142 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
1143 |
+
if self.config.is_decoder and encoder_hidden_states is not None:
|
1144 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
1145 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
1146 |
+
if encoder_attention_mask is None:
|
1147 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
1148 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
1149 |
+
else:
|
1150 |
+
encoder_extended_attention_mask = None
|
1151 |
+
|
1152 |
+
# Prepare head mask if needed
|
1153 |
+
# 1.0 in head_mask indicate we keep the head
|
1154 |
+
# attention_probs has shape bsz x n_heads x N x N
|
1155 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
1156 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
1157 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
1158 |
+
|
1159 |
+
embedding_output = self.embeddings(
|
1160 |
+
input_ids=input_ids,
|
1161 |
+
position_ids=position_ids,
|
1162 |
+
token_type_ids=token_type_ids,
|
1163 |
+
inputs_embeds=inputs_embeds,
|
1164 |
+
past_key_values_length=past_key_values_length,
|
1165 |
+
)
|
1166 |
+
encoder_outputs = self.encoder(
|
1167 |
+
embedding_output,
|
1168 |
+
attention_mask=extended_attention_mask,
|
1169 |
+
head_mask=head_mask,
|
1170 |
+
encoder_hidden_states=encoder_hidden_states,
|
1171 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
1172 |
+
past_key_values=past_key_values,
|
1173 |
+
use_cache=use_cache,
|
1174 |
+
output_attentions=output_attentions,
|
1175 |
+
output_hidden_states=output_hidden_states,
|
1176 |
+
return_dict=return_dict,
|
1177 |
+
)
|
1178 |
+
sequence_output = encoder_outputs[0]
|
1179 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
1180 |
+
|
1181 |
+
if not return_dict:
|
1182 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
1183 |
+
|
1184 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
1185 |
+
last_hidden_state=sequence_output,
|
1186 |
+
pooler_output=pooled_output,
|
1187 |
+
past_key_values=encoder_outputs.past_key_values,
|
1188 |
+
hidden_states=encoder_outputs.hidden_states,
|
1189 |
+
attentions=encoder_outputs.attentions,
|
1190 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
1191 |
+
)
|
1192 |
+
|
1193 |
+
|
1194 |
+
@add_start_docstrings(
|
1195 |
+
"The bare BridgeTower Model transformer outputting BridgeTowerModelOutput object without any specific head on"
|
1196 |
+
" top.",
|
1197 |
+
BRIDGETOWER_START_DOCSTRING,
|
1198 |
+
)
|
1199 |
+
class BridgeTowerModel(BridgeTowerPreTrainedModel):
|
1200 |
+
def __init__(self, config):
|
1201 |
+
super().__init__(config)
|
1202 |
+
self.config = config
|
1203 |
+
vision_config = config.vision_config
|
1204 |
+
text_config = config.text_config
|
1205 |
+
|
1206 |
+
if config.share_cross_modal_transformer_layers:
|
1207 |
+
self.cross_modal_text_transform = nn.Linear(text_config.hidden_size, config.hidden_size)
|
1208 |
+
self.cross_modal_image_transform = nn.Linear(vision_config.hidden_size, config.hidden_size)
|
1209 |
+
else:
|
1210 |
+
self.cross_modal_text_transform = nn.ModuleList(
|
1211 |
+
[nn.Linear(text_config.hidden_size, config.hidden_size) for _ in range(config.num_hidden_layers)]
|
1212 |
+
)
|
1213 |
+
self.cross_modal_image_transform = nn.ModuleList(
|
1214 |
+
[nn.Linear(vision_config.hidden_size, config.hidden_size) for _ in range(config.num_hidden_layers)]
|
1215 |
+
)
|
1216 |
+
|
1217 |
+
self.token_type_embeddings = nn.Embedding(2, config.hidden_size)
|
1218 |
+
|
1219 |
+
self.vision_model = BridgeTowerVisionModel(vision_config)
|
1220 |
+
|
1221 |
+
self.text_model = BridgeTowerTextModel(text_config)
|
1222 |
+
|
1223 |
+
if not vision_config.share_layernorm and config.init_layernorm_from_vision_encoder:
|
1224 |
+
for ln in self.vision_model.visual.cross_modal_ln_separate:
|
1225 |
+
ln.weight.data = self.vision_model.visual.ln_post.weight.data
|
1226 |
+
ln.bias.data = self.vision_model.visual.ln_post.bias.data
|
1227 |
+
|
1228 |
+
self.cross_modal_image_layers = nn.ModuleList(
|
1229 |
+
[BridgeTowerBertCrossLayer(text_config) for _ in range(config.num_hidden_layers)]
|
1230 |
+
)
|
1231 |
+
self.cross_modal_text_layers = nn.ModuleList(
|
1232 |
+
[BridgeTowerBertCrossLayer(text_config) for _ in range(config.num_hidden_layers)]
|
1233 |
+
)
|
1234 |
+
|
1235 |
+
# Class token => Linear => Tanh
|
1236 |
+
self.cross_modal_image_pooler = BridgeTowerPooler(config)
|
1237 |
+
self.cross_modal_text_pooler = BridgeTowerPooler(config)
|
1238 |
+
|
1239 |
+
# Initialize BridgeTower Components
|
1240 |
+
self.cross_modal_text_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
1241 |
+
self.cross_modal_image_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
1242 |
+
|
1243 |
+
if config.share_link_tower_layers:
|
1244 |
+
self.cross_modal_text_link_tower = BridgeTowerLinkTower(config)
|
1245 |
+
self.cross_modal_image_link_tower = BridgeTowerLinkTower(config)
|
1246 |
+
else:
|
1247 |
+
self.cross_modal_text_link_tower = nn.ModuleList(
|
1248 |
+
[BridgeTowerLinkTower(config) for _ in range(config.num_hidden_layers - 1)]
|
1249 |
+
)
|
1250 |
+
self.cross_modal_image_link_tower = nn.ModuleList(
|
1251 |
+
[BridgeTowerLinkTower(config) for _ in range(config.num_hidden_layers - 1)]
|
1252 |
+
)
|
1253 |
+
|
1254 |
+
self.post_init()
|
1255 |
+
|
1256 |
+
def get_input_embeddings(self):
|
1257 |
+
return self.text_model.get_input_embeddings()
|
1258 |
+
|
1259 |
+
def set_input_embeddings(self, value):
|
1260 |
+
self.text_model.set_input_embeddings(value)
|
1261 |
+
|
1262 |
+
@add_start_docstrings_to_model_forward(BRIDGETOWER_INPUTS_DOCSTRING)
|
1263 |
+
@replace_return_docstrings(output_type=BridgeTowerModelOutput, config_class=_CONFIG_FOR_DOC)
|
1264 |
+
def forward(
|
1265 |
+
self,
|
1266 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1267 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1268 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
1269 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
1270 |
+
pixel_mask: Optional[torch.LongTensor] = None,
|
1271 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1272 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1273 |
+
image_embeds: Optional[torch.FloatTensor] = None,
|
1274 |
+
image_token_type_idx: Optional[int] = None,
|
1275 |
+
output_attentions: Optional[bool] = None,
|
1276 |
+
output_hidden_states: Optional[bool] = None,
|
1277 |
+
return_dict: Optional[bool] = None,
|
1278 |
+
labels: Optional[torch.LongTensor] = None,
|
1279 |
+
) -> Union[Tuple[torch.Tensor], BridgeTowerModelOutput]:
|
1280 |
+
r"""
|
1281 |
+
output_hidden_states (`bool`, *optional*):
|
1282 |
+
If set to `True`, hidden states are returned as a list containing the hidden states of text, image, and
|
1283 |
+
cross-modal components respectively. i.e. `(hidden_states_text, hidden_states_image,
|
1284 |
+
hidden_states_cross_modal)` where each element is a list of the hidden states of the corresponding
|
1285 |
+
modality. `hidden_states_txt/img` are a list of tensors corresponding to unimodal hidden states and
|
1286 |
+
`hidden_states_cross_modal` is a list of tuples containing `cross_modal_text_hidden_states` and
|
1287 |
+
`cross_modal_image_hidden_states` of each brdige layer.
|
1288 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1289 |
+
Labels are currently not supported.
|
1290 |
+
Returns:
|
1291 |
+
|
1292 |
+
Examples:
|
1293 |
+
|
1294 |
+
```python
|
1295 |
+
>>> from transformers import BridgeTowerProcessor, BridgeTowerModel
|
1296 |
+
>>> from PIL import Image
|
1297 |
+
>>> import requests
|
1298 |
+
|
1299 |
+
>>> # prepare image and text
|
1300 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
1301 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
1302 |
+
>>> text = "hello world"
|
1303 |
+
>>> processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-base")
|
1304 |
+
>>> model = BridgeTowerModel.from_pretrained("BridgeTower/bridgetower-base")
|
1305 |
+
|
1306 |
+
>>> inputs = processor(image, text, return_tensors="pt")
|
1307 |
+
>>> outputs = model(**inputs)
|
1308 |
+
>>> outputs.keys()
|
1309 |
+
odict_keys(['text_features', 'image_features', 'pooler_output'])
|
1310 |
+
```"""
|
1311 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1312 |
+
output_hidden_states = (
|
1313 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1314 |
+
)
|
1315 |
+
all_hidden_states_text = () if output_hidden_states else None
|
1316 |
+
all_hidden_states_image = () if output_hidden_states else None
|
1317 |
+
all_hidden_states_cross = () if output_hidden_states else None
|
1318 |
+
all_hidden_states = () if output_hidden_states else None
|
1319 |
+
all_self_attentions = () if output_attentions else None
|
1320 |
+
|
1321 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1322 |
+
image_token_type_idx = image_token_type_idx if image_token_type_idx else 1
|
1323 |
+
input_shape = input_ids.size()
|
1324 |
+
text_embeds = self.text_model.embeddings(input_ids=input_ids)
|
1325 |
+
|
1326 |
+
if output_hidden_states:
|
1327 |
+
all_hidden_states_text += (text_embeds,)
|
1328 |
+
|
1329 |
+
if attention_mask is None:
|
1330 |
+
attention_mask = torch.ones(input_shape, dtype=torch.long, device=input_ids.device)
|
1331 |
+
extend_text_masks = self.text_model.get_extended_attention_mask(attention_mask, input_shape).to(
|
1332 |
+
input_ids.device
|
1333 |
+
)
|
1334 |
+
|
1335 |
+
# The split_index determines how many layers of the uni-modal encoder are applied before the cross-modal encoder
|
1336 |
+
split_index = len(self.text_model.encoder.layer) - self.config.num_hidden_layers + 1
|
1337 |
+
|
1338 |
+
# Run the first 'split_index' layers of the textual encoder
|
1339 |
+
for layer in self.text_model.encoder.layer[:split_index]:
|
1340 |
+
text_embeds = layer(text_embeds, extend_text_masks)[0]
|
1341 |
+
|
1342 |
+
if output_hidden_states:
|
1343 |
+
all_hidden_states_text += (text_embeds,)
|
1344 |
+
|
1345 |
+
if image_embeds is None:
|
1346 |
+
image_embeds = self.vision_model.visual.forward_pre(pixel_values.type(self.vision_model.dtype))
|
1347 |
+
else:
|
1348 |
+
# Permute as BridgeTowerResidualAttention has batch_first=True
|
1349 |
+
image_embeds = image_embeds.permute(1, 0, 2)
|
1350 |
+
|
1351 |
+
if output_hidden_states:
|
1352 |
+
all_hidden_states_image += (image_embeds,)
|
1353 |
+
|
1354 |
+
# Run the first 'split_index' layers of the visual encoder
|
1355 |
+
for block in self.vision_model.visual.transformer.resblocks[:split_index]:
|
1356 |
+
image_embeds = block(image_embeds)
|
1357 |
+
if output_hidden_states:
|
1358 |
+
all_hidden_states_image += (image_embeds,)
|
1359 |
+
|
1360 |
+
image_embeds_with_ln = self.vision_model.visual.forward_post(image_embeds.type(self.vision_model.dtype))
|
1361 |
+
|
1362 |
+
# first layer is a special case because we don't have the output from the cross-encoder yet
|
1363 |
+
cross_modal_text = self.cross_modal_text_transform(text_embeds)
|
1364 |
+
|
1365 |
+
text_token_type_embeddings = self.token_type_embeddings(
|
1366 |
+
torch.zeros(1, dtype=torch.long, device=input_ids.device)
|
1367 |
+
).expand_as(cross_modal_text)
|
1368 |
+
|
1369 |
+
cross_modal_text = self.cross_modal_text_layernorm(cross_modal_text + text_token_type_embeddings)
|
1370 |
+
|
1371 |
+
image_embeds_with_ln = self.cross_modal_image_transform(image_embeds_with_ln)
|
1372 |
+
image_token_type_embeddings = self.token_type_embeddings(
|
1373 |
+
torch.full((1,), image_token_type_idx, dtype=torch.long, device=input_ids.device)
|
1374 |
+
).expand_as(image_embeds_with_ln)
|
1375 |
+
|
1376 |
+
image_embeds_with_ln = image_embeds_with_ln + image_token_type_embeddings
|
1377 |
+
cross_modal_image = self.cross_modal_image_layernorm(image_embeds_with_ln)
|
1378 |
+
|
1379 |
+
pixel_mask = torch.ones(
|
1380 |
+
(cross_modal_image.size(0), cross_modal_image.size(1)),
|
1381 |
+
dtype=torch.long,
|
1382 |
+
device=input_ids.device,
|
1383 |
+
)
|
1384 |
+
extend_image_masks = self.text_model.get_extended_attention_mask(pixel_mask, pixel_mask.size()).to(
|
1385 |
+
input_ids.device
|
1386 |
+
)
|
1387 |
+
|
1388 |
+
layer_outputs_text = self.cross_modal_text_layers[0](
|
1389 |
+
cross_modal_text,
|
1390 |
+
cross_modal_image,
|
1391 |
+
attention_mask=extend_text_masks,
|
1392 |
+
encoder_attention_mask=extend_image_masks,
|
1393 |
+
output_attentions=output_attentions,
|
1394 |
+
)
|
1395 |
+
cross_text_features = layer_outputs_text[0]
|
1396 |
+
|
1397 |
+
layer_outputs_image = self.cross_modal_image_layers[0](
|
1398 |
+
cross_modal_image,
|
1399 |
+
cross_modal_text,
|
1400 |
+
attention_mask=extend_image_masks,
|
1401 |
+
encoder_attention_mask=extend_text_masks,
|
1402 |
+
output_attentions=output_attentions,
|
1403 |
+
)
|
1404 |
+
cross_image_features = layer_outputs_image[0]
|
1405 |
+
|
1406 |
+
if output_hidden_states:
|
1407 |
+
all_hidden_states_cross += ((cross_text_features, cross_image_features),)
|
1408 |
+
|
1409 |
+
if output_attentions:
|
1410 |
+
all_self_attentions += ((layer_outputs_text[1], layer_outputs_image[1]),)
|
1411 |
+
|
1412 |
+
link_layer_index = 0
|
1413 |
+
|
1414 |
+
# Each of the top 6 layers of the visual and textual encoders ([split_index:]) is connected to each layer of
|
1415 |
+
# the cross-modal encoder via bridge layers, which brings bottom-up alignment and fusion to the cross-modal encoder.
|
1416 |
+
for i in range(split_index, len(self.text_model.encoder.layer)):
|
1417 |
+
text_embeds = self.text_model.encoder.layer[i](text_embeds, extend_text_masks)[0]
|
1418 |
+
image_embeds = self.vision_model.visual.transformer.resblocks[i](image_embeds).type(
|
1419 |
+
self.vision_model.dtype
|
1420 |
+
)
|
1421 |
+
image_embeds_with_ln = (
|
1422 |
+
self.cross_modal_image_transform(self.vision_model.visual.forward_post(image_embeds))
|
1423 |
+
+ image_token_type_embeddings
|
1424 |
+
)
|
1425 |
+
|
1426 |
+
text_link_tower = self.cross_modal_text_link_tower[link_layer_index]
|
1427 |
+
image_link_tower = self.cross_modal_image_link_tower[link_layer_index]
|
1428 |
+
|
1429 |
+
# Bridge layers for textual and visual encoders
|
1430 |
+
cross_text_features_ = text_link_tower(
|
1431 |
+
self.cross_modal_text_transform(text_embeds) + text_token_type_embeddings,
|
1432 |
+
cross_text_features,
|
1433 |
+
extend_text_masks,
|
1434 |
+
)
|
1435 |
+
cross_image_features_ = image_link_tower(image_embeds_with_ln, cross_image_features, extend_image_masks)
|
1436 |
+
|
1437 |
+
# Cross-modal encoder via bridge layers of textual and visual encoders
|
1438 |
+
layer_outputs_text = self.cross_modal_text_layers[link_layer_index + 1](
|
1439 |
+
cross_text_features_,
|
1440 |
+
cross_image_features_,
|
1441 |
+
attention_mask=extend_text_masks,
|
1442 |
+
encoder_attention_mask=extend_image_masks,
|
1443 |
+
output_attentions=output_attentions,
|
1444 |
+
)
|
1445 |
+
cross_text_features = layer_outputs_text[0]
|
1446 |
+
|
1447 |
+
layer_outputs_image = self.cross_modal_image_layers[link_layer_index + 1](
|
1448 |
+
cross_image_features_,
|
1449 |
+
cross_text_features_,
|
1450 |
+
attention_mask=extend_image_masks,
|
1451 |
+
encoder_attention_mask=extend_text_masks,
|
1452 |
+
output_attentions=output_attentions,
|
1453 |
+
)
|
1454 |
+
cross_image_features = layer_outputs_image[0]
|
1455 |
+
|
1456 |
+
link_layer_index += 1
|
1457 |
+
|
1458 |
+
if output_hidden_states:
|
1459 |
+
all_hidden_states_text += (text_embeds,)
|
1460 |
+
all_hidden_states_image += (image_embeds,)
|
1461 |
+
all_hidden_states_cross += ((cross_text_features, cross_image_features),)
|
1462 |
+
|
1463 |
+
if output_attentions:
|
1464 |
+
all_self_attentions += ((layer_outputs_text[1], layer_outputs_image[1]),)
|
1465 |
+
|
1466 |
+
# Concatenate the cls token of the text and image features to get the final represtation
|
1467 |
+
text_features, image_features = cross_text_features, cross_image_features
|
1468 |
+
cls_features = self.get_cls_features(text_features, image_features)
|
1469 |
+
|
1470 |
+
if output_hidden_states:
|
1471 |
+
all_hidden_states = (all_hidden_states_text, all_hidden_states_image, all_hidden_states_cross)
|
1472 |
+
|
1473 |
+
if not return_dict:
|
1474 |
+
return tuple(
|
1475 |
+
v
|
1476 |
+
for v in [text_features, image_features, cls_features, all_hidden_states, all_self_attentions]
|
1477 |
+
if v is not None
|
1478 |
+
)
|
1479 |
+
|
1480 |
+
return BridgeTowerModelOutput(
|
1481 |
+
text_features=text_features,
|
1482 |
+
image_features=image_features,
|
1483 |
+
pooler_output=cls_features,
|
1484 |
+
hidden_states=all_hidden_states,
|
1485 |
+
attentions=all_self_attentions,
|
1486 |
+
)
|
1487 |
+
|
1488 |
+
def get_cls_features(self, text_features, image_features):
|
1489 |
+
cls_features_text = self.cross_modal_text_pooler(text_features)
|
1490 |
+
cls_features_image = self.cross_modal_image_pooler(image_features)
|
1491 |
+
return torch.cat([cls_features_text, cls_features_image], dim=-1)
|
1492 |
+
|
1493 |
+
|
1494 |
+
# Copied from transformers.models.vilt.modeling_vilt.ViltPredictionHeadTransform with Vilt->BridgeTower
|
1495 |
+
class BridgeTowerPredictionHeadTransform(nn.Module):
|
1496 |
+
def __init__(self, config):
|
1497 |
+
super().__init__()
|
1498 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
1499 |
+
if isinstance(config.hidden_act, str):
|
1500 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
1501 |
+
else:
|
1502 |
+
self.transform_act_fn = config.hidden_act
|
1503 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
1504 |
+
|
1505 |
+
def forward(self, hidden_states):
|
1506 |
+
hidden_states = self.dense(hidden_states)
|
1507 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
1508 |
+
hidden_states = self.LayerNorm(hidden_states)
|
1509 |
+
return hidden_states
|
1510 |
+
|
1511 |
+
|
1512 |
+
class BridgeTowerMLMHead(nn.Module):
|
1513 |
+
def __init__(self, config, weight=None):
|
1514 |
+
super().__init__()
|
1515 |
+
self.config = config
|
1516 |
+
self.transform = BridgeTowerPredictionHeadTransform(config)
|
1517 |
+
self.decoder = nn.Linear(config.hidden_size, config.text_config.vocab_size, bias=False)
|
1518 |
+
self.bias = nn.Parameter(torch.zeros(config.text_config.vocab_size))
|
1519 |
+
if weight is not None:
|
1520 |
+
self.decoder.weight = weight
|
1521 |
+
|
1522 |
+
def forward(self, x):
|
1523 |
+
mlm_score = self.transform(x)
|
1524 |
+
mlm_score = self.decoder(mlm_score) + self.bias
|
1525 |
+
return mlm_score
|
1526 |
+
|
1527 |
+
|
1528 |
+
class BridgeTowerITMHead(nn.Module):
|
1529 |
+
def __init__(self, hidden_size):
|
1530 |
+
super().__init__()
|
1531 |
+
self.fc = nn.Linear(hidden_size, 2)
|
1532 |
+
|
1533 |
+
def forward(self, x):
|
1534 |
+
itm_score = self.fc(x)
|
1535 |
+
return itm_score
|
1536 |
+
|
1537 |
+
|
1538 |
+
@add_start_docstrings(
|
1539 |
+
"""
|
1540 |
+
BridgeTower Model with a language modeling head on top as done during pretraining.
|
1541 |
+
""",
|
1542 |
+
BRIDGETOWER_START_DOCSTRING,
|
1543 |
+
)
|
1544 |
+
class BridgeTowerForMaskedLM(BridgeTowerPreTrainedModel):
|
1545 |
+
_tied_weights_keys = ["mlm_score.decoder.weight"]
|
1546 |
+
|
1547 |
+
def __init__(self, config):
|
1548 |
+
super().__init__(config)
|
1549 |
+
|
1550 |
+
self.bridgetower = BridgeTowerModel(config)
|
1551 |
+
self.mlm_score = BridgeTowerMLMHead(config)
|
1552 |
+
|
1553 |
+
# Initialize weights and apply final processing
|
1554 |
+
self.post_init()
|
1555 |
+
|
1556 |
+
def get_output_embeddings(self):
|
1557 |
+
return self.mlm_score.decoder
|
1558 |
+
|
1559 |
+
def set_output_embeddings(self, new_embeddings):
|
1560 |
+
self.mlm_score.decoder = new_embeddings
|
1561 |
+
|
1562 |
+
@add_start_docstrings_to_model_forward(BRIDGETOWER_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1563 |
+
@replace_return_docstrings(output_type=MaskedLMOutput, config_class=_CONFIG_FOR_DOC)
|
1564 |
+
def forward(
|
1565 |
+
self,
|
1566 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1567 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1568 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
1569 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
1570 |
+
pixel_mask: Optional[torch.LongTensor] = None,
|
1571 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1572 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1573 |
+
image_embeds: Optional[torch.FloatTensor] = None,
|
1574 |
+
output_attentions: Optional[bool] = None,
|
1575 |
+
output_hidden_states: Optional[bool] = None,
|
1576 |
+
return_dict: Optional[bool] = None,
|
1577 |
+
labels: Optional[torch.LongTensor] = None,
|
1578 |
+
) -> Union[MaskedLMOutput, Tuple[torch.FloatTensor]]:
|
1579 |
+
r"""
|
1580 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1581 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
1582 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
1583 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
1584 |
+
Returns:
|
1585 |
+
|
1586 |
+
Examples:
|
1587 |
+
|
1588 |
+
```python
|
1589 |
+
>>> from transformers import BridgeTowerProcessor, BridgeTowerForMaskedLM
|
1590 |
+
>>> from PIL import Image
|
1591 |
+
>>> import requests
|
1592 |
+
|
1593 |
+
>>> url = "http://images.cocodataset.org/val2017/000000360943.jpg"
|
1594 |
+
>>> image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
|
1595 |
+
>>> text = "a <mask> looking out of the window"
|
1596 |
+
|
1597 |
+
>>> processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-base-itm-mlm")
|
1598 |
+
>>> model = BridgeTowerForMaskedLM.from_pretrained("BridgeTower/bridgetower-base-itm-mlm")
|
1599 |
+
|
1600 |
+
>>> # prepare inputs
|
1601 |
+
>>> encoding = processor(image, text, return_tensors="pt")
|
1602 |
+
|
1603 |
+
>>> # forward pass
|
1604 |
+
>>> outputs = model(**encoding)
|
1605 |
+
|
1606 |
+
>>> results = processor.decode(outputs.logits.argmax(dim=-1).squeeze(0).tolist())
|
1607 |
+
|
1608 |
+
>>> print(results)
|
1609 |
+
.a cat looking out of the window.
|
1610 |
+
```"""
|
1611 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1612 |
+
outputs = self.bridgetower(
|
1613 |
+
input_ids,
|
1614 |
+
attention_mask=attention_mask,
|
1615 |
+
token_type_ids=token_type_ids,
|
1616 |
+
pixel_values=pixel_values,
|
1617 |
+
pixel_mask=pixel_mask,
|
1618 |
+
head_mask=head_mask,
|
1619 |
+
inputs_embeds=inputs_embeds,
|
1620 |
+
image_embeds=image_embeds,
|
1621 |
+
output_attentions=output_attentions,
|
1622 |
+
output_hidden_states=output_hidden_states,
|
1623 |
+
return_dict=return_dict,
|
1624 |
+
)
|
1625 |
+
|
1626 |
+
mlm_logits = self.mlm_score(outputs.text_features if return_dict else outputs[0])
|
1627 |
+
masked_lm_loss = None
|
1628 |
+
if labels is not None:
|
1629 |
+
loss_fct = CrossEntropyLoss() # -100 index = padding token
|
1630 |
+
|
1631 |
+
labels = labels.to(mlm_logits.device)
|
1632 |
+
masked_lm_loss = loss_fct(mlm_logits.view(-1, self.config.text_config.vocab_size), labels.view(-1))
|
1633 |
+
|
1634 |
+
if not return_dict:
|
1635 |
+
output = tuple(mlm_logits)
|
1636 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
1637 |
+
|
1638 |
+
return MaskedLMOutput(
|
1639 |
+
loss=masked_lm_loss,
|
1640 |
+
logits=mlm_logits,
|
1641 |
+
hidden_states=outputs.hidden_states,
|
1642 |
+
attentions=outputs.attentions,
|
1643 |
+
)
|
1644 |
+
|
1645 |
+
|
1646 |
+
@add_start_docstrings(
|
1647 |
+
"""
|
1648 |
+
BridgeTower Model transformer with a classifier head on top (a linear layer on top of the final hidden state of the
|
1649 |
+
[CLS] token) for image-to-text matching.
|
1650 |
+
""",
|
1651 |
+
BRIDGETOWER_START_DOCSTRING,
|
1652 |
+
)
|
1653 |
+
class BridgeTowerForImageAndTextRetrieval(BridgeTowerPreTrainedModel):
|
1654 |
+
def __init__(self, config):
|
1655 |
+
super().__init__(config)
|
1656 |
+
|
1657 |
+
self.bridgetower = BridgeTowerModel(config)
|
1658 |
+
|
1659 |
+
self.itm_score = BridgeTowerITMHead(config.hidden_size * 2)
|
1660 |
+
|
1661 |
+
# Initialize weights and apply final processing
|
1662 |
+
self.post_init()
|
1663 |
+
|
1664 |
+
@add_start_docstrings_to_model_forward(BRIDGETOWER_INPUTS_DOCSTRING)
|
1665 |
+
@replace_return_docstrings(output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC)
|
1666 |
+
def forward(
|
1667 |
+
self,
|
1668 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1669 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1670 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
1671 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
1672 |
+
pixel_mask: Optional[torch.LongTensor] = None,
|
1673 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1674 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1675 |
+
image_embeds: Optional[torch.FloatTensor] = None,
|
1676 |
+
output_attentions: Optional[bool] = None,
|
1677 |
+
output_hidden_states: Optional[bool] = None,
|
1678 |
+
return_dict: Optional[bool] = None,
|
1679 |
+
labels: Optional[torch.LongTensor] = None,
|
1680 |
+
) -> Union[SequenceClassifierOutput, Tuple[torch.FloatTensor]]:
|
1681 |
+
r"""
|
1682 |
+
labels (`torch.LongTensor` of shape `(batch_size, 1)`, *optional*):
|
1683 |
+
Labels for computing the image-text matching loss. 0 means the pairs don't match and 1 means they match.
|
1684 |
+
The pairs with 0 will be skipped for calculation.
|
1685 |
+
Returns:
|
1686 |
+
|
1687 |
+
Examples:
|
1688 |
+
|
1689 |
+
```python
|
1690 |
+
>>> from transformers import BridgeTowerProcessor, BridgeTowerForImageAndTextRetrieval
|
1691 |
+
>>> import requests
|
1692 |
+
>>> from PIL import Image
|
1693 |
+
|
1694 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
1695 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
1696 |
+
>>> texts = ["An image of two cats chilling on a couch", "A football player scoring a goal"]
|
1697 |
+
|
1698 |
+
>>> processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-base-itm-mlm")
|
1699 |
+
>>> model = BridgeTowerForImageAndTextRetrieval.from_pretrained("BridgeTower/bridgetower-base-itm-mlm")
|
1700 |
+
|
1701 |
+
>>> # forward pass
|
1702 |
+
>>> scores = dict()
|
1703 |
+
>>> for text in texts:
|
1704 |
+
... # prepare inputs
|
1705 |
+
... encoding = processor(image, text, return_tensors="pt")
|
1706 |
+
... outputs = model(**encoding)
|
1707 |
+
... scores[text] = outputs.logits[0, 1].item()
|
1708 |
+
```"""
|
1709 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1710 |
+
|
1711 |
+
outputs = self.bridgetower(
|
1712 |
+
input_ids,
|
1713 |
+
attention_mask=attention_mask,
|
1714 |
+
token_type_ids=token_type_ids,
|
1715 |
+
pixel_values=pixel_values,
|
1716 |
+
pixel_mask=pixel_mask,
|
1717 |
+
head_mask=head_mask,
|
1718 |
+
inputs_embeds=inputs_embeds,
|
1719 |
+
image_embeds=image_embeds,
|
1720 |
+
output_attentions=output_attentions,
|
1721 |
+
output_hidden_states=output_hidden_states,
|
1722 |
+
return_dict=return_dict,
|
1723 |
+
)
|
1724 |
+
|
1725 |
+
pooler_output = outputs.pooler_output if return_dict else outputs[2]
|
1726 |
+
|
1727 |
+
logits = self.itm_score(pooler_output)
|
1728 |
+
|
1729 |
+
itm_loss = None
|
1730 |
+
if labels is not None:
|
1731 |
+
loss_fct = CrossEntropyLoss()
|
1732 |
+
|
1733 |
+
labels = labels.to(logits.device)
|
1734 |
+
itm_loss = loss_fct(logits, labels)
|
1735 |
+
|
1736 |
+
if not return_dict:
|
1737 |
+
output = tuple(logits)
|
1738 |
+
return ((itm_loss,) + output) if itm_loss is not None else output
|
1739 |
+
|
1740 |
+
return SequenceClassifierOutput(
|
1741 |
+
loss=itm_loss,
|
1742 |
+
logits=logits,
|
1743 |
+
hidden_states=outputs.hidden_states,
|
1744 |
+
attentions=outputs.attentions,
|
1745 |
+
)
|
1746 |
+
|
1747 |
+
|
1748 |
+
class BridgeTowerContrastiveHead(nn.Module):
|
1749 |
+
def __init__(self, hidden_size, embed_size):
|
1750 |
+
super().__init__()
|
1751 |
+
self.fc = nn.Linear(hidden_size, embed_size)
|
1752 |
+
|
1753 |
+
def forward(self, x):
|
1754 |
+
x = self.fc(x)
|
1755 |
+
return x
|
1756 |
+
|
1757 |
+
|
1758 |
+
@add_start_docstrings(
|
1759 |
+
"""
|
1760 |
+
BridgeTower Model with a image-text contrastive head on top computing image-text contrastive loss.
|
1761 |
+
""",
|
1762 |
+
BRIDGETOWER_START_DOCSTRING,
|
1763 |
+
)
|
1764 |
+
class BridgeTowerForContrastiveLearning(BridgeTowerPreTrainedModel):
|
1765 |
+
def __init__(self, config):
|
1766 |
+
super().__init__(config)
|
1767 |
+
|
1768 |
+
self.bridgetower = BridgeTowerModel(config)
|
1769 |
+
|
1770 |
+
self.itc_text_head = BridgeTowerContrastiveHead(config.hidden_size, config.contrastive_hidden_size)
|
1771 |
+
self.itc_image_head = BridgeTowerContrastiveHead(config.hidden_size, config.contrastive_hidden_size)
|
1772 |
+
self.itc_cross_modal_head = BridgeTowerContrastiveHead(config.hidden_size * 2, config.contrastive_hidden_size)
|
1773 |
+
|
1774 |
+
self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
|
1775 |
+
# Initialize weights and apply final processing
|
1776 |
+
self.post_init()
|
1777 |
+
|
1778 |
+
@add_start_docstrings_to_model_forward(BRIDGETOWER_INPUTS_DOCSTRING)
|
1779 |
+
@replace_return_docstrings(output_type=BridgeTowerContrastiveOutput, config_class=_CONFIG_FOR_DOC)
|
1780 |
+
def forward(
|
1781 |
+
self,
|
1782 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1783 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1784 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
1785 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
1786 |
+
pixel_mask: Optional[torch.LongTensor] = None,
|
1787 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1788 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1789 |
+
image_embeds: Optional[torch.FloatTensor] = None,
|
1790 |
+
output_attentions: Optional[bool] = None,
|
1791 |
+
output_hidden_states: Optional[bool] = True,
|
1792 |
+
return_dict: Optional[bool] = None,
|
1793 |
+
return_loss: Optional[bool] = None,
|
1794 |
+
) -> Union[BridgeTowerContrastiveOutput, Tuple[torch.FloatTensor]]:
|
1795 |
+
r"""
|
1796 |
+
return_loss (`bool`, *optional*):
|
1797 |
+
Whether or not to return the contrastive loss.
|
1798 |
+
Returns:
|
1799 |
+
|
1800 |
+
Examples:
|
1801 |
+
|
1802 |
+
```python
|
1803 |
+
>>> from transformers import BridgeTowerProcessor, BridgeTowerForContrastiveLearning
|
1804 |
+
>>> import requests
|
1805 |
+
>>> from PIL import Image
|
1806 |
+
>>> import torch
|
1807 |
+
|
1808 |
+
>>> image_urls = [
|
1809 |
+
... "https://farm4.staticflickr.com/3395/3428278415_81c3e27f15_z.jpg",
|
1810 |
+
... "http://images.cocodataset.org/val2017/000000039769.jpg",
|
1811 |
+
... ]
|
1812 |
+
>>> texts = ["two dogs in a car", "two cats sleeping on a couch"]
|
1813 |
+
>>> images = [Image.open(requests.get(url, stream=True).raw) for url in image_urls]
|
1814 |
+
|
1815 |
+
>>> processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc")
|
1816 |
+
>>> model = BridgeTowerForContrastiveLearning.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc")
|
1817 |
+
|
1818 |
+
>>> inputs = processor(images, texts, padding=True, return_tensors="pt")
|
1819 |
+
>>> loss = model(**inputs, return_loss=True).loss
|
1820 |
+
|
1821 |
+
>>> inputs = processor(images, texts[::-1], padding=True, return_tensors="pt")
|
1822 |
+
>>> loss_swapped = model(**inputs, return_loss=True).loss
|
1823 |
+
|
1824 |
+
>>> print("Loss", round(loss.item(), 4))
|
1825 |
+
Loss 0.0019
|
1826 |
+
|
1827 |
+
>>> print("Loss with swapped images", round(loss_swapped.item(), 4))
|
1828 |
+
Loss with swapped images 2.126
|
1829 |
+
```"""
|
1830 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1831 |
+
|
1832 |
+
outputs = self.bridgetower(
|
1833 |
+
input_ids,
|
1834 |
+
attention_mask=attention_mask,
|
1835 |
+
token_type_ids=token_type_ids,
|
1836 |
+
pixel_values=pixel_values,
|
1837 |
+
pixel_mask=pixel_mask,
|
1838 |
+
head_mask=head_mask,
|
1839 |
+
inputs_embeds=inputs_embeds,
|
1840 |
+
image_embeds=image_embeds,
|
1841 |
+
output_attentions=output_attentions,
|
1842 |
+
output_hidden_states=True,
|
1843 |
+
return_dict=return_dict,
|
1844 |
+
)
|
1845 |
+
|
1846 |
+
pooler_output = outputs.pooler_output if return_dict else outputs[2]
|
1847 |
+
hidden_states_txt, hidden_states_img, hidden_states_cross_modal = (
|
1848 |
+
outputs.hidden_states if return_dict else outputs[3]
|
1849 |
+
)
|
1850 |
+
|
1851 |
+
text_embeds = hidden_states_txt[-1]
|
1852 |
+
image_embeds = hidden_states_img[-1]
|
1853 |
+
|
1854 |
+
image_embeds_with_ln = self.bridgetower.vision_model.visual.forward_post(image_embeds)
|
1855 |
+
image_token_type_embeddings = self.bridgetower.token_type_embeddings(
|
1856 |
+
torch.full((1,), 1, dtype=torch.long, device=self.bridgetower.token_type_embeddings.weight.device)
|
1857 |
+
).expand_as(image_embeds_with_ln)
|
1858 |
+
|
1859 |
+
image_embeds = self.bridgetower.cross_modal_image_transform(image_embeds_with_ln) + image_token_type_embeddings
|
1860 |
+
|
1861 |
+
# normalized features
|
1862 |
+
text_embeds = nn.functional.normalize(self.itc_text_head(text_embeds[:, 0, :]), dim=-1, p=2)
|
1863 |
+
image_embeds = nn.functional.normalize(self.itc_image_head(image_embeds[:, 0, :]), dim=-1, p=2).to(
|
1864 |
+
device=text_embeds.device
|
1865 |
+
)
|
1866 |
+
cross_embeds = nn.functional.normalize(self.itc_cross_modal_head(pooler_output), dim=-1, p=2).to(
|
1867 |
+
device=text_embeds.device
|
1868 |
+
)
|
1869 |
+
|
1870 |
+
logits = torch.stack([text_embeds, image_embeds, cross_embeds], dim=-2)
|
1871 |
+
|
1872 |
+
logit_scale = self.logit_scale.exp().to(device=text_embeds.device)
|
1873 |
+
logits_text_to_image = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
|
1874 |
+
logits_text_to_cross = torch.matmul(text_embeds, cross_embeds.t()) * logit_scale
|
1875 |
+
logits_image_to_cross = torch.matmul(image_embeds, cross_embeds.t()) * logit_scale
|
1876 |
+
|
1877 |
+
itc_loss = None
|
1878 |
+
|
1879 |
+
if return_loss:
|
1880 |
+
labels = torch.arange(len(logits), device=logits.device)
|
1881 |
+
text_to_image_loss = nn.functional.cross_entropy(logits_text_to_image, labels)
|
1882 |
+
text_to_cross_loss = nn.functional.cross_entropy(logits_text_to_cross, labels)
|
1883 |
+
image_to_cross_loss = nn.functional.cross_entropy(logits_image_to_cross, labels)
|
1884 |
+
itc_loss = (text_to_image_loss + text_to_cross_loss + image_to_cross_loss) / 3.0
|
1885 |
+
|
1886 |
+
if not return_dict:
|
1887 |
+
output = (logits, text_embeds, image_embeds, cross_embeds) + outputs[3:]
|
1888 |
+
return ((itc_loss,) + output) if itc_loss is not None else output
|
1889 |
+
|
1890 |
+
return BridgeTowerContrastiveOutput(
|
1891 |
+
loss=itc_loss,
|
1892 |
+
logits=logits,
|
1893 |
+
text_embeds=text_embeds,
|
1894 |
+
image_embeds=image_embeds,
|
1895 |
+
cross_embeds=cross_embeds,
|
1896 |
+
hidden_states=outputs.hidden_states,
|
1897 |
+
attentions=outputs.attentions,
|
1898 |
+
)
|
venv/lib/python3.10/site-packages/transformers/models/bridgetower/processing_bridgetower.py
ADDED
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 The Intel Labs Team Authors, The Microsoft Research Team Authors and 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 |
+
"""
|
16 |
+
Processor class for BridgeTower.
|
17 |
+
"""
|
18 |
+
|
19 |
+
from typing import List, Optional, Union
|
20 |
+
|
21 |
+
from ...processing_utils import ProcessorMixin
|
22 |
+
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
|
23 |
+
from ...utils import TensorType
|
24 |
+
|
25 |
+
|
26 |
+
class BridgeTowerProcessor(ProcessorMixin):
|
27 |
+
r"""
|
28 |
+
Constructs a BridgeTower processor which wraps a Roberta tokenizer and BridgeTower image processor into a single
|
29 |
+
processor.
|
30 |
+
|
31 |
+
[`BridgeTowerProcessor`] offers all the functionalities of [`BridgeTowerImageProcessor`] and
|
32 |
+
[`RobertaTokenizerFast`]. See the docstring of [`~BridgeTowerProcessor.__call__`] and
|
33 |
+
[`~BridgeTowerProcessor.decode`] for more information.
|
34 |
+
|
35 |
+
Args:
|
36 |
+
image_processor (`BridgeTowerImageProcessor`):
|
37 |
+
An instance of [`BridgeTowerImageProcessor`]. The image processor is a required input.
|
38 |
+
tokenizer (`RobertaTokenizerFast`):
|
39 |
+
An instance of ['RobertaTokenizerFast`]. The tokenizer is a required input.
|
40 |
+
"""
|
41 |
+
|
42 |
+
attributes = ["image_processor", "tokenizer"]
|
43 |
+
image_processor_class = "BridgeTowerImageProcessor"
|
44 |
+
tokenizer_class = ("RobertaTokenizer", "RobertaTokenizerFast")
|
45 |
+
|
46 |
+
def __init__(self, image_processor, tokenizer):
|
47 |
+
super().__init__(image_processor, tokenizer)
|
48 |
+
|
49 |
+
def __call__(
|
50 |
+
self,
|
51 |
+
images,
|
52 |
+
text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
|
53 |
+
add_special_tokens: bool = True,
|
54 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
55 |
+
truncation: Union[bool, str, TruncationStrategy] = None,
|
56 |
+
max_length: Optional[int] = None,
|
57 |
+
stride: int = 0,
|
58 |
+
pad_to_multiple_of: Optional[int] = None,
|
59 |
+
return_token_type_ids: Optional[bool] = None,
|
60 |
+
return_attention_mask: Optional[bool] = None,
|
61 |
+
return_overflowing_tokens: bool = False,
|
62 |
+
return_special_tokens_mask: bool = False,
|
63 |
+
return_offsets_mapping: bool = False,
|
64 |
+
return_length: bool = False,
|
65 |
+
verbose: bool = True,
|
66 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
67 |
+
**kwargs,
|
68 |
+
) -> BatchEncoding:
|
69 |
+
"""
|
70 |
+
This method uses [`BridgeTowerImageProcessor.__call__`] method to prepare image(s) for the model, and
|
71 |
+
[`RobertaTokenizerFast.__call__`] to prepare text for the model.
|
72 |
+
|
73 |
+
Please refer to the docstring of the above two methods for more information.
|
74 |
+
"""
|
75 |
+
encoding = self.tokenizer(
|
76 |
+
text=text,
|
77 |
+
add_special_tokens=add_special_tokens,
|
78 |
+
padding=padding,
|
79 |
+
truncation=truncation,
|
80 |
+
max_length=max_length,
|
81 |
+
stride=stride,
|
82 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
83 |
+
return_token_type_ids=return_token_type_ids,
|
84 |
+
return_attention_mask=return_attention_mask,
|
85 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
86 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
87 |
+
return_offsets_mapping=return_offsets_mapping,
|
88 |
+
return_length=return_length,
|
89 |
+
verbose=verbose,
|
90 |
+
return_tensors=return_tensors,
|
91 |
+
**kwargs,
|
92 |
+
)
|
93 |
+
# add pixel_values + pixel_mask
|
94 |
+
encoding_image_processor = self.image_processor(
|
95 |
+
images, return_tensors=return_tensors, do_normalize=True, do_center_crop=True, **kwargs
|
96 |
+
)
|
97 |
+
encoding.update(encoding_image_processor)
|
98 |
+
|
99 |
+
return encoding
|
100 |
+
|
101 |
+
def batch_decode(self, *args, **kwargs):
|
102 |
+
"""
|
103 |
+
This method forwards all its arguments to RobertaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
|
104 |
+
refer to the docstring of this method for more information.
|
105 |
+
"""
|
106 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
107 |
+
|
108 |
+
def decode(self, *args, **kwargs):
|
109 |
+
"""
|
110 |
+
This method forwards all its arguments to RobertaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer
|
111 |
+
to the docstring of this method for more information.
|
112 |
+
"""
|
113 |
+
return self.tokenizer.decode(*args, **kwargs)
|
114 |
+
|
115 |
+
@property
|
116 |
+
def model_input_names(self):
|
117 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
118 |
+
image_processor_input_names = self.image_processor.model_input_names
|
119 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
venv/lib/python3.10/site-packages/transformers/models/conditional_detr/__init__.py
ADDED
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2022 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 typing import TYPE_CHECKING
|
16 |
+
|
17 |
+
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
|
18 |
+
|
19 |
+
|
20 |
+
_import_structure = {
|
21 |
+
"configuration_conditional_detr": [
|
22 |
+
"CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP",
|
23 |
+
"ConditionalDetrConfig",
|
24 |
+
"ConditionalDetrOnnxConfig",
|
25 |
+
]
|
26 |
+
}
|
27 |
+
|
28 |
+
try:
|
29 |
+
if not is_vision_available():
|
30 |
+
raise OptionalDependencyNotAvailable()
|
31 |
+
except OptionalDependencyNotAvailable:
|
32 |
+
pass
|
33 |
+
else:
|
34 |
+
_import_structure["feature_extraction_conditional_detr"] = ["ConditionalDetrFeatureExtractor"]
|
35 |
+
_import_structure["image_processing_conditional_detr"] = ["ConditionalDetrImageProcessor"]
|
36 |
+
|
37 |
+
try:
|
38 |
+
if not is_torch_available():
|
39 |
+
raise OptionalDependencyNotAvailable()
|
40 |
+
except OptionalDependencyNotAvailable:
|
41 |
+
pass
|
42 |
+
else:
|
43 |
+
_import_structure["modeling_conditional_detr"] = [
|
44 |
+
"CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST",
|
45 |
+
"ConditionalDetrForObjectDetection",
|
46 |
+
"ConditionalDetrForSegmentation",
|
47 |
+
"ConditionalDetrModel",
|
48 |
+
"ConditionalDetrPreTrainedModel",
|
49 |
+
]
|
50 |
+
|
51 |
+
|
52 |
+
if TYPE_CHECKING:
|
53 |
+
from .configuration_conditional_detr import (
|
54 |
+
CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP,
|
55 |
+
ConditionalDetrConfig,
|
56 |
+
ConditionalDetrOnnxConfig,
|
57 |
+
)
|
58 |
+
|
59 |
+
try:
|
60 |
+
if not is_vision_available():
|
61 |
+
raise OptionalDependencyNotAvailable()
|
62 |
+
except OptionalDependencyNotAvailable:
|
63 |
+
pass
|
64 |
+
else:
|
65 |
+
from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor
|
66 |
+
from .image_processing_conditional_detr import ConditionalDetrImageProcessor
|
67 |
+
|
68 |
+
try:
|
69 |
+
if not is_torch_available():
|
70 |
+
raise OptionalDependencyNotAvailable()
|
71 |
+
except OptionalDependencyNotAvailable:
|
72 |
+
pass
|
73 |
+
else:
|
74 |
+
from .modeling_conditional_detr import (
|
75 |
+
CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST,
|
76 |
+
ConditionalDetrForObjectDetection,
|
77 |
+
ConditionalDetrForSegmentation,
|
78 |
+
ConditionalDetrModel,
|
79 |
+
ConditionalDetrPreTrainedModel,
|
80 |
+
)
|
81 |
+
|
82 |
+
else:
|
83 |
+
import sys
|
84 |
+
|
85 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
venv/lib/python3.10/site-packages/transformers/models/conditional_detr/modeling_conditional_detr.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
venv/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/__init__.py
ADDED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2022 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 ...file_utils import _LazyModule, is_torch_available
|
17 |
+
from ...utils import OptionalDependencyNotAvailable
|
18 |
+
|
19 |
+
|
20 |
+
_import_structure = {
|
21 |
+
"configuration_gpt_neox_japanese": ["GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoXJapaneseConfig"],
|
22 |
+
"tokenization_gpt_neox_japanese": ["GPTNeoXJapaneseTokenizer"],
|
23 |
+
}
|
24 |
+
|
25 |
+
try:
|
26 |
+
if not is_torch_available():
|
27 |
+
raise OptionalDependencyNotAvailable()
|
28 |
+
except OptionalDependencyNotAvailable:
|
29 |
+
pass
|
30 |
+
else:
|
31 |
+
_import_structure["modeling_gpt_neox_japanese"] = [
|
32 |
+
"GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST",
|
33 |
+
"GPTNeoXJapaneseForCausalLM",
|
34 |
+
"GPTNeoXJapaneseLayer",
|
35 |
+
"GPTNeoXJapaneseModel",
|
36 |
+
"GPTNeoXJapanesePreTrainedModel",
|
37 |
+
]
|
38 |
+
|
39 |
+
|
40 |
+
if TYPE_CHECKING:
|
41 |
+
from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig
|
42 |
+
from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer
|
43 |
+
|
44 |
+
try:
|
45 |
+
if not is_torch_available():
|
46 |
+
raise OptionalDependencyNotAvailable()
|
47 |
+
except OptionalDependencyNotAvailable:
|
48 |
+
pass
|
49 |
+
else:
|
50 |
+
from .modeling_gpt_neox_japanese import (
|
51 |
+
GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST,
|
52 |
+
GPTNeoXJapaneseForCausalLM,
|
53 |
+
GPTNeoXJapaneseLayer,
|
54 |
+
GPTNeoXJapaneseModel,
|
55 |
+
GPTNeoXJapanesePreTrainedModel,
|
56 |
+
)
|
57 |
+
|
58 |
+
|
59 |
+
else:
|
60 |
+
import sys
|
61 |
+
|
62 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
venv/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.15 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/__pycache__/configuration_gpt_neox_japanese.cpython-310.pyc
ADDED
Binary file (5.02 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/__pycache__/modeling_gpt_neox_japanese.cpython-310.pyc
ADDED
Binary file (23.3 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/__pycache__/tokenization_gpt_neox_japanese.cpython-310.pyc
ADDED
Binary file (15.3 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/configuration_gpt_neox_japanese.py
ADDED
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 ABEJA, 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 |
+
""" GPTNeoX Japanese 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 |
+
from ..deprecated._archive_maps import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP # noqa: F401, E402
|
25 |
+
|
26 |
+
|
27 |
+
class GPTNeoXJapaneseConfig(PretrainedConfig):
|
28 |
+
r"""
|
29 |
+
This is the configuration class to store the configuration of a [`GPTNeoXModelJapanese`]. It is used to instantiate
|
30 |
+
a GPTNeoX model according to the specified arguments, defining the model architecture. Instantiating a
|
31 |
+
configuration with the defaults will yield a similar configuration to that of the GPTNeoXJapanese
|
32 |
+
[abeja/gpt-neox-japanese-2.7b](https://huggingface.co/abeja/gpt-neox-japanese-2.7b) architecture.
|
33 |
+
|
34 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
35 |
+
documentation from [`PretrainedConfig`] for more information. Default configs is set as 2.7B model
|
36 |
+
|
37 |
+
Args:
|
38 |
+
vocab_size (`int`, *optional*, defaults to 32000):
|
39 |
+
Vocabulary size of the GPTNeoXJapanese model. Defines the number of different tokens that can be
|
40 |
+
represented by the `inputs_ids` passed when calling [`GPTNeoXJapanese`].
|
41 |
+
hidden_size (`int`, *optional*, defaults to 2560):
|
42 |
+
Dimension of the encoder layers and the pooler layer.
|
43 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
44 |
+
Number of hidden layers in the Transformer encoder.
|
45 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
46 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
47 |
+
intermediate_multiple_size (`int`, *optional*, defaults to 4):
|
48 |
+
Dimension of the "intermediate" layer in the Transformer encoder is calculated by hidden_size *
|
49 |
+
intermediate_multiple_size.
|
50 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
51 |
+
The non-linear activation function (function or string) in the encoder and pooler.
|
52 |
+
rotary_pct (`float`, *optional*, defaults to 1.00):
|
53 |
+
percentage of hidden dimensions to allocate to rotary embeddings
|
54 |
+
rotary_emb_base (`int`, *optional*, defaults to 10000)
|
55 |
+
base for computing rotary embeddings frequency
|
56 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
57 |
+
The maximum sequence length that this model might ever be used with.
|
58 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
59 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
60 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-5):
|
61 |
+
The epsilon used by the layer normalization layers.
|
62 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
63 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
64 |
+
relevant if `config.is_decoder=True`.
|
65 |
+
attention_dropout (`float`, *optional*, defaults to 0.1):
|
66 |
+
The dropout ratio for the attention.
|
67 |
+
hidden_dropout (`float`, *optional*, defaults to 0.0):
|
68 |
+
The dropout ratio for the hidden layer.
|
69 |
+
Example:
|
70 |
+
|
71 |
+
```python
|
72 |
+
>>> from transformers import GPTNeoXJapaneseConfig, GPTNeoXJapaneseModel
|
73 |
+
|
74 |
+
>>> # Initializing a GPTNeoXJapanese gpt-neox-japanese-2.7b style configuration
|
75 |
+
>>> configuration = GPTNeoXJapaneseConfig()
|
76 |
+
|
77 |
+
>>> # Initializing a model (with random weights) from the gpt-neox-japanese-2.7b style configuration
|
78 |
+
>>> model = GPTNeoXJapaneseModel(configuration)
|
79 |
+
|
80 |
+
>>> # Accessing the model configuration
|
81 |
+
>>> configuration = model.config
|
82 |
+
```"""
|
83 |
+
|
84 |
+
model_type = "gpt_neox_japanese"
|
85 |
+
|
86 |
+
def __init__(
|
87 |
+
self,
|
88 |
+
vocab_size=32000,
|
89 |
+
hidden_size=2560,
|
90 |
+
num_hidden_layers=32,
|
91 |
+
num_attention_heads=32,
|
92 |
+
intermediate_multiple_size=4,
|
93 |
+
hidden_act="gelu",
|
94 |
+
rotary_pct=1.00,
|
95 |
+
rotary_emb_base=10000,
|
96 |
+
max_position_embeddings=2048,
|
97 |
+
initializer_range=0.02,
|
98 |
+
layer_norm_eps=1e-5,
|
99 |
+
use_cache=True,
|
100 |
+
bos_token_id=31996,
|
101 |
+
eos_token_id=31999,
|
102 |
+
attention_dropout=0.1,
|
103 |
+
hidden_dropout=0.0,
|
104 |
+
**kwargs,
|
105 |
+
):
|
106 |
+
super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
107 |
+
self.vocab_size = vocab_size
|
108 |
+
self.max_position_embeddings = max_position_embeddings
|
109 |
+
self.hidden_size = hidden_size
|
110 |
+
self.num_hidden_layers = num_hidden_layers
|
111 |
+
self.num_attention_heads = num_attention_heads
|
112 |
+
self.intermediate_multiple_size = intermediate_multiple_size
|
113 |
+
self.hidden_act = hidden_act
|
114 |
+
self.rotary_pct = rotary_pct
|
115 |
+
self.rotary_emb_base = rotary_emb_base
|
116 |
+
self.initializer_range = initializer_range
|
117 |
+
self.layer_norm_eps = layer_norm_eps
|
118 |
+
self.use_cache = use_cache
|
119 |
+
self.attention_dropout = attention_dropout
|
120 |
+
self.hidden_dropout = hidden_dropout
|
venv/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/modeling_gpt_neox_japanese.py
ADDED
@@ -0,0 +1,729 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 ABEJA, 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 GPTNeoX model."""
|
16 |
+
|
17 |
+
from typing import Optional, Tuple, Union
|
18 |
+
|
19 |
+
import torch
|
20 |
+
import torch.utils.checkpoint
|
21 |
+
from torch import Tensor, nn
|
22 |
+
from torch.nn import CrossEntropyLoss
|
23 |
+
|
24 |
+
from ...activations import ACT2FN
|
25 |
+
from ...file_utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings
|
26 |
+
from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
27 |
+
from ...modeling_utils import PreTrainedModel
|
28 |
+
from ...utils import logging
|
29 |
+
from .configuration_gpt_neox_japanese import GPTNeoXJapaneseConfig
|
30 |
+
|
31 |
+
|
32 |
+
logger = logging.get_logger(__name__)
|
33 |
+
|
34 |
+
_CHECKPOINT_FOR_DOC = "abeja/gpt-neox-japanese-2.7b"
|
35 |
+
_CONFIG_FOR_DOC = "GPTNeoXJapaneseConfig"
|
36 |
+
|
37 |
+
|
38 |
+
from ..deprecated._archive_maps import GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST # noqa: F401, E402
|
39 |
+
|
40 |
+
|
41 |
+
class GPTNeoXJapanesePreTrainedModel(PreTrainedModel):
|
42 |
+
"""
|
43 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
44 |
+
models.
|
45 |
+
"""
|
46 |
+
|
47 |
+
config_class = GPTNeoXJapaneseConfig
|
48 |
+
base_model_prefix = "gpt_neox_japanese"
|
49 |
+
_no_split_modules = ["GPTNeoXJapaneseLayer"]
|
50 |
+
_skip_keys_device_placement = "past_key_values"
|
51 |
+
|
52 |
+
def _init_weights(self, module):
|
53 |
+
"""Initialize the weights"""
|
54 |
+
if isinstance(module, nn.Linear):
|
55 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
56 |
+
if module.bias is not None:
|
57 |
+
module.bias.data.zero_()
|
58 |
+
elif isinstance(module, nn.Embedding):
|
59 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
60 |
+
if module.padding_idx is not None:
|
61 |
+
module.weight.data[module.padding_idx].zero_()
|
62 |
+
elif isinstance(module, nn.LayerNorm):
|
63 |
+
module.bias.data.zero_()
|
64 |
+
module.weight.data.fill_(1.0)
|
65 |
+
|
66 |
+
|
67 |
+
class GPTNeoXJapaneseAttention(nn.Module):
|
68 |
+
def __init__(self, config, use_bias=False):
|
69 |
+
super().__init__()
|
70 |
+
self.num_attention_heads = config.num_attention_heads
|
71 |
+
self.hidden_size = config.hidden_size
|
72 |
+
self.head_size = self.hidden_size // self.num_attention_heads
|
73 |
+
|
74 |
+
self.rotary_ndims = int(self.head_size * config.rotary_pct)
|
75 |
+
self.rotary_emb = RotaryEmbedding(
|
76 |
+
self.rotary_ndims, config.max_position_embeddings, base=config.rotary_emb_base
|
77 |
+
)
|
78 |
+
self.max_positions = config.max_position_embeddings
|
79 |
+
self.attention_dropout = nn.Dropout(config.attention_dropout)
|
80 |
+
self.norm_factor = torch.sqrt(torch.tensor(self.head_size, dtype=torch.float32)).to(torch.get_default_dtype())
|
81 |
+
|
82 |
+
self.query_key_value = nn.Linear(config.hidden_size, 3 * config.hidden_size, bias=False)
|
83 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
|
84 |
+
# Activate bias if the last layer
|
85 |
+
self.use_bias = use_bias
|
86 |
+
self.dense_bias = nn.Parameter(torch.zeros(config.hidden_size)) if use_bias else None
|
87 |
+
|
88 |
+
def forward(
|
89 |
+
self,
|
90 |
+
hidden_states,
|
91 |
+
attention_mask,
|
92 |
+
head_mask=None,
|
93 |
+
layer_past=None,
|
94 |
+
use_cache=False,
|
95 |
+
output_attentions=False,
|
96 |
+
):
|
97 |
+
has_layer_past = layer_past is not None and layer_past[0].numel() > 0
|
98 |
+
|
99 |
+
# Compute QKV
|
100 |
+
# Attention heads [batch, seq_len, hidden_size]
|
101 |
+
# --> [batch, seq_len, (np * 3 * head_size)]
|
102 |
+
qkv = self.query_key_value(hidden_states)
|
103 |
+
|
104 |
+
# [batch, seq_len, (num_heads * 3 * head_size)]
|
105 |
+
# --> [batch, seq_len, num_heads, 3 * head_size]
|
106 |
+
new_qkv_shape = qkv.size()[:-1] + (self.num_attention_heads, 3 * self.head_size)
|
107 |
+
qkv = qkv.view(*new_qkv_shape)
|
108 |
+
|
109 |
+
# [batch, seq_len, num_attention_heads, 3 * head_size] --> 3 [batch, num_attention_heads, seq_len, head_size]
|
110 |
+
query = qkv[..., : self.head_size].permute(0, 2, 1, 3)
|
111 |
+
key = qkv[..., self.head_size : 2 * self.head_size].permute(0, 2, 1, 3)
|
112 |
+
value = qkv[..., 2 * self.head_size :].permute(0, 2, 1, 3)
|
113 |
+
|
114 |
+
# Compute rotary embeddings on rotary_ndims
|
115 |
+
query_rot = query[..., : self.rotary_ndims]
|
116 |
+
query_pass = query[..., self.rotary_ndims :]
|
117 |
+
key_rot = key[..., : self.rotary_ndims]
|
118 |
+
key_pass = key[..., self.rotary_ndims :]
|
119 |
+
|
120 |
+
# Compute token offset for rotary embeddings (when decoding)
|
121 |
+
seq_len = key.shape[-2]
|
122 |
+
offset = 0
|
123 |
+
if has_layer_past:
|
124 |
+
offset = layer_past[0].shape[-2]
|
125 |
+
seq_len += offset
|
126 |
+
cos, sin = self.rotary_emb(value, seq_len=seq_len)
|
127 |
+
query, key = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, offset=offset)
|
128 |
+
query = torch.cat((query, query_pass), dim=-1)
|
129 |
+
key = torch.cat((key, key_pass), dim=-1)
|
130 |
+
|
131 |
+
# Cache QKV values
|
132 |
+
if has_layer_past:
|
133 |
+
past_key = layer_past[0]
|
134 |
+
past_value = layer_past[1]
|
135 |
+
key = torch.cat((past_key, key), dim=-2)
|
136 |
+
value = torch.cat((past_value, value), dim=-2)
|
137 |
+
present = (key, value) if use_cache else None
|
138 |
+
|
139 |
+
# Compute attention
|
140 |
+
attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
|
141 |
+
|
142 |
+
# Reshape outputs
|
143 |
+
attn_output = self._merge_heads(attn_output, self.num_attention_heads, self.head_size)
|
144 |
+
attn_output = self.dense(attn_output)
|
145 |
+
|
146 |
+
outputs = (attn_output, present)
|
147 |
+
if output_attentions:
|
148 |
+
outputs += (attn_weights,)
|
149 |
+
|
150 |
+
return outputs, self.dense_bias
|
151 |
+
|
152 |
+
@classmethod
|
153 |
+
def _split_heads(cls, tensor, num_attention_heads, attn_head_size):
|
154 |
+
"""
|
155 |
+
Splits hidden dim into attn_head_size and num_attention_heads
|
156 |
+
"""
|
157 |
+
# tensor: [bs, seq_len, hidden_size]
|
158 |
+
new_shape = tensor.size()[:-1] + (num_attention_heads, attn_head_size)
|
159 |
+
# -> [bs, seq_len, num_attention_heads, attn_head_size]
|
160 |
+
tensor = tensor.view(new_shape)
|
161 |
+
# -> [bs, num_attention_heads, seq_len, attn_head_size]
|
162 |
+
tensor = tensor.permute(0, 2, 1, 3)
|
163 |
+
return tensor
|
164 |
+
|
165 |
+
@classmethod
|
166 |
+
def _merge_heads(cls, tensor, num_attention_heads, attn_head_size):
|
167 |
+
"""
|
168 |
+
Merges attn_head_size dim and num_attn_heads dim into hidden dim
|
169 |
+
"""
|
170 |
+
# tensor [bs, num_attention_heads, seq_len, attn_head_size]
|
171 |
+
tensor = tensor.permute(0, 2, 1, 3).contiguous()
|
172 |
+
# -> [bs, seq_len, num_attention_heads, attn_head_size]
|
173 |
+
tensor = tensor.view(tensor.size(0), tensor.size(1), num_attention_heads * attn_head_size)
|
174 |
+
# -> [bs, seq_len, hidden_size]
|
175 |
+
return tensor
|
176 |
+
|
177 |
+
def _create_causal_mask(self, key_length, query_length):
|
178 |
+
causal_mask = torch.tril(
|
179 |
+
torch.ones((self.max_positions, self.max_positions), dtype=torch.bool).view(
|
180 |
+
1, 1, self.max_positions, self.max_positions
|
181 |
+
)
|
182 |
+
)
|
183 |
+
return causal_mask[:, :, key_length - query_length : key_length, :key_length]
|
184 |
+
|
185 |
+
def _attn(self, query, key, value, attention_mask=None, head_mask=None):
|
186 |
+
# q, k, v: [bs, num_attention_heads, seq_len, attn_head_size]
|
187 |
+
# compute causal mask from causal mask buffer
|
188 |
+
batch_size, num_attention_heads, query_length, attn_head_size = query.size()
|
189 |
+
key_length = key.size(-2)
|
190 |
+
|
191 |
+
causal_mask = self._create_causal_mask(key_length, query_length)
|
192 |
+
|
193 |
+
query = query.view(batch_size * num_attention_heads, query_length, attn_head_size)
|
194 |
+
key = key.view(batch_size * num_attention_heads, key_length, attn_head_size)
|
195 |
+
attn_scores = torch.zeros(
|
196 |
+
batch_size * num_attention_heads,
|
197 |
+
query_length,
|
198 |
+
key_length,
|
199 |
+
dtype=query.dtype,
|
200 |
+
device=key.device,
|
201 |
+
)
|
202 |
+
attn_scores = torch.baddbmm(
|
203 |
+
attn_scores,
|
204 |
+
query,
|
205 |
+
key.transpose(1, 2),
|
206 |
+
beta=1.0,
|
207 |
+
alpha=(torch.tensor(1.0, dtype=self.norm_factor.dtype, device=self.norm_factor.device) / self.norm_factor),
|
208 |
+
)
|
209 |
+
attn_scores = attn_scores.view(batch_size, num_attention_heads, query_length, key_length)
|
210 |
+
|
211 |
+
mask_value = torch.finfo(attn_scores.dtype).min
|
212 |
+
# Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
|
213 |
+
# Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
|
214 |
+
mask_value = torch.tensor(mask_value, dtype=attn_scores.dtype).to(attn_scores.device)
|
215 |
+
causal_mask = causal_mask.to(attn_scores.device)
|
216 |
+
attn_scores = torch.where(causal_mask, attn_scores, mask_value)
|
217 |
+
|
218 |
+
if attention_mask is not None:
|
219 |
+
# Apply the attention mask
|
220 |
+
attn_scores = attn_scores + attention_mask
|
221 |
+
|
222 |
+
attn_weights = nn.functional.softmax(attn_scores, dim=-1)
|
223 |
+
attn_weights = self.attention_dropout(attn_weights)
|
224 |
+
attn_weights = attn_weights.to(value.dtype)
|
225 |
+
|
226 |
+
# Mask heads if we want to
|
227 |
+
if head_mask is not None:
|
228 |
+
attn_weights = attn_weights * head_mask
|
229 |
+
|
230 |
+
attn_output = torch.matmul(attn_weights, value)
|
231 |
+
return attn_output, attn_weights
|
232 |
+
|
233 |
+
|
234 |
+
# Copied from transformers.models.gpt_neox.modeling_gpt_neox.GPTNeoXRotaryEmbedding with GPTNeoXRotaryEmbedding->RotaryEmbedding
|
235 |
+
class RotaryEmbedding(nn.Module):
|
236 |
+
# Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding.__init__
|
237 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
238 |
+
super().__init__()
|
239 |
+
|
240 |
+
self.dim = dim
|
241 |
+
self.max_position_embeddings = max_position_embeddings
|
242 |
+
self.base = base
|
243 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
|
244 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
245 |
+
|
246 |
+
# Build here to make `torch.jit.trace` work.
|
247 |
+
self._set_cos_sin_cache(
|
248 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
249 |
+
)
|
250 |
+
|
251 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
252 |
+
self.max_seq_len_cached = seq_len
|
253 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
|
254 |
+
|
255 |
+
freqs = torch.outer(t, self.inv_freq)
|
256 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
257 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
258 |
+
self.register_buffer("cos_cached", emb.cos(), persistent=False)
|
259 |
+
self.register_buffer("sin_cached", emb.sin(), persistent=False)
|
260 |
+
|
261 |
+
def forward(self, x, seq_len=None):
|
262 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
263 |
+
if seq_len > self.max_seq_len_cached:
|
264 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
265 |
+
|
266 |
+
return (
|
267 |
+
self.cos_cached[:seq_len],
|
268 |
+
self.sin_cached[:seq_len],
|
269 |
+
)
|
270 |
+
|
271 |
+
|
272 |
+
def rotate_half(x):
|
273 |
+
"""Rotates half the hidden dims of the input."""
|
274 |
+
x1 = x[..., : x.shape[-1] // 2]
|
275 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
276 |
+
return torch.cat((-x2, x1), dim=-1)
|
277 |
+
|
278 |
+
|
279 |
+
def apply_rotary_pos_emb(q, k, cos, sin, offset: int = 0):
|
280 |
+
cos = cos[..., offset : q.shape[-2] + offset, :]
|
281 |
+
sin = sin[..., offset : q.shape[-2] + offset, :]
|
282 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
283 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
284 |
+
return q_embed, k_embed
|
285 |
+
|
286 |
+
|
287 |
+
def bias_dropout_add(x: Tensor, bias: Tensor, residual: Optional[Tensor], prob: float, training: bool) -> Tensor:
|
288 |
+
"""add bias to x, apply dropout and residual connection
|
289 |
+
|
290 |
+
Args:
|
291 |
+
x (Tensor): main path of output
|
292 |
+
bias (Tensor): None or attn_bias of the last attention layer
|
293 |
+
residual (Optional[Tensor]): residual value
|
294 |
+
prob (float): dropout probability
|
295 |
+
training (bool): whether in training mode or not
|
296 |
+
|
297 |
+
Returns:
|
298 |
+
Tensor: dropout(x + bias) + residual
|
299 |
+
"""
|
300 |
+
if bias is not None:
|
301 |
+
x = x + bias
|
302 |
+
out = torch.nn.functional.dropout(x, p=prob, training=training)
|
303 |
+
if residual is not None:
|
304 |
+
out = residual + out
|
305 |
+
return out
|
306 |
+
|
307 |
+
|
308 |
+
class GPTNeoXJapaneseMLP(nn.Module):
|
309 |
+
def __init__(self, config):
|
310 |
+
super().__init__()
|
311 |
+
intermediate_size = int(config.hidden_size * config.intermediate_multiple_size)
|
312 |
+
self.dense_h_to_4h = nn.Linear(config.hidden_size, intermediate_size, bias=False)
|
313 |
+
# Project back to h.
|
314 |
+
self.dense_4h_to_h = nn.Linear(intermediate_size, config.hidden_size, bias=False)
|
315 |
+
self.act = ACT2FN[config.hidden_act]
|
316 |
+
|
317 |
+
def forward(self, hidden_states):
|
318 |
+
intermediate = self.dense_h_to_4h(hidden_states)
|
319 |
+
intermediate = self.act(intermediate)
|
320 |
+
output = self.dense_4h_to_h(intermediate)
|
321 |
+
return output
|
322 |
+
|
323 |
+
|
324 |
+
class GPTNeoXJapaneseLayer(nn.Module):
|
325 |
+
def __init__(self, config, layer_number):
|
326 |
+
super().__init__()
|
327 |
+
self.layer_number = layer_number
|
328 |
+
self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
329 |
+
self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
330 |
+
# activate bias only last layer
|
331 |
+
self.attention = GPTNeoXJapaneseAttention(config=config, use_bias=layer_number == config.num_hidden_layers - 1)
|
332 |
+
self.mlp = GPTNeoXJapaneseMLP(config)
|
333 |
+
self.hidden_dropout = config.hidden_dropout
|
334 |
+
|
335 |
+
def forward(
|
336 |
+
self,
|
337 |
+
hidden_states,
|
338 |
+
attention_mask=None,
|
339 |
+
head_mask=None,
|
340 |
+
use_cache=False,
|
341 |
+
layer_past=None,
|
342 |
+
output_attentions=False,
|
343 |
+
):
|
344 |
+
residual = hidden_states
|
345 |
+
ln_out = self.input_layernorm(hidden_states)
|
346 |
+
attention_layer_outputs, attn_bias = self.attention(
|
347 |
+
ln_out,
|
348 |
+
attention_mask=attention_mask,
|
349 |
+
layer_past=layer_past,
|
350 |
+
head_mask=head_mask,
|
351 |
+
use_cache=use_cache,
|
352 |
+
output_attentions=output_attentions,
|
353 |
+
)
|
354 |
+
attn_output = attention_layer_outputs[0] # output_attn: a, present, (attentions)
|
355 |
+
outputs = attention_layer_outputs[1:]
|
356 |
+
|
357 |
+
# attn_output = (atten_output + bias) + residual
|
358 |
+
attn_output = bias_dropout_add(
|
359 |
+
attn_output,
|
360 |
+
bias=attn_bias.expand_as(residual) if attn_bias is not None else attn_bias,
|
361 |
+
residual=residual,
|
362 |
+
prob=self.hidden_dropout,
|
363 |
+
training=self.training,
|
364 |
+
)
|
365 |
+
mlp_output = self.mlp(self.post_attention_layernorm(attn_output))
|
366 |
+
|
367 |
+
# attn_output = (mlp_output + mlp_bias) + atten_output
|
368 |
+
attn_output = bias_dropout_add(
|
369 |
+
mlp_output, bias=None, residual=attn_output, prob=self.hidden_dropout, training=self.training
|
370 |
+
)
|
371 |
+
|
372 |
+
if use_cache:
|
373 |
+
outputs = (attn_output,) + outputs
|
374 |
+
else:
|
375 |
+
outputs = (attn_output,) + outputs[1:]
|
376 |
+
|
377 |
+
return outputs # hidden_states, present, (attentions)
|
378 |
+
|
379 |
+
|
380 |
+
GPT_NEOX_JAPANESE_START_DOCSTRING = r"""
|
381 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
|
382 |
+
it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
383 |
+
behavior.
|
384 |
+
|
385 |
+
Parameters:
|
386 |
+
config ([`~GPTNeoXJapaneseConfig`]): Model configuration class with all the parameters of the model.
|
387 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
388 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
389 |
+
"""
|
390 |
+
|
391 |
+
GPT_NEOX_JAPANESE_INPUTS_DOCSTRING = r"""
|
392 |
+
Args:
|
393 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
394 |
+
Indices of input sequence tokens in the vocabulary.
|
395 |
+
|
396 |
+
Indices can be obtained using [`AutoTokenizer`].
|
397 |
+
|
398 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
399 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
400 |
+
|
401 |
+
- 1 for tokens that are **not masked**,
|
402 |
+
- 0 for tokens that are **masked**.
|
403 |
+
|
404 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
405 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
406 |
+
1]`:
|
407 |
+
|
408 |
+
- 0 corresponds to a *sentence A* token,
|
409 |
+
- 1 corresponds to a *sentence B* token.
|
410 |
+
|
411 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
412 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
413 |
+
config.max_position_embeddings - 1]`.
|
414 |
+
|
415 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
416 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
417 |
+
|
418 |
+
- 1 indicates the head is **not masked**,
|
419 |
+
- 0 indicates the head is **masked**.
|
420 |
+
|
421 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
422 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
423 |
+
is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
|
424 |
+
model's internal embedding lookup matrix.
|
425 |
+
output_attentions (`bool`, *optional*):
|
426 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
427 |
+
tensors for more detail.
|
428 |
+
output_hidden_states (`bool`, *optional*):
|
429 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
430 |
+
more detail.
|
431 |
+
return_dict (`bool`, *optional*):
|
432 |
+
Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
|
433 |
+
"""
|
434 |
+
|
435 |
+
|
436 |
+
@add_start_docstrings(
|
437 |
+
"The bare GPTNeoXJapanese Model transformer outputting raw hidden-states without any specific head on top.",
|
438 |
+
GPT_NEOX_JAPANESE_START_DOCSTRING,
|
439 |
+
)
|
440 |
+
class GPTNeoXJapaneseModel(GPTNeoXJapanesePreTrainedModel):
|
441 |
+
def __init__(self, config):
|
442 |
+
super().__init__(config)
|
443 |
+
self.config = config
|
444 |
+
|
445 |
+
self.embed_in = nn.Embedding(config.vocab_size, config.hidden_size)
|
446 |
+
self.layers = nn.ModuleList(
|
447 |
+
[GPTNeoXJapaneseLayer(config=config, layer_number=i) for i in range(config.num_hidden_layers)]
|
448 |
+
)
|
449 |
+
self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
450 |
+
|
451 |
+
# Initialize weights and apply final processing
|
452 |
+
self.post_init()
|
453 |
+
|
454 |
+
def get_input_embeddings(self):
|
455 |
+
return self.embed_in
|
456 |
+
|
457 |
+
def set_input_embeddings(self, value):
|
458 |
+
self.embed_in = value
|
459 |
+
|
460 |
+
@add_start_docstrings_to_model_forward(GPT_NEOX_JAPANESE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
461 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
462 |
+
def forward(
|
463 |
+
self,
|
464 |
+
input_ids: Optional[torch.LongTensor] = None,
|
465 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
466 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
467 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
468 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
469 |
+
use_cache: Optional[bool] = None,
|
470 |
+
output_attentions: Optional[bool] = None,
|
471 |
+
output_hidden_states: Optional[bool] = None,
|
472 |
+
return_dict: Optional[bool] = None,
|
473 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
474 |
+
r"""
|
475 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
476 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
477 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
478 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
479 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
480 |
+
use_cache (`bool`, *optional*):
|
481 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
482 |
+
`past_key_values`).
|
483 |
+
|
484 |
+
Returns:
|
485 |
+
|
486 |
+
Example:
|
487 |
+
|
488 |
+
```python
|
489 |
+
>>> from transformers import AutoTokenizer, GPTNeoXJapaneseModel
|
490 |
+
>>> import torch
|
491 |
+
|
492 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("abeja/gpt-neox-japanese-2.7b")
|
493 |
+
>>> model = GPTNeoXJapaneseModel.from_pretrained("abeja/gpt-neox-japanese-2.7b")
|
494 |
+
|
495 |
+
>>> inputs = tokenizer("日本語のGPT-neoxがHugging Faceで使えます😀", return_tensors="pt")
|
496 |
+
>>> outputs = model(**inputs)
|
497 |
+
|
498 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
499 |
+
```
|
500 |
+
"""
|
501 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
502 |
+
output_hidden_states = (
|
503 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
504 |
+
)
|
505 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
506 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
507 |
+
|
508 |
+
if input_ids is not None and inputs_embeds is not None:
|
509 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
510 |
+
elif input_ids is not None:
|
511 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
512 |
+
input_shape = input_ids.size()
|
513 |
+
elif inputs_embeds is not None:
|
514 |
+
input_shape = inputs_embeds.size()[:-1]
|
515 |
+
else:
|
516 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
517 |
+
|
518 |
+
batch_size, seq_length = input_shape
|
519 |
+
|
520 |
+
if past_key_values is None:
|
521 |
+
past_key_values = tuple([None] * self.config.num_hidden_layers)
|
522 |
+
|
523 |
+
# Attention mask.
|
524 |
+
if attention_mask is not None:
|
525 |
+
if not batch_size > 0:
|
526 |
+
raise ValueError("batch_size has to be defined and > 0")
|
527 |
+
attention_mask = attention_mask.view(batch_size, -1)
|
528 |
+
# We create a 3D attention mask from a 2D tensor mask.
|
529 |
+
# Sizes are [batch_size, 1, 1, to_seq_length]
|
530 |
+
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
|
531 |
+
# this attention mask is more simple than the triangular masking of causal attention
|
532 |
+
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
|
533 |
+
attention_mask = attention_mask[:, None, None, :]
|
534 |
+
|
535 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
536 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
537 |
+
# positions we want to attend and -10000.0 for masked positions.
|
538 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
539 |
+
# effectively the same as removing these entirely.
|
540 |
+
attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
|
541 |
+
attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
|
542 |
+
|
543 |
+
# Prepare head mask if needed
|
544 |
+
# 1.0 in head_mask indicate we keep the head
|
545 |
+
# attention_probs has shape bsz x n_heads x N x N
|
546 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
547 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
548 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
549 |
+
|
550 |
+
if inputs_embeds is None:
|
551 |
+
inputs_embeds = self.embed_in(input_ids)
|
552 |
+
|
553 |
+
hidden_states = inputs_embeds
|
554 |
+
|
555 |
+
presents = () if use_cache else None
|
556 |
+
all_attentions = () if output_attentions else None
|
557 |
+
all_hidden_states = () if output_hidden_states else None
|
558 |
+
for i, (layer, layer_past) in enumerate(zip(self.layers, past_key_values)):
|
559 |
+
if output_hidden_states:
|
560 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
561 |
+
outputs = layer(
|
562 |
+
hidden_states,
|
563 |
+
attention_mask=attention_mask,
|
564 |
+
head_mask=head_mask[i],
|
565 |
+
layer_past=layer_past,
|
566 |
+
use_cache=use_cache,
|
567 |
+
output_attentions=output_attentions,
|
568 |
+
)
|
569 |
+
hidden_states = outputs[0]
|
570 |
+
if use_cache is True:
|
571 |
+
presents = presents + (outputs[1],)
|
572 |
+
if output_attentions:
|
573 |
+
all_attentions = all_attentions + (outputs[2 if use_cache else 1],)
|
574 |
+
|
575 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
576 |
+
# Add last hidden state
|
577 |
+
if output_hidden_states:
|
578 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
579 |
+
|
580 |
+
if not return_dict:
|
581 |
+
return tuple(v for v in [hidden_states, presents, all_hidden_states, all_attentions] if v is not None)
|
582 |
+
|
583 |
+
return BaseModelOutputWithPast(
|
584 |
+
last_hidden_state=hidden_states,
|
585 |
+
past_key_values=presents,
|
586 |
+
hidden_states=all_hidden_states,
|
587 |
+
attentions=all_attentions,
|
588 |
+
)
|
589 |
+
|
590 |
+
|
591 |
+
@add_start_docstrings(
|
592 |
+
"""GPTNeoXJapanese Model with a `language modeling` head on top for Classifier Model fine-tuning.""",
|
593 |
+
GPT_NEOX_JAPANESE_START_DOCSTRING,
|
594 |
+
)
|
595 |
+
class GPTNeoXJapaneseForCausalLM(GPTNeoXJapanesePreTrainedModel):
|
596 |
+
_tied_weights_keys = ["embed_out.weight"]
|
597 |
+
|
598 |
+
def __init__(self, config):
|
599 |
+
super().__init__(config)
|
600 |
+
self.config = config
|
601 |
+
|
602 |
+
self.gpt_neox_japanese = GPTNeoXJapaneseModel(config)
|
603 |
+
self.embed_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
604 |
+
|
605 |
+
# Initialize weights and apply final processing
|
606 |
+
self.post_init()
|
607 |
+
|
608 |
+
def get_output_embeddings(self):
|
609 |
+
return self.embed_out
|
610 |
+
|
611 |
+
def set_output_embeddings(self, new_embeddings):
|
612 |
+
self.embed_out = new_embeddings
|
613 |
+
|
614 |
+
@add_start_docstrings_to_model_forward(GPT_NEOX_JAPANESE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
615 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
616 |
+
def forward(
|
617 |
+
self,
|
618 |
+
input_ids: Optional[torch.LongTensor] = None,
|
619 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
620 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
621 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
622 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
623 |
+
labels: Optional[torch.LongTensor] = None,
|
624 |
+
use_cache: Optional[bool] = None,
|
625 |
+
output_attentions: Optional[bool] = None,
|
626 |
+
output_hidden_states: Optional[bool] = None,
|
627 |
+
return_dict: Optional[bool] = None,
|
628 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
629 |
+
r"""
|
630 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
631 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
632 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
|
633 |
+
`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional tensors are
|
634 |
+
only required when the model is used as a decoder in a Sequence to Sequence model.
|
635 |
+
|
636 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks that can be used (see
|
637 |
+
`past_key_values` input) to speed up sequential decoding.
|
638 |
+
|
639 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
640 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
641 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
642 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
643 |
+
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
|
644 |
+
`[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
|
645 |
+
ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`.
|
646 |
+
use_cache (`bool`, *optional*):
|
647 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
648 |
+
`past_key_values`).
|
649 |
+
|
650 |
+
Returns:
|
651 |
+
|
652 |
+
Example:
|
653 |
+
|
654 |
+
```python
|
655 |
+
>>> from transformers import AutoTokenizer, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseConfig
|
656 |
+
>>> import torch
|
657 |
+
|
658 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("abeja/gpt-neox-japanese-2.7b")
|
659 |
+
>>> config = GPTNeoXJapaneseConfig.from_pretrained("abeja/gpt-neox-japanese-2.7b")
|
660 |
+
>>> config.is_decoder = True
|
661 |
+
>>> model = GPTNeoXJapaneseForCausalLM.from_pretrained("abeja/gpt-neox-japanese-2.7b", config=config)
|
662 |
+
|
663 |
+
>>> inputs = tokenizer("日本語のGPT-neoxがHugging Faceで使えます😀", return_tensors="pt")
|
664 |
+
>>> outputs = model(**inputs)
|
665 |
+
|
666 |
+
>>> prediction_logits = outputs.logits
|
667 |
+
```
|
668 |
+
"""
|
669 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
670 |
+
|
671 |
+
outputs = self.gpt_neox_japanese(
|
672 |
+
input_ids,
|
673 |
+
attention_mask=attention_mask,
|
674 |
+
head_mask=head_mask,
|
675 |
+
inputs_embeds=inputs_embeds,
|
676 |
+
past_key_values=past_key_values,
|
677 |
+
use_cache=use_cache,
|
678 |
+
output_attentions=output_attentions,
|
679 |
+
output_hidden_states=output_hidden_states,
|
680 |
+
return_dict=return_dict,
|
681 |
+
)
|
682 |
+
|
683 |
+
hidden_states = outputs[0]
|
684 |
+
lm_logits = self.embed_out(hidden_states)
|
685 |
+
|
686 |
+
lm_loss = None
|
687 |
+
if labels is not None:
|
688 |
+
# move labels to correct device to enable model parallelism
|
689 |
+
labels = labels.to(lm_logits.device)
|
690 |
+
|
691 |
+
# we are doing next-token prediction; shift prediction scores and input ids by one
|
692 |
+
shift_logits = lm_logits[:, :-1, :].contiguous()
|
693 |
+
labels = labels[:, 1:].contiguous()
|
694 |
+
loss_fct = CrossEntropyLoss()
|
695 |
+
lm_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), labels.view(-1))
|
696 |
+
|
697 |
+
if not return_dict:
|
698 |
+
output = (lm_logits,) + outputs[1:]
|
699 |
+
return ((lm_loss,) + output) if lm_loss is not None else output
|
700 |
+
|
701 |
+
return CausalLMOutputWithPast(
|
702 |
+
loss=lm_loss,
|
703 |
+
logits=lm_logits,
|
704 |
+
past_key_values=outputs.past_key_values,
|
705 |
+
hidden_states=outputs.hidden_states,
|
706 |
+
attentions=outputs.attentions,
|
707 |
+
)
|
708 |
+
|
709 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
|
710 |
+
input_shape = input_ids.shape
|
711 |
+
|
712 |
+
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
|
713 |
+
if attention_mask is None:
|
714 |
+
attention_mask = input_ids.new_ones(input_shape)
|
715 |
+
|
716 |
+
# cut decoder_input_ids if past is used
|
717 |
+
if past_key_values and past_key_values[0] is not None:
|
718 |
+
input_ids = input_ids[:, -1:]
|
719 |
+
|
720 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values}
|
721 |
+
|
722 |
+
def _reorder_cache(self, past_key_values, beam_idx):
|
723 |
+
reordered_past = ()
|
724 |
+
for layer_past in past_key_values:
|
725 |
+
reordered_past += (
|
726 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past[:2])
|
727 |
+
+ layer_past[2:],
|
728 |
+
)
|
729 |
+
return reordered_past
|
venv/lib/python3.10/site-packages/transformers/models/gpt_neox_japanese/tokenization_gpt_neox_japanese.py
ADDED
@@ -0,0 +1,368 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 ABEJA, 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 classes for GPTNeoXJapanese."""
|
16 |
+
import collections
|
17 |
+
import json
|
18 |
+
import os
|
19 |
+
import re
|
20 |
+
from typing import Optional, Tuple
|
21 |
+
|
22 |
+
import numpy as np
|
23 |
+
|
24 |
+
from ...tokenization_utils_fast import PreTrainedTokenizer
|
25 |
+
from ...utils import logging
|
26 |
+
|
27 |
+
|
28 |
+
logger = logging.get_logger(__name__)
|
29 |
+
|
30 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "emoji_file": "emoji.json"}
|
31 |
+
|
32 |
+
|
33 |
+
def load_vocab_and_emoji(vocab_file, emoji_file):
|
34 |
+
"""Loads a vocabulary file and emoji file into a dictionary."""
|
35 |
+
with open(emoji_file, "r", encoding="utf-8") as f:
|
36 |
+
emoji = json.loads(f.read())
|
37 |
+
|
38 |
+
vocab = collections.OrderedDict()
|
39 |
+
raw_vocab = collections.OrderedDict()
|
40 |
+
ids_to_tokens = collections.OrderedDict()
|
41 |
+
with open(vocab_file, "r", encoding="utf-8") as f:
|
42 |
+
token = f.readlines()
|
43 |
+
token = [[t.rstrip("\n")] if (t == "," or "," not in t) else t.rstrip("\n").split(",") for t in token]
|
44 |
+
for idx, b in enumerate(token):
|
45 |
+
ids_to_tokens[idx] = b
|
46 |
+
raw_vocab[",".join(b)] = idx
|
47 |
+
for wd in b:
|
48 |
+
vocab[wd] = idx
|
49 |
+
|
50 |
+
return vocab, raw_vocab, ids_to_tokens, emoji
|
51 |
+
|
52 |
+
|
53 |
+
class GPTNeoXJapaneseTokenizer(PreTrainedTokenizer):
|
54 |
+
"""
|
55 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] and is based on Japanese special Sub-Word-Encoding that is
|
56 |
+
used in this repository (https://github.com/tanreinama/Japanese-BPEEncoder_V2). Check the repository for details.
|
57 |
+
Japanese has a relatively large vocabulary and there is no separation between words. Furthermore, the language is a
|
58 |
+
combination of hiragana, katakana, and kanji, and variants such as "1" and "①" are often used. In order to cope
|
59 |
+
with these, this tokenizer has the following features
|
60 |
+
- Subword-by-subword segmentation, which is intermediate between byte strings and morphological analysis.
|
61 |
+
- BPEs are created for each Kanji, Hiragana, and Katakana character, and there are no BPEs that cross character
|
62 |
+
types, such as Kanji + Hiragana or Hiragana + Katakana.
|
63 |
+
- All-byte encoding that does not require <unk>.
|
64 |
+
- Independent of UTF codes such as 2-byte and 3-byte characters
|
65 |
+
- Conversion of heterographs to the same token_id
|
66 |
+
- Emoji and Emoticon are grouped into 12 types as special tags.
|
67 |
+
|
68 |
+
Example:
|
69 |
+
|
70 |
+
```python
|
71 |
+
>>> from transformers import GPTNeoXJapaneseTokenizer
|
72 |
+
|
73 |
+
>>> tokenizer = GPTNeoXJapaneseTokenizer.from_pretrained("abeja/gpt-neox-japanese-2.7b")
|
74 |
+
>>> # You can confirm both 慶応 and 慶應 are encoded to 17749
|
75 |
+
>>> tokenizer("吾輩は猫である🐯。実は慶応(慶應)大学出身")["input_ids"]
|
76 |
+
[30014, 26883, 26638, 27228, 25, 26650, 31732, 31679, 27809, 26638, 17749, 31592, 17749, 31593, 321, 1281]
|
77 |
+
|
78 |
+
>>> # Both 慶応 and 慶應 are decoded to 慶応
|
79 |
+
>>> tokenizer.decode(tokenizer("吾輩は猫である🐯。実は慶応(慶應)大学出身")["input_ids"])
|
80 |
+
'吾輩は猫である🐯。実は慶応(慶応)大学出身'
|
81 |
+
```
|
82 |
+
|
83 |
+
Args:
|
84 |
+
vocab_file (`str`):
|
85 |
+
File containing the vocabulary.
|
86 |
+
emoji_file (`str`):
|
87 |
+
File containing the emoji.
|
88 |
+
unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
89 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
90 |
+
token instead.
|
91 |
+
pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
92 |
+
The token used for padding
|
93 |
+
bos_token (`str`, *optional*, defaults to `"<|startoftext|>"`):
|
94 |
+
The beginning of sequence token.
|
95 |
+
eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
96 |
+
The end of sequence token.
|
97 |
+
do_clean_text (`bool`, *optional*, defaults to `False`):
|
98 |
+
Whether or not to clean text for URL, EMAIL, TEL, Japanese DATE and Japanese PRICE.
|
99 |
+
"""
|
100 |
+
|
101 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
102 |
+
model_input_names = ["input_ids", "attention_mask"]
|
103 |
+
|
104 |
+
def __init__(
|
105 |
+
self,
|
106 |
+
vocab_file,
|
107 |
+
emoji_file,
|
108 |
+
unk_token="<|endoftext|>",
|
109 |
+
pad_token="<|endoftext|>",
|
110 |
+
bos_token="<|startoftext|>",
|
111 |
+
eos_token="<|endoftext|>",
|
112 |
+
do_clean_text=False,
|
113 |
+
**kwargs,
|
114 |
+
):
|
115 |
+
if not os.path.isfile(vocab_file):
|
116 |
+
raise ValueError(
|
117 |
+
f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
|
118 |
+
" model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
|
119 |
+
)
|
120 |
+
if not os.path.isfile(emoji_file):
|
121 |
+
raise ValueError(
|
122 |
+
f"Can't find a emoji file at path '{emoji_file}'. To load the emoji information from a Google"
|
123 |
+
" pretrained model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
|
124 |
+
)
|
125 |
+
self.do_clean_text = do_clean_text
|
126 |
+
self.vocab, self.raw_vocab, self.ids_to_tokens, self.emoji = load_vocab_and_emoji(vocab_file, emoji_file)
|
127 |
+
self.subword_tokenizer = SubWordJapaneseTokenizer(
|
128 |
+
vocab=self.vocab, ids_to_tokens=self.ids_to_tokens, emoji=self.emoji
|
129 |
+
)
|
130 |
+
super().__init__(
|
131 |
+
unk_token=unk_token,
|
132 |
+
pad_token=pad_token,
|
133 |
+
bos_token=bos_token,
|
134 |
+
eos_token=eos_token,
|
135 |
+
do_clean_text=do_clean_text,
|
136 |
+
**kwargs,
|
137 |
+
)
|
138 |
+
|
139 |
+
@property
|
140 |
+
def vocab_size(self):
|
141 |
+
# self.vocab contains support for character fluctuation unique to Japanese, and has a large number of vocab
|
142 |
+
return len(self.raw_vocab)
|
143 |
+
|
144 |
+
def get_vocab(self):
|
145 |
+
return dict(self.raw_vocab, **self.added_tokens_encoder)
|
146 |
+
|
147 |
+
def _tokenize(self, text):
|
148 |
+
return self.subword_tokenizer.tokenize(text, clean=self.do_clean_text)
|
149 |
+
|
150 |
+
def _convert_token_to_id(self, token):
|
151 |
+
"""Converts a token (str) in an id using the vocab."""
|
152 |
+
return self.vocab.get(token, self.vocab.get(self.unk_token))
|
153 |
+
|
154 |
+
def _convert_id_to_token(self, index):
|
155 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
156 |
+
return self.subword_tokenizer.convert_id_to_token(index)
|
157 |
+
|
158 |
+
def convert_tokens_to_string(self, tokens):
|
159 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
160 |
+
out_string = "".join(tokens).strip()
|
161 |
+
return out_string
|
162 |
+
|
163 |
+
@property
|
164 |
+
def default_chat_template(self):
|
165 |
+
"""
|
166 |
+
A simple chat template that just adds BOS/EOS tokens around messages while discarding role information.
|
167 |
+
"""
|
168 |
+
logger.warning_once(
|
169 |
+
"\nNo chat template is defined for this tokenizer - using the default template "
|
170 |
+
f"for the {self.__class__.__name__} class. If the default is not appropriate for "
|
171 |
+
"your model, please set `tokenizer.chat_template` to an appropriate template. "
|
172 |
+
"See https://huggingface.co/docs/transformers/main/chat_templating for more information.\n"
|
173 |
+
)
|
174 |
+
return (
|
175 |
+
"{% for message in messages %}"
|
176 |
+
"{{ bos_token + eos_token + message.content + eos_token }}"
|
177 |
+
"{% endfor %}"
|
178 |
+
"{% if add_generation_prompt %} {{ bos_token + eos_token }} {% endif %}"
|
179 |
+
)
|
180 |
+
|
181 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
182 |
+
index = 0
|
183 |
+
if os.path.isdir(save_directory):
|
184 |
+
vocab_file = os.path.join(
|
185 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
186 |
+
)
|
187 |
+
emoji_file = os.path.join(
|
188 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["emoji_file"]
|
189 |
+
)
|
190 |
+
else:
|
191 |
+
vocab_file = (
|
192 |
+
(filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["vocab_file"]
|
193 |
+
)
|
194 |
+
emoji_file = (
|
195 |
+
(filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["emoji_file"]
|
196 |
+
)
|
197 |
+
with open(vocab_file, "w", encoding="utf-8") as writer:
|
198 |
+
for token_index, token in self.ids_to_tokens.items():
|
199 |
+
if index != token_index:
|
200 |
+
logger.warning(
|
201 |
+
f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
|
202 |
+
" Please check that the vocabulary is not corrupted!"
|
203 |
+
)
|
204 |
+
index = token_index
|
205 |
+
writer.write(",".join(token) + "\n")
|
206 |
+
index += 1
|
207 |
+
with open(emoji_file, "w", encoding="utf-8") as writer:
|
208 |
+
json.dump(self.emoji, writer)
|
209 |
+
return vocab_file, emoji_file
|
210 |
+
|
211 |
+
|
212 |
+
class SubWordJapaneseTokenizer(object):
|
213 |
+
"""
|
214 |
+
https://github.com/tanreinama/Japanese-BPEEncoder_V2 This tokenizer class is under MIT Lisence according to the
|
215 |
+
original repository.
|
216 |
+
|
217 |
+
MIT License
|
218 |
+
|
219 |
+
Copyright (c) 2020 tanreinama
|
220 |
+
|
221 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
|
222 |
+
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
|
223 |
+
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
|
224 |
+
permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
225 |
+
|
226 |
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of
|
227 |
+
the Software.
|
228 |
+
|
229 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
|
230 |
+
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
231 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
232 |
+
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
233 |
+
SOFTWARE.
|
234 |
+
"""
|
235 |
+
|
236 |
+
def __init__(self, vocab, ids_to_tokens, emoji):
|
237 |
+
self.vocab = vocab # same as swe
|
238 |
+
self.ids_to_tokens = ids_to_tokens # same as bpe
|
239 |
+
self.emoji = emoji
|
240 |
+
self.maxlen = np.max([len(w) for w in self.vocab.keys()])
|
241 |
+
self.content_repatter1 = re.compile(r"(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)")
|
242 |
+
self.content_repatter2 = re.compile(r"[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*")
|
243 |
+
self.content_repatter3 = re.compile(r"[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}")
|
244 |
+
self.content_repatter4 = re.compile(
|
245 |
+
r"([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*"
|
246 |
+
)
|
247 |
+
self.content_repatter5 = re.compile(
|
248 |
+
r"(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*"
|
249 |
+
)
|
250 |
+
self.content_repatter6 = re.compile(
|
251 |
+
r"((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*億)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*万)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*千)*(0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*(千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+(\(税込\)|\(税抜\)|\+tax)*"
|
252 |
+
)
|
253 |
+
keisen = "─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿"
|
254 |
+
blocks = "▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟"
|
255 |
+
self.content_trans1 = str.maketrans({k: "<BLOCK>" for k in keisen + blocks})
|
256 |
+
|
257 |
+
def __len__(self):
|
258 |
+
return len(self.ids_to_tokens)
|
259 |
+
|
260 |
+
def clean_text(self, content):
|
261 |
+
content = self.content_repatter1.sub("<URL>", content)
|
262 |
+
content = self.content_repatter2.sub("<EMAIL>", content)
|
263 |
+
content = self.content_repatter3.sub("<TEL>", content)
|
264 |
+
content = self.content_repatter4.sub("<DATE>", content)
|
265 |
+
content = self.content_repatter5.sub("<DATE>", content)
|
266 |
+
content = self.content_repatter6.sub("<PRICE>", content)
|
267 |
+
content = content.translate(self.content_trans1)
|
268 |
+
while "<BLOCK><BLOCK>" in content:
|
269 |
+
content = content.replace("<BLOCK><BLOCK>", "<BLOCK>")
|
270 |
+
return content
|
271 |
+
|
272 |
+
def tokenize(self, text, clean=False):
|
273 |
+
text = text.replace(" ", "<SP>")
|
274 |
+
text = text.replace(" ", "<SP>")
|
275 |
+
text = text.replace("\r\n", "<BR>")
|
276 |
+
text = text.replace("\n", "<BR>")
|
277 |
+
text = text.replace("\r", "<BR>")
|
278 |
+
text = text.replace("\t", "<TAB>")
|
279 |
+
text = text.replace("—", "ー")
|
280 |
+
text = text.replace("−", "ー")
|
281 |
+
for k, v in self.emoji["emoji"].items():
|
282 |
+
if k in text:
|
283 |
+
text = text.replace(k, v)
|
284 |
+
if clean:
|
285 |
+
text = self.clean_text(text)
|
286 |
+
|
287 |
+
def check_simbol(x):
|
288 |
+
e = x.encode()
|
289 |
+
if len(x) == 1 and len(e) == 2:
|
290 |
+
c = (int(e[0]) << 8) + int(e[1])
|
291 |
+
if (
|
292 |
+
(c >= 0xC2A1 and c <= 0xC2BF)
|
293 |
+
or (c >= 0xC780 and c <= 0xC783)
|
294 |
+
or (c >= 0xCAB9 and c <= 0xCBBF)
|
295 |
+
or (c >= 0xCC80 and c <= 0xCDA2)
|
296 |
+
):
|
297 |
+
return True
|
298 |
+
return False
|
299 |
+
|
300 |
+
def checku2e(x):
|
301 |
+
e = x.encode()
|
302 |
+
if len(x) == 1 and len(e) == 3:
|
303 |
+
c = (int(e[0]) << 16) + (int(e[1]) << 8) + int(e[2])
|
304 |
+
if c >= 0xE28080 and c <= 0xE2B07F:
|
305 |
+
return True
|
306 |
+
return False
|
307 |
+
|
308 |
+
pos = 0
|
309 |
+
result = []
|
310 |
+
while pos < len(text):
|
311 |
+
end = min(len(text), pos + self.maxlen + 1) if text[pos] == "<" else pos + 3
|
312 |
+
candidates = [] # (token_id, token, pos)
|
313 |
+
for e in range(end, pos, -1):
|
314 |
+
wd = text[pos:e]
|
315 |
+
if wd in self.vocab:
|
316 |
+
if wd[0] == "<" and len(wd) > 2:
|
317 |
+
candidates = [(self.vocab[wd], wd, e)]
|
318 |
+
break
|
319 |
+
else:
|
320 |
+
candidates.append((self.vocab[wd], wd, e))
|
321 |
+
if len(candidates) > 0:
|
322 |
+
# the smallest token_id is adopted
|
323 |
+
_, wd, e = sorted(candidates, key=lambda x: x[0])[0]
|
324 |
+
result.append(wd)
|
325 |
+
pos = e
|
326 |
+
else:
|
327 |
+
end = pos + 1
|
328 |
+
wd = text[pos:end]
|
329 |
+
if check_simbol(wd):
|
330 |
+
result.append("<KIGOU>")
|
331 |
+
elif checku2e(wd):
|
332 |
+
result.append("<U2000U2BFF>")
|
333 |
+
else:
|
334 |
+
for i in wd.encode("utf-8"):
|
335 |
+
result.append("<|byte%d|>" % i)
|
336 |
+
pos = end
|
337 |
+
return result
|
338 |
+
|
339 |
+
def convert_id_to_token(self, index, breakline="\n"):
|
340 |
+
words = []
|
341 |
+
byte_tokens = []
|
342 |
+
word = self.ids_to_tokens[index][0]
|
343 |
+
if word[:6] == "<|byte" and word[-2:] == "|>":
|
344 |
+
byte_tokens.append(int(word[6:-2]))
|
345 |
+
else:
|
346 |
+
if len(byte_tokens) > 0:
|
347 |
+
words.append(bytearray(byte_tokens).decode("utf-8", errors="replace"))
|
348 |
+
byte_tokens = []
|
349 |
+
if word[:7] == "<|emoji" and word[-2:] == "|>":
|
350 |
+
words.append(self.emoji["emoji_inv"][word])
|
351 |
+
elif word == "<SP>":
|
352 |
+
words.append(" ")
|
353 |
+
elif word == "<BR>":
|
354 |
+
words.append(breakline)
|
355 |
+
elif word == "<TAB>":
|
356 |
+
words.append("\t")
|
357 |
+
elif word == "<BLOCK>":
|
358 |
+
words.append("▀")
|
359 |
+
elif word == "<KIGOU>":
|
360 |
+
words.append("ǀ")
|
361 |
+
elif word == "<U2000U2BFF>":
|
362 |
+
words.append("‖")
|
363 |
+
else:
|
364 |
+
words.append(word)
|
365 |
+
if len(byte_tokens) > 0:
|
366 |
+
words.append(bytearray(byte_tokens).decode("utf-8", errors="replace"))
|
367 |
+
text = "".join(words)
|
368 |
+
return text
|
venv/lib/python3.10/site-packages/transformers/models/qwen2/__init__.py
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 The Qwen Team and The HuggingFace Inc. 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 (
|
17 |
+
OptionalDependencyNotAvailable,
|
18 |
+
_LazyModule,
|
19 |
+
is_tokenizers_available,
|
20 |
+
is_torch_available,
|
21 |
+
)
|
22 |
+
|
23 |
+
|
24 |
+
_import_structure = {
|
25 |
+
"configuration_qwen2": ["QWEN2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Qwen2Config"],
|
26 |
+
"tokenization_qwen2": ["Qwen2Tokenizer"],
|
27 |
+
}
|
28 |
+
|
29 |
+
try:
|
30 |
+
if not is_tokenizers_available():
|
31 |
+
raise OptionalDependencyNotAvailable()
|
32 |
+
except OptionalDependencyNotAvailable:
|
33 |
+
pass
|
34 |
+
else:
|
35 |
+
_import_structure["tokenization_qwen2_fast"] = ["Qwen2TokenizerFast"]
|
36 |
+
|
37 |
+
try:
|
38 |
+
if not is_torch_available():
|
39 |
+
raise OptionalDependencyNotAvailable()
|
40 |
+
except OptionalDependencyNotAvailable:
|
41 |
+
pass
|
42 |
+
else:
|
43 |
+
_import_structure["modeling_qwen2"] = [
|
44 |
+
"Qwen2ForCausalLM",
|
45 |
+
"Qwen2Model",
|
46 |
+
"Qwen2PreTrainedModel",
|
47 |
+
"Qwen2ForSequenceClassification",
|
48 |
+
]
|
49 |
+
|
50 |
+
|
51 |
+
if TYPE_CHECKING:
|
52 |
+
from .configuration_qwen2 import QWEN2_PRETRAINED_CONFIG_ARCHIVE_MAP, Qwen2Config
|
53 |
+
from .tokenization_qwen2 import Qwen2Tokenizer
|
54 |
+
|
55 |
+
try:
|
56 |
+
if not is_tokenizers_available():
|
57 |
+
raise OptionalDependencyNotAvailable()
|
58 |
+
except OptionalDependencyNotAvailable:
|
59 |
+
pass
|
60 |
+
else:
|
61 |
+
from .tokenization_qwen2_fast import Qwen2TokenizerFast
|
62 |
+
|
63 |
+
try:
|
64 |
+
if not is_torch_available():
|
65 |
+
raise OptionalDependencyNotAvailable()
|
66 |
+
except OptionalDependencyNotAvailable:
|
67 |
+
pass
|
68 |
+
else:
|
69 |
+
from .modeling_qwen2 import (
|
70 |
+
Qwen2ForCausalLM,
|
71 |
+
Qwen2ForSequenceClassification,
|
72 |
+
Qwen2Model,
|
73 |
+
Qwen2PreTrainedModel,
|
74 |
+
)
|
75 |
+
|
76 |
+
|
77 |
+
else:
|
78 |
+
import sys
|
79 |
+
|
80 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
venv/lib/python3.10/site-packages/transformers/models/qwen2/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.22 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/qwen2/__pycache__/configuration_qwen2.cpython-310.pyc
ADDED
Binary file (5.79 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/qwen2/__pycache__/modeling_qwen2.cpython-310.pyc
ADDED
Binary file (39.1 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/qwen2/__pycache__/tokenization_qwen2.cpython-310.pyc
ADDED
Binary file (11.5 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/qwen2/__pycache__/tokenization_qwen2_fast.cpython-310.pyc
ADDED
Binary file (3.86 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/qwen2/configuration_qwen2.py
ADDED
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 The Qwen team, Alibaba Group 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 |
+
""" Qwen2 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 |
+
from ..deprecated._archive_maps import QWEN2_PRETRAINED_CONFIG_ARCHIVE_MAP # noqa: F401, E402
|
25 |
+
|
26 |
+
|
27 |
+
class Qwen2Config(PretrainedConfig):
|
28 |
+
r"""
|
29 |
+
This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
|
30 |
+
Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
31 |
+
with the defaults will yield a similar configuration to that of
|
32 |
+
Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
|
33 |
+
|
34 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
35 |
+
documentation from [`PretrainedConfig`] for more information.
|
36 |
+
|
37 |
+
|
38 |
+
Args:
|
39 |
+
vocab_size (`int`, *optional*, defaults to 151936):
|
40 |
+
Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
|
41 |
+
`inputs_ids` passed when calling [`Qwen2Model`]
|
42 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
43 |
+
Dimension of the hidden representations.
|
44 |
+
intermediate_size (`int`, *optional*, defaults to 22016):
|
45 |
+
Dimension of the MLP representations.
|
46 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
47 |
+
Number of hidden layers in the Transformer encoder.
|
48 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
49 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
50 |
+
num_key_value_heads (`int`, *optional*, defaults to 32):
|
51 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
52 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
53 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
54 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
55 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
56 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
|
57 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
58 |
+
The non-linear activation function (function or string) in the decoder.
|
59 |
+
max_position_embeddings (`int`, *optional*, defaults to 32768):
|
60 |
+
The maximum sequence length that this model might ever be used with.
|
61 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
62 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
63 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
64 |
+
The epsilon used by the rms normalization layers.
|
65 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
66 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
67 |
+
relevant if `config.is_decoder=True`.
|
68 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
69 |
+
Whether the model's input and output word embeddings should be tied.
|
70 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
71 |
+
The base period of the RoPE embeddings.
|
72 |
+
use_sliding_window (`bool`, *optional*, defaults to `False`):
|
73 |
+
Whether to use sliding window attention.
|
74 |
+
sliding_window (`int`, *optional*, defaults to 4096):
|
75 |
+
Sliding window attention (SWA) window size. If not specified, will default to `4096`.
|
76 |
+
max_window_layers (`int`, *optional*, defaults to 28):
|
77 |
+
The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
|
78 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
79 |
+
The dropout ratio for the attention probabilities.
|
80 |
+
|
81 |
+
```python
|
82 |
+
>>> from transformers import Qwen2Model, Qwen2Config
|
83 |
+
|
84 |
+
>>> # Initializing a Qwen2 style configuration
|
85 |
+
>>> configuration = Qwen2Config()
|
86 |
+
|
87 |
+
>>> # Initializing a model from the Qwen2-7B style configuration
|
88 |
+
>>> model = Qwen2Model(configuration)
|
89 |
+
|
90 |
+
>>> # Accessing the model configuration
|
91 |
+
>>> configuration = model.config
|
92 |
+
```"""
|
93 |
+
|
94 |
+
model_type = "qwen2"
|
95 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
96 |
+
|
97 |
+
def __init__(
|
98 |
+
self,
|
99 |
+
vocab_size=151936,
|
100 |
+
hidden_size=4096,
|
101 |
+
intermediate_size=22016,
|
102 |
+
num_hidden_layers=32,
|
103 |
+
num_attention_heads=32,
|
104 |
+
num_key_value_heads=32,
|
105 |
+
hidden_act="silu",
|
106 |
+
max_position_embeddings=32768,
|
107 |
+
initializer_range=0.02,
|
108 |
+
rms_norm_eps=1e-6,
|
109 |
+
use_cache=True,
|
110 |
+
tie_word_embeddings=False,
|
111 |
+
rope_theta=10000.0,
|
112 |
+
use_sliding_window=False,
|
113 |
+
sliding_window=4096,
|
114 |
+
max_window_layers=28,
|
115 |
+
attention_dropout=0.0,
|
116 |
+
**kwargs,
|
117 |
+
):
|
118 |
+
self.vocab_size = vocab_size
|
119 |
+
self.max_position_embeddings = max_position_embeddings
|
120 |
+
self.hidden_size = hidden_size
|
121 |
+
self.intermediate_size = intermediate_size
|
122 |
+
self.num_hidden_layers = num_hidden_layers
|
123 |
+
self.num_attention_heads = num_attention_heads
|
124 |
+
self.use_sliding_window = use_sliding_window
|
125 |
+
self.sliding_window = sliding_window
|
126 |
+
self.max_window_layers = max_window_layers
|
127 |
+
|
128 |
+
# for backward compatibility
|
129 |
+
if num_key_value_heads is None:
|
130 |
+
num_key_value_heads = num_attention_heads
|
131 |
+
|
132 |
+
self.num_key_value_heads = num_key_value_heads
|
133 |
+
self.hidden_act = hidden_act
|
134 |
+
self.initializer_range = initializer_range
|
135 |
+
self.rms_norm_eps = rms_norm_eps
|
136 |
+
self.use_cache = use_cache
|
137 |
+
self.rope_theta = rope_theta
|
138 |
+
self.attention_dropout = attention_dropout
|
139 |
+
|
140 |
+
super().__init__(
|
141 |
+
tie_word_embeddings=tie_word_embeddings,
|
142 |
+
**kwargs,
|
143 |
+
)
|
venv/lib/python3.10/site-packages/transformers/models/qwen2/modeling_qwen2.py
ADDED
@@ -0,0 +1,1397 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
""" PyTorch Qwen2 model."""
|
21 |
+
import inspect
|
22 |
+
import math
|
23 |
+
import warnings
|
24 |
+
from typing import List, Optional, Tuple, Union
|
25 |
+
|
26 |
+
import torch
|
27 |
+
import torch.nn.functional as F
|
28 |
+
import torch.utils.checkpoint
|
29 |
+
from torch import nn
|
30 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
31 |
+
|
32 |
+
from ...activations import ACT2FN
|
33 |
+
from ...cache_utils import Cache, DynamicCache
|
34 |
+
from ...modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
|
35 |
+
from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
|
36 |
+
from ...modeling_utils import PreTrainedModel
|
37 |
+
from ...utils import (
|
38 |
+
add_start_docstrings,
|
39 |
+
add_start_docstrings_to_model_forward,
|
40 |
+
is_flash_attn_2_available,
|
41 |
+
is_flash_attn_greater_or_equal_2_10,
|
42 |
+
logging,
|
43 |
+
replace_return_docstrings,
|
44 |
+
)
|
45 |
+
from .configuration_qwen2 import Qwen2Config
|
46 |
+
|
47 |
+
|
48 |
+
if is_flash_attn_2_available():
|
49 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
50 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
51 |
+
|
52 |
+
_flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
|
53 |
+
|
54 |
+
|
55 |
+
logger = logging.get_logger(__name__)
|
56 |
+
|
57 |
+
|
58 |
+
_CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
|
59 |
+
_CONFIG_FOR_DOC = "Qwen2Config"
|
60 |
+
|
61 |
+
|
62 |
+
# Copied from transformers.models.llama.modeling_llama._get_unpad_data
|
63 |
+
def _get_unpad_data(attention_mask):
|
64 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
65 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
66 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
67 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
|
68 |
+
return (
|
69 |
+
indices,
|
70 |
+
cu_seqlens,
|
71 |
+
max_seqlen_in_batch,
|
72 |
+
)
|
73 |
+
|
74 |
+
|
75 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
|
76 |
+
class Qwen2RMSNorm(nn.Module):
|
77 |
+
def __init__(self, hidden_size, eps=1e-6):
|
78 |
+
"""
|
79 |
+
Qwen2RMSNorm is equivalent to T5LayerNorm
|
80 |
+
"""
|
81 |
+
super().__init__()
|
82 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
83 |
+
self.variance_epsilon = eps
|
84 |
+
|
85 |
+
def forward(self, hidden_states):
|
86 |
+
input_dtype = hidden_states.dtype
|
87 |
+
hidden_states = hidden_states.to(torch.float32)
|
88 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
89 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
90 |
+
return self.weight * hidden_states.to(input_dtype)
|
91 |
+
|
92 |
+
|
93 |
+
# Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Qwen2
|
94 |
+
class Qwen2RotaryEmbedding(nn.Module):
|
95 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
96 |
+
super().__init__()
|
97 |
+
|
98 |
+
self.dim = dim
|
99 |
+
self.max_position_embeddings = max_position_embeddings
|
100 |
+
self.base = base
|
101 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
|
102 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
103 |
+
|
104 |
+
# Build here to make `torch.jit.trace` work.
|
105 |
+
self._set_cos_sin_cache(
|
106 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
107 |
+
)
|
108 |
+
|
109 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
110 |
+
self.max_seq_len_cached = seq_len
|
111 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
|
112 |
+
|
113 |
+
freqs = torch.outer(t, self.inv_freq)
|
114 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
115 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
116 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
117 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
118 |
+
|
119 |
+
def forward(self, x, seq_len=None):
|
120 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
121 |
+
if seq_len > self.max_seq_len_cached:
|
122 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
123 |
+
|
124 |
+
return (
|
125 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
126 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
127 |
+
)
|
128 |
+
|
129 |
+
|
130 |
+
# Copied from transformers.models.llama.modeling_llama.rotate_half
|
131 |
+
def rotate_half(x):
|
132 |
+
"""Rotates half the hidden dims of the input."""
|
133 |
+
x1 = x[..., : x.shape[-1] // 2]
|
134 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
135 |
+
return torch.cat((-x2, x1), dim=-1)
|
136 |
+
|
137 |
+
|
138 |
+
# Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
|
139 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
140 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
141 |
+
|
142 |
+
Args:
|
143 |
+
q (`torch.Tensor`): The query tensor.
|
144 |
+
k (`torch.Tensor`): The key tensor.
|
145 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
146 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
147 |
+
position_ids (`torch.Tensor`):
|
148 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
149 |
+
used to pass offsetted position ids when working with a KV-cache.
|
150 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
151 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
152 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
153 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
154 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
155 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
156 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
157 |
+
Returns:
|
158 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
159 |
+
"""
|
160 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
161 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
162 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
163 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
164 |
+
return q_embed, k_embed
|
165 |
+
|
166 |
+
|
167 |
+
# Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
|
168 |
+
class Qwen2MLP(nn.Module):
|
169 |
+
def __init__(self, config):
|
170 |
+
super().__init__()
|
171 |
+
self.config = config
|
172 |
+
self.hidden_size = config.hidden_size
|
173 |
+
self.intermediate_size = config.intermediate_size
|
174 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
175 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
176 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
177 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
178 |
+
|
179 |
+
def forward(self, x):
|
180 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
181 |
+
|
182 |
+
|
183 |
+
# Copied from transformers.models.llama.modeling_llama.repeat_kv
|
184 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
185 |
+
"""
|
186 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
187 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
188 |
+
"""
|
189 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
190 |
+
if n_rep == 1:
|
191 |
+
return hidden_states
|
192 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
193 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
194 |
+
|
195 |
+
|
196 |
+
class Qwen2Attention(nn.Module):
|
197 |
+
"""
|
198 |
+
Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
|
199 |
+
and "Generating Long Sequences with Sparse Transformers".
|
200 |
+
"""
|
201 |
+
|
202 |
+
def __init__(self, config: Qwen2Config, layer_idx: Optional[int] = None):
|
203 |
+
super().__init__()
|
204 |
+
self.config = config
|
205 |
+
self.layer_idx = layer_idx
|
206 |
+
if layer_idx is None:
|
207 |
+
logger.warning_once(
|
208 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
209 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
210 |
+
"when creating this class."
|
211 |
+
)
|
212 |
+
|
213 |
+
self.hidden_size = config.hidden_size
|
214 |
+
self.num_heads = config.num_attention_heads
|
215 |
+
self.head_dim = self.hidden_size // self.num_heads
|
216 |
+
self.num_key_value_heads = config.num_key_value_heads
|
217 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
218 |
+
self.max_position_embeddings = config.max_position_embeddings
|
219 |
+
self.rope_theta = config.rope_theta
|
220 |
+
self.is_causal = True
|
221 |
+
self.attention_dropout = config.attention_dropout
|
222 |
+
|
223 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
224 |
+
raise ValueError(
|
225 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
226 |
+
f" and `num_heads`: {self.num_heads})."
|
227 |
+
)
|
228 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
|
229 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
230 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
231 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
232 |
+
|
233 |
+
self.rotary_emb = Qwen2RotaryEmbedding(
|
234 |
+
self.head_dim,
|
235 |
+
max_position_embeddings=self.max_position_embeddings,
|
236 |
+
base=self.rope_theta,
|
237 |
+
)
|
238 |
+
|
239 |
+
def forward(
|
240 |
+
self,
|
241 |
+
hidden_states: torch.Tensor,
|
242 |
+
attention_mask: Optional[torch.Tensor] = None,
|
243 |
+
position_ids: Optional[torch.LongTensor] = None,
|
244 |
+
past_key_value: Optional[Cache] = None,
|
245 |
+
output_attentions: bool = False,
|
246 |
+
use_cache: bool = False,
|
247 |
+
**kwargs,
|
248 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
249 |
+
if "padding_mask" in kwargs:
|
250 |
+
warnings.warn(
|
251 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
252 |
+
)
|
253 |
+
bsz, q_len, _ = hidden_states.size()
|
254 |
+
|
255 |
+
query_states = self.q_proj(hidden_states)
|
256 |
+
key_states = self.k_proj(hidden_states)
|
257 |
+
value_states = self.v_proj(hidden_states)
|
258 |
+
|
259 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
260 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
261 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
262 |
+
|
263 |
+
kv_seq_len = key_states.shape[-2]
|
264 |
+
if past_key_value is not None:
|
265 |
+
if self.layer_idx is None:
|
266 |
+
raise ValueError(
|
267 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
268 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
269 |
+
"with a layer index."
|
270 |
+
)
|
271 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
272 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
273 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
274 |
+
|
275 |
+
if past_key_value is not None:
|
276 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
277 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
278 |
+
|
279 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
280 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
281 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
282 |
+
|
283 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
284 |
+
|
285 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
286 |
+
raise ValueError(
|
287 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
288 |
+
f" {attn_weights.size()}"
|
289 |
+
)
|
290 |
+
|
291 |
+
if attention_mask is not None:
|
292 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
293 |
+
raise ValueError(
|
294 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
295 |
+
)
|
296 |
+
|
297 |
+
attn_weights = attn_weights + attention_mask
|
298 |
+
|
299 |
+
# upcast attention to fp32
|
300 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
301 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
302 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
303 |
+
|
304 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
305 |
+
raise ValueError(
|
306 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
307 |
+
f" {attn_output.size()}"
|
308 |
+
)
|
309 |
+
|
310 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
311 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
312 |
+
|
313 |
+
attn_output = self.o_proj(attn_output)
|
314 |
+
|
315 |
+
if not output_attentions:
|
316 |
+
attn_weights = None
|
317 |
+
|
318 |
+
return attn_output, attn_weights, past_key_value
|
319 |
+
|
320 |
+
|
321 |
+
class Qwen2FlashAttention2(Qwen2Attention):
|
322 |
+
"""
|
323 |
+
Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
|
324 |
+
as the weights of the module stays untouched. The only required change would be on the forward pass
|
325 |
+
where it needs to correctly call the public API of flash attention and deal with padding tokens
|
326 |
+
in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
|
327 |
+
config.max_window_layers layers.
|
328 |
+
"""
|
329 |
+
|
330 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
|
331 |
+
def __init__(self, *args, **kwargs):
|
332 |
+
super().__init__(*args, **kwargs)
|
333 |
+
|
334 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
335 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
|
336 |
+
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
|
337 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
338 |
+
|
339 |
+
def forward(
|
340 |
+
self,
|
341 |
+
hidden_states: torch.Tensor,
|
342 |
+
attention_mask: Optional[torch.Tensor] = None,
|
343 |
+
position_ids: Optional[torch.LongTensor] = None,
|
344 |
+
past_key_value: Optional[Cache] = None,
|
345 |
+
output_attentions: bool = False,
|
346 |
+
use_cache: bool = False,
|
347 |
+
**kwargs,
|
348 |
+
):
|
349 |
+
if "padding_mask" in kwargs:
|
350 |
+
warnings.warn(
|
351 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
352 |
+
)
|
353 |
+
|
354 |
+
# overwrite attention_mask with padding_mask
|
355 |
+
attention_mask = kwargs.pop("padding_mask")
|
356 |
+
bsz, q_len, _ = hidden_states.size()
|
357 |
+
|
358 |
+
query_states = self.q_proj(hidden_states)
|
359 |
+
key_states = self.k_proj(hidden_states)
|
360 |
+
value_states = self.v_proj(hidden_states)
|
361 |
+
|
362 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
363 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
364 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
365 |
+
|
366 |
+
kv_seq_len = key_states.shape[-2]
|
367 |
+
if past_key_value is not None:
|
368 |
+
if self.layer_idx is None:
|
369 |
+
raise ValueError(
|
370 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
371 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
372 |
+
"with a layer index."
|
373 |
+
)
|
374 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
375 |
+
|
376 |
+
# Because the input can be padded, the absolute sequence length depends on the max position id.
|
377 |
+
rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
|
378 |
+
cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
|
379 |
+
|
380 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
381 |
+
|
382 |
+
use_sliding_windows = (
|
383 |
+
_flash_supports_window_size
|
384 |
+
and getattr(self.config, "sliding_window", None) is not None
|
385 |
+
and kv_seq_len > self.config.sliding_window
|
386 |
+
and self.config.use_sliding_window
|
387 |
+
)
|
388 |
+
|
389 |
+
if not _flash_supports_window_size:
|
390 |
+
logger.warning_once(
|
391 |
+
"The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
|
392 |
+
" make sure to upgrade flash-attn library."
|
393 |
+
)
|
394 |
+
|
395 |
+
if past_key_value is not None:
|
396 |
+
# Activate slicing cache only if the config has a value `sliding_windows` attribute
|
397 |
+
cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
|
398 |
+
if (
|
399 |
+
getattr(self.config, "sliding_window", None) is not None
|
400 |
+
and kv_seq_len > self.config.sliding_window
|
401 |
+
and cache_has_contents
|
402 |
+
):
|
403 |
+
slicing_tokens = 1 - self.config.sliding_window
|
404 |
+
|
405 |
+
past_key = past_key_value[self.layer_idx][0]
|
406 |
+
past_value = past_key_value[self.layer_idx][1]
|
407 |
+
|
408 |
+
past_key = past_key[:, :, slicing_tokens:, :].contiguous()
|
409 |
+
past_value = past_value[:, :, slicing_tokens:, :].contiguous()
|
410 |
+
|
411 |
+
if past_key.shape[-2] != self.config.sliding_window - 1:
|
412 |
+
raise ValueError(
|
413 |
+
f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
|
414 |
+
f" {past_key.shape}"
|
415 |
+
)
|
416 |
+
|
417 |
+
if attention_mask is not None:
|
418 |
+
attention_mask = attention_mask[:, slicing_tokens:]
|
419 |
+
attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
|
420 |
+
|
421 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
422 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
423 |
+
|
424 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
425 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
426 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
427 |
+
dropout_rate = 0.0 if not self.training else self.attention_dropout
|
428 |
+
|
429 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
430 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
431 |
+
# cast them back in float16 just to be sure everything works as expected.
|
432 |
+
input_dtype = query_states.dtype
|
433 |
+
if input_dtype == torch.float32:
|
434 |
+
if torch.is_autocast_enabled():
|
435 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
436 |
+
# Handle the case where the model is quantized
|
437 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
438 |
+
target_dtype = self.config._pre_quantization_dtype
|
439 |
+
else:
|
440 |
+
target_dtype = self.q_proj.weight.dtype
|
441 |
+
|
442 |
+
logger.warning_once(
|
443 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
444 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
445 |
+
f" {target_dtype}."
|
446 |
+
)
|
447 |
+
|
448 |
+
query_states = query_states.to(target_dtype)
|
449 |
+
key_states = key_states.to(target_dtype)
|
450 |
+
value_states = value_states.to(target_dtype)
|
451 |
+
|
452 |
+
# Reashape to the expected shape for Flash Attention
|
453 |
+
query_states = query_states.transpose(1, 2)
|
454 |
+
key_states = key_states.transpose(1, 2)
|
455 |
+
value_states = value_states.transpose(1, 2)
|
456 |
+
|
457 |
+
attn_output = self._flash_attention_forward(
|
458 |
+
query_states,
|
459 |
+
key_states,
|
460 |
+
value_states,
|
461 |
+
attention_mask,
|
462 |
+
q_len,
|
463 |
+
dropout=dropout_rate,
|
464 |
+
use_sliding_windows=use_sliding_windows,
|
465 |
+
)
|
466 |
+
|
467 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
468 |
+
attn_output = self.o_proj(attn_output)
|
469 |
+
|
470 |
+
if not output_attentions:
|
471 |
+
attn_weights = None
|
472 |
+
|
473 |
+
return attn_output, attn_weights, past_key_value
|
474 |
+
|
475 |
+
def _flash_attention_forward(
|
476 |
+
self,
|
477 |
+
query_states,
|
478 |
+
key_states,
|
479 |
+
value_states,
|
480 |
+
attention_mask,
|
481 |
+
query_length,
|
482 |
+
dropout=0.0,
|
483 |
+
softmax_scale=None,
|
484 |
+
use_sliding_windows=False,
|
485 |
+
):
|
486 |
+
"""
|
487 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
488 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
489 |
+
|
490 |
+
Args:
|
491 |
+
query_states (`torch.Tensor`):
|
492 |
+
Input query states to be passed to Flash Attention API
|
493 |
+
key_states (`torch.Tensor`):
|
494 |
+
Input key states to be passed to Flash Attention API
|
495 |
+
value_states (`torch.Tensor`):
|
496 |
+
Input value states to be passed to Flash Attention API
|
497 |
+
attention_mask (`torch.Tensor`):
|
498 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
499 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
500 |
+
dropout (`float`):
|
501 |
+
Attention dropout
|
502 |
+
softmax_scale (`float`, *optional*):
|
503 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
504 |
+
use_sliding_windows (`bool`, *optional*):
|
505 |
+
Whether to activate sliding window attention.
|
506 |
+
"""
|
507 |
+
if not self._flash_attn_uses_top_left_mask:
|
508 |
+
causal = self.is_causal
|
509 |
+
else:
|
510 |
+
# TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
|
511 |
+
causal = self.is_causal and query_length != 1
|
512 |
+
|
513 |
+
# Decide whether to use SWA or not by layer index.
|
514 |
+
if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
|
515 |
+
use_sliding_windows = False
|
516 |
+
|
517 |
+
# Contains at least one padding token in the sequence
|
518 |
+
if attention_mask is not None:
|
519 |
+
batch_size = query_states.shape[0]
|
520 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
521 |
+
query_states, key_states, value_states, attention_mask, query_length
|
522 |
+
)
|
523 |
+
|
524 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
525 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
526 |
+
|
527 |
+
if not use_sliding_windows:
|
528 |
+
attn_output_unpad = flash_attn_varlen_func(
|
529 |
+
query_states,
|
530 |
+
key_states,
|
531 |
+
value_states,
|
532 |
+
cu_seqlens_q=cu_seqlens_q,
|
533 |
+
cu_seqlens_k=cu_seqlens_k,
|
534 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
535 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
536 |
+
dropout_p=dropout,
|
537 |
+
softmax_scale=softmax_scale,
|
538 |
+
causal=causal,
|
539 |
+
)
|
540 |
+
else:
|
541 |
+
attn_output_unpad = flash_attn_varlen_func(
|
542 |
+
query_states,
|
543 |
+
key_states,
|
544 |
+
value_states,
|
545 |
+
cu_seqlens_q=cu_seqlens_q,
|
546 |
+
cu_seqlens_k=cu_seqlens_k,
|
547 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
548 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
549 |
+
dropout_p=dropout,
|
550 |
+
softmax_scale=softmax_scale,
|
551 |
+
causal=causal,
|
552 |
+
window_size=(self.config.sliding_window, self.config.sliding_window),
|
553 |
+
)
|
554 |
+
|
555 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
556 |
+
else:
|
557 |
+
if not use_sliding_windows:
|
558 |
+
attn_output = flash_attn_func(
|
559 |
+
query_states,
|
560 |
+
key_states,
|
561 |
+
value_states,
|
562 |
+
dropout,
|
563 |
+
softmax_scale=softmax_scale,
|
564 |
+
causal=causal,
|
565 |
+
)
|
566 |
+
else:
|
567 |
+
attn_output = flash_attn_func(
|
568 |
+
query_states,
|
569 |
+
key_states,
|
570 |
+
value_states,
|
571 |
+
dropout,
|
572 |
+
softmax_scale=softmax_scale,
|
573 |
+
causal=causal,
|
574 |
+
window_size=(self.config.sliding_window, self.config.sliding_window),
|
575 |
+
)
|
576 |
+
|
577 |
+
return attn_output
|
578 |
+
|
579 |
+
# Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
|
580 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
581 |
+
batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
|
582 |
+
|
583 |
+
# On the first iteration we need to properly re-create the padding mask
|
584 |
+
# by slicing it on the proper place
|
585 |
+
if kv_seq_len != attention_mask.shape[-1]:
|
586 |
+
attention_mask_num_tokens = attention_mask.shape[-1]
|
587 |
+
attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
|
588 |
+
|
589 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
590 |
+
|
591 |
+
key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
|
592 |
+
value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
|
593 |
+
|
594 |
+
if query_length == kv_seq_len:
|
595 |
+
query_layer = index_first_axis(
|
596 |
+
query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
|
597 |
+
)
|
598 |
+
cu_seqlens_q = cu_seqlens_k
|
599 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
600 |
+
indices_q = indices_k
|
601 |
+
elif query_length == 1:
|
602 |
+
max_seqlen_in_batch_q = 1
|
603 |
+
cu_seqlens_q = torch.arange(
|
604 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
605 |
+
) # There is a memcpy here, that is very bad.
|
606 |
+
indices_q = cu_seqlens_q[:-1]
|
607 |
+
query_layer = query_layer.squeeze(1)
|
608 |
+
else:
|
609 |
+
# The -q_len: slice assumes left padding.
|
610 |
+
attention_mask = attention_mask[:, -query_length:]
|
611 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
612 |
+
|
613 |
+
return (
|
614 |
+
query_layer,
|
615 |
+
key_layer,
|
616 |
+
value_layer,
|
617 |
+
indices_q,
|
618 |
+
(cu_seqlens_q, cu_seqlens_k),
|
619 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
620 |
+
)
|
621 |
+
|
622 |
+
|
623 |
+
# Copied from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Qwen2
|
624 |
+
class Qwen2SdpaAttention(Qwen2Attention):
|
625 |
+
"""
|
626 |
+
Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
627 |
+
`Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
628 |
+
SDPA API.
|
629 |
+
"""
|
630 |
+
|
631 |
+
# Adapted from Qwen2Attention.forward
|
632 |
+
def forward(
|
633 |
+
self,
|
634 |
+
hidden_states: torch.Tensor,
|
635 |
+
attention_mask: Optional[torch.Tensor] = None,
|
636 |
+
position_ids: Optional[torch.LongTensor] = None,
|
637 |
+
past_key_value: Optional[Cache] = None,
|
638 |
+
output_attentions: bool = False,
|
639 |
+
use_cache: bool = False,
|
640 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
641 |
+
if output_attentions:
|
642 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
643 |
+
logger.warning_once(
|
644 |
+
"Qwen2Model is using Qwen2SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
|
645 |
+
'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.'
|
646 |
+
)
|
647 |
+
return super().forward(
|
648 |
+
hidden_states=hidden_states,
|
649 |
+
attention_mask=attention_mask,
|
650 |
+
position_ids=position_ids,
|
651 |
+
past_key_value=past_key_value,
|
652 |
+
output_attentions=output_attentions,
|
653 |
+
use_cache=use_cache,
|
654 |
+
)
|
655 |
+
|
656 |
+
bsz, q_len, _ = hidden_states.size()
|
657 |
+
|
658 |
+
query_states = self.q_proj(hidden_states)
|
659 |
+
key_states = self.k_proj(hidden_states)
|
660 |
+
value_states = self.v_proj(hidden_states)
|
661 |
+
|
662 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
663 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
664 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
665 |
+
|
666 |
+
kv_seq_len = key_states.shape[-2]
|
667 |
+
if past_key_value is not None:
|
668 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
669 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
670 |
+
|
671 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
672 |
+
|
673 |
+
if past_key_value is not None:
|
674 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
675 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
676 |
+
|
677 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
678 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
679 |
+
|
680 |
+
if attention_mask is not None:
|
681 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
682 |
+
raise ValueError(
|
683 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
684 |
+
)
|
685 |
+
|
686 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
687 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
688 |
+
if query_states.device.type == "cuda" and attention_mask is not None:
|
689 |
+
query_states = query_states.contiguous()
|
690 |
+
key_states = key_states.contiguous()
|
691 |
+
value_states = value_states.contiguous()
|
692 |
+
|
693 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
694 |
+
query_states,
|
695 |
+
key_states,
|
696 |
+
value_states,
|
697 |
+
attn_mask=attention_mask,
|
698 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
699 |
+
# The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
|
700 |
+
is_causal=self.is_causal and attention_mask is None and q_len > 1,
|
701 |
+
)
|
702 |
+
|
703 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
704 |
+
attn_output = attn_output.view(bsz, q_len, self.hidden_size)
|
705 |
+
|
706 |
+
attn_output = self.o_proj(attn_output)
|
707 |
+
|
708 |
+
return attn_output, None, past_key_value
|
709 |
+
|
710 |
+
|
711 |
+
QWEN2_ATTENTION_CLASSES = {
|
712 |
+
"eager": Qwen2Attention,
|
713 |
+
"flash_attention_2": Qwen2FlashAttention2,
|
714 |
+
"sdpa": Qwen2SdpaAttention,
|
715 |
+
}
|
716 |
+
|
717 |
+
|
718 |
+
class Qwen2DecoderLayer(nn.Module):
|
719 |
+
def __init__(self, config: Qwen2Config, layer_idx: int):
|
720 |
+
super().__init__()
|
721 |
+
self.hidden_size = config.hidden_size
|
722 |
+
|
723 |
+
if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
|
724 |
+
logger.warning_once(
|
725 |
+
f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
|
726 |
+
"unexpected results may be encountered."
|
727 |
+
)
|
728 |
+
self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
|
729 |
+
|
730 |
+
self.mlp = Qwen2MLP(config)
|
731 |
+
self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
732 |
+
self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
733 |
+
|
734 |
+
def forward(
|
735 |
+
self,
|
736 |
+
hidden_states: torch.Tensor,
|
737 |
+
attention_mask: Optional[torch.Tensor] = None,
|
738 |
+
position_ids: Optional[torch.LongTensor] = None,
|
739 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
740 |
+
output_attentions: Optional[bool] = False,
|
741 |
+
use_cache: Optional[bool] = False,
|
742 |
+
**kwargs,
|
743 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
744 |
+
if "padding_mask" in kwargs:
|
745 |
+
warnings.warn(
|
746 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. "
|
747 |
+
"Please make sure use `attention_mask` instead.`"
|
748 |
+
)
|
749 |
+
"""
|
750 |
+
Args:
|
751 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
752 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
753 |
+
`(batch, sequence_length)` where padding elements are indicated by 0.
|
754 |
+
output_attentions (`bool`, *optional*):
|
755 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
756 |
+
returned tensors for more detail.
|
757 |
+
use_cache (`bool`, *optional*):
|
758 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
759 |
+
(see `past_key_values`).
|
760 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
761 |
+
"""
|
762 |
+
|
763 |
+
residual = hidden_states
|
764 |
+
|
765 |
+
hidden_states = self.input_layernorm(hidden_states)
|
766 |
+
|
767 |
+
# Self Attention
|
768 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
769 |
+
hidden_states=hidden_states,
|
770 |
+
attention_mask=attention_mask,
|
771 |
+
position_ids=position_ids,
|
772 |
+
past_key_value=past_key_value,
|
773 |
+
output_attentions=output_attentions,
|
774 |
+
use_cache=use_cache,
|
775 |
+
)
|
776 |
+
hidden_states = residual + hidden_states
|
777 |
+
|
778 |
+
# Fully Connected
|
779 |
+
residual = hidden_states
|
780 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
781 |
+
hidden_states = self.mlp(hidden_states)
|
782 |
+
hidden_states = residual + hidden_states
|
783 |
+
|
784 |
+
outputs = (hidden_states,)
|
785 |
+
|
786 |
+
if output_attentions:
|
787 |
+
outputs += (self_attn_weights,)
|
788 |
+
|
789 |
+
if use_cache:
|
790 |
+
outputs += (present_key_value,)
|
791 |
+
|
792 |
+
return outputs
|
793 |
+
|
794 |
+
|
795 |
+
QWEN2_START_DOCSTRING = r"""
|
796 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
797 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
798 |
+
etc.)
|
799 |
+
|
800 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
801 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
802 |
+
and behavior.
|
803 |
+
|
804 |
+
Parameters:
|
805 |
+
config ([`Qwen2Config`]):
|
806 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
807 |
+
load the weights associated with the model, only the configuration. Check out the
|
808 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
809 |
+
"""
|
810 |
+
|
811 |
+
|
812 |
+
@add_start_docstrings(
|
813 |
+
"The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
|
814 |
+
QWEN2_START_DOCSTRING,
|
815 |
+
)
|
816 |
+
class Qwen2PreTrainedModel(PreTrainedModel):
|
817 |
+
config_class = Qwen2Config
|
818 |
+
base_model_prefix = "model"
|
819 |
+
supports_gradient_checkpointing = True
|
820 |
+
_no_split_modules = ["Qwen2DecoderLayer"]
|
821 |
+
_skip_keys_device_placement = "past_key_values"
|
822 |
+
_supports_flash_attn_2 = True
|
823 |
+
_supports_sdpa = True
|
824 |
+
_supports_cache_class = True
|
825 |
+
|
826 |
+
def _init_weights(self, module):
|
827 |
+
std = self.config.initializer_range
|
828 |
+
if isinstance(module, nn.Linear):
|
829 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
830 |
+
if module.bias is not None:
|
831 |
+
module.bias.data.zero_()
|
832 |
+
elif isinstance(module, nn.Embedding):
|
833 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
834 |
+
if module.padding_idx is not None:
|
835 |
+
module.weight.data[module.padding_idx].zero_()
|
836 |
+
|
837 |
+
|
838 |
+
QWEN2_INPUTS_DOCSTRING = r"""
|
839 |
+
Args:
|
840 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
841 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
842 |
+
it.
|
843 |
+
|
844 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
845 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
846 |
+
|
847 |
+
[What are input IDs?](../glossary#input-ids)
|
848 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
849 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
850 |
+
|
851 |
+
- 1 for tokens that are **not masked**,
|
852 |
+
- 0 for tokens that are **masked**.
|
853 |
+
|
854 |
+
[What are attention masks?](../glossary#attention-mask)
|
855 |
+
|
856 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
857 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
858 |
+
|
859 |
+
If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
860 |
+
`past_key_values`).
|
861 |
+
|
862 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
863 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
864 |
+
information on the default strategy.
|
865 |
+
|
866 |
+
- 1 indicates the head is **not masked**,
|
867 |
+
- 0 indicates the head is **masked**.
|
868 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
869 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
870 |
+
config.n_positions - 1]`.
|
871 |
+
|
872 |
+
[What are position IDs?](../glossary#position-ids)
|
873 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
874 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
875 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
876 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
877 |
+
|
878 |
+
Two formats are allowed:
|
879 |
+
- a [`~cache_utils.Cache`] instance;
|
880 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
881 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
882 |
+
cache format.
|
883 |
+
|
884 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
885 |
+
legacy cache format will be returned.
|
886 |
+
|
887 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
888 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
889 |
+
of shape `(batch_size, sequence_length)`.
|
890 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
891 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
892 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
893 |
+
model's internal embedding lookup matrix.
|
894 |
+
use_cache (`bool`, *optional*):
|
895 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
896 |
+
`past_key_values`).
|
897 |
+
output_attentions (`bool`, *optional*):
|
898 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
899 |
+
tensors for more detail.
|
900 |
+
output_hidden_states (`bool`, *optional*):
|
901 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
902 |
+
more detail.
|
903 |
+
return_dict (`bool`, *optional*):
|
904 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
905 |
+
"""
|
906 |
+
|
907 |
+
|
908 |
+
@add_start_docstrings(
|
909 |
+
"The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
|
910 |
+
QWEN2_START_DOCSTRING,
|
911 |
+
)
|
912 |
+
class Qwen2Model(Qwen2PreTrainedModel):
|
913 |
+
"""
|
914 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
|
915 |
+
|
916 |
+
Args:
|
917 |
+
config: Qwen2Config
|
918 |
+
"""
|
919 |
+
|
920 |
+
def __init__(self, config: Qwen2Config):
|
921 |
+
super().__init__(config)
|
922 |
+
self.padding_idx = config.pad_token_id
|
923 |
+
self.vocab_size = config.vocab_size
|
924 |
+
|
925 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
926 |
+
self.layers = nn.ModuleList(
|
927 |
+
[Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
928 |
+
)
|
929 |
+
self._attn_implementation = config._attn_implementation
|
930 |
+
self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
931 |
+
|
932 |
+
self.gradient_checkpointing = False
|
933 |
+
# Initialize weights and apply final processing
|
934 |
+
self.post_init()
|
935 |
+
|
936 |
+
def get_input_embeddings(self):
|
937 |
+
return self.embed_tokens
|
938 |
+
|
939 |
+
def set_input_embeddings(self, value):
|
940 |
+
self.embed_tokens = value
|
941 |
+
|
942 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
943 |
+
def forward(
|
944 |
+
self,
|
945 |
+
input_ids: torch.LongTensor = None,
|
946 |
+
attention_mask: Optional[torch.Tensor] = None,
|
947 |
+
position_ids: Optional[torch.LongTensor] = None,
|
948 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
949 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
950 |
+
use_cache: Optional[bool] = None,
|
951 |
+
output_attentions: Optional[bool] = None,
|
952 |
+
output_hidden_states: Optional[bool] = None,
|
953 |
+
return_dict: Optional[bool] = None,
|
954 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
955 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
956 |
+
output_hidden_states = (
|
957 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
958 |
+
)
|
959 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
960 |
+
|
961 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
962 |
+
|
963 |
+
# retrieve input_ids and inputs_embeds
|
964 |
+
if input_ids is not None and inputs_embeds is not None:
|
965 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
966 |
+
elif input_ids is not None:
|
967 |
+
batch_size, seq_length = input_ids.shape
|
968 |
+
elif inputs_embeds is not None:
|
969 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
970 |
+
else:
|
971 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
972 |
+
|
973 |
+
if self.gradient_checkpointing and self.training:
|
974 |
+
if use_cache:
|
975 |
+
logger.warning_once(
|
976 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
977 |
+
)
|
978 |
+
use_cache = False
|
979 |
+
|
980 |
+
past_key_values_length = 0
|
981 |
+
|
982 |
+
if use_cache:
|
983 |
+
use_legacy_cache = not isinstance(past_key_values, Cache)
|
984 |
+
if use_legacy_cache:
|
985 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
986 |
+
past_key_values_length = past_key_values.get_usable_length(seq_length)
|
987 |
+
|
988 |
+
if position_ids is None:
|
989 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
990 |
+
position_ids = torch.arange(
|
991 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
992 |
+
)
|
993 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
994 |
+
else:
|
995 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
996 |
+
|
997 |
+
if inputs_embeds is None:
|
998 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
999 |
+
|
1000 |
+
if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
|
1001 |
+
is_padding_right = attention_mask[:, -1].sum().item() != batch_size
|
1002 |
+
if is_padding_right:
|
1003 |
+
raise ValueError(
|
1004 |
+
"You are attempting to perform batched generation with padding_side='right'"
|
1005 |
+
" this may lead to unexpected behaviour for Flash Attention version of Qwen2. Make sure to "
|
1006 |
+
" call `tokenizer.padding_side = 'left'` before tokenizing the input. "
|
1007 |
+
)
|
1008 |
+
|
1009 |
+
if self._attn_implementation == "flash_attention_2":
|
1010 |
+
# 2d mask is passed through the layers
|
1011 |
+
attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
|
1012 |
+
elif self._attn_implementation == "sdpa" and not output_attentions:
|
1013 |
+
# output_attentions=True can not be supported when using SDPA, and we fall back on
|
1014 |
+
# the manual implementation that requires a 4D causal mask in all cases.
|
1015 |
+
attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
|
1016 |
+
attention_mask,
|
1017 |
+
(batch_size, seq_length),
|
1018 |
+
inputs_embeds,
|
1019 |
+
past_key_values_length,
|
1020 |
+
sliding_window=self.config.sliding_window,
|
1021 |
+
)
|
1022 |
+
else:
|
1023 |
+
# 4d mask is passed through the layers
|
1024 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
1025 |
+
attention_mask,
|
1026 |
+
(batch_size, seq_length),
|
1027 |
+
inputs_embeds,
|
1028 |
+
past_key_values_length,
|
1029 |
+
sliding_window=self.config.sliding_window,
|
1030 |
+
)
|
1031 |
+
|
1032 |
+
hidden_states = inputs_embeds
|
1033 |
+
|
1034 |
+
# decoder layers
|
1035 |
+
all_hidden_states = () if output_hidden_states else None
|
1036 |
+
all_self_attns = () if output_attentions else None
|
1037 |
+
next_decoder_cache = None
|
1038 |
+
|
1039 |
+
for decoder_layer in self.layers:
|
1040 |
+
if output_hidden_states:
|
1041 |
+
all_hidden_states += (hidden_states,)
|
1042 |
+
|
1043 |
+
if self.gradient_checkpointing and self.training:
|
1044 |
+
layer_outputs = self._gradient_checkpointing_func(
|
1045 |
+
decoder_layer.__call__,
|
1046 |
+
hidden_states,
|
1047 |
+
attention_mask,
|
1048 |
+
position_ids,
|
1049 |
+
past_key_values,
|
1050 |
+
output_attentions,
|
1051 |
+
use_cache,
|
1052 |
+
)
|
1053 |
+
else:
|
1054 |
+
layer_outputs = decoder_layer(
|
1055 |
+
hidden_states,
|
1056 |
+
attention_mask=attention_mask,
|
1057 |
+
position_ids=position_ids,
|
1058 |
+
past_key_value=past_key_values,
|
1059 |
+
output_attentions=output_attentions,
|
1060 |
+
use_cache=use_cache,
|
1061 |
+
)
|
1062 |
+
|
1063 |
+
hidden_states = layer_outputs[0]
|
1064 |
+
|
1065 |
+
if use_cache:
|
1066 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
1067 |
+
|
1068 |
+
if output_attentions:
|
1069 |
+
all_self_attns += (layer_outputs[1],)
|
1070 |
+
|
1071 |
+
hidden_states = self.norm(hidden_states)
|
1072 |
+
|
1073 |
+
# add hidden states from the last decoder layer
|
1074 |
+
if output_hidden_states:
|
1075 |
+
all_hidden_states += (hidden_states,)
|
1076 |
+
|
1077 |
+
next_cache = None
|
1078 |
+
if use_cache:
|
1079 |
+
next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
|
1080 |
+
|
1081 |
+
if not return_dict:
|
1082 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
1083 |
+
return BaseModelOutputWithPast(
|
1084 |
+
last_hidden_state=hidden_states,
|
1085 |
+
past_key_values=next_cache,
|
1086 |
+
hidden_states=all_hidden_states,
|
1087 |
+
attentions=all_self_attns,
|
1088 |
+
)
|
1089 |
+
|
1090 |
+
|
1091 |
+
class Qwen2ForCausalLM(Qwen2PreTrainedModel):
|
1092 |
+
_tied_weights_keys = ["lm_head.weight"]
|
1093 |
+
|
1094 |
+
def __init__(self, config):
|
1095 |
+
super().__init__(config)
|
1096 |
+
self.model = Qwen2Model(config)
|
1097 |
+
self.vocab_size = config.vocab_size
|
1098 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
1099 |
+
|
1100 |
+
# Initialize weights and apply final processing
|
1101 |
+
self.post_init()
|
1102 |
+
|
1103 |
+
def get_input_embeddings(self):
|
1104 |
+
return self.model.embed_tokens
|
1105 |
+
|
1106 |
+
def set_input_embeddings(self, value):
|
1107 |
+
self.model.embed_tokens = value
|
1108 |
+
|
1109 |
+
def get_output_embeddings(self):
|
1110 |
+
return self.lm_head
|
1111 |
+
|
1112 |
+
def set_output_embeddings(self, new_embeddings):
|
1113 |
+
self.lm_head = new_embeddings
|
1114 |
+
|
1115 |
+
def set_decoder(self, decoder):
|
1116 |
+
self.model = decoder
|
1117 |
+
|
1118 |
+
def get_decoder(self):
|
1119 |
+
return self.model
|
1120 |
+
|
1121 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
1122 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
1123 |
+
def forward(
|
1124 |
+
self,
|
1125 |
+
input_ids: torch.LongTensor = None,
|
1126 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1127 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1128 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1129 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1130 |
+
labels: Optional[torch.LongTensor] = None,
|
1131 |
+
use_cache: Optional[bool] = None,
|
1132 |
+
output_attentions: Optional[bool] = None,
|
1133 |
+
output_hidden_states: Optional[bool] = None,
|
1134 |
+
return_dict: Optional[bool] = None,
|
1135 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1136 |
+
r"""
|
1137 |
+
Args:
|
1138 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1139 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
1140 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1141 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
1142 |
+
|
1143 |
+
Returns:
|
1144 |
+
|
1145 |
+
Example:
|
1146 |
+
|
1147 |
+
```python
|
1148 |
+
>>> from transformers import AutoTokenizer, Qwen2ForCausalLM
|
1149 |
+
|
1150 |
+
>>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
1151 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
1152 |
+
|
1153 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
1154 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1155 |
+
|
1156 |
+
>>> # Generate
|
1157 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1158 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1159 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
1160 |
+
```"""
|
1161 |
+
|
1162 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1163 |
+
output_hidden_states = (
|
1164 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1165 |
+
)
|
1166 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1167 |
+
|
1168 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1169 |
+
outputs = self.model(
|
1170 |
+
input_ids=input_ids,
|
1171 |
+
attention_mask=attention_mask,
|
1172 |
+
position_ids=position_ids,
|
1173 |
+
past_key_values=past_key_values,
|
1174 |
+
inputs_embeds=inputs_embeds,
|
1175 |
+
use_cache=use_cache,
|
1176 |
+
output_attentions=output_attentions,
|
1177 |
+
output_hidden_states=output_hidden_states,
|
1178 |
+
return_dict=return_dict,
|
1179 |
+
)
|
1180 |
+
|
1181 |
+
hidden_states = outputs[0]
|
1182 |
+
logits = self.lm_head(hidden_states)
|
1183 |
+
logits = logits.float()
|
1184 |
+
|
1185 |
+
loss = None
|
1186 |
+
if labels is not None:
|
1187 |
+
# Shift so that tokens < n predict n
|
1188 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1189 |
+
shift_labels = labels[..., 1:].contiguous()
|
1190 |
+
# Flatten the tokens
|
1191 |
+
loss_fct = CrossEntropyLoss()
|
1192 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1193 |
+
shift_labels = shift_labels.view(-1)
|
1194 |
+
# Enable model parallelism
|
1195 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1196 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1197 |
+
|
1198 |
+
if not return_dict:
|
1199 |
+
output = (logits,) + outputs[1:]
|
1200 |
+
return (loss,) + output if loss is not None else output
|
1201 |
+
|
1202 |
+
return CausalLMOutputWithPast(
|
1203 |
+
loss=loss,
|
1204 |
+
logits=logits,
|
1205 |
+
past_key_values=outputs.past_key_values,
|
1206 |
+
hidden_states=outputs.hidden_states,
|
1207 |
+
attentions=outputs.attentions,
|
1208 |
+
)
|
1209 |
+
|
1210 |
+
def prepare_inputs_for_generation(
|
1211 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
1212 |
+
):
|
1213 |
+
# Omit tokens covered by past_key_values
|
1214 |
+
if past_key_values is not None:
|
1215 |
+
if isinstance(past_key_values, Cache):
|
1216 |
+
cache_length = past_key_values.get_seq_length()
|
1217 |
+
past_length = past_key_values.seen_tokens
|
1218 |
+
max_cache_length = past_key_values.get_max_length()
|
1219 |
+
else:
|
1220 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
1221 |
+
max_cache_length = None
|
1222 |
+
|
1223 |
+
# Keep only the unprocessed tokens:
|
1224 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
1225 |
+
# some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
|
1226 |
+
# input)
|
1227 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
1228 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
|
1229 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
1230 |
+
# input_ids based on the past_length.
|
1231 |
+
elif past_length < input_ids.shape[1]:
|
1232 |
+
input_ids = input_ids[:, past_length:]
|
1233 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
1234 |
+
|
1235 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
1236 |
+
if (
|
1237 |
+
max_cache_length is not None
|
1238 |
+
and attention_mask is not None
|
1239 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
1240 |
+
):
|
1241 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
1242 |
+
|
1243 |
+
position_ids = kwargs.get("position_ids", None)
|
1244 |
+
if attention_mask is not None and position_ids is None:
|
1245 |
+
# create position_ids on the fly for batch generation
|
1246 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1247 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1248 |
+
if past_key_values:
|
1249 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
1250 |
+
|
1251 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1252 |
+
if inputs_embeds is not None and past_key_values is None:
|
1253 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1254 |
+
else:
|
1255 |
+
model_inputs = {"input_ids": input_ids}
|
1256 |
+
|
1257 |
+
model_inputs.update(
|
1258 |
+
{
|
1259 |
+
"position_ids": position_ids,
|
1260 |
+
"past_key_values": past_key_values,
|
1261 |
+
"use_cache": kwargs.get("use_cache"),
|
1262 |
+
"attention_mask": attention_mask,
|
1263 |
+
}
|
1264 |
+
)
|
1265 |
+
return model_inputs
|
1266 |
+
|
1267 |
+
@staticmethod
|
1268 |
+
def _reorder_cache(past_key_values, beam_idx):
|
1269 |
+
reordered_past = ()
|
1270 |
+
for layer_past in past_key_values:
|
1271 |
+
reordered_past += (
|
1272 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
1273 |
+
)
|
1274 |
+
return reordered_past
|
1275 |
+
|
1276 |
+
|
1277 |
+
@add_start_docstrings(
|
1278 |
+
"""
|
1279 |
+
The Qwen2 Model transformer with a sequence classification head on top (linear layer).
|
1280 |
+
|
1281 |
+
[`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
1282 |
+
(e.g. GPT-2) do.
|
1283 |
+
|
1284 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
1285 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
1286 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
1287 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
1288 |
+
each row of the batch).
|
1289 |
+
""",
|
1290 |
+
QWEN2_START_DOCSTRING,
|
1291 |
+
)
|
1292 |
+
class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
|
1293 |
+
def __init__(self, config):
|
1294 |
+
super().__init__(config)
|
1295 |
+
self.num_labels = config.num_labels
|
1296 |
+
self.model = Qwen2Model(config)
|
1297 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
1298 |
+
|
1299 |
+
# Initialize weights and apply final processing
|
1300 |
+
self.post_init()
|
1301 |
+
|
1302 |
+
def get_input_embeddings(self):
|
1303 |
+
return self.model.embed_tokens
|
1304 |
+
|
1305 |
+
def set_input_embeddings(self, value):
|
1306 |
+
self.model.embed_tokens = value
|
1307 |
+
|
1308 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
1309 |
+
def forward(
|
1310 |
+
self,
|
1311 |
+
input_ids: torch.LongTensor = None,
|
1312 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1313 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1314 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1315 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1316 |
+
labels: Optional[torch.LongTensor] = None,
|
1317 |
+
use_cache: Optional[bool] = None,
|
1318 |
+
output_attentions: Optional[bool] = None,
|
1319 |
+
output_hidden_states: Optional[bool] = None,
|
1320 |
+
return_dict: Optional[bool] = None,
|
1321 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
1322 |
+
r"""
|
1323 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1324 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1325 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1326 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1327 |
+
"""
|
1328 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1329 |
+
|
1330 |
+
transformer_outputs = self.model(
|
1331 |
+
input_ids,
|
1332 |
+
attention_mask=attention_mask,
|
1333 |
+
position_ids=position_ids,
|
1334 |
+
past_key_values=past_key_values,
|
1335 |
+
inputs_embeds=inputs_embeds,
|
1336 |
+
use_cache=use_cache,
|
1337 |
+
output_attentions=output_attentions,
|
1338 |
+
output_hidden_states=output_hidden_states,
|
1339 |
+
return_dict=return_dict,
|
1340 |
+
)
|
1341 |
+
hidden_states = transformer_outputs[0]
|
1342 |
+
logits = self.score(hidden_states)
|
1343 |
+
|
1344 |
+
if input_ids is not None:
|
1345 |
+
batch_size = input_ids.shape[0]
|
1346 |
+
else:
|
1347 |
+
batch_size = inputs_embeds.shape[0]
|
1348 |
+
|
1349 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
1350 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
1351 |
+
if self.config.pad_token_id is None:
|
1352 |
+
sequence_lengths = -1
|
1353 |
+
else:
|
1354 |
+
if input_ids is not None:
|
1355 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
1356 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
1357 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
1358 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
1359 |
+
else:
|
1360 |
+
sequence_lengths = -1
|
1361 |
+
|
1362 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
1363 |
+
|
1364 |
+
loss = None
|
1365 |
+
if labels is not None:
|
1366 |
+
labels = labels.to(logits.device)
|
1367 |
+
if self.config.problem_type is None:
|
1368 |
+
if self.num_labels == 1:
|
1369 |
+
self.config.problem_type = "regression"
|
1370 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1371 |
+
self.config.problem_type = "single_label_classification"
|
1372 |
+
else:
|
1373 |
+
self.config.problem_type = "multi_label_classification"
|
1374 |
+
|
1375 |
+
if self.config.problem_type == "regression":
|
1376 |
+
loss_fct = MSELoss()
|
1377 |
+
if self.num_labels == 1:
|
1378 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
1379 |
+
else:
|
1380 |
+
loss = loss_fct(pooled_logits, labels)
|
1381 |
+
elif self.config.problem_type == "single_label_classification":
|
1382 |
+
loss_fct = CrossEntropyLoss()
|
1383 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
1384 |
+
elif self.config.problem_type == "multi_label_classification":
|
1385 |
+
loss_fct = BCEWithLogitsLoss()
|
1386 |
+
loss = loss_fct(pooled_logits, labels)
|
1387 |
+
if not return_dict:
|
1388 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1389 |
+
return ((loss,) + output) if loss is not None else output
|
1390 |
+
|
1391 |
+
return SequenceClassifierOutputWithPast(
|
1392 |
+
loss=loss,
|
1393 |
+
logits=pooled_logits,
|
1394 |
+
past_key_values=transformer_outputs.past_key_values,
|
1395 |
+
hidden_states=transformer_outputs.hidden_states,
|
1396 |
+
attentions=transformer_outputs.attentions,
|
1397 |
+
)
|
venv/lib/python3.10/site-packages/transformers/models/qwen2/tokenization_qwen2.py
ADDED
@@ -0,0 +1,339 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 The Qwen team, Alibaba Group 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 classes for Qwen2."""
|
16 |
+
|
17 |
+
import json
|
18 |
+
import os
|
19 |
+
import unicodedata
|
20 |
+
from functools import lru_cache
|
21 |
+
from typing import Optional, Tuple
|
22 |
+
|
23 |
+
import regex as re
|
24 |
+
|
25 |
+
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
|
26 |
+
from ...utils import logging
|
27 |
+
|
28 |
+
|
29 |
+
logger = logging.get_logger(__name__)
|
30 |
+
|
31 |
+
VOCAB_FILES_NAMES = {
|
32 |
+
"vocab_file": "vocab.json",
|
33 |
+
"merges_file": "merges.txt",
|
34 |
+
}
|
35 |
+
|
36 |
+
|
37 |
+
MAX_MODEL_INPUT_SIZES = {"qwen/qwen-tokenizer": 32768}
|
38 |
+
|
39 |
+
PRETOKENIZE_REGEX = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
|
40 |
+
|
41 |
+
|
42 |
+
@lru_cache()
|
43 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.bytes_to_unicode
|
44 |
+
def bytes_to_unicode():
|
45 |
+
"""
|
46 |
+
Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
|
47 |
+
characters the bpe code barfs on.
|
48 |
+
|
49 |
+
The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
|
50 |
+
if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
|
51 |
+
decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
|
52 |
+
tables between utf-8 bytes and unicode strings.
|
53 |
+
"""
|
54 |
+
bs = (
|
55 |
+
list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
|
56 |
+
)
|
57 |
+
cs = bs[:]
|
58 |
+
n = 0
|
59 |
+
for b in range(2**8):
|
60 |
+
if b not in bs:
|
61 |
+
bs.append(b)
|
62 |
+
cs.append(2**8 + n)
|
63 |
+
n += 1
|
64 |
+
cs = [chr(n) for n in cs]
|
65 |
+
return dict(zip(bs, cs))
|
66 |
+
|
67 |
+
|
68 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.get_pairs
|
69 |
+
def get_pairs(word):
|
70 |
+
"""
|
71 |
+
Return set of symbol pairs in a word.
|
72 |
+
|
73 |
+
Word is represented as tuple of symbols (symbols being variable-length strings).
|
74 |
+
"""
|
75 |
+
pairs = set()
|
76 |
+
prev_char = word[0]
|
77 |
+
for char in word[1:]:
|
78 |
+
pairs.add((prev_char, char))
|
79 |
+
prev_char = char
|
80 |
+
return pairs
|
81 |
+
|
82 |
+
|
83 |
+
class Qwen2Tokenizer(PreTrainedTokenizer):
|
84 |
+
"""
|
85 |
+
Construct a Qwen2 tokenizer. Based on byte-level Byte-Pair-Encoding.
|
86 |
+
|
87 |
+
Same with GPT2Tokenizer, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
|
88 |
+
be encoded differently whether it is at the beginning of the sentence (without space) or not:
|
89 |
+
|
90 |
+
```python
|
91 |
+
>>> from transformers import Qwen2Tokenizer
|
92 |
+
|
93 |
+
>>> tokenizer = Qwen2Tokenizer.from_pretrained("Qwen/Qwen-tokenizer")
|
94 |
+
>>> tokenizer("Hello world")["input_ids"]
|
95 |
+
[9707, 1879]
|
96 |
+
|
97 |
+
>>> tokenizer(" Hello world")["input_ids"]
|
98 |
+
[21927, 1879]
|
99 |
+
```
|
100 |
+
This is expected.
|
101 |
+
|
102 |
+
You should not use GPT2Tokenizer instead, because of the different pretokenization rules.
|
103 |
+
|
104 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
105 |
+
this superclass for more information regarding those methods.
|
106 |
+
|
107 |
+
Args:
|
108 |
+
vocab_file (`str`):
|
109 |
+
Path to the vocabulary file.
|
110 |
+
merges_file (`str`):
|
111 |
+
Path to the merges file.
|
112 |
+
errors (`str`, *optional*, defaults to `"replace"`):
|
113 |
+
Paradigm to follow when decoding bytes to UTF-8. See
|
114 |
+
[bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
|
115 |
+
unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
116 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
117 |
+
token instead.
|
118 |
+
bos_token (`str`, *optional*):
|
119 |
+
The beginning of sequence token. Not applicable for this tokenizer.
|
120 |
+
eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
121 |
+
The end of sequence token.
|
122 |
+
pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
123 |
+
The token used for padding, for example when batching sequences of different lengths.
|
124 |
+
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
|
125 |
+
Whether or not the model should cleanup the spaces that were added when splitting the input text during the
|
126 |
+
tokenization process. Not applicable to this tokenizer, since tokenization does not add spaces.
|
127 |
+
split_special_tokens (`bool`, *optional*, defaults to `False`):
|
128 |
+
Whether or not the special tokens should be split during the tokenization process. The default behavior is
|
129 |
+
to not split special tokens. This means that if `<|endoftext|>` is the `eos_token`, then `tokenizer.tokenize("<|endoftext|>") =
|
130 |
+
['<|endoftext|>`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize("<|endoftext|>")` will be give `['<',
|
131 |
+
'|', 'endo', 'ft', 'ext', '|', '>']`. This argument is only supported for `slow` tokenizers for the moment.
|
132 |
+
"""
|
133 |
+
|
134 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
135 |
+
model_input_names = ["input_ids", "attention_mask"]
|
136 |
+
|
137 |
+
def __init__(
|
138 |
+
self,
|
139 |
+
vocab_file,
|
140 |
+
merges_file,
|
141 |
+
errors="replace",
|
142 |
+
unk_token="<|endoftext|>",
|
143 |
+
bos_token=None,
|
144 |
+
eos_token="<|endoftext|>",
|
145 |
+
pad_token="<|endoftext|>",
|
146 |
+
clean_up_tokenization_spaces=False,
|
147 |
+
split_special_tokens=False,
|
148 |
+
**kwargs,
|
149 |
+
):
|
150 |
+
# Qwen vocab does not contain control tokens; added tokens need to be special
|
151 |
+
bos_token = (
|
152 |
+
AddedToken(bos_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
153 |
+
if isinstance(bos_token, str)
|
154 |
+
else bos_token
|
155 |
+
)
|
156 |
+
eos_token = (
|
157 |
+
AddedToken(eos_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
158 |
+
if isinstance(eos_token, str)
|
159 |
+
else eos_token
|
160 |
+
)
|
161 |
+
unk_token = (
|
162 |
+
AddedToken(unk_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
163 |
+
if isinstance(unk_token, str)
|
164 |
+
else unk_token
|
165 |
+
)
|
166 |
+
pad_token = (
|
167 |
+
AddedToken(pad_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
168 |
+
if isinstance(pad_token, str)
|
169 |
+
else pad_token
|
170 |
+
)
|
171 |
+
|
172 |
+
with open(vocab_file, encoding="utf-8") as vocab_handle:
|
173 |
+
self.encoder = json.load(vocab_handle)
|
174 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
175 |
+
self.errors = errors # how to handle errors in decoding
|
176 |
+
self.byte_encoder = bytes_to_unicode()
|
177 |
+
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
|
178 |
+
bpe_merges = []
|
179 |
+
with open(merges_file, encoding="utf-8") as merges_handle:
|
180 |
+
for i, line in enumerate(merges_handle):
|
181 |
+
line = line.strip()
|
182 |
+
if (i == 0 and line.startswith("#version:")) or not line:
|
183 |
+
continue
|
184 |
+
bpe_merges.append(tuple(line.split()))
|
185 |
+
self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
|
186 |
+
# NOTE: the cache can grow without bound and will get really large for long running processes
|
187 |
+
# (esp. for texts of language that do not use space between word, e.g. Chinese); technically
|
188 |
+
# not a memory leak but appears as one.
|
189 |
+
# GPT2Tokenizer has the same problem, so let's be consistent.
|
190 |
+
self.cache = {}
|
191 |
+
|
192 |
+
self.pat = re.compile(PRETOKENIZE_REGEX)
|
193 |
+
|
194 |
+
if kwargs.get("add_prefix_space", False):
|
195 |
+
logger.warning_once(
|
196 |
+
f"{self.__class__.__name} does not support `add_prefix_space`, setting it to True has no effect."
|
197 |
+
)
|
198 |
+
|
199 |
+
super().__init__(
|
200 |
+
errors=errors,
|
201 |
+
bos_token=bos_token,
|
202 |
+
eos_token=eos_token,
|
203 |
+
pad_token=pad_token,
|
204 |
+
unk_token=unk_token,
|
205 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
206 |
+
split_special_tokens=split_special_tokens,
|
207 |
+
**kwargs,
|
208 |
+
)
|
209 |
+
|
210 |
+
@property
|
211 |
+
def vocab_size(self) -> int:
|
212 |
+
return len(self.encoder)
|
213 |
+
|
214 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.get_vocab
|
215 |
+
def get_vocab(self):
|
216 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
217 |
+
|
218 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.bpe
|
219 |
+
def bpe(self, token):
|
220 |
+
if token in self.cache:
|
221 |
+
return self.cache[token]
|
222 |
+
word = tuple(token)
|
223 |
+
pairs = get_pairs(word)
|
224 |
+
|
225 |
+
if not pairs:
|
226 |
+
return token
|
227 |
+
|
228 |
+
while True:
|
229 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
230 |
+
if bigram not in self.bpe_ranks:
|
231 |
+
break
|
232 |
+
first, second = bigram
|
233 |
+
new_word = []
|
234 |
+
i = 0
|
235 |
+
while i < len(word):
|
236 |
+
try:
|
237 |
+
j = word.index(first, i)
|
238 |
+
except ValueError:
|
239 |
+
new_word.extend(word[i:])
|
240 |
+
break
|
241 |
+
else:
|
242 |
+
new_word.extend(word[i:j])
|
243 |
+
i = j
|
244 |
+
|
245 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
246 |
+
new_word.append(first + second)
|
247 |
+
i += 2
|
248 |
+
else:
|
249 |
+
new_word.append(word[i])
|
250 |
+
i += 1
|
251 |
+
new_word = tuple(new_word)
|
252 |
+
word = new_word
|
253 |
+
if len(word) == 1:
|
254 |
+
break
|
255 |
+
else:
|
256 |
+
pairs = get_pairs(word)
|
257 |
+
word = " ".join(word)
|
258 |
+
self.cache[token] = word
|
259 |
+
return word
|
260 |
+
|
261 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._tokenize
|
262 |
+
def _tokenize(self, text):
|
263 |
+
"""Tokenize a string."""
|
264 |
+
bpe_tokens = []
|
265 |
+
for token in re.findall(self.pat, text):
|
266 |
+
token = "".join(
|
267 |
+
self.byte_encoder[b] for b in token.encode("utf-8")
|
268 |
+
) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
|
269 |
+
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
|
270 |
+
return bpe_tokens
|
271 |
+
|
272 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_token_to_id
|
273 |
+
def _convert_token_to_id(self, token):
|
274 |
+
"""Converts a token (str) in an id using the vocab."""
|
275 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
276 |
+
|
277 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_id_to_token
|
278 |
+
def _convert_id_to_token(self, index):
|
279 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
280 |
+
return self.decoder.get(index)
|
281 |
+
|
282 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.convert_tokens_to_string
|
283 |
+
def convert_tokens_to_string(self, tokens):
|
284 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
285 |
+
text = "".join(tokens)
|
286 |
+
text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
|
287 |
+
return text
|
288 |
+
|
289 |
+
def decode(
|
290 |
+
self,
|
291 |
+
token_ids,
|
292 |
+
skip_special_tokens: bool = False,
|
293 |
+
clean_up_tokenization_spaces: Optional[bool] = False,
|
294 |
+
spaces_between_special_tokens: bool = False,
|
295 |
+
**kwargs,
|
296 |
+
) -> str:
|
297 |
+
# `spaces_between_special_tokens` defaults to True for _decode in slow tokenizers
|
298 |
+
# and cannot be configured elsewhere, but it should default to False for Qwen2Tokenizer
|
299 |
+
return super().decode(
|
300 |
+
token_ids,
|
301 |
+
skip_special_tokens=skip_special_tokens,
|
302 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
303 |
+
spaces_between_special_tokens=spaces_between_special_tokens,
|
304 |
+
**kwargs,
|
305 |
+
)
|
306 |
+
|
307 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.save_vocabulary
|
308 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
309 |
+
if not os.path.isdir(save_directory):
|
310 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
311 |
+
return
|
312 |
+
vocab_file = os.path.join(
|
313 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
314 |
+
)
|
315 |
+
merge_file = os.path.join(
|
316 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
|
317 |
+
)
|
318 |
+
|
319 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
320 |
+
f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
|
321 |
+
|
322 |
+
index = 0
|
323 |
+
with open(merge_file, "w", encoding="utf-8") as writer:
|
324 |
+
writer.write("#version: 0.2\n")
|
325 |
+
for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
|
326 |
+
if index != token_index:
|
327 |
+
logger.warning(
|
328 |
+
f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
|
329 |
+
" Please check that the tokenizer is not corrupted!"
|
330 |
+
)
|
331 |
+
index = token_index
|
332 |
+
writer.write(" ".join(bpe_tokens) + "\n")
|
333 |
+
index += 1
|
334 |
+
|
335 |
+
return vocab_file, merge_file
|
336 |
+
|
337 |
+
def prepare_for_tokenization(self, text, **kwargs):
|
338 |
+
text = unicodedata.normalize("NFC", text)
|
339 |
+
return (text, kwargs)
|
venv/lib/python3.10/site-packages/transformers/models/qwen2/tokenization_qwen2_fast.py
ADDED
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 The Qwen team, Alibaba Group 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 classes for Qwen2."""
|
16 |
+
|
17 |
+
from typing import Optional, Tuple
|
18 |
+
|
19 |
+
from ...tokenization_utils import AddedToken
|
20 |
+
from ...tokenization_utils_fast import PreTrainedTokenizerFast
|
21 |
+
from ...utils import logging
|
22 |
+
from .tokenization_qwen2 import Qwen2Tokenizer
|
23 |
+
|
24 |
+
|
25 |
+
logger = logging.get_logger(__name__)
|
26 |
+
|
27 |
+
VOCAB_FILES_NAMES = {
|
28 |
+
"vocab_file": "vocab.json",
|
29 |
+
"merges_file": "merges.txt",
|
30 |
+
"tokenizer_file": "tokenizer.json",
|
31 |
+
}
|
32 |
+
|
33 |
+
|
34 |
+
MAX_MODEL_INPUT_SIZES = {"qwen/qwen-tokenizer": 32768}
|
35 |
+
|
36 |
+
|
37 |
+
class Qwen2TokenizerFast(PreTrainedTokenizerFast):
|
38 |
+
"""
|
39 |
+
Construct a "fast" Qwen2 tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
|
40 |
+
Byte-Pair-Encoding.
|
41 |
+
|
42 |
+
Same with GPT2Tokenizer, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
|
43 |
+
be encoded differently whether it is at the beginning of the sentence (without space) or not:
|
44 |
+
|
45 |
+
```python
|
46 |
+
>>> from transformers import Qwen2TokenizerFast
|
47 |
+
|
48 |
+
>>> tokenizer = Qwen2TokenizerFast.from_pretrained("Qwen/Qwen-tokenizer")
|
49 |
+
>>> tokenizer("Hello world")["input_ids"]
|
50 |
+
[9707, 1879]
|
51 |
+
|
52 |
+
>>> tokenizer(" Hello world")["input_ids"]
|
53 |
+
[21927, 1879]
|
54 |
+
```
|
55 |
+
This is expected.
|
56 |
+
|
57 |
+
This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
|
58 |
+
refer to this superclass for more information regarding those methods.
|
59 |
+
|
60 |
+
Args:
|
61 |
+
vocab_file (`str`, *optional*):
|
62 |
+
Path to the vocabulary file.
|
63 |
+
merges_file (`str`, *optional*):
|
64 |
+
Path to the merges file.
|
65 |
+
tokenizer_file (`str`, *optional*):
|
66 |
+
Path to [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that
|
67 |
+
contains everything needed to load the tokenizer.
|
68 |
+
unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
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. Not applicable to this tokenizer.
|
71 |
+
bos_token (`str`, *optional*):
|
72 |
+
The beginning of sequence token. Not applicable for this tokenizer.
|
73 |
+
eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
74 |
+
The end of sequence token.
|
75 |
+
pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
76 |
+
The token used for padding, for example when batching sequences of different lengths.
|
77 |
+
"""
|
78 |
+
|
79 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
80 |
+
model_input_names = ["input_ids", "attention_mask"]
|
81 |
+
slow_tokenizer_class = Qwen2Tokenizer
|
82 |
+
|
83 |
+
def __init__(
|
84 |
+
self,
|
85 |
+
vocab_file=None,
|
86 |
+
merges_file=None,
|
87 |
+
tokenizer_file=None,
|
88 |
+
unk_token="<|endoftext|>",
|
89 |
+
bos_token=None,
|
90 |
+
eos_token="<|endoftext|>",
|
91 |
+
pad_token="<|endoftext|>",
|
92 |
+
**kwargs,
|
93 |
+
):
|
94 |
+
# We need to at least pass vocab_file and merges_file to base class
|
95 |
+
# in case a slow tokenizer needs to be initialized; other can be
|
96 |
+
# configured through files.
|
97 |
+
# following GPT2TokenizerFast, also adding unk_token, bos_token, and eos_token
|
98 |
+
|
99 |
+
bos_token = (
|
100 |
+
AddedToken(bos_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
101 |
+
if isinstance(bos_token, str)
|
102 |
+
else bos_token
|
103 |
+
)
|
104 |
+
eos_token = (
|
105 |
+
AddedToken(eos_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
106 |
+
if isinstance(eos_token, str)
|
107 |
+
else eos_token
|
108 |
+
)
|
109 |
+
unk_token = (
|
110 |
+
AddedToken(unk_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
111 |
+
if isinstance(unk_token, str)
|
112 |
+
else unk_token
|
113 |
+
)
|
114 |
+
pad_token = (
|
115 |
+
AddedToken(pad_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
116 |
+
if isinstance(pad_token, str)
|
117 |
+
else pad_token
|
118 |
+
)
|
119 |
+
|
120 |
+
super().__init__(
|
121 |
+
vocab_file,
|
122 |
+
merges_file,
|
123 |
+
tokenizer_file=tokenizer_file,
|
124 |
+
unk_token=unk_token,
|
125 |
+
bos_token=bos_token,
|
126 |
+
eos_token=eos_token,
|
127 |
+
pad_token=pad_token,
|
128 |
+
**kwargs,
|
129 |
+
)
|
130 |
+
|
131 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2_fast.GPT2TokenizerFast.save_vocabulary
|
132 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
133 |
+
files = self._tokenizer.model.save(save_directory, name=filename_prefix)
|
134 |
+
return tuple(files)
|
venv/lib/python3.10/site-packages/transformers/models/rwkv/__init__.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 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 typing import TYPE_CHECKING
|
16 |
+
|
17 |
+
from ...utils import (
|
18 |
+
OptionalDependencyNotAvailable,
|
19 |
+
_LazyModule,
|
20 |
+
is_torch_available,
|
21 |
+
)
|
22 |
+
|
23 |
+
|
24 |
+
_import_structure = {
|
25 |
+
"configuration_rwkv": ["RWKV_PRETRAINED_CONFIG_ARCHIVE_MAP", "RwkvConfig", "RwkvOnnxConfig"],
|
26 |
+
}
|
27 |
+
|
28 |
+
try:
|
29 |
+
if not is_torch_available():
|
30 |
+
raise OptionalDependencyNotAvailable()
|
31 |
+
except OptionalDependencyNotAvailable:
|
32 |
+
pass
|
33 |
+
else:
|
34 |
+
_import_structure["modeling_rwkv"] = [
|
35 |
+
"RWKV_PRETRAINED_MODEL_ARCHIVE_LIST",
|
36 |
+
"RwkvForCausalLM",
|
37 |
+
"RwkvModel",
|
38 |
+
"RwkvPreTrainedModel",
|
39 |
+
]
|
40 |
+
|
41 |
+
|
42 |
+
if TYPE_CHECKING:
|
43 |
+
from .configuration_rwkv import RWKV_PRETRAINED_CONFIG_ARCHIVE_MAP, RwkvConfig, RwkvOnnxConfig
|
44 |
+
|
45 |
+
try:
|
46 |
+
if not is_torch_available():
|
47 |
+
raise OptionalDependencyNotAvailable()
|
48 |
+
except OptionalDependencyNotAvailable:
|
49 |
+
pass
|
50 |
+
else:
|
51 |
+
from .modeling_rwkv import (
|
52 |
+
RWKV_PRETRAINED_MODEL_ARCHIVE_LIST,
|
53 |
+
RwkvForCausalLM,
|
54 |
+
RwkvModel,
|
55 |
+
RwkvPreTrainedModel,
|
56 |
+
)
|
57 |
+
else:
|
58 |
+
import sys
|
59 |
+
|
60 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|