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/15.mlp.dense_4h_to_h.weight/fp32.pt +3 -0
- ckpts/universal/global_step20/zero/23.attention.query_key_value.weight/exp_avg.pt +3 -0
- lm-evaluation-harness/tests/testdata/arithmetic_1dc-v0-res.json +1 -0
- lm-evaluation-harness/tests/testdata/blimp_determiner_noun_agreement_irregular_2-v0-loglikelihood +1 -0
- lm-evaluation-harness/tests/testdata/blimp_distractor_agreement_relative_clause-v0-res.json +1 -0
- lm-evaluation-harness/tests/testdata/blimp_drop_argument-v0-res.json +1 -0
- lm-evaluation-harness/tests/testdata/blimp_existential_there_quantifiers_2-v0-res.json +1 -0
- lm-evaluation-harness/tests/testdata/blimp_principle_A_reconstruction-v0-res.json +1 -0
- lm-evaluation-harness/tests/testdata/blimp_superlative_quantifiers_1-v0-res.json +1 -0
- lm-evaluation-harness/tests/testdata/crows_pairs_french_autre-v0-loglikelihood +1 -0
- lm-evaluation-harness/tests/testdata/crows_pairs_french_nationality-v0-res.json +1 -0
- lm-evaluation-harness/tests/testdata/ethics_utilitarianism-v0-loglikelihood +1 -0
- lm-evaluation-harness/tests/testdata/headqa-v0-loglikelihood +1 -0
- lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_european_history-v0-res.json +1 -0
- lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_microeconomics-v0-res.json +1 -0
- lm-evaluation-harness/tests/testdata/hendrycksTest-machine_learning-v0-loglikelihood +1 -0
- lm-evaluation-harness/tests/testdata/hendrycksTest-professional_accounting-v0-loglikelihood +1 -0
- lm-evaluation-harness/tests/testdata/lambada_openai_mt_de-v0-loglikelihood +1 -0
- lm-evaluation-harness/tests/testdata/lambada_openai_mt_de-v0-res.json +1 -0
- lm-evaluation-harness/tests/testdata/mnli-v0-res.json +1 -0
- lm-evaluation-harness/tests/testdata/multirc-v0-res.json +1 -0
- lm-evaluation-harness/tests/testdata/pile_arxiv-v0-res.json +1 -0
- lm-evaluation-harness/tests/testdata/pile_gutenberg-v0-loglikelihood_rolling +1 -0
- lm-evaluation-harness/tests/testdata/pile_nih-exporter-v1-loglikelihood_rolling +1 -0
- lm-evaluation-harness/tests/testdata/pile_openwebtext2-v1-res.json +1 -0
- lm-evaluation-harness/tests/testdata/rte-v0-res.json +1 -0
- lm-evaluation-harness/tests/testdata/squad2-v0-greedy_until +1 -0
- lm-evaluation-harness/tests/testdata/wmt14-fr-en-v0-res.json +1 -0
- lm-evaluation-harness/tests/testdata/wmt16-ro-en-v0-greedy_until +1 -0
- lm-evaluation-harness/tests/testdata/wmt20-en-cs-v0-greedy_until +1 -0
- venv/lib/python3.10/site-packages/transformers/models/chinese_clip/__init__.py +88 -0
- venv/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/configuration_chinese_clip.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/convert_chinese_clip_original_pytorch_to_hf.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/feature_extraction_chinese_clip.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/image_processing_chinese_clip.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/modeling_chinese_clip.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/processing_chinese_clip.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/chinese_clip/configuration_chinese_clip.py +468 -0
- venv/lib/python3.10/site-packages/transformers/models/chinese_clip/convert_chinese_clip_original_pytorch_to_hf.py +134 -0
- venv/lib/python3.10/site-packages/transformers/models/chinese_clip/feature_extraction_chinese_clip.py +33 -0
- venv/lib/python3.10/site-packages/transformers/models/chinese_clip/image_processing_chinese_clip.py +331 -0
- venv/lib/python3.10/site-packages/transformers/models/chinese_clip/modeling_chinese_clip.py +1562 -0
- venv/lib/python3.10/site-packages/transformers/models/chinese_clip/processing_chinese_clip.py +141 -0
- venv/lib/python3.10/site-packages/transformers/models/glpn/__pycache__/feature_extraction_glpn.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/regnet/__init__.py +111 -0
- venv/lib/python3.10/site-packages/transformers/models/regnet/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/regnet/__pycache__/configuration_regnet.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/regnet/__pycache__/convert_regnet_seer_10b_to_pytorch.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/transformers/models/regnet/__pycache__/convert_regnet_to_pytorch.cpython-310.pyc +0 -0
ckpts/universal/global_step20/zero/15.mlp.dense_4h_to_h.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e34dde773c9a78fd0f839b9560dab3b6957ca7ed78513e86d75d8a5bb7cb63a9
|
3 |
+
size 33555533
|
ckpts/universal/global_step20/zero/23.attention.query_key_value.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:949e9a6e5d9bf691cc6df3e867ec014eca39783a3c03eafa619cbe639962e2bc
|
3 |
+
size 50332828
|
lm-evaluation-harness/tests/testdata/arithmetic_1dc-v0-res.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"results": {"arithmetic_1dc": {"acc": 0.0, "acc_stderr": 0.0}}, "versions": {"arithmetic_1dc": 0}}
|
lm-evaluation-harness/tests/testdata/blimp_determiner_noun_agreement_irregular_2-v0-loglikelihood
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
ddb24ddfaebe076b3aa7107937d71bf5f4503a78283bc889e39200368603681e
|
lm-evaluation-harness/tests/testdata/blimp_distractor_agreement_relative_clause-v0-res.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"results": {"blimp_distractor_agreement_relative_clause": {"acc": 0.485, "acc_stderr": 0.0158121796418149}}, "versions": {"blimp_distractor_agreement_relative_clause": 0}}
|
lm-evaluation-harness/tests/testdata/blimp_drop_argument-v0-res.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"results": {"blimp_drop_argument": {"acc": 0.485, "acc_stderr": 0.0158121796418149}}, "versions": {"blimp_drop_argument": 0}}
|
lm-evaluation-harness/tests/testdata/blimp_existential_there_quantifiers_2-v0-res.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"results": {"blimp_existential_there_quantifiers_2": {"acc": 0.485, "acc_stderr": 0.0158121796418149}}, "versions": {"blimp_existential_there_quantifiers_2": 0}}
|
lm-evaluation-harness/tests/testdata/blimp_principle_A_reconstruction-v0-res.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"results": {"blimp_principle_A_reconstruction": {"acc": 0.485, "acc_stderr": 0.0158121796418149}}, "versions": {"blimp_principle_A_reconstruction": 0}}
|
lm-evaluation-harness/tests/testdata/blimp_superlative_quantifiers_1-v0-res.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"results": {"blimp_superlative_quantifiers_1": {"acc": 0.485, "acc_stderr": 0.0158121796418149}}, "versions": {"blimp_superlative_quantifiers_1": 0}}
|
lm-evaluation-harness/tests/testdata/crows_pairs_french_autre-v0-loglikelihood
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
f145ad5086da0bf8c76f0730258529fa243efe32b7ab792d3c4716284b4b5495
|
lm-evaluation-harness/tests/testdata/crows_pairs_french_nationality-v0-res.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"results": {"crows_pairs_french_nationality": {"likelihood_difference": 0.33534193269044926, "likelihood_difference_stderr": 0.01429836309463257, "pct_stereotype": 0.4743083003952569, "pct_stereotype_stderr": 0.031455431847992904}}, "versions": {"crows_pairs_french_nationality": 0}}
|
lm-evaluation-harness/tests/testdata/ethics_utilitarianism-v0-loglikelihood
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
88872f1ed1b203f9649a4ced4fb4627d18c17af455d713de6e17c05eced4ec60
|
lm-evaluation-harness/tests/testdata/headqa-v0-loglikelihood
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
767ca34d9714edd9fb030ddbcc35a64e5180d1e247b0cb557fbb22fdf971ad1f
|
lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_european_history-v0-res.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"results": {"hendrycksTest-high_school_european_history": {"acc": 0.23636363636363636, "acc_norm": 0.24242424242424243, "acc_norm_stderr": 0.03346409881055953, "acc_stderr": 0.033175059300091805}}, "versions": {"hendrycksTest-high_school_european_history": 0}}
|
lm-evaluation-harness/tests/testdata/hendrycksTest-high_school_microeconomics-v0-res.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"results": {"hendrycksTest-high_school_microeconomics": {"acc": 0.24369747899159663, "acc_norm": 0.22268907563025211, "acc_norm_stderr": 0.027025433498882378, "acc_stderr": 0.027886828078380558}}, "versions": {"hendrycksTest-high_school_microeconomics": 0}}
|
lm-evaluation-harness/tests/testdata/hendrycksTest-machine_learning-v0-loglikelihood
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
7a7138821a66ef946e427b40344cf7f1a916a2926995a85ef731a3bee40cb7ce
|
lm-evaluation-harness/tests/testdata/hendrycksTest-professional_accounting-v0-loglikelihood
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
847418f7b22cd9b499e95fd73c40a2fbc40076895280cc2c560199c0c4c4f433
|
lm-evaluation-harness/tests/testdata/lambada_openai_mt_de-v0-loglikelihood
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
5ad125e1708499832b2cee8c3388f89f9c0277010fd96fbd3359039ce8105984
|
lm-evaluation-harness/tests/testdata/lambada_openai_mt_de-v0-res.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"results": {"lambada_openai_mt_de": {"acc": 0.0, "acc_stderr": 0.0, "ppl": 1.6479047769869253, "ppl_stderr": 0.006497321146240192}}, "versions": {"lambada_openai_mt_de": 0}}
|
lm-evaluation-harness/tests/testdata/mnli-v0-res.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"results": {"mnli": {"acc": 0.32868059093224655, "acc_stderr": 0.004741640290753859}}, "versions": {"mnli": 0}}
|
lm-evaluation-harness/tests/testdata/multirc-v0-res.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"results": {"multirc": {"acc": 0.07450157397691501, "acc_stderr": 0.008510441526175931}}, "versions": {"multirc": 0}}
|
lm-evaluation-harness/tests/testdata/pile_arxiv-v0-res.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"results": {"pile_arxiv": {"bits_per_byte": 1.0750412350569374e-05, "byte_perplexity": 1.0000107504701365, "word_perplexity": 1.0000819333090385}}, "versions": {"pile_arxiv": 0}}
|
lm-evaluation-harness/tests/testdata/pile_gutenberg-v0-loglikelihood_rolling
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
02a559f74a9105145e7d4d9c5ddea372b5b4938f5368dc8ffafc39cbe3b4c7ef
|
lm-evaluation-harness/tests/testdata/pile_nih-exporter-v1-loglikelihood_rolling
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
520ea6e04e8a39dc0b5f63a837429a78a40e63d39d109096101feb8c5b2cf8d8
|
lm-evaluation-harness/tests/testdata/pile_openwebtext2-v1-res.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"results": {"pile_openwebtext2": {"bits_per_byte": 0.000184802319359215, "byte_perplexity": 1.000128103411166, "word_perplexity": 1.0007951516532847}}, "versions": {"pile_openwebtext2": 1}}
|
lm-evaluation-harness/tests/testdata/rte-v0-res.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"results": {"rte": {"acc": 0.5379061371841155, "acc_stderr": 0.030009848912529117}}, "versions": {"rte": 0}}
|
lm-evaluation-harness/tests/testdata/squad2-v0-greedy_until
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
b261e8885c11750ce6911bb11e8693de03d53758297c26fb14cfc1ef508862cb
|
lm-evaluation-harness/tests/testdata/wmt14-fr-en-v0-res.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"results": {"wmt14-fr-en": {"bleu": 0.0, "bleu_stderr": 0.0, "chrf": 0.01275083169440515, "chrf_stderr": 8.45474998563806e-05, "ter": 1.0, "ter_stderr": 0.0}}, "versions": {"wmt14-fr-en": 0}}
|
lm-evaluation-harness/tests/testdata/wmt16-ro-en-v0-greedy_until
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
d1b7c50751b0d5d7470b7f49f2bab9d09792c91460fc92cc34f06617013d7c65
|
lm-evaluation-harness/tests/testdata/wmt20-en-cs-v0-greedy_until
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
5a34e6863bf6965afd31653de50bac5fecf58db65dbaba46921504a2b7463786
|
venv/lib/python3.10/site-packages/transformers/models/chinese_clip/__init__.py
ADDED
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2022 The OFA-Sys Team Authors and 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 OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
|
17 |
+
|
18 |
+
|
19 |
+
_import_structure = {
|
20 |
+
"configuration_chinese_clip": [
|
21 |
+
"CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP",
|
22 |
+
"ChineseCLIPConfig",
|
23 |
+
"ChineseCLIPOnnxConfig",
|
24 |
+
"ChineseCLIPTextConfig",
|
25 |
+
"ChineseCLIPVisionConfig",
|
26 |
+
],
|
27 |
+
"processing_chinese_clip": ["ChineseCLIPProcessor"],
|
28 |
+
}
|
29 |
+
|
30 |
+
try:
|
31 |
+
if not is_vision_available():
|
32 |
+
raise OptionalDependencyNotAvailable()
|
33 |
+
except OptionalDependencyNotAvailable:
|
34 |
+
pass
|
35 |
+
else:
|
36 |
+
_import_structure["feature_extraction_chinese_clip"] = ["ChineseCLIPFeatureExtractor"]
|
37 |
+
_import_structure["image_processing_chinese_clip"] = ["ChineseCLIPImageProcessor"]
|
38 |
+
|
39 |
+
try:
|
40 |
+
if not is_torch_available():
|
41 |
+
raise OptionalDependencyNotAvailable()
|
42 |
+
except OptionalDependencyNotAvailable:
|
43 |
+
pass
|
44 |
+
else:
|
45 |
+
_import_structure["modeling_chinese_clip"] = [
|
46 |
+
"CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST",
|
47 |
+
"ChineseCLIPModel",
|
48 |
+
"ChineseCLIPPreTrainedModel",
|
49 |
+
"ChineseCLIPTextModel",
|
50 |
+
"ChineseCLIPVisionModel",
|
51 |
+
]
|
52 |
+
|
53 |
+
if TYPE_CHECKING:
|
54 |
+
from .configuration_chinese_clip import (
|
55 |
+
CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
|
56 |
+
ChineseCLIPConfig,
|
57 |
+
ChineseCLIPOnnxConfig,
|
58 |
+
ChineseCLIPTextConfig,
|
59 |
+
ChineseCLIPVisionConfig,
|
60 |
+
)
|
61 |
+
from .processing_chinese_clip import ChineseCLIPProcessor
|
62 |
+
|
63 |
+
try:
|
64 |
+
if not is_vision_available():
|
65 |
+
raise OptionalDependencyNotAvailable()
|
66 |
+
except OptionalDependencyNotAvailable:
|
67 |
+
pass
|
68 |
+
else:
|
69 |
+
from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor
|
70 |
+
|
71 |
+
try:
|
72 |
+
if not is_torch_available():
|
73 |
+
raise OptionalDependencyNotAvailable()
|
74 |
+
except OptionalDependencyNotAvailable:
|
75 |
+
pass
|
76 |
+
else:
|
77 |
+
from .modeling_chinese_clip import (
|
78 |
+
CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
|
79 |
+
ChineseCLIPModel,
|
80 |
+
ChineseCLIPPreTrainedModel,
|
81 |
+
ChineseCLIPTextModel,
|
82 |
+
ChineseCLIPVisionModel,
|
83 |
+
)
|
84 |
+
|
85 |
+
else:
|
86 |
+
import sys
|
87 |
+
|
88 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
venv/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.48 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/configuration_chinese_clip.cpython-310.pyc
ADDED
Binary file (17.8 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/convert_chinese_clip_original_pytorch_to_hf.cpython-310.pyc
ADDED
Binary file (4.05 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/feature_extraction_chinese_clip.cpython-310.pyc
ADDED
Binary file (1.06 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/image_processing_chinese_clip.cpython-310.pyc
ADDED
Binary file (13.2 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/modeling_chinese_clip.cpython-310.pyc
ADDED
Binary file (48.5 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/processing_chinese_clip.cpython-310.pyc
ADDED
Binary file (6.02 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/chinese_clip/configuration_chinese_clip.py
ADDED
@@ -0,0 +1,468 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 The OFA-Sys Team Authors and The HuggingFace 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 |
+
""" Chinese-CLIP model configuration"""
|
16 |
+
|
17 |
+
import os
|
18 |
+
from collections import OrderedDict
|
19 |
+
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union
|
20 |
+
|
21 |
+
|
22 |
+
if TYPE_CHECKING:
|
23 |
+
from ...processing_utils import ProcessorMixin
|
24 |
+
from ...utils import TensorType
|
25 |
+
|
26 |
+
from ...configuration_utils import PretrainedConfig
|
27 |
+
from ...onnx import OnnxConfig
|
28 |
+
from ...utils import logging
|
29 |
+
|
30 |
+
|
31 |
+
logger = logging.get_logger(__name__)
|
32 |
+
|
33 |
+
|
34 |
+
from ..deprecated._archive_maps import CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP # noqa: F401, E402
|
35 |
+
|
36 |
+
|
37 |
+
class ChineseCLIPTextConfig(PretrainedConfig):
|
38 |
+
r"""
|
39 |
+
This is the configuration class to store the configuration of a [`ChineseCLIPModel`]. It is used to instantiate a
|
40 |
+
Chinese CLIP model according to the specified arguments, defining the model architecture. Instantiating a
|
41 |
+
configuration with the defaults will yield a similar configuration to that of the Chinese CLIP
|
42 |
+
[OFA-Sys/chinese-clip-vit-base-patch16](https:
|
43 |
+
//huggingface.co/OFA-Sys/chinese-clip-vit-base-patch16) architecture.
|
44 |
+
|
45 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
46 |
+
documentation from [`PretrainedConfig`] for more information.
|
47 |
+
|
48 |
+
|
49 |
+
Args:
|
50 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
51 |
+
Vocabulary size of the CHINESE_CLIP model. Defines the number of different tokens that can be represented
|
52 |
+
by the `inputs_ids` passed when calling [`ChineseCLIPModel`].
|
53 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
54 |
+
Dimensionality of the encoder layers and the pooler layer.
|
55 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
56 |
+
Number of hidden layers in the Transformer encoder.
|
57 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
58 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
59 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
60 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
61 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
|
62 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
63 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
64 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
65 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
66 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
67 |
+
The dropout ratio for the attention probabilities.
|
68 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
69 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
70 |
+
just in case (e.g., 512 or 1024 or 2048).
|
71 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
72 |
+
The vocabulary size of the `token_type_ids` passed when calling [`ChineseCLIPModel`].
|
73 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
74 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
75 |
+
initializer_factor (`float`, *optional*, defaults to 1.0):
|
76 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
77 |
+
testing).
|
78 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
79 |
+
The epsilon used by the layer normalization layers.
|
80 |
+
pad_token_id (`int`, *optional*, defaults to 0):
|
81 |
+
Padding token id.
|
82 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
83 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
84 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
85 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
86 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
87 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
88 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
89 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
90 |
+
relevant if `config.is_decoder=True`.
|
91 |
+
|
92 |
+
Example:
|
93 |
+
|
94 |
+
```python
|
95 |
+
>>> from transformers import ChineseCLIPTextConfig, ChineseCLIPTextModel
|
96 |
+
|
97 |
+
>>> # Initializing a ChineseCLIPTextConfig with OFA-Sys/chinese-clip-vit-base-patch16 style configuration
|
98 |
+
>>> configuration = ChineseCLIPTextConfig()
|
99 |
+
|
100 |
+
>>> # Initializing a ChineseCLIPTextModel (with random weights) from the OFA-Sys/chinese-clip-vit-base-patch16 style configuration
|
101 |
+
>>> model = ChineseCLIPTextModel(configuration)
|
102 |
+
|
103 |
+
>>> # Accessing the model configuration
|
104 |
+
>>> configuration = model.config
|
105 |
+
```"""
|
106 |
+
|
107 |
+
model_type = "chinese_clip_text_model"
|
108 |
+
|
109 |
+
def __init__(
|
110 |
+
self,
|
111 |
+
vocab_size=30522,
|
112 |
+
hidden_size=768,
|
113 |
+
num_hidden_layers=12,
|
114 |
+
num_attention_heads=12,
|
115 |
+
intermediate_size=3072,
|
116 |
+
hidden_act="gelu",
|
117 |
+
hidden_dropout_prob=0.1,
|
118 |
+
attention_probs_dropout_prob=0.1,
|
119 |
+
max_position_embeddings=512,
|
120 |
+
type_vocab_size=2,
|
121 |
+
initializer_range=0.02,
|
122 |
+
initializer_factor=1.0,
|
123 |
+
layer_norm_eps=1e-12,
|
124 |
+
pad_token_id=0,
|
125 |
+
position_embedding_type="absolute",
|
126 |
+
use_cache=True,
|
127 |
+
**kwargs,
|
128 |
+
):
|
129 |
+
super().__init__(pad_token_id=pad_token_id, **kwargs)
|
130 |
+
|
131 |
+
self.vocab_size = vocab_size
|
132 |
+
self.hidden_size = hidden_size
|
133 |
+
self.num_hidden_layers = num_hidden_layers
|
134 |
+
self.num_attention_heads = num_attention_heads
|
135 |
+
self.hidden_act = hidden_act
|
136 |
+
self.intermediate_size = intermediate_size
|
137 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
138 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
139 |
+
self.max_position_embeddings = max_position_embeddings
|
140 |
+
self.type_vocab_size = type_vocab_size
|
141 |
+
self.initializer_range = initializer_range
|
142 |
+
self.initializer_factor = initializer_factor
|
143 |
+
self.layer_norm_eps = layer_norm_eps
|
144 |
+
self.position_embedding_type = position_embedding_type
|
145 |
+
self.use_cache = use_cache
|
146 |
+
|
147 |
+
@classmethod
|
148 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
149 |
+
cls._set_token_in_kwargs(kwargs)
|
150 |
+
|
151 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
152 |
+
|
153 |
+
# get the vision config dict if we are loading from ChineseCLIPConfig
|
154 |
+
if config_dict.get("model_type") == "chinese_clip":
|
155 |
+
config_dict = config_dict["text_config"]
|
156 |
+
|
157 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
158 |
+
logger.warning(
|
159 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
160 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
161 |
+
)
|
162 |
+
|
163 |
+
return cls.from_dict(config_dict, **kwargs)
|
164 |
+
|
165 |
+
|
166 |
+
class ChineseCLIPVisionConfig(PretrainedConfig):
|
167 |
+
r"""
|
168 |
+
This is the configuration class to store the configuration of a [`ChineseCLIPModel`]. It is used to instantiate an
|
169 |
+
ChineseCLIP model according to the specified arguments, defining the model architecture. Instantiating a
|
170 |
+
configuration with the defaults will yield a similar configuration to that of the ChineseCLIP
|
171 |
+
[OFA-Sys/chinese-clip-vit-base-patch16](https://huggingface.co/OFA-Sys/chinese-clip-vit-base-patch16) architecture.
|
172 |
+
|
173 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
174 |
+
documentation from [`PretrainedConfig`] for more information.
|
175 |
+
|
176 |
+
|
177 |
+
Args:
|
178 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
179 |
+
Dimensionality of the encoder layers and the pooler layer.
|
180 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
181 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
182 |
+
projection_dim (`int`, *optional*, defaults to 512):
|
183 |
+
Dimentionality of text and vision projection layers.
|
184 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
185 |
+
Number of hidden layers in the Transformer encoder.
|
186 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
187 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
188 |
+
num_channels (`int`, *optional*, defaults to 3):
|
189 |
+
The number of input channels.
|
190 |
+
image_size (`int`, *optional*, defaults to 224):
|
191 |
+
The size (resolution) of each image.
|
192 |
+
patch_size (`int`, *optional*, defaults to 32):
|
193 |
+
The size (resolution) of each patch.
|
194 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
|
195 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
196 |
+
`"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
|
197 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
|
198 |
+
The epsilon used by the layer normalization layers.
|
199 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
200 |
+
The dropout ratio for the attention probabilities.
|
201 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
202 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
203 |
+
initializer_factor (`float`, *optional*, defaults to 1.0):
|
204 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
205 |
+
testing).
|
206 |
+
Example:
|
207 |
+
```python
|
208 |
+
>>> from transformers import ChineseCLIPVisionConfig, ChineseCLIPVisionModel
|
209 |
+
|
210 |
+
>>> # Initializing a ChineseCLIPVisionConfig with OFA-Sys/chinese-clip-vit-base-patch16 style configuration
|
211 |
+
>>> configuration = ChineseCLIPVisionConfig()
|
212 |
+
|
213 |
+
>>> # Initializing a ChineseCLIPVisionModel (with random weights) from the OFA-Sys/chinese-clip-vit-base-patch16 style configuration
|
214 |
+
>>> model = ChineseCLIPVisionModel(configuration)
|
215 |
+
|
216 |
+
>>> # Accessing the model configuration
|
217 |
+
>>> configuration = model.config
|
218 |
+
```"""
|
219 |
+
|
220 |
+
model_type = "chinese_clip_vision_model"
|
221 |
+
|
222 |
+
def __init__(
|
223 |
+
self,
|
224 |
+
hidden_size=768,
|
225 |
+
intermediate_size=3072,
|
226 |
+
projection_dim=512,
|
227 |
+
num_hidden_layers=12,
|
228 |
+
num_attention_heads=12,
|
229 |
+
num_channels=3,
|
230 |
+
image_size=224,
|
231 |
+
patch_size=32,
|
232 |
+
hidden_act="quick_gelu",
|
233 |
+
layer_norm_eps=1e-5,
|
234 |
+
attention_dropout=0.0,
|
235 |
+
initializer_range=0.02,
|
236 |
+
initializer_factor=1.0,
|
237 |
+
**kwargs,
|
238 |
+
):
|
239 |
+
super().__init__(**kwargs)
|
240 |
+
|
241 |
+
self.hidden_size = hidden_size
|
242 |
+
self.intermediate_size = intermediate_size
|
243 |
+
self.projection_dim = projection_dim
|
244 |
+
self.num_hidden_layers = num_hidden_layers
|
245 |
+
self.num_attention_heads = num_attention_heads
|
246 |
+
self.num_channels = num_channels
|
247 |
+
self.patch_size = patch_size
|
248 |
+
self.image_size = image_size
|
249 |
+
self.initializer_range = initializer_range
|
250 |
+
self.initializer_factor = initializer_factor
|
251 |
+
self.attention_dropout = attention_dropout
|
252 |
+
self.layer_norm_eps = layer_norm_eps
|
253 |
+
self.hidden_act = hidden_act
|
254 |
+
|
255 |
+
@classmethod
|
256 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
257 |
+
cls._set_token_in_kwargs(kwargs)
|
258 |
+
|
259 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
260 |
+
|
261 |
+
# get the vision config dict if we are loading from ChineseCLIPConfig
|
262 |
+
if config_dict.get("model_type") == "chinese_clip":
|
263 |
+
config_dict = config_dict["vision_config"]
|
264 |
+
|
265 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
266 |
+
logger.warning(
|
267 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
268 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
269 |
+
)
|
270 |
+
|
271 |
+
return cls.from_dict(config_dict, **kwargs)
|
272 |
+
|
273 |
+
|
274 |
+
class ChineseCLIPConfig(PretrainedConfig):
|
275 |
+
r"""
|
276 |
+
[`ChineseCLIPConfig`] is the configuration class to store the configuration of a [`ChineseCLIPModel`]. It is used
|
277 |
+
to instantiate Chinese-CLIP model according to the specified arguments, defining the text model and vision model
|
278 |
+
configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the
|
279 |
+
Chinese-CLIP [OFA-Sys/chinese-clip-vit-base-patch16](https://huggingface.co/OFA-Sys/chinese-clip-vit-base-patch16)
|
280 |
+
architecture.
|
281 |
+
|
282 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
283 |
+
documentation from [`PretrainedConfig`] for more information.
|
284 |
+
|
285 |
+
Args:
|
286 |
+
text_config (`dict`, *optional*):
|
287 |
+
Dictionary of configuration options used to initialize [`ChineseCLIPTextConfig`].
|
288 |
+
vision_config (`dict`, *optional*):
|
289 |
+
Dictionary of configuration options used to initialize [`ChineseCLIPVisionConfig`].
|
290 |
+
projection_dim (`int`, *optional*, defaults to 512):
|
291 |
+
Dimentionality of text and vision projection layers.
|
292 |
+
logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
|
293 |
+
The inital value of the *logit_scale* paramter. Default is used as per the original ChineseCLIP
|
294 |
+
implementation.
|
295 |
+
kwargs (*optional*):
|
296 |
+
Dictionary of keyword arguments.
|
297 |
+
|
298 |
+
Example:
|
299 |
+
|
300 |
+
```python
|
301 |
+
>>> from transformers import ChineseCLIPConfig, ChineseCLIPModel
|
302 |
+
|
303 |
+
>>> # Initializing a ChineseCLIPConfig with OFA-Sys/chinese-clip-vit-base-patch16 style configuration
|
304 |
+
>>> configuration = ChineseCLIPConfig()
|
305 |
+
|
306 |
+
>>> # Initializing a ChineseCLIPModel (with random weights) from the OFA-Sys/chinese-clip-vit-base-patch16 style configuration
|
307 |
+
>>> model = ChineseCLIPModel(configuration)
|
308 |
+
|
309 |
+
>>> # Accessing the model configuration
|
310 |
+
>>> configuration = model.config
|
311 |
+
|
312 |
+
>>> # We can also initialize a ChineseCLIPConfig from a ChineseCLIPTextConfig and a ChineseCLIPVisionConfig
|
313 |
+
|
314 |
+
>>> # Initializing a ChineseCLIPTextConfig and ChineseCLIPVisionConfig configuration
|
315 |
+
>>> config_text = ChineseCLIPTextConfig()
|
316 |
+
>>> config_vision = ChineseCLIPVisionConfig()
|
317 |
+
|
318 |
+
>>> config = ChineseCLIPConfig.from_text_vision_configs(config_text, config_vision)
|
319 |
+
```"""
|
320 |
+
|
321 |
+
model_type = "chinese_clip"
|
322 |
+
|
323 |
+
def __init__(
|
324 |
+
self, text_config=None, vision_config=None, projection_dim=512, logit_scale_init_value=2.6592, **kwargs
|
325 |
+
):
|
326 |
+
# If `_config_dict` exist, we use them for the backward compatibility.
|
327 |
+
# We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
|
328 |
+
# of confusion!).
|
329 |
+
text_config_dict = kwargs.pop("text_config_dict", None)
|
330 |
+
vision_config_dict = kwargs.pop("vision_config_dict", None)
|
331 |
+
|
332 |
+
super().__init__(**kwargs)
|
333 |
+
|
334 |
+
# Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
|
335 |
+
# `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
|
336 |
+
# cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
|
337 |
+
if text_config_dict is not None:
|
338 |
+
if text_config is None:
|
339 |
+
text_config = {}
|
340 |
+
|
341 |
+
# This is the complete result when using `text_config_dict`.
|
342 |
+
_text_config_dict = ChineseCLIPTextConfig(**text_config_dict).to_dict()
|
343 |
+
|
344 |
+
# Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
|
345 |
+
for key, value in _text_config_dict.items():
|
346 |
+
if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
|
347 |
+
# If specified in `text_config_dict`
|
348 |
+
if key in text_config_dict:
|
349 |
+
message = (
|
350 |
+
f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
|
351 |
+
f'The value `text_config_dict["{key}"]` will be used instead.'
|
352 |
+
)
|
353 |
+
# If inferred from default argument values (just to be super careful)
|
354 |
+
else:
|
355 |
+
message = (
|
356 |
+
f"`text_config_dict` is provided which will be used to initialize `ChineseCLIPTextConfig`. "
|
357 |
+
f'The value `text_config["{key}"]` will be overriden.'
|
358 |
+
)
|
359 |
+
logger.info(message)
|
360 |
+
|
361 |
+
# Update all values in `text_config` with the ones in `_text_config_dict`.
|
362 |
+
text_config.update(_text_config_dict)
|
363 |
+
|
364 |
+
if vision_config_dict is not None:
|
365 |
+
if vision_config is None:
|
366 |
+
vision_config = {}
|
367 |
+
|
368 |
+
# This is the complete result when using `vision_config_dict`.
|
369 |
+
_vision_config_dict = ChineseCLIPVisionConfig(**vision_config_dict).to_dict()
|
370 |
+
# convert keys to string instead of integer
|
371 |
+
if "id2label" in _vision_config_dict:
|
372 |
+
_vision_config_dict["id2label"] = {
|
373 |
+
str(key): value for key, value in _vision_config_dict["id2label"].items()
|
374 |
+
}
|
375 |
+
|
376 |
+
# Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
|
377 |
+
for key, value in _vision_config_dict.items():
|
378 |
+
if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
|
379 |
+
# If specified in `vision_config_dict`
|
380 |
+
if key in vision_config_dict:
|
381 |
+
message = (
|
382 |
+
f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
|
383 |
+
f'values. The value `vision_config_dict["{key}"]` will be used instead.'
|
384 |
+
)
|
385 |
+
# If inferred from default argument values (just to be super careful)
|
386 |
+
else:
|
387 |
+
message = (
|
388 |
+
f"`vision_config_dict` is provided which will be used to initialize "
|
389 |
+
f'`ChineseCLIPVisionConfig`. The value `vision_config["{key}"]` will be overriden.'
|
390 |
+
)
|
391 |
+
logger.info(message)
|
392 |
+
|
393 |
+
# Update all values in `vision_config` with the ones in `_vision_config_dict`.
|
394 |
+
vision_config.update(_vision_config_dict)
|
395 |
+
|
396 |
+
if text_config is None:
|
397 |
+
text_config = {}
|
398 |
+
logger.info("`text_config` is `None`. Initializing the `ChineseCLIPTextConfig` with default values.")
|
399 |
+
|
400 |
+
if vision_config is None:
|
401 |
+
vision_config = {}
|
402 |
+
logger.info("`vision_config` is `None`. initializing the `ChineseCLIPVisionConfig` with default values.")
|
403 |
+
|
404 |
+
self.text_config = ChineseCLIPTextConfig(**text_config)
|
405 |
+
self.vision_config = ChineseCLIPVisionConfig(**vision_config)
|
406 |
+
|
407 |
+
self.projection_dim = projection_dim
|
408 |
+
self.logit_scale_init_value = logit_scale_init_value
|
409 |
+
self.initializer_factor = 1.0
|
410 |
+
self.initializer_range = 0.02
|
411 |
+
|
412 |
+
@classmethod
|
413 |
+
def from_text_vision_configs(
|
414 |
+
cls, text_config: ChineseCLIPTextConfig, vision_config: ChineseCLIPVisionConfig, **kwargs
|
415 |
+
):
|
416 |
+
r"""
|
417 |
+
Instantiate a [`ChineseCLIPConfig`] (or a derived class) from Chinese-CLIP text model configuration and
|
418 |
+
Chinese-CLIP vision model configuration. Returns:
|
419 |
+
[`ChineseCLIPConfig`]: An instance of a configuration object
|
420 |
+
"""
|
421 |
+
|
422 |
+
return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
|
423 |
+
|
424 |
+
|
425 |
+
class ChineseCLIPOnnxConfig(OnnxConfig):
|
426 |
+
@property
|
427 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
428 |
+
return OrderedDict(
|
429 |
+
[
|
430 |
+
("input_ids", {0: "batch", 1: "sequence"}),
|
431 |
+
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
|
432 |
+
("attention_mask", {0: "batch", 1: "sequence"}),
|
433 |
+
]
|
434 |
+
)
|
435 |
+
|
436 |
+
@property
|
437 |
+
def outputs(self) -> Mapping[str, Mapping[int, str]]:
|
438 |
+
return OrderedDict(
|
439 |
+
[
|
440 |
+
("logits_per_image", {0: "batch"}),
|
441 |
+
("logits_per_text", {0: "batch"}),
|
442 |
+
("text_embeds", {0: "batch"}),
|
443 |
+
("image_embeds", {0: "batch"}),
|
444 |
+
]
|
445 |
+
)
|
446 |
+
|
447 |
+
@property
|
448 |
+
def atol_for_validation(self) -> float:
|
449 |
+
return 1e-4
|
450 |
+
|
451 |
+
def generate_dummy_inputs(
|
452 |
+
self,
|
453 |
+
processor: "ProcessorMixin",
|
454 |
+
batch_size: int = -1,
|
455 |
+
seq_length: int = -1,
|
456 |
+
framework: Optional["TensorType"] = None,
|
457 |
+
) -> Mapping[str, Any]:
|
458 |
+
text_input_dict = super().generate_dummy_inputs(
|
459 |
+
processor.tokenizer, batch_size=batch_size, seq_length=seq_length, framework=framework
|
460 |
+
)
|
461 |
+
image_input_dict = super().generate_dummy_inputs(
|
462 |
+
processor.image_processor, batch_size=batch_size, framework=framework
|
463 |
+
)
|
464 |
+
return {**text_input_dict, **image_input_dict}
|
465 |
+
|
466 |
+
@property
|
467 |
+
def default_onnx_opset(self) -> int:
|
468 |
+
return 14
|
venv/lib/python3.10/site-packages/transformers/models/chinese_clip/convert_chinese_clip_original_pytorch_to_hf.py
ADDED
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 The OFA-Sys Team Authors and The HuggingFace 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 |
+
import argparse
|
17 |
+
|
18 |
+
import torch
|
19 |
+
|
20 |
+
from transformers import ChineseCLIPConfig, ChineseCLIPModel
|
21 |
+
|
22 |
+
|
23 |
+
def copy_attn_layer(hf_attn_layer, pt_weights, prefix):
|
24 |
+
q_proj, k_proj, v_proj = pt_weights[f"{prefix}.in_proj_weight"].chunk(3, dim=0)
|
25 |
+
q_proj_bias, k_proj_bias, v_proj_bias = pt_weights[f"{prefix}.in_proj_bias"].chunk(3, dim=0)
|
26 |
+
|
27 |
+
out_proj_weights = pt_weights[f"{prefix}.out_proj.weight"]
|
28 |
+
out_proj_bias = pt_weights[f"{prefix}.out_proj.bias"]
|
29 |
+
|
30 |
+
hf_attn_layer.q_proj.weight.data = q_proj
|
31 |
+
hf_attn_layer.q_proj.bias.data = q_proj_bias
|
32 |
+
|
33 |
+
hf_attn_layer.k_proj.weight.data = k_proj
|
34 |
+
hf_attn_layer.k_proj.bias.data = k_proj_bias
|
35 |
+
|
36 |
+
hf_attn_layer.v_proj.weight.data = v_proj
|
37 |
+
hf_attn_layer.v_proj.bias.data = v_proj_bias
|
38 |
+
|
39 |
+
hf_attn_layer.out_proj.weight.data = out_proj_weights
|
40 |
+
hf_attn_layer.out_proj.bias.data = out_proj_bias
|
41 |
+
|
42 |
+
|
43 |
+
def copy_mlp(hf_mlp, pt_weights, prefix):
|
44 |
+
copy_linear(hf_mlp.fc1, pt_weights, f"{prefix}.c_fc")
|
45 |
+
copy_linear(hf_mlp.fc2, pt_weights, f"{prefix}.c_proj")
|
46 |
+
|
47 |
+
|
48 |
+
def copy_linear(hf_linear, pt_weights, prefix):
|
49 |
+
hf_linear.weight.data = pt_weights[f"{prefix}.weight"].data
|
50 |
+
hf_linear.bias.data = pt_weights[f"{prefix}.bias"].data
|
51 |
+
|
52 |
+
|
53 |
+
def copy_layer(hf_layer, pt_weights, prefix):
|
54 |
+
# copy layer norms
|
55 |
+
copy_linear(hf_layer.layer_norm1, pt_weights, f"{prefix}.ln_1")
|
56 |
+
copy_linear(hf_layer.layer_norm2, pt_weights, f"{prefix}.ln_2")
|
57 |
+
|
58 |
+
# copy MLP
|
59 |
+
copy_mlp(hf_layer.mlp, pt_weights, f"{prefix}.mlp")
|
60 |
+
|
61 |
+
# copy attn
|
62 |
+
copy_attn_layer(hf_layer.self_attn, pt_weights, f"{prefix}.attn")
|
63 |
+
|
64 |
+
|
65 |
+
def copy_layers(hf_layers, pt_weights, prefix):
|
66 |
+
for layer_id, hf_layer in enumerate(hf_layers):
|
67 |
+
copy_layer(hf_layer, pt_weights, f"{prefix}.{layer_id}")
|
68 |
+
|
69 |
+
|
70 |
+
def copy_text_model_and_projection(hf_model, pt_weights):
|
71 |
+
# copy projection
|
72 |
+
hf_model.text_projection.weight.data = pt_weights["text_projection"].data.T
|
73 |
+
|
74 |
+
# copy text encoder
|
75 |
+
for name, param in hf_model.text_model.named_parameters():
|
76 |
+
param.data = pt_weights[f"bert.{name}"].data
|
77 |
+
|
78 |
+
|
79 |
+
def copy_vision_model_and_projection(hf_model, pt_weights):
|
80 |
+
# copy projection
|
81 |
+
hf_model.visual_projection.weight.data = pt_weights["visual.proj"].data.T
|
82 |
+
|
83 |
+
# copy layer norms
|
84 |
+
copy_linear(hf_model.vision_model.pre_layrnorm, pt_weights, "visual.ln_pre")
|
85 |
+
copy_linear(hf_model.vision_model.post_layernorm, pt_weights, "visual.ln_post")
|
86 |
+
|
87 |
+
# copy embeddings
|
88 |
+
hf_model.vision_model.embeddings.patch_embedding.weight.data = pt_weights["visual.conv1.weight"].data
|
89 |
+
hf_model.vision_model.embeddings.class_embedding.data = pt_weights["visual.class_embedding"].data
|
90 |
+
hf_model.vision_model.embeddings.position_embedding.weight.data = pt_weights["visual.positional_embedding"].data
|
91 |
+
|
92 |
+
# copy encoder
|
93 |
+
copy_layers(hf_model.vision_model.encoder.layers, pt_weights, "visual.transformer.resblocks")
|
94 |
+
|
95 |
+
|
96 |
+
@torch.no_grad()
|
97 |
+
def convert_chinese_clip_checkpoint(checkpoint_path, pytorch_dump_folder_path, config_path=None):
|
98 |
+
"""
|
99 |
+
Copy/paste/tweak model's weights to transformers design.
|
100 |
+
"""
|
101 |
+
|
102 |
+
assert config_path is not None, "Please specify the ChineseCLIP model config of the corresponding model size."
|
103 |
+
config = ChineseCLIPConfig.from_pretrained(config_path)
|
104 |
+
|
105 |
+
hf_model = ChineseCLIPModel(config).eval()
|
106 |
+
|
107 |
+
pt_weights = torch.load(checkpoint_path, map_location="cpu")["state_dict"]
|
108 |
+
pt_weights = {(name[7:] if name.startswith("module.") else name): value for name, value in pt_weights.items()}
|
109 |
+
|
110 |
+
copy_text_model_and_projection(hf_model, pt_weights)
|
111 |
+
copy_vision_model_and_projection(hf_model, pt_weights)
|
112 |
+
hf_model.logit_scale.data = pt_weights["logit_scale"].data
|
113 |
+
|
114 |
+
hf_model.save_pretrained(pytorch_dump_folder_path)
|
115 |
+
|
116 |
+
|
117 |
+
if __name__ == "__main__":
|
118 |
+
parser = argparse.ArgumentParser()
|
119 |
+
parser.add_argument(
|
120 |
+
"--pytorch_dump_folder_path",
|
121 |
+
default=None,
|
122 |
+
type=str,
|
123 |
+
help="Path to the output folder storing converted hf PyTorch model.",
|
124 |
+
)
|
125 |
+
parser.add_argument(
|
126 |
+
"--checkpoint_path", default=None, type=str, help="Path to original github format ChineseCLIP checkpoint."
|
127 |
+
)
|
128 |
+
parser.add_argument(
|
129 |
+
"--config_path", default=None, required=True, type=str, help="Path to hf config.json of model to convert."
|
130 |
+
)
|
131 |
+
args = parser.parse_args()
|
132 |
+
|
133 |
+
convert_chinese_clip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
|
134 |
+
print("The conversion is finished!")
|
venv/lib/python3.10/site-packages/transformers/models/chinese_clip/feature_extraction_chinese_clip.py
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2021 The OFA-Sys Team Authors and The HuggingFace 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 |
+
"""Feature extractor class for Chinese-CLIP."""
|
16 |
+
|
17 |
+
import warnings
|
18 |
+
|
19 |
+
from ...utils import logging
|
20 |
+
from .image_processing_chinese_clip import ChineseCLIPImageProcessor
|
21 |
+
|
22 |
+
|
23 |
+
logger = logging.get_logger(__name__)
|
24 |
+
|
25 |
+
|
26 |
+
class ChineseCLIPFeatureExtractor(ChineseCLIPImageProcessor):
|
27 |
+
def __init__(self, *args, **kwargs) -> None:
|
28 |
+
warnings.warn(
|
29 |
+
"The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers."
|
30 |
+
" Please use ChineseCLIPImageProcessor instead.",
|
31 |
+
FutureWarning,
|
32 |
+
)
|
33 |
+
super().__init__(*args, **kwargs)
|
venv/lib/python3.10/site-packages/transformers/models/chinese_clip/image_processing_chinese_clip.py
ADDED
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 The OFA-Sys Team Authors and The HuggingFace 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 Chinese-CLIP."""
|
16 |
+
|
17 |
+
from typing import Dict, List, Optional, Union
|
18 |
+
|
19 |
+
import numpy as np
|
20 |
+
|
21 |
+
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
|
22 |
+
from ...image_transforms import (
|
23 |
+
convert_to_rgb,
|
24 |
+
get_resize_output_image_size,
|
25 |
+
resize,
|
26 |
+
to_channel_dimension_format,
|
27 |
+
)
|
28 |
+
from ...image_utils import (
|
29 |
+
OPENAI_CLIP_MEAN,
|
30 |
+
OPENAI_CLIP_STD,
|
31 |
+
ChannelDimension,
|
32 |
+
ImageInput,
|
33 |
+
PILImageResampling,
|
34 |
+
infer_channel_dimension_format,
|
35 |
+
is_scaled_image,
|
36 |
+
make_list_of_images,
|
37 |
+
to_numpy_array,
|
38 |
+
valid_images,
|
39 |
+
validate_kwargs,
|
40 |
+
validate_preprocess_arguments,
|
41 |
+
)
|
42 |
+
from ...utils import TensorType, is_vision_available, logging
|
43 |
+
|
44 |
+
|
45 |
+
logger = logging.get_logger(__name__)
|
46 |
+
|
47 |
+
|
48 |
+
if is_vision_available():
|
49 |
+
import PIL
|
50 |
+
|
51 |
+
|
52 |
+
class ChineseCLIPImageProcessor(BaseImageProcessor):
|
53 |
+
r"""
|
54 |
+
Constructs a Chinese-CLIP image processor.
|
55 |
+
|
56 |
+
Args:
|
57 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
58 |
+
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
|
59 |
+
`do_resize` in the `preprocess` method.
|
60 |
+
size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
|
61 |
+
Size of the image after resizing. The shortest edge of the image is resized to size["shortest_edge"], with
|
62 |
+
the longest edge resized to keep the input aspect ratio. Can be overridden by `size` in the `preprocess`
|
63 |
+
method.
|
64 |
+
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
|
65 |
+
Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
|
66 |
+
do_center_crop (`bool`, *optional*, defaults to `True`):
|
67 |
+
Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the
|
68 |
+
`preprocess` method.
|
69 |
+
crop_size (`Dict[str, int]` *optional*, defaults to 224):
|
70 |
+
Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
|
71 |
+
method.
|
72 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
73 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
|
74 |
+
the `preprocess` method.
|
75 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
76 |
+
Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
|
77 |
+
method.
|
78 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
79 |
+
Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method.
|
80 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
|
81 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
82 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
83 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
|
84 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
85 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
86 |
+
Can be overridden by the `image_std` parameter in the `preprocess` method.
|
87 |
+
do_convert_rgb (`bool`, *optional*, defaults to `True`):
|
88 |
+
Whether to convert the image to RGB.
|
89 |
+
"""
|
90 |
+
|
91 |
+
model_input_names = ["pixel_values"]
|
92 |
+
|
93 |
+
def __init__(
|
94 |
+
self,
|
95 |
+
do_resize: bool = True,
|
96 |
+
size: Dict[str, int] = None,
|
97 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
98 |
+
do_center_crop: bool = True,
|
99 |
+
crop_size: Dict[str, int] = None,
|
100 |
+
do_rescale: bool = True,
|
101 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
102 |
+
do_normalize: bool = True,
|
103 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
104 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
105 |
+
do_convert_rgb: bool = True,
|
106 |
+
**kwargs,
|
107 |
+
) -> None:
|
108 |
+
super().__init__(**kwargs)
|
109 |
+
size = size if size is not None else {"shortest_edge": 224}
|
110 |
+
size = get_size_dict(size, default_to_square=False)
|
111 |
+
crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
|
112 |
+
crop_size = get_size_dict(crop_size)
|
113 |
+
|
114 |
+
self.do_resize = do_resize
|
115 |
+
self.size = size
|
116 |
+
self.resample = resample
|
117 |
+
self.do_center_crop = do_center_crop
|
118 |
+
self.crop_size = crop_size
|
119 |
+
self.do_rescale = do_rescale
|
120 |
+
self.rescale_factor = rescale_factor
|
121 |
+
self.do_normalize = do_normalize
|
122 |
+
self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
|
123 |
+
self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
|
124 |
+
self.do_convert_rgb = do_convert_rgb
|
125 |
+
self._valid_processor_keys = [
|
126 |
+
"images",
|
127 |
+
"do_resize",
|
128 |
+
"size",
|
129 |
+
"resample",
|
130 |
+
"do_center_crop",
|
131 |
+
"crop_size",
|
132 |
+
"do_rescale",
|
133 |
+
"rescale_factor",
|
134 |
+
"do_normalize",
|
135 |
+
"image_mean",
|
136 |
+
"image_std",
|
137 |
+
"do_convert_rgb",
|
138 |
+
"return_tensors",
|
139 |
+
"data_format",
|
140 |
+
"input_data_format",
|
141 |
+
]
|
142 |
+
|
143 |
+
def resize(
|
144 |
+
self,
|
145 |
+
image: np.ndarray,
|
146 |
+
size: Dict[str, int],
|
147 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
148 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
149 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
150 |
+
**kwargs,
|
151 |
+
) -> np.ndarray:
|
152 |
+
"""
|
153 |
+
Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge
|
154 |
+
resized to keep the input aspect ratio.
|
155 |
+
|
156 |
+
Args:
|
157 |
+
image (`np.ndarray`):
|
158 |
+
Image to resize.
|
159 |
+
size (`Dict[str, int]`):
|
160 |
+
Size of the output image.
|
161 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
|
162 |
+
Resampling filter to use when resiizing the image.
|
163 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
164 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
165 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
166 |
+
The channel dimension format of the input image. If not provided, it will be inferred from the input
|
167 |
+
image.
|
168 |
+
"""
|
169 |
+
size = get_size_dict(size, default_to_square=False)
|
170 |
+
output_size = get_resize_output_image_size(
|
171 |
+
image, size=(size["height"], size["width"]), default_to_square=False, input_data_format=input_data_format
|
172 |
+
)
|
173 |
+
return resize(
|
174 |
+
image,
|
175 |
+
size=output_size,
|
176 |
+
resample=resample,
|
177 |
+
data_format=data_format,
|
178 |
+
input_data_format=input_data_format,
|
179 |
+
**kwargs,
|
180 |
+
)
|
181 |
+
|
182 |
+
def preprocess(
|
183 |
+
self,
|
184 |
+
images: ImageInput,
|
185 |
+
do_resize: bool = None,
|
186 |
+
size: Dict[str, int] = None,
|
187 |
+
resample: PILImageResampling = None,
|
188 |
+
do_center_crop: bool = None,
|
189 |
+
crop_size: int = None,
|
190 |
+
do_rescale: bool = None,
|
191 |
+
rescale_factor: float = None,
|
192 |
+
do_normalize: bool = None,
|
193 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
194 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
195 |
+
do_convert_rgb: bool = None,
|
196 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
197 |
+
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
|
198 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
199 |
+
**kwargs,
|
200 |
+
) -> PIL.Image.Image:
|
201 |
+
"""
|
202 |
+
Preprocess an image or batch of images.
|
203 |
+
|
204 |
+
Args:
|
205 |
+
images (`ImageInput`):
|
206 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
207 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
208 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
209 |
+
Whether to resize the image.
|
210 |
+
size (`Dict[str, int]`, *optional*, defaults to `self.size`):
|
211 |
+
Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
|
212 |
+
the longest edge resized to keep the input aspect ratio.
|
213 |
+
resample (`int`, *optional*, defaults to `self.resample`):
|
214 |
+
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
|
215 |
+
has an effect if `do_resize` is set to `True`.
|
216 |
+
do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
|
217 |
+
Whether to center crop the image.
|
218 |
+
crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
|
219 |
+
Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.
|
220 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
221 |
+
Whether to rescale the image.
|
222 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
223 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
224 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
225 |
+
Whether to normalize the image.
|
226 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
227 |
+
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
|
228 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
229 |
+
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
|
230 |
+
`True`.
|
231 |
+
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
|
232 |
+
Whether to convert the image to RGB.
|
233 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
234 |
+
The type of tensors to return. Can be one of:
|
235 |
+
- Unset: Return a list of `np.ndarray`.
|
236 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
237 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
238 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
239 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
240 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
241 |
+
The channel dimension format for the output image. Can be one of:
|
242 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
243 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
244 |
+
- Unset: Use the channel dimension format of the input image.
|
245 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
246 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
247 |
+
from the input image. Can be one of:
|
248 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
249 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
250 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
251 |
+
"""
|
252 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
253 |
+
size = size if size is not None else self.size
|
254 |
+
size = get_size_dict(size, default_to_square=False)
|
255 |
+
resample = resample if resample is not None else self.resample
|
256 |
+
do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
|
257 |
+
crop_size = crop_size if crop_size is not None else self.crop_size
|
258 |
+
crop_size = get_size_dict(crop_size)
|
259 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
260 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
261 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
262 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
263 |
+
image_std = image_std if image_std is not None else self.image_std
|
264 |
+
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
|
265 |
+
|
266 |
+
images = make_list_of_images(images)
|
267 |
+
|
268 |
+
validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)
|
269 |
+
|
270 |
+
if not valid_images(images):
|
271 |
+
raise ValueError(
|
272 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
273 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
274 |
+
)
|
275 |
+
validate_preprocess_arguments(
|
276 |
+
do_rescale=do_rescale,
|
277 |
+
rescale_factor=rescale_factor,
|
278 |
+
do_normalize=do_normalize,
|
279 |
+
image_mean=image_mean,
|
280 |
+
image_std=image_std,
|
281 |
+
do_center_crop=do_center_crop,
|
282 |
+
crop_size=crop_size,
|
283 |
+
do_resize=do_resize,
|
284 |
+
size=size,
|
285 |
+
resample=resample,
|
286 |
+
)
|
287 |
+
if do_convert_rgb:
|
288 |
+
images = [convert_to_rgb(image) for image in images]
|
289 |
+
|
290 |
+
# All transformations expect numpy arrays.
|
291 |
+
images = [to_numpy_array(image) for image in images]
|
292 |
+
|
293 |
+
if is_scaled_image(images[0]) and do_rescale:
|
294 |
+
logger.warning_once(
|
295 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
296 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
297 |
+
)
|
298 |
+
|
299 |
+
if input_data_format is None:
|
300 |
+
# We assume that all images have the same channel dimension format.
|
301 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
302 |
+
|
303 |
+
if do_resize:
|
304 |
+
images = [
|
305 |
+
self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
|
306 |
+
for image in images
|
307 |
+
]
|
308 |
+
|
309 |
+
if do_center_crop:
|
310 |
+
images = [
|
311 |
+
self.center_crop(image=image, size=crop_size, input_data_format=input_data_format) for image in images
|
312 |
+
]
|
313 |
+
|
314 |
+
if do_rescale:
|
315 |
+
images = [
|
316 |
+
self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
|
317 |
+
for image in images
|
318 |
+
]
|
319 |
+
|
320 |
+
if do_normalize:
|
321 |
+
images = [
|
322 |
+
self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
|
323 |
+
for image in images
|
324 |
+
]
|
325 |
+
|
326 |
+
images = [
|
327 |
+
to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
|
328 |
+
]
|
329 |
+
|
330 |
+
data = {"pixel_values": images}
|
331 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
venv/lib/python3.10/site-packages/transformers/models/chinese_clip/modeling_chinese_clip.py
ADDED
@@ -0,0 +1,1562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 The OFA-Sys Team Authors and The HuggingFace 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 Chinese-CLIP model."""
|
16 |
+
|
17 |
+
|
18 |
+
import math
|
19 |
+
from dataclasses import dataclass
|
20 |
+
from typing import Any, List, Optional, Tuple, Union
|
21 |
+
|
22 |
+
import torch
|
23 |
+
import torch.utils.checkpoint
|
24 |
+
from torch import nn
|
25 |
+
|
26 |
+
from ...activations import ACT2FN
|
27 |
+
from ...modeling_outputs import (
|
28 |
+
BaseModelOutput,
|
29 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
30 |
+
BaseModelOutputWithPooling,
|
31 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
32 |
+
)
|
33 |
+
from ...modeling_utils import PreTrainedModel
|
34 |
+
from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
|
35 |
+
from ...utils import (
|
36 |
+
ModelOutput,
|
37 |
+
add_code_sample_docstrings,
|
38 |
+
add_start_docstrings,
|
39 |
+
add_start_docstrings_to_model_forward,
|
40 |
+
logging,
|
41 |
+
replace_return_docstrings,
|
42 |
+
)
|
43 |
+
from .configuration_chinese_clip import ChineseCLIPConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig
|
44 |
+
|
45 |
+
|
46 |
+
logger = logging.get_logger(__name__)
|
47 |
+
|
48 |
+
_CHECKPOINT_FOR_DOC = "OFA-Sys/chinese-clip-vit-base-patch16"
|
49 |
+
_CONFIG_FOR_DOC = "ChineseCLIPConfig"
|
50 |
+
|
51 |
+
|
52 |
+
from ..deprecated._archive_maps import CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST # noqa: F401, E402
|
53 |
+
|
54 |
+
|
55 |
+
# https://sachinruk.github.io/blog/pytorch/pytorch%20lightning/loss%20function/gpu/2021/03/07/CLIP.html
|
56 |
+
# Copied from transformers.models.clip.modeling_clip.contrastive_loss
|
57 |
+
def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
|
58 |
+
return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
|
59 |
+
|
60 |
+
|
61 |
+
def chinese_clip_loss(similarity: torch.Tensor) -> torch.Tensor:
|
62 |
+
caption_loss = contrastive_loss(similarity)
|
63 |
+
image_loss = contrastive_loss(similarity.t())
|
64 |
+
return (caption_loss + image_loss) / 2.0
|
65 |
+
|
66 |
+
|
67 |
+
@dataclass
|
68 |
+
class ChineseCLIPOutput(ModelOutput):
|
69 |
+
"""
|
70 |
+
Args:
|
71 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
|
72 |
+
Contrastive loss for image-text similarity.
|
73 |
+
logits_per_image:(`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
|
74 |
+
The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
|
75 |
+
similarity scores.
|
76 |
+
logits_per_text:(`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
|
77 |
+
The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
|
78 |
+
similarity scores.
|
79 |
+
text_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
80 |
+
The text embeddings obtained by applying the projection layer to the pooled output of
|
81 |
+
[`ChineseCLIPTextModel`].
|
82 |
+
image_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
83 |
+
The image embeddings obtained by applying the projection layer to the pooled output of
|
84 |
+
[`ChineseCLIPVisionModel`].
|
85 |
+
text_model_output(`BaseModelOutputWithPoolingAndCrossAttentions`):
|
86 |
+
The output of the [`ChineseCLIPTextModel`].
|
87 |
+
vision_model_output(`BaseModelOutputWithPoolingAndCrossAttentions`):
|
88 |
+
The output of the [`ChineseCLIPVisionModel`].
|
89 |
+
"""
|
90 |
+
|
91 |
+
loss: Optional[torch.FloatTensor] = None
|
92 |
+
logits_per_image: torch.FloatTensor = None
|
93 |
+
logits_per_text: torch.FloatTensor = None
|
94 |
+
text_embeds: torch.FloatTensor = None
|
95 |
+
image_embeds: torch.FloatTensor = None
|
96 |
+
text_model_output: BaseModelOutputWithPoolingAndCrossAttentions = None
|
97 |
+
vision_model_output: BaseModelOutputWithPoolingAndCrossAttentions = None
|
98 |
+
|
99 |
+
def to_tuple(self) -> Tuple[Any]:
|
100 |
+
return tuple(
|
101 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
102 |
+
for k in self.keys()
|
103 |
+
)
|
104 |
+
|
105 |
+
|
106 |
+
# Copied from transformers.models.bert.modeling_bert.BertEmbeddings with Bert->ChineseCLIPText
|
107 |
+
class ChineseCLIPTextEmbeddings(nn.Module):
|
108 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
109 |
+
|
110 |
+
def __init__(self, config):
|
111 |
+
super().__init__()
|
112 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
113 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
114 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
115 |
+
|
116 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
117 |
+
# any TensorFlow checkpoint file
|
118 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
119 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
120 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
121 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
122 |
+
self.register_buffer(
|
123 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
124 |
+
)
|
125 |
+
self.register_buffer(
|
126 |
+
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
|
127 |
+
)
|
128 |
+
|
129 |
+
def forward(
|
130 |
+
self,
|
131 |
+
input_ids: Optional[torch.LongTensor] = None,
|
132 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
133 |
+
position_ids: Optional[torch.LongTensor] = None,
|
134 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
135 |
+
past_key_values_length: int = 0,
|
136 |
+
) -> torch.Tensor:
|
137 |
+
if input_ids is not None:
|
138 |
+
input_shape = input_ids.size()
|
139 |
+
else:
|
140 |
+
input_shape = inputs_embeds.size()[:-1]
|
141 |
+
|
142 |
+
seq_length = input_shape[1]
|
143 |
+
|
144 |
+
if position_ids is None:
|
145 |
+
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
|
146 |
+
|
147 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
148 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
149 |
+
# issue #5664
|
150 |
+
if token_type_ids is None:
|
151 |
+
if hasattr(self, "token_type_ids"):
|
152 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
153 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
154 |
+
token_type_ids = buffered_token_type_ids_expanded
|
155 |
+
else:
|
156 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
157 |
+
|
158 |
+
if inputs_embeds is None:
|
159 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
160 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
161 |
+
|
162 |
+
embeddings = inputs_embeds + token_type_embeddings
|
163 |
+
if self.position_embedding_type == "absolute":
|
164 |
+
position_embeddings = self.position_embeddings(position_ids)
|
165 |
+
embeddings += position_embeddings
|
166 |
+
embeddings = self.LayerNorm(embeddings)
|
167 |
+
embeddings = self.dropout(embeddings)
|
168 |
+
return embeddings
|
169 |
+
|
170 |
+
|
171 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPVisionEmbeddings with CLIP->ChineseCLIP
|
172 |
+
class ChineseCLIPVisionEmbeddings(nn.Module):
|
173 |
+
def __init__(self, config: ChineseCLIPVisionConfig):
|
174 |
+
super().__init__()
|
175 |
+
self.config = config
|
176 |
+
self.embed_dim = config.hidden_size
|
177 |
+
self.image_size = config.image_size
|
178 |
+
self.patch_size = config.patch_size
|
179 |
+
|
180 |
+
self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
|
181 |
+
|
182 |
+
self.patch_embedding = nn.Conv2d(
|
183 |
+
in_channels=config.num_channels,
|
184 |
+
out_channels=self.embed_dim,
|
185 |
+
kernel_size=self.patch_size,
|
186 |
+
stride=self.patch_size,
|
187 |
+
bias=False,
|
188 |
+
)
|
189 |
+
|
190 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
191 |
+
self.num_positions = self.num_patches + 1
|
192 |
+
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
|
193 |
+
self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
|
194 |
+
|
195 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
196 |
+
batch_size = pixel_values.shape[0]
|
197 |
+
target_dtype = self.patch_embedding.weight.dtype
|
198 |
+
patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
|
199 |
+
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
|
200 |
+
|
201 |
+
class_embeds = self.class_embedding.expand(batch_size, 1, -1)
|
202 |
+
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
203 |
+
embeddings = embeddings + self.position_embedding(self.position_ids)
|
204 |
+
return embeddings
|
205 |
+
|
206 |
+
|
207 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->ChineseCLIPText
|
208 |
+
class ChineseCLIPTextSelfAttention(nn.Module):
|
209 |
+
def __init__(self, config, position_embedding_type=None):
|
210 |
+
super().__init__()
|
211 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
212 |
+
raise ValueError(
|
213 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
214 |
+
f"heads ({config.num_attention_heads})"
|
215 |
+
)
|
216 |
+
|
217 |
+
self.num_attention_heads = config.num_attention_heads
|
218 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
219 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
220 |
+
|
221 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
222 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
223 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
224 |
+
|
225 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
226 |
+
self.position_embedding_type = position_embedding_type or getattr(
|
227 |
+
config, "position_embedding_type", "absolute"
|
228 |
+
)
|
229 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
230 |
+
self.max_position_embeddings = config.max_position_embeddings
|
231 |
+
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
|
232 |
+
|
233 |
+
self.is_decoder = config.is_decoder
|
234 |
+
|
235 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
236 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
237 |
+
x = x.view(new_x_shape)
|
238 |
+
return x.permute(0, 2, 1, 3)
|
239 |
+
|
240 |
+
def forward(
|
241 |
+
self,
|
242 |
+
hidden_states: torch.Tensor,
|
243 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
244 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
245 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
246 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
247 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
248 |
+
output_attentions: Optional[bool] = False,
|
249 |
+
) -> Tuple[torch.Tensor]:
|
250 |
+
mixed_query_layer = self.query(hidden_states)
|
251 |
+
|
252 |
+
# If this is instantiated as a cross-attention module, the keys
|
253 |
+
# and values come from an encoder; the attention mask needs to be
|
254 |
+
# such that the encoder's padding tokens are not attended to.
|
255 |
+
is_cross_attention = encoder_hidden_states is not None
|
256 |
+
|
257 |
+
if is_cross_attention and past_key_value is not None:
|
258 |
+
# reuse k,v, cross_attentions
|
259 |
+
key_layer = past_key_value[0]
|
260 |
+
value_layer = past_key_value[1]
|
261 |
+
attention_mask = encoder_attention_mask
|
262 |
+
elif is_cross_attention:
|
263 |
+
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
|
264 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
|
265 |
+
attention_mask = encoder_attention_mask
|
266 |
+
elif past_key_value is not None:
|
267 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
268 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
269 |
+
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
|
270 |
+
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
|
271 |
+
else:
|
272 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
273 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
274 |
+
|
275 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
276 |
+
|
277 |
+
use_cache = past_key_value is not None
|
278 |
+
if self.is_decoder:
|
279 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
280 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
281 |
+
# key/value_states (first "if" case)
|
282 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
283 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
284 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
285 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
286 |
+
past_key_value = (key_layer, value_layer)
|
287 |
+
|
288 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
289 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
290 |
+
|
291 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
292 |
+
query_length, key_length = query_layer.shape[2], key_layer.shape[2]
|
293 |
+
if use_cache:
|
294 |
+
position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
|
295 |
+
-1, 1
|
296 |
+
)
|
297 |
+
else:
|
298 |
+
position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
|
299 |
+
position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
|
300 |
+
distance = position_ids_l - position_ids_r
|
301 |
+
|
302 |
+
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
|
303 |
+
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
|
304 |
+
|
305 |
+
if self.position_embedding_type == "relative_key":
|
306 |
+
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
307 |
+
attention_scores = attention_scores + relative_position_scores
|
308 |
+
elif self.position_embedding_type == "relative_key_query":
|
309 |
+
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
310 |
+
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
|
311 |
+
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
|
312 |
+
|
313 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
314 |
+
if attention_mask is not None:
|
315 |
+
# Apply the attention mask is (precomputed for all layers in ChineseCLIPTextModel forward() function)
|
316 |
+
attention_scores = attention_scores + attention_mask
|
317 |
+
|
318 |
+
# Normalize the attention scores to probabilities.
|
319 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
320 |
+
|
321 |
+
# This is actually dropping out entire tokens to attend to, which might
|
322 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
323 |
+
attention_probs = self.dropout(attention_probs)
|
324 |
+
|
325 |
+
# Mask heads if we want to
|
326 |
+
if head_mask is not None:
|
327 |
+
attention_probs = attention_probs * head_mask
|
328 |
+
|
329 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
330 |
+
|
331 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
332 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
333 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
334 |
+
|
335 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
336 |
+
|
337 |
+
if self.is_decoder:
|
338 |
+
outputs = outputs + (past_key_value,)
|
339 |
+
return outputs
|
340 |
+
|
341 |
+
|
342 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->ChineseCLIPText
|
343 |
+
class ChineseCLIPTextSelfOutput(nn.Module):
|
344 |
+
def __init__(self, config):
|
345 |
+
super().__init__()
|
346 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
347 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
348 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
349 |
+
|
350 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
351 |
+
hidden_states = self.dense(hidden_states)
|
352 |
+
hidden_states = self.dropout(hidden_states)
|
353 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
354 |
+
return hidden_states
|
355 |
+
|
356 |
+
|
357 |
+
# Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->ChineseCLIPText
|
358 |
+
class ChineseCLIPTextAttention(nn.Module):
|
359 |
+
def __init__(self, config, position_embedding_type=None):
|
360 |
+
super().__init__()
|
361 |
+
self.self = ChineseCLIPTextSelfAttention(config, position_embedding_type=position_embedding_type)
|
362 |
+
self.output = ChineseCLIPTextSelfOutput(config)
|
363 |
+
self.pruned_heads = set()
|
364 |
+
|
365 |
+
def prune_heads(self, heads):
|
366 |
+
if len(heads) == 0:
|
367 |
+
return
|
368 |
+
heads, index = find_pruneable_heads_and_indices(
|
369 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
370 |
+
)
|
371 |
+
|
372 |
+
# Prune linear layers
|
373 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
374 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
375 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
376 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
377 |
+
|
378 |
+
# Update hyper params and store pruned heads
|
379 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
380 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
381 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
382 |
+
|
383 |
+
def forward(
|
384 |
+
self,
|
385 |
+
hidden_states: torch.Tensor,
|
386 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
387 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
388 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
389 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
390 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
391 |
+
output_attentions: Optional[bool] = False,
|
392 |
+
) -> Tuple[torch.Tensor]:
|
393 |
+
self_outputs = self.self(
|
394 |
+
hidden_states,
|
395 |
+
attention_mask,
|
396 |
+
head_mask,
|
397 |
+
encoder_hidden_states,
|
398 |
+
encoder_attention_mask,
|
399 |
+
past_key_value,
|
400 |
+
output_attentions,
|
401 |
+
)
|
402 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
403 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
404 |
+
return outputs
|
405 |
+
|
406 |
+
|
407 |
+
class ChineseCLIPVisionAttention(nn.Module):
|
408 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
409 |
+
|
410 |
+
def __init__(self, config):
|
411 |
+
super().__init__()
|
412 |
+
self.config = config
|
413 |
+
self.embed_dim = config.hidden_size
|
414 |
+
self.num_heads = config.num_attention_heads
|
415 |
+
self.head_dim = self.embed_dim // self.num_heads
|
416 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
417 |
+
raise ValueError(
|
418 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
419 |
+
f" {self.num_heads})."
|
420 |
+
)
|
421 |
+
self.scale = self.head_dim**-0.5
|
422 |
+
self.dropout = config.attention_dropout
|
423 |
+
|
424 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
425 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
426 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
427 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
428 |
+
|
429 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
430 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
431 |
+
|
432 |
+
def forward(
|
433 |
+
self,
|
434 |
+
hidden_states: torch.Tensor,
|
435 |
+
output_attentions: Optional[bool] = False,
|
436 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
437 |
+
"""Input shape: Batch x Time x Channel"""
|
438 |
+
|
439 |
+
bsz, tgt_len, embed_dim = hidden_states.size()
|
440 |
+
|
441 |
+
# get query proj
|
442 |
+
query_states = self.q_proj(hidden_states) * self.scale
|
443 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
444 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
445 |
+
|
446 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
447 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
448 |
+
key_states = key_states.view(*proj_shape)
|
449 |
+
value_states = value_states.view(*proj_shape)
|
450 |
+
|
451 |
+
src_len = key_states.size(1)
|
452 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
453 |
+
|
454 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
455 |
+
raise ValueError(
|
456 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
457 |
+
f" {attn_weights.size()}"
|
458 |
+
)
|
459 |
+
|
460 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
461 |
+
|
462 |
+
if output_attentions:
|
463 |
+
# this operation is a bit akward, but it's required to
|
464 |
+
# make sure that attn_weights keeps its gradient.
|
465 |
+
# In order to do so, attn_weights have to reshaped
|
466 |
+
# twice and have to be reused in the following
|
467 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
468 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
469 |
+
else:
|
470 |
+
attn_weights_reshaped = None
|
471 |
+
|
472 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
473 |
+
|
474 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
475 |
+
|
476 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
477 |
+
raise ValueError(
|
478 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
479 |
+
f" {attn_output.size()}"
|
480 |
+
)
|
481 |
+
|
482 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
483 |
+
attn_output = attn_output.transpose(1, 2)
|
484 |
+
attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
|
485 |
+
|
486 |
+
attn_output = self.out_proj(attn_output)
|
487 |
+
|
488 |
+
return attn_output, attn_weights_reshaped
|
489 |
+
|
490 |
+
|
491 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->ChineseCLIPText
|
492 |
+
class ChineseCLIPTextIntermediate(nn.Module):
|
493 |
+
def __init__(self, config):
|
494 |
+
super().__init__()
|
495 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
496 |
+
if isinstance(config.hidden_act, str):
|
497 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
498 |
+
else:
|
499 |
+
self.intermediate_act_fn = config.hidden_act
|
500 |
+
|
501 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
502 |
+
hidden_states = self.dense(hidden_states)
|
503 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
504 |
+
return hidden_states
|
505 |
+
|
506 |
+
|
507 |
+
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->ChineseCLIPText
|
508 |
+
class ChineseCLIPTextOutput(nn.Module):
|
509 |
+
def __init__(self, config):
|
510 |
+
super().__init__()
|
511 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
512 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
513 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
514 |
+
|
515 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
516 |
+
hidden_states = self.dense(hidden_states)
|
517 |
+
hidden_states = self.dropout(hidden_states)
|
518 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
519 |
+
return hidden_states
|
520 |
+
|
521 |
+
|
522 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->ChineseCLIPVision
|
523 |
+
class ChineseCLIPVisionMLP(nn.Module):
|
524 |
+
def __init__(self, config):
|
525 |
+
super().__init__()
|
526 |
+
self.config = config
|
527 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
528 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
529 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
530 |
+
|
531 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
532 |
+
hidden_states = self.fc1(hidden_states)
|
533 |
+
hidden_states = self.activation_fn(hidden_states)
|
534 |
+
hidden_states = self.fc2(hidden_states)
|
535 |
+
return hidden_states
|
536 |
+
|
537 |
+
|
538 |
+
# Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->ChineseCLIPText
|
539 |
+
class ChineseCLIPTextLayer(nn.Module):
|
540 |
+
def __init__(self, config):
|
541 |
+
super().__init__()
|
542 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
543 |
+
self.seq_len_dim = 1
|
544 |
+
self.attention = ChineseCLIPTextAttention(config)
|
545 |
+
self.is_decoder = config.is_decoder
|
546 |
+
self.add_cross_attention = config.add_cross_attention
|
547 |
+
if self.add_cross_attention:
|
548 |
+
if not self.is_decoder:
|
549 |
+
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
|
550 |
+
self.crossattention = ChineseCLIPTextAttention(config, position_embedding_type="absolute")
|
551 |
+
self.intermediate = ChineseCLIPTextIntermediate(config)
|
552 |
+
self.output = ChineseCLIPTextOutput(config)
|
553 |
+
|
554 |
+
def forward(
|
555 |
+
self,
|
556 |
+
hidden_states: torch.Tensor,
|
557 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
558 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
559 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
560 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
561 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
562 |
+
output_attentions: Optional[bool] = False,
|
563 |
+
) -> Tuple[torch.Tensor]:
|
564 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
565 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
566 |
+
self_attention_outputs = self.attention(
|
567 |
+
hidden_states,
|
568 |
+
attention_mask,
|
569 |
+
head_mask,
|
570 |
+
output_attentions=output_attentions,
|
571 |
+
past_key_value=self_attn_past_key_value,
|
572 |
+
)
|
573 |
+
attention_output = self_attention_outputs[0]
|
574 |
+
|
575 |
+
# if decoder, the last output is tuple of self-attn cache
|
576 |
+
if self.is_decoder:
|
577 |
+
outputs = self_attention_outputs[1:-1]
|
578 |
+
present_key_value = self_attention_outputs[-1]
|
579 |
+
else:
|
580 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
581 |
+
|
582 |
+
cross_attn_present_key_value = None
|
583 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
584 |
+
if not hasattr(self, "crossattention"):
|
585 |
+
raise ValueError(
|
586 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
587 |
+
" by setting `config.add_cross_attention=True`"
|
588 |
+
)
|
589 |
+
|
590 |
+
# cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
|
591 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
592 |
+
cross_attention_outputs = self.crossattention(
|
593 |
+
attention_output,
|
594 |
+
attention_mask,
|
595 |
+
head_mask,
|
596 |
+
encoder_hidden_states,
|
597 |
+
encoder_attention_mask,
|
598 |
+
cross_attn_past_key_value,
|
599 |
+
output_attentions,
|
600 |
+
)
|
601 |
+
attention_output = cross_attention_outputs[0]
|
602 |
+
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
|
603 |
+
|
604 |
+
# add cross-attn cache to positions 3,4 of present_key_value tuple
|
605 |
+
cross_attn_present_key_value = cross_attention_outputs[-1]
|
606 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
607 |
+
|
608 |
+
layer_output = apply_chunking_to_forward(
|
609 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
610 |
+
)
|
611 |
+
outputs = (layer_output,) + outputs
|
612 |
+
|
613 |
+
# if decoder, return the attn key/values as the last output
|
614 |
+
if self.is_decoder:
|
615 |
+
outputs = outputs + (present_key_value,)
|
616 |
+
|
617 |
+
return outputs
|
618 |
+
|
619 |
+
def feed_forward_chunk(self, attention_output):
|
620 |
+
intermediate_output = self.intermediate(attention_output)
|
621 |
+
layer_output = self.output(intermediate_output, attention_output)
|
622 |
+
return layer_output
|
623 |
+
|
624 |
+
|
625 |
+
class ChineseCLIPVisionLayer(nn.Module):
|
626 |
+
def __init__(self, config: ChineseCLIPConfig):
|
627 |
+
super().__init__()
|
628 |
+
self.embed_dim = config.hidden_size
|
629 |
+
self.self_attn = ChineseCLIPVisionAttention(config)
|
630 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
631 |
+
self.mlp = ChineseCLIPVisionMLP(config)
|
632 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
633 |
+
|
634 |
+
def forward(
|
635 |
+
self,
|
636 |
+
hidden_states: torch.Tensor,
|
637 |
+
output_attentions: Optional[bool] = False,
|
638 |
+
) -> Tuple[torch.FloatTensor]:
|
639 |
+
"""
|
640 |
+
Args:
|
641 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
642 |
+
output_attentions (`bool`, *optional*):
|
643 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
644 |
+
returned tensors for more detail.
|
645 |
+
"""
|
646 |
+
residual = hidden_states
|
647 |
+
|
648 |
+
hidden_states = self.layer_norm1(hidden_states)
|
649 |
+
hidden_states, attn_weights = self.self_attn(
|
650 |
+
hidden_states=hidden_states,
|
651 |
+
output_attentions=output_attentions,
|
652 |
+
)
|
653 |
+
hidden_states = residual + hidden_states
|
654 |
+
|
655 |
+
residual = hidden_states
|
656 |
+
hidden_states = self.layer_norm2(hidden_states)
|
657 |
+
hidden_states = self.mlp(hidden_states)
|
658 |
+
hidden_states = residual + hidden_states
|
659 |
+
|
660 |
+
outputs = (hidden_states,)
|
661 |
+
|
662 |
+
if output_attentions:
|
663 |
+
outputs += (attn_weights,)
|
664 |
+
|
665 |
+
return outputs
|
666 |
+
|
667 |
+
|
668 |
+
# Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->ChineseCLIPText
|
669 |
+
class ChineseCLIPTextPooler(nn.Module):
|
670 |
+
def __init__(self, config):
|
671 |
+
super().__init__()
|
672 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
673 |
+
self.activation = nn.Tanh()
|
674 |
+
|
675 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
676 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
677 |
+
# to the first token.
|
678 |
+
first_token_tensor = hidden_states[:, 0]
|
679 |
+
pooled_output = self.dense(first_token_tensor)
|
680 |
+
pooled_output = self.activation(pooled_output)
|
681 |
+
return pooled_output
|
682 |
+
|
683 |
+
|
684 |
+
class ChineseCLIPPreTrainedModel(PreTrainedModel):
|
685 |
+
"""
|
686 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
687 |
+
models.
|
688 |
+
"""
|
689 |
+
|
690 |
+
config_class = ChineseCLIPConfig
|
691 |
+
base_model_prefix = "chinese_clip"
|
692 |
+
supports_gradient_checkpointing = True
|
693 |
+
|
694 |
+
def _init_weights(self, module):
|
695 |
+
"""Initialize the weights"""
|
696 |
+
factor = self.config.initializer_factor
|
697 |
+
if isinstance(module, ChineseCLIPVisionEmbeddings):
|
698 |
+
factor = self.config.initializer_factor
|
699 |
+
nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
|
700 |
+
nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
|
701 |
+
nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
|
702 |
+
elif isinstance(module, ChineseCLIPTextEmbeddings):
|
703 |
+
nn.init.normal_(module.word_embeddings.weight, mean=0.0, std=self.config.initializer_range)
|
704 |
+
nn.init.normal_(module.position_embeddings.weight, mean=0.0, std=self.config.initializer_range)
|
705 |
+
nn.init.normal_(module.token_type_embeddings.weight, mean=0.0, std=self.config.initializer_range)
|
706 |
+
for embedding in [module.word_embeddings, module.position_embeddings, module.token_type_embeddings]:
|
707 |
+
if embedding.padding_idx is not None:
|
708 |
+
embedding.weight.data[embedding.padding_idx].zero_()
|
709 |
+
elif isinstance(module, ChineseCLIPVisionAttention):
|
710 |
+
factor = self.config.initializer_factor
|
711 |
+
in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
712 |
+
out_proj_std = (module.embed_dim**-0.5) * factor
|
713 |
+
nn.init.normal_(module.q_proj.weight, std=in_proj_std)
|
714 |
+
nn.init.normal_(module.k_proj.weight, std=in_proj_std)
|
715 |
+
nn.init.normal_(module.v_proj.weight, std=in_proj_std)
|
716 |
+
nn.init.normal_(module.out_proj.weight, std=out_proj_std)
|
717 |
+
elif isinstance(module, ChineseCLIPVisionMLP):
|
718 |
+
factor = self.config.initializer_factor
|
719 |
+
in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
720 |
+
fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
|
721 |
+
nn.init.normal_(module.fc1.weight, std=fc_std)
|
722 |
+
nn.init.normal_(module.fc2.weight, std=in_proj_std)
|
723 |
+
elif isinstance(module, ChineseCLIPModel):
|
724 |
+
nn.init.normal_(
|
725 |
+
module.text_projection.weight,
|
726 |
+
std=module.text_embed_dim**-0.5 * self.config.initializer_factor,
|
727 |
+
)
|
728 |
+
nn.init.normal_(
|
729 |
+
module.visual_projection.weight,
|
730 |
+
std=module.vision_embed_dim**-0.5 * self.config.initializer_factor,
|
731 |
+
)
|
732 |
+
|
733 |
+
if isinstance(module, nn.LayerNorm):
|
734 |
+
module.bias.data.zero_()
|
735 |
+
module.weight.data.fill_(1.0)
|
736 |
+
if isinstance(module, nn.Linear):
|
737 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
738 |
+
if module.bias is not None:
|
739 |
+
module.bias.data.zero_()
|
740 |
+
|
741 |
+
|
742 |
+
CHINESE_CLIP_START_DOCSTRING = r"""
|
743 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
744 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
745 |
+
behavior.
|
746 |
+
|
747 |
+
Parameters:
|
748 |
+
config ([`ChineseCLIPConfig`]): Model configuration class with all the parameters of the model.
|
749 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
750 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
751 |
+
"""
|
752 |
+
|
753 |
+
CHINESE_CLIP_TEXT_INPUTS_DOCSTRING = r"""
|
754 |
+
Args:
|
755 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
756 |
+
Indices of input sequence tokens in the vocabulary.
|
757 |
+
|
758 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
759 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
760 |
+
|
761 |
+
[What are input IDs?](../glossary#input-ids)
|
762 |
+
attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
763 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
764 |
+
|
765 |
+
- 1 for tokens that are **not masked**,
|
766 |
+
- 0 for tokens that are **masked**.
|
767 |
+
|
768 |
+
[What are attention masks?](../glossary#attention-mask)
|
769 |
+
token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
770 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
771 |
+
1]`:
|
772 |
+
|
773 |
+
- 0 corresponds to a *sentence A* token,
|
774 |
+
- 1 corresponds to a *sentence B* token.
|
775 |
+
|
776 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
777 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
778 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
779 |
+
config.max_position_embeddings - 1]`.
|
780 |
+
|
781 |
+
[What are position IDs?](../glossary#position-ids)
|
782 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
783 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
784 |
+
|
785 |
+
- 1 indicates the head is **not masked**,
|
786 |
+
- 0 indicates the head is **masked**.
|
787 |
+
|
788 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
789 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
790 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
791 |
+
model's internal embedding lookup matrix.
|
792 |
+
output_attentions (`bool`, *optional*):
|
793 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
794 |
+
tensors for more detail.
|
795 |
+
output_hidden_states (`bool`, *optional*):
|
796 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
797 |
+
more detail.
|
798 |
+
return_dict (`bool`, *optional*):
|
799 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
800 |
+
"""
|
801 |
+
|
802 |
+
CHINESE_CLIP_VISION_INPUTS_DOCSTRING = r"""
|
803 |
+
Args:
|
804 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
805 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
806 |
+
[`AutoImageProcessor`]. See [`ChineseCLIPImageProcessor.__call__`] for details.
|
807 |
+
output_attentions (`bool`, *optional*):
|
808 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
809 |
+
tensors for more detail.
|
810 |
+
output_hidden_states (`bool`, *optional*):
|
811 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
812 |
+
more detail.
|
813 |
+
return_dict (`bool`, *optional*):
|
814 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
815 |
+
"""
|
816 |
+
|
817 |
+
CHINESE_CLIP_INPUTS_DOCSTRING = r"""
|
818 |
+
Args:
|
819 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
820 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
821 |
+
it.
|
822 |
+
|
823 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
824 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
825 |
+
|
826 |
+
[What are input IDs?](../glossary#input-ids)
|
827 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
828 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
829 |
+
|
830 |
+
- 1 for tokens that are **not masked**,
|
831 |
+
- 0 for tokens that are **masked**.
|
832 |
+
|
833 |
+
[What are attention masks?](../glossary#attention-mask)
|
834 |
+
token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
835 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
836 |
+
1]`:
|
837 |
+
|
838 |
+
- 0 corresponds to a *sentence A* token,
|
839 |
+
- 1 corresponds to a *sentence B* token.
|
840 |
+
|
841 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
842 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
843 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
844 |
+
config.max_position_embeddings - 1]`.
|
845 |
+
|
846 |
+
[What are position IDs?](../glossary#position-ids)
|
847 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
848 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
849 |
+
[`AutoImageProcessor`]. See [`ChineseCLIPImageProcessor.__call__`] for details.
|
850 |
+
return_loss (`bool`, *optional*):
|
851 |
+
Whether or not to return the contrastive loss.
|
852 |
+
output_attentions (`bool`, *optional*):
|
853 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
854 |
+
tensors for more detail.
|
855 |
+
output_hidden_states (`bool`, *optional*):
|
856 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
857 |
+
more detail.
|
858 |
+
return_dict (`bool`, *optional*):
|
859 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
860 |
+
"""
|
861 |
+
|
862 |
+
|
863 |
+
# Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->ChineseCLIPText
|
864 |
+
class ChineseCLIPTextEncoder(nn.Module):
|
865 |
+
def __init__(self, config):
|
866 |
+
super().__init__()
|
867 |
+
self.config = config
|
868 |
+
self.layer = nn.ModuleList([ChineseCLIPTextLayer(config) for _ in range(config.num_hidden_layers)])
|
869 |
+
self.gradient_checkpointing = False
|
870 |
+
|
871 |
+
def forward(
|
872 |
+
self,
|
873 |
+
hidden_states: torch.Tensor,
|
874 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
875 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
876 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
877 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
878 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
879 |
+
use_cache: Optional[bool] = None,
|
880 |
+
output_attentions: Optional[bool] = False,
|
881 |
+
output_hidden_states: Optional[bool] = False,
|
882 |
+
return_dict: Optional[bool] = True,
|
883 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
|
884 |
+
all_hidden_states = () if output_hidden_states else None
|
885 |
+
all_self_attentions = () if output_attentions else None
|
886 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
887 |
+
|
888 |
+
if self.gradient_checkpointing and self.training:
|
889 |
+
if use_cache:
|
890 |
+
logger.warning_once(
|
891 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
892 |
+
)
|
893 |
+
use_cache = False
|
894 |
+
|
895 |
+
next_decoder_cache = () if use_cache else None
|
896 |
+
for i, layer_module in enumerate(self.layer):
|
897 |
+
if output_hidden_states:
|
898 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
899 |
+
|
900 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
901 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
902 |
+
|
903 |
+
if self.gradient_checkpointing and self.training:
|
904 |
+
layer_outputs = self._gradient_checkpointing_func(
|
905 |
+
layer_module.__call__,
|
906 |
+
hidden_states,
|
907 |
+
attention_mask,
|
908 |
+
layer_head_mask,
|
909 |
+
encoder_hidden_states,
|
910 |
+
encoder_attention_mask,
|
911 |
+
past_key_value,
|
912 |
+
output_attentions,
|
913 |
+
)
|
914 |
+
else:
|
915 |
+
layer_outputs = layer_module(
|
916 |
+
hidden_states,
|
917 |
+
attention_mask,
|
918 |
+
layer_head_mask,
|
919 |
+
encoder_hidden_states,
|
920 |
+
encoder_attention_mask,
|
921 |
+
past_key_value,
|
922 |
+
output_attentions,
|
923 |
+
)
|
924 |
+
|
925 |
+
hidden_states = layer_outputs[0]
|
926 |
+
if use_cache:
|
927 |
+
next_decoder_cache += (layer_outputs[-1],)
|
928 |
+
if output_attentions:
|
929 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
930 |
+
if self.config.add_cross_attention:
|
931 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
932 |
+
|
933 |
+
if output_hidden_states:
|
934 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
935 |
+
|
936 |
+
if not return_dict:
|
937 |
+
return tuple(
|
938 |
+
v
|
939 |
+
for v in [
|
940 |
+
hidden_states,
|
941 |
+
next_decoder_cache,
|
942 |
+
all_hidden_states,
|
943 |
+
all_self_attentions,
|
944 |
+
all_cross_attentions,
|
945 |
+
]
|
946 |
+
if v is not None
|
947 |
+
)
|
948 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
949 |
+
last_hidden_state=hidden_states,
|
950 |
+
past_key_values=next_decoder_cache,
|
951 |
+
hidden_states=all_hidden_states,
|
952 |
+
attentions=all_self_attentions,
|
953 |
+
cross_attentions=all_cross_attentions,
|
954 |
+
)
|
955 |
+
|
956 |
+
|
957 |
+
class ChineseCLIPVisionEncoder(nn.Module):
|
958 |
+
"""
|
959 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
960 |
+
[`ChineseCLIPVisionEncoderLayer`].
|
961 |
+
|
962 |
+
Args:
|
963 |
+
config: ChineseCLIPConfig
|
964 |
+
"""
|
965 |
+
|
966 |
+
def __init__(self, config: ChineseCLIPConfig):
|
967 |
+
super().__init__()
|
968 |
+
self.config = config
|
969 |
+
self.layers = nn.ModuleList([ChineseCLIPVisionLayer(config) for _ in range(config.num_hidden_layers)])
|
970 |
+
self.gradient_checkpointing = False
|
971 |
+
|
972 |
+
def forward(
|
973 |
+
self,
|
974 |
+
inputs_embeds,
|
975 |
+
output_attentions: Optional[bool] = None,
|
976 |
+
output_hidden_states: Optional[bool] = None,
|
977 |
+
return_dict: Optional[bool] = None,
|
978 |
+
) -> Union[Tuple, BaseModelOutput]:
|
979 |
+
r"""
|
980 |
+
Args:
|
981 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
982 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
983 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
984 |
+
than the model's internal embedding lookup matrix.
|
985 |
+
output_attentions (`bool`, *optional*):
|
986 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
987 |
+
returned tensors for more detail.
|
988 |
+
output_hidden_states (`bool`, *optional*):
|
989 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
990 |
+
for more detail.
|
991 |
+
return_dict (`bool`, *optional*):
|
992 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
993 |
+
"""
|
994 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
995 |
+
output_hidden_states = (
|
996 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
997 |
+
)
|
998 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
999 |
+
|
1000 |
+
encoder_states = () if output_hidden_states else None
|
1001 |
+
all_attentions = () if output_attentions else None
|
1002 |
+
|
1003 |
+
hidden_states = inputs_embeds
|
1004 |
+
for idx, encoder_layer in enumerate(self.layers):
|
1005 |
+
if output_hidden_states:
|
1006 |
+
encoder_states = encoder_states + (hidden_states,)
|
1007 |
+
if self.gradient_checkpointing and self.training:
|
1008 |
+
layer_outputs = self._gradient_checkpointing_func(
|
1009 |
+
encoder_layer.__call__,
|
1010 |
+
hidden_states,
|
1011 |
+
output_attentions,
|
1012 |
+
)
|
1013 |
+
else:
|
1014 |
+
layer_outputs = encoder_layer(
|
1015 |
+
hidden_states,
|
1016 |
+
output_attentions=output_attentions,
|
1017 |
+
)
|
1018 |
+
|
1019 |
+
hidden_states = layer_outputs[0]
|
1020 |
+
|
1021 |
+
if output_attentions:
|
1022 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
1023 |
+
|
1024 |
+
if output_hidden_states:
|
1025 |
+
encoder_states = encoder_states + (hidden_states,)
|
1026 |
+
|
1027 |
+
if not return_dict:
|
1028 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
1029 |
+
return BaseModelOutput(
|
1030 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
1031 |
+
)
|
1032 |
+
|
1033 |
+
|
1034 |
+
class ChineseCLIPVisionTransformer(nn.Module):
|
1035 |
+
def __init__(self, config: ChineseCLIPVisionConfig):
|
1036 |
+
super().__init__()
|
1037 |
+
self.config = config
|
1038 |
+
embed_dim = config.hidden_size
|
1039 |
+
|
1040 |
+
self.embeddings = ChineseCLIPVisionEmbeddings(config)
|
1041 |
+
self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
1042 |
+
self.encoder = ChineseCLIPVisionEncoder(config)
|
1043 |
+
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
1044 |
+
|
1045 |
+
@add_start_docstrings_to_model_forward(CHINESE_CLIP_VISION_INPUTS_DOCSTRING)
|
1046 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=ChineseCLIPVisionConfig)
|
1047 |
+
def forward(
|
1048 |
+
self,
|
1049 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
1050 |
+
output_attentions: Optional[bool] = None,
|
1051 |
+
output_hidden_states: Optional[bool] = None,
|
1052 |
+
return_dict: Optional[bool] = None,
|
1053 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
1054 |
+
r"""
|
1055 |
+
Returns:
|
1056 |
+
"""
|
1057 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1058 |
+
output_hidden_states = (
|
1059 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1060 |
+
)
|
1061 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1062 |
+
|
1063 |
+
if pixel_values is None:
|
1064 |
+
raise ValueError("You have to specify pixel_values")
|
1065 |
+
|
1066 |
+
hidden_states = self.embeddings(pixel_values)
|
1067 |
+
hidden_states = self.pre_layrnorm(hidden_states)
|
1068 |
+
|
1069 |
+
encoder_outputs = self.encoder(
|
1070 |
+
inputs_embeds=hidden_states,
|
1071 |
+
output_attentions=output_attentions,
|
1072 |
+
output_hidden_states=output_hidden_states,
|
1073 |
+
return_dict=return_dict,
|
1074 |
+
)
|
1075 |
+
|
1076 |
+
last_hidden_state = encoder_outputs[0]
|
1077 |
+
pooled_output = last_hidden_state[:, 0, :]
|
1078 |
+
pooled_output = self.post_layernorm(pooled_output)
|
1079 |
+
|
1080 |
+
if not return_dict:
|
1081 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
1082 |
+
|
1083 |
+
return BaseModelOutputWithPooling(
|
1084 |
+
last_hidden_state=last_hidden_state,
|
1085 |
+
pooler_output=pooled_output,
|
1086 |
+
hidden_states=encoder_outputs.hidden_states,
|
1087 |
+
attentions=encoder_outputs.attentions,
|
1088 |
+
)
|
1089 |
+
|
1090 |
+
|
1091 |
+
@add_start_docstrings(
|
1092 |
+
"The text model from CHINESE_CLIP without any head or projection on top.",
|
1093 |
+
CHINESE_CLIP_START_DOCSTRING,
|
1094 |
+
)
|
1095 |
+
class ChineseCLIPTextModel(ChineseCLIPPreTrainedModel):
|
1096 |
+
"""
|
1097 |
+
|
1098 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
1099 |
+
cross-attention is added between the self-attention layers, following the architecture described in [Attention is
|
1100 |
+
all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
|
1101 |
+
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
|
1102 |
+
|
1103 |
+
To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
|
1104 |
+
to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
|
1105 |
+
`add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
|
1106 |
+
"""
|
1107 |
+
|
1108 |
+
config_class = ChineseCLIPTextConfig
|
1109 |
+
|
1110 |
+
def __init__(self, config, add_pooling_layer=True):
|
1111 |
+
super().__init__(config)
|
1112 |
+
self.config = config
|
1113 |
+
|
1114 |
+
self.embeddings = ChineseCLIPTextEmbeddings(config)
|
1115 |
+
self.encoder = ChineseCLIPTextEncoder(config)
|
1116 |
+
|
1117 |
+
self.pooler = ChineseCLIPTextPooler(config) if add_pooling_layer else None
|
1118 |
+
|
1119 |
+
# Initialize weights and apply final processing
|
1120 |
+
self.post_init()
|
1121 |
+
|
1122 |
+
def get_input_embeddings(self):
|
1123 |
+
return self.embeddings.word_embeddings
|
1124 |
+
|
1125 |
+
def set_input_embeddings(self, value):
|
1126 |
+
self.embeddings.word_embeddings = value
|
1127 |
+
|
1128 |
+
def _prune_heads(self, heads_to_prune):
|
1129 |
+
"""
|
1130 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
1131 |
+
class PreTrainedModel
|
1132 |
+
"""
|
1133 |
+
for layer, heads in heads_to_prune.items():
|
1134 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
1135 |
+
|
1136 |
+
@add_start_docstrings_to_model_forward(CHINESE_CLIP_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1137 |
+
@add_code_sample_docstrings(
|
1138 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1139 |
+
output_type=BaseModelOutputWithPoolingAndCrossAttentions,
|
1140 |
+
config_class=_CONFIG_FOR_DOC,
|
1141 |
+
)
|
1142 |
+
def forward(
|
1143 |
+
self,
|
1144 |
+
input_ids: Optional[torch.Tensor] = None,
|
1145 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1146 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
1147 |
+
position_ids: Optional[torch.Tensor] = None,
|
1148 |
+
head_mask: Optional[torch.Tensor] = None,
|
1149 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1150 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
1151 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
1152 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1153 |
+
use_cache: Optional[bool] = None,
|
1154 |
+
output_attentions: Optional[bool] = None,
|
1155 |
+
output_hidden_states: Optional[bool] = None,
|
1156 |
+
return_dict: Optional[bool] = None,
|
1157 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
|
1158 |
+
r"""
|
1159 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
1160 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
1161 |
+
the model is configured as a decoder.
|
1162 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1163 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
1164 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
1165 |
+
|
1166 |
+
- 1 for tokens that are **not masked**,
|
1167 |
+
- 0 for tokens that are **masked**.
|
1168 |
+
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)`):
|
1169 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
1170 |
+
|
1171 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
1172 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
1173 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
1174 |
+
use_cache (`bool`, *optional*):
|
1175 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
1176 |
+
`past_key_values`).
|
1177 |
+
"""
|
1178 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1179 |
+
output_hidden_states = (
|
1180 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1181 |
+
)
|
1182 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1183 |
+
|
1184 |
+
if self.config.is_decoder:
|
1185 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1186 |
+
else:
|
1187 |
+
use_cache = False
|
1188 |
+
|
1189 |
+
if input_ids is not None and inputs_embeds is not None:
|
1190 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
1191 |
+
elif input_ids is not None:
|
1192 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
1193 |
+
input_shape = input_ids.size()
|
1194 |
+
elif inputs_embeds is not None:
|
1195 |
+
input_shape = inputs_embeds.size()[:-1]
|
1196 |
+
else:
|
1197 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
1198 |
+
|
1199 |
+
batch_size, seq_length = input_shape
|
1200 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
1201 |
+
|
1202 |
+
# past_key_values_length
|
1203 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
1204 |
+
|
1205 |
+
if attention_mask is None:
|
1206 |
+
attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
|
1207 |
+
|
1208 |
+
if token_type_ids is None:
|
1209 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
1210 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
1211 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
|
1212 |
+
token_type_ids = buffered_token_type_ids_expanded
|
1213 |
+
else:
|
1214 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
1215 |
+
|
1216 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
1217 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
1218 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
|
1219 |
+
|
1220 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
1221 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
1222 |
+
if self.config.is_decoder and encoder_hidden_states is not None:
|
1223 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
1224 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
1225 |
+
if encoder_attention_mask is None:
|
1226 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
1227 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
1228 |
+
else:
|
1229 |
+
encoder_extended_attention_mask = None
|
1230 |
+
|
1231 |
+
# Prepare head mask if needed
|
1232 |
+
# 1.0 in head_mask indicate we keep the head
|
1233 |
+
# attention_probs has shape bsz x n_heads x N x N
|
1234 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
1235 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
1236 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
1237 |
+
|
1238 |
+
embedding_output = self.embeddings(
|
1239 |
+
input_ids=input_ids,
|
1240 |
+
position_ids=position_ids,
|
1241 |
+
token_type_ids=token_type_ids,
|
1242 |
+
inputs_embeds=inputs_embeds,
|
1243 |
+
past_key_values_length=past_key_values_length,
|
1244 |
+
)
|
1245 |
+
encoder_outputs = self.encoder(
|
1246 |
+
embedding_output,
|
1247 |
+
attention_mask=extended_attention_mask,
|
1248 |
+
head_mask=head_mask,
|
1249 |
+
encoder_hidden_states=encoder_hidden_states,
|
1250 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
1251 |
+
past_key_values=past_key_values,
|
1252 |
+
use_cache=use_cache,
|
1253 |
+
output_attentions=output_attentions,
|
1254 |
+
output_hidden_states=output_hidden_states,
|
1255 |
+
return_dict=return_dict,
|
1256 |
+
)
|
1257 |
+
sequence_output = encoder_outputs[0]
|
1258 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
1259 |
+
|
1260 |
+
if not return_dict:
|
1261 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
1262 |
+
|
1263 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
1264 |
+
last_hidden_state=sequence_output,
|
1265 |
+
pooler_output=pooled_output,
|
1266 |
+
past_key_values=encoder_outputs.past_key_values,
|
1267 |
+
hidden_states=encoder_outputs.hidden_states,
|
1268 |
+
attentions=encoder_outputs.attentions,
|
1269 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
1270 |
+
)
|
1271 |
+
|
1272 |
+
|
1273 |
+
@add_start_docstrings(
|
1274 |
+
"""The vision model from CHINESE_CLIP without any head or projection on top.""",
|
1275 |
+
CHINESE_CLIP_START_DOCSTRING,
|
1276 |
+
)
|
1277 |
+
class ChineseCLIPVisionModel(ChineseCLIPPreTrainedModel):
|
1278 |
+
config_class = ChineseCLIPVisionConfig
|
1279 |
+
main_input_name = "pixel_values"
|
1280 |
+
|
1281 |
+
def __init__(self, config: ChineseCLIPVisionConfig):
|
1282 |
+
super().__init__(config)
|
1283 |
+
self.vision_model = ChineseCLIPVisionTransformer(config)
|
1284 |
+
# Initialize weights and apply final processing
|
1285 |
+
self.post_init()
|
1286 |
+
|
1287 |
+
def get_input_embeddings(self) -> nn.Module:
|
1288 |
+
return self.vision_model.embeddings.patch_embedding
|
1289 |
+
|
1290 |
+
@add_start_docstrings_to_model_forward(CHINESE_CLIP_VISION_INPUTS_DOCSTRING)
|
1291 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=ChineseCLIPVisionConfig)
|
1292 |
+
def forward(
|
1293 |
+
self,
|
1294 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
1295 |
+
output_attentions: Optional[bool] = None,
|
1296 |
+
output_hidden_states: Optional[bool] = None,
|
1297 |
+
return_dict: Optional[bool] = None,
|
1298 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
1299 |
+
r"""
|
1300 |
+
Returns:
|
1301 |
+
|
1302 |
+
Examples:
|
1303 |
+
|
1304 |
+
```python
|
1305 |
+
>>> from PIL import Image
|
1306 |
+
>>> import requests
|
1307 |
+
>>> from transformers import CLIPProcessor, ChineseCLIPVisionModel
|
1308 |
+
|
1309 |
+
>>> model = ChineseCLIPVisionModel.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
1310 |
+
>>> processor = CLIPProcessor.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
1311 |
+
|
1312 |
+
>>> url = "https://clip-cn-beijing.oss-cn-beijing.aliyuncs.com/pokemon.jpeg"
|
1313 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
1314 |
+
|
1315 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
1316 |
+
|
1317 |
+
>>> outputs = model(**inputs)
|
1318 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
1319 |
+
>>> pooled_output = outputs.pooler_output # pooled CLS states
|
1320 |
+
```"""
|
1321 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1322 |
+
|
1323 |
+
return self.vision_model(
|
1324 |
+
pixel_values=pixel_values,
|
1325 |
+
output_attentions=output_attentions,
|
1326 |
+
output_hidden_states=output_hidden_states,
|
1327 |
+
return_dict=return_dict,
|
1328 |
+
)
|
1329 |
+
|
1330 |
+
|
1331 |
+
@add_start_docstrings(CHINESE_CLIP_START_DOCSTRING)
|
1332 |
+
class ChineseCLIPModel(ChineseCLIPPreTrainedModel):
|
1333 |
+
config_class = ChineseCLIPConfig
|
1334 |
+
|
1335 |
+
def __init__(self, config: ChineseCLIPConfig):
|
1336 |
+
super().__init__(config)
|
1337 |
+
|
1338 |
+
if not isinstance(config.text_config, ChineseCLIPTextConfig):
|
1339 |
+
raise ValueError(
|
1340 |
+
"config.text_config is expected to be of type ChineseCLIPTextConfig but is of type"
|
1341 |
+
f" {type(config.text_config)}."
|
1342 |
+
)
|
1343 |
+
|
1344 |
+
if not isinstance(config.vision_config, ChineseCLIPVisionConfig):
|
1345 |
+
raise ValueError(
|
1346 |
+
"config.vision_config is expected to be of type ChineseCLIPVisionConfig but is of type"
|
1347 |
+
f" {type(config.vision_config)}."
|
1348 |
+
)
|
1349 |
+
|
1350 |
+
text_config = config.text_config
|
1351 |
+
vision_config = config.vision_config
|
1352 |
+
|
1353 |
+
self.projection_dim = config.projection_dim
|
1354 |
+
self.text_embed_dim = text_config.hidden_size
|
1355 |
+
self.vision_embed_dim = vision_config.hidden_size
|
1356 |
+
|
1357 |
+
self.text_model = ChineseCLIPTextModel(text_config, add_pooling_layer=False)
|
1358 |
+
self.vision_model = ChineseCLIPVisionTransformer(vision_config)
|
1359 |
+
|
1360 |
+
self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
|
1361 |
+
self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
|
1362 |
+
self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
|
1363 |
+
|
1364 |
+
# Initialize weights and apply final processing
|
1365 |
+
self.post_init()
|
1366 |
+
|
1367 |
+
@add_start_docstrings_to_model_forward(CHINESE_CLIP_TEXT_INPUTS_DOCSTRING)
|
1368 |
+
def get_text_features(
|
1369 |
+
self,
|
1370 |
+
input_ids: Optional[torch.Tensor] = None,
|
1371 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1372 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
1373 |
+
position_ids: Optional[torch.Tensor] = None,
|
1374 |
+
output_attentions: Optional[bool] = None,
|
1375 |
+
output_hidden_states: Optional[bool] = None,
|
1376 |
+
return_dict: Optional[bool] = None,
|
1377 |
+
) -> torch.FloatTensor:
|
1378 |
+
r"""
|
1379 |
+
Returns:
|
1380 |
+
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
|
1381 |
+
applying the projection layer to the final [CLS] hidden state of Text-Transformer.
|
1382 |
+
|
1383 |
+
Examples:
|
1384 |
+
|
1385 |
+
```python
|
1386 |
+
>>> from transformers import AutoTokenizer, ChineseCLIPModel
|
1387 |
+
|
1388 |
+
>>> model = ChineseCLIPModel.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
1389 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
1390 |
+
|
1391 |
+
>>> inputs = tokenizer(["杰尼龟", "妙蛙种子", "小火龙", "皮卡丘"], padding=True, return_tensors="pt")
|
1392 |
+
>>> text_features = model.get_text_features(**inputs)
|
1393 |
+
>>> text_features = text_features / text_features.norm(p=2, dim=-1, keepdim=True)
|
1394 |
+
```"""
|
1395 |
+
# Use CHINESE_CLIP model's config for some fields (if specified) instead of those of vision & text components.
|
1396 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1397 |
+
output_hidden_states = (
|
1398 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1399 |
+
)
|
1400 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1401 |
+
|
1402 |
+
text_outputs = self.text_model(
|
1403 |
+
input_ids=input_ids,
|
1404 |
+
attention_mask=attention_mask,
|
1405 |
+
token_type_ids=token_type_ids,
|
1406 |
+
position_ids=position_ids,
|
1407 |
+
output_attentions=output_attentions,
|
1408 |
+
output_hidden_states=output_hidden_states,
|
1409 |
+
return_dict=return_dict,
|
1410 |
+
)
|
1411 |
+
|
1412 |
+
pooled_output = text_outputs[0][:, 0, :]
|
1413 |
+
text_features = self.text_projection(pooled_output)
|
1414 |
+
|
1415 |
+
return text_features
|
1416 |
+
|
1417 |
+
@add_start_docstrings_to_model_forward(CHINESE_CLIP_VISION_INPUTS_DOCSTRING)
|
1418 |
+
def get_image_features(
|
1419 |
+
self,
|
1420 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
1421 |
+
output_attentions: Optional[bool] = None,
|
1422 |
+
output_hidden_states: Optional[bool] = None,
|
1423 |
+
return_dict: Optional[bool] = None,
|
1424 |
+
) -> torch.FloatTensor:
|
1425 |
+
r"""
|
1426 |
+
Returns:
|
1427 |
+
image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
|
1428 |
+
applying the projection layer to the final [CLS] hidden state of Vision-Transformer.
|
1429 |
+
|
1430 |
+
Examples:
|
1431 |
+
|
1432 |
+
```python
|
1433 |
+
>>> from PIL import Image
|
1434 |
+
>>> import requests
|
1435 |
+
>>> from transformers import AutoProcessor, ChineseCLIPModel
|
1436 |
+
|
1437 |
+
>>> model = ChineseCLIPModel.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
1438 |
+
>>> processor = AutoProcessor.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
1439 |
+
|
1440 |
+
>>> url = "https://clip-cn-beijing.oss-cn-beijing.aliyuncs.com/pokemon.jpeg"
|
1441 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
1442 |
+
|
1443 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
1444 |
+
|
1445 |
+
>>> image_features = model.get_image_features(**inputs)
|
1446 |
+
>>> image_features = image_features / image_features.norm(p=2, dim=-1, keepdim=True)
|
1447 |
+
```"""
|
1448 |
+
# Use CHINESE_CLIP model's config for some fields (if specified) instead of those of vision & text components.
|
1449 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1450 |
+
output_hidden_states = (
|
1451 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1452 |
+
)
|
1453 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1454 |
+
|
1455 |
+
vision_outputs = self.vision_model(
|
1456 |
+
pixel_values=pixel_values,
|
1457 |
+
output_attentions=output_attentions,
|
1458 |
+
output_hidden_states=output_hidden_states,
|
1459 |
+
return_dict=return_dict,
|
1460 |
+
)
|
1461 |
+
|
1462 |
+
pooled_output = vision_outputs[1] # pooled_output
|
1463 |
+
image_features = self.visual_projection(pooled_output)
|
1464 |
+
|
1465 |
+
return image_features
|
1466 |
+
|
1467 |
+
@add_start_docstrings_to_model_forward(CHINESE_CLIP_INPUTS_DOCSTRING)
|
1468 |
+
@replace_return_docstrings(output_type=ChineseCLIPOutput, config_class=ChineseCLIPConfig)
|
1469 |
+
def forward(
|
1470 |
+
self,
|
1471 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1472 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
1473 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1474 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
1475 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1476 |
+
return_loss: Optional[bool] = None,
|
1477 |
+
output_attentions: Optional[bool] = None,
|
1478 |
+
output_hidden_states: Optional[bool] = None,
|
1479 |
+
return_dict: Optional[bool] = None,
|
1480 |
+
) -> Union[Tuple, ChineseCLIPOutput]:
|
1481 |
+
r"""
|
1482 |
+
Returns:
|
1483 |
+
|
1484 |
+
Examples:
|
1485 |
+
|
1486 |
+
```python
|
1487 |
+
>>> from PIL import Image
|
1488 |
+
>>> import requests
|
1489 |
+
>>> from transformers import AutoProcessor, ChineseCLIPModel
|
1490 |
+
|
1491 |
+
>>> model = ChineseCLIPModel.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
1492 |
+
>>> processor = AutoProcessor.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
1493 |
+
|
1494 |
+
>>> url = "https://clip-cn-beijing.oss-cn-beijing.aliyuncs.com/pokemon.jpeg"
|
1495 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
1496 |
+
|
1497 |
+
>>> inputs = processor(text=["杰尼龟", "妙蛙种子", "小火龙", "皮卡丘"], images=image, return_tensors="pt", padding=True)
|
1498 |
+
|
1499 |
+
>>> outputs = model(**inputs)
|
1500 |
+
>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
|
1501 |
+
>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
|
1502 |
+
```"""
|
1503 |
+
# Use CHINESE_CLIP model's config for some fields (if specified) instead of those of vision & text components.
|
1504 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1505 |
+
output_hidden_states = (
|
1506 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1507 |
+
)
|
1508 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1509 |
+
|
1510 |
+
vision_outputs = self.vision_model(
|
1511 |
+
pixel_values=pixel_values,
|
1512 |
+
output_attentions=output_attentions,
|
1513 |
+
output_hidden_states=output_hidden_states,
|
1514 |
+
return_dict=return_dict,
|
1515 |
+
)
|
1516 |
+
|
1517 |
+
text_outputs = self.text_model(
|
1518 |
+
input_ids=input_ids,
|
1519 |
+
attention_mask=attention_mask,
|
1520 |
+
token_type_ids=token_type_ids,
|
1521 |
+
position_ids=position_ids,
|
1522 |
+
output_attentions=output_attentions,
|
1523 |
+
output_hidden_states=output_hidden_states,
|
1524 |
+
return_dict=return_dict,
|
1525 |
+
)
|
1526 |
+
|
1527 |
+
image_embeds = vision_outputs[1]
|
1528 |
+
image_embeds = self.visual_projection(image_embeds)
|
1529 |
+
|
1530 |
+
text_embeds = text_outputs[0][:, 0, :]
|
1531 |
+
text_embeds = self.text_projection(text_embeds)
|
1532 |
+
|
1533 |
+
# normalized features
|
1534 |
+
image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
|
1535 |
+
text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
|
1536 |
+
|
1537 |
+
# cosine similarity as logits
|
1538 |
+
logit_scale = self.logit_scale.exp()
|
1539 |
+
logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
|
1540 |
+
logits_per_image = logits_per_text.t()
|
1541 |
+
|
1542 |
+
loss = None
|
1543 |
+
if return_loss:
|
1544 |
+
loss = chinese_clip_loss(logits_per_text)
|
1545 |
+
|
1546 |
+
if not return_dict:
|
1547 |
+
# fix the None pooled_output of text_outputs to conform with dict_output
|
1548 |
+
pooled_output = text_outputs[1]
|
1549 |
+
if pooled_output is None:
|
1550 |
+
text_outputs = (text_outputs[0],) + text_outputs[2:]
|
1551 |
+
output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
|
1552 |
+
return ((loss,) + output) if loss is not None else output
|
1553 |
+
|
1554 |
+
return ChineseCLIPOutput(
|
1555 |
+
loss=loss,
|
1556 |
+
logits_per_image=logits_per_image,
|
1557 |
+
logits_per_text=logits_per_text,
|
1558 |
+
text_embeds=text_embeds,
|
1559 |
+
image_embeds=image_embeds,
|
1560 |
+
text_model_output=text_outputs,
|
1561 |
+
vision_model_output=vision_outputs,
|
1562 |
+
)
|
venv/lib/python3.10/site-packages/transformers/models/chinese_clip/processing_chinese_clip.py
ADDED
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 The OFA-Sys Team Authors and The HuggingFace 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 |
+
Image/Text processor class for Chinese-CLIP
|
17 |
+
"""
|
18 |
+
|
19 |
+
import warnings
|
20 |
+
|
21 |
+
from ...processing_utils import ProcessorMixin
|
22 |
+
from ...tokenization_utils_base import BatchEncoding
|
23 |
+
|
24 |
+
|
25 |
+
class ChineseCLIPProcessor(ProcessorMixin):
|
26 |
+
r"""
|
27 |
+
Constructs a Chinese-CLIP processor which wraps a Chinese-CLIP image processor and a Chinese-CLIP tokenizer into a
|
28 |
+
single processor.
|
29 |
+
|
30 |
+
[`ChineseCLIPProcessor`] offers all the functionalities of [`ChineseCLIPImageProcessor`] and [`BertTokenizerFast`].
|
31 |
+
See the [`~ChineseCLIPProcessor.__call__`] and [`~ChineseCLIPProcessor.decode`] for more information.
|
32 |
+
|
33 |
+
Args:
|
34 |
+
image_processor ([`ChineseCLIPImageProcessor`], *optional*):
|
35 |
+
The image processor is a required input.
|
36 |
+
tokenizer ([`BertTokenizerFast`], *optional*):
|
37 |
+
The tokenizer is a required input.
|
38 |
+
"""
|
39 |
+
|
40 |
+
attributes = ["image_processor", "tokenizer"]
|
41 |
+
image_processor_class = "ChineseCLIPImageProcessor"
|
42 |
+
tokenizer_class = ("BertTokenizer", "BertTokenizerFast")
|
43 |
+
|
44 |
+
def __init__(self, image_processor=None, tokenizer=None, **kwargs):
|
45 |
+
feature_extractor = None
|
46 |
+
if "feature_extractor" in kwargs:
|
47 |
+
warnings.warn(
|
48 |
+
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
|
49 |
+
" instead.",
|
50 |
+
FutureWarning,
|
51 |
+
)
|
52 |
+
feature_extractor = kwargs.pop("feature_extractor")
|
53 |
+
|
54 |
+
image_processor = image_processor if image_processor is not None else feature_extractor
|
55 |
+
if image_processor is None:
|
56 |
+
raise ValueError("You need to specify an `image_processor`.")
|
57 |
+
if tokenizer is None:
|
58 |
+
raise ValueError("You need to specify a `tokenizer`.")
|
59 |
+
|
60 |
+
super().__init__(image_processor, tokenizer)
|
61 |
+
self.current_processor = self.image_processor
|
62 |
+
|
63 |
+
def __call__(self, text=None, images=None, return_tensors=None, **kwargs):
|
64 |
+
"""
|
65 |
+
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
|
66 |
+
and `kwargs` arguments to BertTokenizerFast's [`~BertTokenizerFast.__call__`] if `text` is not `None` to encode
|
67 |
+
the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
|
68 |
+
CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
|
69 |
+
of the above two methods for more information.
|
70 |
+
|
71 |
+
Args:
|
72 |
+
text (`str`, `List[str]`, `List[List[str]]`):
|
73 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
74 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
75 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
76 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
77 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
78 |
+
tensor. Both channels-first and channels-last formats are supported.
|
79 |
+
|
80 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
81 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
82 |
+
|
83 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
84 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
85 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
86 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
87 |
+
|
88 |
+
Returns:
|
89 |
+
[`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
|
90 |
+
|
91 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
92 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
93 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
94 |
+
`None`).
|
95 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
96 |
+
"""
|
97 |
+
|
98 |
+
if text is None and images is None:
|
99 |
+
raise ValueError("You have to specify either text or images. Both cannot be none.")
|
100 |
+
|
101 |
+
if text is not None:
|
102 |
+
encoding = self.tokenizer(text, return_tensors=return_tensors, **kwargs)
|
103 |
+
|
104 |
+
if images is not None:
|
105 |
+
image_features = self.image_processor(images, return_tensors=return_tensors, **kwargs)
|
106 |
+
|
107 |
+
if text is not None and images is not None:
|
108 |
+
encoding["pixel_values"] = image_features.pixel_values
|
109 |
+
return encoding
|
110 |
+
elif text is not None:
|
111 |
+
return encoding
|
112 |
+
else:
|
113 |
+
return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors)
|
114 |
+
|
115 |
+
def batch_decode(self, *args, **kwargs):
|
116 |
+
"""
|
117 |
+
This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
|
118 |
+
refer to the docstring of this method for more information.
|
119 |
+
"""
|
120 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
121 |
+
|
122 |
+
def decode(self, *args, **kwargs):
|
123 |
+
"""
|
124 |
+
This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
|
125 |
+
the docstring of this method for more information.
|
126 |
+
"""
|
127 |
+
return self.tokenizer.decode(*args, **kwargs)
|
128 |
+
|
129 |
+
@property
|
130 |
+
def model_input_names(self):
|
131 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
132 |
+
image_processor_input_names = self.image_processor.model_input_names
|
133 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
134 |
+
|
135 |
+
@property
|
136 |
+
def feature_extractor_class(self):
|
137 |
+
warnings.warn(
|
138 |
+
"`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
|
139 |
+
FutureWarning,
|
140 |
+
)
|
141 |
+
return self.image_processor_class
|
venv/lib/python3.10/site-packages/transformers/models/glpn/__pycache__/feature_extraction_glpn.cpython-310.pyc
ADDED
Binary file (997 Bytes). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/regnet/__init__.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 ...utils import (
|
17 |
+
OptionalDependencyNotAvailable,
|
18 |
+
_LazyModule,
|
19 |
+
is_flax_available,
|
20 |
+
is_tf_available,
|
21 |
+
is_torch_available,
|
22 |
+
)
|
23 |
+
|
24 |
+
|
25 |
+
_import_structure = {"configuration_regnet": ["REGNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "RegNetConfig"]}
|
26 |
+
|
27 |
+
try:
|
28 |
+
if not is_torch_available():
|
29 |
+
raise OptionalDependencyNotAvailable()
|
30 |
+
except OptionalDependencyNotAvailable:
|
31 |
+
pass
|
32 |
+
else:
|
33 |
+
_import_structure["modeling_regnet"] = [
|
34 |
+
"REGNET_PRETRAINED_MODEL_ARCHIVE_LIST",
|
35 |
+
"RegNetForImageClassification",
|
36 |
+
"RegNetModel",
|
37 |
+
"RegNetPreTrainedModel",
|
38 |
+
]
|
39 |
+
|
40 |
+
try:
|
41 |
+
if not is_tf_available():
|
42 |
+
raise OptionalDependencyNotAvailable()
|
43 |
+
except OptionalDependencyNotAvailable:
|
44 |
+
pass
|
45 |
+
else:
|
46 |
+
_import_structure["modeling_tf_regnet"] = [
|
47 |
+
"TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST",
|
48 |
+
"TFRegNetForImageClassification",
|
49 |
+
"TFRegNetModel",
|
50 |
+
"TFRegNetPreTrainedModel",
|
51 |
+
]
|
52 |
+
|
53 |
+
try:
|
54 |
+
if not is_flax_available():
|
55 |
+
raise OptionalDependencyNotAvailable()
|
56 |
+
except OptionalDependencyNotAvailable:
|
57 |
+
pass
|
58 |
+
else:
|
59 |
+
_import_structure["modeling_flax_regnet"] = [
|
60 |
+
"FlaxRegNetForImageClassification",
|
61 |
+
"FlaxRegNetModel",
|
62 |
+
"FlaxRegNetPreTrainedModel",
|
63 |
+
]
|
64 |
+
|
65 |
+
|
66 |
+
if TYPE_CHECKING:
|
67 |
+
from .configuration_regnet import REGNET_PRETRAINED_CONFIG_ARCHIVE_MAP, RegNetConfig
|
68 |
+
|
69 |
+
try:
|
70 |
+
if not is_torch_available():
|
71 |
+
raise OptionalDependencyNotAvailable()
|
72 |
+
except OptionalDependencyNotAvailable:
|
73 |
+
pass
|
74 |
+
else:
|
75 |
+
from .modeling_regnet import (
|
76 |
+
REGNET_PRETRAINED_MODEL_ARCHIVE_LIST,
|
77 |
+
RegNetForImageClassification,
|
78 |
+
RegNetModel,
|
79 |
+
RegNetPreTrainedModel,
|
80 |
+
)
|
81 |
+
|
82 |
+
try:
|
83 |
+
if not is_tf_available():
|
84 |
+
raise OptionalDependencyNotAvailable()
|
85 |
+
except OptionalDependencyNotAvailable:
|
86 |
+
pass
|
87 |
+
else:
|
88 |
+
from .modeling_tf_regnet import (
|
89 |
+
TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST,
|
90 |
+
TFRegNetForImageClassification,
|
91 |
+
TFRegNetModel,
|
92 |
+
TFRegNetPreTrainedModel,
|
93 |
+
)
|
94 |
+
|
95 |
+
try:
|
96 |
+
if not is_flax_available():
|
97 |
+
raise OptionalDependencyNotAvailable()
|
98 |
+
except OptionalDependencyNotAvailable:
|
99 |
+
pass
|
100 |
+
else:
|
101 |
+
from .modeling_flax_regnet import (
|
102 |
+
FlaxRegNetForImageClassification,
|
103 |
+
FlaxRegNetModel,
|
104 |
+
FlaxRegNetPreTrainedModel,
|
105 |
+
)
|
106 |
+
|
107 |
+
|
108 |
+
else:
|
109 |
+
import sys
|
110 |
+
|
111 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure)
|
venv/lib/python3.10/site-packages/transformers/models/regnet/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.5 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/regnet/__pycache__/configuration_regnet.cpython-310.pyc
ADDED
Binary file (3.54 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/regnet/__pycache__/convert_regnet_seer_10b_to_pytorch.cpython-310.pyc
ADDED
Binary file (9.51 kB). View file
|
|
venv/lib/python3.10/site-packages/transformers/models/regnet/__pycache__/convert_regnet_to_pytorch.cpython-310.pyc
ADDED
Binary file (15.3 kB). View file
|
|