Stage Harbor release files 87001-87500
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-e0f68dd4420c/environment/source/utils/release.py +206 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/utils/set_cuda_devices_for_ci.py +26 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/utils/slow_documentation_tests.txt +16 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/utils/sort_auto_mappings.py +125 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/utils/split_doctest_jobs.py +91 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/utils/split_model_tests.py +65 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/utils/test_module/__init__.py +0 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/utils/test_module/custom_configuration.py +16 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/utils/test_module/custom_feature_extraction.py +5 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/utils/test_module/custom_image_processing.py +5 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/utils/test_module/custom_modeling.py +33 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/utils/test_module/custom_pipeline.py +33 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/utils/test_module/custom_processing.py +6 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/utils/test_module/custom_tokenization.py +5 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/utils/test_module/custom_tokenization_fast.py +8 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/utils/tests_fetcher.py +1255 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/utils/tf_ops/onnx.json +245 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/utils/update_metadata.py +372 -0
- tasks/tasksmith-e0f68dd4420c/environment/source/utils/update_tiny_models.py +199 -0
- tasks/tasksmith-e0f68dd4420c/instruction.md +15 -0
- tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/__init__.py +0 -0
- tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/models/__init__.py +316 -0
- tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/models/auto/configuration_auto.py +1143 -0
- tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/models/auto/modeling_auto.py +1918 -0
- tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/models/auto/processing_auto.py +380 -0
- tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/models/auto/tokenization_auto.py +1027 -0
- tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/models/aya_vision/__init__.py +28 -0
- tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/models/aya_vision/configuration_aya_vision.py +109 -0
- tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/models/aya_vision/modeling_aya_vision.py +503 -0
- tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/models/aya_vision/processing_aya_vision.py +264 -0
- tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/utils/dummy_pt_objects.py +0 -0
- tasks/tasksmith-e0f68dd4420c/solution/solve.sh +24 -0
- tasks/tasksmith-e0f68dd4420c/task.toml +113 -0
- tasks/tasksmith-e0f68dd4420c/tests/Dockerfile +10 -0
- tasks/tasksmith-e0f68dd4420c/tests/contract.json +0 -0
- tasks/tasksmith-e0f68dd4420c/tests/grade.py +168 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/.circleci/TROUBLESHOOT.md +7 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/.circleci/config.yml +224 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/.circleci/create_circleci_config.py +389 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/.circleci/parse_test_outputs.py +70 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/.gitattributes +4 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml +128 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/.github/ISSUE_TEMPLATE/config.yml +12 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/.github/ISSUE_TEMPLATE/feature-request.yml +31 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/.github/ISSUE_TEMPLATE/i18n.md +46 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/.github/ISSUE_TEMPLATE/migration.yml +72 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/.github/ISSUE_TEMPLATE/new-model-addition.yml +31 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/.github/PULL_REQUEST_TEMPLATE.md +79 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/.github/conda/build.sh +1 -0
- tasks/tasksmith-e0f68dd4420c/tests/source/.github/conda/meta.yaml +56 -0
tasks/tasksmith-e0f68dd4420c/environment/source/utils/release.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 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 |
+
Utility that prepares the repository for releases (or patches) by updating all versions in the relevant places. It
|
| 17 |
+
also performs some post-release cleanup, by updating the links in the main README to respective model doc pages (from
|
| 18 |
+
main to stable).
|
| 19 |
+
|
| 20 |
+
To prepare for a release, use from the root of the repo on the release branch with:
|
| 21 |
+
|
| 22 |
+
```bash
|
| 23 |
+
python release.py
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
or use `make pre-release`.
|
| 27 |
+
|
| 28 |
+
To prepare for a patch release, use from the root of the repo on the release branch with:
|
| 29 |
+
|
| 30 |
+
```bash
|
| 31 |
+
python release.py --patch
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
or use `make pre-patch`.
|
| 35 |
+
|
| 36 |
+
To do the post-release cleanup, use from the root of the repo on the main branch with:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
python release.py --post_release
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
or use `make post-release`.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
import argparse
|
| 46 |
+
import os
|
| 47 |
+
import re
|
| 48 |
+
from pathlib import Path
|
| 49 |
+
|
| 50 |
+
import packaging.version
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# All paths are defined with the intent that this script should be run from the root of the repo.
|
| 54 |
+
PATH_TO_EXAMPLES = "examples/"
|
| 55 |
+
PATH_TO_MODELS = "src/transformers/models"
|
| 56 |
+
# This maps a type of file to the pattern to look for when searching where the version is defined, as well as the
|
| 57 |
+
# template to follow when replacing it with the new version.
|
| 58 |
+
REPLACE_PATTERNS = {
|
| 59 |
+
"examples": (re.compile(r'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'),
|
| 60 |
+
"init": (re.compile(r'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTILINE), '__version__ = "VERSION"\n'),
|
| 61 |
+
"setup": (re.compile(r'^(\s*)version\s*=\s*"[^"]+",', re.MULTILINE), r'\1version="VERSION",'),
|
| 62 |
+
}
|
| 63 |
+
# This maps a type of file to its path in Transformers
|
| 64 |
+
REPLACE_FILES = {
|
| 65 |
+
"init": "src/transformers/__init__.py",
|
| 66 |
+
"setup": "setup.py",
|
| 67 |
+
}
|
| 68 |
+
README_FILE = "README.md"
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def update_version_in_file(fname: str, version: str, file_type: str):
|
| 72 |
+
"""
|
| 73 |
+
Update the version of Transformers in one file.
|
| 74 |
+
|
| 75 |
+
Args:
|
| 76 |
+
fname (`str`): The path to the file where we want to update the version.
|
| 77 |
+
version (`str`): The new version to set in the file.
|
| 78 |
+
file_type (`str`): The type of the file (should be a key in `REPLACE_PATTERNS`).
|
| 79 |
+
"""
|
| 80 |
+
with open(fname, "r", encoding="utf-8", newline="\n") as f:
|
| 81 |
+
code = f.read()
|
| 82 |
+
re_pattern, replace = REPLACE_PATTERNS[file_type]
|
| 83 |
+
replace = replace.replace("VERSION", version)
|
| 84 |
+
code = re_pattern.sub(replace, code)
|
| 85 |
+
with open(fname, "w", encoding="utf-8", newline="\n") as f:
|
| 86 |
+
f.write(code)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def update_version_in_examples(version: str):
|
| 90 |
+
"""
|
| 91 |
+
Update the version in all examples files.
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
version (`str`): The new version to set in the examples.
|
| 95 |
+
"""
|
| 96 |
+
for folder, directories, fnames in os.walk(PATH_TO_EXAMPLES):
|
| 97 |
+
# Removing some of the folders with non-actively maintained examples from the walk
|
| 98 |
+
if "research_projects" in directories:
|
| 99 |
+
directories.remove("research_projects")
|
| 100 |
+
if "legacy" in directories:
|
| 101 |
+
directories.remove("legacy")
|
| 102 |
+
for fname in fnames:
|
| 103 |
+
if fname.endswith(".py"):
|
| 104 |
+
update_version_in_file(os.path.join(folder, fname), version, file_type="examples")
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def global_version_update(version: str, patch: bool = False):
|
| 108 |
+
"""
|
| 109 |
+
Update the version in all needed files.
|
| 110 |
+
|
| 111 |
+
Args:
|
| 112 |
+
version (`str`): The new version to set everywhere.
|
| 113 |
+
patch (`bool`, *optional*, defaults to `False`): Whether or not this is a patch release.
|
| 114 |
+
"""
|
| 115 |
+
for pattern, fname in REPLACE_FILES.items():
|
| 116 |
+
update_version_in_file(fname, version, pattern)
|
| 117 |
+
if not patch:
|
| 118 |
+
# We don't update the version in the examples for patch releases.
|
| 119 |
+
update_version_in_examples(version)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def remove_conversion_scripts():
|
| 123 |
+
"""
|
| 124 |
+
Delete the scripts that convert models from older, unsupported formats. We don't want to include these
|
| 125 |
+
in release wheels because they often have to open insecure file types (pickle, Torch .bin models). This results in
|
| 126 |
+
vulnerability scanners flagging us and can cause compliance issues for users with strict security policies.
|
| 127 |
+
"""
|
| 128 |
+
model_dir = Path(PATH_TO_MODELS)
|
| 129 |
+
for conversion_script in list(model_dir.glob("**/convert*.py")):
|
| 130 |
+
conversion_script.unlink()
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def get_version() -> packaging.version.Version:
|
| 134 |
+
"""
|
| 135 |
+
Reads the current version in the main __init__.
|
| 136 |
+
"""
|
| 137 |
+
with open(REPLACE_FILES["init"], "r") as f:
|
| 138 |
+
code = f.read()
|
| 139 |
+
default_version = REPLACE_PATTERNS["init"][0].search(code).groups()[0]
|
| 140 |
+
return packaging.version.parse(default_version)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def pre_release_work(patch: bool = False):
|
| 144 |
+
"""
|
| 145 |
+
Do all the necessary pre-release steps:
|
| 146 |
+
- figure out the next minor release version and ask confirmation
|
| 147 |
+
- update the version everywhere
|
| 148 |
+
- clean-up the model list in the main README
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
patch (`bool`, *optional*, defaults to `False`): Whether or not this is a patch release.
|
| 152 |
+
"""
|
| 153 |
+
# First let's get the default version: base version if we are in dev, bump minor otherwise.
|
| 154 |
+
default_version = get_version()
|
| 155 |
+
if patch and default_version.is_devrelease:
|
| 156 |
+
raise ValueError("Can't create a patch version from the dev branch, checkout a released version!")
|
| 157 |
+
if default_version.is_devrelease:
|
| 158 |
+
default_version = default_version.base_version
|
| 159 |
+
elif patch:
|
| 160 |
+
default_version = f"{default_version.major}.{default_version.minor}.{default_version.micro + 1}"
|
| 161 |
+
else:
|
| 162 |
+
default_version = f"{default_version.major}.{default_version.minor + 1}.0"
|
| 163 |
+
|
| 164 |
+
# Now let's ask nicely if we have found the right version.
|
| 165 |
+
version = input(f"Which version are you releasing? [{default_version}]")
|
| 166 |
+
if len(version) == 0:
|
| 167 |
+
version = default_version
|
| 168 |
+
|
| 169 |
+
print(f"Updating version to {version}.")
|
| 170 |
+
global_version_update(version, patch=patch)
|
| 171 |
+
print("Deleting conversion scripts.")
|
| 172 |
+
remove_conversion_scripts()
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def post_release_work():
|
| 176 |
+
"""
|
| 177 |
+
Do all the necessary post-release steps:
|
| 178 |
+
- figure out the next dev version and ask confirmation
|
| 179 |
+
- update the version everywhere
|
| 180 |
+
- clean-up the model list in the main README
|
| 181 |
+
"""
|
| 182 |
+
# First let's get the current version
|
| 183 |
+
current_version = get_version()
|
| 184 |
+
dev_version = f"{current_version.major}.{current_version.minor + 1}.0.dev0"
|
| 185 |
+
current_version = current_version.base_version
|
| 186 |
+
|
| 187 |
+
# Check with the user we got that right.
|
| 188 |
+
version = input(f"Which version are we developing now? [{dev_version}]")
|
| 189 |
+
if len(version) == 0:
|
| 190 |
+
version = dev_version
|
| 191 |
+
|
| 192 |
+
print(f"Updating version to {version}.")
|
| 193 |
+
global_version_update(version)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
if __name__ == "__main__":
|
| 197 |
+
parser = argparse.ArgumentParser()
|
| 198 |
+
parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.")
|
| 199 |
+
parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.")
|
| 200 |
+
args = parser.parse_args()
|
| 201 |
+
if not args.post_release:
|
| 202 |
+
pre_release_work(patch=args.patch)
|
| 203 |
+
elif args.patch:
|
| 204 |
+
print("Nothing to do after a patch :-)")
|
| 205 |
+
else:
|
| 206 |
+
post_release_work()
|
tasks/tasksmith-e0f68dd4420c/environment/source/utils/set_cuda_devices_for_ci.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A simple script to set flexibly CUDA_VISIBLE_DEVICES in GitHub Actions CI workflow files."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
if __name__ == "__main__":
|
| 8 |
+
parser = argparse.ArgumentParser()
|
| 9 |
+
parser.add_argument(
|
| 10 |
+
"--test_folder",
|
| 11 |
+
type=str,
|
| 12 |
+
default=None,
|
| 13 |
+
help="The test folder name of the model being tested. For example, `models/cohere`.",
|
| 14 |
+
)
|
| 15 |
+
args = parser.parse_args()
|
| 16 |
+
|
| 17 |
+
# `test_eager_matches_sdpa_generate` for `cohere` needs a lot of GPU memory!
|
| 18 |
+
# This depends on the runners. At this moment we are targeting our AWS CI runners.
|
| 19 |
+
if args.test_folder == "models/cohere":
|
| 20 |
+
cuda_visible_devices = "0,1,2,3"
|
| 21 |
+
elif "CUDA_VISIBLE_DEVICES" in os.environ:
|
| 22 |
+
cuda_visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES")
|
| 23 |
+
else:
|
| 24 |
+
cuda_visible_devices = "0"
|
| 25 |
+
|
| 26 |
+
print(cuda_visible_devices)
|
tasks/tasksmith-e0f68dd4420c/environment/source/utils/slow_documentation_tests.txt
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
docs/source/en/generation_strategies.md
|
| 2 |
+
docs/source/en/model_doc/code_llama.md
|
| 3 |
+
docs/source/en/model_doc/ctrl.md
|
| 4 |
+
docs/source/en/model_doc/kosmos-2.md
|
| 5 |
+
docs/source/en/model_doc/seamless_m4t.md
|
| 6 |
+
docs/source/en/model_doc/seamless_m4t_v2.md
|
| 7 |
+
docs/source/en/task_summary.md
|
| 8 |
+
docs/source/en/tasks/prompting.md
|
| 9 |
+
docs/source/ja/model_doc/code_llama.md
|
| 10 |
+
src/transformers/models/blip_2/modeling_blip_2.py
|
| 11 |
+
src/transformers/models/ctrl/modeling_ctrl.py
|
| 12 |
+
src/transformers/models/fuyu/modeling_fuyu.py
|
| 13 |
+
src/transformers/models/idefics2/modeling_idefics2.py
|
| 14 |
+
src/transformers/models/kosmos2/modeling_kosmos2.py
|
| 15 |
+
src/transformers/models/musicgen_melody/modeling_musicgen_melody.py
|
| 16 |
+
src/transformers/models/musicgen_melody/processing_musicgen_melody.py
|
tasks/tasksmith-e0f68dd4420c/environment/source/utils/sort_auto_mappings.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Utility that sorts the names in the auto mappings defines in the auto modules in alphabetical order.
|
| 17 |
+
|
| 18 |
+
Use from the root of the repo with:
|
| 19 |
+
|
| 20 |
+
```bash
|
| 21 |
+
python utils/sort_auto_mappings.py
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
to auto-fix all the auto mappings (used in `make style`).
|
| 25 |
+
|
| 26 |
+
To only check if the mappings are properly sorted (as used in `make quality`), do:
|
| 27 |
+
|
| 28 |
+
```bash
|
| 29 |
+
python utils/sort_auto_mappings.py --check_only
|
| 30 |
+
```
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
import argparse
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
from typing import Optional
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# Path are set with the intent you should run this script from the root of the repo.
|
| 40 |
+
PATH_TO_AUTO_MODULE = "src/transformers/models/auto"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# re pattern that matches mapping introductions:
|
| 44 |
+
# SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict
|
| 45 |
+
_re_intro_mapping = re.compile(r"[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict")
|
| 46 |
+
# re pattern that matches identifiers in mappings
|
| 47 |
+
_re_identifier = re.compile(r'\s*\(\s*"(\S[^"]+)"')
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def sort_auto_mapping(fname: str, overwrite: bool = False) -> Optional[bool]:
|
| 51 |
+
"""
|
| 52 |
+
Sort all auto mappings in a file.
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
fname (`str`): The name of the file where we want to sort auto-mappings.
|
| 56 |
+
overwrite (`bool`, *optional*, defaults to `False`): Whether or not to fix and overwrite the file.
|
| 57 |
+
|
| 58 |
+
Returns:
|
| 59 |
+
`Optional[bool]`: Returns `None` if `overwrite=True`. Otherwise returns `True` if the file has an auto-mapping
|
| 60 |
+
improperly sorted, `False` if the file is okay.
|
| 61 |
+
"""
|
| 62 |
+
with open(fname, "r", encoding="utf-8") as f:
|
| 63 |
+
content = f.read()
|
| 64 |
+
|
| 65 |
+
lines = content.split("\n")
|
| 66 |
+
new_lines = []
|
| 67 |
+
line_idx = 0
|
| 68 |
+
while line_idx < len(lines):
|
| 69 |
+
if _re_intro_mapping.search(lines[line_idx]) is not None:
|
| 70 |
+
# Start of a new mapping!
|
| 71 |
+
indent = len(re.search(r"^(\s*)\S", lines[line_idx]).groups()[0]) + 8
|
| 72 |
+
while not lines[line_idx].startswith(" " * indent + "("):
|
| 73 |
+
new_lines.append(lines[line_idx])
|
| 74 |
+
line_idx += 1
|
| 75 |
+
|
| 76 |
+
blocks = []
|
| 77 |
+
while lines[line_idx].strip() != "]":
|
| 78 |
+
# Blocks either fit in one line or not
|
| 79 |
+
if lines[line_idx].strip() == "(":
|
| 80 |
+
start_idx = line_idx
|
| 81 |
+
while not lines[line_idx].startswith(" " * indent + ")"):
|
| 82 |
+
line_idx += 1
|
| 83 |
+
blocks.append("\n".join(lines[start_idx : line_idx + 1]))
|
| 84 |
+
else:
|
| 85 |
+
blocks.append(lines[line_idx])
|
| 86 |
+
line_idx += 1
|
| 87 |
+
|
| 88 |
+
# Sort blocks by their identifiers
|
| 89 |
+
blocks = sorted(blocks, key=lambda x: _re_identifier.search(x).groups()[0])
|
| 90 |
+
new_lines += blocks
|
| 91 |
+
else:
|
| 92 |
+
new_lines.append(lines[line_idx])
|
| 93 |
+
line_idx += 1
|
| 94 |
+
|
| 95 |
+
if overwrite:
|
| 96 |
+
with open(fname, "w", encoding="utf-8") as f:
|
| 97 |
+
f.write("\n".join(new_lines))
|
| 98 |
+
else:
|
| 99 |
+
return "\n".join(new_lines) != content
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def sort_all_auto_mappings(overwrite: bool = False):
|
| 103 |
+
"""
|
| 104 |
+
Sort all auto mappings in the library.
|
| 105 |
+
|
| 106 |
+
Args:
|
| 107 |
+
overwrite (`bool`, *optional*, defaults to `False`): Whether or not to fix and overwrite the file.
|
| 108 |
+
"""
|
| 109 |
+
fnames = [os.path.join(PATH_TO_AUTO_MODULE, f) for f in os.listdir(PATH_TO_AUTO_MODULE) if f.endswith(".py")]
|
| 110 |
+
diffs = [sort_auto_mapping(fname, overwrite=overwrite) for fname in fnames]
|
| 111 |
+
|
| 112 |
+
if not overwrite and any(diffs):
|
| 113 |
+
failures = [f for f, d in zip(fnames, diffs) if d]
|
| 114 |
+
raise ValueError(
|
| 115 |
+
f"The following files have auto mappings that need sorting: {', '.join(failures)}. Run `make style` to fix"
|
| 116 |
+
" this."
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
if __name__ == "__main__":
|
| 121 |
+
parser = argparse.ArgumentParser()
|
| 122 |
+
parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.")
|
| 123 |
+
args = parser.parse_args()
|
| 124 |
+
|
| 125 |
+
sort_all_auto_mappings(not args.check_only)
|
tasks/tasksmith-e0f68dd4420c/environment/source/utils/split_doctest_jobs.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""
|
| 16 |
+
This script is used to get the files against which we will run doc testing.
|
| 17 |
+
This uses `tests_fetcher.get_all_doctest_files` then groups the test files by their directory paths.
|
| 18 |
+
|
| 19 |
+
The files in `docs/source/en/model_doc` or `docs/source/en/tasks` are **NOT** grouped together with other files in the
|
| 20 |
+
same directory: the objective is to run doctest against them in independent GitHub Actions jobs.
|
| 21 |
+
|
| 22 |
+
Assume we are under `transformers` root directory:
|
| 23 |
+
To get a map (dictionary) between directory (or file) paths and the corresponding files
|
| 24 |
+
```bash
|
| 25 |
+
python utils/split_doctest_jobs.py
|
| 26 |
+
```
|
| 27 |
+
or to get a list of lists of directory (or file) paths
|
| 28 |
+
```bash
|
| 29 |
+
python utils/split_doctest_jobs.py --only_return_keys --num_splits 4
|
| 30 |
+
```
|
| 31 |
+
(this is used to allow GitHub Actions to generate more than 256 jobs using matrix)
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
import argparse
|
| 35 |
+
from collections import defaultdict
|
| 36 |
+
from pathlib import Path
|
| 37 |
+
|
| 38 |
+
from tests_fetcher import get_all_doctest_files
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
if __name__ == "__main__":
|
| 42 |
+
parser = argparse.ArgumentParser()
|
| 43 |
+
parser.add_argument(
|
| 44 |
+
"--only_return_keys",
|
| 45 |
+
action="store_true",
|
| 46 |
+
help="if to only return the keys (which is a list of list of files' directory or file paths).",
|
| 47 |
+
)
|
| 48 |
+
parser.add_argument(
|
| 49 |
+
"--num_splits",
|
| 50 |
+
type=int,
|
| 51 |
+
default=1,
|
| 52 |
+
help="the number of splits into which the (flat) list of direcotry/file paths will be split. This has effect only if `only_return_keys` is `True`.",
|
| 53 |
+
)
|
| 54 |
+
args = parser.parse_args()
|
| 55 |
+
|
| 56 |
+
all_doctest_files = get_all_doctest_files()
|
| 57 |
+
|
| 58 |
+
raw_test_collection_map = defaultdict(list)
|
| 59 |
+
|
| 60 |
+
for file in all_doctest_files:
|
| 61 |
+
file_dir = "/".join(Path(file).parents[0].parts)
|
| 62 |
+
raw_test_collection_map[file_dir].append(file)
|
| 63 |
+
|
| 64 |
+
refined_test_collection_map = {}
|
| 65 |
+
for file_dir in raw_test_collection_map.keys():
|
| 66 |
+
if file_dir in ["docs/source/en/model_doc", "docs/source/en/tasks"]:
|
| 67 |
+
for file in raw_test_collection_map[file_dir]:
|
| 68 |
+
refined_test_collection_map[file] = file
|
| 69 |
+
else:
|
| 70 |
+
refined_test_collection_map[file_dir] = " ".join(sorted(raw_test_collection_map[file_dir]))
|
| 71 |
+
|
| 72 |
+
sorted_file_dirs = sorted(refined_test_collection_map.keys())
|
| 73 |
+
|
| 74 |
+
test_collection_map = {}
|
| 75 |
+
for file_dir in sorted_file_dirs:
|
| 76 |
+
test_collection_map[file_dir] = refined_test_collection_map[file_dir]
|
| 77 |
+
|
| 78 |
+
num_jobs = len(test_collection_map)
|
| 79 |
+
num_jobs_per_splits = num_jobs // args.num_splits
|
| 80 |
+
|
| 81 |
+
file_directory_splits = []
|
| 82 |
+
end = 0
|
| 83 |
+
for idx in range(args.num_splits):
|
| 84 |
+
start = end
|
| 85 |
+
end = start + num_jobs_per_splits + (1 if idx < num_jobs % args.num_splits else 0)
|
| 86 |
+
file_directory_splits.append(sorted_file_dirs[start:end])
|
| 87 |
+
|
| 88 |
+
if args.only_return_keys:
|
| 89 |
+
print(file_directory_splits)
|
| 90 |
+
else:
|
| 91 |
+
print(dict(test_collection_map))
|
tasks/tasksmith-e0f68dd4420c/environment/source/utils/split_model_tests.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""
|
| 16 |
+
This script is used to get the list of folders under `tests/models` and split the list into `NUM_SLICES` splits.
|
| 17 |
+
The main use case is a GitHub Actions workflow file calling this script to get the (nested) list of folders allowing it
|
| 18 |
+
to split the list of jobs to run into multiple slices each containing a smaller number of jobs. This way, we can bypass
|
| 19 |
+
the maximum of 256 jobs in a matrix.
|
| 20 |
+
|
| 21 |
+
See the `setup` and `run_models_gpu` jobs defined in the workflow file `.github/workflows/self-scheduled.yml` for more
|
| 22 |
+
details.
|
| 23 |
+
|
| 24 |
+
Usage:
|
| 25 |
+
|
| 26 |
+
This script is required to be run under `tests` folder of `transformers` root directory.
|
| 27 |
+
|
| 28 |
+
Assume we are under `transformers` root directory:
|
| 29 |
+
```bash
|
| 30 |
+
cd tests
|
| 31 |
+
python ../utils/split_model_tests.py --num_splits 64
|
| 32 |
+
```
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
import argparse
|
| 36 |
+
import os
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
if __name__ == "__main__":
|
| 40 |
+
parser = argparse.ArgumentParser()
|
| 41 |
+
parser.add_argument(
|
| 42 |
+
"--num_splits",
|
| 43 |
+
type=int,
|
| 44 |
+
default=1,
|
| 45 |
+
help="the number of splits into which the (flat) list of folders will be split.",
|
| 46 |
+
)
|
| 47 |
+
args = parser.parse_args()
|
| 48 |
+
|
| 49 |
+
tests = os.getcwd()
|
| 50 |
+
model_tests = os.listdir(os.path.join(tests, "models"))
|
| 51 |
+
d1 = sorted(filter(os.path.isdir, os.listdir(tests)))
|
| 52 |
+
d2 = sorted(filter(os.path.isdir, [f"models/{x}" for x in model_tests]))
|
| 53 |
+
d1.remove("models")
|
| 54 |
+
d = d2 + d1
|
| 55 |
+
|
| 56 |
+
num_jobs = len(d)
|
| 57 |
+
num_jobs_per_splits = num_jobs // args.num_splits
|
| 58 |
+
|
| 59 |
+
model_splits = []
|
| 60 |
+
end = 0
|
| 61 |
+
for idx in range(args.num_splits):
|
| 62 |
+
start = end
|
| 63 |
+
end = start + num_jobs_per_splits + (1 if idx < num_jobs % args.num_splits else 0)
|
| 64 |
+
model_splits.append(d[start:end])
|
| 65 |
+
print(model_splits)
|
tasks/tasksmith-e0f68dd4420c/environment/source/utils/test_module/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-e0f68dd4420c/environment/source/utils/test_module/custom_configuration.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class CustomConfig(PretrainedConfig):
|
| 5 |
+
model_type = "custom"
|
| 6 |
+
|
| 7 |
+
def __init__(self, attribute=1, **kwargs):
|
| 8 |
+
self.attribute = attribute
|
| 9 |
+
super().__init__(**kwargs)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class NoSuperInitConfig(PretrainedConfig):
|
| 13 |
+
model_type = "custom"
|
| 14 |
+
|
| 15 |
+
def __init__(self, attribute=1, **kwargs):
|
| 16 |
+
self.attribute = attribute
|
tasks/tasksmith-e0f68dd4420c/environment/source/utils/test_module/custom_feature_extraction.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import Wav2Vec2FeatureExtractor
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class CustomFeatureExtractor(Wav2Vec2FeatureExtractor):
|
| 5 |
+
pass
|
tasks/tasksmith-e0f68dd4420c/environment/source/utils/test_module/custom_image_processing.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import CLIPImageProcessor
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class CustomImageProcessor(CLIPImageProcessor):
|
| 5 |
+
pass
|
tasks/tasksmith-e0f68dd4420c/environment/source/utils/test_module/custom_modeling.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
from transformers import PreTrainedModel
|
| 4 |
+
|
| 5 |
+
from .custom_configuration import CustomConfig, NoSuperInitConfig
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class CustomModel(PreTrainedModel):
|
| 9 |
+
config_class = CustomConfig
|
| 10 |
+
|
| 11 |
+
def __init__(self, config):
|
| 12 |
+
super().__init__(config)
|
| 13 |
+
self.linear = torch.nn.Linear(config.hidden_size, config.hidden_size)
|
| 14 |
+
|
| 15 |
+
def forward(self, x):
|
| 16 |
+
return self.linear(x)
|
| 17 |
+
|
| 18 |
+
def _init_weights(self, module):
|
| 19 |
+
pass
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class NoSuperInitModel(PreTrainedModel):
|
| 23 |
+
config_class = NoSuperInitConfig
|
| 24 |
+
|
| 25 |
+
def __init__(self, config):
|
| 26 |
+
super().__init__(config)
|
| 27 |
+
self.linear = torch.nn.Linear(config.attribute, config.attribute)
|
| 28 |
+
|
| 29 |
+
def forward(self, x):
|
| 30 |
+
return self.linear(x)
|
| 31 |
+
|
| 32 |
+
def _init_weights(self, module):
|
| 33 |
+
pass
|
tasks/tasksmith-e0f68dd4420c/environment/source/utils/test_module/custom_pipeline.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
from transformers import Pipeline
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def softmax(outputs):
|
| 7 |
+
maxes = np.max(outputs, axis=-1, keepdims=True)
|
| 8 |
+
shifted_exp = np.exp(outputs - maxes)
|
| 9 |
+
return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class PairClassificationPipeline(Pipeline):
|
| 13 |
+
def _sanitize_parameters(self, **kwargs):
|
| 14 |
+
preprocess_kwargs = {}
|
| 15 |
+
if "second_text" in kwargs:
|
| 16 |
+
preprocess_kwargs["second_text"] = kwargs["second_text"]
|
| 17 |
+
return preprocess_kwargs, {}, {}
|
| 18 |
+
|
| 19 |
+
def preprocess(self, text, second_text=None):
|
| 20 |
+
return self.tokenizer(text, text_pair=second_text, return_tensors=self.framework)
|
| 21 |
+
|
| 22 |
+
def _forward(self, model_inputs):
|
| 23 |
+
return self.model(**model_inputs)
|
| 24 |
+
|
| 25 |
+
def postprocess(self, model_outputs):
|
| 26 |
+
logits = model_outputs.logits[0].numpy()
|
| 27 |
+
probabilities = softmax(logits)
|
| 28 |
+
|
| 29 |
+
best_class = np.argmax(probabilities)
|
| 30 |
+
label = self.model.config.id2label[best_class]
|
| 31 |
+
score = probabilities[best_class].item()
|
| 32 |
+
logits = logits.tolist()
|
| 33 |
+
return {"label": label, "score": score, "logits": logits}
|
tasks/tasksmith-e0f68dd4420c/environment/source/utils/test_module/custom_processing.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import ProcessorMixin
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class CustomProcessor(ProcessorMixin):
|
| 5 |
+
feature_extractor_class = "AutoFeatureExtractor"
|
| 6 |
+
tokenizer_class = "AutoTokenizer"
|
tasks/tasksmith-e0f68dd4420c/environment/source/utils/test_module/custom_tokenization.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import BertTokenizer
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class CustomTokenizer(BertTokenizer):
|
| 5 |
+
pass
|
tasks/tasksmith-e0f68dd4420c/environment/source/utils/test_module/custom_tokenization_fast.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import BertTokenizerFast
|
| 2 |
+
|
| 3 |
+
from .custom_tokenization import CustomTokenizer
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class CustomTokenizerFast(BertTokenizerFast):
|
| 7 |
+
slow_tokenizer_class = CustomTokenizer
|
| 8 |
+
pass
|
tasks/tasksmith-e0f68dd4420c/environment/source/utils/tests_fetcher.py
ADDED
|
@@ -0,0 +1,1255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
"""
|
| 17 |
+
Welcome to tests_fetcher V2.
|
| 18 |
+
|
| 19 |
+
This util is designed to fetch tests to run on a PR so that only the tests impacted by the modifications are run, and
|
| 20 |
+
when too many models are being impacted, only run the tests of a subset of core models. It works like this.
|
| 21 |
+
|
| 22 |
+
Stage 1: Identify the modified files. For jobs that run on the main branch, it's just the diff with the last commit.
|
| 23 |
+
On a PR, this takes all the files from the branching point to the current commit (so all modifications in a PR, not
|
| 24 |
+
just the last commit) but excludes modifications that are on docstrings or comments only.
|
| 25 |
+
|
| 26 |
+
Stage 2: Extract the tests to run. This is done by looking at the imports in each module and test file: if module A
|
| 27 |
+
imports module B, then changing module B impacts module A, so the tests using module A should be run. We thus get the
|
| 28 |
+
dependencies of each model and then recursively builds the 'reverse' map of dependencies to get all modules and tests
|
| 29 |
+
impacted by a given file. We then only keep the tests (and only the core models tests if there are too many modules).
|
| 30 |
+
|
| 31 |
+
Caveats:
|
| 32 |
+
- This module only filters tests by files (not individual tests) so it's better to have tests for different things
|
| 33 |
+
in different files.
|
| 34 |
+
- This module assumes inits are just importing things, not really building objects, so it's better to structure
|
| 35 |
+
them this way and move objects building in separate submodules.
|
| 36 |
+
|
| 37 |
+
Usage:
|
| 38 |
+
|
| 39 |
+
Base use to fetch the tests in a pull request
|
| 40 |
+
|
| 41 |
+
```bash
|
| 42 |
+
python utils/tests_fetcher.py
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
Base use to fetch the tests on a the main branch (with diff from the last commit):
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
python utils/tests_fetcher.py --diff_with_last_commit
|
| 49 |
+
```
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
import argparse
|
| 53 |
+
import collections
|
| 54 |
+
import glob
|
| 55 |
+
import importlib.util
|
| 56 |
+
import json
|
| 57 |
+
import os
|
| 58 |
+
import re
|
| 59 |
+
import tempfile
|
| 60 |
+
from contextlib import contextmanager
|
| 61 |
+
from pathlib import Path
|
| 62 |
+
from typing import Dict, List, Tuple, Union
|
| 63 |
+
|
| 64 |
+
from git import Repo
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
PATH_TO_REPO = Path(__file__).parent.parent.resolve()
|
| 68 |
+
PATH_TO_EXAMPLES = PATH_TO_REPO / "examples"
|
| 69 |
+
PATH_TO_TRANFORMERS = PATH_TO_REPO / "src/transformers"
|
| 70 |
+
PATH_TO_TESTS = PATH_TO_REPO / "tests"
|
| 71 |
+
|
| 72 |
+
# The value is just a heuristic to determine if we `guess` all models are impacted.
|
| 73 |
+
# This variable has effect only if `filter_models=False`.
|
| 74 |
+
NUM_MODELS_TO_TRIGGER_FULL_CI = 30
|
| 75 |
+
|
| 76 |
+
# List here the models to always test.
|
| 77 |
+
IMPORTANT_MODELS = [
|
| 78 |
+
"auto",
|
| 79 |
+
# Most downloaded models
|
| 80 |
+
"bert",
|
| 81 |
+
"clip",
|
| 82 |
+
"t5",
|
| 83 |
+
"xlm-roberta",
|
| 84 |
+
"gpt2",
|
| 85 |
+
"bart",
|
| 86 |
+
"mpnet",
|
| 87 |
+
"gpt-j",
|
| 88 |
+
"wav2vec2",
|
| 89 |
+
"deberta-v2",
|
| 90 |
+
"layoutlm",
|
| 91 |
+
"llama",
|
| 92 |
+
"opt",
|
| 93 |
+
"longformer",
|
| 94 |
+
"vit",
|
| 95 |
+
"whisper",
|
| 96 |
+
# Pipeline-specific model (to be sure each pipeline has one model in this list)
|
| 97 |
+
"tapas",
|
| 98 |
+
"vilt",
|
| 99 |
+
"clap",
|
| 100 |
+
"detr",
|
| 101 |
+
"owlvit",
|
| 102 |
+
"dpt",
|
| 103 |
+
"videomae",
|
| 104 |
+
]
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@contextmanager
|
| 108 |
+
def checkout_commit(repo: Repo, commit_id: str):
|
| 109 |
+
"""
|
| 110 |
+
Context manager that checks out a given commit when entered, but gets back to the reference it was at on exit.
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
repo (`git.Repo`): A git repository (for instance the Transformers repo).
|
| 114 |
+
commit_id (`str`): The commit reference to checkout inside the context manager.
|
| 115 |
+
"""
|
| 116 |
+
current_head = repo.head.commit if repo.head.is_detached else repo.head.ref
|
| 117 |
+
|
| 118 |
+
try:
|
| 119 |
+
repo.git.checkout(commit_id)
|
| 120 |
+
yield
|
| 121 |
+
|
| 122 |
+
finally:
|
| 123 |
+
repo.git.checkout(current_head)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def clean_code(content: str) -> str:
|
| 127 |
+
"""
|
| 128 |
+
Remove docstrings, empty line or comments from some code (used to detect if a diff is real or only concern
|
| 129 |
+
comments or docstings).
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
content (`str`): The code to clean
|
| 133 |
+
|
| 134 |
+
Returns:
|
| 135 |
+
`str`: The cleaned code.
|
| 136 |
+
"""
|
| 137 |
+
# We need to deactivate autoformatting here to write escaped triple quotes (we cannot use real triple quotes or
|
| 138 |
+
# this would mess up the result if this function applied to this particular file).
|
| 139 |
+
# fmt: off
|
| 140 |
+
# Remove docstrings by splitting on triple " then triple ':
|
| 141 |
+
splits = content.split('\"\"\"')
|
| 142 |
+
content = "".join(splits[::2])
|
| 143 |
+
splits = content.split("\'\'\'")
|
| 144 |
+
# fmt: on
|
| 145 |
+
content = "".join(splits[::2])
|
| 146 |
+
|
| 147 |
+
# Remove empty lines and comments
|
| 148 |
+
lines_to_keep = []
|
| 149 |
+
for line in content.split("\n"):
|
| 150 |
+
# remove anything that is after a # sign.
|
| 151 |
+
line = re.sub("#.*$", "", line)
|
| 152 |
+
# remove white lines
|
| 153 |
+
if len(line) != 0 and not line.isspace():
|
| 154 |
+
lines_to_keep.append(line)
|
| 155 |
+
return "\n".join(lines_to_keep)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def keep_doc_examples_only(content: str) -> str:
|
| 159 |
+
"""
|
| 160 |
+
Remove everything from the code content except the doc examples (used to determined if a diff should trigger doc
|
| 161 |
+
tests or not).
|
| 162 |
+
|
| 163 |
+
Args:
|
| 164 |
+
content (`str`): The code to clean
|
| 165 |
+
|
| 166 |
+
Returns:
|
| 167 |
+
`str`: The cleaned code.
|
| 168 |
+
"""
|
| 169 |
+
# Keep doc examples only by splitting on triple "`"
|
| 170 |
+
splits = content.split("```")
|
| 171 |
+
# Add leading and trailing "```" so the navigation is easier when compared to the original input `content`
|
| 172 |
+
content = "```" + "```".join(splits[1::2]) + "```"
|
| 173 |
+
|
| 174 |
+
# Remove empty lines and comments
|
| 175 |
+
lines_to_keep = []
|
| 176 |
+
for line in content.split("\n"):
|
| 177 |
+
# remove anything that is after a # sign.
|
| 178 |
+
line = re.sub("#.*$", "", line)
|
| 179 |
+
# remove white lines
|
| 180 |
+
if len(line) != 0 and not line.isspace():
|
| 181 |
+
lines_to_keep.append(line)
|
| 182 |
+
return "\n".join(lines_to_keep)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def get_all_tests() -> List[str]:
|
| 186 |
+
"""
|
| 187 |
+
Walks the `tests` folder to return a list of files/subfolders. This is used to split the tests to run when using
|
| 188 |
+
paralellism. The split is:
|
| 189 |
+
|
| 190 |
+
- folders under `tests`: (`tokenization`, `pipelines`, etc) except the subfolder `models` is excluded.
|
| 191 |
+
- folders under `tests/models`: `bert`, `gpt2`, etc.
|
| 192 |
+
- test files under `tests`: `test_modeling_common.py`, `test_tokenization_common.py`, etc.
|
| 193 |
+
"""
|
| 194 |
+
|
| 195 |
+
# test folders/files directly under `tests` folder
|
| 196 |
+
tests = os.listdir(PATH_TO_TESTS)
|
| 197 |
+
tests = [f"tests/{f}" for f in tests if "__pycache__" not in f]
|
| 198 |
+
tests = sorted([f for f in tests if (PATH_TO_REPO / f).is_dir() or f.startswith("tests/test_")])
|
| 199 |
+
|
| 200 |
+
# model specific test folders
|
| 201 |
+
model_test_folders = os.listdir(PATH_TO_TESTS / "models")
|
| 202 |
+
model_test_folders = [f"tests/models/{f}" for f in model_test_folders if "__pycache__" not in f]
|
| 203 |
+
model_test_folders = sorted([f for f in model_test_folders if (PATH_TO_REPO / f).is_dir()])
|
| 204 |
+
|
| 205 |
+
tests.remove("tests/models")
|
| 206 |
+
# Sagemaker tests are not meant to be run on the CI.
|
| 207 |
+
if "tests/sagemaker" in tests:
|
| 208 |
+
tests.remove("tests/sagemaker")
|
| 209 |
+
tests = model_test_folders + tests
|
| 210 |
+
|
| 211 |
+
return tests
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def diff_is_docstring_only(repo: Repo, branching_point: str, filename: str) -> bool:
|
| 215 |
+
"""
|
| 216 |
+
Check if the diff is only in docstrings (or comments and whitespace) in a filename.
|
| 217 |
+
|
| 218 |
+
Args:
|
| 219 |
+
repo (`git.Repo`): A git repository (for instance the Transformers repo).
|
| 220 |
+
branching_point (`str`): The commit reference of where to compare for the diff.
|
| 221 |
+
filename (`str`): The filename where we want to know if the diff isonly in docstrings/comments.
|
| 222 |
+
|
| 223 |
+
Returns:
|
| 224 |
+
`bool`: Whether the diff is docstring/comments only or not.
|
| 225 |
+
"""
|
| 226 |
+
folder = Path(repo.working_dir)
|
| 227 |
+
with checkout_commit(repo, branching_point):
|
| 228 |
+
with open(folder / filename, "r", encoding="utf-8") as f:
|
| 229 |
+
old_content = f.read()
|
| 230 |
+
|
| 231 |
+
with open(folder / filename, "r", encoding="utf-8") as f:
|
| 232 |
+
new_content = f.read()
|
| 233 |
+
|
| 234 |
+
old_content_clean = clean_code(old_content)
|
| 235 |
+
new_content_clean = clean_code(new_content)
|
| 236 |
+
|
| 237 |
+
return old_content_clean == new_content_clean
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def diff_contains_doc_examples(repo: Repo, branching_point: str, filename: str) -> bool:
|
| 241 |
+
"""
|
| 242 |
+
Check if the diff is only in code examples of the doc in a filename.
|
| 243 |
+
|
| 244 |
+
Args:
|
| 245 |
+
repo (`git.Repo`): A git repository (for instance the Transformers repo).
|
| 246 |
+
branching_point (`str`): The commit reference of where to compare for the diff.
|
| 247 |
+
filename (`str`): The filename where we want to know if the diff is only in codes examples.
|
| 248 |
+
|
| 249 |
+
Returns:
|
| 250 |
+
`bool`: Whether the diff is only in code examples of the doc or not.
|
| 251 |
+
"""
|
| 252 |
+
folder = Path(repo.working_dir)
|
| 253 |
+
with checkout_commit(repo, branching_point):
|
| 254 |
+
with open(folder / filename, "r", encoding="utf-8") as f:
|
| 255 |
+
old_content = f.read()
|
| 256 |
+
|
| 257 |
+
with open(folder / filename, "r", encoding="utf-8") as f:
|
| 258 |
+
new_content = f.read()
|
| 259 |
+
|
| 260 |
+
old_content_clean = keep_doc_examples_only(old_content)
|
| 261 |
+
new_content_clean = keep_doc_examples_only(new_content)
|
| 262 |
+
|
| 263 |
+
return old_content_clean != new_content_clean
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def get_impacted_files_from_tiny_model_summary(diff_with_last_commit: bool = False) -> List[str]:
|
| 267 |
+
"""
|
| 268 |
+
Return a list of python modeling files that are impacted by the changes of `tiny_model_summary.json` in between:
|
| 269 |
+
|
| 270 |
+
- the current head and the main branch if `diff_with_last_commit=False` (default)
|
| 271 |
+
- the current head and its parent commit otherwise.
|
| 272 |
+
|
| 273 |
+
Returns:
|
| 274 |
+
`List[str]`: The list of Python modeling files that are impacted by the changes of `tiny_model_summary.json`.
|
| 275 |
+
"""
|
| 276 |
+
repo = Repo(PATH_TO_REPO)
|
| 277 |
+
|
| 278 |
+
folder = Path(repo.working_dir)
|
| 279 |
+
|
| 280 |
+
if not diff_with_last_commit:
|
| 281 |
+
print(f"main is at {repo.refs.main.commit}")
|
| 282 |
+
print(f"Current head is at {repo.head.commit}")
|
| 283 |
+
|
| 284 |
+
commits = repo.merge_base(repo.refs.main, repo.head)
|
| 285 |
+
for commit in commits:
|
| 286 |
+
print(f"Branching commit: {commit}")
|
| 287 |
+
else:
|
| 288 |
+
print(f"main is at {repo.head.commit}")
|
| 289 |
+
commits = repo.head.commit.parents
|
| 290 |
+
for commit in commits:
|
| 291 |
+
print(f"Parent commit: {commit}")
|
| 292 |
+
|
| 293 |
+
if not os.path.isfile(folder / "tests/utils/tiny_model_summary.json"):
|
| 294 |
+
return []
|
| 295 |
+
|
| 296 |
+
files = set()
|
| 297 |
+
for commit in commits:
|
| 298 |
+
with checkout_commit(repo, commit):
|
| 299 |
+
with open(folder / "tests/utils/tiny_model_summary.json", "r", encoding="utf-8") as f:
|
| 300 |
+
old_content = f.read()
|
| 301 |
+
|
| 302 |
+
with open(folder / "tests/utils/tiny_model_summary.json", "r", encoding="utf-8") as f:
|
| 303 |
+
new_content = f.read()
|
| 304 |
+
|
| 305 |
+
# get the content as json object
|
| 306 |
+
old_content = json.loads(old_content)
|
| 307 |
+
new_content = json.loads(new_content)
|
| 308 |
+
|
| 309 |
+
old_keys = set(old_content.keys())
|
| 310 |
+
new_keys = set(new_content.keys())
|
| 311 |
+
|
| 312 |
+
# get the difference
|
| 313 |
+
keys_with_diff = old_keys.symmetric_difference(new_keys)
|
| 314 |
+
common_keys = old_keys.intersection(new_keys)
|
| 315 |
+
# if both have the same key, check its content
|
| 316 |
+
for key in common_keys:
|
| 317 |
+
if old_content[key] != new_content[key]:
|
| 318 |
+
keys_with_diff.add(key)
|
| 319 |
+
|
| 320 |
+
# get the model classes
|
| 321 |
+
impacted_model_classes = []
|
| 322 |
+
for key in keys_with_diff:
|
| 323 |
+
if key in new_keys:
|
| 324 |
+
impacted_model_classes.extend(new_content[key]["model_classes"])
|
| 325 |
+
|
| 326 |
+
# get the module where the model classes are defined. We want to use the main `__init__` file, but it requires
|
| 327 |
+
# all the framework being installed, which is not ideal for a simple script like test fetcher.
|
| 328 |
+
# So we create a temporary and modified main `__init__` and access its `_import_structure`.
|
| 329 |
+
with open(folder / "src/transformers/__init__.py") as fp:
|
| 330 |
+
lines = fp.readlines()
|
| 331 |
+
new_lines = []
|
| 332 |
+
# Get all the code related to `_import_structure`
|
| 333 |
+
for line in lines:
|
| 334 |
+
if line == "_import_structure = {\n":
|
| 335 |
+
new_lines.append(line)
|
| 336 |
+
elif line == "# Direct imports for type-checking\n":
|
| 337 |
+
break
|
| 338 |
+
elif len(new_lines) > 0:
|
| 339 |
+
# bypass the framework check so we can get all the information even if frameworks are not available
|
| 340 |
+
line = re.sub(r"is_.+_available\(\)", "True", line)
|
| 341 |
+
line = line.replace("OptionalDependencyNotAvailable", "Exception")
|
| 342 |
+
line = line.replace("Exception()", "Exception")
|
| 343 |
+
new_lines.append(line)
|
| 344 |
+
|
| 345 |
+
# create and load the temporary module
|
| 346 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 347 |
+
with open(os.path.join(tmpdirname, "temp_init.py"), "w") as fp:
|
| 348 |
+
fp.write("".join(new_lines))
|
| 349 |
+
|
| 350 |
+
spec = importlib.util.spec_from_file_location("temp_init", os.path.join(tmpdirname, "temp_init.py"))
|
| 351 |
+
module = importlib.util.module_from_spec(spec)
|
| 352 |
+
spec.loader.exec_module(module)
|
| 353 |
+
# Finally, get `_import_structure` that we need
|
| 354 |
+
import_structure = module._import_structure
|
| 355 |
+
|
| 356 |
+
# map model classes to their defined module
|
| 357 |
+
reversed_structure = {}
|
| 358 |
+
for key, values in import_structure.items():
|
| 359 |
+
for value in values:
|
| 360 |
+
reversed_structure[value] = key
|
| 361 |
+
|
| 362 |
+
# Get the corresponding modeling file path
|
| 363 |
+
for model_class in impacted_model_classes:
|
| 364 |
+
module = reversed_structure[model_class]
|
| 365 |
+
framework = ""
|
| 366 |
+
if model_class.startswith("TF"):
|
| 367 |
+
framework = "tf"
|
| 368 |
+
elif model_class.startswith("Flax"):
|
| 369 |
+
framework = "flax"
|
| 370 |
+
fn = (
|
| 371 |
+
f"modeling_{module.split('.')[-1]}.py"
|
| 372 |
+
if framework == ""
|
| 373 |
+
else f"modeling_{framework}_{module.split('.')[-1]}.py"
|
| 374 |
+
)
|
| 375 |
+
files.add(
|
| 376 |
+
f"src.transformers.{module}.{fn}".replace(".", os.path.sep).replace(f"{os.path.sep}py", ".py")
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
return sorted(files)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def get_diff(repo: Repo, base_commit: str, commits: List[str]) -> List[str]:
|
| 383 |
+
"""
|
| 384 |
+
Get the diff between a base commit and one or several commits.
|
| 385 |
+
|
| 386 |
+
Args:
|
| 387 |
+
repo (`git.Repo`):
|
| 388 |
+
A git repository (for instance the Transformers repo).
|
| 389 |
+
base_commit (`str`):
|
| 390 |
+
The commit reference of where to compare for the diff. This is the current commit, not the branching point!
|
| 391 |
+
commits (`List[str]`):
|
| 392 |
+
The list of commits with which to compare the repo at `base_commit` (so the branching point).
|
| 393 |
+
|
| 394 |
+
Returns:
|
| 395 |
+
`List[str]`: The list of Python files with a diff (files added, renamed or deleted are always returned, files
|
| 396 |
+
modified are returned if the diff in the file is not only in docstrings or comments, see
|
| 397 |
+
`diff_is_docstring_only`).
|
| 398 |
+
"""
|
| 399 |
+
print("\n### DIFF ###\n")
|
| 400 |
+
code_diff = []
|
| 401 |
+
for commit in commits:
|
| 402 |
+
for diff_obj in commit.diff(base_commit):
|
| 403 |
+
# We always add new python files
|
| 404 |
+
if diff_obj.change_type == "A" and diff_obj.b_path.endswith(".py"):
|
| 405 |
+
code_diff.append(diff_obj.b_path)
|
| 406 |
+
# We check that deleted python files won't break corresponding tests.
|
| 407 |
+
elif diff_obj.change_type == "D" and diff_obj.a_path.endswith(".py"):
|
| 408 |
+
code_diff.append(diff_obj.a_path)
|
| 409 |
+
# Now for modified files
|
| 410 |
+
elif diff_obj.change_type in ["M", "R"] and diff_obj.b_path.endswith(".py"):
|
| 411 |
+
# In case of renames, we'll look at the tests using both the old and new name.
|
| 412 |
+
if diff_obj.a_path != diff_obj.b_path:
|
| 413 |
+
code_diff.extend([diff_obj.a_path, diff_obj.b_path])
|
| 414 |
+
else:
|
| 415 |
+
# Otherwise, we check modifications are in code and not docstrings.
|
| 416 |
+
if diff_is_docstring_only(repo, commit, diff_obj.b_path):
|
| 417 |
+
print(f"Ignoring diff in {diff_obj.b_path} as it only concerns docstrings or comments.")
|
| 418 |
+
else:
|
| 419 |
+
code_diff.append(diff_obj.a_path)
|
| 420 |
+
|
| 421 |
+
return code_diff
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def get_modified_python_files(diff_with_last_commit: bool = False) -> List[str]:
|
| 425 |
+
"""
|
| 426 |
+
Return a list of python files that have been modified between:
|
| 427 |
+
|
| 428 |
+
- the current head and the main branch if `diff_with_last_commit=False` (default)
|
| 429 |
+
- the current head and its parent commit otherwise.
|
| 430 |
+
|
| 431 |
+
Returns:
|
| 432 |
+
`List[str]`: The list of Python files with a diff (files added, renamed or deleted are always returned, files
|
| 433 |
+
modified are returned if the diff in the file is not only in docstrings or comments, see
|
| 434 |
+
`diff_is_docstring_only`).
|
| 435 |
+
"""
|
| 436 |
+
repo = Repo(PATH_TO_REPO)
|
| 437 |
+
|
| 438 |
+
if not diff_with_last_commit:
|
| 439 |
+
print(f"main is at {repo.refs.main.commit}")
|
| 440 |
+
print(f"Current head is at {repo.head.commit}")
|
| 441 |
+
|
| 442 |
+
branching_commits = repo.merge_base(repo.refs.main, repo.head)
|
| 443 |
+
for commit in branching_commits:
|
| 444 |
+
print(f"Branching commit: {commit}")
|
| 445 |
+
return get_diff(repo, repo.head.commit, branching_commits)
|
| 446 |
+
else:
|
| 447 |
+
print(f"main is at {repo.head.commit}")
|
| 448 |
+
parent_commits = repo.head.commit.parents
|
| 449 |
+
for commit in parent_commits:
|
| 450 |
+
print(f"Parent commit: {commit}")
|
| 451 |
+
return get_diff(repo, repo.head.commit, parent_commits)
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def get_diff_for_doctesting(repo: Repo, base_commit: str, commits: List[str]) -> List[str]:
|
| 455 |
+
"""
|
| 456 |
+
Get the diff in doc examples between a base commit and one or several commits.
|
| 457 |
+
|
| 458 |
+
Args:
|
| 459 |
+
repo (`git.Repo`):
|
| 460 |
+
A git repository (for instance the Transformers repo).
|
| 461 |
+
base_commit (`str`):
|
| 462 |
+
The commit reference of where to compare for the diff. This is the current commit, not the branching point!
|
| 463 |
+
commits (`List[str]`):
|
| 464 |
+
The list of commits with which to compare the repo at `base_commit` (so the branching point).
|
| 465 |
+
|
| 466 |
+
Returns:
|
| 467 |
+
`List[str]`: The list of Python and Markdown files with a diff (files added or renamed are always returned, files
|
| 468 |
+
modified are returned if the diff in the file is only in doctest examples).
|
| 469 |
+
"""
|
| 470 |
+
print("\n### DIFF ###\n")
|
| 471 |
+
code_diff = []
|
| 472 |
+
for commit in commits:
|
| 473 |
+
for diff_obj in commit.diff(base_commit):
|
| 474 |
+
# We only consider Python files and doc files.
|
| 475 |
+
if not diff_obj.b_path.endswith(".py") and not diff_obj.b_path.endswith(".md"):
|
| 476 |
+
continue
|
| 477 |
+
# We always add new python/md files
|
| 478 |
+
if diff_obj.change_type in ["A"]:
|
| 479 |
+
code_diff.append(diff_obj.b_path)
|
| 480 |
+
# Now for modified files
|
| 481 |
+
elif diff_obj.change_type in ["M", "R"]:
|
| 482 |
+
# In case of renames, we'll look at the tests using both the old and new name.
|
| 483 |
+
if diff_obj.a_path != diff_obj.b_path:
|
| 484 |
+
code_diff.extend([diff_obj.a_path, diff_obj.b_path])
|
| 485 |
+
else:
|
| 486 |
+
# Otherwise, we check modifications contain some doc example(s).
|
| 487 |
+
if diff_contains_doc_examples(repo, commit, diff_obj.b_path):
|
| 488 |
+
code_diff.append(diff_obj.a_path)
|
| 489 |
+
else:
|
| 490 |
+
print(f"Ignoring diff in {diff_obj.b_path} as it doesn't contain any doc example.")
|
| 491 |
+
|
| 492 |
+
return code_diff
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def get_all_doctest_files() -> List[str]:
|
| 496 |
+
"""
|
| 497 |
+
Return the complete list of python and Markdown files on which we run doctest.
|
| 498 |
+
|
| 499 |
+
At this moment, we restrict this to only take files from `src/` or `docs/source/en/` that are not in `utils/not_doctested.txt`.
|
| 500 |
+
|
| 501 |
+
Returns:
|
| 502 |
+
`List[str]`: The complete list of Python and Markdown files on which we run doctest.
|
| 503 |
+
"""
|
| 504 |
+
py_files = [str(x.relative_to(PATH_TO_REPO)) for x in PATH_TO_REPO.glob("**/*.py")]
|
| 505 |
+
md_files = [str(x.relative_to(PATH_TO_REPO)) for x in PATH_TO_REPO.glob("**/*.md")]
|
| 506 |
+
|
| 507 |
+
test_files_to_run = py_files + md_files
|
| 508 |
+
# change to use "/" as path separator
|
| 509 |
+
test_files_to_run = ["/".join(Path(x).parts) for x in test_files_to_run]
|
| 510 |
+
# don't run doctest for files in `src/transformers/models/deprecated`
|
| 511 |
+
test_files_to_run = [x for x in test_files_to_run if "models/deprecated" not in x]
|
| 512 |
+
|
| 513 |
+
# only include files in `src` or `docs/source/en/`
|
| 514 |
+
test_files_to_run = [x for x in test_files_to_run if x.startswith(("src/", "docs/source/en/"))]
|
| 515 |
+
# not include init files
|
| 516 |
+
test_files_to_run = [x for x in test_files_to_run if not x.endswith(("__init__.py",))]
|
| 517 |
+
|
| 518 |
+
# These are files not doctested yet.
|
| 519 |
+
with open("utils/not_doctested.txt") as fp:
|
| 520 |
+
not_doctested = {x.split(" ")[0] for x in fp.read().strip().split("\n")}
|
| 521 |
+
|
| 522 |
+
# So far we don't have 100% coverage for doctest. This line will be removed once we achieve 100%.
|
| 523 |
+
test_files_to_run = [x for x in test_files_to_run if x not in not_doctested]
|
| 524 |
+
|
| 525 |
+
return sorted(test_files_to_run)
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def get_new_doctest_files(repo, base_commit, branching_commit) -> List[str]:
|
| 529 |
+
"""
|
| 530 |
+
Get the list of files that were removed from "utils/not_doctested.txt", between `base_commit` and
|
| 531 |
+
`branching_commit`.
|
| 532 |
+
|
| 533 |
+
Returns:
|
| 534 |
+
`List[str]`: List of files that were removed from "utils/not_doctested.txt".
|
| 535 |
+
"""
|
| 536 |
+
for diff_obj in branching_commit.diff(base_commit):
|
| 537 |
+
# Ignores all but the "utils/not_doctested.txt" file.
|
| 538 |
+
if diff_obj.a_path != "utils/not_doctested.txt":
|
| 539 |
+
continue
|
| 540 |
+
# Loads the two versions
|
| 541 |
+
folder = Path(repo.working_dir)
|
| 542 |
+
with checkout_commit(repo, branching_commit):
|
| 543 |
+
with open(folder / "utils/not_doctested.txt", "r", encoding="utf-8") as f:
|
| 544 |
+
old_content = f.read()
|
| 545 |
+
with open(folder / "utils/not_doctested.txt", "r", encoding="utf-8") as f:
|
| 546 |
+
new_content = f.read()
|
| 547 |
+
# Compute the removed lines and return them
|
| 548 |
+
removed_content = {x.split(" ")[0] for x in old_content.split("\n")} - {
|
| 549 |
+
x.split(" ")[0] for x in new_content.split("\n")
|
| 550 |
+
}
|
| 551 |
+
return sorted(removed_content)
|
| 552 |
+
return []
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
def get_doctest_files(diff_with_last_commit: bool = False) -> List[str]:
|
| 556 |
+
"""
|
| 557 |
+
Return a list of python and Markdown files where doc example have been modified between:
|
| 558 |
+
|
| 559 |
+
- the current head and the main branch if `diff_with_last_commit=False` (default)
|
| 560 |
+
- the current head and its parent commit otherwise.
|
| 561 |
+
|
| 562 |
+
Returns:
|
| 563 |
+
`List[str]`: The list of Python and Markdown files with a diff (files added or renamed are always returned, files
|
| 564 |
+
modified are returned if the diff in the file is only in doctest examples).
|
| 565 |
+
"""
|
| 566 |
+
repo = Repo(PATH_TO_REPO)
|
| 567 |
+
|
| 568 |
+
test_files_to_run = [] # noqa
|
| 569 |
+
if not diff_with_last_commit:
|
| 570 |
+
print(f"main is at {repo.refs.main.commit}")
|
| 571 |
+
print(f"Current head is at {repo.head.commit}")
|
| 572 |
+
|
| 573 |
+
branching_commits = repo.merge_base(repo.refs.main, repo.head)
|
| 574 |
+
for commit in branching_commits:
|
| 575 |
+
print(f"Branching commit: {commit}")
|
| 576 |
+
test_files_to_run = get_diff_for_doctesting(repo, repo.head.commit, branching_commits)
|
| 577 |
+
else:
|
| 578 |
+
print(f"main is at {repo.head.commit}")
|
| 579 |
+
parent_commits = repo.head.commit.parents
|
| 580 |
+
for commit in parent_commits:
|
| 581 |
+
print(f"Parent commit: {commit}")
|
| 582 |
+
test_files_to_run = get_diff_for_doctesting(repo, repo.head.commit, parent_commits)
|
| 583 |
+
|
| 584 |
+
all_test_files_to_run = get_all_doctest_files()
|
| 585 |
+
|
| 586 |
+
# Add to the test files to run any removed entry from "utils/not_doctested.txt".
|
| 587 |
+
new_test_files = get_new_doctest_files(repo, repo.head.commit, repo.refs.main.commit)
|
| 588 |
+
test_files_to_run = list(set(test_files_to_run + new_test_files))
|
| 589 |
+
|
| 590 |
+
# Do not run slow doctest tests on CircleCI
|
| 591 |
+
with open("utils/slow_documentation_tests.txt") as fp:
|
| 592 |
+
slow_documentation_tests = set(fp.read().strip().split("\n"))
|
| 593 |
+
test_files_to_run = [
|
| 594 |
+
x for x in test_files_to_run if x in all_test_files_to_run and x not in slow_documentation_tests
|
| 595 |
+
]
|
| 596 |
+
|
| 597 |
+
# Make sure we did not end up with a test file that was removed
|
| 598 |
+
test_files_to_run = [f for f in test_files_to_run if (PATH_TO_REPO / f).exists()]
|
| 599 |
+
|
| 600 |
+
return sorted(test_files_to_run)
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
# (:?^|\n) -> Non-catching group for the beginning of the doc or a new line.
|
| 604 |
+
# \s*from\s+(\.+\S+)\s+import\s+([^\n]+) -> Line only contains from .xxx import yyy and we catch .xxx and yyy
|
| 605 |
+
# (?=\n) -> Look-ahead to a new line. We can't just put \n here or using find_all on this re will only catch every
|
| 606 |
+
# other import.
|
| 607 |
+
_re_single_line_relative_imports = re.compile(r"(?:^|\n)\s*from\s+(\.+\S+)\s+import\s+([^\n]+)(?=\n)")
|
| 608 |
+
# (:?^|\n) -> Non-catching group for the beginning of the doc or a new line.
|
| 609 |
+
# \s*from\s+(\.+\S+)\s+import\s+\(([^\)]+)\) -> Line continues with from .xxx import (yyy) and we catch .xxx and yyy
|
| 610 |
+
# yyy will take multiple lines otherwise there wouldn't be parenthesis.
|
| 611 |
+
_re_multi_line_relative_imports = re.compile(r"(?:^|\n)\s*from\s+(\.+\S+)\s+import\s+\(([^\)]+)\)")
|
| 612 |
+
# (:?^|\n) -> Non-catching group for the beginning of the doc or a new line.
|
| 613 |
+
# \s*from\s+transformers(\S*)\s+import\s+([^\n]+) -> Line only contains from transformers.xxx import yyy and we catch
|
| 614 |
+
# .xxx and yyy
|
| 615 |
+
# (?=\n) -> Look-ahead to a new line. We can't just put \n here or using find_all on this re will only catch every
|
| 616 |
+
# other import.
|
| 617 |
+
_re_single_line_direct_imports = re.compile(r"(?:^|\n)\s*from\s+transformers(\S*)\s+import\s+([^\n]+)(?=\n)")
|
| 618 |
+
# (:?^|\n) -> Non-catching group for the beginning of the doc or a new line.
|
| 619 |
+
# \s*from\s+transformers(\S*)\s+import\s+\(([^\)]+)\) -> Line continues with from transformers.xxx import (yyy) and we
|
| 620 |
+
# catch .xxx and yyy. yyy will take multiple lines otherwise there wouldn't be parenthesis.
|
| 621 |
+
_re_multi_line_direct_imports = re.compile(r"(?:^|\n)\s*from\s+transformers(\S*)\s+import\s+\(([^\)]+)\)")
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
def extract_imports(module_fname: str, cache: Dict[str, List[str]] = None) -> List[str]:
|
| 625 |
+
"""
|
| 626 |
+
Get the imports a given module makes.
|
| 627 |
+
|
| 628 |
+
Args:
|
| 629 |
+
module_fname (`str`):
|
| 630 |
+
The name of the file of the module where we want to look at the imports (given relative to the root of
|
| 631 |
+
the repo).
|
| 632 |
+
cache (Dictionary `str` to `List[str]`, *optional*):
|
| 633 |
+
To speed up this function if it was previously called on `module_fname`, the cache of all previously
|
| 634 |
+
computed results.
|
| 635 |
+
|
| 636 |
+
Returns:
|
| 637 |
+
`List[str]`: The list of module filenames imported in the input `module_fname` (a submodule we import from that
|
| 638 |
+
is a subfolder will give its init file).
|
| 639 |
+
"""
|
| 640 |
+
if cache is not None and module_fname in cache:
|
| 641 |
+
return cache[module_fname]
|
| 642 |
+
|
| 643 |
+
with open(PATH_TO_REPO / module_fname, "r", encoding="utf-8") as f:
|
| 644 |
+
content = f.read()
|
| 645 |
+
|
| 646 |
+
# Filter out all docstrings to not get imports in code examples. As before we need to deactivate formatting to
|
| 647 |
+
# keep this as escaped quotes and avoid this function failing on this file.
|
| 648 |
+
splits = content.split('\"\"\"') # fmt: skip
|
| 649 |
+
content = "".join(splits[::2])
|
| 650 |
+
|
| 651 |
+
module_parts = str(module_fname).split(os.path.sep)
|
| 652 |
+
imported_modules = []
|
| 653 |
+
|
| 654 |
+
# Let's start with relative imports
|
| 655 |
+
relative_imports = _re_single_line_relative_imports.findall(content)
|
| 656 |
+
relative_imports = [
|
| 657 |
+
(mod, imp) for mod, imp in relative_imports if "# tests_ignore" not in imp and imp.strip() != "("
|
| 658 |
+
]
|
| 659 |
+
multiline_relative_imports = _re_multi_line_relative_imports.findall(content)
|
| 660 |
+
relative_imports += [(mod, imp) for mod, imp in multiline_relative_imports if "# tests_ignore" not in imp]
|
| 661 |
+
|
| 662 |
+
# We need to remove parts of the module name depending on the depth of the relative imports.
|
| 663 |
+
for module, imports in relative_imports:
|
| 664 |
+
level = 0
|
| 665 |
+
while module.startswith("."):
|
| 666 |
+
module = module[1:]
|
| 667 |
+
level += 1
|
| 668 |
+
|
| 669 |
+
if len(module) > 0:
|
| 670 |
+
dep_parts = module_parts[: len(module_parts) - level] + module.split(".")
|
| 671 |
+
else:
|
| 672 |
+
dep_parts = module_parts[: len(module_parts) - level]
|
| 673 |
+
imported_module = os.path.sep.join(dep_parts)
|
| 674 |
+
imported_modules.append((imported_module, [imp.strip() for imp in imports.split(",")]))
|
| 675 |
+
|
| 676 |
+
# Let's continue with direct imports
|
| 677 |
+
direct_imports = _re_single_line_direct_imports.findall(content)
|
| 678 |
+
direct_imports = [(mod, imp) for mod, imp in direct_imports if "# tests_ignore" not in imp and imp.strip() != "("]
|
| 679 |
+
multiline_direct_imports = _re_multi_line_direct_imports.findall(content)
|
| 680 |
+
direct_imports += [(mod, imp) for mod, imp in multiline_direct_imports if "# tests_ignore" not in imp]
|
| 681 |
+
|
| 682 |
+
# We need to find the relative path of those imports.
|
| 683 |
+
for module, imports in direct_imports:
|
| 684 |
+
import_parts = module.split(".")[1:] # ignore the name of the repo since we add it below.
|
| 685 |
+
dep_parts = ["src", "transformers"] + import_parts
|
| 686 |
+
imported_module = os.path.sep.join(dep_parts)
|
| 687 |
+
imported_modules.append((imported_module, [imp.strip() for imp in imports.split(",")]))
|
| 688 |
+
|
| 689 |
+
result = []
|
| 690 |
+
# Double check we get proper modules (either a python file or a folder with an init).
|
| 691 |
+
for module_file, imports in imported_modules:
|
| 692 |
+
if (PATH_TO_REPO / f"{module_file}.py").is_file():
|
| 693 |
+
module_file = f"{module_file}.py"
|
| 694 |
+
elif (PATH_TO_REPO / module_file).is_dir() and (PATH_TO_REPO / module_file / "__init__.py").is_file():
|
| 695 |
+
module_file = os.path.sep.join([module_file, "__init__.py"])
|
| 696 |
+
imports = [imp for imp in imports if len(imp) > 0 and re.match("^[A-Za-z0-9_]*$", imp)]
|
| 697 |
+
if len(imports) > 0:
|
| 698 |
+
result.append((module_file, imports))
|
| 699 |
+
|
| 700 |
+
if cache is not None:
|
| 701 |
+
cache[module_fname] = result
|
| 702 |
+
|
| 703 |
+
return result
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def get_module_dependencies(module_fname: str, cache: Dict[str, List[str]] = None) -> List[str]:
|
| 707 |
+
"""
|
| 708 |
+
Refines the result of `extract_imports` to remove subfolders and get a proper list of module filenames: if a file
|
| 709 |
+
as an import `from utils import Foo, Bar`, with `utils` being a subfolder containing many files, this will traverse
|
| 710 |
+
the `utils` init file to check where those dependencies come from: for instance the files utils/foo.py and utils/bar.py.
|
| 711 |
+
|
| 712 |
+
Warning: This presupposes that all intermediate inits are properly built (with imports from the respective
|
| 713 |
+
submodules) and work better if objects are defined in submodules and not the intermediate init (otherwise the
|
| 714 |
+
intermediate init is added, and inits usually have a lot of dependencies).
|
| 715 |
+
|
| 716 |
+
Args:
|
| 717 |
+
module_fname (`str`):
|
| 718 |
+
The name of the file of the module where we want to look at the imports (given relative to the root of
|
| 719 |
+
the repo).
|
| 720 |
+
cache (Dictionary `str` to `List[str]`, *optional*):
|
| 721 |
+
To speed up this function if it was previously called on `module_fname`, the cache of all previously
|
| 722 |
+
computed results.
|
| 723 |
+
|
| 724 |
+
Returns:
|
| 725 |
+
`List[str]`: The list of module filenames imported in the input `module_fname` (with submodule imports refined).
|
| 726 |
+
"""
|
| 727 |
+
dependencies = []
|
| 728 |
+
imported_modules = extract_imports(module_fname, cache=cache)
|
| 729 |
+
# The while loop is to recursively traverse all inits we may encounter: we will add things as we go.
|
| 730 |
+
while len(imported_modules) > 0:
|
| 731 |
+
new_modules = []
|
| 732 |
+
for module, imports in imported_modules:
|
| 733 |
+
if "models" in module.split("/") and module.split("/")[-1].startswith("convert_"):
|
| 734 |
+
continue
|
| 735 |
+
# If we end up in an __init__ we are often not actually importing from this init (except in the case where
|
| 736 |
+
# the object is fully defined in the __init__)
|
| 737 |
+
if module.endswith("__init__.py"):
|
| 738 |
+
# So we get the imports from that init then try to find where our objects come from.
|
| 739 |
+
new_imported_modules = extract_imports(module, cache=cache)
|
| 740 |
+
|
| 741 |
+
# Add imports via `define_import_structure` after the #35167 as we remove explicit import in `__init__.py`
|
| 742 |
+
from transformers.utils.import_utils import define_import_structure
|
| 743 |
+
|
| 744 |
+
new_imported_modules_2 = define_import_structure(PATH_TO_REPO / module)
|
| 745 |
+
|
| 746 |
+
for mapping in new_imported_modules_2.values():
|
| 747 |
+
for _module, _imports in mapping.items():
|
| 748 |
+
_module = module.replace("__init__.py", f"{_module}.py")
|
| 749 |
+
new_imported_modules.append((_module, list(_imports)))
|
| 750 |
+
|
| 751 |
+
for new_module, new_imports in new_imported_modules:
|
| 752 |
+
if any(i in new_imports for i in imports):
|
| 753 |
+
if new_module not in dependencies:
|
| 754 |
+
new_modules.append((new_module, [i for i in new_imports if i in imports]))
|
| 755 |
+
imports = [i for i in imports if i not in new_imports]
|
| 756 |
+
|
| 757 |
+
if len(imports) > 0:
|
| 758 |
+
# If there are any objects lefts, they may be a submodule
|
| 759 |
+
path_to_module = PATH_TO_REPO / module.replace("__init__.py", "")
|
| 760 |
+
dependencies.extend(
|
| 761 |
+
[
|
| 762 |
+
os.path.join(module.replace("__init__.py", ""), f"{i}.py")
|
| 763 |
+
for i in imports
|
| 764 |
+
if (path_to_module / f"{i}.py").is_file()
|
| 765 |
+
]
|
| 766 |
+
)
|
| 767 |
+
imports = [i for i in imports if not (path_to_module / f"{i}.py").is_file()]
|
| 768 |
+
if len(imports) > 0:
|
| 769 |
+
# Then if there are still objects left, they are fully defined in the init, so we keep it as a
|
| 770 |
+
# dependency.
|
| 771 |
+
dependencies.append(module)
|
| 772 |
+
else:
|
| 773 |
+
dependencies.append(module)
|
| 774 |
+
|
| 775 |
+
imported_modules = new_modules
|
| 776 |
+
|
| 777 |
+
return dependencies
|
| 778 |
+
|
| 779 |
+
|
| 780 |
+
def create_reverse_dependency_tree() -> List[Tuple[str, str]]:
|
| 781 |
+
"""
|
| 782 |
+
Create a list of all edges (a, b) which mean that modifying a impacts b with a going over all module and test files.
|
| 783 |
+
"""
|
| 784 |
+
cache = {}
|
| 785 |
+
all_modules = list(PATH_TO_TRANFORMERS.glob("**/*.py"))
|
| 786 |
+
all_modules = [x for x in all_modules if not ("models" in x.parts and x.parts[-1].startswith("convert_"))]
|
| 787 |
+
all_modules += list(PATH_TO_TESTS.glob("**/*.py"))
|
| 788 |
+
all_modules = [str(mod.relative_to(PATH_TO_REPO)) for mod in all_modules]
|
| 789 |
+
edges = [(dep, mod) for mod in all_modules for dep in get_module_dependencies(mod, cache=cache)]
|
| 790 |
+
|
| 791 |
+
return list(set(edges))
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
def get_tree_starting_at(module: str, edges: List[Tuple[str, str]]) -> List[Union[str, List[str]]]:
|
| 795 |
+
"""
|
| 796 |
+
Returns the tree starting at a given module following all edges.
|
| 797 |
+
|
| 798 |
+
Args:
|
| 799 |
+
module (`str`): The module that will be the root of the subtree we want.
|
| 800 |
+
eges (`List[Tuple[str, str]]`): The list of all edges of the tree.
|
| 801 |
+
|
| 802 |
+
Returns:
|
| 803 |
+
`List[Union[str, List[str]]]`: The tree to print in the following format: [module, [list of edges
|
| 804 |
+
starting at module], [list of edges starting at the preceding level], ...]
|
| 805 |
+
"""
|
| 806 |
+
vertices_seen = [module]
|
| 807 |
+
new_edges = [edge for edge in edges if edge[0] == module and edge[1] != module and "__init__.py" not in edge[1]]
|
| 808 |
+
tree = [module]
|
| 809 |
+
while len(new_edges) > 0:
|
| 810 |
+
tree.append(new_edges)
|
| 811 |
+
final_vertices = list({edge[1] for edge in new_edges})
|
| 812 |
+
vertices_seen.extend(final_vertices)
|
| 813 |
+
new_edges = [
|
| 814 |
+
edge
|
| 815 |
+
for edge in edges
|
| 816 |
+
if edge[0] in final_vertices and edge[1] not in vertices_seen and "__init__.py" not in edge[1]
|
| 817 |
+
]
|
| 818 |
+
|
| 819 |
+
return tree
|
| 820 |
+
|
| 821 |
+
|
| 822 |
+
def print_tree_deps_of(module, all_edges=None):
|
| 823 |
+
"""
|
| 824 |
+
Prints the tree of modules depending on a given module.
|
| 825 |
+
|
| 826 |
+
Args:
|
| 827 |
+
module (`str`): The module that will be the root of the subtree we want.
|
| 828 |
+
all_eges (`List[Tuple[str, str]]`, *optional*):
|
| 829 |
+
The list of all edges of the tree. Will be set to `create_reverse_dependency_tree()` if not passed.
|
| 830 |
+
"""
|
| 831 |
+
if all_edges is None:
|
| 832 |
+
all_edges = create_reverse_dependency_tree()
|
| 833 |
+
tree = get_tree_starting_at(module, all_edges)
|
| 834 |
+
|
| 835 |
+
# The list of lines is a list of tuples (line_to_be_printed, module)
|
| 836 |
+
# Keeping the modules lets us know where to insert each new lines in the list.
|
| 837 |
+
lines = [(tree[0], tree[0])]
|
| 838 |
+
for index in range(1, len(tree)):
|
| 839 |
+
edges = tree[index]
|
| 840 |
+
start_edges = {edge[0] for edge in edges}
|
| 841 |
+
|
| 842 |
+
for start in start_edges:
|
| 843 |
+
end_edges = {edge[1] for edge in edges if edge[0] == start}
|
| 844 |
+
# We will insert all those edges just after the line showing start.
|
| 845 |
+
pos = 0
|
| 846 |
+
while lines[pos][1] != start:
|
| 847 |
+
pos += 1
|
| 848 |
+
lines = lines[: pos + 1] + [(" " * (2 * index) + end, end) for end in end_edges] + lines[pos + 1 :]
|
| 849 |
+
|
| 850 |
+
for line in lines:
|
| 851 |
+
# We don't print the refs that where just here to help build lines.
|
| 852 |
+
print(line[0])
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
def init_test_examples_dependencies() -> Tuple[Dict[str, List[str]], List[str]]:
|
| 856 |
+
"""
|
| 857 |
+
The test examples do not import from the examples (which are just scripts, not modules) so we need som extra
|
| 858 |
+
care initializing the dependency map, which is the goal of this function. It initializes the dependency map for
|
| 859 |
+
example files by linking each example to the example test file for the example framework.
|
| 860 |
+
|
| 861 |
+
Returns:
|
| 862 |
+
`Tuple[Dict[str, List[str]], List[str]]`: A tuple with two elements: the initialized dependency map which is a
|
| 863 |
+
dict test example file to list of example files potentially tested by that test file, and the list of all
|
| 864 |
+
example files (to avoid recomputing it later).
|
| 865 |
+
"""
|
| 866 |
+
test_example_deps = {}
|
| 867 |
+
all_examples = []
|
| 868 |
+
for framework in ["flax", "pytorch", "tensorflow"]:
|
| 869 |
+
test_files = list((PATH_TO_EXAMPLES / framework).glob("test_*.py"))
|
| 870 |
+
all_examples.extend(test_files)
|
| 871 |
+
# Remove the files at the root of examples/framework since they are not proper examples (they are eith utils
|
| 872 |
+
# or example test files).
|
| 873 |
+
examples = [
|
| 874 |
+
f for f in (PATH_TO_EXAMPLES / framework).glob("**/*.py") if f.parent != PATH_TO_EXAMPLES / framework
|
| 875 |
+
]
|
| 876 |
+
all_examples.extend(examples)
|
| 877 |
+
for test_file in test_files:
|
| 878 |
+
with open(test_file, "r", encoding="utf-8") as f:
|
| 879 |
+
content = f.read()
|
| 880 |
+
# Map all examples to the test files found in examples/framework.
|
| 881 |
+
test_example_deps[str(test_file.relative_to(PATH_TO_REPO))] = [
|
| 882 |
+
str(e.relative_to(PATH_TO_REPO)) for e in examples if e.name in content
|
| 883 |
+
]
|
| 884 |
+
# Also map the test files to themselves.
|
| 885 |
+
test_example_deps[str(test_file.relative_to(PATH_TO_REPO))].append(
|
| 886 |
+
str(test_file.relative_to(PATH_TO_REPO))
|
| 887 |
+
)
|
| 888 |
+
return test_example_deps, all_examples
|
| 889 |
+
|
| 890 |
+
|
| 891 |
+
def create_reverse_dependency_map() -> Dict[str, List[str]]:
|
| 892 |
+
"""
|
| 893 |
+
Create the dependency map from module/test filename to the list of modules/tests that depend on it recursively.
|
| 894 |
+
|
| 895 |
+
Returns:
|
| 896 |
+
`Dict[str, List[str]]`: The reverse dependency map as a dictionary mapping filenames to all the filenames
|
| 897 |
+
depending on it recursively. This way the tests impacted by a change in file A are the test files in the list
|
| 898 |
+
corresponding to key A in this result.
|
| 899 |
+
"""
|
| 900 |
+
|
| 901 |
+
cache = {}
|
| 902 |
+
# Start from the example deps init.
|
| 903 |
+
example_deps, examples = init_test_examples_dependencies()
|
| 904 |
+
# Add all modules and all tests to all examples
|
| 905 |
+
all_modules = list(PATH_TO_TRANFORMERS.glob("**/*.py"))
|
| 906 |
+
all_modules = [x for x in all_modules if not ("models" in x.parts and x.parts[-1].startswith("convert_"))]
|
| 907 |
+
all_modules += list(PATH_TO_TESTS.glob("**/*.py")) + examples
|
| 908 |
+
all_modules = [str(mod.relative_to(PATH_TO_REPO)) for mod in all_modules]
|
| 909 |
+
# Compute the direct dependencies of all modules.
|
| 910 |
+
direct_deps = {m: get_module_dependencies(m, cache=cache) for m in all_modules}
|
| 911 |
+
direct_deps.update(example_deps)
|
| 912 |
+
|
| 913 |
+
# This recurses the dependencies
|
| 914 |
+
something_changed = True
|
| 915 |
+
while something_changed:
|
| 916 |
+
something_changed = False
|
| 917 |
+
for m in all_modules:
|
| 918 |
+
for d in direct_deps[m]:
|
| 919 |
+
# We stop recursing at an init (cause we always end up in the main init and we don't want to add all
|
| 920 |
+
# files which the main init imports)
|
| 921 |
+
if d.endswith("__init__.py"):
|
| 922 |
+
continue
|
| 923 |
+
if d not in direct_deps:
|
| 924 |
+
raise ValueError(f"KeyError:{d}. From {m}")
|
| 925 |
+
new_deps = set(direct_deps[d]) - set(direct_deps[m])
|
| 926 |
+
if len(new_deps) > 0:
|
| 927 |
+
direct_deps[m].extend(list(new_deps))
|
| 928 |
+
something_changed = True
|
| 929 |
+
|
| 930 |
+
# Finally we can build the reverse map.
|
| 931 |
+
reverse_map = collections.defaultdict(list)
|
| 932 |
+
for m in all_modules:
|
| 933 |
+
for d in direct_deps[m]:
|
| 934 |
+
reverse_map[d].append(m)
|
| 935 |
+
|
| 936 |
+
# For inits, we don't do the reverse deps but the direct deps: if modifying an init, we want to make sure we test
|
| 937 |
+
# all the modules impacted by that init.
|
| 938 |
+
for m in [f for f in all_modules if f.endswith("__init__.py")]:
|
| 939 |
+
direct_deps = get_module_dependencies(m, cache=cache)
|
| 940 |
+
deps = sum([reverse_map[d] for d in direct_deps if not d.endswith("__init__.py")], direct_deps)
|
| 941 |
+
reverse_map[m] = list(set(deps) - {m})
|
| 942 |
+
|
| 943 |
+
return reverse_map
|
| 944 |
+
|
| 945 |
+
|
| 946 |
+
def create_module_to_test_map(
|
| 947 |
+
reverse_map: Dict[str, List[str]] = None, filter_models: bool = False
|
| 948 |
+
) -> Dict[str, List[str]]:
|
| 949 |
+
"""
|
| 950 |
+
Extract the tests from the reverse_dependency_map and potentially filters the model tests.
|
| 951 |
+
|
| 952 |
+
Args:
|
| 953 |
+
reverse_map (`Dict[str, List[str]]`, *optional*):
|
| 954 |
+
The reverse dependency map as created by `create_reverse_dependency_map`. Will default to the result of
|
| 955 |
+
that function if not provided.
|
| 956 |
+
filter_models (`bool`, *optional*, defaults to `False`):
|
| 957 |
+
Whether or not to filter model tests to only include core models if a file impacts a lot of models.
|
| 958 |
+
|
| 959 |
+
Returns:
|
| 960 |
+
`Dict[str, List[str]]`: A dictionary that maps each file to the tests to execute if that file was modified.
|
| 961 |
+
"""
|
| 962 |
+
if reverse_map is None:
|
| 963 |
+
reverse_map = create_reverse_dependency_map()
|
| 964 |
+
|
| 965 |
+
# Utility that tells us if a given file is a test (taking test examples into account)
|
| 966 |
+
def is_test(fname):
|
| 967 |
+
if fname.startswith("tests"):
|
| 968 |
+
return True
|
| 969 |
+
if fname.startswith("examples") and fname.split(os.path.sep)[-1].startswith("test"):
|
| 970 |
+
return True
|
| 971 |
+
return False
|
| 972 |
+
|
| 973 |
+
# Build the test map
|
| 974 |
+
test_map = {module: [f for f in deps if is_test(f)] for module, deps in reverse_map.items()}
|
| 975 |
+
|
| 976 |
+
if not filter_models:
|
| 977 |
+
return test_map
|
| 978 |
+
|
| 979 |
+
# Now we deal with the filtering if `filter_models` is True.
|
| 980 |
+
num_model_tests = len(list(PATH_TO_TESTS.glob("models/*")))
|
| 981 |
+
|
| 982 |
+
def has_many_models(tests):
|
| 983 |
+
# We filter to core models when a given file impacts more than half the model tests.
|
| 984 |
+
model_tests = {Path(t).parts[2] for t in tests if t.startswith("tests/models/")}
|
| 985 |
+
return len(model_tests) > num_model_tests // 2
|
| 986 |
+
|
| 987 |
+
# for each module (if specified in the argument `module`) of the form `models/my_model` (i.e. starting with it),
|
| 988 |
+
# we always keep the tests (those are already in the argument `tests`) which are in `tests/models/my_model`.
|
| 989 |
+
# This is to avoid them being excluded when a module has many impacted tests: the directly related test files should
|
| 990 |
+
# always be included!
|
| 991 |
+
def filter_tests(tests, module=""):
|
| 992 |
+
filtered_tests = []
|
| 993 |
+
for t in tests:
|
| 994 |
+
if (
|
| 995 |
+
not t.startswith("tests/models/")
|
| 996 |
+
or Path(t).parts[2] in IMPORTANT_MODELS
|
| 997 |
+
# at this point, `t` is of the form `tests/models/my_model`, and we check if `models/my_model`
|
| 998 |
+
# (i.e. `parts[1:3]`) is in `module`.
|
| 999 |
+
or "/".join(Path(t).parts[1:3]) in module
|
| 1000 |
+
):
|
| 1001 |
+
filtered_tests += [t]
|
| 1002 |
+
return filtered_tests
|
| 1003 |
+
|
| 1004 |
+
return {
|
| 1005 |
+
module: (filter_tests(tests, module=module) if has_many_models(tests) else tests)
|
| 1006 |
+
for module, tests in test_map.items()
|
| 1007 |
+
}
|
| 1008 |
+
|
| 1009 |
+
|
| 1010 |
+
def _print_list(l) -> str:
|
| 1011 |
+
"""
|
| 1012 |
+
Pretty print a list of elements with one line per element and a - starting each line.
|
| 1013 |
+
"""
|
| 1014 |
+
return "\n".join([f"- {f}" for f in l])
|
| 1015 |
+
|
| 1016 |
+
|
| 1017 |
+
def infer_tests_to_run(
|
| 1018 |
+
output_file: str, diff_with_last_commit: bool = False, filter_models: bool = False, test_all: bool = False
|
| 1019 |
+
):
|
| 1020 |
+
"""
|
| 1021 |
+
The main function called by the test fetcher. Determines the tests to run from the diff.
|
| 1022 |
+
|
| 1023 |
+
Args:
|
| 1024 |
+
output_file (`str`):
|
| 1025 |
+
The path where to store the summary of the test fetcher analysis. Other files will be stored in the same
|
| 1026 |
+
folder:
|
| 1027 |
+
|
| 1028 |
+
- examples_test_list.txt: The list of examples tests to run.
|
| 1029 |
+
- test_repo_utils.txt: Will indicate if the repo utils tests should be run or not.
|
| 1030 |
+
- doctest_list.txt: The list of doctests to run.
|
| 1031 |
+
|
| 1032 |
+
diff_with_last_commit (`bool`, *optional*, defaults to `False`):
|
| 1033 |
+
Whether to analyze the diff with the last commit (for use on the main branch after a PR is merged) or with
|
| 1034 |
+
the branching point from main (for use on each PR).
|
| 1035 |
+
filter_models (`bool`, *optional*, defaults to `True`):
|
| 1036 |
+
Whether or not to filter the tests to core models only, when a file modified results in a lot of model
|
| 1037 |
+
tests.
|
| 1038 |
+
"""
|
| 1039 |
+
if not test_all:
|
| 1040 |
+
modified_files = get_modified_python_files(diff_with_last_commit=diff_with_last_commit)
|
| 1041 |
+
else:
|
| 1042 |
+
modified_files = [str(k) for k in PATH_TO_TESTS.glob("*/*") if str(k).endswith(".py") and "test_" in str(k)]
|
| 1043 |
+
print("\n### test_all is TRUE, FETCHING ALL FILES###\n")
|
| 1044 |
+
print(f"\n### MODIFIED FILES ###\n{_print_list(modified_files)}")
|
| 1045 |
+
|
| 1046 |
+
# Create the map that will give us all impacted modules.
|
| 1047 |
+
reverse_map = create_reverse_dependency_map()
|
| 1048 |
+
impacted_files = modified_files.copy()
|
| 1049 |
+
for f in modified_files:
|
| 1050 |
+
if f in reverse_map:
|
| 1051 |
+
impacted_files.extend(reverse_map[f])
|
| 1052 |
+
|
| 1053 |
+
# Remove duplicates
|
| 1054 |
+
impacted_files = sorted(set(impacted_files))
|
| 1055 |
+
print(f"\n### IMPACTED FILES ###\n{_print_list(impacted_files)}")
|
| 1056 |
+
|
| 1057 |
+
model_impacted = {"/".join(x.split("/")[:3]) for x in impacted_files if x.startswith("tests/models/")}
|
| 1058 |
+
# Grab the corresponding test files:
|
| 1059 |
+
if (
|
| 1060 |
+
any(x in modified_files for x in ["setup.py", ".circleci/create_circleci_config.py"])
|
| 1061 |
+
or not filter_models
|
| 1062 |
+
and len(model_impacted) >= NUM_MODELS_TO_TRIGGER_FULL_CI
|
| 1063 |
+
or commit_flags["test_all"]
|
| 1064 |
+
):
|
| 1065 |
+
test_files_to_run = glob.glob("tests/**/test_**.py", recursive=True) + glob.glob(
|
| 1066 |
+
"examples/**/*.py", recursive=True
|
| 1067 |
+
)
|
| 1068 |
+
if len(model_impacted) >= NUM_MODELS_TO_TRIGGER_FULL_CI and filter_models:
|
| 1069 |
+
print(
|
| 1070 |
+
f"More than {NUM_MODELS_TO_TRIGGER_FULL_CI - 1} models are impacted and `filter_models=False`. CI is configured to test everything."
|
| 1071 |
+
)
|
| 1072 |
+
else:
|
| 1073 |
+
# All modified tests need to be run.
|
| 1074 |
+
test_files_to_run = [f for f in modified_files if f.startswith("tests") and "/test_" in f]
|
| 1075 |
+
impacted_files = get_impacted_files_from_tiny_model_summary(diff_with_last_commit=diff_with_last_commit)
|
| 1076 |
+
|
| 1077 |
+
# Then we grab the corresponding test files.
|
| 1078 |
+
test_map = create_module_to_test_map(reverse_map=reverse_map, filter_models=filter_models)
|
| 1079 |
+
for f in modified_files + impacted_files:
|
| 1080 |
+
if f in test_map:
|
| 1081 |
+
test_files_to_run.extend(test_map[f])
|
| 1082 |
+
test_files_to_run = sorted(set(test_files_to_run))
|
| 1083 |
+
# Remove repo utils tests
|
| 1084 |
+
test_files_to_run = [f for f in test_files_to_run if not f.split(os.path.sep)[1] == "repo_utils"]
|
| 1085 |
+
# Remove SageMaker tests
|
| 1086 |
+
test_files_to_run = [f for f in test_files_to_run if not f.split(os.path.sep)[1] == "sagemaker"]
|
| 1087 |
+
# Make sure we did not end up with a test file that was removed
|
| 1088 |
+
test_files_to_run = [f for f in test_files_to_run if (PATH_TO_REPO / f).exists()]
|
| 1089 |
+
|
| 1090 |
+
print(f"\n### TEST TO RUN ###\n{_print_list(test_files_to_run)}")
|
| 1091 |
+
|
| 1092 |
+
create_test_list_from_filter(test_files_to_run, out_path="test_preparation/")
|
| 1093 |
+
|
| 1094 |
+
doctest_list = get_doctest_files()
|
| 1095 |
+
|
| 1096 |
+
print(f"\n### DOCTEST TO RUN ###\n{_print_list(doctest_list)}")
|
| 1097 |
+
if len(doctest_list) > 0:
|
| 1098 |
+
doctest_file = Path(output_file).parent / "doctest_list.txt"
|
| 1099 |
+
with open(doctest_file, "w", encoding="utf-8") as f:
|
| 1100 |
+
f.write(" ".join(doctest_list))
|
| 1101 |
+
|
| 1102 |
+
|
| 1103 |
+
def filter_tests(output_file: str, filters: List[str]):
|
| 1104 |
+
"""
|
| 1105 |
+
Reads the content of the output file and filters out all the tests in a list of given folders.
|
| 1106 |
+
|
| 1107 |
+
Args:
|
| 1108 |
+
output_file (`str` or `os.PathLike`): The path to the output file of the tests fetcher.
|
| 1109 |
+
filters (`List[str]`): A list of folders to filter.
|
| 1110 |
+
"""
|
| 1111 |
+
if not os.path.isfile(output_file):
|
| 1112 |
+
print("No test file found.")
|
| 1113 |
+
return
|
| 1114 |
+
with open(output_file, "r", encoding="utf-8") as f:
|
| 1115 |
+
test_files = f.read().split(" ")
|
| 1116 |
+
|
| 1117 |
+
if len(test_files) == 0 or test_files == [""]:
|
| 1118 |
+
print("No tests to filter.")
|
| 1119 |
+
return
|
| 1120 |
+
|
| 1121 |
+
if test_files == ["tests"]:
|
| 1122 |
+
test_files = [os.path.join("tests", f) for f in os.listdir("tests") if f not in ["__init__.py"] + filters]
|
| 1123 |
+
else:
|
| 1124 |
+
test_files = [f for f in test_files if f.split(os.path.sep)[1] not in filters]
|
| 1125 |
+
|
| 1126 |
+
with open(output_file, "w", encoding="utf-8") as f:
|
| 1127 |
+
f.write(" ".join(test_files))
|
| 1128 |
+
|
| 1129 |
+
|
| 1130 |
+
def parse_commit_message(commit_message: str) -> Dict[str, bool]:
|
| 1131 |
+
"""
|
| 1132 |
+
Parses the commit message to detect if a command is there to skip, force all or part of the CI.
|
| 1133 |
+
|
| 1134 |
+
Args:
|
| 1135 |
+
commit_message (`str`): The commit message of the current commit.
|
| 1136 |
+
|
| 1137 |
+
Returns:
|
| 1138 |
+
`Dict[str, bool]`: A dictionary of strings to bools with keys the following keys: `"skip"`,
|
| 1139 |
+
`"test_all_models"` and `"test_all"`.
|
| 1140 |
+
"""
|
| 1141 |
+
if commit_message is None:
|
| 1142 |
+
return {"skip": False, "no_filter": False, "test_all": False}
|
| 1143 |
+
|
| 1144 |
+
command_search = re.search(r"\[([^\]]*)\]", commit_message)
|
| 1145 |
+
if command_search is not None:
|
| 1146 |
+
command = command_search.groups()[0]
|
| 1147 |
+
command = command.lower().replace("-", " ").replace("_", " ")
|
| 1148 |
+
skip = command in ["ci skip", "skip ci", "circleci skip", "skip circleci"]
|
| 1149 |
+
no_filter = set(command.split(" ")) == {"no", "filter"}
|
| 1150 |
+
test_all = set(command.split(" ")) == {"test", "all"}
|
| 1151 |
+
return {"skip": skip, "no_filter": no_filter, "test_all": test_all}
|
| 1152 |
+
else:
|
| 1153 |
+
return {"skip": False, "no_filter": False, "test_all": False}
|
| 1154 |
+
|
| 1155 |
+
|
| 1156 |
+
JOB_TO_TEST_FILE = {
|
| 1157 |
+
"tests_tf": r"tests/models/.*/test_modeling_tf_.*",
|
| 1158 |
+
"tests_torch": r"tests/models/.*/test_modeling_(?!(?:flax_|tf_)).*",
|
| 1159 |
+
"tests_generate": r"tests/models/.*/test_modeling_(?!(?:flax_|tf_)).*",
|
| 1160 |
+
"tests_tokenization": r"tests/models/.*/test_tokenization.*",
|
| 1161 |
+
"tests_processors": r"tests/models/.*/test_(?!(?:modeling_|tokenization_)).*", # takes feature extractors, image processors, processors
|
| 1162 |
+
"examples_torch": r"examples/pytorch/.*test_.*",
|
| 1163 |
+
"examples_tensorflow": r"examples/tensorflow/.*test_.*",
|
| 1164 |
+
"tests_exotic_models": r"tests/models/.*(?=layoutlmv|nat|deta|udop|nougat).*",
|
| 1165 |
+
"tests_custom_tokenizers": r"tests/models/.*/test_tokenization_(?=bert_japanese|openai|clip).*",
|
| 1166 |
+
# "repo_utils": r"tests/[^models].*test.*", TODO later on we might want to do
|
| 1167 |
+
"pipelines_tf": r"tests/models/.*/test_modeling_tf_.*",
|
| 1168 |
+
"pipelines_torch": r"tests/models/.*/test_modeling_(?!(?:flax_|tf_)).*",
|
| 1169 |
+
"tests_hub": r"tests/.*",
|
| 1170 |
+
"tests_onnx": r"tests/models/.*/test_modeling_(?:tf_|(?!flax)).*",
|
| 1171 |
+
"tests_non_model": r"tests/[^/]*?/test_.*\.py",
|
| 1172 |
+
}
|
| 1173 |
+
|
| 1174 |
+
|
| 1175 |
+
def create_test_list_from_filter(full_test_list, out_path):
|
| 1176 |
+
os.makedirs(out_path, exist_ok=True)
|
| 1177 |
+
all_test_files = "\n".join(full_test_list)
|
| 1178 |
+
for job_name, _filter in JOB_TO_TEST_FILE.items():
|
| 1179 |
+
file_name = os.path.join(out_path, f"{job_name}_test_list.txt")
|
| 1180 |
+
if job_name == "tests_hub":
|
| 1181 |
+
files_to_test = ["tests"]
|
| 1182 |
+
else:
|
| 1183 |
+
files_to_test = list(re.findall(_filter, all_test_files))
|
| 1184 |
+
print(job_name, file_name)
|
| 1185 |
+
if len(files_to_test) > 0: # No tests -> no file with test list
|
| 1186 |
+
with open(file_name, "w") as f:
|
| 1187 |
+
f.write("\n".join(files_to_test))
|
| 1188 |
+
|
| 1189 |
+
|
| 1190 |
+
if __name__ == "__main__":
|
| 1191 |
+
parser = argparse.ArgumentParser()
|
| 1192 |
+
parser.add_argument(
|
| 1193 |
+
"--output_file", type=str, default="test_list.txt", help="Where to store the list of tests to run"
|
| 1194 |
+
)
|
| 1195 |
+
parser.add_argument(
|
| 1196 |
+
"--json_output_file",
|
| 1197 |
+
type=str,
|
| 1198 |
+
default="test_map.json",
|
| 1199 |
+
help="Where to store the tests to run in a dictionary format mapping test categories to test files",
|
| 1200 |
+
)
|
| 1201 |
+
parser.add_argument(
|
| 1202 |
+
"--diff_with_last_commit",
|
| 1203 |
+
action="store_true",
|
| 1204 |
+
help="To fetch the tests between the current commit and the last commit",
|
| 1205 |
+
)
|
| 1206 |
+
parser.add_argument(
|
| 1207 |
+
"--filter_tests",
|
| 1208 |
+
action="store_true",
|
| 1209 |
+
help="Will filter the pipeline/repo utils tests outside of the generated list of tests.",
|
| 1210 |
+
)
|
| 1211 |
+
parser.add_argument(
|
| 1212 |
+
"--print_dependencies_of",
|
| 1213 |
+
type=str,
|
| 1214 |
+
help="Will only print the tree of modules depending on the file passed.",
|
| 1215 |
+
default=None,
|
| 1216 |
+
)
|
| 1217 |
+
parser.add_argument(
|
| 1218 |
+
"--fetch_all",
|
| 1219 |
+
action="store_true",
|
| 1220 |
+
help="Will fetch all tests.",
|
| 1221 |
+
default=None,
|
| 1222 |
+
)
|
| 1223 |
+
args = parser.parse_args()
|
| 1224 |
+
if args.print_dependencies_of is not None:
|
| 1225 |
+
print_tree_deps_of(args.print_dependencies_of)
|
| 1226 |
+
elif args.filter_tests:
|
| 1227 |
+
filter_tests(args.output_file, ["pipelines", "repo_utils"])
|
| 1228 |
+
else:
|
| 1229 |
+
repo = Repo(PATH_TO_REPO)
|
| 1230 |
+
commit_message = repo.head.commit.message
|
| 1231 |
+
commit_flags = parse_commit_message(commit_message)
|
| 1232 |
+
if commit_flags["skip"]:
|
| 1233 |
+
print("Force-skipping the CI")
|
| 1234 |
+
quit()
|
| 1235 |
+
if commit_flags["no_filter"]:
|
| 1236 |
+
print("Running all tests fetched without filtering.")
|
| 1237 |
+
|
| 1238 |
+
if args.fetch_all:
|
| 1239 |
+
commit_flags["test_all"] = True
|
| 1240 |
+
if commit_flags["test_all"]:
|
| 1241 |
+
print("Force-launching all tests")
|
| 1242 |
+
|
| 1243 |
+
is_main_branch = not repo.head.is_detached and repo.head.ref == repo.refs.main
|
| 1244 |
+
diff_with_last_commit = args.diff_with_last_commit
|
| 1245 |
+
if not diff_with_last_commit and is_main_branch:
|
| 1246 |
+
print("main branch detected, fetching tests against last commit.")
|
| 1247 |
+
diff_with_last_commit = True
|
| 1248 |
+
|
| 1249 |
+
infer_tests_to_run(
|
| 1250 |
+
args.output_file,
|
| 1251 |
+
diff_with_last_commit=diff_with_last_commit,
|
| 1252 |
+
filter_models=False,
|
| 1253 |
+
test_all=commit_flags["test_all"],
|
| 1254 |
+
)
|
| 1255 |
+
filter_tests(args.output_file, ["repo_utils"])
|
tasks/tasksmith-e0f68dd4420c/environment/source/utils/tf_ops/onnx.json
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"opsets": {
|
| 3 |
+
"1": [
|
| 4 |
+
"Abs",
|
| 5 |
+
"Add",
|
| 6 |
+
"AddV2",
|
| 7 |
+
"ArgMax",
|
| 8 |
+
"ArgMin",
|
| 9 |
+
"AvgPool",
|
| 10 |
+
"AvgPool3D",
|
| 11 |
+
"BatchMatMul",
|
| 12 |
+
"BatchMatMulV2",
|
| 13 |
+
"BatchToSpaceND",
|
| 14 |
+
"BiasAdd",
|
| 15 |
+
"BiasAddV1",
|
| 16 |
+
"Cast",
|
| 17 |
+
"Ceil",
|
| 18 |
+
"CheckNumerics",
|
| 19 |
+
"ComplexAbs",
|
| 20 |
+
"Concat",
|
| 21 |
+
"ConcatV2",
|
| 22 |
+
"Const",
|
| 23 |
+
"ConstV2",
|
| 24 |
+
"Conv1D",
|
| 25 |
+
"Conv2D",
|
| 26 |
+
"Conv2DBackpropInput",
|
| 27 |
+
"Conv3D",
|
| 28 |
+
"Conv3DBackpropInputV2",
|
| 29 |
+
"DepthToSpace",
|
| 30 |
+
"DepthwiseConv2d",
|
| 31 |
+
"DepthwiseConv2dNative",
|
| 32 |
+
"Div",
|
| 33 |
+
"Dropout",
|
| 34 |
+
"Elu",
|
| 35 |
+
"Equal",
|
| 36 |
+
"Erf",
|
| 37 |
+
"Exp",
|
| 38 |
+
"ExpandDims",
|
| 39 |
+
"Flatten",
|
| 40 |
+
"Floor",
|
| 41 |
+
"Gather",
|
| 42 |
+
"GatherNd",
|
| 43 |
+
"GatherV2",
|
| 44 |
+
"Greater",
|
| 45 |
+
"Identity",
|
| 46 |
+
"IdentityN",
|
| 47 |
+
"If",
|
| 48 |
+
"LRN",
|
| 49 |
+
"LSTMBlockCell",
|
| 50 |
+
"LeakyRelu",
|
| 51 |
+
"Less",
|
| 52 |
+
"Log",
|
| 53 |
+
"LogSoftmax",
|
| 54 |
+
"LogicalAnd",
|
| 55 |
+
"LogicalNot",
|
| 56 |
+
"LogicalOr",
|
| 57 |
+
"LookupTableSizeV2",
|
| 58 |
+
"MatMul",
|
| 59 |
+
"Max",
|
| 60 |
+
"MaxPool",
|
| 61 |
+
"MaxPool3D",
|
| 62 |
+
"MaxPoolV2",
|
| 63 |
+
"Maximum",
|
| 64 |
+
"Mean",
|
| 65 |
+
"Min",
|
| 66 |
+
"Minimum",
|
| 67 |
+
"MirrorPad",
|
| 68 |
+
"Mul",
|
| 69 |
+
"Neg",
|
| 70 |
+
"NoOp",
|
| 71 |
+
"NotEqual",
|
| 72 |
+
"OneHot",
|
| 73 |
+
"Pack",
|
| 74 |
+
"Pad",
|
| 75 |
+
"PadV2",
|
| 76 |
+
"Placeholder",
|
| 77 |
+
"PlaceholderV2",
|
| 78 |
+
"PlaceholderWithDefault",
|
| 79 |
+
"Pow",
|
| 80 |
+
"Prod",
|
| 81 |
+
"RFFT",
|
| 82 |
+
"RandomNormal",
|
| 83 |
+
"RandomNormalLike",
|
| 84 |
+
"RandomUniform",
|
| 85 |
+
"RandomUniformLike",
|
| 86 |
+
"RealDiv",
|
| 87 |
+
"Reciprocal",
|
| 88 |
+
"Relu",
|
| 89 |
+
"Relu6",
|
| 90 |
+
"Reshape",
|
| 91 |
+
"Rsqrt",
|
| 92 |
+
"Selu",
|
| 93 |
+
"Shape",
|
| 94 |
+
"Sigmoid",
|
| 95 |
+
"Sign",
|
| 96 |
+
"Size",
|
| 97 |
+
"Slice",
|
| 98 |
+
"Softmax",
|
| 99 |
+
"Softplus",
|
| 100 |
+
"Softsign",
|
| 101 |
+
"SpaceToBatchND",
|
| 102 |
+
"SpaceToDepth",
|
| 103 |
+
"Split",
|
| 104 |
+
"SplitV",
|
| 105 |
+
"Sqrt",
|
| 106 |
+
"Square",
|
| 107 |
+
"SquaredDifference",
|
| 108 |
+
"Squeeze",
|
| 109 |
+
"StatelessIf",
|
| 110 |
+
"StopGradient",
|
| 111 |
+
"StridedSlice",
|
| 112 |
+
"StringJoin",
|
| 113 |
+
"Sub",
|
| 114 |
+
"Sum",
|
| 115 |
+
"Tanh",
|
| 116 |
+
"Tile",
|
| 117 |
+
"TopKV2",
|
| 118 |
+
"Transpose",
|
| 119 |
+
"TruncateDiv",
|
| 120 |
+
"Unpack",
|
| 121 |
+
"ZerosLike"
|
| 122 |
+
],
|
| 123 |
+
"2": [],
|
| 124 |
+
"3": [],
|
| 125 |
+
"4": [],
|
| 126 |
+
"5": [],
|
| 127 |
+
"6": [
|
| 128 |
+
"AddN",
|
| 129 |
+
"All",
|
| 130 |
+
"Any",
|
| 131 |
+
"FloorDiv",
|
| 132 |
+
"FusedBatchNorm",
|
| 133 |
+
"FusedBatchNormV2",
|
| 134 |
+
"FusedBatchNormV3"
|
| 135 |
+
],
|
| 136 |
+
"7": [
|
| 137 |
+
"Acos",
|
| 138 |
+
"Asin",
|
| 139 |
+
"Atan",
|
| 140 |
+
"Cos",
|
| 141 |
+
"Fill",
|
| 142 |
+
"FloorMod",
|
| 143 |
+
"GreaterEqual",
|
| 144 |
+
"LessEqual",
|
| 145 |
+
"Loop",
|
| 146 |
+
"MatrixBandPart",
|
| 147 |
+
"Multinomial",
|
| 148 |
+
"Range",
|
| 149 |
+
"ResizeBilinear",
|
| 150 |
+
"ResizeNearestNeighbor",
|
| 151 |
+
"Scan",
|
| 152 |
+
"Select",
|
| 153 |
+
"SelectV2",
|
| 154 |
+
"Sin",
|
| 155 |
+
"SoftmaxCrossEntropyWithLogits",
|
| 156 |
+
"SparseSoftmaxCrossEntropyWithLogits",
|
| 157 |
+
"StatelessWhile",
|
| 158 |
+
"Tan",
|
| 159 |
+
"TensorListFromTensor",
|
| 160 |
+
"TensorListGetItem",
|
| 161 |
+
"TensorListLength",
|
| 162 |
+
"TensorListReserve",
|
| 163 |
+
"TensorListResize",
|
| 164 |
+
"TensorListSetItem",
|
| 165 |
+
"TensorListStack",
|
| 166 |
+
"While"
|
| 167 |
+
],
|
| 168 |
+
"8": [
|
| 169 |
+
"BroadcastTo",
|
| 170 |
+
"ClipByValue",
|
| 171 |
+
"FIFOQueueV2",
|
| 172 |
+
"HashTableV2",
|
| 173 |
+
"IteratorGetNext",
|
| 174 |
+
"IteratorV2",
|
| 175 |
+
"LookupTableFindV2",
|
| 176 |
+
"MaxPoolWithArgmax",
|
| 177 |
+
"QueueDequeueManyV2",
|
| 178 |
+
"QueueDequeueUpToV2",
|
| 179 |
+
"QueueDequeueV2",
|
| 180 |
+
"ReverseSequence"
|
| 181 |
+
],
|
| 182 |
+
"9": [
|
| 183 |
+
"SegmentMax",
|
| 184 |
+
"SegmentMean",
|
| 185 |
+
"SegmentMin",
|
| 186 |
+
"SegmentProd",
|
| 187 |
+
"SegmentSum",
|
| 188 |
+
"Sinh",
|
| 189 |
+
"SparseSegmentMean",
|
| 190 |
+
"SparseSegmentMeanWithNumSegments",
|
| 191 |
+
"SparseSegmentSqrtN",
|
| 192 |
+
"SparseSegmentSqrtNWithNumSegments",
|
| 193 |
+
"SparseSegmentSum",
|
| 194 |
+
"SparseSegmentSumWithNumSegments",
|
| 195 |
+
"UnsortedSegmentMax",
|
| 196 |
+
"UnsortedSegmentMin",
|
| 197 |
+
"UnsortedSegmentProd",
|
| 198 |
+
"UnsortedSegmentSum",
|
| 199 |
+
"Where"
|
| 200 |
+
],
|
| 201 |
+
"10": [
|
| 202 |
+
"CropAndResize",
|
| 203 |
+
"CudnnRNN",
|
| 204 |
+
"DynamicStitch",
|
| 205 |
+
"FakeQuantWithMinMaxArgs",
|
| 206 |
+
"IsFinite",
|
| 207 |
+
"IsInf",
|
| 208 |
+
"NonMaxSuppressionV2",
|
| 209 |
+
"NonMaxSuppressionV3",
|
| 210 |
+
"NonMaxSuppressionV4",
|
| 211 |
+
"NonMaxSuppressionV5",
|
| 212 |
+
"ParallelDynamicStitch",
|
| 213 |
+
"ReverseV2",
|
| 214 |
+
"Roll"
|
| 215 |
+
],
|
| 216 |
+
"11": [
|
| 217 |
+
"Bincount",
|
| 218 |
+
"Cumsum",
|
| 219 |
+
"InvertPermutation",
|
| 220 |
+
"LeftShift",
|
| 221 |
+
"MatrixDeterminant",
|
| 222 |
+
"MatrixDiagPart",
|
| 223 |
+
"MatrixDiagPartV2",
|
| 224 |
+
"MatrixDiagPartV3",
|
| 225 |
+
"RaggedRange",
|
| 226 |
+
"RightShift",
|
| 227 |
+
"Round",
|
| 228 |
+
"ScatterNd",
|
| 229 |
+
"SparseFillEmptyRows",
|
| 230 |
+
"SparseReshape",
|
| 231 |
+
"SparseToDense",
|
| 232 |
+
"TensorScatterUpdate",
|
| 233 |
+
"Unique"
|
| 234 |
+
],
|
| 235 |
+
"12": [
|
| 236 |
+
"Einsum",
|
| 237 |
+
"MatrixDiag",
|
| 238 |
+
"MatrixDiagV2",
|
| 239 |
+
"MatrixDiagV3",
|
| 240 |
+
"MatrixSetDiagV3",
|
| 241 |
+
"SquaredDistance"
|
| 242 |
+
],
|
| 243 |
+
"13": []
|
| 244 |
+
}
|
| 245 |
+
}
|
tasks/tasksmith-e0f68dd4420c/environment/source/utils/update_metadata.py
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Utility that updates the metadata of the Transformers library in the repository `huggingface/transformers-metadata`.
|
| 17 |
+
|
| 18 |
+
Usage for an update (as used by the GitHub action `update_metadata`):
|
| 19 |
+
|
| 20 |
+
```bash
|
| 21 |
+
python utils/update_metadata.py --token <token> --commit_sha <commit_sha>
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
Usage to check all pipelines are properly defined in the constant `PIPELINE_TAGS_AND_AUTO_MODELS` of this script, so
|
| 25 |
+
that new pipelines are properly added as metadata (as used in `make repo-consistency`):
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
python utils/update_metadata.py --check-only
|
| 29 |
+
```
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
import argparse
|
| 33 |
+
import collections
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import tempfile
|
| 37 |
+
from typing import Dict, List, Tuple
|
| 38 |
+
|
| 39 |
+
import pandas as pd
|
| 40 |
+
from datasets import Dataset
|
| 41 |
+
from huggingface_hub import hf_hub_download, upload_folder
|
| 42 |
+
|
| 43 |
+
from transformers.utils import direct_transformers_import
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# All paths are set with the intent you should run this script from the root of the repo with the command
|
| 47 |
+
# python utils/update_metadata.py
|
| 48 |
+
TRANSFORMERS_PATH = "src/transformers"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# This is to make sure the transformers module imported is the one in the repo.
|
| 52 |
+
transformers_module = direct_transformers_import(TRANSFORMERS_PATH)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# Regexes that match TF/Flax/PT model names.
|
| 56 |
+
_re_tf_models = re.compile(r"TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)")
|
| 57 |
+
_re_flax_models = re.compile(r"Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)")
|
| 58 |
+
# Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes.
|
| 59 |
+
_re_pt_models = re.compile(r"(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration|ForRetrieval)")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# Fill this with tuples (pipeline_tag, model_mapping, auto_model)
|
| 63 |
+
PIPELINE_TAGS_AND_AUTO_MODELS = [
|
| 64 |
+
("pretraining", "MODEL_FOR_PRETRAINING_MAPPING_NAMES", "AutoModelForPreTraining"),
|
| 65 |
+
("feature-extraction", "MODEL_MAPPING_NAMES", "AutoModel"),
|
| 66 |
+
("image-feature-extraction", "MODEL_FOR_IMAGE_MAPPING_NAMES", "AutoModel"),
|
| 67 |
+
("audio-classification", "MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES", "AutoModelForAudioClassification"),
|
| 68 |
+
("text-generation", "MODEL_FOR_CAUSAL_LM_MAPPING_NAMES", "AutoModelForCausalLM"),
|
| 69 |
+
("automatic-speech-recognition", "MODEL_FOR_CTC_MAPPING_NAMES", "AutoModelForCTC"),
|
| 70 |
+
("image-classification", "MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES", "AutoModelForImageClassification"),
|
| 71 |
+
("image-segmentation", "MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES", "AutoModelForImageSegmentation"),
|
| 72 |
+
("image-text-to-text", "MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES", "AutoModelForImageTextToText"),
|
| 73 |
+
("image-to-image", "MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES", "AutoModelForImageToImage"),
|
| 74 |
+
("fill-mask", "MODEL_FOR_MASKED_LM_MAPPING_NAMES", "AutoModelForMaskedLM"),
|
| 75 |
+
("object-detection", "MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES", "AutoModelForObjectDetection"),
|
| 76 |
+
(
|
| 77 |
+
"zero-shot-object-detection",
|
| 78 |
+
"MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES",
|
| 79 |
+
"AutoModelForZeroShotObjectDetection",
|
| 80 |
+
),
|
| 81 |
+
("question-answering", "MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES", "AutoModelForQuestionAnswering"),
|
| 82 |
+
("text2text-generation", "MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES", "AutoModelForSeq2SeqLM"),
|
| 83 |
+
("text-classification", "MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES", "AutoModelForSequenceClassification"),
|
| 84 |
+
("automatic-speech-recognition", "MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES", "AutoModelForSpeechSeq2Seq"),
|
| 85 |
+
(
|
| 86 |
+
"table-question-answering",
|
| 87 |
+
"MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES",
|
| 88 |
+
"AutoModelForTableQuestionAnswering",
|
| 89 |
+
),
|
| 90 |
+
("token-classification", "MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES", "AutoModelForTokenClassification"),
|
| 91 |
+
("multiple-choice", "MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES", "AutoModelForMultipleChoice"),
|
| 92 |
+
(
|
| 93 |
+
"next-sentence-prediction",
|
| 94 |
+
"MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES",
|
| 95 |
+
"AutoModelForNextSentencePrediction",
|
| 96 |
+
),
|
| 97 |
+
(
|
| 98 |
+
"audio-frame-classification",
|
| 99 |
+
"MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES",
|
| 100 |
+
"AutoModelForAudioFrameClassification",
|
| 101 |
+
),
|
| 102 |
+
("audio-xvector", "MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES", "AutoModelForAudioXVector"),
|
| 103 |
+
(
|
| 104 |
+
"document-question-answering",
|
| 105 |
+
"MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES",
|
| 106 |
+
"AutoModelForDocumentQuestionAnswering",
|
| 107 |
+
),
|
| 108 |
+
(
|
| 109 |
+
"visual-question-answering",
|
| 110 |
+
"MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES",
|
| 111 |
+
"AutoModelForVisualQuestionAnswering",
|
| 112 |
+
),
|
| 113 |
+
("image-to-text", "MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES", "AutoModelForVision2Seq"),
|
| 114 |
+
(
|
| 115 |
+
"zero-shot-image-classification",
|
| 116 |
+
"MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES",
|
| 117 |
+
"AutoModelForZeroShotImageClassification",
|
| 118 |
+
),
|
| 119 |
+
("depth-estimation", "MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES", "AutoModelForDepthEstimation"),
|
| 120 |
+
("video-classification", "MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES", "AutoModelForVideoClassification"),
|
| 121 |
+
("mask-generation", "MODEL_FOR_MASK_GENERATION_MAPPING_NAMES", "AutoModelForMaskGeneration"),
|
| 122 |
+
("text-to-audio", "MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES", "AutoModelForTextToSpectrogram"),
|
| 123 |
+
("text-to-audio", "MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES", "AutoModelForTextToWaveform"),
|
| 124 |
+
]
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def camel_case_split(identifier: str) -> List[str]:
|
| 128 |
+
"""
|
| 129 |
+
Split a camel-cased name into words.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
identifier (`str`): The camel-cased name to parse.
|
| 133 |
+
|
| 134 |
+
Returns:
|
| 135 |
+
`List[str]`: The list of words in the identifier (as seprated by capital letters).
|
| 136 |
+
|
| 137 |
+
Example:
|
| 138 |
+
|
| 139 |
+
```py
|
| 140 |
+
>>> camel_case_split("CamelCasedClass")
|
| 141 |
+
["Camel", "Cased", "Class"]
|
| 142 |
+
```
|
| 143 |
+
"""
|
| 144 |
+
# Regex thanks to https://stackoverflow.com/questions/29916065/how-to-do-camelcase-split-in-python
|
| 145 |
+
matches = re.finditer(".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)", identifier)
|
| 146 |
+
return [m.group(0) for m in matches]
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def get_frameworks_table() -> pd.DataFrame:
|
| 150 |
+
"""
|
| 151 |
+
Generates a dataframe containing the supported auto classes for each model type, using the content of the auto
|
| 152 |
+
modules.
|
| 153 |
+
"""
|
| 154 |
+
# Dictionary model names to config.
|
| 155 |
+
config_maping_names = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
|
| 156 |
+
model_prefix_to_model_type = {
|
| 157 |
+
config.replace("Config", ""): model_type for model_type, config in config_maping_names.items()
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
# Dictionaries flagging if each model prefix has a backend in PT/TF/Flax.
|
| 161 |
+
pt_models = collections.defaultdict(bool)
|
| 162 |
+
tf_models = collections.defaultdict(bool)
|
| 163 |
+
flax_models = collections.defaultdict(bool)
|
| 164 |
+
|
| 165 |
+
# Let's lookup through all transformers object (once) and find if models are supported by a given backend.
|
| 166 |
+
for attr_name in dir(transformers_module):
|
| 167 |
+
lookup_dict = None
|
| 168 |
+
if _re_tf_models.match(attr_name) is not None:
|
| 169 |
+
lookup_dict = tf_models
|
| 170 |
+
attr_name = _re_tf_models.match(attr_name).groups()[0]
|
| 171 |
+
elif _re_flax_models.match(attr_name) is not None:
|
| 172 |
+
lookup_dict = flax_models
|
| 173 |
+
attr_name = _re_flax_models.match(attr_name).groups()[0]
|
| 174 |
+
elif _re_pt_models.match(attr_name) is not None:
|
| 175 |
+
lookup_dict = pt_models
|
| 176 |
+
attr_name = _re_pt_models.match(attr_name).groups()[0]
|
| 177 |
+
|
| 178 |
+
if lookup_dict is not None:
|
| 179 |
+
while len(attr_name) > 0:
|
| 180 |
+
if attr_name in model_prefix_to_model_type:
|
| 181 |
+
lookup_dict[model_prefix_to_model_type[attr_name]] = True
|
| 182 |
+
break
|
| 183 |
+
# Try again after removing the last word in the name
|
| 184 |
+
attr_name = "".join(camel_case_split(attr_name)[:-1])
|
| 185 |
+
|
| 186 |
+
all_models = set(list(pt_models.keys()) + list(tf_models.keys()) + list(flax_models.keys()))
|
| 187 |
+
all_models = list(all_models)
|
| 188 |
+
all_models.sort()
|
| 189 |
+
|
| 190 |
+
data = {"model_type": all_models}
|
| 191 |
+
data["pytorch"] = [pt_models[t] for t in all_models]
|
| 192 |
+
data["tensorflow"] = [tf_models[t] for t in all_models]
|
| 193 |
+
data["flax"] = [flax_models[t] for t in all_models]
|
| 194 |
+
|
| 195 |
+
# Now let's find the right processing class for each model. In order we check if there is a Processor, then a
|
| 196 |
+
# Tokenizer, then a FeatureExtractor, then an ImageProcessor
|
| 197 |
+
processors = {}
|
| 198 |
+
for t in all_models:
|
| 199 |
+
if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES:
|
| 200 |
+
processors[t] = "AutoProcessor"
|
| 201 |
+
elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES:
|
| 202 |
+
processors[t] = "AutoTokenizer"
|
| 203 |
+
elif t in transformers_module.models.auto.image_processing_auto.IMAGE_PROCESSOR_MAPPING_NAMES:
|
| 204 |
+
processors[t] = "AutoImageProcessor"
|
| 205 |
+
elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES:
|
| 206 |
+
processors[t] = "AutoFeatureExtractor"
|
| 207 |
+
else:
|
| 208 |
+
# Default to AutoTokenizer if a model has nothing, for backward compatibility.
|
| 209 |
+
processors[t] = "AutoTokenizer"
|
| 210 |
+
|
| 211 |
+
data["processor"] = [processors[t] for t in all_models]
|
| 212 |
+
|
| 213 |
+
return pd.DataFrame(data)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def update_pipeline_and_auto_class_table(table: Dict[str, Tuple[str, str]]) -> Dict[str, Tuple[str, str]]:
|
| 217 |
+
"""
|
| 218 |
+
Update the table maping models to pipelines and auto classes without removing old keys if they don't exist anymore.
|
| 219 |
+
|
| 220 |
+
Args:
|
| 221 |
+
table (`Dict[str, Tuple[str, str]]`):
|
| 222 |
+
The existing table mapping model names to a tuple containing the pipeline tag and the auto-class name with
|
| 223 |
+
which they should be used.
|
| 224 |
+
|
| 225 |
+
Returns:
|
| 226 |
+
`Dict[str, Tuple[str, str]]`: The updated table in the same format.
|
| 227 |
+
"""
|
| 228 |
+
auto_modules = [
|
| 229 |
+
transformers_module.models.auto.modeling_auto,
|
| 230 |
+
transformers_module.models.auto.modeling_tf_auto,
|
| 231 |
+
transformers_module.models.auto.modeling_flax_auto,
|
| 232 |
+
]
|
| 233 |
+
for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS:
|
| 234 |
+
model_mappings = [model_mapping, f"TF_{model_mapping}", f"FLAX_{model_mapping}"]
|
| 235 |
+
auto_classes = [auto_class, f"TF_{auto_class}", f"Flax_{auto_class}"]
|
| 236 |
+
# Loop through all three frameworks
|
| 237 |
+
for module, cls, mapping in zip(auto_modules, auto_classes, model_mappings):
|
| 238 |
+
# The type of pipeline may not exist in this framework
|
| 239 |
+
if not hasattr(module, mapping):
|
| 240 |
+
continue
|
| 241 |
+
# First extract all model_names
|
| 242 |
+
model_names = []
|
| 243 |
+
for name in getattr(module, mapping).values():
|
| 244 |
+
if isinstance(name, str):
|
| 245 |
+
model_names.append(name)
|
| 246 |
+
else:
|
| 247 |
+
model_names.extend(list(name))
|
| 248 |
+
|
| 249 |
+
# Add pipeline tag and auto model class for those models
|
| 250 |
+
table.update({model_name: (pipeline_tag, cls) for model_name in model_names})
|
| 251 |
+
|
| 252 |
+
return table
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def update_metadata(token: str, commit_sha: str):
|
| 256 |
+
"""
|
| 257 |
+
Update the metadata for the Transformers repo in `huggingface/transformers-metadata`.
|
| 258 |
+
|
| 259 |
+
Args:
|
| 260 |
+
token (`str`): A valid token giving write access to `huggingface/transformers-metadata`.
|
| 261 |
+
commit_sha (`str`): The commit SHA on Transformers corresponding to this update.
|
| 262 |
+
"""
|
| 263 |
+
frameworks_table = get_frameworks_table()
|
| 264 |
+
frameworks_dataset = Dataset.from_pandas(frameworks_table)
|
| 265 |
+
|
| 266 |
+
resolved_tags_file = hf_hub_download(
|
| 267 |
+
"huggingface/transformers-metadata", "pipeline_tags.json", repo_type="dataset", token=token
|
| 268 |
+
)
|
| 269 |
+
tags_dataset = Dataset.from_json(resolved_tags_file)
|
| 270 |
+
table = {
|
| 271 |
+
tags_dataset[i]["model_class"]: (tags_dataset[i]["pipeline_tag"], tags_dataset[i]["auto_class"])
|
| 272 |
+
for i in range(len(tags_dataset))
|
| 273 |
+
}
|
| 274 |
+
table = update_pipeline_and_auto_class_table(table)
|
| 275 |
+
|
| 276 |
+
# Sort the model classes to avoid some nondeterministic updates to create false update commits.
|
| 277 |
+
model_classes = sorted(table.keys())
|
| 278 |
+
tags_table = pd.DataFrame(
|
| 279 |
+
{
|
| 280 |
+
"model_class": model_classes,
|
| 281 |
+
"pipeline_tag": [table[m][0] for m in model_classes],
|
| 282 |
+
"auto_class": [table[m][1] for m in model_classes],
|
| 283 |
+
}
|
| 284 |
+
)
|
| 285 |
+
tags_dataset = Dataset.from_pandas(tags_table)
|
| 286 |
+
|
| 287 |
+
hub_frameworks_json = hf_hub_download(
|
| 288 |
+
repo_id="huggingface/transformers-metadata",
|
| 289 |
+
filename="frameworks.json",
|
| 290 |
+
repo_type="dataset",
|
| 291 |
+
token=token,
|
| 292 |
+
)
|
| 293 |
+
with open(hub_frameworks_json) as f:
|
| 294 |
+
hub_frameworks_json = f.read()
|
| 295 |
+
|
| 296 |
+
hub_pipeline_tags_json = hf_hub_download(
|
| 297 |
+
repo_id="huggingface/transformers-metadata",
|
| 298 |
+
filename="pipeline_tags.json",
|
| 299 |
+
repo_type="dataset",
|
| 300 |
+
token=token,
|
| 301 |
+
)
|
| 302 |
+
with open(hub_pipeline_tags_json) as f:
|
| 303 |
+
hub_pipeline_tags_json = f.read()
|
| 304 |
+
|
| 305 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 306 |
+
frameworks_dataset.to_json(os.path.join(tmp_dir, "frameworks.json"))
|
| 307 |
+
tags_dataset.to_json(os.path.join(tmp_dir, "pipeline_tags.json"))
|
| 308 |
+
|
| 309 |
+
with open(os.path.join(tmp_dir, "frameworks.json")) as f:
|
| 310 |
+
frameworks_json = f.read()
|
| 311 |
+
with open(os.path.join(tmp_dir, "pipeline_tags.json")) as f:
|
| 312 |
+
pipeline_tags_json = f.read()
|
| 313 |
+
|
| 314 |
+
frameworks_equal = hub_frameworks_json == frameworks_json
|
| 315 |
+
hub_pipeline_tags_equal = hub_pipeline_tags_json == pipeline_tags_json
|
| 316 |
+
|
| 317 |
+
if frameworks_equal and hub_pipeline_tags_equal:
|
| 318 |
+
print("No updates on the Hub, not pushing the metadata files.")
|
| 319 |
+
return
|
| 320 |
+
|
| 321 |
+
if commit_sha is not None:
|
| 322 |
+
commit_message = (
|
| 323 |
+
f"Update with commit {commit_sha}\n\nSee: "
|
| 324 |
+
f"https://github.com/huggingface/transformers/commit/{commit_sha}"
|
| 325 |
+
)
|
| 326 |
+
else:
|
| 327 |
+
commit_message = "Update"
|
| 328 |
+
|
| 329 |
+
upload_folder(
|
| 330 |
+
repo_id="huggingface/transformers-metadata",
|
| 331 |
+
folder_path=tmp_dir,
|
| 332 |
+
repo_type="dataset",
|
| 333 |
+
token=token,
|
| 334 |
+
commit_message=commit_message,
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def check_pipeline_tags():
|
| 339 |
+
"""
|
| 340 |
+
Check all pipeline tags are properly defined in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant of this script.
|
| 341 |
+
"""
|
| 342 |
+
in_table = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS}
|
| 343 |
+
pipeline_tasks = transformers_module.pipelines.SUPPORTED_TASKS
|
| 344 |
+
missing = []
|
| 345 |
+
for key in pipeline_tasks:
|
| 346 |
+
if key not in in_table:
|
| 347 |
+
model = pipeline_tasks[key]["pt"]
|
| 348 |
+
if isinstance(model, (list, tuple)):
|
| 349 |
+
model = model[0]
|
| 350 |
+
model = model.__name__
|
| 351 |
+
if model not in in_table.values():
|
| 352 |
+
missing.append(key)
|
| 353 |
+
|
| 354 |
+
if len(missing) > 0:
|
| 355 |
+
msg = ", ".join(missing)
|
| 356 |
+
raise ValueError(
|
| 357 |
+
"The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside "
|
| 358 |
+
f"`utils/update_metadata.py`: {msg}. Please add them!"
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
if __name__ == "__main__":
|
| 363 |
+
parser = argparse.ArgumentParser()
|
| 364 |
+
parser.add_argument("--token", type=str, help="The token to use to push to the transformers-metadata dataset.")
|
| 365 |
+
parser.add_argument("--commit_sha", type=str, help="The sha of the commit going with this update.")
|
| 366 |
+
parser.add_argument("--check-only", action="store_true", help="Activate to just check all pipelines are present.")
|
| 367 |
+
args = parser.parse_args()
|
| 368 |
+
|
| 369 |
+
if args.check_only:
|
| 370 |
+
check_pipeline_tags()
|
| 371 |
+
else:
|
| 372 |
+
update_metadata(args.token, args.commit_sha)
|
tasks/tasksmith-e0f68dd4420c/environment/source/utils/update_tiny_models.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""A script running `create_dummy_models.py` with a pre-defined set of arguments.
|
| 16 |
+
|
| 17 |
+
This file is intended to be used in a CI workflow file without the need of specifying arguments. It creates and uploads
|
| 18 |
+
tiny models for all model classes (if their tiny versions are not on the Hub yet), as well as produces an updated
|
| 19 |
+
version of `tests/utils/tiny_model_summary.json`. That updated file should be merged into the `main` branch of
|
| 20 |
+
`transformers` so the pipeline testing will use the latest created/updated tiny models.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
import argparse
|
| 24 |
+
import copy
|
| 25 |
+
import json
|
| 26 |
+
import multiprocessing
|
| 27 |
+
import os
|
| 28 |
+
import time
|
| 29 |
+
|
| 30 |
+
from create_dummy_models import COMPOSITE_MODELS, create_tiny_models
|
| 31 |
+
from huggingface_hub import ModelFilter, hf_api
|
| 32 |
+
|
| 33 |
+
import transformers
|
| 34 |
+
from transformers import AutoFeatureExtractor, AutoImageProcessor, AutoTokenizer
|
| 35 |
+
from transformers.image_processing_utils import BaseImageProcessor
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def get_all_model_names():
|
| 39 |
+
model_names = set()
|
| 40 |
+
# Each auto modeling files contains multiple mappings. Let's get them in a dynamic way.
|
| 41 |
+
for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]:
|
| 42 |
+
module = getattr(transformers.models.auto, module_name, None)
|
| 43 |
+
if module is None:
|
| 44 |
+
continue
|
| 45 |
+
# all mappings in a single auto modeling file
|
| 46 |
+
mapping_names = [
|
| 47 |
+
x
|
| 48 |
+
for x in dir(module)
|
| 49 |
+
if x.endswith("_MAPPING_NAMES")
|
| 50 |
+
and (x.startswith("MODEL_") or x.startswith("TF_MODEL_") or x.startswith("FLAX_MODEL_"))
|
| 51 |
+
]
|
| 52 |
+
for name in mapping_names:
|
| 53 |
+
mapping = getattr(module, name)
|
| 54 |
+
if mapping is not None:
|
| 55 |
+
for v in mapping.values():
|
| 56 |
+
if isinstance(v, (list, tuple)):
|
| 57 |
+
model_names.update(v)
|
| 58 |
+
elif isinstance(v, str):
|
| 59 |
+
model_names.add(v)
|
| 60 |
+
|
| 61 |
+
return sorted(model_names)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def get_tiny_model_names_from_repo():
|
| 65 |
+
# All model names defined in auto mappings
|
| 66 |
+
model_names = set(get_all_model_names())
|
| 67 |
+
|
| 68 |
+
with open("tests/utils/tiny_model_summary.json") as fp:
|
| 69 |
+
tiny_model_info = json.load(fp)
|
| 70 |
+
tiny_models_names = set()
|
| 71 |
+
for model_base_name in tiny_model_info:
|
| 72 |
+
tiny_models_names.update(tiny_model_info[model_base_name]["model_classes"])
|
| 73 |
+
|
| 74 |
+
# Remove a tiny model name if one of its framework implementation hasn't yet a tiny version on the Hub.
|
| 75 |
+
not_on_hub = model_names.difference(tiny_models_names)
|
| 76 |
+
for model_name in copy.copy(tiny_models_names):
|
| 77 |
+
if not model_name.startswith("TF") and f"TF{model_name}" in not_on_hub:
|
| 78 |
+
tiny_models_names.remove(model_name)
|
| 79 |
+
elif model_name.startswith("TF") and model_name[2:] in not_on_hub:
|
| 80 |
+
tiny_models_names.remove(model_name)
|
| 81 |
+
|
| 82 |
+
return sorted(tiny_models_names)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def get_tiny_model_summary_from_hub(output_path):
|
| 86 |
+
special_models = COMPOSITE_MODELS.values()
|
| 87 |
+
|
| 88 |
+
# All tiny model base names on Hub
|
| 89 |
+
model_names = get_all_model_names()
|
| 90 |
+
models = hf_api.list_models(
|
| 91 |
+
filter=ModelFilter(
|
| 92 |
+
author="hf-internal-testing",
|
| 93 |
+
)
|
| 94 |
+
)
|
| 95 |
+
_models = set()
|
| 96 |
+
for x in models:
|
| 97 |
+
model = x.id
|
| 98 |
+
org, model = model.split("/")
|
| 99 |
+
if not model.startswith("tiny-random-"):
|
| 100 |
+
continue
|
| 101 |
+
model = model.replace("tiny-random-", "")
|
| 102 |
+
if not model[0].isupper():
|
| 103 |
+
continue
|
| 104 |
+
if model not in model_names and model not in special_models:
|
| 105 |
+
continue
|
| 106 |
+
_models.add(model)
|
| 107 |
+
|
| 108 |
+
models = sorted(_models)
|
| 109 |
+
# All tiny model names on Hub
|
| 110 |
+
summary = {}
|
| 111 |
+
for model in models:
|
| 112 |
+
repo_id = f"hf-internal-testing/tiny-random-{model}"
|
| 113 |
+
model = model.split("-")[0]
|
| 114 |
+
try:
|
| 115 |
+
repo_info = hf_api.repo_info(repo_id)
|
| 116 |
+
content = {
|
| 117 |
+
"tokenizer_classes": set(),
|
| 118 |
+
"processor_classes": set(),
|
| 119 |
+
"model_classes": set(),
|
| 120 |
+
"sha": repo_info.sha,
|
| 121 |
+
}
|
| 122 |
+
except Exception:
|
| 123 |
+
continue
|
| 124 |
+
try:
|
| 125 |
+
time.sleep(1)
|
| 126 |
+
tokenizer_fast = AutoTokenizer.from_pretrained(repo_id)
|
| 127 |
+
content["tokenizer_classes"].add(tokenizer_fast.__class__.__name__)
|
| 128 |
+
except Exception:
|
| 129 |
+
pass
|
| 130 |
+
try:
|
| 131 |
+
time.sleep(1)
|
| 132 |
+
tokenizer_slow = AutoTokenizer.from_pretrained(repo_id, use_fast=False)
|
| 133 |
+
content["tokenizer_classes"].add(tokenizer_slow.__class__.__name__)
|
| 134 |
+
except Exception:
|
| 135 |
+
pass
|
| 136 |
+
try:
|
| 137 |
+
time.sleep(1)
|
| 138 |
+
img_p = AutoImageProcessor.from_pretrained(repo_id)
|
| 139 |
+
content["processor_classes"].add(img_p.__class__.__name__)
|
| 140 |
+
except Exception:
|
| 141 |
+
pass
|
| 142 |
+
try:
|
| 143 |
+
time.sleep(1)
|
| 144 |
+
feat_p = AutoFeatureExtractor.from_pretrained(repo_id)
|
| 145 |
+
if not isinstance(feat_p, BaseImageProcessor):
|
| 146 |
+
content["processor_classes"].add(feat_p.__class__.__name__)
|
| 147 |
+
except Exception:
|
| 148 |
+
pass
|
| 149 |
+
try:
|
| 150 |
+
time.sleep(1)
|
| 151 |
+
model_class = getattr(transformers, model)
|
| 152 |
+
m = model_class.from_pretrained(repo_id)
|
| 153 |
+
content["model_classes"].add(m.__class__.__name__)
|
| 154 |
+
except Exception:
|
| 155 |
+
pass
|
| 156 |
+
try:
|
| 157 |
+
time.sleep(1)
|
| 158 |
+
model_class = getattr(transformers, f"TF{model}")
|
| 159 |
+
m = model_class.from_pretrained(repo_id)
|
| 160 |
+
content["model_classes"].add(m.__class__.__name__)
|
| 161 |
+
except Exception:
|
| 162 |
+
pass
|
| 163 |
+
|
| 164 |
+
content["tokenizer_classes"] = sorted(content["tokenizer_classes"])
|
| 165 |
+
content["processor_classes"] = sorted(content["processor_classes"])
|
| 166 |
+
content["model_classes"] = sorted(content["model_classes"])
|
| 167 |
+
|
| 168 |
+
summary[model] = content
|
| 169 |
+
with open(os.path.join(output_path, "hub_tiny_model_summary.json"), "w") as fp:
|
| 170 |
+
json.dump(summary, fp, ensure_ascii=False, indent=4)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
if __name__ == "__main__":
|
| 174 |
+
parser = argparse.ArgumentParser()
|
| 175 |
+
parser.add_argument("--num_workers", default=1, type=int, help="The number of workers to run.")
|
| 176 |
+
args = parser.parse_args()
|
| 177 |
+
|
| 178 |
+
# This has to be `spawn` to avoid hanging forever!
|
| 179 |
+
multiprocessing.set_start_method("spawn")
|
| 180 |
+
|
| 181 |
+
output_path = "tiny_models"
|
| 182 |
+
all = True
|
| 183 |
+
model_types = None
|
| 184 |
+
models_to_skip = get_tiny_model_names_from_repo()
|
| 185 |
+
no_check = True
|
| 186 |
+
upload = True
|
| 187 |
+
organization = "hf-internal-testing"
|
| 188 |
+
|
| 189 |
+
create_tiny_models(
|
| 190 |
+
output_path,
|
| 191 |
+
all,
|
| 192 |
+
model_types,
|
| 193 |
+
models_to_skip,
|
| 194 |
+
no_check,
|
| 195 |
+
upload,
|
| 196 |
+
organization,
|
| 197 |
+
token=os.environ.get("TOKEN", None),
|
| 198 |
+
num_workers=args.num_workers,
|
| 199 |
+
)
|
tasks/tasksmith-e0f68dd4420c/instruction.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Add a new `AyaVision` vision-language model family to the transformers library. The implementation must expose the following public APIs from `transformers`:
|
| 2 |
+
|
| 3 |
+
- `AyaVisionConfig` – config class with `model_type = "aya_vision"`, sub-configs `vision_config` and `text_config`, and parameters `vision_feature_select_strategy` ("default" or "full", default "full"; raises `ValueError` for anything else), `vision_feature_layer` (default -1), `downsample_factor` (default 2), `adapter_layer_norm_eps` (default 1e-6), and `image_token_index` (default 255036). When `vision_config` is `None` it defaults to a `siglip_vision_model` config; when `text_config` is `None` it defaults to a `cohere2` config. Both can also be passed as dicts.
|
| 4 |
+
- `AyaVisionProcessor` – wraps an image processor and tokenizer. Its `patch_size` attribute stores `patch_size * downsample_factor`. The `_prompt_split_image(num_patches)` method builds an image-token string: starts with `start_of_img_token`, then for each index from 1 to `num_patches-1` appends `TILE_{idx}` followed by `(img_size // patch_size)^2` copies of `img_patch_token`, then appends `tile_global_token` and the same number of patch tokens, and finishes with `end_of_img_token`. When `num_patches == 1` no numbered TILE tokens appear.
|
| 5 |
+
- `AyaVisionForConditionalGeneration` – model combining a vision tower, a multi-modal projector, and a causal LM. The projector applies pixel-shuffle (downsample factor `f` reduces `H×W` tokens to `(H/f)×(W/f)` tokens while multiplying channel dimension by `f²`), a LayerNorm, a linear expansion, a SwiGLU gate (split + silu(gate) × x), and a linear projection to text hidden size. Image features are merged into input embeddings by masked scatter at `image_token_index` positions. With labels, returns a cross-entropy loss.
|
| 6 |
+
- `AyaVisionPreTrainedModel` – base class.
|
| 7 |
+
- Registered in the auto mappings: `MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES["aya_vision"] = "AyaVisionForConditionalGeneration"`, `AutoProcessor` mapping, and `AutoTokenizer` mapping to `CohereTokenizerFast`.
|
| 8 |
+
|
| 9 |
+
Example pixel-shuffle output shape: input `(B, 64, 32)` with `downsample_factor=2` produces `(B, 4, 4, 128)`; after the full projector with `text_hidden=64` the output is `(B, 4, 4, 64)`.
|
| 10 |
+
|
| 11 |
+
The modeling module should expose `AyaVisionMultiModalProjector(config)` with a `pixel_shuffle(image_features)` method, and the full model should expose its projector as `multi_modal_projector`. For checkpoint-compatible spatial packing, view input tokens as a row-major square grid. Each output position collects its `f × f` block in row-offset, column-offset, then input-channel order; preserve the block grid's row/column order. The first half of the projector expansion is the value half and the second is the gate half. Internal layer attribute names are unrestricted.
|
| 12 |
+
|
| 13 |
+
Config save/reload must preserve all sub-config fields.
|
| 14 |
+
|
| 15 |
+
Work in `/workspace`. Submit your fix in Python source files under `src/transformers`. Preserve the other public behavior. The environment is offline; dependencies are preinstalled. Grading runs the relevant repository tests in a fresh environment, using your submitted source files.
|
tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/__init__.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/models/__init__.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from . import (
|
| 16 |
+
albert,
|
| 17 |
+
align,
|
| 18 |
+
altclip,
|
| 19 |
+
aria,
|
| 20 |
+
audio_spectrogram_transformer,
|
| 21 |
+
auto,
|
| 22 |
+
autoformer,
|
| 23 |
+
aya_vision,
|
| 24 |
+
bamba,
|
| 25 |
+
bark,
|
| 26 |
+
bart,
|
| 27 |
+
barthez,
|
| 28 |
+
bartpho,
|
| 29 |
+
beit,
|
| 30 |
+
bert,
|
| 31 |
+
bert_generation,
|
| 32 |
+
bert_japanese,
|
| 33 |
+
bertweet,
|
| 34 |
+
big_bird,
|
| 35 |
+
bigbird_pegasus,
|
| 36 |
+
biogpt,
|
| 37 |
+
bit,
|
| 38 |
+
blenderbot,
|
| 39 |
+
blenderbot_small,
|
| 40 |
+
blip,
|
| 41 |
+
blip_2,
|
| 42 |
+
bloom,
|
| 43 |
+
bridgetower,
|
| 44 |
+
bros,
|
| 45 |
+
byt5,
|
| 46 |
+
camembert,
|
| 47 |
+
canine,
|
| 48 |
+
chameleon,
|
| 49 |
+
chinese_clip,
|
| 50 |
+
clap,
|
| 51 |
+
clip,
|
| 52 |
+
clipseg,
|
| 53 |
+
clvp,
|
| 54 |
+
code_llama,
|
| 55 |
+
codegen,
|
| 56 |
+
cohere,
|
| 57 |
+
cohere2,
|
| 58 |
+
colpali,
|
| 59 |
+
conditional_detr,
|
| 60 |
+
convbert,
|
| 61 |
+
convnext,
|
| 62 |
+
convnextv2,
|
| 63 |
+
cpm,
|
| 64 |
+
cpmant,
|
| 65 |
+
ctrl,
|
| 66 |
+
cvt,
|
| 67 |
+
dab_detr,
|
| 68 |
+
dac,
|
| 69 |
+
data2vec,
|
| 70 |
+
dbrx,
|
| 71 |
+
deberta,
|
| 72 |
+
deberta_v2,
|
| 73 |
+
decision_transformer,
|
| 74 |
+
deformable_detr,
|
| 75 |
+
deit,
|
| 76 |
+
deprecated,
|
| 77 |
+
depth_anything,
|
| 78 |
+
depth_pro,
|
| 79 |
+
detr,
|
| 80 |
+
dialogpt,
|
| 81 |
+
diffllama,
|
| 82 |
+
dinat,
|
| 83 |
+
dinov2,
|
| 84 |
+
dinov2_with_registers,
|
| 85 |
+
distilbert,
|
| 86 |
+
dit,
|
| 87 |
+
donut,
|
| 88 |
+
dpr,
|
| 89 |
+
dpt,
|
| 90 |
+
efficientnet,
|
| 91 |
+
electra,
|
| 92 |
+
emu3,
|
| 93 |
+
encodec,
|
| 94 |
+
encoder_decoder,
|
| 95 |
+
ernie,
|
| 96 |
+
esm,
|
| 97 |
+
falcon,
|
| 98 |
+
falcon_mamba,
|
| 99 |
+
fastspeech2_conformer,
|
| 100 |
+
flaubert,
|
| 101 |
+
flava,
|
| 102 |
+
fnet,
|
| 103 |
+
focalnet,
|
| 104 |
+
fsmt,
|
| 105 |
+
funnel,
|
| 106 |
+
fuyu,
|
| 107 |
+
gemma,
|
| 108 |
+
gemma2,
|
| 109 |
+
git,
|
| 110 |
+
glm,
|
| 111 |
+
glpn,
|
| 112 |
+
got_ocr2,
|
| 113 |
+
gpt2,
|
| 114 |
+
gpt_bigcode,
|
| 115 |
+
gpt_neo,
|
| 116 |
+
gpt_neox,
|
| 117 |
+
gpt_neox_japanese,
|
| 118 |
+
gpt_sw3,
|
| 119 |
+
gptj,
|
| 120 |
+
granite,
|
| 121 |
+
granitemoe,
|
| 122 |
+
granitemoeshared,
|
| 123 |
+
grounding_dino,
|
| 124 |
+
groupvit,
|
| 125 |
+
helium,
|
| 126 |
+
herbert,
|
| 127 |
+
hiera,
|
| 128 |
+
hubert,
|
| 129 |
+
ibert,
|
| 130 |
+
idefics,
|
| 131 |
+
idefics2,
|
| 132 |
+
idefics3,
|
| 133 |
+
ijepa,
|
| 134 |
+
imagegpt,
|
| 135 |
+
informer,
|
| 136 |
+
instructblip,
|
| 137 |
+
instructblipvideo,
|
| 138 |
+
jamba,
|
| 139 |
+
jetmoe,
|
| 140 |
+
kosmos2,
|
| 141 |
+
layoutlm,
|
| 142 |
+
layoutlmv2,
|
| 143 |
+
layoutlmv3,
|
| 144 |
+
layoutxlm,
|
| 145 |
+
led,
|
| 146 |
+
levit,
|
| 147 |
+
lilt,
|
| 148 |
+
llama,
|
| 149 |
+
llava,
|
| 150 |
+
llava_next,
|
| 151 |
+
llava_next_video,
|
| 152 |
+
llava_onevision,
|
| 153 |
+
longformer,
|
| 154 |
+
longt5,
|
| 155 |
+
luke,
|
| 156 |
+
lxmert,
|
| 157 |
+
m2m_100,
|
| 158 |
+
mamba,
|
| 159 |
+
mamba2,
|
| 160 |
+
marian,
|
| 161 |
+
markuplm,
|
| 162 |
+
mask2former,
|
| 163 |
+
maskformer,
|
| 164 |
+
mbart,
|
| 165 |
+
mbart50,
|
| 166 |
+
megatron_bert,
|
| 167 |
+
megatron_gpt2,
|
| 168 |
+
mgp_str,
|
| 169 |
+
mimi,
|
| 170 |
+
mistral,
|
| 171 |
+
mixtral,
|
| 172 |
+
mllama,
|
| 173 |
+
mluke,
|
| 174 |
+
mobilebert,
|
| 175 |
+
mobilenet_v1,
|
| 176 |
+
mobilenet_v2,
|
| 177 |
+
mobilevit,
|
| 178 |
+
mobilevitv2,
|
| 179 |
+
modernbert,
|
| 180 |
+
moonshine,
|
| 181 |
+
moshi,
|
| 182 |
+
mpnet,
|
| 183 |
+
mpt,
|
| 184 |
+
mra,
|
| 185 |
+
mt5,
|
| 186 |
+
musicgen,
|
| 187 |
+
musicgen_melody,
|
| 188 |
+
mvp,
|
| 189 |
+
myt5,
|
| 190 |
+
nemotron,
|
| 191 |
+
nllb,
|
| 192 |
+
nllb_moe,
|
| 193 |
+
nougat,
|
| 194 |
+
nystromformer,
|
| 195 |
+
olmo,
|
| 196 |
+
olmo2,
|
| 197 |
+
olmoe,
|
| 198 |
+
omdet_turbo,
|
| 199 |
+
oneformer,
|
| 200 |
+
openai,
|
| 201 |
+
opt,
|
| 202 |
+
owlv2,
|
| 203 |
+
owlvit,
|
| 204 |
+
paligemma,
|
| 205 |
+
patchtsmixer,
|
| 206 |
+
patchtst,
|
| 207 |
+
pegasus,
|
| 208 |
+
pegasus_x,
|
| 209 |
+
perceiver,
|
| 210 |
+
persimmon,
|
| 211 |
+
phi,
|
| 212 |
+
phi3,
|
| 213 |
+
phimoe,
|
| 214 |
+
phobert,
|
| 215 |
+
pix2struct,
|
| 216 |
+
pixtral,
|
| 217 |
+
plbart,
|
| 218 |
+
poolformer,
|
| 219 |
+
pop2piano,
|
| 220 |
+
prophetnet,
|
| 221 |
+
pvt,
|
| 222 |
+
pvt_v2,
|
| 223 |
+
qwen2,
|
| 224 |
+
qwen2_5_vl,
|
| 225 |
+
qwen2_audio,
|
| 226 |
+
qwen2_moe,
|
| 227 |
+
qwen2_vl,
|
| 228 |
+
rag,
|
| 229 |
+
recurrent_gemma,
|
| 230 |
+
reformer,
|
| 231 |
+
regnet,
|
| 232 |
+
rembert,
|
| 233 |
+
resnet,
|
| 234 |
+
roberta,
|
| 235 |
+
roberta_prelayernorm,
|
| 236 |
+
roc_bert,
|
| 237 |
+
roformer,
|
| 238 |
+
rt_detr,
|
| 239 |
+
rt_detr_v2,
|
| 240 |
+
rwkv,
|
| 241 |
+
sam,
|
| 242 |
+
seamless_m4t,
|
| 243 |
+
seamless_m4t_v2,
|
| 244 |
+
segformer,
|
| 245 |
+
seggpt,
|
| 246 |
+
sew,
|
| 247 |
+
sew_d,
|
| 248 |
+
siglip,
|
| 249 |
+
siglip2,
|
| 250 |
+
smolvlm,
|
| 251 |
+
speech_encoder_decoder,
|
| 252 |
+
speech_to_text,
|
| 253 |
+
speecht5,
|
| 254 |
+
splinter,
|
| 255 |
+
squeezebert,
|
| 256 |
+
stablelm,
|
| 257 |
+
starcoder2,
|
| 258 |
+
superglue,
|
| 259 |
+
superpoint,
|
| 260 |
+
swiftformer,
|
| 261 |
+
swin,
|
| 262 |
+
swin2sr,
|
| 263 |
+
swinv2,
|
| 264 |
+
switch_transformers,
|
| 265 |
+
t5,
|
| 266 |
+
table_transformer,
|
| 267 |
+
tapas,
|
| 268 |
+
textnet,
|
| 269 |
+
time_series_transformer,
|
| 270 |
+
timesformer,
|
| 271 |
+
timm_backbone,
|
| 272 |
+
timm_wrapper,
|
| 273 |
+
trocr,
|
| 274 |
+
tvp,
|
| 275 |
+
udop,
|
| 276 |
+
umt5,
|
| 277 |
+
unispeech,
|
| 278 |
+
unispeech_sat,
|
| 279 |
+
univnet,
|
| 280 |
+
upernet,
|
| 281 |
+
video_llava,
|
| 282 |
+
videomae,
|
| 283 |
+
vilt,
|
| 284 |
+
vipllava,
|
| 285 |
+
vision_encoder_decoder,
|
| 286 |
+
vision_text_dual_encoder,
|
| 287 |
+
visual_bert,
|
| 288 |
+
vit,
|
| 289 |
+
vit_mae,
|
| 290 |
+
vit_msn,
|
| 291 |
+
vitdet,
|
| 292 |
+
vitmatte,
|
| 293 |
+
vitpose,
|
| 294 |
+
vitpose_backbone,
|
| 295 |
+
vits,
|
| 296 |
+
vivit,
|
| 297 |
+
wav2vec2,
|
| 298 |
+
wav2vec2_bert,
|
| 299 |
+
wav2vec2_conformer,
|
| 300 |
+
wav2vec2_phoneme,
|
| 301 |
+
wav2vec2_with_lm,
|
| 302 |
+
wavlm,
|
| 303 |
+
whisper,
|
| 304 |
+
x_clip,
|
| 305 |
+
xglm,
|
| 306 |
+
xlm,
|
| 307 |
+
xlm_roberta,
|
| 308 |
+
xlm_roberta_xl,
|
| 309 |
+
xlnet,
|
| 310 |
+
xmod,
|
| 311 |
+
yolos,
|
| 312 |
+
yoso,
|
| 313 |
+
zamba,
|
| 314 |
+
zamba2,
|
| 315 |
+
zoedepth,
|
| 316 |
+
)
|
tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/models/auto/configuration_auto.py
ADDED
|
@@ -0,0 +1,1143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Auto Config class."""
|
| 16 |
+
|
| 17 |
+
import importlib
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
import warnings
|
| 21 |
+
from collections import OrderedDict
|
| 22 |
+
from typing import List, Union
|
| 23 |
+
|
| 24 |
+
from ...configuration_utils import PretrainedConfig
|
| 25 |
+
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
|
| 26 |
+
from ...utils import CONFIG_NAME, logging
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
logger = logging.get_logger(__name__)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
CONFIG_MAPPING_NAMES = OrderedDict(
|
| 33 |
+
[
|
| 34 |
+
# Add configs here
|
| 35 |
+
("albert", "AlbertConfig"),
|
| 36 |
+
("align", "AlignConfig"),
|
| 37 |
+
("altclip", "AltCLIPConfig"),
|
| 38 |
+
("aria", "AriaConfig"),
|
| 39 |
+
("aria_text", "AriaTextConfig"),
|
| 40 |
+
("audio-spectrogram-transformer", "ASTConfig"),
|
| 41 |
+
("autoformer", "AutoformerConfig"),
|
| 42 |
+
("aya_vision", "AyaVisionConfig"),
|
| 43 |
+
("bamba", "BambaConfig"),
|
| 44 |
+
("bark", "BarkConfig"),
|
| 45 |
+
("bart", "BartConfig"),
|
| 46 |
+
("beit", "BeitConfig"),
|
| 47 |
+
("bert", "BertConfig"),
|
| 48 |
+
("bert-generation", "BertGenerationConfig"),
|
| 49 |
+
("big_bird", "BigBirdConfig"),
|
| 50 |
+
("bigbird_pegasus", "BigBirdPegasusConfig"),
|
| 51 |
+
("biogpt", "BioGptConfig"),
|
| 52 |
+
("bit", "BitConfig"),
|
| 53 |
+
("blenderbot", "BlenderbotConfig"),
|
| 54 |
+
("blenderbot-small", "BlenderbotSmallConfig"),
|
| 55 |
+
("blip", "BlipConfig"),
|
| 56 |
+
("blip-2", "Blip2Config"),
|
| 57 |
+
("bloom", "BloomConfig"),
|
| 58 |
+
("bridgetower", "BridgeTowerConfig"),
|
| 59 |
+
("bros", "BrosConfig"),
|
| 60 |
+
("camembert", "CamembertConfig"),
|
| 61 |
+
("canine", "CanineConfig"),
|
| 62 |
+
("chameleon", "ChameleonConfig"),
|
| 63 |
+
("chinese_clip", "ChineseCLIPConfig"),
|
| 64 |
+
("chinese_clip_vision_model", "ChineseCLIPVisionConfig"),
|
| 65 |
+
("clap", "ClapConfig"),
|
| 66 |
+
("clip", "CLIPConfig"),
|
| 67 |
+
("clip_text_model", "CLIPTextConfig"),
|
| 68 |
+
("clip_vision_model", "CLIPVisionConfig"),
|
| 69 |
+
("clipseg", "CLIPSegConfig"),
|
| 70 |
+
("clvp", "ClvpConfig"),
|
| 71 |
+
("code_llama", "LlamaConfig"),
|
| 72 |
+
("codegen", "CodeGenConfig"),
|
| 73 |
+
("cohere", "CohereConfig"),
|
| 74 |
+
("cohere2", "Cohere2Config"),
|
| 75 |
+
("colpali", "ColPaliConfig"),
|
| 76 |
+
("conditional_detr", "ConditionalDetrConfig"),
|
| 77 |
+
("convbert", "ConvBertConfig"),
|
| 78 |
+
("convnext", "ConvNextConfig"),
|
| 79 |
+
("convnextv2", "ConvNextV2Config"),
|
| 80 |
+
("cpmant", "CpmAntConfig"),
|
| 81 |
+
("ctrl", "CTRLConfig"),
|
| 82 |
+
("cvt", "CvtConfig"),
|
| 83 |
+
("dab-detr", "DabDetrConfig"),
|
| 84 |
+
("dac", "DacConfig"),
|
| 85 |
+
("data2vec-audio", "Data2VecAudioConfig"),
|
| 86 |
+
("data2vec-text", "Data2VecTextConfig"),
|
| 87 |
+
("data2vec-vision", "Data2VecVisionConfig"),
|
| 88 |
+
("dbrx", "DbrxConfig"),
|
| 89 |
+
("deberta", "DebertaConfig"),
|
| 90 |
+
("deberta-v2", "DebertaV2Config"),
|
| 91 |
+
("decision_transformer", "DecisionTransformerConfig"),
|
| 92 |
+
("deformable_detr", "DeformableDetrConfig"),
|
| 93 |
+
("deit", "DeiTConfig"),
|
| 94 |
+
("depth_anything", "DepthAnythingConfig"),
|
| 95 |
+
("depth_pro", "DepthProConfig"),
|
| 96 |
+
("deta", "DetaConfig"),
|
| 97 |
+
("detr", "DetrConfig"),
|
| 98 |
+
("diffllama", "DiffLlamaConfig"),
|
| 99 |
+
("dinat", "DinatConfig"),
|
| 100 |
+
("dinov2", "Dinov2Config"),
|
| 101 |
+
("dinov2_with_registers", "Dinov2WithRegistersConfig"),
|
| 102 |
+
("distilbert", "DistilBertConfig"),
|
| 103 |
+
("donut-swin", "DonutSwinConfig"),
|
| 104 |
+
("dpr", "DPRConfig"),
|
| 105 |
+
("dpt", "DPTConfig"),
|
| 106 |
+
("efficientformer", "EfficientFormerConfig"),
|
| 107 |
+
("efficientnet", "EfficientNetConfig"),
|
| 108 |
+
("electra", "ElectraConfig"),
|
| 109 |
+
("emu3", "Emu3Config"),
|
| 110 |
+
("encodec", "EncodecConfig"),
|
| 111 |
+
("encoder-decoder", "EncoderDecoderConfig"),
|
| 112 |
+
("ernie", "ErnieConfig"),
|
| 113 |
+
("ernie_m", "ErnieMConfig"),
|
| 114 |
+
("esm", "EsmConfig"),
|
| 115 |
+
("falcon", "FalconConfig"),
|
| 116 |
+
("falcon_mamba", "FalconMambaConfig"),
|
| 117 |
+
("fastspeech2_conformer", "FastSpeech2ConformerConfig"),
|
| 118 |
+
("flaubert", "FlaubertConfig"),
|
| 119 |
+
("flava", "FlavaConfig"),
|
| 120 |
+
("fnet", "FNetConfig"),
|
| 121 |
+
("focalnet", "FocalNetConfig"),
|
| 122 |
+
("fsmt", "FSMTConfig"),
|
| 123 |
+
("funnel", "FunnelConfig"),
|
| 124 |
+
("fuyu", "FuyuConfig"),
|
| 125 |
+
("gemma", "GemmaConfig"),
|
| 126 |
+
("gemma2", "Gemma2Config"),
|
| 127 |
+
("git", "GitConfig"),
|
| 128 |
+
("glm", "GlmConfig"),
|
| 129 |
+
("glpn", "GLPNConfig"),
|
| 130 |
+
("got_ocr2", "GotOcr2Config"),
|
| 131 |
+
("gpt-sw3", "GPT2Config"),
|
| 132 |
+
("gpt2", "GPT2Config"),
|
| 133 |
+
("gpt_bigcode", "GPTBigCodeConfig"),
|
| 134 |
+
("gpt_neo", "GPTNeoConfig"),
|
| 135 |
+
("gpt_neox", "GPTNeoXConfig"),
|
| 136 |
+
("gpt_neox_japanese", "GPTNeoXJapaneseConfig"),
|
| 137 |
+
("gptj", "GPTJConfig"),
|
| 138 |
+
("gptsan-japanese", "GPTSanJapaneseConfig"),
|
| 139 |
+
("granite", "GraniteConfig"),
|
| 140 |
+
("granitemoe", "GraniteMoeConfig"),
|
| 141 |
+
("granitemoeshared", "GraniteMoeSharedConfig"),
|
| 142 |
+
("granitevision", "LlavaNextConfig"),
|
| 143 |
+
("graphormer", "GraphormerConfig"),
|
| 144 |
+
("grounding-dino", "GroundingDinoConfig"),
|
| 145 |
+
("groupvit", "GroupViTConfig"),
|
| 146 |
+
("helium", "HeliumConfig"),
|
| 147 |
+
("hiera", "HieraConfig"),
|
| 148 |
+
("hubert", "HubertConfig"),
|
| 149 |
+
("ibert", "IBertConfig"),
|
| 150 |
+
("idefics", "IdeficsConfig"),
|
| 151 |
+
("idefics2", "Idefics2Config"),
|
| 152 |
+
("idefics3", "Idefics3Config"),
|
| 153 |
+
("idefics3_vision", "Idefics3VisionConfig"),
|
| 154 |
+
("ijepa", "IJepaConfig"),
|
| 155 |
+
("imagegpt", "ImageGPTConfig"),
|
| 156 |
+
("informer", "InformerConfig"),
|
| 157 |
+
("instructblip", "InstructBlipConfig"),
|
| 158 |
+
("instructblipvideo", "InstructBlipVideoConfig"),
|
| 159 |
+
("jamba", "JambaConfig"),
|
| 160 |
+
("jetmoe", "JetMoeConfig"),
|
| 161 |
+
("jukebox", "JukeboxConfig"),
|
| 162 |
+
("kosmos-2", "Kosmos2Config"),
|
| 163 |
+
("layoutlm", "LayoutLMConfig"),
|
| 164 |
+
("layoutlmv2", "LayoutLMv2Config"),
|
| 165 |
+
("layoutlmv3", "LayoutLMv3Config"),
|
| 166 |
+
("led", "LEDConfig"),
|
| 167 |
+
("levit", "LevitConfig"),
|
| 168 |
+
("lilt", "LiltConfig"),
|
| 169 |
+
("llama", "LlamaConfig"),
|
| 170 |
+
("llava", "LlavaConfig"),
|
| 171 |
+
("llava_next", "LlavaNextConfig"),
|
| 172 |
+
("llava_next_video", "LlavaNextVideoConfig"),
|
| 173 |
+
("llava_onevision", "LlavaOnevisionConfig"),
|
| 174 |
+
("longformer", "LongformerConfig"),
|
| 175 |
+
("longt5", "LongT5Config"),
|
| 176 |
+
("luke", "LukeConfig"),
|
| 177 |
+
("lxmert", "LxmertConfig"),
|
| 178 |
+
("m2m_100", "M2M100Config"),
|
| 179 |
+
("mamba", "MambaConfig"),
|
| 180 |
+
("mamba2", "Mamba2Config"),
|
| 181 |
+
("marian", "MarianConfig"),
|
| 182 |
+
("markuplm", "MarkupLMConfig"),
|
| 183 |
+
("mask2former", "Mask2FormerConfig"),
|
| 184 |
+
("maskformer", "MaskFormerConfig"),
|
| 185 |
+
("maskformer-swin", "MaskFormerSwinConfig"),
|
| 186 |
+
("mbart", "MBartConfig"),
|
| 187 |
+
("mctct", "MCTCTConfig"),
|
| 188 |
+
("mega", "MegaConfig"),
|
| 189 |
+
("megatron-bert", "MegatronBertConfig"),
|
| 190 |
+
("mgp-str", "MgpstrConfig"),
|
| 191 |
+
("mimi", "MimiConfig"),
|
| 192 |
+
("mistral", "MistralConfig"),
|
| 193 |
+
("mixtral", "MixtralConfig"),
|
| 194 |
+
("mllama", "MllamaConfig"),
|
| 195 |
+
("mobilebert", "MobileBertConfig"),
|
| 196 |
+
("mobilenet_v1", "MobileNetV1Config"),
|
| 197 |
+
("mobilenet_v2", "MobileNetV2Config"),
|
| 198 |
+
("mobilevit", "MobileViTConfig"),
|
| 199 |
+
("mobilevitv2", "MobileViTV2Config"),
|
| 200 |
+
("modernbert", "ModernBertConfig"),
|
| 201 |
+
("moonshine", "MoonshineConfig"),
|
| 202 |
+
("moshi", "MoshiConfig"),
|
| 203 |
+
("mpnet", "MPNetConfig"),
|
| 204 |
+
("mpt", "MptConfig"),
|
| 205 |
+
("mra", "MraConfig"),
|
| 206 |
+
("mt5", "MT5Config"),
|
| 207 |
+
("musicgen", "MusicgenConfig"),
|
| 208 |
+
("musicgen_melody", "MusicgenMelodyConfig"),
|
| 209 |
+
("mvp", "MvpConfig"),
|
| 210 |
+
("nat", "NatConfig"),
|
| 211 |
+
("nemotron", "NemotronConfig"),
|
| 212 |
+
("nezha", "NezhaConfig"),
|
| 213 |
+
("nllb-moe", "NllbMoeConfig"),
|
| 214 |
+
("nougat", "VisionEncoderDecoderConfig"),
|
| 215 |
+
("nystromformer", "NystromformerConfig"),
|
| 216 |
+
("olmo", "OlmoConfig"),
|
| 217 |
+
("olmo2", "Olmo2Config"),
|
| 218 |
+
("olmoe", "OlmoeConfig"),
|
| 219 |
+
("omdet-turbo", "OmDetTurboConfig"),
|
| 220 |
+
("oneformer", "OneFormerConfig"),
|
| 221 |
+
("open-llama", "OpenLlamaConfig"),
|
| 222 |
+
("openai-gpt", "OpenAIGPTConfig"),
|
| 223 |
+
("opt", "OPTConfig"),
|
| 224 |
+
("owlv2", "Owlv2Config"),
|
| 225 |
+
("owlvit", "OwlViTConfig"),
|
| 226 |
+
("paligemma", "PaliGemmaConfig"),
|
| 227 |
+
("patchtsmixer", "PatchTSMixerConfig"),
|
| 228 |
+
("patchtst", "PatchTSTConfig"),
|
| 229 |
+
("pegasus", "PegasusConfig"),
|
| 230 |
+
("pegasus_x", "PegasusXConfig"),
|
| 231 |
+
("perceiver", "PerceiverConfig"),
|
| 232 |
+
("persimmon", "PersimmonConfig"),
|
| 233 |
+
("phi", "PhiConfig"),
|
| 234 |
+
("phi3", "Phi3Config"),
|
| 235 |
+
("phimoe", "PhimoeConfig"),
|
| 236 |
+
("pix2struct", "Pix2StructConfig"),
|
| 237 |
+
("pixtral", "PixtralVisionConfig"),
|
| 238 |
+
("plbart", "PLBartConfig"),
|
| 239 |
+
("poolformer", "PoolFormerConfig"),
|
| 240 |
+
("pop2piano", "Pop2PianoConfig"),
|
| 241 |
+
("prophetnet", "ProphetNetConfig"),
|
| 242 |
+
("pvt", "PvtConfig"),
|
| 243 |
+
("pvt_v2", "PvtV2Config"),
|
| 244 |
+
("qdqbert", "QDQBertConfig"),
|
| 245 |
+
("qwen2", "Qwen2Config"),
|
| 246 |
+
("qwen2_5_vl", "Qwen2_5_VLConfig"),
|
| 247 |
+
("qwen2_audio", "Qwen2AudioConfig"),
|
| 248 |
+
("qwen2_audio_encoder", "Qwen2AudioEncoderConfig"),
|
| 249 |
+
("qwen2_moe", "Qwen2MoeConfig"),
|
| 250 |
+
("qwen2_vl", "Qwen2VLConfig"),
|
| 251 |
+
("rag", "RagConfig"),
|
| 252 |
+
("realm", "RealmConfig"),
|
| 253 |
+
("recurrent_gemma", "RecurrentGemmaConfig"),
|
| 254 |
+
("reformer", "ReformerConfig"),
|
| 255 |
+
("regnet", "RegNetConfig"),
|
| 256 |
+
("rembert", "RemBertConfig"),
|
| 257 |
+
("resnet", "ResNetConfig"),
|
| 258 |
+
("retribert", "RetriBertConfig"),
|
| 259 |
+
("roberta", "RobertaConfig"),
|
| 260 |
+
("roberta-prelayernorm", "RobertaPreLayerNormConfig"),
|
| 261 |
+
("roc_bert", "RoCBertConfig"),
|
| 262 |
+
("roformer", "RoFormerConfig"),
|
| 263 |
+
("rt_detr", "RTDetrConfig"),
|
| 264 |
+
("rt_detr_resnet", "RTDetrResNetConfig"),
|
| 265 |
+
("rt_detr_v2", "RTDetrV2Config"),
|
| 266 |
+
("rwkv", "RwkvConfig"),
|
| 267 |
+
("sam", "SamConfig"),
|
| 268 |
+
("seamless_m4t", "SeamlessM4TConfig"),
|
| 269 |
+
("seamless_m4t_v2", "SeamlessM4Tv2Config"),
|
| 270 |
+
("segformer", "SegformerConfig"),
|
| 271 |
+
("seggpt", "SegGptConfig"),
|
| 272 |
+
("sew", "SEWConfig"),
|
| 273 |
+
("sew-d", "SEWDConfig"),
|
| 274 |
+
("siglip", "SiglipConfig"),
|
| 275 |
+
("siglip2", "Siglip2Config"),
|
| 276 |
+
("siglip_vision_model", "SiglipVisionConfig"),
|
| 277 |
+
("smolvlm", "SmolVLMConfig"),
|
| 278 |
+
("smolvlm_vision", "SmolVLMVisionConfig"),
|
| 279 |
+
("speech-encoder-decoder", "SpeechEncoderDecoderConfig"),
|
| 280 |
+
("speech_to_text", "Speech2TextConfig"),
|
| 281 |
+
("speech_to_text_2", "Speech2Text2Config"),
|
| 282 |
+
("speecht5", "SpeechT5Config"),
|
| 283 |
+
("splinter", "SplinterConfig"),
|
| 284 |
+
("squeezebert", "SqueezeBertConfig"),
|
| 285 |
+
("stablelm", "StableLmConfig"),
|
| 286 |
+
("starcoder2", "Starcoder2Config"),
|
| 287 |
+
("superglue", "SuperGlueConfig"),
|
| 288 |
+
("superpoint", "SuperPointConfig"),
|
| 289 |
+
("swiftformer", "SwiftFormerConfig"),
|
| 290 |
+
("swin", "SwinConfig"),
|
| 291 |
+
("swin2sr", "Swin2SRConfig"),
|
| 292 |
+
("swinv2", "Swinv2Config"),
|
| 293 |
+
("switch_transformers", "SwitchTransformersConfig"),
|
| 294 |
+
("t5", "T5Config"),
|
| 295 |
+
("table-transformer", "TableTransformerConfig"),
|
| 296 |
+
("tapas", "TapasConfig"),
|
| 297 |
+
("textnet", "TextNetConfig"),
|
| 298 |
+
("time_series_transformer", "TimeSeriesTransformerConfig"),
|
| 299 |
+
("timesformer", "TimesformerConfig"),
|
| 300 |
+
("timm_backbone", "TimmBackboneConfig"),
|
| 301 |
+
("timm_wrapper", "TimmWrapperConfig"),
|
| 302 |
+
("trajectory_transformer", "TrajectoryTransformerConfig"),
|
| 303 |
+
("transfo-xl", "TransfoXLConfig"),
|
| 304 |
+
("trocr", "TrOCRConfig"),
|
| 305 |
+
("tvlt", "TvltConfig"),
|
| 306 |
+
("tvp", "TvpConfig"),
|
| 307 |
+
("udop", "UdopConfig"),
|
| 308 |
+
("umt5", "UMT5Config"),
|
| 309 |
+
("unispeech", "UniSpeechConfig"),
|
| 310 |
+
("unispeech-sat", "UniSpeechSatConfig"),
|
| 311 |
+
("univnet", "UnivNetConfig"),
|
| 312 |
+
("upernet", "UperNetConfig"),
|
| 313 |
+
("van", "VanConfig"),
|
| 314 |
+
("video_llava", "VideoLlavaConfig"),
|
| 315 |
+
("videomae", "VideoMAEConfig"),
|
| 316 |
+
("vilt", "ViltConfig"),
|
| 317 |
+
("vipllava", "VipLlavaConfig"),
|
| 318 |
+
("vision-encoder-decoder", "VisionEncoderDecoderConfig"),
|
| 319 |
+
("vision-text-dual-encoder", "VisionTextDualEncoderConfig"),
|
| 320 |
+
("visual_bert", "VisualBertConfig"),
|
| 321 |
+
("vit", "ViTConfig"),
|
| 322 |
+
("vit_hybrid", "ViTHybridConfig"),
|
| 323 |
+
("vit_mae", "ViTMAEConfig"),
|
| 324 |
+
("vit_msn", "ViTMSNConfig"),
|
| 325 |
+
("vitdet", "VitDetConfig"),
|
| 326 |
+
("vitmatte", "VitMatteConfig"),
|
| 327 |
+
("vitpose", "VitPoseConfig"),
|
| 328 |
+
("vitpose_backbone", "VitPoseBackboneConfig"),
|
| 329 |
+
("vits", "VitsConfig"),
|
| 330 |
+
("vivit", "VivitConfig"),
|
| 331 |
+
("wav2vec2", "Wav2Vec2Config"),
|
| 332 |
+
("wav2vec2-bert", "Wav2Vec2BertConfig"),
|
| 333 |
+
("wav2vec2-conformer", "Wav2Vec2ConformerConfig"),
|
| 334 |
+
("wavlm", "WavLMConfig"),
|
| 335 |
+
("whisper", "WhisperConfig"),
|
| 336 |
+
("xclip", "XCLIPConfig"),
|
| 337 |
+
("xglm", "XGLMConfig"),
|
| 338 |
+
("xlm", "XLMConfig"),
|
| 339 |
+
("xlm-prophetnet", "XLMProphetNetConfig"),
|
| 340 |
+
("xlm-roberta", "XLMRobertaConfig"),
|
| 341 |
+
("xlm-roberta-xl", "XLMRobertaXLConfig"),
|
| 342 |
+
("xlnet", "XLNetConfig"),
|
| 343 |
+
("xmod", "XmodConfig"),
|
| 344 |
+
("yolos", "YolosConfig"),
|
| 345 |
+
("yoso", "YosoConfig"),
|
| 346 |
+
("zamba", "ZambaConfig"),
|
| 347 |
+
("zamba2", "Zamba2Config"),
|
| 348 |
+
("zoedepth", "ZoeDepthConfig"),
|
| 349 |
+
]
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
MODEL_NAMES_MAPPING = OrderedDict(
|
| 354 |
+
[
|
| 355 |
+
# Add full (and cased) model names here
|
| 356 |
+
("albert", "ALBERT"),
|
| 357 |
+
("align", "ALIGN"),
|
| 358 |
+
("altclip", "AltCLIP"),
|
| 359 |
+
("aria", "Aria"),
|
| 360 |
+
("aria_text", "AriaText"),
|
| 361 |
+
("audio-spectrogram-transformer", "Audio Spectrogram Transformer"),
|
| 362 |
+
("autoformer", "Autoformer"),
|
| 363 |
+
("aya_vision", "AyaVision"),
|
| 364 |
+
("bamba", "Bamba"),
|
| 365 |
+
("bark", "Bark"),
|
| 366 |
+
("bart", "BART"),
|
| 367 |
+
("barthez", "BARThez"),
|
| 368 |
+
("bartpho", "BARTpho"),
|
| 369 |
+
("beit", "BEiT"),
|
| 370 |
+
("bert", "BERT"),
|
| 371 |
+
("bert-generation", "Bert Generation"),
|
| 372 |
+
("bert-japanese", "BertJapanese"),
|
| 373 |
+
("bertweet", "BERTweet"),
|
| 374 |
+
("big_bird", "BigBird"),
|
| 375 |
+
("bigbird_pegasus", "BigBird-Pegasus"),
|
| 376 |
+
("biogpt", "BioGpt"),
|
| 377 |
+
("bit", "BiT"),
|
| 378 |
+
("blenderbot", "Blenderbot"),
|
| 379 |
+
("blenderbot-small", "BlenderbotSmall"),
|
| 380 |
+
("blip", "BLIP"),
|
| 381 |
+
("blip-2", "BLIP-2"),
|
| 382 |
+
("bloom", "BLOOM"),
|
| 383 |
+
("bort", "BORT"),
|
| 384 |
+
("bridgetower", "BridgeTower"),
|
| 385 |
+
("bros", "BROS"),
|
| 386 |
+
("byt5", "ByT5"),
|
| 387 |
+
("camembert", "CamemBERT"),
|
| 388 |
+
("canine", "CANINE"),
|
| 389 |
+
("chameleon", "Chameleon"),
|
| 390 |
+
("chinese_clip", "Chinese-CLIP"),
|
| 391 |
+
("chinese_clip_vision_model", "ChineseCLIPVisionModel"),
|
| 392 |
+
("clap", "CLAP"),
|
| 393 |
+
("clip", "CLIP"),
|
| 394 |
+
("clip_text_model", "CLIPTextModel"),
|
| 395 |
+
("clip_vision_model", "CLIPVisionModel"),
|
| 396 |
+
("clipseg", "CLIPSeg"),
|
| 397 |
+
("clvp", "CLVP"),
|
| 398 |
+
("code_llama", "CodeLlama"),
|
| 399 |
+
("codegen", "CodeGen"),
|
| 400 |
+
("cohere", "Cohere"),
|
| 401 |
+
("cohere2", "Cohere2"),
|
| 402 |
+
("colpali", "ColPali"),
|
| 403 |
+
("conditional_detr", "Conditional DETR"),
|
| 404 |
+
("convbert", "ConvBERT"),
|
| 405 |
+
("convnext", "ConvNeXT"),
|
| 406 |
+
("convnextv2", "ConvNeXTV2"),
|
| 407 |
+
("cpm", "CPM"),
|
| 408 |
+
("cpmant", "CPM-Ant"),
|
| 409 |
+
("ctrl", "CTRL"),
|
| 410 |
+
("cvt", "CvT"),
|
| 411 |
+
("dab-detr", "DAB-DETR"),
|
| 412 |
+
("dac", "DAC"),
|
| 413 |
+
("data2vec-audio", "Data2VecAudio"),
|
| 414 |
+
("data2vec-text", "Data2VecText"),
|
| 415 |
+
("data2vec-vision", "Data2VecVision"),
|
| 416 |
+
("dbrx", "DBRX"),
|
| 417 |
+
("deberta", "DeBERTa"),
|
| 418 |
+
("deberta-v2", "DeBERTa-v2"),
|
| 419 |
+
("decision_transformer", "Decision Transformer"),
|
| 420 |
+
("deformable_detr", "Deformable DETR"),
|
| 421 |
+
("deit", "DeiT"),
|
| 422 |
+
("deplot", "DePlot"),
|
| 423 |
+
("depth_anything", "Depth Anything"),
|
| 424 |
+
("depth_anything_v2", "Depth Anything V2"),
|
| 425 |
+
("depth_pro", "DepthPro"),
|
| 426 |
+
("deta", "DETA"),
|
| 427 |
+
("detr", "DETR"),
|
| 428 |
+
("dialogpt", "DialoGPT"),
|
| 429 |
+
("diffllama", "DiffLlama"),
|
| 430 |
+
("dinat", "DiNAT"),
|
| 431 |
+
("dinov2", "DINOv2"),
|
| 432 |
+
("dinov2_with_registers", "DINOv2 with Registers"),
|
| 433 |
+
("distilbert", "DistilBERT"),
|
| 434 |
+
("dit", "DiT"),
|
| 435 |
+
("donut-swin", "DonutSwin"),
|
| 436 |
+
("dpr", "DPR"),
|
| 437 |
+
("dpt", "DPT"),
|
| 438 |
+
("efficientformer", "EfficientFormer"),
|
| 439 |
+
("efficientnet", "EfficientNet"),
|
| 440 |
+
("electra", "ELECTRA"),
|
| 441 |
+
("emu3", "Emu3"),
|
| 442 |
+
("encodec", "EnCodec"),
|
| 443 |
+
("encoder-decoder", "Encoder decoder"),
|
| 444 |
+
("ernie", "ERNIE"),
|
| 445 |
+
("ernie_m", "ErnieM"),
|
| 446 |
+
("esm", "ESM"),
|
| 447 |
+
("falcon", "Falcon"),
|
| 448 |
+
("falcon3", "Falcon3"),
|
| 449 |
+
("falcon_mamba", "FalconMamba"),
|
| 450 |
+
("fastspeech2_conformer", "FastSpeech2Conformer"),
|
| 451 |
+
("flan-t5", "FLAN-T5"),
|
| 452 |
+
("flan-ul2", "FLAN-UL2"),
|
| 453 |
+
("flaubert", "FlauBERT"),
|
| 454 |
+
("flava", "FLAVA"),
|
| 455 |
+
("fnet", "FNet"),
|
| 456 |
+
("focalnet", "FocalNet"),
|
| 457 |
+
("fsmt", "FairSeq Machine-Translation"),
|
| 458 |
+
("funnel", "Funnel Transformer"),
|
| 459 |
+
("fuyu", "Fuyu"),
|
| 460 |
+
("gemma", "Gemma"),
|
| 461 |
+
("gemma2", "Gemma2"),
|
| 462 |
+
("git", "GIT"),
|
| 463 |
+
("glm", "GLM"),
|
| 464 |
+
("glpn", "GLPN"),
|
| 465 |
+
("got_ocr2", "GOT-OCR2"),
|
| 466 |
+
("gpt-sw3", "GPT-Sw3"),
|
| 467 |
+
("gpt2", "OpenAI GPT-2"),
|
| 468 |
+
("gpt_bigcode", "GPTBigCode"),
|
| 469 |
+
("gpt_neo", "GPT Neo"),
|
| 470 |
+
("gpt_neox", "GPT NeoX"),
|
| 471 |
+
("gpt_neox_japanese", "GPT NeoX Japanese"),
|
| 472 |
+
("gptj", "GPT-J"),
|
| 473 |
+
("gptsan-japanese", "GPTSAN-japanese"),
|
| 474 |
+
("granite", "Granite"),
|
| 475 |
+
("granitemoe", "GraniteMoeMoe"),
|
| 476 |
+
("granitemoeshared", "GraniteMoeSharedMoe"),
|
| 477 |
+
("granitevision", "LLaVA-NeXT"),
|
| 478 |
+
("graphormer", "Graphormer"),
|
| 479 |
+
("grounding-dino", "Grounding DINO"),
|
| 480 |
+
("groupvit", "GroupViT"),
|
| 481 |
+
("helium", "Helium"),
|
| 482 |
+
("herbert", "HerBERT"),
|
| 483 |
+
("hiera", "Hiera"),
|
| 484 |
+
("hubert", "Hubert"),
|
| 485 |
+
("ibert", "I-BERT"),
|
| 486 |
+
("idefics", "IDEFICS"),
|
| 487 |
+
("idefics2", "Idefics2"),
|
| 488 |
+
("idefics3", "Idefics3"),
|
| 489 |
+
("idefics3_vision", "Idefics3VisionTransformer"),
|
| 490 |
+
("ijepa", "I-JEPA"),
|
| 491 |
+
("imagegpt", "ImageGPT"),
|
| 492 |
+
("informer", "Informer"),
|
| 493 |
+
("instructblip", "InstructBLIP"),
|
| 494 |
+
("instructblipvideo", "InstructBlipVideo"),
|
| 495 |
+
("jamba", "Jamba"),
|
| 496 |
+
("jetmoe", "JetMoe"),
|
| 497 |
+
("jukebox", "Jukebox"),
|
| 498 |
+
("kosmos-2", "KOSMOS-2"),
|
| 499 |
+
("layoutlm", "LayoutLM"),
|
| 500 |
+
("layoutlmv2", "LayoutLMv2"),
|
| 501 |
+
("layoutlmv3", "LayoutLMv3"),
|
| 502 |
+
("layoutxlm", "LayoutXLM"),
|
| 503 |
+
("led", "LED"),
|
| 504 |
+
("levit", "LeViT"),
|
| 505 |
+
("lilt", "LiLT"),
|
| 506 |
+
("llama", "LLaMA"),
|
| 507 |
+
("llama2", "Llama2"),
|
| 508 |
+
("llama3", "Llama3"),
|
| 509 |
+
("llava", "LLaVa"),
|
| 510 |
+
("llava_next", "LLaVA-NeXT"),
|
| 511 |
+
("llava_next_video", "LLaVa-NeXT-Video"),
|
| 512 |
+
("llava_onevision", "LLaVA-Onevision"),
|
| 513 |
+
("longformer", "Longformer"),
|
| 514 |
+
("longt5", "LongT5"),
|
| 515 |
+
("luke", "LUKE"),
|
| 516 |
+
("lxmert", "LXMERT"),
|
| 517 |
+
("m2m_100", "M2M100"),
|
| 518 |
+
("madlad-400", "MADLAD-400"),
|
| 519 |
+
("mamba", "Mamba"),
|
| 520 |
+
("mamba2", "mamba2"),
|
| 521 |
+
("marian", "Marian"),
|
| 522 |
+
("markuplm", "MarkupLM"),
|
| 523 |
+
("mask2former", "Mask2Former"),
|
| 524 |
+
("maskformer", "MaskFormer"),
|
| 525 |
+
("maskformer-swin", "MaskFormerSwin"),
|
| 526 |
+
("matcha", "MatCha"),
|
| 527 |
+
("mbart", "mBART"),
|
| 528 |
+
("mbart50", "mBART-50"),
|
| 529 |
+
("mctct", "M-CTC-T"),
|
| 530 |
+
("mega", "MEGA"),
|
| 531 |
+
("megatron-bert", "Megatron-BERT"),
|
| 532 |
+
("megatron_gpt2", "Megatron-GPT2"),
|
| 533 |
+
("mgp-str", "MGP-STR"),
|
| 534 |
+
("mimi", "Mimi"),
|
| 535 |
+
("mistral", "Mistral"),
|
| 536 |
+
("mixtral", "Mixtral"),
|
| 537 |
+
("mllama", "Mllama"),
|
| 538 |
+
("mluke", "mLUKE"),
|
| 539 |
+
("mms", "MMS"),
|
| 540 |
+
("mobilebert", "MobileBERT"),
|
| 541 |
+
("mobilenet_v1", "MobileNetV1"),
|
| 542 |
+
("mobilenet_v2", "MobileNetV2"),
|
| 543 |
+
("mobilevit", "MobileViT"),
|
| 544 |
+
("mobilevitv2", "MobileViTV2"),
|
| 545 |
+
("modernbert", "ModernBERT"),
|
| 546 |
+
("moonshine", "Moonshine"),
|
| 547 |
+
("moshi", "Moshi"),
|
| 548 |
+
("mpnet", "MPNet"),
|
| 549 |
+
("mpt", "MPT"),
|
| 550 |
+
("mra", "MRA"),
|
| 551 |
+
("mt5", "MT5"),
|
| 552 |
+
("musicgen", "MusicGen"),
|
| 553 |
+
("musicgen_melody", "MusicGen Melody"),
|
| 554 |
+
("mvp", "MVP"),
|
| 555 |
+
("myt5", "myt5"),
|
| 556 |
+
("nat", "NAT"),
|
| 557 |
+
("nemotron", "Nemotron"),
|
| 558 |
+
("nezha", "Nezha"),
|
| 559 |
+
("nllb", "NLLB"),
|
| 560 |
+
("nllb-moe", "NLLB-MOE"),
|
| 561 |
+
("nougat", "Nougat"),
|
| 562 |
+
("nystromformer", "Nyströmformer"),
|
| 563 |
+
("olmo", "OLMo"),
|
| 564 |
+
("olmo2", "OLMo2"),
|
| 565 |
+
("olmoe", "OLMoE"),
|
| 566 |
+
("omdet-turbo", "OmDet-Turbo"),
|
| 567 |
+
("oneformer", "OneFormer"),
|
| 568 |
+
("open-llama", "OpenLlama"),
|
| 569 |
+
("openai-gpt", "OpenAI GPT"),
|
| 570 |
+
("opt", "OPT"),
|
| 571 |
+
("owlv2", "OWLv2"),
|
| 572 |
+
("owlvit", "OWL-ViT"),
|
| 573 |
+
("paligemma", "PaliGemma"),
|
| 574 |
+
("patchtsmixer", "PatchTSMixer"),
|
| 575 |
+
("patchtst", "PatchTST"),
|
| 576 |
+
("pegasus", "Pegasus"),
|
| 577 |
+
("pegasus_x", "PEGASUS-X"),
|
| 578 |
+
("perceiver", "Perceiver"),
|
| 579 |
+
("persimmon", "Persimmon"),
|
| 580 |
+
("phi", "Phi"),
|
| 581 |
+
("phi3", "Phi3"),
|
| 582 |
+
("phimoe", "Phimoe"),
|
| 583 |
+
("phobert", "PhoBERT"),
|
| 584 |
+
("pix2struct", "Pix2Struct"),
|
| 585 |
+
("pixtral", "Pixtral"),
|
| 586 |
+
("plbart", "PLBart"),
|
| 587 |
+
("poolformer", "PoolFormer"),
|
| 588 |
+
("pop2piano", "Pop2Piano"),
|
| 589 |
+
("prophetnet", "ProphetNet"),
|
| 590 |
+
("pvt", "PVT"),
|
| 591 |
+
("pvt_v2", "PVTv2"),
|
| 592 |
+
("qdqbert", "QDQBert"),
|
| 593 |
+
("qwen2", "Qwen2"),
|
| 594 |
+
("qwen2_5_vl", "Qwen2_5_VL"),
|
| 595 |
+
("qwen2_audio", "Qwen2Audio"),
|
| 596 |
+
("qwen2_audio_encoder", "Qwen2AudioEncoder"),
|
| 597 |
+
("qwen2_moe", "Qwen2MoE"),
|
| 598 |
+
("qwen2_vl", "Qwen2VL"),
|
| 599 |
+
("rag", "RAG"),
|
| 600 |
+
("realm", "REALM"),
|
| 601 |
+
("recurrent_gemma", "RecurrentGemma"),
|
| 602 |
+
("reformer", "Reformer"),
|
| 603 |
+
("regnet", "RegNet"),
|
| 604 |
+
("rembert", "RemBERT"),
|
| 605 |
+
("resnet", "ResNet"),
|
| 606 |
+
("retribert", "RetriBERT"),
|
| 607 |
+
("roberta", "RoBERTa"),
|
| 608 |
+
("roberta-prelayernorm", "RoBERTa-PreLayerNorm"),
|
| 609 |
+
("roc_bert", "RoCBert"),
|
| 610 |
+
("roformer", "RoFormer"),
|
| 611 |
+
("rt_detr", "RT-DETR"),
|
| 612 |
+
("rt_detr_resnet", "RT-DETR-ResNet"),
|
| 613 |
+
("rt_detr_v2", "RT-DETRv2"),
|
| 614 |
+
("rwkv", "RWKV"),
|
| 615 |
+
("sam", "SAM"),
|
| 616 |
+
("seamless_m4t", "SeamlessM4T"),
|
| 617 |
+
("seamless_m4t_v2", "SeamlessM4Tv2"),
|
| 618 |
+
("segformer", "SegFormer"),
|
| 619 |
+
("seggpt", "SegGPT"),
|
| 620 |
+
("sew", "SEW"),
|
| 621 |
+
("sew-d", "SEW-D"),
|
| 622 |
+
("siglip", "SigLIP"),
|
| 623 |
+
("siglip2", "SigLIP2"),
|
| 624 |
+
("siglip2_vision_model", "Siglip2VisionModel"),
|
| 625 |
+
("siglip_vision_model", "SiglipVisionModel"),
|
| 626 |
+
("smolvlm", "SmolVLM"),
|
| 627 |
+
("smolvlm_vision", "SmolVLMVisionTransformer"),
|
| 628 |
+
("speech-encoder-decoder", "Speech Encoder decoder"),
|
| 629 |
+
("speech_to_text", "Speech2Text"),
|
| 630 |
+
("speech_to_text_2", "Speech2Text2"),
|
| 631 |
+
("speecht5", "SpeechT5"),
|
| 632 |
+
("splinter", "Splinter"),
|
| 633 |
+
("squeezebert", "SqueezeBERT"),
|
| 634 |
+
("stablelm", "StableLm"),
|
| 635 |
+
("starcoder2", "Starcoder2"),
|
| 636 |
+
("superglue", "SuperGlue"),
|
| 637 |
+
("superpoint", "SuperPoint"),
|
| 638 |
+
("swiftformer", "SwiftFormer"),
|
| 639 |
+
("swin", "Swin Transformer"),
|
| 640 |
+
("swin2sr", "Swin2SR"),
|
| 641 |
+
("swinv2", "Swin Transformer V2"),
|
| 642 |
+
("switch_transformers", "SwitchTransformers"),
|
| 643 |
+
("t5", "T5"),
|
| 644 |
+
("t5v1.1", "T5v1.1"),
|
| 645 |
+
("table-transformer", "Table Transformer"),
|
| 646 |
+
("tapas", "TAPAS"),
|
| 647 |
+
("tapex", "TAPEX"),
|
| 648 |
+
("textnet", "TextNet"),
|
| 649 |
+
("time_series_transformer", "Time Series Transformer"),
|
| 650 |
+
("timesformer", "TimeSformer"),
|
| 651 |
+
("timm_backbone", "TimmBackbone"),
|
| 652 |
+
("timm_wrapper", "TimmWrapperModel"),
|
| 653 |
+
("trajectory_transformer", "Trajectory Transformer"),
|
| 654 |
+
("transfo-xl", "Transformer-XL"),
|
| 655 |
+
("trocr", "TrOCR"),
|
| 656 |
+
("tvlt", "TVLT"),
|
| 657 |
+
("tvp", "TVP"),
|
| 658 |
+
("udop", "UDOP"),
|
| 659 |
+
("ul2", "UL2"),
|
| 660 |
+
("umt5", "UMT5"),
|
| 661 |
+
("unispeech", "UniSpeech"),
|
| 662 |
+
("unispeech-sat", "UniSpeechSat"),
|
| 663 |
+
("univnet", "UnivNet"),
|
| 664 |
+
("upernet", "UPerNet"),
|
| 665 |
+
("van", "VAN"),
|
| 666 |
+
("video_llava", "VideoLlava"),
|
| 667 |
+
("videomae", "VideoMAE"),
|
| 668 |
+
("vilt", "ViLT"),
|
| 669 |
+
("vipllava", "VipLlava"),
|
| 670 |
+
("vision-encoder-decoder", "Vision Encoder decoder"),
|
| 671 |
+
("vision-text-dual-encoder", "VisionTextDualEncoder"),
|
| 672 |
+
("visual_bert", "VisualBERT"),
|
| 673 |
+
("vit", "ViT"),
|
| 674 |
+
("vit_hybrid", "ViT Hybrid"),
|
| 675 |
+
("vit_mae", "ViTMAE"),
|
| 676 |
+
("vit_msn", "ViTMSN"),
|
| 677 |
+
("vitdet", "VitDet"),
|
| 678 |
+
("vitmatte", "ViTMatte"),
|
| 679 |
+
("vitpose", "ViTPose"),
|
| 680 |
+
("vitpose_backbone", "ViTPoseBackbone"),
|
| 681 |
+
("vits", "VITS"),
|
| 682 |
+
("vivit", "ViViT"),
|
| 683 |
+
("wav2vec2", "Wav2Vec2"),
|
| 684 |
+
("wav2vec2-bert", "Wav2Vec2-BERT"),
|
| 685 |
+
("wav2vec2-conformer", "Wav2Vec2-Conformer"),
|
| 686 |
+
("wav2vec2_phoneme", "Wav2Vec2Phoneme"),
|
| 687 |
+
("wavlm", "WavLM"),
|
| 688 |
+
("whisper", "Whisper"),
|
| 689 |
+
("xclip", "X-CLIP"),
|
| 690 |
+
("xglm", "XGLM"),
|
| 691 |
+
("xlm", "XLM"),
|
| 692 |
+
("xlm-prophetnet", "XLM-ProphetNet"),
|
| 693 |
+
("xlm-roberta", "XLM-RoBERTa"),
|
| 694 |
+
("xlm-roberta-xl", "XLM-RoBERTa-XL"),
|
| 695 |
+
("xlm-v", "XLM-V"),
|
| 696 |
+
("xlnet", "XLNet"),
|
| 697 |
+
("xls_r", "XLS-R"),
|
| 698 |
+
("xlsr_wav2vec2", "XLSR-Wav2Vec2"),
|
| 699 |
+
("xmod", "X-MOD"),
|
| 700 |
+
("yolos", "YOLOS"),
|
| 701 |
+
("yoso", "YOSO"),
|
| 702 |
+
("zamba", "Zamba"),
|
| 703 |
+
("zamba2", "Zamba2"),
|
| 704 |
+
("zoedepth", "ZoeDepth"),
|
| 705 |
+
]
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
# This is tied to the processing `-` -> `_` in `model_type_to_module_name`. For example, instead of putting
|
| 709 |
+
# `transfo-xl` (as in `CONFIG_MAPPING_NAMES`), we should use `transfo_xl`.
|
| 710 |
+
DEPRECATED_MODELS = [
|
| 711 |
+
"bort",
|
| 712 |
+
"deta",
|
| 713 |
+
"efficientformer",
|
| 714 |
+
"ernie_m",
|
| 715 |
+
"gptsan_japanese",
|
| 716 |
+
"graphormer",
|
| 717 |
+
"jukebox",
|
| 718 |
+
"mctct",
|
| 719 |
+
"mega",
|
| 720 |
+
"mmbt",
|
| 721 |
+
"nat",
|
| 722 |
+
"nezha",
|
| 723 |
+
"open_llama",
|
| 724 |
+
"qdqbert",
|
| 725 |
+
"realm",
|
| 726 |
+
"retribert",
|
| 727 |
+
"speech_to_text_2",
|
| 728 |
+
"tapex",
|
| 729 |
+
"trajectory_transformer",
|
| 730 |
+
"transfo_xl",
|
| 731 |
+
"tvlt",
|
| 732 |
+
"van",
|
| 733 |
+
"vit_hybrid",
|
| 734 |
+
"xlm_prophetnet",
|
| 735 |
+
]
|
| 736 |
+
|
| 737 |
+
SPECIAL_MODEL_TYPE_TO_MODULE_NAME = OrderedDict(
|
| 738 |
+
[
|
| 739 |
+
("openai-gpt", "openai"),
|
| 740 |
+
("data2vec-audio", "data2vec"),
|
| 741 |
+
("data2vec-text", "data2vec"),
|
| 742 |
+
("data2vec-vision", "data2vec"),
|
| 743 |
+
("donut-swin", "donut"),
|
| 744 |
+
("kosmos-2", "kosmos2"),
|
| 745 |
+
("maskformer-swin", "maskformer"),
|
| 746 |
+
("xclip", "x_clip"),
|
| 747 |
+
("clip_vision_model", "clip"),
|
| 748 |
+
("qwen2_audio_encoder", "qwen2_audio"),
|
| 749 |
+
("clip_text_model", "clip"),
|
| 750 |
+
("aria_text", "aria"),
|
| 751 |
+
("idefics3_vision", "idefics3"),
|
| 752 |
+
("siglip_vision_model", "siglip"),
|
| 753 |
+
("smolvlm_vision", "smolvlm"),
|
| 754 |
+
("chinese_clip_vision_model", "chinese_clip"),
|
| 755 |
+
("rt_detr_resnet", "rt_detr"),
|
| 756 |
+
("granitevision", "llava_next"),
|
| 757 |
+
]
|
| 758 |
+
)
|
| 759 |
+
|
| 760 |
+
|
| 761 |
+
def model_type_to_module_name(key):
|
| 762 |
+
"""Converts a config key to the corresponding module."""
|
| 763 |
+
# Special treatment
|
| 764 |
+
if key in SPECIAL_MODEL_TYPE_TO_MODULE_NAME:
|
| 765 |
+
key = SPECIAL_MODEL_TYPE_TO_MODULE_NAME[key]
|
| 766 |
+
|
| 767 |
+
if key in DEPRECATED_MODELS:
|
| 768 |
+
key = f"deprecated.{key}"
|
| 769 |
+
return key
|
| 770 |
+
|
| 771 |
+
key = key.replace("-", "_")
|
| 772 |
+
if key in DEPRECATED_MODELS:
|
| 773 |
+
key = f"deprecated.{key}"
|
| 774 |
+
|
| 775 |
+
return key
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
def config_class_to_model_type(config):
|
| 779 |
+
"""Converts a config class name to the corresponding model type"""
|
| 780 |
+
for key, cls in CONFIG_MAPPING_NAMES.items():
|
| 781 |
+
if cls == config:
|
| 782 |
+
return key
|
| 783 |
+
# if key not found check in extra content
|
| 784 |
+
for key, cls in CONFIG_MAPPING._extra_content.items():
|
| 785 |
+
if cls.__name__ == config:
|
| 786 |
+
return key
|
| 787 |
+
return None
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
class _LazyConfigMapping(OrderedDict):
|
| 791 |
+
"""
|
| 792 |
+
A dictionary that lazily load its values when they are requested.
|
| 793 |
+
"""
|
| 794 |
+
|
| 795 |
+
def __init__(self, mapping):
|
| 796 |
+
self._mapping = mapping
|
| 797 |
+
self._extra_content = {}
|
| 798 |
+
self._modules = {}
|
| 799 |
+
|
| 800 |
+
def __getitem__(self, key):
|
| 801 |
+
if key in self._extra_content:
|
| 802 |
+
return self._extra_content[key]
|
| 803 |
+
if key not in self._mapping:
|
| 804 |
+
raise KeyError(key)
|
| 805 |
+
value = self._mapping[key]
|
| 806 |
+
module_name = model_type_to_module_name(key)
|
| 807 |
+
if module_name not in self._modules:
|
| 808 |
+
self._modules[module_name] = importlib.import_module(f".{module_name}", "transformers.models")
|
| 809 |
+
if hasattr(self._modules[module_name], value):
|
| 810 |
+
return getattr(self._modules[module_name], value)
|
| 811 |
+
|
| 812 |
+
# Some of the mappings have entries model_type -> config of another model type. In that case we try to grab the
|
| 813 |
+
# object at the top level.
|
| 814 |
+
transformers_module = importlib.import_module("transformers")
|
| 815 |
+
return getattr(transformers_module, value)
|
| 816 |
+
|
| 817 |
+
def keys(self):
|
| 818 |
+
return list(self._mapping.keys()) + list(self._extra_content.keys())
|
| 819 |
+
|
| 820 |
+
def values(self):
|
| 821 |
+
return [self[k] for k in self._mapping.keys()] + list(self._extra_content.values())
|
| 822 |
+
|
| 823 |
+
def items(self):
|
| 824 |
+
return [(k, self[k]) for k in self._mapping.keys()] + list(self._extra_content.items())
|
| 825 |
+
|
| 826 |
+
def __iter__(self):
|
| 827 |
+
return iter(list(self._mapping.keys()) + list(self._extra_content.keys()))
|
| 828 |
+
|
| 829 |
+
def __contains__(self, item):
|
| 830 |
+
return item in self._mapping or item in self._extra_content
|
| 831 |
+
|
| 832 |
+
def register(self, key, value, exist_ok=False):
|
| 833 |
+
"""
|
| 834 |
+
Register a new configuration in this mapping.
|
| 835 |
+
"""
|
| 836 |
+
if key in self._mapping.keys() and not exist_ok:
|
| 837 |
+
raise ValueError(f"'{key}' is already used by a Transformers config, pick another name.")
|
| 838 |
+
self._extra_content[key] = value
|
| 839 |
+
|
| 840 |
+
|
| 841 |
+
CONFIG_MAPPING = _LazyConfigMapping(CONFIG_MAPPING_NAMES)
|
| 842 |
+
|
| 843 |
+
|
| 844 |
+
class _LazyLoadAllMappings(OrderedDict):
|
| 845 |
+
"""
|
| 846 |
+
A mapping that will load all pairs of key values at the first access (either by indexing, requestions keys, values,
|
| 847 |
+
etc.)
|
| 848 |
+
|
| 849 |
+
Args:
|
| 850 |
+
mapping: The mapping to load.
|
| 851 |
+
"""
|
| 852 |
+
|
| 853 |
+
def __init__(self, mapping):
|
| 854 |
+
self._mapping = mapping
|
| 855 |
+
self._initialized = False
|
| 856 |
+
self._data = {}
|
| 857 |
+
|
| 858 |
+
def _initialize(self):
|
| 859 |
+
if self._initialized:
|
| 860 |
+
return
|
| 861 |
+
|
| 862 |
+
for model_type, map_name in self._mapping.items():
|
| 863 |
+
module_name = model_type_to_module_name(model_type)
|
| 864 |
+
module = importlib.import_module(f".{module_name}", "transformers.models")
|
| 865 |
+
mapping = getattr(module, map_name)
|
| 866 |
+
self._data.update(mapping)
|
| 867 |
+
|
| 868 |
+
self._initialized = True
|
| 869 |
+
|
| 870 |
+
def __getitem__(self, key):
|
| 871 |
+
self._initialize()
|
| 872 |
+
return self._data[key]
|
| 873 |
+
|
| 874 |
+
def keys(self):
|
| 875 |
+
self._initialize()
|
| 876 |
+
return self._data.keys()
|
| 877 |
+
|
| 878 |
+
def values(self):
|
| 879 |
+
self._initialize()
|
| 880 |
+
return self._data.values()
|
| 881 |
+
|
| 882 |
+
def items(self):
|
| 883 |
+
self._initialize()
|
| 884 |
+
return self._data.keys()
|
| 885 |
+
|
| 886 |
+
def __iter__(self):
|
| 887 |
+
self._initialize()
|
| 888 |
+
return iter(self._data)
|
| 889 |
+
|
| 890 |
+
def __contains__(self, item):
|
| 891 |
+
self._initialize()
|
| 892 |
+
return item in self._data
|
| 893 |
+
|
| 894 |
+
|
| 895 |
+
def _get_class_name(model_class: Union[str, List[str]]):
|
| 896 |
+
if isinstance(model_class, (list, tuple)):
|
| 897 |
+
return " or ".join([f"[`{c}`]" for c in model_class if c is not None])
|
| 898 |
+
return f"[`{model_class}`]"
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
def _list_model_options(indent, config_to_class=None, use_model_types=True):
|
| 902 |
+
if config_to_class is None and not use_model_types:
|
| 903 |
+
raise ValueError("Using `use_model_types=False` requires a `config_to_class` dictionary.")
|
| 904 |
+
if use_model_types:
|
| 905 |
+
if config_to_class is None:
|
| 906 |
+
model_type_to_name = {model_type: f"[`{config}`]" for model_type, config in CONFIG_MAPPING_NAMES.items()}
|
| 907 |
+
else:
|
| 908 |
+
model_type_to_name = {
|
| 909 |
+
model_type: _get_class_name(model_class)
|
| 910 |
+
for model_type, model_class in config_to_class.items()
|
| 911 |
+
if model_type in MODEL_NAMES_MAPPING
|
| 912 |
+
}
|
| 913 |
+
lines = [
|
| 914 |
+
f"{indent}- **{model_type}** -- {model_type_to_name[model_type]} ({MODEL_NAMES_MAPPING[model_type]} model)"
|
| 915 |
+
for model_type in sorted(model_type_to_name.keys())
|
| 916 |
+
]
|
| 917 |
+
else:
|
| 918 |
+
config_to_name = {
|
| 919 |
+
CONFIG_MAPPING_NAMES[config]: _get_class_name(clas)
|
| 920 |
+
for config, clas in config_to_class.items()
|
| 921 |
+
if config in CONFIG_MAPPING_NAMES
|
| 922 |
+
}
|
| 923 |
+
config_to_model_name = {
|
| 924 |
+
config: MODEL_NAMES_MAPPING[model_type] for model_type, config in CONFIG_MAPPING_NAMES.items()
|
| 925 |
+
}
|
| 926 |
+
lines = [
|
| 927 |
+
f"{indent}- [`{config_name}`] configuration class:"
|
| 928 |
+
f" {config_to_name[config_name]} ({config_to_model_name[config_name]} model)"
|
| 929 |
+
for config_name in sorted(config_to_name.keys())
|
| 930 |
+
]
|
| 931 |
+
return "\n".join(lines)
|
| 932 |
+
|
| 933 |
+
|
| 934 |
+
def replace_list_option_in_docstrings(config_to_class=None, use_model_types=True):
|
| 935 |
+
def docstring_decorator(fn):
|
| 936 |
+
docstrings = fn.__doc__
|
| 937 |
+
if docstrings is None:
|
| 938 |
+
# Example: -OO
|
| 939 |
+
return fn
|
| 940 |
+
lines = docstrings.split("\n")
|
| 941 |
+
i = 0
|
| 942 |
+
while i < len(lines) and re.search(r"^(\s*)List options\s*$", lines[i]) is None:
|
| 943 |
+
i += 1
|
| 944 |
+
if i < len(lines):
|
| 945 |
+
indent = re.search(r"^(\s*)List options\s*$", lines[i]).groups()[0]
|
| 946 |
+
if use_model_types:
|
| 947 |
+
indent = f"{indent} "
|
| 948 |
+
lines[i] = _list_model_options(indent, config_to_class=config_to_class, use_model_types=use_model_types)
|
| 949 |
+
docstrings = "\n".join(lines)
|
| 950 |
+
else:
|
| 951 |
+
raise ValueError(
|
| 952 |
+
f"The function {fn} should have an empty 'List options' in its docstring as placeholder, current"
|
| 953 |
+
f" docstring is:\n{docstrings}"
|
| 954 |
+
)
|
| 955 |
+
fn.__doc__ = docstrings
|
| 956 |
+
return fn
|
| 957 |
+
|
| 958 |
+
return docstring_decorator
|
| 959 |
+
|
| 960 |
+
|
| 961 |
+
class AutoConfig:
|
| 962 |
+
r"""
|
| 963 |
+
This is a generic configuration class that will be instantiated as one of the configuration classes of the library
|
| 964 |
+
when created with the [`~AutoConfig.from_pretrained`] class method.
|
| 965 |
+
|
| 966 |
+
This class cannot be instantiated directly using `__init__()` (throws an error).
|
| 967 |
+
"""
|
| 968 |
+
|
| 969 |
+
def __init__(self):
|
| 970 |
+
raise EnvironmentError(
|
| 971 |
+
"AutoConfig is designed to be instantiated "
|
| 972 |
+
"using the `AutoConfig.from_pretrained(pretrained_model_name_or_path)` method."
|
| 973 |
+
)
|
| 974 |
+
|
| 975 |
+
@classmethod
|
| 976 |
+
def for_model(cls, model_type: str, *args, **kwargs):
|
| 977 |
+
if model_type in CONFIG_MAPPING:
|
| 978 |
+
config_class = CONFIG_MAPPING[model_type]
|
| 979 |
+
return config_class(*args, **kwargs)
|
| 980 |
+
raise ValueError(
|
| 981 |
+
f"Unrecognized model identifier: {model_type}. Should contain one of {', '.join(CONFIG_MAPPING.keys())}"
|
| 982 |
+
)
|
| 983 |
+
|
| 984 |
+
@classmethod
|
| 985 |
+
@replace_list_option_in_docstrings()
|
| 986 |
+
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
|
| 987 |
+
r"""
|
| 988 |
+
Instantiate one of the configuration classes of the library from a pretrained model configuration.
|
| 989 |
+
|
| 990 |
+
The configuration class to instantiate is selected based on the `model_type` property of the config object that
|
| 991 |
+
is loaded, or when it's missing, by falling back to using pattern matching on `pretrained_model_name_or_path`:
|
| 992 |
+
|
| 993 |
+
List options
|
| 994 |
+
|
| 995 |
+
Args:
|
| 996 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 997 |
+
Can be either:
|
| 998 |
+
|
| 999 |
+
- A string, the *model id* of a pretrained model configuration hosted inside a model repo on
|
| 1000 |
+
huggingface.co.
|
| 1001 |
+
- A path to a *directory* containing a configuration file saved using the
|
| 1002 |
+
[`~PretrainedConfig.save_pretrained`] method, or the [`~PreTrainedModel.save_pretrained`] method,
|
| 1003 |
+
e.g., `./my_model_directory/`.
|
| 1004 |
+
- A path or url to a saved configuration JSON *file*, e.g.,
|
| 1005 |
+
`./my_model_directory/configuration.json`.
|
| 1006 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 1007 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the
|
| 1008 |
+
standard cache should not be used.
|
| 1009 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 1010 |
+
Whether or not to force the (re-)download the model weights and configuration files and override the
|
| 1011 |
+
cached versions if they exist.
|
| 1012 |
+
resume_download:
|
| 1013 |
+
Deprecated and ignored. All downloads are now resumed by default when possible.
|
| 1014 |
+
Will be removed in v5 of Transformers.
|
| 1015 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 1016 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 1017 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 1018 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 1019 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 1020 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 1021 |
+
identifier allowed by git.
|
| 1022 |
+
return_unused_kwargs (`bool`, *optional*, defaults to `False`):
|
| 1023 |
+
If `False`, then this function returns just the final configuration object.
|
| 1024 |
+
|
| 1025 |
+
If `True`, then this functions returns a `Tuple(config, unused_kwargs)` where *unused_kwargs* is a
|
| 1026 |
+
dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the
|
| 1027 |
+
part of `kwargs` which has not been used to update `config` and is otherwise ignored.
|
| 1028 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 1029 |
+
Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
|
| 1030 |
+
should only be set to `True` for repositories you trust and in which you have read the code, as it will
|
| 1031 |
+
execute code present on the Hub on your local machine.
|
| 1032 |
+
kwargs(additional keyword arguments, *optional*):
|
| 1033 |
+
The values in kwargs of any keys which are configuration attributes will be used to override the loaded
|
| 1034 |
+
values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled
|
| 1035 |
+
by the `return_unused_kwargs` keyword parameter.
|
| 1036 |
+
|
| 1037 |
+
Examples:
|
| 1038 |
+
|
| 1039 |
+
```python
|
| 1040 |
+
>>> from transformers import AutoConfig
|
| 1041 |
+
|
| 1042 |
+
>>> # Download configuration from huggingface.co and cache.
|
| 1043 |
+
>>> config = AutoConfig.from_pretrained("google-bert/bert-base-uncased")
|
| 1044 |
+
|
| 1045 |
+
>>> # Download configuration from huggingface.co (user-uploaded) and cache.
|
| 1046 |
+
>>> config = AutoConfig.from_pretrained("dbmdz/bert-base-german-cased")
|
| 1047 |
+
|
| 1048 |
+
>>> # If configuration file is in a directory (e.g., was saved using *save_pretrained('./test/saved_model/')*).
|
| 1049 |
+
>>> config = AutoConfig.from_pretrained("./test/bert_saved_model/")
|
| 1050 |
+
|
| 1051 |
+
>>> # Load a specific configuration file.
|
| 1052 |
+
>>> config = AutoConfig.from_pretrained("./test/bert_saved_model/my_configuration.json")
|
| 1053 |
+
|
| 1054 |
+
>>> # Change some config attributes when loading a pretrained config.
|
| 1055 |
+
>>> config = AutoConfig.from_pretrained("google-bert/bert-base-uncased", output_attentions=True, foo=False)
|
| 1056 |
+
>>> config.output_attentions
|
| 1057 |
+
True
|
| 1058 |
+
|
| 1059 |
+
>>> config, unused_kwargs = AutoConfig.from_pretrained(
|
| 1060 |
+
... "google-bert/bert-base-uncased", output_attentions=True, foo=False, return_unused_kwargs=True
|
| 1061 |
+
... )
|
| 1062 |
+
>>> config.output_attentions
|
| 1063 |
+
True
|
| 1064 |
+
|
| 1065 |
+
>>> unused_kwargs
|
| 1066 |
+
{'foo': False}
|
| 1067 |
+
```"""
|
| 1068 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 1069 |
+
if use_auth_token is not None:
|
| 1070 |
+
warnings.warn(
|
| 1071 |
+
"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
|
| 1072 |
+
FutureWarning,
|
| 1073 |
+
)
|
| 1074 |
+
if kwargs.get("token", None) is not None:
|
| 1075 |
+
raise ValueError(
|
| 1076 |
+
"`token` and `use_auth_token` are both specified. Please set only the argument `token`."
|
| 1077 |
+
)
|
| 1078 |
+
kwargs["token"] = use_auth_token
|
| 1079 |
+
|
| 1080 |
+
kwargs["_from_auto"] = True
|
| 1081 |
+
kwargs["name_or_path"] = pretrained_model_name_or_path
|
| 1082 |
+
trust_remote_code = kwargs.pop("trust_remote_code", None)
|
| 1083 |
+
code_revision = kwargs.pop("code_revision", None)
|
| 1084 |
+
|
| 1085 |
+
config_dict, unused_kwargs = PretrainedConfig.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 1086 |
+
has_remote_code = "auto_map" in config_dict and "AutoConfig" in config_dict["auto_map"]
|
| 1087 |
+
has_local_code = "model_type" in config_dict and config_dict["model_type"] in CONFIG_MAPPING
|
| 1088 |
+
trust_remote_code = resolve_trust_remote_code(
|
| 1089 |
+
trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code
|
| 1090 |
+
)
|
| 1091 |
+
|
| 1092 |
+
if has_remote_code and trust_remote_code:
|
| 1093 |
+
class_ref = config_dict["auto_map"]["AutoConfig"]
|
| 1094 |
+
config_class = get_class_from_dynamic_module(
|
| 1095 |
+
class_ref, pretrained_model_name_or_path, code_revision=code_revision, **kwargs
|
| 1096 |
+
)
|
| 1097 |
+
if os.path.isdir(pretrained_model_name_or_path):
|
| 1098 |
+
config_class.register_for_auto_class()
|
| 1099 |
+
return config_class.from_pretrained(pretrained_model_name_or_path, **kwargs)
|
| 1100 |
+
elif "model_type" in config_dict:
|
| 1101 |
+
try:
|
| 1102 |
+
config_class = CONFIG_MAPPING[config_dict["model_type"]]
|
| 1103 |
+
except KeyError:
|
| 1104 |
+
raise ValueError(
|
| 1105 |
+
f"The checkpoint you are trying to load has model type `{config_dict['model_type']}` "
|
| 1106 |
+
"but Transformers does not recognize this architecture. This could be because of an "
|
| 1107 |
+
"issue with the checkpoint, or because your version of Transformers is out of date.\n\n"
|
| 1108 |
+
"You can update Transformers with the command `pip install --upgrade transformers`. If this "
|
| 1109 |
+
"does not work, and the checkpoint is very new, then there may not be a release version "
|
| 1110 |
+
"that supports this model yet. In this case, you can get the most up-to-date code by installing "
|
| 1111 |
+
"Transformers from source with the command "
|
| 1112 |
+
"`pip install git+https://github.com/huggingface/transformers.git`"
|
| 1113 |
+
)
|
| 1114 |
+
return config_class.from_dict(config_dict, **unused_kwargs)
|
| 1115 |
+
else:
|
| 1116 |
+
# Fallback: use pattern matching on the string.
|
| 1117 |
+
# We go from longer names to shorter names to catch roberta before bert (for instance)
|
| 1118 |
+
for pattern in sorted(CONFIG_MAPPING.keys(), key=len, reverse=True):
|
| 1119 |
+
if pattern in str(pretrained_model_name_or_path):
|
| 1120 |
+
return CONFIG_MAPPING[pattern].from_dict(config_dict, **unused_kwargs)
|
| 1121 |
+
|
| 1122 |
+
raise ValueError(
|
| 1123 |
+
f"Unrecognized model in {pretrained_model_name_or_path}. "
|
| 1124 |
+
f"Should have a `model_type` key in its {CONFIG_NAME}, or contain one of the following strings "
|
| 1125 |
+
f"in its name: {', '.join(CONFIG_MAPPING.keys())}"
|
| 1126 |
+
)
|
| 1127 |
+
|
| 1128 |
+
@staticmethod
|
| 1129 |
+
def register(model_type, config, exist_ok=False):
|
| 1130 |
+
"""
|
| 1131 |
+
Register a new configuration for this class.
|
| 1132 |
+
|
| 1133 |
+
Args:
|
| 1134 |
+
model_type (`str`): The model type like "bert" or "gpt".
|
| 1135 |
+
config ([`PretrainedConfig`]): The config to register.
|
| 1136 |
+
"""
|
| 1137 |
+
if issubclass(config, PretrainedConfig) and config.model_type != model_type:
|
| 1138 |
+
raise ValueError(
|
| 1139 |
+
"The config you are passing has a `model_type` attribute that is not consistent with the model type "
|
| 1140 |
+
f"you passed (config has {config.model_type} and you passed {model_type}. Fix one of those so they "
|
| 1141 |
+
"match!"
|
| 1142 |
+
)
|
| 1143 |
+
CONFIG_MAPPING.register(model_type, config, exist_ok=exist_ok)
|
tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/models/auto/modeling_auto.py
ADDED
|
@@ -0,0 +1,1918 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Auto Model class."""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
from collections import OrderedDict
|
| 19 |
+
|
| 20 |
+
from ...utils import logging
|
| 21 |
+
from .auto_factory import (
|
| 22 |
+
_BaseAutoBackboneClass,
|
| 23 |
+
_BaseAutoModelClass,
|
| 24 |
+
_LazyAutoMapping,
|
| 25 |
+
auto_class_update,
|
| 26 |
+
)
|
| 27 |
+
from .configuration_auto import CONFIG_MAPPING_NAMES
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
MODEL_MAPPING_NAMES = OrderedDict(
|
| 33 |
+
[
|
| 34 |
+
# Base model mapping
|
| 35 |
+
("albert", "AlbertModel"),
|
| 36 |
+
("align", "AlignModel"),
|
| 37 |
+
("altclip", "AltCLIPModel"),
|
| 38 |
+
("aria", "AriaForConditionalGeneration"),
|
| 39 |
+
("aria_text", "AriaTextModel"),
|
| 40 |
+
("audio-spectrogram-transformer", "ASTModel"),
|
| 41 |
+
("autoformer", "AutoformerModel"),
|
| 42 |
+
("bamba", "BambaModel"),
|
| 43 |
+
("bark", "BarkModel"),
|
| 44 |
+
("bart", "BartModel"),
|
| 45 |
+
("beit", "BeitModel"),
|
| 46 |
+
("bert", "BertModel"),
|
| 47 |
+
("bert-generation", "BertGenerationEncoder"),
|
| 48 |
+
("big_bird", "BigBirdModel"),
|
| 49 |
+
("bigbird_pegasus", "BigBirdPegasusModel"),
|
| 50 |
+
("biogpt", "BioGptModel"),
|
| 51 |
+
("bit", "BitModel"),
|
| 52 |
+
("blenderbot", "BlenderbotModel"),
|
| 53 |
+
("blenderbot-small", "BlenderbotSmallModel"),
|
| 54 |
+
("blip", "BlipModel"),
|
| 55 |
+
("blip-2", "Blip2Model"),
|
| 56 |
+
("bloom", "BloomModel"),
|
| 57 |
+
("bridgetower", "BridgeTowerModel"),
|
| 58 |
+
("bros", "BrosModel"),
|
| 59 |
+
("camembert", "CamembertModel"),
|
| 60 |
+
("canine", "CanineModel"),
|
| 61 |
+
("chameleon", "ChameleonModel"),
|
| 62 |
+
("chinese_clip", "ChineseCLIPModel"),
|
| 63 |
+
("chinese_clip_vision_model", "ChineseCLIPVisionModel"),
|
| 64 |
+
("clap", "ClapModel"),
|
| 65 |
+
("clip", "CLIPModel"),
|
| 66 |
+
("clip_text_model", "CLIPTextModel"),
|
| 67 |
+
("clip_vision_model", "CLIPVisionModel"),
|
| 68 |
+
("clipseg", "CLIPSegModel"),
|
| 69 |
+
("clvp", "ClvpModelForConditionalGeneration"),
|
| 70 |
+
("code_llama", "LlamaModel"),
|
| 71 |
+
("codegen", "CodeGenModel"),
|
| 72 |
+
("cohere", "CohereModel"),
|
| 73 |
+
("cohere2", "Cohere2Model"),
|
| 74 |
+
("conditional_detr", "ConditionalDetrModel"),
|
| 75 |
+
("convbert", "ConvBertModel"),
|
| 76 |
+
("convnext", "ConvNextModel"),
|
| 77 |
+
("convnextv2", "ConvNextV2Model"),
|
| 78 |
+
("cpmant", "CpmAntModel"),
|
| 79 |
+
("ctrl", "CTRLModel"),
|
| 80 |
+
("cvt", "CvtModel"),
|
| 81 |
+
("dab-detr", "DabDetrModel"),
|
| 82 |
+
("dac", "DacModel"),
|
| 83 |
+
("data2vec-audio", "Data2VecAudioModel"),
|
| 84 |
+
("data2vec-text", "Data2VecTextModel"),
|
| 85 |
+
("data2vec-vision", "Data2VecVisionModel"),
|
| 86 |
+
("dbrx", "DbrxModel"),
|
| 87 |
+
("deberta", "DebertaModel"),
|
| 88 |
+
("deberta-v2", "DebertaV2Model"),
|
| 89 |
+
("decision_transformer", "DecisionTransformerModel"),
|
| 90 |
+
("deformable_detr", "DeformableDetrModel"),
|
| 91 |
+
("deit", "DeiTModel"),
|
| 92 |
+
("depth_pro", "DepthProModel"),
|
| 93 |
+
("deta", "DetaModel"),
|
| 94 |
+
("detr", "DetrModel"),
|
| 95 |
+
("diffllama", "DiffLlamaModel"),
|
| 96 |
+
("dinat", "DinatModel"),
|
| 97 |
+
("dinov2", "Dinov2Model"),
|
| 98 |
+
("dinov2_with_registers", "Dinov2WithRegistersModel"),
|
| 99 |
+
("distilbert", "DistilBertModel"),
|
| 100 |
+
("donut-swin", "DonutSwinModel"),
|
| 101 |
+
("dpr", "DPRQuestionEncoder"),
|
| 102 |
+
("dpt", "DPTModel"),
|
| 103 |
+
("efficientformer", "EfficientFormerModel"),
|
| 104 |
+
("efficientnet", "EfficientNetModel"),
|
| 105 |
+
("electra", "ElectraModel"),
|
| 106 |
+
("encodec", "EncodecModel"),
|
| 107 |
+
("ernie", "ErnieModel"),
|
| 108 |
+
("ernie_m", "ErnieMModel"),
|
| 109 |
+
("esm", "EsmModel"),
|
| 110 |
+
("falcon", "FalconModel"),
|
| 111 |
+
("falcon_mamba", "FalconMambaModel"),
|
| 112 |
+
("fastspeech2_conformer", "FastSpeech2ConformerModel"),
|
| 113 |
+
("flaubert", "FlaubertModel"),
|
| 114 |
+
("flava", "FlavaModel"),
|
| 115 |
+
("fnet", "FNetModel"),
|
| 116 |
+
("focalnet", "FocalNetModel"),
|
| 117 |
+
("fsmt", "FSMTModel"),
|
| 118 |
+
("funnel", ("FunnelModel", "FunnelBaseModel")),
|
| 119 |
+
("gemma", "GemmaModel"),
|
| 120 |
+
("gemma2", "Gemma2Model"),
|
| 121 |
+
("git", "GitModel"),
|
| 122 |
+
("glm", "GlmModel"),
|
| 123 |
+
("glpn", "GLPNModel"),
|
| 124 |
+
("got_ocr2", "GotOcr2ForConditionalGeneration"),
|
| 125 |
+
("gpt-sw3", "GPT2Model"),
|
| 126 |
+
("gpt2", "GPT2Model"),
|
| 127 |
+
("gpt_bigcode", "GPTBigCodeModel"),
|
| 128 |
+
("gpt_neo", "GPTNeoModel"),
|
| 129 |
+
("gpt_neox", "GPTNeoXModel"),
|
| 130 |
+
("gpt_neox_japanese", "GPTNeoXJapaneseModel"),
|
| 131 |
+
("gptj", "GPTJModel"),
|
| 132 |
+
("gptsan-japanese", "GPTSanJapaneseForConditionalGeneration"),
|
| 133 |
+
("granite", "GraniteModel"),
|
| 134 |
+
("granitemoe", "GraniteMoeModel"),
|
| 135 |
+
("granitemoeshared", "GraniteMoeSharedModel"),
|
| 136 |
+
("graphormer", "GraphormerModel"),
|
| 137 |
+
("grounding-dino", "GroundingDinoModel"),
|
| 138 |
+
("groupvit", "GroupViTModel"),
|
| 139 |
+
("helium", "HeliumModel"),
|
| 140 |
+
("hiera", "HieraModel"),
|
| 141 |
+
("hubert", "HubertModel"),
|
| 142 |
+
("ibert", "IBertModel"),
|
| 143 |
+
("idefics", "IdeficsModel"),
|
| 144 |
+
("idefics2", "Idefics2Model"),
|
| 145 |
+
("idefics3", "Idefics3Model"),
|
| 146 |
+
("idefics3_vision", "Idefics3VisionTransformer"),
|
| 147 |
+
("ijepa", "IJepaModel"),
|
| 148 |
+
("imagegpt", "ImageGPTModel"),
|
| 149 |
+
("informer", "InformerModel"),
|
| 150 |
+
("jamba", "JambaModel"),
|
| 151 |
+
("jetmoe", "JetMoeModel"),
|
| 152 |
+
("jukebox", "JukeboxModel"),
|
| 153 |
+
("kosmos-2", "Kosmos2Model"),
|
| 154 |
+
("layoutlm", "LayoutLMModel"),
|
| 155 |
+
("layoutlmv2", "LayoutLMv2Model"),
|
| 156 |
+
("layoutlmv3", "LayoutLMv3Model"),
|
| 157 |
+
("led", "LEDModel"),
|
| 158 |
+
("levit", "LevitModel"),
|
| 159 |
+
("lilt", "LiltModel"),
|
| 160 |
+
("llama", "LlamaModel"),
|
| 161 |
+
("longformer", "LongformerModel"),
|
| 162 |
+
("longt5", "LongT5Model"),
|
| 163 |
+
("luke", "LukeModel"),
|
| 164 |
+
("lxmert", "LxmertModel"),
|
| 165 |
+
("m2m_100", "M2M100Model"),
|
| 166 |
+
("mamba", "MambaModel"),
|
| 167 |
+
("mamba2", "Mamba2Model"),
|
| 168 |
+
("marian", "MarianModel"),
|
| 169 |
+
("markuplm", "MarkupLMModel"),
|
| 170 |
+
("mask2former", "Mask2FormerModel"),
|
| 171 |
+
("maskformer", "MaskFormerModel"),
|
| 172 |
+
("maskformer-swin", "MaskFormerSwinModel"),
|
| 173 |
+
("mbart", "MBartModel"),
|
| 174 |
+
("mctct", "MCTCTModel"),
|
| 175 |
+
("mega", "MegaModel"),
|
| 176 |
+
("megatron-bert", "MegatronBertModel"),
|
| 177 |
+
("mgp-str", "MgpstrForSceneTextRecognition"),
|
| 178 |
+
("mimi", "MimiModel"),
|
| 179 |
+
("mistral", "MistralModel"),
|
| 180 |
+
("mixtral", "MixtralModel"),
|
| 181 |
+
("mobilebert", "MobileBertModel"),
|
| 182 |
+
("mobilenet_v1", "MobileNetV1Model"),
|
| 183 |
+
("mobilenet_v2", "MobileNetV2Model"),
|
| 184 |
+
("mobilevit", "MobileViTModel"),
|
| 185 |
+
("mobilevitv2", "MobileViTV2Model"),
|
| 186 |
+
("modernbert", "ModernBertModel"),
|
| 187 |
+
("moonshine", "MoonshineModel"),
|
| 188 |
+
("moshi", "MoshiModel"),
|
| 189 |
+
("mpnet", "MPNetModel"),
|
| 190 |
+
("mpt", "MptModel"),
|
| 191 |
+
("mra", "MraModel"),
|
| 192 |
+
("mt5", "MT5Model"),
|
| 193 |
+
("musicgen", "MusicgenModel"),
|
| 194 |
+
("musicgen_melody", "MusicgenMelodyModel"),
|
| 195 |
+
("mvp", "MvpModel"),
|
| 196 |
+
("nat", "NatModel"),
|
| 197 |
+
("nemotron", "NemotronModel"),
|
| 198 |
+
("nezha", "NezhaModel"),
|
| 199 |
+
("nllb-moe", "NllbMoeModel"),
|
| 200 |
+
("nystromformer", "NystromformerModel"),
|
| 201 |
+
("olmo", "OlmoModel"),
|
| 202 |
+
("olmo2", "Olmo2Model"),
|
| 203 |
+
("olmoe", "OlmoeModel"),
|
| 204 |
+
("omdet-turbo", "OmDetTurboForObjectDetection"),
|
| 205 |
+
("oneformer", "OneFormerModel"),
|
| 206 |
+
("open-llama", "OpenLlamaModel"),
|
| 207 |
+
("openai-gpt", "OpenAIGPTModel"),
|
| 208 |
+
("opt", "OPTModel"),
|
| 209 |
+
("owlv2", "Owlv2Model"),
|
| 210 |
+
("owlvit", "OwlViTModel"),
|
| 211 |
+
("patchtsmixer", "PatchTSMixerModel"),
|
| 212 |
+
("patchtst", "PatchTSTModel"),
|
| 213 |
+
("pegasus", "PegasusModel"),
|
| 214 |
+
("pegasus_x", "PegasusXModel"),
|
| 215 |
+
("perceiver", "PerceiverModel"),
|
| 216 |
+
("persimmon", "PersimmonModel"),
|
| 217 |
+
("phi", "PhiModel"),
|
| 218 |
+
("phi3", "Phi3Model"),
|
| 219 |
+
("phimoe", "PhimoeModel"),
|
| 220 |
+
("pixtral", "PixtralVisionModel"),
|
| 221 |
+
("plbart", "PLBartModel"),
|
| 222 |
+
("poolformer", "PoolFormerModel"),
|
| 223 |
+
("prophetnet", "ProphetNetModel"),
|
| 224 |
+
("pvt", "PvtModel"),
|
| 225 |
+
("pvt_v2", "PvtV2Model"),
|
| 226 |
+
("qdqbert", "QDQBertModel"),
|
| 227 |
+
("qwen2", "Qwen2Model"),
|
| 228 |
+
("qwen2_5_vl", "Qwen2_5_VLModel"),
|
| 229 |
+
("qwen2_audio_encoder", "Qwen2AudioEncoder"),
|
| 230 |
+
("qwen2_moe", "Qwen2MoeModel"),
|
| 231 |
+
("qwen2_vl", "Qwen2VLModel"),
|
| 232 |
+
("recurrent_gemma", "RecurrentGemmaModel"),
|
| 233 |
+
("reformer", "ReformerModel"),
|
| 234 |
+
("regnet", "RegNetModel"),
|
| 235 |
+
("rembert", "RemBertModel"),
|
| 236 |
+
("resnet", "ResNetModel"),
|
| 237 |
+
("retribert", "RetriBertModel"),
|
| 238 |
+
("roberta", "RobertaModel"),
|
| 239 |
+
("roberta-prelayernorm", "RobertaPreLayerNormModel"),
|
| 240 |
+
("roc_bert", "RoCBertModel"),
|
| 241 |
+
("roformer", "RoFormerModel"),
|
| 242 |
+
("rt_detr", "RTDetrModel"),
|
| 243 |
+
("rt_detr_v2", "RTDetrV2Model"),
|
| 244 |
+
("rwkv", "RwkvModel"),
|
| 245 |
+
("sam", "SamModel"),
|
| 246 |
+
("seamless_m4t", "SeamlessM4TModel"),
|
| 247 |
+
("seamless_m4t_v2", "SeamlessM4Tv2Model"),
|
| 248 |
+
("segformer", "SegformerModel"),
|
| 249 |
+
("seggpt", "SegGptModel"),
|
| 250 |
+
("sew", "SEWModel"),
|
| 251 |
+
("sew-d", "SEWDModel"),
|
| 252 |
+
("siglip", "SiglipModel"),
|
| 253 |
+
("siglip2", "Siglip2Model"),
|
| 254 |
+
("siglip_vision_model", "SiglipVisionModel"),
|
| 255 |
+
("smolvlm", "SmolVLMModel"),
|
| 256 |
+
("smolvlm_vision", "SmolVLMVisionTransformer"),
|
| 257 |
+
("speech_to_text", "Speech2TextModel"),
|
| 258 |
+
("speecht5", "SpeechT5Model"),
|
| 259 |
+
("splinter", "SplinterModel"),
|
| 260 |
+
("squeezebert", "SqueezeBertModel"),
|
| 261 |
+
("stablelm", "StableLmModel"),
|
| 262 |
+
("starcoder2", "Starcoder2Model"),
|
| 263 |
+
("superglue", "SuperGlueForKeypointMatching"),
|
| 264 |
+
("swiftformer", "SwiftFormerModel"),
|
| 265 |
+
("swin", "SwinModel"),
|
| 266 |
+
("swin2sr", "Swin2SRModel"),
|
| 267 |
+
("swinv2", "Swinv2Model"),
|
| 268 |
+
("switch_transformers", "SwitchTransformersModel"),
|
| 269 |
+
("t5", "T5Model"),
|
| 270 |
+
("table-transformer", "TableTransformerModel"),
|
| 271 |
+
("tapas", "TapasModel"),
|
| 272 |
+
("textnet", "TextNetModel"),
|
| 273 |
+
("time_series_transformer", "TimeSeriesTransformerModel"),
|
| 274 |
+
("timesformer", "TimesformerModel"),
|
| 275 |
+
("timm_backbone", "TimmBackbone"),
|
| 276 |
+
("timm_wrapper", "TimmWrapperModel"),
|
| 277 |
+
("trajectory_transformer", "TrajectoryTransformerModel"),
|
| 278 |
+
("transfo-xl", "TransfoXLModel"),
|
| 279 |
+
("tvlt", "TvltModel"),
|
| 280 |
+
("tvp", "TvpModel"),
|
| 281 |
+
("udop", "UdopModel"),
|
| 282 |
+
("umt5", "UMT5Model"),
|
| 283 |
+
("unispeech", "UniSpeechModel"),
|
| 284 |
+
("unispeech-sat", "UniSpeechSatModel"),
|
| 285 |
+
("univnet", "UnivNetModel"),
|
| 286 |
+
("van", "VanModel"),
|
| 287 |
+
("videomae", "VideoMAEModel"),
|
| 288 |
+
("vilt", "ViltModel"),
|
| 289 |
+
("vision-text-dual-encoder", "VisionTextDualEncoderModel"),
|
| 290 |
+
("visual_bert", "VisualBertModel"),
|
| 291 |
+
("vit", "ViTModel"),
|
| 292 |
+
("vit_hybrid", "ViTHybridModel"),
|
| 293 |
+
("vit_mae", "ViTMAEModel"),
|
| 294 |
+
("vit_msn", "ViTMSNModel"),
|
| 295 |
+
("vitdet", "VitDetModel"),
|
| 296 |
+
("vits", "VitsModel"),
|
| 297 |
+
("vivit", "VivitModel"),
|
| 298 |
+
("wav2vec2", "Wav2Vec2Model"),
|
| 299 |
+
("wav2vec2-bert", "Wav2Vec2BertModel"),
|
| 300 |
+
("wav2vec2-conformer", "Wav2Vec2ConformerModel"),
|
| 301 |
+
("wavlm", "WavLMModel"),
|
| 302 |
+
("whisper", "WhisperModel"),
|
| 303 |
+
("xclip", "XCLIPModel"),
|
| 304 |
+
("xglm", "XGLMModel"),
|
| 305 |
+
("xlm", "XLMModel"),
|
| 306 |
+
("xlm-prophetnet", "XLMProphetNetModel"),
|
| 307 |
+
("xlm-roberta", "XLMRobertaModel"),
|
| 308 |
+
("xlm-roberta-xl", "XLMRobertaXLModel"),
|
| 309 |
+
("xlnet", "XLNetModel"),
|
| 310 |
+
("xmod", "XmodModel"),
|
| 311 |
+
("yolos", "YolosModel"),
|
| 312 |
+
("yoso", "YosoModel"),
|
| 313 |
+
("zamba", "ZambaModel"),
|
| 314 |
+
("zamba2", "Zamba2Model"),
|
| 315 |
+
]
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
MODEL_FOR_PRETRAINING_MAPPING_NAMES = OrderedDict(
|
| 319 |
+
[
|
| 320 |
+
# Model for pre-training mapping
|
| 321 |
+
("albert", "AlbertForPreTraining"),
|
| 322 |
+
("bart", "BartForConditionalGeneration"),
|
| 323 |
+
("bert", "BertForPreTraining"),
|
| 324 |
+
("big_bird", "BigBirdForPreTraining"),
|
| 325 |
+
("bloom", "BloomForCausalLM"),
|
| 326 |
+
("camembert", "CamembertForMaskedLM"),
|
| 327 |
+
("colpali", "ColPaliForRetrieval"),
|
| 328 |
+
("ctrl", "CTRLLMHeadModel"),
|
| 329 |
+
("data2vec-text", "Data2VecTextForMaskedLM"),
|
| 330 |
+
("deberta", "DebertaForMaskedLM"),
|
| 331 |
+
("deberta-v2", "DebertaV2ForMaskedLM"),
|
| 332 |
+
("distilbert", "DistilBertForMaskedLM"),
|
| 333 |
+
("electra", "ElectraForPreTraining"),
|
| 334 |
+
("ernie", "ErnieForPreTraining"),
|
| 335 |
+
("falcon_mamba", "FalconMambaForCausalLM"),
|
| 336 |
+
("flaubert", "FlaubertWithLMHeadModel"),
|
| 337 |
+
("flava", "FlavaForPreTraining"),
|
| 338 |
+
("fnet", "FNetForPreTraining"),
|
| 339 |
+
("fsmt", "FSMTForConditionalGeneration"),
|
| 340 |
+
("funnel", "FunnelForPreTraining"),
|
| 341 |
+
("gpt-sw3", "GPT2LMHeadModel"),
|
| 342 |
+
("gpt2", "GPT2LMHeadModel"),
|
| 343 |
+
("gpt_bigcode", "GPTBigCodeForCausalLM"),
|
| 344 |
+
("gptsan-japanese", "GPTSanJapaneseForConditionalGeneration"),
|
| 345 |
+
("hiera", "HieraForPreTraining"),
|
| 346 |
+
("ibert", "IBertForMaskedLM"),
|
| 347 |
+
("idefics", "IdeficsForVisionText2Text"),
|
| 348 |
+
("idefics2", "Idefics2ForConditionalGeneration"),
|
| 349 |
+
("idefics3", "Idefics3ForConditionalGeneration"),
|
| 350 |
+
("layoutlm", "LayoutLMForMaskedLM"),
|
| 351 |
+
("llava", "LlavaForConditionalGeneration"),
|
| 352 |
+
("llava_next", "LlavaNextForConditionalGeneration"),
|
| 353 |
+
("llava_next_video", "LlavaNextVideoForConditionalGeneration"),
|
| 354 |
+
("llava_onevision", "LlavaOnevisionForConditionalGeneration"),
|
| 355 |
+
("longformer", "LongformerForMaskedLM"),
|
| 356 |
+
("luke", "LukeForMaskedLM"),
|
| 357 |
+
("lxmert", "LxmertForPreTraining"),
|
| 358 |
+
("mamba", "MambaForCausalLM"),
|
| 359 |
+
("mamba2", "Mamba2ForCausalLM"),
|
| 360 |
+
("mega", "MegaForMaskedLM"),
|
| 361 |
+
("megatron-bert", "MegatronBertForPreTraining"),
|
| 362 |
+
("mllama", "MllamaForConditionalGeneration"),
|
| 363 |
+
("mobilebert", "MobileBertForPreTraining"),
|
| 364 |
+
("mpnet", "MPNetForMaskedLM"),
|
| 365 |
+
("mpt", "MptForCausalLM"),
|
| 366 |
+
("mra", "MraForMaskedLM"),
|
| 367 |
+
("mvp", "MvpForConditionalGeneration"),
|
| 368 |
+
("nezha", "NezhaForPreTraining"),
|
| 369 |
+
("nllb-moe", "NllbMoeForConditionalGeneration"),
|
| 370 |
+
("openai-gpt", "OpenAIGPTLMHeadModel"),
|
| 371 |
+
("paligemma", "PaliGemmaForConditionalGeneration"),
|
| 372 |
+
("qwen2_audio", "Qwen2AudioForConditionalGeneration"),
|
| 373 |
+
("retribert", "RetriBertModel"),
|
| 374 |
+
("roberta", "RobertaForMaskedLM"),
|
| 375 |
+
("roberta-prelayernorm", "RobertaPreLayerNormForMaskedLM"),
|
| 376 |
+
("roc_bert", "RoCBertForPreTraining"),
|
| 377 |
+
("rwkv", "RwkvForCausalLM"),
|
| 378 |
+
("splinter", "SplinterForPreTraining"),
|
| 379 |
+
("squeezebert", "SqueezeBertForMaskedLM"),
|
| 380 |
+
("switch_transformers", "SwitchTransformersForConditionalGeneration"),
|
| 381 |
+
("t5", "T5ForConditionalGeneration"),
|
| 382 |
+
("tapas", "TapasForMaskedLM"),
|
| 383 |
+
("transfo-xl", "TransfoXLLMHeadModel"),
|
| 384 |
+
("tvlt", "TvltForPreTraining"),
|
| 385 |
+
("unispeech", "UniSpeechForPreTraining"),
|
| 386 |
+
("unispeech-sat", "UniSpeechSatForPreTraining"),
|
| 387 |
+
("video_llava", "VideoLlavaForConditionalGeneration"),
|
| 388 |
+
("videomae", "VideoMAEForPreTraining"),
|
| 389 |
+
("vipllava", "VipLlavaForConditionalGeneration"),
|
| 390 |
+
("visual_bert", "VisualBertForPreTraining"),
|
| 391 |
+
("vit_mae", "ViTMAEForPreTraining"),
|
| 392 |
+
("wav2vec2", "Wav2Vec2ForPreTraining"),
|
| 393 |
+
("wav2vec2-conformer", "Wav2Vec2ConformerForPreTraining"),
|
| 394 |
+
("xlm", "XLMWithLMHeadModel"),
|
| 395 |
+
("xlm-roberta", "XLMRobertaForMaskedLM"),
|
| 396 |
+
("xlm-roberta-xl", "XLMRobertaXLForMaskedLM"),
|
| 397 |
+
("xlnet", "XLNetLMHeadModel"),
|
| 398 |
+
("xmod", "XmodForMaskedLM"),
|
| 399 |
+
]
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
MODEL_WITH_LM_HEAD_MAPPING_NAMES = OrderedDict(
|
| 403 |
+
[
|
| 404 |
+
# Model with LM heads mapping
|
| 405 |
+
("albert", "AlbertForMaskedLM"),
|
| 406 |
+
("bart", "BartForConditionalGeneration"),
|
| 407 |
+
("bert", "BertForMaskedLM"),
|
| 408 |
+
("big_bird", "BigBirdForMaskedLM"),
|
| 409 |
+
("bigbird_pegasus", "BigBirdPegasusForConditionalGeneration"),
|
| 410 |
+
("blenderbot-small", "BlenderbotSmallForConditionalGeneration"),
|
| 411 |
+
("bloom", "BloomForCausalLM"),
|
| 412 |
+
("camembert", "CamembertForMaskedLM"),
|
| 413 |
+
("codegen", "CodeGenForCausalLM"),
|
| 414 |
+
("convbert", "ConvBertForMaskedLM"),
|
| 415 |
+
("cpmant", "CpmAntForCausalLM"),
|
| 416 |
+
("ctrl", "CTRLLMHeadModel"),
|
| 417 |
+
("data2vec-text", "Data2VecTextForMaskedLM"),
|
| 418 |
+
("deberta", "DebertaForMaskedLM"),
|
| 419 |
+
("deberta-v2", "DebertaV2ForMaskedLM"),
|
| 420 |
+
("distilbert", "DistilBertForMaskedLM"),
|
| 421 |
+
("electra", "ElectraForMaskedLM"),
|
| 422 |
+
("encoder-decoder", "EncoderDecoderModel"),
|
| 423 |
+
("ernie", "ErnieForMaskedLM"),
|
| 424 |
+
("esm", "EsmForMaskedLM"),
|
| 425 |
+
("falcon_mamba", "FalconMambaForCausalLM"),
|
| 426 |
+
("flaubert", "FlaubertWithLMHeadModel"),
|
| 427 |
+
("fnet", "FNetForMaskedLM"),
|
| 428 |
+
("fsmt", "FSMTForConditionalGeneration"),
|
| 429 |
+
("funnel", "FunnelForMaskedLM"),
|
| 430 |
+
("git", "GitForCausalLM"),
|
| 431 |
+
("gpt-sw3", "GPT2LMHeadModel"),
|
| 432 |
+
("gpt2", "GPT2LMHeadModel"),
|
| 433 |
+
("gpt_bigcode", "GPTBigCodeForCausalLM"),
|
| 434 |
+
("gpt_neo", "GPTNeoForCausalLM"),
|
| 435 |
+
("gpt_neox", "GPTNeoXForCausalLM"),
|
| 436 |
+
("gpt_neox_japanese", "GPTNeoXJapaneseForCausalLM"),
|
| 437 |
+
("gptj", "GPTJForCausalLM"),
|
| 438 |
+
("gptsan-japanese", "GPTSanJapaneseForConditionalGeneration"),
|
| 439 |
+
("ibert", "IBertForMaskedLM"),
|
| 440 |
+
("layoutlm", "LayoutLMForMaskedLM"),
|
| 441 |
+
("led", "LEDForConditionalGeneration"),
|
| 442 |
+
("longformer", "LongformerForMaskedLM"),
|
| 443 |
+
("longt5", "LongT5ForConditionalGeneration"),
|
| 444 |
+
("luke", "LukeForMaskedLM"),
|
| 445 |
+
("m2m_100", "M2M100ForConditionalGeneration"),
|
| 446 |
+
("mamba", "MambaForCausalLM"),
|
| 447 |
+
("mamba2", "Mamba2ForCausalLM"),
|
| 448 |
+
("marian", "MarianMTModel"),
|
| 449 |
+
("mega", "MegaForMaskedLM"),
|
| 450 |
+
("megatron-bert", "MegatronBertForCausalLM"),
|
| 451 |
+
("mobilebert", "MobileBertForMaskedLM"),
|
| 452 |
+
("moonshine", "MoonshineForConditionalGeneration"),
|
| 453 |
+
("mpnet", "MPNetForMaskedLM"),
|
| 454 |
+
("mpt", "MptForCausalLM"),
|
| 455 |
+
("mra", "MraForMaskedLM"),
|
| 456 |
+
("mvp", "MvpForConditionalGeneration"),
|
| 457 |
+
("nezha", "NezhaForMaskedLM"),
|
| 458 |
+
("nllb-moe", "NllbMoeForConditionalGeneration"),
|
| 459 |
+
("nystromformer", "NystromformerForMaskedLM"),
|
| 460 |
+
("openai-gpt", "OpenAIGPTLMHeadModel"),
|
| 461 |
+
("pegasus_x", "PegasusXForConditionalGeneration"),
|
| 462 |
+
("plbart", "PLBartForConditionalGeneration"),
|
| 463 |
+
("pop2piano", "Pop2PianoForConditionalGeneration"),
|
| 464 |
+
("qdqbert", "QDQBertForMaskedLM"),
|
| 465 |
+
("reformer", "ReformerModelWithLMHead"),
|
| 466 |
+
("rembert", "RemBertForMaskedLM"),
|
| 467 |
+
("roberta", "RobertaForMaskedLM"),
|
| 468 |
+
("roberta-prelayernorm", "RobertaPreLayerNormForMaskedLM"),
|
| 469 |
+
("roc_bert", "RoCBertForMaskedLM"),
|
| 470 |
+
("roformer", "RoFormerForMaskedLM"),
|
| 471 |
+
("rwkv", "RwkvForCausalLM"),
|
| 472 |
+
("speech_to_text", "Speech2TextForConditionalGeneration"),
|
| 473 |
+
("squeezebert", "SqueezeBertForMaskedLM"),
|
| 474 |
+
("switch_transformers", "SwitchTransformersForConditionalGeneration"),
|
| 475 |
+
("t5", "T5ForConditionalGeneration"),
|
| 476 |
+
("tapas", "TapasForMaskedLM"),
|
| 477 |
+
("transfo-xl", "TransfoXLLMHeadModel"),
|
| 478 |
+
("wav2vec2", "Wav2Vec2ForMaskedLM"),
|
| 479 |
+
("whisper", "WhisperForConditionalGeneration"),
|
| 480 |
+
("xlm", "XLMWithLMHeadModel"),
|
| 481 |
+
("xlm-roberta", "XLMRobertaForMaskedLM"),
|
| 482 |
+
("xlm-roberta-xl", "XLMRobertaXLForMaskedLM"),
|
| 483 |
+
("xlnet", "XLNetLMHeadModel"),
|
| 484 |
+
("xmod", "XmodForMaskedLM"),
|
| 485 |
+
("yoso", "YosoForMaskedLM"),
|
| 486 |
+
]
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
MODEL_FOR_CAUSAL_LM_MAPPING_NAMES = OrderedDict(
|
| 490 |
+
[
|
| 491 |
+
# Model for Causal LM mapping
|
| 492 |
+
("aria_text", "AriaTextForCausalLM"),
|
| 493 |
+
("bamba", "BambaForCausalLM"),
|
| 494 |
+
("bart", "BartForCausalLM"),
|
| 495 |
+
("bert", "BertLMHeadModel"),
|
| 496 |
+
("bert-generation", "BertGenerationDecoder"),
|
| 497 |
+
("big_bird", "BigBirdForCausalLM"),
|
| 498 |
+
("bigbird_pegasus", "BigBirdPegasusForCausalLM"),
|
| 499 |
+
("biogpt", "BioGptForCausalLM"),
|
| 500 |
+
("blenderbot", "BlenderbotForCausalLM"),
|
| 501 |
+
("blenderbot-small", "BlenderbotSmallForCausalLM"),
|
| 502 |
+
("bloom", "BloomForCausalLM"),
|
| 503 |
+
("camembert", "CamembertForCausalLM"),
|
| 504 |
+
("code_llama", "LlamaForCausalLM"),
|
| 505 |
+
("codegen", "CodeGenForCausalLM"),
|
| 506 |
+
("cohere", "CohereForCausalLM"),
|
| 507 |
+
("cohere2", "Cohere2ForCausalLM"),
|
| 508 |
+
("cpmant", "CpmAntForCausalLM"),
|
| 509 |
+
("ctrl", "CTRLLMHeadModel"),
|
| 510 |
+
("data2vec-text", "Data2VecTextForCausalLM"),
|
| 511 |
+
("dbrx", "DbrxForCausalLM"),
|
| 512 |
+
("diffllama", "DiffLlamaForCausalLM"),
|
| 513 |
+
("electra", "ElectraForCausalLM"),
|
| 514 |
+
("emu3", "Emu3ForCausalLM"),
|
| 515 |
+
("ernie", "ErnieForCausalLM"),
|
| 516 |
+
("falcon", "FalconForCausalLM"),
|
| 517 |
+
("falcon_mamba", "FalconMambaForCausalLM"),
|
| 518 |
+
("fuyu", "FuyuForCausalLM"),
|
| 519 |
+
("gemma", "GemmaForCausalLM"),
|
| 520 |
+
("gemma2", "Gemma2ForCausalLM"),
|
| 521 |
+
("git", "GitForCausalLM"),
|
| 522 |
+
("glm", "GlmForCausalLM"),
|
| 523 |
+
("got_ocr2", "GotOcr2ForConditionalGeneration"),
|
| 524 |
+
("gpt-sw3", "GPT2LMHeadModel"),
|
| 525 |
+
("gpt2", "GPT2LMHeadModel"),
|
| 526 |
+
("gpt_bigcode", "GPTBigCodeForCausalLM"),
|
| 527 |
+
("gpt_neo", "GPTNeoForCausalLM"),
|
| 528 |
+
("gpt_neox", "GPTNeoXForCausalLM"),
|
| 529 |
+
("gpt_neox_japanese", "GPTNeoXJapaneseForCausalLM"),
|
| 530 |
+
("gptj", "GPTJForCausalLM"),
|
| 531 |
+
("granite", "GraniteForCausalLM"),
|
| 532 |
+
("granitemoe", "GraniteMoeForCausalLM"),
|
| 533 |
+
("granitemoeshared", "GraniteMoeSharedForCausalLM"),
|
| 534 |
+
("helium", "HeliumForCausalLM"),
|
| 535 |
+
("jamba", "JambaForCausalLM"),
|
| 536 |
+
("jetmoe", "JetMoeForCausalLM"),
|
| 537 |
+
("llama", "LlamaForCausalLM"),
|
| 538 |
+
("mamba", "MambaForCausalLM"),
|
| 539 |
+
("mamba2", "Mamba2ForCausalLM"),
|
| 540 |
+
("marian", "MarianForCausalLM"),
|
| 541 |
+
("mbart", "MBartForCausalLM"),
|
| 542 |
+
("mega", "MegaForCausalLM"),
|
| 543 |
+
("megatron-bert", "MegatronBertForCausalLM"),
|
| 544 |
+
("mistral", "MistralForCausalLM"),
|
| 545 |
+
("mixtral", "MixtralForCausalLM"),
|
| 546 |
+
("mllama", "MllamaForCausalLM"),
|
| 547 |
+
("moshi", "MoshiForCausalLM"),
|
| 548 |
+
("mpt", "MptForCausalLM"),
|
| 549 |
+
("musicgen", "MusicgenForCausalLM"),
|
| 550 |
+
("musicgen_melody", "MusicgenMelodyForCausalLM"),
|
| 551 |
+
("mvp", "MvpForCausalLM"),
|
| 552 |
+
("nemotron", "NemotronForCausalLM"),
|
| 553 |
+
("olmo", "OlmoForCausalLM"),
|
| 554 |
+
("olmo2", "Olmo2ForCausalLM"),
|
| 555 |
+
("olmoe", "OlmoeForCausalLM"),
|
| 556 |
+
("open-llama", "OpenLlamaForCausalLM"),
|
| 557 |
+
("openai-gpt", "OpenAIGPTLMHeadModel"),
|
| 558 |
+
("opt", "OPTForCausalLM"),
|
| 559 |
+
("pegasus", "PegasusForCausalLM"),
|
| 560 |
+
("persimmon", "PersimmonForCausalLM"),
|
| 561 |
+
("phi", "PhiForCausalLM"),
|
| 562 |
+
("phi3", "Phi3ForCausalLM"),
|
| 563 |
+
("phimoe", "PhimoeForCausalLM"),
|
| 564 |
+
("plbart", "PLBartForCausalLM"),
|
| 565 |
+
("prophetnet", "ProphetNetForCausalLM"),
|
| 566 |
+
("qdqbert", "QDQBertLMHeadModel"),
|
| 567 |
+
("qwen2", "Qwen2ForCausalLM"),
|
| 568 |
+
("qwen2_moe", "Qwen2MoeForCausalLM"),
|
| 569 |
+
("recurrent_gemma", "RecurrentGemmaForCausalLM"),
|
| 570 |
+
("reformer", "ReformerModelWithLMHead"),
|
| 571 |
+
("rembert", "RemBertForCausalLM"),
|
| 572 |
+
("roberta", "RobertaForCausalLM"),
|
| 573 |
+
("roberta-prelayernorm", "RobertaPreLayerNormForCausalLM"),
|
| 574 |
+
("roc_bert", "RoCBertForCausalLM"),
|
| 575 |
+
("roformer", "RoFormerForCausalLM"),
|
| 576 |
+
("rwkv", "RwkvForCausalLM"),
|
| 577 |
+
("speech_to_text_2", "Speech2Text2ForCausalLM"),
|
| 578 |
+
("stablelm", "StableLmForCausalLM"),
|
| 579 |
+
("starcoder2", "Starcoder2ForCausalLM"),
|
| 580 |
+
("transfo-xl", "TransfoXLLMHeadModel"),
|
| 581 |
+
("trocr", "TrOCRForCausalLM"),
|
| 582 |
+
("whisper", "WhisperForCausalLM"),
|
| 583 |
+
("xglm", "XGLMForCausalLM"),
|
| 584 |
+
("xlm", "XLMWithLMHeadModel"),
|
| 585 |
+
("xlm-prophetnet", "XLMProphetNetForCausalLM"),
|
| 586 |
+
("xlm-roberta", "XLMRobertaForCausalLM"),
|
| 587 |
+
("xlm-roberta-xl", "XLMRobertaXLForCausalLM"),
|
| 588 |
+
("xlnet", "XLNetLMHeadModel"),
|
| 589 |
+
("xmod", "XmodForCausalLM"),
|
| 590 |
+
("zamba", "ZambaForCausalLM"),
|
| 591 |
+
("zamba2", "Zamba2ForCausalLM"),
|
| 592 |
+
]
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
MODEL_FOR_IMAGE_MAPPING_NAMES = OrderedDict(
|
| 596 |
+
[
|
| 597 |
+
# Model for Image mapping
|
| 598 |
+
("beit", "BeitModel"),
|
| 599 |
+
("bit", "BitModel"),
|
| 600 |
+
("conditional_detr", "ConditionalDetrModel"),
|
| 601 |
+
("convnext", "ConvNextModel"),
|
| 602 |
+
("convnextv2", "ConvNextV2Model"),
|
| 603 |
+
("dab-detr", "DabDetrModel"),
|
| 604 |
+
("data2vec-vision", "Data2VecVisionModel"),
|
| 605 |
+
("deformable_detr", "DeformableDetrModel"),
|
| 606 |
+
("deit", "DeiTModel"),
|
| 607 |
+
("depth_pro", "DepthProModel"),
|
| 608 |
+
("deta", "DetaModel"),
|
| 609 |
+
("detr", "DetrModel"),
|
| 610 |
+
("dinat", "DinatModel"),
|
| 611 |
+
("dinov2", "Dinov2Model"),
|
| 612 |
+
("dinov2_with_registers", "Dinov2WithRegistersModel"),
|
| 613 |
+
("dpt", "DPTModel"),
|
| 614 |
+
("efficientformer", "EfficientFormerModel"),
|
| 615 |
+
("efficientnet", "EfficientNetModel"),
|
| 616 |
+
("focalnet", "FocalNetModel"),
|
| 617 |
+
("glpn", "GLPNModel"),
|
| 618 |
+
("hiera", "HieraModel"),
|
| 619 |
+
("ijepa", "IJepaModel"),
|
| 620 |
+
("imagegpt", "ImageGPTModel"),
|
| 621 |
+
("levit", "LevitModel"),
|
| 622 |
+
("mllama", "MllamaVisionModel"),
|
| 623 |
+
("mobilenet_v1", "MobileNetV1Model"),
|
| 624 |
+
("mobilenet_v2", "MobileNetV2Model"),
|
| 625 |
+
("mobilevit", "MobileViTModel"),
|
| 626 |
+
("mobilevitv2", "MobileViTV2Model"),
|
| 627 |
+
("nat", "NatModel"),
|
| 628 |
+
("poolformer", "PoolFormerModel"),
|
| 629 |
+
("pvt", "PvtModel"),
|
| 630 |
+
("regnet", "RegNetModel"),
|
| 631 |
+
("resnet", "ResNetModel"),
|
| 632 |
+
("segformer", "SegformerModel"),
|
| 633 |
+
("siglip_vision_model", "SiglipVisionModel"),
|
| 634 |
+
("swiftformer", "SwiftFormerModel"),
|
| 635 |
+
("swin", "SwinModel"),
|
| 636 |
+
("swin2sr", "Swin2SRModel"),
|
| 637 |
+
("swinv2", "Swinv2Model"),
|
| 638 |
+
("table-transformer", "TableTransformerModel"),
|
| 639 |
+
("timesformer", "TimesformerModel"),
|
| 640 |
+
("timm_backbone", "TimmBackbone"),
|
| 641 |
+
("timm_wrapper", "TimmWrapperModel"),
|
| 642 |
+
("van", "VanModel"),
|
| 643 |
+
("videomae", "VideoMAEModel"),
|
| 644 |
+
("vit", "ViTModel"),
|
| 645 |
+
("vit_hybrid", "ViTHybridModel"),
|
| 646 |
+
("vit_mae", "ViTMAEModel"),
|
| 647 |
+
("vit_msn", "ViTMSNModel"),
|
| 648 |
+
("vitdet", "VitDetModel"),
|
| 649 |
+
("vivit", "VivitModel"),
|
| 650 |
+
("yolos", "YolosModel"),
|
| 651 |
+
]
|
| 652 |
+
)
|
| 653 |
+
|
| 654 |
+
MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING_NAMES = OrderedDict(
|
| 655 |
+
[
|
| 656 |
+
("deit", "DeiTForMaskedImageModeling"),
|
| 657 |
+
("focalnet", "FocalNetForMaskedImageModeling"),
|
| 658 |
+
("swin", "SwinForMaskedImageModeling"),
|
| 659 |
+
("swinv2", "Swinv2ForMaskedImageModeling"),
|
| 660 |
+
("vit", "ViTForMaskedImageModeling"),
|
| 661 |
+
]
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING_NAMES = OrderedDict(
|
| 666 |
+
# Model for Causal Image Modeling mapping
|
| 667 |
+
[
|
| 668 |
+
("imagegpt", "ImageGPTForCausalImageModeling"),
|
| 669 |
+
]
|
| 670 |
+
)
|
| 671 |
+
|
| 672 |
+
MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 673 |
+
[
|
| 674 |
+
# Model for Image Classification mapping
|
| 675 |
+
("beit", "BeitForImageClassification"),
|
| 676 |
+
("bit", "BitForImageClassification"),
|
| 677 |
+
("clip", "CLIPForImageClassification"),
|
| 678 |
+
("convnext", "ConvNextForImageClassification"),
|
| 679 |
+
("convnextv2", "ConvNextV2ForImageClassification"),
|
| 680 |
+
("cvt", "CvtForImageClassification"),
|
| 681 |
+
("data2vec-vision", "Data2VecVisionForImageClassification"),
|
| 682 |
+
(
|
| 683 |
+
"deit",
|
| 684 |
+
("DeiTForImageClassification", "DeiTForImageClassificationWithTeacher"),
|
| 685 |
+
),
|
| 686 |
+
("dinat", "DinatForImageClassification"),
|
| 687 |
+
("dinov2", "Dinov2ForImageClassification"),
|
| 688 |
+
("dinov2_with_registers", "Dinov2WithRegistersForImageClassification"),
|
| 689 |
+
(
|
| 690 |
+
"efficientformer",
|
| 691 |
+
(
|
| 692 |
+
"EfficientFormerForImageClassification",
|
| 693 |
+
"EfficientFormerForImageClassificationWithTeacher",
|
| 694 |
+
),
|
| 695 |
+
),
|
| 696 |
+
("efficientnet", "EfficientNetForImageClassification"),
|
| 697 |
+
("focalnet", "FocalNetForImageClassification"),
|
| 698 |
+
("hiera", "HieraForImageClassification"),
|
| 699 |
+
("ijepa", "IJepaForImageClassification"),
|
| 700 |
+
("imagegpt", "ImageGPTForImageClassification"),
|
| 701 |
+
(
|
| 702 |
+
"levit",
|
| 703 |
+
("LevitForImageClassification", "LevitForImageClassificationWithTeacher"),
|
| 704 |
+
),
|
| 705 |
+
("mobilenet_v1", "MobileNetV1ForImageClassification"),
|
| 706 |
+
("mobilenet_v2", "MobileNetV2ForImageClassification"),
|
| 707 |
+
("mobilevit", "MobileViTForImageClassification"),
|
| 708 |
+
("mobilevitv2", "MobileViTV2ForImageClassification"),
|
| 709 |
+
("nat", "NatForImageClassification"),
|
| 710 |
+
(
|
| 711 |
+
"perceiver",
|
| 712 |
+
(
|
| 713 |
+
"PerceiverForImageClassificationLearned",
|
| 714 |
+
"PerceiverForImageClassificationFourier",
|
| 715 |
+
"PerceiverForImageClassificationConvProcessing",
|
| 716 |
+
),
|
| 717 |
+
),
|
| 718 |
+
("poolformer", "PoolFormerForImageClassification"),
|
| 719 |
+
("pvt", "PvtForImageClassification"),
|
| 720 |
+
("pvt_v2", "PvtV2ForImageClassification"),
|
| 721 |
+
("regnet", "RegNetForImageClassification"),
|
| 722 |
+
("resnet", "ResNetForImageClassification"),
|
| 723 |
+
("segformer", "SegformerForImageClassification"),
|
| 724 |
+
("siglip", "SiglipForImageClassification"),
|
| 725 |
+
("siglip2", "Siglip2ForImageClassification"),
|
| 726 |
+
("swiftformer", "SwiftFormerForImageClassification"),
|
| 727 |
+
("swin", "SwinForImageClassification"),
|
| 728 |
+
("swinv2", "Swinv2ForImageClassification"),
|
| 729 |
+
("textnet", "TextNetForImageClassification"),
|
| 730 |
+
("timm_wrapper", "TimmWrapperForImageClassification"),
|
| 731 |
+
("van", "VanForImageClassification"),
|
| 732 |
+
("vit", "ViTForImageClassification"),
|
| 733 |
+
("vit_hybrid", "ViTHybridForImageClassification"),
|
| 734 |
+
("vit_msn", "ViTMSNForImageClassification"),
|
| 735 |
+
]
|
| 736 |
+
)
|
| 737 |
+
|
| 738 |
+
MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES = OrderedDict(
|
| 739 |
+
[
|
| 740 |
+
# Do not add new models here, this class will be deprecated in the future.
|
| 741 |
+
# Model for Image Segmentation mapping
|
| 742 |
+
("detr", "DetrForSegmentation"),
|
| 743 |
+
]
|
| 744 |
+
)
|
| 745 |
+
|
| 746 |
+
MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = OrderedDict(
|
| 747 |
+
[
|
| 748 |
+
# Model for Semantic Segmentation mapping
|
| 749 |
+
("beit", "BeitForSemanticSegmentation"),
|
| 750 |
+
("data2vec-vision", "Data2VecVisionForSemanticSegmentation"),
|
| 751 |
+
("dpt", "DPTForSemanticSegmentation"),
|
| 752 |
+
("mobilenet_v2", "MobileNetV2ForSemanticSegmentation"),
|
| 753 |
+
("mobilevit", "MobileViTForSemanticSegmentation"),
|
| 754 |
+
("mobilevitv2", "MobileViTV2ForSemanticSegmentation"),
|
| 755 |
+
("segformer", "SegformerForSemanticSegmentation"),
|
| 756 |
+
("upernet", "UperNetForSemanticSegmentation"),
|
| 757 |
+
]
|
| 758 |
+
)
|
| 759 |
+
|
| 760 |
+
MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING_NAMES = OrderedDict(
|
| 761 |
+
[
|
| 762 |
+
# Model for Instance Segmentation mapping
|
| 763 |
+
# MaskFormerForInstanceSegmentation can be removed from this mapping in v5
|
| 764 |
+
("maskformer", "MaskFormerForInstanceSegmentation"),
|
| 765 |
+
]
|
| 766 |
+
)
|
| 767 |
+
|
| 768 |
+
MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES = OrderedDict(
|
| 769 |
+
[
|
| 770 |
+
# Model for Universal Segmentation mapping
|
| 771 |
+
("detr", "DetrForSegmentation"),
|
| 772 |
+
("mask2former", "Mask2FormerForUniversalSegmentation"),
|
| 773 |
+
("maskformer", "MaskFormerForInstanceSegmentation"),
|
| 774 |
+
("oneformer", "OneFormerForUniversalSegmentation"),
|
| 775 |
+
]
|
| 776 |
+
)
|
| 777 |
+
|
| 778 |
+
MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 779 |
+
[
|
| 780 |
+
("timesformer", "TimesformerForVideoClassification"),
|
| 781 |
+
("videomae", "VideoMAEForVideoClassification"),
|
| 782 |
+
("vivit", "VivitForVideoClassification"),
|
| 783 |
+
]
|
| 784 |
+
)
|
| 785 |
+
|
| 786 |
+
MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = OrderedDict(
|
| 787 |
+
[
|
| 788 |
+
("blip", "BlipForConditionalGeneration"),
|
| 789 |
+
("blip-2", "Blip2ForConditionalGeneration"),
|
| 790 |
+
("chameleon", "ChameleonForConditionalGeneration"),
|
| 791 |
+
("git", "GitForCausalLM"),
|
| 792 |
+
("idefics2", "Idefics2ForConditionalGeneration"),
|
| 793 |
+
("idefics3", "Idefics3ForConditionalGeneration"),
|
| 794 |
+
("instructblip", "InstructBlipForConditionalGeneration"),
|
| 795 |
+
("instructblipvideo", "InstructBlipVideoForConditionalGeneration"),
|
| 796 |
+
("kosmos-2", "Kosmos2ForConditionalGeneration"),
|
| 797 |
+
("llava", "LlavaForConditionalGeneration"),
|
| 798 |
+
("llava_next", "LlavaNextForConditionalGeneration"),
|
| 799 |
+
("llava_next_video", "LlavaNextVideoForConditionalGeneration"),
|
| 800 |
+
("llava_onevision", "LlavaOnevisionForConditionalGeneration"),
|
| 801 |
+
("mllama", "MllamaForConditionalGeneration"),
|
| 802 |
+
("paligemma", "PaliGemmaForConditionalGeneration"),
|
| 803 |
+
("pix2struct", "Pix2StructForConditionalGeneration"),
|
| 804 |
+
("qwen2_5_vl", "Qwen2_5_VLForConditionalGeneration"),
|
| 805 |
+
("qwen2_vl", "Qwen2VLForConditionalGeneration"),
|
| 806 |
+
("video_llava", "VideoLlavaForConditionalGeneration"),
|
| 807 |
+
("vipllava", "VipLlavaForConditionalGeneration"),
|
| 808 |
+
("vision-encoder-decoder", "VisionEncoderDecoderModel"),
|
| 809 |
+
]
|
| 810 |
+
)
|
| 811 |
+
|
| 812 |
+
MODEL_FOR_RETRIEVAL_MAPPING_NAMES = OrderedDict(
|
| 813 |
+
[
|
| 814 |
+
("colpali", "ColPaliForRetrieval"),
|
| 815 |
+
]
|
| 816 |
+
)
|
| 817 |
+
|
| 818 |
+
MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES = OrderedDict(
|
| 819 |
+
[
|
| 820 |
+
("aria", "AriaForConditionalGeneration"),
|
| 821 |
+
("aya_vision", "AyaVisionForConditionalGeneration"),
|
| 822 |
+
("blip", "BlipForConditionalGeneration"),
|
| 823 |
+
("blip-2", "Blip2ForConditionalGeneration"),
|
| 824 |
+
("chameleon", "ChameleonForConditionalGeneration"),
|
| 825 |
+
("emu3", "Emu3ForConditionalGeneration"),
|
| 826 |
+
("fuyu", "FuyuForCausalLM"),
|
| 827 |
+
("git", "GitForCausalLM"),
|
| 828 |
+
("got_ocr2", "GotOcr2ForConditionalGeneration"),
|
| 829 |
+
("idefics", "IdeficsForVisionText2Text"),
|
| 830 |
+
("idefics2", "Idefics2ForConditionalGeneration"),
|
| 831 |
+
("idefics3", "Idefics3ForConditionalGeneration"),
|
| 832 |
+
("instructblip", "InstructBlipForConditionalGeneration"),
|
| 833 |
+
("kosmos-2", "Kosmos2ForConditionalGeneration"),
|
| 834 |
+
("llava", "LlavaForConditionalGeneration"),
|
| 835 |
+
("llava_next", "LlavaNextForConditionalGeneration"),
|
| 836 |
+
("llava_onevision", "LlavaOnevisionForConditionalGeneration"),
|
| 837 |
+
("mllama", "MllamaForConditionalGeneration"),
|
| 838 |
+
("paligemma", "PaliGemmaForConditionalGeneration"),
|
| 839 |
+
("pix2struct", "Pix2StructForConditionalGeneration"),
|
| 840 |
+
("pixtral", "LlavaForConditionalGeneration"),
|
| 841 |
+
("qwen2_5_vl", "Qwen2_5_VLForConditionalGeneration"),
|
| 842 |
+
("qwen2_vl", "Qwen2VLForConditionalGeneration"),
|
| 843 |
+
("smolvlm", "SmolVLMForConditionalGeneration"),
|
| 844 |
+
("udop", "UdopForConditionalGeneration"),
|
| 845 |
+
("vipllava", "VipLlavaForConditionalGeneration"),
|
| 846 |
+
("vision-encoder-decoder", "VisionEncoderDecoderModel"),
|
| 847 |
+
]
|
| 848 |
+
)
|
| 849 |
+
|
| 850 |
+
MODEL_FOR_MASKED_LM_MAPPING_NAMES = OrderedDict(
|
| 851 |
+
[
|
| 852 |
+
# Model for Masked LM mapping
|
| 853 |
+
("albert", "AlbertForMaskedLM"),
|
| 854 |
+
("bart", "BartForConditionalGeneration"),
|
| 855 |
+
("bert", "BertForMaskedLM"),
|
| 856 |
+
("big_bird", "BigBirdForMaskedLM"),
|
| 857 |
+
("camembert", "CamembertForMaskedLM"),
|
| 858 |
+
("convbert", "ConvBertForMaskedLM"),
|
| 859 |
+
("data2vec-text", "Data2VecTextForMaskedLM"),
|
| 860 |
+
("deberta", "DebertaForMaskedLM"),
|
| 861 |
+
("deberta-v2", "DebertaV2ForMaskedLM"),
|
| 862 |
+
("distilbert", "DistilBertForMaskedLM"),
|
| 863 |
+
("electra", "ElectraForMaskedLM"),
|
| 864 |
+
("ernie", "ErnieForMaskedLM"),
|
| 865 |
+
("esm", "EsmForMaskedLM"),
|
| 866 |
+
("flaubert", "FlaubertWithLMHeadModel"),
|
| 867 |
+
("fnet", "FNetForMaskedLM"),
|
| 868 |
+
("funnel", "FunnelForMaskedLM"),
|
| 869 |
+
("ibert", "IBertForMaskedLM"),
|
| 870 |
+
("layoutlm", "LayoutLMForMaskedLM"),
|
| 871 |
+
("longformer", "LongformerForMaskedLM"),
|
| 872 |
+
("luke", "LukeForMaskedLM"),
|
| 873 |
+
("mbart", "MBartForConditionalGeneration"),
|
| 874 |
+
("mega", "MegaForMaskedLM"),
|
| 875 |
+
("megatron-bert", "MegatronBertForMaskedLM"),
|
| 876 |
+
("mobilebert", "MobileBertForMaskedLM"),
|
| 877 |
+
("modernbert", "ModernBertForMaskedLM"),
|
| 878 |
+
("mpnet", "MPNetForMaskedLM"),
|
| 879 |
+
("mra", "MraForMaskedLM"),
|
| 880 |
+
("mvp", "MvpForConditionalGeneration"),
|
| 881 |
+
("nezha", "NezhaForMaskedLM"),
|
| 882 |
+
("nystromformer", "NystromformerForMaskedLM"),
|
| 883 |
+
("perceiver", "PerceiverForMaskedLM"),
|
| 884 |
+
("qdqbert", "QDQBertForMaskedLM"),
|
| 885 |
+
("reformer", "ReformerForMaskedLM"),
|
| 886 |
+
("rembert", "RemBertForMaskedLM"),
|
| 887 |
+
("roberta", "RobertaForMaskedLM"),
|
| 888 |
+
("roberta-prelayernorm", "RobertaPreLayerNormForMaskedLM"),
|
| 889 |
+
("roc_bert", "RoCBertForMaskedLM"),
|
| 890 |
+
("roformer", "RoFormerForMaskedLM"),
|
| 891 |
+
("squeezebert", "SqueezeBertForMaskedLM"),
|
| 892 |
+
("tapas", "TapasForMaskedLM"),
|
| 893 |
+
("wav2vec2", "Wav2Vec2ForMaskedLM"),
|
| 894 |
+
("xlm", "XLMWithLMHeadModel"),
|
| 895 |
+
("xlm-roberta", "XLMRobertaForMaskedLM"),
|
| 896 |
+
("xlm-roberta-xl", "XLMRobertaXLForMaskedLM"),
|
| 897 |
+
("xmod", "XmodForMaskedLM"),
|
| 898 |
+
("yoso", "YosoForMaskedLM"),
|
| 899 |
+
]
|
| 900 |
+
)
|
| 901 |
+
|
| 902 |
+
MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES = OrderedDict(
|
| 903 |
+
[
|
| 904 |
+
# Model for Object Detection mapping
|
| 905 |
+
("conditional_detr", "ConditionalDetrForObjectDetection"),
|
| 906 |
+
("dab-detr", "DabDetrForObjectDetection"),
|
| 907 |
+
("deformable_detr", "DeformableDetrForObjectDetection"),
|
| 908 |
+
("deta", "DetaForObjectDetection"),
|
| 909 |
+
("detr", "DetrForObjectDetection"),
|
| 910 |
+
("rt_detr", "RTDetrForObjectDetection"),
|
| 911 |
+
("rt_detr_v2", "RTDetrV2ForObjectDetection"),
|
| 912 |
+
("table-transformer", "TableTransformerForObjectDetection"),
|
| 913 |
+
("yolos", "YolosForObjectDetection"),
|
| 914 |
+
]
|
| 915 |
+
)
|
| 916 |
+
|
| 917 |
+
MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES = OrderedDict(
|
| 918 |
+
[
|
| 919 |
+
# Model for Zero Shot Object Detection mapping
|
| 920 |
+
("grounding-dino", "GroundingDinoForObjectDetection"),
|
| 921 |
+
("omdet-turbo", "OmDetTurboForObjectDetection"),
|
| 922 |
+
("owlv2", "Owlv2ForObjectDetection"),
|
| 923 |
+
("owlvit", "OwlViTForObjectDetection"),
|
| 924 |
+
]
|
| 925 |
+
)
|
| 926 |
+
|
| 927 |
+
MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES = OrderedDict(
|
| 928 |
+
[
|
| 929 |
+
# Model for depth estimation mapping
|
| 930 |
+
("depth_anything", "DepthAnythingForDepthEstimation"),
|
| 931 |
+
("depth_pro", "DepthProForDepthEstimation"),
|
| 932 |
+
("dpt", "DPTForDepthEstimation"),
|
| 933 |
+
("glpn", "GLPNForDepthEstimation"),
|
| 934 |
+
("zoedepth", "ZoeDepthForDepthEstimation"),
|
| 935 |
+
]
|
| 936 |
+
)
|
| 937 |
+
MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = OrderedDict(
|
| 938 |
+
[
|
| 939 |
+
# Model for Seq2Seq Causal LM mapping
|
| 940 |
+
("bart", "BartForConditionalGeneration"),
|
| 941 |
+
("bigbird_pegasus", "BigBirdPegasusForConditionalGeneration"),
|
| 942 |
+
("blenderbot", "BlenderbotForConditionalGeneration"),
|
| 943 |
+
("blenderbot-small", "BlenderbotSmallForConditionalGeneration"),
|
| 944 |
+
("encoder-decoder", "EncoderDecoderModel"),
|
| 945 |
+
("fsmt", "FSMTForConditionalGeneration"),
|
| 946 |
+
("gptsan-japanese", "GPTSanJapaneseForConditionalGeneration"),
|
| 947 |
+
("led", "LEDForConditionalGeneration"),
|
| 948 |
+
("longt5", "LongT5ForConditionalGeneration"),
|
| 949 |
+
("m2m_100", "M2M100ForConditionalGeneration"),
|
| 950 |
+
("marian", "MarianMTModel"),
|
| 951 |
+
("mbart", "MBartForConditionalGeneration"),
|
| 952 |
+
("mt5", "MT5ForConditionalGeneration"),
|
| 953 |
+
("mvp", "MvpForConditionalGeneration"),
|
| 954 |
+
("nllb-moe", "NllbMoeForConditionalGeneration"),
|
| 955 |
+
("pegasus", "PegasusForConditionalGeneration"),
|
| 956 |
+
("pegasus_x", "PegasusXForConditionalGeneration"),
|
| 957 |
+
("plbart", "PLBartForConditionalGeneration"),
|
| 958 |
+
("prophetnet", "ProphetNetForConditionalGeneration"),
|
| 959 |
+
("qwen2_audio", "Qwen2AudioForConditionalGeneration"),
|
| 960 |
+
("seamless_m4t", "SeamlessM4TForTextToText"),
|
| 961 |
+
("seamless_m4t_v2", "SeamlessM4Tv2ForTextToText"),
|
| 962 |
+
("switch_transformers", "SwitchTransformersForConditionalGeneration"),
|
| 963 |
+
("t5", "T5ForConditionalGeneration"),
|
| 964 |
+
("umt5", "UMT5ForConditionalGeneration"),
|
| 965 |
+
("xlm-prophetnet", "XLMProphetNetForConditionalGeneration"),
|
| 966 |
+
]
|
| 967 |
+
)
|
| 968 |
+
|
| 969 |
+
MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = OrderedDict(
|
| 970 |
+
[
|
| 971 |
+
("moonshine", "MoonshineForConditionalGeneration"),
|
| 972 |
+
("pop2piano", "Pop2PianoForConditionalGeneration"),
|
| 973 |
+
("seamless_m4t", "SeamlessM4TForSpeechToText"),
|
| 974 |
+
("seamless_m4t_v2", "SeamlessM4Tv2ForSpeechToText"),
|
| 975 |
+
("speech-encoder-decoder", "SpeechEncoderDecoderModel"),
|
| 976 |
+
("speech_to_text", "Speech2TextForConditionalGeneration"),
|
| 977 |
+
("speecht5", "SpeechT5ForSpeechToText"),
|
| 978 |
+
("whisper", "WhisperForConditionalGeneration"),
|
| 979 |
+
]
|
| 980 |
+
)
|
| 981 |
+
|
| 982 |
+
MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 983 |
+
[
|
| 984 |
+
# Model for Sequence Classification mapping
|
| 985 |
+
("albert", "AlbertForSequenceClassification"),
|
| 986 |
+
("bart", "BartForSequenceClassification"),
|
| 987 |
+
("bert", "BertForSequenceClassification"),
|
| 988 |
+
("big_bird", "BigBirdForSequenceClassification"),
|
| 989 |
+
("bigbird_pegasus", "BigBirdPegasusForSequenceClassification"),
|
| 990 |
+
("biogpt", "BioGptForSequenceClassification"),
|
| 991 |
+
("bloom", "BloomForSequenceClassification"),
|
| 992 |
+
("camembert", "CamembertForSequenceClassification"),
|
| 993 |
+
("canine", "CanineForSequenceClassification"),
|
| 994 |
+
("code_llama", "LlamaForSequenceClassification"),
|
| 995 |
+
("convbert", "ConvBertForSequenceClassification"),
|
| 996 |
+
("ctrl", "CTRLForSequenceClassification"),
|
| 997 |
+
("data2vec-text", "Data2VecTextForSequenceClassification"),
|
| 998 |
+
("deberta", "DebertaForSequenceClassification"),
|
| 999 |
+
("deberta-v2", "DebertaV2ForSequenceClassification"),
|
| 1000 |
+
("diffllama", "DiffLlamaForSequenceClassification"),
|
| 1001 |
+
("distilbert", "DistilBertForSequenceClassification"),
|
| 1002 |
+
("electra", "ElectraForSequenceClassification"),
|
| 1003 |
+
("ernie", "ErnieForSequenceClassification"),
|
| 1004 |
+
("ernie_m", "ErnieMForSequenceClassification"),
|
| 1005 |
+
("esm", "EsmForSequenceClassification"),
|
| 1006 |
+
("falcon", "FalconForSequenceClassification"),
|
| 1007 |
+
("flaubert", "FlaubertForSequenceClassification"),
|
| 1008 |
+
("fnet", "FNetForSequenceClassification"),
|
| 1009 |
+
("funnel", "FunnelForSequenceClassification"),
|
| 1010 |
+
("gemma", "GemmaForSequenceClassification"),
|
| 1011 |
+
("gemma2", "Gemma2ForSequenceClassification"),
|
| 1012 |
+
("glm", "GlmForSequenceClassification"),
|
| 1013 |
+
("gpt-sw3", "GPT2ForSequenceClassification"),
|
| 1014 |
+
("gpt2", "GPT2ForSequenceClassification"),
|
| 1015 |
+
("gpt_bigcode", "GPTBigCodeForSequenceClassification"),
|
| 1016 |
+
("gpt_neo", "GPTNeoForSequenceClassification"),
|
| 1017 |
+
("gpt_neox", "GPTNeoXForSequenceClassification"),
|
| 1018 |
+
("gptj", "GPTJForSequenceClassification"),
|
| 1019 |
+
("helium", "HeliumForSequenceClassification"),
|
| 1020 |
+
("ibert", "IBertForSequenceClassification"),
|
| 1021 |
+
("jamba", "JambaForSequenceClassification"),
|
| 1022 |
+
("jetmoe", "JetMoeForSequenceClassification"),
|
| 1023 |
+
("layoutlm", "LayoutLMForSequenceClassification"),
|
| 1024 |
+
("layoutlmv2", "LayoutLMv2ForSequenceClassification"),
|
| 1025 |
+
("layoutlmv3", "LayoutLMv3ForSequenceClassification"),
|
| 1026 |
+
("led", "LEDForSequenceClassification"),
|
| 1027 |
+
("lilt", "LiltForSequenceClassification"),
|
| 1028 |
+
("llama", "LlamaForSequenceClassification"),
|
| 1029 |
+
("longformer", "LongformerForSequenceClassification"),
|
| 1030 |
+
("luke", "LukeForSequenceClassification"),
|
| 1031 |
+
("markuplm", "MarkupLMForSequenceClassification"),
|
| 1032 |
+
("mbart", "MBartForSequenceClassification"),
|
| 1033 |
+
("mega", "MegaForSequenceClassification"),
|
| 1034 |
+
("megatron-bert", "MegatronBertForSequenceClassification"),
|
| 1035 |
+
("mistral", "MistralForSequenceClassification"),
|
| 1036 |
+
("mixtral", "MixtralForSequenceClassification"),
|
| 1037 |
+
("mobilebert", "MobileBertForSequenceClassification"),
|
| 1038 |
+
("modernbert", "ModernBertForSequenceClassification"),
|
| 1039 |
+
("mpnet", "MPNetForSequenceClassification"),
|
| 1040 |
+
("mpt", "MptForSequenceClassification"),
|
| 1041 |
+
("mra", "MraForSequenceClassification"),
|
| 1042 |
+
("mt5", "MT5ForSequenceClassification"),
|
| 1043 |
+
("mvp", "MvpForSequenceClassification"),
|
| 1044 |
+
("nemotron", "NemotronForSequenceClassification"),
|
| 1045 |
+
("nezha", "NezhaForSequenceClassification"),
|
| 1046 |
+
("nystromformer", "NystromformerForSequenceClassification"),
|
| 1047 |
+
("open-llama", "OpenLlamaForSequenceClassification"),
|
| 1048 |
+
("openai-gpt", "OpenAIGPTForSequenceClassification"),
|
| 1049 |
+
("opt", "OPTForSequenceClassification"),
|
| 1050 |
+
("perceiver", "PerceiverForSequenceClassification"),
|
| 1051 |
+
("persimmon", "PersimmonForSequenceClassification"),
|
| 1052 |
+
("phi", "PhiForSequenceClassification"),
|
| 1053 |
+
("phi3", "Phi3ForSequenceClassification"),
|
| 1054 |
+
("phimoe", "PhimoeForSequenceClassification"),
|
| 1055 |
+
("plbart", "PLBartForSequenceClassification"),
|
| 1056 |
+
("qdqbert", "QDQBertForSequenceClassification"),
|
| 1057 |
+
("qwen2", "Qwen2ForSequenceClassification"),
|
| 1058 |
+
("qwen2_moe", "Qwen2MoeForSequenceClassification"),
|
| 1059 |
+
("reformer", "ReformerForSequenceClassification"),
|
| 1060 |
+
("rembert", "RemBertForSequenceClassification"),
|
| 1061 |
+
("roberta", "RobertaForSequenceClassification"),
|
| 1062 |
+
("roberta-prelayernorm", "RobertaPreLayerNormForSequenceClassification"),
|
| 1063 |
+
("roc_bert", "RoCBertForSequenceClassification"),
|
| 1064 |
+
("roformer", "RoFormerForSequenceClassification"),
|
| 1065 |
+
("squeezebert", "SqueezeBertForSequenceClassification"),
|
| 1066 |
+
("stablelm", "StableLmForSequenceClassification"),
|
| 1067 |
+
("starcoder2", "Starcoder2ForSequenceClassification"),
|
| 1068 |
+
("t5", "T5ForSequenceClassification"),
|
| 1069 |
+
("tapas", "TapasForSequenceClassification"),
|
| 1070 |
+
("transfo-xl", "TransfoXLForSequenceClassification"),
|
| 1071 |
+
("umt5", "UMT5ForSequenceClassification"),
|
| 1072 |
+
("xlm", "XLMForSequenceClassification"),
|
| 1073 |
+
("xlm-roberta", "XLMRobertaForSequenceClassification"),
|
| 1074 |
+
("xlm-roberta-xl", "XLMRobertaXLForSequenceClassification"),
|
| 1075 |
+
("xlnet", "XLNetForSequenceClassification"),
|
| 1076 |
+
("xmod", "XmodForSequenceClassification"),
|
| 1077 |
+
("yoso", "YosoForSequenceClassification"),
|
| 1078 |
+
("zamba", "ZambaForSequenceClassification"),
|
| 1079 |
+
("zamba2", "Zamba2ForSequenceClassification"),
|
| 1080 |
+
]
|
| 1081 |
+
)
|
| 1082 |
+
|
| 1083 |
+
MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
|
| 1084 |
+
[
|
| 1085 |
+
# Model for Question Answering mapping
|
| 1086 |
+
("albert", "AlbertForQuestionAnswering"),
|
| 1087 |
+
("bart", "BartForQuestionAnswering"),
|
| 1088 |
+
("bert", "BertForQuestionAnswering"),
|
| 1089 |
+
("big_bird", "BigBirdForQuestionAnswering"),
|
| 1090 |
+
("bigbird_pegasus", "BigBirdPegasusForQuestionAnswering"),
|
| 1091 |
+
("bloom", "BloomForQuestionAnswering"),
|
| 1092 |
+
("camembert", "CamembertForQuestionAnswering"),
|
| 1093 |
+
("canine", "CanineForQuestionAnswering"),
|
| 1094 |
+
("convbert", "ConvBertForQuestionAnswering"),
|
| 1095 |
+
("data2vec-text", "Data2VecTextForQuestionAnswering"),
|
| 1096 |
+
("deberta", "DebertaForQuestionAnswering"),
|
| 1097 |
+
("deberta-v2", "DebertaV2ForQuestionAnswering"),
|
| 1098 |
+
("diffllama", "DiffLlamaForQuestionAnswering"),
|
| 1099 |
+
("distilbert", "DistilBertForQuestionAnswering"),
|
| 1100 |
+
("electra", "ElectraForQuestionAnswering"),
|
| 1101 |
+
("ernie", "ErnieForQuestionAnswering"),
|
| 1102 |
+
("ernie_m", "ErnieMForQuestionAnswering"),
|
| 1103 |
+
("falcon", "FalconForQuestionAnswering"),
|
| 1104 |
+
("flaubert", "FlaubertForQuestionAnsweringSimple"),
|
| 1105 |
+
("fnet", "FNetForQuestionAnswering"),
|
| 1106 |
+
("funnel", "FunnelForQuestionAnswering"),
|
| 1107 |
+
("gpt2", "GPT2ForQuestionAnswering"),
|
| 1108 |
+
("gpt_neo", "GPTNeoForQuestionAnswering"),
|
| 1109 |
+
("gpt_neox", "GPTNeoXForQuestionAnswering"),
|
| 1110 |
+
("gptj", "GPTJForQuestionAnswering"),
|
| 1111 |
+
("ibert", "IBertForQuestionAnswering"),
|
| 1112 |
+
("layoutlmv2", "LayoutLMv2ForQuestionAnswering"),
|
| 1113 |
+
("layoutlmv3", "LayoutLMv3ForQuestionAnswering"),
|
| 1114 |
+
("led", "LEDForQuestionAnswering"),
|
| 1115 |
+
("lilt", "LiltForQuestionAnswering"),
|
| 1116 |
+
("llama", "LlamaForQuestionAnswering"),
|
| 1117 |
+
("longformer", "LongformerForQuestionAnswering"),
|
| 1118 |
+
("luke", "LukeForQuestionAnswering"),
|
| 1119 |
+
("lxmert", "LxmertForQuestionAnswering"),
|
| 1120 |
+
("markuplm", "MarkupLMForQuestionAnswering"),
|
| 1121 |
+
("mbart", "MBartForQuestionAnswering"),
|
| 1122 |
+
("mega", "MegaForQuestionAnswering"),
|
| 1123 |
+
("megatron-bert", "MegatronBertForQuestionAnswering"),
|
| 1124 |
+
("mistral", "MistralForQuestionAnswering"),
|
| 1125 |
+
("mixtral", "MixtralForQuestionAnswering"),
|
| 1126 |
+
("mobilebert", "MobileBertForQuestionAnswering"),
|
| 1127 |
+
("mpnet", "MPNetForQuestionAnswering"),
|
| 1128 |
+
("mpt", "MptForQuestionAnswering"),
|
| 1129 |
+
("mra", "MraForQuestionAnswering"),
|
| 1130 |
+
("mt5", "MT5ForQuestionAnswering"),
|
| 1131 |
+
("mvp", "MvpForQuestionAnswering"),
|
| 1132 |
+
("nemotron", "NemotronForQuestionAnswering"),
|
| 1133 |
+
("nezha", "NezhaForQuestionAnswering"),
|
| 1134 |
+
("nystromformer", "NystromformerForQuestionAnswering"),
|
| 1135 |
+
("opt", "OPTForQuestionAnswering"),
|
| 1136 |
+
("qdqbert", "QDQBertForQuestionAnswering"),
|
| 1137 |
+
("qwen2", "Qwen2ForQuestionAnswering"),
|
| 1138 |
+
("qwen2_moe", "Qwen2MoeForQuestionAnswering"),
|
| 1139 |
+
("reformer", "ReformerForQuestionAnswering"),
|
| 1140 |
+
("rembert", "RemBertForQuestionAnswering"),
|
| 1141 |
+
("roberta", "RobertaForQuestionAnswering"),
|
| 1142 |
+
("roberta-prelayernorm", "RobertaPreLayerNormForQuestionAnswering"),
|
| 1143 |
+
("roc_bert", "RoCBertForQuestionAnswering"),
|
| 1144 |
+
("roformer", "RoFormerForQuestionAnswering"),
|
| 1145 |
+
("splinter", "SplinterForQuestionAnswering"),
|
| 1146 |
+
("squeezebert", "SqueezeBertForQuestionAnswering"),
|
| 1147 |
+
("t5", "T5ForQuestionAnswering"),
|
| 1148 |
+
("umt5", "UMT5ForQuestionAnswering"),
|
| 1149 |
+
("xlm", "XLMForQuestionAnsweringSimple"),
|
| 1150 |
+
("xlm-roberta", "XLMRobertaForQuestionAnswering"),
|
| 1151 |
+
("xlm-roberta-xl", "XLMRobertaXLForQuestionAnswering"),
|
| 1152 |
+
("xlnet", "XLNetForQuestionAnsweringSimple"),
|
| 1153 |
+
("xmod", "XmodForQuestionAnswering"),
|
| 1154 |
+
("yoso", "YosoForQuestionAnswering"),
|
| 1155 |
+
]
|
| 1156 |
+
)
|
| 1157 |
+
|
| 1158 |
+
MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
|
| 1159 |
+
[
|
| 1160 |
+
# Model for Table Question Answering mapping
|
| 1161 |
+
("tapas", "TapasForQuestionAnswering"),
|
| 1162 |
+
]
|
| 1163 |
+
)
|
| 1164 |
+
|
| 1165 |
+
MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
|
| 1166 |
+
[
|
| 1167 |
+
("blip", "BlipForQuestionAnswering"),
|
| 1168 |
+
("blip-2", "Blip2ForConditionalGeneration"),
|
| 1169 |
+
("vilt", "ViltForQuestionAnswering"),
|
| 1170 |
+
]
|
| 1171 |
+
)
|
| 1172 |
+
|
| 1173 |
+
MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
|
| 1174 |
+
[
|
| 1175 |
+
("layoutlm", "LayoutLMForQuestionAnswering"),
|
| 1176 |
+
("layoutlmv2", "LayoutLMv2ForQuestionAnswering"),
|
| 1177 |
+
("layoutlmv3", "LayoutLMv3ForQuestionAnswering"),
|
| 1178 |
+
]
|
| 1179 |
+
)
|
| 1180 |
+
|
| 1181 |
+
MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 1182 |
+
[
|
| 1183 |
+
# Model for Token Classification mapping
|
| 1184 |
+
("albert", "AlbertForTokenClassification"),
|
| 1185 |
+
("bert", "BertForTokenClassification"),
|
| 1186 |
+
("big_bird", "BigBirdForTokenClassification"),
|
| 1187 |
+
("biogpt", "BioGptForTokenClassification"),
|
| 1188 |
+
("bloom", "BloomForTokenClassification"),
|
| 1189 |
+
("bros", "BrosForTokenClassification"),
|
| 1190 |
+
("camembert", "CamembertForTokenClassification"),
|
| 1191 |
+
("canine", "CanineForTokenClassification"),
|
| 1192 |
+
("convbert", "ConvBertForTokenClassification"),
|
| 1193 |
+
("data2vec-text", "Data2VecTextForTokenClassification"),
|
| 1194 |
+
("deberta", "DebertaForTokenClassification"),
|
| 1195 |
+
("deberta-v2", "DebertaV2ForTokenClassification"),
|
| 1196 |
+
("diffllama", "DiffLlamaForTokenClassification"),
|
| 1197 |
+
("distilbert", "DistilBertForTokenClassification"),
|
| 1198 |
+
("electra", "ElectraForTokenClassification"),
|
| 1199 |
+
("ernie", "ErnieForTokenClassification"),
|
| 1200 |
+
("ernie_m", "ErnieMForTokenClassification"),
|
| 1201 |
+
("esm", "EsmForTokenClassification"),
|
| 1202 |
+
("falcon", "FalconForTokenClassification"),
|
| 1203 |
+
("flaubert", "FlaubertForTokenClassification"),
|
| 1204 |
+
("fnet", "FNetForTokenClassification"),
|
| 1205 |
+
("funnel", "FunnelForTokenClassification"),
|
| 1206 |
+
("gemma", "GemmaForTokenClassification"),
|
| 1207 |
+
("gemma2", "Gemma2ForTokenClassification"),
|
| 1208 |
+
("glm", "GlmForTokenClassification"),
|
| 1209 |
+
("gpt-sw3", "GPT2ForTokenClassification"),
|
| 1210 |
+
("gpt2", "GPT2ForTokenClassification"),
|
| 1211 |
+
("gpt_bigcode", "GPTBigCodeForTokenClassification"),
|
| 1212 |
+
("gpt_neo", "GPTNeoForTokenClassification"),
|
| 1213 |
+
("gpt_neox", "GPTNeoXForTokenClassification"),
|
| 1214 |
+
("helium", "HeliumForTokenClassification"),
|
| 1215 |
+
("ibert", "IBertForTokenClassification"),
|
| 1216 |
+
("layoutlm", "LayoutLMForTokenClassification"),
|
| 1217 |
+
("layoutlmv2", "LayoutLMv2ForTokenClassification"),
|
| 1218 |
+
("layoutlmv3", "LayoutLMv3ForTokenClassification"),
|
| 1219 |
+
("lilt", "LiltForTokenClassification"),
|
| 1220 |
+
("llama", "LlamaForTokenClassification"),
|
| 1221 |
+
("longformer", "LongformerForTokenClassification"),
|
| 1222 |
+
("luke", "LukeForTokenClassification"),
|
| 1223 |
+
("markuplm", "MarkupLMForTokenClassification"),
|
| 1224 |
+
("mega", "MegaForTokenClassification"),
|
| 1225 |
+
("megatron-bert", "MegatronBertForTokenClassification"),
|
| 1226 |
+
("mistral", "MistralForTokenClassification"),
|
| 1227 |
+
("mixtral", "MixtralForTokenClassification"),
|
| 1228 |
+
("mobilebert", "MobileBertForTokenClassification"),
|
| 1229 |
+
("modernbert", "ModernBertForTokenClassification"),
|
| 1230 |
+
("mpnet", "MPNetForTokenClassification"),
|
| 1231 |
+
("mpt", "MptForTokenClassification"),
|
| 1232 |
+
("mra", "MraForTokenClassification"),
|
| 1233 |
+
("mt5", "MT5ForTokenClassification"),
|
| 1234 |
+
("nemotron", "NemotronForTokenClassification"),
|
| 1235 |
+
("nezha", "NezhaForTokenClassification"),
|
| 1236 |
+
("nystromformer", "NystromformerForTokenClassification"),
|
| 1237 |
+
("persimmon", "PersimmonForTokenClassification"),
|
| 1238 |
+
("phi", "PhiForTokenClassification"),
|
| 1239 |
+
("phi3", "Phi3ForTokenClassification"),
|
| 1240 |
+
("qdqbert", "QDQBertForTokenClassification"),
|
| 1241 |
+
("qwen2", "Qwen2ForTokenClassification"),
|
| 1242 |
+
("qwen2_moe", "Qwen2MoeForTokenClassification"),
|
| 1243 |
+
("rembert", "RemBertForTokenClassification"),
|
| 1244 |
+
("roberta", "RobertaForTokenClassification"),
|
| 1245 |
+
("roberta-prelayernorm", "RobertaPreLayerNormForTokenClassification"),
|
| 1246 |
+
("roc_bert", "RoCBertForTokenClassification"),
|
| 1247 |
+
("roformer", "RoFormerForTokenClassification"),
|
| 1248 |
+
("squeezebert", "SqueezeBertForTokenClassification"),
|
| 1249 |
+
("stablelm", "StableLmForTokenClassification"),
|
| 1250 |
+
("starcoder2", "Starcoder2ForTokenClassification"),
|
| 1251 |
+
("t5", "T5ForTokenClassification"),
|
| 1252 |
+
("umt5", "UMT5ForTokenClassification"),
|
| 1253 |
+
("xlm", "XLMForTokenClassification"),
|
| 1254 |
+
("xlm-roberta", "XLMRobertaForTokenClassification"),
|
| 1255 |
+
("xlm-roberta-xl", "XLMRobertaXLForTokenClassification"),
|
| 1256 |
+
("xlnet", "XLNetForTokenClassification"),
|
| 1257 |
+
("xmod", "XmodForTokenClassification"),
|
| 1258 |
+
("yoso", "YosoForTokenClassification"),
|
| 1259 |
+
]
|
| 1260 |
+
)
|
| 1261 |
+
|
| 1262 |
+
MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES = OrderedDict(
|
| 1263 |
+
[
|
| 1264 |
+
# Model for Multiple Choice mapping
|
| 1265 |
+
("albert", "AlbertForMultipleChoice"),
|
| 1266 |
+
("bert", "BertForMultipleChoice"),
|
| 1267 |
+
("big_bird", "BigBirdForMultipleChoice"),
|
| 1268 |
+
("camembert", "CamembertForMultipleChoice"),
|
| 1269 |
+
("canine", "CanineForMultipleChoice"),
|
| 1270 |
+
("convbert", "ConvBertForMultipleChoice"),
|
| 1271 |
+
("data2vec-text", "Data2VecTextForMultipleChoice"),
|
| 1272 |
+
("deberta-v2", "DebertaV2ForMultipleChoice"),
|
| 1273 |
+
("distilbert", "DistilBertForMultipleChoice"),
|
| 1274 |
+
("electra", "ElectraForMultipleChoice"),
|
| 1275 |
+
("ernie", "ErnieForMultipleChoice"),
|
| 1276 |
+
("ernie_m", "ErnieMForMultipleChoice"),
|
| 1277 |
+
("flaubert", "FlaubertForMultipleChoice"),
|
| 1278 |
+
("fnet", "FNetForMultipleChoice"),
|
| 1279 |
+
("funnel", "FunnelForMultipleChoice"),
|
| 1280 |
+
("ibert", "IBertForMultipleChoice"),
|
| 1281 |
+
("longformer", "LongformerForMultipleChoice"),
|
| 1282 |
+
("luke", "LukeForMultipleChoice"),
|
| 1283 |
+
("mega", "MegaForMultipleChoice"),
|
| 1284 |
+
("megatron-bert", "MegatronBertForMultipleChoice"),
|
| 1285 |
+
("mobilebert", "MobileBertForMultipleChoice"),
|
| 1286 |
+
("mpnet", "MPNetForMultipleChoice"),
|
| 1287 |
+
("mra", "MraForMultipleChoice"),
|
| 1288 |
+
("nezha", "NezhaForMultipleChoice"),
|
| 1289 |
+
("nystromformer", "NystromformerForMultipleChoice"),
|
| 1290 |
+
("qdqbert", "QDQBertForMultipleChoice"),
|
| 1291 |
+
("rembert", "RemBertForMultipleChoice"),
|
| 1292 |
+
("roberta", "RobertaForMultipleChoice"),
|
| 1293 |
+
("roberta-prelayernorm", "RobertaPreLayerNormForMultipleChoice"),
|
| 1294 |
+
("roc_bert", "RoCBertForMultipleChoice"),
|
| 1295 |
+
("roformer", "RoFormerForMultipleChoice"),
|
| 1296 |
+
("squeezebert", "SqueezeBertForMultipleChoice"),
|
| 1297 |
+
("xlm", "XLMForMultipleChoice"),
|
| 1298 |
+
("xlm-roberta", "XLMRobertaForMultipleChoice"),
|
| 1299 |
+
("xlm-roberta-xl", "XLMRobertaXLForMultipleChoice"),
|
| 1300 |
+
("xlnet", "XLNetForMultipleChoice"),
|
| 1301 |
+
("xmod", "XmodForMultipleChoice"),
|
| 1302 |
+
("yoso", "YosoForMultipleChoice"),
|
| 1303 |
+
]
|
| 1304 |
+
)
|
| 1305 |
+
|
| 1306 |
+
MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES = OrderedDict(
|
| 1307 |
+
[
|
| 1308 |
+
("bert", "BertForNextSentencePrediction"),
|
| 1309 |
+
("ernie", "ErnieForNextSentencePrediction"),
|
| 1310 |
+
("fnet", "FNetForNextSentencePrediction"),
|
| 1311 |
+
("megatron-bert", "MegatronBertForNextSentencePrediction"),
|
| 1312 |
+
("mobilebert", "MobileBertForNextSentencePrediction"),
|
| 1313 |
+
("nezha", "NezhaForNextSentencePrediction"),
|
| 1314 |
+
("qdqbert", "QDQBertForNextSentencePrediction"),
|
| 1315 |
+
]
|
| 1316 |
+
)
|
| 1317 |
+
|
| 1318 |
+
MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 1319 |
+
[
|
| 1320 |
+
# Model for Audio Classification mapping
|
| 1321 |
+
("audio-spectrogram-transformer", "ASTForAudioClassification"),
|
| 1322 |
+
("data2vec-audio", "Data2VecAudioForSequenceClassification"),
|
| 1323 |
+
("hubert", "HubertForSequenceClassification"),
|
| 1324 |
+
("sew", "SEWForSequenceClassification"),
|
| 1325 |
+
("sew-d", "SEWDForSequenceClassification"),
|
| 1326 |
+
("unispeech", "UniSpeechForSequenceClassification"),
|
| 1327 |
+
("unispeech-sat", "UniSpeechSatForSequenceClassification"),
|
| 1328 |
+
("wav2vec2", "Wav2Vec2ForSequenceClassification"),
|
| 1329 |
+
("wav2vec2-bert", "Wav2Vec2BertForSequenceClassification"),
|
| 1330 |
+
("wav2vec2-conformer", "Wav2Vec2ConformerForSequenceClassification"),
|
| 1331 |
+
("wavlm", "WavLMForSequenceClassification"),
|
| 1332 |
+
("whisper", "WhisperForAudioClassification"),
|
| 1333 |
+
]
|
| 1334 |
+
)
|
| 1335 |
+
|
| 1336 |
+
MODEL_FOR_CTC_MAPPING_NAMES = OrderedDict(
|
| 1337 |
+
[
|
| 1338 |
+
# Model for Connectionist temporal classification (CTC) mapping
|
| 1339 |
+
("data2vec-audio", "Data2VecAudioForCTC"),
|
| 1340 |
+
("hubert", "HubertForCTC"),
|
| 1341 |
+
("mctct", "MCTCTForCTC"),
|
| 1342 |
+
("sew", "SEWForCTC"),
|
| 1343 |
+
("sew-d", "SEWDForCTC"),
|
| 1344 |
+
("unispeech", "UniSpeechForCTC"),
|
| 1345 |
+
("unispeech-sat", "UniSpeechSatForCTC"),
|
| 1346 |
+
("wav2vec2", "Wav2Vec2ForCTC"),
|
| 1347 |
+
("wav2vec2-bert", "Wav2Vec2BertForCTC"),
|
| 1348 |
+
("wav2vec2-conformer", "Wav2Vec2ConformerForCTC"),
|
| 1349 |
+
("wavlm", "WavLMForCTC"),
|
| 1350 |
+
]
|
| 1351 |
+
)
|
| 1352 |
+
|
| 1353 |
+
MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 1354 |
+
[
|
| 1355 |
+
# Model for Audio Classification mapping
|
| 1356 |
+
("data2vec-audio", "Data2VecAudioForAudioFrameClassification"),
|
| 1357 |
+
("unispeech-sat", "UniSpeechSatForAudioFrameClassification"),
|
| 1358 |
+
("wav2vec2", "Wav2Vec2ForAudioFrameClassification"),
|
| 1359 |
+
("wav2vec2-bert", "Wav2Vec2BertForAudioFrameClassification"),
|
| 1360 |
+
("wav2vec2-conformer", "Wav2Vec2ConformerForAudioFrameClassification"),
|
| 1361 |
+
("wavlm", "WavLMForAudioFrameClassification"),
|
| 1362 |
+
]
|
| 1363 |
+
)
|
| 1364 |
+
|
| 1365 |
+
MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES = OrderedDict(
|
| 1366 |
+
[
|
| 1367 |
+
# Model for Audio Classification mapping
|
| 1368 |
+
("data2vec-audio", "Data2VecAudioForXVector"),
|
| 1369 |
+
("unispeech-sat", "UniSpeechSatForXVector"),
|
| 1370 |
+
("wav2vec2", "Wav2Vec2ForXVector"),
|
| 1371 |
+
("wav2vec2-bert", "Wav2Vec2BertForXVector"),
|
| 1372 |
+
("wav2vec2-conformer", "Wav2Vec2ConformerForXVector"),
|
| 1373 |
+
("wavlm", "WavLMForXVector"),
|
| 1374 |
+
]
|
| 1375 |
+
)
|
| 1376 |
+
|
| 1377 |
+
MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES = OrderedDict(
|
| 1378 |
+
[
|
| 1379 |
+
# Model for Text-To-Spectrogram mapping
|
| 1380 |
+
("fastspeech2_conformer", "FastSpeech2ConformerModel"),
|
| 1381 |
+
("speecht5", "SpeechT5ForTextToSpeech"),
|
| 1382 |
+
]
|
| 1383 |
+
)
|
| 1384 |
+
|
| 1385 |
+
MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES = OrderedDict(
|
| 1386 |
+
[
|
| 1387 |
+
# Model for Text-To-Waveform mapping
|
| 1388 |
+
("bark", "BarkModel"),
|
| 1389 |
+
("fastspeech2_conformer", "FastSpeech2ConformerWithHifiGan"),
|
| 1390 |
+
("musicgen", "MusicgenForConditionalGeneration"),
|
| 1391 |
+
("musicgen_melody", "MusicgenMelodyForConditionalGeneration"),
|
| 1392 |
+
("seamless_m4t", "SeamlessM4TForTextToSpeech"),
|
| 1393 |
+
("seamless_m4t_v2", "SeamlessM4Tv2ForTextToSpeech"),
|
| 1394 |
+
("vits", "VitsModel"),
|
| 1395 |
+
]
|
| 1396 |
+
)
|
| 1397 |
+
|
| 1398 |
+
MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 1399 |
+
[
|
| 1400 |
+
# Model for Zero Shot Image Classification mapping
|
| 1401 |
+
("align", "AlignModel"),
|
| 1402 |
+
("altclip", "AltCLIPModel"),
|
| 1403 |
+
("blip", "BlipModel"),
|
| 1404 |
+
("blip-2", "Blip2ForImageTextRetrieval"),
|
| 1405 |
+
("chinese_clip", "ChineseCLIPModel"),
|
| 1406 |
+
("clip", "CLIPModel"),
|
| 1407 |
+
("clipseg", "CLIPSegModel"),
|
| 1408 |
+
("siglip", "SiglipModel"),
|
| 1409 |
+
("siglip2", "Siglip2Model"),
|
| 1410 |
+
]
|
| 1411 |
+
)
|
| 1412 |
+
|
| 1413 |
+
MODEL_FOR_BACKBONE_MAPPING_NAMES = OrderedDict(
|
| 1414 |
+
[
|
| 1415 |
+
# Backbone mapping
|
| 1416 |
+
("beit", "BeitBackbone"),
|
| 1417 |
+
("bit", "BitBackbone"),
|
| 1418 |
+
("convnext", "ConvNextBackbone"),
|
| 1419 |
+
("convnextv2", "ConvNextV2Backbone"),
|
| 1420 |
+
("dinat", "DinatBackbone"),
|
| 1421 |
+
("dinov2", "Dinov2Backbone"),
|
| 1422 |
+
("dinov2_with_registers", "Dinov2WithRegistersBackbone"),
|
| 1423 |
+
("focalnet", "FocalNetBackbone"),
|
| 1424 |
+
("hiera", "HieraBackbone"),
|
| 1425 |
+
("maskformer-swin", "MaskFormerSwinBackbone"),
|
| 1426 |
+
("nat", "NatBackbone"),
|
| 1427 |
+
("pvt_v2", "PvtV2Backbone"),
|
| 1428 |
+
("resnet", "ResNetBackbone"),
|
| 1429 |
+
("rt_detr_resnet", "RTDetrResNetBackbone"),
|
| 1430 |
+
("swin", "SwinBackbone"),
|
| 1431 |
+
("swinv2", "Swinv2Backbone"),
|
| 1432 |
+
("textnet", "TextNetBackbone"),
|
| 1433 |
+
("timm_backbone", "TimmBackbone"),
|
| 1434 |
+
("vitdet", "VitDetBackbone"),
|
| 1435 |
+
("vitpose_backbone", "VitPoseBackbone"),
|
| 1436 |
+
]
|
| 1437 |
+
)
|
| 1438 |
+
|
| 1439 |
+
MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = OrderedDict(
|
| 1440 |
+
[
|
| 1441 |
+
("sam", "SamModel"),
|
| 1442 |
+
]
|
| 1443 |
+
)
|
| 1444 |
+
|
| 1445 |
+
|
| 1446 |
+
MODEL_FOR_KEYPOINT_DETECTION_MAPPING_NAMES = OrderedDict(
|
| 1447 |
+
[
|
| 1448 |
+
("superpoint", "SuperPointForKeypointDetection"),
|
| 1449 |
+
]
|
| 1450 |
+
)
|
| 1451 |
+
|
| 1452 |
+
|
| 1453 |
+
MODEL_FOR_TEXT_ENCODING_MAPPING_NAMES = OrderedDict(
|
| 1454 |
+
[
|
| 1455 |
+
("albert", "AlbertModel"),
|
| 1456 |
+
("bert", "BertModel"),
|
| 1457 |
+
("big_bird", "BigBirdModel"),
|
| 1458 |
+
("clip_text_model", "CLIPTextModel"),
|
| 1459 |
+
("data2vec-text", "Data2VecTextModel"),
|
| 1460 |
+
("deberta", "DebertaModel"),
|
| 1461 |
+
("deberta-v2", "DebertaV2Model"),
|
| 1462 |
+
("distilbert", "DistilBertModel"),
|
| 1463 |
+
("electra", "ElectraModel"),
|
| 1464 |
+
("emu3", "Emu3TextModel"),
|
| 1465 |
+
("flaubert", "FlaubertModel"),
|
| 1466 |
+
("ibert", "IBertModel"),
|
| 1467 |
+
("longformer", "LongformerModel"),
|
| 1468 |
+
("mllama", "MllamaTextModel"),
|
| 1469 |
+
("mobilebert", "MobileBertModel"),
|
| 1470 |
+
("mt5", "MT5EncoderModel"),
|
| 1471 |
+
("nystromformer", "NystromformerModel"),
|
| 1472 |
+
("reformer", "ReformerModel"),
|
| 1473 |
+
("rembert", "RemBertModel"),
|
| 1474 |
+
("roberta", "RobertaModel"),
|
| 1475 |
+
("roberta-prelayernorm", "RobertaPreLayerNormModel"),
|
| 1476 |
+
("roc_bert", "RoCBertModel"),
|
| 1477 |
+
("roformer", "RoFormerModel"),
|
| 1478 |
+
("squeezebert", "SqueezeBertModel"),
|
| 1479 |
+
("t5", "T5EncoderModel"),
|
| 1480 |
+
("umt5", "UMT5EncoderModel"),
|
| 1481 |
+
("xlm", "XLMModel"),
|
| 1482 |
+
("xlm-roberta", "XLMRobertaModel"),
|
| 1483 |
+
("xlm-roberta-xl", "XLMRobertaXLModel"),
|
| 1484 |
+
]
|
| 1485 |
+
)
|
| 1486 |
+
|
| 1487 |
+
MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 1488 |
+
[
|
| 1489 |
+
("patchtsmixer", "PatchTSMixerForTimeSeriesClassification"),
|
| 1490 |
+
("patchtst", "PatchTSTForClassification"),
|
| 1491 |
+
]
|
| 1492 |
+
)
|
| 1493 |
+
|
| 1494 |
+
MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING_NAMES = OrderedDict(
|
| 1495 |
+
[
|
| 1496 |
+
("patchtsmixer", "PatchTSMixerForRegression"),
|
| 1497 |
+
("patchtst", "PatchTSTForRegression"),
|
| 1498 |
+
]
|
| 1499 |
+
)
|
| 1500 |
+
|
| 1501 |
+
MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES = OrderedDict(
|
| 1502 |
+
[
|
| 1503 |
+
("swin2sr", "Swin2SRForImageSuperResolution"),
|
| 1504 |
+
]
|
| 1505 |
+
)
|
| 1506 |
+
|
| 1507 |
+
MODEL_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_MAPPING_NAMES)
|
| 1508 |
+
MODEL_FOR_PRETRAINING_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_PRETRAINING_MAPPING_NAMES)
|
| 1509 |
+
MODEL_WITH_LM_HEAD_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_WITH_LM_HEAD_MAPPING_NAMES)
|
| 1510 |
+
MODEL_FOR_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_CAUSAL_LM_MAPPING_NAMES)
|
| 1511 |
+
MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING = _LazyAutoMapping(
|
| 1512 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING_NAMES
|
| 1513 |
+
)
|
| 1514 |
+
MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 1515 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES
|
| 1516 |
+
)
|
| 1517 |
+
MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 1518 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES
|
| 1519 |
+
)
|
| 1520 |
+
MODEL_FOR_IMAGE_SEGMENTATION_MAPPING = _LazyAutoMapping(
|
| 1521 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES
|
| 1522 |
+
)
|
| 1523 |
+
MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING = _LazyAutoMapping(
|
| 1524 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES
|
| 1525 |
+
)
|
| 1526 |
+
MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING = _LazyAutoMapping(
|
| 1527 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING_NAMES
|
| 1528 |
+
)
|
| 1529 |
+
MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING = _LazyAutoMapping(
|
| 1530 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES
|
| 1531 |
+
)
|
| 1532 |
+
MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 1533 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES
|
| 1534 |
+
)
|
| 1535 |
+
MODEL_FOR_VISION_2_SEQ_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES)
|
| 1536 |
+
MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING = _LazyAutoMapping(
|
| 1537 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES
|
| 1538 |
+
)
|
| 1539 |
+
MODEL_FOR_RETRIEVAL_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_RETRIEVAL_MAPPING_NAMES)
|
| 1540 |
+
MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
|
| 1541 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES
|
| 1542 |
+
)
|
| 1543 |
+
MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
|
| 1544 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES
|
| 1545 |
+
)
|
| 1546 |
+
MODEL_FOR_MASKED_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_MASKED_LM_MAPPING_NAMES)
|
| 1547 |
+
MODEL_FOR_IMAGE_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_IMAGE_MAPPING_NAMES)
|
| 1548 |
+
MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING = _LazyAutoMapping(
|
| 1549 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING_NAMES
|
| 1550 |
+
)
|
| 1551 |
+
MODEL_FOR_OBJECT_DETECTION_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES)
|
| 1552 |
+
MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING = _LazyAutoMapping(
|
| 1553 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES
|
| 1554 |
+
)
|
| 1555 |
+
MODEL_FOR_DEPTH_ESTIMATION_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES)
|
| 1556 |
+
MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING = _LazyAutoMapping(
|
| 1557 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
|
| 1558 |
+
)
|
| 1559 |
+
MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 1560 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
|
| 1561 |
+
)
|
| 1562 |
+
MODEL_FOR_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
|
| 1563 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
|
| 1564 |
+
)
|
| 1565 |
+
MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
|
| 1566 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES
|
| 1567 |
+
)
|
| 1568 |
+
MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 1569 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES
|
| 1570 |
+
)
|
| 1571 |
+
MODEL_FOR_MULTIPLE_CHOICE_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES)
|
| 1572 |
+
MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING = _LazyAutoMapping(
|
| 1573 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES
|
| 1574 |
+
)
|
| 1575 |
+
MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 1576 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES
|
| 1577 |
+
)
|
| 1578 |
+
MODEL_FOR_CTC_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_CTC_MAPPING_NAMES)
|
| 1579 |
+
MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES)
|
| 1580 |
+
MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 1581 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES
|
| 1582 |
+
)
|
| 1583 |
+
MODEL_FOR_AUDIO_XVECTOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES)
|
| 1584 |
+
|
| 1585 |
+
MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING = _LazyAutoMapping(
|
| 1586 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES
|
| 1587 |
+
)
|
| 1588 |
+
|
| 1589 |
+
MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES)
|
| 1590 |
+
|
| 1591 |
+
MODEL_FOR_BACKBONE_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_BACKBONE_MAPPING_NAMES)
|
| 1592 |
+
|
| 1593 |
+
MODEL_FOR_MASK_GENERATION_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_MASK_GENERATION_MAPPING_NAMES)
|
| 1594 |
+
|
| 1595 |
+
MODEL_FOR_KEYPOINT_DETECTION_MAPPING = _LazyAutoMapping(
|
| 1596 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_KEYPOINT_DETECTION_MAPPING_NAMES
|
| 1597 |
+
)
|
| 1598 |
+
|
| 1599 |
+
MODEL_FOR_TEXT_ENCODING_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_TEXT_ENCODING_MAPPING_NAMES)
|
| 1600 |
+
|
| 1601 |
+
MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 1602 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING_NAMES
|
| 1603 |
+
)
|
| 1604 |
+
|
| 1605 |
+
MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING = _LazyAutoMapping(
|
| 1606 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING_NAMES
|
| 1607 |
+
)
|
| 1608 |
+
|
| 1609 |
+
MODEL_FOR_IMAGE_TO_IMAGE_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES)
|
| 1610 |
+
|
| 1611 |
+
|
| 1612 |
+
class AutoModelForMaskGeneration(_BaseAutoModelClass):
|
| 1613 |
+
_model_mapping = MODEL_FOR_MASK_GENERATION_MAPPING
|
| 1614 |
+
|
| 1615 |
+
|
| 1616 |
+
class AutoModelForKeypointDetection(_BaseAutoModelClass):
|
| 1617 |
+
_model_mapping = MODEL_FOR_KEYPOINT_DETECTION_MAPPING
|
| 1618 |
+
|
| 1619 |
+
|
| 1620 |
+
class AutoModelForTextEncoding(_BaseAutoModelClass):
|
| 1621 |
+
_model_mapping = MODEL_FOR_TEXT_ENCODING_MAPPING
|
| 1622 |
+
|
| 1623 |
+
|
| 1624 |
+
class AutoModelForImageToImage(_BaseAutoModelClass):
|
| 1625 |
+
_model_mapping = MODEL_FOR_IMAGE_TO_IMAGE_MAPPING
|
| 1626 |
+
|
| 1627 |
+
|
| 1628 |
+
class AutoModel(_BaseAutoModelClass):
|
| 1629 |
+
_model_mapping = MODEL_MAPPING
|
| 1630 |
+
|
| 1631 |
+
|
| 1632 |
+
AutoModel = auto_class_update(AutoModel)
|
| 1633 |
+
|
| 1634 |
+
|
| 1635 |
+
class AutoModelForPreTraining(_BaseAutoModelClass):
|
| 1636 |
+
_model_mapping = MODEL_FOR_PRETRAINING_MAPPING
|
| 1637 |
+
|
| 1638 |
+
|
| 1639 |
+
AutoModelForPreTraining = auto_class_update(AutoModelForPreTraining, head_doc="pretraining")
|
| 1640 |
+
|
| 1641 |
+
|
| 1642 |
+
# Private on purpose, the public class will add the deprecation warnings.
|
| 1643 |
+
class _AutoModelWithLMHead(_BaseAutoModelClass):
|
| 1644 |
+
_model_mapping = MODEL_WITH_LM_HEAD_MAPPING
|
| 1645 |
+
|
| 1646 |
+
|
| 1647 |
+
_AutoModelWithLMHead = auto_class_update(_AutoModelWithLMHead, head_doc="language modeling")
|
| 1648 |
+
|
| 1649 |
+
|
| 1650 |
+
class AutoModelForCausalLM(_BaseAutoModelClass):
|
| 1651 |
+
_model_mapping = MODEL_FOR_CAUSAL_LM_MAPPING
|
| 1652 |
+
|
| 1653 |
+
|
| 1654 |
+
AutoModelForCausalLM = auto_class_update(AutoModelForCausalLM, head_doc="causal language modeling")
|
| 1655 |
+
|
| 1656 |
+
|
| 1657 |
+
class AutoModelForMaskedLM(_BaseAutoModelClass):
|
| 1658 |
+
_model_mapping = MODEL_FOR_MASKED_LM_MAPPING
|
| 1659 |
+
|
| 1660 |
+
|
| 1661 |
+
AutoModelForMaskedLM = auto_class_update(AutoModelForMaskedLM, head_doc="masked language modeling")
|
| 1662 |
+
|
| 1663 |
+
|
| 1664 |
+
class AutoModelForSeq2SeqLM(_BaseAutoModelClass):
|
| 1665 |
+
_model_mapping = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
|
| 1666 |
+
|
| 1667 |
+
|
| 1668 |
+
AutoModelForSeq2SeqLM = auto_class_update(
|
| 1669 |
+
AutoModelForSeq2SeqLM,
|
| 1670 |
+
head_doc="sequence-to-sequence language modeling",
|
| 1671 |
+
checkpoint_for_example="google-t5/t5-base",
|
| 1672 |
+
)
|
| 1673 |
+
|
| 1674 |
+
|
| 1675 |
+
class AutoModelForSequenceClassification(_BaseAutoModelClass):
|
| 1676 |
+
_model_mapping = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
|
| 1677 |
+
|
| 1678 |
+
|
| 1679 |
+
AutoModelForSequenceClassification = auto_class_update(
|
| 1680 |
+
AutoModelForSequenceClassification, head_doc="sequence classification"
|
| 1681 |
+
)
|
| 1682 |
+
|
| 1683 |
+
|
| 1684 |
+
class AutoModelForQuestionAnswering(_BaseAutoModelClass):
|
| 1685 |
+
_model_mapping = MODEL_FOR_QUESTION_ANSWERING_MAPPING
|
| 1686 |
+
|
| 1687 |
+
|
| 1688 |
+
AutoModelForQuestionAnswering = auto_class_update(AutoModelForQuestionAnswering, head_doc="question answering")
|
| 1689 |
+
|
| 1690 |
+
|
| 1691 |
+
class AutoModelForTableQuestionAnswering(_BaseAutoModelClass):
|
| 1692 |
+
_model_mapping = MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING
|
| 1693 |
+
|
| 1694 |
+
|
| 1695 |
+
AutoModelForTableQuestionAnswering = auto_class_update(
|
| 1696 |
+
AutoModelForTableQuestionAnswering,
|
| 1697 |
+
head_doc="table question answering",
|
| 1698 |
+
checkpoint_for_example="google/tapas-base-finetuned-wtq",
|
| 1699 |
+
)
|
| 1700 |
+
|
| 1701 |
+
|
| 1702 |
+
class AutoModelForVisualQuestionAnswering(_BaseAutoModelClass):
|
| 1703 |
+
_model_mapping = MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING
|
| 1704 |
+
|
| 1705 |
+
|
| 1706 |
+
AutoModelForVisualQuestionAnswering = auto_class_update(
|
| 1707 |
+
AutoModelForVisualQuestionAnswering,
|
| 1708 |
+
head_doc="visual question answering",
|
| 1709 |
+
checkpoint_for_example="dandelin/vilt-b32-finetuned-vqa",
|
| 1710 |
+
)
|
| 1711 |
+
|
| 1712 |
+
|
| 1713 |
+
class AutoModelForDocumentQuestionAnswering(_BaseAutoModelClass):
|
| 1714 |
+
_model_mapping = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING
|
| 1715 |
+
|
| 1716 |
+
|
| 1717 |
+
AutoModelForDocumentQuestionAnswering = auto_class_update(
|
| 1718 |
+
AutoModelForDocumentQuestionAnswering,
|
| 1719 |
+
head_doc="document question answering",
|
| 1720 |
+
checkpoint_for_example='impira/layoutlm-document-qa", revision="52e01b3',
|
| 1721 |
+
)
|
| 1722 |
+
|
| 1723 |
+
|
| 1724 |
+
class AutoModelForTokenClassification(_BaseAutoModelClass):
|
| 1725 |
+
_model_mapping = MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING
|
| 1726 |
+
|
| 1727 |
+
|
| 1728 |
+
AutoModelForTokenClassification = auto_class_update(AutoModelForTokenClassification, head_doc="token classification")
|
| 1729 |
+
|
| 1730 |
+
|
| 1731 |
+
class AutoModelForMultipleChoice(_BaseAutoModelClass):
|
| 1732 |
+
_model_mapping = MODEL_FOR_MULTIPLE_CHOICE_MAPPING
|
| 1733 |
+
|
| 1734 |
+
|
| 1735 |
+
AutoModelForMultipleChoice = auto_class_update(AutoModelForMultipleChoice, head_doc="multiple choice")
|
| 1736 |
+
|
| 1737 |
+
|
| 1738 |
+
class AutoModelForNextSentencePrediction(_BaseAutoModelClass):
|
| 1739 |
+
_model_mapping = MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING
|
| 1740 |
+
|
| 1741 |
+
|
| 1742 |
+
AutoModelForNextSentencePrediction = auto_class_update(
|
| 1743 |
+
AutoModelForNextSentencePrediction, head_doc="next sentence prediction"
|
| 1744 |
+
)
|
| 1745 |
+
|
| 1746 |
+
|
| 1747 |
+
class AutoModelForImageClassification(_BaseAutoModelClass):
|
| 1748 |
+
_model_mapping = MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
|
| 1749 |
+
|
| 1750 |
+
|
| 1751 |
+
AutoModelForImageClassification = auto_class_update(AutoModelForImageClassification, head_doc="image classification")
|
| 1752 |
+
|
| 1753 |
+
|
| 1754 |
+
class AutoModelForZeroShotImageClassification(_BaseAutoModelClass):
|
| 1755 |
+
_model_mapping = MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
|
| 1756 |
+
|
| 1757 |
+
|
| 1758 |
+
AutoModelForZeroShotImageClassification = auto_class_update(
|
| 1759 |
+
AutoModelForZeroShotImageClassification, head_doc="zero-shot image classification"
|
| 1760 |
+
)
|
| 1761 |
+
|
| 1762 |
+
|
| 1763 |
+
class AutoModelForImageSegmentation(_BaseAutoModelClass):
|
| 1764 |
+
_model_mapping = MODEL_FOR_IMAGE_SEGMENTATION_MAPPING
|
| 1765 |
+
|
| 1766 |
+
|
| 1767 |
+
AutoModelForImageSegmentation = auto_class_update(AutoModelForImageSegmentation, head_doc="image segmentation")
|
| 1768 |
+
|
| 1769 |
+
|
| 1770 |
+
class AutoModelForSemanticSegmentation(_BaseAutoModelClass):
|
| 1771 |
+
_model_mapping = MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING
|
| 1772 |
+
|
| 1773 |
+
|
| 1774 |
+
AutoModelForSemanticSegmentation = auto_class_update(
|
| 1775 |
+
AutoModelForSemanticSegmentation, head_doc="semantic segmentation"
|
| 1776 |
+
)
|
| 1777 |
+
|
| 1778 |
+
|
| 1779 |
+
class AutoModelForUniversalSegmentation(_BaseAutoModelClass):
|
| 1780 |
+
_model_mapping = MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING
|
| 1781 |
+
|
| 1782 |
+
|
| 1783 |
+
AutoModelForUniversalSegmentation = auto_class_update(
|
| 1784 |
+
AutoModelForUniversalSegmentation, head_doc="universal image segmentation"
|
| 1785 |
+
)
|
| 1786 |
+
|
| 1787 |
+
|
| 1788 |
+
class AutoModelForInstanceSegmentation(_BaseAutoModelClass):
|
| 1789 |
+
_model_mapping = MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING
|
| 1790 |
+
|
| 1791 |
+
|
| 1792 |
+
AutoModelForInstanceSegmentation = auto_class_update(
|
| 1793 |
+
AutoModelForInstanceSegmentation, head_doc="instance segmentation"
|
| 1794 |
+
)
|
| 1795 |
+
|
| 1796 |
+
|
| 1797 |
+
class AutoModelForObjectDetection(_BaseAutoModelClass):
|
| 1798 |
+
_model_mapping = MODEL_FOR_OBJECT_DETECTION_MAPPING
|
| 1799 |
+
|
| 1800 |
+
|
| 1801 |
+
AutoModelForObjectDetection = auto_class_update(AutoModelForObjectDetection, head_doc="object detection")
|
| 1802 |
+
|
| 1803 |
+
|
| 1804 |
+
class AutoModelForZeroShotObjectDetection(_BaseAutoModelClass):
|
| 1805 |
+
_model_mapping = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING
|
| 1806 |
+
|
| 1807 |
+
|
| 1808 |
+
AutoModelForZeroShotObjectDetection = auto_class_update(
|
| 1809 |
+
AutoModelForZeroShotObjectDetection, head_doc="zero-shot object detection"
|
| 1810 |
+
)
|
| 1811 |
+
|
| 1812 |
+
|
| 1813 |
+
class AutoModelForDepthEstimation(_BaseAutoModelClass):
|
| 1814 |
+
_model_mapping = MODEL_FOR_DEPTH_ESTIMATION_MAPPING
|
| 1815 |
+
|
| 1816 |
+
|
| 1817 |
+
AutoModelForDepthEstimation = auto_class_update(AutoModelForDepthEstimation, head_doc="depth estimation")
|
| 1818 |
+
|
| 1819 |
+
|
| 1820 |
+
class AutoModelForVideoClassification(_BaseAutoModelClass):
|
| 1821 |
+
_model_mapping = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING
|
| 1822 |
+
|
| 1823 |
+
|
| 1824 |
+
AutoModelForVideoClassification = auto_class_update(AutoModelForVideoClassification, head_doc="video classification")
|
| 1825 |
+
|
| 1826 |
+
|
| 1827 |
+
class AutoModelForVision2Seq(_BaseAutoModelClass):
|
| 1828 |
+
_model_mapping = MODEL_FOR_VISION_2_SEQ_MAPPING
|
| 1829 |
+
|
| 1830 |
+
|
| 1831 |
+
AutoModelForVision2Seq = auto_class_update(AutoModelForVision2Seq, head_doc="vision-to-text modeling")
|
| 1832 |
+
|
| 1833 |
+
|
| 1834 |
+
class AutoModelForImageTextToText(_BaseAutoModelClass):
|
| 1835 |
+
_model_mapping = MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING
|
| 1836 |
+
|
| 1837 |
+
|
| 1838 |
+
AutoModelForImageTextToText = auto_class_update(AutoModelForImageTextToText, head_doc="image-text-to-text modeling")
|
| 1839 |
+
|
| 1840 |
+
|
| 1841 |
+
class AutoModelForAudioClassification(_BaseAutoModelClass):
|
| 1842 |
+
_model_mapping = MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
|
| 1843 |
+
|
| 1844 |
+
|
| 1845 |
+
AutoModelForAudioClassification = auto_class_update(AutoModelForAudioClassification, head_doc="audio classification")
|
| 1846 |
+
|
| 1847 |
+
|
| 1848 |
+
class AutoModelForCTC(_BaseAutoModelClass):
|
| 1849 |
+
_model_mapping = MODEL_FOR_CTC_MAPPING
|
| 1850 |
+
|
| 1851 |
+
|
| 1852 |
+
AutoModelForCTC = auto_class_update(AutoModelForCTC, head_doc="connectionist temporal classification")
|
| 1853 |
+
|
| 1854 |
+
|
| 1855 |
+
class AutoModelForSpeechSeq2Seq(_BaseAutoModelClass):
|
| 1856 |
+
_model_mapping = MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING
|
| 1857 |
+
|
| 1858 |
+
|
| 1859 |
+
AutoModelForSpeechSeq2Seq = auto_class_update(
|
| 1860 |
+
AutoModelForSpeechSeq2Seq, head_doc="sequence-to-sequence speech-to-text modeling"
|
| 1861 |
+
)
|
| 1862 |
+
|
| 1863 |
+
|
| 1864 |
+
class AutoModelForAudioFrameClassification(_BaseAutoModelClass):
|
| 1865 |
+
_model_mapping = MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING
|
| 1866 |
+
|
| 1867 |
+
|
| 1868 |
+
AutoModelForAudioFrameClassification = auto_class_update(
|
| 1869 |
+
AutoModelForAudioFrameClassification, head_doc="audio frame (token) classification"
|
| 1870 |
+
)
|
| 1871 |
+
|
| 1872 |
+
|
| 1873 |
+
class AutoModelForAudioXVector(_BaseAutoModelClass):
|
| 1874 |
+
_model_mapping = MODEL_FOR_AUDIO_XVECTOR_MAPPING
|
| 1875 |
+
|
| 1876 |
+
|
| 1877 |
+
class AutoModelForTextToSpectrogram(_BaseAutoModelClass):
|
| 1878 |
+
_model_mapping = MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING
|
| 1879 |
+
|
| 1880 |
+
|
| 1881 |
+
class AutoModelForTextToWaveform(_BaseAutoModelClass):
|
| 1882 |
+
_model_mapping = MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING
|
| 1883 |
+
|
| 1884 |
+
|
| 1885 |
+
class AutoBackbone(_BaseAutoBackboneClass):
|
| 1886 |
+
_model_mapping = MODEL_FOR_BACKBONE_MAPPING
|
| 1887 |
+
|
| 1888 |
+
|
| 1889 |
+
AutoModelForAudioXVector = auto_class_update(AutoModelForAudioXVector, head_doc="audio retrieval via x-vector")
|
| 1890 |
+
|
| 1891 |
+
|
| 1892 |
+
class AutoModelForMaskedImageModeling(_BaseAutoModelClass):
|
| 1893 |
+
_model_mapping = MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING
|
| 1894 |
+
|
| 1895 |
+
|
| 1896 |
+
AutoModelForMaskedImageModeling = auto_class_update(AutoModelForMaskedImageModeling, head_doc="masked image modeling")
|
| 1897 |
+
|
| 1898 |
+
|
| 1899 |
+
class AutoModelWithLMHead(_AutoModelWithLMHead):
|
| 1900 |
+
@classmethod
|
| 1901 |
+
def from_config(cls, config):
|
| 1902 |
+
warnings.warn(
|
| 1903 |
+
"The class `AutoModelWithLMHead` is deprecated and will be removed in a future version. Please use "
|
| 1904 |
+
"`AutoModelForCausalLM` for causal language models, `AutoModelForMaskedLM` for masked language models and "
|
| 1905 |
+
"`AutoModelForSeq2SeqLM` for encoder-decoder models.",
|
| 1906 |
+
FutureWarning,
|
| 1907 |
+
)
|
| 1908 |
+
return super().from_config(config)
|
| 1909 |
+
|
| 1910 |
+
@classmethod
|
| 1911 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 1912 |
+
warnings.warn(
|
| 1913 |
+
"The class `AutoModelWithLMHead` is deprecated and will be removed in a future version. Please use "
|
| 1914 |
+
"`AutoModelForCausalLM` for causal language models, `AutoModelForMaskedLM` for masked language models and "
|
| 1915 |
+
"`AutoModelForSeq2SeqLM` for encoder-decoder models.",
|
| 1916 |
+
FutureWarning,
|
| 1917 |
+
)
|
| 1918 |
+
return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
|
tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/models/auto/processing_auto.py
ADDED
|
@@ -0,0 +1,380 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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2 |
+
# Copyright 2021 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""AutoProcessor class."""
|
| 16 |
+
|
| 17 |
+
import importlib
|
| 18 |
+
import inspect
|
| 19 |
+
import json
|
| 20 |
+
import os
|
| 21 |
+
import warnings
|
| 22 |
+
from collections import OrderedDict
|
| 23 |
+
|
| 24 |
+
# Build the list of all feature extractors
|
| 25 |
+
from ...configuration_utils import PretrainedConfig
|
| 26 |
+
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
|
| 27 |
+
from ...feature_extraction_utils import FeatureExtractionMixin
|
| 28 |
+
from ...image_processing_utils import ImageProcessingMixin
|
| 29 |
+
from ...processing_utils import ProcessorMixin
|
| 30 |
+
from ...tokenization_utils import TOKENIZER_CONFIG_FILE
|
| 31 |
+
from ...utils import FEATURE_EXTRACTOR_NAME, PROCESSOR_NAME, get_file_from_repo, logging
|
| 32 |
+
from .auto_factory import _LazyAutoMapping
|
| 33 |
+
from .configuration_auto import (
|
| 34 |
+
CONFIG_MAPPING_NAMES,
|
| 35 |
+
AutoConfig,
|
| 36 |
+
model_type_to_module_name,
|
| 37 |
+
replace_list_option_in_docstrings,
|
| 38 |
+
)
|
| 39 |
+
from .feature_extraction_auto import AutoFeatureExtractor
|
| 40 |
+
from .image_processing_auto import AutoImageProcessor
|
| 41 |
+
from .tokenization_auto import AutoTokenizer
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
logger = logging.get_logger(__name__)
|
| 45 |
+
|
| 46 |
+
PROCESSOR_MAPPING_NAMES = OrderedDict(
|
| 47 |
+
[
|
| 48 |
+
("align", "AlignProcessor"),
|
| 49 |
+
("altclip", "AltCLIPProcessor"),
|
| 50 |
+
("aria", "AriaProcessor"),
|
| 51 |
+
("aya_vision", "AyaVisionProcessor"),
|
| 52 |
+
("bark", "BarkProcessor"),
|
| 53 |
+
("blip", "BlipProcessor"),
|
| 54 |
+
("blip-2", "Blip2Processor"),
|
| 55 |
+
("bridgetower", "BridgeTowerProcessor"),
|
| 56 |
+
("chameleon", "ChameleonProcessor"),
|
| 57 |
+
("chinese_clip", "ChineseCLIPProcessor"),
|
| 58 |
+
("clap", "ClapProcessor"),
|
| 59 |
+
("clip", "CLIPProcessor"),
|
| 60 |
+
("clipseg", "CLIPSegProcessor"),
|
| 61 |
+
("clvp", "ClvpProcessor"),
|
| 62 |
+
("colpali", "ColPaliProcessor"),
|
| 63 |
+
("emu3", "Emu3Processor"),
|
| 64 |
+
("flava", "FlavaProcessor"),
|
| 65 |
+
("fuyu", "FuyuProcessor"),
|
| 66 |
+
("git", "GitProcessor"),
|
| 67 |
+
("got_ocr2", "GotOcr2Processor"),
|
| 68 |
+
("grounding-dino", "GroundingDinoProcessor"),
|
| 69 |
+
("groupvit", "CLIPProcessor"),
|
| 70 |
+
("hubert", "Wav2Vec2Processor"),
|
| 71 |
+
("idefics", "IdeficsProcessor"),
|
| 72 |
+
("idefics2", "Idefics2Processor"),
|
| 73 |
+
("idefics3", "Idefics3Processor"),
|
| 74 |
+
("instructblip", "InstructBlipProcessor"),
|
| 75 |
+
("instructblipvideo", "InstructBlipVideoProcessor"),
|
| 76 |
+
("kosmos-2", "Kosmos2Processor"),
|
| 77 |
+
("layoutlmv2", "LayoutLMv2Processor"),
|
| 78 |
+
("layoutlmv3", "LayoutLMv3Processor"),
|
| 79 |
+
("llava", "LlavaProcessor"),
|
| 80 |
+
("llava_next", "LlavaNextProcessor"),
|
| 81 |
+
("llava_next_video", "LlavaNextVideoProcessor"),
|
| 82 |
+
("llava_onevision", "LlavaOnevisionProcessor"),
|
| 83 |
+
("markuplm", "MarkupLMProcessor"),
|
| 84 |
+
("mctct", "MCTCTProcessor"),
|
| 85 |
+
("mgp-str", "MgpstrProcessor"),
|
| 86 |
+
("mllama", "MllamaProcessor"),
|
| 87 |
+
("moonshine", "Wav2Vec2Processor"),
|
| 88 |
+
("oneformer", "OneFormerProcessor"),
|
| 89 |
+
("owlv2", "Owlv2Processor"),
|
| 90 |
+
("owlvit", "OwlViTProcessor"),
|
| 91 |
+
("paligemma", "PaliGemmaProcessor"),
|
| 92 |
+
("pix2struct", "Pix2StructProcessor"),
|
| 93 |
+
("pixtral", "PixtralProcessor"),
|
| 94 |
+
("pop2piano", "Pop2PianoProcessor"),
|
| 95 |
+
("qwen2_5_vl", "Qwen2_5_VLProcessor"),
|
| 96 |
+
("qwen2_audio", "Qwen2AudioProcessor"),
|
| 97 |
+
("qwen2_vl", "Qwen2VLProcessor"),
|
| 98 |
+
("sam", "SamProcessor"),
|
| 99 |
+
("seamless_m4t", "SeamlessM4TProcessor"),
|
| 100 |
+
("sew", "Wav2Vec2Processor"),
|
| 101 |
+
("sew-d", "Wav2Vec2Processor"),
|
| 102 |
+
("siglip", "SiglipProcessor"),
|
| 103 |
+
("siglip2", "Siglip2Processor"),
|
| 104 |
+
("speech_to_text", "Speech2TextProcessor"),
|
| 105 |
+
("speech_to_text_2", "Speech2Text2Processor"),
|
| 106 |
+
("speecht5", "SpeechT5Processor"),
|
| 107 |
+
("trocr", "TrOCRProcessor"),
|
| 108 |
+
("tvlt", "TvltProcessor"),
|
| 109 |
+
("tvp", "TvpProcessor"),
|
| 110 |
+
("udop", "UdopProcessor"),
|
| 111 |
+
("unispeech", "Wav2Vec2Processor"),
|
| 112 |
+
("unispeech-sat", "Wav2Vec2Processor"),
|
| 113 |
+
("video_llava", "VideoLlavaProcessor"),
|
| 114 |
+
("vilt", "ViltProcessor"),
|
| 115 |
+
("vipllava", "LlavaProcessor"),
|
| 116 |
+
("vision-text-dual-encoder", "VisionTextDualEncoderProcessor"),
|
| 117 |
+
("wav2vec2", "Wav2Vec2Processor"),
|
| 118 |
+
("wav2vec2-bert", "Wav2Vec2Processor"),
|
| 119 |
+
("wav2vec2-conformer", "Wav2Vec2Processor"),
|
| 120 |
+
("wavlm", "Wav2Vec2Processor"),
|
| 121 |
+
("whisper", "WhisperProcessor"),
|
| 122 |
+
("xclip", "XCLIPProcessor"),
|
| 123 |
+
]
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
PROCESSOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, PROCESSOR_MAPPING_NAMES)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def processor_class_from_name(class_name: str):
|
| 130 |
+
for module_name, processors in PROCESSOR_MAPPING_NAMES.items():
|
| 131 |
+
if class_name in processors:
|
| 132 |
+
module_name = model_type_to_module_name(module_name)
|
| 133 |
+
|
| 134 |
+
module = importlib.import_module(f".{module_name}", "transformers.models")
|
| 135 |
+
try:
|
| 136 |
+
return getattr(module, class_name)
|
| 137 |
+
except AttributeError:
|
| 138 |
+
continue
|
| 139 |
+
|
| 140 |
+
for processor in PROCESSOR_MAPPING._extra_content.values():
|
| 141 |
+
if getattr(processor, "__name__", None) == class_name:
|
| 142 |
+
return processor
|
| 143 |
+
|
| 144 |
+
# We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
|
| 145 |
+
# init and we return the proper dummy to get an appropriate error message.
|
| 146 |
+
main_module = importlib.import_module("transformers")
|
| 147 |
+
if hasattr(main_module, class_name):
|
| 148 |
+
return getattr(main_module, class_name)
|
| 149 |
+
|
| 150 |
+
return None
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class AutoProcessor:
|
| 154 |
+
r"""
|
| 155 |
+
This is a generic processor class that will be instantiated as one of the processor classes of the library when
|
| 156 |
+
created with the [`AutoProcessor.from_pretrained`] class method.
|
| 157 |
+
|
| 158 |
+
This class cannot be instantiated directly using `__init__()` (throws an error).
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
def __init__(self):
|
| 162 |
+
raise EnvironmentError(
|
| 163 |
+
"AutoProcessor is designed to be instantiated "
|
| 164 |
+
"using the `AutoProcessor.from_pretrained(pretrained_model_name_or_path)` method."
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
@classmethod
|
| 168 |
+
@replace_list_option_in_docstrings(PROCESSOR_MAPPING_NAMES)
|
| 169 |
+
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
|
| 170 |
+
r"""
|
| 171 |
+
Instantiate one of the processor classes of the library from a pretrained model vocabulary.
|
| 172 |
+
|
| 173 |
+
The processor class to instantiate is selected based on the `model_type` property of the config object (either
|
| 174 |
+
passed as an argument or loaded from `pretrained_model_name_or_path` if possible):
|
| 175 |
+
|
| 176 |
+
List options
|
| 177 |
+
|
| 178 |
+
Params:
|
| 179 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 180 |
+
This can be either:
|
| 181 |
+
|
| 182 |
+
- a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on
|
| 183 |
+
huggingface.co.
|
| 184 |
+
- a path to a *directory* containing a processor files saved using the `save_pretrained()` method,
|
| 185 |
+
e.g., `./my_model_directory/`.
|
| 186 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 187 |
+
Path to a directory in which a downloaded pretrained model feature extractor should be cached if the
|
| 188 |
+
standard cache should not be used.
|
| 189 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 190 |
+
Whether or not to force to (re-)download the feature extractor files and override the cached versions
|
| 191 |
+
if they exist.
|
| 192 |
+
resume_download:
|
| 193 |
+
Deprecated and ignored. All downloads are now resumed by default when possible.
|
| 194 |
+
Will be removed in v5 of Transformers.
|
| 195 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 196 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 197 |
+
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
|
| 198 |
+
token (`str` or *bool*, *optional*):
|
| 199 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
|
| 200 |
+
when running `huggingface-cli login` (stored in `~/.huggingface`).
|
| 201 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 202 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 203 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 204 |
+
identifier allowed by git.
|
| 205 |
+
return_unused_kwargs (`bool`, *optional*, defaults to `False`):
|
| 206 |
+
If `False`, then this function returns just the final feature extractor object. If `True`, then this
|
| 207 |
+
functions returns a `Tuple(feature_extractor, unused_kwargs)` where *unused_kwargs* is a dictionary
|
| 208 |
+
consisting of the key/value pairs whose keys are not feature extractor attributes: i.e., the part of
|
| 209 |
+
`kwargs` which has not been used to update `feature_extractor` and is otherwise ignored.
|
| 210 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 211 |
+
Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
|
| 212 |
+
should only be set to `True` for repositories you trust and in which you have read the code, as it will
|
| 213 |
+
execute code present on the Hub on your local machine.
|
| 214 |
+
kwargs (`Dict[str, Any]`, *optional*):
|
| 215 |
+
The values in kwargs of any keys which are feature extractor attributes will be used to override the
|
| 216 |
+
loaded values. Behavior concerning key/value pairs whose keys are *not* feature extractor attributes is
|
| 217 |
+
controlled by the `return_unused_kwargs` keyword parameter.
|
| 218 |
+
|
| 219 |
+
<Tip>
|
| 220 |
+
|
| 221 |
+
Passing `token=True` is required when you want to use a private model.
|
| 222 |
+
|
| 223 |
+
</Tip>
|
| 224 |
+
|
| 225 |
+
Examples:
|
| 226 |
+
|
| 227 |
+
```python
|
| 228 |
+
>>> from transformers import AutoProcessor
|
| 229 |
+
|
| 230 |
+
>>> # Download processor from huggingface.co and cache.
|
| 231 |
+
>>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h")
|
| 232 |
+
|
| 233 |
+
>>> # If processor files are in a directory (e.g. processor was saved using *save_pretrained('./test/saved_model/')*)
|
| 234 |
+
>>> # processor = AutoProcessor.from_pretrained("./test/saved_model/")
|
| 235 |
+
```"""
|
| 236 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 237 |
+
if use_auth_token is not None:
|
| 238 |
+
warnings.warn(
|
| 239 |
+
"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
|
| 240 |
+
FutureWarning,
|
| 241 |
+
)
|
| 242 |
+
if kwargs.get("token", None) is not None:
|
| 243 |
+
raise ValueError(
|
| 244 |
+
"`token` and `use_auth_token` are both specified. Please set only the argument `token`."
|
| 245 |
+
)
|
| 246 |
+
kwargs["token"] = use_auth_token
|
| 247 |
+
|
| 248 |
+
config = kwargs.pop("config", None)
|
| 249 |
+
trust_remote_code = kwargs.pop("trust_remote_code", None)
|
| 250 |
+
kwargs["_from_auto"] = True
|
| 251 |
+
|
| 252 |
+
processor_class = None
|
| 253 |
+
processor_auto_map = None
|
| 254 |
+
|
| 255 |
+
# First, let's see if we have a processor or preprocessor config.
|
| 256 |
+
# Filter the kwargs for `get_file_from_repo`.
|
| 257 |
+
get_file_from_repo_kwargs = {
|
| 258 |
+
key: kwargs[key] for key in inspect.signature(get_file_from_repo).parameters.keys() if key in kwargs
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
# Let's start by checking whether the processor class is saved in a processor config
|
| 262 |
+
processor_config_file = get_file_from_repo(
|
| 263 |
+
pretrained_model_name_or_path, PROCESSOR_NAME, **get_file_from_repo_kwargs
|
| 264 |
+
)
|
| 265 |
+
if processor_config_file is not None:
|
| 266 |
+
config_dict, _ = ProcessorMixin.get_processor_dict(pretrained_model_name_or_path, **kwargs)
|
| 267 |
+
processor_class = config_dict.get("processor_class", None)
|
| 268 |
+
if "AutoProcessor" in config_dict.get("auto_map", {}):
|
| 269 |
+
processor_auto_map = config_dict["auto_map"]["AutoProcessor"]
|
| 270 |
+
|
| 271 |
+
if processor_class is None:
|
| 272 |
+
# If not found, let's check whether the processor class is saved in an image processor config
|
| 273 |
+
preprocessor_config_file = get_file_from_repo(
|
| 274 |
+
pretrained_model_name_or_path, FEATURE_EXTRACTOR_NAME, **get_file_from_repo_kwargs
|
| 275 |
+
)
|
| 276 |
+
if preprocessor_config_file is not None:
|
| 277 |
+
config_dict, _ = ImageProcessingMixin.get_image_processor_dict(pretrained_model_name_or_path, **kwargs)
|
| 278 |
+
processor_class = config_dict.get("processor_class", None)
|
| 279 |
+
if "AutoProcessor" in config_dict.get("auto_map", {}):
|
| 280 |
+
processor_auto_map = config_dict["auto_map"]["AutoProcessor"]
|
| 281 |
+
|
| 282 |
+
# If not found, let's check whether the processor class is saved in a feature extractor config
|
| 283 |
+
if preprocessor_config_file is not None and processor_class is None:
|
| 284 |
+
config_dict, _ = FeatureExtractionMixin.get_feature_extractor_dict(
|
| 285 |
+
pretrained_model_name_or_path, **kwargs
|
| 286 |
+
)
|
| 287 |
+
processor_class = config_dict.get("processor_class", None)
|
| 288 |
+
if "AutoProcessor" in config_dict.get("auto_map", {}):
|
| 289 |
+
processor_auto_map = config_dict["auto_map"]["AutoProcessor"]
|
| 290 |
+
|
| 291 |
+
if processor_class is None:
|
| 292 |
+
# Next, let's check whether the processor class is saved in a tokenizer
|
| 293 |
+
tokenizer_config_file = get_file_from_repo(
|
| 294 |
+
pretrained_model_name_or_path, TOKENIZER_CONFIG_FILE, **get_file_from_repo_kwargs
|
| 295 |
+
)
|
| 296 |
+
if tokenizer_config_file is not None:
|
| 297 |
+
with open(tokenizer_config_file, encoding="utf-8") as reader:
|
| 298 |
+
config_dict = json.load(reader)
|
| 299 |
+
|
| 300 |
+
processor_class = config_dict.get("processor_class", None)
|
| 301 |
+
if "AutoProcessor" in config_dict.get("auto_map", {}):
|
| 302 |
+
processor_auto_map = config_dict["auto_map"]["AutoProcessor"]
|
| 303 |
+
|
| 304 |
+
if processor_class is None:
|
| 305 |
+
# Otherwise, load config, if it can be loaded.
|
| 306 |
+
if not isinstance(config, PretrainedConfig):
|
| 307 |
+
config = AutoConfig.from_pretrained(
|
| 308 |
+
pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
# And check if the config contains the processor class.
|
| 312 |
+
processor_class = getattr(config, "processor_class", None)
|
| 313 |
+
if hasattr(config, "auto_map") and "AutoProcessor" in config.auto_map:
|
| 314 |
+
processor_auto_map = config.auto_map["AutoProcessor"]
|
| 315 |
+
|
| 316 |
+
if processor_class is not None:
|
| 317 |
+
processor_class = processor_class_from_name(processor_class)
|
| 318 |
+
|
| 319 |
+
has_remote_code = processor_auto_map is not None
|
| 320 |
+
has_local_code = processor_class is not None or type(config) in PROCESSOR_MAPPING
|
| 321 |
+
trust_remote_code = resolve_trust_remote_code(
|
| 322 |
+
trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
if has_remote_code and trust_remote_code:
|
| 326 |
+
processor_class = get_class_from_dynamic_module(
|
| 327 |
+
processor_auto_map, pretrained_model_name_or_path, **kwargs
|
| 328 |
+
)
|
| 329 |
+
_ = kwargs.pop("code_revision", None)
|
| 330 |
+
if os.path.isdir(pretrained_model_name_or_path):
|
| 331 |
+
processor_class.register_for_auto_class()
|
| 332 |
+
return processor_class.from_pretrained(
|
| 333 |
+
pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
|
| 334 |
+
)
|
| 335 |
+
elif processor_class is not None:
|
| 336 |
+
return processor_class.from_pretrained(
|
| 337 |
+
pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
|
| 338 |
+
)
|
| 339 |
+
# Last try: we use the PROCESSOR_MAPPING.
|
| 340 |
+
elif type(config) in PROCESSOR_MAPPING:
|
| 341 |
+
return PROCESSOR_MAPPING[type(config)].from_pretrained(pretrained_model_name_or_path, **kwargs)
|
| 342 |
+
|
| 343 |
+
# At this stage, there doesn't seem to be a `Processor` class available for this model, so let's try a
|
| 344 |
+
# tokenizer.
|
| 345 |
+
try:
|
| 346 |
+
return AutoTokenizer.from_pretrained(
|
| 347 |
+
pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
|
| 348 |
+
)
|
| 349 |
+
except Exception:
|
| 350 |
+
try:
|
| 351 |
+
return AutoImageProcessor.from_pretrained(
|
| 352 |
+
pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
|
| 353 |
+
)
|
| 354 |
+
except Exception:
|
| 355 |
+
pass
|
| 356 |
+
|
| 357 |
+
try:
|
| 358 |
+
return AutoFeatureExtractor.from_pretrained(
|
| 359 |
+
pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
|
| 360 |
+
)
|
| 361 |
+
except Exception:
|
| 362 |
+
pass
|
| 363 |
+
|
| 364 |
+
raise ValueError(
|
| 365 |
+
f"Unrecognized processing class in {pretrained_model_name_or_path}. Can't instantiate a processor, a "
|
| 366 |
+
"tokenizer, an image processor or a feature extractor for this model. Make sure the repository contains "
|
| 367 |
+
"the files of at least one of those processing classes."
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
@staticmethod
|
| 371 |
+
def register(config_class, processor_class, exist_ok=False):
|
| 372 |
+
"""
|
| 373 |
+
Register a new processor for this class.
|
| 374 |
+
|
| 375 |
+
Args:
|
| 376 |
+
config_class ([`PretrainedConfig`]):
|
| 377 |
+
The configuration corresponding to the model to register.
|
| 378 |
+
processor_class ([`FeatureExtractorMixin`]): The processor to register.
|
| 379 |
+
"""
|
| 380 |
+
PROCESSOR_MAPPING.register(config_class, processor_class, exist_ok=exist_ok)
|
tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/models/auto/tokenization_auto.py
ADDED
|
@@ -0,0 +1,1027 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Auto Tokenizer class."""
|
| 16 |
+
|
| 17 |
+
import importlib
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import warnings
|
| 21 |
+
from collections import OrderedDict
|
| 22 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union
|
| 23 |
+
|
| 24 |
+
from ...configuration_utils import PretrainedConfig
|
| 25 |
+
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
|
| 26 |
+
from ...modeling_gguf_pytorch_utils import load_gguf_checkpoint
|
| 27 |
+
from ...tokenization_utils import PreTrainedTokenizer
|
| 28 |
+
from ...tokenization_utils_base import TOKENIZER_CONFIG_FILE
|
| 29 |
+
from ...utils import (
|
| 30 |
+
cached_file,
|
| 31 |
+
extract_commit_hash,
|
| 32 |
+
is_g2p_en_available,
|
| 33 |
+
is_sentencepiece_available,
|
| 34 |
+
is_tokenizers_available,
|
| 35 |
+
logging,
|
| 36 |
+
)
|
| 37 |
+
from ..encoder_decoder import EncoderDecoderConfig
|
| 38 |
+
from .auto_factory import _LazyAutoMapping
|
| 39 |
+
from .configuration_auto import (
|
| 40 |
+
CONFIG_MAPPING_NAMES,
|
| 41 |
+
AutoConfig,
|
| 42 |
+
config_class_to_model_type,
|
| 43 |
+
model_type_to_module_name,
|
| 44 |
+
replace_list_option_in_docstrings,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if is_tokenizers_available():
|
| 49 |
+
from ...tokenization_utils_fast import PreTrainedTokenizerFast
|
| 50 |
+
else:
|
| 51 |
+
PreTrainedTokenizerFast = None
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
logger = logging.get_logger(__name__)
|
| 55 |
+
|
| 56 |
+
if TYPE_CHECKING:
|
| 57 |
+
# This significantly improves completion suggestion performance when
|
| 58 |
+
# the transformers package is used with Microsoft's Pylance language server.
|
| 59 |
+
TOKENIZER_MAPPING_NAMES: OrderedDict[str, Tuple[Optional[str], Optional[str]]] = OrderedDict()
|
| 60 |
+
else:
|
| 61 |
+
TOKENIZER_MAPPING_NAMES = OrderedDict(
|
| 62 |
+
[
|
| 63 |
+
(
|
| 64 |
+
"albert",
|
| 65 |
+
(
|
| 66 |
+
"AlbertTokenizer" if is_sentencepiece_available() else None,
|
| 67 |
+
"AlbertTokenizerFast" if is_tokenizers_available() else None,
|
| 68 |
+
),
|
| 69 |
+
),
|
| 70 |
+
("align", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 71 |
+
("aria", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
|
| 72 |
+
("aya_vision", (None, "CohereTokenizerFast" if is_tokenizers_available() else None)),
|
| 73 |
+
("bark", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 74 |
+
("bart", ("BartTokenizer", "BartTokenizerFast")),
|
| 75 |
+
(
|
| 76 |
+
"barthez",
|
| 77 |
+
(
|
| 78 |
+
"BarthezTokenizer" if is_sentencepiece_available() else None,
|
| 79 |
+
"BarthezTokenizerFast" if is_tokenizers_available() else None,
|
| 80 |
+
),
|
| 81 |
+
),
|
| 82 |
+
("bartpho", ("BartphoTokenizer", None)),
|
| 83 |
+
("bert", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 84 |
+
("bert-generation", ("BertGenerationTokenizer" if is_sentencepiece_available() else None, None)),
|
| 85 |
+
("bert-japanese", ("BertJapaneseTokenizer", None)),
|
| 86 |
+
("bertweet", ("BertweetTokenizer", None)),
|
| 87 |
+
(
|
| 88 |
+
"big_bird",
|
| 89 |
+
(
|
| 90 |
+
"BigBirdTokenizer" if is_sentencepiece_available() else None,
|
| 91 |
+
"BigBirdTokenizerFast" if is_tokenizers_available() else None,
|
| 92 |
+
),
|
| 93 |
+
),
|
| 94 |
+
("bigbird_pegasus", ("PegasusTokenizer", "PegasusTokenizerFast" if is_tokenizers_available() else None)),
|
| 95 |
+
("biogpt", ("BioGptTokenizer", None)),
|
| 96 |
+
("blenderbot", ("BlenderbotTokenizer", "BlenderbotTokenizerFast")),
|
| 97 |
+
("blenderbot-small", ("BlenderbotSmallTokenizer", None)),
|
| 98 |
+
("blip", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 99 |
+
("blip-2", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
|
| 100 |
+
("bloom", (None, "BloomTokenizerFast" if is_tokenizers_available() else None)),
|
| 101 |
+
("bridgetower", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)),
|
| 102 |
+
("bros", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 103 |
+
("byt5", ("ByT5Tokenizer", None)),
|
| 104 |
+
(
|
| 105 |
+
"camembert",
|
| 106 |
+
(
|
| 107 |
+
"CamembertTokenizer" if is_sentencepiece_available() else None,
|
| 108 |
+
"CamembertTokenizerFast" if is_tokenizers_available() else None,
|
| 109 |
+
),
|
| 110 |
+
),
|
| 111 |
+
("canine", ("CanineTokenizer", None)),
|
| 112 |
+
(
|
| 113 |
+
"chameleon",
|
| 114 |
+
(
|
| 115 |
+
"LlamaTokenizer" if is_sentencepiece_available() else None,
|
| 116 |
+
"LlamaTokenizerFast" if is_tokenizers_available() else None,
|
| 117 |
+
),
|
| 118 |
+
),
|
| 119 |
+
("chinese_clip", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 120 |
+
(
|
| 121 |
+
"clap",
|
| 122 |
+
(
|
| 123 |
+
"RobertaTokenizer",
|
| 124 |
+
"RobertaTokenizerFast" if is_tokenizers_available() else None,
|
| 125 |
+
),
|
| 126 |
+
),
|
| 127 |
+
(
|
| 128 |
+
"clip",
|
| 129 |
+
(
|
| 130 |
+
"CLIPTokenizer",
|
| 131 |
+
"CLIPTokenizerFast" if is_tokenizers_available() else None,
|
| 132 |
+
),
|
| 133 |
+
),
|
| 134 |
+
(
|
| 135 |
+
"clipseg",
|
| 136 |
+
(
|
| 137 |
+
"CLIPTokenizer",
|
| 138 |
+
"CLIPTokenizerFast" if is_tokenizers_available() else None,
|
| 139 |
+
),
|
| 140 |
+
),
|
| 141 |
+
("clvp", ("ClvpTokenizer", None)),
|
| 142 |
+
(
|
| 143 |
+
"code_llama",
|
| 144 |
+
(
|
| 145 |
+
"CodeLlamaTokenizer" if is_sentencepiece_available() else None,
|
| 146 |
+
"CodeLlamaTokenizerFast" if is_tokenizers_available() else None,
|
| 147 |
+
),
|
| 148 |
+
),
|
| 149 |
+
("codegen", ("CodeGenTokenizer", "CodeGenTokenizerFast" if is_tokenizers_available() else None)),
|
| 150 |
+
("cohere", (None, "CohereTokenizerFast" if is_tokenizers_available() else None)),
|
| 151 |
+
("cohere2", (None, "CohereTokenizerFast" if is_tokenizers_available() else None)),
|
| 152 |
+
("colpali", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
|
| 153 |
+
("convbert", ("ConvBertTokenizer", "ConvBertTokenizerFast" if is_tokenizers_available() else None)),
|
| 154 |
+
(
|
| 155 |
+
"cpm",
|
| 156 |
+
(
|
| 157 |
+
"CpmTokenizer" if is_sentencepiece_available() else None,
|
| 158 |
+
"CpmTokenizerFast" if is_tokenizers_available() else None,
|
| 159 |
+
),
|
| 160 |
+
),
|
| 161 |
+
("cpmant", ("CpmAntTokenizer", None)),
|
| 162 |
+
("ctrl", ("CTRLTokenizer", None)),
|
| 163 |
+
("data2vec-audio", ("Wav2Vec2CTCTokenizer", None)),
|
| 164 |
+
("data2vec-text", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)),
|
| 165 |
+
("dbrx", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
|
| 166 |
+
("deberta", ("DebertaTokenizer", "DebertaTokenizerFast" if is_tokenizers_available() else None)),
|
| 167 |
+
(
|
| 168 |
+
"deberta-v2",
|
| 169 |
+
(
|
| 170 |
+
"DebertaV2Tokenizer" if is_sentencepiece_available() else None,
|
| 171 |
+
"DebertaV2TokenizerFast" if is_tokenizers_available() else None,
|
| 172 |
+
),
|
| 173 |
+
),
|
| 174 |
+
(
|
| 175 |
+
"diffllama",
|
| 176 |
+
(
|
| 177 |
+
"LlamaTokenizer" if is_sentencepiece_available() else None,
|
| 178 |
+
"LlamaTokenizerFast" if is_tokenizers_available() else None,
|
| 179 |
+
),
|
| 180 |
+
),
|
| 181 |
+
("distilbert", ("DistilBertTokenizer", "DistilBertTokenizerFast" if is_tokenizers_available() else None)),
|
| 182 |
+
(
|
| 183 |
+
"dpr",
|
| 184 |
+
(
|
| 185 |
+
"DPRQuestionEncoderTokenizer",
|
| 186 |
+
"DPRQuestionEncoderTokenizerFast" if is_tokenizers_available() else None,
|
| 187 |
+
),
|
| 188 |
+
),
|
| 189 |
+
("electra", ("ElectraTokenizer", "ElectraTokenizerFast" if is_tokenizers_available() else None)),
|
| 190 |
+
("emu3", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
|
| 191 |
+
("ernie", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 192 |
+
("ernie_m", ("ErnieMTokenizer" if is_sentencepiece_available() else None, None)),
|
| 193 |
+
("esm", ("EsmTokenizer", None)),
|
| 194 |
+
("falcon", (None, "PreTrainedTokenizerFast" if is_tokenizers_available() else None)),
|
| 195 |
+
("falcon_mamba", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
|
| 196 |
+
(
|
| 197 |
+
"fastspeech2_conformer",
|
| 198 |
+
("FastSpeech2ConformerTokenizer" if is_g2p_en_available() else None, None),
|
| 199 |
+
),
|
| 200 |
+
("flaubert", ("FlaubertTokenizer", None)),
|
| 201 |
+
("fnet", ("FNetTokenizer", "FNetTokenizerFast" if is_tokenizers_available() else None)),
|
| 202 |
+
("fsmt", ("FSMTTokenizer", None)),
|
| 203 |
+
("funnel", ("FunnelTokenizer", "FunnelTokenizerFast" if is_tokenizers_available() else None)),
|
| 204 |
+
(
|
| 205 |
+
"gemma",
|
| 206 |
+
(
|
| 207 |
+
"GemmaTokenizer" if is_sentencepiece_available() else None,
|
| 208 |
+
"GemmaTokenizerFast" if is_tokenizers_available() else None,
|
| 209 |
+
),
|
| 210 |
+
),
|
| 211 |
+
(
|
| 212 |
+
"gemma2",
|
| 213 |
+
(
|
| 214 |
+
"GemmaTokenizer" if is_sentencepiece_available() else None,
|
| 215 |
+
"GemmaTokenizerFast" if is_tokenizers_available() else None,
|
| 216 |
+
),
|
| 217 |
+
),
|
| 218 |
+
("git", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 219 |
+
("glm", (None, "PreTrainedTokenizerFast" if is_tokenizers_available() else None)),
|
| 220 |
+
("gpt-sw3", ("GPTSw3Tokenizer" if is_sentencepiece_available() else None, None)),
|
| 221 |
+
("gpt2", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
|
| 222 |
+
("gpt_bigcode", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
|
| 223 |
+
("gpt_neo", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
|
| 224 |
+
("gpt_neox", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
|
| 225 |
+
("gpt_neox_japanese", ("GPTNeoXJapaneseTokenizer", None)),
|
| 226 |
+
("gptj", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
|
| 227 |
+
("gptsan-japanese", ("GPTSanJapaneseTokenizer", None)),
|
| 228 |
+
("grounding-dino", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 229 |
+
("groupvit", ("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None)),
|
| 230 |
+
("helium", (None, "PreTrainedTokenizerFast" if is_tokenizers_available() else None)),
|
| 231 |
+
("herbert", ("HerbertTokenizer", "HerbertTokenizerFast" if is_tokenizers_available() else None)),
|
| 232 |
+
("hubert", ("Wav2Vec2CTCTokenizer", None)),
|
| 233 |
+
("ibert", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)),
|
| 234 |
+
("idefics", (None, "LlamaTokenizerFast" if is_tokenizers_available() else None)),
|
| 235 |
+
("idefics2", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
|
| 236 |
+
("idefics3", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
|
| 237 |
+
("instructblip", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
|
| 238 |
+
("instructblipvideo", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
|
| 239 |
+
(
|
| 240 |
+
"jamba",
|
| 241 |
+
(
|
| 242 |
+
"LlamaTokenizer" if is_sentencepiece_available() else None,
|
| 243 |
+
"LlamaTokenizerFast" if is_tokenizers_available() else None,
|
| 244 |
+
),
|
| 245 |
+
),
|
| 246 |
+
(
|
| 247 |
+
"jetmoe",
|
| 248 |
+
(
|
| 249 |
+
"LlamaTokenizer" if is_sentencepiece_available() else None,
|
| 250 |
+
"LlamaTokenizerFast" if is_tokenizers_available() else None,
|
| 251 |
+
),
|
| 252 |
+
),
|
| 253 |
+
("jukebox", ("JukeboxTokenizer", None)),
|
| 254 |
+
(
|
| 255 |
+
"kosmos-2",
|
| 256 |
+
(
|
| 257 |
+
"XLMRobertaTokenizer" if is_sentencepiece_available() else None,
|
| 258 |
+
"XLMRobertaTokenizerFast" if is_tokenizers_available() else None,
|
| 259 |
+
),
|
| 260 |
+
),
|
| 261 |
+
("layoutlm", ("LayoutLMTokenizer", "LayoutLMTokenizerFast" if is_tokenizers_available() else None)),
|
| 262 |
+
("layoutlmv2", ("LayoutLMv2Tokenizer", "LayoutLMv2TokenizerFast" if is_tokenizers_available() else None)),
|
| 263 |
+
("layoutlmv3", ("LayoutLMv3Tokenizer", "LayoutLMv3TokenizerFast" if is_tokenizers_available() else None)),
|
| 264 |
+
("layoutxlm", ("LayoutXLMTokenizer", "LayoutXLMTokenizerFast" if is_tokenizers_available() else None)),
|
| 265 |
+
("led", ("LEDTokenizer", "LEDTokenizerFast" if is_tokenizers_available() else None)),
|
| 266 |
+
("lilt", ("LayoutLMv3Tokenizer", "LayoutLMv3TokenizerFast" if is_tokenizers_available() else None)),
|
| 267 |
+
(
|
| 268 |
+
"llama",
|
| 269 |
+
(
|
| 270 |
+
"LlamaTokenizer" if is_sentencepiece_available() else None,
|
| 271 |
+
"LlamaTokenizerFast" if is_tokenizers_available() else None,
|
| 272 |
+
),
|
| 273 |
+
),
|
| 274 |
+
("llava", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
|
| 275 |
+
("llava_next", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
|
| 276 |
+
("llava_next_video", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
|
| 277 |
+
("llava_onevision", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
|
| 278 |
+
("longformer", ("LongformerTokenizer", "LongformerTokenizerFast" if is_tokenizers_available() else None)),
|
| 279 |
+
(
|
| 280 |
+
"longt5",
|
| 281 |
+
(
|
| 282 |
+
"T5Tokenizer" if is_sentencepiece_available() else None,
|
| 283 |
+
"T5TokenizerFast" if is_tokenizers_available() else None,
|
| 284 |
+
),
|
| 285 |
+
),
|
| 286 |
+
("luke", ("LukeTokenizer", None)),
|
| 287 |
+
("lxmert", ("LxmertTokenizer", "LxmertTokenizerFast" if is_tokenizers_available() else None)),
|
| 288 |
+
("m2m_100", ("M2M100Tokenizer" if is_sentencepiece_available() else None, None)),
|
| 289 |
+
("mamba", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
|
| 290 |
+
("mamba2", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
|
| 291 |
+
("marian", ("MarianTokenizer" if is_sentencepiece_available() else None, None)),
|
| 292 |
+
(
|
| 293 |
+
"mbart",
|
| 294 |
+
(
|
| 295 |
+
"MBartTokenizer" if is_sentencepiece_available() else None,
|
| 296 |
+
"MBartTokenizerFast" if is_tokenizers_available() else None,
|
| 297 |
+
),
|
| 298 |
+
),
|
| 299 |
+
(
|
| 300 |
+
"mbart50",
|
| 301 |
+
(
|
| 302 |
+
"MBart50Tokenizer" if is_sentencepiece_available() else None,
|
| 303 |
+
"MBart50TokenizerFast" if is_tokenizers_available() else None,
|
| 304 |
+
),
|
| 305 |
+
),
|
| 306 |
+
("mega", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)),
|
| 307 |
+
("megatron-bert", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 308 |
+
("mgp-str", ("MgpstrTokenizer", None)),
|
| 309 |
+
(
|
| 310 |
+
"mistral",
|
| 311 |
+
(
|
| 312 |
+
"LlamaTokenizer" if is_sentencepiece_available() else None,
|
| 313 |
+
"LlamaTokenizerFast" if is_tokenizers_available() else None,
|
| 314 |
+
),
|
| 315 |
+
),
|
| 316 |
+
(
|
| 317 |
+
"mixtral",
|
| 318 |
+
(
|
| 319 |
+
"LlamaTokenizer" if is_sentencepiece_available() else None,
|
| 320 |
+
"LlamaTokenizerFast" if is_tokenizers_available() else None,
|
| 321 |
+
),
|
| 322 |
+
),
|
| 323 |
+
("mllama", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
|
| 324 |
+
("mluke", ("MLukeTokenizer" if is_sentencepiece_available() else None, None)),
|
| 325 |
+
("mobilebert", ("MobileBertTokenizer", "MobileBertTokenizerFast" if is_tokenizers_available() else None)),
|
| 326 |
+
("modernbert", (None, "PreTrainedTokenizerFast" if is_tokenizers_available() else None)),
|
| 327 |
+
("moonshine", (None, "PreTrainedTokenizerFast" if is_tokenizers_available() else None)),
|
| 328 |
+
("moshi", (None, "PreTrainedTokenizerFast" if is_tokenizers_available() else None)),
|
| 329 |
+
("mpnet", ("MPNetTokenizer", "MPNetTokenizerFast" if is_tokenizers_available() else None)),
|
| 330 |
+
("mpt", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
|
| 331 |
+
("mra", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)),
|
| 332 |
+
(
|
| 333 |
+
"mt5",
|
| 334 |
+
(
|
| 335 |
+
"MT5Tokenizer" if is_sentencepiece_available() else None,
|
| 336 |
+
"MT5TokenizerFast" if is_tokenizers_available() else None,
|
| 337 |
+
),
|
| 338 |
+
),
|
| 339 |
+
("musicgen", ("T5Tokenizer", "T5TokenizerFast" if is_tokenizers_available() else None)),
|
| 340 |
+
("musicgen_melody", ("T5Tokenizer", "T5TokenizerFast" if is_tokenizers_available() else None)),
|
| 341 |
+
("mvp", ("MvpTokenizer", "MvpTokenizerFast" if is_tokenizers_available() else None)),
|
| 342 |
+
("myt5", ("MyT5Tokenizer", None)),
|
| 343 |
+
("nemotron", (None, "PreTrainedTokenizerFast" if is_tokenizers_available() else None)),
|
| 344 |
+
("nezha", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 345 |
+
(
|
| 346 |
+
"nllb",
|
| 347 |
+
(
|
| 348 |
+
"NllbTokenizer" if is_sentencepiece_available() else None,
|
| 349 |
+
"NllbTokenizerFast" if is_tokenizers_available() else None,
|
| 350 |
+
),
|
| 351 |
+
),
|
| 352 |
+
(
|
| 353 |
+
"nllb-moe",
|
| 354 |
+
(
|
| 355 |
+
"NllbTokenizer" if is_sentencepiece_available() else None,
|
| 356 |
+
"NllbTokenizerFast" if is_tokenizers_available() else None,
|
| 357 |
+
),
|
| 358 |
+
),
|
| 359 |
+
(
|
| 360 |
+
"nystromformer",
|
| 361 |
+
(
|
| 362 |
+
"AlbertTokenizer" if is_sentencepiece_available() else None,
|
| 363 |
+
"AlbertTokenizerFast" if is_tokenizers_available() else None,
|
| 364 |
+
),
|
| 365 |
+
),
|
| 366 |
+
("olmo", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
|
| 367 |
+
("olmo2", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
|
| 368 |
+
("olmoe", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
|
| 369 |
+
(
|
| 370 |
+
"omdet-turbo",
|
| 371 |
+
("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None),
|
| 372 |
+
),
|
| 373 |
+
("oneformer", ("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None)),
|
| 374 |
+
(
|
| 375 |
+
"openai-gpt",
|
| 376 |
+
("OpenAIGPTTokenizer", "OpenAIGPTTokenizerFast" if is_tokenizers_available() else None),
|
| 377 |
+
),
|
| 378 |
+
("opt", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
|
| 379 |
+
("owlv2", ("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None)),
|
| 380 |
+
("owlvit", ("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None)),
|
| 381 |
+
("paligemma", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
|
| 382 |
+
(
|
| 383 |
+
"pegasus",
|
| 384 |
+
(
|
| 385 |
+
"PegasusTokenizer" if is_sentencepiece_available() else None,
|
| 386 |
+
"PegasusTokenizerFast" if is_tokenizers_available() else None,
|
| 387 |
+
),
|
| 388 |
+
),
|
| 389 |
+
(
|
| 390 |
+
"pegasus_x",
|
| 391 |
+
(
|
| 392 |
+
"PegasusTokenizer" if is_sentencepiece_available() else None,
|
| 393 |
+
"PegasusTokenizerFast" if is_tokenizers_available() else None,
|
| 394 |
+
),
|
| 395 |
+
),
|
| 396 |
+
(
|
| 397 |
+
"perceiver",
|
| 398 |
+
(
|
| 399 |
+
"PerceiverTokenizer",
|
| 400 |
+
None,
|
| 401 |
+
),
|
| 402 |
+
),
|
| 403 |
+
(
|
| 404 |
+
"persimmon",
|
| 405 |
+
(
|
| 406 |
+
"LlamaTokenizer" if is_sentencepiece_available() else None,
|
| 407 |
+
"LlamaTokenizerFast" if is_tokenizers_available() else None,
|
| 408 |
+
),
|
| 409 |
+
),
|
| 410 |
+
("phi", ("CodeGenTokenizer", "CodeGenTokenizerFast" if is_tokenizers_available() else None)),
|
| 411 |
+
("phi3", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
|
| 412 |
+
("phimoe", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
|
| 413 |
+
("phobert", ("PhobertTokenizer", None)),
|
| 414 |
+
("pix2struct", ("T5Tokenizer", "T5TokenizerFast" if is_tokenizers_available() else None)),
|
| 415 |
+
("pixtral", (None, "PreTrainedTokenizerFast" if is_tokenizers_available() else None)),
|
| 416 |
+
("plbart", ("PLBartTokenizer" if is_sentencepiece_available() else None, None)),
|
| 417 |
+
("prophetnet", ("ProphetNetTokenizer", None)),
|
| 418 |
+
("qdqbert", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 419 |
+
(
|
| 420 |
+
"qwen2",
|
| 421 |
+
(
|
| 422 |
+
"Qwen2Tokenizer",
|
| 423 |
+
"Qwen2TokenizerFast" if is_tokenizers_available() else None,
|
| 424 |
+
),
|
| 425 |
+
),
|
| 426 |
+
("qwen2_5_vl", ("Qwen2Tokenizer", "Qwen2TokenizerFast" if is_tokenizers_available() else None)),
|
| 427 |
+
("qwen2_audio", ("Qwen2Tokenizer", "Qwen2TokenizerFast" if is_tokenizers_available() else None)),
|
| 428 |
+
(
|
| 429 |
+
"qwen2_moe",
|
| 430 |
+
(
|
| 431 |
+
"Qwen2Tokenizer",
|
| 432 |
+
"Qwen2TokenizerFast" if is_tokenizers_available() else None,
|
| 433 |
+
),
|
| 434 |
+
),
|
| 435 |
+
("qwen2_vl", ("Qwen2Tokenizer", "Qwen2TokenizerFast" if is_tokenizers_available() else None)),
|
| 436 |
+
("rag", ("RagTokenizer", None)),
|
| 437 |
+
("realm", ("RealmTokenizer", "RealmTokenizerFast" if is_tokenizers_available() else None)),
|
| 438 |
+
(
|
| 439 |
+
"recurrent_gemma",
|
| 440 |
+
(
|
| 441 |
+
"GemmaTokenizer" if is_sentencepiece_available() else None,
|
| 442 |
+
"GemmaTokenizerFast" if is_tokenizers_available() else None,
|
| 443 |
+
),
|
| 444 |
+
),
|
| 445 |
+
(
|
| 446 |
+
"reformer",
|
| 447 |
+
(
|
| 448 |
+
"ReformerTokenizer" if is_sentencepiece_available() else None,
|
| 449 |
+
"ReformerTokenizerFast" if is_tokenizers_available() else None,
|
| 450 |
+
),
|
| 451 |
+
),
|
| 452 |
+
(
|
| 453 |
+
"rembert",
|
| 454 |
+
(
|
| 455 |
+
"RemBertTokenizer" if is_sentencepiece_available() else None,
|
| 456 |
+
"RemBertTokenizerFast" if is_tokenizers_available() else None,
|
| 457 |
+
),
|
| 458 |
+
),
|
| 459 |
+
("retribert", ("RetriBertTokenizer", "RetriBertTokenizerFast" if is_tokenizers_available() else None)),
|
| 460 |
+
("roberta", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)),
|
| 461 |
+
(
|
| 462 |
+
"roberta-prelayernorm",
|
| 463 |
+
("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None),
|
| 464 |
+
),
|
| 465 |
+
("roc_bert", ("RoCBertTokenizer", None)),
|
| 466 |
+
("roformer", ("RoFormerTokenizer", "RoFormerTokenizerFast" if is_tokenizers_available() else None)),
|
| 467 |
+
("rwkv", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
|
| 468 |
+
(
|
| 469 |
+
"seamless_m4t",
|
| 470 |
+
(
|
| 471 |
+
"SeamlessM4TTokenizer" if is_sentencepiece_available() else None,
|
| 472 |
+
"SeamlessM4TTokenizerFast" if is_tokenizers_available() else None,
|
| 473 |
+
),
|
| 474 |
+
),
|
| 475 |
+
(
|
| 476 |
+
"seamless_m4t_v2",
|
| 477 |
+
(
|
| 478 |
+
"SeamlessM4TTokenizer" if is_sentencepiece_available() else None,
|
| 479 |
+
"SeamlessM4TTokenizerFast" if is_tokenizers_available() else None,
|
| 480 |
+
),
|
| 481 |
+
),
|
| 482 |
+
("siglip", ("SiglipTokenizer" if is_sentencepiece_available() else None, None)),
|
| 483 |
+
(
|
| 484 |
+
"siglip2",
|
| 485 |
+
(
|
| 486 |
+
"GemmaTokenizer" if is_sentencepiece_available() else None,
|
| 487 |
+
"GemmaTokenizerFast" if is_tokenizers_available() else None,
|
| 488 |
+
),
|
| 489 |
+
),
|
| 490 |
+
("speech_to_text", ("Speech2TextTokenizer" if is_sentencepiece_available() else None, None)),
|
| 491 |
+
("speech_to_text_2", ("Speech2Text2Tokenizer", None)),
|
| 492 |
+
("speecht5", ("SpeechT5Tokenizer" if is_sentencepiece_available() else None, None)),
|
| 493 |
+
("splinter", ("SplinterTokenizer", "SplinterTokenizerFast")),
|
| 494 |
+
(
|
| 495 |
+
"squeezebert",
|
| 496 |
+
("SqueezeBertTokenizer", "SqueezeBertTokenizerFast" if is_tokenizers_available() else None),
|
| 497 |
+
),
|
| 498 |
+
("stablelm", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
|
| 499 |
+
("starcoder2", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
|
| 500 |
+
(
|
| 501 |
+
"switch_transformers",
|
| 502 |
+
(
|
| 503 |
+
"T5Tokenizer" if is_sentencepiece_available() else None,
|
| 504 |
+
"T5TokenizerFast" if is_tokenizers_available() else None,
|
| 505 |
+
),
|
| 506 |
+
),
|
| 507 |
+
(
|
| 508 |
+
"t5",
|
| 509 |
+
(
|
| 510 |
+
"T5Tokenizer" if is_sentencepiece_available() else None,
|
| 511 |
+
"T5TokenizerFast" if is_tokenizers_available() else None,
|
| 512 |
+
),
|
| 513 |
+
),
|
| 514 |
+
("tapas", ("TapasTokenizer", None)),
|
| 515 |
+
("tapex", ("TapexTokenizer", None)),
|
| 516 |
+
("transfo-xl", ("TransfoXLTokenizer", None)),
|
| 517 |
+
("tvp", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 518 |
+
(
|
| 519 |
+
"udop",
|
| 520 |
+
(
|
| 521 |
+
"UdopTokenizer" if is_sentencepiece_available() else None,
|
| 522 |
+
"UdopTokenizerFast" if is_tokenizers_available() else None,
|
| 523 |
+
),
|
| 524 |
+
),
|
| 525 |
+
(
|
| 526 |
+
"umt5",
|
| 527 |
+
(
|
| 528 |
+
"T5Tokenizer" if is_sentencepiece_available() else None,
|
| 529 |
+
"T5TokenizerFast" if is_tokenizers_available() else None,
|
| 530 |
+
),
|
| 531 |
+
),
|
| 532 |
+
("video_llava", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
|
| 533 |
+
("vilt", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 534 |
+
("vipllava", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)),
|
| 535 |
+
("visual_bert", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 536 |
+
("vits", ("VitsTokenizer", None)),
|
| 537 |
+
("wav2vec2", ("Wav2Vec2CTCTokenizer", None)),
|
| 538 |
+
("wav2vec2-bert", ("Wav2Vec2CTCTokenizer", None)),
|
| 539 |
+
("wav2vec2-conformer", ("Wav2Vec2CTCTokenizer", None)),
|
| 540 |
+
("wav2vec2_phoneme", ("Wav2Vec2PhonemeCTCTokenizer", None)),
|
| 541 |
+
("whisper", ("WhisperTokenizer", "WhisperTokenizerFast" if is_tokenizers_available() else None)),
|
| 542 |
+
("xclip", ("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None)),
|
| 543 |
+
(
|
| 544 |
+
"xglm",
|
| 545 |
+
(
|
| 546 |
+
"XGLMTokenizer" if is_sentencepiece_available() else None,
|
| 547 |
+
"XGLMTokenizerFast" if is_tokenizers_available() else None,
|
| 548 |
+
),
|
| 549 |
+
),
|
| 550 |
+
("xlm", ("XLMTokenizer", None)),
|
| 551 |
+
("xlm-prophetnet", ("XLMProphetNetTokenizer" if is_sentencepiece_available() else None, None)),
|
| 552 |
+
(
|
| 553 |
+
"xlm-roberta",
|
| 554 |
+
(
|
| 555 |
+
"XLMRobertaTokenizer" if is_sentencepiece_available() else None,
|
| 556 |
+
"XLMRobertaTokenizerFast" if is_tokenizers_available() else None,
|
| 557 |
+
),
|
| 558 |
+
),
|
| 559 |
+
(
|
| 560 |
+
"xlm-roberta-xl",
|
| 561 |
+
(
|
| 562 |
+
"XLMRobertaTokenizer" if is_sentencepiece_available() else None,
|
| 563 |
+
"XLMRobertaTokenizerFast" if is_tokenizers_available() else None,
|
| 564 |
+
),
|
| 565 |
+
),
|
| 566 |
+
(
|
| 567 |
+
"xlnet",
|
| 568 |
+
(
|
| 569 |
+
"XLNetTokenizer" if is_sentencepiece_available() else None,
|
| 570 |
+
"XLNetTokenizerFast" if is_tokenizers_available() else None,
|
| 571 |
+
),
|
| 572 |
+
),
|
| 573 |
+
(
|
| 574 |
+
"xmod",
|
| 575 |
+
(
|
| 576 |
+
"XLMRobertaTokenizer" if is_sentencepiece_available() else None,
|
| 577 |
+
"XLMRobertaTokenizerFast" if is_tokenizers_available() else None,
|
| 578 |
+
),
|
| 579 |
+
),
|
| 580 |
+
(
|
| 581 |
+
"yoso",
|
| 582 |
+
(
|
| 583 |
+
"AlbertTokenizer" if is_sentencepiece_available() else None,
|
| 584 |
+
"AlbertTokenizerFast" if is_tokenizers_available() else None,
|
| 585 |
+
),
|
| 586 |
+
),
|
| 587 |
+
(
|
| 588 |
+
"zamba",
|
| 589 |
+
(
|
| 590 |
+
"LlamaTokenizer" if is_sentencepiece_available() else None,
|
| 591 |
+
"LlamaTokenizerFast" if is_tokenizers_available() else None,
|
| 592 |
+
),
|
| 593 |
+
),
|
| 594 |
+
(
|
| 595 |
+
"zamba2",
|
| 596 |
+
(
|
| 597 |
+
"LlamaTokenizer" if is_sentencepiece_available() else None,
|
| 598 |
+
"LlamaTokenizerFast" if is_tokenizers_available() else None,
|
| 599 |
+
),
|
| 600 |
+
),
|
| 601 |
+
]
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
TOKENIZER_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, TOKENIZER_MAPPING_NAMES)
|
| 605 |
+
|
| 606 |
+
CONFIG_TO_TYPE = {v: k for k, v in CONFIG_MAPPING_NAMES.items()}
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
def tokenizer_class_from_name(class_name: str):
|
| 610 |
+
if class_name == "PreTrainedTokenizerFast":
|
| 611 |
+
return PreTrainedTokenizerFast
|
| 612 |
+
|
| 613 |
+
for module_name, tokenizers in TOKENIZER_MAPPING_NAMES.items():
|
| 614 |
+
if class_name in tokenizers:
|
| 615 |
+
module_name = model_type_to_module_name(module_name)
|
| 616 |
+
|
| 617 |
+
module = importlib.import_module(f".{module_name}", "transformers.models")
|
| 618 |
+
try:
|
| 619 |
+
return getattr(module, class_name)
|
| 620 |
+
except AttributeError:
|
| 621 |
+
continue
|
| 622 |
+
|
| 623 |
+
for config, tokenizers in TOKENIZER_MAPPING._extra_content.items():
|
| 624 |
+
for tokenizer in tokenizers:
|
| 625 |
+
if getattr(tokenizer, "__name__", None) == class_name:
|
| 626 |
+
return tokenizer
|
| 627 |
+
|
| 628 |
+
# We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
|
| 629 |
+
# init and we return the proper dummy to get an appropriate error message.
|
| 630 |
+
main_module = importlib.import_module("transformers")
|
| 631 |
+
if hasattr(main_module, class_name):
|
| 632 |
+
return getattr(main_module, class_name)
|
| 633 |
+
|
| 634 |
+
return None
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def get_tokenizer_config(
|
| 638 |
+
pretrained_model_name_or_path: Union[str, os.PathLike],
|
| 639 |
+
cache_dir: Optional[Union[str, os.PathLike]] = None,
|
| 640 |
+
force_download: bool = False,
|
| 641 |
+
resume_download: Optional[bool] = None,
|
| 642 |
+
proxies: Optional[Dict[str, str]] = None,
|
| 643 |
+
token: Optional[Union[bool, str]] = None,
|
| 644 |
+
revision: Optional[str] = None,
|
| 645 |
+
local_files_only: bool = False,
|
| 646 |
+
subfolder: str = "",
|
| 647 |
+
**kwargs,
|
| 648 |
+
):
|
| 649 |
+
"""
|
| 650 |
+
Loads the tokenizer configuration from a pretrained model tokenizer configuration.
|
| 651 |
+
|
| 652 |
+
Args:
|
| 653 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 654 |
+
This can be either:
|
| 655 |
+
|
| 656 |
+
- a string, the *model id* of a pretrained model configuration hosted inside a model repo on
|
| 657 |
+
huggingface.co.
|
| 658 |
+
- a path to a *directory* containing a configuration file saved using the
|
| 659 |
+
[`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
|
| 660 |
+
|
| 661 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 662 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
|
| 663 |
+
cache should not be used.
|
| 664 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 665 |
+
Whether or not to force to (re-)download the configuration files and override the cached versions if they
|
| 666 |
+
exist.
|
| 667 |
+
resume_download:
|
| 668 |
+
Deprecated and ignored. All downloads are now resumed by default when possible.
|
| 669 |
+
Will be removed in v5 of Transformers.
|
| 670 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 671 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 672 |
+
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
|
| 673 |
+
token (`str` or *bool*, *optional*):
|
| 674 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
|
| 675 |
+
when running `huggingface-cli login` (stored in `~/.huggingface`).
|
| 676 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 677 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 678 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 679 |
+
identifier allowed by git.
|
| 680 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 681 |
+
If `True`, will only try to load the tokenizer configuration from local files.
|
| 682 |
+
subfolder (`str`, *optional*, defaults to `""`):
|
| 683 |
+
In case the tokenizer config is located inside a subfolder of the model repo on huggingface.co, you can
|
| 684 |
+
specify the folder name here.
|
| 685 |
+
|
| 686 |
+
<Tip>
|
| 687 |
+
|
| 688 |
+
Passing `token=True` is required when you want to use a private model.
|
| 689 |
+
|
| 690 |
+
</Tip>
|
| 691 |
+
|
| 692 |
+
Returns:
|
| 693 |
+
`Dict`: The configuration of the tokenizer.
|
| 694 |
+
|
| 695 |
+
Examples:
|
| 696 |
+
|
| 697 |
+
```python
|
| 698 |
+
# Download configuration from huggingface.co and cache.
|
| 699 |
+
tokenizer_config = get_tokenizer_config("google-bert/bert-base-uncased")
|
| 700 |
+
# This model does not have a tokenizer config so the result will be an empty dict.
|
| 701 |
+
tokenizer_config = get_tokenizer_config("FacebookAI/xlm-roberta-base")
|
| 702 |
+
|
| 703 |
+
# Save a pretrained tokenizer locally and you can reload its config
|
| 704 |
+
from transformers import AutoTokenizer
|
| 705 |
+
|
| 706 |
+
tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
|
| 707 |
+
tokenizer.save_pretrained("tokenizer-test")
|
| 708 |
+
tokenizer_config = get_tokenizer_config("tokenizer-test")
|
| 709 |
+
```"""
|
| 710 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 711 |
+
if use_auth_token is not None:
|
| 712 |
+
warnings.warn(
|
| 713 |
+
"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
|
| 714 |
+
FutureWarning,
|
| 715 |
+
)
|
| 716 |
+
if token is not None:
|
| 717 |
+
raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
|
| 718 |
+
token = use_auth_token
|
| 719 |
+
|
| 720 |
+
commit_hash = kwargs.get("_commit_hash", None)
|
| 721 |
+
resolved_config_file = cached_file(
|
| 722 |
+
pretrained_model_name_or_path,
|
| 723 |
+
TOKENIZER_CONFIG_FILE,
|
| 724 |
+
cache_dir=cache_dir,
|
| 725 |
+
force_download=force_download,
|
| 726 |
+
resume_download=resume_download,
|
| 727 |
+
proxies=proxies,
|
| 728 |
+
token=token,
|
| 729 |
+
revision=revision,
|
| 730 |
+
local_files_only=local_files_only,
|
| 731 |
+
subfolder=subfolder,
|
| 732 |
+
_raise_exceptions_for_gated_repo=False,
|
| 733 |
+
_raise_exceptions_for_missing_entries=False,
|
| 734 |
+
_raise_exceptions_for_connection_errors=False,
|
| 735 |
+
_commit_hash=commit_hash,
|
| 736 |
+
)
|
| 737 |
+
if resolved_config_file is None:
|
| 738 |
+
logger.info("Could not locate the tokenizer configuration file, will try to use the model config instead.")
|
| 739 |
+
return {}
|
| 740 |
+
commit_hash = extract_commit_hash(resolved_config_file, commit_hash)
|
| 741 |
+
|
| 742 |
+
with open(resolved_config_file, encoding="utf-8") as reader:
|
| 743 |
+
result = json.load(reader)
|
| 744 |
+
result["_commit_hash"] = commit_hash
|
| 745 |
+
return result
|
| 746 |
+
|
| 747 |
+
|
| 748 |
+
class AutoTokenizer:
|
| 749 |
+
r"""
|
| 750 |
+
This is a generic tokenizer class that will be instantiated as one of the tokenizer classes of the library when
|
| 751 |
+
created with the [`AutoTokenizer.from_pretrained`] class method.
|
| 752 |
+
|
| 753 |
+
This class cannot be instantiated directly using `__init__()` (throws an error).
|
| 754 |
+
"""
|
| 755 |
+
|
| 756 |
+
def __init__(self):
|
| 757 |
+
raise EnvironmentError(
|
| 758 |
+
"AutoTokenizer is designed to be instantiated "
|
| 759 |
+
"using the `AutoTokenizer.from_pretrained(pretrained_model_name_or_path)` method."
|
| 760 |
+
)
|
| 761 |
+
|
| 762 |
+
@classmethod
|
| 763 |
+
@replace_list_option_in_docstrings(TOKENIZER_MAPPING_NAMES)
|
| 764 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs):
|
| 765 |
+
r"""
|
| 766 |
+
Instantiate one of the tokenizer classes of the library from a pretrained model vocabulary.
|
| 767 |
+
|
| 768 |
+
The tokenizer class to instantiate is selected based on the `model_type` property of the config object (either
|
| 769 |
+
passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's missing, by
|
| 770 |
+
falling back to using pattern matching on `pretrained_model_name_or_path`:
|
| 771 |
+
|
| 772 |
+
List options
|
| 773 |
+
|
| 774 |
+
Params:
|
| 775 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 776 |
+
Can be either:
|
| 777 |
+
|
| 778 |
+
- A string, the *model id* of a predefined tokenizer hosted inside a model repo on huggingface.co.
|
| 779 |
+
- A path to a *directory* containing vocabulary files required by the tokenizer, for instance saved
|
| 780 |
+
using the [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
|
| 781 |
+
- A path or url to a single saved vocabulary file if and only if the tokenizer only requires a
|
| 782 |
+
single vocabulary file (like Bert or XLNet), e.g.: `./my_model_directory/vocab.txt`. (Not
|
| 783 |
+
applicable to all derived classes)
|
| 784 |
+
inputs (additional positional arguments, *optional*):
|
| 785 |
+
Will be passed along to the Tokenizer `__init__()` method.
|
| 786 |
+
config ([`PretrainedConfig`], *optional*)
|
| 787 |
+
The configuration object used to determine the tokenizer class to instantiate.
|
| 788 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 789 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the
|
| 790 |
+
standard cache should not be used.
|
| 791 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 792 |
+
Whether or not to force the (re-)download the model weights and configuration files and override the
|
| 793 |
+
cached versions if they exist.
|
| 794 |
+
resume_download:
|
| 795 |
+
Deprecated and ignored. All downloads are now resumed by default when possible.
|
| 796 |
+
Will be removed in v5 of Transformers.
|
| 797 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 798 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 799 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 800 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 801 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 802 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 803 |
+
identifier allowed by git.
|
| 804 |
+
subfolder (`str`, *optional*):
|
| 805 |
+
In case the relevant files are located inside a subfolder of the model repo on huggingface.co (e.g. for
|
| 806 |
+
facebook/rag-token-base), specify it here.
|
| 807 |
+
use_fast (`bool`, *optional*, defaults to `True`):
|
| 808 |
+
Use a [fast Rust-based tokenizer](https://huggingface.co/docs/tokenizers/index) if it is supported for
|
| 809 |
+
a given model. If a fast tokenizer is not available for a given model, a normal Python-based tokenizer
|
| 810 |
+
is returned instead.
|
| 811 |
+
tokenizer_type (`str`, *optional*):
|
| 812 |
+
Tokenizer type to be loaded.
|
| 813 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 814 |
+
Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
|
| 815 |
+
should only be set to `True` for repositories you trust and in which you have read the code, as it will
|
| 816 |
+
execute code present on the Hub on your local machine.
|
| 817 |
+
kwargs (additional keyword arguments, *optional*):
|
| 818 |
+
Will be passed to the Tokenizer `__init__()` method. Can be used to set special tokens like
|
| 819 |
+
`bos_token`, `eos_token`, `unk_token`, `sep_token`, `pad_token`, `cls_token`, `mask_token`,
|
| 820 |
+
`additional_special_tokens`. See parameters in the `__init__()` for more details.
|
| 821 |
+
|
| 822 |
+
Examples:
|
| 823 |
+
|
| 824 |
+
```python
|
| 825 |
+
>>> from transformers import AutoTokenizer
|
| 826 |
+
|
| 827 |
+
>>> # Download vocabulary from huggingface.co and cache.
|
| 828 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
|
| 829 |
+
|
| 830 |
+
>>> # Download vocabulary from huggingface.co (user-uploaded) and cache.
|
| 831 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("dbmdz/bert-base-german-cased")
|
| 832 |
+
|
| 833 |
+
>>> # If vocabulary files are in a directory (e.g. tokenizer was saved using *save_pretrained('./test/saved_model/')*)
|
| 834 |
+
>>> # tokenizer = AutoTokenizer.from_pretrained("./test/bert_saved_model/")
|
| 835 |
+
|
| 836 |
+
>>> # Download vocabulary from huggingface.co and define model-specific arguments
|
| 837 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/roberta-base", add_prefix_space=True)
|
| 838 |
+
```"""
|
| 839 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 840 |
+
if use_auth_token is not None:
|
| 841 |
+
warnings.warn(
|
| 842 |
+
"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
|
| 843 |
+
FutureWarning,
|
| 844 |
+
)
|
| 845 |
+
if kwargs.get("token", None) is not None:
|
| 846 |
+
raise ValueError(
|
| 847 |
+
"`token` and `use_auth_token` are both specified. Please set only the argument `token`."
|
| 848 |
+
)
|
| 849 |
+
kwargs["token"] = use_auth_token
|
| 850 |
+
|
| 851 |
+
config = kwargs.pop("config", None)
|
| 852 |
+
kwargs["_from_auto"] = True
|
| 853 |
+
|
| 854 |
+
use_fast = kwargs.pop("use_fast", True)
|
| 855 |
+
tokenizer_type = kwargs.pop("tokenizer_type", None)
|
| 856 |
+
trust_remote_code = kwargs.pop("trust_remote_code", None)
|
| 857 |
+
gguf_file = kwargs.get("gguf_file", None)
|
| 858 |
+
|
| 859 |
+
# First, let's see whether the tokenizer_type is passed so that we can leverage it
|
| 860 |
+
if tokenizer_type is not None:
|
| 861 |
+
tokenizer_class = None
|
| 862 |
+
tokenizer_class_tuple = TOKENIZER_MAPPING_NAMES.get(tokenizer_type, None)
|
| 863 |
+
|
| 864 |
+
if tokenizer_class_tuple is None:
|
| 865 |
+
raise ValueError(
|
| 866 |
+
f"Passed `tokenizer_type` {tokenizer_type} does not exist. `tokenizer_type` should be one of "
|
| 867 |
+
f"{', '.join(c for c in TOKENIZER_MAPPING_NAMES.keys())}."
|
| 868 |
+
)
|
| 869 |
+
|
| 870 |
+
tokenizer_class_name, tokenizer_fast_class_name = tokenizer_class_tuple
|
| 871 |
+
|
| 872 |
+
if use_fast:
|
| 873 |
+
if tokenizer_fast_class_name is not None:
|
| 874 |
+
tokenizer_class = tokenizer_class_from_name(tokenizer_fast_class_name)
|
| 875 |
+
else:
|
| 876 |
+
logger.warning(
|
| 877 |
+
"`use_fast` is set to `True` but the tokenizer class does not have a fast version. "
|
| 878 |
+
" Falling back to the slow version."
|
| 879 |
+
)
|
| 880 |
+
if tokenizer_class is None:
|
| 881 |
+
tokenizer_class = tokenizer_class_from_name(tokenizer_class_name)
|
| 882 |
+
|
| 883 |
+
if tokenizer_class is None:
|
| 884 |
+
raise ValueError(f"Tokenizer class {tokenizer_class_name} is not currently imported.")
|
| 885 |
+
|
| 886 |
+
return tokenizer_class.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
|
| 887 |
+
|
| 888 |
+
# Next, let's try to use the tokenizer_config file to get the tokenizer class.
|
| 889 |
+
tokenizer_config = get_tokenizer_config(pretrained_model_name_or_path, **kwargs)
|
| 890 |
+
if "_commit_hash" in tokenizer_config:
|
| 891 |
+
kwargs["_commit_hash"] = tokenizer_config["_commit_hash"]
|
| 892 |
+
config_tokenizer_class = tokenizer_config.get("tokenizer_class")
|
| 893 |
+
tokenizer_auto_map = None
|
| 894 |
+
if "auto_map" in tokenizer_config:
|
| 895 |
+
if isinstance(tokenizer_config["auto_map"], (tuple, list)):
|
| 896 |
+
# Legacy format for dynamic tokenizers
|
| 897 |
+
tokenizer_auto_map = tokenizer_config["auto_map"]
|
| 898 |
+
else:
|
| 899 |
+
tokenizer_auto_map = tokenizer_config["auto_map"].get("AutoTokenizer", None)
|
| 900 |
+
|
| 901 |
+
# If that did not work, let's try to use the config.
|
| 902 |
+
if config_tokenizer_class is None:
|
| 903 |
+
if not isinstance(config, PretrainedConfig):
|
| 904 |
+
if gguf_file:
|
| 905 |
+
gguf_path = cached_file(pretrained_model_name_or_path, gguf_file, **kwargs)
|
| 906 |
+
config_dict = load_gguf_checkpoint(gguf_path, return_tensors=False)["config"]
|
| 907 |
+
config = AutoConfig.for_model(**config_dict)
|
| 908 |
+
else:
|
| 909 |
+
config = AutoConfig.from_pretrained(
|
| 910 |
+
pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
|
| 911 |
+
)
|
| 912 |
+
config_tokenizer_class = config.tokenizer_class
|
| 913 |
+
if hasattr(config, "auto_map") and "AutoTokenizer" in config.auto_map:
|
| 914 |
+
tokenizer_auto_map = config.auto_map["AutoTokenizer"]
|
| 915 |
+
|
| 916 |
+
has_remote_code = tokenizer_auto_map is not None
|
| 917 |
+
has_local_code = type(config) in TOKENIZER_MAPPING or (
|
| 918 |
+
config_tokenizer_class is not None
|
| 919 |
+
and (
|
| 920 |
+
tokenizer_class_from_name(config_tokenizer_class) is not None
|
| 921 |
+
or tokenizer_class_from_name(config_tokenizer_class + "Fast") is not None
|
| 922 |
+
)
|
| 923 |
+
)
|
| 924 |
+
trust_remote_code = resolve_trust_remote_code(
|
| 925 |
+
trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
if has_remote_code and trust_remote_code:
|
| 929 |
+
if use_fast and tokenizer_auto_map[1] is not None:
|
| 930 |
+
class_ref = tokenizer_auto_map[1]
|
| 931 |
+
else:
|
| 932 |
+
class_ref = tokenizer_auto_map[0]
|
| 933 |
+
tokenizer_class = get_class_from_dynamic_module(class_ref, pretrained_model_name_or_path, **kwargs)
|
| 934 |
+
_ = kwargs.pop("code_revision", None)
|
| 935 |
+
if os.path.isdir(pretrained_model_name_or_path):
|
| 936 |
+
tokenizer_class.register_for_auto_class()
|
| 937 |
+
return tokenizer_class.from_pretrained(
|
| 938 |
+
pretrained_model_name_or_path, *inputs, trust_remote_code=trust_remote_code, **kwargs
|
| 939 |
+
)
|
| 940 |
+
elif config_tokenizer_class is not None:
|
| 941 |
+
tokenizer_class = None
|
| 942 |
+
if use_fast and not config_tokenizer_class.endswith("Fast"):
|
| 943 |
+
tokenizer_class_candidate = f"{config_tokenizer_class}Fast"
|
| 944 |
+
tokenizer_class = tokenizer_class_from_name(tokenizer_class_candidate)
|
| 945 |
+
if tokenizer_class is None:
|
| 946 |
+
tokenizer_class_candidate = config_tokenizer_class
|
| 947 |
+
tokenizer_class = tokenizer_class_from_name(tokenizer_class_candidate)
|
| 948 |
+
if tokenizer_class is None:
|
| 949 |
+
raise ValueError(
|
| 950 |
+
f"Tokenizer class {tokenizer_class_candidate} does not exist or is not currently imported."
|
| 951 |
+
)
|
| 952 |
+
return tokenizer_class.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
|
| 953 |
+
|
| 954 |
+
# Otherwise we have to be creative.
|
| 955 |
+
# if model is an encoder decoder, the encoder tokenizer class is used by default
|
| 956 |
+
if isinstance(config, EncoderDecoderConfig):
|
| 957 |
+
if type(config.decoder) is not type(config.encoder): # noqa: E721
|
| 958 |
+
logger.warning(
|
| 959 |
+
f"The encoder model config class: {config.encoder.__class__} is different from the decoder model "
|
| 960 |
+
f"config class: {config.decoder.__class__}. It is not recommended to use the "
|
| 961 |
+
"`AutoTokenizer.from_pretrained()` method in this case. Please use the encoder and decoder "
|
| 962 |
+
"specific tokenizer classes."
|
| 963 |
+
)
|
| 964 |
+
config = config.encoder
|
| 965 |
+
|
| 966 |
+
model_type = config_class_to_model_type(type(config).__name__)
|
| 967 |
+
if model_type is not None:
|
| 968 |
+
tokenizer_class_py, tokenizer_class_fast = TOKENIZER_MAPPING[type(config)]
|
| 969 |
+
|
| 970 |
+
if tokenizer_class_fast and (use_fast or tokenizer_class_py is None):
|
| 971 |
+
return tokenizer_class_fast.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
|
| 972 |
+
else:
|
| 973 |
+
if tokenizer_class_py is not None:
|
| 974 |
+
return tokenizer_class_py.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
|
| 975 |
+
else:
|
| 976 |
+
raise ValueError(
|
| 977 |
+
"This tokenizer cannot be instantiated. Please make sure you have `sentencepiece` installed "
|
| 978 |
+
"in order to use this tokenizer."
|
| 979 |
+
)
|
| 980 |
+
|
| 981 |
+
raise ValueError(
|
| 982 |
+
f"Unrecognized configuration class {config.__class__} to build an AutoTokenizer.\n"
|
| 983 |
+
f"Model type should be one of {', '.join(c.__name__ for c in TOKENIZER_MAPPING.keys())}."
|
| 984 |
+
)
|
| 985 |
+
|
| 986 |
+
def register(config_class, slow_tokenizer_class=None, fast_tokenizer_class=None, exist_ok=False):
|
| 987 |
+
"""
|
| 988 |
+
Register a new tokenizer in this mapping.
|
| 989 |
+
|
| 990 |
+
|
| 991 |
+
Args:
|
| 992 |
+
config_class ([`PretrainedConfig`]):
|
| 993 |
+
The configuration corresponding to the model to register.
|
| 994 |
+
slow_tokenizer_class ([`PretrainedTokenizer`], *optional*):
|
| 995 |
+
The slow tokenizer to register.
|
| 996 |
+
fast_tokenizer_class ([`PretrainedTokenizerFast`], *optional*):
|
| 997 |
+
The fast tokenizer to register.
|
| 998 |
+
"""
|
| 999 |
+
if slow_tokenizer_class is None and fast_tokenizer_class is None:
|
| 1000 |
+
raise ValueError("You need to pass either a `slow_tokenizer_class` or a `fast_tokenizer_class")
|
| 1001 |
+
if slow_tokenizer_class is not None and issubclass(slow_tokenizer_class, PreTrainedTokenizerFast):
|
| 1002 |
+
raise ValueError("You passed a fast tokenizer in the `slow_tokenizer_class`.")
|
| 1003 |
+
if fast_tokenizer_class is not None and issubclass(fast_tokenizer_class, PreTrainedTokenizer):
|
| 1004 |
+
raise ValueError("You passed a slow tokenizer in the `fast_tokenizer_class`.")
|
| 1005 |
+
|
| 1006 |
+
if (
|
| 1007 |
+
slow_tokenizer_class is not None
|
| 1008 |
+
and fast_tokenizer_class is not None
|
| 1009 |
+
and issubclass(fast_tokenizer_class, PreTrainedTokenizerFast)
|
| 1010 |
+
and fast_tokenizer_class.slow_tokenizer_class != slow_tokenizer_class
|
| 1011 |
+
):
|
| 1012 |
+
raise ValueError(
|
| 1013 |
+
"The fast tokenizer class you are passing has a `slow_tokenizer_class` attribute that is not "
|
| 1014 |
+
"consistent with the slow tokenizer class you passed (fast tokenizer has "
|
| 1015 |
+
f"{fast_tokenizer_class.slow_tokenizer_class} and you passed {slow_tokenizer_class}. Fix one of those "
|
| 1016 |
+
"so they match!"
|
| 1017 |
+
)
|
| 1018 |
+
|
| 1019 |
+
# Avoid resetting a set slow/fast tokenizer if we are passing just the other ones.
|
| 1020 |
+
if config_class in TOKENIZER_MAPPING._extra_content:
|
| 1021 |
+
existing_slow, existing_fast = TOKENIZER_MAPPING[config_class]
|
| 1022 |
+
if slow_tokenizer_class is None:
|
| 1023 |
+
slow_tokenizer_class = existing_slow
|
| 1024 |
+
if fast_tokenizer_class is None:
|
| 1025 |
+
fast_tokenizer_class = existing_fast
|
| 1026 |
+
|
| 1027 |
+
TOKENIZER_MAPPING.register(config_class, (slow_tokenizer_class, fast_tokenizer_class), exist_ok=exist_ok)
|
tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/models/aya_vision/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_aya_vision import *
|
| 22 |
+
from .modeling_aya_vision import *
|
| 23 |
+
from .processing_aya_vision import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/models/aya_vision/configuration_aya_vision.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 Cohere 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 |
+
"""AyaVision model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
from ..auto import CONFIG_MAPPING, AutoConfig
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.get_logger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class AyaVisionConfig(PretrainedConfig):
|
| 26 |
+
r"""
|
| 27 |
+
This is the configuration class to store the configuration of a [`AyaVisionForConditionalGeneration`]. It is used to instantiate an
|
| 28 |
+
AyaVision model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 29 |
+
with the defaults will yield a similar configuration to that of AyaVision.
|
| 30 |
+
e.g. [CohereForAI/aya-vision-8b](https://huggingface.co/CohereForAI/aya-vision-8b)
|
| 31 |
+
|
| 32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 33 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `CLIPVisionConfig`):
|
| 37 |
+
The config object or dictionary of the vision backbone.
|
| 38 |
+
text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `LlamaConfig`):
|
| 39 |
+
The config object or dictionary of the text backbone.
|
| 40 |
+
vision_feature_select_strategy (`str`, *optional*, defaults to `"full"`):
|
| 41 |
+
The feature selection strategy used to select the vision feature from the vision backbone.
|
| 42 |
+
Can be one of `"default"` or `"full"`. If `"default"`, the CLS token is removed from the vision features.
|
| 43 |
+
If `"full"`, the full vision features are used.
|
| 44 |
+
vision_feature_layer (`int`, *optional*, defaults to -1):
|
| 45 |
+
The index of the layer to select the vision feature.
|
| 46 |
+
downsample_factor (`int`, *optional*, defaults to 2):
|
| 47 |
+
The downsample factor to apply to the vision features.
|
| 48 |
+
adapter_layer_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 49 |
+
The epsilon value used for layer normalization in the adapter.
|
| 50 |
+
image_token_index (`int`, *optional*, defaults to 255036):
|
| 51 |
+
The image token index to encode the image prompt.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
model_type = "aya_vision"
|
| 55 |
+
sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
|
| 56 |
+
|
| 57 |
+
def __init__(
|
| 58 |
+
self,
|
| 59 |
+
vision_config=None,
|
| 60 |
+
text_config=None,
|
| 61 |
+
vision_feature_select_strategy="full",
|
| 62 |
+
vision_feature_layer=-1,
|
| 63 |
+
downsample_factor=2,
|
| 64 |
+
adapter_layer_norm_eps=1e-6,
|
| 65 |
+
image_token_index=255036,
|
| 66 |
+
**kwargs,
|
| 67 |
+
):
|
| 68 |
+
self.image_token_index = image_token_index
|
| 69 |
+
self.downsample_factor = downsample_factor
|
| 70 |
+
self.adapter_layer_norm_eps = adapter_layer_norm_eps
|
| 71 |
+
if vision_feature_select_strategy not in ["default", "full"]:
|
| 72 |
+
raise ValueError(
|
| 73 |
+
"vision_feature_select_strategy should be one of 'default', 'full'."
|
| 74 |
+
f"Got: {vision_feature_select_strategy}"
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
self.vision_feature_select_strategy = vision_feature_select_strategy
|
| 78 |
+
self.vision_feature_layer = vision_feature_layer
|
| 79 |
+
|
| 80 |
+
if isinstance(vision_config, dict):
|
| 81 |
+
vision_config["model_type"] = (
|
| 82 |
+
vision_config["model_type"] if "model_type" in vision_config else "clip_vision_model"
|
| 83 |
+
)
|
| 84 |
+
vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config)
|
| 85 |
+
elif vision_config is None:
|
| 86 |
+
vision_config = CONFIG_MAPPING["siglip_vision_model"](
|
| 87 |
+
hidden_size=1152,
|
| 88 |
+
intermediate_size=4304,
|
| 89 |
+
patch_size=14,
|
| 90 |
+
image_size=384,
|
| 91 |
+
num_hidden_layers=26,
|
| 92 |
+
num_attention_heads=14,
|
| 93 |
+
vision_use_head=False,
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
self.vision_config = vision_config
|
| 97 |
+
|
| 98 |
+
if isinstance(text_config, dict):
|
| 99 |
+
text_config["model_type"] = text_config["model_type"] if "model_type" in text_config else "llama"
|
| 100 |
+
text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
|
| 101 |
+
elif text_config is None:
|
| 102 |
+
text_config = CONFIG_MAPPING["cohere2"]()
|
| 103 |
+
|
| 104 |
+
self.text_config = text_config
|
| 105 |
+
|
| 106 |
+
super().__init__(**kwargs)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
__all__ = ["AyaVisionConfig"]
|
tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/models/aya_vision/modeling_aya_vision.py
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 the Cohere Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch AyaVision model."""
|
| 16 |
+
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from typing import List, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.utils.checkpoint
|
| 22 |
+
from torch import nn
|
| 23 |
+
|
| 24 |
+
from ...activations import ACT2FN
|
| 25 |
+
from ...generation import GenerationMixin
|
| 26 |
+
from ...modeling_outputs import ModelOutput
|
| 27 |
+
from ...modeling_utils import PreTrainedModel
|
| 28 |
+
from ...utils import (
|
| 29 |
+
add_start_docstrings,
|
| 30 |
+
add_start_docstrings_to_model_forward,
|
| 31 |
+
is_torchdynamo_compiling,
|
| 32 |
+
logging,
|
| 33 |
+
replace_return_docstrings,
|
| 34 |
+
)
|
| 35 |
+
from ..auto import AutoModel, AutoModelForCausalLM
|
| 36 |
+
from .configuration_aya_vision import AyaVisionConfig
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
logger = logging.get_logger(__name__)
|
| 40 |
+
|
| 41 |
+
_CONFIG_FOR_DOC = "AyaVisionConfig"
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# copied from transformers.models.Llava.modeling_llava.LlavaCausalLMOutputWithPast
|
| 45 |
+
@dataclass
|
| 46 |
+
class AyaVisionCausalLMOutputWithPast(ModelOutput):
|
| 47 |
+
"""
|
| 48 |
+
Base class for AyaVision causal language model (or autoregressive) outputs.
|
| 49 |
+
|
| 50 |
+
Args:
|
| 51 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 52 |
+
Language modeling loss (for next-token prediction).
|
| 53 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 54 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 55 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 56 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
| 57 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`)
|
| 58 |
+
|
| 59 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
|
| 60 |
+
`past_key_values` input) to speed up sequential decoding.
|
| 61 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 62 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 63 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 64 |
+
|
| 65 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 66 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 67 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 68 |
+
sequence_length)`.
|
| 69 |
+
|
| 70 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 71 |
+
heads.
|
| 72 |
+
image_hidden_states (`torch.FloatTensor`, *optional*):
|
| 73 |
+
A `torch.FloatTensor` of size (batch_size * num_patches, num_images, sequence_length, hidden_size)`.
|
| 74 |
+
image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
loss: Optional[torch.FloatTensor] = None
|
| 78 |
+
logits: torch.FloatTensor = None
|
| 79 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None
|
| 80 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 81 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 82 |
+
image_hidden_states: Optional[torch.FloatTensor] = None
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class AyaVisionMultiModalProjector(nn.Module):
|
| 86 |
+
def __init__(self, config: AyaVisionConfig):
|
| 87 |
+
super().__init__()
|
| 88 |
+
self.config = config
|
| 89 |
+
self.downsample_factor = config.downsample_factor
|
| 90 |
+
self.alignment_intermediate_size = getattr(
|
| 91 |
+
config, "alignment_intermediate_size", config.text_config.hidden_size
|
| 92 |
+
)
|
| 93 |
+
self.layernorm = nn.LayerNorm(
|
| 94 |
+
config.vision_config.hidden_size * (config.downsample_factor**2), eps=config.adapter_layer_norm_eps
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
self.linear_1 = nn.Linear(
|
| 98 |
+
config.vision_config.hidden_size * (config.downsample_factor**2),
|
| 99 |
+
self.alignment_intermediate_size,
|
| 100 |
+
bias=True,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
self.act = ACT2FN["silu"] # SwiGLU uses SiLU activation
|
| 104 |
+
# For SwiGLU, project down to half size since we split intermediate dim
|
| 105 |
+
self.linear_2 = nn.Linear(self.alignment_intermediate_size // 2, config.text_config.hidden_size, bias=True)
|
| 106 |
+
|
| 107 |
+
def forward(self, image_features):
|
| 108 |
+
image_features = self.pixel_shuffle(image_features)
|
| 109 |
+
image_features = self.layernorm(image_features)
|
| 110 |
+
hidden_states = self.linear_1(image_features)
|
| 111 |
+
|
| 112 |
+
# Split along last dimension and apply SwiGLU
|
| 113 |
+
x, gate = hidden_states.chunk(2, dim=-1)
|
| 114 |
+
hidden_states = self.act(gate) * x
|
| 115 |
+
|
| 116 |
+
hidden_states = self.linear_2(hidden_states)
|
| 117 |
+
return hidden_states
|
| 118 |
+
|
| 119 |
+
def pixel_shuffle(self, image_features): # B, S, D
|
| 120 |
+
batch_size, seq_length, feature_dim = image_features.shape
|
| 121 |
+
height = width = int(seq_length**0.5)
|
| 122 |
+
image_features = image_features.reshape(image_features.shape[0], width, height, -1)
|
| 123 |
+
channels = image_features.shape[-1]
|
| 124 |
+
image_features = image_features.reshape(
|
| 125 |
+
batch_size, width, int(height / self.downsample_factor), int(channels * self.downsample_factor)
|
| 126 |
+
)
|
| 127 |
+
image_features = image_features.permute(0, 2, 1, 3)
|
| 128 |
+
image_features = image_features.reshape(
|
| 129 |
+
batch_size, int(height / self.downsample_factor), int(width / self.downsample_factor), -1
|
| 130 |
+
)
|
| 131 |
+
image_features = image_features.permute(0, 2, 1, 3)
|
| 132 |
+
return image_features
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
AYA_VISION_START_DOCSTRING = r"""
|
| 136 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 137 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 138 |
+
etc.)
|
| 139 |
+
|
| 140 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 141 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 142 |
+
and behavior.
|
| 143 |
+
|
| 144 |
+
Parameters:
|
| 145 |
+
config ([`AyaVisionConfig`] or [`AyaVisionVisionConfig`]):
|
| 146 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 147 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 148 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
@add_start_docstrings(
|
| 153 |
+
"The bare Aya Vision Model outputting raw hidden-states without any specific head on top.",
|
| 154 |
+
AYA_VISION_START_DOCSTRING,
|
| 155 |
+
)
|
| 156 |
+
class AyaVisionPreTrainedModel(PreTrainedModel):
|
| 157 |
+
config_class = AyaVisionConfig
|
| 158 |
+
base_model_prefix = "model"
|
| 159 |
+
supports_gradient_checkpointing = True
|
| 160 |
+
_no_split_modules = ["AyaVisionVisionAttention"]
|
| 161 |
+
_skip_keys_device_placement = "past_key_values"
|
| 162 |
+
_supports_cache_class = True
|
| 163 |
+
_supports_flash_attn_2 = True
|
| 164 |
+
_supports_sdpa = True
|
| 165 |
+
|
| 166 |
+
def _init_weights(self, module):
|
| 167 |
+
# important: this ported version of AyaVision isn't meant for training from scratch - only
|
| 168 |
+
# inference and fine-tuning - so the proper init weights code has been removed - the original codebase
|
| 169 |
+
std = (
|
| 170 |
+
self.config.initializer_range
|
| 171 |
+
if hasattr(self.config, "initializer_range")
|
| 172 |
+
else self.config.text_config.initializer_range
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
if hasattr(module, "class_embedding"):
|
| 176 |
+
module.class_embedding.data.normal_(mean=0.0, std=std)
|
| 177 |
+
|
| 178 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 179 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 180 |
+
if module.bias is not None:
|
| 181 |
+
module.bias.data.zero_()
|
| 182 |
+
elif isinstance(module, nn.Embedding):
|
| 183 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 184 |
+
if module.padding_idx is not None:
|
| 185 |
+
module.weight.data[module.padding_idx].zero_()
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
AYA_VISION_INPUTS_DOCSTRING = r"""
|
| 189 |
+
Args:
|
| 190 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 191 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 192 |
+
it.
|
| 193 |
+
|
| 194 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 195 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 196 |
+
|
| 197 |
+
[What are input IDs?](../glossary#input-ids)
|
| 198 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
|
| 199 |
+
The tensors corresponding to the input images. Pixel values can be obtained using
|
| 200 |
+
[`AutoImageProcessor`]. See [`GotOcr2ImageProcessor.__call__`] for details. [`CohereProcessor`] uses
|
| 201 |
+
[`GotOcr2ImageProcessor`] for processing images.
|
| 202 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 203 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 204 |
+
|
| 205 |
+
- 1 for tokens that are **not masked**,
|
| 206 |
+
- 0 for tokens that are **masked**.
|
| 207 |
+
|
| 208 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 209 |
+
|
| 210 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 211 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 212 |
+
|
| 213 |
+
If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 214 |
+
`past_key_values`).
|
| 215 |
+
|
| 216 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
| 217 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
| 218 |
+
information on the default strategy.
|
| 219 |
+
|
| 220 |
+
- 1 indicates the head is **not masked**,
|
| 221 |
+
- 0 indicates the head is **masked**.
|
| 222 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 223 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 224 |
+
config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
|
| 225 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 226 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
| 227 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
|
| 228 |
+
`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
|
| 229 |
+
|
| 230 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
| 231 |
+
blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 232 |
+
|
| 233 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 234 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 235 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 236 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 237 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 238 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 239 |
+
model's internal embedding lookup matrix.
|
| 240 |
+
vision_feature_layer (`int`, *optional*, defaults to -2):
|
| 241 |
+
The index of the layer to select the vision feature.
|
| 242 |
+
vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
|
| 243 |
+
The feature selection strategy used to select the vision feature from the vision backbone.
|
| 244 |
+
Can be one of `"default"` or `"full"`. If `"default"`, the CLS token is removed from the vision features.
|
| 245 |
+
If `"full"`, the full vision features are used.
|
| 246 |
+
use_cache (`bool`, *optional*):
|
| 247 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 248 |
+
`past_key_values`).
|
| 249 |
+
output_attentions (`bool`, *optional*):
|
| 250 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 251 |
+
tensors for more detail.
|
| 252 |
+
output_hidden_states (`bool`, *optional*):
|
| 253 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 254 |
+
more detail.
|
| 255 |
+
return_dict (`bool`, *optional*):
|
| 256 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 257 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 258 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
| 259 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
| 260 |
+
the complete sequence length.
|
| 261 |
+
"""
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
@add_start_docstrings(
|
| 265 |
+
"""The AyaVision model which consists of a vision backbone and a language model.""",
|
| 266 |
+
AYA_VISION_START_DOCSTRING,
|
| 267 |
+
)
|
| 268 |
+
class AyaVisionForConditionalGeneration(AyaVisionPreTrainedModel, GenerationMixin):
|
| 269 |
+
def __init__(self, config: AyaVisionConfig):
|
| 270 |
+
super().__init__(config)
|
| 271 |
+
self.vision_tower = AutoModel.from_config(config.vision_config)
|
| 272 |
+
|
| 273 |
+
self.multi_modal_projector = AyaVisionMultiModalProjector(config)
|
| 274 |
+
|
| 275 |
+
self.vocab_size = config.text_config.vocab_size
|
| 276 |
+
self.language_model = AutoModelForCausalLM.from_config(config.text_config)
|
| 277 |
+
if self.language_model._tied_weights_keys is not None:
|
| 278 |
+
self._tied_weights_keys = [f"language_model.{key}" for key in self.language_model._tied_weights_keys]
|
| 279 |
+
|
| 280 |
+
self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
|
| 281 |
+
self.post_init()
|
| 282 |
+
|
| 283 |
+
def get_input_embeddings(self):
|
| 284 |
+
return self.language_model.get_input_embeddings()
|
| 285 |
+
|
| 286 |
+
def set_input_embeddings(self, value):
|
| 287 |
+
self.language_model.set_input_embeddings(value)
|
| 288 |
+
|
| 289 |
+
def get_output_embeddings(self):
|
| 290 |
+
return self.language_model.get_output_embeddings()
|
| 291 |
+
|
| 292 |
+
def set_output_embeddings(self, new_embeddings):
|
| 293 |
+
self.language_model.set_output_embeddings(new_embeddings)
|
| 294 |
+
|
| 295 |
+
def set_decoder(self, decoder):
|
| 296 |
+
self.language_model.set_decoder(decoder)
|
| 297 |
+
|
| 298 |
+
def get_decoder(self):
|
| 299 |
+
return self.language_model.get_decoder()
|
| 300 |
+
|
| 301 |
+
def tie_weights(self):
|
| 302 |
+
return self.language_model.tie_weights()
|
| 303 |
+
|
| 304 |
+
def resize_token_embeddings(self, new_num_tokens: Optional[int] = None, pad_to_multiple_of=None) -> nn.Embedding:
|
| 305 |
+
model_embeds = self.language_model.resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
|
| 306 |
+
# update vocab size
|
| 307 |
+
self.config.text_config.vocab_size = model_embeds.num_embeddings
|
| 308 |
+
self.vocab_size = model_embeds.num_embeddings
|
| 309 |
+
return model_embeds
|
| 310 |
+
|
| 311 |
+
def get_image_features(
|
| 312 |
+
self,
|
| 313 |
+
pixel_values: torch.FloatTensor,
|
| 314 |
+
vision_feature_layer: int,
|
| 315 |
+
vision_feature_select_strategy: str,
|
| 316 |
+
):
|
| 317 |
+
"""
|
| 318 |
+
Obtains image last hidden states from the vision tower and apply multimodal projection.
|
| 319 |
+
|
| 320 |
+
Args:
|
| 321 |
+
pixel_values (`torch.FloatTensor]` of shape `(batch_size, num_patches, channels, height, width)`)
|
| 322 |
+
The tensors corresponding to the input images.
|
| 323 |
+
vision_feature_layer (`int`):
|
| 324 |
+
The index of the layer to select the vision feature.
|
| 325 |
+
vision_feature_select_strategy (`str`):
|
| 326 |
+
The feature selection strategy used to select the vision feature from the vision backbone.
|
| 327 |
+
Can be one of `"default"` or `"full"`
|
| 328 |
+
Returns:
|
| 329 |
+
image_features (List[`torch.Tensor`]): List of image feature tensor, each contains all the visual feature of all patches
|
| 330 |
+
and are of shape `(num_patches, image_length, embed_dim)`).
|
| 331 |
+
"""
|
| 332 |
+
|
| 333 |
+
image_features = self.vision_tower(pixel_values, output_hidden_states=True)
|
| 334 |
+
selected_image_feature = image_features.hidden_states[vision_feature_layer]
|
| 335 |
+
if vision_feature_select_strategy == "default":
|
| 336 |
+
selected_image_feature = selected_image_feature[:, 1:]
|
| 337 |
+
elif vision_feature_select_strategy == "full":
|
| 338 |
+
selected_image_feature = selected_image_feature
|
| 339 |
+
image_features = self.multi_modal_projector(selected_image_feature)
|
| 340 |
+
|
| 341 |
+
return image_features
|
| 342 |
+
|
| 343 |
+
@add_start_docstrings_to_model_forward(AYA_VISION_INPUTS_DOCSTRING)
|
| 344 |
+
@replace_return_docstrings(output_type=AyaVisionCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
| 345 |
+
def forward(
|
| 346 |
+
self,
|
| 347 |
+
input_ids: torch.LongTensor = None,
|
| 348 |
+
pixel_values: torch.FloatTensor = None,
|
| 349 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 350 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 351 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 352 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 353 |
+
vision_feature_layer: Optional[int] = None,
|
| 354 |
+
vision_feature_select_strategy: Optional[str] = None,
|
| 355 |
+
labels: Optional[torch.LongTensor] = None,
|
| 356 |
+
use_cache: Optional[bool] = None,
|
| 357 |
+
output_attentions: Optional[bool] = None,
|
| 358 |
+
output_hidden_states: Optional[bool] = None,
|
| 359 |
+
return_dict: Optional[bool] = None,
|
| 360 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 361 |
+
last_cache_position: int = 0,
|
| 362 |
+
num_logits_to_keep: int = 0,
|
| 363 |
+
**lm_kwargs,
|
| 364 |
+
) -> Union[Tuple, AyaVisionCausalLMOutputWithPast]:
|
| 365 |
+
r"""
|
| 366 |
+
Args:
|
| 367 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 368 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 369 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 370 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 371 |
+
|
| 372 |
+
num_logits_to_keep (`int`, *optional*):
|
| 373 |
+
Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
|
| 374 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
| 375 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
| 376 |
+
|
| 377 |
+
Returns:
|
| 378 |
+
"""
|
| 379 |
+
|
| 380 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 381 |
+
output_hidden_states = (
|
| 382 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 383 |
+
)
|
| 384 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 385 |
+
vision_feature_layer = (
|
| 386 |
+
vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
|
| 387 |
+
)
|
| 388 |
+
vision_feature_select_strategy = (
|
| 389 |
+
vision_feature_select_strategy
|
| 390 |
+
if vision_feature_select_strategy is not None
|
| 391 |
+
else self.config.vision_feature_select_strategy
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 395 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 396 |
+
|
| 397 |
+
if pixel_values is not None and inputs_embeds is not None:
|
| 398 |
+
raise ValueError(
|
| 399 |
+
"You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
if inputs_embeds is None:
|
| 403 |
+
inputs_embeds = self.get_input_embeddings()(input_ids)
|
| 404 |
+
|
| 405 |
+
if pixel_values is not None:
|
| 406 |
+
image_features = self.get_image_features(
|
| 407 |
+
pixel_values=pixel_values,
|
| 408 |
+
vision_feature_layer=vision_feature_layer,
|
| 409 |
+
vision_feature_select_strategy=vision_feature_select_strategy,
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
|
| 413 |
+
special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
|
| 414 |
+
if not is_torchdynamo_compiling() and inputs_embeds[special_image_mask].numel() != image_features.numel():
|
| 415 |
+
n_image_tokens = (input_ids == self.config.image_token_index).sum()
|
| 416 |
+
n_image_features = image_features.shape[0] * image_features.shape[1]
|
| 417 |
+
raise ValueError(
|
| 418 |
+
f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
|
| 419 |
+
)
|
| 420 |
+
image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
|
| 421 |
+
inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
|
| 422 |
+
|
| 423 |
+
outputs = self.language_model(
|
| 424 |
+
attention_mask=attention_mask,
|
| 425 |
+
position_ids=position_ids,
|
| 426 |
+
past_key_values=past_key_values,
|
| 427 |
+
inputs_embeds=inputs_embeds,
|
| 428 |
+
use_cache=use_cache,
|
| 429 |
+
output_attentions=output_attentions,
|
| 430 |
+
output_hidden_states=output_hidden_states,
|
| 431 |
+
return_dict=return_dict,
|
| 432 |
+
cache_position=cache_position,
|
| 433 |
+
last_cache_position=last_cache_position,
|
| 434 |
+
num_logits_to_keep=num_logits_to_keep,
|
| 435 |
+
logits_to_keep=0,
|
| 436 |
+
**lm_kwargs,
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
logits = outputs[0]
|
| 440 |
+
|
| 441 |
+
loss = None
|
| 442 |
+
if labels is not None:
|
| 443 |
+
# Shift so that tokens < n predict n
|
| 444 |
+
if attention_mask is not None:
|
| 445 |
+
# we use the input attention mask to shift the logits and labels, because it is 2D.
|
| 446 |
+
# we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
|
| 447 |
+
shift_attention_mask = attention_mask[:, -(logits.shape[1] - 1) :].to(logits.device)
|
| 448 |
+
shift_logits = logits[..., :-1, :][shift_attention_mask.to(logits.device) != 0].contiguous()
|
| 449 |
+
shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous()
|
| 450 |
+
else:
|
| 451 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 452 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 453 |
+
# Flatten the tokens
|
| 454 |
+
loss_fct = nn.CrossEntropyLoss()
|
| 455 |
+
loss = loss_fct(
|
| 456 |
+
shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1).to(shift_logits.device)
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
if not return_dict:
|
| 460 |
+
output = (logits,) + outputs[1:]
|
| 461 |
+
return (loss,) + output if loss is not None else output
|
| 462 |
+
|
| 463 |
+
return AyaVisionCausalLMOutputWithPast(
|
| 464 |
+
loss=loss,
|
| 465 |
+
logits=logits,
|
| 466 |
+
past_key_values=outputs.past_key_values,
|
| 467 |
+
hidden_states=outputs.hidden_states,
|
| 468 |
+
attentions=outputs.attentions,
|
| 469 |
+
image_hidden_states=image_features if pixel_values is not None else None,
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
def prepare_inputs_for_generation(
|
| 473 |
+
self,
|
| 474 |
+
input_ids,
|
| 475 |
+
past_key_values=None,
|
| 476 |
+
inputs_embeds=None,
|
| 477 |
+
pixel_values=None,
|
| 478 |
+
attention_mask=None,
|
| 479 |
+
cache_position=None,
|
| 480 |
+
num_logits_to_keep=None,
|
| 481 |
+
**kwargs,
|
| 482 |
+
):
|
| 483 |
+
# Overwritten -- in specific circumstances we don't want to forward image inputs to the model
|
| 484 |
+
|
| 485 |
+
model_inputs = self.language_model.prepare_inputs_for_generation(
|
| 486 |
+
input_ids,
|
| 487 |
+
past_key_values=past_key_values,
|
| 488 |
+
inputs_embeds=inputs_embeds,
|
| 489 |
+
attention_mask=attention_mask,
|
| 490 |
+
cache_position=cache_position,
|
| 491 |
+
num_logits_to_keep=num_logits_to_keep,
|
| 492 |
+
**kwargs,
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
# If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
|
| 496 |
+
# Otherwise we need pixel values to be passed to model
|
| 497 |
+
if cache_position[0] == 0:
|
| 498 |
+
model_inputs["pixel_values"] = pixel_values
|
| 499 |
+
|
| 500 |
+
return model_inputs
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
__all__ = ["AyaVisionForConditionalGeneration", "AyaVisionPreTrainedModel"]
|
tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/models/aya_vision/processing_aya_vision.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
from typing import List, Optional, Union
|
| 18 |
+
|
| 19 |
+
from transformers.processing_utils import (
|
| 20 |
+
ImagesKwargs,
|
| 21 |
+
ProcessingKwargs,
|
| 22 |
+
ProcessorMixin,
|
| 23 |
+
Unpack,
|
| 24 |
+
)
|
| 25 |
+
from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
|
| 26 |
+
|
| 27 |
+
from ...image_processing_utils import BatchFeature
|
| 28 |
+
from ...image_utils import (
|
| 29 |
+
ImageInput,
|
| 30 |
+
make_flat_list_of_images,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class AyaVisionImagesKwargs(ImagesKwargs, total=False):
|
| 35 |
+
crop_to_patches: Optional[bool]
|
| 36 |
+
min_patches: Optional[int]
|
| 37 |
+
max_patches: Optional[int]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class AyaVisionProcessorKwargs(ProcessingKwargs, total=False):
|
| 41 |
+
images_kwargs: AyaVisionImagesKwargs
|
| 42 |
+
_defaults = {
|
| 43 |
+
"text_kwargs": {
|
| 44 |
+
"padding_side": "left",
|
| 45 |
+
"padding": True,
|
| 46 |
+
},
|
| 47 |
+
"images_kwargs": {
|
| 48 |
+
"crop_to_patches": True,
|
| 49 |
+
},
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class AyaVisionProcessor(ProcessorMixin):
|
| 54 |
+
r"""
|
| 55 |
+
Constructs a AyaVision processor which wraps a [`AutoImageProcessor`] and
|
| 56 |
+
[`PretrainedTokenizerFast`] tokenizer into a single processor that inherits both the image processor and
|
| 57 |
+
tokenizer functionalities. See the [`~AyaVisionProcessor.__call__`] and [`~AyaVisionProcessor.decode`] for more information.
|
| 58 |
+
Args:
|
| 59 |
+
image_processor ([`AutoImageProcessor`], *optional*):
|
| 60 |
+
The image processor is a required input.
|
| 61 |
+
tokenizer ([`PreTrainedTokenizer`, `PreTrainedTokenizerFast`], *optional*):
|
| 62 |
+
The tokenizer is a required input.
|
| 63 |
+
patch_size (`int`, *optional*, defaults to 28):
|
| 64 |
+
The size of image patches for tokenization.
|
| 65 |
+
img_size (`int`, *optional*, defaults to 364):
|
| 66 |
+
The size of the image to be tokenized. This should correspond to the size given to the image processor.
|
| 67 |
+
vision_feature_select_strategy (`str`, *optional*, defaults to `"full"`):
|
| 68 |
+
The feature selection strategy used to select the vision feature from the vision backbone.
|
| 69 |
+
image_token (`str`, *optional*, defaults to `"<image>"`):
|
| 70 |
+
The token to be used to represent an image in the text.
|
| 71 |
+
downsample_factor (`int`, *optional*, defaults to 1):
|
| 72 |
+
The factor by which to scale the patch size.
|
| 73 |
+
start_of_img_token (`str`, *optional*, defaults to `"<|START_OF_IMG|>"`):
|
| 74 |
+
The token to be used to represent the start of an image in the text.
|
| 75 |
+
end_of_img_token (`str`, *optional*, defaults to `"<|END_OF_IMG|>"`):
|
| 76 |
+
The token to be used to represent the end of an image in the text.
|
| 77 |
+
img_patch_token (`str`, *optional*, defaults to `"<|IMG_PATCH|>"`):
|
| 78 |
+
The token to be used to represent an image patch in the text.
|
| 79 |
+
img_line_break_token (`str`, *optional*, defaults to `"<|IMG_LINE_BREAK|>"`):
|
| 80 |
+
The token to be used to represent a line break in the text.
|
| 81 |
+
tile_token (`str`, *optional*, defaults to `"TILE"`):
|
| 82 |
+
The token to be used to represent an image patch in the text.
|
| 83 |
+
tile_global_token (`str`, *optional*, defaults to `"TILE_GLOBAL"`):
|
| 84 |
+
The token to be used to represent the cover image in the text.
|
| 85 |
+
chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
|
| 86 |
+
in a chat into a tokenizable string.
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
attributes = ["image_processor", "tokenizer"]
|
| 90 |
+
valid_kwargs = [
|
| 91 |
+
"chat_template",
|
| 92 |
+
"image_token",
|
| 93 |
+
"patch_size",
|
| 94 |
+
"img_size",
|
| 95 |
+
"downsample_factor",
|
| 96 |
+
"vision_feature_select_strategy",
|
| 97 |
+
"start_of_img_token",
|
| 98 |
+
"end_of_img_token",
|
| 99 |
+
"img_patch_token",
|
| 100 |
+
"img_line_break_token",
|
| 101 |
+
"tile_token",
|
| 102 |
+
"tile_global_token",
|
| 103 |
+
]
|
| 104 |
+
image_processor_class = "AutoImageProcessor"
|
| 105 |
+
tokenizer_class = "AutoTokenizer"
|
| 106 |
+
|
| 107 |
+
def __init__(
|
| 108 |
+
self,
|
| 109 |
+
image_processor=None,
|
| 110 |
+
tokenizer=None,
|
| 111 |
+
patch_size: int = 28,
|
| 112 |
+
img_size: int = 364,
|
| 113 |
+
vision_feature_select_strategy="full",
|
| 114 |
+
image_token="<image>", # set the default and let users change if they have peculiar special tokens in rare cases
|
| 115 |
+
downsample_factor: int = 1,
|
| 116 |
+
start_of_img_token="<|START_OF_IMG|>",
|
| 117 |
+
end_of_img_token="<|END_OF_IMG|>",
|
| 118 |
+
img_patch_token="<|IMG_PATCH|>",
|
| 119 |
+
img_line_break_token="<|IMG_LINE_BREAK|>",
|
| 120 |
+
tile_token="TILE",
|
| 121 |
+
tile_global_token="TILE_GLOBAL",
|
| 122 |
+
chat_template=None,
|
| 123 |
+
**kwargs,
|
| 124 |
+
):
|
| 125 |
+
super().__init__(image_processor, tokenizer, chat_template=chat_template)
|
| 126 |
+
|
| 127 |
+
self.image_token = image_token
|
| 128 |
+
self.patch_size = patch_size * downsample_factor
|
| 129 |
+
self.img_size = img_size
|
| 130 |
+
self.vision_feature_select_strategy = vision_feature_select_strategy
|
| 131 |
+
|
| 132 |
+
self.start_of_img_token = start_of_img_token
|
| 133 |
+
self.end_of_img_token = end_of_img_token
|
| 134 |
+
self.img_patch_token = img_patch_token
|
| 135 |
+
self.img_line_break_token = img_line_break_token
|
| 136 |
+
self.tile_token = tile_token
|
| 137 |
+
self.tile_global_token = tile_global_token
|
| 138 |
+
|
| 139 |
+
def _prompt_split_image(self, num_patches):
|
| 140 |
+
"""
|
| 141 |
+
Create a structured string representation of image tokens
|
| 142 |
+
|
| 143 |
+
Args:
|
| 144 |
+
num_patches: Number of patches in the image
|
| 145 |
+
|
| 146 |
+
Returns:
|
| 147 |
+
String with appropriate image tokens
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
img_patches_per_tile = (self.img_size // self.patch_size) ** 2
|
| 151 |
+
img_string = f"{self.start_of_img_token}"
|
| 152 |
+
if num_patches > 1:
|
| 153 |
+
for idx in range(1, num_patches):
|
| 154 |
+
img_string += f"{self.tile_token}_{idx}" + f"{self.img_patch_token}" * img_patches_per_tile
|
| 155 |
+
|
| 156 |
+
img_string += f"{self.tile_global_token}" + f"{self.img_patch_token}" * img_patches_per_tile
|
| 157 |
+
img_string += f"{self.end_of_img_token}"
|
| 158 |
+
return img_string
|
| 159 |
+
|
| 160 |
+
def __call__(
|
| 161 |
+
self,
|
| 162 |
+
images: Optional[ImageInput] = None,
|
| 163 |
+
text: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None,
|
| 164 |
+
audio=None,
|
| 165 |
+
videos=None,
|
| 166 |
+
**kwargs: Unpack[AyaVisionProcessorKwargs],
|
| 167 |
+
) -> BatchFeature:
|
| 168 |
+
"""
|
| 169 |
+
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
|
| 170 |
+
and `kwargs` arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizerFast.__call__`] to encode the text.
|
| 171 |
+
To prepare the vision inputs, this method forwards the `images` and `kwargs` arguments to
|
| 172 |
+
GotOcr2ImageProcessor's [`~GotOcr2ImageProcessor.__call__`] if `images` is not `None`.
|
| 173 |
+
|
| 174 |
+
Args:
|
| 175 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
| 176 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 177 |
+
tensor. Both channels-first and channels-last formats are supported.
|
| 178 |
+
text (`str`, `List[str]`, `List[List[str]]`):
|
| 179 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
| 180 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 181 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 182 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 183 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 184 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 185 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 186 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 187 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
| 188 |
+
|
| 189 |
+
Returns:
|
| 190 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 191 |
+
|
| 192 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
| 193 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 194 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 195 |
+
`None`).
|
| 196 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 197 |
+
"""
|
| 198 |
+
if text is None:
|
| 199 |
+
raise ValueError("You have to specify text.")
|
| 200 |
+
|
| 201 |
+
output_kwargs = self._merge_kwargs(
|
| 202 |
+
AyaVisionProcessorKwargs,
|
| 203 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 204 |
+
**kwargs,
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
if not isinstance(text, (list, tuple)):
|
| 208 |
+
text = [text]
|
| 209 |
+
|
| 210 |
+
# Process images
|
| 211 |
+
image_inputs = {}
|
| 212 |
+
if images is not None:
|
| 213 |
+
images = make_flat_list_of_images(images)
|
| 214 |
+
image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
|
| 215 |
+
num_patches = image_inputs.pop("num_patches")
|
| 216 |
+
image_index = 0
|
| 217 |
+
img_start_idx = 0
|
| 218 |
+
processed_text = []
|
| 219 |
+
image_num_patches = []
|
| 220 |
+
for prompt in text:
|
| 221 |
+
new_prompt = prompt
|
| 222 |
+
curr_num_image_patches = 0
|
| 223 |
+
while "<image>" in new_prompt:
|
| 224 |
+
# Replace the image placeholder with structured image tokens
|
| 225 |
+
image_tokens = self._prompt_split_image(num_patches[image_index])
|
| 226 |
+
new_prompt = new_prompt.replace("<image>", image_tokens, 1)
|
| 227 |
+
curr_num_image_patches += num_patches[image_index]
|
| 228 |
+
image_index += 1
|
| 229 |
+
|
| 230 |
+
processed_text.append(new_prompt)
|
| 231 |
+
image_num_patches.append(curr_num_image_patches.item())
|
| 232 |
+
img_start_idx += curr_num_image_patches
|
| 233 |
+
|
| 234 |
+
if image_index != len(images):
|
| 235 |
+
raise ValueError("Number of image placeholders in the prompt does not match the number of images.")
|
| 236 |
+
|
| 237 |
+
text = processed_text
|
| 238 |
+
|
| 239 |
+
text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
|
| 240 |
+
|
| 241 |
+
return BatchFeature(data={**text_inputs, **image_inputs})
|
| 242 |
+
|
| 243 |
+
def batch_decode(self, *args, **kwargs):
|
| 244 |
+
"""
|
| 245 |
+
This method forwards all its arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
|
| 246 |
+
refer to the docstring of this method for more information.
|
| 247 |
+
"""
|
| 248 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
| 249 |
+
|
| 250 |
+
def decode(self, *args, **kwargs):
|
| 251 |
+
"""
|
| 252 |
+
This method forwards all its arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
|
| 253 |
+
the docstring of this method for more information.
|
| 254 |
+
"""
|
| 255 |
+
return self.tokenizer.decode(*args, **kwargs)
|
| 256 |
+
|
| 257 |
+
@property
|
| 258 |
+
def model_input_names(self):
|
| 259 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
| 260 |
+
image_processor_input_names = self.image_processor.model_input_names
|
| 261 |
+
return list(tokenizer_input_names) + list(image_processor_input_names)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
__all__ = ["AyaVisionProcessor"]
|
tasks/tasksmith-e0f68dd4420c/solution/reference/src/transformers/utils/dummy_pt_objects.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-e0f68dd4420c/solution/solve.sh
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/sh
|
| 2 |
+
set -eu
|
| 3 |
+
mkdir -p -- /workspace/src/transformers
|
| 4 |
+
cp /solution/reference/src/transformers/__init__.py /workspace/src/transformers/__init__.py
|
| 5 |
+
mkdir -p -- /workspace/src/transformers/models
|
| 6 |
+
cp /solution/reference/src/transformers/models/__init__.py /workspace/src/transformers/models/__init__.py
|
| 7 |
+
mkdir -p -- /workspace/src/transformers/models/auto
|
| 8 |
+
cp /solution/reference/src/transformers/models/auto/configuration_auto.py /workspace/src/transformers/models/auto/configuration_auto.py
|
| 9 |
+
mkdir -p -- /workspace/src/transformers/models/auto
|
| 10 |
+
cp /solution/reference/src/transformers/models/auto/modeling_auto.py /workspace/src/transformers/models/auto/modeling_auto.py
|
| 11 |
+
mkdir -p -- /workspace/src/transformers/models/auto
|
| 12 |
+
cp /solution/reference/src/transformers/models/auto/processing_auto.py /workspace/src/transformers/models/auto/processing_auto.py
|
| 13 |
+
mkdir -p -- /workspace/src/transformers/models/auto
|
| 14 |
+
cp /solution/reference/src/transformers/models/auto/tokenization_auto.py /workspace/src/transformers/models/auto/tokenization_auto.py
|
| 15 |
+
mkdir -p -- /workspace/src/transformers/models/aya_vision
|
| 16 |
+
cp /solution/reference/src/transformers/models/aya_vision/__init__.py /workspace/src/transformers/models/aya_vision/__init__.py
|
| 17 |
+
mkdir -p -- /workspace/src/transformers/models/aya_vision
|
| 18 |
+
cp /solution/reference/src/transformers/models/aya_vision/configuration_aya_vision.py /workspace/src/transformers/models/aya_vision/configuration_aya_vision.py
|
| 19 |
+
mkdir -p -- /workspace/src/transformers/models/aya_vision
|
| 20 |
+
cp /solution/reference/src/transformers/models/aya_vision/modeling_aya_vision.py /workspace/src/transformers/models/aya_vision/modeling_aya_vision.py
|
| 21 |
+
mkdir -p -- /workspace/src/transformers/models/aya_vision
|
| 22 |
+
cp /solution/reference/src/transformers/models/aya_vision/processing_aya_vision.py /workspace/src/transformers/models/aya_vision/processing_aya_vision.py
|
| 23 |
+
mkdir -p -- /workspace/src/transformers/utils
|
| 24 |
+
cp /solution/reference/src/transformers/utils/dummy_pt_objects.py /workspace/src/transformers/utils/dummy_pt_objects.py
|
tasks/tasksmith-e0f68dd4420c/task.toml
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version = "1.3"
|
| 2 |
+
|
| 3 |
+
[task]
|
| 4 |
+
name = "repo2rlenv/tasksmith-e0f68dd4420c"
|
| 5 |
+
|
| 6 |
+
[metadata.repo2env]
|
| 7 |
+
recipe = "tasksmith"
|
| 8 |
+
recipe_version = "1"
|
| 9 |
+
source_url = "https://github.com/huggingface/transformers/pull/36521"
|
| 10 |
+
source_head = "ce63421c42ff8e63a8a12d4fe8caf47d524a7ac1"
|
| 11 |
+
source_base = "c0f8d055ce7a218e041e20a06946bf0baa8a7d6a"
|
| 12 |
+
workspace_strategy = "head_minus_source_patch"
|
| 13 |
+
source_diff_sha256 = "6aa39f9f92c3c0eab25a1c7cdd17f53de6e322f860a4bdeee1820cd7bdc68304"
|
| 14 |
+
acceptance_profile = "practical-generation-v1"
|
| 15 |
+
upstream_test_policy = "replace"
|
| 16 |
+
reward_kinds = [
|
| 17 |
+
"test_execution",
|
| 18 |
+
]
|
| 19 |
+
quality_status = "exported"
|
| 20 |
+
fail_to_pass_count = 11
|
| 21 |
+
pass_to_pass_count = 1
|
| 22 |
+
bundle_hash = "sha256:468fa3e7ed8d1fc91c6009bc1a09237590061ce70e5d2cf49a32e330697adcf8"
|
| 23 |
+
|
| 24 |
+
[metadata.repo2env.evaluation]
|
| 25 |
+
schema_version = "1"
|
| 26 |
+
status = "verified"
|
| 27 |
+
stage = "complete"
|
| 28 |
+
reason_codes = [
|
| 29 |
+
"quality_verified",
|
| 30 |
+
]
|
| 31 |
+
detail = "Reviewed controls, semantic probes and blind rollout passed the quality profile."
|
| 32 |
+
checked_at = "2026-09-14T05:21:23.146418Z"
|
| 33 |
+
provenance = "assisted"
|
| 34 |
+
subject_bundle_hash = "sha256:468fa3e7ed8d1fc91c6009bc1a09237590061ce70e5d2cf49a32e330697adcf8"
|
| 35 |
+
profile = "practical-generation-v1"
|
| 36 |
+
source_task_path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v8/candidates/9fedd08d88fd/candidates/e0f68dd4420c/quality/revisions/r0/tasksmith-e0f68dd4420c"
|
| 37 |
+
source_task_toml_sha256 = "32a4029a0229e0dc106b6a585713a16ee6c50705da9801d4909643cdd71100b7"
|
| 38 |
+
|
| 39 |
+
[[metadata.repo2env.evaluation.evidence]]
|
| 40 |
+
kind = "quality_result"
|
| 41 |
+
path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v8/candidates/9fedd08d88fd/candidates/e0f68dd4420c/quality/result.json"
|
| 42 |
+
sha256 = "4035f0daa1ed778fdb094ee8dbe1d07ef4f3badfa5cadd81a26a111b24dd7ccb"
|
| 43 |
+
subject_bundle_hash = "sha256:468fa3e7ed8d1fc91c6009bc1a09237590061ce70e5d2cf49a32e330697adcf8"
|
| 44 |
+
|
| 45 |
+
[[metadata.repo2env.evaluation.evidence]]
|
| 46 |
+
kind = "baseline"
|
| 47 |
+
path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v8/candidates/9fedd08d88fd/candidates/e0f68dd4420c/quality/trials/r0-baseline/tsbatch-63b11d77dad4-9fedd08d88fd-q-e0f68dd4-r0-baseline/tasksmith-e0f68dd4420c__ZFzW7x3/result.json"
|
| 48 |
+
sha256 = "72c205e1a6c2be10416041ce64a5cc9f53d82860eb7b36bec8cc647a66ddeb95"
|
| 49 |
+
subject_bundle_hash = "sha256:468fa3e7ed8d1fc91c6009bc1a09237590061ce70e5d2cf49a32e330697adcf8"
|
| 50 |
+
harbor_task_checksum = "bf9ff018c0b3b642a01c256b9b6186b88f7efe32fca53c4aedc4429bc5c3f80d"
|
| 51 |
+
|
| 52 |
+
[[metadata.repo2env.evaluation.evidence]]
|
| 53 |
+
kind = "oracle"
|
| 54 |
+
path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v8/candidates/9fedd08d88fd/candidates/e0f68dd4420c/quality/trials/r0-oracle/tsbatch-63b11d77dad4-9fedd08d88fd-q-e0f68dd4-r0-oracle/tasksmith-e0f68dd4420c__A475ycC/result.json"
|
| 55 |
+
sha256 = "00297a6cc8bc6df85db9bce6836126a908869869dff74420e85e2048536345b4"
|
| 56 |
+
subject_bundle_hash = "sha256:468fa3e7ed8d1fc91c6009bc1a09237590061ce70e5d2cf49a32e330697adcf8"
|
| 57 |
+
harbor_task_checksum = "bf9ff018c0b3b642a01c256b9b6186b88f7efe32fca53c4aedc4429bc5c3f80d"
|
| 58 |
+
|
| 59 |
+
[[metadata.repo2env.evaluation.evidence]]
|
| 60 |
+
kind = "probe"
|
| 61 |
+
path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v8/candidates/9fedd08d88fd/candidates/e0f68dd4420c/quality/trials/r0-probe0/tsbatch-63b11d77dad4-9fedd08d88fd-q-e0f68dd4-r0-probe0/tasksmith-e0f68dd4420c__2sBczfo/result.json"
|
| 62 |
+
sha256 = "7e173adc2400e2353fe8ae76d86cefaef6a1136c71823b25b64a42a4c489aac4"
|
| 63 |
+
subject_bundle_hash = "sha256:9b26bc84fbe157776ff22ac335e89cd13dd97df93025263ff68b657a676b82b3"
|
| 64 |
+
harbor_task_checksum = "52a9574a3a72b5dd12c33174bfd29385faa75284f0bca4052eb9d11cfed0ffb2"
|
| 65 |
+
|
| 66 |
+
[[metadata.repo2env.evaluation.evidence]]
|
| 67 |
+
kind = "probe"
|
| 68 |
+
path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v8/candidates/9fedd08d88fd/candidates/e0f68dd4420c/quality/trials/r0-probe1/tsbatch-63b11d77dad4-9fedd08d88fd-q-e0f68dd4-r0-probe1/tasksmith-e0f68dd4420c__thGmJQ4/result.json"
|
| 69 |
+
sha256 = "88efdff37d1f89123cc3a50edbe9eb05ab4a6313109bc4a4ffe77f1b499a3bf7"
|
| 70 |
+
subject_bundle_hash = "sha256:e7b9778fbab95a31df48d6c2490a9fed5fed5d10c71c448b496d9176c7cb346e"
|
| 71 |
+
harbor_task_checksum = "7b67ea257d2a3e2c2eb680ac10953acbda6821fc2db223c583de556da341ebbb"
|
| 72 |
+
|
| 73 |
+
[[metadata.repo2env.evaluation.evidence]]
|
| 74 |
+
kind = "rollout"
|
| 75 |
+
path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v8/candidates/9fedd08d88fd/candidates/e0f68dd4420c/quality/trials/r0-rollout/tsbatch-63b11d77dad4-9fedd08d88fd-q-e0f68dd4-r0-rollout/tasksmith-e0f68dd4420c__7okb4r3/result.json"
|
| 76 |
+
sha256 = "50fc69a57b0e720f9ad893a94e59ac7ecae0ebe3cd926655fc130375bbdfb55f"
|
| 77 |
+
subject_bundle_hash = "sha256:468fa3e7ed8d1fc91c6009bc1a09237590061ce70e5d2cf49a32e330697adcf8"
|
| 78 |
+
harbor_task_checksum = "bf9ff018c0b3b642a01c256b9b6186b88f7efe32fca53c4aedc4429bc5c3f80d"
|
| 79 |
+
|
| 80 |
+
[metadata.repo2env.quality_requirements]
|
| 81 |
+
probe_focus = [
|
| 82 |
+
"model_behavior",
|
| 83 |
+
]
|
| 84 |
+
|
| 85 |
+
[environment]
|
| 86 |
+
cpus = 1
|
| 87 |
+
memory_mb = 2048
|
| 88 |
+
build_timeout_sec = 600
|
| 89 |
+
network_mode = "no-network"
|
| 90 |
+
|
| 91 |
+
[agent]
|
| 92 |
+
timeout_sec = 600
|
| 93 |
+
user = "learner"
|
| 94 |
+
network_mode = "no-network"
|
| 95 |
+
|
| 96 |
+
[verifier]
|
| 97 |
+
timeout_sec = 330
|
| 98 |
+
user = "root"
|
| 99 |
+
network_mode = "no-network"
|
| 100 |
+
environment_mode = "separate"
|
| 101 |
+
|
| 102 |
+
[verifier.environment]
|
| 103 |
+
network_mode = "no-network"
|
| 104 |
+
cpus = 1
|
| 105 |
+
memory_mb = 2048
|
| 106 |
+
|
| 107 |
+
[[artifacts]]
|
| 108 |
+
source = "/workspace/src/transformers"
|
| 109 |
+
exclude = [
|
| 110 |
+
"__pycache__",
|
| 111 |
+
"*.pyc",
|
| 112 |
+
".pytest_cache",
|
| 113 |
+
]
|
tasks/tasksmith-e0f68dd4420c/tests/Dockerfile
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.12-slim
|
| 2 |
+
WORKDIR /workspace
|
| 3 |
+
RUN python -m pip install --no-cache-dir torch==2.11.0+cpu --extra-index-url https://download.pytorch.org/whl/cpu numpy==2.5.3 packaging==26.3 parameterized==0.9.0 pytest==8.4.2 setuptools==78.1.0 wheel==0.48.0 tokenizers==0.21.4 huggingface-hub==0.28.1 safetensors==0.5.3 regex==2026.9.10 requests==2.34.2 filelock==3.32.6 Pillow==12.3.0 tqdm==4.70.1 PyYAML==6.0.3 certifi==2026.7.22 charset-normalizer==3.5.1 idna==3.19 urllib3==2.7.0 typing_extensions==4.16.0 datasets==2.21.0 dill==0.3.8 multiprocess==0.70.16 xxhash==4.0.1 pyarrow==25.0.1 fsspec==2024.6.1 pandas==3.0.5 python-dateutil==2.9.0.post0 six==1.17.0 aiohappyeyeballs==2.7.1 aiohttp==3.14.3 aiosignal==1.4.0 attrs==26.1.0 frozenlist==1.8.0 multidict==6.8.0 propcache==0.5.2 yarl==1.24.5
|
| 4 |
+
COPY source /workspace
|
| 5 |
+
RUN python -m pip install --no-cache-dir --no-deps --no-build-isolation -e .
|
| 6 |
+
ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
|
| 7 |
+
ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
|
| 8 |
+
RUN useradd -m -u 1001 grader
|
| 9 |
+
COPY grade.py test_driver.py test_results.py contract.json test.sh /tests/
|
| 10 |
+
RUN chmod 755 /tests && chmod 644 /tests/*
|
tasks/tasksmith-e0f68dd4420c/tests/contract.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-e0f68dd4420c/tests/grade.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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Submitted Python
|
| 4 |
+
runs as an unprivileged user; this parent owns the result parser and reward file.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import hashlib
|
| 10 |
+
import importlib.util
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import signal
|
| 14 |
+
import stat
|
| 15 |
+
import subprocess
|
| 16 |
+
import sys
|
| 17 |
+
import tempfile
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def child_environment(temporary: str) -> dict[str, str]:
|
| 22 |
+
"""Preserve prepared runtime assets without inheriting controller credentials."""
|
| 23 |
+
return {
|
| 24 |
+
**{
|
| 25 |
+
key: os.environ[key]
|
| 26 |
+
for key in (
|
| 27 |
+
"LD_LIBRARY_PATH",
|
| 28 |
+
"CUDA_VISIBLE_DEVICES",
|
| 29 |
+
"NVIDIA_VISIBLE_DEVICES",
|
| 30 |
+
"NVIDIA_DRIVER_CAPABILITIES",
|
| 31 |
+
"NCCL_SOCKET_IFNAME",
|
| 32 |
+
"GLOO_SOCKET_IFNAME",
|
| 33 |
+
"HF_HOME",
|
| 34 |
+
"HF_HUB_CACHE",
|
| 35 |
+
"HF_HUB_OFFLINE",
|
| 36 |
+
"TRANSFORMERS_OFFLINE",
|
| 37 |
+
"HF_DATASETS_OFFLINE",
|
| 38 |
+
)
|
| 39 |
+
if key in os.environ
|
| 40 |
+
},
|
| 41 |
+
"PATH": str(Path(sys.executable).parent) + ":/usr/local/bin:/usr/bin:/bin",
|
| 42 |
+
"HOME": temporary,
|
| 43 |
+
"PYTHONDONTWRITEBYTECODE": "1",
|
| 44 |
+
"PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1",
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def validate_submission(workspace: Path, contract: dict) -> None:
|
| 49 |
+
"""Validate collected data before any learner-controlled Python is imported."""
|
| 50 |
+
paths = set(contract["submitted_files"]) - set(contract.get("optional_files", []))
|
| 51 |
+
roots = contract.get("submitted_roots", [])
|
| 52 |
+
immutable = contract.get("immutable_assets", {})
|
| 53 |
+
paths.update(immutable)
|
| 54 |
+
for relative in roots:
|
| 55 |
+
root = workspace / relative
|
| 56 |
+
if root.is_symlink() or not root.is_dir():
|
| 57 |
+
raise ValueError("Submitted source root is missing or linked")
|
| 58 |
+
for path in root.rglob("*"):
|
| 59 |
+
if path.is_symlink():
|
| 60 |
+
raise ValueError("Submitted source contains a symlink")
|
| 61 |
+
if path.is_dir():
|
| 62 |
+
continue
|
| 63 |
+
name = path.relative_to(workspace).as_posix()
|
| 64 |
+
if path.suffix != ".py" and name not in immutable:
|
| 65 |
+
raise ValueError("Only Python source files may be added")
|
| 66 |
+
paths.add(name)
|
| 67 |
+
for relative in sorted(paths):
|
| 68 |
+
path = workspace / relative
|
| 69 |
+
for component in (path, *path.parents):
|
| 70 |
+
if component.is_symlink():
|
| 71 |
+
raise ValueError("Submitted source contains a symlink")
|
| 72 |
+
if (
|
| 73 |
+
not path.is_file()
|
| 74 |
+
or not stat.S_ISREG(path.stat().st_mode)
|
| 75 |
+
or path.stat().st_size > 8 * 1024 * 1024
|
| 76 |
+
):
|
| 77 |
+
raise ValueError("Submitted source is not a bounded regular file")
|
| 78 |
+
if (
|
| 79 |
+
relative in immutable
|
| 80 |
+
and hashlib.sha256(path.read_bytes()).hexdigest() != immutable[relative]
|
| 81 |
+
):
|
| 82 |
+
raise ValueError("Non-Python source assets must remain unchanged")
|
| 83 |
+
os.chown(path, 0, 0)
|
| 84 |
+
path.chmod(0o644)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def main() -> None:
|
| 88 |
+
directory = Path("/tests")
|
| 89 |
+
parser_spec = importlib.util.spec_from_file_location(
|
| 90 |
+
"test_results", directory / "test_results.py"
|
| 91 |
+
)
|
| 92 |
+
parser = importlib.util.module_from_spec(parser_spec)
|
| 93 |
+
sys.modules[parser_spec.name] = parser
|
| 94 |
+
parser_spec.loader.exec_module(parser)
|
| 95 |
+
contract = json.loads((directory / "contract.json").read_text())
|
| 96 |
+
logs = Path("/logs/verifier")
|
| 97 |
+
logs.mkdir(parents=True, exist_ok=True)
|
| 98 |
+
logs.chmod(0o755)
|
| 99 |
+
reward = logs / "reward.txt"
|
| 100 |
+
reward.write_text("0\n")
|
| 101 |
+
reward.chmod(0o644)
|
| 102 |
+
try:
|
| 103 |
+
validate_submission(Path("/workspace"), contract)
|
| 104 |
+
except (ValueError, OSError) as exc:
|
| 105 |
+
(logs / "result.json").write_text(json.dumps({"passed": False, "reason": str(exc)}))
|
| 106 |
+
return
|
| 107 |
+
with tempfile.TemporaryDirectory(prefix="r2e-grade-") as temporary:
|
| 108 |
+
working = Path(temporary)
|
| 109 |
+
os.chown(working, 1001, 1001)
|
| 110 |
+
working.chmod(0o700)
|
| 111 |
+
report = working / "results.xml"
|
| 112 |
+
command = [
|
| 113 |
+
sys.executable,
|
| 114 |
+
"-I",
|
| 115 |
+
"/tests/test_driver.py",
|
| 116 |
+
*contract["test_paths"],
|
| 117 |
+
"-q",
|
| 118 |
+
"--tb=short",
|
| 119 |
+
"-p",
|
| 120 |
+
"no:cacheprovider",
|
| 121 |
+
f"--junitxml={report}",
|
| 122 |
+
]
|
| 123 |
+
with (logs / "stdout.txt").open("w") as stdout, (logs / "stderr.txt").open("w") as stderr:
|
| 124 |
+
process = subprocess.Popen(
|
| 125 |
+
command,
|
| 126 |
+
cwd="/workspace",
|
| 127 |
+
stdout=stdout,
|
| 128 |
+
stderr=stderr,
|
| 129 |
+
user=1001,
|
| 130 |
+
group=1001,
|
| 131 |
+
extra_groups=[],
|
| 132 |
+
start_new_session=True,
|
| 133 |
+
env=child_environment(temporary),
|
| 134 |
+
)
|
| 135 |
+
try:
|
| 136 |
+
code = process.wait(timeout=contract["timeout_sec"])
|
| 137 |
+
finally:
|
| 138 |
+
# Terminate descendants too: they must not keep modifying the
|
| 139 |
+
# child-owned report while the trusted parent checks it.
|
| 140 |
+
try:
|
| 141 |
+
os.killpg(process.pid, signal.SIGKILL)
|
| 142 |
+
except ProcessLookupError:
|
| 143 |
+
pass
|
| 144 |
+
process.wait()
|
| 145 |
+
if report.is_symlink() or not report.is_file() or report.stat().st_size > 16 * 1024 * 1024:
|
| 146 |
+
(logs / "result.json").write_text(
|
| 147 |
+
json.dumps({"passed": False, "returncode": code, "reason": "invalid_report"})
|
| 148 |
+
)
|
| 149 |
+
return
|
| 150 |
+
text = report.read_text()
|
| 151 |
+
(logs / "results.xml").write_text(text)
|
| 152 |
+
try:
|
| 153 |
+
parsed = parser.parse_junit(text, returncode=code)
|
| 154 |
+
except ValueError as exc:
|
| 155 |
+
(logs / "result.json").write_text(
|
| 156 |
+
json.dumps({"passed": False, "returncode": code, "reason": str(exc)})
|
| 157 |
+
)
|
| 158 |
+
return
|
| 159 |
+
expected = set(contract["expected_passes"])
|
| 160 |
+
passed = code == 0 and bool(expected) and parsed.passed == expected
|
| 161 |
+
(logs / "result.json").write_text(
|
| 162 |
+
json.dumps({"passed": passed, "returncode": code, "statuses": parsed.statuses})
|
| 163 |
+
)
|
| 164 |
+
reward.write_text("1\n" if passed else "0\n")
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
if __name__ == "__main__":
|
| 168 |
+
main()
|
tasks/tasksmith-e0f68dd4420c/tests/source/.circleci/TROUBLESHOOT.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Troubleshooting
|
| 2 |
+
|
| 3 |
+
This is a document explaining how to deal with various issues on Circle-CI. The entries may include actual solutions or pointers to Issues that cover those.
|
| 4 |
+
|
| 5 |
+
## Circle CI
|
| 6 |
+
|
| 7 |
+
* pytest worker runs out of resident RAM and gets killed by `cgroups`: https://github.com/huggingface/transformers/issues/11408
|
tasks/tasksmith-e0f68dd4420c/tests/source/.circleci/config.yml
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version: 2.1
|
| 2 |
+
setup: true
|
| 3 |
+
orbs:
|
| 4 |
+
continuation: circleci/continuation@0.1.0
|
| 5 |
+
|
| 6 |
+
parameters:
|
| 7 |
+
nightly:
|
| 8 |
+
type: boolean
|
| 9 |
+
default: false
|
| 10 |
+
|
| 11 |
+
jobs:
|
| 12 |
+
# Ensure running with CircleCI/huggingface
|
| 13 |
+
check_circleci_user:
|
| 14 |
+
docker:
|
| 15 |
+
- image: python:3.10-slim
|
| 16 |
+
resource_class: small
|
| 17 |
+
parallelism: 1
|
| 18 |
+
steps:
|
| 19 |
+
- run: echo $CIRCLE_PROJECT_USERNAME
|
| 20 |
+
- run: |
|
| 21 |
+
if [ "$CIRCLE_PROJECT_USERNAME" = "huggingface" ]; then
|
| 22 |
+
exit 0
|
| 23 |
+
else
|
| 24 |
+
echo "The CI is running under $CIRCLE_PROJECT_USERNAME personal account. Please follow https://support.circleci.com/hc/en-us/articles/360008097173-Troubleshooting-why-pull-requests-are-not-triggering-jobs-on-my-organization- to fix it."; exit -1
|
| 25 |
+
fi
|
| 26 |
+
# Fetch the tests to run
|
| 27 |
+
fetch_tests:
|
| 28 |
+
working_directory: ~/transformers
|
| 29 |
+
docker:
|
| 30 |
+
- image: huggingface/transformers-quality
|
| 31 |
+
parallelism: 1
|
| 32 |
+
steps:
|
| 33 |
+
- checkout
|
| 34 |
+
- run: if [[ "$CIRCLE_PULL_REQUEST" == "" && "$CIRCLE_BRANCH" != "main" && "$CIRCLE_BRANCH" != *-release ]]; then echo "Not a PR, not the main branch and not a release branch, skip test!"; circleci-agent step halt; fi
|
| 35 |
+
- run: 'curl -L -H "Accept: application/vnd.github+json" -H "X-GitHub-Api-Version: 2022-11-28" https://api.github.com/repos/$CIRCLE_PROJECT_USERNAME/$CIRCLE_PROJECT_REPONAME/pulls/${CIRCLE_PULL_REQUEST##*/} >> github.txt'
|
| 36 |
+
- run: cat github.txt
|
| 37 |
+
- run: (python3 -c 'import json; from datetime import datetime; fp = open("github.txt"); data = json.load(fp); fp.close(); f = "%Y-%m-%dT%H:%M:%SZ"; created = datetime.strptime(data["created_at"], f); updated = datetime.strptime(data["updated_at"], f); s = (updated - created).total_seconds(); print(int(s))' || true) > elapsed.txt
|
| 38 |
+
- run: if [ "$(cat elapsed.txt)" == "" ]; then echo 60 > elapsed.txt; fi
|
| 39 |
+
- run: cat elapsed.txt
|
| 40 |
+
- run: if [ "$(cat elapsed.txt)" -lt "30" ]; then echo "PR is just opened, wait some actions from GitHub"; sleep 30; fi
|
| 41 |
+
- run: 'if grep -q "\"draft\": true," github.txt; then echo "draft mode, skip test!"; circleci-agent step halt; fi'
|
| 42 |
+
- run: uv pip install -U -e .
|
| 43 |
+
- run: echo 'export "GIT_COMMIT_MESSAGE=$(git show -s --format=%s)"' >> "$BASH_ENV" && source "$BASH_ENV"
|
| 44 |
+
- run: mkdir -p test_preparation
|
| 45 |
+
- run: python utils/tests_fetcher.py | tee tests_fetched_summary.txt
|
| 46 |
+
- run: python utils/tests_fetcher.py --filter_tests
|
| 47 |
+
- run: export "GIT_COMMIT_MESSAGE=$(git show -s --format=%s)" && echo $GIT_COMMIT_MESSAGE && python .circleci/create_circleci_config.py --fetcher_folder test_preparation
|
| 48 |
+
- run: |
|
| 49 |
+
if [ ! -s test_preparation/generated_config.yml ]; then
|
| 50 |
+
echo "No tests to run, exiting early!"
|
| 51 |
+
circleci-agent step halt
|
| 52 |
+
fi
|
| 53 |
+
|
| 54 |
+
- store_artifacts:
|
| 55 |
+
path: test_preparation
|
| 56 |
+
|
| 57 |
+
- run:
|
| 58 |
+
name: "Retrieve Artifact Paths"
|
| 59 |
+
# [reference] https://circleci.com/docs/api/v2/index.html#operation/getJobArtifacts
|
| 60 |
+
# `CIRCLE_TOKEN` is defined as an environment variables set within a context, see `https://circleci.com/docs/contexts/`
|
| 61 |
+
command: |
|
| 62 |
+
project_slug="gh/${CIRCLE_PROJECT_USERNAME}/${CIRCLE_PROJECT_REPONAME}"
|
| 63 |
+
job_number=${CIRCLE_BUILD_NUM}
|
| 64 |
+
url="https://circleci.com/api/v2/project/${project_slug}/${job_number}/artifacts"
|
| 65 |
+
curl -o test_preparation/artifacts.json ${url} --header "Circle-Token: $CIRCLE_TOKEN"
|
| 66 |
+
- run:
|
| 67 |
+
name: "Prepare pipeline parameters"
|
| 68 |
+
command: |
|
| 69 |
+
python utils/process_test_artifacts.py
|
| 70 |
+
|
| 71 |
+
# To avoid too long generated_config.yaml on the continuation orb, we pass the links to the artifacts as parameters.
|
| 72 |
+
# Otherwise the list of tests was just too big. Explicit is good but for that it was a limitation.
|
| 73 |
+
# We used:
|
| 74 |
+
|
| 75 |
+
# https://circleci.com/docs/api/v2/index.html#operation/getJobArtifacts : to get the job artifacts
|
| 76 |
+
# We could not pass a nested dict, which is why we create the test_file_... parameters for every single job
|
| 77 |
+
|
| 78 |
+
- store_artifacts:
|
| 79 |
+
path: test_preparation/transformed_artifacts.json
|
| 80 |
+
- store_artifacts:
|
| 81 |
+
path: test_preparation/artifacts.json
|
| 82 |
+
- continuation/continue:
|
| 83 |
+
parameters: test_preparation/transformed_artifacts.json
|
| 84 |
+
configuration_path: test_preparation/generated_config.yml
|
| 85 |
+
|
| 86 |
+
# To run all tests for the nightly build
|
| 87 |
+
fetch_all_tests:
|
| 88 |
+
working_directory: ~/transformers
|
| 89 |
+
docker:
|
| 90 |
+
- image: huggingface/transformers-quality
|
| 91 |
+
parallelism: 1
|
| 92 |
+
steps:
|
| 93 |
+
- checkout
|
| 94 |
+
- run: uv pip install -U -e .
|
| 95 |
+
- run: echo 'export "GIT_COMMIT_MESSAGE=$(git show -s --format=%s)"' >> "$BASH_ENV" && source "$BASH_ENV"
|
| 96 |
+
- run: mkdir -p test_preparation
|
| 97 |
+
- run: python utils/tests_fetcher.py --fetch_all | tee tests_fetched_summary.txt
|
| 98 |
+
- run: python utils/tests_fetcher.py --filter_tests
|
| 99 |
+
- run: export "GIT_COMMIT_MESSAGE=$(git show -s --format=%s)" && echo $GIT_COMMIT_MESSAGE && python .circleci/create_circleci_config.py --fetcher_folder test_preparation
|
| 100 |
+
- run: |
|
| 101 |
+
if [ ! -s test_preparation/generated_config.yml ]; then
|
| 102 |
+
echo "No tests to run, exiting early!"
|
| 103 |
+
circleci-agent step halt
|
| 104 |
+
fi
|
| 105 |
+
|
| 106 |
+
- store_artifacts:
|
| 107 |
+
path: test_preparation
|
| 108 |
+
|
| 109 |
+
- run:
|
| 110 |
+
name: "Retrieve Artifact Paths"
|
| 111 |
+
env:
|
| 112 |
+
CIRCLE_TOKEN: ${{ secrets.CI_ARTIFACT_TOKEN }}
|
| 113 |
+
command: |
|
| 114 |
+
project_slug="gh/${CIRCLE_PROJECT_USERNAME}/${CIRCLE_PROJECT_REPONAME}"
|
| 115 |
+
job_number=${CIRCLE_BUILD_NUM}
|
| 116 |
+
url="https://circleci.com/api/v2/project/${project_slug}/${job_number}/artifacts"
|
| 117 |
+
curl -o test_preparation/artifacts.json ${url}
|
| 118 |
+
- run:
|
| 119 |
+
name: "Prepare pipeline parameters"
|
| 120 |
+
command: |
|
| 121 |
+
python utils/process_test_artifacts.py
|
| 122 |
+
|
| 123 |
+
# To avoid too long generated_config.yaml on the continuation orb, we pass the links to the artifacts as parameters.
|
| 124 |
+
# Otherwise the list of tests was just too big. Explicit is good but for that it was a limitation.
|
| 125 |
+
# We used:
|
| 126 |
+
|
| 127 |
+
# https://circleci.com/docs/api/v2/index.html#operation/getJobArtifacts : to get the job artifacts
|
| 128 |
+
# We could not pass a nested dict, which is why we create the test_file_... parameters for every single job
|
| 129 |
+
|
| 130 |
+
- store_artifacts:
|
| 131 |
+
path: test_preparation/transformed_artifacts.json
|
| 132 |
+
- store_artifacts:
|
| 133 |
+
path: test_preparation/artifacts.json
|
| 134 |
+
- continuation/continue:
|
| 135 |
+
parameters: test_preparation/transformed_artifacts.json
|
| 136 |
+
configuration_path: test_preparation/generated_config.yml
|
| 137 |
+
|
| 138 |
+
check_code_quality:
|
| 139 |
+
working_directory: ~/transformers
|
| 140 |
+
docker:
|
| 141 |
+
- image: huggingface/transformers-quality
|
| 142 |
+
resource_class: large
|
| 143 |
+
environment:
|
| 144 |
+
TRANSFORMERS_IS_CI: yes
|
| 145 |
+
PYTEST_TIMEOUT: 120
|
| 146 |
+
parallelism: 1
|
| 147 |
+
steps:
|
| 148 |
+
- checkout
|
| 149 |
+
- run: uv pip install -e ".[quality]"
|
| 150 |
+
- run:
|
| 151 |
+
name: Show installed libraries and their versions
|
| 152 |
+
command: pip freeze | tee installed.txt
|
| 153 |
+
- store_artifacts:
|
| 154 |
+
path: ~/transformers/installed.txt
|
| 155 |
+
- run: python -c "from transformers import *" || (echo '🚨 import failed, this means you introduced unprotected imports! 🚨'; exit 1)
|
| 156 |
+
- run: ruff check examples tests src utils
|
| 157 |
+
- run: ruff format tests src utils --check
|
| 158 |
+
- run: python utils/custom_init_isort.py --check_only
|
| 159 |
+
- run: python utils/sort_auto_mappings.py --check_only
|
| 160 |
+
- run: python utils/check_doc_toc.py
|
| 161 |
+
- run: python utils/check_docstrings.py --check_all
|
| 162 |
+
|
| 163 |
+
check_repository_consistency:
|
| 164 |
+
working_directory: ~/transformers
|
| 165 |
+
docker:
|
| 166 |
+
- image: huggingface/transformers-consistency
|
| 167 |
+
resource_class: large
|
| 168 |
+
environment:
|
| 169 |
+
TRANSFORMERS_IS_CI: yes
|
| 170 |
+
PYTEST_TIMEOUT: 120
|
| 171 |
+
parallelism: 1
|
| 172 |
+
steps:
|
| 173 |
+
- checkout
|
| 174 |
+
- run: uv pip install -e ".[quality]"
|
| 175 |
+
- run:
|
| 176 |
+
name: Show installed libraries and their versions
|
| 177 |
+
command: pip freeze | tee installed.txt
|
| 178 |
+
- store_artifacts:
|
| 179 |
+
path: ~/transformers/installed.txt
|
| 180 |
+
- run: python utils/check_copies.py
|
| 181 |
+
- run: python utils/check_modular_conversion.py
|
| 182 |
+
- run: python utils/check_dummies.py
|
| 183 |
+
- run: python utils/check_repo.py
|
| 184 |
+
- run: python utils/check_inits.py
|
| 185 |
+
- run: python utils/check_config_docstrings.py
|
| 186 |
+
- run: python utils/check_config_attributes.py
|
| 187 |
+
- run: python utils/check_doctest_list.py
|
| 188 |
+
- run: make deps_table_check_updated
|
| 189 |
+
- run: python utils/update_metadata.py --check-only
|
| 190 |
+
- run: python utils/check_docstrings.py
|
| 191 |
+
|
| 192 |
+
workflows:
|
| 193 |
+
version: 2
|
| 194 |
+
setup_and_quality:
|
| 195 |
+
when:
|
| 196 |
+
and:
|
| 197 |
+
- equal: [<<pipeline.project.git_url>>, https://github.com/huggingface/transformers]
|
| 198 |
+
- not: <<pipeline.parameters.nightly>>
|
| 199 |
+
jobs:
|
| 200 |
+
- check_circleci_user
|
| 201 |
+
- check_code_quality
|
| 202 |
+
- check_repository_consistency
|
| 203 |
+
- fetch_tests
|
| 204 |
+
|
| 205 |
+
setup_and_quality_2:
|
| 206 |
+
when:
|
| 207 |
+
not:
|
| 208 |
+
equal: [<<pipeline.project.git_url>>, https://github.com/huggingface/transformers]
|
| 209 |
+
jobs:
|
| 210 |
+
- check_circleci_user
|
| 211 |
+
- check_code_quality
|
| 212 |
+
- check_repository_consistency
|
| 213 |
+
- fetch_tests:
|
| 214 |
+
# [reference] https://circleci.com/docs/contexts/
|
| 215 |
+
context:
|
| 216 |
+
- TRANSFORMERS_CONTEXT
|
| 217 |
+
|
| 218 |
+
nightly:
|
| 219 |
+
when: <<pipeline.parameters.nightly>>
|
| 220 |
+
jobs:
|
| 221 |
+
- check_circleci_user
|
| 222 |
+
- check_code_quality
|
| 223 |
+
- check_repository_consistency
|
| 224 |
+
- fetch_all_tests
|
tasks/tasksmith-e0f68dd4420c/tests/source/.circleci/create_circleci_config.py
ADDED
|
@@ -0,0 +1,389 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import copy
|
| 18 |
+
import os
|
| 19 |
+
import random
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
from typing import Any, Dict, List, Optional
|
| 22 |
+
import glob
|
| 23 |
+
import yaml
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
COMMON_ENV_VARIABLES = {
|
| 27 |
+
"OMP_NUM_THREADS": 1,
|
| 28 |
+
"TRANSFORMERS_IS_CI": True,
|
| 29 |
+
"PYTEST_TIMEOUT": 120,
|
| 30 |
+
"RUN_PIPELINE_TESTS": False,
|
| 31 |
+
}
|
| 32 |
+
# Disable the use of {"s": None} as the output is way too long, causing the navigation on CircleCI impractical
|
| 33 |
+
COMMON_PYTEST_OPTIONS = {"max-worker-restart": 0, "dist": "loadfile", "vvv": None, "rsfE":None}
|
| 34 |
+
DEFAULT_DOCKER_IMAGE = [{"image": "cimg/python:3.8.12"}]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class EmptyJob:
|
| 38 |
+
job_name = "empty"
|
| 39 |
+
|
| 40 |
+
def to_dict(self):
|
| 41 |
+
steps = [{"run": 'ls -la'}]
|
| 42 |
+
if self.job_name == "collection_job":
|
| 43 |
+
steps.extend(
|
| 44 |
+
[
|
| 45 |
+
"checkout",
|
| 46 |
+
{"run": "pip install requests || true"},
|
| 47 |
+
{"run": """while [[ $(curl --location --request GET "https://circleci.com/api/v2/workflow/$CIRCLE_WORKFLOW_ID/job" --header "Circle-Token: $CCI_TOKEN"| jq -r '.items[]|select(.name != "collection_job")|.status' | grep -c "running") -gt 0 ]]; do sleep 5; done || true"""},
|
| 48 |
+
{"run": 'python utils/process_circleci_workflow_test_reports.py --workflow_id $CIRCLE_WORKFLOW_ID || true'},
|
| 49 |
+
{"store_artifacts": {"path": "outputs"}},
|
| 50 |
+
{"run": 'echo "All required jobs have now completed"'},
|
| 51 |
+
]
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
return {
|
| 55 |
+
"docker": copy.deepcopy(DEFAULT_DOCKER_IMAGE),
|
| 56 |
+
"resource_class": "small",
|
| 57 |
+
"steps": steps,
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@dataclass
|
| 62 |
+
class CircleCIJob:
|
| 63 |
+
name: str
|
| 64 |
+
additional_env: Dict[str, Any] = None
|
| 65 |
+
docker_image: List[Dict[str, str]] = None
|
| 66 |
+
install_steps: List[str] = None
|
| 67 |
+
marker: Optional[str] = None
|
| 68 |
+
parallelism: Optional[int] = 0
|
| 69 |
+
pytest_num_workers: int = 8
|
| 70 |
+
pytest_options: Dict[str, Any] = None
|
| 71 |
+
resource_class: Optional[str] = "xlarge"
|
| 72 |
+
tests_to_run: Optional[List[str]] = None
|
| 73 |
+
num_test_files_per_worker: Optional[int] = 10
|
| 74 |
+
# This should be only used for doctest job!
|
| 75 |
+
command_timeout: Optional[int] = None
|
| 76 |
+
|
| 77 |
+
def __post_init__(self):
|
| 78 |
+
# Deal with defaults for mutable attributes.
|
| 79 |
+
if self.additional_env is None:
|
| 80 |
+
self.additional_env = {}
|
| 81 |
+
if self.docker_image is None:
|
| 82 |
+
# Let's avoid changing the default list and make a copy.
|
| 83 |
+
self.docker_image = copy.deepcopy(DEFAULT_DOCKER_IMAGE)
|
| 84 |
+
else:
|
| 85 |
+
# BIG HACK WILL REMOVE ONCE FETCHER IS UPDATED
|
| 86 |
+
print(os.environ.get("GIT_COMMIT_MESSAGE"))
|
| 87 |
+
if "[build-ci-image]" in os.environ.get("GIT_COMMIT_MESSAGE", "") or os.environ.get("GIT_COMMIT_MESSAGE", "") == "dev-ci":
|
| 88 |
+
self.docker_image[0]["image"] = f"{self.docker_image[0]['image']}:dev"
|
| 89 |
+
print(f"Using {self.docker_image} docker image")
|
| 90 |
+
if self.install_steps is None:
|
| 91 |
+
self.install_steps = ["uv venv && uv pip install ."]
|
| 92 |
+
if self.pytest_options is None:
|
| 93 |
+
self.pytest_options = {}
|
| 94 |
+
if isinstance(self.tests_to_run, str):
|
| 95 |
+
self.tests_to_run = [self.tests_to_run]
|
| 96 |
+
else:
|
| 97 |
+
test_file = os.path.join("test_preparation" , f"{self.job_name}_test_list.txt")
|
| 98 |
+
print("Looking for ", test_file)
|
| 99 |
+
if os.path.exists(test_file):
|
| 100 |
+
with open(test_file) as f:
|
| 101 |
+
expanded_tests = f.read().strip().split("\n")
|
| 102 |
+
self.tests_to_run = expanded_tests
|
| 103 |
+
print("Found:", expanded_tests)
|
| 104 |
+
else:
|
| 105 |
+
self.tests_to_run = []
|
| 106 |
+
print("not Found")
|
| 107 |
+
|
| 108 |
+
def to_dict(self):
|
| 109 |
+
env = COMMON_ENV_VARIABLES.copy()
|
| 110 |
+
env.update(self.additional_env)
|
| 111 |
+
|
| 112 |
+
job = {
|
| 113 |
+
"docker": self.docker_image,
|
| 114 |
+
"environment": env,
|
| 115 |
+
}
|
| 116 |
+
if self.resource_class is not None:
|
| 117 |
+
job["resource_class"] = self.resource_class
|
| 118 |
+
|
| 119 |
+
all_options = {**COMMON_PYTEST_OPTIONS, **self.pytest_options}
|
| 120 |
+
pytest_flags = [f"--{key}={value}" if (value is not None or key in ["doctest-modules"]) else f"-{key}" for key, value in all_options.items()]
|
| 121 |
+
pytest_flags.append(
|
| 122 |
+
f"--make-reports={self.name}" if "examples" in self.name else f"--make-reports=tests_{self.name}"
|
| 123 |
+
)
|
| 124 |
+
# Examples special case: we need to download NLTK files in advance to avoid cuncurrency issues
|
| 125 |
+
timeout_cmd = f"timeout {self.command_timeout} " if self.command_timeout else ""
|
| 126 |
+
marker_cmd = f"-m '{self.marker}'" if self.marker is not None else ""
|
| 127 |
+
additional_flags = f" -p no:warning -o junit_family=xunit1 --junitxml=test-results/junit.xml"
|
| 128 |
+
parallel = f' << pipeline.parameters.{self.job_name}_parallelism >> '
|
| 129 |
+
steps = [
|
| 130 |
+
"checkout",
|
| 131 |
+
{"attach_workspace": {"at": "test_preparation"}},
|
| 132 |
+
{"run": "apt-get update && apt-get install -y curl"},
|
| 133 |
+
{"run": " && ".join(self.install_steps)},
|
| 134 |
+
{"run": {"name": "Download NLTK files", "command": """python -c "import nltk; nltk.download('punkt', quiet=True)" """} if "example" in self.name else "echo Skipping"},
|
| 135 |
+
{"run": {
|
| 136 |
+
"name": "Show installed libraries and their size",
|
| 137 |
+
"command": """du -h -d 1 "$(pip -V | cut -d ' ' -f 4 | sed 's/pip//g')" | grep -vE "dist-info|_distutils_hack|__pycache__" | sort -h | tee installed.txt || true"""}
|
| 138 |
+
},
|
| 139 |
+
{"run": {
|
| 140 |
+
"name": "Show installed libraries and their versions",
|
| 141 |
+
"command": """pip list --format=freeze | tee installed.txt || true"""}
|
| 142 |
+
},
|
| 143 |
+
{"run": {
|
| 144 |
+
"name": "Show biggest libraries",
|
| 145 |
+
"command": """dpkg-query --show --showformat='${Installed-Size}\t${Package}\n' | sort -rh | head -25 | sort -h | awk '{ package=$2; sub(".*/", "", package); printf("%.5f GB %s\n", $1/1024/1024, package)}' || true"""}
|
| 146 |
+
},
|
| 147 |
+
{"run": {"name": "Create `test-results` directory", "command": "mkdir test-results"}},
|
| 148 |
+
{"run": {"name": "Get files to test", "command":f'curl -L -o {self.job_name}_test_list.txt <<pipeline.parameters.{self.job_name}_test_list>> --header "Circle-Token: $CIRCLE_TOKEN"' if self.name != "pr_documentation_tests" else 'echo "Skipped"'}},
|
| 149 |
+
{"run": {"name": "Split tests across parallel nodes: show current parallel tests",
|
| 150 |
+
"command": f"TESTS=$(circleci tests split --split-by=timings {self.job_name}_test_list.txt) && echo $TESTS > splitted_tests.txt && echo $TESTS | tr ' ' '\n'" if self.parallelism else f"awk '{{printf \"%s \", $0}}' {self.job_name}_test_list.txt > splitted_tests.txt"
|
| 151 |
+
}
|
| 152 |
+
},
|
| 153 |
+
{"run": {
|
| 154 |
+
"name": "Run tests",
|
| 155 |
+
"command": f"({timeout_cmd} python3 -m pytest {marker_cmd} -n {self.pytest_num_workers} {additional_flags} {' '.join(pytest_flags)} $(cat splitted_tests.txt) | tee tests_output.txt)"}
|
| 156 |
+
},
|
| 157 |
+
{"run": {"name": "Expand to show skipped tests", "when": "always", "command": f"python3 .circleci/parse_test_outputs.py --file tests_output.txt --skip"}},
|
| 158 |
+
{"run": {"name": "Failed tests: show reasons", "when": "always", "command": f"python3 .circleci/parse_test_outputs.py --file tests_output.txt --fail"}},
|
| 159 |
+
{"run": {"name": "Errors", "when": "always", "command": f"python3 .circleci/parse_test_outputs.py --file tests_output.txt --errors"}},
|
| 160 |
+
{"store_test_results": {"path": "test-results"}},
|
| 161 |
+
{"store_artifacts": {"path": "test-results/junit.xml"}},
|
| 162 |
+
{"store_artifacts": {"path": "reports"}},
|
| 163 |
+
{"store_artifacts": {"path": "tests.txt"}},
|
| 164 |
+
{"store_artifacts": {"path": "splitted_tests.txt"}},
|
| 165 |
+
{"store_artifacts": {"path": "installed.txt"}},
|
| 166 |
+
]
|
| 167 |
+
if self.parallelism:
|
| 168 |
+
job["parallelism"] = parallel
|
| 169 |
+
job["steps"] = steps
|
| 170 |
+
return job
|
| 171 |
+
|
| 172 |
+
@property
|
| 173 |
+
def job_name(self):
|
| 174 |
+
return self.name if ("examples" in self.name or "pipeline" in self.name or "pr_documentation" in self.name) else f"tests_{self.name}"
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
# JOBS
|
| 178 |
+
torch_job = CircleCIJob(
|
| 179 |
+
"torch",
|
| 180 |
+
docker_image=[{"image": "huggingface/transformers-torch-light"}],
|
| 181 |
+
marker="not generate",
|
| 182 |
+
parallelism=6,
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
generate_job = CircleCIJob(
|
| 186 |
+
"generate",
|
| 187 |
+
docker_image=[{"image": "huggingface/transformers-torch-light"}],
|
| 188 |
+
marker="generate",
|
| 189 |
+
parallelism=6,
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
tokenization_job = CircleCIJob(
|
| 193 |
+
"tokenization",
|
| 194 |
+
docker_image=[{"image": "huggingface/transformers-torch-light"}],
|
| 195 |
+
parallelism=8,
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
processor_job = CircleCIJob(
|
| 199 |
+
"processors",
|
| 200 |
+
docker_image=[{"image": "huggingface/transformers-torch-light"}],
|
| 201 |
+
parallelism=8,
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
tf_job = CircleCIJob(
|
| 205 |
+
"tf",
|
| 206 |
+
docker_image=[{"image":"huggingface/transformers-tf-light"}],
|
| 207 |
+
parallelism=6,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
flax_job = CircleCIJob(
|
| 212 |
+
"flax",
|
| 213 |
+
docker_image=[{"image":"huggingface/transformers-jax-light"}],
|
| 214 |
+
parallelism=6,
|
| 215 |
+
pytest_num_workers=16,
|
| 216 |
+
resource_class="2xlarge",
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
pipelines_torch_job = CircleCIJob(
|
| 221 |
+
"pipelines_torch",
|
| 222 |
+
additional_env={"RUN_PIPELINE_TESTS": True},
|
| 223 |
+
docker_image=[{"image":"huggingface/transformers-torch-light"}],
|
| 224 |
+
marker="is_pipeline_test",
|
| 225 |
+
parallelism=4,
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
pipelines_tf_job = CircleCIJob(
|
| 230 |
+
"pipelines_tf",
|
| 231 |
+
additional_env={"RUN_PIPELINE_TESTS": True},
|
| 232 |
+
docker_image=[{"image":"huggingface/transformers-tf-light"}],
|
| 233 |
+
marker="is_pipeline_test",
|
| 234 |
+
parallelism=4,
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
custom_tokenizers_job = CircleCIJob(
|
| 239 |
+
"custom_tokenizers",
|
| 240 |
+
additional_env={"RUN_CUSTOM_TOKENIZERS": True},
|
| 241 |
+
docker_image=[{"image": "huggingface/transformers-custom-tokenizers"}],
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
examples_torch_job = CircleCIJob(
|
| 246 |
+
"examples_torch",
|
| 247 |
+
additional_env={"OMP_NUM_THREADS": 8},
|
| 248 |
+
docker_image=[{"image":"huggingface/transformers-examples-torch"}],
|
| 249 |
+
# TODO @ArthurZucker remove this once docker is easier to build
|
| 250 |
+
install_steps=["uv venv && uv pip install . && uv pip install -r examples/pytorch/_tests_requirements.txt"],
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
examples_tensorflow_job = CircleCIJob(
|
| 255 |
+
"examples_tensorflow",
|
| 256 |
+
additional_env={"OMP_NUM_THREADS": 8},
|
| 257 |
+
docker_image=[{"image":"huggingface/transformers-examples-tf"}],
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
hub_job = CircleCIJob(
|
| 262 |
+
"hub",
|
| 263 |
+
additional_env={"HUGGINGFACE_CO_STAGING": True},
|
| 264 |
+
docker_image=[{"image":"huggingface/transformers-torch-light"}],
|
| 265 |
+
install_steps=[
|
| 266 |
+
'uv venv && uv pip install .',
|
| 267 |
+
'git config --global user.email "ci@dummy.com"',
|
| 268 |
+
'git config --global user.name "ci"',
|
| 269 |
+
],
|
| 270 |
+
marker="is_staging_test",
|
| 271 |
+
pytest_num_workers=2,
|
| 272 |
+
resource_class="medium",
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
onnx_job = CircleCIJob(
|
| 277 |
+
"onnx",
|
| 278 |
+
docker_image=[{"image":"huggingface/transformers-torch-tf-light"}],
|
| 279 |
+
install_steps=[
|
| 280 |
+
"uv venv",
|
| 281 |
+
"uv pip install .[torch,tf,testing,sentencepiece,onnxruntime,vision,rjieba]",
|
| 282 |
+
],
|
| 283 |
+
pytest_options={"k onnx": None},
|
| 284 |
+
pytest_num_workers=1,
|
| 285 |
+
resource_class="small",
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
exotic_models_job = CircleCIJob(
|
| 290 |
+
"exotic_models",
|
| 291 |
+
docker_image=[{"image":"huggingface/transformers-exotic-models"}],
|
| 292 |
+
parallelism=4,
|
| 293 |
+
pytest_options={"durations": 100},
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
repo_utils_job = CircleCIJob(
|
| 298 |
+
"repo_utils",
|
| 299 |
+
docker_image=[{"image":"huggingface/transformers-consistency"}],
|
| 300 |
+
pytest_num_workers=4,
|
| 301 |
+
resource_class="large",
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
non_model_job = CircleCIJob(
|
| 306 |
+
"non_model",
|
| 307 |
+
docker_image=[{"image": "huggingface/transformers-torch-light"}],
|
| 308 |
+
marker="not generate",
|
| 309 |
+
parallelism=6,
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
# We also include a `dummy.py` file in the files to be doc-tested to prevent edge case failure. Otherwise, the pytest
|
| 314 |
+
# hangs forever during test collection while showing `collecting 0 items / 21 errors`. (To see this, we have to remove
|
| 315 |
+
# the bash output redirection.)
|
| 316 |
+
py_command = 'from utils.tests_fetcher import get_doctest_files; to_test = get_doctest_files() + ["dummy.py"]; to_test = " ".join(to_test); print(to_test)'
|
| 317 |
+
py_command = f"$(python3 -c '{py_command}')"
|
| 318 |
+
command = f'echo """{py_command}""" > pr_documentation_tests_temp.txt'
|
| 319 |
+
doc_test_job = CircleCIJob(
|
| 320 |
+
"pr_documentation_tests",
|
| 321 |
+
docker_image=[{"image":"huggingface/transformers-consistency"}],
|
| 322 |
+
additional_env={"TRANSFORMERS_VERBOSITY": "error", "DATASETS_VERBOSITY": "error", "SKIP_CUDA_DOCTEST": "1"},
|
| 323 |
+
install_steps=[
|
| 324 |
+
# Add an empty file to keep the test step running correctly even no file is selected to be tested.
|
| 325 |
+
"uv venv && pip install .",
|
| 326 |
+
"touch dummy.py",
|
| 327 |
+
command,
|
| 328 |
+
"cat pr_documentation_tests_temp.txt",
|
| 329 |
+
"tail -n1 pr_documentation_tests_temp.txt | tee pr_documentation_tests_test_list.txt"
|
| 330 |
+
],
|
| 331 |
+
tests_to_run="$(cat pr_documentation_tests.txt)", # noqa
|
| 332 |
+
pytest_options={"-doctest-modules": None, "doctest-glob": "*.md", "dist": "loadfile", "rvsA": None},
|
| 333 |
+
command_timeout=1200, # test cannot run longer than 1200 seconds
|
| 334 |
+
pytest_num_workers=1,
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
REGULAR_TESTS = [torch_job, tf_job, flax_job, hub_job, onnx_job, tokenization_job, processor_job, generate_job, non_model_job] # fmt: skip
|
| 338 |
+
EXAMPLES_TESTS = [examples_torch_job, examples_tensorflow_job]
|
| 339 |
+
PIPELINE_TESTS = [pipelines_torch_job, pipelines_tf_job]
|
| 340 |
+
REPO_UTIL_TESTS = [repo_utils_job]
|
| 341 |
+
DOC_TESTS = [doc_test_job]
|
| 342 |
+
ALL_TESTS = REGULAR_TESTS + EXAMPLES_TESTS + PIPELINE_TESTS + REPO_UTIL_TESTS + DOC_TESTS + [custom_tokenizers_job] + [exotic_models_job] # fmt: skip
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def create_circleci_config(folder=None):
|
| 346 |
+
if folder is None:
|
| 347 |
+
folder = os.getcwd()
|
| 348 |
+
os.environ["test_preparation_dir"] = folder
|
| 349 |
+
jobs = [k for k in ALL_TESTS if os.path.isfile(os.path.join("test_preparation" , f"{k.job_name}_test_list.txt") )]
|
| 350 |
+
print("The following jobs will be run ", jobs)
|
| 351 |
+
|
| 352 |
+
if len(jobs) == 0:
|
| 353 |
+
jobs = [EmptyJob()]
|
| 354 |
+
else:
|
| 355 |
+
print("Full list of job name inputs", {j.job_name + "_test_list":{"type":"string", "default":''} for j in jobs})
|
| 356 |
+
# Add a job waiting all the test jobs and aggregate their test summary files at the end
|
| 357 |
+
collection_job = EmptyJob()
|
| 358 |
+
collection_job.job_name = "collection_job"
|
| 359 |
+
jobs = [collection_job] + jobs
|
| 360 |
+
|
| 361 |
+
config = {
|
| 362 |
+
"version": "2.1",
|
| 363 |
+
"parameters": {
|
| 364 |
+
# Only used to accept the parameters from the trigger
|
| 365 |
+
"nightly": {"type": "boolean", "default": False},
|
| 366 |
+
"tests_to_run": {"type": "string", "default": ''},
|
| 367 |
+
**{j.job_name + "_test_list":{"type":"string", "default":''} for j in jobs},
|
| 368 |
+
**{j.job_name + "_parallelism":{"type":"integer", "default":1} for j in jobs},
|
| 369 |
+
},
|
| 370 |
+
"jobs": {j.job_name: j.to_dict() for j in jobs}
|
| 371 |
+
}
|
| 372 |
+
if "CIRCLE_TOKEN" in os.environ:
|
| 373 |
+
# For private forked repo. (e.g. new model addition)
|
| 374 |
+
config["workflows"] = {"version": 2, "run_tests": {"jobs": [{j.job_name: {"context": ["TRANSFORMERS_CONTEXT"]}} for j in jobs]}}
|
| 375 |
+
else:
|
| 376 |
+
# For public repo. (e.g. `transformers`)
|
| 377 |
+
config["workflows"] = {"version": 2, "run_tests": {"jobs": [j.job_name for j in jobs]}}
|
| 378 |
+
with open(os.path.join(folder, "generated_config.yml"), "w") as f:
|
| 379 |
+
f.write(yaml.dump(config, sort_keys=False, default_flow_style=False).replace("' << pipeline", " << pipeline").replace(">> '", " >>"))
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
if __name__ == "__main__":
|
| 383 |
+
parser = argparse.ArgumentParser()
|
| 384 |
+
parser.add_argument(
|
| 385 |
+
"--fetcher_folder", type=str, default=None, help="Only test that all tests and modules are accounted for."
|
| 386 |
+
)
|
| 387 |
+
args = parser.parse_args()
|
| 388 |
+
|
| 389 |
+
create_circleci_config(args.fetcher_folder)
|
tasks/tasksmith-e0f68dd4420c/tests/source/.circleci/parse_test_outputs.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import argparse
|
| 3 |
+
|
| 4 |
+
def parse_pytest_output(file_path):
|
| 5 |
+
skipped_tests = {}
|
| 6 |
+
skipped_count = 0
|
| 7 |
+
with open(file_path, 'r') as file:
|
| 8 |
+
for line in file:
|
| 9 |
+
match = re.match(r'^SKIPPED \[(\d+)\] (tests/.*): (.*)$', line)
|
| 10 |
+
if match:
|
| 11 |
+
skipped_count += 1
|
| 12 |
+
test_file, test_line, reason = match.groups()
|
| 13 |
+
skipped_tests[reason] = skipped_tests.get(reason, []) + [(test_file, test_line)]
|
| 14 |
+
for k,v in sorted(skipped_tests.items(), key=lambda x:len(x[1])):
|
| 15 |
+
print(f"{len(v):4} skipped because: {k}")
|
| 16 |
+
print("Number of skipped tests:", skipped_count)
|
| 17 |
+
|
| 18 |
+
def parse_pytest_failure_output(file_path):
|
| 19 |
+
failed_tests = {}
|
| 20 |
+
failed_count = 0
|
| 21 |
+
with open(file_path, 'r') as file:
|
| 22 |
+
for line in file:
|
| 23 |
+
match = re.match(r'^FAILED (tests/.*) - (.*): (.*)$', line)
|
| 24 |
+
if match:
|
| 25 |
+
failed_count += 1
|
| 26 |
+
_, error, reason = match.groups()
|
| 27 |
+
failed_tests[reason] = failed_tests.get(reason, []) + [error]
|
| 28 |
+
for k,v in sorted(failed_tests.items(), key=lambda x:len(x[1])):
|
| 29 |
+
print(f"{len(v):4} failed because `{v[0]}` -> {k}")
|
| 30 |
+
print("Number of failed tests:", failed_count)
|
| 31 |
+
if failed_count>0:
|
| 32 |
+
exit(1)
|
| 33 |
+
|
| 34 |
+
def parse_pytest_errors_output(file_path):
|
| 35 |
+
print(file_path)
|
| 36 |
+
error_tests = {}
|
| 37 |
+
error_count = 0
|
| 38 |
+
with open(file_path, 'r') as file:
|
| 39 |
+
for line in file:
|
| 40 |
+
match = re.match(r'^ERROR (tests/.*) - (.*): (.*)$', line)
|
| 41 |
+
if match:
|
| 42 |
+
error_count += 1
|
| 43 |
+
_, test_error, reason = match.groups()
|
| 44 |
+
error_tests[reason] = error_tests.get(reason, []) + [test_error]
|
| 45 |
+
for k,v in sorted(error_tests.items(), key=lambda x:len(x[1])):
|
| 46 |
+
print(f"{len(v):4} errored out because of `{v[0]}` -> {k}")
|
| 47 |
+
print("Number of errors:", error_count)
|
| 48 |
+
if error_count>0:
|
| 49 |
+
exit(1)
|
| 50 |
+
|
| 51 |
+
def main():
|
| 52 |
+
parser = argparse.ArgumentParser()
|
| 53 |
+
parser.add_argument("--file", help="file to parse")
|
| 54 |
+
parser.add_argument("--skip", action="store_true", help="show skipped reasons")
|
| 55 |
+
parser.add_argument("--fail", action="store_true", help="show failed tests")
|
| 56 |
+
parser.add_argument("--errors", action="store_true", help="show failed tests")
|
| 57 |
+
args = parser.parse_args()
|
| 58 |
+
|
| 59 |
+
if args.skip:
|
| 60 |
+
parse_pytest_output(args.file)
|
| 61 |
+
|
| 62 |
+
if args.fail:
|
| 63 |
+
parse_pytest_failure_output(args.file)
|
| 64 |
+
|
| 65 |
+
if args.errors:
|
| 66 |
+
parse_pytest_errors_output(args.file)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
if __name__ == "__main__":
|
| 70 |
+
main()
|
tasks/tasksmith-e0f68dd4420c/tests/source/.gitattributes
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.py eol=lf
|
| 2 |
+
*.rst eol=lf
|
| 3 |
+
*.md eol=lf
|
| 4 |
+
*.mdx eol=lf
|
tasks/tasksmith-e0f68dd4420c/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: "\U0001F41B Bug Report"
|
| 2 |
+
description: Submit a bug report to help us improve transformers
|
| 3 |
+
labels: [ "bug" ]
|
| 4 |
+
body:
|
| 5 |
+
- type: markdown
|
| 6 |
+
attributes:
|
| 7 |
+
value: |
|
| 8 |
+
Thanks for taking the time to fill out this bug report! 🤗
|
| 9 |
+
|
| 10 |
+
Before you submit your bug report:
|
| 11 |
+
|
| 12 |
+
- If it is your first time submitting, be sure to check our [bug report guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#did-you-find-a-bug)
|
| 13 |
+
- Try our [docs bot](https://huggingface.co/spaces/huggingchat/hf-docs-chat) -- it might be able to help you with your issue
|
| 14 |
+
|
| 15 |
+
- type: textarea
|
| 16 |
+
id: system-info
|
| 17 |
+
attributes:
|
| 18 |
+
label: System Info
|
| 19 |
+
description: Please share your system info with us. You can run the command `transformers-cli env` and copy-paste its output below.
|
| 20 |
+
placeholder: transformers version, platform, python version, ...
|
| 21 |
+
validations:
|
| 22 |
+
required: true
|
| 23 |
+
|
| 24 |
+
- type: textarea
|
| 25 |
+
id: who-can-help
|
| 26 |
+
attributes:
|
| 27 |
+
label: Who can help?
|
| 28 |
+
description: |
|
| 29 |
+
Your issue will be replied to more quickly if you can figure out the right person to tag with @
|
| 30 |
+
If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
|
| 31 |
+
|
| 32 |
+
All issues are read by one of the core maintainers, so if you don't know who to tag, just leave this blank and
|
| 33 |
+
a core maintainer will ping the right person.
|
| 34 |
+
|
| 35 |
+
Please tag fewer than 3 people.
|
| 36 |
+
|
| 37 |
+
Models:
|
| 38 |
+
|
| 39 |
+
- text models: @ArthurZucker
|
| 40 |
+
- vision models: @amyeroberts, @qubvel
|
| 41 |
+
- speech models: @ylacombe, @eustlb
|
| 42 |
+
- graph models: @clefourrier
|
| 43 |
+
|
| 44 |
+
Library:
|
| 45 |
+
|
| 46 |
+
- flax: @sanchit-gandhi
|
| 47 |
+
- generate: @zucchini-nlp (visual-language models) or @gante (all others)
|
| 48 |
+
- pipelines: @Rocketknight1
|
| 49 |
+
- tensorflow: @gante and @Rocketknight1
|
| 50 |
+
- tokenizers: @ArthurZucker and @itazap
|
| 51 |
+
- trainer: @muellerzr @SunMarc
|
| 52 |
+
|
| 53 |
+
Integrations:
|
| 54 |
+
|
| 55 |
+
- deepspeed: HF Trainer/Accelerate: @muellerzr
|
| 56 |
+
- ray/raytune: @richardliaw, @amogkam
|
| 57 |
+
- Big Model Inference: @SunMarc
|
| 58 |
+
- quantization (bitsandbytes, autogpt): @SunMarc @MekkCyber
|
| 59 |
+
|
| 60 |
+
Documentation: @stevhliu
|
| 61 |
+
|
| 62 |
+
Model hub:
|
| 63 |
+
|
| 64 |
+
- for issues with a model, report at https://discuss.huggingface.co/ and tag the model's creator.
|
| 65 |
+
|
| 66 |
+
HF projects:
|
| 67 |
+
|
| 68 |
+
- accelerate: [different repo](https://github.com/huggingface/accelerate)
|
| 69 |
+
- datasets: [different repo](https://github.com/huggingface/datasets)
|
| 70 |
+
- diffusers: [different repo](https://github.com/huggingface/diffusers)
|
| 71 |
+
- rust tokenizers: [different repo](https://github.com/huggingface/tokenizers)
|
| 72 |
+
|
| 73 |
+
Maintained examples (not research project or legacy):
|
| 74 |
+
|
| 75 |
+
- Flax: @sanchit-gandhi
|
| 76 |
+
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
|
| 77 |
+
- TensorFlow: @Rocketknight1
|
| 78 |
+
|
| 79 |
+
Research projects are not maintained and should be taken as is.
|
| 80 |
+
|
| 81 |
+
placeholder: "@Username ..."
|
| 82 |
+
|
| 83 |
+
- type: checkboxes
|
| 84 |
+
id: information-scripts-examples
|
| 85 |
+
attributes:
|
| 86 |
+
label: Information
|
| 87 |
+
description: 'The problem arises when using:'
|
| 88 |
+
options:
|
| 89 |
+
- label: "The official example scripts"
|
| 90 |
+
- label: "My own modified scripts"
|
| 91 |
+
|
| 92 |
+
- type: checkboxes
|
| 93 |
+
id: information-tasks
|
| 94 |
+
attributes:
|
| 95 |
+
label: Tasks
|
| 96 |
+
description: "The tasks I am working on are:"
|
| 97 |
+
options:
|
| 98 |
+
- label: "An officially supported task in the `examples` folder (such as GLUE/SQuAD, ...)"
|
| 99 |
+
- label: "My own task or dataset (give details below)"
|
| 100 |
+
|
| 101 |
+
- type: textarea
|
| 102 |
+
id: reproduction
|
| 103 |
+
validations:
|
| 104 |
+
required: true
|
| 105 |
+
attributes:
|
| 106 |
+
label: Reproduction
|
| 107 |
+
description: |
|
| 108 |
+
Please provide a code sample that reproduces the problem you ran into. It can be a Colab link or just a code snippet.
|
| 109 |
+
Please include relevant config information with your code, for example your Trainers, TRL, Peft, and DeepSpeed configs.
|
| 110 |
+
If you have code snippets, error messages, stack traces please provide them here as well.
|
| 111 |
+
Important! Use code tags to correctly format your code. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting
|
| 112 |
+
Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code.
|
| 113 |
+
|
| 114 |
+
placeholder: |
|
| 115 |
+
Steps to reproduce the behavior:
|
| 116 |
+
|
| 117 |
+
1.
|
| 118 |
+
2.
|
| 119 |
+
3.
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
- type: textarea
|
| 123 |
+
id: expected-behavior
|
| 124 |
+
validations:
|
| 125 |
+
required: true
|
| 126 |
+
attributes:
|
| 127 |
+
label: Expected behavior
|
| 128 |
+
description: "A clear and concise description of what you would expect to happen."
|
tasks/tasksmith-e0f68dd4420c/tests/source/.github/ISSUE_TEMPLATE/config.yml
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
blank_issues_enabled: true
|
| 2 |
+
version: 2.1
|
| 3 |
+
contact_links:
|
| 4 |
+
- name: Model checkpoints on the Hugging Face Hub
|
| 5 |
+
url: https://huggingface.co/models
|
| 6 |
+
about: Open a Pull request / Discussion related to a specific model checkpoint directly on the Hugging Face Hub
|
| 7 |
+
- name: Website Related
|
| 8 |
+
url: https://github.com/huggingface/hub-docs/issues
|
| 9 |
+
about: Feature requests and bug reports related to the website
|
| 10 |
+
- name: Forum
|
| 11 |
+
url: https://discuss.huggingface.co/
|
| 12 |
+
about: General usage questions and community discussions
|
tasks/tasksmith-e0f68dd4420c/tests/source/.github/ISSUE_TEMPLATE/feature-request.yml
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: "\U0001F680 Feature request"
|
| 2 |
+
description: Submit a proposal/request for a new transformers feature
|
| 3 |
+
labels: [ "Feature request" ]
|
| 4 |
+
body:
|
| 5 |
+
- type: textarea
|
| 6 |
+
id: feature-request
|
| 7 |
+
validations:
|
| 8 |
+
required: true
|
| 9 |
+
attributes:
|
| 10 |
+
label: Feature request
|
| 11 |
+
description: |
|
| 12 |
+
A clear and concise description of the feature proposal. Please provide a link to the paper and code in case they exist.
|
| 13 |
+
|
| 14 |
+
- type: textarea
|
| 15 |
+
id: motivation
|
| 16 |
+
validations:
|
| 17 |
+
required: true
|
| 18 |
+
attributes:
|
| 19 |
+
label: Motivation
|
| 20 |
+
description: |
|
| 21 |
+
Please outline the motivation for the proposal. Is your feature request related to a problem? e.g., I'm always frustrated when [...]. If this is related to another GitHub issue, please link here too.
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
- type: textarea
|
| 25 |
+
id: contribution
|
| 26 |
+
validations:
|
| 27 |
+
required: true
|
| 28 |
+
attributes:
|
| 29 |
+
label: Your contribution
|
| 30 |
+
description: |
|
| 31 |
+
Is there any way that you could help, e.g. by submitting a PR? Make sure to read the CONTRIBUTING.MD [readme](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md)
|
tasks/tasksmith-e0f68dd4420c/tests/source/.github/ISSUE_TEMPLATE/i18n.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: 🌐 Translating a new language?
|
| 3 |
+
about: Start a new translation effort in your language
|
| 4 |
+
title: '[i18n-<languageCode>] Translating docs to <languageName>'
|
| 5 |
+
labels: WIP
|
| 6 |
+
assignees: ''
|
| 7 |
+
|
| 8 |
+
---
|
| 9 |
+
|
| 10 |
+
<!--
|
| 11 |
+
Note: Please search to see if an issue already exists for the language you are trying to translate.
|
| 12 |
+
-->
|
| 13 |
+
|
| 14 |
+
Hi!
|
| 15 |
+
|
| 16 |
+
Let's bring the documentation to all the <languageName>-speaking community 🌐 (currently 0 out of 267 complete)
|
| 17 |
+
|
| 18 |
+
Who would want to translate? Please follow the 🤗 [TRANSLATING guide](https://github.com/huggingface/transformers/blob/main/docs/TRANSLATING.md). Here is a list of the files ready for translation. Let us know in this issue if you'd like to translate any, and we'll add your name to the list.
|
| 19 |
+
|
| 20 |
+
Some notes:
|
| 21 |
+
|
| 22 |
+
* Please translate using an informal tone (imagine you are talking with a friend about transformers 🤗).
|
| 23 |
+
* Please translate in a gender-neutral way.
|
| 24 |
+
* Add your translations to the folder called `<languageCode>` inside the [source folder](https://github.com/huggingface/transformers/tree/main/docs/source).
|
| 25 |
+
* Register your translation in `<languageCode>/_toctree.yml`; please follow the order of the [English version](https://github.com/huggingface/transformers/blob/main/docs/source/en/_toctree.yml).
|
| 26 |
+
* Once you're finished, open a pull request and tag this issue by including #issue-number in the description, where issue-number is the number of this issue. Please ping @stevhliu and @MKhalusova for review.
|
| 27 |
+
* 🙋 If you'd like others to help you with the translation, you can also post in the 🤗 [forums](https://discuss.huggingface.co/).
|
| 28 |
+
|
| 29 |
+
## Get Started section
|
| 30 |
+
|
| 31 |
+
- [ ] [index.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/index.md) https://github.com/huggingface/transformers/pull/20180
|
| 32 |
+
- [ ] [quicktour.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/quicktour.md) (waiting for initial PR to go through)
|
| 33 |
+
- [ ] [installation.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/installation.md).
|
| 34 |
+
|
| 35 |
+
## Tutorial section
|
| 36 |
+
- [ ] [pipeline_tutorial.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/pipeline_tutorial.md)
|
| 37 |
+
- [ ] [autoclass_tutorial.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/autoclass_tutorial.md)
|
| 38 |
+
- [ ] [preprocessing.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/preprocessing.md)
|
| 39 |
+
- [ ] [training.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/training.md)
|
| 40 |
+
- [ ] [accelerate.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/accelerate.md)
|
| 41 |
+
- [ ] [model_sharing.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/model_sharing.md)
|
| 42 |
+
- [ ] [multilingual.md](https://github.com/huggingface/transformers/blob/main/docs/source/en/multilingual.md)
|
| 43 |
+
|
| 44 |
+
<!--
|
| 45 |
+
Keep on adding more as you go 🔥
|
| 46 |
+
-->
|
tasks/tasksmith-e0f68dd4420c/tests/source/.github/ISSUE_TEMPLATE/migration.yml
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: "\U0001F4DA Migration from pytorch-pretrained-bert or pytorch-transformers"
|
| 2 |
+
description: Report a problem when migrating from pytorch-pretrained-bert or pytorch-transformers to transformers
|
| 3 |
+
labels: [ "migration" ]
|
| 4 |
+
body:
|
| 5 |
+
- type: textarea
|
| 6 |
+
id: system-info
|
| 7 |
+
attributes:
|
| 8 |
+
label: System Info
|
| 9 |
+
description: Please share your system info with us. You can run the command `transformers-cli env` and copy-paste its output below.
|
| 10 |
+
render: shell
|
| 11 |
+
placeholder: transformers version, platform, python version, ...
|
| 12 |
+
validations:
|
| 13 |
+
required: true
|
| 14 |
+
|
| 15 |
+
- type: checkboxes
|
| 16 |
+
id: information-scripts-examples
|
| 17 |
+
attributes:
|
| 18 |
+
label: Information
|
| 19 |
+
description: 'The problem arises when using:'
|
| 20 |
+
options:
|
| 21 |
+
- label: "The official example scripts"
|
| 22 |
+
- label: "My own modified scripts"
|
| 23 |
+
|
| 24 |
+
- type: checkboxes
|
| 25 |
+
id: information-tasks
|
| 26 |
+
attributes:
|
| 27 |
+
label: Tasks
|
| 28 |
+
description: "The tasks I am working on are:"
|
| 29 |
+
options:
|
| 30 |
+
- label: "An officially supported task in the `examples` folder (such as GLUE/SQuAD, ...)"
|
| 31 |
+
- label: "My own task or dataset (give details below)"
|
| 32 |
+
|
| 33 |
+
- type: textarea
|
| 34 |
+
id: reproduction
|
| 35 |
+
validations:
|
| 36 |
+
required: true
|
| 37 |
+
attributes:
|
| 38 |
+
label: Reproduction
|
| 39 |
+
description: |
|
| 40 |
+
Please provide a code sample that reproduces the problem you ran into. It can be a Colab link or just a code snippet.
|
| 41 |
+
If you have code snippets, error messages, stack traces please provide them here as well.
|
| 42 |
+
Important! Use code tags to correctly format your code. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting
|
| 43 |
+
Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code.
|
| 44 |
+
|
| 45 |
+
placeholder: |
|
| 46 |
+
Steps to reproduce the behavior:
|
| 47 |
+
|
| 48 |
+
1.
|
| 49 |
+
2.
|
| 50 |
+
3.
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
- type: textarea
|
| 54 |
+
id: expected-behavior
|
| 55 |
+
validations:
|
| 56 |
+
required: true
|
| 57 |
+
attributes:
|
| 58 |
+
label: Expected behavior
|
| 59 |
+
description: "A clear and concise description of what you would expect to happen."
|
| 60 |
+
render: shell
|
| 61 |
+
|
| 62 |
+
- type: checkboxes
|
| 63 |
+
id: checklist
|
| 64 |
+
attributes:
|
| 65 |
+
label: Checklist
|
| 66 |
+
options:
|
| 67 |
+
- label: "I have read the migration guide in the readme.
|
| 68 |
+
([pytorch-transformers](https://github.com/huggingface/transformers#migrating-from-pytorch-transformers-to-transformers);
|
| 69 |
+
[pytorch-pretrained-bert](https://github.com/huggingface/transformers#migrating-from-pytorch-pretrained-bert-to-transformers))"
|
| 70 |
+
required: true
|
| 71 |
+
- label: "I checked if a related official extension example runs on my machine."
|
| 72 |
+
required: true
|
tasks/tasksmith-e0f68dd4420c/tests/source/.github/ISSUE_TEMPLATE/new-model-addition.yml
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: "\U0001F31F New model addition"
|
| 2 |
+
description: Submit a proposal/request to implement a new model
|
| 3 |
+
labels: [ "New model" ]
|
| 4 |
+
|
| 5 |
+
body:
|
| 6 |
+
- type: textarea
|
| 7 |
+
id: description-request
|
| 8 |
+
validations:
|
| 9 |
+
required: true
|
| 10 |
+
attributes:
|
| 11 |
+
label: Model description
|
| 12 |
+
description: |
|
| 13 |
+
Put any and all important information relative to the model
|
| 14 |
+
|
| 15 |
+
- type: checkboxes
|
| 16 |
+
id: information-tasks
|
| 17 |
+
attributes:
|
| 18 |
+
label: Open source status
|
| 19 |
+
description: |
|
| 20 |
+
Please note that if the model implementation isn't available or if the weights aren't open-source, we are less likely to implement it in `transformers`.
|
| 21 |
+
options:
|
| 22 |
+
- label: "The model implementation is available"
|
| 23 |
+
- label: "The model weights are available"
|
| 24 |
+
|
| 25 |
+
- type: textarea
|
| 26 |
+
id: additional-info
|
| 27 |
+
attributes:
|
| 28 |
+
label: Provide useful links for the implementation
|
| 29 |
+
description: |
|
| 30 |
+
Please provide information regarding the implementation, the weights, and the authors.
|
| 31 |
+
Please mention the authors by @gh-username if you're aware of their usernames.
|
tasks/tasksmith-e0f68dd4420c/tests/source/.github/PULL_REQUEST_TEMPLATE.md
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# What does this PR do?
|
| 2 |
+
|
| 3 |
+
<!--
|
| 4 |
+
Congratulations! You've made it this far! You're not quite done yet though.
|
| 5 |
+
|
| 6 |
+
Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.
|
| 7 |
+
|
| 8 |
+
Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.
|
| 9 |
+
|
| 10 |
+
Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
|
| 11 |
+
-->
|
| 12 |
+
|
| 13 |
+
<!-- Remove if not applicable -->
|
| 14 |
+
|
| 15 |
+
Fixes # (issue)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
## Before submitting
|
| 19 |
+
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
|
| 20 |
+
- [ ] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request),
|
| 21 |
+
Pull Request section?
|
| 22 |
+
- [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
|
| 23 |
+
to it if that's the case.
|
| 24 |
+
- [ ] Did you make sure to update the documentation with your changes? Here are the
|
| 25 |
+
[documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and
|
| 26 |
+
[here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
|
| 27 |
+
- [ ] Did you write any new necessary tests?
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
## Who can review?
|
| 31 |
+
|
| 32 |
+
Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
|
| 33 |
+
members/contributors who may be interested in your PR.
|
| 34 |
+
|
| 35 |
+
<!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @
|
| 36 |
+
|
| 37 |
+
If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
|
| 38 |
+
Please tag fewer than 3 people.
|
| 39 |
+
|
| 40 |
+
Models:
|
| 41 |
+
|
| 42 |
+
- text models: @ArthurZucker
|
| 43 |
+
- vision models: @amyeroberts, @qubvel
|
| 44 |
+
- speech models: @ylacombe, @eustlb
|
| 45 |
+
- graph models: @clefourrier
|
| 46 |
+
|
| 47 |
+
Library:
|
| 48 |
+
|
| 49 |
+
- flax: @sanchit-gandhi
|
| 50 |
+
- generate: @zucchini-nlp (visual-language models) or @gante (all others)
|
| 51 |
+
- pipelines: @Rocketknight1
|
| 52 |
+
- tensorflow: @gante and @Rocketknight1
|
| 53 |
+
- tokenizers: @ArthurZucker
|
| 54 |
+
- trainer: @muellerzr and @SunMarc
|
| 55 |
+
- chat templates: @Rocketknight1
|
| 56 |
+
|
| 57 |
+
Integrations:
|
| 58 |
+
|
| 59 |
+
- deepspeed: HF Trainer/Accelerate: @muellerzr
|
| 60 |
+
- ray/raytune: @richardliaw, @amogkam
|
| 61 |
+
- Big Model Inference: @SunMarc
|
| 62 |
+
- quantization (bitsandbytes, autogpt): @SunMarc @MekkCyber
|
| 63 |
+
|
| 64 |
+
Documentation: @stevhliu
|
| 65 |
+
|
| 66 |
+
HF projects:
|
| 67 |
+
|
| 68 |
+
- accelerate: [different repo](https://github.com/huggingface/accelerate)
|
| 69 |
+
- datasets: [different repo](https://github.com/huggingface/datasets)
|
| 70 |
+
- diffusers: [different repo](https://github.com/huggingface/diffusers)
|
| 71 |
+
- rust tokenizers: [different repo](https://github.com/huggingface/tokenizers)
|
| 72 |
+
|
| 73 |
+
Maintained examples (not research project or legacy):
|
| 74 |
+
|
| 75 |
+
- Flax: @sanchit-gandhi
|
| 76 |
+
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
|
| 77 |
+
- TensorFlow: @Rocketknight1
|
| 78 |
+
|
| 79 |
+
-->
|
tasks/tasksmith-e0f68dd4420c/tests/source/.github/conda/build.sh
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
$PYTHON setup.py install # Python command to install the script.
|
tasks/tasksmith-e0f68dd4420c/tests/source/.github/conda/meta.yaml
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% set name = "transformers" %}
|
| 2 |
+
|
| 3 |
+
package:
|
| 4 |
+
name: "{{ name|lower }}"
|
| 5 |
+
version: "{{ TRANSFORMERS_VERSION }}"
|
| 6 |
+
|
| 7 |
+
source:
|
| 8 |
+
path: ../../
|
| 9 |
+
|
| 10 |
+
build:
|
| 11 |
+
noarch: python
|
| 12 |
+
|
| 13 |
+
requirements:
|
| 14 |
+
host:
|
| 15 |
+
- python
|
| 16 |
+
- pip
|
| 17 |
+
- numpy >=1.17
|
| 18 |
+
- dataclasses
|
| 19 |
+
- huggingface_hub
|
| 20 |
+
- packaging
|
| 21 |
+
- filelock
|
| 22 |
+
- requests
|
| 23 |
+
- tqdm >=4.27
|
| 24 |
+
- sacremoses
|
| 25 |
+
- regex !=2019.12.17
|
| 26 |
+
- protobuf
|
| 27 |
+
- tokenizers >=0.11.1,!=0.11.3,<0.13
|
| 28 |
+
- pyyaml >=5.1
|
| 29 |
+
- safetensors
|
| 30 |
+
- fsspec
|
| 31 |
+
run:
|
| 32 |
+
- python
|
| 33 |
+
- numpy >=1.17
|
| 34 |
+
- dataclasses
|
| 35 |
+
- huggingface_hub
|
| 36 |
+
- packaging
|
| 37 |
+
- filelock
|
| 38 |
+
- requests
|
| 39 |
+
- tqdm >=4.27
|
| 40 |
+
- sacremoses
|
| 41 |
+
- regex !=2019.12.17
|
| 42 |
+
- protobuf
|
| 43 |
+
- tokenizers >=0.11.1,!=0.11.3,<0.13
|
| 44 |
+
- pyyaml >=5.1
|
| 45 |
+
- safetensors
|
| 46 |
+
- fsspec
|
| 47 |
+
|
| 48 |
+
test:
|
| 49 |
+
imports:
|
| 50 |
+
- transformers
|
| 51 |
+
|
| 52 |
+
about:
|
| 53 |
+
home: https://huggingface.co
|
| 54 |
+
license: Apache License 2.0
|
| 55 |
+
license_file: LICENSE
|
| 56 |
+
summary: "🤗Transformers: State-of-the-art Natural Language Processing for Pytorch and TensorFlow 2.0."
|