Stage Harbor release files 23501-24000
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-441eeab80047/environment/source/utils/check_inits.py +374 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/check_model_tester.py +63 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/check_modular_conversion.py +177 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/check_repo.py +1222 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/check_self_hosted_runner.py +52 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/check_tf_ops.py +101 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/create_dependency_mapping.py +70 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/create_dummy_models.py +1577 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/custom_init_isort.py +330 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/deprecate_models.py +378 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/download_glue_data.py +157 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/extract_warnings.py +134 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/get_ci_error_statistics.py +303 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/get_github_job_time.py +71 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/get_modified_files.py +36 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/get_previous_daily_ci.py +85 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/get_test_info.py +198 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/important_models.txt +4 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/models_to_deprecate.py +200 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/modular_model_converter.py +1746 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/not_doctested.txt +979 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/notification_service.py +1285 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/notification_service_doc_tests.py +385 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/notification_service_quantization.py +274 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/past_ci_versions.py +126 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/patch_helper.py +95 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/pr_slow_ci_models.py +173 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/print_env.py +57 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/process_bad_commit_report.py +90 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/process_circleci_workflow_test_reports.py +85 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/process_test_artifacts.py +75 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/release.py +204 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/set_cuda_devices_for_ci.py +26 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/slow_documentation_tests.txt +16 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/sort_auto_mappings.py +125 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/split_doctest_jobs.py +91 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/split_model_tests.py +65 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/test_module/__init__.py +0 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_configuration.py +16 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_feature_extraction.py +5 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_image_processing.py +5 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_modeling.py +33 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_pipeline.py +33 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_processing.py +6 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_tokenization.py +5 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/test_module/custom_tokenization_fast.py +8 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/tests_fetcher.py +1255 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/tf_ops/onnx.json +245 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/update_metadata.py +372 -0
- tasks/tasksmith-441eeab80047/environment/source/utils/update_tiny_models.py +199 -0
tasks/tasksmith-441eeab80047/environment/source/utils/check_inits.py
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 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 checks the custom inits of Transformers are well-defined: Transformers uses init files that delay the
|
| 17 |
+
import of an object to when it's actually needed. This is to avoid the main init importing all models, which would
|
| 18 |
+
make the line `import transformers` very slow when the user has all optional dependencies installed. The inits with
|
| 19 |
+
delayed imports have two halves: one definining a dictionary `_import_structure` which maps modules to the name of the
|
| 20 |
+
objects in each module, and one in `TYPE_CHECKING` which looks like a normal init for type-checkers. The goal of this
|
| 21 |
+
script is to check the objects defined in both halves are the same.
|
| 22 |
+
|
| 23 |
+
This also checks the main init properly references all submodules, even if it doesn't import anything from them: every
|
| 24 |
+
submodule should be defined as a key of `_import_structure`, with an empty list as value potentially, or the submodule
|
| 25 |
+
won't be importable.
|
| 26 |
+
|
| 27 |
+
Use from the root of the repo with:
|
| 28 |
+
|
| 29 |
+
```bash
|
| 30 |
+
python utils/check_inits.py
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
for a check that will error in case of inconsistencies (used by `make repo-consistency`).
|
| 34 |
+
|
| 35 |
+
There is no auto-fix possible here sadly :-(
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
import collections
|
| 39 |
+
import os
|
| 40 |
+
import re
|
| 41 |
+
from pathlib import Path
|
| 42 |
+
from typing import Dict, List, Optional, Tuple
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# Path is set with the intent you should run this script from the root of the repo.
|
| 46 |
+
PATH_TO_TRANSFORMERS = "src/transformers"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# Matches is_xxx_available()
|
| 50 |
+
_re_backend = re.compile(r"is\_([a-z_]*)_available()")
|
| 51 |
+
# Catches a one-line _import_struct = {xxx}
|
| 52 |
+
_re_one_line_import_struct = re.compile(r"^_import_structure\s+=\s+\{([^\}]+)\}")
|
| 53 |
+
# Catches a line with a key-values pattern: "bla": ["foo", "bar"]
|
| 54 |
+
_re_import_struct_key_value = re.compile(r'\s+"\S*":\s+\[([^\]]*)\]')
|
| 55 |
+
# Catches a line if not is_foo_available
|
| 56 |
+
_re_test_backend = re.compile(r"^\s*if\s+not\s+is\_[a-z_]*\_available\(\)")
|
| 57 |
+
# Catches a line _import_struct["bla"].append("foo")
|
| 58 |
+
_re_import_struct_add_one = re.compile(r'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)')
|
| 59 |
+
# Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"]
|
| 60 |
+
_re_import_struct_add_many = re.compile(r"^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]")
|
| 61 |
+
# Catches a line with an object between quotes and a comma: "MyModel",
|
| 62 |
+
_re_quote_object = re.compile(r'^\s+"([^"]+)",')
|
| 63 |
+
# Catches a line with objects between brackets only: ["foo", "bar"],
|
| 64 |
+
_re_between_brackets = re.compile(r"^\s+\[([^\]]+)\]")
|
| 65 |
+
# Catches a line with from foo import bar, bla, boo
|
| 66 |
+
_re_import = re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n")
|
| 67 |
+
# Catches a line with try:
|
| 68 |
+
_re_try = re.compile(r"^\s*try:")
|
| 69 |
+
# Catches a line with else:
|
| 70 |
+
_re_else = re.compile(r"^\s*else:")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def find_backend(line: str) -> Optional[str]:
|
| 74 |
+
"""
|
| 75 |
+
Find one (or multiple) backend in a code line of the init.
|
| 76 |
+
|
| 77 |
+
Args:
|
| 78 |
+
line (`str`): A code line of the main init.
|
| 79 |
+
|
| 80 |
+
Returns:
|
| 81 |
+
Optional[`str`]: If one (or several) backend is found, returns it. In the case of multiple backends (the line
|
| 82 |
+
contains `if is_xxx_available() and `is_yyy_available()`) returns all backends joined on `_and_` (so
|
| 83 |
+
`xxx_and_yyy` for instance).
|
| 84 |
+
"""
|
| 85 |
+
if _re_test_backend.search(line) is None:
|
| 86 |
+
return None
|
| 87 |
+
backends = [b[0] for b in _re_backend.findall(line)]
|
| 88 |
+
backends.sort()
|
| 89 |
+
return "_and_".join(backends)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def parse_init(init_file) -> Optional[Tuple[Dict[str, List[str]], Dict[str, List[str]]]]:
|
| 93 |
+
"""
|
| 94 |
+
Read an init_file and parse (per backend) the `_import_structure` objects defined and the `TYPE_CHECKING` objects
|
| 95 |
+
defined.
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
init_file (`str`): Path to the init file to inspect.
|
| 99 |
+
|
| 100 |
+
Returns:
|
| 101 |
+
`Optional[Tuple[Dict[str, List[str]], Dict[str, List[str]]]]`: A tuple of two dictionaries mapping backends to list of
|
| 102 |
+
imported objects, one for the `_import_structure` part of the init and one for the `TYPE_CHECKING` part of the
|
| 103 |
+
init. Returns `None` if the init is not a custom init.
|
| 104 |
+
"""
|
| 105 |
+
with open(init_file, "r", encoding="utf-8", newline="\n") as f:
|
| 106 |
+
lines = f.readlines()
|
| 107 |
+
|
| 108 |
+
# Get the to `_import_structure` definition.
|
| 109 |
+
line_index = 0
|
| 110 |
+
while line_index < len(lines) and not lines[line_index].startswith("_import_structure = {"):
|
| 111 |
+
line_index += 1
|
| 112 |
+
|
| 113 |
+
# If this is a traditional init, just return.
|
| 114 |
+
if line_index >= len(lines):
|
| 115 |
+
return None
|
| 116 |
+
|
| 117 |
+
# First grab the objects without a specific backend in _import_structure
|
| 118 |
+
objects = []
|
| 119 |
+
while not lines[line_index].startswith("if TYPE_CHECKING") and find_backend(lines[line_index]) is None:
|
| 120 |
+
line = lines[line_index]
|
| 121 |
+
# If we have everything on a single line, let's deal with it.
|
| 122 |
+
if _re_one_line_import_struct.search(line):
|
| 123 |
+
content = _re_one_line_import_struct.search(line).groups()[0]
|
| 124 |
+
imports = re.findall(r"\[([^\]]+)\]", content)
|
| 125 |
+
for imp in imports:
|
| 126 |
+
objects.extend([obj[1:-1] for obj in imp.split(", ")])
|
| 127 |
+
line_index += 1
|
| 128 |
+
continue
|
| 129 |
+
single_line_import_search = _re_import_struct_key_value.search(line)
|
| 130 |
+
if single_line_import_search is not None:
|
| 131 |
+
imports = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(", ") if len(obj) > 0]
|
| 132 |
+
objects.extend(imports)
|
| 133 |
+
elif line.startswith(" " * 8 + '"'):
|
| 134 |
+
objects.append(line[9:-3])
|
| 135 |
+
line_index += 1
|
| 136 |
+
|
| 137 |
+
# Those are stored with the key "none".
|
| 138 |
+
import_dict_objects = {"none": objects}
|
| 139 |
+
|
| 140 |
+
# Let's continue with backend-specific objects in _import_structure
|
| 141 |
+
while not lines[line_index].startswith("if TYPE_CHECKING"):
|
| 142 |
+
# If the line is an if not is_backend_available, we grab all objects associated.
|
| 143 |
+
backend = find_backend(lines[line_index])
|
| 144 |
+
# Check if the backend declaration is inside a try block:
|
| 145 |
+
if _re_try.search(lines[line_index - 1]) is None:
|
| 146 |
+
backend = None
|
| 147 |
+
|
| 148 |
+
if backend is not None:
|
| 149 |
+
line_index += 1
|
| 150 |
+
|
| 151 |
+
# Scroll until we hit the else block of try-except-else
|
| 152 |
+
while _re_else.search(lines[line_index]) is None:
|
| 153 |
+
line_index += 1
|
| 154 |
+
|
| 155 |
+
line_index += 1
|
| 156 |
+
|
| 157 |
+
objects = []
|
| 158 |
+
# Until we unindent, add backend objects to the list
|
| 159 |
+
while len(lines[line_index]) <= 1 or lines[line_index].startswith(" " * 4):
|
| 160 |
+
line = lines[line_index]
|
| 161 |
+
if _re_import_struct_add_one.search(line) is not None:
|
| 162 |
+
objects.append(_re_import_struct_add_one.search(line).groups()[0])
|
| 163 |
+
elif _re_import_struct_add_many.search(line) is not None:
|
| 164 |
+
imports = _re_import_struct_add_many.search(line).groups()[0].split(", ")
|
| 165 |
+
imports = [obj[1:-1] for obj in imports if len(obj) > 0]
|
| 166 |
+
objects.extend(imports)
|
| 167 |
+
elif _re_between_brackets.search(line) is not None:
|
| 168 |
+
imports = _re_between_brackets.search(line).groups()[0].split(", ")
|
| 169 |
+
imports = [obj[1:-1] for obj in imports if len(obj) > 0]
|
| 170 |
+
objects.extend(imports)
|
| 171 |
+
elif _re_quote_object.search(line) is not None:
|
| 172 |
+
objects.append(_re_quote_object.search(line).groups()[0])
|
| 173 |
+
elif line.startswith(" " * 8 + '"'):
|
| 174 |
+
objects.append(line[9:-3])
|
| 175 |
+
elif line.startswith(" " * 12 + '"'):
|
| 176 |
+
objects.append(line[13:-3])
|
| 177 |
+
line_index += 1
|
| 178 |
+
|
| 179 |
+
import_dict_objects[backend] = objects
|
| 180 |
+
else:
|
| 181 |
+
line_index += 1
|
| 182 |
+
|
| 183 |
+
# At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend
|
| 184 |
+
objects = []
|
| 185 |
+
while (
|
| 186 |
+
line_index < len(lines)
|
| 187 |
+
and find_backend(lines[line_index]) is None
|
| 188 |
+
and not lines[line_index].startswith("else")
|
| 189 |
+
):
|
| 190 |
+
line = lines[line_index]
|
| 191 |
+
single_line_import_search = _re_import.search(line)
|
| 192 |
+
if single_line_import_search is not None:
|
| 193 |
+
objects.extend(single_line_import_search.groups()[0].split(", "))
|
| 194 |
+
elif line.startswith(" " * 8):
|
| 195 |
+
objects.append(line[8:-2])
|
| 196 |
+
line_index += 1
|
| 197 |
+
|
| 198 |
+
type_hint_objects = {"none": objects}
|
| 199 |
+
|
| 200 |
+
# Let's continue with backend-specific objects
|
| 201 |
+
while line_index < len(lines):
|
| 202 |
+
# If the line is an if is_backend_available, we grab all objects associated.
|
| 203 |
+
backend = find_backend(lines[line_index])
|
| 204 |
+
# Check if the backend declaration is inside a try block:
|
| 205 |
+
if _re_try.search(lines[line_index - 1]) is None:
|
| 206 |
+
backend = None
|
| 207 |
+
|
| 208 |
+
if backend is not None:
|
| 209 |
+
line_index += 1
|
| 210 |
+
|
| 211 |
+
# Scroll until we hit the else block of try-except-else
|
| 212 |
+
while _re_else.search(lines[line_index]) is None:
|
| 213 |
+
line_index += 1
|
| 214 |
+
|
| 215 |
+
line_index += 1
|
| 216 |
+
|
| 217 |
+
objects = []
|
| 218 |
+
# Until we unindent, add backend objects to the list
|
| 219 |
+
while len(lines[line_index]) <= 1 or lines[line_index].startswith(" " * 8):
|
| 220 |
+
line = lines[line_index]
|
| 221 |
+
single_line_import_search = _re_import.search(line)
|
| 222 |
+
if single_line_import_search is not None:
|
| 223 |
+
objects.extend(single_line_import_search.groups()[0].split(", "))
|
| 224 |
+
elif line.startswith(" " * 12):
|
| 225 |
+
objects.append(line[12:-2])
|
| 226 |
+
line_index += 1
|
| 227 |
+
|
| 228 |
+
type_hint_objects[backend] = objects
|
| 229 |
+
else:
|
| 230 |
+
line_index += 1
|
| 231 |
+
|
| 232 |
+
return import_dict_objects, type_hint_objects
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def analyze_results(import_dict_objects: Dict[str, List[str]], type_hint_objects: Dict[str, List[str]]) -> List[str]:
|
| 236 |
+
"""
|
| 237 |
+
Analyze the differences between _import_structure objects and TYPE_CHECKING objects found in an init.
|
| 238 |
+
|
| 239 |
+
Args:
|
| 240 |
+
import_dict_objects (`Dict[str, List[str]]`):
|
| 241 |
+
A dictionary mapping backend names (`"none"` for the objects independent of any specific backend) to
|
| 242 |
+
list of imported objects.
|
| 243 |
+
type_hint_objects (`Dict[str, List[str]]`):
|
| 244 |
+
A dictionary mapping backend names (`"none"` for the objects independent of any specific backend) to
|
| 245 |
+
list of imported objects.
|
| 246 |
+
|
| 247 |
+
Returns:
|
| 248 |
+
`List[str]`: The list of errors corresponding to mismatches.
|
| 249 |
+
"""
|
| 250 |
+
|
| 251 |
+
def find_duplicates(seq):
|
| 252 |
+
return [k for k, v in collections.Counter(seq).items() if v > 1]
|
| 253 |
+
|
| 254 |
+
# If one backend is missing from the other part of the init, error early.
|
| 255 |
+
if list(import_dict_objects.keys()) != list(type_hint_objects.keys()):
|
| 256 |
+
return ["Both sides of the init do not have the same backends!"]
|
| 257 |
+
|
| 258 |
+
errors = []
|
| 259 |
+
# Find all errors.
|
| 260 |
+
for key in import_dict_objects.keys():
|
| 261 |
+
# Duplicate imports in any half.
|
| 262 |
+
duplicate_imports = find_duplicates(import_dict_objects[key])
|
| 263 |
+
if duplicate_imports:
|
| 264 |
+
errors.append(f"Duplicate _import_structure definitions for: {duplicate_imports}")
|
| 265 |
+
duplicate_type_hints = find_duplicates(type_hint_objects[key])
|
| 266 |
+
if duplicate_type_hints:
|
| 267 |
+
errors.append(f"Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}")
|
| 268 |
+
|
| 269 |
+
# Missing imports in either part of the init.
|
| 270 |
+
if sorted(set(import_dict_objects[key])) != sorted(set(type_hint_objects[key])):
|
| 271 |
+
name = "base imports" if key == "none" else f"{key} backend"
|
| 272 |
+
errors.append(f"Differences for {name}:")
|
| 273 |
+
for a in type_hint_objects[key]:
|
| 274 |
+
if a not in import_dict_objects[key]:
|
| 275 |
+
errors.append(f" {a} in TYPE_HINT but not in _import_structure.")
|
| 276 |
+
for a in import_dict_objects[key]:
|
| 277 |
+
if a not in type_hint_objects[key]:
|
| 278 |
+
errors.append(f" {a} in _import_structure but not in TYPE_HINT.")
|
| 279 |
+
return errors
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def check_all_inits():
|
| 283 |
+
"""
|
| 284 |
+
Check all inits in the transformers repo and raise an error if at least one does not define the same objects in
|
| 285 |
+
both halves.
|
| 286 |
+
"""
|
| 287 |
+
failures = []
|
| 288 |
+
for root, _, files in os.walk(PATH_TO_TRANSFORMERS):
|
| 289 |
+
if "__init__.py" in files:
|
| 290 |
+
fname = os.path.join(root, "__init__.py")
|
| 291 |
+
objects = parse_init(fname)
|
| 292 |
+
if objects is not None:
|
| 293 |
+
errors = analyze_results(*objects)
|
| 294 |
+
if len(errors) > 0:
|
| 295 |
+
errors[0] = f"Problem in {fname}, both halves do not define the same objects.\n{errors[0]}"
|
| 296 |
+
failures.append("\n".join(errors))
|
| 297 |
+
if len(failures) > 0:
|
| 298 |
+
raise ValueError("\n\n".join(failures))
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def get_transformers_submodules() -> List[str]:
|
| 302 |
+
"""
|
| 303 |
+
Returns the list of Transformers submodules.
|
| 304 |
+
"""
|
| 305 |
+
submodules = []
|
| 306 |
+
for path, directories, files in os.walk(PATH_TO_TRANSFORMERS):
|
| 307 |
+
for folder in directories:
|
| 308 |
+
# Ignore private modules
|
| 309 |
+
if folder.startswith("_"):
|
| 310 |
+
directories.remove(folder)
|
| 311 |
+
continue
|
| 312 |
+
# Ignore leftovers from branches (empty folders apart from pycache)
|
| 313 |
+
if len(list((Path(path) / folder).glob("*.py"))) == 0:
|
| 314 |
+
continue
|
| 315 |
+
short_path = str((Path(path) / folder).relative_to(PATH_TO_TRANSFORMERS))
|
| 316 |
+
submodule = short_path.replace(os.path.sep, ".")
|
| 317 |
+
submodules.append(submodule)
|
| 318 |
+
for fname in files:
|
| 319 |
+
if fname == "__init__.py":
|
| 320 |
+
continue
|
| 321 |
+
short_path = str((Path(path) / fname).relative_to(PATH_TO_TRANSFORMERS))
|
| 322 |
+
submodule = short_path.replace(".py", "").replace(os.path.sep, ".")
|
| 323 |
+
if len(submodule.split(".")) == 1:
|
| 324 |
+
submodules.append(submodule)
|
| 325 |
+
return submodules
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
IGNORE_SUBMODULES = [
|
| 329 |
+
"convert_pytorch_checkpoint_to_tf2",
|
| 330 |
+
"modeling_flax_pytorch_utils",
|
| 331 |
+
"models.esm.openfold_utils",
|
| 332 |
+
"modeling_attn_mask_utils",
|
| 333 |
+
"safetensors_conversion",
|
| 334 |
+
"modeling_gguf_pytorch_utils",
|
| 335 |
+
"kernels.falcon_mamba",
|
| 336 |
+
"kernels",
|
| 337 |
+
]
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def check_submodules():
|
| 341 |
+
"""
|
| 342 |
+
Check all submodules of Transformers are properly registered in the main init. Error otherwise.
|
| 343 |
+
"""
|
| 344 |
+
# This is to make sure the transformers module imported is the one in the repo.
|
| 345 |
+
from transformers.utils import direct_transformers_import
|
| 346 |
+
|
| 347 |
+
transformers = direct_transformers_import(PATH_TO_TRANSFORMERS)
|
| 348 |
+
|
| 349 |
+
import_structure_keys = set(transformers._import_structure.keys())
|
| 350 |
+
# This contains all the base keys of the _import_structure object defined in the init, but if the user is missing
|
| 351 |
+
# some optional dependencies, they may not have all of them. Thus we read the init to read all additions and
|
| 352 |
+
# (potentiall re-) add them.
|
| 353 |
+
with open(os.path.join(PATH_TO_TRANSFORMERS, "__init__.py"), "r") as f:
|
| 354 |
+
init_content = f.read()
|
| 355 |
+
import_structure_keys.update(set(re.findall(r"import_structure\[\"([^\"]*)\"\]", init_content)))
|
| 356 |
+
|
| 357 |
+
module_not_registered = [
|
| 358 |
+
module
|
| 359 |
+
for module in get_transformers_submodules()
|
| 360 |
+
if module not in IGNORE_SUBMODULES and module not in import_structure_keys
|
| 361 |
+
]
|
| 362 |
+
|
| 363 |
+
if len(module_not_registered) > 0:
|
| 364 |
+
list_of_modules = "\n".join(f"- {module}" for module in module_not_registered)
|
| 365 |
+
raise ValueError(
|
| 366 |
+
"The following submodules are not properly registed in the main init of Transformers:\n"
|
| 367 |
+
f"{list_of_modules}\n"
|
| 368 |
+
"Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value."
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
if __name__ == "__main__":
|
| 373 |
+
check_all_inits()
|
| 374 |
+
check_submodules()
|
tasks/tasksmith-441eeab80047/environment/source/utils/check_model_tester.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 16 |
+
|
| 17 |
+
import glob
|
| 18 |
+
import os
|
| 19 |
+
|
| 20 |
+
from get_test_info import get_tester_classes
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
if __name__ == "__main__":
|
| 24 |
+
failures = []
|
| 25 |
+
|
| 26 |
+
pattern = os.path.join("tests", "models", "**", "test_modeling_*.py")
|
| 27 |
+
test_files = glob.glob(pattern)
|
| 28 |
+
# TODO: deal with TF/Flax too
|
| 29 |
+
test_files = [
|
| 30 |
+
x for x in test_files if not (x.startswith("test_modeling_tf_") or x.startswith("test_modeling_flax_"))
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
for test_file in test_files:
|
| 34 |
+
tester_classes = get_tester_classes(test_file)
|
| 35 |
+
for tester_class in tester_classes:
|
| 36 |
+
# A few tester classes don't have `parent` parameter in `__init__`.
|
| 37 |
+
# TODO: deal this better
|
| 38 |
+
try:
|
| 39 |
+
tester = tester_class(parent=None)
|
| 40 |
+
except Exception:
|
| 41 |
+
continue
|
| 42 |
+
if hasattr(tester, "get_config"):
|
| 43 |
+
config = tester.get_config()
|
| 44 |
+
for k, v in config.to_dict().items():
|
| 45 |
+
if isinstance(v, int):
|
| 46 |
+
target = None
|
| 47 |
+
if k in ["vocab_size"]:
|
| 48 |
+
target = 100
|
| 49 |
+
elif k in ["max_position_embeddings"]:
|
| 50 |
+
target = 128
|
| 51 |
+
elif k in ["hidden_size", "d_model"]:
|
| 52 |
+
target = 40
|
| 53 |
+
elif k == ["num_layers", "num_hidden_layers", "num_encoder_layers", "num_decoder_layers"]:
|
| 54 |
+
target = 5
|
| 55 |
+
if target is not None and v > target:
|
| 56 |
+
failures.append(
|
| 57 |
+
f"{tester_class.__name__} will produce a `config` of type `{config.__class__.__name__}`"
|
| 58 |
+
f' with config["{k}"] = {v} which is too large for testing! Set its value to be smaller'
|
| 59 |
+
f" than {target}."
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
if len(failures) > 0:
|
| 63 |
+
raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures))
|
tasks/tasksmith-441eeab80047/environment/source/utils/check_modular_conversion.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import difflib
|
| 3 |
+
import glob
|
| 4 |
+
import logging
|
| 5 |
+
import subprocess
|
| 6 |
+
from io import StringIO
|
| 7 |
+
|
| 8 |
+
from create_dependency_mapping import find_priority_list
|
| 9 |
+
|
| 10 |
+
# Console for rich printing
|
| 11 |
+
from modular_model_converter import convert_modular_file
|
| 12 |
+
from rich.console import Console
|
| 13 |
+
from rich.syntax import Syntax
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
logging.basicConfig()
|
| 17 |
+
logging.getLogger().setLevel(logging.ERROR)
|
| 18 |
+
console = Console()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def process_file(modular_file_path, generated_modeling_content, file_type="modeling_", fix_and_overwrite=False):
|
| 22 |
+
file_name_prefix = file_type.split("*")[0]
|
| 23 |
+
file_name_suffix = file_type.split("*")[-1] if "*" in file_type else ""
|
| 24 |
+
file_path = modular_file_path.replace("modular_", f"{file_name_prefix}_").replace(".py", f"{file_name_suffix}.py")
|
| 25 |
+
# Read the actual modeling file
|
| 26 |
+
with open(file_path, "r", encoding="utf-8") as modeling_file:
|
| 27 |
+
content = modeling_file.read()
|
| 28 |
+
output_buffer = StringIO(generated_modeling_content[file_type][0])
|
| 29 |
+
output_buffer.seek(0)
|
| 30 |
+
output_content = output_buffer.read()
|
| 31 |
+
diff = difflib.unified_diff(
|
| 32 |
+
output_content.splitlines(),
|
| 33 |
+
content.splitlines(),
|
| 34 |
+
fromfile=f"{file_path}_generated",
|
| 35 |
+
tofile=f"{file_path}",
|
| 36 |
+
lineterm="",
|
| 37 |
+
)
|
| 38 |
+
diff_list = list(diff)
|
| 39 |
+
# Check for differences
|
| 40 |
+
if diff_list:
|
| 41 |
+
if fix_and_overwrite:
|
| 42 |
+
with open(file_path, "w", encoding="utf-8", newline="\n") as modeling_file:
|
| 43 |
+
modeling_file.write(generated_modeling_content[file_type][0])
|
| 44 |
+
console.print(f"[bold blue]Overwritten {file_path} with the generated content.[/bold blue]")
|
| 45 |
+
else:
|
| 46 |
+
console.print(f"\n[bold red]Differences found between the generated code and {file_path}:[/bold red]\n")
|
| 47 |
+
diff_text = "\n".join(diff_list)
|
| 48 |
+
syntax = Syntax(diff_text, "diff", theme="ansi_dark", line_numbers=True)
|
| 49 |
+
console.print(syntax)
|
| 50 |
+
return 1
|
| 51 |
+
else:
|
| 52 |
+
console.print(f"[bold green]No differences found for {file_path}.[/bold green]")
|
| 53 |
+
return 0
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def compare_files(modular_file_path, fix_and_overwrite=False):
|
| 57 |
+
# Generate the expected modeling content
|
| 58 |
+
generated_modeling_content = convert_modular_file(modular_file_path)
|
| 59 |
+
diff = 0
|
| 60 |
+
for file_type in generated_modeling_content.keys():
|
| 61 |
+
diff += process_file(modular_file_path, generated_modeling_content, file_type, fix_and_overwrite)
|
| 62 |
+
return diff
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def get_models_in_diff():
|
| 66 |
+
"""
|
| 67 |
+
Finds all models that have been modified in the diff.
|
| 68 |
+
|
| 69 |
+
Returns:
|
| 70 |
+
A set containing the names of the models that have been modified (e.g. {'llama', 'whisper'}).
|
| 71 |
+
"""
|
| 72 |
+
fork_point_sha = subprocess.check_output("git merge-base main HEAD".split()).decode("utf-8")
|
| 73 |
+
modified_files = (
|
| 74 |
+
subprocess.check_output(f"git diff --diff-filter=d --name-only {fork_point_sha}".split())
|
| 75 |
+
.decode("utf-8")
|
| 76 |
+
.split()
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
# Matches both modelling files and tests
|
| 80 |
+
relevant_modified_files = [x for x in modified_files if "/models/" in x and x.endswith(".py")]
|
| 81 |
+
model_names = set()
|
| 82 |
+
for file_path in relevant_modified_files:
|
| 83 |
+
model_name = file_path.split("/")[-2]
|
| 84 |
+
model_names.add(model_name)
|
| 85 |
+
return model_names
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def guaranteed_no_diff(modular_file_path, dependencies, models_in_diff):
|
| 89 |
+
"""
|
| 90 |
+
Returns whether it is guaranteed to have no differences between the modular file and the modeling file.
|
| 91 |
+
|
| 92 |
+
Model is in the diff -> not guaranteed to have no differences
|
| 93 |
+
Dependency is in the diff -> not guaranteed to have no differences
|
| 94 |
+
Otherwise -> guaranteed to have no differences
|
| 95 |
+
|
| 96 |
+
Args:
|
| 97 |
+
modular_file_path: The path to the modular file.
|
| 98 |
+
dependencies: A dictionary containing the dependencies of each modular file.
|
| 99 |
+
models_in_diff: A set containing the names of the models that have been modified.
|
| 100 |
+
|
| 101 |
+
Returns:
|
| 102 |
+
A boolean indicating whether the model (code and tests) is guaranteed to have no differences.
|
| 103 |
+
"""
|
| 104 |
+
model_name = modular_file_path.rsplit("modular_", 1)[1].replace(".py", "")
|
| 105 |
+
if model_name in models_in_diff:
|
| 106 |
+
return False
|
| 107 |
+
for dep in dependencies[modular_file_path]:
|
| 108 |
+
# two possible patterns: `transformers.models.model_name.(...)` or `model_name.(...)`
|
| 109 |
+
dependency_model_name = dep.split(".")[-2]
|
| 110 |
+
if dependency_model_name in models_in_diff:
|
| 111 |
+
return False
|
| 112 |
+
return True
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
if __name__ == "__main__":
|
| 116 |
+
parser = argparse.ArgumentParser(description="Compare modular_xxx.py files with modeling_xxx.py files.")
|
| 117 |
+
parser.add_argument(
|
| 118 |
+
"--files", default=["all"], type=list, nargs="+", help="List of modular_xxx.py files to compare."
|
| 119 |
+
)
|
| 120 |
+
parser.add_argument(
|
| 121 |
+
"--fix_and_overwrite", action="store_true", help="Overwrite the modeling_xxx.py file if differences are found."
|
| 122 |
+
)
|
| 123 |
+
parser.add_argument(
|
| 124 |
+
"--num_workers",
|
| 125 |
+
default=1,
|
| 126 |
+
type=int,
|
| 127 |
+
help="The number of workers to run. No effect if `fix_and_overwrite` is specified.",
|
| 128 |
+
)
|
| 129 |
+
args = parser.parse_args()
|
| 130 |
+
if args.files == ["all"]:
|
| 131 |
+
args.files = glob.glob("src/transformers/models/**/modular_*.py", recursive=True)
|
| 132 |
+
|
| 133 |
+
# Assuming there is a topological sort on the dependency mapping: if the file being checked and its dependencies
|
| 134 |
+
# are not in the diff, then there it is guaranteed to have no differences. If no models are in the diff, then this
|
| 135 |
+
# script will do nothing.
|
| 136 |
+
models_in_diff = get_models_in_diff()
|
| 137 |
+
if not models_in_diff:
|
| 138 |
+
console.print("[bold green]No models files or model tests in the diff, skipping modular checks[/bold green]")
|
| 139 |
+
exit(0)
|
| 140 |
+
|
| 141 |
+
skipped_models = set()
|
| 142 |
+
non_matching_files = 0
|
| 143 |
+
ordered_files, dependencies = find_priority_list(args.files)
|
| 144 |
+
if args.fix_and_overwrite or args.num_workers == 1:
|
| 145 |
+
for modular_file_path in ordered_files:
|
| 146 |
+
is_guaranteed_no_diff = guaranteed_no_diff(modular_file_path, dependencies, models_in_diff)
|
| 147 |
+
if is_guaranteed_no_diff:
|
| 148 |
+
model_name = modular_file_path.rsplit("modular_", 1)[1].replace(".py", "")
|
| 149 |
+
skipped_models.add(model_name)
|
| 150 |
+
continue
|
| 151 |
+
non_matching_files += compare_files(modular_file_path, args.fix_and_overwrite)
|
| 152 |
+
models_in_diff = get_models_in_diff() # When overwriting, the diff changes
|
| 153 |
+
else:
|
| 154 |
+
new_ordered_files = []
|
| 155 |
+
for modular_file_path in ordered_files:
|
| 156 |
+
is_guaranteed_no_diff = guaranteed_no_diff(modular_file_path, dependencies, models_in_diff)
|
| 157 |
+
if is_guaranteed_no_diff:
|
| 158 |
+
model_name = modular_file_path.rsplit("modular_", 1)[1].replace(".py", "")
|
| 159 |
+
skipped_models.add(model_name)
|
| 160 |
+
else:
|
| 161 |
+
new_ordered_files.append(modular_file_path)
|
| 162 |
+
|
| 163 |
+
import multiprocessing
|
| 164 |
+
|
| 165 |
+
with multiprocessing.Pool(args.num_workers) as p:
|
| 166 |
+
outputs = p.map(compare_files, new_ordered_files)
|
| 167 |
+
for output in outputs:
|
| 168 |
+
non_matching_files += output
|
| 169 |
+
|
| 170 |
+
if non_matching_files and not args.fix_and_overwrite:
|
| 171 |
+
raise ValueError("Some diff and their modeling code did not match.")
|
| 172 |
+
|
| 173 |
+
if skipped_models:
|
| 174 |
+
console.print(
|
| 175 |
+
f"[bold green]Skipped {len(skipped_models)} models and their dependencies that are not in the diff: "
|
| 176 |
+
f"{', '.join(skipped_models)}[/bold green]"
|
| 177 |
+
)
|
tasks/tasksmith-441eeab80047/environment/source/utils/check_repo.py
ADDED
|
@@ -0,0 +1,1222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 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 performs several consistency checks on the repo. This includes:
|
| 17 |
+
- checking all models are properly defined in the __init__ of models/
|
| 18 |
+
- checking all models are in the main __init__
|
| 19 |
+
- checking all models are properly tested
|
| 20 |
+
- checking all object in the main __init__ are documented
|
| 21 |
+
- checking all models are in at least one auto class
|
| 22 |
+
- checking all the auto mapping are properly defined (no typos, importable)
|
| 23 |
+
- checking the list of deprecated models is up to date
|
| 24 |
+
|
| 25 |
+
Use from the root of the repo with (as used in `make repo-consistency`):
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
python utils/check_repo.py
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
It has no auto-fix mode.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import sys
|
| 37 |
+
import types
|
| 38 |
+
import warnings
|
| 39 |
+
from collections import OrderedDict
|
| 40 |
+
from difflib import get_close_matches
|
| 41 |
+
from pathlib import Path
|
| 42 |
+
from typing import List, Tuple
|
| 43 |
+
|
| 44 |
+
from transformers import is_flax_available, is_tf_available, is_torch_available
|
| 45 |
+
from transformers.models.auto import get_values
|
| 46 |
+
from transformers.models.auto.configuration_auto import CONFIG_MAPPING_NAMES
|
| 47 |
+
from transformers.models.auto.feature_extraction_auto import FEATURE_EXTRACTOR_MAPPING_NAMES
|
| 48 |
+
from transformers.models.auto.image_processing_auto import IMAGE_PROCESSOR_MAPPING_NAMES
|
| 49 |
+
from transformers.models.auto.processing_auto import PROCESSOR_MAPPING_NAMES
|
| 50 |
+
from transformers.models.auto.tokenization_auto import TOKENIZER_MAPPING_NAMES
|
| 51 |
+
from transformers.utils import ENV_VARS_TRUE_VALUES, direct_transformers_import
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# All paths are set with the intent you should run this script from the root of the repo with the command
|
| 55 |
+
# python utils/check_repo.py
|
| 56 |
+
PATH_TO_TRANSFORMERS = "src/transformers"
|
| 57 |
+
PATH_TO_TESTS = "tests"
|
| 58 |
+
PATH_TO_DOC = "docs/source/en"
|
| 59 |
+
|
| 60 |
+
# Update this list with models that are supposed to be private.
|
| 61 |
+
PRIVATE_MODELS = [
|
| 62 |
+
"AltRobertaModel",
|
| 63 |
+
"DPRSpanPredictor",
|
| 64 |
+
"UdopStack",
|
| 65 |
+
"LongT5Stack",
|
| 66 |
+
"RealmBertModel",
|
| 67 |
+
"T5Stack",
|
| 68 |
+
"MT5Stack",
|
| 69 |
+
"UMT5Stack",
|
| 70 |
+
"Pop2PianoStack",
|
| 71 |
+
"Qwen2AudioEncoder",
|
| 72 |
+
"Qwen2VisionTransformerPretrainedModel",
|
| 73 |
+
"Qwen2_5_VisionTransformerPretrainedModel",
|
| 74 |
+
"SwitchTransformersStack",
|
| 75 |
+
"TFDPRSpanPredictor",
|
| 76 |
+
"MaskFormerSwinModel",
|
| 77 |
+
"MaskFormerSwinPreTrainedModel",
|
| 78 |
+
"BridgeTowerTextModel",
|
| 79 |
+
"BridgeTowerVisionModel",
|
| 80 |
+
"Kosmos2TextModel",
|
| 81 |
+
"Kosmos2TextForCausalLM",
|
| 82 |
+
"Kosmos2VisionModel",
|
| 83 |
+
"SeamlessM4Tv2TextToUnitModel",
|
| 84 |
+
"SeamlessM4Tv2CodeHifiGan",
|
| 85 |
+
"SeamlessM4Tv2TextToUnitForConditionalGeneration",
|
| 86 |
+
"Idefics2PerceiverResampler",
|
| 87 |
+
"Idefics2VisionTransformer",
|
| 88 |
+
"Idefics3VisionTransformer",
|
| 89 |
+
"SmolVLMVisionTransformer",
|
| 90 |
+
"AriaTextForCausalLM",
|
| 91 |
+
"AriaTextModel",
|
| 92 |
+
]
|
| 93 |
+
|
| 94 |
+
# Update this list for models that are not tested with a comment explaining the reason it should not be.
|
| 95 |
+
# Being in this list is an exception and should **not** be the rule.
|
| 96 |
+
IGNORE_NON_TESTED = (
|
| 97 |
+
PRIVATE_MODELS.copy()
|
| 98 |
+
+ [
|
| 99 |
+
# models to ignore for not tested
|
| 100 |
+
"RecurrentGemmaModel", # Building part of bigger (tested) model.
|
| 101 |
+
"FuyuForCausalLM", # Not tested fort now
|
| 102 |
+
"InstructBlipQFormerModel", # Building part of bigger (tested) model.
|
| 103 |
+
"InstructBlipVideoQFormerModel", # Building part of bigger (tested) model.
|
| 104 |
+
"UMT5EncoderModel", # Building part of bigger (tested) model.
|
| 105 |
+
"Blip2QFormerModel", # Building part of bigger (tested) model.
|
| 106 |
+
"ErnieMForInformationExtraction",
|
| 107 |
+
"FastSpeech2ConformerHifiGan", # Already tested by SpeechT5HifiGan (# Copied from)
|
| 108 |
+
"FastSpeech2ConformerWithHifiGan", # Built with two smaller (tested) models.
|
| 109 |
+
"GraphormerDecoderHead", # Building part of bigger (tested) model.
|
| 110 |
+
"JukeboxVQVAE", # Building part of bigger (tested) model.
|
| 111 |
+
"JukeboxPrior", # Building part of bigger (tested) model.
|
| 112 |
+
"DecisionTransformerGPT2Model", # Building part of bigger (tested) model.
|
| 113 |
+
"SegformerDecodeHead", # Building part of bigger (tested) model.
|
| 114 |
+
"MgpstrModel", # Building part of bigger (tested) model.
|
| 115 |
+
"BertLMHeadModel", # Needs to be setup as decoder.
|
| 116 |
+
"MegatronBertLMHeadModel", # Building part of bigger (tested) model.
|
| 117 |
+
"RealmBertModel", # Building part of bigger (tested) model.
|
| 118 |
+
"RealmReader", # Not regular model.
|
| 119 |
+
"RealmScorer", # Not regular model.
|
| 120 |
+
"RealmForOpenQA", # Not regular model.
|
| 121 |
+
"ReformerForMaskedLM", # Needs to be setup as decoder.
|
| 122 |
+
"TFElectraMainLayer", # Building part of bigger (tested) model (should it be a TFPreTrainedModel ?)
|
| 123 |
+
"TFRobertaForMultipleChoice", # TODO: fix
|
| 124 |
+
"TFRobertaPreLayerNormForMultipleChoice", # TODO: fix
|
| 125 |
+
"SeparableConv1D", # Building part of bigger (tested) model.
|
| 126 |
+
"FlaxBartForCausalLM", # Building part of bigger (tested) model.
|
| 127 |
+
"FlaxBertForCausalLM", # Building part of bigger (tested) model. Tested implicitly through FlaxRobertaForCausalLM.
|
| 128 |
+
"OPTDecoderWrapper",
|
| 129 |
+
"TFSegformerDecodeHead", # Not a regular model.
|
| 130 |
+
"AltRobertaModel", # Building part of bigger (tested) model.
|
| 131 |
+
"BlipTextLMHeadModel", # No need to test it as it is tested by BlipTextVision models
|
| 132 |
+
"TFBlipTextLMHeadModel", # No need to test it as it is tested by BlipTextVision models
|
| 133 |
+
"BridgeTowerTextModel", # No need to test it as it is tested by BridgeTowerModel model.
|
| 134 |
+
"BridgeTowerVisionModel", # No need to test it as it is tested by BridgeTowerModel model.
|
| 135 |
+
"BarkCausalModel", # Building part of bigger (tested) model.
|
| 136 |
+
"BarkModel", # Does not have a forward signature - generation tested with integration tests.
|
| 137 |
+
"SeamlessM4TTextToUnitModel", # Building part of bigger (tested) model.
|
| 138 |
+
"SeamlessM4TCodeHifiGan", # Building part of bigger (tested) model.
|
| 139 |
+
"SeamlessM4TTextToUnitForConditionalGeneration", # Building part of bigger (tested) model.
|
| 140 |
+
"ChameleonVQVAE", # VQVAE here is used only for encoding (discretizing) and is tested as part of bigger model
|
| 141 |
+
"Qwen2VLModel", # Building part of bigger (tested) model. Tested implicitly through Qwen2VLForConditionalGeneration.
|
| 142 |
+
"Qwen2_5_VLModel", # Building part of bigger (tested) model. Tested implicitly through Qwen2_5_VLForConditionalGeneration.
|
| 143 |
+
"MllamaTextModel", # Building part of bigger (tested) model. # TODO: add tests
|
| 144 |
+
"MllamaVisionModel", # Building part of bigger (tested) model. # TODO: add tests
|
| 145 |
+
"Emu3VQVAE", # Building part of bigger (tested) model
|
| 146 |
+
"Emu3TextModel", # Building part of bigger (tested) model
|
| 147 |
+
]
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
# Update this list with test files that don't have a tester with a `all_model_classes` variable and which don't
|
| 151 |
+
# trigger the common tests.
|
| 152 |
+
TEST_FILES_WITH_NO_COMMON_TESTS = [
|
| 153 |
+
"models/decision_transformer/test_modeling_decision_transformer.py",
|
| 154 |
+
"models/camembert/test_modeling_camembert.py",
|
| 155 |
+
"models/mt5/test_modeling_flax_mt5.py",
|
| 156 |
+
"models/mbart/test_modeling_mbart.py",
|
| 157 |
+
"models/mt5/test_modeling_mt5.py",
|
| 158 |
+
"models/pegasus/test_modeling_pegasus.py",
|
| 159 |
+
"models/camembert/test_modeling_tf_camembert.py",
|
| 160 |
+
"models/mt5/test_modeling_tf_mt5.py",
|
| 161 |
+
"models/xlm_roberta/test_modeling_tf_xlm_roberta.py",
|
| 162 |
+
"models/xlm_roberta/test_modeling_flax_xlm_roberta.py",
|
| 163 |
+
"models/xlm_prophetnet/test_modeling_xlm_prophetnet.py",
|
| 164 |
+
"models/xlm_roberta/test_modeling_xlm_roberta.py",
|
| 165 |
+
"models/vision_text_dual_encoder/test_modeling_vision_text_dual_encoder.py",
|
| 166 |
+
"models/vision_text_dual_encoder/test_modeling_tf_vision_text_dual_encoder.py",
|
| 167 |
+
"models/vision_text_dual_encoder/test_modeling_flax_vision_text_dual_encoder.py",
|
| 168 |
+
"models/decision_transformer/test_modeling_decision_transformer.py",
|
| 169 |
+
"models/bark/test_modeling_bark.py",
|
| 170 |
+
]
|
| 171 |
+
|
| 172 |
+
# Update this list for models that are not in any of the auto MODEL_XXX_MAPPING. Being in this list is an exception and
|
| 173 |
+
# should **not** be the rule.
|
| 174 |
+
IGNORE_NON_AUTO_CONFIGURED = PRIVATE_MODELS.copy() + [
|
| 175 |
+
# models to ignore for model xxx mapping
|
| 176 |
+
"AlignTextModel",
|
| 177 |
+
"AlignVisionModel",
|
| 178 |
+
"ClapTextModel",
|
| 179 |
+
"ClapTextModelWithProjection",
|
| 180 |
+
"ClapAudioModel",
|
| 181 |
+
"ClapAudioModelWithProjection",
|
| 182 |
+
"Blip2TextModelWithProjection",
|
| 183 |
+
"Blip2VisionModelWithProjection",
|
| 184 |
+
"Blip2QFormerModel",
|
| 185 |
+
"Blip2VisionModel",
|
| 186 |
+
"ErnieMForInformationExtraction",
|
| 187 |
+
"FastSpeech2ConformerHifiGan",
|
| 188 |
+
"FastSpeech2ConformerWithHifiGan",
|
| 189 |
+
"GitVisionModel",
|
| 190 |
+
"GraphormerModel",
|
| 191 |
+
"GraphormerForGraphClassification",
|
| 192 |
+
"BlipForImageTextRetrieval",
|
| 193 |
+
"BlipForQuestionAnswering",
|
| 194 |
+
"BlipVisionModel",
|
| 195 |
+
"BlipTextLMHeadModel",
|
| 196 |
+
"BlipTextModel",
|
| 197 |
+
"BrosSpadeEEForTokenClassification",
|
| 198 |
+
"BrosSpadeELForTokenClassification",
|
| 199 |
+
"TFBlipForConditionalGeneration",
|
| 200 |
+
"TFBlipForImageTextRetrieval",
|
| 201 |
+
"TFBlipForQuestionAnswering",
|
| 202 |
+
"TFBlipVisionModel",
|
| 203 |
+
"TFBlipTextLMHeadModel",
|
| 204 |
+
"TFBlipTextModel",
|
| 205 |
+
"Swin2SRForImageSuperResolution",
|
| 206 |
+
"BridgeTowerForImageAndTextRetrieval",
|
| 207 |
+
"BridgeTowerForMaskedLM",
|
| 208 |
+
"BridgeTowerForContrastiveLearning",
|
| 209 |
+
"CLIPSegForImageSegmentation",
|
| 210 |
+
"CLIPSegVisionModel",
|
| 211 |
+
"CLIPSegTextModel",
|
| 212 |
+
"EsmForProteinFolding",
|
| 213 |
+
"GPTSanJapaneseModel",
|
| 214 |
+
"TimeSeriesTransformerForPrediction",
|
| 215 |
+
"InformerForPrediction",
|
| 216 |
+
"AutoformerForPrediction",
|
| 217 |
+
"PatchTSTForPretraining",
|
| 218 |
+
"PatchTSTForPrediction",
|
| 219 |
+
"JukeboxVQVAE",
|
| 220 |
+
"JukeboxPrior",
|
| 221 |
+
"SamModel",
|
| 222 |
+
"DPTForDepthEstimation",
|
| 223 |
+
"DecisionTransformerGPT2Model",
|
| 224 |
+
"GLPNForDepthEstimation",
|
| 225 |
+
"ViltForImagesAndTextClassification",
|
| 226 |
+
"ViltForImageAndTextRetrieval",
|
| 227 |
+
"ViltForTokenClassification",
|
| 228 |
+
"ViltForMaskedLM",
|
| 229 |
+
"PerceiverForMultimodalAutoencoding",
|
| 230 |
+
"PerceiverForOpticalFlow",
|
| 231 |
+
"SegformerDecodeHead",
|
| 232 |
+
"TFSegformerDecodeHead",
|
| 233 |
+
"FlaxBeitForMaskedImageModeling",
|
| 234 |
+
"BeitForMaskedImageModeling",
|
| 235 |
+
"ChineseCLIPTextModel",
|
| 236 |
+
"ChineseCLIPVisionModel",
|
| 237 |
+
"CLIPTextModelWithProjection",
|
| 238 |
+
"CLIPVisionModelWithProjection",
|
| 239 |
+
"ClvpForCausalLM",
|
| 240 |
+
"ClvpModel",
|
| 241 |
+
"GroupViTTextModel",
|
| 242 |
+
"GroupViTVisionModel",
|
| 243 |
+
"TFCLIPTextModel",
|
| 244 |
+
"TFCLIPVisionModel",
|
| 245 |
+
"TFGroupViTTextModel",
|
| 246 |
+
"TFGroupViTVisionModel",
|
| 247 |
+
"FlaxCLIPTextModel",
|
| 248 |
+
"FlaxCLIPTextModelWithProjection",
|
| 249 |
+
"FlaxCLIPVisionModel",
|
| 250 |
+
"FlaxWav2Vec2ForCTC",
|
| 251 |
+
"DetrForSegmentation",
|
| 252 |
+
"Pix2StructVisionModel",
|
| 253 |
+
"Pix2StructTextModel",
|
| 254 |
+
"ConditionalDetrForSegmentation",
|
| 255 |
+
"DPRReader",
|
| 256 |
+
"FlaubertForQuestionAnswering",
|
| 257 |
+
"FlavaImageCodebook",
|
| 258 |
+
"FlavaTextModel",
|
| 259 |
+
"FlavaImageModel",
|
| 260 |
+
"FlavaMultimodalModel",
|
| 261 |
+
"GPT2DoubleHeadsModel",
|
| 262 |
+
"GPTSw3DoubleHeadsModel",
|
| 263 |
+
"InstructBlipVisionModel",
|
| 264 |
+
"InstructBlipQFormerModel",
|
| 265 |
+
"InstructBlipVideoVisionModel",
|
| 266 |
+
"InstructBlipVideoQFormerModel",
|
| 267 |
+
"LayoutLMForQuestionAnswering",
|
| 268 |
+
"LukeForMaskedLM",
|
| 269 |
+
"LukeForEntityClassification",
|
| 270 |
+
"LukeForEntityPairClassification",
|
| 271 |
+
"LukeForEntitySpanClassification",
|
| 272 |
+
"MgpstrModel",
|
| 273 |
+
"OpenAIGPTDoubleHeadsModel",
|
| 274 |
+
"OwlViTTextModel",
|
| 275 |
+
"OwlViTVisionModel",
|
| 276 |
+
"Owlv2TextModel",
|
| 277 |
+
"Owlv2VisionModel",
|
| 278 |
+
"OwlViTForObjectDetection",
|
| 279 |
+
"PatchTSMixerForPrediction",
|
| 280 |
+
"PatchTSMixerForPretraining",
|
| 281 |
+
"RagModel",
|
| 282 |
+
"RagSequenceForGeneration",
|
| 283 |
+
"RagTokenForGeneration",
|
| 284 |
+
"RealmEmbedder",
|
| 285 |
+
"RealmForOpenQA",
|
| 286 |
+
"RealmScorer",
|
| 287 |
+
"RealmReader",
|
| 288 |
+
"TFDPRReader",
|
| 289 |
+
"TFGPT2DoubleHeadsModel",
|
| 290 |
+
"TFLayoutLMForQuestionAnswering",
|
| 291 |
+
"TFOpenAIGPTDoubleHeadsModel",
|
| 292 |
+
"TFRagModel",
|
| 293 |
+
"TFRagSequenceForGeneration",
|
| 294 |
+
"TFRagTokenForGeneration",
|
| 295 |
+
"Wav2Vec2ForCTC",
|
| 296 |
+
"HubertForCTC",
|
| 297 |
+
"SEWForCTC",
|
| 298 |
+
"SEWDForCTC",
|
| 299 |
+
"XLMForQuestionAnswering",
|
| 300 |
+
"XLNetForQuestionAnswering",
|
| 301 |
+
"SeparableConv1D",
|
| 302 |
+
"VisualBertForRegionToPhraseAlignment",
|
| 303 |
+
"VisualBertForVisualReasoning",
|
| 304 |
+
"VisualBertForQuestionAnswering",
|
| 305 |
+
"VisualBertForMultipleChoice",
|
| 306 |
+
"TFWav2Vec2ForCTC",
|
| 307 |
+
"TFHubertForCTC",
|
| 308 |
+
"XCLIPVisionModel",
|
| 309 |
+
"XCLIPTextModel",
|
| 310 |
+
"AltCLIPTextModel",
|
| 311 |
+
"AltCLIPVisionModel",
|
| 312 |
+
"AltRobertaModel",
|
| 313 |
+
"TvltForAudioVisualClassification",
|
| 314 |
+
"BarkCausalModel",
|
| 315 |
+
"BarkCoarseModel",
|
| 316 |
+
"BarkFineModel",
|
| 317 |
+
"BarkSemanticModel",
|
| 318 |
+
"MusicgenMelodyModel",
|
| 319 |
+
"MusicgenModel",
|
| 320 |
+
"MusicgenForConditionalGeneration",
|
| 321 |
+
"SpeechT5ForSpeechToSpeech",
|
| 322 |
+
"SpeechT5ForTextToSpeech",
|
| 323 |
+
"SpeechT5HifiGan",
|
| 324 |
+
"VitMatteForImageMatting",
|
| 325 |
+
"SeamlessM4TTextToUnitModel",
|
| 326 |
+
"SeamlessM4TTextToUnitForConditionalGeneration",
|
| 327 |
+
"SeamlessM4TCodeHifiGan",
|
| 328 |
+
"SeamlessM4TForSpeechToSpeech", # no auto class for speech-to-speech
|
| 329 |
+
"TvpForVideoGrounding",
|
| 330 |
+
"SeamlessM4Tv2NARTextToUnitModel",
|
| 331 |
+
"SeamlessM4Tv2NARTextToUnitForConditionalGeneration",
|
| 332 |
+
"SeamlessM4Tv2CodeHifiGan",
|
| 333 |
+
"SeamlessM4Tv2ForSpeechToSpeech", # no auto class for speech-to-speech
|
| 334 |
+
"SegGptForImageSegmentation",
|
| 335 |
+
"SiglipVisionModel",
|
| 336 |
+
"SiglipTextModel",
|
| 337 |
+
"Siglip2VisionModel",
|
| 338 |
+
"Siglip2TextModel",
|
| 339 |
+
"ChameleonVQVAE", # no autoclass for VQ-VAE models
|
| 340 |
+
"VitPoseForPoseEstimation",
|
| 341 |
+
"CLIPTextModel",
|
| 342 |
+
"MoshiForConditionalGeneration", # no auto class for speech-to-speech
|
| 343 |
+
"Emu3VQVAE", # no autoclass for VQ-VAE models
|
| 344 |
+
"Emu3TextModel", # Building part of bigger (tested) model
|
| 345 |
+
]
|
| 346 |
+
|
| 347 |
+
# DO NOT edit this list!
|
| 348 |
+
# (The corresponding pytorch objects should never have been in the main `__init__`, but it's too late to remove)
|
| 349 |
+
OBJECT_TO_SKIP_IN_MAIN_INIT_CHECK = [
|
| 350 |
+
"FlaxBertLayer",
|
| 351 |
+
"FlaxBigBirdLayer",
|
| 352 |
+
"FlaxRoFormerLayer",
|
| 353 |
+
"TFBertLayer",
|
| 354 |
+
"TFLxmertEncoder",
|
| 355 |
+
"TFLxmertXLayer",
|
| 356 |
+
"TFMPNetLayer",
|
| 357 |
+
"TFMobileBertLayer",
|
| 358 |
+
"TFSegformerLayer",
|
| 359 |
+
"TFViTMAELayer",
|
| 360 |
+
]
|
| 361 |
+
|
| 362 |
+
# Update this list for models that have multiple model types for the same model doc.
|
| 363 |
+
MODEL_TYPE_TO_DOC_MAPPING = OrderedDict(
|
| 364 |
+
[
|
| 365 |
+
("data2vec-text", "data2vec"),
|
| 366 |
+
("data2vec-audio", "data2vec"),
|
| 367 |
+
("data2vec-vision", "data2vec"),
|
| 368 |
+
("donut-swin", "donut"),
|
| 369 |
+
]
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
# This is to make sure the transformers module imported is the one in the repo.
|
| 374 |
+
transformers = direct_transformers_import(PATH_TO_TRANSFORMERS)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def check_missing_backends():
|
| 378 |
+
"""
|
| 379 |
+
Checks if all backends are installed (otherwise the check of this script is incomplete). Will error in the CI if
|
| 380 |
+
that's not the case but only throw a warning for users running this.
|
| 381 |
+
"""
|
| 382 |
+
missing_backends = []
|
| 383 |
+
if not is_torch_available():
|
| 384 |
+
missing_backends.append("PyTorch")
|
| 385 |
+
if not is_tf_available():
|
| 386 |
+
missing_backends.append("TensorFlow")
|
| 387 |
+
if not is_flax_available():
|
| 388 |
+
missing_backends.append("Flax")
|
| 389 |
+
if len(missing_backends) > 0:
|
| 390 |
+
missing = ", ".join(missing_backends)
|
| 391 |
+
if os.getenv("TRANSFORMERS_IS_CI", "").upper() in ENV_VARS_TRUE_VALUES:
|
| 392 |
+
raise Exception(
|
| 393 |
+
"Full repo consistency checks require all backends to be installed (with `pip install -e '.[dev]'` in the "
|
| 394 |
+
f"Transformers repo, the following are missing: {missing}."
|
| 395 |
+
)
|
| 396 |
+
else:
|
| 397 |
+
warnings.warn(
|
| 398 |
+
"Full repo consistency checks require all backends to be installed (with `pip install -e '.[dev]'` in the "
|
| 399 |
+
f"Transformers repo, the following are missing: {missing}. While it's probably fine as long as you "
|
| 400 |
+
"didn't make any change in one of those backends modeling files, you should probably execute the "
|
| 401 |
+
"command above to be on the safe side."
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def check_model_list():
|
| 406 |
+
"""
|
| 407 |
+
Checks the model listed as subfolders of `models` match the models available in `transformers.models`.
|
| 408 |
+
"""
|
| 409 |
+
# Get the models from the directory structure of `src/transformers/models/`
|
| 410 |
+
models_dir = os.path.join(PATH_TO_TRANSFORMERS, "models")
|
| 411 |
+
_models = []
|
| 412 |
+
for model in os.listdir(models_dir):
|
| 413 |
+
if model == "deprecated":
|
| 414 |
+
continue
|
| 415 |
+
model_dir = os.path.join(models_dir, model)
|
| 416 |
+
if os.path.isdir(model_dir) and "__init__.py" in os.listdir(model_dir):
|
| 417 |
+
_models.append(model)
|
| 418 |
+
|
| 419 |
+
# Get the models in the submodule `transformers.models`
|
| 420 |
+
models = [model for model in dir(transformers.models) if not model.startswith("__")]
|
| 421 |
+
|
| 422 |
+
missing_models = sorted(set(_models).difference(models))
|
| 423 |
+
if missing_models:
|
| 424 |
+
raise Exception(
|
| 425 |
+
f"The following models should be included in {models_dir}/__init__.py: {','.join(missing_models)}."
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
# If some modeling modules should be ignored for all checks, they should be added in the nested list
|
| 430 |
+
# _ignore_modules of this function.
|
| 431 |
+
def get_model_modules() -> List[str]:
|
| 432 |
+
"""Get all the model modules inside the transformers library (except deprecated models)."""
|
| 433 |
+
_ignore_modules = [
|
| 434 |
+
"modeling_auto",
|
| 435 |
+
"modeling_encoder_decoder",
|
| 436 |
+
"modeling_marian",
|
| 437 |
+
"modeling_retribert",
|
| 438 |
+
"modeling_flax_auto",
|
| 439 |
+
"modeling_flax_encoder_decoder",
|
| 440 |
+
"modeling_speech_encoder_decoder",
|
| 441 |
+
"modeling_flax_speech_encoder_decoder",
|
| 442 |
+
"modeling_flax_vision_encoder_decoder",
|
| 443 |
+
"modeling_timm_backbone",
|
| 444 |
+
"modeling_tf_auto",
|
| 445 |
+
"modeling_tf_encoder_decoder",
|
| 446 |
+
"modeling_tf_vision_encoder_decoder",
|
| 447 |
+
"modeling_vision_encoder_decoder",
|
| 448 |
+
]
|
| 449 |
+
modules = []
|
| 450 |
+
for model in dir(transformers.models):
|
| 451 |
+
# There are some magic dunder attributes in the dir, we ignore them
|
| 452 |
+
if model == "deprecated" or model.startswith("__"):
|
| 453 |
+
continue
|
| 454 |
+
|
| 455 |
+
model_module = getattr(transformers.models, model)
|
| 456 |
+
for submodule in dir(model_module):
|
| 457 |
+
if submodule.startswith("modeling") and submodule not in _ignore_modules:
|
| 458 |
+
modeling_module = getattr(model_module, submodule)
|
| 459 |
+
modules.append(modeling_module)
|
| 460 |
+
return modules
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def get_models(module: types.ModuleType, include_pretrained: bool = False) -> List[Tuple[str, type]]:
|
| 464 |
+
"""
|
| 465 |
+
Get the objects in a module that are models.
|
| 466 |
+
|
| 467 |
+
Args:
|
| 468 |
+
module (`types.ModuleType`):
|
| 469 |
+
The module from which we are extracting models.
|
| 470 |
+
include_pretrained (`bool`, *optional*, defaults to `False`):
|
| 471 |
+
Whether or not to include the `PreTrainedModel` subclass (like `BertPreTrainedModel`) or not.
|
| 472 |
+
|
| 473 |
+
Returns:
|
| 474 |
+
List[Tuple[str, type]]: List of models as tuples (class name, actual class).
|
| 475 |
+
"""
|
| 476 |
+
models = []
|
| 477 |
+
model_classes = (transformers.PreTrainedModel, transformers.TFPreTrainedModel, transformers.FlaxPreTrainedModel)
|
| 478 |
+
for attr_name in dir(module):
|
| 479 |
+
if not include_pretrained and ("Pretrained" in attr_name or "PreTrained" in attr_name):
|
| 480 |
+
continue
|
| 481 |
+
attr = getattr(module, attr_name)
|
| 482 |
+
if isinstance(attr, type) and issubclass(attr, model_classes) and attr.__module__ == module.__name__:
|
| 483 |
+
models.append((attr_name, attr))
|
| 484 |
+
return models
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def is_building_block(model: str) -> bool:
|
| 488 |
+
"""
|
| 489 |
+
Returns `True` if a model is a building block part of a bigger model.
|
| 490 |
+
"""
|
| 491 |
+
if model.endswith("Wrapper"):
|
| 492 |
+
return True
|
| 493 |
+
if model.endswith("Encoder"):
|
| 494 |
+
return True
|
| 495 |
+
if model.endswith("Decoder"):
|
| 496 |
+
return True
|
| 497 |
+
if model.endswith("Prenet"):
|
| 498 |
+
return True
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
def is_a_private_model(model: str) -> bool:
|
| 502 |
+
"""Returns `True` if the model should not be in the main init."""
|
| 503 |
+
if model in PRIVATE_MODELS:
|
| 504 |
+
return True
|
| 505 |
+
return is_building_block(model)
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def check_models_are_in_init():
|
| 509 |
+
"""Checks all models defined in the library are in the main init."""
|
| 510 |
+
models_not_in_init = []
|
| 511 |
+
dir_transformers = dir(transformers)
|
| 512 |
+
for module in get_model_modules():
|
| 513 |
+
models_not_in_init += [
|
| 514 |
+
model[0] for model in get_models(module, include_pretrained=True) if model[0] not in dir_transformers
|
| 515 |
+
]
|
| 516 |
+
|
| 517 |
+
# Remove private models
|
| 518 |
+
models_not_in_init = [model for model in models_not_in_init if not is_a_private_model(model)]
|
| 519 |
+
if len(models_not_in_init) > 0:
|
| 520 |
+
raise Exception(f"The following models should be in the main init: {','.join(models_not_in_init)}.")
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
# If some test_modeling files should be ignored when checking models are all tested, they should be added in the
|
| 524 |
+
# nested list _ignore_files of this function.
|
| 525 |
+
def get_model_test_files() -> List[str]:
|
| 526 |
+
"""
|
| 527 |
+
Get the model test files.
|
| 528 |
+
|
| 529 |
+
Returns:
|
| 530 |
+
`List[str]`: The list of test files. The returned files will NOT contain the `tests` (i.e. `PATH_TO_TESTS`
|
| 531 |
+
defined in this script). They will be considered as paths relative to `tests`. A caller has to use
|
| 532 |
+
`os.path.join(PATH_TO_TESTS, ...)` to access the files.
|
| 533 |
+
"""
|
| 534 |
+
|
| 535 |
+
_ignore_files = [
|
| 536 |
+
"test_modeling_common",
|
| 537 |
+
"test_modeling_encoder_decoder",
|
| 538 |
+
"test_modeling_flax_encoder_decoder",
|
| 539 |
+
"test_modeling_flax_speech_encoder_decoder",
|
| 540 |
+
"test_modeling_marian",
|
| 541 |
+
"test_modeling_tf_common",
|
| 542 |
+
"test_modeling_tf_encoder_decoder",
|
| 543 |
+
]
|
| 544 |
+
test_files = []
|
| 545 |
+
model_test_root = os.path.join(PATH_TO_TESTS, "models")
|
| 546 |
+
model_test_dirs = []
|
| 547 |
+
for x in os.listdir(model_test_root):
|
| 548 |
+
x = os.path.join(model_test_root, x)
|
| 549 |
+
if os.path.isdir(x):
|
| 550 |
+
model_test_dirs.append(x)
|
| 551 |
+
|
| 552 |
+
for target_dir in [PATH_TO_TESTS] + model_test_dirs:
|
| 553 |
+
for file_or_dir in os.listdir(target_dir):
|
| 554 |
+
path = os.path.join(target_dir, file_or_dir)
|
| 555 |
+
if os.path.isfile(path):
|
| 556 |
+
filename = os.path.split(path)[-1]
|
| 557 |
+
if "test_modeling" in filename and os.path.splitext(filename)[0] not in _ignore_files:
|
| 558 |
+
file = os.path.join(*path.split(os.sep)[1:])
|
| 559 |
+
test_files.append(file)
|
| 560 |
+
|
| 561 |
+
return test_files
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
# This is a bit hacky but I didn't find a way to import the test_file as a module and read inside the tester class
|
| 565 |
+
# for the all_model_classes variable.
|
| 566 |
+
def find_tested_models(test_file: str) -> List[str]:
|
| 567 |
+
"""
|
| 568 |
+
Parse the content of test_file to detect what's in `all_model_classes`. This detects the models that inherit from
|
| 569 |
+
the common test class.
|
| 570 |
+
|
| 571 |
+
Args:
|
| 572 |
+
test_file (`str`): The path to the test file to check
|
| 573 |
+
|
| 574 |
+
Returns:
|
| 575 |
+
`List[str]`: The list of models tested in that file.
|
| 576 |
+
"""
|
| 577 |
+
with open(os.path.join(PATH_TO_TESTS, test_file), "r", encoding="utf-8", newline="\n") as f:
|
| 578 |
+
content = f.read()
|
| 579 |
+
all_models = re.findall(r"all_model_classes\s+=\s+\(\s*\(([^\)]*)\)", content)
|
| 580 |
+
# Check with one less parenthesis as well
|
| 581 |
+
all_models += re.findall(r"all_model_classes\s+=\s+\(([^\)]*)\)", content)
|
| 582 |
+
if len(all_models) > 0:
|
| 583 |
+
model_tested = []
|
| 584 |
+
for entry in all_models:
|
| 585 |
+
for line in entry.split(","):
|
| 586 |
+
name = line.strip()
|
| 587 |
+
if len(name) > 0:
|
| 588 |
+
model_tested.append(name)
|
| 589 |
+
return model_tested
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
def should_be_tested(model_name: str) -> bool:
|
| 593 |
+
"""
|
| 594 |
+
Whether or not a model should be tested.
|
| 595 |
+
"""
|
| 596 |
+
if model_name in IGNORE_NON_TESTED:
|
| 597 |
+
return False
|
| 598 |
+
return not is_building_block(model_name)
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
def check_models_are_tested(module: types.ModuleType, test_file: str) -> List[str]:
|
| 602 |
+
"""Check models defined in a module are all tested in a given file.
|
| 603 |
+
|
| 604 |
+
Args:
|
| 605 |
+
module (`types.ModuleType`): The module in which we get the models.
|
| 606 |
+
test_file (`str`): The path to the file where the module is tested.
|
| 607 |
+
|
| 608 |
+
Returns:
|
| 609 |
+
`List[str]`: The list of error messages corresponding to models not tested.
|
| 610 |
+
"""
|
| 611 |
+
# XxxPreTrainedModel are not tested
|
| 612 |
+
defined_models = get_models(module)
|
| 613 |
+
tested_models = find_tested_models(test_file)
|
| 614 |
+
if tested_models is None:
|
| 615 |
+
if test_file.replace(os.path.sep, "/") in TEST_FILES_WITH_NO_COMMON_TESTS:
|
| 616 |
+
return
|
| 617 |
+
return [
|
| 618 |
+
f"{test_file} should define `all_model_classes` to apply common tests to the models it tests. "
|
| 619 |
+
+ "If this intentional, add the test filename to `TEST_FILES_WITH_NO_COMMON_TESTS` in the file "
|
| 620 |
+
+ "`utils/check_repo.py`."
|
| 621 |
+
]
|
| 622 |
+
failures = []
|
| 623 |
+
for model_name, _ in defined_models:
|
| 624 |
+
if model_name not in tested_models and should_be_tested(model_name):
|
| 625 |
+
failures.append(
|
| 626 |
+
f"{model_name} is defined in {module.__name__} but is not tested in "
|
| 627 |
+
+ f"{os.path.join(PATH_TO_TESTS, test_file)}. Add it to the all_model_classes in that file."
|
| 628 |
+
+ "If common tests should not applied to that model, add its name to `IGNORE_NON_TESTED`"
|
| 629 |
+
+ "in the file `utils/check_repo.py`."
|
| 630 |
+
)
|
| 631 |
+
return failures
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
def check_all_models_are_tested():
|
| 635 |
+
"""Check all models are properly tested."""
|
| 636 |
+
modules = get_model_modules()
|
| 637 |
+
test_files = get_model_test_files()
|
| 638 |
+
failures = []
|
| 639 |
+
for module in modules:
|
| 640 |
+
# Matches a module to its test file.
|
| 641 |
+
test_file = [file for file in test_files if f"test_{module.__name__.split('.')[-1]}.py" in file]
|
| 642 |
+
if len(test_file) == 0:
|
| 643 |
+
failures.append(f"{module.__name__} does not have its corresponding test file {test_file}.")
|
| 644 |
+
elif len(test_file) > 1:
|
| 645 |
+
failures.append(f"{module.__name__} has several test files: {test_file}.")
|
| 646 |
+
else:
|
| 647 |
+
test_file = test_file[0]
|
| 648 |
+
new_failures = check_models_are_tested(module, test_file)
|
| 649 |
+
if new_failures is not None:
|
| 650 |
+
failures += new_failures
|
| 651 |
+
if len(failures) > 0:
|
| 652 |
+
raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures))
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
def get_all_auto_configured_models() -> List[str]:
|
| 656 |
+
"""Return the list of all models in at least one auto class."""
|
| 657 |
+
result = set() # To avoid duplicates we concatenate all model classes in a set.
|
| 658 |
+
if is_torch_available():
|
| 659 |
+
for attr_name in dir(transformers.models.auto.modeling_auto):
|
| 660 |
+
if attr_name.startswith("MODEL_") and attr_name.endswith("MAPPING_NAMES"):
|
| 661 |
+
result = result | set(get_values(getattr(transformers.models.auto.modeling_auto, attr_name)))
|
| 662 |
+
if is_tf_available():
|
| 663 |
+
for attr_name in dir(transformers.models.auto.modeling_tf_auto):
|
| 664 |
+
if attr_name.startswith("TF_MODEL_") and attr_name.endswith("MAPPING_NAMES"):
|
| 665 |
+
result = result | set(get_values(getattr(transformers.models.auto.modeling_tf_auto, attr_name)))
|
| 666 |
+
if is_flax_available():
|
| 667 |
+
for attr_name in dir(transformers.models.auto.modeling_flax_auto):
|
| 668 |
+
if attr_name.startswith("FLAX_MODEL_") and attr_name.endswith("MAPPING_NAMES"):
|
| 669 |
+
result = result | set(get_values(getattr(transformers.models.auto.modeling_flax_auto, attr_name)))
|
| 670 |
+
return list(result)
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
def ignore_unautoclassed(model_name: str) -> bool:
|
| 674 |
+
"""Rules to determine if a model should be in an auto class."""
|
| 675 |
+
# Special white list
|
| 676 |
+
if model_name in IGNORE_NON_AUTO_CONFIGURED:
|
| 677 |
+
return True
|
| 678 |
+
# Encoder and Decoder should be ignored
|
| 679 |
+
if "Encoder" in model_name or "Decoder" in model_name:
|
| 680 |
+
return True
|
| 681 |
+
return False
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def check_models_are_auto_configured(module: types.ModuleType, all_auto_models: List[str]) -> List[str]:
|
| 685 |
+
"""
|
| 686 |
+
Check models defined in module are each in an auto class.
|
| 687 |
+
|
| 688 |
+
Args:
|
| 689 |
+
module (`types.ModuleType`):
|
| 690 |
+
The module in which we get the models.
|
| 691 |
+
all_auto_models (`List[str]`):
|
| 692 |
+
The list of all models in an auto class (as obtained with `get_all_auto_configured_models()`).
|
| 693 |
+
|
| 694 |
+
Returns:
|
| 695 |
+
`List[str]`: The list of error messages corresponding to models not tested.
|
| 696 |
+
"""
|
| 697 |
+
defined_models = get_models(module)
|
| 698 |
+
failures = []
|
| 699 |
+
for model_name, _ in defined_models:
|
| 700 |
+
if model_name not in all_auto_models and not ignore_unautoclassed(model_name):
|
| 701 |
+
failures.append(
|
| 702 |
+
f"{model_name} is defined in {module.__name__} but is not present in any of the auto mapping. "
|
| 703 |
+
"If that is intended behavior, add its name to `IGNORE_NON_AUTO_CONFIGURED` in the file "
|
| 704 |
+
"`utils/check_repo.py`."
|
| 705 |
+
)
|
| 706 |
+
return failures
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
def check_all_models_are_auto_configured():
|
| 710 |
+
"""Check all models are each in an auto class."""
|
| 711 |
+
# This is where we need to check we have all backends or the check is incomplete.
|
| 712 |
+
check_missing_backends()
|
| 713 |
+
modules = get_model_modules()
|
| 714 |
+
all_auto_models = get_all_auto_configured_models()
|
| 715 |
+
failures = []
|
| 716 |
+
for module in modules:
|
| 717 |
+
new_failures = check_models_are_auto_configured(module, all_auto_models)
|
| 718 |
+
if new_failures is not None:
|
| 719 |
+
failures += new_failures
|
| 720 |
+
if len(failures) > 0:
|
| 721 |
+
raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures))
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
def check_all_auto_object_names_being_defined():
|
| 725 |
+
"""Check all names defined in auto (name) mappings exist in the library."""
|
| 726 |
+
# This is where we need to check we have all backends or the check is incomplete.
|
| 727 |
+
check_missing_backends()
|
| 728 |
+
|
| 729 |
+
failures = []
|
| 730 |
+
mappings_to_check = {
|
| 731 |
+
"TOKENIZER_MAPPING_NAMES": TOKENIZER_MAPPING_NAMES,
|
| 732 |
+
"IMAGE_PROCESSOR_MAPPING_NAMES": IMAGE_PROCESSOR_MAPPING_NAMES,
|
| 733 |
+
"FEATURE_EXTRACTOR_MAPPING_NAMES": FEATURE_EXTRACTOR_MAPPING_NAMES,
|
| 734 |
+
"PROCESSOR_MAPPING_NAMES": PROCESSOR_MAPPING_NAMES,
|
| 735 |
+
}
|
| 736 |
+
|
| 737 |
+
# Each auto modeling files contains multiple mappings. Let's get them in a dynamic way.
|
| 738 |
+
for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]:
|
| 739 |
+
module = getattr(transformers.models.auto, module_name, None)
|
| 740 |
+
if module is None:
|
| 741 |
+
continue
|
| 742 |
+
# all mappings in a single auto modeling file
|
| 743 |
+
mapping_names = [x for x in dir(module) if x.endswith("_MAPPING_NAMES")]
|
| 744 |
+
mappings_to_check.update({name: getattr(module, name) for name in mapping_names})
|
| 745 |
+
|
| 746 |
+
for name, mapping in mappings_to_check.items():
|
| 747 |
+
for _, class_names in mapping.items():
|
| 748 |
+
if not isinstance(class_names, tuple):
|
| 749 |
+
class_names = (class_names,)
|
| 750 |
+
for class_name in class_names:
|
| 751 |
+
if class_name is None:
|
| 752 |
+
continue
|
| 753 |
+
# dummy object is accepted
|
| 754 |
+
if not hasattr(transformers, class_name):
|
| 755 |
+
# If the class name is in a model name mapping, let's not check if there is a definition in any modeling
|
| 756 |
+
# module, if it's a private model defined in this file.
|
| 757 |
+
if name.endswith("MODEL_MAPPING_NAMES") and is_a_private_model(class_name):
|
| 758 |
+
continue
|
| 759 |
+
if name.endswith("MODEL_FOR_IMAGE_MAPPING_NAMES") and is_a_private_model(class_name):
|
| 760 |
+
continue
|
| 761 |
+
failures.append(
|
| 762 |
+
f"`{class_name}` appears in the mapping `{name}` but it is not defined in the library."
|
| 763 |
+
)
|
| 764 |
+
if len(failures) > 0:
|
| 765 |
+
raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures))
|
| 766 |
+
|
| 767 |
+
|
| 768 |
+
def check_all_auto_mapping_names_in_config_mapping_names():
|
| 769 |
+
"""Check all keys defined in auto mappings (mappings of names) appear in `CONFIG_MAPPING_NAMES`."""
|
| 770 |
+
# This is where we need to check we have all backends or the check is incomplete.
|
| 771 |
+
check_missing_backends()
|
| 772 |
+
|
| 773 |
+
failures = []
|
| 774 |
+
# `TOKENIZER_PROCESSOR_MAPPING_NAMES` and `AutoTokenizer` is special, and don't need to follow the rule.
|
| 775 |
+
mappings_to_check = {
|
| 776 |
+
"IMAGE_PROCESSOR_MAPPING_NAMES": IMAGE_PROCESSOR_MAPPING_NAMES,
|
| 777 |
+
"FEATURE_EXTRACTOR_MAPPING_NAMES": FEATURE_EXTRACTOR_MAPPING_NAMES,
|
| 778 |
+
"PROCESSOR_MAPPING_NAMES": PROCESSOR_MAPPING_NAMES,
|
| 779 |
+
}
|
| 780 |
+
|
| 781 |
+
# Each auto modeling files contains multiple mappings. Let's get them in a dynamic way.
|
| 782 |
+
for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]:
|
| 783 |
+
module = getattr(transformers.models.auto, module_name, None)
|
| 784 |
+
if module is None:
|
| 785 |
+
continue
|
| 786 |
+
# all mappings in a single auto modeling file
|
| 787 |
+
mapping_names = [x for x in dir(module) if x.endswith("_MAPPING_NAMES")]
|
| 788 |
+
mappings_to_check.update({name: getattr(module, name) for name in mapping_names})
|
| 789 |
+
|
| 790 |
+
for name, mapping in mappings_to_check.items():
|
| 791 |
+
for model_type in mapping:
|
| 792 |
+
if model_type not in CONFIG_MAPPING_NAMES:
|
| 793 |
+
failures.append(
|
| 794 |
+
f"`{model_type}` appears in the mapping `{name}` but it is not defined in the keys of "
|
| 795 |
+
"`CONFIG_MAPPING_NAMES`."
|
| 796 |
+
)
|
| 797 |
+
if len(failures) > 0:
|
| 798 |
+
raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures))
|
| 799 |
+
|
| 800 |
+
|
| 801 |
+
def check_all_auto_mappings_importable():
|
| 802 |
+
"""Check all auto mappings can be imported."""
|
| 803 |
+
# This is where we need to check we have all backends or the check is incomplete.
|
| 804 |
+
check_missing_backends()
|
| 805 |
+
|
| 806 |
+
failures = []
|
| 807 |
+
mappings_to_check = {}
|
| 808 |
+
# Each auto modeling files contains multiple mappings. Let's get them in a dynamic way.
|
| 809 |
+
for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]:
|
| 810 |
+
module = getattr(transformers.models.auto, module_name, None)
|
| 811 |
+
if module is None:
|
| 812 |
+
continue
|
| 813 |
+
# all mappings in a single auto modeling file
|
| 814 |
+
mapping_names = [x for x in dir(module) if x.endswith("_MAPPING_NAMES")]
|
| 815 |
+
mappings_to_check.update({name: getattr(module, name) for name in mapping_names})
|
| 816 |
+
|
| 817 |
+
for name in mappings_to_check:
|
| 818 |
+
name = name.replace("_MAPPING_NAMES", "_MAPPING")
|
| 819 |
+
if not hasattr(transformers, name):
|
| 820 |
+
failures.append(f"`{name}`")
|
| 821 |
+
if len(failures) > 0:
|
| 822 |
+
raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures))
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
def check_objects_being_equally_in_main_init():
|
| 826 |
+
"""
|
| 827 |
+
Check if a (TensorFlow or Flax) object is in the main __init__ iif its counterpart in PyTorch is.
|
| 828 |
+
"""
|
| 829 |
+
attrs = dir(transformers)
|
| 830 |
+
|
| 831 |
+
failures = []
|
| 832 |
+
for attr in attrs:
|
| 833 |
+
obj = getattr(transformers, attr)
|
| 834 |
+
if not hasattr(obj, "__module__") or "models.deprecated" in obj.__module__:
|
| 835 |
+
continue
|
| 836 |
+
|
| 837 |
+
module_path = obj.__module__
|
| 838 |
+
module_name = module_path.split(".")[-1]
|
| 839 |
+
module_dir = ".".join(module_path.split(".")[:-1])
|
| 840 |
+
if (
|
| 841 |
+
module_name.startswith("modeling_")
|
| 842 |
+
and not module_name.startswith("modeling_tf_")
|
| 843 |
+
and not module_name.startswith("modeling_flax_")
|
| 844 |
+
):
|
| 845 |
+
parent_module = sys.modules[module_dir]
|
| 846 |
+
|
| 847 |
+
frameworks = []
|
| 848 |
+
if is_tf_available():
|
| 849 |
+
frameworks.append("TF")
|
| 850 |
+
if is_flax_available():
|
| 851 |
+
frameworks.append("Flax")
|
| 852 |
+
|
| 853 |
+
for framework in frameworks:
|
| 854 |
+
other_module_path = module_path.replace("modeling_", f"modeling_{framework.lower()}_")
|
| 855 |
+
if os.path.isfile("src/" + other_module_path.replace(".", "/") + ".py"):
|
| 856 |
+
other_module_name = module_name.replace("modeling_", f"modeling_{framework.lower()}_")
|
| 857 |
+
other_module = getattr(parent_module, other_module_name)
|
| 858 |
+
if hasattr(other_module, f"{framework}{attr}"):
|
| 859 |
+
if not hasattr(transformers, f"{framework}{attr}"):
|
| 860 |
+
if f"{framework}{attr}" not in OBJECT_TO_SKIP_IN_MAIN_INIT_CHECK:
|
| 861 |
+
failures.append(f"{framework}{attr}")
|
| 862 |
+
if hasattr(other_module, f"{framework}_{attr}"):
|
| 863 |
+
if not hasattr(transformers, f"{framework}_{attr}"):
|
| 864 |
+
if f"{framework}_{attr}" not in OBJECT_TO_SKIP_IN_MAIN_INIT_CHECK:
|
| 865 |
+
failures.append(f"{framework}_{attr}")
|
| 866 |
+
if len(failures) > 0:
|
| 867 |
+
raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures))
|
| 868 |
+
|
| 869 |
+
|
| 870 |
+
_re_decorator = re.compile(r"^\s*@(\S+)\s+$")
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
def check_decorator_order(filename: str) -> List[int]:
|
| 874 |
+
"""
|
| 875 |
+
Check that in a given test file, the slow decorator is always last.
|
| 876 |
+
|
| 877 |
+
Args:
|
| 878 |
+
filename (`str`): The path to a test file to check.
|
| 879 |
+
|
| 880 |
+
Returns:
|
| 881 |
+
`List[int]`: The list of failures as a list of indices where there are problems.
|
| 882 |
+
"""
|
| 883 |
+
with open(filename, "r", encoding="utf-8", newline="\n") as f:
|
| 884 |
+
lines = f.readlines()
|
| 885 |
+
decorator_before = None
|
| 886 |
+
errors = []
|
| 887 |
+
for i, line in enumerate(lines):
|
| 888 |
+
search = _re_decorator.search(line)
|
| 889 |
+
if search is not None:
|
| 890 |
+
decorator_name = search.groups()[0]
|
| 891 |
+
if decorator_before is not None and decorator_name.startswith("parameterized"):
|
| 892 |
+
errors.append(i)
|
| 893 |
+
decorator_before = decorator_name
|
| 894 |
+
elif decorator_before is not None:
|
| 895 |
+
decorator_before = None
|
| 896 |
+
return errors
|
| 897 |
+
|
| 898 |
+
|
| 899 |
+
def check_all_decorator_order():
|
| 900 |
+
"""Check that in all test files, the slow decorator is always last."""
|
| 901 |
+
errors = []
|
| 902 |
+
for fname in os.listdir(PATH_TO_TESTS):
|
| 903 |
+
if fname.endswith(".py"):
|
| 904 |
+
filename = os.path.join(PATH_TO_TESTS, fname)
|
| 905 |
+
new_errors = check_decorator_order(filename)
|
| 906 |
+
errors += [f"- {filename}, line {i}" for i in new_errors]
|
| 907 |
+
if len(errors) > 0:
|
| 908 |
+
msg = "\n".join(errors)
|
| 909 |
+
raise ValueError(
|
| 910 |
+
"The parameterized decorator (and its variants) should always be first, but this is not the case in the"
|
| 911 |
+
f" following files:\n{msg}"
|
| 912 |
+
)
|
| 913 |
+
|
| 914 |
+
|
| 915 |
+
def find_all_documented_objects() -> List[str]:
|
| 916 |
+
"""
|
| 917 |
+
Parse the content of all doc files to detect which classes and functions it documents.
|
| 918 |
+
|
| 919 |
+
Returns:
|
| 920 |
+
`List[str]`: The list of all object names being documented.
|
| 921 |
+
`Dict[str, List[str]]`: A dictionary mapping the object name (full import path, e.g.
|
| 922 |
+
`integrations.PeftAdapterMixin`) to its documented methods
|
| 923 |
+
"""
|
| 924 |
+
documented_obj = []
|
| 925 |
+
documented_methods_map = {}
|
| 926 |
+
for doc_file in Path(PATH_TO_DOC).glob("**/*.md"):
|
| 927 |
+
with open(doc_file, "r", encoding="utf-8", newline="\n") as f:
|
| 928 |
+
content = f.read()
|
| 929 |
+
raw_doc_objs = re.findall(r"\[\[autodoc\]\]\s+(\S+)\s+", content)
|
| 930 |
+
documented_obj += [obj.split(".")[-1] for obj in raw_doc_objs]
|
| 931 |
+
|
| 932 |
+
for obj in raw_doc_objs:
|
| 933 |
+
obj_public_methods = re.findall(rf"\[\[autodoc\]\] {obj}((\n\s+-.*)+)", content)
|
| 934 |
+
# Some objects have no methods documented
|
| 935 |
+
if len(obj_public_methods) == 0:
|
| 936 |
+
continue
|
| 937 |
+
else:
|
| 938 |
+
documented_methods_map[obj] = re.findall(r"(?<=-\s).*", obj_public_methods[0][0])
|
| 939 |
+
|
| 940 |
+
return documented_obj, documented_methods_map
|
| 941 |
+
|
| 942 |
+
|
| 943 |
+
# One good reason for not being documented is to be deprecated. Put in this list deprecated objects.
|
| 944 |
+
DEPRECATED_OBJECTS = [
|
| 945 |
+
"AutoModelWithLMHead",
|
| 946 |
+
"BartPretrainedModel",
|
| 947 |
+
"DataCollator",
|
| 948 |
+
"DataCollatorForSOP",
|
| 949 |
+
"GlueDataset",
|
| 950 |
+
"GlueDataTrainingArguments",
|
| 951 |
+
"LineByLineTextDataset",
|
| 952 |
+
"LineByLineWithRefDataset",
|
| 953 |
+
"LineByLineWithSOPTextDataset",
|
| 954 |
+
"NerPipeline",
|
| 955 |
+
"PretrainedBartModel",
|
| 956 |
+
"PretrainedFSMTModel",
|
| 957 |
+
"SingleSentenceClassificationProcessor",
|
| 958 |
+
"SquadDataTrainingArguments",
|
| 959 |
+
"SquadDataset",
|
| 960 |
+
"SquadExample",
|
| 961 |
+
"SquadFeatures",
|
| 962 |
+
"SquadV1Processor",
|
| 963 |
+
"SquadV2Processor",
|
| 964 |
+
"TFAutoModelWithLMHead",
|
| 965 |
+
"TFBartPretrainedModel",
|
| 966 |
+
"TextDataset",
|
| 967 |
+
"TextDatasetForNextSentencePrediction",
|
| 968 |
+
"Wav2Vec2ForMaskedLM",
|
| 969 |
+
"Wav2Vec2Tokenizer",
|
| 970 |
+
"glue_compute_metrics",
|
| 971 |
+
"glue_convert_examples_to_features",
|
| 972 |
+
"glue_output_modes",
|
| 973 |
+
"glue_processors",
|
| 974 |
+
"glue_tasks_num_labels",
|
| 975 |
+
"squad_convert_examples_to_features",
|
| 976 |
+
"xnli_compute_metrics",
|
| 977 |
+
"xnli_output_modes",
|
| 978 |
+
"xnli_processors",
|
| 979 |
+
"xnli_tasks_num_labels",
|
| 980 |
+
"TFTrainingArguments",
|
| 981 |
+
"OwlViTFeatureExtractor",
|
| 982 |
+
]
|
| 983 |
+
|
| 984 |
+
# Exceptionally, some objects should not be documented after all rules passed.
|
| 985 |
+
# ONLY PUT SOMETHING IN THIS LIST AS A LAST RESORT!
|
| 986 |
+
UNDOCUMENTED_OBJECTS = [
|
| 987 |
+
"AddedToken", # This is a tokenizers class.
|
| 988 |
+
"BasicTokenizer", # Internal, should never have been in the main init.
|
| 989 |
+
"CharacterTokenizer", # Internal, should never have been in the main init.
|
| 990 |
+
"DPRPretrainedReader", # Like an Encoder.
|
| 991 |
+
"DummyObject", # Just picked by mistake sometimes.
|
| 992 |
+
"MecabTokenizer", # Internal, should never have been in the main init.
|
| 993 |
+
"ModelCard", # Internal type.
|
| 994 |
+
"SqueezeBertModule", # Internal building block (should have been called SqueezeBertLayer)
|
| 995 |
+
"TFDPRPretrainedReader", # Like an Encoder.
|
| 996 |
+
"TransfoXLCorpus", # Internal type.
|
| 997 |
+
"WordpieceTokenizer", # Internal, should never have been in the main init.
|
| 998 |
+
"absl", # External module
|
| 999 |
+
"add_end_docstrings", # Internal, should never have been in the main init.
|
| 1000 |
+
"add_start_docstrings", # Internal, should never have been in the main init.
|
| 1001 |
+
"convert_tf_weight_name_to_pt_weight_name", # Internal used to convert model weights
|
| 1002 |
+
"logger", # Internal logger
|
| 1003 |
+
"logging", # External module
|
| 1004 |
+
"requires_backends", # Internal function
|
| 1005 |
+
"AltRobertaModel", # Internal module
|
| 1006 |
+
"VitPoseBackbone", # Internal module
|
| 1007 |
+
"VitPoseBackboneConfig", # Internal module
|
| 1008 |
+
]
|
| 1009 |
+
|
| 1010 |
+
# This list should be empty. Objects in it should get their own doc page.
|
| 1011 |
+
SHOULD_HAVE_THEIR_OWN_PAGE = [
|
| 1012 |
+
"AutoBackbone",
|
| 1013 |
+
"BeitBackbone",
|
| 1014 |
+
"BitBackbone",
|
| 1015 |
+
"ConvNextBackbone",
|
| 1016 |
+
"ConvNextV2Backbone",
|
| 1017 |
+
"DinatBackbone",
|
| 1018 |
+
"Dinov2Backbone",
|
| 1019 |
+
"Dinov2WithRegistersBackbone",
|
| 1020 |
+
"FocalNetBackbone",
|
| 1021 |
+
"HieraBackbone",
|
| 1022 |
+
"MaskFormerSwinBackbone",
|
| 1023 |
+
"MaskFormerSwinConfig",
|
| 1024 |
+
"MaskFormerSwinModel",
|
| 1025 |
+
"NatBackbone",
|
| 1026 |
+
"PvtV2Backbone",
|
| 1027 |
+
"ResNetBackbone",
|
| 1028 |
+
"SwinBackbone",
|
| 1029 |
+
"Swinv2Backbone",
|
| 1030 |
+
"TextNetBackbone",
|
| 1031 |
+
"TimmBackbone",
|
| 1032 |
+
"TimmBackboneConfig",
|
| 1033 |
+
"VitDetBackbone",
|
| 1034 |
+
]
|
| 1035 |
+
|
| 1036 |
+
|
| 1037 |
+
def ignore_undocumented(name: str) -> bool:
|
| 1038 |
+
"""Rules to determine if `name` should be undocumented (returns `True` if it should not be documented)."""
|
| 1039 |
+
# NOT DOCUMENTED ON PURPOSE.
|
| 1040 |
+
# Constants uppercase are not documented.
|
| 1041 |
+
if name.isupper():
|
| 1042 |
+
return True
|
| 1043 |
+
# PreTrainedModels / Encoders / Decoders / Layers / Embeddings / Attention are not documented.
|
| 1044 |
+
if (
|
| 1045 |
+
name.endswith("PreTrainedModel")
|
| 1046 |
+
or name.endswith("Decoder")
|
| 1047 |
+
or name.endswith("Encoder")
|
| 1048 |
+
or name.endswith("Layer")
|
| 1049 |
+
or name.endswith("Embeddings")
|
| 1050 |
+
or name.endswith("Attention")
|
| 1051 |
+
):
|
| 1052 |
+
return True
|
| 1053 |
+
# Submodules are not documented.
|
| 1054 |
+
if os.path.isdir(os.path.join(PATH_TO_TRANSFORMERS, name)) or os.path.isfile(
|
| 1055 |
+
os.path.join(PATH_TO_TRANSFORMERS, f"{name}.py")
|
| 1056 |
+
):
|
| 1057 |
+
return True
|
| 1058 |
+
# All load functions are not documented.
|
| 1059 |
+
if name.startswith("load_tf") or name.startswith("load_pytorch"):
|
| 1060 |
+
return True
|
| 1061 |
+
# is_xxx_available functions are not documented.
|
| 1062 |
+
if name.startswith("is_") and name.endswith("_available"):
|
| 1063 |
+
return True
|
| 1064 |
+
# Deprecated objects are not documented.
|
| 1065 |
+
if name in DEPRECATED_OBJECTS or name in UNDOCUMENTED_OBJECTS:
|
| 1066 |
+
return True
|
| 1067 |
+
# MMBT model does not really work.
|
| 1068 |
+
if name.startswith("MMBT"):
|
| 1069 |
+
return True
|
| 1070 |
+
if name in SHOULD_HAVE_THEIR_OWN_PAGE:
|
| 1071 |
+
return True
|
| 1072 |
+
return False
|
| 1073 |
+
|
| 1074 |
+
|
| 1075 |
+
def check_all_objects_are_documented():
|
| 1076 |
+
"""Check all models are properly documented."""
|
| 1077 |
+
documented_objs, documented_methods_map = find_all_documented_objects()
|
| 1078 |
+
modules = transformers._modules
|
| 1079 |
+
objects = [c for c in dir(transformers) if c not in modules and not c.startswith("_")]
|
| 1080 |
+
undocumented_objs = [c for c in objects if c not in documented_objs and not ignore_undocumented(c)]
|
| 1081 |
+
if len(undocumented_objs) > 0:
|
| 1082 |
+
raise Exception(
|
| 1083 |
+
"The following objects are in the public init so should be documented:\n - "
|
| 1084 |
+
+ "\n - ".join(undocumented_objs)
|
| 1085 |
+
)
|
| 1086 |
+
check_model_type_doc_match()
|
| 1087 |
+
check_public_method_exists(documented_methods_map)
|
| 1088 |
+
|
| 1089 |
+
|
| 1090 |
+
def check_public_method_exists(documented_methods_map):
|
| 1091 |
+
"""Check that all explicitly documented public methods are defined in the corresponding class."""
|
| 1092 |
+
failures = []
|
| 1093 |
+
for obj, methods in documented_methods_map.items():
|
| 1094 |
+
# Let's ensure there is no repetition
|
| 1095 |
+
if len(set(methods)) != len(methods):
|
| 1096 |
+
failures.append(f"Error in the documentation of {obj}: there are repeated documented methods.")
|
| 1097 |
+
|
| 1098 |
+
# Navigates into the object, given the full import path
|
| 1099 |
+
nested_path = obj.split(".")
|
| 1100 |
+
submodule = transformers
|
| 1101 |
+
if len(nested_path) > 1:
|
| 1102 |
+
nested_submodules = nested_path[:-1]
|
| 1103 |
+
for submodule_name in nested_submodules:
|
| 1104 |
+
if submodule_name == "transformers":
|
| 1105 |
+
continue
|
| 1106 |
+
|
| 1107 |
+
try:
|
| 1108 |
+
submodule = getattr(submodule, submodule_name)
|
| 1109 |
+
except AttributeError:
|
| 1110 |
+
failures.append(f"Could not parse {submodule_name}. Are the required dependencies installed?")
|
| 1111 |
+
continue
|
| 1112 |
+
|
| 1113 |
+
class_name = nested_path[-1]
|
| 1114 |
+
|
| 1115 |
+
try:
|
| 1116 |
+
obj_class = getattr(submodule, class_name)
|
| 1117 |
+
except AttributeError:
|
| 1118 |
+
failures.append(f"Could not parse {class_name}. Are the required dependencies installed?")
|
| 1119 |
+
continue
|
| 1120 |
+
|
| 1121 |
+
# Checks that all explicitly documented methods are defined in the class
|
| 1122 |
+
for method in methods:
|
| 1123 |
+
if method == "all": # Special keyword to document all public methods
|
| 1124 |
+
continue
|
| 1125 |
+
try:
|
| 1126 |
+
if not hasattr(obj_class, method):
|
| 1127 |
+
failures.append(
|
| 1128 |
+
"The following public method is explicitly documented but not defined in the corresponding "
|
| 1129 |
+
f"class. class: {obj}, method: {method}. If the method is defined, this error can be due to "
|
| 1130 |
+
f"lacking dependencies."
|
| 1131 |
+
)
|
| 1132 |
+
except ImportError:
|
| 1133 |
+
pass
|
| 1134 |
+
|
| 1135 |
+
if len(failures) > 0:
|
| 1136 |
+
raise Exception("\n".join(failures))
|
| 1137 |
+
|
| 1138 |
+
|
| 1139 |
+
def check_model_type_doc_match():
|
| 1140 |
+
"""Check all doc pages have a corresponding model type."""
|
| 1141 |
+
model_doc_folder = Path(PATH_TO_DOC) / "model_doc"
|
| 1142 |
+
model_docs = [m.stem for m in model_doc_folder.glob("*.md")]
|
| 1143 |
+
|
| 1144 |
+
model_types = list(transformers.models.auto.configuration_auto.MODEL_NAMES_MAPPING.keys())
|
| 1145 |
+
model_types = [MODEL_TYPE_TO_DOC_MAPPING[m] if m in MODEL_TYPE_TO_DOC_MAPPING else m for m in model_types]
|
| 1146 |
+
|
| 1147 |
+
errors = []
|
| 1148 |
+
for m in model_docs:
|
| 1149 |
+
if m not in model_types and m != "auto":
|
| 1150 |
+
close_matches = get_close_matches(m, model_types)
|
| 1151 |
+
error_message = f"{m} is not a proper model identifier."
|
| 1152 |
+
if len(close_matches) > 0:
|
| 1153 |
+
close_matches = "/".join(close_matches)
|
| 1154 |
+
error_message += f" Did you mean {close_matches}?"
|
| 1155 |
+
errors.append(error_message)
|
| 1156 |
+
|
| 1157 |
+
if len(errors) > 0:
|
| 1158 |
+
raise ValueError(
|
| 1159 |
+
"Some model doc pages do not match any existing model type:\n"
|
| 1160 |
+
+ "\n".join(errors)
|
| 1161 |
+
+ "\nYou can add any missing model type to the `MODEL_NAMES_MAPPING` constant in "
|
| 1162 |
+
"models/auto/configuration_auto.py."
|
| 1163 |
+
)
|
| 1164 |
+
|
| 1165 |
+
|
| 1166 |
+
def check_deprecated_constant_is_up_to_date():
|
| 1167 |
+
"""
|
| 1168 |
+
Check if the constant `DEPRECATED_MODELS` in `models/auto/configuration_auto.py` is up to date.
|
| 1169 |
+
"""
|
| 1170 |
+
deprecated_folder = os.path.join(PATH_TO_TRANSFORMERS, "models", "deprecated")
|
| 1171 |
+
deprecated_models = [m for m in os.listdir(deprecated_folder) if not m.startswith("_")]
|
| 1172 |
+
|
| 1173 |
+
constant_to_check = transformers.models.auto.configuration_auto.DEPRECATED_MODELS
|
| 1174 |
+
message = []
|
| 1175 |
+
missing_models = sorted(set(deprecated_models) - set(constant_to_check))
|
| 1176 |
+
if len(missing_models) != 0:
|
| 1177 |
+
missing_models = ", ".join(missing_models)
|
| 1178 |
+
message.append(
|
| 1179 |
+
"The following models are in the deprecated folder, make sure to add them to `DEPRECATED_MODELS` in "
|
| 1180 |
+
f"`models/auto/configuration_auto.py`: {missing_models}."
|
| 1181 |
+
)
|
| 1182 |
+
|
| 1183 |
+
extra_models = sorted(set(constant_to_check) - set(deprecated_models))
|
| 1184 |
+
if len(extra_models) != 0:
|
| 1185 |
+
extra_models = ", ".join(extra_models)
|
| 1186 |
+
message.append(
|
| 1187 |
+
"The following models are in the `DEPRECATED_MODELS` constant but not in the deprecated folder. Either "
|
| 1188 |
+
f"remove them from the constant or move to the deprecated folder: {extra_models}."
|
| 1189 |
+
)
|
| 1190 |
+
|
| 1191 |
+
if len(message) > 0:
|
| 1192 |
+
raise Exception("\n".join(message))
|
| 1193 |
+
|
| 1194 |
+
|
| 1195 |
+
def check_repo_quality():
|
| 1196 |
+
"""Check all models are tested and documented."""
|
| 1197 |
+
print("Repository-wide checks:")
|
| 1198 |
+
print(" - checking all models are included.")
|
| 1199 |
+
check_model_list()
|
| 1200 |
+
print(" - checking all models are public.")
|
| 1201 |
+
check_models_are_in_init()
|
| 1202 |
+
print(" - checking all models have tests.")
|
| 1203 |
+
check_all_decorator_order()
|
| 1204 |
+
check_all_models_are_tested()
|
| 1205 |
+
print(" - checking all objects have documentation.")
|
| 1206 |
+
check_all_objects_are_documented()
|
| 1207 |
+
print(" - checking all models are in at least one auto class.")
|
| 1208 |
+
check_all_models_are_auto_configured()
|
| 1209 |
+
print(" - checking all names in auto name mappings are defined.")
|
| 1210 |
+
check_all_auto_object_names_being_defined()
|
| 1211 |
+
print(" - checking all keys in auto name mappings are defined in `CONFIG_MAPPING_NAMES`.")
|
| 1212 |
+
check_all_auto_mapping_names_in_config_mapping_names()
|
| 1213 |
+
print(" - checking all auto mappings could be imported.")
|
| 1214 |
+
check_all_auto_mappings_importable()
|
| 1215 |
+
print(" - checking all objects are equally (across frameworks) in the main __init__.")
|
| 1216 |
+
check_objects_being_equally_in_main_init()
|
| 1217 |
+
print(" - checking the DEPRECATED_MODELS constant is up to date.")
|
| 1218 |
+
check_deprecated_constant_is_up_to_date()
|
| 1219 |
+
|
| 1220 |
+
|
| 1221 |
+
if __name__ == "__main__":
|
| 1222 |
+
check_repo_quality()
|
tasks/tasksmith-441eeab80047/environment/source/utils/check_self_hosted_runner.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
import subprocess
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def get_runner_status(target_runners, token):
|
| 7 |
+
offline_runners = []
|
| 8 |
+
|
| 9 |
+
cmd = (
|
| 10 |
+
f'curl -H "Accept: application/vnd.github+json" -H "Authorization: Bearer {token}"'
|
| 11 |
+
" https://api.github.com/repos/huggingface/transformers/actions/runners"
|
| 12 |
+
)
|
| 13 |
+
output = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE)
|
| 14 |
+
o = output.stdout.decode("utf-8")
|
| 15 |
+
status = json.loads(o)
|
| 16 |
+
|
| 17 |
+
runners = status["runners"]
|
| 18 |
+
for runner in runners:
|
| 19 |
+
if runner["name"] in target_runners:
|
| 20 |
+
if runner["status"] == "offline":
|
| 21 |
+
offline_runners.append(runner)
|
| 22 |
+
|
| 23 |
+
# save the result so we can report them on Slack
|
| 24 |
+
with open("offline_runners.txt", "w") as fp:
|
| 25 |
+
fp.write(json.dumps(offline_runners))
|
| 26 |
+
|
| 27 |
+
if len(offline_runners) > 0:
|
| 28 |
+
failed = "\n".join([x["name"] for x in offline_runners])
|
| 29 |
+
raise ValueError(f"The following runners are offline:\n{failed}")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
if __name__ == "__main__":
|
| 33 |
+
|
| 34 |
+
def list_str(values):
|
| 35 |
+
return values.split(",")
|
| 36 |
+
|
| 37 |
+
parser = argparse.ArgumentParser()
|
| 38 |
+
# Required parameters
|
| 39 |
+
parser.add_argument(
|
| 40 |
+
"--target_runners",
|
| 41 |
+
default=None,
|
| 42 |
+
type=list_str,
|
| 43 |
+
required=True,
|
| 44 |
+
help="Comma-separated list of runners to check status.",
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
parser.add_argument(
|
| 48 |
+
"--token", default=None, type=str, required=True, help="A token that has actions:read permission."
|
| 49 |
+
)
|
| 50 |
+
args = parser.parse_args()
|
| 51 |
+
|
| 52 |
+
get_runner_status(args.target_runners, args.token)
|
tasks/tasksmith-441eeab80047/environment/source/utils/check_tf_ops.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 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 json
|
| 18 |
+
import os
|
| 19 |
+
|
| 20 |
+
from tensorflow.core.protobuf.saved_model_pb2 import SavedModel
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# All paths are set with the intent you should run this script from the root of the repo with the command
|
| 24 |
+
# python utils/check_copies.py
|
| 25 |
+
REPO_PATH = "."
|
| 26 |
+
|
| 27 |
+
# Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model)
|
| 28 |
+
INTERNAL_OPS = [
|
| 29 |
+
"Assert",
|
| 30 |
+
"AssignVariableOp",
|
| 31 |
+
"EmptyTensorList",
|
| 32 |
+
"MergeV2Checkpoints",
|
| 33 |
+
"ReadVariableOp",
|
| 34 |
+
"ResourceGather",
|
| 35 |
+
"RestoreV2",
|
| 36 |
+
"SaveV2",
|
| 37 |
+
"ShardedFilename",
|
| 38 |
+
"StatefulPartitionedCall",
|
| 39 |
+
"StaticRegexFullMatch",
|
| 40 |
+
"VarHandleOp",
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def onnx_compliancy(saved_model_path, strict, opset):
|
| 45 |
+
saved_model = SavedModel()
|
| 46 |
+
onnx_ops = []
|
| 47 |
+
|
| 48 |
+
with open(os.path.join(REPO_PATH, "utils", "tf_ops", "onnx.json")) as f:
|
| 49 |
+
onnx_opsets = json.load(f)["opsets"]
|
| 50 |
+
|
| 51 |
+
for i in range(1, opset + 1):
|
| 52 |
+
onnx_ops.extend(onnx_opsets[str(i)])
|
| 53 |
+
|
| 54 |
+
with open(saved_model_path, "rb") as f:
|
| 55 |
+
saved_model.ParseFromString(f.read())
|
| 56 |
+
|
| 57 |
+
model_op_names = set()
|
| 58 |
+
|
| 59 |
+
# Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs)
|
| 60 |
+
for meta_graph in saved_model.meta_graphs:
|
| 61 |
+
# Add operations in the graph definition
|
| 62 |
+
model_op_names.update(node.op for node in meta_graph.graph_def.node)
|
| 63 |
+
|
| 64 |
+
# Go through the functions in the graph definition
|
| 65 |
+
for func in meta_graph.graph_def.library.function:
|
| 66 |
+
# Add operations in each function
|
| 67 |
+
model_op_names.update(node.op for node in func.node_def)
|
| 68 |
+
|
| 69 |
+
# Convert to list, sorted if you want
|
| 70 |
+
model_op_names = sorted(model_op_names)
|
| 71 |
+
incompatible_ops = []
|
| 72 |
+
|
| 73 |
+
for op in model_op_names:
|
| 74 |
+
if op not in onnx_ops and op not in INTERNAL_OPS:
|
| 75 |
+
incompatible_ops.append(op)
|
| 76 |
+
|
| 77 |
+
if strict and len(incompatible_ops) > 0:
|
| 78 |
+
raise Exception(f"Found the following incompatible ops for the opset {opset}:\n" + incompatible_ops)
|
| 79 |
+
elif len(incompatible_ops) > 0:
|
| 80 |
+
print(f"Found the following incompatible ops for the opset {opset}:")
|
| 81 |
+
print(*incompatible_ops, sep="\n")
|
| 82 |
+
else:
|
| 83 |
+
print(f"The saved model {saved_model_path} can properly be converted with ONNX.")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
if __name__ == "__main__":
|
| 87 |
+
parser = argparse.ArgumentParser()
|
| 88 |
+
parser.add_argument("--saved_model_path", help="Path of the saved model to check (the .pb file).")
|
| 89 |
+
parser.add_argument(
|
| 90 |
+
"--opset", default=12, type=int, help="The ONNX opset against which the model has to be tested."
|
| 91 |
+
)
|
| 92 |
+
parser.add_argument(
|
| 93 |
+
"--framework", choices=["onnx"], default="onnx", help="Frameworks against which to test the saved model."
|
| 94 |
+
)
|
| 95 |
+
parser.add_argument(
|
| 96 |
+
"--strict", action="store_true", help="Whether make the checking strict (raise errors) or not (raise warnings)"
|
| 97 |
+
)
|
| 98 |
+
args = parser.parse_args()
|
| 99 |
+
|
| 100 |
+
if args.framework == "onnx":
|
| 101 |
+
onnx_compliancy(args.saved_model_path, args.strict, args.opset)
|
tasks/tasksmith-441eeab80047/environment/source/utils/create_dependency_mapping.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ast
|
| 2 |
+
from collections import defaultdict
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
# Function to perform topological sorting
|
| 6 |
+
def topological_sort(dependencies: dict):
|
| 7 |
+
# Nodes are the name of the models to convert (we only add those to the graph)
|
| 8 |
+
nodes = {node.rsplit("modular_", 1)[1].replace(".py", "") for node in dependencies.keys()}
|
| 9 |
+
# This will be a graph from models to convert, to models to convert that should be converted before (as they are a dependency)
|
| 10 |
+
graph = {}
|
| 11 |
+
name_mapping = {}
|
| 12 |
+
for node, deps in dependencies.items():
|
| 13 |
+
node_name = node.rsplit("modular_", 1)[1].replace(".py", "")
|
| 14 |
+
dep_names = {dep.split(".")[-2] for dep in deps}
|
| 15 |
+
dependencies = {dep for dep in dep_names if dep in nodes and dep != node_name}
|
| 16 |
+
graph[node_name] = dependencies
|
| 17 |
+
name_mapping[node_name] = node
|
| 18 |
+
|
| 19 |
+
sorting_list = []
|
| 20 |
+
while len(graph) > 0:
|
| 21 |
+
# Find the nodes with 0 out-degree
|
| 22 |
+
leaf_nodes = {node for node in graph if len(graph[node]) == 0}
|
| 23 |
+
# Add them to the list
|
| 24 |
+
sorting_list += list(leaf_nodes)
|
| 25 |
+
# Remove the leafs from the graph (and from the deps of other nodes)
|
| 26 |
+
graph = {node: deps - leaf_nodes for node, deps in graph.items() if node not in leaf_nodes}
|
| 27 |
+
|
| 28 |
+
return [name_mapping[x] for x in sorting_list]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Function to extract class and import info from a file
|
| 32 |
+
def extract_classes_and_imports(file_path):
|
| 33 |
+
with open(file_path, "r", encoding="utf-8") as file:
|
| 34 |
+
tree = ast.parse(file.read(), filename=file_path)
|
| 35 |
+
imports = set()
|
| 36 |
+
|
| 37 |
+
for node in ast.walk(tree):
|
| 38 |
+
if isinstance(node, (ast.Import, ast.ImportFrom)):
|
| 39 |
+
module = node.module if isinstance(node, ast.ImportFrom) else None
|
| 40 |
+
if module and (".modeling_" in module or "transformers.models" in module):
|
| 41 |
+
imports.add(module)
|
| 42 |
+
return imports
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# Function to map dependencies between classes
|
| 46 |
+
def map_dependencies(py_files):
|
| 47 |
+
dependencies = defaultdict(set)
|
| 48 |
+
# First pass: Extract all classes and map to files
|
| 49 |
+
for file_path in py_files:
|
| 50 |
+
# dependencies[file_path].add(None)
|
| 51 |
+
class_to_file = extract_classes_and_imports(file_path)
|
| 52 |
+
for module in class_to_file:
|
| 53 |
+
dependencies[file_path].add(module)
|
| 54 |
+
return dependencies
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def find_priority_list(py_files):
|
| 58 |
+
"""
|
| 59 |
+
Given a list of modular files, sorts them by topological order. Modular models that DON'T depend on other modular
|
| 60 |
+
models will be higher in the topological order.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
py_files: List of paths to the modular files
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
A tuple with the ordered files (list) and their dependencies (dict)
|
| 67 |
+
"""
|
| 68 |
+
dependencies = map_dependencies(py_files)
|
| 69 |
+
ordered_files = topological_sort(dependencies)
|
| 70 |
+
return ordered_files, dependencies
|
tasks/tasksmith-441eeab80047/environment/source/utils/create_dummy_models.py
ADDED
|
@@ -0,0 +1,1577 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import collections.abc
|
| 18 |
+
import copy
|
| 19 |
+
import inspect
|
| 20 |
+
import json
|
| 21 |
+
import multiprocessing
|
| 22 |
+
import os
|
| 23 |
+
import shutil
|
| 24 |
+
import tempfile
|
| 25 |
+
import traceback
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
from check_config_docstrings import get_checkpoint_from_config_class
|
| 29 |
+
from datasets import load_dataset
|
| 30 |
+
from get_test_info import get_model_to_tester_mapping, get_tester_classes_for_model
|
| 31 |
+
from huggingface_hub import Repository, create_repo, hf_api, upload_folder
|
| 32 |
+
|
| 33 |
+
from transformers import (
|
| 34 |
+
CONFIG_MAPPING,
|
| 35 |
+
FEATURE_EXTRACTOR_MAPPING,
|
| 36 |
+
IMAGE_PROCESSOR_MAPPING,
|
| 37 |
+
PROCESSOR_MAPPING,
|
| 38 |
+
TOKENIZER_MAPPING,
|
| 39 |
+
AutoTokenizer,
|
| 40 |
+
LayoutLMv3TokenizerFast,
|
| 41 |
+
PreTrainedTokenizer,
|
| 42 |
+
PreTrainedTokenizerFast,
|
| 43 |
+
logging,
|
| 44 |
+
)
|
| 45 |
+
from transformers.feature_extraction_utils import FeatureExtractionMixin
|
| 46 |
+
from transformers.file_utils import is_tf_available, is_torch_available
|
| 47 |
+
from transformers.image_processing_utils import BaseImageProcessor
|
| 48 |
+
from transformers.models.auto.configuration_auto import AutoConfig, model_type_to_module_name
|
| 49 |
+
from transformers.models.fsmt import configuration_fsmt
|
| 50 |
+
from transformers.processing_utils import ProcessorMixin, transformers_module
|
| 51 |
+
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# make sure tokenizer plays nice with multiprocessing
|
| 55 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 56 |
+
|
| 57 |
+
logging.set_verbosity_error()
|
| 58 |
+
logging.disable_progress_bar()
|
| 59 |
+
logger = logging.get_logger(__name__)
|
| 60 |
+
|
| 61 |
+
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
|
| 62 |
+
|
| 63 |
+
if not is_torch_available():
|
| 64 |
+
raise ValueError("Please install PyTorch.")
|
| 65 |
+
|
| 66 |
+
if not is_tf_available():
|
| 67 |
+
raise ValueError("Please install TensorFlow.")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
FRAMEWORKS = ["pytorch", "tensorflow"]
|
| 71 |
+
INVALID_ARCH = []
|
| 72 |
+
TARGET_VOCAB_SIZE = 1024
|
| 73 |
+
|
| 74 |
+
data = {"training_ds": None, "testing_ds": None}
|
| 75 |
+
|
| 76 |
+
COMPOSITE_MODELS = {
|
| 77 |
+
"EncoderDecoderModel": "EncoderDecoderModel-bert-bert",
|
| 78 |
+
"SpeechEncoderDecoderModel": "SpeechEncoderDecoderModel-wav2vec2-bert",
|
| 79 |
+
"VisionEncoderDecoderModel": "VisionEncoderDecoderModel-vit-gpt2",
|
| 80 |
+
"VisionTextDualEncoderModel": "VisionTextDualEncoderModel-vit-bert",
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
# This list contains the model architectures for which a tiny version could not be created.
|
| 84 |
+
# Avoid to add new architectures here - unless we have verified carefully that it's (almost) impossible to create them.
|
| 85 |
+
# One such case is: no model tester class is implemented for a model type (like `MT5`) because its architecture is
|
| 86 |
+
# identical to another one (`MT5` is based on `T5`), but trained on different datasets or with different techniques.
|
| 87 |
+
UNCONVERTIBLE_MODEL_ARCHITECTURES = {
|
| 88 |
+
"BertGenerationEncoder",
|
| 89 |
+
"BertGenerationDecoder",
|
| 90 |
+
"CamembertForSequenceClassification",
|
| 91 |
+
"CamembertForMultipleChoice",
|
| 92 |
+
"CamembertForMaskedLM",
|
| 93 |
+
"CamembertForCausalLM",
|
| 94 |
+
"CamembertForTokenClassification",
|
| 95 |
+
"CamembertForQuestionAnswering",
|
| 96 |
+
"CamembertModel",
|
| 97 |
+
"TFCamembertForMultipleChoice",
|
| 98 |
+
"TFCamembertForTokenClassification",
|
| 99 |
+
"TFCamembertForQuestionAnswering",
|
| 100 |
+
"TFCamembertForSequenceClassification",
|
| 101 |
+
"TFCamembertForMaskedLM",
|
| 102 |
+
"TFCamembertModel",
|
| 103 |
+
"TFCamembertForCausalLM",
|
| 104 |
+
"DecisionTransformerModel",
|
| 105 |
+
"GraphormerModel",
|
| 106 |
+
"InformerModel",
|
| 107 |
+
"JukeboxModel",
|
| 108 |
+
"MarianForCausalLM",
|
| 109 |
+
"MaskFormerSwinModel",
|
| 110 |
+
"MaskFormerSwinBackbone",
|
| 111 |
+
"MT5Model",
|
| 112 |
+
"MT5ForConditionalGeneration",
|
| 113 |
+
"UMT5ForConditionalGeneration",
|
| 114 |
+
"TFMT5ForConditionalGeneration",
|
| 115 |
+
"TFMT5Model",
|
| 116 |
+
"QDQBertForSequenceClassification",
|
| 117 |
+
"QDQBertForMaskedLM",
|
| 118 |
+
"QDQBertModel",
|
| 119 |
+
"QDQBertForTokenClassification",
|
| 120 |
+
"QDQBertLMHeadModel",
|
| 121 |
+
"QDQBertForMultipleChoice",
|
| 122 |
+
"QDQBertForQuestionAnswering",
|
| 123 |
+
"QDQBertForNextSentencePrediction",
|
| 124 |
+
"ReformerModelWithLMHead",
|
| 125 |
+
"RetriBertModel",
|
| 126 |
+
"Speech2Text2ForCausalLM",
|
| 127 |
+
"TimeSeriesTransformerModel",
|
| 128 |
+
"TrajectoryTransformerModel",
|
| 129 |
+
"TrOCRForCausalLM",
|
| 130 |
+
"XLMProphetNetForConditionalGeneration",
|
| 131 |
+
"XLMProphetNetForCausalLM",
|
| 132 |
+
"XLMProphetNetModel",
|
| 133 |
+
"XLMRobertaModel",
|
| 134 |
+
"XLMRobertaForTokenClassification",
|
| 135 |
+
"XLMRobertaForMultipleChoice",
|
| 136 |
+
"XLMRobertaForMaskedLM",
|
| 137 |
+
"XLMRobertaForCausalLM",
|
| 138 |
+
"XLMRobertaForSequenceClassification",
|
| 139 |
+
"XLMRobertaForQuestionAnswering",
|
| 140 |
+
"TFXLMRobertaForSequenceClassification",
|
| 141 |
+
"TFXLMRobertaForMaskedLM",
|
| 142 |
+
"TFXLMRobertaForCausalLM",
|
| 143 |
+
"TFXLMRobertaForQuestionAnswering",
|
| 144 |
+
"TFXLMRobertaModel",
|
| 145 |
+
"TFXLMRobertaForMultipleChoice",
|
| 146 |
+
"TFXLMRobertaForTokenClassification",
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def get_processor_types_from_config_class(config_class, allowed_mappings=None):
|
| 151 |
+
"""Return a tuple of processors for `config_class`.
|
| 152 |
+
|
| 153 |
+
We use `tuple` here to include (potentially) both slow & fast tokenizers.
|
| 154 |
+
"""
|
| 155 |
+
|
| 156 |
+
# To make a uniform return type
|
| 157 |
+
def _to_tuple(x):
|
| 158 |
+
if not isinstance(x, collections.abc.Sequence):
|
| 159 |
+
x = (x,)
|
| 160 |
+
else:
|
| 161 |
+
x = tuple(x)
|
| 162 |
+
return x
|
| 163 |
+
|
| 164 |
+
if allowed_mappings is None:
|
| 165 |
+
allowed_mappings = ["processor", "tokenizer", "image_processor", "feature_extractor"]
|
| 166 |
+
|
| 167 |
+
processor_types = ()
|
| 168 |
+
|
| 169 |
+
# Check first if a model has `ProcessorMixin`. Otherwise, check if it has tokenizers, and/or an image processor or
|
| 170 |
+
# a feature extractor
|
| 171 |
+
if config_class in PROCESSOR_MAPPING and "processor" in allowed_mappings:
|
| 172 |
+
processor_types = _to_tuple(PROCESSOR_MAPPING[config_class])
|
| 173 |
+
else:
|
| 174 |
+
if config_class in TOKENIZER_MAPPING and "tokenizer" in allowed_mappings:
|
| 175 |
+
processor_types = TOKENIZER_MAPPING[config_class]
|
| 176 |
+
|
| 177 |
+
if config_class in IMAGE_PROCESSOR_MAPPING and "image_processor" in allowed_mappings:
|
| 178 |
+
processor_types += _to_tuple(IMAGE_PROCESSOR_MAPPING[config_class])
|
| 179 |
+
elif config_class in FEATURE_EXTRACTOR_MAPPING and "feature_extractor" in allowed_mappings:
|
| 180 |
+
processor_types += _to_tuple(FEATURE_EXTRACTOR_MAPPING[config_class])
|
| 181 |
+
|
| 182 |
+
# Remark: some configurations have no processor at all. For example, generic composite models like
|
| 183 |
+
# `EncoderDecoderModel` is used for any (compatible) text models. Also, `DecisionTransformer` doesn't
|
| 184 |
+
# require any processor.
|
| 185 |
+
|
| 186 |
+
# We might get `None` for some tokenizers - remove them here.
|
| 187 |
+
processor_types = tuple(p for p in processor_types if p is not None)
|
| 188 |
+
|
| 189 |
+
return processor_types
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def get_architectures_from_config_class(config_class, arch_mappings, models_to_skip=None):
|
| 193 |
+
"""Return a tuple of all possible architectures attributed to a configuration class `config_class`.
|
| 194 |
+
|
| 195 |
+
For example, BertConfig -> [BertModel, BertForMaskedLM, ..., BertForQuestionAnswering].
|
| 196 |
+
"""
|
| 197 |
+
# A model architecture could appear in several mappings. For example, `BartForConditionalGeneration` is in
|
| 198 |
+
# - MODEL_FOR_PRETRAINING_MAPPING_NAMES
|
| 199 |
+
# - MODEL_WITH_LM_HEAD_MAPPING_NAMES
|
| 200 |
+
# - MODEL_FOR_MASKED_LM_MAPPING_NAMES
|
| 201 |
+
# - MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
|
| 202 |
+
# We avoid the duplication.
|
| 203 |
+
architectures = set()
|
| 204 |
+
|
| 205 |
+
if models_to_skip is None:
|
| 206 |
+
models_to_skip = []
|
| 207 |
+
models_to_skip = UNCONVERTIBLE_MODEL_ARCHITECTURES.union(models_to_skip)
|
| 208 |
+
|
| 209 |
+
for mapping in arch_mappings:
|
| 210 |
+
if config_class in mapping:
|
| 211 |
+
models = mapping[config_class]
|
| 212 |
+
models = tuple(models) if isinstance(models, collections.abc.Sequence) else (models,)
|
| 213 |
+
for model in models:
|
| 214 |
+
if model.__name__ not in models_to_skip:
|
| 215 |
+
architectures.add(model)
|
| 216 |
+
|
| 217 |
+
architectures = tuple(architectures)
|
| 218 |
+
|
| 219 |
+
return architectures
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def get_config_class_from_processor_class(processor_class):
|
| 223 |
+
"""Get the config class from a processor class.
|
| 224 |
+
|
| 225 |
+
Some config/model classes use tokenizers/feature_extractors from other models. For example, `GPT-J` uses
|
| 226 |
+
`GPT2Tokenizer`. If no checkpoint is found for a config class, or a checkpoint is found without necessary file(s) to
|
| 227 |
+
create the processor for `processor_class`, we get the config class that corresponds to `processor_class` and use it
|
| 228 |
+
to find a checkpoint in order to create the processor.
|
| 229 |
+
"""
|
| 230 |
+
|
| 231 |
+
processor_prefix = processor_class.__name__
|
| 232 |
+
for postfix in ["TokenizerFast", "Tokenizer", "ImageProcessor", "FeatureExtractor", "Processor"]:
|
| 233 |
+
processor_prefix = processor_prefix.replace(postfix, "")
|
| 234 |
+
|
| 235 |
+
# `Wav2Vec2CTCTokenizer` -> `Wav2Vec2Config`
|
| 236 |
+
if processor_prefix == "Wav2Vec2CTC":
|
| 237 |
+
processor_prefix = "Wav2Vec2"
|
| 238 |
+
|
| 239 |
+
# Find the new configuration class
|
| 240 |
+
new_config_name = f"{processor_prefix}Config"
|
| 241 |
+
new_config_class = getattr(transformers_module, new_config_name)
|
| 242 |
+
|
| 243 |
+
return new_config_class
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def build_processor(config_class, processor_class, allow_no_checkpoint=False):
|
| 247 |
+
"""Create a processor for `processor_class`.
|
| 248 |
+
|
| 249 |
+
If a processor is not able to be built with the original arguments, this method tries to change the arguments and
|
| 250 |
+
call itself recursively, by inferring a new `config_class` or a new `processor_class` from another one, in order to
|
| 251 |
+
find a checkpoint containing the necessary files to build a processor.
|
| 252 |
+
|
| 253 |
+
The processor is not saved here. Instead, it will be saved in `convert_processors` after further changes in
|
| 254 |
+
`convert_processors`. For each model architecture`, a copy will be created and saved along the built model.
|
| 255 |
+
"""
|
| 256 |
+
# Currently, this solely uses the docstring in the source file of `config_class` to find a checkpoint.
|
| 257 |
+
checkpoint = get_checkpoint_from_config_class(config_class)
|
| 258 |
+
|
| 259 |
+
if checkpoint is None:
|
| 260 |
+
# try to get the checkpoint from the config class for `processor_class`.
|
| 261 |
+
# This helps cases like `XCLIPConfig` and `VideoMAEFeatureExtractor` to find a checkpoint from `VideoMAEConfig`.
|
| 262 |
+
config_class_from_processor_class = get_config_class_from_processor_class(processor_class)
|
| 263 |
+
checkpoint = get_checkpoint_from_config_class(config_class_from_processor_class)
|
| 264 |
+
|
| 265 |
+
processor = None
|
| 266 |
+
try:
|
| 267 |
+
processor = processor_class.from_pretrained(checkpoint)
|
| 268 |
+
except Exception as e:
|
| 269 |
+
logger.error(f"{e.__class__.__name__}: {e}")
|
| 270 |
+
|
| 271 |
+
# Try to get a new processor class from checkpoint. This is helpful for a checkpoint without necessary file to load
|
| 272 |
+
# processor while `processor_class` is an Auto class. For example, `sew` has `Wav2Vec2Processor` in
|
| 273 |
+
# `PROCESSOR_MAPPING_NAMES`, its `tokenizer_class` is `AutoTokenizer`, and the checkpoint
|
| 274 |
+
# `https://huggingface.co/asapp/sew-tiny-100k` has no tokenizer file, but we can get
|
| 275 |
+
# `tokenizer_class: Wav2Vec2CTCTokenizer` from the config file. (The new processor class won't be able to load from
|
| 276 |
+
# `checkpoint`, but it helps this recursive method to find a way to build a processor).
|
| 277 |
+
if (
|
| 278 |
+
processor is None
|
| 279 |
+
and checkpoint is not None
|
| 280 |
+
and issubclass(processor_class, (PreTrainedTokenizerBase, AutoTokenizer))
|
| 281 |
+
):
|
| 282 |
+
try:
|
| 283 |
+
config = AutoConfig.from_pretrained(checkpoint)
|
| 284 |
+
except Exception as e:
|
| 285 |
+
logger.error(f"{e.__class__.__name__}: {e}")
|
| 286 |
+
config = None
|
| 287 |
+
if config is not None:
|
| 288 |
+
if not isinstance(config, config_class):
|
| 289 |
+
raise ValueError(
|
| 290 |
+
f"`config` (which is of type {config.__class__.__name__}) should be an instance of `config_class`"
|
| 291 |
+
f" ({config_class.__name__})!"
|
| 292 |
+
)
|
| 293 |
+
tokenizer_class = config.tokenizer_class
|
| 294 |
+
new_processor_class = None
|
| 295 |
+
if tokenizer_class is not None:
|
| 296 |
+
new_processor_class = getattr(transformers_module, tokenizer_class)
|
| 297 |
+
if new_processor_class != processor_class:
|
| 298 |
+
processor = build_processor(config_class, new_processor_class)
|
| 299 |
+
# If `tokenizer_class` is not specified in `config`, let's use `config` to get the process class via auto
|
| 300 |
+
# mappings, but only allow the tokenizer mapping being used. This is to make `Wav2Vec2Conformer` build
|
| 301 |
+
if processor is None:
|
| 302 |
+
new_processor_classes = get_processor_types_from_config_class(
|
| 303 |
+
config.__class__, allowed_mappings=["tokenizer"]
|
| 304 |
+
)
|
| 305 |
+
# Used to avoid infinite recursion between a pair of fast/slow tokenizer types
|
| 306 |
+
names = [
|
| 307 |
+
x.__name__.replace("Fast", "") for x in [processor_class, new_processor_class] if x is not None
|
| 308 |
+
]
|
| 309 |
+
new_processor_classes = [
|
| 310 |
+
x for x in new_processor_classes if x is not None and x.__name__.replace("Fast", "") not in names
|
| 311 |
+
]
|
| 312 |
+
if len(new_processor_classes) > 0:
|
| 313 |
+
new_processor_class = new_processor_classes[0]
|
| 314 |
+
# Let's use fast tokenizer if there is any
|
| 315 |
+
for x in new_processor_classes:
|
| 316 |
+
if x.__name__.endswith("Fast"):
|
| 317 |
+
new_processor_class = x
|
| 318 |
+
break
|
| 319 |
+
processor = build_processor(config_class, new_processor_class)
|
| 320 |
+
|
| 321 |
+
if processor is None:
|
| 322 |
+
# Try to build each component (tokenizer & feature extractor) of a `ProcessorMixin`.
|
| 323 |
+
if issubclass(processor_class, ProcessorMixin):
|
| 324 |
+
attrs = {}
|
| 325 |
+
for attr_name in processor_class.attributes:
|
| 326 |
+
attrs[attr_name] = []
|
| 327 |
+
# This could be a tuple (for tokenizers). For example, `CLIPProcessor` has
|
| 328 |
+
# - feature_extractor_class = "CLIPFeatureExtractor"
|
| 329 |
+
# - tokenizer_class = ("CLIPTokenizer", "CLIPTokenizerFast")
|
| 330 |
+
attr_class_names = getattr(processor_class, f"{attr_name}_class")
|
| 331 |
+
if not isinstance(attr_class_names, tuple):
|
| 332 |
+
attr_class_names = (attr_class_names,)
|
| 333 |
+
|
| 334 |
+
for name in attr_class_names:
|
| 335 |
+
attr_class = getattr(transformers_module, name)
|
| 336 |
+
attr = build_processor(config_class, attr_class)
|
| 337 |
+
if attr is not None:
|
| 338 |
+
attrs[attr_name].append(attr)
|
| 339 |
+
|
| 340 |
+
# try to build a `ProcessorMixin`, so we can return a single value
|
| 341 |
+
if all(len(v) > 0 for v in attrs.values()):
|
| 342 |
+
try:
|
| 343 |
+
processor = processor_class(**{k: v[0] for k, v in attrs.items()})
|
| 344 |
+
except Exception as e:
|
| 345 |
+
logger.error(f"{e.__class__.__name__}: {e}")
|
| 346 |
+
else:
|
| 347 |
+
# `checkpoint` might lack some file(s) to load a processor. For example, `facebook/hubert-base-ls960`
|
| 348 |
+
# has no tokenizer file to load `Wav2Vec2CTCTokenizer`. In this case, we try to build a processor
|
| 349 |
+
# with the configuration class (for example, `Wav2Vec2Config`) corresponding to `processor_class`.
|
| 350 |
+
config_class_from_processor_class = get_config_class_from_processor_class(processor_class)
|
| 351 |
+
if config_class_from_processor_class != config_class:
|
| 352 |
+
processor = build_processor(config_class_from_processor_class, processor_class)
|
| 353 |
+
|
| 354 |
+
# Try to create an image processor or a feature extractor without any checkpoint
|
| 355 |
+
if (
|
| 356 |
+
processor is None
|
| 357 |
+
and allow_no_checkpoint
|
| 358 |
+
and (issubclass(processor_class, BaseImageProcessor) or issubclass(processor_class, FeatureExtractionMixin))
|
| 359 |
+
):
|
| 360 |
+
try:
|
| 361 |
+
processor = processor_class()
|
| 362 |
+
except Exception as e:
|
| 363 |
+
logger.error(f"{e.__class__.__name__}: {e}")
|
| 364 |
+
|
| 365 |
+
# validation
|
| 366 |
+
if processor is not None:
|
| 367 |
+
if not (isinstance(processor, processor_class) or processor_class.__name__.startswith("Auto")):
|
| 368 |
+
raise ValueError(
|
| 369 |
+
f"`processor` (which is of type {processor.__class__.__name__}) should be an instance of"
|
| 370 |
+
f" {processor_class.__name__} or an Auto class!"
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
return processor
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def get_tiny_config(config_class, model_class=None, **model_tester_kwargs):
|
| 377 |
+
"""Retrieve a tiny configuration from `config_class` using each model's `ModelTester`.
|
| 378 |
+
|
| 379 |
+
Args:
|
| 380 |
+
config_class: Subclass of `PreTrainedConfig`.
|
| 381 |
+
|
| 382 |
+
Returns:
|
| 383 |
+
An instance of `config_class` with tiny hyperparameters
|
| 384 |
+
"""
|
| 385 |
+
model_type = config_class.model_type
|
| 386 |
+
|
| 387 |
+
# For model type like `data2vec-vision` and `donut-swin`, we can't get the config/model file name directly via
|
| 388 |
+
# `model_type` as it would be sth. like `configuration_data2vec_vision.py`.
|
| 389 |
+
# A simple way is to use `inspect.getsourcefile(config_class)`.
|
| 390 |
+
config_source_file = inspect.getsourcefile(config_class)
|
| 391 |
+
# The modeling file name without prefix (`modeling_`) and postfix (`.py`)
|
| 392 |
+
modeling_name = config_source_file.split(os.path.sep)[-1].replace("configuration_", "").replace(".py", "")
|
| 393 |
+
|
| 394 |
+
try:
|
| 395 |
+
print("Importing", model_type_to_module_name(model_type))
|
| 396 |
+
module_name = model_type_to_module_name(model_type)
|
| 397 |
+
if not modeling_name.startswith(module_name):
|
| 398 |
+
raise ValueError(f"{modeling_name} doesn't start with {module_name}!")
|
| 399 |
+
test_file = os.path.join("tests", "models", module_name, f"test_modeling_{modeling_name}.py")
|
| 400 |
+
models_to_model_testers = get_model_to_tester_mapping(test_file)
|
| 401 |
+
# Find the model tester class
|
| 402 |
+
model_tester_class = None
|
| 403 |
+
tester_classes = []
|
| 404 |
+
if model_class is not None:
|
| 405 |
+
tester_classes = get_tester_classes_for_model(test_file, model_class)
|
| 406 |
+
else:
|
| 407 |
+
for _tester_classes in models_to_model_testers.values():
|
| 408 |
+
tester_classes.extend(_tester_classes)
|
| 409 |
+
if len(tester_classes) > 0:
|
| 410 |
+
# sort with the length of the class names first, then the alphabetical order
|
| 411 |
+
# This is to avoid `T5EncoderOnlyModelTest` is used instead of `T5ModelTest`, which has
|
| 412 |
+
# `is_encoder_decoder=False` and causes some pipeline tests failing (also failures in `Optimum` CI).
|
| 413 |
+
# TODO: More fine grained control of the desired tester class.
|
| 414 |
+
model_tester_class = sorted(tester_classes, key=lambda x: (len(x.__name__), x.__name__))[0]
|
| 415 |
+
except ModuleNotFoundError:
|
| 416 |
+
error = f"Tiny config not created for {model_type} - cannot find the testing module from the model name."
|
| 417 |
+
raise ValueError(error)
|
| 418 |
+
|
| 419 |
+
if model_tester_class is None:
|
| 420 |
+
error = f"Tiny config not created for {model_type} - no model tester is found in the testing module."
|
| 421 |
+
raise ValueError(error)
|
| 422 |
+
|
| 423 |
+
# CLIP-like models have `text_model_tester` and `vision_model_tester`, and we need to pass `vocab_size` to
|
| 424 |
+
# `text_model_tester` via `text_kwargs`. The same trick is also necessary for `Flava`.
|
| 425 |
+
|
| 426 |
+
if "vocab_size" in model_tester_kwargs:
|
| 427 |
+
if "text_kwargs" in inspect.signature(model_tester_class.__init__).parameters.keys():
|
| 428 |
+
vocab_size = model_tester_kwargs.pop("vocab_size")
|
| 429 |
+
model_tester_kwargs["text_kwargs"] = {"vocab_size": vocab_size}
|
| 430 |
+
|
| 431 |
+
# `parent` is an instance of `unittest.TestCase`, but we don't need it here.
|
| 432 |
+
model_tester = model_tester_class(parent=None, **model_tester_kwargs)
|
| 433 |
+
|
| 434 |
+
if hasattr(model_tester, "get_pipeline_config"):
|
| 435 |
+
config = model_tester.get_pipeline_config()
|
| 436 |
+
elif hasattr(model_tester, "prepare_config_and_inputs"):
|
| 437 |
+
# `PoolFormer` has no `get_config` defined. Furthermore, it's better to use `prepare_config_and_inputs` even if
|
| 438 |
+
# `get_config` is defined, since there might be some extra changes in `prepare_config_and_inputs`.
|
| 439 |
+
config = model_tester.prepare_config_and_inputs()[0]
|
| 440 |
+
elif hasattr(model_tester, "get_config"):
|
| 441 |
+
config = model_tester.get_config()
|
| 442 |
+
else:
|
| 443 |
+
error = (
|
| 444 |
+
f"Tiny config not created for {model_type} - the model tester {model_tester_class.__name__} lacks"
|
| 445 |
+
" necessary method to create config."
|
| 446 |
+
)
|
| 447 |
+
raise ValueError(error)
|
| 448 |
+
|
| 449 |
+
# make sure this is long enough (some model tester has `20` for this attr.) to pass `text-generation`
|
| 450 |
+
# pipeline tests.
|
| 451 |
+
max_positions = []
|
| 452 |
+
for key in ["max_position_embeddings", "max_source_positions", "max_target_positions"]:
|
| 453 |
+
if getattr(config, key, 0) > 0:
|
| 454 |
+
max_positions.append(getattr(config, key))
|
| 455 |
+
if getattr(config, "text_config", None) is not None:
|
| 456 |
+
if getattr(config.text_config, key, None) is not None:
|
| 457 |
+
max_positions.append(getattr(config.text_config, key))
|
| 458 |
+
if len(max_positions) > 0:
|
| 459 |
+
max_position = max(200, min(max_positions))
|
| 460 |
+
for key in ["max_position_embeddings", "max_source_positions", "max_target_positions"]:
|
| 461 |
+
if getattr(config, key, 0) > 0:
|
| 462 |
+
setattr(config, key, max_position)
|
| 463 |
+
if getattr(config, "text_config", None) is not None:
|
| 464 |
+
if getattr(config.text_config, key, None) is not None:
|
| 465 |
+
setattr(config.text_config, key, max_position)
|
| 466 |
+
|
| 467 |
+
return config
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def convert_tokenizer(tokenizer_fast: PreTrainedTokenizerFast):
|
| 471 |
+
new_tokenizer = tokenizer_fast.train_new_from_iterator(
|
| 472 |
+
data["training_ds"]["text"], TARGET_VOCAB_SIZE, show_progress=False
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
# Make sure it at least runs
|
| 476 |
+
if not isinstance(new_tokenizer, LayoutLMv3TokenizerFast):
|
| 477 |
+
new_tokenizer(data["testing_ds"]["text"])
|
| 478 |
+
|
| 479 |
+
return new_tokenizer
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def convert_feature_extractor(feature_extractor, tiny_config):
|
| 483 |
+
to_convert = False
|
| 484 |
+
kwargs = {}
|
| 485 |
+
if hasattr(tiny_config, "image_size"):
|
| 486 |
+
kwargs["size"] = tiny_config.image_size
|
| 487 |
+
kwargs["crop_size"] = tiny_config.image_size
|
| 488 |
+
to_convert = True
|
| 489 |
+
elif (
|
| 490 |
+
hasattr(tiny_config, "vision_config")
|
| 491 |
+
and tiny_config.vision_config is not None
|
| 492 |
+
and hasattr(tiny_config.vision_config, "image_size")
|
| 493 |
+
):
|
| 494 |
+
kwargs["size"] = tiny_config.vision_config.image_size
|
| 495 |
+
kwargs["crop_size"] = tiny_config.vision_config.image_size
|
| 496 |
+
to_convert = True
|
| 497 |
+
|
| 498 |
+
# Speech2TextModel specific.
|
| 499 |
+
if hasattr(tiny_config, "input_feat_per_channel"):
|
| 500 |
+
kwargs["feature_size"] = tiny_config.input_feat_per_channel
|
| 501 |
+
kwargs["num_mel_bins"] = tiny_config.input_feat_per_channel
|
| 502 |
+
to_convert = True
|
| 503 |
+
|
| 504 |
+
if to_convert:
|
| 505 |
+
feature_extractor = feature_extractor.__class__(**kwargs)
|
| 506 |
+
|
| 507 |
+
# Sanity check: on tiny image feature extractors, a large image size results in slow CI -- up to the point where it
|
| 508 |
+
# can result in timeout issues.
|
| 509 |
+
if (
|
| 510 |
+
isinstance(feature_extractor, BaseImageProcessor)
|
| 511 |
+
and hasattr(feature_extractor, "size")
|
| 512 |
+
and isinstance(feature_extractor.size, dict)
|
| 513 |
+
):
|
| 514 |
+
largest_image_size = max(feature_extractor.size.values())
|
| 515 |
+
if largest_image_size > 64:
|
| 516 |
+
# hardcoded exceptions
|
| 517 |
+
models_with_large_image_size = ("deformable_detr", "flava", "grounding_dino", "mgp_str", "swiftformer")
|
| 518 |
+
if any(model_name in tiny_config.model_type for model_name in models_with_large_image_size):
|
| 519 |
+
pass
|
| 520 |
+
else:
|
| 521 |
+
raise ValueError(
|
| 522 |
+
f"Image size of {tiny_config.model_type} is too large ({feature_extractor.size}). "
|
| 523 |
+
"Please reduce it to 64 or less on each dimension. The following steps are usually the "
|
| 524 |
+
"easiest solution: 1) confirm that you're setting `image_size` in your ModelTester class; "
|
| 525 |
+
"2) ensure that it gets passed to the tester config init, `get_config()`."
|
| 526 |
+
)
|
| 527 |
+
|
| 528 |
+
return feature_extractor
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def convert_processors(processors, tiny_config, output_folder, result):
|
| 532 |
+
"""Change a processor to work with smaller inputs.
|
| 533 |
+
|
| 534 |
+
For tokenizers, we try to reduce their vocabulary size.
|
| 535 |
+
|
| 536 |
+
For feature extractor, we use smaller image size or change
|
| 537 |
+
other attributes using the values from `tiny_config`. See `convert_feature_extractor`.
|
| 538 |
+
|
| 539 |
+
This method should not fail: we catch the errors and put them in `result["warnings"]` with descriptive messages.
|
| 540 |
+
"""
|
| 541 |
+
|
| 542 |
+
def _sanity_check(fast_tokenizer, slow_tokenizer, keep_fast_tokenizer=False):
|
| 543 |
+
"""Set tokenizer(s) to `None` if the fast/slow tokenizers have different values for `vocab_size` or `length`.
|
| 544 |
+
|
| 545 |
+
If `keep_fast_tokenizer=True`, the fast tokenizer will be kept.
|
| 546 |
+
"""
|
| 547 |
+
# sanity check 1: fast and slow tokenizers should be compatible (vocab_size)
|
| 548 |
+
if fast_tokenizer is not None and slow_tokenizer is not None:
|
| 549 |
+
if fast_tokenizer.vocab_size != slow_tokenizer.vocab_size:
|
| 550 |
+
warning_message = (
|
| 551 |
+
"The fast/slow tokenizers "
|
| 552 |
+
f"({fast_tokenizer.__class__.__name__}/{slow_tokenizer.__class__.__name__}) have different "
|
| 553 |
+
"vocabulary size: "
|
| 554 |
+
f"fast_tokenizer.vocab_size = {fast_tokenizer.vocab_size} and "
|
| 555 |
+
f"slow_tokenizer.vocab_size = {slow_tokenizer.vocab_size}."
|
| 556 |
+
)
|
| 557 |
+
result["warnings"].append(warning_message)
|
| 558 |
+
if not keep_fast_tokenizer:
|
| 559 |
+
fast_tokenizer = None
|
| 560 |
+
slow_tokenizer = None
|
| 561 |
+
|
| 562 |
+
# sanity check 2: fast and slow tokenizers should be compatible (length)
|
| 563 |
+
if fast_tokenizer is not None and slow_tokenizer is not None:
|
| 564 |
+
if len(fast_tokenizer) != len(slow_tokenizer):
|
| 565 |
+
warning_message = (
|
| 566 |
+
f"The fast/slow tokenizers () have different length: "
|
| 567 |
+
f"len(fast_tokenizer) = {len(fast_tokenizer)} and "
|
| 568 |
+
f"len(slow_tokenizer) = {len(slow_tokenizer)}."
|
| 569 |
+
)
|
| 570 |
+
result["warnings"].append(warning_message)
|
| 571 |
+
if not keep_fast_tokenizer:
|
| 572 |
+
fast_tokenizer = None
|
| 573 |
+
slow_tokenizer = None
|
| 574 |
+
|
| 575 |
+
return fast_tokenizer, slow_tokenizer
|
| 576 |
+
|
| 577 |
+
tokenizers = []
|
| 578 |
+
feature_extractors = []
|
| 579 |
+
for processor in processors:
|
| 580 |
+
if isinstance(processor, PreTrainedTokenizerBase):
|
| 581 |
+
if processor.__class__.__name__ not in {x.__class__.__name__ for x in tokenizers}:
|
| 582 |
+
tokenizers.append(processor)
|
| 583 |
+
elif isinstance(processor, BaseImageProcessor):
|
| 584 |
+
if processor.__class__.__name__ not in {x.__class__.__name__ for x in feature_extractors}:
|
| 585 |
+
feature_extractors.append(processor)
|
| 586 |
+
elif isinstance(processor, FeatureExtractionMixin):
|
| 587 |
+
if processor.__class__.__name__ not in {x.__class__.__name__ for x in feature_extractors}:
|
| 588 |
+
feature_extractors.append(processor)
|
| 589 |
+
elif isinstance(processor, ProcessorMixin):
|
| 590 |
+
if hasattr(processor, "tokenizer"):
|
| 591 |
+
if processor.tokenizer.__class__.__name__ not in {x.__class__.__name__ for x in tokenizers}:
|
| 592 |
+
tokenizers.append(processor.tokenizer)
|
| 593 |
+
# Currently, we only have these 2 possibilities
|
| 594 |
+
if hasattr(processor, "image_processor"):
|
| 595 |
+
if processor.image_processor.__class__.__name__ not in {
|
| 596 |
+
x.__class__.__name__ for x in feature_extractors
|
| 597 |
+
}:
|
| 598 |
+
feature_extractors.append(processor.image_processor)
|
| 599 |
+
elif hasattr(processor, "feature_extractor"):
|
| 600 |
+
if processor.feature_extractor.__class__.__name__ not in {
|
| 601 |
+
x.__class__.__name__ for x in feature_extractors
|
| 602 |
+
}:
|
| 603 |
+
feature_extractors.append(processor.feature_extractor)
|
| 604 |
+
|
| 605 |
+
# check the built processors have the unique type
|
| 606 |
+
num_types = len({x.__class__.__name__ for x in feature_extractors})
|
| 607 |
+
if num_types >= 2:
|
| 608 |
+
raise ValueError(f"`feature_extractors` should contain at most 1 type, but it contains {num_types} types!")
|
| 609 |
+
num_types = len({x.__class__.__name__.replace("Fast", "") for x in tokenizers})
|
| 610 |
+
if num_types >= 2:
|
| 611 |
+
raise ValueError(f"`tokenizers` should contain at most 1 tokenizer type, but it contains {num_types} types!")
|
| 612 |
+
|
| 613 |
+
fast_tokenizer = None
|
| 614 |
+
slow_tokenizer = None
|
| 615 |
+
|
| 616 |
+
for tokenizer in tokenizers:
|
| 617 |
+
if isinstance(tokenizer, PreTrainedTokenizerFast):
|
| 618 |
+
fast_tokenizer = tokenizer
|
| 619 |
+
else:
|
| 620 |
+
slow_tokenizer = tokenizer
|
| 621 |
+
|
| 622 |
+
# If the (original) fast/slow tokenizers don't correspond, keep only the fast tokenizer.
|
| 623 |
+
# This doesn't necessarily imply the fast/slow tokenizers in a single Hub repo. has issues.
|
| 624 |
+
# It's more of an issue in `build_processor` which tries to get a checkpoint with as much effort as possible.
|
| 625 |
+
# For `YosoModel` (which uses `AlbertTokenizer(Fast)`), its real (Hub) checkpoint doesn't contain valid files to
|
| 626 |
+
# load the slower tokenizer (`AlbertTokenizer`), and it ends up finding the (canonical) checkpoint of `AlbertModel`,
|
| 627 |
+
# which has different vocabulary.
|
| 628 |
+
# TODO: Try to improve `build_processor`'s definition and/or usage to avoid the above situation in the first place.
|
| 629 |
+
fast_tokenizer, slow_tokenizer = _sanity_check(fast_tokenizer, slow_tokenizer, keep_fast_tokenizer=True)
|
| 630 |
+
original_fast_tokenizer, original_slow_tokenizer = fast_tokenizer, slow_tokenizer
|
| 631 |
+
|
| 632 |
+
if fast_tokenizer:
|
| 633 |
+
try:
|
| 634 |
+
# Wav2Vec2ForCTC , ByT5Tokenizer etc. all are already small enough and have no fast version that can
|
| 635 |
+
# be retrained
|
| 636 |
+
if fast_tokenizer.vocab_size > TARGET_VOCAB_SIZE:
|
| 637 |
+
fast_tokenizer = convert_tokenizer(fast_tokenizer)
|
| 638 |
+
except Exception:
|
| 639 |
+
result["warnings"].append(
|
| 640 |
+
(
|
| 641 |
+
f"Failed to convert the fast tokenizer for {fast_tokenizer.__class__.__name__}.",
|
| 642 |
+
traceback.format_exc(),
|
| 643 |
+
)
|
| 644 |
+
)
|
| 645 |
+
|
| 646 |
+
# If `fast_tokenizer` exists, `slow_tokenizer` should correspond to it.
|
| 647 |
+
if fast_tokenizer:
|
| 648 |
+
# Make sure the fast tokenizer can be saved
|
| 649 |
+
try:
|
| 650 |
+
# We don't save it to `output_folder` at this moment - only at the end of this function.
|
| 651 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 652 |
+
fast_tokenizer.save_pretrained(tmpdir)
|
| 653 |
+
try:
|
| 654 |
+
slow_tokenizer = AutoTokenizer.from_pretrained(tmpdir, use_fast=False)
|
| 655 |
+
except Exception:
|
| 656 |
+
result["warnings"].append(
|
| 657 |
+
(
|
| 658 |
+
f"Failed to load the slow tokenizer saved from {fast_tokenizer.__class__.__name__}.",
|
| 659 |
+
traceback.format_exc(),
|
| 660 |
+
)
|
| 661 |
+
)
|
| 662 |
+
# Let's just keep the fast version
|
| 663 |
+
slow_tokenizer = None
|
| 664 |
+
except Exception:
|
| 665 |
+
result["warnings"].append(
|
| 666 |
+
(
|
| 667 |
+
f"Failed to save the fast tokenizer for {fast_tokenizer.__class__.__name__}.",
|
| 668 |
+
traceback.format_exc(),
|
| 669 |
+
)
|
| 670 |
+
)
|
| 671 |
+
fast_tokenizer = None
|
| 672 |
+
|
| 673 |
+
# If the (possibly converted) fast/slow tokenizers don't correspond, set them to `None`, and use the original
|
| 674 |
+
# tokenizers.
|
| 675 |
+
fast_tokenizer, slow_tokenizer = _sanity_check(fast_tokenizer, slow_tokenizer, keep_fast_tokenizer=False)
|
| 676 |
+
|
| 677 |
+
# If there is any conversion failed, we keep the original tokenizers.
|
| 678 |
+
if (original_fast_tokenizer is not None and fast_tokenizer is None) or (
|
| 679 |
+
original_slow_tokenizer is not None and slow_tokenizer is None
|
| 680 |
+
):
|
| 681 |
+
warning_messagae = (
|
| 682 |
+
"There are some issues when converting the fast/slow tokenizers. The original tokenizers from the Hub "
|
| 683 |
+
" will be used instead."
|
| 684 |
+
)
|
| 685 |
+
result["warnings"].append(warning_messagae)
|
| 686 |
+
# Let's use the original version at the end (`original_fast_tokenizer` and `original_slow_tokenizer`)
|
| 687 |
+
fast_tokenizer = original_fast_tokenizer
|
| 688 |
+
slow_tokenizer = original_slow_tokenizer
|
| 689 |
+
|
| 690 |
+
# Make sure the fast tokenizer can be saved
|
| 691 |
+
if fast_tokenizer:
|
| 692 |
+
# We don't save it to `output_folder` at this moment - only at the end of this function.
|
| 693 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 694 |
+
try:
|
| 695 |
+
fast_tokenizer.save_pretrained(tmpdir)
|
| 696 |
+
except Exception:
|
| 697 |
+
result["warnings"].append(
|
| 698 |
+
(
|
| 699 |
+
f"Failed to save the fast tokenizer for {fast_tokenizer.__class__.__name__}.",
|
| 700 |
+
traceback.format_exc(),
|
| 701 |
+
)
|
| 702 |
+
)
|
| 703 |
+
fast_tokenizer = None
|
| 704 |
+
# Make sure the slow tokenizer can be saved
|
| 705 |
+
if slow_tokenizer:
|
| 706 |
+
# We don't save it to `output_folder` at this moment - only at the end of this function.
|
| 707 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 708 |
+
try:
|
| 709 |
+
slow_tokenizer.save_pretrained(tmpdir)
|
| 710 |
+
except Exception:
|
| 711 |
+
result["warnings"].append(
|
| 712 |
+
(
|
| 713 |
+
f"Failed to save the slow tokenizer for {slow_tokenizer.__class__.__name__}.",
|
| 714 |
+
traceback.format_exc(),
|
| 715 |
+
)
|
| 716 |
+
)
|
| 717 |
+
slow_tokenizer = None
|
| 718 |
+
|
| 719 |
+
# update feature extractors using the tiny config
|
| 720 |
+
try:
|
| 721 |
+
feature_extractors = [convert_feature_extractor(p, tiny_config) for p in feature_extractors]
|
| 722 |
+
except Exception:
|
| 723 |
+
result["warnings"].append(
|
| 724 |
+
(
|
| 725 |
+
"Failed to convert feature extractors.",
|
| 726 |
+
traceback.format_exc(),
|
| 727 |
+
)
|
| 728 |
+
)
|
| 729 |
+
feature_extractors = []
|
| 730 |
+
|
| 731 |
+
if hasattr(tiny_config, "max_position_embeddings") and tiny_config.max_position_embeddings > 0:
|
| 732 |
+
if fast_tokenizer is not None:
|
| 733 |
+
if fast_tokenizer.__class__.__name__ in [
|
| 734 |
+
"RobertaTokenizerFast",
|
| 735 |
+
"XLMRobertaTokenizerFast",
|
| 736 |
+
"LongformerTokenizerFast",
|
| 737 |
+
"MPNetTokenizerFast",
|
| 738 |
+
]:
|
| 739 |
+
fast_tokenizer.model_max_length = tiny_config.max_position_embeddings - 2
|
| 740 |
+
else:
|
| 741 |
+
fast_tokenizer.model_max_length = tiny_config.max_position_embeddings
|
| 742 |
+
if slow_tokenizer is not None:
|
| 743 |
+
if slow_tokenizer.__class__.__name__ in [
|
| 744 |
+
"RobertaTokenizer",
|
| 745 |
+
"XLMRobertaTokenizer",
|
| 746 |
+
"LongformerTokenizer",
|
| 747 |
+
"MPNetTokenizer",
|
| 748 |
+
]:
|
| 749 |
+
slow_tokenizer.model_max_length = tiny_config.max_position_embeddings - 2
|
| 750 |
+
else:
|
| 751 |
+
slow_tokenizer.model_max_length = tiny_config.max_position_embeddings
|
| 752 |
+
|
| 753 |
+
processors = [fast_tokenizer, slow_tokenizer] + feature_extractors
|
| 754 |
+
processors = [p for p in processors if p is not None]
|
| 755 |
+
for p in processors:
|
| 756 |
+
p.save_pretrained(output_folder)
|
| 757 |
+
|
| 758 |
+
return processors
|
| 759 |
+
|
| 760 |
+
|
| 761 |
+
def get_checkpoint_dir(output_dir, model_arch):
|
| 762 |
+
"""Get framework-agnostic architecture name. Used to save all PT/TF/Flax models into the same directory."""
|
| 763 |
+
|
| 764 |
+
arch_name = model_arch.__name__
|
| 765 |
+
if arch_name.startswith("TF"):
|
| 766 |
+
arch_name = arch_name[2:]
|
| 767 |
+
elif arch_name.startswith("Flax"):
|
| 768 |
+
arch_name = arch_name[4:]
|
| 769 |
+
|
| 770 |
+
return os.path.join(output_dir, arch_name)
|
| 771 |
+
|
| 772 |
+
|
| 773 |
+
def build_model(model_arch, tiny_config, output_dir):
|
| 774 |
+
"""Create and save a model for `model_arch`.
|
| 775 |
+
|
| 776 |
+
Also copy the set of processors to each model (under the same model type) output folder.
|
| 777 |
+
"""
|
| 778 |
+
|
| 779 |
+
checkpoint_dir = get_checkpoint_dir(output_dir, model_arch)
|
| 780 |
+
|
| 781 |
+
processor_output_dir = os.path.join(output_dir, "processors")
|
| 782 |
+
# copy the (same set of) processors (for a model type) to the model arch. specific folder
|
| 783 |
+
if os.path.isdir(processor_output_dir):
|
| 784 |
+
shutil.copytree(processor_output_dir, checkpoint_dir, dirs_exist_ok=True)
|
| 785 |
+
|
| 786 |
+
tiny_config = copy.deepcopy(tiny_config)
|
| 787 |
+
|
| 788 |
+
if any(model_arch.__name__.endswith(x) for x in ["ForCausalLM", "LMHeadModel"]):
|
| 789 |
+
tiny_config.is_encoder_decoder = False
|
| 790 |
+
tiny_config.is_decoder = True
|
| 791 |
+
|
| 792 |
+
model = model_arch(config=tiny_config)
|
| 793 |
+
model.save_pretrained(checkpoint_dir)
|
| 794 |
+
model.from_pretrained(checkpoint_dir)
|
| 795 |
+
|
| 796 |
+
return model
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
def fill_result_with_error(result, error, trace, models_to_create):
|
| 800 |
+
"""Fill `result` with errors for all target model arch if we can't build processor"""
|
| 801 |
+
error = (error, trace)
|
| 802 |
+
result["error"] = error
|
| 803 |
+
for framework in FRAMEWORKS:
|
| 804 |
+
if framework in models_to_create:
|
| 805 |
+
result[framework] = {}
|
| 806 |
+
for model_arch in models_to_create[framework]:
|
| 807 |
+
result[framework][model_arch.__name__] = {"model": None, "checkpoint": None, "error": error}
|
| 808 |
+
|
| 809 |
+
result["processor"] = {p.__class__.__name__: p.__class__.__name__ for p in result["processor"].values()}
|
| 810 |
+
|
| 811 |
+
|
| 812 |
+
def upload_model(model_dir, organization, token):
|
| 813 |
+
"""Upload the tiny models"""
|
| 814 |
+
|
| 815 |
+
arch_name = model_dir.split(os.path.sep)[-1]
|
| 816 |
+
repo_name = f"tiny-random-{arch_name}"
|
| 817 |
+
repo_id = f"{organization}/{repo_name}"
|
| 818 |
+
|
| 819 |
+
repo_exist = False
|
| 820 |
+
error = None
|
| 821 |
+
try:
|
| 822 |
+
create_repo(repo_id=repo_id, exist_ok=False, repo_type="model", token=token)
|
| 823 |
+
except Exception as e:
|
| 824 |
+
error = e
|
| 825 |
+
if "You already created" in str(e):
|
| 826 |
+
error = None
|
| 827 |
+
logger.warning("Remote repository exists and will be cloned.")
|
| 828 |
+
repo_exist = True
|
| 829 |
+
try:
|
| 830 |
+
create_repo(repo_id=repo_id, exist_ok=True, repo_type="model", token=token)
|
| 831 |
+
except Exception as e:
|
| 832 |
+
error = e
|
| 833 |
+
if error is not None:
|
| 834 |
+
raise error
|
| 835 |
+
|
| 836 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 837 |
+
repo = Repository(local_dir=tmpdir, clone_from=repo_id, token=token)
|
| 838 |
+
repo.git_pull()
|
| 839 |
+
shutil.copytree(model_dir, tmpdir, dirs_exist_ok=True)
|
| 840 |
+
|
| 841 |
+
if repo_exist:
|
| 842 |
+
# Open a PR on the existing Hub repo.
|
| 843 |
+
hub_pr_url = upload_folder(
|
| 844 |
+
folder_path=model_dir,
|
| 845 |
+
repo_id=repo_id,
|
| 846 |
+
repo_type="model",
|
| 847 |
+
commit_message=f"Update tiny models for {arch_name}",
|
| 848 |
+
commit_description=f"Upload tiny models for {arch_name}",
|
| 849 |
+
create_pr=True,
|
| 850 |
+
token=token,
|
| 851 |
+
)
|
| 852 |
+
logger.warning(f"PR open in {hub_pr_url}.")
|
| 853 |
+
# TODO: We need this information?
|
| 854 |
+
else:
|
| 855 |
+
# Push to Hub repo directly
|
| 856 |
+
repo.git_add(auto_lfs_track=True)
|
| 857 |
+
repo.git_commit(f"Upload tiny models for {arch_name}")
|
| 858 |
+
repo.git_push(blocking=True) # this prints a progress bar with the upload
|
| 859 |
+
logger.warning(f"Tiny models {arch_name} pushed to {repo_id}.")
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
def build_composite_models(config_class, output_dir):
|
| 863 |
+
import tempfile
|
| 864 |
+
|
| 865 |
+
from transformers import (
|
| 866 |
+
BertConfig,
|
| 867 |
+
BertLMHeadModel,
|
| 868 |
+
BertModel,
|
| 869 |
+
BertTokenizer,
|
| 870 |
+
BertTokenizerFast,
|
| 871 |
+
EncoderDecoderModel,
|
| 872 |
+
GPT2Config,
|
| 873 |
+
GPT2LMHeadModel,
|
| 874 |
+
GPT2Tokenizer,
|
| 875 |
+
GPT2TokenizerFast,
|
| 876 |
+
SpeechEncoderDecoderModel,
|
| 877 |
+
TFEncoderDecoderModel,
|
| 878 |
+
TFVisionEncoderDecoderModel,
|
| 879 |
+
TFVisionTextDualEncoderModel,
|
| 880 |
+
VisionEncoderDecoderModel,
|
| 881 |
+
VisionTextDualEncoderModel,
|
| 882 |
+
ViTConfig,
|
| 883 |
+
ViTFeatureExtractor,
|
| 884 |
+
ViTModel,
|
| 885 |
+
Wav2Vec2Config,
|
| 886 |
+
Wav2Vec2Model,
|
| 887 |
+
Wav2Vec2Processor,
|
| 888 |
+
)
|
| 889 |
+
|
| 890 |
+
# These will be removed at the end if they are empty
|
| 891 |
+
result = {"error": None, "warnings": []}
|
| 892 |
+
|
| 893 |
+
if config_class.model_type == "encoder-decoder":
|
| 894 |
+
encoder_config_class = BertConfig
|
| 895 |
+
decoder_config_class = BertConfig
|
| 896 |
+
encoder_processor = (BertTokenizerFast, BertTokenizer)
|
| 897 |
+
decoder_processor = (BertTokenizerFast, BertTokenizer)
|
| 898 |
+
encoder_class = BertModel
|
| 899 |
+
decoder_class = BertLMHeadModel
|
| 900 |
+
model_class = EncoderDecoderModel
|
| 901 |
+
tf_model_class = TFEncoderDecoderModel
|
| 902 |
+
elif config_class.model_type == "vision-encoder-decoder":
|
| 903 |
+
encoder_config_class = ViTConfig
|
| 904 |
+
decoder_config_class = GPT2Config
|
| 905 |
+
encoder_processor = (ViTFeatureExtractor,)
|
| 906 |
+
decoder_processor = (GPT2TokenizerFast, GPT2Tokenizer)
|
| 907 |
+
encoder_class = ViTModel
|
| 908 |
+
decoder_class = GPT2LMHeadModel
|
| 909 |
+
model_class = VisionEncoderDecoderModel
|
| 910 |
+
tf_model_class = TFVisionEncoderDecoderModel
|
| 911 |
+
elif config_class.model_type == "speech-encoder-decoder":
|
| 912 |
+
encoder_config_class = Wav2Vec2Config
|
| 913 |
+
decoder_config_class = BertConfig
|
| 914 |
+
encoder_processor = (Wav2Vec2Processor,)
|
| 915 |
+
decoder_processor = (BertTokenizerFast, BertTokenizer)
|
| 916 |
+
encoder_class = Wav2Vec2Model
|
| 917 |
+
decoder_class = BertLMHeadModel
|
| 918 |
+
model_class = SpeechEncoderDecoderModel
|
| 919 |
+
tf_model_class = None
|
| 920 |
+
elif config_class.model_type == "vision-text-dual-encoder":
|
| 921 |
+
# Not encoder-decoder, but encoder-encoder. We just keep the same name as above to make code easier
|
| 922 |
+
encoder_config_class = ViTConfig
|
| 923 |
+
decoder_config_class = BertConfig
|
| 924 |
+
encoder_processor = (ViTFeatureExtractor,)
|
| 925 |
+
decoder_processor = (BertTokenizerFast, BertTokenizer)
|
| 926 |
+
encoder_class = ViTModel
|
| 927 |
+
decoder_class = BertModel
|
| 928 |
+
model_class = VisionTextDualEncoderModel
|
| 929 |
+
tf_model_class = TFVisionTextDualEncoderModel
|
| 930 |
+
|
| 931 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 932 |
+
try:
|
| 933 |
+
# build encoder
|
| 934 |
+
models_to_create = {"processor": encoder_processor, "pytorch": (encoder_class,), "tensorflow": []}
|
| 935 |
+
encoder_output_dir = os.path.join(tmpdir, "encoder")
|
| 936 |
+
build(encoder_config_class, models_to_create, encoder_output_dir)
|
| 937 |
+
|
| 938 |
+
# build decoder
|
| 939 |
+
models_to_create = {"processor": decoder_processor, "pytorch": (decoder_class,), "tensorflow": []}
|
| 940 |
+
decoder_output_dir = os.path.join(tmpdir, "decoder")
|
| 941 |
+
build(decoder_config_class, models_to_create, decoder_output_dir)
|
| 942 |
+
|
| 943 |
+
# build encoder-decoder
|
| 944 |
+
encoder_path = os.path.join(encoder_output_dir, encoder_class.__name__)
|
| 945 |
+
decoder_path = os.path.join(decoder_output_dir, decoder_class.__name__)
|
| 946 |
+
|
| 947 |
+
if config_class.model_type != "vision-text-dual-encoder":
|
| 948 |
+
# Specify these explicitly for encoder-decoder like models, but not for `vision-text-dual-encoder` as it
|
| 949 |
+
# has no decoder.
|
| 950 |
+
decoder_config = decoder_config_class.from_pretrained(decoder_path)
|
| 951 |
+
decoder_config.is_decoder = True
|
| 952 |
+
decoder_config.add_cross_attention = True
|
| 953 |
+
model = model_class.from_encoder_decoder_pretrained(
|
| 954 |
+
encoder_path,
|
| 955 |
+
decoder_path,
|
| 956 |
+
decoder_config=decoder_config,
|
| 957 |
+
)
|
| 958 |
+
elif config_class.model_type == "vision-text-dual-encoder":
|
| 959 |
+
model = model_class.from_vision_text_pretrained(encoder_path, decoder_path)
|
| 960 |
+
|
| 961 |
+
model_path = os.path.join(
|
| 962 |
+
output_dir,
|
| 963 |
+
f"{model_class.__name__}-{encoder_config_class.model_type}-{decoder_config_class.model_type}",
|
| 964 |
+
)
|
| 965 |
+
model.save_pretrained(model_path)
|
| 966 |
+
|
| 967 |
+
if tf_model_class is not None:
|
| 968 |
+
model = tf_model_class.from_pretrained(model_path)
|
| 969 |
+
model.save_pretrained(model_path)
|
| 970 |
+
|
| 971 |
+
# copy the processors
|
| 972 |
+
encoder_processor_path = os.path.join(encoder_output_dir, "processors")
|
| 973 |
+
decoder_processor_path = os.path.join(decoder_output_dir, "processors")
|
| 974 |
+
if os.path.isdir(encoder_processor_path):
|
| 975 |
+
shutil.copytree(encoder_processor_path, model_path, dirs_exist_ok=True)
|
| 976 |
+
if os.path.isdir(decoder_processor_path):
|
| 977 |
+
shutil.copytree(decoder_processor_path, model_path, dirs_exist_ok=True)
|
| 978 |
+
|
| 979 |
+
# fill `result`
|
| 980 |
+
result["processor"] = {x.__name__: x.__name__ for x in encoder_processor + decoder_processor}
|
| 981 |
+
|
| 982 |
+
result["pytorch"] = {model_class.__name__: {"model": model_class.__name__, "checkpoint": model_path}}
|
| 983 |
+
|
| 984 |
+
result["tensorflow"] = {}
|
| 985 |
+
if tf_model_class is not None:
|
| 986 |
+
result["tensorflow"] = {
|
| 987 |
+
tf_model_class.__name__: {"model": tf_model_class.__name__, "checkpoint": model_path}
|
| 988 |
+
}
|
| 989 |
+
except Exception:
|
| 990 |
+
result["error"] = (
|
| 991 |
+
f"Failed to build models for {config_class.__name__}.",
|
| 992 |
+
traceback.format_exc(),
|
| 993 |
+
)
|
| 994 |
+
|
| 995 |
+
if not result["error"]:
|
| 996 |
+
del result["error"]
|
| 997 |
+
if not result["warnings"]:
|
| 998 |
+
del result["warnings"]
|
| 999 |
+
|
| 1000 |
+
return result
|
| 1001 |
+
|
| 1002 |
+
|
| 1003 |
+
def get_token_id_from_tokenizer(token_id_name, tokenizer, original_token_id):
|
| 1004 |
+
"""Use `tokenizer` to get the values of `bos_token_id`, `eos_token_ids`, etc.
|
| 1005 |
+
|
| 1006 |
+
The argument `token_id_name` should be a string ending with `_token_id`, and `original_token_id` should be an
|
| 1007 |
+
integer that will be return if `tokenizer` has no token corresponding to `token_id_name`.
|
| 1008 |
+
"""
|
| 1009 |
+
|
| 1010 |
+
token_id = original_token_id
|
| 1011 |
+
|
| 1012 |
+
if not token_id_name.endswith("_token_id"):
|
| 1013 |
+
raise ValueError(f"`token_id_name` is {token_id_name}, which doesn't end with `_token_id`!")
|
| 1014 |
+
|
| 1015 |
+
token = getattr(tokenizer, token_id_name.replace("_token_id", "_token"), None)
|
| 1016 |
+
if token is not None:
|
| 1017 |
+
if isinstance(tokenizer, PreTrainedTokenizerFast):
|
| 1018 |
+
token_id = tokenizer._convert_token_to_id_with_added_voc(token)
|
| 1019 |
+
else:
|
| 1020 |
+
token_id = tokenizer._convert_token_to_id(token)
|
| 1021 |
+
|
| 1022 |
+
return token_id
|
| 1023 |
+
|
| 1024 |
+
|
| 1025 |
+
def get_config_overrides(config_class, processors):
|
| 1026 |
+
# `Bark` configuration is too special. Let's just not handle this for now.
|
| 1027 |
+
if config_class.__name__ == "BarkConfig":
|
| 1028 |
+
return {}
|
| 1029 |
+
|
| 1030 |
+
config_overrides = {}
|
| 1031 |
+
|
| 1032 |
+
# Check if there is any tokenizer (prefer fast version if any)
|
| 1033 |
+
tokenizer = None
|
| 1034 |
+
for processor in processors:
|
| 1035 |
+
if isinstance(processor, PreTrainedTokenizerFast):
|
| 1036 |
+
tokenizer = processor
|
| 1037 |
+
break
|
| 1038 |
+
elif isinstance(processor, PreTrainedTokenizer):
|
| 1039 |
+
tokenizer = processor
|
| 1040 |
+
|
| 1041 |
+
if tokenizer is None:
|
| 1042 |
+
return config_overrides
|
| 1043 |
+
|
| 1044 |
+
# Get some properties of the (already converted) tokenizer (smaller vocab size, special token ids, etc.)
|
| 1045 |
+
# We use `len(tokenizer)` instead of `tokenizer.vocab_size` to avoid potential issues for tokenizers with non-empty
|
| 1046 |
+
# `added_tokens_encoder`. One example is the `DebertaV2Tokenizer` where the mask token is the extra token.
|
| 1047 |
+
vocab_size = len(tokenizer)
|
| 1048 |
+
|
| 1049 |
+
# The original checkpoint has length `35998`, but it doesn't have ids `30400` and `30514` but instead `35998` and
|
| 1050 |
+
# `35999`.
|
| 1051 |
+
if config_class.__name__ == "GPTSanJapaneseConfig":
|
| 1052 |
+
vocab_size += 2
|
| 1053 |
+
|
| 1054 |
+
config_overrides["vocab_size"] = vocab_size
|
| 1055 |
+
|
| 1056 |
+
# Used to create a new model tester with `tokenizer.vocab_size` in order to get the (updated) special token ids.
|
| 1057 |
+
model_tester_kwargs = {"vocab_size": vocab_size}
|
| 1058 |
+
# `FSMTModelTester` accepts `src_vocab_size` and `tgt_vocab_size` but not `vocab_size`.
|
| 1059 |
+
if config_class.__name__ == "FSMTConfig":
|
| 1060 |
+
del model_tester_kwargs["vocab_size"]
|
| 1061 |
+
model_tester_kwargs["src_vocab_size"] = tokenizer.src_vocab_size
|
| 1062 |
+
model_tester_kwargs["tgt_vocab_size"] = tokenizer.tgt_vocab_size
|
| 1063 |
+
|
| 1064 |
+
_tiny_config = get_tiny_config(config_class, **model_tester_kwargs)
|
| 1065 |
+
|
| 1066 |
+
# handle the possibility of `text_config` inside `_tiny_config` for clip-like models (`owlvit`, `groupvit`, etc.)
|
| 1067 |
+
if hasattr(_tiny_config, "text_config"):
|
| 1068 |
+
_tiny_config = _tiny_config.text_config
|
| 1069 |
+
|
| 1070 |
+
# Collect values of some special token ids
|
| 1071 |
+
for attr in dir(_tiny_config):
|
| 1072 |
+
if attr.endswith("_token_id"):
|
| 1073 |
+
token_id = getattr(_tiny_config, attr)
|
| 1074 |
+
if token_id is not None:
|
| 1075 |
+
# Using the token id values from `tokenizer` instead of from `_tiny_config`.
|
| 1076 |
+
token_id = get_token_id_from_tokenizer(attr, tokenizer, original_token_id=token_id)
|
| 1077 |
+
config_overrides[attr] = token_id
|
| 1078 |
+
|
| 1079 |
+
if config_class.__name__ == "FSMTConfig":
|
| 1080 |
+
config_overrides["src_vocab_size"] = tokenizer.src_vocab_size
|
| 1081 |
+
config_overrides["tgt_vocab_size"] = tokenizer.tgt_vocab_size
|
| 1082 |
+
# `FSMTConfig` has `DecoderConfig` as `decoder` attribute.
|
| 1083 |
+
config_overrides["decoder"] = configuration_fsmt.DecoderConfig(
|
| 1084 |
+
vocab_size=tokenizer.tgt_vocab_size, bos_token_id=config_overrides["eos_token_id"]
|
| 1085 |
+
)
|
| 1086 |
+
|
| 1087 |
+
return config_overrides
|
| 1088 |
+
|
| 1089 |
+
|
| 1090 |
+
def build(config_class, models_to_create, output_dir):
|
| 1091 |
+
"""Create all models for a certain model type.
|
| 1092 |
+
|
| 1093 |
+
Args:
|
| 1094 |
+
config_class (`PretrainedConfig`):
|
| 1095 |
+
A subclass of `PretrainedConfig` that is used to determine `models_to_create`.
|
| 1096 |
+
models_to_create (`dict`):
|
| 1097 |
+
A dictionary containing the processor/model classes that we want to create the instances. These models are
|
| 1098 |
+
of the same model type which is associated to `config_class`.
|
| 1099 |
+
output_dir (`str`):
|
| 1100 |
+
The directory to save all the checkpoints. Each model architecture will be saved in a subdirectory under
|
| 1101 |
+
it. Models in different frameworks with the same architecture will be saved in the same subdirectory.
|
| 1102 |
+
"""
|
| 1103 |
+
if data["training_ds"] is None or data["testing_ds"] is None:
|
| 1104 |
+
ds = load_dataset("Salesforce/wikitext", "wikitext-2-raw-v1")
|
| 1105 |
+
data["training_ds"] = ds["train"]
|
| 1106 |
+
data["testing_ds"] = ds["test"]
|
| 1107 |
+
|
| 1108 |
+
if config_class.model_type in [
|
| 1109 |
+
"encoder-decoder",
|
| 1110 |
+
"vision-encoder-decoder",
|
| 1111 |
+
"speech-encoder-decoder",
|
| 1112 |
+
"vision-text-dual-encoder",
|
| 1113 |
+
]:
|
| 1114 |
+
return build_composite_models(config_class, output_dir)
|
| 1115 |
+
|
| 1116 |
+
result = {k: {} for k in models_to_create}
|
| 1117 |
+
|
| 1118 |
+
# These will be removed at the end if they are empty
|
| 1119 |
+
result["error"] = None
|
| 1120 |
+
result["warnings"] = []
|
| 1121 |
+
|
| 1122 |
+
# Build processors
|
| 1123 |
+
processor_classes = models_to_create["processor"]
|
| 1124 |
+
|
| 1125 |
+
if len(processor_classes) == 0:
|
| 1126 |
+
error = f"No processor class could be found in {config_class.__name__}."
|
| 1127 |
+
fill_result_with_error(result, error, None, models_to_create)
|
| 1128 |
+
logger.error(result["error"][0])
|
| 1129 |
+
return result
|
| 1130 |
+
|
| 1131 |
+
for processor_class in processor_classes:
|
| 1132 |
+
try:
|
| 1133 |
+
processor = build_processor(config_class, processor_class, allow_no_checkpoint=True)
|
| 1134 |
+
if processor is not None:
|
| 1135 |
+
result["processor"][processor_class] = processor
|
| 1136 |
+
except Exception:
|
| 1137 |
+
error = f"Failed to build processor for {processor_class.__name__}."
|
| 1138 |
+
trace = traceback.format_exc()
|
| 1139 |
+
fill_result_with_error(result, error, trace, models_to_create)
|
| 1140 |
+
logger.error(result["error"][0])
|
| 1141 |
+
return result
|
| 1142 |
+
|
| 1143 |
+
if len(result["processor"]) == 0:
|
| 1144 |
+
error = f"No processor could be built for {config_class.__name__}."
|
| 1145 |
+
fill_result_with_error(result, error, None, models_to_create)
|
| 1146 |
+
logger.error(result["error"][0])
|
| 1147 |
+
return result
|
| 1148 |
+
|
| 1149 |
+
try:
|
| 1150 |
+
tiny_config = get_tiny_config(config_class)
|
| 1151 |
+
except Exception as e:
|
| 1152 |
+
error = f"Failed to get tiny config for {config_class.__name__}: {e}"
|
| 1153 |
+
trace = traceback.format_exc()
|
| 1154 |
+
fill_result_with_error(result, error, trace, models_to_create)
|
| 1155 |
+
logger.error(result["error"][0])
|
| 1156 |
+
return result
|
| 1157 |
+
|
| 1158 |
+
# Convert the processors (reduce vocabulary size, smaller image size, etc.)
|
| 1159 |
+
processors = list(result["processor"].values())
|
| 1160 |
+
processor_output_folder = os.path.join(output_dir, "processors")
|
| 1161 |
+
try:
|
| 1162 |
+
processors = convert_processors(processors, tiny_config, processor_output_folder, result)
|
| 1163 |
+
except Exception:
|
| 1164 |
+
error = "Failed to convert the processors."
|
| 1165 |
+
trace = traceback.format_exc()
|
| 1166 |
+
result["warnings"].append((error, trace))
|
| 1167 |
+
|
| 1168 |
+
if len(processors) == 0:
|
| 1169 |
+
error = f"No processor is returned by `convert_processors` for {config_class.__name__}."
|
| 1170 |
+
fill_result_with_error(result, error, None, models_to_create)
|
| 1171 |
+
logger.error(result["error"][0])
|
| 1172 |
+
return result
|
| 1173 |
+
|
| 1174 |
+
try:
|
| 1175 |
+
config_overrides = get_config_overrides(config_class, processors)
|
| 1176 |
+
except Exception as e:
|
| 1177 |
+
error = f"Failure occurs while calling `get_config_overrides`: {e}"
|
| 1178 |
+
trace = traceback.format_exc()
|
| 1179 |
+
fill_result_with_error(result, error, trace, models_to_create)
|
| 1180 |
+
logger.error(result["error"][0])
|
| 1181 |
+
return result
|
| 1182 |
+
|
| 1183 |
+
# Just for us to see this easily in the report
|
| 1184 |
+
if "vocab_size" in config_overrides:
|
| 1185 |
+
result["vocab_size"] = config_overrides["vocab_size"]
|
| 1186 |
+
|
| 1187 |
+
# Update attributes that `vocab_size` involves
|
| 1188 |
+
for k, v in config_overrides.items():
|
| 1189 |
+
if hasattr(tiny_config, k):
|
| 1190 |
+
setattr(tiny_config, k, v)
|
| 1191 |
+
# So far, we only have to deal with `text_config`, as `config_overrides` contains text-related attributes only.
|
| 1192 |
+
# `FuyuConfig` saves data under both FuyuConfig and its `text_config`. This is not good, but let's just update
|
| 1193 |
+
# every involved fields to avoid potential failure.
|
| 1194 |
+
if (
|
| 1195 |
+
hasattr(tiny_config, "text_config")
|
| 1196 |
+
and tiny_config.text_config is not None
|
| 1197 |
+
and hasattr(tiny_config.text_config, k)
|
| 1198 |
+
):
|
| 1199 |
+
setattr(tiny_config.text_config, k, v)
|
| 1200 |
+
# If `text_config_dict` exists, we need to update its value here too in order to # make
|
| 1201 |
+
# `save_pretrained -> from_pretrained` work.
|
| 1202 |
+
if hasattr(tiny_config, "text_config_dict"):
|
| 1203 |
+
tiny_config.text_config_dict[k] = v
|
| 1204 |
+
|
| 1205 |
+
if result["warnings"]:
|
| 1206 |
+
logger.warning(result["warnings"][0][0])
|
| 1207 |
+
|
| 1208 |
+
# update `result["processor"]`
|
| 1209 |
+
result["processor"] = {type(p).__name__: p.__class__.__name__ for p in processors}
|
| 1210 |
+
|
| 1211 |
+
for pytorch_arch in models_to_create["pytorch"]:
|
| 1212 |
+
result["pytorch"][pytorch_arch.__name__] = {}
|
| 1213 |
+
error = None
|
| 1214 |
+
try:
|
| 1215 |
+
model = build_model(pytorch_arch, tiny_config, output_dir=output_dir)
|
| 1216 |
+
except Exception as e:
|
| 1217 |
+
model = None
|
| 1218 |
+
error = f"Failed to create the pytorch model for {pytorch_arch}: {e}"
|
| 1219 |
+
trace = traceback.format_exc()
|
| 1220 |
+
|
| 1221 |
+
result["pytorch"][pytorch_arch.__name__]["model"] = model.__class__.__name__ if model is not None else None
|
| 1222 |
+
result["pytorch"][pytorch_arch.__name__]["checkpoint"] = (
|
| 1223 |
+
get_checkpoint_dir(output_dir, pytorch_arch) if model is not None else None
|
| 1224 |
+
)
|
| 1225 |
+
if error is not None:
|
| 1226 |
+
result["pytorch"][pytorch_arch.__name__]["error"] = (error, trace)
|
| 1227 |
+
logger.error(f"{pytorch_arch.__name__}: {error}")
|
| 1228 |
+
|
| 1229 |
+
for tensorflow_arch in models_to_create["tensorflow"]:
|
| 1230 |
+
# Make PT/TF weights compatible
|
| 1231 |
+
pt_arch_name = tensorflow_arch.__name__[2:] # Remove `TF`
|
| 1232 |
+
pt_arch = getattr(transformers_module, pt_arch_name)
|
| 1233 |
+
|
| 1234 |
+
result["tensorflow"][tensorflow_arch.__name__] = {}
|
| 1235 |
+
error = None
|
| 1236 |
+
if pt_arch.__name__ in result["pytorch"] and result["pytorch"][pt_arch.__name__]["checkpoint"] is not None:
|
| 1237 |
+
ckpt = get_checkpoint_dir(output_dir, pt_arch)
|
| 1238 |
+
# Use the same weights from PyTorch.
|
| 1239 |
+
try:
|
| 1240 |
+
model = tensorflow_arch.from_pretrained(ckpt)
|
| 1241 |
+
model.save_pretrained(ckpt)
|
| 1242 |
+
except Exception as e:
|
| 1243 |
+
# Conversion may fail. Let's not create a model with different weights to avoid confusion (for now).
|
| 1244 |
+
model = None
|
| 1245 |
+
error = f"Failed to convert the pytorch model to the tensorflow model for {pt_arch}: {e}"
|
| 1246 |
+
trace = traceback.format_exc()
|
| 1247 |
+
else:
|
| 1248 |
+
try:
|
| 1249 |
+
model = build_model(tensorflow_arch, tiny_config, output_dir=output_dir)
|
| 1250 |
+
except Exception as e:
|
| 1251 |
+
model = None
|
| 1252 |
+
error = f"Failed to create the tensorflow model for {tensorflow_arch}: {e}"
|
| 1253 |
+
trace = traceback.format_exc()
|
| 1254 |
+
|
| 1255 |
+
result["tensorflow"][tensorflow_arch.__name__]["model"] = (
|
| 1256 |
+
model.__class__.__name__ if model is not None else None
|
| 1257 |
+
)
|
| 1258 |
+
result["tensorflow"][tensorflow_arch.__name__]["checkpoint"] = (
|
| 1259 |
+
get_checkpoint_dir(output_dir, tensorflow_arch) if model is not None else None
|
| 1260 |
+
)
|
| 1261 |
+
if error is not None:
|
| 1262 |
+
result["tensorflow"][tensorflow_arch.__name__]["error"] = (error, trace)
|
| 1263 |
+
logger.error(f"{tensorflow_arch.__name__}: {error}")
|
| 1264 |
+
|
| 1265 |
+
if not result["error"]:
|
| 1266 |
+
del result["error"]
|
| 1267 |
+
if not result["warnings"]:
|
| 1268 |
+
del result["warnings"]
|
| 1269 |
+
|
| 1270 |
+
return result
|
| 1271 |
+
|
| 1272 |
+
|
| 1273 |
+
def build_tiny_model_summary(results, organization=None, token=None):
|
| 1274 |
+
"""Build a summary: a dictionary of the form
|
| 1275 |
+
{
|
| 1276 |
+
model architecture name:
|
| 1277 |
+
{
|
| 1278 |
+
"tokenizer_classes": [...],
|
| 1279 |
+
"processor_classes": [...],
|
| 1280 |
+
"model_classes": [...],
|
| 1281 |
+
}
|
| 1282 |
+
..
|
| 1283 |
+
}
|
| 1284 |
+
"""
|
| 1285 |
+
tiny_model_summary = {}
|
| 1286 |
+
for config_name in results:
|
| 1287 |
+
processors = [key for key, value in results[config_name]["processor"].items()]
|
| 1288 |
+
tokenizer_classes = sorted([x for x in processors if x.endswith("TokenizerFast") or x.endswith("Tokenizer")])
|
| 1289 |
+
processor_classes = sorted([x for x in processors if x not in tokenizer_classes])
|
| 1290 |
+
for framework in FRAMEWORKS:
|
| 1291 |
+
if framework not in results[config_name]:
|
| 1292 |
+
continue
|
| 1293 |
+
for arch_name in results[config_name][framework]:
|
| 1294 |
+
model_classes = [arch_name]
|
| 1295 |
+
base_arch_name = arch_name[2:] if arch_name.startswith("TF") else arch_name
|
| 1296 |
+
# tiny model is not created for `arch_name`
|
| 1297 |
+
if results[config_name][framework][arch_name]["model"] is None:
|
| 1298 |
+
model_classes = []
|
| 1299 |
+
if base_arch_name not in tiny_model_summary:
|
| 1300 |
+
tiny_model_summary[base_arch_name] = {}
|
| 1301 |
+
tiny_model_summary[base_arch_name].update(
|
| 1302 |
+
{
|
| 1303 |
+
"tokenizer_classes": tokenizer_classes,
|
| 1304 |
+
"processor_classes": processor_classes,
|
| 1305 |
+
}
|
| 1306 |
+
)
|
| 1307 |
+
tiny_model_summary[base_arch_name]["model_classes"] = sorted(
|
| 1308 |
+
tiny_model_summary[base_arch_name].get("model_classes", []) + model_classes
|
| 1309 |
+
)
|
| 1310 |
+
if organization is not None:
|
| 1311 |
+
repo_name = f"tiny-random-{base_arch_name}"
|
| 1312 |
+
# composite models' checkpoints have more precise repo. names on the Hub.
|
| 1313 |
+
if base_arch_name in COMPOSITE_MODELS:
|
| 1314 |
+
repo_name = f"tiny-random-{COMPOSITE_MODELS[base_arch_name]}"
|
| 1315 |
+
repo_id = f"{organization}/{repo_name}"
|
| 1316 |
+
try:
|
| 1317 |
+
commit_hash = hf_api.repo_info(repo_id, token=token).sha
|
| 1318 |
+
except Exception:
|
| 1319 |
+
# The directory is not created, but processor(s) is/are included in `results`.
|
| 1320 |
+
logger.warning(f"Failed to get information for {repo_id}.\n{traceback.format_exc()}")
|
| 1321 |
+
del tiny_model_summary[base_arch_name]
|
| 1322 |
+
continue
|
| 1323 |
+
tiny_model_summary[base_arch_name]["sha"] = commit_hash
|
| 1324 |
+
|
| 1325 |
+
return tiny_model_summary
|
| 1326 |
+
|
| 1327 |
+
|
| 1328 |
+
def build_failed_report(results, include_warning=True):
|
| 1329 |
+
failed_results = {}
|
| 1330 |
+
for config_name in results:
|
| 1331 |
+
if "error" in results[config_name]:
|
| 1332 |
+
if config_name not in failed_results:
|
| 1333 |
+
failed_results[config_name] = {}
|
| 1334 |
+
failed_results[config_name] = {"error": results[config_name]["error"]}
|
| 1335 |
+
|
| 1336 |
+
if include_warning and "warnings" in results[config_name]:
|
| 1337 |
+
if config_name not in failed_results:
|
| 1338 |
+
failed_results[config_name] = {}
|
| 1339 |
+
failed_results[config_name]["warnings"] = results[config_name]["warnings"]
|
| 1340 |
+
|
| 1341 |
+
for framework in FRAMEWORKS:
|
| 1342 |
+
if framework not in results[config_name]:
|
| 1343 |
+
continue
|
| 1344 |
+
for arch_name in results[config_name][framework]:
|
| 1345 |
+
if "error" in results[config_name][framework][arch_name]:
|
| 1346 |
+
if config_name not in failed_results:
|
| 1347 |
+
failed_results[config_name] = {}
|
| 1348 |
+
if framework not in failed_results[config_name]:
|
| 1349 |
+
failed_results[config_name][framework] = {}
|
| 1350 |
+
if arch_name not in failed_results[config_name][framework]:
|
| 1351 |
+
failed_results[config_name][framework][arch_name] = {}
|
| 1352 |
+
error = results[config_name][framework][arch_name]["error"]
|
| 1353 |
+
failed_results[config_name][framework][arch_name]["error"] = error
|
| 1354 |
+
|
| 1355 |
+
return failed_results
|
| 1356 |
+
|
| 1357 |
+
|
| 1358 |
+
def build_simple_report(results):
|
| 1359 |
+
text = ""
|
| 1360 |
+
failed_text = ""
|
| 1361 |
+
for config_name in results:
|
| 1362 |
+
for framework in FRAMEWORKS:
|
| 1363 |
+
if framework not in results[config_name]:
|
| 1364 |
+
continue
|
| 1365 |
+
for arch_name in results[config_name][framework]:
|
| 1366 |
+
if "error" in results[config_name][framework][arch_name]:
|
| 1367 |
+
result = results[config_name][framework][arch_name]["error"]
|
| 1368 |
+
failed_text += f"{arch_name}: {result[0]}\n"
|
| 1369 |
+
else:
|
| 1370 |
+
result = ("OK",)
|
| 1371 |
+
text += f"{arch_name}: {result[0]}\n"
|
| 1372 |
+
|
| 1373 |
+
return text, failed_text
|
| 1374 |
+
|
| 1375 |
+
|
| 1376 |
+
def update_tiny_model_summary_file(report_path):
|
| 1377 |
+
with open(os.path.join(report_path, "tiny_model_summary.json")) as fp:
|
| 1378 |
+
new_data = json.load(fp)
|
| 1379 |
+
with open("tests/utils/tiny_model_summary.json") as fp:
|
| 1380 |
+
data = json.load(fp)
|
| 1381 |
+
for key, value in new_data.items():
|
| 1382 |
+
if key not in data:
|
| 1383 |
+
data[key] = value
|
| 1384 |
+
else:
|
| 1385 |
+
for attr in ["tokenizer_classes", "processor_classes", "model_classes"]:
|
| 1386 |
+
# we might get duplication here. We will remove them below when creating `updated_data`.
|
| 1387 |
+
data[key][attr].extend(value[attr])
|
| 1388 |
+
new_sha = value.get("sha", None)
|
| 1389 |
+
if new_sha is not None:
|
| 1390 |
+
data[key]["sha"] = new_sha
|
| 1391 |
+
|
| 1392 |
+
updated_data = {}
|
| 1393 |
+
for key in sorted(data.keys()):
|
| 1394 |
+
updated_data[key] = {}
|
| 1395 |
+
for attr, value in data[key].items():
|
| 1396 |
+
# deduplication and sort
|
| 1397 |
+
updated_data[key][attr] = sorted(set(value)) if attr != "sha" else value
|
| 1398 |
+
|
| 1399 |
+
with open(os.path.join(report_path, "updated_tiny_model_summary.json"), "w") as fp:
|
| 1400 |
+
json.dump(updated_data, fp, indent=4, ensure_ascii=False)
|
| 1401 |
+
|
| 1402 |
+
|
| 1403 |
+
def create_tiny_models(
|
| 1404 |
+
output_path,
|
| 1405 |
+
all,
|
| 1406 |
+
model_types,
|
| 1407 |
+
models_to_skip,
|
| 1408 |
+
no_check,
|
| 1409 |
+
upload,
|
| 1410 |
+
organization,
|
| 1411 |
+
token,
|
| 1412 |
+
num_workers=1,
|
| 1413 |
+
):
|
| 1414 |
+
clone_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
|
| 1415 |
+
if os.getcwd() != clone_path:
|
| 1416 |
+
raise ValueError(f"This script should be run from the root of the clone of `transformers` {clone_path}")
|
| 1417 |
+
|
| 1418 |
+
report_path = os.path.join(output_path, "reports")
|
| 1419 |
+
os.makedirs(report_path, exist_ok=True)
|
| 1420 |
+
|
| 1421 |
+
_pytorch_arch_mappings = [
|
| 1422 |
+
x
|
| 1423 |
+
for x in dir(transformers_module)
|
| 1424 |
+
if x.startswith("MODEL_") and x.endswith("_MAPPING") and x != "MODEL_NAMES_MAPPING"
|
| 1425 |
+
]
|
| 1426 |
+
_tensorflow_arch_mappings = [
|
| 1427 |
+
x for x in dir(transformers_module) if x.startswith("TF_MODEL_") and x.endswith("_MAPPING")
|
| 1428 |
+
]
|
| 1429 |
+
|
| 1430 |
+
pytorch_arch_mappings = [getattr(transformers_module, x) for x in _pytorch_arch_mappings]
|
| 1431 |
+
tensorflow_arch_mappings = [getattr(transformers_module, x) for x in _tensorflow_arch_mappings]
|
| 1432 |
+
|
| 1433 |
+
config_classes = CONFIG_MAPPING.values()
|
| 1434 |
+
if not all:
|
| 1435 |
+
config_classes = [CONFIG_MAPPING[model_type] for model_type in model_types]
|
| 1436 |
+
|
| 1437 |
+
# A map from config classes to tuples of processors (tokenizer, feature extractor, processor) classes
|
| 1438 |
+
processor_type_map = {c: get_processor_types_from_config_class(c) for c in config_classes}
|
| 1439 |
+
|
| 1440 |
+
to_create = {}
|
| 1441 |
+
for c in config_classes:
|
| 1442 |
+
processors = processor_type_map[c]
|
| 1443 |
+
models = get_architectures_from_config_class(c, pytorch_arch_mappings, models_to_skip)
|
| 1444 |
+
tf_models = get_architectures_from_config_class(c, tensorflow_arch_mappings, models_to_skip)
|
| 1445 |
+
if len(models) + len(tf_models) > 0:
|
| 1446 |
+
to_create[c] = {"processor": processors, "pytorch": models, "tensorflow": tf_models}
|
| 1447 |
+
|
| 1448 |
+
results = {}
|
| 1449 |
+
if num_workers <= 1:
|
| 1450 |
+
for c, models_to_create in list(to_create.items()):
|
| 1451 |
+
print(f"Create models for {c.__name__} ...")
|
| 1452 |
+
result = build(c, models_to_create, output_dir=os.path.join(output_path, c.model_type))
|
| 1453 |
+
results[c.__name__] = result
|
| 1454 |
+
print("=" * 40)
|
| 1455 |
+
else:
|
| 1456 |
+
all_build_args = []
|
| 1457 |
+
for c, models_to_create in list(to_create.items()):
|
| 1458 |
+
all_build_args.append((c, models_to_create, os.path.join(output_path, c.model_type)))
|
| 1459 |
+
with multiprocessing.Pool() as pool:
|
| 1460 |
+
results = pool.starmap(build, all_build_args)
|
| 1461 |
+
results = {buid_args[0].__name__: result for buid_args, result in zip(all_build_args, results)}
|
| 1462 |
+
|
| 1463 |
+
if upload:
|
| 1464 |
+
if organization is None:
|
| 1465 |
+
raise ValueError("The argument `organization` could not be `None`. No model is uploaded")
|
| 1466 |
+
|
| 1467 |
+
to_upload = []
|
| 1468 |
+
for model_type in os.listdir(output_path):
|
| 1469 |
+
# This is the directory containing the reports
|
| 1470 |
+
if model_type == "reports":
|
| 1471 |
+
continue
|
| 1472 |
+
for arch in os.listdir(os.path.join(output_path, model_type)):
|
| 1473 |
+
if arch == "processors":
|
| 1474 |
+
continue
|
| 1475 |
+
to_upload.append(os.path.join(output_path, model_type, arch))
|
| 1476 |
+
to_upload = sorted(to_upload)
|
| 1477 |
+
|
| 1478 |
+
upload_results = {}
|
| 1479 |
+
if len(to_upload) > 0:
|
| 1480 |
+
for model_dir in to_upload:
|
| 1481 |
+
try:
|
| 1482 |
+
upload_model(model_dir, organization, token)
|
| 1483 |
+
except Exception as e:
|
| 1484 |
+
error = f"Failed to upload {model_dir}. {e.__class__.__name__}: {e}"
|
| 1485 |
+
logger.error(error)
|
| 1486 |
+
upload_results[model_dir] = error
|
| 1487 |
+
|
| 1488 |
+
with open(os.path.join(report_path, "failed_uploads.json"), "w") as fp:
|
| 1489 |
+
json.dump(upload_results, fp, indent=4)
|
| 1490 |
+
|
| 1491 |
+
# Build the tiny model summary file. The `tokenizer_classes` and `processor_classes` could be both empty lists.
|
| 1492 |
+
# When using the items in this file to update the file `tests/utils/tiny_model_summary.json`, the model
|
| 1493 |
+
# architectures with `tokenizer_classes` and `processor_classes` being both empty should **NOT** be added to
|
| 1494 |
+
# `tests/utils/tiny_model_summary.json`.
|
| 1495 |
+
tiny_model_summary = build_tiny_model_summary(results, organization=organization, token=token)
|
| 1496 |
+
with open(os.path.join(report_path, "tiny_model_summary.json"), "w") as fp:
|
| 1497 |
+
json.dump(tiny_model_summary, fp, indent=4)
|
| 1498 |
+
|
| 1499 |
+
with open(os.path.join(report_path, "tiny_model_creation_report.json"), "w") as fp:
|
| 1500 |
+
json.dump(results, fp, indent=4)
|
| 1501 |
+
|
| 1502 |
+
# Build the warning/failure report (json format): same format as the complete `results` except this contains only
|
| 1503 |
+
# warnings or errors.
|
| 1504 |
+
failed_results = build_failed_report(results)
|
| 1505 |
+
with open(os.path.join(report_path, "failed_report.json"), "w") as fp:
|
| 1506 |
+
json.dump(failed_results, fp, indent=4)
|
| 1507 |
+
|
| 1508 |
+
simple_report, failed_report = build_simple_report(results)
|
| 1509 |
+
# The simplified report: a .txt file with each line of format:
|
| 1510 |
+
# {model architecture name}: {OK or error message}
|
| 1511 |
+
with open(os.path.join(report_path, "simple_report.txt"), "w") as fp:
|
| 1512 |
+
fp.write(simple_report)
|
| 1513 |
+
|
| 1514 |
+
# The simplified failure report: same above except this only contains line with errors
|
| 1515 |
+
with open(os.path.join(report_path, "simple_failed_report.txt"), "w") as fp:
|
| 1516 |
+
fp.write(failed_report)
|
| 1517 |
+
|
| 1518 |
+
update_tiny_model_summary_file(report_path=os.path.join(output_path, "reports"))
|
| 1519 |
+
|
| 1520 |
+
|
| 1521 |
+
if __name__ == "__main__":
|
| 1522 |
+
# This has to be `spawn` to avoid hanging forever!
|
| 1523 |
+
multiprocessing.set_start_method("spawn")
|
| 1524 |
+
|
| 1525 |
+
def list_str(values):
|
| 1526 |
+
return values.split(",")
|
| 1527 |
+
|
| 1528 |
+
parser = argparse.ArgumentParser()
|
| 1529 |
+
parser.add_argument("--all", action="store_true", help="Will create all tiny models.")
|
| 1530 |
+
parser.add_argument(
|
| 1531 |
+
"--no_check",
|
| 1532 |
+
action="store_true",
|
| 1533 |
+
help="If set, will not check the validity of architectures. Use with caution.",
|
| 1534 |
+
)
|
| 1535 |
+
parser.add_argument(
|
| 1536 |
+
"-m",
|
| 1537 |
+
"--model_types",
|
| 1538 |
+
type=list_str,
|
| 1539 |
+
help="Comma-separated list of model type(s) from which the tiny models will be created.",
|
| 1540 |
+
)
|
| 1541 |
+
parser.add_argument(
|
| 1542 |
+
"--models_to_skip",
|
| 1543 |
+
type=list_str,
|
| 1544 |
+
help=(
|
| 1545 |
+
"Comma-separated list of model class names(s) from which the tiny models won't be created.\nThis is usually "
|
| 1546 |
+
"the list of model classes that have their tiny versions already uploaded to the Hub."
|
| 1547 |
+
),
|
| 1548 |
+
)
|
| 1549 |
+
parser.add_argument("--upload", action="store_true", help="If to upload the created tiny models to the Hub.")
|
| 1550 |
+
parser.add_argument(
|
| 1551 |
+
"--organization",
|
| 1552 |
+
default=None,
|
| 1553 |
+
type=str,
|
| 1554 |
+
help="The organization on the Hub to which the tiny models will be uploaded.",
|
| 1555 |
+
)
|
| 1556 |
+
parser.add_argument(
|
| 1557 |
+
"--token", default=None, type=str, help="A valid authentication token for HuggingFace Hub with write access."
|
| 1558 |
+
)
|
| 1559 |
+
parser.add_argument("output_path", type=Path, help="Path indicating where to store generated model.")
|
| 1560 |
+
parser.add_argument("--num_workers", default=1, type=int, help="The number of workers to run.")
|
| 1561 |
+
|
| 1562 |
+
args = parser.parse_args()
|
| 1563 |
+
|
| 1564 |
+
if not args.all and not args.model_types:
|
| 1565 |
+
raise ValueError("Please provide at least one model type or pass `--all` to export all architectures.")
|
| 1566 |
+
|
| 1567 |
+
create_tiny_models(
|
| 1568 |
+
args.output_path,
|
| 1569 |
+
args.all,
|
| 1570 |
+
args.model_types,
|
| 1571 |
+
args.models_to_skip,
|
| 1572 |
+
args.no_check,
|
| 1573 |
+
args.upload,
|
| 1574 |
+
args.organization,
|
| 1575 |
+
args.token,
|
| 1576 |
+
args.num_workers,
|
| 1577 |
+
)
|
tasks/tasksmith-441eeab80047/environment/source/utils/custom_init_isort.py
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 sorts the imports in the custom inits of Transformers. Transformers uses init files that delay the
|
| 17 |
+
import of an object to when it's actually needed. This is to avoid the main init importing all models, which would
|
| 18 |
+
make the line `import transformers` very slow when the user has all optional dependencies installed. The inits with
|
| 19 |
+
delayed imports have two halves: one definining a dictionary `_import_structure` which maps modules to the name of the
|
| 20 |
+
objects in each module, and one in `TYPE_CHECKING` which looks like a normal init for type-checkers. `isort` or `ruff`
|
| 21 |
+
properly sort the second half which looks like traditionl imports, the goal of this script is to sort the first half.
|
| 22 |
+
|
| 23 |
+
Use from the root of the repo with:
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
python utils/custom_init_isort.py
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
which will auto-sort the imports (used in `make style`).
|
| 30 |
+
|
| 31 |
+
For a check only (as used in `make quality`) run:
|
| 32 |
+
|
| 33 |
+
```bash
|
| 34 |
+
python utils/custom_init_isort.py --check_only
|
| 35 |
+
```
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
import argparse
|
| 39 |
+
import os
|
| 40 |
+
import re
|
| 41 |
+
from typing import Any, Callable, List, Optional
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# Path is defined with the intent you should run this script from the root of the repo.
|
| 45 |
+
PATH_TO_TRANSFORMERS = "src/transformers"
|
| 46 |
+
|
| 47 |
+
# Pattern that looks at the indentation in a line.
|
| 48 |
+
_re_indent = re.compile(r"^(\s*)\S")
|
| 49 |
+
# Pattern that matches `"key":" and puts `key` in group 0.
|
| 50 |
+
_re_direct_key = re.compile(r'^\s*"([^"]+)":')
|
| 51 |
+
# Pattern that matches `_import_structure["key"]` and puts `key` in group 0.
|
| 52 |
+
_re_indirect_key = re.compile(r'^\s*_import_structure\["([^"]+)"\]')
|
| 53 |
+
# Pattern that matches `"key",` and puts `key` in group 0.
|
| 54 |
+
_re_strip_line = re.compile(r'^\s*"([^"]+)",\s*$')
|
| 55 |
+
# Pattern that matches any `[stuff]` and puts `stuff` in group 0.
|
| 56 |
+
_re_bracket_content = re.compile(r"\[([^\]]+)\]")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def get_indent(line: str) -> str:
|
| 60 |
+
"""Returns the indent in given line (as string)."""
|
| 61 |
+
search = _re_indent.search(line)
|
| 62 |
+
return "" if search is None else search.groups()[0]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def split_code_in_indented_blocks(
|
| 66 |
+
code: str, indent_level: str = "", start_prompt: Optional[str] = None, end_prompt: Optional[str] = None
|
| 67 |
+
) -> List[str]:
|
| 68 |
+
"""
|
| 69 |
+
Split some code into its indented blocks, starting at a given level.
|
| 70 |
+
|
| 71 |
+
Args:
|
| 72 |
+
code (`str`): The code to split.
|
| 73 |
+
indent_level (`str`): The indent level (as string) to use for identifying the blocks to split.
|
| 74 |
+
start_prompt (`str`, *optional*): If provided, only starts splitting at the line where this text is.
|
| 75 |
+
end_prompt (`str`, *optional*): If provided, stops splitting at a line where this text is.
|
| 76 |
+
|
| 77 |
+
Warning:
|
| 78 |
+
The text before `start_prompt` or after `end_prompt` (if provided) is not ignored, just not split. The input `code`
|
| 79 |
+
can thus be retrieved by joining the result.
|
| 80 |
+
|
| 81 |
+
Returns:
|
| 82 |
+
`List[str]`: The list of blocks.
|
| 83 |
+
"""
|
| 84 |
+
# Let's split the code into lines and move to start_index.
|
| 85 |
+
index = 0
|
| 86 |
+
lines = code.split("\n")
|
| 87 |
+
if start_prompt is not None:
|
| 88 |
+
while not lines[index].startswith(start_prompt):
|
| 89 |
+
index += 1
|
| 90 |
+
blocks = ["\n".join(lines[:index])]
|
| 91 |
+
else:
|
| 92 |
+
blocks = []
|
| 93 |
+
|
| 94 |
+
# This variable contains the block treated at a given time.
|
| 95 |
+
current_block = [lines[index]]
|
| 96 |
+
index += 1
|
| 97 |
+
# We split into blocks until we get to the `end_prompt` (or the end of the file).
|
| 98 |
+
while index < len(lines) and (end_prompt is None or not lines[index].startswith(end_prompt)):
|
| 99 |
+
# We have a non-empty line with the proper indent -> start of a new block
|
| 100 |
+
if len(lines[index]) > 0 and get_indent(lines[index]) == indent_level:
|
| 101 |
+
# Store the current block in the result and rest. There are two cases: the line is part of the block (like
|
| 102 |
+
# a closing parenthesis) or not.
|
| 103 |
+
if len(current_block) > 0 and get_indent(current_block[-1]).startswith(indent_level + " "):
|
| 104 |
+
# Line is part of the current block
|
| 105 |
+
current_block.append(lines[index])
|
| 106 |
+
blocks.append("\n".join(current_block))
|
| 107 |
+
if index < len(lines) - 1:
|
| 108 |
+
current_block = [lines[index + 1]]
|
| 109 |
+
index += 1
|
| 110 |
+
else:
|
| 111 |
+
current_block = []
|
| 112 |
+
else:
|
| 113 |
+
# Line is not part of the current block
|
| 114 |
+
blocks.append("\n".join(current_block))
|
| 115 |
+
current_block = [lines[index]]
|
| 116 |
+
else:
|
| 117 |
+
# Just add the line to the current block
|
| 118 |
+
current_block.append(lines[index])
|
| 119 |
+
index += 1
|
| 120 |
+
|
| 121 |
+
# Adds current block if it's nonempty.
|
| 122 |
+
if len(current_block) > 0:
|
| 123 |
+
blocks.append("\n".join(current_block))
|
| 124 |
+
|
| 125 |
+
# Add final block after end_prompt if provided.
|
| 126 |
+
if end_prompt is not None and index < len(lines):
|
| 127 |
+
blocks.append("\n".join(lines[index:]))
|
| 128 |
+
|
| 129 |
+
return blocks
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def ignore_underscore_and_lowercase(key: Callable[[Any], str]) -> Callable[[Any], str]:
|
| 133 |
+
"""
|
| 134 |
+
Wraps a key function (as used in a sort) to lowercase and ignore underscores.
|
| 135 |
+
"""
|
| 136 |
+
|
| 137 |
+
def _inner(x):
|
| 138 |
+
return key(x).lower().replace("_", "")
|
| 139 |
+
|
| 140 |
+
return _inner
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def sort_objects(objects: List[Any], key: Optional[Callable[[Any], str]] = None) -> List[Any]:
|
| 144 |
+
"""
|
| 145 |
+
Sort a list of objects following the rules of isort (all uppercased first, camel-cased second and lower-cased
|
| 146 |
+
last).
|
| 147 |
+
|
| 148 |
+
Args:
|
| 149 |
+
objects (`List[Any]`):
|
| 150 |
+
The list of objects to sort.
|
| 151 |
+
key (`Callable[[Any], str]`, *optional*):
|
| 152 |
+
A function taking an object as input and returning a string, used to sort them by alphabetical order.
|
| 153 |
+
If not provided, will default to noop (so a `key` must be provided if the `objects` are not of type string).
|
| 154 |
+
|
| 155 |
+
Returns:
|
| 156 |
+
`List[Any]`: The sorted list with the same elements as in the inputs
|
| 157 |
+
"""
|
| 158 |
+
|
| 159 |
+
# If no key is provided, we use a noop.
|
| 160 |
+
def noop(x):
|
| 161 |
+
return x
|
| 162 |
+
|
| 163 |
+
if key is None:
|
| 164 |
+
key = noop
|
| 165 |
+
# Constants are all uppercase, they go first.
|
| 166 |
+
constants = [obj for obj in objects if key(obj).isupper()]
|
| 167 |
+
# Classes are not all uppercase but start with a capital, they go second.
|
| 168 |
+
classes = [obj for obj in objects if key(obj)[0].isupper() and not key(obj).isupper()]
|
| 169 |
+
# Functions begin with a lowercase, they go last.
|
| 170 |
+
functions = [obj for obj in objects if not key(obj)[0].isupper()]
|
| 171 |
+
|
| 172 |
+
# Then we sort each group.
|
| 173 |
+
key1 = ignore_underscore_and_lowercase(key)
|
| 174 |
+
return sorted(constants, key=key1) + sorted(classes, key=key1) + sorted(functions, key=key1)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def sort_objects_in_import(import_statement: str) -> str:
|
| 178 |
+
"""
|
| 179 |
+
Sorts the imports in a single import statement.
|
| 180 |
+
|
| 181 |
+
Args:
|
| 182 |
+
import_statement (`str`): The import statement in which to sort the imports.
|
| 183 |
+
|
| 184 |
+
Returns:
|
| 185 |
+
`str`: The same as the input, but with objects properly sorted.
|
| 186 |
+
"""
|
| 187 |
+
|
| 188 |
+
# This inner function sort imports between [ ].
|
| 189 |
+
def _replace(match):
|
| 190 |
+
imports = match.groups()[0]
|
| 191 |
+
# If there is one import only, nothing to do.
|
| 192 |
+
if "," not in imports:
|
| 193 |
+
return f"[{imports}]"
|
| 194 |
+
keys = [part.strip().replace('"', "") for part in imports.split(",")]
|
| 195 |
+
# We will have a final empty element if the line finished with a comma.
|
| 196 |
+
if len(keys[-1]) == 0:
|
| 197 |
+
keys = keys[:-1]
|
| 198 |
+
return "[" + ", ".join([f'"{k}"' for k in sort_objects(keys)]) + "]"
|
| 199 |
+
|
| 200 |
+
lines = import_statement.split("\n")
|
| 201 |
+
if len(lines) > 3:
|
| 202 |
+
# Here we have to sort internal imports that are on several lines (one per name):
|
| 203 |
+
# key: [
|
| 204 |
+
# "object1",
|
| 205 |
+
# "object2",
|
| 206 |
+
# ...
|
| 207 |
+
# ]
|
| 208 |
+
|
| 209 |
+
# We may have to ignore one or two lines on each side.
|
| 210 |
+
idx = 2 if lines[1].strip() == "[" else 1
|
| 211 |
+
keys_to_sort = [(i, _re_strip_line.search(line).groups()[0]) for i, line in enumerate(lines[idx:-idx])]
|
| 212 |
+
sorted_indices = sort_objects(keys_to_sort, key=lambda x: x[1])
|
| 213 |
+
sorted_lines = [lines[x[0] + idx] for x in sorted_indices]
|
| 214 |
+
return "\n".join(lines[:idx] + sorted_lines + lines[-idx:])
|
| 215 |
+
elif len(lines) == 3:
|
| 216 |
+
# Here we have to sort internal imports that are on one separate line:
|
| 217 |
+
# key: [
|
| 218 |
+
# "object1", "object2", ...
|
| 219 |
+
# ]
|
| 220 |
+
if _re_bracket_content.search(lines[1]) is not None:
|
| 221 |
+
lines[1] = _re_bracket_content.sub(_replace, lines[1])
|
| 222 |
+
else:
|
| 223 |
+
keys = [part.strip().replace('"', "") for part in lines[1].split(",")]
|
| 224 |
+
# We will have a final empty element if the line finished with a comma.
|
| 225 |
+
if len(keys[-1]) == 0:
|
| 226 |
+
keys = keys[:-1]
|
| 227 |
+
lines[1] = get_indent(lines[1]) + ", ".join([f'"{k}"' for k in sort_objects(keys)])
|
| 228 |
+
return "\n".join(lines)
|
| 229 |
+
else:
|
| 230 |
+
# Finally we have to deal with imports fitting on one line
|
| 231 |
+
import_statement = _re_bracket_content.sub(_replace, import_statement)
|
| 232 |
+
return import_statement
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def sort_imports(file: str, check_only: bool = True):
|
| 236 |
+
"""
|
| 237 |
+
Sort the imports defined in the `_import_structure` of a given init.
|
| 238 |
+
|
| 239 |
+
Args:
|
| 240 |
+
file (`str`): The path to the init to check/fix.
|
| 241 |
+
check_only (`bool`, *optional*, defaults to `True`): Whether or not to just check (and not auto-fix) the init.
|
| 242 |
+
"""
|
| 243 |
+
with open(file, encoding="utf-8") as f:
|
| 244 |
+
code = f.read()
|
| 245 |
+
|
| 246 |
+
# If the file is not a custom init, there is nothing to do.
|
| 247 |
+
if "_import_structure" not in code or "define_import_structure" in code:
|
| 248 |
+
return
|
| 249 |
+
|
| 250 |
+
# Blocks of indent level 0
|
| 251 |
+
main_blocks = split_code_in_indented_blocks(
|
| 252 |
+
code, start_prompt="_import_structure = {", end_prompt="if TYPE_CHECKING:"
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
# We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt).
|
| 256 |
+
for block_idx in range(1, len(main_blocks) - 1):
|
| 257 |
+
# Check if the block contains some `_import_structure`s thingy to sort.
|
| 258 |
+
block = main_blocks[block_idx]
|
| 259 |
+
block_lines = block.split("\n")
|
| 260 |
+
|
| 261 |
+
# Get to the start of the imports.
|
| 262 |
+
line_idx = 0
|
| 263 |
+
while line_idx < len(block_lines) and "_import_structure" not in block_lines[line_idx]:
|
| 264 |
+
# Skip dummy import blocks
|
| 265 |
+
if "import dummy" in block_lines[line_idx]:
|
| 266 |
+
line_idx = len(block_lines)
|
| 267 |
+
else:
|
| 268 |
+
line_idx += 1
|
| 269 |
+
if line_idx >= len(block_lines):
|
| 270 |
+
continue
|
| 271 |
+
|
| 272 |
+
# Ignore beginning and last line: they don't contain anything.
|
| 273 |
+
internal_block_code = "\n".join(block_lines[line_idx:-1])
|
| 274 |
+
indent = get_indent(block_lines[1])
|
| 275 |
+
# Slit the internal block into blocks of indent level 1.
|
| 276 |
+
internal_blocks = split_code_in_indented_blocks(internal_block_code, indent_level=indent)
|
| 277 |
+
# We have two categories of import key: list or _import_structure[key].append/extend
|
| 278 |
+
pattern = _re_direct_key if "_import_structure = {" in block_lines[0] else _re_indirect_key
|
| 279 |
+
# Grab the keys, but there is a trap: some lines are empty or just comments.
|
| 280 |
+
keys = [(pattern.search(b).groups()[0] if pattern.search(b) is not None else None) for b in internal_blocks]
|
| 281 |
+
# We only sort the lines with a key.
|
| 282 |
+
keys_to_sort = [(i, key) for i, key in enumerate(keys) if key is not None]
|
| 283 |
+
sorted_indices = [x[0] for x in sorted(keys_to_sort, key=lambda x: x[1])]
|
| 284 |
+
|
| 285 |
+
# We reorder the blocks by leaving empty lines/comments as they were and reorder the rest.
|
| 286 |
+
count = 0
|
| 287 |
+
reorderded_blocks = []
|
| 288 |
+
for i in range(len(internal_blocks)):
|
| 289 |
+
if keys[i] is None:
|
| 290 |
+
reorderded_blocks.append(internal_blocks[i])
|
| 291 |
+
else:
|
| 292 |
+
block = sort_objects_in_import(internal_blocks[sorted_indices[count]])
|
| 293 |
+
reorderded_blocks.append(block)
|
| 294 |
+
count += 1
|
| 295 |
+
|
| 296 |
+
# And we put our main block back together with its first and last line.
|
| 297 |
+
main_blocks[block_idx] = "\n".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]])
|
| 298 |
+
|
| 299 |
+
if code != "\n".join(main_blocks):
|
| 300 |
+
if check_only:
|
| 301 |
+
return True
|
| 302 |
+
else:
|
| 303 |
+
print(f"Overwriting {file}.")
|
| 304 |
+
with open(file, "w", encoding="utf-8") as f:
|
| 305 |
+
f.write("\n".join(main_blocks))
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def sort_imports_in_all_inits(check_only=True):
|
| 309 |
+
"""
|
| 310 |
+
Sort the imports defined in the `_import_structure` of all inits in the repo.
|
| 311 |
+
|
| 312 |
+
Args:
|
| 313 |
+
check_only (`bool`, *optional*, defaults to `True`): Whether or not to just check (and not auto-fix) the init.
|
| 314 |
+
"""
|
| 315 |
+
failures = []
|
| 316 |
+
for root, _, files in os.walk(PATH_TO_TRANSFORMERS):
|
| 317 |
+
if "__init__.py" in files:
|
| 318 |
+
result = sort_imports(os.path.join(root, "__init__.py"), check_only=check_only)
|
| 319 |
+
if result:
|
| 320 |
+
failures = [os.path.join(root, "__init__.py")]
|
| 321 |
+
if len(failures) > 0:
|
| 322 |
+
raise ValueError(f"Would overwrite {len(failures)} files, run `make style`.")
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
if __name__ == "__main__":
|
| 326 |
+
parser = argparse.ArgumentParser()
|
| 327 |
+
parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.")
|
| 328 |
+
args = parser.parse_args()
|
| 329 |
+
|
| 330 |
+
sort_imports_in_all_inits(check_only=args.check_only)
|
tasks/tasksmith-441eeab80047/environment/source/utils/deprecate_models.py
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Script which deprecates a list of given models
|
| 3 |
+
|
| 4 |
+
Example usage:
|
| 5 |
+
python utils/deprecate_models.py --models bert distilbert
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import os
|
| 10 |
+
from collections import defaultdict
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Optional, Tuple
|
| 13 |
+
|
| 14 |
+
import requests
|
| 15 |
+
from custom_init_isort import sort_imports_in_all_inits
|
| 16 |
+
from git import Repo
|
| 17 |
+
from packaging import version
|
| 18 |
+
|
| 19 |
+
from transformers import CONFIG_MAPPING, logging
|
| 20 |
+
from transformers import __version__ as current_version
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
REPO_PATH = Path(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
|
| 24 |
+
repo = Repo(REPO_PATH)
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def get_last_stable_minor_release():
|
| 30 |
+
# Get the last stable release of transformers
|
| 31 |
+
url = "https://pypi.org/pypi/transformers/json"
|
| 32 |
+
release_data = requests.get(url).json()
|
| 33 |
+
|
| 34 |
+
# Find the last stable release of of transformers (version below current version)
|
| 35 |
+
major_version, minor_version, patch_version, _ = current_version.split(".")
|
| 36 |
+
last_major_minor = f"{major_version}.{int(minor_version) - 1}"
|
| 37 |
+
last_stable_minor_releases = [
|
| 38 |
+
release for release in release_data["releases"] if release.startswith(last_major_minor)
|
| 39 |
+
]
|
| 40 |
+
last_stable_release = sorted(last_stable_minor_releases, key=version.parse)[-1]
|
| 41 |
+
|
| 42 |
+
return last_stable_release
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def build_tip_message(last_stable_release):
|
| 46 |
+
return (
|
| 47 |
+
"""
|
| 48 |
+
<Tip warning={true}>
|
| 49 |
+
|
| 50 |
+
This model is in maintenance mode only, we don't accept any new PRs changing its code.
|
| 51 |
+
"""
|
| 52 |
+
+ f"""If you run into any issues running this model, please reinstall the last version that supported this model: v{last_stable_release}.
|
| 53 |
+
You can do so by running the following command: `pip install -U transformers=={last_stable_release}`.
|
| 54 |
+
|
| 55 |
+
</Tip>"""
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def insert_tip_to_model_doc(model_doc_path, tip_message):
|
| 60 |
+
tip_message_lines = tip_message.split("\n")
|
| 61 |
+
|
| 62 |
+
with open(model_doc_path, "r") as f:
|
| 63 |
+
model_doc = f.read()
|
| 64 |
+
|
| 65 |
+
# Add the tip message to the model doc page directly underneath the title
|
| 66 |
+
lines = model_doc.split("\n")
|
| 67 |
+
|
| 68 |
+
new_model_lines = []
|
| 69 |
+
for line in lines:
|
| 70 |
+
if line.startswith("# "):
|
| 71 |
+
new_model_lines.append(line)
|
| 72 |
+
new_model_lines.extend(tip_message_lines)
|
| 73 |
+
else:
|
| 74 |
+
new_model_lines.append(line)
|
| 75 |
+
|
| 76 |
+
with open(model_doc_path, "w") as f:
|
| 77 |
+
f.write("\n".join(new_model_lines))
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def get_model_doc_path(model: str) -> Tuple[Optional[str], Optional[str]]:
|
| 81 |
+
# Possible variants of the model name in the model doc path
|
| 82 |
+
model_names = [model, model.replace("_", "-"), model.replace("_", "")]
|
| 83 |
+
|
| 84 |
+
model_doc_paths = [REPO_PATH / f"docs/source/en/model_doc/{model_name}.md" for model_name in model_names]
|
| 85 |
+
|
| 86 |
+
for model_doc_path, model_name in zip(model_doc_paths, model_names):
|
| 87 |
+
if os.path.exists(model_doc_path):
|
| 88 |
+
return model_doc_path, model_name
|
| 89 |
+
|
| 90 |
+
return None, None
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def extract_model_info(model):
|
| 94 |
+
model_info = {}
|
| 95 |
+
model_doc_path, model_doc_name = get_model_doc_path(model)
|
| 96 |
+
model_path = REPO_PATH / f"src/transformers/models/{model}"
|
| 97 |
+
|
| 98 |
+
if model_doc_path is None:
|
| 99 |
+
print(f"Model doc path does not exist for {model}")
|
| 100 |
+
return None
|
| 101 |
+
model_info["model_doc_path"] = model_doc_path
|
| 102 |
+
model_info["model_doc_name"] = model_doc_name
|
| 103 |
+
|
| 104 |
+
if not os.path.exists(model_path):
|
| 105 |
+
print(f"Model path does not exist for {model}")
|
| 106 |
+
return None
|
| 107 |
+
model_info["model_path"] = model_path
|
| 108 |
+
|
| 109 |
+
return model_info
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def update_relative_imports(filename, model):
|
| 113 |
+
with open(filename, "r") as f:
|
| 114 |
+
filelines = f.read()
|
| 115 |
+
|
| 116 |
+
new_file_lines = []
|
| 117 |
+
for line in filelines.split("\n"):
|
| 118 |
+
if line.startswith("from .."):
|
| 119 |
+
new_file_lines.append(line.replace("from ..", "from ..."))
|
| 120 |
+
else:
|
| 121 |
+
new_file_lines.append(line)
|
| 122 |
+
|
| 123 |
+
with open(filename, "w") as f:
|
| 124 |
+
f.write("\n".join(new_file_lines))
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def remove_copied_from_statements(model):
|
| 128 |
+
model_path = REPO_PATH / f"src/transformers/models/{model}"
|
| 129 |
+
for file in os.listdir(model_path):
|
| 130 |
+
if file == "__pycache__":
|
| 131 |
+
continue
|
| 132 |
+
file_path = model_path / file
|
| 133 |
+
with open(file_path, "r") as f:
|
| 134 |
+
file_lines = f.read()
|
| 135 |
+
|
| 136 |
+
new_file_lines = []
|
| 137 |
+
for line in file_lines.split("\n"):
|
| 138 |
+
if "# Copied from" in line:
|
| 139 |
+
continue
|
| 140 |
+
new_file_lines.append(line)
|
| 141 |
+
|
| 142 |
+
with open(file_path, "w") as f:
|
| 143 |
+
f.write("\n".join(new_file_lines))
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def move_model_files_to_deprecated(model):
|
| 147 |
+
model_path = REPO_PATH / f"src/transformers/models/{model}"
|
| 148 |
+
deprecated_model_path = REPO_PATH / f"src/transformers/models/deprecated/{model}"
|
| 149 |
+
|
| 150 |
+
if not os.path.exists(deprecated_model_path):
|
| 151 |
+
os.makedirs(deprecated_model_path)
|
| 152 |
+
|
| 153 |
+
for file in os.listdir(model_path):
|
| 154 |
+
if file == "__pycache__":
|
| 155 |
+
continue
|
| 156 |
+
repo.git.mv(f"{model_path}/{file}", f"{deprecated_model_path}/{file}")
|
| 157 |
+
|
| 158 |
+
# For deprecated files, we then need to update the relative imports
|
| 159 |
+
update_relative_imports(f"{deprecated_model_path}/{file}", model)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def delete_model_tests(model):
|
| 163 |
+
tests_path = REPO_PATH / f"tests/models/{model}"
|
| 164 |
+
|
| 165 |
+
if os.path.exists(tests_path):
|
| 166 |
+
repo.git.rm("-r", tests_path)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def get_line_indent(s):
|
| 170 |
+
return len(s) - len(s.lstrip())
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def update_main_init_file(models):
|
| 174 |
+
"""
|
| 175 |
+
Replace all instances of model.model_name with model.deprecated.model_name in the __init__.py file
|
| 176 |
+
|
| 177 |
+
Args:
|
| 178 |
+
models (List[str]): The models to mark as deprecated
|
| 179 |
+
"""
|
| 180 |
+
filename = REPO_PATH / "src/transformers/__init__.py"
|
| 181 |
+
with open(filename, "r") as f:
|
| 182 |
+
init_file = f.read()
|
| 183 |
+
|
| 184 |
+
# 1. For each model, find all the instances of model.model_name and replace with model.deprecated.model_name
|
| 185 |
+
for model in models:
|
| 186 |
+
init_file = init_file.replace(f'models.{model}"', f'models.deprecated.{model}"')
|
| 187 |
+
init_file = init_file.replace(f"models.{model} import", f"models.deprecated.{model} import")
|
| 188 |
+
|
| 189 |
+
with open(filename, "w") as f:
|
| 190 |
+
f.write(init_file)
|
| 191 |
+
|
| 192 |
+
# 2. Resort the imports
|
| 193 |
+
sort_imports_in_all_inits(check_only=False)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def remove_model_references_from_file(filename, models, condition):
|
| 197 |
+
"""
|
| 198 |
+
Remove all references to the given models from the given file
|
| 199 |
+
|
| 200 |
+
Args:
|
| 201 |
+
filename (str): The file to remove the references from
|
| 202 |
+
models (List[str]): The models to remove
|
| 203 |
+
condition (Callable): A function that takes the line and model and returns True if the line should be removed
|
| 204 |
+
"""
|
| 205 |
+
filename = REPO_PATH / filename
|
| 206 |
+
with open(filename, "r") as f:
|
| 207 |
+
init_file = f.read()
|
| 208 |
+
|
| 209 |
+
new_file_lines = []
|
| 210 |
+
for i, line in enumerate(init_file.split("\n")):
|
| 211 |
+
if any(condition(line, model) for model in models):
|
| 212 |
+
continue
|
| 213 |
+
new_file_lines.append(line)
|
| 214 |
+
|
| 215 |
+
with open(filename, "w") as f:
|
| 216 |
+
f.write("\n".join(new_file_lines))
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def remove_model_config_classes_from_config_check(model_config_classes):
|
| 220 |
+
"""
|
| 221 |
+
Remove the deprecated model config classes from the check_config_attributes.py file
|
| 222 |
+
|
| 223 |
+
Args:
|
| 224 |
+
model_config_classes (List[str]): The model config classes to remove e.g. ["BertConfig", "DistilBertConfig"]
|
| 225 |
+
"""
|
| 226 |
+
filename = REPO_PATH / "utils/check_config_attributes.py"
|
| 227 |
+
with open(filename, "r") as f:
|
| 228 |
+
check_config_attributes = f.read()
|
| 229 |
+
|
| 230 |
+
# Keep track as we have to delete comment above too
|
| 231 |
+
in_special_cases_to_allow = False
|
| 232 |
+
in_indent = False
|
| 233 |
+
new_file_lines = []
|
| 234 |
+
|
| 235 |
+
for line in check_config_attributes.split("\n"):
|
| 236 |
+
indent = get_line_indent(line)
|
| 237 |
+
if (line.strip() == "SPECIAL_CASES_TO_ALLOW = {") or (line.strip() == "SPECIAL_CASES_TO_ALLOW.update("):
|
| 238 |
+
in_special_cases_to_allow = True
|
| 239 |
+
|
| 240 |
+
elif in_special_cases_to_allow and indent == 0 and line.strip() in ("}", ")"):
|
| 241 |
+
in_special_cases_to_allow = False
|
| 242 |
+
|
| 243 |
+
if in_indent:
|
| 244 |
+
if line.strip().endswith(("]", "],")):
|
| 245 |
+
in_indent = False
|
| 246 |
+
continue
|
| 247 |
+
|
| 248 |
+
if in_special_cases_to_allow and any(
|
| 249 |
+
model_config_class in line for model_config_class in model_config_classes
|
| 250 |
+
):
|
| 251 |
+
# Remove comments above the model config class to remove
|
| 252 |
+
while new_file_lines[-1].strip().startswith("#"):
|
| 253 |
+
new_file_lines.pop()
|
| 254 |
+
|
| 255 |
+
if line.strip().endswith("["):
|
| 256 |
+
in_indent = True
|
| 257 |
+
|
| 258 |
+
continue
|
| 259 |
+
|
| 260 |
+
elif any(model_config_class in line for model_config_class in model_config_classes):
|
| 261 |
+
continue
|
| 262 |
+
|
| 263 |
+
new_file_lines.append(line)
|
| 264 |
+
|
| 265 |
+
with open(filename, "w") as f:
|
| 266 |
+
f.write("\n".join(new_file_lines))
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def add_models_to_deprecated_models_in_config_auto(models):
|
| 270 |
+
"""
|
| 271 |
+
Add the models to the DEPRECATED_MODELS list in configuration_auto.py and sorts the list
|
| 272 |
+
to be in alphabetical order.
|
| 273 |
+
"""
|
| 274 |
+
filepath = REPO_PATH / "src/transformers/models/auto/configuration_auto.py"
|
| 275 |
+
with open(filepath, "r") as f:
|
| 276 |
+
config_auto = f.read()
|
| 277 |
+
|
| 278 |
+
new_file_lines = []
|
| 279 |
+
deprecated_models_list = []
|
| 280 |
+
in_deprecated_models = False
|
| 281 |
+
for line in config_auto.split("\n"):
|
| 282 |
+
if line.strip() == "DEPRECATED_MODELS = [":
|
| 283 |
+
in_deprecated_models = True
|
| 284 |
+
new_file_lines.append(line)
|
| 285 |
+
elif in_deprecated_models and line.strip() == "]":
|
| 286 |
+
in_deprecated_models = False
|
| 287 |
+
# Add the new models to deprecated models list
|
| 288 |
+
deprecated_models_list.extend([f' "{model}", ' for model in models])
|
| 289 |
+
# Sort so they're in alphabetical order in the file
|
| 290 |
+
deprecated_models_list = sorted(deprecated_models_list)
|
| 291 |
+
new_file_lines.extend(deprecated_models_list)
|
| 292 |
+
# Make sure we still have the closing bracket
|
| 293 |
+
new_file_lines.append(line)
|
| 294 |
+
elif in_deprecated_models:
|
| 295 |
+
deprecated_models_list.append(line)
|
| 296 |
+
else:
|
| 297 |
+
new_file_lines.append(line)
|
| 298 |
+
|
| 299 |
+
with open(filepath, "w") as f:
|
| 300 |
+
f.write("\n".join(new_file_lines))
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def deprecate_models(models):
|
| 304 |
+
# Get model info
|
| 305 |
+
skipped_models = []
|
| 306 |
+
models_info = defaultdict(dict)
|
| 307 |
+
for model in models:
|
| 308 |
+
single_model_info = extract_model_info(model)
|
| 309 |
+
if single_model_info is None:
|
| 310 |
+
skipped_models.append(model)
|
| 311 |
+
else:
|
| 312 |
+
models_info[model] = single_model_info
|
| 313 |
+
|
| 314 |
+
model_config_classes = []
|
| 315 |
+
for model, model_info in models_info.items():
|
| 316 |
+
if model in CONFIG_MAPPING:
|
| 317 |
+
model_config_classes.append(CONFIG_MAPPING[model].__name__)
|
| 318 |
+
elif model_info["model_doc_name"] in CONFIG_MAPPING:
|
| 319 |
+
model_config_classes.append(CONFIG_MAPPING[model_info["model_doc_name"]].__name__)
|
| 320 |
+
else:
|
| 321 |
+
skipped_models.append(model)
|
| 322 |
+
print(f"Model config class not found for model: {model}")
|
| 323 |
+
|
| 324 |
+
# Filter out skipped models
|
| 325 |
+
models = [model for model in models if model not in skipped_models]
|
| 326 |
+
|
| 327 |
+
if skipped_models:
|
| 328 |
+
print(f"Skipped models: {skipped_models} as the model doc or model path could not be found.")
|
| 329 |
+
print(f"Models to deprecate: {models}")
|
| 330 |
+
|
| 331 |
+
# Remove model config classes from config check
|
| 332 |
+
print("Removing model config classes from config checks")
|
| 333 |
+
remove_model_config_classes_from_config_check(model_config_classes)
|
| 334 |
+
|
| 335 |
+
tip_message = build_tip_message(get_last_stable_minor_release())
|
| 336 |
+
|
| 337 |
+
for model, model_info in models_info.items():
|
| 338 |
+
print(f"Processing model: {model}")
|
| 339 |
+
# Add the tip message to the model doc page directly underneath the title
|
| 340 |
+
print("Adding tip message to model doc page")
|
| 341 |
+
insert_tip_to_model_doc(model_info["model_doc_path"], tip_message)
|
| 342 |
+
|
| 343 |
+
# Remove #Copied from statements from model's files
|
| 344 |
+
print("Removing #Copied from statements from model's files")
|
| 345 |
+
remove_copied_from_statements(model)
|
| 346 |
+
|
| 347 |
+
# Move the model file to deprecated: src/transfomers/models/model -> src/transformers/models/deprecated/model
|
| 348 |
+
print("Moving model files to deprecated for model")
|
| 349 |
+
move_model_files_to_deprecated(model)
|
| 350 |
+
|
| 351 |
+
# Delete the model tests: tests/models/model
|
| 352 |
+
print("Deleting model tests")
|
| 353 |
+
delete_model_tests(model)
|
| 354 |
+
|
| 355 |
+
# # We do the following with all models passed at once to avoid having to re-write the file multiple times
|
| 356 |
+
print("Updating __init__.py file to point to the deprecated models")
|
| 357 |
+
update_main_init_file(models)
|
| 358 |
+
|
| 359 |
+
# Remove model references from other files
|
| 360 |
+
print("Removing model references from other files")
|
| 361 |
+
remove_model_references_from_file(
|
| 362 |
+
"src/transformers/models/__init__.py", models, lambda line, model: model == line.strip().strip(",")
|
| 363 |
+
)
|
| 364 |
+
remove_model_references_from_file(
|
| 365 |
+
"utils/slow_documentation_tests.txt", models, lambda line, model: "/" + model + "/" in line
|
| 366 |
+
)
|
| 367 |
+
remove_model_references_from_file("utils/not_doctested.txt", models, lambda line, model: "/" + model + "/" in line)
|
| 368 |
+
|
| 369 |
+
# Add models to DEPRECATED_MODELS in the configuration_auto.py
|
| 370 |
+
print("Adding models to DEPRECATED_MODELS in configuration_auto.py")
|
| 371 |
+
add_models_to_deprecated_models_in_config_auto(models)
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
if __name__ == "__main__":
|
| 375 |
+
parser = argparse.ArgumentParser()
|
| 376 |
+
parser.add_argument("--models", nargs="+", help="List of models to deprecate")
|
| 377 |
+
args = parser.parse_args()
|
| 378 |
+
deprecate_models(args.models)
|
tasks/tasksmith-441eeab80047/environment/source/utils/download_glue_data.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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RPC.
|
| 5 |
+
You can either use the version hosted by the SentEval team, which is already tokenized,
|
| 6 |
+
or you can download the original data from (https://download.microsoft.com/download/D/4/6/D46FF87A-F6B9-4252-AA8B-3604ED519838/MSRParaphraseCorpus.msi) and extract the data from it manually.
|
| 7 |
+
For Windows users, you can run the .msi file. For Mac and Linux users, consider an external library such as 'cabextract' (see below for an example).
|
| 8 |
+
You should then rename and place specific files in a folder (see below for an example).
|
| 9 |
+
|
| 10 |
+
mkdir MRPC
|
| 11 |
+
cabextract MSRParaphraseCorpus.msi -d MRPC
|
| 12 |
+
cat MRPC/_2DEC3DBE877E4DB192D17C0256E90F1D | tr -d $'\r' > MRPC/msr_paraphrase_train.txt
|
| 13 |
+
cat MRPC/_D7B391F9EAFF4B1B8BCE8F21B20B1B61 | tr -d $'\r' > MRPC/msr_paraphrase_test.txt
|
| 14 |
+
rm MRPC/_*
|
| 15 |
+
rm MSRParaphraseCorpus.msi
|
| 16 |
+
|
| 17 |
+
1/30/19: It looks like SentEval is no longer hosting their extracted and tokenized MRPC data, so you'll need to download the data from the original source for now.
|
| 18 |
+
2/11/19: It looks like SentEval actually *is* hosting the extracted data. Hooray!
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
import argparse
|
| 22 |
+
import os
|
| 23 |
+
import sys
|
| 24 |
+
import urllib.request
|
| 25 |
+
import zipfile
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
TASKS = ["CoLA", "SST", "MRPC", "QQP", "STS", "MNLI", "SNLI", "QNLI", "RTE", "WNLI", "diagnostic"]
|
| 29 |
+
TASK2PATH = {
|
| 30 |
+
"CoLA": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FCoLA.zip?alt=media&token=46d5e637-3411-4188-bc44-5809b5bfb5f4",
|
| 31 |
+
"SST": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FSST-2.zip?alt=media&token=aabc5f6b-e466-44a2-b9b4-cf6337f84ac8",
|
| 32 |
+
"MRPC": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2Fmrpc_dev_ids.tsv?alt=media&token=ec5c0836-31d5-48f4-b431-7480817f1adc",
|
| 33 |
+
"QQP": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FQQP.zip?alt=media&token=700c6acf-160d-4d89-81d1-de4191d02cb5",
|
| 34 |
+
"STS": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FSTS-B.zip?alt=media&token=bddb94a7-8706-4e0d-a694-1109e12273b5",
|
| 35 |
+
"MNLI": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FMNLI.zip?alt=media&token=50329ea1-e339-40e2-809c-10c40afff3ce",
|
| 36 |
+
"SNLI": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FSNLI.zip?alt=media&token=4afcfbb2-ff0c-4b2d-a09a-dbf07926f4df",
|
| 37 |
+
"QNLI": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FQNLIv2.zip?alt=media&token=6fdcf570-0fc5-4631-8456-9505272d1601",
|
| 38 |
+
"RTE": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FRTE.zip?alt=media&token=5efa7e85-a0bb-4f19-8ea2-9e1840f077fb",
|
| 39 |
+
"WNLI": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FWNLI.zip?alt=media&token=068ad0a0-ded7-4bd7-99a5-5e00222e0faf",
|
| 40 |
+
"diagnostic": "https://storage.googleapis.com/mtl-sentence-representations.appspot.com/tsvsWithoutLabels%2FAX.tsv?GoogleAccessId=firebase-adminsdk-0khhl@mtl-sentence-representations.iam.gserviceaccount.com&Expires=2498860800&Signature=DuQ2CSPt2Yfre0C%2BiISrVYrIFaZH1Lc7hBVZDD4ZyR7fZYOMNOUGpi8QxBmTNOrNPjR3z1cggo7WXFfrgECP6FBJSsURv8Ybrue8Ypt%2FTPxbuJ0Xc2FhDi%2BarnecCBFO77RSbfuz%2Bs95hRrYhTnByqu3U%2FYZPaj3tZt5QdfpH2IUROY8LiBXoXS46LE%2FgOQc%2FKN%2BA9SoscRDYsnxHfG0IjXGwHN%2Bf88q6hOmAxeNPx6moDulUF6XMUAaXCSFU%2BnRO2RDL9CapWxj%2BDl7syNyHhB7987hZ80B%2FwFkQ3MEs8auvt5XW1%2Bd4aCU7ytgM69r8JDCwibfhZxpaa4gd50QXQ%3D%3D",
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
MRPC_TRAIN = "https://dl.fbaipublicfiles.com/senteval/senteval_data/msr_paraphrase_train.txt"
|
| 44 |
+
MRPC_TEST = "https://dl.fbaipublicfiles.com/senteval/senteval_data/msr_paraphrase_test.txt"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def download_and_extract(task, data_dir):
|
| 48 |
+
print(f"Downloading and extracting {task}...")
|
| 49 |
+
data_file = f"{task}.zip"
|
| 50 |
+
urllib.request.urlretrieve(TASK2PATH[task], data_file)
|
| 51 |
+
with zipfile.ZipFile(data_file) as zip_ref:
|
| 52 |
+
zip_ref.extractall(data_dir)
|
| 53 |
+
os.remove(data_file)
|
| 54 |
+
print("\tCompleted!")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def format_mrpc(data_dir, path_to_data):
|
| 58 |
+
print("Processing MRPC...")
|
| 59 |
+
mrpc_dir = os.path.join(data_dir, "MRPC")
|
| 60 |
+
if not os.path.isdir(mrpc_dir):
|
| 61 |
+
os.mkdir(mrpc_dir)
|
| 62 |
+
if path_to_data:
|
| 63 |
+
mrpc_train_file = os.path.join(path_to_data, "msr_paraphrase_train.txt")
|
| 64 |
+
mrpc_test_file = os.path.join(path_to_data, "msr_paraphrase_test.txt")
|
| 65 |
+
else:
|
| 66 |
+
print("Local MRPC data not specified, downloading data from %s" % MRPC_TRAIN)
|
| 67 |
+
mrpc_train_file = os.path.join(mrpc_dir, "msr_paraphrase_train.txt")
|
| 68 |
+
mrpc_test_file = os.path.join(mrpc_dir, "msr_paraphrase_test.txt")
|
| 69 |
+
urllib.request.urlretrieve(MRPC_TRAIN, mrpc_train_file)
|
| 70 |
+
urllib.request.urlretrieve(MRPC_TEST, mrpc_test_file)
|
| 71 |
+
if not os.path.isfile(mrpc_train_file):
|
| 72 |
+
raise ValueError(f"Train data not found at {mrpc_train_file}")
|
| 73 |
+
if not os.path.isfile(mrpc_test_file):
|
| 74 |
+
raise ValueError(f"Test data not found at {mrpc_test_file}")
|
| 75 |
+
urllib.request.urlretrieve(TASK2PATH["MRPC"], os.path.join(mrpc_dir, "dev_ids.tsv"))
|
| 76 |
+
|
| 77 |
+
dev_ids = []
|
| 78 |
+
with open(os.path.join(mrpc_dir, "dev_ids.tsv"), encoding="utf8") as ids_fh:
|
| 79 |
+
for row in ids_fh:
|
| 80 |
+
dev_ids.append(row.strip().split("\t"))
|
| 81 |
+
|
| 82 |
+
with open(mrpc_train_file, encoding="utf8") as data_fh, open(
|
| 83 |
+
os.path.join(mrpc_dir, "train.tsv"), "w", encoding="utf8"
|
| 84 |
+
) as train_fh, open(os.path.join(mrpc_dir, "dev.tsv"), "w", encoding="utf8") as dev_fh:
|
| 85 |
+
header = data_fh.readline()
|
| 86 |
+
train_fh.write(header)
|
| 87 |
+
dev_fh.write(header)
|
| 88 |
+
for row in data_fh:
|
| 89 |
+
label, id1, id2, s1, s2 = row.strip().split("\t")
|
| 90 |
+
if [id1, id2] in dev_ids:
|
| 91 |
+
dev_fh.write("%s\t%s\t%s\t%s\t%s\n" % (label, id1, id2, s1, s2))
|
| 92 |
+
else:
|
| 93 |
+
train_fh.write("%s\t%s\t%s\t%s\t%s\n" % (label, id1, id2, s1, s2))
|
| 94 |
+
|
| 95 |
+
with open(mrpc_test_file, encoding="utf8") as data_fh, open(
|
| 96 |
+
os.path.join(mrpc_dir, "test.tsv"), "w", encoding="utf8"
|
| 97 |
+
) as test_fh:
|
| 98 |
+
header = data_fh.readline()
|
| 99 |
+
test_fh.write("index\t#1 ID\t#2 ID\t#1 String\t#2 String\n")
|
| 100 |
+
for idx, row in enumerate(data_fh):
|
| 101 |
+
label, id1, id2, s1, s2 = row.strip().split("\t")
|
| 102 |
+
test_fh.write("%d\t%s\t%s\t%s\t%s\n" % (idx, id1, id2, s1, s2))
|
| 103 |
+
print("\tCompleted!")
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def download_diagnostic(data_dir):
|
| 107 |
+
print("Downloading and extracting diagnostic...")
|
| 108 |
+
if not os.path.isdir(os.path.join(data_dir, "diagnostic")):
|
| 109 |
+
os.mkdir(os.path.join(data_dir, "diagnostic"))
|
| 110 |
+
data_file = os.path.join(data_dir, "diagnostic", "diagnostic.tsv")
|
| 111 |
+
urllib.request.urlretrieve(TASK2PATH["diagnostic"], data_file)
|
| 112 |
+
print("\tCompleted!")
|
| 113 |
+
return
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def get_tasks(task_names):
|
| 117 |
+
task_names = task_names.split(",")
|
| 118 |
+
if "all" in task_names:
|
| 119 |
+
tasks = TASKS
|
| 120 |
+
else:
|
| 121 |
+
tasks = []
|
| 122 |
+
for task_name in task_names:
|
| 123 |
+
if task_name not in TASKS:
|
| 124 |
+
raise ValueError(f"Task {task_name} not found!")
|
| 125 |
+
tasks.append(task_name)
|
| 126 |
+
return tasks
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def main(arguments):
|
| 130 |
+
parser = argparse.ArgumentParser()
|
| 131 |
+
parser.add_argument("--data_dir", help="directory to save data to", type=str, default="glue_data")
|
| 132 |
+
parser.add_argument(
|
| 133 |
+
"--tasks", help="tasks to download data for as a comma separated string", type=str, default="all"
|
| 134 |
+
)
|
| 135 |
+
parser.add_argument(
|
| 136 |
+
"--path_to_mrpc",
|
| 137 |
+
help="path to directory containing extracted MRPC data, msr_paraphrase_train.txt and msr_paraphrase_text.txt",
|
| 138 |
+
type=str,
|
| 139 |
+
default="",
|
| 140 |
+
)
|
| 141 |
+
args = parser.parse_args(arguments)
|
| 142 |
+
|
| 143 |
+
if not os.path.isdir(args.data_dir):
|
| 144 |
+
os.mkdir(args.data_dir)
|
| 145 |
+
tasks = get_tasks(args.tasks)
|
| 146 |
+
|
| 147 |
+
for task in tasks:
|
| 148 |
+
if task == "MRPC":
|
| 149 |
+
format_mrpc(args.data_dir, args.path_to_mrpc)
|
| 150 |
+
elif task == "diagnostic":
|
| 151 |
+
download_diagnostic(args.data_dir)
|
| 152 |
+
else:
|
| 153 |
+
download_and_extract(task, args.data_dir)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
if __name__ == "__main__":
|
| 157 |
+
sys.exit(main(sys.argv[1:]))
|
tasks/tasksmith-441eeab80047/environment/source/utils/extract_warnings.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
import zipfile
|
| 6 |
+
|
| 7 |
+
from get_ci_error_statistics import download_artifact, get_artifacts_links
|
| 8 |
+
|
| 9 |
+
from transformers import logging
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
logger = logging.get_logger(__name__)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def extract_warnings_from_single_artifact(artifact_path, targets):
|
| 16 |
+
"""Extract warnings from a downloaded artifact (in .zip format)"""
|
| 17 |
+
selected_warnings = set()
|
| 18 |
+
buffer = []
|
| 19 |
+
|
| 20 |
+
def parse_line(fp):
|
| 21 |
+
for line in fp:
|
| 22 |
+
if isinstance(line, bytes):
|
| 23 |
+
line = line.decode("UTF-8")
|
| 24 |
+
if "warnings summary (final)" in line:
|
| 25 |
+
continue
|
| 26 |
+
# This means we are outside the body of a warning
|
| 27 |
+
elif not line.startswith(" "):
|
| 28 |
+
# process a single warning and move it to `selected_warnings`.
|
| 29 |
+
if len(buffer) > 0:
|
| 30 |
+
warning = "\n".join(buffer)
|
| 31 |
+
# Only keep the warnings specified in `targets`
|
| 32 |
+
if any(f": {x}: " in warning for x in targets):
|
| 33 |
+
selected_warnings.add(warning)
|
| 34 |
+
buffer.clear()
|
| 35 |
+
continue
|
| 36 |
+
else:
|
| 37 |
+
line = line.strip()
|
| 38 |
+
buffer.append(line)
|
| 39 |
+
|
| 40 |
+
if from_gh:
|
| 41 |
+
for filename in os.listdir(artifact_path):
|
| 42 |
+
file_path = os.path.join(artifact_path, filename)
|
| 43 |
+
if not os.path.isdir(file_path):
|
| 44 |
+
# read the file
|
| 45 |
+
if filename != "warnings.txt":
|
| 46 |
+
continue
|
| 47 |
+
with open(file_path) as fp:
|
| 48 |
+
parse_line(fp)
|
| 49 |
+
else:
|
| 50 |
+
try:
|
| 51 |
+
with zipfile.ZipFile(artifact_path) as z:
|
| 52 |
+
for filename in z.namelist():
|
| 53 |
+
if not os.path.isdir(filename):
|
| 54 |
+
# read the file
|
| 55 |
+
if filename != "warnings.txt":
|
| 56 |
+
continue
|
| 57 |
+
with z.open(filename) as fp:
|
| 58 |
+
parse_line(fp)
|
| 59 |
+
except Exception:
|
| 60 |
+
logger.warning(
|
| 61 |
+
f"{artifact_path} is either an invalid zip file or something else wrong. This file is skipped."
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
return selected_warnings
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def extract_warnings(artifact_dir, targets):
|
| 68 |
+
"""Extract warnings from all artifact files"""
|
| 69 |
+
|
| 70 |
+
selected_warnings = set()
|
| 71 |
+
|
| 72 |
+
paths = [os.path.join(artifact_dir, p) for p in os.listdir(artifact_dir) if (p.endswith(".zip") or from_gh)]
|
| 73 |
+
for p in paths:
|
| 74 |
+
selected_warnings.update(extract_warnings_from_single_artifact(p, targets))
|
| 75 |
+
|
| 76 |
+
return selected_warnings
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
if __name__ == "__main__":
|
| 80 |
+
|
| 81 |
+
def list_str(values):
|
| 82 |
+
return values.split(",")
|
| 83 |
+
|
| 84 |
+
parser = argparse.ArgumentParser()
|
| 85 |
+
# Required parameters
|
| 86 |
+
parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.")
|
| 87 |
+
parser.add_argument(
|
| 88 |
+
"--output_dir",
|
| 89 |
+
type=str,
|
| 90 |
+
required=True,
|
| 91 |
+
help="Where to store the downloaded artifacts and other result files.",
|
| 92 |
+
)
|
| 93 |
+
parser.add_argument("--token", default=None, type=str, help="A token that has actions:read permission.")
|
| 94 |
+
# optional parameters
|
| 95 |
+
parser.add_argument(
|
| 96 |
+
"--targets",
|
| 97 |
+
default="DeprecationWarning,UserWarning,FutureWarning",
|
| 98 |
+
type=list_str,
|
| 99 |
+
help="Comma-separated list of target warning(s) which we want to extract.",
|
| 100 |
+
)
|
| 101 |
+
parser.add_argument(
|
| 102 |
+
"--from_gh",
|
| 103 |
+
action="store_true",
|
| 104 |
+
help="If running from a GitHub action workflow and collecting warnings from its artifacts.",
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
args = parser.parse_args()
|
| 108 |
+
|
| 109 |
+
from_gh = args.from_gh
|
| 110 |
+
if from_gh:
|
| 111 |
+
# The artifacts have to be downloaded using `actions/download-artifact@v4`
|
| 112 |
+
pass
|
| 113 |
+
else:
|
| 114 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 115 |
+
|
| 116 |
+
# get download links
|
| 117 |
+
artifacts = get_artifacts_links(args.workflow_run_id, token=args.token)
|
| 118 |
+
with open(os.path.join(args.output_dir, "artifacts.json"), "w", encoding="UTF-8") as fp:
|
| 119 |
+
json.dump(artifacts, fp, ensure_ascii=False, indent=4)
|
| 120 |
+
|
| 121 |
+
# download artifacts
|
| 122 |
+
for idx, (name, url) in enumerate(artifacts.items()):
|
| 123 |
+
print(name)
|
| 124 |
+
print(url)
|
| 125 |
+
print("=" * 80)
|
| 126 |
+
download_artifact(name, url, args.output_dir, args.token)
|
| 127 |
+
# Be gentle to GitHub
|
| 128 |
+
time.sleep(1)
|
| 129 |
+
|
| 130 |
+
# extract warnings from artifacts
|
| 131 |
+
selected_warnings = extract_warnings(args.output_dir, args.targets)
|
| 132 |
+
selected_warnings = sorted(selected_warnings)
|
| 133 |
+
with open(os.path.join(args.output_dir, "selected_warnings.json"), "w", encoding="UTF-8") as fp:
|
| 134 |
+
json.dump(selected_warnings, fp, ensure_ascii=False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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
import math
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
import traceback
|
| 7 |
+
import zipfile
|
| 8 |
+
from collections import Counter
|
| 9 |
+
|
| 10 |
+
import requests
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def get_jobs(workflow_run_id, token=None):
|
| 14 |
+
"""Extract jobs in a GitHub Actions workflow run"""
|
| 15 |
+
|
| 16 |
+
headers = None
|
| 17 |
+
if token is not None:
|
| 18 |
+
headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"}
|
| 19 |
+
|
| 20 |
+
url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100"
|
| 21 |
+
result = requests.get(url, headers=headers).json()
|
| 22 |
+
jobs = []
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
jobs.extend(result["jobs"])
|
| 26 |
+
pages_to_iterate_over = math.ceil((result["total_count"] - 100) / 100)
|
| 27 |
+
|
| 28 |
+
for i in range(pages_to_iterate_over):
|
| 29 |
+
result = requests.get(url + f"&page={i + 2}", headers=headers).json()
|
| 30 |
+
jobs.extend(result["jobs"])
|
| 31 |
+
|
| 32 |
+
return jobs
|
| 33 |
+
except Exception:
|
| 34 |
+
print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}")
|
| 35 |
+
|
| 36 |
+
return []
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def get_job_links(workflow_run_id, token=None):
|
| 40 |
+
"""Extract job names and their job links in a GitHub Actions workflow run"""
|
| 41 |
+
|
| 42 |
+
headers = None
|
| 43 |
+
if token is not None:
|
| 44 |
+
headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"}
|
| 45 |
+
|
| 46 |
+
url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100"
|
| 47 |
+
result = requests.get(url, headers=headers).json()
|
| 48 |
+
job_links = {}
|
| 49 |
+
|
| 50 |
+
try:
|
| 51 |
+
job_links.update({job["name"]: job["html_url"] for job in result["jobs"]})
|
| 52 |
+
pages_to_iterate_over = math.ceil((result["total_count"] - 100) / 100)
|
| 53 |
+
|
| 54 |
+
for i in range(pages_to_iterate_over):
|
| 55 |
+
result = requests.get(url + f"&page={i + 2}", headers=headers).json()
|
| 56 |
+
job_links.update({job["name"]: job["html_url"] for job in result["jobs"]})
|
| 57 |
+
|
| 58 |
+
return job_links
|
| 59 |
+
except Exception:
|
| 60 |
+
print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}")
|
| 61 |
+
|
| 62 |
+
return {}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def get_artifacts_links(worflow_run_id, token=None):
|
| 66 |
+
"""Get all artifact links from a workflow run"""
|
| 67 |
+
|
| 68 |
+
headers = None
|
| 69 |
+
if token is not None:
|
| 70 |
+
headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"}
|
| 71 |
+
|
| 72 |
+
url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100"
|
| 73 |
+
result = requests.get(url, headers=headers).json()
|
| 74 |
+
artifacts = {}
|
| 75 |
+
|
| 76 |
+
try:
|
| 77 |
+
artifacts.update({artifact["name"]: artifact["archive_download_url"] for artifact in result["artifacts"]})
|
| 78 |
+
pages_to_iterate_over = math.ceil((result["total_count"] - 100) / 100)
|
| 79 |
+
|
| 80 |
+
for i in range(pages_to_iterate_over):
|
| 81 |
+
result = requests.get(url + f"&page={i + 2}", headers=headers).json()
|
| 82 |
+
artifacts.update({artifact["name"]: artifact["archive_download_url"] for artifact in result["artifacts"]})
|
| 83 |
+
|
| 84 |
+
return artifacts
|
| 85 |
+
except Exception:
|
| 86 |
+
print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}")
|
| 87 |
+
|
| 88 |
+
return {}
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def download_artifact(artifact_name, artifact_url, output_dir, token):
|
| 92 |
+
"""Download a GitHub Action artifact from a URL.
|
| 93 |
+
|
| 94 |
+
The URL is of the form `https://api.github.com/repos/huggingface/transformers/actions/artifacts/{ARTIFACT_ID}/zip`,
|
| 95 |
+
but it can't be used to download directly. We need to get a redirect URL first.
|
| 96 |
+
See https://docs.github.com/en/rest/actions/artifacts#download-an-artifact
|
| 97 |
+
"""
|
| 98 |
+
headers = None
|
| 99 |
+
if token is not None:
|
| 100 |
+
headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"}
|
| 101 |
+
|
| 102 |
+
result = requests.get(artifact_url, headers=headers, allow_redirects=False)
|
| 103 |
+
download_url = result.headers["Location"]
|
| 104 |
+
response = requests.get(download_url, allow_redirects=True)
|
| 105 |
+
file_path = os.path.join(output_dir, f"{artifact_name}.zip")
|
| 106 |
+
with open(file_path, "wb") as fp:
|
| 107 |
+
fp.write(response.content)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def get_errors_from_single_artifact(artifact_zip_path, job_links=None):
|
| 111 |
+
"""Extract errors from a downloaded artifact (in .zip format)"""
|
| 112 |
+
errors = []
|
| 113 |
+
failed_tests = []
|
| 114 |
+
job_name = None
|
| 115 |
+
|
| 116 |
+
with zipfile.ZipFile(artifact_zip_path) as z:
|
| 117 |
+
for filename in z.namelist():
|
| 118 |
+
if not os.path.isdir(filename):
|
| 119 |
+
# read the file
|
| 120 |
+
if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]:
|
| 121 |
+
with z.open(filename) as f:
|
| 122 |
+
for line in f:
|
| 123 |
+
line = line.decode("UTF-8").strip()
|
| 124 |
+
if filename == "failures_line.txt":
|
| 125 |
+
try:
|
| 126 |
+
# `error_line` is the place where `error` occurs
|
| 127 |
+
error_line = line[: line.index(": ")]
|
| 128 |
+
error = line[line.index(": ") + len(": ") :]
|
| 129 |
+
errors.append([error_line, error])
|
| 130 |
+
except Exception:
|
| 131 |
+
# skip un-related lines
|
| 132 |
+
pass
|
| 133 |
+
elif filename == "summary_short.txt" and line.startswith("FAILED "):
|
| 134 |
+
# `test` is the test method that failed
|
| 135 |
+
test = line[len("FAILED ") :]
|
| 136 |
+
failed_tests.append(test)
|
| 137 |
+
elif filename == "job_name.txt":
|
| 138 |
+
job_name = line
|
| 139 |
+
|
| 140 |
+
if len(errors) != len(failed_tests):
|
| 141 |
+
raise ValueError(
|
| 142 |
+
f"`errors` and `failed_tests` should have the same number of elements. Got {len(errors)} for `errors` "
|
| 143 |
+
f"and {len(failed_tests)} for `failed_tests` instead. The test reports in {artifact_zip_path} have some"
|
| 144 |
+
" problem."
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
job_link = None
|
| 148 |
+
if job_name and job_links:
|
| 149 |
+
job_link = job_links.get(job_name, None)
|
| 150 |
+
|
| 151 |
+
# A list with elements of the form (line of error, error, failed test)
|
| 152 |
+
result = [x + [y] + [job_link] for x, y in zip(errors, failed_tests)]
|
| 153 |
+
|
| 154 |
+
return result
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def get_all_errors(artifact_dir, job_links=None):
|
| 158 |
+
"""Extract errors from all artifact files"""
|
| 159 |
+
|
| 160 |
+
errors = []
|
| 161 |
+
|
| 162 |
+
paths = [os.path.join(artifact_dir, p) for p in os.listdir(artifact_dir) if p.endswith(".zip")]
|
| 163 |
+
for p in paths:
|
| 164 |
+
errors.extend(get_errors_from_single_artifact(p, job_links=job_links))
|
| 165 |
+
|
| 166 |
+
return errors
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def reduce_by_error(logs, error_filter=None):
|
| 170 |
+
"""count each error"""
|
| 171 |
+
|
| 172 |
+
counter = Counter()
|
| 173 |
+
counter.update([x[1] for x in logs])
|
| 174 |
+
counts = counter.most_common()
|
| 175 |
+
r = {}
|
| 176 |
+
for error, count in counts:
|
| 177 |
+
if error_filter is None or error not in error_filter:
|
| 178 |
+
r[error] = {"count": count, "failed_tests": [(x[2], x[0]) for x in logs if x[1] == error]}
|
| 179 |
+
|
| 180 |
+
r = dict(sorted(r.items(), key=lambda item: item[1]["count"], reverse=True))
|
| 181 |
+
return r
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def get_model(test):
|
| 185 |
+
"""Get the model name from a test method"""
|
| 186 |
+
test = test.split("::")[0]
|
| 187 |
+
if test.startswith("tests/models/"):
|
| 188 |
+
test = test.split("/")[2]
|
| 189 |
+
else:
|
| 190 |
+
test = None
|
| 191 |
+
|
| 192 |
+
return test
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def reduce_by_model(logs, error_filter=None):
|
| 196 |
+
"""count each error per model"""
|
| 197 |
+
|
| 198 |
+
logs = [(x[0], x[1], get_model(x[2])) for x in logs]
|
| 199 |
+
logs = [x for x in logs if x[2] is not None]
|
| 200 |
+
tests = {x[2] for x in logs}
|
| 201 |
+
|
| 202 |
+
r = {}
|
| 203 |
+
for test in tests:
|
| 204 |
+
counter = Counter()
|
| 205 |
+
# count by errors in `test`
|
| 206 |
+
counter.update([x[1] for x in logs if x[2] == test])
|
| 207 |
+
counts = counter.most_common()
|
| 208 |
+
error_counts = {error: count for error, count in counts if (error_filter is None or error not in error_filter)}
|
| 209 |
+
n_errors = sum(error_counts.values())
|
| 210 |
+
if n_errors > 0:
|
| 211 |
+
r[test] = {"count": n_errors, "errors": error_counts}
|
| 212 |
+
|
| 213 |
+
r = dict(sorted(r.items(), key=lambda item: item[1]["count"], reverse=True))
|
| 214 |
+
return r
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def make_github_table(reduced_by_error):
|
| 218 |
+
header = "| no. | error | status |"
|
| 219 |
+
sep = "|-:|:-|:-|"
|
| 220 |
+
lines = [header, sep]
|
| 221 |
+
for error in reduced_by_error:
|
| 222 |
+
count = reduced_by_error[error]["count"]
|
| 223 |
+
line = f"| {count} | {error[:100]} | |"
|
| 224 |
+
lines.append(line)
|
| 225 |
+
|
| 226 |
+
return "\n".join(lines)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def make_github_table_per_model(reduced_by_model):
|
| 230 |
+
header = "| model | no. of errors | major error | count |"
|
| 231 |
+
sep = "|-:|-:|-:|-:|"
|
| 232 |
+
lines = [header, sep]
|
| 233 |
+
for model in reduced_by_model:
|
| 234 |
+
count = reduced_by_model[model]["count"]
|
| 235 |
+
error, _count = list(reduced_by_model[model]["errors"].items())[0]
|
| 236 |
+
line = f"| {model} | {count} | {error[:60]} | {_count} |"
|
| 237 |
+
lines.append(line)
|
| 238 |
+
|
| 239 |
+
return "\n".join(lines)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
if __name__ == "__main__":
|
| 243 |
+
parser = argparse.ArgumentParser()
|
| 244 |
+
# Required parameters
|
| 245 |
+
parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.")
|
| 246 |
+
parser.add_argument(
|
| 247 |
+
"--output_dir",
|
| 248 |
+
type=str,
|
| 249 |
+
required=True,
|
| 250 |
+
help="Where to store the downloaded artifacts and other result files.",
|
| 251 |
+
)
|
| 252 |
+
parser.add_argument("--token", default=None, type=str, help="A token that has actions:read permission.")
|
| 253 |
+
args = parser.parse_args()
|
| 254 |
+
|
| 255 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 256 |
+
|
| 257 |
+
_job_links = get_job_links(args.workflow_run_id, token=args.token)
|
| 258 |
+
job_links = {}
|
| 259 |
+
# To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee.
|
| 260 |
+
# For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`.
|
| 261 |
+
if _job_links:
|
| 262 |
+
for k, v in _job_links.items():
|
| 263 |
+
# This is how GitHub actions combine job names.
|
| 264 |
+
if " / " in k:
|
| 265 |
+
index = k.find(" / ")
|
| 266 |
+
k = k[index + len(" / ") :]
|
| 267 |
+
job_links[k] = v
|
| 268 |
+
with open(os.path.join(args.output_dir, "job_links.json"), "w", encoding="UTF-8") as fp:
|
| 269 |
+
json.dump(job_links, fp, ensure_ascii=False, indent=4)
|
| 270 |
+
|
| 271 |
+
artifacts = get_artifacts_links(args.workflow_run_id, token=args.token)
|
| 272 |
+
with open(os.path.join(args.output_dir, "artifacts.json"), "w", encoding="UTF-8") as fp:
|
| 273 |
+
json.dump(artifacts, fp, ensure_ascii=False, indent=4)
|
| 274 |
+
|
| 275 |
+
for idx, (name, url) in enumerate(artifacts.items()):
|
| 276 |
+
download_artifact(name, url, args.output_dir, args.token)
|
| 277 |
+
# Be gentle to GitHub
|
| 278 |
+
time.sleep(1)
|
| 279 |
+
|
| 280 |
+
errors = get_all_errors(args.output_dir, job_links=job_links)
|
| 281 |
+
|
| 282 |
+
# `e[1]` is the error
|
| 283 |
+
counter = Counter()
|
| 284 |
+
counter.update([e[1] for e in errors])
|
| 285 |
+
|
| 286 |
+
# print the top 30 most common test errors
|
| 287 |
+
most_common = counter.most_common(30)
|
| 288 |
+
for item in most_common:
|
| 289 |
+
print(item)
|
| 290 |
+
|
| 291 |
+
with open(os.path.join(args.output_dir, "errors.json"), "w", encoding="UTF-8") as fp:
|
| 292 |
+
json.dump(errors, fp, ensure_ascii=False, indent=4)
|
| 293 |
+
|
| 294 |
+
reduced_by_error = reduce_by_error(errors)
|
| 295 |
+
reduced_by_model = reduce_by_model(errors)
|
| 296 |
+
|
| 297 |
+
s1 = make_github_table(reduced_by_error)
|
| 298 |
+
s2 = make_github_table_per_model(reduced_by_model)
|
| 299 |
+
|
| 300 |
+
with open(os.path.join(args.output_dir, "reduced_by_error.txt"), "w", encoding="UTF-8") as fp:
|
| 301 |
+
fp.write(s1)
|
| 302 |
+
with open(os.path.join(args.output_dir, "reduced_by_model.txt"), "w", encoding="UTF-8") as fp:
|
| 303 |
+
fp.write(s2)
|
tasks/tasksmith-441eeab80047/environment/source/utils/get_github_job_time.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import math
|
| 3 |
+
import traceback
|
| 4 |
+
|
| 5 |
+
import dateutil.parser as date_parser
|
| 6 |
+
import requests
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def extract_time_from_single_job(job):
|
| 10 |
+
"""Extract time info from a single job in a GitHub Actions workflow run"""
|
| 11 |
+
|
| 12 |
+
job_info = {}
|
| 13 |
+
|
| 14 |
+
start = job["started_at"]
|
| 15 |
+
end = job["completed_at"]
|
| 16 |
+
|
| 17 |
+
start_datetime = date_parser.parse(start)
|
| 18 |
+
end_datetime = date_parser.parse(end)
|
| 19 |
+
|
| 20 |
+
duration_in_min = round((end_datetime - start_datetime).total_seconds() / 60.0)
|
| 21 |
+
|
| 22 |
+
job_info["started_at"] = start
|
| 23 |
+
job_info["completed_at"] = end
|
| 24 |
+
job_info["duration"] = duration_in_min
|
| 25 |
+
|
| 26 |
+
return job_info
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def get_job_time(workflow_run_id, token=None):
|
| 30 |
+
"""Extract time info for all jobs in a GitHub Actions workflow run"""
|
| 31 |
+
|
| 32 |
+
headers = None
|
| 33 |
+
if token is not None:
|
| 34 |
+
headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"}
|
| 35 |
+
|
| 36 |
+
url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100"
|
| 37 |
+
result = requests.get(url, headers=headers).json()
|
| 38 |
+
job_time = {}
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
job_time.update({job["name"]: extract_time_from_single_job(job) for job in result["jobs"]})
|
| 42 |
+
pages_to_iterate_over = math.ceil((result["total_count"] - 100) / 100)
|
| 43 |
+
|
| 44 |
+
for i in range(pages_to_iterate_over):
|
| 45 |
+
result = requests.get(url + f"&page={i + 2}", headers=headers).json()
|
| 46 |
+
job_time.update({job["name"]: extract_time_from_single_job(job) for job in result["jobs"]})
|
| 47 |
+
|
| 48 |
+
return job_time
|
| 49 |
+
except Exception:
|
| 50 |
+
print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}")
|
| 51 |
+
|
| 52 |
+
return {}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
if __name__ == "__main__":
|
| 56 |
+
r"""
|
| 57 |
+
Example:
|
| 58 |
+
|
| 59 |
+
python get_github_job_time.py --workflow_run_id 2945609517
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
parser = argparse.ArgumentParser()
|
| 63 |
+
# Required parameters
|
| 64 |
+
parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.")
|
| 65 |
+
args = parser.parse_args()
|
| 66 |
+
|
| 67 |
+
job_time = get_job_time(args.workflow_run_id)
|
| 68 |
+
job_time = dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True))
|
| 69 |
+
|
| 70 |
+
for k, v in job_time.items():
|
| 71 |
+
print(f'{k}: {v["duration"]}')
|
tasks/tasksmith-441eeab80047/environment/source/utils/get_modified_files.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 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 |
+
# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.:
|
| 17 |
+
# python ./utils/get_modified_files.py utils src tests examples
|
| 18 |
+
#
|
| 19 |
+
# it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered
|
| 20 |
+
# since the output of this script is fed into Makefile commands it doesn't print a newline after the results
|
| 21 |
+
|
| 22 |
+
import re
|
| 23 |
+
import subprocess
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
fork_point_sha = subprocess.check_output("git merge-base main HEAD".split()).decode("utf-8")
|
| 28 |
+
modified_files = (
|
| 29 |
+
subprocess.check_output(f"git diff --diff-filter=d --name-only {fork_point_sha}".split()).decode("utf-8").split()
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
joined_dirs = "|".join(sys.argv[1:])
|
| 33 |
+
regex = re.compile(rf"^({joined_dirs}).*?\.py$")
|
| 34 |
+
|
| 35 |
+
relevant_modified_files = [x for x in modified_files if regex.match(x)]
|
| 36 |
+
print(" ".join(relevant_modified_files), end="")
|
tasks/tasksmith-441eeab80047/environment/source/utils/get_previous_daily_ci.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import zipfile
|
| 3 |
+
|
| 4 |
+
import requests
|
| 5 |
+
from get_ci_error_statistics import download_artifact, get_artifacts_links
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def get_daily_ci_runs(token, num_runs=7):
|
| 9 |
+
"""Get the workflow runs of the scheduled (daily) CI.
|
| 10 |
+
|
| 11 |
+
This only selects the runs triggered by the `schedule` event on the `main` branch.
|
| 12 |
+
"""
|
| 13 |
+
headers = None
|
| 14 |
+
if token is not None:
|
| 15 |
+
headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"}
|
| 16 |
+
|
| 17 |
+
# The id of a workflow (not of a workflow run).
|
| 18 |
+
# From a given workflow run (where we have workflow run id), we can get the workflow id by going to
|
| 19 |
+
# https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}
|
| 20 |
+
# and check the `workflow_id` key.
|
| 21 |
+
workflow_id = "90575235"
|
| 22 |
+
|
| 23 |
+
url = f"https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs"
|
| 24 |
+
# On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results
|
| 25 |
+
url += f"?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}"
|
| 26 |
+
|
| 27 |
+
result = requests.get(url, headers=headers).json()
|
| 28 |
+
|
| 29 |
+
return result["workflow_runs"]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def get_last_daily_ci_runs(token):
|
| 33 |
+
"""Get the last completed workflow run id of the scheduled (daily) CI."""
|
| 34 |
+
workflow_runs = get_daily_ci_runs(token)
|
| 35 |
+
workflow_run_id = None
|
| 36 |
+
for workflow_run in workflow_runs:
|
| 37 |
+
if workflow_run["status"] == "completed":
|
| 38 |
+
workflow_run_id = workflow_run["id"]
|
| 39 |
+
break
|
| 40 |
+
|
| 41 |
+
return workflow_run_id
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def get_last_daily_ci_run_commit(token):
|
| 45 |
+
"""Get the commit sha of the last completed scheduled daily CI workflow run."""
|
| 46 |
+
workflow_runs = get_daily_ci_runs(token)
|
| 47 |
+
head_sha = None
|
| 48 |
+
for workflow_run in workflow_runs:
|
| 49 |
+
if workflow_run["status"] == "completed":
|
| 50 |
+
head_sha = workflow_run["head_sha"]
|
| 51 |
+
break
|
| 52 |
+
|
| 53 |
+
return head_sha
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def get_last_daily_ci_artifacts(artifact_names, output_dir, token):
|
| 57 |
+
"""Get the artifacts of last completed workflow run id of the scheduled (daily) CI."""
|
| 58 |
+
workflow_run_id = get_last_daily_ci_runs(token)
|
| 59 |
+
if workflow_run_id is not None:
|
| 60 |
+
artifacts_links = get_artifacts_links(worflow_run_id=workflow_run_id, token=token)
|
| 61 |
+
for artifact_name in artifact_names:
|
| 62 |
+
if artifact_name in artifacts_links:
|
| 63 |
+
artifact_url = artifacts_links[artifact_name]
|
| 64 |
+
download_artifact(
|
| 65 |
+
artifact_name=artifact_name, artifact_url=artifact_url, output_dir=output_dir, token=token
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def get_last_daily_ci_reports(artifact_names, output_dir, token):
|
| 70 |
+
"""Get the artifacts' content of the last completed workflow run id of the scheduled (daily) CI."""
|
| 71 |
+
get_last_daily_ci_artifacts(artifact_names, output_dir, token)
|
| 72 |
+
|
| 73 |
+
results = {}
|
| 74 |
+
for artifact_name in artifact_names:
|
| 75 |
+
artifact_zip_path = os.path.join(output_dir, f"{artifact_name}.zip")
|
| 76 |
+
if os.path.isfile(artifact_zip_path):
|
| 77 |
+
results[artifact_name] = {}
|
| 78 |
+
with zipfile.ZipFile(artifact_zip_path) as z:
|
| 79 |
+
for filename in z.namelist():
|
| 80 |
+
if not os.path.isdir(filename):
|
| 81 |
+
# read the file
|
| 82 |
+
with z.open(filename) as f:
|
| 83 |
+
results[artifact_name][filename] = f.read().decode("UTF-8")
|
| 84 |
+
|
| 85 |
+
return results
|
tasks/tasksmith-441eeab80047/environment/source/utils/get_test_info.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 16 |
+
import importlib
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# This is required to make the module import works (when the python process is running from the root of the repo)
|
| 22 |
+
sys.path.append(".")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
r"""
|
| 26 |
+
The argument `test_file` in this file refers to a model test file. This should be a string of the from
|
| 27 |
+
`tests/models/*/test_modeling_*.py`.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def get_module_path(test_file):
|
| 32 |
+
"""Return the module path of a model test file."""
|
| 33 |
+
components = test_file.split(os.path.sep)
|
| 34 |
+
if components[0:2] != ["tests", "models"]:
|
| 35 |
+
raise ValueError(
|
| 36 |
+
"`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got "
|
| 37 |
+
f"{test_file} instead."
|
| 38 |
+
)
|
| 39 |
+
test_fn = components[-1]
|
| 40 |
+
if not test_fn.endswith("py"):
|
| 41 |
+
raise ValueError(f"`test_file` should be a python file. Got {test_fn} instead.")
|
| 42 |
+
if not test_fn.startswith("test_modeling_"):
|
| 43 |
+
raise ValueError(
|
| 44 |
+
f"`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead."
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
components = components[:-1] + [test_fn.replace(".py", "")]
|
| 48 |
+
test_module_path = ".".join(components)
|
| 49 |
+
|
| 50 |
+
return test_module_path
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def get_test_module(test_file):
|
| 54 |
+
"""Get the module of a model test file."""
|
| 55 |
+
test_module_path = get_module_path(test_file)
|
| 56 |
+
try:
|
| 57 |
+
test_module = importlib.import_module(test_module_path)
|
| 58 |
+
except AttributeError as exc:
|
| 59 |
+
# e.g. if you have a `tests` folder in `site-packages`, created by another package, when trying to import
|
| 60 |
+
# `tests.models...`
|
| 61 |
+
raise ValueError(
|
| 62 |
+
f"Could not import module {test_module_path}. Confirm that you don't have a package with the same root "
|
| 63 |
+
"name installed or in your environment's `site-packages`."
|
| 64 |
+
) from exc
|
| 65 |
+
|
| 66 |
+
return test_module
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def get_tester_classes(test_file):
|
| 70 |
+
"""Get all classes in a model test file whose names ends with `ModelTester`."""
|
| 71 |
+
tester_classes = []
|
| 72 |
+
test_module = get_test_module(test_file)
|
| 73 |
+
for attr in dir(test_module):
|
| 74 |
+
if attr.endswith("ModelTester"):
|
| 75 |
+
tester_classes.append(getattr(test_module, attr))
|
| 76 |
+
|
| 77 |
+
# sort with class names
|
| 78 |
+
return sorted(tester_classes, key=lambda x: x.__name__)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def get_test_classes(test_file):
|
| 82 |
+
"""Get all [test] classes in a model test file with attribute `all_model_classes` that are non-empty.
|
| 83 |
+
|
| 84 |
+
These are usually the (model) test classes containing the (non-slow) tests to run and are subclasses of one of the
|
| 85 |
+
classes `ModelTesterMixin`, `TFModelTesterMixin` or `FlaxModelTesterMixin`, as well as a subclass of
|
| 86 |
+
`unittest.TestCase`. Exceptions include `RagTestMixin` (and its subclasses).
|
| 87 |
+
"""
|
| 88 |
+
test_classes = []
|
| 89 |
+
test_module = get_test_module(test_file)
|
| 90 |
+
for attr in dir(test_module):
|
| 91 |
+
attr_value = getattr(test_module, attr)
|
| 92 |
+
# (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking
|
| 93 |
+
# `all_model_classes` is not empty (which also excludes other special classes).
|
| 94 |
+
model_classes = getattr(attr_value, "all_model_classes", [])
|
| 95 |
+
if len(model_classes) > 0:
|
| 96 |
+
test_classes.append(attr_value)
|
| 97 |
+
|
| 98 |
+
# sort with class names
|
| 99 |
+
return sorted(test_classes, key=lambda x: x.__name__)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def get_model_classes(test_file):
|
| 103 |
+
"""Get all model classes that appear in `all_model_classes` attributes in a model test file."""
|
| 104 |
+
test_classes = get_test_classes(test_file)
|
| 105 |
+
model_classes = set()
|
| 106 |
+
for test_class in test_classes:
|
| 107 |
+
model_classes.update(test_class.all_model_classes)
|
| 108 |
+
|
| 109 |
+
# sort with class names
|
| 110 |
+
return sorted(model_classes, key=lambda x: x.__name__)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def get_model_tester_from_test_class(test_class):
|
| 114 |
+
"""Get the model tester class of a model test class."""
|
| 115 |
+
test = test_class()
|
| 116 |
+
if hasattr(test, "setUp"):
|
| 117 |
+
test.setUp()
|
| 118 |
+
|
| 119 |
+
model_tester = None
|
| 120 |
+
if hasattr(test, "model_tester"):
|
| 121 |
+
# `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case.
|
| 122 |
+
if test.model_tester is not None:
|
| 123 |
+
model_tester = test.model_tester.__class__
|
| 124 |
+
|
| 125 |
+
return model_tester
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def get_test_classes_for_model(test_file, model_class):
|
| 129 |
+
"""Get all [test] classes in `test_file` that have `model_class` in their `all_model_classes`."""
|
| 130 |
+
test_classes = get_test_classes(test_file)
|
| 131 |
+
|
| 132 |
+
target_test_classes = []
|
| 133 |
+
for test_class in test_classes:
|
| 134 |
+
if model_class in test_class.all_model_classes:
|
| 135 |
+
target_test_classes.append(test_class)
|
| 136 |
+
|
| 137 |
+
# sort with class names
|
| 138 |
+
return sorted(target_test_classes, key=lambda x: x.__name__)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def get_tester_classes_for_model(test_file, model_class):
|
| 142 |
+
"""Get all model tester classes in `test_file` that are associated to `model_class`."""
|
| 143 |
+
test_classes = get_test_classes_for_model(test_file, model_class)
|
| 144 |
+
|
| 145 |
+
tester_classes = []
|
| 146 |
+
for test_class in test_classes:
|
| 147 |
+
tester_class = get_model_tester_from_test_class(test_class)
|
| 148 |
+
if tester_class is not None:
|
| 149 |
+
tester_classes.append(tester_class)
|
| 150 |
+
|
| 151 |
+
# sort with class names
|
| 152 |
+
return sorted(tester_classes, key=lambda x: x.__name__)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def get_test_to_tester_mapping(test_file):
|
| 156 |
+
"""Get a mapping from [test] classes to model tester classes in `test_file`.
|
| 157 |
+
|
| 158 |
+
This uses `get_test_classes` which may return classes that are NOT subclasses of `unittest.TestCase`.
|
| 159 |
+
"""
|
| 160 |
+
test_classes = get_test_classes(test_file)
|
| 161 |
+
test_tester_mapping = {test_class: get_model_tester_from_test_class(test_class) for test_class in test_classes}
|
| 162 |
+
return test_tester_mapping
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def get_model_to_test_mapping(test_file):
|
| 166 |
+
"""Get a mapping from model classes to test classes in `test_file`."""
|
| 167 |
+
model_classes = get_model_classes(test_file)
|
| 168 |
+
model_test_mapping = {
|
| 169 |
+
model_class: get_test_classes_for_model(test_file, model_class) for model_class in model_classes
|
| 170 |
+
}
|
| 171 |
+
return model_test_mapping
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def get_model_to_tester_mapping(test_file):
|
| 175 |
+
"""Get a mapping from model classes to model tester classes in `test_file`."""
|
| 176 |
+
model_classes = get_model_classes(test_file)
|
| 177 |
+
model_to_tester_mapping = {
|
| 178 |
+
model_class: get_tester_classes_for_model(test_file, model_class) for model_class in model_classes
|
| 179 |
+
}
|
| 180 |
+
return model_to_tester_mapping
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def to_json(o):
|
| 184 |
+
"""Make the information succinct and easy to read.
|
| 185 |
+
|
| 186 |
+
Avoid the full class representation like `<class 'transformers.models.bert.modeling_bert.BertForMaskedLM'>` when
|
| 187 |
+
displaying the results. Instead, we use class name (`BertForMaskedLM`) for the readability.
|
| 188 |
+
"""
|
| 189 |
+
if isinstance(o, str):
|
| 190 |
+
return o
|
| 191 |
+
elif isinstance(o, type):
|
| 192 |
+
return o.__name__
|
| 193 |
+
elif isinstance(o, (list, tuple)):
|
| 194 |
+
return [to_json(x) for x in o]
|
| 195 |
+
elif isinstance(o, dict):
|
| 196 |
+
return {to_json(k): to_json(v) for k, v in o.items()}
|
| 197 |
+
else:
|
| 198 |
+
return o
|
tasks/tasksmith-441eeab80047/environment/source/utils/important_models.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
models/llama
|
| 2 |
+
models/mistral
|
| 3 |
+
models/mixtral
|
| 4 |
+
models/gemma
|
tasks/tasksmith-441eeab80047/environment/source/utils/models_to_deprecate.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
Script to find a candidate list of models to deprecate based on the number of downloads and the date of the last commit.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import glob
|
| 20 |
+
import json
|
| 21 |
+
import os
|
| 22 |
+
from collections import defaultdict
|
| 23 |
+
from datetime import datetime, timezone
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
from git import Repo
|
| 27 |
+
from huggingface_hub import HfApi
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
api = HfApi()
|
| 31 |
+
|
| 32 |
+
PATH_TO_REPO = Path(__file__).parent.parent.resolve()
|
| 33 |
+
repo = Repo(PATH_TO_REPO)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class HubModelLister:
|
| 37 |
+
"""
|
| 38 |
+
Utility for getting models from the hub based on tags. Handles errors without crashing the script.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def __init__(self, tags):
|
| 42 |
+
self.tags = tags
|
| 43 |
+
self.model_list = api.list_models(tags=tags)
|
| 44 |
+
|
| 45 |
+
def __iter__(self):
|
| 46 |
+
try:
|
| 47 |
+
yield from self.model_list
|
| 48 |
+
except Exception as e:
|
| 49 |
+
print(f"Error: {e}")
|
| 50 |
+
return
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _extract_commit_hash(commits):
|
| 54 |
+
for commit in commits:
|
| 55 |
+
if commit.startswith("commit "):
|
| 56 |
+
return commit.split(" ")[1]
|
| 57 |
+
return ""
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def get_list_of_repo_model_paths(models_dir):
|
| 61 |
+
# Get list of all models in the library
|
| 62 |
+
models = glob.glob(os.path.join(models_dir, "*/modeling_*.py"))
|
| 63 |
+
|
| 64 |
+
# Remove flax and tf models
|
| 65 |
+
models = [model for model in models if "_flax_" not in model]
|
| 66 |
+
models = [model for model in models if "_tf_" not in model]
|
| 67 |
+
|
| 68 |
+
# Get list of all deprecated models in the library
|
| 69 |
+
deprecated_models = glob.glob(os.path.join(models_dir, "deprecated", "*"))
|
| 70 |
+
# For each deprecated model, remove the deprecated models from the list of all models as well as the symlink path
|
| 71 |
+
for deprecated_model in deprecated_models:
|
| 72 |
+
deprecated_model_name = "/" + deprecated_model.split("/")[-1] + "/"
|
| 73 |
+
models = [model for model in models if deprecated_model_name not in model]
|
| 74 |
+
# Remove deprecated models
|
| 75 |
+
models = [model for model in models if "/deprecated" not in model]
|
| 76 |
+
# Remove auto
|
| 77 |
+
models = [model for model in models if "/auto/" not in model]
|
| 78 |
+
return models
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def get_list_of_models_to_deprecate(
|
| 82 |
+
thresh_num_downloads=5_000,
|
| 83 |
+
thresh_date=None,
|
| 84 |
+
use_cache=False,
|
| 85 |
+
save_model_info=False,
|
| 86 |
+
max_num_models=-1,
|
| 87 |
+
):
|
| 88 |
+
if thresh_date is None:
|
| 89 |
+
thresh_date = datetime.now(timezone.utc).replace(year=datetime.now(timezone.utc).year - 1)
|
| 90 |
+
else:
|
| 91 |
+
thresh_date = datetime.strptime(thresh_date, "%Y-%m-%d").replace(tzinfo=timezone.utc)
|
| 92 |
+
|
| 93 |
+
models_dir = PATH_TO_REPO / "src/transformers/models"
|
| 94 |
+
model_paths = get_list_of_repo_model_paths(models_dir=models_dir)
|
| 95 |
+
|
| 96 |
+
if use_cache and os.path.exists("models_info.json"):
|
| 97 |
+
with open("models_info.json", "r") as f:
|
| 98 |
+
models_info = json.load(f)
|
| 99 |
+
# Convert datetimes back to datetime objects
|
| 100 |
+
for model, info in models_info.items():
|
| 101 |
+
info["first_commit_datetime"] = datetime.fromisoformat(info["first_commit_datetime"])
|
| 102 |
+
|
| 103 |
+
else:
|
| 104 |
+
# Build a dictionary of model info: first commit datetime, commit hash, model path
|
| 105 |
+
models_info = defaultdict(dict)
|
| 106 |
+
for model_path in model_paths:
|
| 107 |
+
model = model_path.split("/")[-2]
|
| 108 |
+
if model in models_info:
|
| 109 |
+
continue
|
| 110 |
+
commits = repo.git.log("--diff-filter=A", "--", model_path).split("\n")
|
| 111 |
+
commit_hash = _extract_commit_hash(commits)
|
| 112 |
+
commit_obj = repo.commit(commit_hash)
|
| 113 |
+
committed_datetime = commit_obj.committed_datetime
|
| 114 |
+
models_info[model]["commit_hash"] = commit_hash
|
| 115 |
+
models_info[model]["first_commit_datetime"] = committed_datetime
|
| 116 |
+
models_info[model]["model_path"] = model_path
|
| 117 |
+
models_info[model]["downloads"] = 0
|
| 118 |
+
|
| 119 |
+
# Some tags on the hub are formatted differently than in the library
|
| 120 |
+
tags = [model]
|
| 121 |
+
if "_" in model:
|
| 122 |
+
tags.append(model.replace("_", "-"))
|
| 123 |
+
models_info[model]["tags"] = tags
|
| 124 |
+
|
| 125 |
+
# Filter out models which were added less than a year ago
|
| 126 |
+
models_info = {
|
| 127 |
+
model: info for model, info in models_info.items() if info["first_commit_datetime"] < thresh_date
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
# We make successive calls to the hub, filtering based on the model tags
|
| 131 |
+
n_seen = 0
|
| 132 |
+
for model, model_info in models_info.items():
|
| 133 |
+
for model_tag in model_info["tags"]:
|
| 134 |
+
model_list = HubModelLister(tags=model_tag)
|
| 135 |
+
for i, hub_model in enumerate(model_list):
|
| 136 |
+
n_seen += 1
|
| 137 |
+
if i % 100 == 0:
|
| 138 |
+
print(f"Processing model {i} for tag {model_tag}")
|
| 139 |
+
if max_num_models != -1 and i > n_seen:
|
| 140 |
+
break
|
| 141 |
+
if hub_model.private:
|
| 142 |
+
continue
|
| 143 |
+
model_info["downloads"] += hub_model.downloads
|
| 144 |
+
|
| 145 |
+
if save_model_info and not (use_cache and os.path.exists("models_info.json")):
|
| 146 |
+
# Make datetimes serializable
|
| 147 |
+
for model, info in models_info.items():
|
| 148 |
+
info["first_commit_datetime"] = info["first_commit_datetime"].isoformat()
|
| 149 |
+
with open("models_info.json", "w") as f:
|
| 150 |
+
json.dump(models_info, f, indent=4)
|
| 151 |
+
|
| 152 |
+
print("\nFinding models to deprecate:")
|
| 153 |
+
n_models_to_deprecate = 0
|
| 154 |
+
models_to_deprecate = {}
|
| 155 |
+
for model, info in models_info.items():
|
| 156 |
+
n_downloads = info["downloads"]
|
| 157 |
+
if n_downloads < thresh_num_downloads:
|
| 158 |
+
n_models_to_deprecate += 1
|
| 159 |
+
models_to_deprecate[model] = info
|
| 160 |
+
print(f"\nModel: {model}")
|
| 161 |
+
print(f"Downloads: {n_downloads}")
|
| 162 |
+
print(f"Date: {info['first_commit_datetime']}")
|
| 163 |
+
print("\nModels to deprecate: ", "\n" + "\n".join(models_to_deprecate.keys()))
|
| 164 |
+
print(f"\nNumber of models to deprecate: {n_models_to_deprecate}")
|
| 165 |
+
print("Before deprecating make sure to verify the models, including if they're used as a module in other models.")
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
if __name__ == "__main__":
|
| 169 |
+
parser = argparse.ArgumentParser()
|
| 170 |
+
parser.add_argument("--save_model_info", action="store_true", help="Save the retrieved model info to a json file.")
|
| 171 |
+
parser.add_argument(
|
| 172 |
+
"--use_cache", action="store_true", help="Use the cached model info instead of calling the hub."
|
| 173 |
+
)
|
| 174 |
+
parser.add_argument(
|
| 175 |
+
"--thresh_num_downloads",
|
| 176 |
+
type=int,
|
| 177 |
+
default=5_000,
|
| 178 |
+
help="Threshold number of downloads below which a model should be deprecated. Default is 5,000.",
|
| 179 |
+
)
|
| 180 |
+
parser.add_argument(
|
| 181 |
+
"--thresh_date",
|
| 182 |
+
type=str,
|
| 183 |
+
default=None,
|
| 184 |
+
help="Date to consider the first commit from. Format: YYYY-MM-DD. If unset, defaults to one year ago from today.",
|
| 185 |
+
)
|
| 186 |
+
parser.add_argument(
|
| 187 |
+
"--max_num_models",
|
| 188 |
+
type=int,
|
| 189 |
+
default=-1,
|
| 190 |
+
help="Maximum number of models to consider from the hub. -1 means all models. Useful for testing.",
|
| 191 |
+
)
|
| 192 |
+
args = parser.parse_args()
|
| 193 |
+
|
| 194 |
+
models_to_deprecate = get_list_of_models_to_deprecate(
|
| 195 |
+
thresh_num_downloads=args.thresh_num_downloads,
|
| 196 |
+
thresh_date=args.thresh_date,
|
| 197 |
+
use_cache=args.use_cache,
|
| 198 |
+
save_model_info=args.save_model_info,
|
| 199 |
+
max_num_models=args.max_num_models,
|
| 200 |
+
)
|
tasks/tasksmith-441eeab80047/environment/source/utils/modular_model_converter.py
ADDED
|
@@ -0,0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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
import argparse
|
| 16 |
+
import glob
|
| 17 |
+
import importlib
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
from abc import ABC, abstractmethod
|
| 21 |
+
from collections import Counter, defaultdict, deque
|
| 22 |
+
from typing import Dict, Optional, Set, Union
|
| 23 |
+
|
| 24 |
+
import libcst as cst
|
| 25 |
+
from check_copies import run_ruff
|
| 26 |
+
from create_dependency_mapping import find_priority_list
|
| 27 |
+
from libcst import ClassDef, CSTVisitor
|
| 28 |
+
from libcst import matchers as m
|
| 29 |
+
from libcst.metadata import MetadataWrapper, ParentNodeProvider, PositionProvider, ScopeProvider
|
| 30 |
+
|
| 31 |
+
from transformers import logging
|
| 32 |
+
from transformers.models.auto.configuration_auto import CONFIG_MAPPING_NAMES
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
logger = logging.get_logger(__name__)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
AUTO_GENERATED_MESSAGE = """# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 39 |
+
# This file was automatically generated from {relative_path}.
|
| 40 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 41 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 42 |
+
# {short_name} file directly. One of our CI enforces this.
|
| 43 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def get_module_source_from_name(module_name: str) -> str:
|
| 48 |
+
# Extract the source code from the module name
|
| 49 |
+
spec = importlib.util.find_spec(module_name)
|
| 50 |
+
if spec is None or spec.origin is None:
|
| 51 |
+
raise ValueError(f"Cannot open file associated with {module_name} module.")
|
| 52 |
+
|
| 53 |
+
with open(spec.origin, "r", encoding="utf-8") as file:
|
| 54 |
+
source_code = file.read()
|
| 55 |
+
return source_code
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def preserve_case_replace(text, patterns: dict, default_name: str):
|
| 59 |
+
# Create a regex pattern to match all variations
|
| 60 |
+
regex_pattern = "|".join(re.escape(key) for key in patterns.keys())
|
| 61 |
+
compiled_regex = re.compile(f"(?<![a-z0-9])({regex_pattern})(.|$)", re.IGNORECASE | re.DOTALL)
|
| 62 |
+
|
| 63 |
+
def replace(match):
|
| 64 |
+
matched_pattern = match.group(1)
|
| 65 |
+
next_char = match.group(2)
|
| 66 |
+
new_pattern = patterns.get(matched_pattern, default_name)
|
| 67 |
+
|
| 68 |
+
# In this case, the cased old model did not respect CamelCase and was all UPPERCASE, so we need to rely on next char
|
| 69 |
+
# The heuristic is: if next char is not a letter, then it is not part of a model name and result should be `new_name`.upper()
|
| 70 |
+
if len(patterns) == 2 and matched_pattern.isupper():
|
| 71 |
+
if not next_char.isalpha():
|
| 72 |
+
# `new_name.upper()` is just the other entry for `matched_pattern.lower()`, uppercased
|
| 73 |
+
new_pattern = patterns[matched_pattern.lower()].upper()
|
| 74 |
+
|
| 75 |
+
return new_pattern + next_char
|
| 76 |
+
|
| 77 |
+
return compiled_regex.sub(replace, text)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def get_cased_name(lowercase_name: str) -> str:
|
| 81 |
+
"""From a model name in lowercase in the format `my_model`, return the cased name in the format `MyModel`."""
|
| 82 |
+
if lowercase_name in CONFIG_MAPPING_NAMES:
|
| 83 |
+
return CONFIG_MAPPING_NAMES[lowercase_name].replace("Config", "")
|
| 84 |
+
else:
|
| 85 |
+
return "".join(x.title() for x in lowercase_name.split("_"))
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def get_lowercase_name(cased_name: str) -> str:
|
| 89 |
+
"""From a model name in Camelcase in the format `MyModel`, return the lowercase name in the format `my_model`."""
|
| 90 |
+
inverse_mapping = {value: key for key, value in CONFIG_MAPPING_NAMES.items()}
|
| 91 |
+
if cased_name + "Config" in inverse_mapping:
|
| 92 |
+
return inverse_mapping[cased_name + "Config"]
|
| 93 |
+
else:
|
| 94 |
+
return "_".join([s.lower() for s in re.findall(r"[A-Z][^A-Z]*", cased_name)])
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class ReplaceNameTransformer(m.MatcherDecoratableTransformer):
|
| 98 |
+
"""A transformer that replaces `old_name` with `new_name` in comments, string and any references.
|
| 99 |
+
It should take into account name like `MyNewModel`, or `my_new_model`. Without using the AUTO_MAPPING.
|
| 100 |
+
Supported renaming patterns:
|
| 101 |
+
- llama -> my_new_model and my_new_model -> llama
|
| 102 |
+
- Llama -> MyNewModel and MyNewModel -> Llama
|
| 103 |
+
- LLAMA -> MY_NEW_MODEL and MY_NEW_MODEL -> LLAMA
|
| 104 |
+
- LLaMa -> MyNewModel abd MyNewModel -> Llama
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
def __init__(self, old_name: str, new_name: str, original_new_model_name: str = "", only_doc: bool = False):
|
| 108 |
+
super().__init__()
|
| 109 |
+
self.old_name = old_name
|
| 110 |
+
self.new_name = new_name
|
| 111 |
+
self.cased_new_name = get_cased_name(self.new_name)
|
| 112 |
+
self.cased_old_name = get_cased_name(self.old_name)
|
| 113 |
+
self.patterns = {
|
| 114 |
+
old_name: new_name,
|
| 115 |
+
old_name.upper(): new_name.upper(),
|
| 116 |
+
# For some old models, `self.cased_old_name` == `old_name.upper()` in which case this overwrite previous entry
|
| 117 |
+
self.cased_old_name: self.cased_new_name,
|
| 118 |
+
}
|
| 119 |
+
# In case new_name is a prefix alias, and not the original new model name
|
| 120 |
+
self.original_new_model_name = original_new_model_name
|
| 121 |
+
self.only_doc = only_doc
|
| 122 |
+
|
| 123 |
+
def _replace_name(self, original_node, updated_node):
|
| 124 |
+
if re.findall(r"# Copied from", updated_node.value):
|
| 125 |
+
return cst.RemoveFromParent()
|
| 126 |
+
update = preserve_case_replace(updated_node.value, self.patterns, self.cased_new_name)
|
| 127 |
+
return updated_node.with_changes(value=update)
|
| 128 |
+
|
| 129 |
+
@m.leave(m.SimpleString() | m.Comment())
|
| 130 |
+
def replace_name(self, original_node, updated_node):
|
| 131 |
+
return self._replace_name(original_node, updated_node)
|
| 132 |
+
|
| 133 |
+
def leave_Name(self, original_node, updated_node):
|
| 134 |
+
if not self.only_doc:
|
| 135 |
+
return self._replace_name(original_node, updated_node)
|
| 136 |
+
return updated_node
|
| 137 |
+
|
| 138 |
+
def leave_ImportFrom(self, original_node, updated_node):
|
| 139 |
+
"""The imports from other file types (configuration, processing etc) should use original model name."""
|
| 140 |
+
if self.original_new_model_name != self.new_name and m.matches(updated_node.module, m.Name()):
|
| 141 |
+
patterns = "|".join(ALL_FILE_TYPES)
|
| 142 |
+
regex = rf"({patterns})_{self.new_name}"
|
| 143 |
+
new_source = re.sub(
|
| 144 |
+
regex, lambda m: f"{m.group(1)}_{self.original_new_model_name}", updated_node.module.value
|
| 145 |
+
)
|
| 146 |
+
updated_node = updated_node.with_changes(module=updated_node.module.with_changes(value=new_source))
|
| 147 |
+
return updated_node
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
DOCSTRING_NODE = m.SimpleStatementLine(
|
| 151 |
+
body=[
|
| 152 |
+
m.Expr(
|
| 153 |
+
value=m.SimpleString(
|
| 154 |
+
# match anything between """ """
|
| 155 |
+
value=m.MatchIfTrue(lambda value: re.search(r"\"\"\"[\s\S]*\"\"\"", value) is not None)
|
| 156 |
+
)
|
| 157 |
+
)
|
| 158 |
+
]
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def SUPER_CALL_NODE(func_name):
|
| 163 |
+
return m.Call(func=m.Attribute(value=m.Call(func=m.Name("super")), attr=m.Name(func_name)))
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def is_call_to_super(node, func_name):
|
| 167 |
+
return m.matches(
|
| 168 |
+
node, m.SimpleStatementLine(body=[m.Return(SUPER_CALL_NODE(func_name)) | m.Expr(SUPER_CALL_NODE(func_name))])
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def get_full_attribute_name(node: Union[cst.Attribute, cst.Name]) -> Optional[str]:
|
| 173 |
+
"""Get the full name of an Attribute or Name node (e.g. `"nn.Module"` for an Attribute representing it). If the
|
| 174 |
+
successive value of an Attribute are not Name nodes, return `None`."""
|
| 175 |
+
if m.matches(node, m.Name()):
|
| 176 |
+
return node.value
|
| 177 |
+
elif m.matches(node, m.Attribute()):
|
| 178 |
+
if not m.matches(node.attr, m.Name()):
|
| 179 |
+
return None
|
| 180 |
+
name = node.attr.value
|
| 181 |
+
new_node = node.value
|
| 182 |
+
while m.matches(new_node, m.Attribute()):
|
| 183 |
+
if not m.matches(new_node.attr, m.Name()):
|
| 184 |
+
return None
|
| 185 |
+
name = new_node.attr.value + "." + name
|
| 186 |
+
new_node = new_node.value
|
| 187 |
+
if not m.matches(new_node, m.Name()):
|
| 188 |
+
return None
|
| 189 |
+
return new_node.value + "." + name
|
| 190 |
+
return None
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
# Transformer class to replace ClassB.call_to_method and ClassB().call_to_method with super().call_to_method
|
| 194 |
+
class ReplaceMethodCallTransformer(cst.CSTTransformer):
|
| 195 |
+
def __init__(self, all_bases: Set[str]):
|
| 196 |
+
self.all_bases = all_bases
|
| 197 |
+
|
| 198 |
+
def leave_Attribute(self, original_node: cst.Attribute, updated_node: cst.Attribute) -> cst.CSTNode:
|
| 199 |
+
# Handle ClassB.call_to_method or module.classB.call_to_method
|
| 200 |
+
if (
|
| 201 |
+
m.matches(original_node.value, m.Name() | m.Attribute())
|
| 202 |
+
and get_full_attribute_name(original_node.value) in self.all_bases
|
| 203 |
+
and m.matches(original_node.attr, m.Name())
|
| 204 |
+
):
|
| 205 |
+
# Replace with super().call_to_method
|
| 206 |
+
return updated_node.with_changes(
|
| 207 |
+
value=cst.Call(cst.Name("super")),
|
| 208 |
+
)
|
| 209 |
+
# Handle ClassB().call_to_method or module.ClassB().call_to_method
|
| 210 |
+
elif (
|
| 211 |
+
m.matches(original_node.value, m.Call())
|
| 212 |
+
and m.matches(original_node.value.func, m.Name() | m.Attribute())
|
| 213 |
+
and get_full_attribute_name(original_node.value.func) in self.all_bases
|
| 214 |
+
and m.matches(original_node.attr, m.Name())
|
| 215 |
+
):
|
| 216 |
+
# Replace with super().call_to_method
|
| 217 |
+
return updated_node.with_changes(value=cst.Call(cst.Name("super")))
|
| 218 |
+
return updated_node
|
| 219 |
+
|
| 220 |
+
def leave_Call(self, original_node: cst.Call, updated_node: cst.Call) -> cst.CSTNode:
|
| 221 |
+
# Check if the function being called is of the form ClassB().func_a or ClassB.func_a
|
| 222 |
+
if m.matches(original_node.func, m.Attribute()) and (
|
| 223 |
+
# Match ClassB().func_a(...) or module
|
| 224 |
+
(
|
| 225 |
+
m.matches(original_node.func.value, m.Call())
|
| 226 |
+
and m.matches(original_node.func.value.func, m.Name() | m.Attribute())
|
| 227 |
+
and get_full_attribute_name(original_node.func.value.func) in self.all_bases
|
| 228 |
+
)
|
| 229 |
+
or
|
| 230 |
+
# Match ClassB.func_a(...)
|
| 231 |
+
(
|
| 232 |
+
m.matches(original_node.func.value, m.Name() | m.Attribute())
|
| 233 |
+
and get_full_attribute_name(original_node.func.value) in self.all_bases
|
| 234 |
+
)
|
| 235 |
+
):
|
| 236 |
+
# Check if the first argument is 'self', and remove it
|
| 237 |
+
if len(original_node.args) > 0 and m.matches(original_node.args[0].value, m.Name("self")):
|
| 238 |
+
# Create the new argument list without 'self'
|
| 239 |
+
new_args = updated_node.args[1:]
|
| 240 |
+
else:
|
| 241 |
+
new_args = updated_node.args
|
| 242 |
+
|
| 243 |
+
return updated_node.with_changes(args=new_args)
|
| 244 |
+
return updated_node
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def get_docstring_indent(docstring):
|
| 248 |
+
# Match the first line after the opening triple quotes
|
| 249 |
+
match = re.search(r'(?:"""|\'\'\'|```)\n(\s+)', docstring)
|
| 250 |
+
if match:
|
| 251 |
+
# Return the indentation spaces captured
|
| 252 |
+
return len(match.group(1))
|
| 253 |
+
return 0
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def is_full_docstring(new_docstring: str) -> bool:
|
| 257 |
+
"""Check if `new_docstring` is a full docstring, or if it is only part of a docstring that should then
|
| 258 |
+
be merged with the existing old one.
|
| 259 |
+
"""
|
| 260 |
+
# libcst returns the docstrinbgs with litteral `r"""` quotes in front
|
| 261 |
+
new_docstring = new_docstring.split('"""', 1)[1]
|
| 262 |
+
# The docstring contains Args definition, so it is self-contained
|
| 263 |
+
if re.search(r"\n\s*Args:\n", new_docstring):
|
| 264 |
+
return True
|
| 265 |
+
# If it contains Returns, but starts with text indented with an additional 4 spaces before, it is self-contained
|
| 266 |
+
# (this is the scenario when using `@add_start_docstrings_to_model_forward`, but adding more args to docstring)
|
| 267 |
+
match_object = re.search(r"\n([^\S\n]*)Returns:\n", new_docstring)
|
| 268 |
+
if match_object is not None:
|
| 269 |
+
full_indent = match_object.group(1)
|
| 270 |
+
striped_doc = new_docstring.strip("\n")
|
| 271 |
+
if striped_doc.startswith(full_indent + " " * 4) or striped_doc.startswith(full_indent + "\t"):
|
| 272 |
+
return True
|
| 273 |
+
return False
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def merge_docstrings(original_docstring, updated_docstring):
|
| 277 |
+
original_level = get_docstring_indent(original_docstring)
|
| 278 |
+
if not is_full_docstring(updated_docstring):
|
| 279 |
+
# Split the docstring at the example section, assuming `"""` is used to define the docstring
|
| 280 |
+
parts = original_docstring.split("```")
|
| 281 |
+
if "```" in updated_docstring and len(parts) > 1:
|
| 282 |
+
updated_docstring = updated_docstring.lstrip('r"')
|
| 283 |
+
new_parts = updated_docstring.split("```")
|
| 284 |
+
if len(new_parts) != 3:
|
| 285 |
+
raise ValueError("There should only be one example, and it should have opening and closing '```'")
|
| 286 |
+
parts[1] = new_parts[1]
|
| 287 |
+
updated_docstring = "".join(
|
| 288 |
+
[
|
| 289 |
+
parts[0].rstrip(" \n") + new_parts[0],
|
| 290 |
+
f"\n{original_level * ' '}```",
|
| 291 |
+
parts[1],
|
| 292 |
+
"```",
|
| 293 |
+
parts[2],
|
| 294 |
+
]
|
| 295 |
+
)
|
| 296 |
+
elif updated_docstring not in original_docstring:
|
| 297 |
+
# add tabulation if we are at the lowest level.
|
| 298 |
+
if re.search(r"\n\s*.*\(.*\)\:\n\s*\w", updated_docstring):
|
| 299 |
+
updated_docstring = updated_docstring.replace("\n ", "\n ")
|
| 300 |
+
updated_docstring = original_docstring.rstrip('"') + "\n" + updated_docstring.lstrip('r"\n')
|
| 301 |
+
return updated_docstring
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
class SuperTransformer(cst.CSTTransformer):
|
| 305 |
+
METADATA_DEPENDENCIES = (ParentNodeProvider,)
|
| 306 |
+
|
| 307 |
+
def __init__(self, python_module: cst.Module, original_methods, updated_methods, all_bases=None):
|
| 308 |
+
self.python_module = python_module
|
| 309 |
+
self.original_methods = original_methods
|
| 310 |
+
self.updated_methods = updated_methods
|
| 311 |
+
self.all_assign_target = {}
|
| 312 |
+
self.deleted_targets = {} # child node can delete some arguments
|
| 313 |
+
self.all_bases = all_bases or []
|
| 314 |
+
self.transformer = ReplaceMethodCallTransformer(set(self.all_bases))
|
| 315 |
+
|
| 316 |
+
def update_body(self, existing_body, new_statements):
|
| 317 |
+
"""
|
| 318 |
+
Helper method to update the body by removing duplicates before adding new statements.
|
| 319 |
+
`existing_body` is the body of the original method, the parent class
|
| 320 |
+
`new_statements` are the additional statements
|
| 321 |
+
"""
|
| 322 |
+
deduplicated_new_body = []
|
| 323 |
+
existing_nodes = set()
|
| 324 |
+
for node in new_statements:
|
| 325 |
+
if m.matches(node, m.SimpleStatementLine(body=[m.Assign()])):
|
| 326 |
+
target = self.python_module.code_for_node(node.body[0].targets[0].target)
|
| 327 |
+
self.all_assign_target[target] = node
|
| 328 |
+
if m.matches(node, m.SimpleStatementLine(body=[m.Del()])):
|
| 329 |
+
target = self.python_module.code_for_node(node.body[0].target)
|
| 330 |
+
self.deleted_targets[target] = node
|
| 331 |
+
|
| 332 |
+
for stmt in existing_body:
|
| 333 |
+
if m.matches(stmt, m.SimpleStatementLine(body=[m.Assign()])):
|
| 334 |
+
target = self.python_module.code_for_node(stmt.body[0].targets[0].target)
|
| 335 |
+
if target in self.deleted_targets:
|
| 336 |
+
continue
|
| 337 |
+
if target in self.all_assign_target:
|
| 338 |
+
stmt = self.all_assign_target[target]
|
| 339 |
+
# Skip the docstring (will be added later on, at the beginning)
|
| 340 |
+
elif m.matches(stmt, DOCSTRING_NODE):
|
| 341 |
+
continue
|
| 342 |
+
comment_less_code = re.sub(r"#.*", "", self.python_module.code_for_node(stmt)).strip()
|
| 343 |
+
comment_less_code = re.sub(r"\ *\n", "\n", comment_less_code).strip()
|
| 344 |
+
deduplicated_new_body.append(stmt)
|
| 345 |
+
existing_nodes.add(comment_less_code)
|
| 346 |
+
|
| 347 |
+
for node in new_statements:
|
| 348 |
+
code = self.python_module.code_for_node(node)
|
| 349 |
+
comment_less_code = re.sub(r"#.*", "", code).strip()
|
| 350 |
+
comment_less_code = re.sub(r"\ *\n", "\n", comment_less_code).strip()
|
| 351 |
+
if node not in deduplicated_new_body and comment_less_code not in existing_nodes:
|
| 352 |
+
if not m.matches(node, m.SimpleStatementLine(body=[m.Del()])):
|
| 353 |
+
deduplicated_new_body.append(node)
|
| 354 |
+
existing_nodes.add(comment_less_code)
|
| 355 |
+
|
| 356 |
+
deduplicated_new_body = self._fix_post_init_location(deduplicated_new_body)
|
| 357 |
+
|
| 358 |
+
return deduplicated_new_body
|
| 359 |
+
|
| 360 |
+
def _fix_post_init_location(self, new_body: list[cst.CSTNode]):
|
| 361 |
+
"""Fix the location of the `post_init()` in the new body, if we added statements after the call to
|
| 362 |
+
`super()` (it needs to be the very last statement called)"""
|
| 363 |
+
# Fix the post_init() that has to be last
|
| 364 |
+
for i, node in enumerate(new_body):
|
| 365 |
+
code = self.python_module.code_for_node(node)
|
| 366 |
+
comment_less_code = re.sub(r"#.*", "", code).strip()
|
| 367 |
+
comment_less_code = re.sub(r"\ *\n", "\n", comment_less_code).strip()
|
| 368 |
+
if "self.post_init(" in comment_less_code and i < len(new_body) - 1:
|
| 369 |
+
# Remove it and add it again at the end
|
| 370 |
+
new_body.pop(i)
|
| 371 |
+
new_body.append(node)
|
| 372 |
+
break
|
| 373 |
+
return new_body
|
| 374 |
+
|
| 375 |
+
def _fix_init_location(self, new_body):
|
| 376 |
+
"""Fix the location of the `super().__init__()` in the new body, if we had new statements before it."""
|
| 377 |
+
start_index = 0
|
| 378 |
+
for i, node in enumerate(new_body):
|
| 379 |
+
if m.matches(node, DOCSTRING_NODE) and i == start_index:
|
| 380 |
+
start_index += 1
|
| 381 |
+
continue
|
| 382 |
+
code = self.python_module.code_for_node(node)
|
| 383 |
+
comment_less_code = re.sub(r"#.*", "", code).strip()
|
| 384 |
+
comment_less_code = re.sub(r"\ *\n", "\n", comment_less_code).strip()
|
| 385 |
+
if "super().__init__" in comment_less_code and i > start_index:
|
| 386 |
+
# Remove it and add it again at the top after the docstrings
|
| 387 |
+
node = new_body.pop(i)
|
| 388 |
+
new_body = new_body[:start_index] + [node] + new_body[start_index:]
|
| 389 |
+
break
|
| 390 |
+
return new_body
|
| 391 |
+
|
| 392 |
+
def replace_super_calls(self, node: cst.IndentedBlock, func_name: str) -> cst.CSTNode:
|
| 393 |
+
"""Updates the body of the input `node`'s `func_name` function by replacing calls
|
| 394 |
+
to super().func_name() with the source code of the parent class' `func_name`.
|
| 395 |
+
It keeps everything that is defined before `super().func_name()`.
|
| 396 |
+
"""
|
| 397 |
+
self.has_docstring = False
|
| 398 |
+
parent_has_docstring = False
|
| 399 |
+
if func_name in self.original_methods:
|
| 400 |
+
parent_has_docstring = m.matches(self.original_methods[func_name].body.body[0], DOCSTRING_NODE)
|
| 401 |
+
new_body = []
|
| 402 |
+
has_super_call = False
|
| 403 |
+
|
| 404 |
+
for i, expr in enumerate(node.body):
|
| 405 |
+
if is_call_to_super(expr, func_name):
|
| 406 |
+
has_super_call = True
|
| 407 |
+
new_body.extend(self.update_body(self.original_methods[func_name].body.body, node.body[i + 1 :]))
|
| 408 |
+
new_body = self._fix_init_location(new_body)
|
| 409 |
+
else:
|
| 410 |
+
expr = expr.visit(self.transformer)
|
| 411 |
+
if m.matches(expr, DOCSTRING_NODE):
|
| 412 |
+
self.has_docstring = True
|
| 413 |
+
if parent_has_docstring: # actually here we ought to de-duplicate?
|
| 414 |
+
original_docstring = self.original_methods[func_name].body.body[0].body[0].value.value
|
| 415 |
+
updated_docstring = expr.body[0].value.value
|
| 416 |
+
merged_doc = merge_docstrings(original_docstring, updated_docstring)
|
| 417 |
+
new_node = [expr.with_changes(body=[cst.Expr(value=cst.SimpleString(value=merged_doc))])]
|
| 418 |
+
else:
|
| 419 |
+
new_node = [expr]
|
| 420 |
+
new_body.extend(new_node)
|
| 421 |
+
elif not m.matches(expr, m.SimpleStatementLine(body=[m.Del()])) and not has_super_call:
|
| 422 |
+
new_body.append(expr)
|
| 423 |
+
if not self.has_docstring and parent_has_docstring:
|
| 424 |
+
new_body = [self.original_methods[func_name].body.body[0]] + new_body
|
| 425 |
+
return node.with_changes(body=new_body)
|
| 426 |
+
|
| 427 |
+
def leave_FunctionDef(self, original_node: cst.Call, updated_node: cst.Call) -> cst.CSTNode:
|
| 428 |
+
if updated_node.name.value in self.updated_methods:
|
| 429 |
+
name = updated_node.name.value
|
| 430 |
+
new_body = self.replace_super_calls(updated_node.body, name)
|
| 431 |
+
return updated_node.with_changes(body=new_body, params=updated_node.params)
|
| 432 |
+
return updated_node
|
| 433 |
+
|
| 434 |
+
def leave_Return(self, original_node: cst.Return, updated_node: cst.Return) -> cst.CSTNode:
|
| 435 |
+
""" "When a return statement is reached, it is replaced with the unrolled super code"""
|
| 436 |
+
if m.matches(updated_node.value, m.Call(func=m.Attribute(attr=m.Name("super")))):
|
| 437 |
+
func_def = self.get_metadata(ParentNodeProvider, original_node)
|
| 438 |
+
if m.matched(func_def, m.FunctionDef()) and func_def.name.value in self.original_methods:
|
| 439 |
+
updated_return_value = updated_node.value.with_changes(
|
| 440 |
+
args=[
|
| 441 |
+
cst.Arg(
|
| 442 |
+
value=cst.Call(func=cst.Name("super"), args=[cst.Arg(value=cst.Name(func_def.name.value))])
|
| 443 |
+
)
|
| 444 |
+
]
|
| 445 |
+
)
|
| 446 |
+
return updated_node.with_changes(value=updated_return_value)
|
| 447 |
+
return updated_node
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def find_all_dependencies(
|
| 451 |
+
dependency_mapping: Dict[str, set],
|
| 452 |
+
start_entity: Optional[str] = None,
|
| 453 |
+
initial_dependencies: Optional[set] = None,
|
| 454 |
+
initial_checked_dependencies: Optional[set] = None,
|
| 455 |
+
return_parent: bool = False,
|
| 456 |
+
) -> Union[list, set]:
|
| 457 |
+
"""Return all the dependencies of the given `start_entity` or `initial_dependencies`. This is basically some kind of
|
| 458 |
+
BFS traversal algorithm. It can either start from `start_entity`, or `initial_dependencies`.
|
| 459 |
+
|
| 460 |
+
Args:
|
| 461 |
+
dependency_mapping (`Dict[str, set]`):
|
| 462 |
+
A mapping from entities (usually function/assignment names), to immediate dependencies. That is, for function names,
|
| 463 |
+
a mapping {"foo": {"bar", "test"}} would indicate that functions `bar` and `test` are immediately called
|
| 464 |
+
in `foo`'s definition.
|
| 465 |
+
start_entity (str | None, *optional*):
|
| 466 |
+
A key of `dependency_mapping`, indicating from which entity to start the search.
|
| 467 |
+
initial_dependencies (set | None, *optional*):
|
| 468 |
+
If `start_entity` is not provided, this can be used as an alternative. In this case, the search will continue
|
| 469 |
+
from all the entities in `initial_dependencies`, if they are in `dependency_mapping`.
|
| 470 |
+
initial_checked_dependencies (set | None, *optional*):
|
| 471 |
+
If provided, entities already present in `initial_checked_dependencies` will not be part of the returned dependencies.
|
| 472 |
+
return_parent (bool, *optional*):
|
| 473 |
+
If `True`, will return a list consisting of tuples (dependency, parent) instead of a simple set of dependencies. Note
|
| 474 |
+
that the order of the items in the list reflects the traversal order. Thus, no parent can ever appear before childs.
|
| 475 |
+
Returns:
|
| 476 |
+
A set of all the dependencies, or a list of tuples `(dependency, parent)` if `return_parent=True`.
|
| 477 |
+
|
| 478 |
+
Example:
|
| 479 |
+
Given the following structure in the `modular_xxx.py` file:
|
| 480 |
+
```
|
| 481 |
+
def foo1():
|
| 482 |
+
pass
|
| 483 |
+
|
| 484 |
+
def foo2():
|
| 485 |
+
pass
|
| 486 |
+
|
| 487 |
+
def bar():
|
| 488 |
+
foo1()
|
| 489 |
+
|
| 490 |
+
def foobar():
|
| 491 |
+
bar()
|
| 492 |
+
foo2()
|
| 493 |
+
|
| 494 |
+
class MyLayer(SomeOtherModelLayer):
|
| 495 |
+
def forward(...):
|
| 496 |
+
foobar()
|
| 497 |
+
```
|
| 498 |
+
and the `dependency_mapping` created when visiting the `modular_xxx.py` file, we get:
|
| 499 |
+
```
|
| 500 |
+
dependency_mapping = {'bar': {'foo1'}, 'foobar': {'bar', 'foo2'}}
|
| 501 |
+
find_all_dependencies(dependency_mapping, start_entity='foobar', return_parent=True)
|
| 502 |
+
>>> [('bar', 'foobar'), ('foo2', 'foobar'), ('foo1', 'bar')]
|
| 503 |
+
```
|
| 504 |
+
That is, all the functions needed (and potentially their immediate parent) so that the function to be added
|
| 505 |
+
in MyLayer (`foobar`) can work correctly.
|
| 506 |
+
"""
|
| 507 |
+
if initial_dependencies is None and start_entity is not None:
|
| 508 |
+
initial_dependencies = dependency_mapping[start_entity]
|
| 509 |
+
if initial_checked_dependencies is None:
|
| 510 |
+
initial_checked_dependencies = set()
|
| 511 |
+
|
| 512 |
+
dependency_queue = deque(initial_dependencies)
|
| 513 |
+
all_dependencies = set()
|
| 514 |
+
all_dependencies_with_parent = []
|
| 515 |
+
checked_dependencies = set(initial_checked_dependencies)
|
| 516 |
+
parents = {initial_dep: start_entity for initial_dep in initial_dependencies}
|
| 517 |
+
while len(dependency_queue) > 0:
|
| 518 |
+
# Pick element to visit
|
| 519 |
+
current = dependency_queue.popleft()
|
| 520 |
+
if current not in checked_dependencies:
|
| 521 |
+
# Add the dependencies
|
| 522 |
+
all_dependencies.add(current)
|
| 523 |
+
all_dependencies_with_parent += [(current, parents[current])]
|
| 524 |
+
if current in dependency_mapping.keys():
|
| 525 |
+
# Update dependency queue
|
| 526 |
+
dependency_queue.extend(dependency_mapping[current])
|
| 527 |
+
parents.update({dep: current for dep in dependency_mapping[current]})
|
| 528 |
+
# add visited node to the list
|
| 529 |
+
checked_dependencies.add(current)
|
| 530 |
+
|
| 531 |
+
if not return_parent:
|
| 532 |
+
return all_dependencies
|
| 533 |
+
# no child can ever appear before its parent thanks to the queue (needed to add them at the correct location in the body later)
|
| 534 |
+
return all_dependencies_with_parent
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
# Top-level variables that match the following patterns will always use the value in the `modular_xxx.py` file
|
| 538 |
+
ASSIGNMENTS_REGEX_TO_KEEP = [r"_CHECKPOINT", r"_EXPECTED", r"_FOR_DOC"]
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
class ClassDependencyMapper(CSTVisitor):
|
| 542 |
+
"""A visitor which is designed to analyze a single class node to get all its dependencies that are shared with the set of
|
| 543 |
+
`global_names`.
|
| 544 |
+
"""
|
| 545 |
+
|
| 546 |
+
def __init__(
|
| 547 |
+
self, class_name: str, global_names: set[str], objects_imported_from_modeling: Optional[set[str]] = None
|
| 548 |
+
):
|
| 549 |
+
super().__init__()
|
| 550 |
+
self.class_name = class_name
|
| 551 |
+
self.dependencies = set()
|
| 552 |
+
self.global_names = global_names
|
| 553 |
+
self.objects_imported_from_modeling = (
|
| 554 |
+
set() if objects_imported_from_modeling is None else objects_imported_from_modeling
|
| 555 |
+
)
|
| 556 |
+
|
| 557 |
+
def visit_Name(self, node):
|
| 558 |
+
if (
|
| 559 |
+
node.value != self.class_name
|
| 560 |
+
and node.value in self.global_names
|
| 561 |
+
and node.value not in self.objects_imported_from_modeling
|
| 562 |
+
):
|
| 563 |
+
self.dependencies.add(node.value)
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def dependencies_for_class_node(node: cst.ClassDef, global_names: set[str]) -> set:
|
| 567 |
+
"""Create immediate dependencies for a class node based on the `global_names`."""
|
| 568 |
+
temp_module = cst.Module(body=[node])
|
| 569 |
+
visitor = ClassDependencyMapper(node.name.value, global_names)
|
| 570 |
+
temp_module.visit(visitor)
|
| 571 |
+
return visitor.dependencies
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
def augmented_dependencies_for_class_node(
|
| 575 |
+
node: cst.ClassDef, mapper: "ModuleMapper", objects_imported_from_modeling: Optional[set[str]] = None
|
| 576 |
+
) -> set:
|
| 577 |
+
"""Create augmented dependencies for a class node based on a `mapper`.
|
| 578 |
+
Augmented dependencies means immediate dependencies + recursive function and assignments dependencies.
|
| 579 |
+
"""
|
| 580 |
+
temp_module = cst.Module(body=[node])
|
| 581 |
+
visitor = ClassDependencyMapper(node.name.value, set(mapper.global_nodes.keys()), objects_imported_from_modeling)
|
| 582 |
+
temp_module.visit(visitor)
|
| 583 |
+
return mapper.augment_dependencies(visitor.dependencies)
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
# All the potential file types to create
|
| 587 |
+
ALL_FILE_TYPES = (
|
| 588 |
+
"modeling",
|
| 589 |
+
"configuration",
|
| 590 |
+
"tokenization",
|
| 591 |
+
"processing",
|
| 592 |
+
"image_processing",
|
| 593 |
+
"feature_extractor",
|
| 594 |
+
)
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
class ModuleMapper(CSTVisitor, ABC):
|
| 598 |
+
"""An abstract visitor class which analyses a module, creating a mapping of dependencies for classes, functions and assignments.
|
| 599 |
+
Class dependencies are computed with `compute_class_dependencies()`, while function and assignment dependencies are stored in
|
| 600 |
+
`self.object_recursive_dependency_mapping` (can be computed by `_compute_recursive_object_dependencies()`).
|
| 601 |
+
It defines common visiting patterns (i.e. common visit_xxx/leave_xxx functions) between the modular file and the
|
| 602 |
+
modeling files that will be visited.
|
| 603 |
+
"""
|
| 604 |
+
|
| 605 |
+
METADATA_DEPENDENCIES = (ParentNodeProvider, PositionProvider)
|
| 606 |
+
|
| 607 |
+
def __init__(self, python_module: cst.Module):
|
| 608 |
+
# fmt: off
|
| 609 |
+
self.python_module: cst.Module = python_module # original cst.Module being visited
|
| 610 |
+
self.classes: Dict[str, cst.ClassDef] = {} # mapping from class names to Nodes (it will be ordered by default!!)
|
| 611 |
+
self.imports = [] # stores all import statements
|
| 612 |
+
self.functions: Dict[str, cst.FunctionDef] = {} # mapping of global scope function names to Nodes
|
| 613 |
+
self.object_dependency_mapping = defaultdict(set) # immediate function/assignment dependency mapping (i.e. dependencies immediately in the function/assignment definition)
|
| 614 |
+
self.assignments: Dict[str, cst.SimpleStatementLine] = {} # mapping of global assignments names to Nodes
|
| 615 |
+
self.current_function = None # this keeps track of the current module-scope function
|
| 616 |
+
self.current_assignment = None # this keeps track of the current module-scope assignment
|
| 617 |
+
# this keeps track of objects imported from modeling files (`from .configuration import Config`) -> `Config` should not be a dependency
|
| 618 |
+
self.objects_imported_from_modeling = set()
|
| 619 |
+
# regex pattern joining every possible file type
|
| 620 |
+
self.match_patterns = "|".join(ALL_FILE_TYPES)
|
| 621 |
+
# fmt: on
|
| 622 |
+
|
| 623 |
+
def visit_ImportFrom(self, node):
|
| 624 |
+
"""This keeps track of objects imported from neighbor modeling files (e.g. in `modeling_xxx.py, we have
|
| 625 |
+
`from .configuration_xxx import Config`, then `Config` should be recorded as it is not a dependency that needs
|
| 626 |
+
to be added (because it will be part of the imports)"""
|
| 627 |
+
import_module = self.python_module.code_for_node(node.module)
|
| 628 |
+
import_statement = "." * len(node.relative) + import_module
|
| 629 |
+
if re.search(rf"^\.({self.match_patterns})_.*", import_statement):
|
| 630 |
+
for imported_object in node.names:
|
| 631 |
+
# If an alias is present, we record it and not the original name
|
| 632 |
+
if imported_object.evaluated_alias is not None:
|
| 633 |
+
self.objects_imported_from_modeling.add(imported_object.evaluated_alias)
|
| 634 |
+
else:
|
| 635 |
+
self.objects_imported_from_modeling.add(imported_object.evaluated_name)
|
| 636 |
+
|
| 637 |
+
def visit_SimpleStatementLine(self, node):
|
| 638 |
+
"""
|
| 639 |
+
Global Assigns like `GEMMA_INPUT_DOCSTRING = 'THIS IS THE INPUT'` and all import statements
|
| 640 |
+
are extracted and saved in their corresponding dict. They are then used when updating dependency mappings.
|
| 641 |
+
"""
|
| 642 |
+
parent_node = self.get_metadata(cst.metadata.ParentNodeProvider, node)
|
| 643 |
+
simple_top_level_assign_structure = m.SimpleStatementLine(
|
| 644 |
+
body=[m.Assign(targets=[m.AssignTarget(target=m.Name())])]
|
| 645 |
+
)
|
| 646 |
+
if m.matches(parent_node, m.Module()):
|
| 647 |
+
if m.matches(node, simple_top_level_assign_structure):
|
| 648 |
+
left_hand_side = node.body[0].targets[0].target.value
|
| 649 |
+
self.current_assignment = left_hand_side
|
| 650 |
+
self.assignments[left_hand_side] = node
|
| 651 |
+
elif m.matches(node, m.SimpleStatementLine(body=[m.Import() | m.ImportFrom()])):
|
| 652 |
+
self.imports.append(node)
|
| 653 |
+
|
| 654 |
+
def leave_SimpleStatementLine(self, node):
|
| 655 |
+
# No need to check for the parent here -> everytime we exit one, it should be None anyway independently of where the
|
| 656 |
+
# SimpleStatement is located
|
| 657 |
+
self.current_assignment = None
|
| 658 |
+
|
| 659 |
+
def visit_FunctionDef(self, node):
|
| 660 |
+
parent_node = self.get_metadata(cst.metadata.ParentNodeProvider, node)
|
| 661 |
+
if m.matches(parent_node, m.Module()):
|
| 662 |
+
self.current_function = node.name.value
|
| 663 |
+
self.functions[node.name.value] = node
|
| 664 |
+
|
| 665 |
+
def leave_FunctionDef(self, node):
|
| 666 |
+
parent_node = self.get_metadata(cst.metadata.ParentNodeProvider, node)
|
| 667 |
+
if m.matches(parent_node, m.Module()):
|
| 668 |
+
self.current_function = None
|
| 669 |
+
|
| 670 |
+
def visit_If(self, node):
|
| 671 |
+
# If we are inside a function, do not add the import to the list of imports
|
| 672 |
+
if self.current_function is None:
|
| 673 |
+
for stmt in node.body.body:
|
| 674 |
+
if m.matches(stmt, m.SimpleStatementLine(body=[m.ImportFrom() | m.Import()])):
|
| 675 |
+
self.imports.append(node)
|
| 676 |
+
|
| 677 |
+
def visit_ClassDef(self, node: ClassDef) -> None:
|
| 678 |
+
"""Record class nodes to create their dependencies at the end."""
|
| 679 |
+
self.classes[node.name.value] = node
|
| 680 |
+
|
| 681 |
+
def visit_Name(self, node: cst.Call):
|
| 682 |
+
"""This is used to create a mapping from module-scope functions and assignments to objects used inside them."""
|
| 683 |
+
if self.current_function is not None:
|
| 684 |
+
self.object_dependency_mapping[self.current_function].add(node.value)
|
| 685 |
+
if self.current_assignment is not None:
|
| 686 |
+
self.object_dependency_mapping[self.current_assignment].add(node.value)
|
| 687 |
+
|
| 688 |
+
def leave_Module(self, node):
|
| 689 |
+
"""When leaving the module, we store the position of each global scoped node to allow sorting the dependencies
|
| 690 |
+
based on their position in the code later. We use the PositionProvider metadata wrapper for this.
|
| 691 |
+
We also make sure to update `self.object_dependency_mapping` so that it contains only names recorded in
|
| 692 |
+
`self.global_nodes`.
|
| 693 |
+
"""
|
| 694 |
+
# assign all nodes
|
| 695 |
+
self.global_nodes = {**self.assignments, **self.classes, **self.functions}
|
| 696 |
+
# now sort the class dependency_mapping based on the position of the nodes
|
| 697 |
+
self.start_lines = {}
|
| 698 |
+
for id, node in self.global_nodes.items():
|
| 699 |
+
self.start_lines[id] = self.get_metadata(cst.metadata.PositionProvider, node).start.line
|
| 700 |
+
|
| 701 |
+
def _restrict_dependencies_to_known_entities(self):
|
| 702 |
+
"""Since we added every Name as part of `self.object_dependency_mapping`, we need to remove those that
|
| 703 |
+
are not part of the recorded objects in `self.global_nodes` (i.e. built-in variables, imports, etc).
|
| 704 |
+
This should be called only after all merging operations have been finalized!!"""
|
| 705 |
+
global_objects = set(self.global_nodes.keys())
|
| 706 |
+
for object_name, dependencies in self.object_dependency_mapping.items():
|
| 707 |
+
self.object_dependency_mapping[object_name] = {dep for dep in dependencies if dep in global_objects}
|
| 708 |
+
|
| 709 |
+
def _compute_recursive_object_dependencies(self) -> dict[str, set]:
|
| 710 |
+
"""Based on immediate dependency mapping, create the recursive dependency mapping. For example, given the
|
| 711 |
+
following file:
|
| 712 |
+
```
|
| 713 |
+
def foo():
|
| 714 |
+
pass
|
| 715 |
+
|
| 716 |
+
def bar():
|
| 717 |
+
foo()
|
| 718 |
+
|
| 719 |
+
def test():
|
| 720 |
+
bar()
|
| 721 |
+
```
|
| 722 |
+
this visitor can only record immediate dependencies, i.e. it will record the following
|
| 723 |
+
`self.object_dependency_mapping = {"test": {"bar"}, "bar": {"foo}}`. This function is used to create
|
| 724 |
+
the recursive mapping, i.e. `recursive_dependencies = {"test": {"bar", "foo"}, "bar": {"foo}}`.
|
| 725 |
+
"""
|
| 726 |
+
recursive_dependencies = {}
|
| 727 |
+
for object_name in self.object_dependency_mapping.keys():
|
| 728 |
+
all_dependencies = find_all_dependencies(self.object_dependency_mapping, start_entity=object_name)
|
| 729 |
+
recursive_dependencies[object_name] = all_dependencies
|
| 730 |
+
return recursive_dependencies
|
| 731 |
+
|
| 732 |
+
def augment_dependencies(self, dependencies: set[str]) -> set[str]:
|
| 733 |
+
"""For a set of `dependencies`, augment them by adding all potential dependencies of the **functions** and
|
| 734 |
+
**assignments** present in the `dependencies`.
|
| 735 |
+
"""
|
| 736 |
+
new_dependencies = dependencies.copy()
|
| 737 |
+
# Go through the set of dependencies
|
| 738 |
+
for dep in tuple(dependencies):
|
| 739 |
+
if dep in self.object_recursive_dependency_mapping.keys():
|
| 740 |
+
new_dependencies.update(self.object_recursive_dependency_mapping[dep])
|
| 741 |
+
return new_dependencies
|
| 742 |
+
|
| 743 |
+
def compute_class_dependencies(self):
|
| 744 |
+
"""For each visited class, find its dependencies based on visiting the current file + potential merged dependencies."""
|
| 745 |
+
self.class_dependency_mapping = {}
|
| 746 |
+
for class_name, class_node in self.classes.items():
|
| 747 |
+
dependencies = dependencies_for_class_node(class_node, set(self.global_nodes.keys()))
|
| 748 |
+
# Correctly augment class dependencies with all needed objects
|
| 749 |
+
self.class_dependency_mapping[class_name] = self.augment_dependencies(dependencies)
|
| 750 |
+
|
| 751 |
+
@abstractmethod
|
| 752 |
+
def compute_relative_order(self, missing_dependencies: set) -> dict[str, int]:
|
| 753 |
+
raise NotImplementedError
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
class ModelFileMapper(ModuleMapper):
|
| 757 |
+
"""A mapper designed to parse modeling files (like `modeling_llama.py`). When encountering such a file
|
| 758 |
+
in the `modular_xxx.py` file, we need to correctly visit it and merge the dependencies of the modular and current file.
|
| 759 |
+
For this reason, this class should only be instantiated from the class method `visit_and_merge_dependencies`, which takes
|
| 760 |
+
care of correctly merging dependencies, then finalizes all dependency graph computations.
|
| 761 |
+
Note that we only merge functions and assignments here, as classes will be treated later on as they may be modified.
|
| 762 |
+
For example, if you redefine `apply_rotary_pos_emb()` in the modular, the new node should be used in the dependencies
|
| 763 |
+
of the modeling files as well.
|
| 764 |
+
"""
|
| 765 |
+
|
| 766 |
+
def __init__(self, python_module: cst.Module):
|
| 767 |
+
super().__init__(python_module)
|
| 768 |
+
|
| 769 |
+
def compute_relative_order(self, missing_dependencies: set[str]) -> dict[str, int]:
|
| 770 |
+
"""Compute in which relative order the `missing_dependencies` should appear when the nodes are added to the final file that
|
| 771 |
+
will be created based on the modular.
|
| 772 |
+
"""
|
| 773 |
+
relative_order = {}
|
| 774 |
+
idx = 0
|
| 775 |
+
classes = sorted(
|
| 776 |
+
[dep for dep in tuple(missing_dependencies) if dep in self.classes], key=lambda x: self.start_lines[x]
|
| 777 |
+
)
|
| 778 |
+
# This is because for merged dependencies, we only have relative order in the other visited file, so we need
|
| 779 |
+
# to track dependency order relative to a given class
|
| 780 |
+
if len(classes) > 0 and not hasattr(self, "class_dependency_mapping"):
|
| 781 |
+
raise ValueError("Cannot correctly find the relative order of the dependencies.")
|
| 782 |
+
|
| 783 |
+
remaining_dependencies = missing_dependencies.copy()
|
| 784 |
+
|
| 785 |
+
# Start by tracking relative order class by class
|
| 786 |
+
for class_name in classes:
|
| 787 |
+
class_dependencies = tuple(self.class_dependency_mapping[class_name] & remaining_dependencies)
|
| 788 |
+
original_dependencies = []
|
| 789 |
+
merged_dependencies = []
|
| 790 |
+
# We need to differentiate between nodes that were already present (we can get relative order globally) and
|
| 791 |
+
# nodes that were merged (we can get relative order only relative to the class the dependencies relate to)
|
| 792 |
+
for class_dep in class_dependencies:
|
| 793 |
+
if class_dep in self.start_lines:
|
| 794 |
+
original_dependencies.append(class_dep)
|
| 795 |
+
else:
|
| 796 |
+
merged_dependencies.append(class_dep)
|
| 797 |
+
# We need to sort deterministically before actual sorting, so that entries missing (i.e. with value 1e10)
|
| 798 |
+
# will always get the same order independently of the system (they come from a set, which has no deterministic order)
|
| 799 |
+
original_dependencies = sorted(original_dependencies, reverse=True)
|
| 800 |
+
# Sort both list according to the order in their respective file
|
| 801 |
+
original_dependencies = sorted(original_dependencies, key=lambda x: self.start_lines.get(x, 1e10))
|
| 802 |
+
merged_dependencies = sorted(merged_dependencies, key=lambda x: self.modular_file_start_lines[x])
|
| 803 |
+
|
| 804 |
+
# Add all original node first, then merged ones
|
| 805 |
+
for dep in original_dependencies + merged_dependencies:
|
| 806 |
+
remaining_dependencies.remove(dep)
|
| 807 |
+
relative_order[dep] = idx
|
| 808 |
+
idx += 1
|
| 809 |
+
# Add the class itself (it can sometimes already be present if the order of classes in the source file
|
| 810 |
+
# does not make sense, i.e. a class is used somewhere before being defined like in `rt_detr`...)
|
| 811 |
+
if class_name in remaining_dependencies:
|
| 812 |
+
remaining_dependencies.remove(class_name)
|
| 813 |
+
relative_order[class_name] = idx
|
| 814 |
+
idx += 1
|
| 815 |
+
|
| 816 |
+
# Now add what still remains
|
| 817 |
+
remaining_dependencies = tuple(remaining_dependencies)
|
| 818 |
+
original_dependencies = []
|
| 819 |
+
merged_dependencies = []
|
| 820 |
+
for dep in remaining_dependencies:
|
| 821 |
+
if dep in self.modular_file_start_lines:
|
| 822 |
+
merged_dependencies.append(dep)
|
| 823 |
+
else:
|
| 824 |
+
original_dependencies.append(dep)
|
| 825 |
+
# We need to sort deterministically before actual sorting, so that entries missing (i.e. with value 1e10)
|
| 826 |
+
# will always get the same order independently of the system (they come from a set, which has no deterministic order)
|
| 827 |
+
original_dependencies = sorted(original_dependencies, reverse=True)
|
| 828 |
+
# Sort both list according to the order in their respective file
|
| 829 |
+
original_dependencies = sorted(original_dependencies, key=lambda x: self.start_lines.get(x, 1e10))
|
| 830 |
+
merged_dependencies = sorted(merged_dependencies, key=lambda x: self.modular_file_start_lines[x])
|
| 831 |
+
|
| 832 |
+
# Add all original node first, then merged ones
|
| 833 |
+
for dep in original_dependencies + merged_dependencies:
|
| 834 |
+
relative_order[dep] = idx
|
| 835 |
+
idx += 1
|
| 836 |
+
|
| 837 |
+
return relative_order
|
| 838 |
+
|
| 839 |
+
def _merge_functions(self, functions: dict[str, cst.CSTNode], object_mapping: dict[str, set]):
|
| 840 |
+
"""Update the global nodes and function dependency mapping with those from the modular file.
|
| 841 |
+
|
| 842 |
+
Merging rule: if any function with the same name was redefined in the modular, use it and its dependencies
|
| 843 |
+
instead of the original ones (this may mean to add new functions as well, if any redefined function uses a new one).
|
| 844 |
+
"""
|
| 845 |
+
# Add/overwrite all needed function nodes and dependencies
|
| 846 |
+
self.functions.update(functions)
|
| 847 |
+
self.object_dependency_mapping.update(
|
| 848 |
+
{obj: dep for obj, dep in object_mapping.items() if obj in functions.keys()}
|
| 849 |
+
)
|
| 850 |
+
# Add them to global nodes
|
| 851 |
+
self.global_nodes.update(self.functions)
|
| 852 |
+
|
| 853 |
+
def _merge_assignments(self, assignments: dict[str, cst.CSTNode], object_mapping: dict[str, set]):
|
| 854 |
+
"""Update the global nodes with the assignment from the modular file.
|
| 855 |
+
|
| 856 |
+
Merging rule: if any assignment with the same name was redefined in the modular, we use it and its dependencies ONLY if it matches
|
| 857 |
+
a pattern in `ASSIGNMENTS_REGEX_TO_KEEP`. Otherwise, we use the original value and dependencies. This rule was chosen to avoid having to rewrite the
|
| 858 |
+
big docstrings.
|
| 859 |
+
"""
|
| 860 |
+
for assignment, node in assignments.items():
|
| 861 |
+
should_keep = any(re.search(pattern, assignment) for pattern in ASSIGNMENTS_REGEX_TO_KEEP)
|
| 862 |
+
|
| 863 |
+
if should_keep or assignment not in self.assignments:
|
| 864 |
+
self.assignments[assignment] = node
|
| 865 |
+
if assignment in object_mapping:
|
| 866 |
+
self.object_dependency_mapping[assignment] = object_mapping[assignment]
|
| 867 |
+
# Add them to global nodes
|
| 868 |
+
self.global_nodes.update(self.assignments)
|
| 869 |
+
|
| 870 |
+
def _merge_classes(self, classes: dict[str, cst.CSTNode]):
|
| 871 |
+
"""Update the global nodes with the new classes from the modular (i.e. classes which do not exist in current file, and
|
| 872 |
+
are not imported). We do NOT update any dependency mapping here. This is because we only need the names of newly defined
|
| 873 |
+
classes in the modular to be discoverable when computing dependencies for new nodes later on. For this reason, we
|
| 874 |
+
do not add the new classes to `self.classes`, but only to `global_nodes`.
|
| 875 |
+
"""
|
| 876 |
+
# Add/overwrite all needed function nodes and dependencies
|
| 877 |
+
self.global_nodes.update(
|
| 878 |
+
{
|
| 879 |
+
name: node
|
| 880 |
+
for name, node in classes.items()
|
| 881 |
+
if name not in self.classes and name not in self.objects_imported_from_modeling
|
| 882 |
+
}
|
| 883 |
+
)
|
| 884 |
+
|
| 885 |
+
def merge_modular_dependencies(self, classes, functions, assignments, object_mapping, start_lines):
|
| 886 |
+
"""Merge classes, functions and assignments from the modular definitions into the current module file,
|
| 887 |
+
then record the relative order of all nodes.
|
| 888 |
+
Note: This function takes care of updating `global_nodes` and `object_recursive_dependency_mapping` as well after the
|
| 889 |
+
merge with other files dependencies.
|
| 890 |
+
"""
|
| 891 |
+
self._merge_functions(functions, object_mapping)
|
| 892 |
+
self._merge_assignments(assignments, object_mapping)
|
| 893 |
+
self._merge_classes(classes)
|
| 894 |
+
self.modular_file_start_lines = start_lines
|
| 895 |
+
|
| 896 |
+
# Restrict the dependency mappings to the known entities to avoid Python's built-ins and imports
|
| 897 |
+
self._restrict_dependencies_to_known_entities()
|
| 898 |
+
# Create the global mapping of recursive dependencies for functions and assignments
|
| 899 |
+
self.object_recursive_dependency_mapping = self._compute_recursive_object_dependencies()
|
| 900 |
+
|
| 901 |
+
@classmethod
|
| 902 |
+
def visit_and_merge_dependencies(
|
| 903 |
+
cls, module: cst.Module, classes, functions, assignments, object_mapping, start_lines
|
| 904 |
+
) -> "ModelFileMapper":
|
| 905 |
+
wrapper = MetadataWrapper(module)
|
| 906 |
+
mapper = cls(module)
|
| 907 |
+
wrapper.visit(mapper)
|
| 908 |
+
# Merge dependencies
|
| 909 |
+
mapper.merge_modular_dependencies(classes, functions, assignments, object_mapping, start_lines)
|
| 910 |
+
# Create the class dependencies graph
|
| 911 |
+
mapper.compute_class_dependencies()
|
| 912 |
+
return mapper
|
| 913 |
+
|
| 914 |
+
|
| 915 |
+
def common_partial_suffix(str1: str, str2: str) -> str:
|
| 916 |
+
"""Return the biggest common suffix between 2 strings. If one string is a full suffix of the other string,
|
| 917 |
+
we do not consider it a common suffix and return `""`"""
|
| 918 |
+
common_suffix = ""
|
| 919 |
+
for i in range(1, min(len(str1), len(str2)) + 1):
|
| 920 |
+
if str1[-i] == str2[-i]:
|
| 921 |
+
common_suffix = str1[-i] + common_suffix
|
| 922 |
+
else:
|
| 923 |
+
break
|
| 924 |
+
# We do not allow full string suffix
|
| 925 |
+
if common_suffix == str1 or common_suffix == str2:
|
| 926 |
+
common_suffix = ""
|
| 927 |
+
return common_suffix
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
def replace_class_node(
|
| 931 |
+
mapper: ModelFileMapper, class_node: cst.ClassDef, renamed_super_class: str, original_super_class: str
|
| 932 |
+
):
|
| 933 |
+
"""
|
| 934 |
+
Replace a class node which inherits from another modeling class. This function works in the following way:
|
| 935 |
+
- start from the base class node of the inherited class (a cst.Node)
|
| 936 |
+
- replace all methods of the base node with the methods defined in the child class
|
| 937 |
+
- append all new methods defined in the child class
|
| 938 |
+
- replace all calls to super() with the unravelled code
|
| 939 |
+
|
| 940 |
+
| ```python | | ```python
|
| 941 |
+
| class GemmaModel(LlamaModel): | | class GemmaModel(nn.Module):
|
| 942 |
+
| def __init__(self): | | def __init__(self):
|
| 943 |
+
Going from: | super().__init__() | to: | super().__init__(config)
|
| 944 |
+
| self.dropout = 0.2 | | self.dropout = 0.2
|
| 945 |
+
| ``` | | self.padding_idx = config.pad_token_id
|
| 946 |
+
| self.vocab_size = config.vocab_size
|
| 947 |
+
| self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 948 |
+
| self.layers = nn.ModuleList(
|
| 949 |
+
| [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 950 |
+
| )
|
| 951 |
+
| self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 952 |
+
| self.gradient_checkpointing = False
|
| 953 |
+
| # Initialize weights and apply final processing
|
| 954 |
+
| self.post_init()
|
| 955 |
+
| ```
|
| 956 |
+
"""
|
| 957 |
+
all_bases = [get_full_attribute_name(k.value) for k in class_node.bases]
|
| 958 |
+
if any(base is None for base in all_bases):
|
| 959 |
+
raise ValueError(f"Could not parse the name of the bases for {class_node.name.value}")
|
| 960 |
+
|
| 961 |
+
original_node = mapper.classes[renamed_super_class]
|
| 962 |
+
# Always use the new name of the class (in case we use e.g. `ColPaliForRetrieval` inheriting from `PaliGemmaForConditionalGeneration`)
|
| 963 |
+
new_name = class_node.name
|
| 964 |
+
|
| 965 |
+
# If the new class name is different from the renamed super class name, we need to update the docstrings/comments accordingly
|
| 966 |
+
if new_name.value != renamed_super_class:
|
| 967 |
+
common_suffix = common_partial_suffix(new_name.value, renamed_super_class)
|
| 968 |
+
# Note that this works even without common prefix, in which case it does not replace anything
|
| 969 |
+
old, new = renamed_super_class.replace(common_suffix, ""), new_name.value.replace(common_suffix, "")
|
| 970 |
+
temp_module = cst.Module(body=[original_node])
|
| 971 |
+
original_node = temp_module.visit(
|
| 972 |
+
ReplaceNameTransformer(get_lowercase_name(old), get_lowercase_name(new), only_doc=True)
|
| 973 |
+
).body[0]
|
| 974 |
+
|
| 975 |
+
# If we explicitly passed a new base with common suffix to an old base, it is for switching the prefix
|
| 976 |
+
# e.g. if the "natural" parent class is `PreTrainedModel` but we wanted to rename it to `PreTrainedVisionModel`
|
| 977 |
+
additional_bases = [base for base in all_bases if base != original_super_class]
|
| 978 |
+
new_bases = []
|
| 979 |
+
for original_base in original_node.bases:
|
| 980 |
+
new_base = original_base
|
| 981 |
+
# we only potentially switch base for Name-based bases, not Attribute
|
| 982 |
+
if m.matches(original_base.value, m.Name()):
|
| 983 |
+
original_base_name = original_base.value.value
|
| 984 |
+
for additional_base_name in additional_bases:
|
| 985 |
+
suffix = common_partial_suffix(original_base_name, additional_base_name)
|
| 986 |
+
if len(suffix) > 0 and suffix[0].isupper():
|
| 987 |
+
new_name_node = original_base.value.with_changes(value=additional_base_name)
|
| 988 |
+
new_base = original_base.with_changes(value=new_name_node)
|
| 989 |
+
break
|
| 990 |
+
new_bases.append(new_base)
|
| 991 |
+
|
| 992 |
+
original_methods = {
|
| 993 |
+
f.name.value if hasattr(f, "name") else mapper.python_module.code_for_node(f): f
|
| 994 |
+
for f in original_node.body.body
|
| 995 |
+
}
|
| 996 |
+
updated_methods = {
|
| 997 |
+
f.name.value if hasattr(f, "name") else mapper.python_module.code_for_node(f): f for f in class_node.body.body
|
| 998 |
+
}
|
| 999 |
+
end_meth = []
|
| 1000 |
+
|
| 1001 |
+
assign_targets = {}
|
| 1002 |
+
docstring_node = []
|
| 1003 |
+
# Iterate directly from node.body as there can be property/setters with same names which are overwritten when we use a dict
|
| 1004 |
+
for func in original_node.body.body:
|
| 1005 |
+
name = func.name.value if hasattr(func, "name") else mapper.python_module.code_for_node(func)
|
| 1006 |
+
if m.matches(func, m.FunctionDef()) and name in updated_methods and updated_methods[name] is not None:
|
| 1007 |
+
new_params = updated_methods[name].params
|
| 1008 |
+
# Replace the method in the replacement class, preserving decorators
|
| 1009 |
+
kwarg_name = getattr(updated_methods[name].params, "star_kwarg", None)
|
| 1010 |
+
if kwarg_name and kwarg_name.name.value == "super_kwargs":
|
| 1011 |
+
parent_params = {k.name.value: k for k in func.params.params}
|
| 1012 |
+
parent_params.update({k.name.value: k for k in new_params.params[1:]})
|
| 1013 |
+
new_params = new_params.with_changes(
|
| 1014 |
+
params=list(parent_params.values()), star_kwarg=func.params.star_kwarg
|
| 1015 |
+
)
|
| 1016 |
+
# Keep decorators in `modular_xxx.py` if any, else original decorators
|
| 1017 |
+
new_decorators = (
|
| 1018 |
+
updated_methods[name].decorators if len(updated_methods[name].decorators) > 0 else func.decorators
|
| 1019 |
+
)
|
| 1020 |
+
if not re.match(
|
| 1021 |
+
r"\ndef .*\(.*\):\n raise.*Error\(.*",
|
| 1022 |
+
mapper.python_module.code_for_node(updated_methods[name]),
|
| 1023 |
+
):
|
| 1024 |
+
func = func.with_changes(body=updated_methods[name].body, params=new_params, decorators=new_decorators)
|
| 1025 |
+
else:
|
| 1026 |
+
continue
|
| 1027 |
+
|
| 1028 |
+
if m.matches(func, m.SimpleStatementLine(body=[m.Assign()])):
|
| 1029 |
+
target = mapper.python_module.code_for_node(func.body[0].targets[0])
|
| 1030 |
+
assign_targets[target] = func
|
| 1031 |
+
elif m.matches(func, m.SimpleStatementLine(body=[m.AnnAssign()])):
|
| 1032 |
+
target = mapper.python_module.code_for_node(func.body[0].target)
|
| 1033 |
+
assign_targets[target] = func
|
| 1034 |
+
elif m.matches(func, DOCSTRING_NODE):
|
| 1035 |
+
docstring_node = [func]
|
| 1036 |
+
else:
|
| 1037 |
+
end_meth.append(func)
|
| 1038 |
+
|
| 1039 |
+
# Port new methods that are defined only in modular-file and append at the end
|
| 1040 |
+
for func in class_node.body.body:
|
| 1041 |
+
name = func.name.value if hasattr(func, "name") else mapper.python_module.code_for_node(func)
|
| 1042 |
+
if m.matches(func, DOCSTRING_NODE): # This processes the docstring of the class!
|
| 1043 |
+
# Extract the original docstring
|
| 1044 |
+
updated_docstring = func.body[0].value.value
|
| 1045 |
+
if len(docstring_node) == 0: # If the original docstring is empty, just create one from the updated.
|
| 1046 |
+
docstring_node = [
|
| 1047 |
+
cst.SimpleStatementLine(body=[cst.Expr(value=cst.SimpleString(value=updated_docstring))])
|
| 1048 |
+
]
|
| 1049 |
+
else:
|
| 1050 |
+
original_docstring = docstring_node[0].body[0].value.value
|
| 1051 |
+
merged_doc = merge_docstrings(original_docstring, updated_docstring)
|
| 1052 |
+
# Update the docstring in the original function
|
| 1053 |
+
docstring_node = [
|
| 1054 |
+
docstring_node[0].with_changes(body=[cst.Expr(value=cst.SimpleString(value=merged_doc))])
|
| 1055 |
+
]
|
| 1056 |
+
if name not in original_methods and func is not None and isinstance(func, cst.FunctionDef):
|
| 1057 |
+
end_meth.append(func)
|
| 1058 |
+
if m.matches(func, m.SimpleStatementLine(body=[m.Assign()])):
|
| 1059 |
+
# TODO we only use single assign might cause issues
|
| 1060 |
+
target = mapper.python_module.code_for_node(func.body[0].targets[0])
|
| 1061 |
+
assign_targets[target] = func
|
| 1062 |
+
if m.matches(func, m.SimpleStatementLine(body=[m.AnnAssign()])):
|
| 1063 |
+
target = mapper.python_module.code_for_node(func.body[0].target)
|
| 1064 |
+
assign_targets[target] = func
|
| 1065 |
+
end_meth = docstring_node + list(assign_targets.values()) + end_meth
|
| 1066 |
+
|
| 1067 |
+
# Replace the calls to `super()` with the unrolled code
|
| 1068 |
+
result_node = original_node.with_changes(body=cst.IndentedBlock(body=end_meth))
|
| 1069 |
+
temp_module = cst.Module(body=[result_node])
|
| 1070 |
+
new_module = MetadataWrapper(temp_module)
|
| 1071 |
+
new_replacement_class = new_module.visit(
|
| 1072 |
+
SuperTransformer(temp_module, original_methods, updated_methods, all_bases)
|
| 1073 |
+
)
|
| 1074 |
+
new_replacement_body = new_replacement_class.body[0].body # get the indented block
|
| 1075 |
+
|
| 1076 |
+
# Use decorators redefined in `modular_xxx.py` if any
|
| 1077 |
+
new_decorators = class_node.decorators if len(class_node.decorators) > 0 else original_node.decorators
|
| 1078 |
+
|
| 1079 |
+
return original_node.with_changes(
|
| 1080 |
+
body=new_replacement_body, decorators=new_decorators, bases=new_bases, name=new_name
|
| 1081 |
+
)
|
| 1082 |
+
|
| 1083 |
+
|
| 1084 |
+
TYPE_TO_FILE_TYPE = {
|
| 1085 |
+
"Config": "configuration",
|
| 1086 |
+
"Tokenizer": "tokenization",
|
| 1087 |
+
"Processor": "processing",
|
| 1088 |
+
"ImageProcessor": "image_processing",
|
| 1089 |
+
"ImageProcessorFast": "image_processing*_fast", # "*" indicates where to insert the model name before the "_fast" suffix
|
| 1090 |
+
"FastImageProcessorKwargs": "image_processing*_fast",
|
| 1091 |
+
"FeatureExtractor": "feature_extractor",
|
| 1092 |
+
"ProcessorKwargs": "processing",
|
| 1093 |
+
"ImagesKwargs": "processing",
|
| 1094 |
+
"TextKwargs": "processing",
|
| 1095 |
+
}
|
| 1096 |
+
|
| 1097 |
+
|
| 1098 |
+
def find_file_type(class_name: str) -> str:
|
| 1099 |
+
"""Based on a class name, find the file type corresponding to the class.
|
| 1100 |
+
If the class name is `LlamaConfig` it will return `configuration`.
|
| 1101 |
+
The list of suffixes is in `TYPE_TO_FILE_TYPE`. If there are no match, we match by default to `modeling`
|
| 1102 |
+
"""
|
| 1103 |
+
match_pattern = "|".join(TYPE_TO_FILE_TYPE.keys())
|
| 1104 |
+
match = re.search(rf"({match_pattern})$", class_name)
|
| 1105 |
+
if match:
|
| 1106 |
+
file_type = TYPE_TO_FILE_TYPE[match.group(1)]
|
| 1107 |
+
else:
|
| 1108 |
+
file_type = "modeling"
|
| 1109 |
+
return file_type
|
| 1110 |
+
|
| 1111 |
+
|
| 1112 |
+
# These top-level variables will always appear at the very beginning of the file, in the order they are defined in
|
| 1113 |
+
# this list (this is to avoid having variables at weird places, even if they are not used before)
|
| 1114 |
+
VARIABLES_AT_THE_BEGINNING = (
|
| 1115 |
+
"logger",
|
| 1116 |
+
"_CHECKPOINT_FOR_DOC",
|
| 1117 |
+
"_CONFIG_FOR_DOC",
|
| 1118 |
+
)
|
| 1119 |
+
|
| 1120 |
+
# These specific modeling imports should not be visited as other modeling files
|
| 1121 |
+
IMPORTS_TO_SKIP_IN_MODULAR = ("auto.modeling_auto",)
|
| 1122 |
+
|
| 1123 |
+
|
| 1124 |
+
def append_new_import_node(
|
| 1125 |
+
node: cst.CSTNode, unused_imports: set[str], added_names: set, imports_to_keep: list[cst.CSTNode]
|
| 1126 |
+
):
|
| 1127 |
+
"""Insert the new `node` to the list of `imports_to_keep` in-place, if it is not part of the `unused_imports` or `added_names`.
|
| 1128 |
+
Also modifies `added_names` in-place accordingly."""
|
| 1129 |
+
import_node = node.body[0]
|
| 1130 |
+
names_to_keep = []
|
| 1131 |
+
for name in import_node.names:
|
| 1132 |
+
name_value = name.evaluated_name
|
| 1133 |
+
if name_value not in unused_imports and name_value not in added_names:
|
| 1134 |
+
names_to_keep.append(name.with_changes(comma=cst.MaybeSentinel.DEFAULT))
|
| 1135 |
+
added_names.add(name_value)
|
| 1136 |
+
if len(names_to_keep) > 0:
|
| 1137 |
+
new_node = node.with_changes(body=[import_node.with_changes(names=names_to_keep)])
|
| 1138 |
+
imports_to_keep.append(new_node)
|
| 1139 |
+
|
| 1140 |
+
|
| 1141 |
+
def get_needed_imports(body: dict[str, dict], all_imports: list[cst.CSTNode]) -> list[cst.CSTNode]:
|
| 1142 |
+
"""Get all the imports needed in the `body`, from the list of `all_imports`.
|
| 1143 |
+
`body` is a dict with the following structure `{str: {"insert_idx": int, "node": cst.CSTNode}}`.
|
| 1144 |
+
Note: we need to use `isinstance` on scope assignements, m.matches apparently does not work here yet!
|
| 1145 |
+
"""
|
| 1146 |
+
new_body = [k[1]["node"] for k in sorted(body.items(), key=lambda x: x[1]["insert_idx"])]
|
| 1147 |
+
wrapper = MetadataWrapper(cst.Module(body=all_imports + new_body))
|
| 1148 |
+
scopes = set(wrapper.resolve(ScopeProvider).values())
|
| 1149 |
+
unused_imports = set()
|
| 1150 |
+
import_ref_count = defaultdict(lambda: 0)
|
| 1151 |
+
for scope in scopes:
|
| 1152 |
+
for assignment in scope.assignments:
|
| 1153 |
+
node = assignment.node
|
| 1154 |
+
if isinstance(assignment, cst.metadata.Assignment) and isinstance(node, (cst.Import, cst.ImportFrom)):
|
| 1155 |
+
ref_count = len(assignment.references)
|
| 1156 |
+
name = assignment.name
|
| 1157 |
+
import_ref_count[name] = max(ref_count, import_ref_count[name])
|
| 1158 |
+
# Similar imports may be redefined, and only used between their 1st and 2nd definition so if we already have
|
| 1159 |
+
# a ref count > 0 at any point, the imports is actually used
|
| 1160 |
+
unused_imports = {name for name, count in import_ref_count.items() if count <= 0 or name in body.keys()}
|
| 1161 |
+
|
| 1162 |
+
imports_to_keep = []
|
| 1163 |
+
# We need to keep track of which names were already imported, because some import may be duplicated from multiple sources
|
| 1164 |
+
# or be both protected and unprotected due to inconsistency between models
|
| 1165 |
+
added_names = set()
|
| 1166 |
+
existing_protected_statements = set() # str repr of the import nodes - does not work with the nodes directly
|
| 1167 |
+
for node in all_imports:
|
| 1168 |
+
if m.matches(node, m.If()): # handle safe imports
|
| 1169 |
+
new_statements = []
|
| 1170 |
+
for stmt_node in node.body.body:
|
| 1171 |
+
append_new_import_node(stmt_node, unused_imports, added_names, new_statements)
|
| 1172 |
+
new_statements = [stmt for stmt in new_statements if str(stmt) not in existing_protected_statements]
|
| 1173 |
+
if len(new_statements) > 0:
|
| 1174 |
+
new_node = node.with_changes(body=node.body.with_changes(body=new_statements))
|
| 1175 |
+
imports_to_keep.append(new_node)
|
| 1176 |
+
existing_protected_statements.update({str(stmt) for stmt in new_statements})
|
| 1177 |
+
else:
|
| 1178 |
+
append_new_import_node(node, unused_imports, added_names, imports_to_keep)
|
| 1179 |
+
|
| 1180 |
+
protected_import_nodes = [node for node in imports_to_keep if m.matches(node, m.If())]
|
| 1181 |
+
usual_import_nodes = [node for node in imports_to_keep if not m.matches(node, m.If())]
|
| 1182 |
+
|
| 1183 |
+
# Protected imports always appear at the end of all imports
|
| 1184 |
+
return usual_import_nodes + protected_import_nodes
|
| 1185 |
+
|
| 1186 |
+
|
| 1187 |
+
def split_all_assignment(node: cst.CSTNode) -> dict[str, cst.CSTNode]:
|
| 1188 |
+
"""Split the `__all__` assignment found in the modular between each corresponding files."""
|
| 1189 |
+
all_all_per_file = {}
|
| 1190 |
+
assign_node = node.body[0]
|
| 1191 |
+
if isinstance(assign_node.value, cst.List):
|
| 1192 |
+
# Extract the elements from the list
|
| 1193 |
+
all_all_to_add = defaultdict(list)
|
| 1194 |
+
for element in assign_node.value.elements:
|
| 1195 |
+
if isinstance(element.value, cst.SimpleString):
|
| 1196 |
+
# Remove quotes and add the string to the elements list
|
| 1197 |
+
class_name = element.value.value
|
| 1198 |
+
file = find_file_type(element.value.evaluated_value)
|
| 1199 |
+
all_all_to_add[file] += [class_name]
|
| 1200 |
+
for file, new_alls in all_all_to_add.items():
|
| 1201 |
+
new_node = assign_node.with_changes(
|
| 1202 |
+
value=cst.List(elements=[cst.Element(value=cst.SimpleString(value=k)) for k in new_alls])
|
| 1203 |
+
)
|
| 1204 |
+
all_all_per_file[file] = node.with_changes(body=[new_node])
|
| 1205 |
+
return all_all_per_file
|
| 1206 |
+
|
| 1207 |
+
|
| 1208 |
+
class ModularFileMapper(ModuleMapper):
|
| 1209 |
+
"""This is a Mapper to visit a modular file (like `modular_llama.py`). It visits the whole file, recording dependency,
|
| 1210 |
+
then visits all imported modeling files (like `modeling_llama.py`), and manages their mutual dependencies.
|
| 1211 |
+
Calling the method `create_modules()` after visit will create all modules based on this modular file.
|
| 1212 |
+
"""
|
| 1213 |
+
|
| 1214 |
+
def __init__(self, python_module, new_name):
|
| 1215 |
+
super().__init__(python_module)
|
| 1216 |
+
# fmt: off
|
| 1217 |
+
self.model_name = new_name # name of the model being defined. Should be in the format of `llama` or `layout_xlm` or `phi3`
|
| 1218 |
+
|
| 1219 |
+
self.model_specific_imported_objects: Dict[str, str] = {} # e.g. {"LlamaModel": "transformers.models.llama.modeling_llama"}
|
| 1220 |
+
self.model_specific_modules: Dict[str, cst.Module] = {} # e.g. {"transformers.models.llama.modeling_llama": cst.Module}
|
| 1221 |
+
|
| 1222 |
+
self.all_all_to_add = {}
|
| 1223 |
+
# fmt: on
|
| 1224 |
+
|
| 1225 |
+
def visit_ImportFrom(self, node: cst.ImportFrom) -> None:
|
| 1226 |
+
"""When visiting imports from modeling files (i.e. `transformers.models.xxx`) we get the code, parse it,
|
| 1227 |
+
and save it in `self.model_specific_modules` to later visit. The imported objects are saved in `self.model_specific_imported_objects`.
|
| 1228 |
+
"""
|
| 1229 |
+
import_module = self.python_module.code_for_node(node.module)
|
| 1230 |
+
import_statement = "." * len(node.relative) + import_module
|
| 1231 |
+
if any(import_to_skip in import_statement for import_to_skip in IMPORTS_TO_SKIP_IN_MODULAR):
|
| 1232 |
+
return
|
| 1233 |
+
if m.matches(node.module, m.Attribute()):
|
| 1234 |
+
for imported_ in node.names:
|
| 1235 |
+
_import = re.search(
|
| 1236 |
+
rf"(?:transformers\.models\.)|(?:\.\.)\w+\.({self.match_patterns})_.*", import_statement
|
| 1237 |
+
)
|
| 1238 |
+
if _import:
|
| 1239 |
+
source = _import.group(1)
|
| 1240 |
+
if source == "modeling" and "Config" in self.python_module.code_for_node(imported_):
|
| 1241 |
+
raise ValueError(
|
| 1242 |
+
f"You are importing {self.python_module.code_for_node(imported_)} from the modeling file. Import from the `configuration_xxxx.py` file instead"
|
| 1243 |
+
)
|
| 1244 |
+
if import_module not in self.model_specific_modules:
|
| 1245 |
+
if "models" not in import_module:
|
| 1246 |
+
import_module = "models." + import_module
|
| 1247 |
+
if "transformers" not in import_module:
|
| 1248 |
+
import_module = "transformers." + import_module
|
| 1249 |
+
source_code = get_module_source_from_name(import_module)
|
| 1250 |
+
tree = cst.parse_module(source_code)
|
| 1251 |
+
self.model_specific_modules[import_module] = tree
|
| 1252 |
+
imported_object = self.python_module.code_for_node(imported_.name)
|
| 1253 |
+
self.model_specific_imported_objects[imported_object] = import_module
|
| 1254 |
+
if m.matches(node.module, m.Name()):
|
| 1255 |
+
if "transformers" == import_module:
|
| 1256 |
+
raise ValueError(
|
| 1257 |
+
f"You are importing from {import_module} directly using global imports. Import from the correct local path"
|
| 1258 |
+
)
|
| 1259 |
+
|
| 1260 |
+
def visit_SimpleStatementLine(self, node):
|
| 1261 |
+
"""If we visit an import statement not previously visited, record it. If we visit a module-scope assignment,
|
| 1262 |
+
simply record it or, if it is `__all__`, split it between files where we should dispatch it.
|
| 1263 |
+
"""
|
| 1264 |
+
parent_node = self.get_metadata(cst.metadata.ParentNodeProvider, node)
|
| 1265 |
+
simple_top_level_assign_structure = m.SimpleStatementLine(
|
| 1266 |
+
body=[m.Assign(targets=[m.AssignTarget(target=m.Name())])]
|
| 1267 |
+
)
|
| 1268 |
+
if m.matches(parent_node, m.Module()):
|
| 1269 |
+
if m.matches(node, m.SimpleStatementLine(body=[m.Import()])):
|
| 1270 |
+
self.imports.append(node)
|
| 1271 |
+
elif m.matches(node, m.SimpleStatementLine(body=[m.ImportFrom()])):
|
| 1272 |
+
import_module = self.python_module.code_for_node(node.body[0].module)
|
| 1273 |
+
import_statement = "." * len(node.body[0].relative) + import_module
|
| 1274 |
+
if not (
|
| 1275 |
+
re.search(rf"(?:transformers\.models\.)|(?:\.\.)\w+\.({self.match_patterns})_.*", import_statement)
|
| 1276 |
+
and not any(import_to_skip in import_statement for import_to_skip in IMPORTS_TO_SKIP_IN_MODULAR)
|
| 1277 |
+
):
|
| 1278 |
+
self.imports.append(node)
|
| 1279 |
+
elif m.matches(node, simple_top_level_assign_structure):
|
| 1280 |
+
assigned_variable = node.body[0].targets[0].target.value
|
| 1281 |
+
# __all__ is treated differently and not added to general assignments
|
| 1282 |
+
if assigned_variable == "__all__":
|
| 1283 |
+
self.all_all_to_add = split_all_assignment(node)
|
| 1284 |
+
else:
|
| 1285 |
+
self.current_assignment = assigned_variable
|
| 1286 |
+
self.assignments[assigned_variable] = node
|
| 1287 |
+
|
| 1288 |
+
def leave_Module(self, node):
|
| 1289 |
+
"""When we leave the modular file, we do the following in order:
|
| 1290 |
+
1. for each modeling file found in the imports, rename it with the new model name, visit it, and update
|
| 1291 |
+
its dependency graph with the new function and assignment definitions found in the modular
|
| 1292 |
+
2. update the modular dependency graph with the imported functions and assignments (found when visiting the matching files)
|
| 1293 |
+
3. compute the nested (recursive) function and assignment dependencies
|
| 1294 |
+
"""
|
| 1295 |
+
# Takes care of finalizing our visit
|
| 1296 |
+
super().leave_Module(node)
|
| 1297 |
+
|
| 1298 |
+
# 1. for each modeling file found in the imports, rename it with the new model name, visit it, and update dependencies
|
| 1299 |
+
self.visited_modules = {}
|
| 1300 |
+
self.renamers = {}
|
| 1301 |
+
name_prefixes = self.infer_new_model_name()
|
| 1302 |
+
for file, module in self.model_specific_modules.items():
|
| 1303 |
+
file_model_name = file.split(".")[-2]
|
| 1304 |
+
new_name = name_prefixes[file]
|
| 1305 |
+
renamer = ReplaceNameTransformer(file_model_name, new_name, self.model_name)
|
| 1306 |
+
renamed_module = module.visit(renamer)
|
| 1307 |
+
self.visited_modules[file] = ModelFileMapper.visit_and_merge_dependencies(
|
| 1308 |
+
renamed_module,
|
| 1309 |
+
self.classes,
|
| 1310 |
+
self.functions,
|
| 1311 |
+
self.assignments,
|
| 1312 |
+
self.object_dependency_mapping,
|
| 1313 |
+
self.start_lines,
|
| 1314 |
+
)
|
| 1315 |
+
# We record it so that we can rename classes later the exact same way
|
| 1316 |
+
self.renamers[file] = renamer
|
| 1317 |
+
|
| 1318 |
+
# 2. in turn, we need to add the imported functions/assignments to the dependencies of the modular mapper, using the
|
| 1319 |
+
# definitions found in the visited files
|
| 1320 |
+
self.merge_model_specific_imports(self.visited_modules)
|
| 1321 |
+
|
| 1322 |
+
# 3. compute the nested (recursive) function and assignment dependencies
|
| 1323 |
+
self.object_recursive_dependency_mapping = self._compute_recursive_object_dependencies()
|
| 1324 |
+
|
| 1325 |
+
# We need to keep track of which objects were imported directly into which modeling file to not add them wrongly later
|
| 1326 |
+
# Note that we may visit several of the same file types, thus we save them per file type, not file
|
| 1327 |
+
self.imported_objects_per_file = defaultdict(set)
|
| 1328 |
+
for file, mapper in self.visited_modules.items():
|
| 1329 |
+
file_type = re.search(rf"^transformers\.models\.\w+\.({self.match_patterns})_.*", file).group(1)
|
| 1330 |
+
self.imported_objects_per_file[file_type].update(mapper.objects_imported_from_modeling)
|
| 1331 |
+
|
| 1332 |
+
def merge_model_specific_imports(self, visited_modules):
|
| 1333 |
+
"""Merge the functions and assignments imported from the modeling files to the modular nodes and dependency graph,
|
| 1334 |
+
based on the visited files."""
|
| 1335 |
+
self.start_lines_file_mapping = {}
|
| 1336 |
+
self.added_objects_file_mapping = {}
|
| 1337 |
+
for object_name, file in self.model_specific_imported_objects.items():
|
| 1338 |
+
visited_module = visited_modules[file]
|
| 1339 |
+
self.start_lines_file_mapping[file] = visited_module.start_lines
|
| 1340 |
+
# Add functions and their dependencies
|
| 1341 |
+
if object_name in visited_module.functions and object_name not in self.functions:
|
| 1342 |
+
self.functions[object_name] = visited_module.functions[object_name]
|
| 1343 |
+
self.added_objects_file_mapping[object_name] = file
|
| 1344 |
+
dependencies = visited_module.object_dependency_mapping.get(object_name, None)
|
| 1345 |
+
if dependencies is not None:
|
| 1346 |
+
self.object_dependency_mapping[object_name] = dependencies
|
| 1347 |
+
for dep in dependencies:
|
| 1348 |
+
if dep not in self.global_nodes:
|
| 1349 |
+
self.added_objects_file_mapping[dep] = file
|
| 1350 |
+
self.functions[dep] = visited_module.global_nodes[dep]
|
| 1351 |
+
|
| 1352 |
+
# Add/overwrite the imported functions to other visited modules as well, in case it is absent/different
|
| 1353 |
+
# in he modeling source file of the inherited class. See `examples/modular-tranformers/modular_switch_function.py`
|
| 1354 |
+
# and `examples/modular-tranformers/modular_add_function.py` for examples
|
| 1355 |
+
recursive_dependencies = visited_module.object_recursive_dependency_mapping.get(object_name, set())
|
| 1356 |
+
node_recursive_dependencies_mapping = {
|
| 1357 |
+
dep: visited_module.global_nodes[dep] for dep in recursive_dependencies
|
| 1358 |
+
}
|
| 1359 |
+
for filename, module_mapper in self.visited_modules.items():
|
| 1360 |
+
if filename != file:
|
| 1361 |
+
module_mapper.global_nodes[object_name] = visited_module.functions[object_name]
|
| 1362 |
+
if len(recursive_dependencies) > 0:
|
| 1363 |
+
module_mapper.object_recursive_dependency_mapping[object_name] = recursive_dependencies
|
| 1364 |
+
module_mapper.global_nodes.update(node_recursive_dependencies_mapping)
|
| 1365 |
+
|
| 1366 |
+
# Add assignments and their dependencies
|
| 1367 |
+
elif object_name in visited_module.assignments and object_name not in self.assignments:
|
| 1368 |
+
self.assignments[object_name] = visited_module.assignments[object_name]
|
| 1369 |
+
self.added_objects_file_mapping[object_name] = file
|
| 1370 |
+
dependencies = visited_module.object_dependency_mapping.get(object_name, None)
|
| 1371 |
+
if dependencies is not None:
|
| 1372 |
+
self.object_dependency_mapping[object_name] = dependencies
|
| 1373 |
+
for dep in dependencies:
|
| 1374 |
+
if dep not in self.global_nodes:
|
| 1375 |
+
self.added_objects_file_mapping[dep] = file
|
| 1376 |
+
self.assignments[dep] = visited_module.global_nodes[dep]
|
| 1377 |
+
|
| 1378 |
+
# Do not forget to re-assign all nodes after the merge
|
| 1379 |
+
self.global_nodes = {**self.assignments, **self.classes, **self.functions}
|
| 1380 |
+
# And restric dependencies to those nodes only
|
| 1381 |
+
self._restrict_dependencies_to_known_entities()
|
| 1382 |
+
|
| 1383 |
+
def compute_relative_order(self, missing_dependencies: set) -> dict[str, int]:
|
| 1384 |
+
"""Compute in which relative order the `missing_dependencies` should appear when the nodes are added to the final file that
|
| 1385 |
+
will be created based on the modular.
|
| 1386 |
+
"""
|
| 1387 |
+
relative_order = {}
|
| 1388 |
+
idx = 0
|
| 1389 |
+
|
| 1390 |
+
original_dependencies = []
|
| 1391 |
+
other_files_dependencies = defaultdict(list)
|
| 1392 |
+
for dep in tuple(missing_dependencies):
|
| 1393 |
+
if dep in self.added_objects_file_mapping:
|
| 1394 |
+
file = self.added_objects_file_mapping[dep]
|
| 1395 |
+
other_files_dependencies[file].append(dep)
|
| 1396 |
+
else:
|
| 1397 |
+
original_dependencies.append(dep)
|
| 1398 |
+
# Sort all lists according to the order in their respective file
|
| 1399 |
+
all_dependencies = []
|
| 1400 |
+
for file, dependencies in other_files_dependencies.items():
|
| 1401 |
+
sorted_dependencies = sorted(dependencies, key=lambda x: self.start_lines_file_mapping[file][x])
|
| 1402 |
+
all_dependencies += sorted_dependencies
|
| 1403 |
+
all_dependencies += sorted(original_dependencies, key=lambda x: self.start_lines[x])
|
| 1404 |
+
|
| 1405 |
+
# Add all original node first, then merged ones (one file at a time)
|
| 1406 |
+
for dep in all_dependencies:
|
| 1407 |
+
relative_order[dep] = idx
|
| 1408 |
+
idx += 1
|
| 1409 |
+
|
| 1410 |
+
return relative_order
|
| 1411 |
+
|
| 1412 |
+
def infer_new_model_name(self) -> dict:
|
| 1413 |
+
"""Infer whether we are using a model name prefix different from the usual model name as defined from the filename.
|
| 1414 |
+
This is useful e.g. when we define a new multi-modal model, and only the text part inherits from `LlamaModel`,
|
| 1415 |
+
so we have something like:
|
| 1416 |
+
```python
|
| 1417 |
+
class NewModelNameTextDecoderLayer(LlamaDecoderLayer):
|
| 1418 |
+
pass
|
| 1419 |
+
```
|
| 1420 |
+
with the `Text` prefix added to the model name.
|
| 1421 |
+
However, in case of multiple prefix used, we raise a warning and use the most frequent prefix, to avoid parsing
|
| 1422 |
+
the same file multiple times and inconsistencies in the objects added from dependencies.
|
| 1423 |
+
If the new prefix collides with a prefix of another class in the file where we are importing from, then we also
|
| 1424 |
+
raise a warning, and use the default prefix (model name) to avoid collisions in dependencies.
|
| 1425 |
+
"""
|
| 1426 |
+
prefix_model_name_mapping = defaultdict(Counter)
|
| 1427 |
+
cased_default_name = get_cased_name(self.model_name)
|
| 1428 |
+
# Iterate over all new classes to get modeling super classes
|
| 1429 |
+
for class_name, class_node in self.classes.items():
|
| 1430 |
+
modeling_bases = [
|
| 1431 |
+
k.value.value for k in class_node.bases if k.value.value in self.model_specific_imported_objects
|
| 1432 |
+
]
|
| 1433 |
+
if len(modeling_bases) > 1:
|
| 1434 |
+
raise ValueError(
|
| 1435 |
+
f"{class_name} was defined with more than 1 model-specific super class. This is unsupported. We found {(*modeling_bases,)}."
|
| 1436 |
+
)
|
| 1437 |
+
if len(modeling_bases) == 1:
|
| 1438 |
+
filename = self.model_specific_imported_objects[modeling_bases[0]]
|
| 1439 |
+
cased_model_name = cased_default_name # the default name prefix
|
| 1440 |
+
suffix = common_partial_suffix(class_name, modeling_bases[0])
|
| 1441 |
+
if len(suffix) > 0 and suffix[0].isupper():
|
| 1442 |
+
cased_model_name = class_name.replace(suffix, "")
|
| 1443 |
+
prefix_model_name_mapping[filename].update([cased_model_name])
|
| 1444 |
+
|
| 1445 |
+
# Check if we found multiple prefixes for some modeling files
|
| 1446 |
+
final_name_mapping = {}
|
| 1447 |
+
for file, prefixes_counter in prefix_model_name_mapping.items():
|
| 1448 |
+
if len(prefixes_counter) > 1:
|
| 1449 |
+
_, total = prefixes_counter.most_common(1)[0]
|
| 1450 |
+
most_used_entities = [name for name, count in prefixes_counter.most_common() if count == total]
|
| 1451 |
+
# if the default name is in the pool of equally used prefixes, use it, otherwise last encountered
|
| 1452 |
+
final_name = cased_default_name if cased_default_name in most_used_entities else most_used_entities[-1]
|
| 1453 |
+
else:
|
| 1454 |
+
final_name = list(prefixes_counter)[0]
|
| 1455 |
+
# Check if the prefix can be used without collisions in the names
|
| 1456 |
+
old_cased_model_name = get_cased_name(file.split(".")[-2])
|
| 1457 |
+
old_model_name_prefix = final_name.replace(cased_default_name, old_cased_model_name)
|
| 1458 |
+
# Raise adequate warning depending on the situation
|
| 1459 |
+
has_prefix_collision = f"\nclass {old_model_name_prefix}" in get_module_source_from_name(file)
|
| 1460 |
+
if final_name != cased_default_name and has_prefix_collision:
|
| 1461 |
+
if len(prefixes_counter) > 1:
|
| 1462 |
+
logger.warning(
|
| 1463 |
+
f"We detected multiple prefix names when inheriting from {file}: {(*set(prefixes_counter),)}. However, the "
|
| 1464 |
+
f"most used one, '{final_name}', is already present in the source file and will likely cause consistency "
|
| 1465 |
+
f"issues. For this reason we fallback to the default prefix '{cased_default_name}' when grabbing args "
|
| 1466 |
+
"and dependencies. Make sure to subclass the intermediate classes with the prefix you want (if different "
|
| 1467 |
+
f"from '{cased_default_name}') or use a single prefix in all the modular (best)."
|
| 1468 |
+
)
|
| 1469 |
+
else:
|
| 1470 |
+
logger.warning(
|
| 1471 |
+
f"We detected the use of the new default prefix {final_name} when inheriting from {file}. However, it is "
|
| 1472 |
+
"already present in the source file and will likely cause consistency issues. For this reason we fallback "
|
| 1473 |
+
f"to the default prefix '{cased_default_name}' when grabbing args and dependencies. Make sure to subclass "
|
| 1474 |
+
f"the intermediate classes with the prefix you want (if different from '{cased_default_name}')"
|
| 1475 |
+
)
|
| 1476 |
+
final_name = cased_default_name
|
| 1477 |
+
elif len(prefixes_counter) > 1:
|
| 1478 |
+
logger.warning(
|
| 1479 |
+
f"We detected multiple prefix names when inheriting from {file}: {(*set(prefixes_counter),)}. We will only "
|
| 1480 |
+
f"use the most used '{final_name}' prefix when grabbing args and dependencies. Make sure to subclass the "
|
| 1481 |
+
f"intermediate classes with the prefix you want (if different from '{final_name}') or use a single prefix "
|
| 1482 |
+
"in all the modular (best)."
|
| 1483 |
+
)
|
| 1484 |
+
final_name_mapping[file] = get_lowercase_name(final_name)
|
| 1485 |
+
|
| 1486 |
+
# Check we are not missing imported files
|
| 1487 |
+
for file in self.model_specific_modules.keys():
|
| 1488 |
+
if file not in final_name_mapping.keys():
|
| 1489 |
+
final_name_mapping[file] = self.model_name
|
| 1490 |
+
|
| 1491 |
+
return final_name_mapping
|
| 1492 |
+
|
| 1493 |
+
|
| 1494 |
+
def check_dependencies_and_create_import_node(
|
| 1495 |
+
file_type: str, new_dependencies: set[str], mapper: ModuleMapper, new_name: str
|
| 1496 |
+
) -> tuple[set[str], dict[str, cst.CSTNode]]:
|
| 1497 |
+
"""Check that all class nodes in the `new_dependencies` belong to the correct `file_type`. If this is not the case,
|
| 1498 |
+
we need to remove it from the dependencies, and create a new import to it instead.
|
| 1499 |
+
This scenario may appear in the following case:
|
| 1500 |
+
If a new class in the `modular_xxx.py` file does not belong to `type_xxx.py`, but is used somewhere in `other_type_xxx.py`
|
| 1501 |
+
(e.g. as a type hint), but none of the visited files had a similar class, then it would be imported in `type_xxx.py` as
|
| 1502 |
+
part of the standard dependency graph (because we never encountered an import towards this new class in any file).
|
| 1503 |
+
For example imagine the following `modular.py`:
|
| 1504 |
+
```
|
| 1505 |
+
from ..llama.modeling_llama import LlamaModel
|
| 1506 |
+
|
| 1507 |
+
class NewNameTextConfig(PretrainedConfig):
|
| 1508 |
+
...
|
| 1509 |
+
|
| 1510 |
+
class NewNameConfig(PretrainedConfig):
|
| 1511 |
+
...
|
| 1512 |
+
|
| 1513 |
+
class NewNameModel(LlamaModel):
|
| 1514 |
+
config = NewNameConfig()
|
| 1515 |
+
text_config = NewNameTextConfig()
|
| 1516 |
+
...
|
| 1517 |
+
```
|
| 1518 |
+
then without the help of this function, `NewNameTextConfig` would be imported in the `modeling_newname.py` as well as
|
| 1519 |
+
`configuration_newname.py`, because `modeling_llama.py` tells us to not import `NewNameConfig`, but has no
|
| 1520 |
+
knowledge of `NewNameTextConfig`.
|
| 1521 |
+
"""
|
| 1522 |
+
class_dependencies = {dep for dep in new_dependencies if m.matches(mapper.global_nodes[dep], m.ClassDef())}
|
| 1523 |
+
corrected_dependencies = new_dependencies.copy()
|
| 1524 |
+
new_imports = {}
|
| 1525 |
+
for class_name in class_dependencies:
|
| 1526 |
+
class_file_type = find_file_type(class_name)
|
| 1527 |
+
# In this case, we need to remove it from the dependencies and create a new import instead
|
| 1528 |
+
if class_file_type != file_type:
|
| 1529 |
+
corrected_dependencies.remove(class_name)
|
| 1530 |
+
import_statement = f"from .{class_file_type}_{new_name} import {class_name}"
|
| 1531 |
+
new_imports[class_name] = cst.parse_statement(import_statement)
|
| 1532 |
+
|
| 1533 |
+
return corrected_dependencies, new_imports
|
| 1534 |
+
|
| 1535 |
+
|
| 1536 |
+
def get_class_node_and_dependencies(
|
| 1537 |
+
modular_mapper: ModularFileMapper, class_name: str, node: cst.CSTNode, files: dict[str, dict]
|
| 1538 |
+
) -> tuple[dict, str, dict]:
|
| 1539 |
+
"""Return a single class node (and all its dependency nodes), to be added to the `files`. It creates the new
|
| 1540 |
+
class node based on the inherited classes if needed. Also returns any new imports of a new class defined in
|
| 1541 |
+
the modular that we nay need.
|
| 1542 |
+
"""
|
| 1543 |
+
# An exception was already raised if this has len > 1
|
| 1544 |
+
model_specific_bases = [
|
| 1545 |
+
k.value.value for k in node.bases if k.value.value in modular_mapper.model_specific_imported_objects
|
| 1546 |
+
]
|
| 1547 |
+
super_class = model_specific_bases[0] if len(model_specific_bases) == 1 else None
|
| 1548 |
+
|
| 1549 |
+
file_type = find_file_type(class_name)
|
| 1550 |
+
file_to_update = files[file_type]
|
| 1551 |
+
model_name = modular_mapper.model_name
|
| 1552 |
+
|
| 1553 |
+
# This is used to avoid adding objects to the dependencies graph if they will be imported already
|
| 1554 |
+
imported_objects = modular_mapper.imported_objects_per_file[file_type]
|
| 1555 |
+
|
| 1556 |
+
# We need to replace the class node with the transformers (modeling file) super class node
|
| 1557 |
+
if super_class is not None:
|
| 1558 |
+
super_file_name = modular_mapper.model_specific_imported_objects[super_class]
|
| 1559 |
+
|
| 1560 |
+
# Get the mapper corresponding to the inherited class
|
| 1561 |
+
mapper = modular_mapper.visited_modules[super_file_name]
|
| 1562 |
+
# Rename the super class according to the exact same rule we used when renaming the whole module
|
| 1563 |
+
renamer = modular_mapper.renamers[super_file_name]
|
| 1564 |
+
renamed_super_class = preserve_case_replace(super_class, renamer.patterns, renamer.cased_new_name)
|
| 1565 |
+
|
| 1566 |
+
# Create the new class node
|
| 1567 |
+
updated_node = replace_class_node(mapper, node, renamed_super_class, super_class)
|
| 1568 |
+
|
| 1569 |
+
# Grab all immediate dependencies of the new node
|
| 1570 |
+
new_node_dependencies = augmented_dependencies_for_class_node(updated_node, mapper, imported_objects)
|
| 1571 |
+
|
| 1572 |
+
# At this point, if any class dependency is found, but belongs to another file, it means that we need to remove
|
| 1573 |
+
# it from the dependencies, and add a new import of it instead
|
| 1574 |
+
new_node_dependencies, new_imports = check_dependencies_and_create_import_node(
|
| 1575 |
+
file_type, new_node_dependencies, mapper, model_name
|
| 1576 |
+
)
|
| 1577 |
+
|
| 1578 |
+
# The node was modified -> look for all recursive dependencies of the new node
|
| 1579 |
+
all_dependencies_to_add = find_all_dependencies(
|
| 1580 |
+
dependency_mapping=mapper.class_dependency_mapping,
|
| 1581 |
+
initial_dependencies=new_node_dependencies,
|
| 1582 |
+
initial_checked_dependencies=set(file_to_update.keys()),
|
| 1583 |
+
)
|
| 1584 |
+
|
| 1585 |
+
relative_dependency_order = mapper.compute_relative_order(all_dependencies_to_add)
|
| 1586 |
+
nodes_to_add = {
|
| 1587 |
+
dep: (relative_dependency_order[dep], mapper.global_nodes[dep]) for dep in all_dependencies_to_add
|
| 1588 |
+
}
|
| 1589 |
+
|
| 1590 |
+
# No transformers (modeling file) super class, just check functions and assignments dependencies
|
| 1591 |
+
else:
|
| 1592 |
+
updated_node = node
|
| 1593 |
+
# The node was NOT modified -> no need to look recursively for other class dependencies. Indeed, even if they are not
|
| 1594 |
+
# already defined (which would mean a weird order of the code in the modular...), they will be in the future
|
| 1595 |
+
all_dependencies_to_add = augmented_dependencies_for_class_node(updated_node, modular_mapper, imported_objects)
|
| 1596 |
+
|
| 1597 |
+
# At this point, if any class dependency is found, but belongs to another file, it means that we need to remove
|
| 1598 |
+
# it from the dependencies, and add a new import of it instead
|
| 1599 |
+
all_dependencies_to_add, new_imports = check_dependencies_and_create_import_node(
|
| 1600 |
+
file_type, all_dependencies_to_add, modular_mapper, model_name
|
| 1601 |
+
)
|
| 1602 |
+
|
| 1603 |
+
relative_dependency_order = modular_mapper.compute_relative_order(all_dependencies_to_add)
|
| 1604 |
+
nodes_to_add = {
|
| 1605 |
+
dep: (relative_dependency_order[dep], modular_mapper.global_nodes[dep])
|
| 1606 |
+
for dep in all_dependencies_to_add
|
| 1607 |
+
if dep not in file_to_update.keys()
|
| 1608 |
+
}
|
| 1609 |
+
|
| 1610 |
+
# Add the class node itself to the nodes to add
|
| 1611 |
+
class_idx = max(relative_dependency_order.values()) + 1 if len(relative_dependency_order) > 0 else 0
|
| 1612 |
+
nodes_to_add[class_name] = (class_idx, updated_node)
|
| 1613 |
+
|
| 1614 |
+
return nodes_to_add, file_type, new_imports
|
| 1615 |
+
|
| 1616 |
+
|
| 1617 |
+
def create_modules(modular_mapper: ModularFileMapper) -> dict[str, cst.Module]:
|
| 1618 |
+
"""Create all the new modules based on visiting the modular file. It replaces all classes as necesary."""
|
| 1619 |
+
files = defaultdict(dict)
|
| 1620 |
+
current_file_indices = defaultdict(lambda: 0)
|
| 1621 |
+
|
| 1622 |
+
# For each class defined in modular, potentially replace the node and add it with its dependencies
|
| 1623 |
+
for class_name, node in modular_mapper.classes.items():
|
| 1624 |
+
nodes_to_add, file_type, new_imports = get_class_node_and_dependencies(modular_mapper, class_name, node, files)
|
| 1625 |
+
|
| 1626 |
+
# Add the new potential new imports that we may need to the `modular_mapper` variable
|
| 1627 |
+
modular_mapper.imported_objects_per_file[file_type].update(new_imports.keys())
|
| 1628 |
+
modular_mapper.imports.extend(list(new_imports.values()))
|
| 1629 |
+
|
| 1630 |
+
# Sort the nodes according to their relative order
|
| 1631 |
+
nodes_to_add = sorted(nodes_to_add.items(), key=lambda x: x[1][0])
|
| 1632 |
+
# Write all nodes to file
|
| 1633 |
+
for dependency, (_, node) in nodes_to_add:
|
| 1634 |
+
# This is used to keep certain variables at the beginning of the file
|
| 1635 |
+
try:
|
| 1636 |
+
# The -1000 is arbitrary -> just keep it bigger than the list
|
| 1637 |
+
idx = -1000 + VARIABLES_AT_THE_BEGINNING.index(dependency)
|
| 1638 |
+
except ValueError:
|
| 1639 |
+
idx = current_file_indices[file_type]
|
| 1640 |
+
current_file_indices[file_type] += 1
|
| 1641 |
+
files[file_type][dependency] = {"insert_idx": idx, "node": node}
|
| 1642 |
+
|
| 1643 |
+
# Add the __all__ statement to files at the end
|
| 1644 |
+
for file_type, node in modular_mapper.all_all_to_add.items():
|
| 1645 |
+
idx = current_file_indices[file_type]
|
| 1646 |
+
files[file_type]["__all__"] = {"insert_idx": idx, "node": node}
|
| 1647 |
+
|
| 1648 |
+
# Aggregate all the imports statements (we look for duplicates with the code_for_node, not the nodes themselves because
|
| 1649 |
+
# they are wrapped in SimpleStatementLine or If which could have different newlines, blanks etc)
|
| 1650 |
+
all_imports = modular_mapper.imports.copy()
|
| 1651 |
+
all_imports_code = {modular_mapper.python_module.code_for_node(node).strip() for node in all_imports}
|
| 1652 |
+
for file, mapper in modular_mapper.visited_modules.items():
|
| 1653 |
+
new_imports = [
|
| 1654 |
+
node for node in mapper.imports if mapper.python_module.code_for_node(node).strip() not in all_imports_code
|
| 1655 |
+
]
|
| 1656 |
+
new_imports_code = {mapper.python_module.code_for_node(node).strip() for node in new_imports}
|
| 1657 |
+
all_imports.extend(new_imports)
|
| 1658 |
+
all_imports_code.update(new_imports_code)
|
| 1659 |
+
|
| 1660 |
+
# Find the correct imports, and write the new modules
|
| 1661 |
+
for file, body in files.items():
|
| 1662 |
+
new_body = [k[1]["node"] for k in sorted(body.items(), key=lambda x: x[1]["insert_idx"])]
|
| 1663 |
+
needed_imports = get_needed_imports(body, all_imports)
|
| 1664 |
+
full_module = needed_imports + new_body
|
| 1665 |
+
new_module = cst.Module(body=full_module, header=modular_mapper.python_module.header)
|
| 1666 |
+
files[file] = new_module
|
| 1667 |
+
|
| 1668 |
+
return files
|
| 1669 |
+
|
| 1670 |
+
|
| 1671 |
+
def convert_modular_file(modular_file):
|
| 1672 |
+
pattern = re.search(r"modular_(.*)(?=\.py$)", modular_file)
|
| 1673 |
+
output = {}
|
| 1674 |
+
if pattern is not None:
|
| 1675 |
+
model_name = pattern.groups()[0]
|
| 1676 |
+
# Parse the Python file
|
| 1677 |
+
with open(modular_file, "r", encoding="utf-8") as file:
|
| 1678 |
+
code = file.read()
|
| 1679 |
+
module = cst.parse_module(code)
|
| 1680 |
+
wrapper = MetadataWrapper(module)
|
| 1681 |
+
cst_transformers = ModularFileMapper(module, model_name)
|
| 1682 |
+
wrapper.visit(cst_transformers)
|
| 1683 |
+
for file, module in create_modules(cst_transformers).items():
|
| 1684 |
+
if module != {}:
|
| 1685 |
+
# Get relative path starting from src/transformers/
|
| 1686 |
+
relative_path = re.search(
|
| 1687 |
+
r"(src/transformers/.*|examples/.*)", os.path.abspath(modular_file).replace("\\", "/")
|
| 1688 |
+
).group(1)
|
| 1689 |
+
|
| 1690 |
+
header = AUTO_GENERATED_MESSAGE.format(
|
| 1691 |
+
relative_path=relative_path, short_name=os.path.basename(relative_path)
|
| 1692 |
+
)
|
| 1693 |
+
ruffed_code = run_ruff(header + module.code, True)
|
| 1694 |
+
formatted_code = run_ruff(ruffed_code, False)
|
| 1695 |
+
output[file] = [formatted_code, ruffed_code]
|
| 1696 |
+
return output
|
| 1697 |
+
else:
|
| 1698 |
+
print(f"modular pattern not found in {modular_file}, exiting")
|
| 1699 |
+
return {}
|
| 1700 |
+
|
| 1701 |
+
|
| 1702 |
+
def save_modeling_file(modular_file, converted_file):
|
| 1703 |
+
for file_type in converted_file.keys():
|
| 1704 |
+
file_name_prefix = file_type.split("*")[0]
|
| 1705 |
+
file_name_suffix = file_type.split("*")[-1] if "*" in file_type else ""
|
| 1706 |
+
new_file_name = modular_file.replace("modular_", f"{file_name_prefix}_").replace(
|
| 1707 |
+
".py", f"{file_name_suffix}.py"
|
| 1708 |
+
)
|
| 1709 |
+
non_comment_lines = len(
|
| 1710 |
+
[line for line in converted_file[file_type][0].strip().split("\n") if not line.strip().startswith("#")]
|
| 1711 |
+
)
|
| 1712 |
+
if len(converted_file[file_type][0].strip()) > 0 and non_comment_lines > 0:
|
| 1713 |
+
with open(new_file_name, "w", encoding="utf-8") as f:
|
| 1714 |
+
f.write(converted_file[file_type][0])
|
| 1715 |
+
else:
|
| 1716 |
+
non_comment_lines = len(
|
| 1717 |
+
[line for line in converted_file[file_type][0].strip().split("\n") if not line.strip().startswith("#")]
|
| 1718 |
+
)
|
| 1719 |
+
if len(converted_file[file_type][1].strip()) > 0 and non_comment_lines > 0:
|
| 1720 |
+
logger.warning("The modeling code contains errors, it's written without formatting")
|
| 1721 |
+
with open(new_file_name, "w", encoding="utf-8") as f:
|
| 1722 |
+
f.write(converted_file[file_type][1])
|
| 1723 |
+
|
| 1724 |
+
|
| 1725 |
+
if __name__ == "__main__":
|
| 1726 |
+
parser = argparse.ArgumentParser()
|
| 1727 |
+
parser.add_argument(
|
| 1728 |
+
"--files_to_parse",
|
| 1729 |
+
default=["all"],
|
| 1730 |
+
nargs="+",
|
| 1731 |
+
help="A list of `modular_xxxx` files that should be converted to single model file",
|
| 1732 |
+
)
|
| 1733 |
+
args = parser.parse_args()
|
| 1734 |
+
if args.files_to_parse == ["all"]:
|
| 1735 |
+
args.files_to_parse = glob.glob("src/transformers/models/**/modular_*.py", recursive=True)
|
| 1736 |
+
if args.files_to_parse == ["examples"]:
|
| 1737 |
+
args.files_to_parse = glob.glob("examples/**/modular_*.py", recursive=True)
|
| 1738 |
+
|
| 1739 |
+
priority_list, _ = find_priority_list(args.files_to_parse)
|
| 1740 |
+
assert len(priority_list) == len(args.files_to_parse), "Some files will not be converted"
|
| 1741 |
+
|
| 1742 |
+
for file_name in priority_list:
|
| 1743 |
+
print(f"Converting {file_name} to a single model single file format")
|
| 1744 |
+
module_path = file_name.replace("/", ".").replace(".py", "").replace("src.", "")
|
| 1745 |
+
converted_files = convert_modular_file(file_name)
|
| 1746 |
+
converter = save_modeling_file(file_name, converted_files)
|
tasks/tasksmith-441eeab80047/environment/source/utils/not_doctested.txt
ADDED
|
@@ -0,0 +1,979 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
docs/source/en/_config.py
|
| 2 |
+
docs/source/en/accelerate.md
|
| 3 |
+
docs/source/en/add_new_model.md
|
| 4 |
+
docs/source/en/add_new_pipeline.md
|
| 5 |
+
docs/source/en/agents.md
|
| 6 |
+
docs/source/en/agents.md
|
| 7 |
+
docs/source/en/attention.md
|
| 8 |
+
docs/source/en/community.md
|
| 9 |
+
docs/source/en/contributing.md
|
| 10 |
+
docs/source/en/custom_models.md
|
| 11 |
+
docs/source/en/debugging.md
|
| 12 |
+
docs/source/en/fast_tokenizers.md
|
| 13 |
+
docs/source/en/glossary.md
|
| 14 |
+
docs/source/en/hpo_train.md
|
| 15 |
+
docs/source/en/index.md
|
| 16 |
+
docs/source/en/installation.md
|
| 17 |
+
docs/source/en/internal/audio_utils.md
|
| 18 |
+
docs/source/en/internal/file_utils.md
|
| 19 |
+
docs/source/en/internal/image_processing_utils.md
|
| 20 |
+
docs/source/en/internal/modeling_utils.md
|
| 21 |
+
docs/source/en/internal/pipelines_utils.md
|
| 22 |
+
docs/source/en/internal/time_series_utils.md
|
| 23 |
+
docs/source/en/internal/tokenization_utils.md
|
| 24 |
+
docs/source/en/internal/trainer_utils.md
|
| 25 |
+
docs/source/en/llm_tutorial.md
|
| 26 |
+
docs/source/en/main_classes/agent.md
|
| 27 |
+
docs/source/en/main_classes/callback.md
|
| 28 |
+
docs/source/en/main_classes/configuration.md
|
| 29 |
+
docs/source/en/main_classes/data_collator.md
|
| 30 |
+
docs/source/en/main_classes/deepspeed.md
|
| 31 |
+
docs/source/en/main_classes/feature_extractor.md
|
| 32 |
+
docs/source/en/main_classes/image_processor.md
|
| 33 |
+
docs/source/en/main_classes/keras_callbacks.md
|
| 34 |
+
docs/source/en/main_classes/logging.md
|
| 35 |
+
docs/source/en/main_classes/model.md
|
| 36 |
+
docs/source/en/main_classes/onnx.md
|
| 37 |
+
docs/source/en/main_classes/optimizer_schedules.md
|
| 38 |
+
docs/source/en/main_classes/output.md
|
| 39 |
+
docs/source/en/main_classes/pipelines.md
|
| 40 |
+
docs/source/en/main_classes/processors.md
|
| 41 |
+
docs/source/en/main_classes/quantization.md
|
| 42 |
+
docs/source/en/main_classes/tokenizer.md
|
| 43 |
+
docs/source/en/main_classes/trainer.md
|
| 44 |
+
docs/source/en/model_doc/albert.md
|
| 45 |
+
docs/source/en/model_doc/align.md
|
| 46 |
+
docs/source/en/model_doc/altclip.md
|
| 47 |
+
docs/source/en/model_doc/audio-spectrogram-transformer.md
|
| 48 |
+
docs/source/en/model_doc/auto.md
|
| 49 |
+
docs/source/en/model_doc/autoformer.md
|
| 50 |
+
docs/source/en/model_doc/bark.md
|
| 51 |
+
docs/source/en/model_doc/bart.md
|
| 52 |
+
docs/source/en/model_doc/barthez.md
|
| 53 |
+
docs/source/en/model_doc/bartpho.md
|
| 54 |
+
docs/source/en/model_doc/beit.md
|
| 55 |
+
docs/source/en/model_doc/bert-generation.md
|
| 56 |
+
docs/source/en/model_doc/bert-japanese.md
|
| 57 |
+
docs/source/en/model_doc/bert.md
|
| 58 |
+
docs/source/en/model_doc/bertweet.md
|
| 59 |
+
docs/source/en/model_doc/big_bird.md
|
| 60 |
+
docs/source/en/model_doc/bigbird_pegasus.md
|
| 61 |
+
docs/source/en/model_doc/biogpt.md
|
| 62 |
+
docs/source/en/model_doc/bit.md
|
| 63 |
+
docs/source/en/model_doc/blenderbot-small.md
|
| 64 |
+
docs/source/en/model_doc/blenderbot.md
|
| 65 |
+
docs/source/en/model_doc/blip-2.md
|
| 66 |
+
docs/source/en/model_doc/blip.md
|
| 67 |
+
docs/source/en/model_doc/bloom.md
|
| 68 |
+
docs/source/en/model_doc/bort.md
|
| 69 |
+
docs/source/en/model_doc/bridgetower.md
|
| 70 |
+
docs/source/en/model_doc/camembert.md
|
| 71 |
+
docs/source/en/model_doc/canine.md
|
| 72 |
+
docs/source/en/model_doc/chinese_clip.md
|
| 73 |
+
docs/source/en/model_doc/clap.md
|
| 74 |
+
docs/source/en/model_doc/clip.md
|
| 75 |
+
docs/source/en/model_doc/clipseg.md
|
| 76 |
+
docs/source/en/model_doc/codegen.md
|
| 77 |
+
docs/source/en/model_doc/conditional_detr.md
|
| 78 |
+
docs/source/en/model_doc/convbert.md
|
| 79 |
+
docs/source/en/model_doc/convnext.md
|
| 80 |
+
docs/source/en/model_doc/convnextv2.md
|
| 81 |
+
docs/source/en/model_doc/cpm.md
|
| 82 |
+
docs/source/en/model_doc/cpmant.md
|
| 83 |
+
docs/source/en/model_doc/ctrl.md
|
| 84 |
+
docs/source/en/model_doc/cvt.md
|
| 85 |
+
docs/source/en/model_doc/data2vec.md
|
| 86 |
+
docs/source/en/model_doc/deberta-v2.md
|
| 87 |
+
docs/source/en/model_doc/deberta.md
|
| 88 |
+
docs/source/en/model_doc/decision_transformer.md
|
| 89 |
+
docs/source/en/model_doc/deformable_detr.md
|
| 90 |
+
docs/source/en/model_doc/deit.md
|
| 91 |
+
docs/source/en/model_doc/deplot.md
|
| 92 |
+
docs/source/en/model_doc/deta.md
|
| 93 |
+
docs/source/en/model_doc/detr.md
|
| 94 |
+
docs/source/en/model_doc/dialogpt.md
|
| 95 |
+
docs/source/en/model_doc/dinat.md
|
| 96 |
+
docs/source/en/model_doc/dinov2.md
|
| 97 |
+
docs/source/en/model_doc/distilbert.md
|
| 98 |
+
docs/source/en/model_doc/dit.md
|
| 99 |
+
docs/source/en/model_doc/dpr.md
|
| 100 |
+
docs/source/en/model_doc/dpt.md
|
| 101 |
+
docs/source/en/model_doc/efficientformer.md
|
| 102 |
+
docs/source/en/model_doc/efficientnet.md
|
| 103 |
+
docs/source/en/model_doc/electra.md
|
| 104 |
+
docs/source/en/model_doc/encodec.md
|
| 105 |
+
docs/source/en/model_doc/ernie.md
|
| 106 |
+
docs/source/en/model_doc/ernie_m.md
|
| 107 |
+
docs/source/en/model_doc/esm.md
|
| 108 |
+
docs/source/en/model_doc/flan-t5.md
|
| 109 |
+
docs/source/en/model_doc/flan-ul2.md
|
| 110 |
+
docs/source/en/model_doc/flaubert.md
|
| 111 |
+
docs/source/en/model_doc/flava.md
|
| 112 |
+
docs/source/en/model_doc/fnet.md
|
| 113 |
+
docs/source/en/model_doc/focalnet.md
|
| 114 |
+
docs/source/en/model_doc/fsmt.md
|
| 115 |
+
docs/source/en/model_doc/funnel.md
|
| 116 |
+
docs/source/en/model_doc/git.md
|
| 117 |
+
docs/source/en/model_doc/glpn.md
|
| 118 |
+
docs/source/en/model_doc/gpt-sw3.md
|
| 119 |
+
docs/source/en/model_doc/gpt2.md
|
| 120 |
+
docs/source/en/model_doc/gpt_bigcode.md
|
| 121 |
+
docs/source/en/model_doc/gpt_neo.md
|
| 122 |
+
docs/source/en/model_doc/gpt_neox.md
|
| 123 |
+
docs/source/en/model_doc/gpt_neox_japanese.md
|
| 124 |
+
docs/source/en/model_doc/gptj.md
|
| 125 |
+
docs/source/en/model_doc/gptsan-japanese.md
|
| 126 |
+
docs/source/en/model_doc/graphormer.md
|
| 127 |
+
docs/source/en/model_doc/groupvit.md
|
| 128 |
+
docs/source/en/model_doc/herbert.md
|
| 129 |
+
docs/source/en/model_doc/hubert.md
|
| 130 |
+
docs/source/en/model_doc/ibert.md
|
| 131 |
+
docs/source/en/model_doc/idefics.md
|
| 132 |
+
docs/source/en/model_doc/imagegpt.md
|
| 133 |
+
docs/source/en/model_doc/informer.md
|
| 134 |
+
docs/source/en/model_doc/instructblip.md
|
| 135 |
+
docs/source/en/model_doc/jukebox.md
|
| 136 |
+
docs/source/en/model_doc/layoutlm.md
|
| 137 |
+
docs/source/en/model_doc/layoutlmv2.md
|
| 138 |
+
docs/source/en/model_doc/layoutlmv3.md
|
| 139 |
+
docs/source/en/model_doc/layoutxlm.md
|
| 140 |
+
docs/source/en/model_doc/led.md
|
| 141 |
+
docs/source/en/model_doc/levit.md
|
| 142 |
+
docs/source/en/model_doc/lilt.md
|
| 143 |
+
docs/source/en/model_doc/llama.md
|
| 144 |
+
docs/source/en/model_doc/llama2.md
|
| 145 |
+
docs/source/en/model_doc/llava.md
|
| 146 |
+
docs/source/en/model_doc/llava_next.md
|
| 147 |
+
docs/source/en/model_doc/longformer.md
|
| 148 |
+
docs/source/en/model_doc/longt5.md
|
| 149 |
+
docs/source/en/model_doc/luke.md
|
| 150 |
+
docs/source/en/model_doc/lxmert.md
|
| 151 |
+
docs/source/en/model_doc/m2m_100.md
|
| 152 |
+
docs/source/en/model_doc/madlad-400.md
|
| 153 |
+
docs/source/en/model_doc/marian.md
|
| 154 |
+
docs/source/en/model_doc/mask2former.md
|
| 155 |
+
docs/source/en/model_doc/maskformer.md
|
| 156 |
+
docs/source/en/model_doc/matcha.md
|
| 157 |
+
docs/source/en/model_doc/mbart.md
|
| 158 |
+
docs/source/en/model_doc/mctct.md
|
| 159 |
+
docs/source/en/model_doc/mega.md
|
| 160 |
+
docs/source/en/model_doc/megatron-bert.md
|
| 161 |
+
docs/source/en/model_doc/megatron_gpt2.md
|
| 162 |
+
docs/source/en/model_doc/mgp-str.md
|
| 163 |
+
docs/source/en/model_doc/mistral.md
|
| 164 |
+
docs/source/en/model_doc/mixtral.md
|
| 165 |
+
docs/source/en/model_doc/mluke.md
|
| 166 |
+
docs/source/en/model_doc/mms.md
|
| 167 |
+
docs/source/en/model_doc/mobilebert.md
|
| 168 |
+
docs/source/en/model_doc/mobilenet_v1.md
|
| 169 |
+
docs/source/en/model_doc/mobilenet_v2.md
|
| 170 |
+
docs/source/en/model_doc/mobilevit.md
|
| 171 |
+
docs/source/en/model_doc/mobilevitv2.md
|
| 172 |
+
docs/source/en/model_doc/mpnet.md
|
| 173 |
+
docs/source/en/model_doc/mpt.md
|
| 174 |
+
docs/source/en/model_doc/mra.md
|
| 175 |
+
docs/source/en/model_doc/mt5.md
|
| 176 |
+
docs/source/en/model_doc/musicgen.md
|
| 177 |
+
docs/source/en/model_doc/musicgen_melody.md
|
| 178 |
+
docs/source/en/model_doc/mvp.md
|
| 179 |
+
docs/source/en/model_doc/nat.md
|
| 180 |
+
docs/source/en/model_doc/nezha.md
|
| 181 |
+
docs/source/en/model_doc/nllb-moe.md
|
| 182 |
+
docs/source/en/model_doc/nllb.md
|
| 183 |
+
docs/source/en/model_doc/nystromformer.md
|
| 184 |
+
docs/source/en/model_doc/oneformer.md
|
| 185 |
+
docs/source/en/model_doc/open-llama.md
|
| 186 |
+
docs/source/en/model_doc/openai-gpt.md
|
| 187 |
+
docs/source/en/model_doc/opt.md
|
| 188 |
+
docs/source/en/model_doc/owlvit.md
|
| 189 |
+
docs/source/en/model_doc/pegasus.md
|
| 190 |
+
docs/source/en/model_doc/pegasus_x.md
|
| 191 |
+
docs/source/en/model_doc/perceiver.md
|
| 192 |
+
docs/source/en/model_doc/phobert.md
|
| 193 |
+
docs/source/en/model_doc/pix2struct.md
|
| 194 |
+
docs/source/en/model_doc/plbart.md
|
| 195 |
+
docs/source/en/model_doc/poolformer.md
|
| 196 |
+
docs/source/en/model_doc/pop2piano.md
|
| 197 |
+
docs/source/en/model_doc/prophetnet.md
|
| 198 |
+
docs/source/en/model_doc/pvt.md
|
| 199 |
+
docs/source/en/model_doc/qdqbert.md
|
| 200 |
+
docs/source/en/model_doc/qwen2.md
|
| 201 |
+
docs/source/en/model_doc/qwen2_moe.md
|
| 202 |
+
docs/source/en/model_doc/rag.md
|
| 203 |
+
docs/source/en/model_doc/realm.md
|
| 204 |
+
docs/source/en/model_doc/reformer.md
|
| 205 |
+
docs/source/en/model_doc/regnet.md
|
| 206 |
+
docs/source/en/model_doc/rembert.md
|
| 207 |
+
docs/source/en/model_doc/resnet.md
|
| 208 |
+
docs/source/en/model_doc/retribert.md
|
| 209 |
+
docs/source/en/model_doc/roberta-prelayernorm.md
|
| 210 |
+
docs/source/en/model_doc/roberta.md
|
| 211 |
+
docs/source/en/model_doc/roc_bert.md
|
| 212 |
+
docs/source/en/model_doc/roformer.md
|
| 213 |
+
docs/source/en/model_doc/rwkv.md
|
| 214 |
+
docs/source/en/model_doc/sam.md
|
| 215 |
+
docs/source/en/model_doc/segformer.md
|
| 216 |
+
docs/source/en/model_doc/sew-d.md
|
| 217 |
+
docs/source/en/model_doc/sew.md
|
| 218 |
+
docs/source/en/model_doc/speech-encoder-decoder.md
|
| 219 |
+
docs/source/en/model_doc/speech_to_text_2.md
|
| 220 |
+
docs/source/en/model_doc/speecht5.md
|
| 221 |
+
docs/source/en/model_doc/splinter.md
|
| 222 |
+
docs/source/en/model_doc/squeezebert.md
|
| 223 |
+
docs/source/en/model_doc/swiftformer.md
|
| 224 |
+
docs/source/en/model_doc/swin.md
|
| 225 |
+
docs/source/en/model_doc/swin2sr.md
|
| 226 |
+
docs/source/en/model_doc/swinv2.md
|
| 227 |
+
docs/source/en/model_doc/table-transformer.md
|
| 228 |
+
docs/source/en/model_doc/tapas.md
|
| 229 |
+
docs/source/en/model_doc/time_series_transformer.md
|
| 230 |
+
docs/source/en/model_doc/timesformer.md
|
| 231 |
+
docs/source/en/model_doc/trajectory_transformer.md
|
| 232 |
+
docs/source/en/model_doc/transfo-xl.md
|
| 233 |
+
docs/source/en/model_doc/trocr.md
|
| 234 |
+
docs/source/en/model_doc/tvlt.md
|
| 235 |
+
docs/source/en/model_doc/ul2.md
|
| 236 |
+
docs/source/en/model_doc/umt5.md
|
| 237 |
+
docs/source/en/model_doc/unispeech-sat.md
|
| 238 |
+
docs/source/en/model_doc/unispeech.md
|
| 239 |
+
docs/source/en/model_doc/upernet.md
|
| 240 |
+
docs/source/en/model_doc/van.md
|
| 241 |
+
docs/source/en/model_doc/videomae.md
|
| 242 |
+
docs/source/en/model_doc/vilt.md
|
| 243 |
+
docs/source/en/model_doc/vipllava.md
|
| 244 |
+
docs/source/en/model_doc/vision-encoder-decoder.md
|
| 245 |
+
docs/source/en/model_doc/vision-text-dual-encoder.md
|
| 246 |
+
docs/source/en/model_doc/visual_bert.md
|
| 247 |
+
docs/source/en/model_doc/vit.md
|
| 248 |
+
docs/source/en/model_doc/vit_hybrid.md
|
| 249 |
+
docs/source/en/model_doc/vit_mae.md
|
| 250 |
+
docs/source/en/model_doc/vit_msn.md
|
| 251 |
+
docs/source/en/model_doc/vivit.md
|
| 252 |
+
docs/source/en/model_doc/wav2vec2-conformer.md
|
| 253 |
+
docs/source/en/model_doc/wav2vec2.md
|
| 254 |
+
docs/source/en/model_doc/wav2vec2_phoneme.md
|
| 255 |
+
docs/source/en/model_doc/wavlm.md
|
| 256 |
+
docs/source/en/model_doc/whisper.md
|
| 257 |
+
docs/source/en/model_doc/xclip.md
|
| 258 |
+
docs/source/en/model_doc/xglm.md
|
| 259 |
+
docs/source/en/model_doc/xlm-prophetnet.md
|
| 260 |
+
docs/source/en/model_doc/xlm-roberta-xl.md
|
| 261 |
+
docs/source/en/model_doc/xlm-roberta.md
|
| 262 |
+
docs/source/en/model_doc/xlm-v.md
|
| 263 |
+
docs/source/en/model_doc/xlm.md
|
| 264 |
+
docs/source/en/model_doc/xlnet.md
|
| 265 |
+
docs/source/en/model_doc/xls_r.md
|
| 266 |
+
docs/source/en/model_doc/xlsr_wav2vec2.md
|
| 267 |
+
docs/source/en/model_doc/xmod.md
|
| 268 |
+
docs/source/en/model_doc/yolos.md
|
| 269 |
+
docs/source/en/model_doc/yoso.md
|
| 270 |
+
docs/source/en/model_memory_anatomy.md
|
| 271 |
+
docs/source/en/model_sharing.md
|
| 272 |
+
docs/source/en/model_summary.md
|
| 273 |
+
docs/source/en/notebooks.md
|
| 274 |
+
docs/source/en/pad_truncation.md
|
| 275 |
+
docs/source/en/peft.md
|
| 276 |
+
docs/source/en/perf_hardware.md
|
| 277 |
+
docs/source/en/perf_infer_cpu.md
|
| 278 |
+
docs/source/en/perf_infer_gpu_one.md
|
| 279 |
+
docs/source/en/perf_torch_compile.md
|
| 280 |
+
docs/source/en/perf_train_cpu.md
|
| 281 |
+
docs/source/en/perf_train_cpu_many.md
|
| 282 |
+
docs/source/en/perf_train_gpu_many.md
|
| 283 |
+
docs/source/en/perf_train_gpu_one.md
|
| 284 |
+
docs/source/en/perf_train_special.md
|
| 285 |
+
docs/source/en/perf_train_tpu_tf.md
|
| 286 |
+
docs/source/en/perplexity.md
|
| 287 |
+
docs/source/en/philosophy.md
|
| 288 |
+
docs/source/en/pipeline_webserver.md
|
| 289 |
+
docs/source/en/pr_checks.md
|
| 290 |
+
docs/source/en/run_scripts.md
|
| 291 |
+
docs/source/en/serialization.md
|
| 292 |
+
docs/source/en/tasks/asr.md
|
| 293 |
+
docs/source/en/tasks/audio_classification.md
|
| 294 |
+
docs/source/en/tasks/document_question_answering.md
|
| 295 |
+
docs/source/en/tasks/idefics.md
|
| 296 |
+
docs/source/en/tasks/image_captioning.md
|
| 297 |
+
docs/source/en/tasks/image_classification.md
|
| 298 |
+
docs/source/en/tasks/language_modeling.md
|
| 299 |
+
docs/source/en/tasks/masked_language_modeling.md
|
| 300 |
+
docs/source/en/tasks/monocular_depth_estimation.md
|
| 301 |
+
docs/source/en/tasks/multiple_choice.md
|
| 302 |
+
docs/source/en/tasks/object_detection.md
|
| 303 |
+
docs/source/en/tasks/question_answering.md
|
| 304 |
+
docs/source/en/tasks/semantic_segmentation.md
|
| 305 |
+
docs/source/en/tasks/sequence_classification.md
|
| 306 |
+
docs/source/en/tasks/summarization.md
|
| 307 |
+
docs/source/en/tasks/text-to-speech.md
|
| 308 |
+
docs/source/en/tasks/token_classification.md
|
| 309 |
+
docs/source/en/tasks/translation.md
|
| 310 |
+
docs/source/en/tasks/video_classification.md
|
| 311 |
+
docs/source/en/tasks/visual_question_answering.md
|
| 312 |
+
docs/source/en/tasks/zero_shot_image_classification.md
|
| 313 |
+
docs/source/en/tasks/zero_shot_object_detection.md
|
| 314 |
+
docs/source/en/tasks_explained.md
|
| 315 |
+
docs/source/en/tf_xla.md
|
| 316 |
+
docs/source/en/tflite.md
|
| 317 |
+
docs/source/en/tokenizer_summary.md
|
| 318 |
+
docs/source/en/torchscript.md
|
| 319 |
+
docs/source/en/training.md
|
| 320 |
+
docs/source/en/troubleshooting.md
|
| 321 |
+
src/transformers/activations.py
|
| 322 |
+
src/transformers/activations_tf.py
|
| 323 |
+
src/transformers/agents/agent_types.py
|
| 324 |
+
src/transformers/agents/agents.py
|
| 325 |
+
src/transformers/agents/document_question_answering.py
|
| 326 |
+
src/transformers/agents/evaluate_agent.py
|
| 327 |
+
src/transformers/agents/image_question_answering.py
|
| 328 |
+
src/transformers/agents/prompts.py
|
| 329 |
+
src/transformers/agents/python_interpreter.py
|
| 330 |
+
src/transformers/agents/speech_to_text.py
|
| 331 |
+
src/transformers/agents/text_to_speech.py
|
| 332 |
+
src/transformers/agents/tools.py
|
| 333 |
+
src/transformers/agents/translation.py
|
| 334 |
+
src/transformers/audio_utils.py
|
| 335 |
+
src/transformers/commands/add_new_model_like.py
|
| 336 |
+
src/transformers/commands/convert.py
|
| 337 |
+
src/transformers/commands/download.py
|
| 338 |
+
src/transformers/commands/env.py
|
| 339 |
+
src/transformers/commands/run.py
|
| 340 |
+
src/transformers/commands/serving.py
|
| 341 |
+
src/transformers/commands/train.py
|
| 342 |
+
src/transformers/commands/transformers_cli.py
|
| 343 |
+
src/transformers/configuration_utils.py
|
| 344 |
+
src/transformers/convert_graph_to_onnx.py
|
| 345 |
+
src/transformers/convert_pytorch_checkpoint_to_tf2.py
|
| 346 |
+
src/transformers/convert_slow_tokenizer.py
|
| 347 |
+
src/transformers/convert_slow_tokenizers_checkpoints_to_fast.py
|
| 348 |
+
src/transformers/convert_tf_hub_seq_to_seq_bert_to_pytorch.py
|
| 349 |
+
src/transformers/data/data_collator.py
|
| 350 |
+
src/transformers/data/datasets/glue.py
|
| 351 |
+
src/transformers/data/datasets/language_modeling.py
|
| 352 |
+
src/transformers/data/datasets/squad.py
|
| 353 |
+
src/transformers/data/metrics/squad_metrics.py
|
| 354 |
+
src/transformers/data/processors/glue.py
|
| 355 |
+
src/transformers/data/processors/squad.py
|
| 356 |
+
src/transformers/data/processors/utils.py
|
| 357 |
+
src/transformers/data/processors/xnli.py
|
| 358 |
+
src/transformers/debug_utils.py
|
| 359 |
+
src/transformers/dependency_versions_check.py
|
| 360 |
+
src/transformers/dependency_versions_table.py
|
| 361 |
+
src/transformers/dynamic_module_utils.py
|
| 362 |
+
src/transformers/feature_extraction_sequence_utils.py
|
| 363 |
+
src/transformers/feature_extraction_utils.py
|
| 364 |
+
src/transformers/file_utils.py
|
| 365 |
+
src/transformers/hf_argparser.py
|
| 366 |
+
src/transformers/hyperparameter_search.py
|
| 367 |
+
src/transformers/image_processing_utils.py
|
| 368 |
+
src/transformers/image_transforms.py
|
| 369 |
+
src/transformers/image_utils.py
|
| 370 |
+
src/transformers/integrations/bitsandbytes.py
|
| 371 |
+
src/transformers/integrations/deepspeed.py
|
| 372 |
+
src/transformers/integrations/integration_utils.py
|
| 373 |
+
src/transformers/integrations/peft.py
|
| 374 |
+
src/transformers/keras_callbacks.py
|
| 375 |
+
src/transformers/modelcard.py
|
| 376 |
+
src/transformers/modeling_flax_outputs.py
|
| 377 |
+
src/transformers/modeling_flax_pytorch_utils.py
|
| 378 |
+
src/transformers/modeling_flax_utils.py
|
| 379 |
+
src/transformers/modeling_outputs.py
|
| 380 |
+
src/transformers/modeling_tf_outputs.py
|
| 381 |
+
src/transformers/modeling_tf_pytorch_utils.py
|
| 382 |
+
src/transformers/modeling_tf_utils.py
|
| 383 |
+
src/transformers/modeling_utils.py
|
| 384 |
+
src/transformers/models/albert/convert_albert_original_tf_checkpoint_to_pytorch.py
|
| 385 |
+
src/transformers/models/albert/modeling_flax_albert.py
|
| 386 |
+
src/transformers/models/align/configuration_align.py
|
| 387 |
+
src/transformers/models/align/convert_align_tf_to_hf.py
|
| 388 |
+
src/transformers/models/align/modeling_align.py
|
| 389 |
+
src/transformers/models/altclip/configuration_altclip.py
|
| 390 |
+
src/transformers/models/altclip/modeling_altclip.py
|
| 391 |
+
src/transformers/models/audio_spectrogram_transformer/configuration_audio_spectrogram_transformer.py
|
| 392 |
+
src/transformers/models/audio_spectrogram_transformer/convert_audio_spectrogram_transformer_original_to_pytorch.py
|
| 393 |
+
src/transformers/models/auto/auto_factory.py
|
| 394 |
+
src/transformers/models/auto/configuration_auto.py
|
| 395 |
+
src/transformers/models/auto/modeling_auto.py
|
| 396 |
+
src/transformers/models/auto/modeling_flax_auto.py
|
| 397 |
+
src/transformers/models/auto/modeling_tf_auto.py
|
| 398 |
+
src/transformers/models/autoformer/configuration_autoformer.py
|
| 399 |
+
src/transformers/models/autoformer/modeling_autoformer.py
|
| 400 |
+
src/transformers/models/bark/convert_suno_to_hf.py
|
| 401 |
+
src/transformers/models/bart/convert_bart_original_pytorch_checkpoint_to_pytorch.py
|
| 402 |
+
src/transformers/models/bart/modeling_flax_bart.py
|
| 403 |
+
src/transformers/models/bart/modeling_tf_bart.py
|
| 404 |
+
src/transformers/models/beit/convert_beit_unilm_to_pytorch.py
|
| 405 |
+
src/transformers/models/beit/modeling_flax_beit.py
|
| 406 |
+
src/transformers/models/bert/convert_bert_original_tf2_checkpoint_to_pytorch.py
|
| 407 |
+
src/transformers/models/bert/convert_bert_original_tf_checkpoint_to_pytorch.py
|
| 408 |
+
src/transformers/models/bert/convert_bert_pytorch_checkpoint_to_original_tf.py
|
| 409 |
+
src/transformers/models/bert/convert_bert_token_dropping_original_tf2_checkpoint_to_pytorch.py
|
| 410 |
+
src/transformers/models/bert/modeling_flax_bert.py
|
| 411 |
+
src/transformers/models/bert_generation/modeling_bert_generation.py
|
| 412 |
+
src/transformers/models/big_bird/convert_bigbird_original_tf_checkpoint_to_pytorch.py
|
| 413 |
+
src/transformers/models/big_bird/modeling_flax_big_bird.py
|
| 414 |
+
src/transformers/models/bigbird_pegasus/convert_bigbird_pegasus_tf_to_pytorch.py
|
| 415 |
+
src/transformers/models/biogpt/configuration_biogpt.py
|
| 416 |
+
src/transformers/models/biogpt/convert_biogpt_original_pytorch_checkpoint_to_pytorch.py
|
| 417 |
+
src/transformers/models/biogpt/modeling_biogpt.py
|
| 418 |
+
src/transformers/models/bit/configuration_bit.py
|
| 419 |
+
src/transformers/models/bit/convert_bit_to_pytorch.py
|
| 420 |
+
src/transformers/models/bit/modeling_bit.py
|
| 421 |
+
src/transformers/models/blenderbot/convert_blenderbot_original_pytorch_checkpoint_to_pytorch.py
|
| 422 |
+
src/transformers/models/blenderbot/modeling_flax_blenderbot.py
|
| 423 |
+
src/transformers/models/blenderbot/modeling_tf_blenderbot.py
|
| 424 |
+
src/transformers/models/blenderbot_small/modeling_flax_blenderbot_small.py
|
| 425 |
+
src/transformers/models/blenderbot_small/modeling_tf_blenderbot_small.py
|
| 426 |
+
src/transformers/models/blip/configuration_blip.py
|
| 427 |
+
src/transformers/models/blip/convert_blip_original_pytorch_to_hf.py
|
| 428 |
+
src/transformers/models/blip/modeling_blip_text.py
|
| 429 |
+
src/transformers/models/blip/modeling_tf_blip_text.py
|
| 430 |
+
src/transformers/models/blip_2/configuration_blip_2.py
|
| 431 |
+
src/transformers/models/blip_2/convert_blip_2_original_to_pytorch.py
|
| 432 |
+
src/transformers/models/blip_2/modeling_blip_2.py
|
| 433 |
+
src/transformers/models/bloom/convert_bloom_original_checkpoint_to_pytorch.py
|
| 434 |
+
src/transformers/models/bloom/modeling_bloom.py
|
| 435 |
+
src/transformers/models/bloom/modeling_flax_bloom.py
|
| 436 |
+
src/transformers/models/bridgetower/configuration_bridgetower.py
|
| 437 |
+
src/transformers/models/bridgetower/modeling_bridgetower.py
|
| 438 |
+
src/transformers/models/bros/convert_bros_to_pytorch.py
|
| 439 |
+
src/transformers/models/byt5/convert_byt5_original_tf_checkpoint_to_pytorch.py
|
| 440 |
+
src/transformers/models/camembert/modeling_camembert.py
|
| 441 |
+
src/transformers/models/camembert/modeling_tf_camembert.py
|
| 442 |
+
src/transformers/models/canine/convert_canine_original_tf_checkpoint_to_pytorch.py
|
| 443 |
+
src/transformers/models/chinese_clip/configuration_chinese_clip.py
|
| 444 |
+
src/transformers/models/chinese_clip/convert_chinese_clip_original_pytorch_to_hf.py
|
| 445 |
+
src/transformers/models/chinese_clip/modeling_chinese_clip.py
|
| 446 |
+
src/transformers/models/clap/convert_clap_original_pytorch_to_hf.py
|
| 447 |
+
src/transformers/models/clip/convert_clip_original_pytorch_to_hf.py
|
| 448 |
+
src/transformers/models/clip/modeling_clip.py
|
| 449 |
+
src/transformers/models/clip/modeling_flax_clip.py
|
| 450 |
+
src/transformers/models/clip/modeling_tf_clip.py
|
| 451 |
+
src/transformers/models/clipseg/configuration_clipseg.py
|
| 452 |
+
src/transformers/models/clipseg/convert_clipseg_original_pytorch_to_hf.py
|
| 453 |
+
src/transformers/models/codegen/modeling_codegen.py
|
| 454 |
+
src/transformers/models/conditional_detr/convert_conditional_detr_original_pytorch_checkpoint_to_pytorch.py
|
| 455 |
+
src/transformers/models/convbert/convert_convbert_original_tf1_checkpoint_to_pytorch_and_tf2.py
|
| 456 |
+
src/transformers/models/convbert/modeling_convbert.py
|
| 457 |
+
src/transformers/models/convbert/modeling_tf_convbert.py
|
| 458 |
+
src/transformers/models/convnext/convert_convnext_to_pytorch.py
|
| 459 |
+
src/transformers/models/convnext/modeling_tf_convnext.py
|
| 460 |
+
src/transformers/models/convnextv2/configuration_convnextv2.py
|
| 461 |
+
src/transformers/models/convnextv2/convert_convnextv2_to_pytorch.py
|
| 462 |
+
src/transformers/models/convnextv2/modeling_convnextv2.py
|
| 463 |
+
src/transformers/models/cpmant/configuration_cpmant.py
|
| 464 |
+
src/transformers/models/cpmant/modeling_cpmant.py
|
| 465 |
+
src/transformers/models/cpmant/tokenization_cpmant.py
|
| 466 |
+
src/transformers/models/ctrl/modeling_tf_ctrl.py
|
| 467 |
+
src/transformers/models/cvt/convert_cvt_original_pytorch_checkpoint_to_pytorch.py
|
| 468 |
+
src/transformers/models/cvt/modeling_tf_cvt.py
|
| 469 |
+
src/transformers/models/data2vec/convert_data2vec_audio_original_pytorch_checkpoint_to_pytorch.py
|
| 470 |
+
src/transformers/models/data2vec/convert_data2vec_text_original_pytorch_checkpoint_to_pytorch.py
|
| 471 |
+
src/transformers/models/data2vec/convert_data2vec_vision_original_pytorch_checkpoint_to_pytorch.py
|
| 472 |
+
src/transformers/models/data2vec/modeling_data2vec_text.py
|
| 473 |
+
src/transformers/models/data2vec/modeling_tf_data2vec_vision.py
|
| 474 |
+
src/transformers/models/deberta/modeling_tf_deberta.py
|
| 475 |
+
src/transformers/models/deberta_v2/modeling_tf_deberta_v2.py
|
| 476 |
+
src/transformers/models/decision_transformer/modeling_decision_transformer.py
|
| 477 |
+
src/transformers/models/deformable_detr/convert_deformable_detr_to_pytorch.py
|
| 478 |
+
src/transformers/models/deformable_detr/load_custom.py
|
| 479 |
+
src/transformers/models/deit/convert_deit_timm_to_pytorch.py
|
| 480 |
+
src/transformers/models/deprecated/bort/convert_bort_original_gluonnlp_checkpoint_to_pytorch.py
|
| 481 |
+
src/transformers/models/deprecated/mctct/configuration_mctct.py
|
| 482 |
+
src/transformers/models/deprecated/mctct/feature_extraction_mctct.py
|
| 483 |
+
src/transformers/models/deprecated/mctct/modeling_mctct.py
|
| 484 |
+
src/transformers/models/deprecated/mctct/processing_mctct.py
|
| 485 |
+
src/transformers/models/deprecated/mmbt/configuration_mmbt.py
|
| 486 |
+
src/transformers/models/deprecated/mmbt/modeling_mmbt.py
|
| 487 |
+
src/transformers/models/deprecated/open_llama/configuration_open_llama.py
|
| 488 |
+
src/transformers/models/deprecated/open_llama/modeling_open_llama.py
|
| 489 |
+
src/transformers/models/deprecated/retribert/configuration_retribert.py
|
| 490 |
+
src/transformers/models/deprecated/retribert/modeling_retribert.py
|
| 491 |
+
src/transformers/models/deprecated/retribert/tokenization_retribert.py
|
| 492 |
+
src/transformers/models/deprecated/retribert/tokenization_retribert_fast.py
|
| 493 |
+
src/transformers/models/deprecated/tapex/tokenization_tapex.py
|
| 494 |
+
src/transformers/models/deprecated/trajectory_transformer/configuration_trajectory_transformer.py
|
| 495 |
+
src/transformers/models/deprecated/trajectory_transformer/convert_trajectory_transformer_original_pytorch_checkpoint_to_pytorch.py
|
| 496 |
+
src/transformers/models/deprecated/trajectory_transformer/modeling_trajectory_transformer.py
|
| 497 |
+
src/transformers/models/deprecated/transfo_xl/convert_transfo_xl_original_tf_checkpoint_to_pytorch.py
|
| 498 |
+
src/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl.py
|
| 499 |
+
src/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl_utilities.py
|
| 500 |
+
src/transformers/models/deprecated/transfo_xl/modeling_transfo_xl.py
|
| 501 |
+
src/transformers/models/deprecated/transfo_xl/modeling_transfo_xl_utilities.py
|
| 502 |
+
src/transformers/models/deprecated/van/configuration_van.py
|
| 503 |
+
src/transformers/models/deprecated/van/convert_van_to_pytorch.py
|
| 504 |
+
src/transformers/models/deprecated/van/modeling_van.py
|
| 505 |
+
src/transformers/models/detr/convert_detr_original_pytorch_checkpoint_to_pytorch.py
|
| 506 |
+
src/transformers/models/detr/convert_detr_to_pytorch.py
|
| 507 |
+
src/transformers/models/dialogpt/convert_dialogpt_original_pytorch_checkpoint_to_pytorch.py
|
| 508 |
+
src/transformers/models/dinov2/configuration_dinov2.py
|
| 509 |
+
src/transformers/models/dinov2/convert_dinov2_to_hf.py
|
| 510 |
+
src/transformers/models/dinov2/modeling_dinov2.py
|
| 511 |
+
src/transformers/models/distilbert/modeling_distilbert.py
|
| 512 |
+
src/transformers/models/distilbert/modeling_flax_distilbert.py
|
| 513 |
+
src/transformers/models/distilbert/modeling_tf_distilbert.py
|
| 514 |
+
src/transformers/models/dit/convert_dit_unilm_to_pytorch.py
|
| 515 |
+
src/transformers/models/donut/configuration_donut_swin.py
|
| 516 |
+
src/transformers/models/donut/convert_donut_to_pytorch.py
|
| 517 |
+
src/transformers/models/donut/modeling_donut_swin.py
|
| 518 |
+
src/transformers/models/dpr/convert_dpr_original_checkpoint_to_pytorch.py
|
| 519 |
+
src/transformers/models/dpr/modeling_dpr.py
|
| 520 |
+
src/transformers/models/dpr/modeling_tf_dpr.py
|
| 521 |
+
src/transformers/models/dpt/configuration_dpt.py
|
| 522 |
+
src/transformers/models/dpt/convert_dpt_hybrid_to_pytorch.py
|
| 523 |
+
src/transformers/models/dpt/convert_dpt_to_pytorch.py
|
| 524 |
+
src/transformers/models/efficientnet/configuration_efficientnet.py
|
| 525 |
+
src/transformers/models/efficientnet/convert_efficientnet_to_pytorch.py
|
| 526 |
+
src/transformers/models/efficientnet/modeling_efficientnet.py
|
| 527 |
+
src/transformers/models/electra/convert_electra_original_tf_checkpoint_to_pytorch.py
|
| 528 |
+
src/transformers/models/electra/modeling_flax_electra.py
|
| 529 |
+
src/transformers/models/encodec/configuration_encodec.py
|
| 530 |
+
src/transformers/models/encodec/convert_encodec_checkpoint_to_pytorch.py
|
| 531 |
+
src/transformers/models/encoder_decoder/modeling_encoder_decoder.py
|
| 532 |
+
src/transformers/models/encoder_decoder/modeling_flax_encoder_decoder.py
|
| 533 |
+
src/transformers/models/encoder_decoder/modeling_tf_encoder_decoder.py
|
| 534 |
+
src/transformers/models/ernie/modeling_ernie.py
|
| 535 |
+
src/transformers/models/esm/configuration_esm.py
|
| 536 |
+
src/transformers/models/esm/convert_esm.py
|
| 537 |
+
src/transformers/models/esm/modeling_esm.py
|
| 538 |
+
src/transformers/models/esm/modeling_esmfold.py
|
| 539 |
+
src/transformers/models/esm/modeling_tf_esm.py
|
| 540 |
+
src/transformers/models/esm/openfold_utils/chunk_utils.py
|
| 541 |
+
src/transformers/models/esm/openfold_utils/data_transforms.py
|
| 542 |
+
src/transformers/models/esm/openfold_utils/feats.py
|
| 543 |
+
src/transformers/models/esm/openfold_utils/loss.py
|
| 544 |
+
src/transformers/models/esm/openfold_utils/protein.py
|
| 545 |
+
src/transformers/models/esm/openfold_utils/residue_constants.py
|
| 546 |
+
src/transformers/models/esm/openfold_utils/rigid_utils.py
|
| 547 |
+
src/transformers/models/esm/openfold_utils/tensor_utils.py
|
| 548 |
+
src/transformers/models/falcon/configuration_falcon.py
|
| 549 |
+
src/transformers/models/falcon/modeling_falcon.py
|
| 550 |
+
src/transformers/models/flaubert/configuration_flaubert.py
|
| 551 |
+
src/transformers/models/flaubert/modeling_flaubert.py
|
| 552 |
+
src/transformers/models/flaubert/modeling_tf_flaubert.py
|
| 553 |
+
src/transformers/models/flava/convert_dalle_to_flava_codebook.py
|
| 554 |
+
src/transformers/models/flava/convert_flava_original_pytorch_to_hf.py
|
| 555 |
+
src/transformers/models/flava/modeling_flava.py
|
| 556 |
+
src/transformers/models/fnet/convert_fnet_original_flax_checkpoint_to_pytorch.py
|
| 557 |
+
src/transformers/models/fnet/modeling_fnet.py
|
| 558 |
+
src/transformers/models/focalnet/configuration_focalnet.py
|
| 559 |
+
src/transformers/models/focalnet/convert_focalnet_to_hf_format.py
|
| 560 |
+
src/transformers/models/focalnet/modeling_focalnet.py
|
| 561 |
+
src/transformers/models/fsmt/convert_fsmt_original_pytorch_checkpoint_to_pytorch.py
|
| 562 |
+
src/transformers/models/fsmt/modeling_fsmt.py
|
| 563 |
+
src/transformers/models/funnel/configuration_funnel.py
|
| 564 |
+
src/transformers/models/funnel/convert_funnel_original_tf_checkpoint_to_pytorch.py
|
| 565 |
+
src/transformers/models/funnel/modeling_funnel.py
|
| 566 |
+
src/transformers/models/funnel/modeling_tf_funnel.py
|
| 567 |
+
src/transformers/models/fuyu/convert_fuyu_model_weights_to_hf.py
|
| 568 |
+
src/transformers/models/gemma/configuration_gemma.py
|
| 569 |
+
src/transformers/models/gemma/convert_gemma_weights_to_hf.py
|
| 570 |
+
src/transformers/models/gemma/modeling_flax_gemma.py
|
| 571 |
+
src/transformers/models/gemma/modeling_gemma.py
|
| 572 |
+
src/transformers/models/git/configuration_git.py
|
| 573 |
+
src/transformers/models/git/convert_git_to_pytorch.py
|
| 574 |
+
src/transformers/models/glpn/configuration_glpn.py
|
| 575 |
+
src/transformers/models/glpn/convert_glpn_to_pytorch.py
|
| 576 |
+
src/transformers/models/gpt2/CONVERSION.md
|
| 577 |
+
src/transformers/models/gpt2/convert_gpt2_original_tf_checkpoint_to_pytorch.py
|
| 578 |
+
src/transformers/models/gpt2/modeling_flax_gpt2.py
|
| 579 |
+
src/transformers/models/gpt2/modeling_tf_gpt2.py
|
| 580 |
+
src/transformers/models/gpt_bigcode/configuration_gpt_bigcode.py
|
| 581 |
+
src/transformers/models/gpt_bigcode/modeling_gpt_bigcode.py
|
| 582 |
+
src/transformers/models/gpt_neo/convert_gpt_neo_mesh_tf_to_pytorch.py
|
| 583 |
+
src/transformers/models/gpt_neo/modeling_flax_gpt_neo.py
|
| 584 |
+
src/transformers/models/gpt_neo/modeling_gpt_neo.py
|
| 585 |
+
src/transformers/models/gpt_neox/modeling_gpt_neox.py
|
| 586 |
+
src/transformers/models/gpt_neox_japanese/modeling_gpt_neox_japanese.py
|
| 587 |
+
src/transformers/models/gpt_sw3/convert_megatron_to_pytorch.py
|
| 588 |
+
src/transformers/models/gptj/configuration_gptj.py
|
| 589 |
+
src/transformers/models/gptj/modeling_flax_gptj.py
|
| 590 |
+
src/transformers/models/gptj/modeling_tf_gptj.py
|
| 591 |
+
src/transformers/models/groupvit/configuration_groupvit.py
|
| 592 |
+
src/transformers/models/groupvit/convert_groupvit_nvlab_to_hf.py
|
| 593 |
+
src/transformers/models/hubert/configuration_hubert.py
|
| 594 |
+
src/transformers/models/hubert/convert_distilhubert_original_s3prl_checkpoint_to_pytorch.py
|
| 595 |
+
src/transformers/models/hubert/convert_hubert_original_pytorch_checkpoint_to_pytorch.py
|
| 596 |
+
src/transformers/models/hubert/convert_hubert_original_s3prl_checkpoint_to_pytorch.py
|
| 597 |
+
src/transformers/models/hubert/modeling_tf_hubert.py
|
| 598 |
+
src/transformers/models/ibert/configuration_ibert.py
|
| 599 |
+
src/transformers/models/ibert/modeling_ibert.py
|
| 600 |
+
src/transformers/models/ibert/quant_modules.py
|
| 601 |
+
src/transformers/models/idefics/configuration_idefics.py
|
| 602 |
+
src/transformers/models/idefics/image_processing_idefics.py
|
| 603 |
+
src/transformers/models/idefics/modeling_idefics.py
|
| 604 |
+
src/transformers/models/idefics/perceiver.py
|
| 605 |
+
src/transformers/models/idefics/processing_idefics.py
|
| 606 |
+
src/transformers/models/idefics/vision.py
|
| 607 |
+
src/transformers/models/imagegpt/convert_imagegpt_original_tf2_to_pytorch.py
|
| 608 |
+
src/transformers/models/informer/configuration_informer.py
|
| 609 |
+
src/transformers/models/informer/modeling_informer.py
|
| 610 |
+
src/transformers/models/instructblip/configuration_instructblip.py
|
| 611 |
+
src/transformers/models/instructblip/convert_instructblip_original_to_pytorch.py
|
| 612 |
+
src/transformers/models/instructblip/modeling_instructblip.py
|
| 613 |
+
src/transformers/models/instructblip/processing_instructblip.py
|
| 614 |
+
src/transformers/models/jamba/configuration_jamba.py
|
| 615 |
+
src/transformers/models/jamba/modeling_jamba.py
|
| 616 |
+
src/transformers/models/kosmos2/convert_kosmos2_original_pytorch_checkpoint_to_pytorch.py
|
| 617 |
+
src/transformers/models/led/configuration_led.py
|
| 618 |
+
src/transformers/models/led/modeling_led.py
|
| 619 |
+
src/transformers/models/led/modeling_tf_led.py
|
| 620 |
+
src/transformers/models/levit/convert_levit_timm_to_pytorch.py
|
| 621 |
+
src/transformers/models/levit/modeling_levit.py
|
| 622 |
+
src/transformers/models/lilt/configuration_lilt.py
|
| 623 |
+
src/transformers/models/llama/configuration_llama.py
|
| 624 |
+
src/transformers/models/llama/convert_llama_weights_to_hf.py
|
| 625 |
+
src/transformers/models/llama/modeling_llama.py
|
| 626 |
+
src/transformers/models/llava/configuration_llava.py
|
| 627 |
+
src/transformers/models/llava/modeling_llava.py
|
| 628 |
+
src/transformers/models/llava_next/configuration_llava_next.py
|
| 629 |
+
src/transformers/models/llava_next/modeling_llava_next.py
|
| 630 |
+
src/transformers/models/longformer/configuration_longformer.py
|
| 631 |
+
src/transformers/models/longformer/convert_longformer_original_pytorch_lightning_to_pytorch.py
|
| 632 |
+
src/transformers/models/longt5/configuration_longt5.py
|
| 633 |
+
src/transformers/models/longt5/convert_longt5x_checkpoint_to_flax.py
|
| 634 |
+
src/transformers/models/longt5/modeling_flax_longt5.py
|
| 635 |
+
src/transformers/models/luke/configuration_luke.py
|
| 636 |
+
src/transformers/models/luke/convert_luke_original_pytorch_checkpoint_to_pytorch.py
|
| 637 |
+
src/transformers/models/luke/modeling_luke.py
|
| 638 |
+
src/transformers/models/lxmert/configuration_lxmert.py
|
| 639 |
+
src/transformers/models/lxmert/convert_lxmert_original_tf_checkpoint_to_pytorch.py
|
| 640 |
+
src/transformers/models/lxmert/modeling_lxmert.py
|
| 641 |
+
src/transformers/models/lxmert/modeling_tf_lxmert.py
|
| 642 |
+
src/transformers/models/m2m_100/convert_m2m100_original_checkpoint_to_pytorch.py
|
| 643 |
+
src/transformers/models/m2m_100/modeling_m2m_100.py
|
| 644 |
+
src/transformers/models/marian/configuration_marian.py
|
| 645 |
+
src/transformers/models/marian/convert_marian_tatoeba_to_pytorch.py
|
| 646 |
+
src/transformers/models/marian/convert_marian_to_pytorch.py
|
| 647 |
+
src/transformers/models/marian/modeling_flax_marian.py
|
| 648 |
+
src/transformers/models/marian/modeling_tf_marian.py
|
| 649 |
+
src/transformers/models/markuplm/configuration_markuplm.py
|
| 650 |
+
src/transformers/models/markuplm/feature_extraction_markuplm.py
|
| 651 |
+
src/transformers/models/mask2former/convert_mask2former_original_pytorch_checkpoint_to_pytorch.py
|
| 652 |
+
src/transformers/models/maskformer/configuration_maskformer_swin.py
|
| 653 |
+
src/transformers/models/maskformer/convert_maskformer_original_pytorch_checkpoint_to_pytorch.py
|
| 654 |
+
src/transformers/models/maskformer/convert_maskformer_resnet_to_pytorch.py
|
| 655 |
+
src/transformers/models/maskformer/convert_maskformer_swin_to_pytorch.py
|
| 656 |
+
src/transformers/models/maskformer/modeling_maskformer_swin.py
|
| 657 |
+
src/transformers/models/mbart/convert_mbart_original_checkpoint_to_pytorch.py
|
| 658 |
+
src/transformers/models/mbart/modeling_flax_mbart.py
|
| 659 |
+
src/transformers/models/megatron_bert/convert_megatron_bert_checkpoint.py
|
| 660 |
+
src/transformers/models/megatron_bert/modeling_megatron_bert.py
|
| 661 |
+
src/transformers/models/megatron_gpt2/checkpoint_reshaping_and_interoperability.py
|
| 662 |
+
src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py
|
| 663 |
+
src/transformers/models/mgp_str/configuration_mgp_str.py
|
| 664 |
+
src/transformers/models/mgp_str/modeling_mgp_str.py
|
| 665 |
+
src/transformers/models/mistral/configuration_mistral.py
|
| 666 |
+
src/transformers/models/mistral/modeling_mistral.py
|
| 667 |
+
src/transformers/models/mixtral/configuration_mixtral.py
|
| 668 |
+
src/transformers/models/mixtral/modeling_mixtral.py
|
| 669 |
+
src/transformers/models/mluke/convert_mluke_original_pytorch_checkpoint_to_pytorch.py
|
| 670 |
+
src/transformers/models/mobilebert/convert_mobilebert_original_tf_checkpoint_to_pytorch.py
|
| 671 |
+
src/transformers/models/mobilenet_v1/configuration_mobilenet_v1.py
|
| 672 |
+
src/transformers/models/mobilenet_v1/convert_original_tf_checkpoint_to_pytorch.py
|
| 673 |
+
src/transformers/models/mobilenet_v2/configuration_mobilenet_v2.py
|
| 674 |
+
src/transformers/models/mobilenet_v2/convert_original_tf_checkpoint_to_pytorch.py
|
| 675 |
+
src/transformers/models/mobilevit/configuration_mobilevit.py
|
| 676 |
+
src/transformers/models/mobilevit/convert_mlcvnets_to_pytorch.py
|
| 677 |
+
src/transformers/models/mobilevitv2/convert_mlcvnets_to_pytorch.py
|
| 678 |
+
src/transformers/models/mpnet/configuration_mpnet.py
|
| 679 |
+
src/transformers/models/mpnet/modeling_mpnet.py
|
| 680 |
+
src/transformers/models/mpnet/modeling_tf_mpnet.py
|
| 681 |
+
src/transformers/models/mpt/configuration_mpt.py
|
| 682 |
+
src/transformers/models/mpt/modeling_mpt.py
|
| 683 |
+
src/transformers/models/mra/configuration_mra.py
|
| 684 |
+
src/transformers/models/mra/convert_mra_pytorch_to_pytorch.py
|
| 685 |
+
src/transformers/models/mra/modeling_mra.py
|
| 686 |
+
src/transformers/models/mt5/configuration_mt5.py
|
| 687 |
+
src/transformers/models/mt5/modeling_flax_mt5.py
|
| 688 |
+
src/transformers/models/mt5/modeling_mt5.py
|
| 689 |
+
src/transformers/models/mt5/modeling_tf_mt5.py
|
| 690 |
+
src/transformers/models/musicgen/convert_musicgen_transformers.py
|
| 691 |
+
src/transformers/models/musicgen_melody/convert_musicgen_melody_transformers.py
|
| 692 |
+
src/transformers/models/mvp/modeling_mvp.py
|
| 693 |
+
src/transformers/models/nllb_moe/configuration_nllb_moe.py
|
| 694 |
+
src/transformers/models/nllb_moe/convert_nllb_moe_sharded_original_checkpoint_to_pytorch.py
|
| 695 |
+
src/transformers/models/nllb_moe/modeling_nllb_moe.py
|
| 696 |
+
src/transformers/models/nougat/convert_nougat_to_hf.py
|
| 697 |
+
src/transformers/models/nystromformer/configuration_nystromformer.py
|
| 698 |
+
src/transformers/models/nystromformer/convert_nystromformer_original_pytorch_checkpoint_to_pytorch.py
|
| 699 |
+
src/transformers/models/nystromformer/modeling_nystromformer.py
|
| 700 |
+
src/transformers/models/oneformer/convert_to_hf_oneformer.py
|
| 701 |
+
src/transformers/models/openai/convert_openai_original_tf_checkpoint_to_pytorch.py
|
| 702 |
+
src/transformers/models/openai/modeling_openai.py
|
| 703 |
+
src/transformers/models/openai/modeling_tf_openai.py
|
| 704 |
+
src/transformers/models/opt/convert_opt_original_pytorch_checkpoint_to_pytorch.py
|
| 705 |
+
src/transformers/models/opt/modeling_flax_opt.py
|
| 706 |
+
src/transformers/models/owlvit/configuration_owlvit.py
|
| 707 |
+
src/transformers/models/owlvit/convert_owlvit_original_flax_to_hf.py
|
| 708 |
+
src/transformers/models/pegasus/convert_pegasus_tf_to_pytorch.py
|
| 709 |
+
src/transformers/models/pegasus/modeling_flax_pegasus.py
|
| 710 |
+
src/transformers/models/pegasus/modeling_tf_pegasus.py
|
| 711 |
+
src/transformers/models/pegasus_x/modeling_pegasus_x.py
|
| 712 |
+
src/transformers/models/perceiver/configuration_perceiver.py
|
| 713 |
+
src/transformers/models/perceiver/convert_perceiver_haiku_to_pytorch.py
|
| 714 |
+
src/transformers/models/persimmon/convert_persimmon_weights_to_hf.py
|
| 715 |
+
src/transformers/models/persimmon/modeling_persimmon.py
|
| 716 |
+
src/transformers/models/pix2struct/configuration_pix2struct.py
|
| 717 |
+
src/transformers/models/pix2struct/convert_pix2struct_original_pytorch_to_hf.py
|
| 718 |
+
src/transformers/models/pix2struct/image_processing_pix2struct.py
|
| 719 |
+
src/transformers/models/pix2struct/processing_pix2struct.py
|
| 720 |
+
src/transformers/models/plbart/convert_plbart_original_checkpoint_to_torch.py
|
| 721 |
+
src/transformers/models/poolformer/convert_poolformer_original_to_pytorch.py
|
| 722 |
+
src/transformers/models/pop2piano/convert_pop2piano_weights_to_hf.py
|
| 723 |
+
src/transformers/models/pop2piano/feature_extraction_pop2piano.py
|
| 724 |
+
src/transformers/models/pop2piano/processing_pop2piano.py
|
| 725 |
+
src/transformers/models/pop2piano/tokenization_pop2piano.py
|
| 726 |
+
src/transformers/models/prophetnet/configuration_prophetnet.py
|
| 727 |
+
src/transformers/models/prophetnet/convert_prophetnet_original_pytorch_checkpoint_to_pytorch.py
|
| 728 |
+
src/transformers/models/prophetnet/modeling_prophetnet.py
|
| 729 |
+
src/transformers/models/pvt/configuration_pvt.py
|
| 730 |
+
src/transformers/models/pvt/convert_pvt_to_pytorch.py
|
| 731 |
+
src/transformers/models/pvt/image_processing_pvt.py
|
| 732 |
+
src/transformers/models/pvt/modeling_pvt.py
|
| 733 |
+
src/transformers/models/qwen2/configuration_qwen2.py
|
| 734 |
+
src/transformers/models/qwen2/modeling_qwen2.py
|
| 735 |
+
src/transformers/models/qwen2/tokenization_qwen2.py
|
| 736 |
+
src/transformers/models/qwen2/tokenization_qwen2_fast.py
|
| 737 |
+
src/transformers/models/qwen2_moe/configuration_qwen2_moe.py
|
| 738 |
+
src/transformers/models/qwen2_moe/modeling_qwen2_moe.py
|
| 739 |
+
src/transformers/models/rag/configuration_rag.py
|
| 740 |
+
src/transformers/models/rag/modeling_rag.py
|
| 741 |
+
src/transformers/models/rag/modeling_tf_rag.py
|
| 742 |
+
src/transformers/models/rag/retrieval_rag.py
|
| 743 |
+
src/transformers/models/recurrent_gemma/modeling_recurrent_gemma.py
|
| 744 |
+
src/transformers/models/reformer/convert_reformer_trax_checkpoint_to_pytorch.py
|
| 745 |
+
src/transformers/models/regnet/configuration_regnet.py
|
| 746 |
+
src/transformers/models/regnet/convert_regnet_seer_10b_to_pytorch.py
|
| 747 |
+
src/transformers/models/regnet/convert_regnet_to_pytorch.py
|
| 748 |
+
src/transformers/models/regnet/modeling_flax_regnet.py
|
| 749 |
+
src/transformers/models/rembert/configuration_rembert.py
|
| 750 |
+
src/transformers/models/rembert/convert_rembert_tf_checkpoint_to_pytorch.py
|
| 751 |
+
src/transformers/models/rembert/modeling_rembert.py
|
| 752 |
+
src/transformers/models/rembert/modeling_tf_rembert.py
|
| 753 |
+
src/transformers/models/resnet/convert_resnet_to_pytorch.py
|
| 754 |
+
src/transformers/models/resnet/modeling_flax_resnet.py
|
| 755 |
+
src/transformers/models/roberta/convert_roberta_original_pytorch_checkpoint_to_pytorch.py
|
| 756 |
+
src/transformers/models/roberta/modeling_flax_roberta.py
|
| 757 |
+
src/transformers/models/roberta_prelayernorm/convert_roberta_prelayernorm_original_pytorch_checkpoint_to_pytorch.py
|
| 758 |
+
src/transformers/models/roberta_prelayernorm/modeling_flax_roberta_prelayernorm.py
|
| 759 |
+
src/transformers/models/roc_bert/configuration_roc_bert.py
|
| 760 |
+
src/transformers/models/roformer/convert_roformer_original_tf_checkpoint_to_pytorch.py
|
| 761 |
+
src/transformers/models/roformer/modeling_flax_roformer.py
|
| 762 |
+
src/transformers/models/roformer/modeling_roformer.py
|
| 763 |
+
src/transformers/models/roformer/modeling_tf_roformer.py
|
| 764 |
+
src/transformers/models/rwkv/configuration_rwkv.py
|
| 765 |
+
src/transformers/models/rwkv/convert_rwkv_checkpoint_to_hf.py
|
| 766 |
+
src/transformers/models/rwkv/modeling_rwkv.py
|
| 767 |
+
src/transformers/models/sam/configuration_sam.py
|
| 768 |
+
src/transformers/models/sam/convert_sam_to_hf.py
|
| 769 |
+
src/transformers/models/sam/image_processing_sam.py
|
| 770 |
+
src/transformers/models/sam/modeling_sam.py
|
| 771 |
+
src/transformers/models/sam/modeling_tf_sam.py
|
| 772 |
+
src/transformers/models/sam/processing_sam.py
|
| 773 |
+
src/transformers/models/seamless_m4t/convert_fairseq2_to_hf.py
|
| 774 |
+
src/transformers/models/seamless_m4t_v2/convert_fairseq2_to_hf.py
|
| 775 |
+
src/transformers/models/segformer/configuration_segformer.py
|
| 776 |
+
src/transformers/models/segformer/convert_segformer_original_to_pytorch.py
|
| 777 |
+
src/transformers/models/sew/convert_sew_original_pytorch_checkpoint_to_pytorch.py
|
| 778 |
+
src/transformers/models/sew_d/convert_sew_d_original_pytorch_checkpoint_to_pytorch.py
|
| 779 |
+
src/transformers/models/speech_encoder_decoder/configuration_speech_encoder_decoder.py
|
| 780 |
+
src/transformers/models/speech_encoder_decoder/convert_mbart_wav2vec2_seq2seq_original_to_pytorch.py
|
| 781 |
+
src/transformers/models/speech_encoder_decoder/convert_speech_to_text_wav2vec2_seq2seq_original_to_pytorch.py
|
| 782 |
+
src/transformers/models/speech_encoder_decoder/modeling_flax_speech_encoder_decoder.py
|
| 783 |
+
src/transformers/models/speech_to_text/convert_s2t_fairseq_to_tfms.py
|
| 784 |
+
src/transformers/models/speech_to_text/modeling_tf_speech_to_text.py
|
| 785 |
+
src/transformers/models/speecht5/configuration_speecht5.py
|
| 786 |
+
src/transformers/models/speecht5/convert_hifigan.py
|
| 787 |
+
src/transformers/models/speecht5/convert_speecht5_original_pytorch_checkpoint_to_pytorch.py
|
| 788 |
+
src/transformers/models/speecht5/number_normalizer.py
|
| 789 |
+
src/transformers/models/splinter/configuration_splinter.py
|
| 790 |
+
src/transformers/models/splinter/modeling_splinter.py
|
| 791 |
+
src/transformers/models/squeezebert/modeling_squeezebert.py
|
| 792 |
+
src/transformers/models/stablelm/modeling_stablelm.py
|
| 793 |
+
src/transformers/models/starcoder2/modeling_starcoder2.py
|
| 794 |
+
src/transformers/models/swiftformer/configuration_swiftformer.py
|
| 795 |
+
src/transformers/models/swiftformer/convert_swiftformer_original_to_hf.py
|
| 796 |
+
src/transformers/models/swiftformer/modeling_swiftformer.py
|
| 797 |
+
src/transformers/models/swin/convert_swin_simmim_to_pytorch.py
|
| 798 |
+
src/transformers/models/swin/convert_swin_timm_to_pytorch.py
|
| 799 |
+
src/transformers/models/swin/modeling_tf_swin.py
|
| 800 |
+
src/transformers/models/swin2sr/configuration_swin2sr.py
|
| 801 |
+
src/transformers/models/swin2sr/convert_swin2sr_original_to_pytorch.py
|
| 802 |
+
src/transformers/models/swinv2/convert_swinv2_timm_to_pytorch.py
|
| 803 |
+
src/transformers/models/swinv2/modeling_swinv2.py
|
| 804 |
+
src/transformers/models/switch_transformers/configuration_switch_transformers.py
|
| 805 |
+
src/transformers/models/switch_transformers/convert_big_switch.py
|
| 806 |
+
src/transformers/models/switch_transformers/convert_switch_transformers_original_flax_checkpoint_to_pytorch.py
|
| 807 |
+
src/transformers/models/switch_transformers/modeling_switch_transformers.py
|
| 808 |
+
src/transformers/models/t5/configuration_t5.py
|
| 809 |
+
src/transformers/models/t5/convert_t5_original_tf_checkpoint_to_pytorch.py
|
| 810 |
+
src/transformers/models/t5/convert_t5x_checkpoint_to_flax.py
|
| 811 |
+
src/transformers/models/t5/convert_t5x_checkpoint_to_pytorch.py
|
| 812 |
+
src/transformers/models/t5/modeling_flax_t5.py
|
| 813 |
+
src/transformers/models/t5/modeling_t5.py
|
| 814 |
+
src/transformers/models/t5/modeling_tf_t5.py
|
| 815 |
+
src/transformers/models/table_transformer/configuration_table_transformer.py
|
| 816 |
+
src/transformers/models/table_transformer/convert_table_transformer_to_hf.py
|
| 817 |
+
src/transformers/models/table_transformer/convert_table_transformer_to_hf_no_timm.py
|
| 818 |
+
src/transformers/models/tapas/configuration_tapas.py
|
| 819 |
+
src/transformers/models/tapas/convert_tapas_original_tf_checkpoint_to_pytorch.py
|
| 820 |
+
src/transformers/models/tapas/modeling_tapas.py
|
| 821 |
+
src/transformers/models/tapas/modeling_tf_tapas.py
|
| 822 |
+
src/transformers/models/timesformer/convert_timesformer_to_pytorch.py
|
| 823 |
+
src/transformers/models/timm_backbone/configuration_timm_backbone.py
|
| 824 |
+
src/transformers/models/timm_backbone/modeling_timm_backbone.py
|
| 825 |
+
src/transformers/models/trocr/convert_trocr_unilm_to_pytorch.py
|
| 826 |
+
src/transformers/models/umt5/configuration_umt5.py
|
| 827 |
+
src/transformers/models/umt5/convert_umt5_checkpoint_to_pytorch.py
|
| 828 |
+
src/transformers/models/umt5/modeling_umt5.py
|
| 829 |
+
src/transformers/models/unispeech/convert_unispeech_original_pytorch_checkpoint_to_pytorch.py
|
| 830 |
+
src/transformers/models/unispeech_sat/configuration_unispeech_sat.py
|
| 831 |
+
src/transformers/models/unispeech_sat/convert_unispeech_original_s3prl_checkpoint_to_pytorch.py
|
| 832 |
+
src/transformers/models/unispeech_sat/convert_unispeech_sat_original_pytorch_checkpoint_to_pytorch.py
|
| 833 |
+
src/transformers/models/upernet/configuration_upernet.py
|
| 834 |
+
src/transformers/models/upernet/convert_convnext_upernet_to_pytorch.py
|
| 835 |
+
src/transformers/models/upernet/convert_swin_upernet_to_pytorch.py
|
| 836 |
+
src/transformers/models/videomae/configuration_videomae.py
|
| 837 |
+
src/transformers/models/videomae/convert_videomae_to_pytorch.py
|
| 838 |
+
src/transformers/models/vilt/configuration_vilt.py
|
| 839 |
+
src/transformers/models/vilt/convert_vilt_original_to_pytorch.py
|
| 840 |
+
src/transformers/models/vipllava/configuration_vipllava.py
|
| 841 |
+
src/transformers/models/vipllava/modeling_vipllava.py
|
| 842 |
+
src/transformers/models/vision_encoder_decoder/modeling_flax_vision_encoder_decoder.py
|
| 843 |
+
src/transformers/models/vision_encoder_decoder/modeling_tf_vision_encoder_decoder.py
|
| 844 |
+
src/transformers/models/vision_text_dual_encoder/modeling_flax_vision_text_dual_encoder.py
|
| 845 |
+
src/transformers/models/vision_text_dual_encoder/modeling_vision_text_dual_encoder.py
|
| 846 |
+
src/transformers/models/visual_bert/convert_visual_bert_original_pytorch_checkpoint_to_pytorch.py
|
| 847 |
+
src/transformers/models/visual_bert/modeling_visual_bert.py
|
| 848 |
+
src/transformers/models/vit/convert_dino_to_pytorch.py
|
| 849 |
+
src/transformers/models/vit/convert_vit_timm_to_pytorch.py
|
| 850 |
+
src/transformers/models/vit/modeling_flax_vit.py
|
| 851 |
+
src/transformers/models/vit_mae/convert_vit_mae_to_pytorch.py
|
| 852 |
+
src/transformers/models/vit_mae/modeling_tf_vit_mae.py
|
| 853 |
+
src/transformers/models/vit_msn/configuration_vit_msn.py
|
| 854 |
+
src/transformers/models/vit_msn/convert_msn_to_pytorch.py
|
| 855 |
+
src/transformers/models/vivit/configuration_vivit.py
|
| 856 |
+
src/transformers/models/vivit/convert_vivit_flax_to_pytorch.py
|
| 857 |
+
src/transformers/models/vivit/image_processing_vivit.py
|
| 858 |
+
src/transformers/models/vivit/modeling_vivit.py
|
| 859 |
+
src/transformers/models/wav2vec2/convert_wav2vec2_original_pytorch_checkpoint_to_pytorch.py
|
| 860 |
+
src/transformers/models/wav2vec2/convert_wav2vec2_original_s3prl_checkpoint_to_pytorch.py
|
| 861 |
+
src/transformers/models/wav2vec2/modeling_flax_wav2vec2.py
|
| 862 |
+
src/transformers/models/wav2vec2/modeling_tf_wav2vec2.py
|
| 863 |
+
src/transformers/models/wav2vec2_bert/convert_wav2vec2_seamless_checkpoint.py
|
| 864 |
+
src/transformers/models/wav2vec2_conformer/convert_wav2vec2_conformer_original_pytorch_checkpoint_to_pytorch.py
|
| 865 |
+
src/transformers/models/wavlm/convert_wavlm_original_pytorch_checkpoint_to_pytorch.py
|
| 866 |
+
src/transformers/models/wavlm/convert_wavlm_original_s3prl_checkpoint_to_pytorch.py
|
| 867 |
+
src/transformers/models/whisper/convert_openai_to_hf.py
|
| 868 |
+
src/transformers/models/whisper/english_normalizer.py
|
| 869 |
+
src/transformers/models/whisper/modeling_flax_whisper.py
|
| 870 |
+
src/transformers/models/x_clip/configuration_x_clip.py
|
| 871 |
+
src/transformers/models/x_clip/convert_x_clip_original_pytorch_to_hf.py
|
| 872 |
+
src/transformers/models/xglm/configuration_xglm.py
|
| 873 |
+
src/transformers/models/xglm/convert_xglm_original_ckpt_to_trfms.py
|
| 874 |
+
src/transformers/models/xglm/modeling_flax_xglm.py
|
| 875 |
+
src/transformers/models/xglm/modeling_tf_xglm.py
|
| 876 |
+
src/transformers/models/xglm/modeling_xglm.py
|
| 877 |
+
src/transformers/models/xlm/convert_xlm_original_pytorch_checkpoint_to_pytorch.py
|
| 878 |
+
src/transformers/models/xlm/modeling_tf_xlm.py
|
| 879 |
+
src/transformers/models/xlm/modeling_xlm.py
|
| 880 |
+
src/transformers/models/xlm_roberta/modeling_flax_xlm_roberta.py
|
| 881 |
+
src/transformers/models/xlm_roberta/modeling_tf_xlm_roberta.py
|
| 882 |
+
src/transformers/models/xlm_roberta/modeling_xlm_roberta.py
|
| 883 |
+
src/transformers/models/xlm_roberta_xl/convert_xlm_roberta_xl_original_pytorch_checkpoint_to_pytorch.py
|
| 884 |
+
src/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py
|
| 885 |
+
src/transformers/models/xlnet/convert_xlnet_original_tf_checkpoint_to_pytorch.py
|
| 886 |
+
src/transformers/models/xlnet/modeling_tf_xlnet.py
|
| 887 |
+
src/transformers/models/xlnet/modeling_xlnet.py
|
| 888 |
+
src/transformers/models/xmod/convert_xmod_original_pytorch_checkpoint_to_pytorch.py
|
| 889 |
+
src/transformers/models/yolos/convert_yolos_to_pytorch.py
|
| 890 |
+
src/transformers/models/yoso/convert_yoso_pytorch_to_pytorch.py
|
| 891 |
+
src/transformers/models/yoso/modeling_yoso.py
|
| 892 |
+
src/transformers/models/zamba/configuration_zamba.py
|
| 893 |
+
src/transformers/models/zamba/modeling_zamba.py
|
| 894 |
+
src/transformers/onnx/__main__.py
|
| 895 |
+
src/transformers/onnx/config.py
|
| 896 |
+
src/transformers/onnx/convert.py
|
| 897 |
+
src/transformers/onnx/features.py
|
| 898 |
+
src/transformers/onnx/utils.py
|
| 899 |
+
src/transformers/optimization.py
|
| 900 |
+
src/transformers/optimization_tf.py
|
| 901 |
+
src/transformers/pipelines/audio_classification.py
|
| 902 |
+
src/transformers/pipelines/audio_utils.py
|
| 903 |
+
src/transformers/pipelines/automatic_speech_recognition.py
|
| 904 |
+
src/transformers/pipelines/base.py
|
| 905 |
+
src/transformers/pipelines/depth_estimation.py
|
| 906 |
+
src/transformers/pipelines/document_question_answering.py
|
| 907 |
+
src/transformers/pipelines/feature_extraction.py
|
| 908 |
+
src/transformers/pipelines/fill_mask.py
|
| 909 |
+
src/transformers/pipelines/image_classification.py
|
| 910 |
+
src/transformers/pipelines/image_segmentation.py
|
| 911 |
+
src/transformers/pipelines/image_to_text.py
|
| 912 |
+
src/transformers/pipelines/mask_generation.py
|
| 913 |
+
src/transformers/pipelines/object_detection.py
|
| 914 |
+
src/transformers/pipelines/pt_utils.py
|
| 915 |
+
src/transformers/pipelines/question_answering.py
|
| 916 |
+
src/transformers/pipelines/table_question_answering.py
|
| 917 |
+
src/transformers/pipelines/text_classification.py
|
| 918 |
+
src/transformers/pipelines/token_classification.py
|
| 919 |
+
src/transformers/pipelines/video_classification.py
|
| 920 |
+
src/transformers/pipelines/visual_question_answering.py
|
| 921 |
+
src/transformers/pipelines/zero_shot_audio_classification.py
|
| 922 |
+
src/transformers/pipelines/zero_shot_classification.py
|
| 923 |
+
src/transformers/pipelines/zero_shot_image_classification.py
|
| 924 |
+
src/transformers/pipelines/zero_shot_object_detection.py
|
| 925 |
+
src/transformers/processing_utils.py
|
| 926 |
+
src/transformers/pytorch_utils.py
|
| 927 |
+
src/transformers/quantizers/auto.py
|
| 928 |
+
src/transformers/quantizers/base.py
|
| 929 |
+
src/transformers/quantizers/quantizer_awq.py
|
| 930 |
+
src/transformers/quantizers/quantizer_bnb_4bit.py
|
| 931 |
+
src/transformers/quantizers/quantizer_bnb_8bit.py
|
| 932 |
+
src/transformers/quantizers/quantizer_gptq.py
|
| 933 |
+
src/transformers/quantizers/quantizers_utils.py
|
| 934 |
+
src/transformers/sagemaker/trainer_sm.py
|
| 935 |
+
src/transformers/sagemaker/training_args_sm.py
|
| 936 |
+
src/transformers/testing_utils.py
|
| 937 |
+
src/transformers/tf_utils.py
|
| 938 |
+
src/transformers/time_series_utils.py
|
| 939 |
+
src/transformers/tokenization_utils.py
|
| 940 |
+
src/transformers/tokenization_utils_base.py
|
| 941 |
+
src/transformers/tokenization_utils_fast.py
|
| 942 |
+
src/transformers/trainer.py
|
| 943 |
+
src/transformers/trainer_callback.py
|
| 944 |
+
src/transformers/trainer_pt_utils.py
|
| 945 |
+
src/transformers/trainer_seq2seq.py
|
| 946 |
+
src/transformers/trainer_utils.py
|
| 947 |
+
src/transformers/training_args.py
|
| 948 |
+
src/transformers/training_args_seq2seq.py
|
| 949 |
+
src/transformers/training_args_tf.py
|
| 950 |
+
src/transformers/utils/backbone_utils.py
|
| 951 |
+
src/transformers/utils/bitsandbytes.py
|
| 952 |
+
src/transformers/utils/constants.py
|
| 953 |
+
src/transformers/utils/doc.py
|
| 954 |
+
src/transformers/utils/dummy_detectron2_objects.py
|
| 955 |
+
src/transformers/utils/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.py
|
| 956 |
+
src/transformers/utils/dummy_flax_objects.py
|
| 957 |
+
src/transformers/utils/dummy_keras_nlp_objects.py
|
| 958 |
+
src/transformers/utils/dummy_music_objects.py
|
| 959 |
+
src/transformers/utils/dummy_pt_objects.py
|
| 960 |
+
src/transformers/utils/dummy_sentencepiece_and_tokenizers_objects.py
|
| 961 |
+
src/transformers/utils/dummy_sentencepiece_objects.py
|
| 962 |
+
src/transformers/utils/dummy_speech_objects.py
|
| 963 |
+
src/transformers/utils/dummy_tensorflow_text_objects.py
|
| 964 |
+
src/transformers/utils/dummy_tf_objects.py
|
| 965 |
+
src/transformers/utils/dummy_tokenizers_objects.py
|
| 966 |
+
src/transformers/utils/dummy_vision_objects.py
|
| 967 |
+
src/transformers/utils/fx.py
|
| 968 |
+
src/transformers/utils/generic.py
|
| 969 |
+
src/transformers/utils/hp_naming.py
|
| 970 |
+
src/transformers/utils/hub.py
|
| 971 |
+
src/transformers/utils/import_utils.py
|
| 972 |
+
src/transformers/utils/logging.py
|
| 973 |
+
src/transformers/utils/model_parallel_utils.py
|
| 974 |
+
src/transformers/utils/notebook.py
|
| 975 |
+
src/transformers/utils/peft_utils.py
|
| 976 |
+
src/transformers/utils/quantization_config.py
|
| 977 |
+
src/transformers/utils/sentencepiece_model_pb2.py
|
| 978 |
+
src/transformers/utils/sentencepiece_model_pb2_new.py
|
| 979 |
+
src/transformers/utils/versions.py
|
tasks/tasksmith-441eeab80047/environment/source/utils/notification_service.py
ADDED
|
@@ -0,0 +1,1285 @@
|
|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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 |
+
import ast
|
| 16 |
+
import collections
|
| 17 |
+
import datetime
|
| 18 |
+
import functools
|
| 19 |
+
import json
|
| 20 |
+
import operator
|
| 21 |
+
import os
|
| 22 |
+
import re
|
| 23 |
+
import sys
|
| 24 |
+
import time
|
| 25 |
+
from typing import Dict, List, Optional, Union
|
| 26 |
+
|
| 27 |
+
import requests
|
| 28 |
+
from get_ci_error_statistics import get_jobs
|
| 29 |
+
from get_previous_daily_ci import get_last_daily_ci_reports
|
| 30 |
+
from huggingface_hub import HfApi
|
| 31 |
+
from slack_sdk import WebClient
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
api = HfApi()
|
| 35 |
+
client = WebClient(token=os.environ["CI_SLACK_BOT_TOKEN"])
|
| 36 |
+
|
| 37 |
+
NON_MODEL_TEST_MODULES = [
|
| 38 |
+
"deepspeed",
|
| 39 |
+
"extended",
|
| 40 |
+
"fixtures",
|
| 41 |
+
"generation",
|
| 42 |
+
"onnx",
|
| 43 |
+
"optimization",
|
| 44 |
+
"pipelines",
|
| 45 |
+
"sagemaker",
|
| 46 |
+
"trainer",
|
| 47 |
+
"utils",
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def handle_test_results(test_results):
|
| 52 |
+
expressions = test_results.split(" ")
|
| 53 |
+
|
| 54 |
+
failed = 0
|
| 55 |
+
success = 0
|
| 56 |
+
|
| 57 |
+
# When the output is short enough, the output is surrounded by = signs: "== OUTPUT =="
|
| 58 |
+
# When it is too long, those signs are not present.
|
| 59 |
+
time_spent = expressions[-2] if "=" in expressions[-1] else expressions[-1]
|
| 60 |
+
|
| 61 |
+
for i, expression in enumerate(expressions):
|
| 62 |
+
if "failed" in expression:
|
| 63 |
+
failed += int(expressions[i - 1])
|
| 64 |
+
if "passed" in expression:
|
| 65 |
+
success += int(expressions[i - 1])
|
| 66 |
+
|
| 67 |
+
return failed, success, time_spent
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def handle_stacktraces(test_results):
|
| 71 |
+
# These files should follow the following architecture:
|
| 72 |
+
# === FAILURES ===
|
| 73 |
+
# <path>:<line>: Error ...
|
| 74 |
+
# <path>:<line>: Error ...
|
| 75 |
+
# <empty line>
|
| 76 |
+
|
| 77 |
+
total_stacktraces = test_results.split("\n")[1:-1]
|
| 78 |
+
stacktraces = []
|
| 79 |
+
for stacktrace in total_stacktraces:
|
| 80 |
+
try:
|
| 81 |
+
line = stacktrace[: stacktrace.index(" ")].split(":")[-2]
|
| 82 |
+
error_message = stacktrace[stacktrace.index(" ") :]
|
| 83 |
+
|
| 84 |
+
stacktraces.append(f"(line {line}) {error_message}")
|
| 85 |
+
except Exception:
|
| 86 |
+
stacktraces.append("Cannot retrieve error message.")
|
| 87 |
+
|
| 88 |
+
return stacktraces
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def dicts_to_sum(objects: Union[Dict[str, Dict], List[dict]]):
|
| 92 |
+
if isinstance(objects, dict):
|
| 93 |
+
lists = objects.values()
|
| 94 |
+
else:
|
| 95 |
+
lists = objects
|
| 96 |
+
|
| 97 |
+
# Convert each dictionary to counter
|
| 98 |
+
counters = map(collections.Counter, lists)
|
| 99 |
+
# Sum all the counters
|
| 100 |
+
return functools.reduce(operator.add, counters)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class Message:
|
| 104 |
+
def __init__(
|
| 105 |
+
self,
|
| 106 |
+
title: str,
|
| 107 |
+
ci_title: str,
|
| 108 |
+
model_results: Dict,
|
| 109 |
+
additional_results: Dict,
|
| 110 |
+
selected_warnings: List = None,
|
| 111 |
+
prev_ci_artifacts=None,
|
| 112 |
+
):
|
| 113 |
+
self.title = title
|
| 114 |
+
self.ci_title = ci_title
|
| 115 |
+
|
| 116 |
+
# Failures and success of the modeling tests
|
| 117 |
+
self.n_model_success = sum(r["success"] for r in model_results.values())
|
| 118 |
+
self.n_model_single_gpu_failures = sum(dicts_to_sum(r["failed"])["single"] for r in model_results.values())
|
| 119 |
+
self.n_model_multi_gpu_failures = sum(dicts_to_sum(r["failed"])["multi"] for r in model_results.values())
|
| 120 |
+
|
| 121 |
+
# Some suites do not have a distinction between single and multi GPU.
|
| 122 |
+
self.n_model_unknown_failures = sum(dicts_to_sum(r["failed"])["unclassified"] for r in model_results.values())
|
| 123 |
+
self.n_model_failures = (
|
| 124 |
+
self.n_model_single_gpu_failures + self.n_model_multi_gpu_failures + self.n_model_unknown_failures
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
# Failures and success of the additional tests
|
| 128 |
+
self.n_additional_success = sum(r["success"] for r in additional_results.values())
|
| 129 |
+
|
| 130 |
+
if len(additional_results) > 0:
|
| 131 |
+
# `dicts_to_sum` uses `dicts_to_sum` which requires a non empty dictionary. Let's just add an empty entry.
|
| 132 |
+
all_additional_failures = dicts_to_sum([r["failed"] for r in additional_results.values()])
|
| 133 |
+
self.n_additional_single_gpu_failures = all_additional_failures["single"]
|
| 134 |
+
self.n_additional_multi_gpu_failures = all_additional_failures["multi"]
|
| 135 |
+
self.n_additional_unknown_gpu_failures = all_additional_failures["unclassified"]
|
| 136 |
+
else:
|
| 137 |
+
self.n_additional_single_gpu_failures = 0
|
| 138 |
+
self.n_additional_multi_gpu_failures = 0
|
| 139 |
+
self.n_additional_unknown_gpu_failures = 0
|
| 140 |
+
|
| 141 |
+
self.n_additional_failures = (
|
| 142 |
+
self.n_additional_single_gpu_failures
|
| 143 |
+
+ self.n_additional_multi_gpu_failures
|
| 144 |
+
+ self.n_additional_unknown_gpu_failures
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
# Results
|
| 148 |
+
self.n_failures = self.n_model_failures + self.n_additional_failures
|
| 149 |
+
self.n_success = self.n_model_success + self.n_additional_success
|
| 150 |
+
self.n_tests = self.n_failures + self.n_success
|
| 151 |
+
|
| 152 |
+
self.model_results = model_results
|
| 153 |
+
self.additional_results = additional_results
|
| 154 |
+
|
| 155 |
+
self.thread_ts = None
|
| 156 |
+
|
| 157 |
+
if selected_warnings is None:
|
| 158 |
+
selected_warnings = []
|
| 159 |
+
self.selected_warnings = selected_warnings
|
| 160 |
+
|
| 161 |
+
self.prev_ci_artifacts = prev_ci_artifacts
|
| 162 |
+
|
| 163 |
+
@property
|
| 164 |
+
def time(self) -> str:
|
| 165 |
+
all_results = [*self.model_results.values(), *self.additional_results.values()]
|
| 166 |
+
time_spent = [r["time_spent"].split(", ")[0] for r in all_results if len(r["time_spent"])]
|
| 167 |
+
total_secs = 0
|
| 168 |
+
|
| 169 |
+
for time in time_spent:
|
| 170 |
+
time_parts = time.split(":")
|
| 171 |
+
|
| 172 |
+
# Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute.
|
| 173 |
+
if len(time_parts) == 1:
|
| 174 |
+
time_parts = [0, 0, time_parts[0]]
|
| 175 |
+
|
| 176 |
+
hours, minutes, seconds = int(time_parts[0]), int(time_parts[1]), float(time_parts[2])
|
| 177 |
+
total_secs += hours * 3600 + minutes * 60 + seconds
|
| 178 |
+
|
| 179 |
+
hours, minutes, seconds = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60
|
| 180 |
+
return f"{int(hours)}h{int(minutes)}m{int(seconds)}s"
|
| 181 |
+
|
| 182 |
+
@property
|
| 183 |
+
def header(self) -> Dict:
|
| 184 |
+
return {"type": "header", "text": {"type": "plain_text", "text": self.title}}
|
| 185 |
+
|
| 186 |
+
@property
|
| 187 |
+
def ci_title_section(self) -> Dict:
|
| 188 |
+
return {"type": "section", "text": {"type": "mrkdwn", "text": self.ci_title}}
|
| 189 |
+
|
| 190 |
+
@property
|
| 191 |
+
def no_failures(self) -> Dict:
|
| 192 |
+
return {
|
| 193 |
+
"type": "section",
|
| 194 |
+
"text": {
|
| 195 |
+
"type": "plain_text",
|
| 196 |
+
"text": f"🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.",
|
| 197 |
+
"emoji": True,
|
| 198 |
+
},
|
| 199 |
+
"accessory": {
|
| 200 |
+
"type": "button",
|
| 201 |
+
"text": {"type": "plain_text", "text": "Check Action results", "emoji": True},
|
| 202 |
+
"url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}",
|
| 203 |
+
},
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
@property
|
| 207 |
+
def failures(self) -> Dict:
|
| 208 |
+
return {
|
| 209 |
+
"type": "section",
|
| 210 |
+
"text": {
|
| 211 |
+
"type": "plain_text",
|
| 212 |
+
"text": (
|
| 213 |
+
f"There were {self.n_failures} failures, out of {self.n_tests} tests.\n"
|
| 214 |
+
f"Number of model failures: {self.n_model_failures}.\n"
|
| 215 |
+
f"The suite ran in {self.time}."
|
| 216 |
+
),
|
| 217 |
+
"emoji": True,
|
| 218 |
+
},
|
| 219 |
+
"accessory": {
|
| 220 |
+
"type": "button",
|
| 221 |
+
"text": {"type": "plain_text", "text": "Check Action results", "emoji": True},
|
| 222 |
+
"url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}",
|
| 223 |
+
},
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
@property
|
| 227 |
+
def warnings(self) -> Dict:
|
| 228 |
+
# If something goes wrong, let's avoid the CI report failing to be sent.
|
| 229 |
+
button_text = "Check warnings (Link not found)"
|
| 230 |
+
# Use the workflow run link
|
| 231 |
+
job_link = f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}"
|
| 232 |
+
|
| 233 |
+
for job in github_actions_jobs:
|
| 234 |
+
if "Extract warnings in CI artifacts" in job["name"] and job["conclusion"] == "success":
|
| 235 |
+
button_text = "Check warnings"
|
| 236 |
+
# Use the actual job link
|
| 237 |
+
job_link = job["html_url"]
|
| 238 |
+
break
|
| 239 |
+
|
| 240 |
+
huggingface_hub_warnings = [x for x in self.selected_warnings if "huggingface_hub" in x]
|
| 241 |
+
text = f"There are {len(self.selected_warnings)} warnings being selected."
|
| 242 |
+
text += f"\n{len(huggingface_hub_warnings)} of them are from `huggingface_hub`."
|
| 243 |
+
|
| 244 |
+
return {
|
| 245 |
+
"type": "section",
|
| 246 |
+
"text": {
|
| 247 |
+
"type": "plain_text",
|
| 248 |
+
"text": text,
|
| 249 |
+
"emoji": True,
|
| 250 |
+
},
|
| 251 |
+
"accessory": {
|
| 252 |
+
"type": "button",
|
| 253 |
+
"text": {"type": "plain_text", "text": button_text, "emoji": True},
|
| 254 |
+
"url": job_link,
|
| 255 |
+
},
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
@staticmethod
|
| 259 |
+
def get_device_report(report, rjust=6):
|
| 260 |
+
if "single" in report and "multi" in report:
|
| 261 |
+
return f"{str(report['single']).rjust(rjust)} | {str(report['multi']).rjust(rjust)} | "
|
| 262 |
+
elif "single" in report:
|
| 263 |
+
return f"{str(report['single']).rjust(rjust)} | {'0'.rjust(rjust)} | "
|
| 264 |
+
elif "multi" in report:
|
| 265 |
+
return f"{'0'.rjust(rjust)} | {str(report['multi']).rjust(rjust)} | "
|
| 266 |
+
|
| 267 |
+
@property
|
| 268 |
+
def category_failures(self) -> Dict:
|
| 269 |
+
model_failures = [v["failed"] for v in self.model_results.values()]
|
| 270 |
+
|
| 271 |
+
category_failures = {}
|
| 272 |
+
|
| 273 |
+
for model_failure in model_failures:
|
| 274 |
+
for key, value in model_failure.items():
|
| 275 |
+
if key not in category_failures:
|
| 276 |
+
category_failures[key] = dict(value)
|
| 277 |
+
else:
|
| 278 |
+
category_failures[key]["unclassified"] += value["unclassified"]
|
| 279 |
+
category_failures[key]["single"] += value["single"]
|
| 280 |
+
category_failures[key]["multi"] += value["multi"]
|
| 281 |
+
|
| 282 |
+
individual_reports = []
|
| 283 |
+
for key, value in category_failures.items():
|
| 284 |
+
device_report = self.get_device_report(value)
|
| 285 |
+
|
| 286 |
+
if sum(value.values()):
|
| 287 |
+
if device_report:
|
| 288 |
+
individual_reports.append(f"{device_report}{key}")
|
| 289 |
+
else:
|
| 290 |
+
individual_reports.append(key)
|
| 291 |
+
|
| 292 |
+
header = "Single | Multi | Category\n"
|
| 293 |
+
category_failures_report = prepare_reports(
|
| 294 |
+
title="The following modeling categories had failures", header=header, reports=individual_reports
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
return {"type": "section", "text": {"type": "mrkdwn", "text": category_failures_report}}
|
| 298 |
+
|
| 299 |
+
def compute_diff_for_failure_reports(self, curr_failure_report, prev_failure_report): # noqa
|
| 300 |
+
# Remove the leading and training parts that don't contain failure count information.
|
| 301 |
+
model_failures = curr_failure_report.split("\n")[3:-2]
|
| 302 |
+
prev_model_failures = prev_failure_report.split("\n")[3:-2]
|
| 303 |
+
entries_changed = set(model_failures).difference(prev_model_failures)
|
| 304 |
+
|
| 305 |
+
prev_map = {}
|
| 306 |
+
for f in prev_model_failures:
|
| 307 |
+
items = [x.strip() for x in f.split("| ")]
|
| 308 |
+
prev_map[items[-1]] = [int(x) for x in items[:-1]]
|
| 309 |
+
|
| 310 |
+
curr_map = {}
|
| 311 |
+
for f in entries_changed:
|
| 312 |
+
items = [x.strip() for x in f.split("| ")]
|
| 313 |
+
curr_map[items[-1]] = [int(x) for x in items[:-1]]
|
| 314 |
+
|
| 315 |
+
diff_map = {}
|
| 316 |
+
for k, v in curr_map.items():
|
| 317 |
+
if k not in prev_map:
|
| 318 |
+
diff_map[k] = v
|
| 319 |
+
else:
|
| 320 |
+
diff = [x - y for x, y in zip(v, prev_map[k])]
|
| 321 |
+
if max(diff) > 0:
|
| 322 |
+
diff_map[k] = diff
|
| 323 |
+
|
| 324 |
+
entries_changed = []
|
| 325 |
+
for model_name, diff_values in diff_map.items():
|
| 326 |
+
diff = [str(x) for x in diff_values]
|
| 327 |
+
diff = [f"+{x}" if (x != "0" and not x.startswith("-")) else x for x in diff]
|
| 328 |
+
diff = [x.rjust(9) for x in diff]
|
| 329 |
+
device_report = " | ".join(diff) + " | "
|
| 330 |
+
report = f"{device_report}{model_name}"
|
| 331 |
+
entries_changed.append(report)
|
| 332 |
+
entries_changed = sorted(entries_changed, key=lambda s: s.split("| ")[-1])
|
| 333 |
+
|
| 334 |
+
return entries_changed
|
| 335 |
+
|
| 336 |
+
@property
|
| 337 |
+
def model_failures(self) -> List[Dict]:
|
| 338 |
+
# Obtain per-model failures
|
| 339 |
+
def per_model_sum(model_category_dict):
|
| 340 |
+
return dicts_to_sum(model_category_dict["failed"].values())
|
| 341 |
+
|
| 342 |
+
failures = {}
|
| 343 |
+
non_model_failures = {
|
| 344 |
+
k: per_model_sum(v) for k, v in self.model_results.items() if sum(per_model_sum(v).values())
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
for k, v in self.model_results.items():
|
| 348 |
+
if k in NON_MODEL_TEST_MODULES:
|
| 349 |
+
pass
|
| 350 |
+
|
| 351 |
+
if sum(per_model_sum(v).values()):
|
| 352 |
+
dict_failed = dict(v["failed"])
|
| 353 |
+
pytorch_specific_failures = dict_failed.pop("PyTorch")
|
| 354 |
+
tensorflow_specific_failures = dict_failed.pop("TensorFlow")
|
| 355 |
+
other_failures = dicts_to_sum(dict_failed.values())
|
| 356 |
+
|
| 357 |
+
failures[k] = {
|
| 358 |
+
"PyTorch": pytorch_specific_failures,
|
| 359 |
+
"TensorFlow": tensorflow_specific_failures,
|
| 360 |
+
"other": other_failures,
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
model_reports = []
|
| 364 |
+
other_module_reports = []
|
| 365 |
+
|
| 366 |
+
for key, value in non_model_failures.items():
|
| 367 |
+
if key in NON_MODEL_TEST_MODULES:
|
| 368 |
+
device_report = self.get_device_report(value)
|
| 369 |
+
|
| 370 |
+
if sum(value.values()):
|
| 371 |
+
if device_report:
|
| 372 |
+
report = f"{device_report}{key}"
|
| 373 |
+
else:
|
| 374 |
+
report = key
|
| 375 |
+
|
| 376 |
+
other_module_reports.append(report)
|
| 377 |
+
|
| 378 |
+
for key, value in failures.items():
|
| 379 |
+
device_report_values = [
|
| 380 |
+
value["PyTorch"]["single"],
|
| 381 |
+
value["PyTorch"]["multi"],
|
| 382 |
+
value["TensorFlow"]["single"],
|
| 383 |
+
value["TensorFlow"]["multi"],
|
| 384 |
+
sum(value["other"].values()),
|
| 385 |
+
]
|
| 386 |
+
|
| 387 |
+
if sum(device_report_values):
|
| 388 |
+
device_report = " | ".join([str(x).rjust(9) for x in device_report_values]) + " | "
|
| 389 |
+
report = f"{device_report}{key}"
|
| 390 |
+
|
| 391 |
+
model_reports.append(report)
|
| 392 |
+
|
| 393 |
+
# (Possibly truncated) reports for the current workflow run - to be sent to Slack channels
|
| 394 |
+
model_header = "Single PT | Multi PT | Single TF | Multi TF | Other | Category\n"
|
| 395 |
+
sorted_model_reports = sorted(model_reports, key=lambda s: s.split("| ")[-1])
|
| 396 |
+
model_failures_report = prepare_reports(
|
| 397 |
+
title="These following model modules had failures", header=model_header, reports=sorted_model_reports
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
module_header = "Single | Multi | Category\n"
|
| 401 |
+
sorted_module_reports = sorted(other_module_reports, key=lambda s: s.split("| ")[-1])
|
| 402 |
+
module_failures_report = prepare_reports(
|
| 403 |
+
title="The following non-model modules had failures", header=module_header, reports=sorted_module_reports
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
# To be sent to Slack channels
|
| 407 |
+
model_failure_sections = [
|
| 408 |
+
{"type": "section", "text": {"type": "mrkdwn", "text": model_failures_report}},
|
| 409 |
+
{"type": "section", "text": {"type": "mrkdwn", "text": module_failures_report}},
|
| 410 |
+
]
|
| 411 |
+
|
| 412 |
+
# Save the complete (i.e. no truncation) failure tables (of the current workflow run)
|
| 413 |
+
# (to be uploaded as artifacts)
|
| 414 |
+
|
| 415 |
+
model_failures_report = prepare_reports(
|
| 416 |
+
title="These following model modules had failures",
|
| 417 |
+
header=model_header,
|
| 418 |
+
reports=sorted_model_reports,
|
| 419 |
+
to_truncate=False,
|
| 420 |
+
)
|
| 421 |
+
file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/model_failures_report.txt")
|
| 422 |
+
with open(file_path, "w", encoding="UTF-8") as fp:
|
| 423 |
+
fp.write(model_failures_report)
|
| 424 |
+
|
| 425 |
+
module_failures_report = prepare_reports(
|
| 426 |
+
title="The following non-model modules had failures",
|
| 427 |
+
header=module_header,
|
| 428 |
+
reports=sorted_module_reports,
|
| 429 |
+
to_truncate=False,
|
| 430 |
+
)
|
| 431 |
+
file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/module_failures_report.txt")
|
| 432 |
+
with open(file_path, "w", encoding="UTF-8") as fp:
|
| 433 |
+
fp.write(module_failures_report)
|
| 434 |
+
|
| 435 |
+
if self.prev_ci_artifacts is not None:
|
| 436 |
+
# if the last run produces artifact named `ci_results_{job_name}`
|
| 437 |
+
if (
|
| 438 |
+
f"ci_results_{job_name}" in self.prev_ci_artifacts
|
| 439 |
+
and "model_failures_report.txt" in self.prev_ci_artifacts[f"ci_results_{job_name}"]
|
| 440 |
+
):
|
| 441 |
+
# Compute the difference of the previous/current (model failure) table
|
| 442 |
+
prev_model_failures = self.prev_ci_artifacts[f"ci_results_{job_name}"]["model_failures_report.txt"]
|
| 443 |
+
entries_changed = self.compute_diff_for_failure_reports(model_failures_report, prev_model_failures)
|
| 444 |
+
if len(entries_changed) > 0:
|
| 445 |
+
# Save the complete difference
|
| 446 |
+
diff_report = prepare_reports(
|
| 447 |
+
title="Changed model modules failures",
|
| 448 |
+
header=model_header,
|
| 449 |
+
reports=entries_changed,
|
| 450 |
+
to_truncate=False,
|
| 451 |
+
)
|
| 452 |
+
file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/changed_model_failures_report.txt")
|
| 453 |
+
with open(file_path, "w", encoding="UTF-8") as fp:
|
| 454 |
+
fp.write(diff_report)
|
| 455 |
+
|
| 456 |
+
# To be sent to Slack channels
|
| 457 |
+
diff_report = prepare_reports(
|
| 458 |
+
title="*Changed model modules failures*",
|
| 459 |
+
header=model_header,
|
| 460 |
+
reports=entries_changed,
|
| 461 |
+
)
|
| 462 |
+
model_failure_sections.append(
|
| 463 |
+
{"type": "section", "text": {"type": "mrkdwn", "text": diff_report}},
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
return model_failure_sections
|
| 467 |
+
|
| 468 |
+
@property
|
| 469 |
+
def additional_failures(self) -> Dict:
|
| 470 |
+
failures = {k: v["failed"] for k, v in self.additional_results.items()}
|
| 471 |
+
errors = {k: v["error"] for k, v in self.additional_results.items()}
|
| 472 |
+
|
| 473 |
+
individual_reports = []
|
| 474 |
+
for key, value in failures.items():
|
| 475 |
+
device_report = self.get_device_report(value)
|
| 476 |
+
|
| 477 |
+
if sum(value.values()) or errors[key]:
|
| 478 |
+
report = f"{key}"
|
| 479 |
+
if errors[key]:
|
| 480 |
+
report = f"[Errored out] {report}"
|
| 481 |
+
if device_report:
|
| 482 |
+
report = f"{device_report}{report}"
|
| 483 |
+
|
| 484 |
+
individual_reports.append(report)
|
| 485 |
+
|
| 486 |
+
header = "Single | Multi | Category\n"
|
| 487 |
+
failures_report = prepare_reports(
|
| 488 |
+
title="The following non-modeling tests had failures", header=header, reports=individual_reports
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
return {"type": "section", "text": {"type": "mrkdwn", "text": failures_report}}
|
| 492 |
+
|
| 493 |
+
@property
|
| 494 |
+
def payload(self) -> str:
|
| 495 |
+
blocks = [self.header]
|
| 496 |
+
|
| 497 |
+
if self.ci_title:
|
| 498 |
+
blocks.append(self.ci_title_section)
|
| 499 |
+
|
| 500 |
+
if self.n_model_failures > 0 or self.n_additional_failures > 0:
|
| 501 |
+
blocks.append(self.failures)
|
| 502 |
+
|
| 503 |
+
if self.n_model_failures > 0:
|
| 504 |
+
blocks.append(self.category_failures)
|
| 505 |
+
for block in self.model_failures:
|
| 506 |
+
if block["text"]["text"]:
|
| 507 |
+
blocks.append(block)
|
| 508 |
+
|
| 509 |
+
if self.n_additional_failures > 0:
|
| 510 |
+
blocks.append(self.additional_failures)
|
| 511 |
+
|
| 512 |
+
if self.n_model_failures == 0 and self.n_additional_failures == 0:
|
| 513 |
+
blocks.append(self.no_failures)
|
| 514 |
+
|
| 515 |
+
if len(self.selected_warnings) > 0:
|
| 516 |
+
blocks.append(self.warnings)
|
| 517 |
+
|
| 518 |
+
new_failure_blocks = self.get_new_model_failure_blocks(with_header=False)
|
| 519 |
+
if len(new_failure_blocks) > 0:
|
| 520 |
+
blocks.extend(new_failure_blocks)
|
| 521 |
+
|
| 522 |
+
# To save the list of new model failures
|
| 523 |
+
extra_blocks = self.get_new_model_failure_blocks(to_truncate=False)
|
| 524 |
+
if extra_blocks:
|
| 525 |
+
failure_text = extra_blocks[-1]["text"]["text"]
|
| 526 |
+
file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/new_model_failures.txt")
|
| 527 |
+
with open(file_path, "w", encoding="UTF-8") as fp:
|
| 528 |
+
fp.write(failure_text)
|
| 529 |
+
|
| 530 |
+
# upload results to Hub dataset
|
| 531 |
+
file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/new_model_failures.txt")
|
| 532 |
+
commit_info = api.upload_file(
|
| 533 |
+
path_or_fileobj=file_path,
|
| 534 |
+
path_in_repo=f"{datetime.datetime.today().strftime('%Y-%m-%d')}/ci_results_{job_name}/new_model_failures.txt",
|
| 535 |
+
repo_id="hf-internal-testing/transformers_daily_ci",
|
| 536 |
+
repo_type="dataset",
|
| 537 |
+
token=os.environ.get("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN", None),
|
| 538 |
+
)
|
| 539 |
+
url = f"https://huggingface.co/datasets/hf-internal-testing/transformers_daily_ci/raw/{commit_info.oid}/{datetime.datetime.today().strftime('%Y-%m-%d')}/ci_results_{job_name}/new_model_failures.txt"
|
| 540 |
+
|
| 541 |
+
# extra processing to save to json format
|
| 542 |
+
new_failed_tests = {}
|
| 543 |
+
for line in failure_text.split():
|
| 544 |
+
if "https://github.com/huggingface/transformers/actions/runs" in line:
|
| 545 |
+
pattern = r"<(https://github.com/huggingface/transformers/actions/runs/.+?/job/.+?)\|(.+?)>"
|
| 546 |
+
items = re.findall(pattern, line)
|
| 547 |
+
elif "tests/models/" in line:
|
| 548 |
+
model = line.split("/")[2]
|
| 549 |
+
if model not in new_failed_tests:
|
| 550 |
+
new_failed_tests[model] = {"single-gpu": [], "multi-gpu": []}
|
| 551 |
+
for url, device in items:
|
| 552 |
+
new_failed_tests[model][f"{device}-gpu"].append(line)
|
| 553 |
+
file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/new_model_failures.json")
|
| 554 |
+
with open(file_path, "w", encoding="UTF-8") as fp:
|
| 555 |
+
json.dump(new_failed_tests, fp, ensure_ascii=False, indent=4)
|
| 556 |
+
|
| 557 |
+
# upload results to Hub dataset
|
| 558 |
+
file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/new_model_failures.json")
|
| 559 |
+
_ = api.upload_file(
|
| 560 |
+
path_or_fileobj=file_path,
|
| 561 |
+
path_in_repo=f"{datetime.datetime.today().strftime('%Y-%m-%d')}/ci_results_{job_name}/new_model_failures.json",
|
| 562 |
+
repo_id="hf-internal-testing/transformers_daily_ci",
|
| 563 |
+
repo_type="dataset",
|
| 564 |
+
token=os.environ.get("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN", None),
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
block = {
|
| 568 |
+
"type": "section",
|
| 569 |
+
"text": {
|
| 570 |
+
"type": "plain_text",
|
| 571 |
+
"text": " ",
|
| 572 |
+
},
|
| 573 |
+
"accessory": {
|
| 574 |
+
"type": "button",
|
| 575 |
+
"text": {"type": "plain_text", "text": "Check New model failures"},
|
| 576 |
+
"url": url,
|
| 577 |
+
},
|
| 578 |
+
}
|
| 579 |
+
blocks.append(block)
|
| 580 |
+
|
| 581 |
+
return json.dumps(blocks)
|
| 582 |
+
|
| 583 |
+
@staticmethod
|
| 584 |
+
def error_out(title, ci_title="", runner_not_available=False, runner_failed=False, setup_failed=False):
|
| 585 |
+
blocks = []
|
| 586 |
+
title_block = {"type": "header", "text": {"type": "plain_text", "text": title}}
|
| 587 |
+
blocks.append(title_block)
|
| 588 |
+
|
| 589 |
+
if ci_title:
|
| 590 |
+
ci_title_block = {"type": "section", "text": {"type": "mrkdwn", "text": ci_title}}
|
| 591 |
+
blocks.append(ci_title_block)
|
| 592 |
+
|
| 593 |
+
offline_runners = []
|
| 594 |
+
if runner_not_available:
|
| 595 |
+
text = "💔 CI runners are not available! Tests are not run. 😭"
|
| 596 |
+
result = os.environ.get("OFFLINE_RUNNERS")
|
| 597 |
+
if result is not None:
|
| 598 |
+
offline_runners = json.loads(result)
|
| 599 |
+
elif runner_failed:
|
| 600 |
+
text = "💔 CI runners have problems! Tests are not run. 😭"
|
| 601 |
+
elif setup_failed:
|
| 602 |
+
text = "💔 Setup job failed. Tests are not run. 😭"
|
| 603 |
+
else:
|
| 604 |
+
text = "💔 There was an issue running the tests. 😭"
|
| 605 |
+
|
| 606 |
+
error_block_1 = {
|
| 607 |
+
"type": "header",
|
| 608 |
+
"text": {
|
| 609 |
+
"type": "plain_text",
|
| 610 |
+
"text": text,
|
| 611 |
+
},
|
| 612 |
+
}
|
| 613 |
+
|
| 614 |
+
text = ""
|
| 615 |
+
if len(offline_runners) > 0:
|
| 616 |
+
text = "\n • " + "\n • ".join(offline_runners)
|
| 617 |
+
text = f"The following runners are offline:\n{text}\n\n"
|
| 618 |
+
text += "🙏 Let's fix it ASAP! 🙏"
|
| 619 |
+
|
| 620 |
+
error_block_2 = {
|
| 621 |
+
"type": "section",
|
| 622 |
+
"text": {
|
| 623 |
+
"type": "plain_text",
|
| 624 |
+
"text": text,
|
| 625 |
+
},
|
| 626 |
+
"accessory": {
|
| 627 |
+
"type": "button",
|
| 628 |
+
"text": {"type": "plain_text", "text": "Check Action results", "emoji": True},
|
| 629 |
+
"url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}",
|
| 630 |
+
},
|
| 631 |
+
}
|
| 632 |
+
blocks.extend([error_block_1, error_block_2])
|
| 633 |
+
|
| 634 |
+
payload = json.dumps(blocks)
|
| 635 |
+
|
| 636 |
+
print("Sending the following payload")
|
| 637 |
+
print(json.dumps({"blocks": blocks}))
|
| 638 |
+
|
| 639 |
+
client.chat_postMessage(
|
| 640 |
+
channel=SLACK_REPORT_CHANNEL_ID,
|
| 641 |
+
text=text,
|
| 642 |
+
blocks=payload,
|
| 643 |
+
)
|
| 644 |
+
|
| 645 |
+
def post(self):
|
| 646 |
+
payload = self.payload
|
| 647 |
+
print("Sending the following payload")
|
| 648 |
+
print(json.dumps({"blocks": json.loads(payload)}))
|
| 649 |
+
|
| 650 |
+
text = f"{self.n_failures} failures out of {self.n_tests} tests," if self.n_failures else "All tests passed."
|
| 651 |
+
|
| 652 |
+
self.thread_ts = client.chat_postMessage(
|
| 653 |
+
channel=SLACK_REPORT_CHANNEL_ID,
|
| 654 |
+
blocks=payload,
|
| 655 |
+
text=text,
|
| 656 |
+
)
|
| 657 |
+
|
| 658 |
+
def get_reply_blocks(self, job_name, job_result, failures, device, text):
|
| 659 |
+
"""
|
| 660 |
+
failures: A list with elements of the form {"line": full test name, "trace": error trace}
|
| 661 |
+
"""
|
| 662 |
+
# `text` must be less than 3001 characters in Slack SDK
|
| 663 |
+
# keep some room for adding "[Truncated]" when necessary
|
| 664 |
+
MAX_ERROR_TEXT = 3000 - len("[Truncated]")
|
| 665 |
+
|
| 666 |
+
failure_text = ""
|
| 667 |
+
for idx, error in enumerate(failures):
|
| 668 |
+
new_text = failure_text + f'*{error["line"]}*\n_{error["trace"]}_\n\n'
|
| 669 |
+
if len(new_text) > MAX_ERROR_TEXT:
|
| 670 |
+
# `failure_text` here has length <= 3000
|
| 671 |
+
failure_text = failure_text + "[Truncated]"
|
| 672 |
+
break
|
| 673 |
+
# `failure_text` here has length <= MAX_ERROR_TEXT
|
| 674 |
+
failure_text = new_text
|
| 675 |
+
|
| 676 |
+
title = job_name
|
| 677 |
+
if device is not None:
|
| 678 |
+
title += f" ({device}-gpu)"
|
| 679 |
+
|
| 680 |
+
content = {"type": "section", "text": {"type": "mrkdwn", "text": text}}
|
| 681 |
+
|
| 682 |
+
# TODO: Make sure we always have a valid job link (or at least a way not to break the report sending)
|
| 683 |
+
# Currently we get the device from a job's artifact name.
|
| 684 |
+
# If a device is found, the job name should contain the device type, for example, `XXX (single-gpu)`.
|
| 685 |
+
# This could be done by adding `machine_type` in a job's `strategy`.
|
| 686 |
+
# (If `job_result["job_link"][device]` is `None`, we get an error: `... [ERROR] must provide a string ...`)
|
| 687 |
+
if job_result["job_link"] is not None and job_result["job_link"][device] is not None:
|
| 688 |
+
content["accessory"] = {
|
| 689 |
+
"type": "button",
|
| 690 |
+
"text": {"type": "plain_text", "text": "GitHub Action job", "emoji": True},
|
| 691 |
+
"url": job_result["job_link"][device],
|
| 692 |
+
}
|
| 693 |
+
|
| 694 |
+
return [
|
| 695 |
+
{"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}},
|
| 696 |
+
content,
|
| 697 |
+
{"type": "section", "text": {"type": "mrkdwn", "text": failure_text}},
|
| 698 |
+
]
|
| 699 |
+
|
| 700 |
+
def get_new_model_failure_blocks(self, with_header=True, to_truncate=True):
|
| 701 |
+
if self.prev_ci_artifacts is None:
|
| 702 |
+
return []
|
| 703 |
+
|
| 704 |
+
sorted_dict = sorted(self.model_results.items(), key=lambda t: t[0])
|
| 705 |
+
|
| 706 |
+
prev_model_results = {}
|
| 707 |
+
if (
|
| 708 |
+
f"ci_results_{job_name}" in self.prev_ci_artifacts
|
| 709 |
+
and "model_results.json" in self.prev_ci_artifacts[f"ci_results_{job_name}"]
|
| 710 |
+
):
|
| 711 |
+
prev_model_results = json.loads(self.prev_ci_artifacts[f"ci_results_{job_name}"]["model_results.json"])
|
| 712 |
+
|
| 713 |
+
all_failure_lines = {}
|
| 714 |
+
for job, job_result in sorted_dict:
|
| 715 |
+
if len(job_result["failures"]):
|
| 716 |
+
devices = sorted(job_result["failures"].keys(), reverse=True)
|
| 717 |
+
for device in devices:
|
| 718 |
+
failures = job_result["failures"][device]
|
| 719 |
+
prev_error_lines = {}
|
| 720 |
+
if job in prev_model_results and device in prev_model_results[job]["failures"]:
|
| 721 |
+
prev_error_lines = {error["line"] for error in prev_model_results[job]["failures"][device]}
|
| 722 |
+
|
| 723 |
+
url = None
|
| 724 |
+
if job_result["job_link"] is not None and job_result["job_link"][device] is not None:
|
| 725 |
+
url = job_result["job_link"][device]
|
| 726 |
+
|
| 727 |
+
for idx, error in enumerate(failures):
|
| 728 |
+
if error["line"] in prev_error_lines:
|
| 729 |
+
continue
|
| 730 |
+
|
| 731 |
+
new_text = f'{error["line"]}\n\n'
|
| 732 |
+
|
| 733 |
+
if new_text not in all_failure_lines:
|
| 734 |
+
all_failure_lines[new_text] = []
|
| 735 |
+
|
| 736 |
+
all_failure_lines[new_text].append(f"<{url}|{device}>" if url is not None else device)
|
| 737 |
+
|
| 738 |
+
MAX_ERROR_TEXT = 3000 - len("[Truncated]") - len("```New model failures```\n\n")
|
| 739 |
+
if not to_truncate:
|
| 740 |
+
MAX_ERROR_TEXT = float("inf")
|
| 741 |
+
failure_text = ""
|
| 742 |
+
for line, devices in all_failure_lines.items():
|
| 743 |
+
new_text = failure_text + f"{'|'.join(devices)} gpu\n{line}"
|
| 744 |
+
if len(new_text) > MAX_ERROR_TEXT:
|
| 745 |
+
# `failure_text` here has length <= 3000
|
| 746 |
+
failure_text = failure_text + "[Truncated]"
|
| 747 |
+
break
|
| 748 |
+
# `failure_text` here has length <= MAX_ERROR_TEXT
|
| 749 |
+
failure_text = new_text
|
| 750 |
+
|
| 751 |
+
blocks = []
|
| 752 |
+
if failure_text:
|
| 753 |
+
if with_header:
|
| 754 |
+
blocks.append(
|
| 755 |
+
{"type": "header", "text": {"type": "plain_text", "text": "New model failures", "emoji": True}}
|
| 756 |
+
)
|
| 757 |
+
else:
|
| 758 |
+
failure_text = f"*New model failures*\n\n{failure_text}"
|
| 759 |
+
blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": failure_text}})
|
| 760 |
+
|
| 761 |
+
return blocks
|
| 762 |
+
|
| 763 |
+
def post_reply(self):
|
| 764 |
+
if self.thread_ts is None:
|
| 765 |
+
raise ValueError("Can only post reply if a post has been made.")
|
| 766 |
+
|
| 767 |
+
sorted_dict = sorted(self.model_results.items(), key=lambda t: t[0])
|
| 768 |
+
for job, job_result in sorted_dict:
|
| 769 |
+
if len(job_result["failures"]):
|
| 770 |
+
for device, failures in job_result["failures"].items():
|
| 771 |
+
text = "\n".join(
|
| 772 |
+
sorted([f"*{k}*: {v[device]}" for k, v in job_result["failed"].items() if v[device]])
|
| 773 |
+
)
|
| 774 |
+
|
| 775 |
+
blocks = self.get_reply_blocks(job, job_result, failures, device, text=text)
|
| 776 |
+
|
| 777 |
+
print("Sending the following reply")
|
| 778 |
+
print(json.dumps({"blocks": blocks}))
|
| 779 |
+
|
| 780 |
+
client.chat_postMessage(
|
| 781 |
+
channel=SLACK_REPORT_CHANNEL_ID,
|
| 782 |
+
text=f"Results for {job}",
|
| 783 |
+
blocks=blocks,
|
| 784 |
+
thread_ts=self.thread_ts["ts"],
|
| 785 |
+
)
|
| 786 |
+
|
| 787 |
+
time.sleep(1)
|
| 788 |
+
|
| 789 |
+
for job, job_result in self.additional_results.items():
|
| 790 |
+
if len(job_result["failures"]):
|
| 791 |
+
for device, failures in job_result["failures"].items():
|
| 792 |
+
blocks = self.get_reply_blocks(
|
| 793 |
+
job,
|
| 794 |
+
job_result,
|
| 795 |
+
failures,
|
| 796 |
+
device,
|
| 797 |
+
text=f'Number of failures: {job_result["failed"][device]}',
|
| 798 |
+
)
|
| 799 |
+
|
| 800 |
+
print("Sending the following reply")
|
| 801 |
+
print(json.dumps({"blocks": blocks}))
|
| 802 |
+
|
| 803 |
+
client.chat_postMessage(
|
| 804 |
+
channel=SLACK_REPORT_CHANNEL_ID,
|
| 805 |
+
text=f"Results for {job}",
|
| 806 |
+
blocks=blocks,
|
| 807 |
+
thread_ts=self.thread_ts["ts"],
|
| 808 |
+
)
|
| 809 |
+
|
| 810 |
+
time.sleep(1)
|
| 811 |
+
|
| 812 |
+
blocks = self.get_new_model_failure_blocks()
|
| 813 |
+
if blocks:
|
| 814 |
+
print("Sending the following reply")
|
| 815 |
+
print(json.dumps({"blocks": blocks}))
|
| 816 |
+
|
| 817 |
+
client.chat_postMessage(
|
| 818 |
+
channel=SLACK_REPORT_CHANNEL_ID,
|
| 819 |
+
text="Results for new failures",
|
| 820 |
+
blocks=blocks,
|
| 821 |
+
thread_ts=self.thread_ts["ts"],
|
| 822 |
+
)
|
| 823 |
+
|
| 824 |
+
time.sleep(1)
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
def retrieve_artifact(artifact_path: str, gpu: Optional[str]):
|
| 828 |
+
if gpu not in [None, "single", "multi"]:
|
| 829 |
+
raise ValueError(f"Invalid GPU for artifact. Passed GPU: `{gpu}`.")
|
| 830 |
+
|
| 831 |
+
_artifact = {}
|
| 832 |
+
|
| 833 |
+
if os.path.exists(artifact_path):
|
| 834 |
+
files = os.listdir(artifact_path)
|
| 835 |
+
for file in files:
|
| 836 |
+
try:
|
| 837 |
+
with open(os.path.join(artifact_path, file)) as f:
|
| 838 |
+
_artifact[file.split(".")[0]] = f.read()
|
| 839 |
+
except UnicodeDecodeError as e:
|
| 840 |
+
raise ValueError(f"Could not open {os.path.join(artifact_path, file)}.") from e
|
| 841 |
+
|
| 842 |
+
return _artifact
|
| 843 |
+
|
| 844 |
+
|
| 845 |
+
def retrieve_available_artifacts():
|
| 846 |
+
class Artifact:
|
| 847 |
+
def __init__(self, name: str, single_gpu: bool = False, multi_gpu: bool = False):
|
| 848 |
+
self.name = name
|
| 849 |
+
self.single_gpu = single_gpu
|
| 850 |
+
self.multi_gpu = multi_gpu
|
| 851 |
+
self.paths = []
|
| 852 |
+
|
| 853 |
+
def __str__(self):
|
| 854 |
+
return self.name
|
| 855 |
+
|
| 856 |
+
def add_path(self, path: str, gpu: str = None):
|
| 857 |
+
self.paths.append({"name": self.name, "path": path, "gpu": gpu})
|
| 858 |
+
|
| 859 |
+
_available_artifacts: Dict[str, Artifact] = {}
|
| 860 |
+
|
| 861 |
+
directories = filter(os.path.isdir, os.listdir())
|
| 862 |
+
for directory in directories:
|
| 863 |
+
artifact_name = directory
|
| 864 |
+
|
| 865 |
+
name_parts = artifact_name.split("_postfix_")
|
| 866 |
+
if len(name_parts) > 1:
|
| 867 |
+
artifact_name = name_parts[0]
|
| 868 |
+
|
| 869 |
+
if artifact_name.startswith("single-gpu"):
|
| 870 |
+
artifact_name = artifact_name[len("single-gpu") + 1 :]
|
| 871 |
+
|
| 872 |
+
if artifact_name in _available_artifacts:
|
| 873 |
+
_available_artifacts[artifact_name].single_gpu = True
|
| 874 |
+
else:
|
| 875 |
+
_available_artifacts[artifact_name] = Artifact(artifact_name, single_gpu=True)
|
| 876 |
+
|
| 877 |
+
_available_artifacts[artifact_name].add_path(directory, gpu="single")
|
| 878 |
+
|
| 879 |
+
elif artifact_name.startswith("multi-gpu"):
|
| 880 |
+
artifact_name = artifact_name[len("multi-gpu") + 1 :]
|
| 881 |
+
|
| 882 |
+
if artifact_name in _available_artifacts:
|
| 883 |
+
_available_artifacts[artifact_name].multi_gpu = True
|
| 884 |
+
else:
|
| 885 |
+
_available_artifacts[artifact_name] = Artifact(artifact_name, multi_gpu=True)
|
| 886 |
+
|
| 887 |
+
_available_artifacts[artifact_name].add_path(directory, gpu="multi")
|
| 888 |
+
else:
|
| 889 |
+
if artifact_name not in _available_artifacts:
|
| 890 |
+
_available_artifacts[artifact_name] = Artifact(artifact_name)
|
| 891 |
+
|
| 892 |
+
_available_artifacts[artifact_name].add_path(directory)
|
| 893 |
+
|
| 894 |
+
return _available_artifacts
|
| 895 |
+
|
| 896 |
+
|
| 897 |
+
def prepare_reports(title, header, reports, to_truncate=True):
|
| 898 |
+
report = ""
|
| 899 |
+
|
| 900 |
+
MAX_ERROR_TEXT = 3000 - len("[Truncated]")
|
| 901 |
+
if not to_truncate:
|
| 902 |
+
MAX_ERROR_TEXT = float("inf")
|
| 903 |
+
|
| 904 |
+
if len(reports) > 0:
|
| 905 |
+
# `text` must be less than 3001 characters in Slack SDK
|
| 906 |
+
# keep some room for adding "[Truncated]" when necessary
|
| 907 |
+
|
| 908 |
+
for idx in range(len(reports)):
|
| 909 |
+
_report = header + "\n".join(reports[: idx + 1])
|
| 910 |
+
new_report = f"{title}:\n```\n{_report}\n```\n"
|
| 911 |
+
if len(new_report) > MAX_ERROR_TEXT:
|
| 912 |
+
# `report` here has length <= 3000
|
| 913 |
+
report = report + "[Truncated]"
|
| 914 |
+
break
|
| 915 |
+
report = new_report
|
| 916 |
+
|
| 917 |
+
return report
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
if __name__ == "__main__":
|
| 921 |
+
SLACK_REPORT_CHANNEL_ID = os.environ["SLACK_REPORT_CHANNEL"]
|
| 922 |
+
|
| 923 |
+
# runner_status = os.environ.get("RUNNER_STATUS")
|
| 924 |
+
# runner_env_status = os.environ.get("RUNNER_ENV_STATUS")
|
| 925 |
+
setup_status = os.environ.get("SETUP_STATUS")
|
| 926 |
+
|
| 927 |
+
# runner_not_available = True if runner_status is not None and runner_status != "success" else False
|
| 928 |
+
# runner_failed = True if runner_env_status is not None and runner_env_status != "success" else False
|
| 929 |
+
# Let's keep the lines regardig runners' status (we might be able to use them again in the future)
|
| 930 |
+
runner_not_available = False
|
| 931 |
+
runner_failed = False
|
| 932 |
+
# Some jobs don't depend (`needs`) on the job `setup`: in this case, the status of the job `setup` is `skipped`.
|
| 933 |
+
setup_failed = False if setup_status in ["skipped", "success"] else True
|
| 934 |
+
|
| 935 |
+
org = "huggingface"
|
| 936 |
+
repo = "transformers"
|
| 937 |
+
repository_full_name = f"{org}/{repo}"
|
| 938 |
+
|
| 939 |
+
# This env. variable is set in workflow file (under the job `send_results`).
|
| 940 |
+
ci_event = os.environ["CI_EVENT"]
|
| 941 |
+
|
| 942 |
+
# To find the PR number in a commit title, for example, `Add AwesomeFormer model (#99999)`
|
| 943 |
+
pr_number_re = re.compile(r"\(#(\d+)\)$")
|
| 944 |
+
|
| 945 |
+
title = f"🤗 Results of {ci_event} - {os.getenv('CI_TEST_JOB')}."
|
| 946 |
+
# Add Commit/PR title with a link for push CI
|
| 947 |
+
# (check the title in 2 env. variables - depending on the CI is triggered via `push` or `workflow_run` event)
|
| 948 |
+
ci_title_push = os.environ.get("CI_TITLE_PUSH")
|
| 949 |
+
ci_title_workflow_run = os.environ.get("CI_TITLE_WORKFLOW_RUN")
|
| 950 |
+
ci_title = ci_title_push if ci_title_push else ci_title_workflow_run
|
| 951 |
+
|
| 952 |
+
ci_sha = os.environ.get("CI_SHA")
|
| 953 |
+
|
| 954 |
+
ci_url = None
|
| 955 |
+
if ci_sha:
|
| 956 |
+
ci_url = f"https://github.com/{repository_full_name}/commit/{ci_sha}"
|
| 957 |
+
|
| 958 |
+
if ci_title is not None:
|
| 959 |
+
if ci_url is None:
|
| 960 |
+
raise ValueError(
|
| 961 |
+
"When a title is found (`ci_title`), it means a `push` event or a `workflow_run` even (triggered by "
|
| 962 |
+
"another `push` event), and the commit SHA has to be provided in order to create the URL to the "
|
| 963 |
+
"commit page."
|
| 964 |
+
)
|
| 965 |
+
ci_title = ci_title.strip().split("\n")[0].strip()
|
| 966 |
+
|
| 967 |
+
# Retrieve the PR title and author login to complete the report
|
| 968 |
+
commit_number = ci_url.split("/")[-1]
|
| 969 |
+
ci_detail_url = f"https://api.github.com/repos/{repository_full_name}/commits/{commit_number}"
|
| 970 |
+
ci_details = requests.get(ci_detail_url).json()
|
| 971 |
+
ci_author = ci_details["author"]["login"]
|
| 972 |
+
|
| 973 |
+
merged_by = None
|
| 974 |
+
# Find the PR number (if any) and change the url to the actual PR page.
|
| 975 |
+
numbers = pr_number_re.findall(ci_title)
|
| 976 |
+
if len(numbers) > 0:
|
| 977 |
+
pr_number = numbers[0]
|
| 978 |
+
ci_detail_url = f"https://api.github.com/repos/{repository_full_name}/pulls/{pr_number}"
|
| 979 |
+
ci_details = requests.get(ci_detail_url).json()
|
| 980 |
+
|
| 981 |
+
ci_author = ci_details["user"]["login"]
|
| 982 |
+
ci_url = f"https://github.com/{repository_full_name}/pull/{pr_number}"
|
| 983 |
+
|
| 984 |
+
merged_by = ci_details["merged_by"]["login"]
|
| 985 |
+
|
| 986 |
+
if merged_by is None:
|
| 987 |
+
ci_title = f"<{ci_url}|{ci_title}>\nAuthor: {ci_author}"
|
| 988 |
+
else:
|
| 989 |
+
ci_title = f"<{ci_url}|{ci_title}>\nAuthor: {ci_author} | Merged by: {merged_by}"
|
| 990 |
+
|
| 991 |
+
elif ci_sha:
|
| 992 |
+
ci_title = f"<{ci_url}|commit: {ci_sha}>"
|
| 993 |
+
|
| 994 |
+
else:
|
| 995 |
+
ci_title = ""
|
| 996 |
+
|
| 997 |
+
if runner_not_available or runner_failed or setup_failed:
|
| 998 |
+
Message.error_out(title, ci_title, runner_not_available, runner_failed, setup_failed)
|
| 999 |
+
exit(0)
|
| 1000 |
+
|
| 1001 |
+
# sys.argv[0] is always `utils/notification_service.py`.
|
| 1002 |
+
arguments = sys.argv[1:]
|
| 1003 |
+
# In our usage in `.github/workflows/slack-report.yml`, we always pass an argument when calling this script.
|
| 1004 |
+
# The argument could be an empty string `""` if a job doesn't depend on the job `setup`.
|
| 1005 |
+
if arguments[0] == "":
|
| 1006 |
+
models = []
|
| 1007 |
+
else:
|
| 1008 |
+
model_list_as_str = arguments[0]
|
| 1009 |
+
try:
|
| 1010 |
+
folder_slices = ast.literal_eval(model_list_as_str)
|
| 1011 |
+
# Need to change from elements like `models/bert` to `models_bert` (the ones used as artifact names).
|
| 1012 |
+
models = [x.replace("models/", "models_") for folders in folder_slices for x in folders]
|
| 1013 |
+
except Exception:
|
| 1014 |
+
Message.error_out(title, ci_title)
|
| 1015 |
+
raise ValueError("Errored out.")
|
| 1016 |
+
|
| 1017 |
+
github_actions_jobs = get_jobs(
|
| 1018 |
+
workflow_run_id=os.environ["GITHUB_RUN_ID"], token=os.environ["ACCESS_REPO_INFO_TOKEN"]
|
| 1019 |
+
)
|
| 1020 |
+
github_actions_job_links = {job["name"]: job["html_url"] for job in github_actions_jobs}
|
| 1021 |
+
|
| 1022 |
+
artifact_name_to_job_map = {}
|
| 1023 |
+
for job in github_actions_jobs:
|
| 1024 |
+
for step in job["steps"]:
|
| 1025 |
+
if step["name"].startswith("Test suite reports artifacts: "):
|
| 1026 |
+
artifact_name = step["name"][len("Test suite reports artifacts: ") :]
|
| 1027 |
+
artifact_name_to_job_map[artifact_name] = job
|
| 1028 |
+
break
|
| 1029 |
+
|
| 1030 |
+
available_artifacts = retrieve_available_artifacts()
|
| 1031 |
+
|
| 1032 |
+
modeling_categories = [
|
| 1033 |
+
"PyTorch",
|
| 1034 |
+
"TensorFlow",
|
| 1035 |
+
"Flax",
|
| 1036 |
+
"Tokenizers",
|
| 1037 |
+
"Pipelines",
|
| 1038 |
+
"Trainer",
|
| 1039 |
+
"ONNX",
|
| 1040 |
+
"Auto",
|
| 1041 |
+
"Unclassified",
|
| 1042 |
+
]
|
| 1043 |
+
|
| 1044 |
+
# This dict will contain all the information relative to each model:
|
| 1045 |
+
# - Failures: the total, as well as the number of failures per-category defined above
|
| 1046 |
+
# - Success: total
|
| 1047 |
+
# - Time spent: as a comma-separated list of elapsed time
|
| 1048 |
+
# - Failures: as a line-break separated list of errors
|
| 1049 |
+
model_results = {
|
| 1050 |
+
model: {
|
| 1051 |
+
"failed": {m: {"unclassified": 0, "single": 0, "multi": 0} for m in modeling_categories},
|
| 1052 |
+
"success": 0,
|
| 1053 |
+
"time_spent": "",
|
| 1054 |
+
"failures": {},
|
| 1055 |
+
"job_link": {},
|
| 1056 |
+
}
|
| 1057 |
+
for model in models
|
| 1058 |
+
if f"run_models_gpu_{model}_test_reports" in available_artifacts
|
| 1059 |
+
}
|
| 1060 |
+
|
| 1061 |
+
unclassified_model_failures = []
|
| 1062 |
+
|
| 1063 |
+
for model in model_results.keys():
|
| 1064 |
+
for artifact_path in available_artifacts[f"run_models_gpu_{model}_test_reports"].paths:
|
| 1065 |
+
artifact = retrieve_artifact(artifact_path["path"], artifact_path["gpu"])
|
| 1066 |
+
if "stats" in artifact:
|
| 1067 |
+
# Link to the GitHub Action job
|
| 1068 |
+
job = artifact_name_to_job_map[artifact_path["path"]]
|
| 1069 |
+
model_results[model]["job_link"][artifact_path["gpu"]] = job["html_url"]
|
| 1070 |
+
failed, success, time_spent = handle_test_results(artifact["stats"])
|
| 1071 |
+
model_results[model]["success"] += success
|
| 1072 |
+
model_results[model]["time_spent"] += time_spent[1:-1] + ", "
|
| 1073 |
+
|
| 1074 |
+
stacktraces = handle_stacktraces(artifact["failures_line"])
|
| 1075 |
+
|
| 1076 |
+
for line in artifact["summary_short"].split("\n"):
|
| 1077 |
+
if line.startswith("FAILED "):
|
| 1078 |
+
# Avoid the extra `FAILED` entry given by `run_test_using_subprocess` causing issue when calling
|
| 1079 |
+
# `stacktraces.pop` below.
|
| 1080 |
+
# See `run_test_using_subprocess` in `src/transformers/testing_utils.py`
|
| 1081 |
+
if " - Failed: (subprocess)" in line:
|
| 1082 |
+
continue
|
| 1083 |
+
line = line[len("FAILED ") :]
|
| 1084 |
+
line = line.split()[0].replace("\n", "")
|
| 1085 |
+
|
| 1086 |
+
if artifact_path["gpu"] not in model_results[model]["failures"]:
|
| 1087 |
+
model_results[model]["failures"][artifact_path["gpu"]] = []
|
| 1088 |
+
|
| 1089 |
+
model_results[model]["failures"][artifact_path["gpu"]].append(
|
| 1090 |
+
{"line": line, "trace": stacktraces.pop(0)}
|
| 1091 |
+
)
|
| 1092 |
+
|
| 1093 |
+
if re.search("test_modeling_tf_", line):
|
| 1094 |
+
model_results[model]["failed"]["TensorFlow"][artifact_path["gpu"]] += 1
|
| 1095 |
+
|
| 1096 |
+
elif re.search("test_modeling_flax_", line):
|
| 1097 |
+
model_results[model]["failed"]["Flax"][artifact_path["gpu"]] += 1
|
| 1098 |
+
|
| 1099 |
+
elif re.search("test_modeling", line):
|
| 1100 |
+
model_results[model]["failed"]["PyTorch"][artifact_path["gpu"]] += 1
|
| 1101 |
+
|
| 1102 |
+
elif re.search("test_tokenization", line):
|
| 1103 |
+
model_results[model]["failed"]["Tokenizers"][artifact_path["gpu"]] += 1
|
| 1104 |
+
|
| 1105 |
+
elif re.search("test_pipelines", line):
|
| 1106 |
+
model_results[model]["failed"]["Pipelines"][artifact_path["gpu"]] += 1
|
| 1107 |
+
|
| 1108 |
+
elif re.search("test_trainer", line):
|
| 1109 |
+
model_results[model]["failed"]["Trainer"][artifact_path["gpu"]] += 1
|
| 1110 |
+
|
| 1111 |
+
elif re.search("onnx", line):
|
| 1112 |
+
model_results[model]["failed"]["ONNX"][artifact_path["gpu"]] += 1
|
| 1113 |
+
|
| 1114 |
+
elif re.search("auto", line):
|
| 1115 |
+
model_results[model]["failed"]["Auto"][artifact_path["gpu"]] += 1
|
| 1116 |
+
|
| 1117 |
+
else:
|
| 1118 |
+
model_results[model]["failed"]["Unclassified"][artifact_path["gpu"]] += 1
|
| 1119 |
+
unclassified_model_failures.append(line)
|
| 1120 |
+
|
| 1121 |
+
# Additional runs
|
| 1122 |
+
additional_files = {
|
| 1123 |
+
"PyTorch pipelines": "run_pipelines_torch_gpu_test_reports",
|
| 1124 |
+
"TensorFlow pipelines": "run_pipelines_tf_gpu_test_reports",
|
| 1125 |
+
"Examples directory": "run_examples_gpu_test_reports",
|
| 1126 |
+
"Torch CUDA extension tests": "run_torch_cuda_extensions_gpu_test_reports",
|
| 1127 |
+
}
|
| 1128 |
+
|
| 1129 |
+
if ci_event in ["push", "Nightly CI"] or ci_event.startswith("Past CI"):
|
| 1130 |
+
del additional_files["Examples directory"]
|
| 1131 |
+
del additional_files["PyTorch pipelines"]
|
| 1132 |
+
del additional_files["TensorFlow pipelines"]
|
| 1133 |
+
elif ci_event.startswith("Scheduled CI (AMD)"):
|
| 1134 |
+
del additional_files["TensorFlow pipelines"]
|
| 1135 |
+
del additional_files["Torch CUDA extension tests"]
|
| 1136 |
+
elif ci_event.startswith("Push CI (AMD)"):
|
| 1137 |
+
additional_files = {}
|
| 1138 |
+
|
| 1139 |
+
# A map associating the job names (specified by `inputs.job` in a workflow file) with the keys of
|
| 1140 |
+
# `additional_files`. This is used to remove some entries in `additional_files` that are not concerned by a
|
| 1141 |
+
# specific job. See below.
|
| 1142 |
+
job_to_test_map = {
|
| 1143 |
+
"run_pipelines_torch_gpu": "PyTorch pipelines",
|
| 1144 |
+
"run_pipelines_tf_gpu": "TensorFlow pipelines",
|
| 1145 |
+
"run_examples_gpu": "Examples directory",
|
| 1146 |
+
"run_torch_cuda_extensions_gpu": "Torch CUDA extension tests",
|
| 1147 |
+
}
|
| 1148 |
+
|
| 1149 |
+
# Remove some entries in `additional_files` if they are not concerned.
|
| 1150 |
+
test_name = None
|
| 1151 |
+
job_name = os.getenv("CI_TEST_JOB")
|
| 1152 |
+
if job_name in job_to_test_map:
|
| 1153 |
+
test_name = job_to_test_map[job_name]
|
| 1154 |
+
additional_files = {k: v for k, v in additional_files.items() if k == test_name}
|
| 1155 |
+
|
| 1156 |
+
additional_results = {
|
| 1157 |
+
key: {
|
| 1158 |
+
"failed": {"unclassified": 0, "single": 0, "multi": 0},
|
| 1159 |
+
"success": 0,
|
| 1160 |
+
"time_spent": "",
|
| 1161 |
+
"error": False,
|
| 1162 |
+
"failures": {},
|
| 1163 |
+
"job_link": {},
|
| 1164 |
+
}
|
| 1165 |
+
for key in additional_files.keys()
|
| 1166 |
+
}
|
| 1167 |
+
|
| 1168 |
+
for key in additional_results.keys():
|
| 1169 |
+
# If a whole suite of test fails, the artifact isn't available.
|
| 1170 |
+
if additional_files[key] not in available_artifacts:
|
| 1171 |
+
additional_results[key]["error"] = True
|
| 1172 |
+
continue
|
| 1173 |
+
|
| 1174 |
+
for artifact_path in available_artifacts[additional_files[key]].paths:
|
| 1175 |
+
# Link to the GitHub Action job
|
| 1176 |
+
job = artifact_name_to_job_map[artifact_path["path"]]
|
| 1177 |
+
additional_results[key]["job_link"][artifact_path["gpu"]] = job["html_url"]
|
| 1178 |
+
|
| 1179 |
+
artifact = retrieve_artifact(artifact_path["path"], artifact_path["gpu"])
|
| 1180 |
+
stacktraces = handle_stacktraces(artifact["failures_line"])
|
| 1181 |
+
|
| 1182 |
+
failed, success, time_spent = handle_test_results(artifact["stats"])
|
| 1183 |
+
additional_results[key]["failed"][artifact_path["gpu"] or "unclassified"] += failed
|
| 1184 |
+
additional_results[key]["success"] += success
|
| 1185 |
+
additional_results[key]["time_spent"] += time_spent[1:-1] + ", "
|
| 1186 |
+
|
| 1187 |
+
if len(artifact["errors"]):
|
| 1188 |
+
additional_results[key]["error"] = True
|
| 1189 |
+
|
| 1190 |
+
if failed:
|
| 1191 |
+
for line in artifact["summary_short"].split("\n"):
|
| 1192 |
+
if line.startswith("FAILED "):
|
| 1193 |
+
# Avoid the extra `FAILED` entry given by `run_test_using_subprocess` causing issue when calling
|
| 1194 |
+
# `stacktraces.pop` below.
|
| 1195 |
+
# See `run_test_using_subprocess` in `src/transformers/testing_utils.py`
|
| 1196 |
+
if " - Failed: (subprocess)" in line:
|
| 1197 |
+
continue
|
| 1198 |
+
line = line[len("FAILED ") :]
|
| 1199 |
+
line = line.split()[0].replace("\n", "")
|
| 1200 |
+
|
| 1201 |
+
if artifact_path["gpu"] not in additional_results[key]["failures"]:
|
| 1202 |
+
additional_results[key]["failures"][artifact_path["gpu"]] = []
|
| 1203 |
+
|
| 1204 |
+
additional_results[key]["failures"][artifact_path["gpu"]].append(
|
| 1205 |
+
{"line": line, "trace": stacktraces.pop(0)}
|
| 1206 |
+
)
|
| 1207 |
+
|
| 1208 |
+
# Let's only check the warning for the model testing job. Currently, the job `run_extract_warnings` is only run
|
| 1209 |
+
# when `inputs.job` (in the workflow file) is `run_models_gpu`. The reason is: otherwise we need to save several
|
| 1210 |
+
# artifacts with different names which complicates the logic for an insignificant part of the CI workflow reporting.
|
| 1211 |
+
selected_warnings = []
|
| 1212 |
+
if job_name == "run_models_gpu":
|
| 1213 |
+
if "warnings_in_ci" in available_artifacts:
|
| 1214 |
+
directory = available_artifacts["warnings_in_ci"].paths[0]["path"]
|
| 1215 |
+
with open(os.path.join(directory, "selected_warnings.json")) as fp:
|
| 1216 |
+
selected_warnings = json.load(fp)
|
| 1217 |
+
|
| 1218 |
+
if not os.path.isdir(os.path.join(os.getcwd(), f"ci_results_{job_name}")):
|
| 1219 |
+
os.makedirs(os.path.join(os.getcwd(), f"ci_results_{job_name}"))
|
| 1220 |
+
|
| 1221 |
+
target_workflow = "huggingface/transformers/.github/workflows/self-scheduled-caller.yml@refs/heads/main"
|
| 1222 |
+
is_scheduled_ci_run = os.environ.get("CI_WORKFLOW_REF") == target_workflow
|
| 1223 |
+
|
| 1224 |
+
# Only the model testing job is concerned: this condition is to avoid other jobs to upload the empty list as
|
| 1225 |
+
# results.
|
| 1226 |
+
if job_name == "run_models_gpu":
|
| 1227 |
+
with open(f"ci_results_{job_name}/model_results.json", "w", encoding="UTF-8") as fp:
|
| 1228 |
+
json.dump(model_results, fp, indent=4, ensure_ascii=False)
|
| 1229 |
+
|
| 1230 |
+
# upload results to Hub dataset (only for the scheduled daily CI run on `main`)
|
| 1231 |
+
if is_scheduled_ci_run:
|
| 1232 |
+
api.upload_file(
|
| 1233 |
+
path_or_fileobj=f"ci_results_{job_name}/model_results.json",
|
| 1234 |
+
path_in_repo=f"{datetime.datetime.today().strftime('%Y-%m-%d')}/ci_results_{job_name}/model_results.json",
|
| 1235 |
+
repo_id="hf-internal-testing/transformers_daily_ci",
|
| 1236 |
+
repo_type="dataset",
|
| 1237 |
+
token=os.environ.get("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN", None),
|
| 1238 |
+
)
|
| 1239 |
+
|
| 1240 |
+
# Must have the same keys as in `additional_results`.
|
| 1241 |
+
# The values are used as the file names where to save the corresponding CI job results.
|
| 1242 |
+
test_to_result_name = {
|
| 1243 |
+
"PyTorch pipelines": "torch_pipeline",
|
| 1244 |
+
"TensorFlow pipelines": "tf_pipeline",
|
| 1245 |
+
"Examples directory": "example",
|
| 1246 |
+
"Torch CUDA extension tests": "deepspeed",
|
| 1247 |
+
}
|
| 1248 |
+
for job, job_result in additional_results.items():
|
| 1249 |
+
with open(f"ci_results_{job_name}/{test_to_result_name[job]}_results.json", "w", encoding="UTF-8") as fp:
|
| 1250 |
+
json.dump(job_result, fp, indent=4, ensure_ascii=False)
|
| 1251 |
+
|
| 1252 |
+
# upload results to Hub dataset (only for the scheduled daily CI run on `main`)
|
| 1253 |
+
if is_scheduled_ci_run:
|
| 1254 |
+
api.upload_file(
|
| 1255 |
+
path_or_fileobj=f"ci_results_{job_name}/{test_to_result_name[job]}_results.json",
|
| 1256 |
+
path_in_repo=f"{datetime.datetime.today().strftime('%Y-%m-%d')}/ci_results_{job_name}/{test_to_result_name[job]}_results.json",
|
| 1257 |
+
repo_id="hf-internal-testing/transformers_daily_ci",
|
| 1258 |
+
repo_type="dataset",
|
| 1259 |
+
token=os.environ.get("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN", None),
|
| 1260 |
+
)
|
| 1261 |
+
|
| 1262 |
+
prev_ci_artifacts = None
|
| 1263 |
+
if is_scheduled_ci_run:
|
| 1264 |
+
if job_name == "run_models_gpu":
|
| 1265 |
+
# Get the last previously completed CI's failure tables
|
| 1266 |
+
artifact_names = [f"ci_results_{job_name}"]
|
| 1267 |
+
output_dir = os.path.join(os.getcwd(), "previous_reports")
|
| 1268 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 1269 |
+
prev_ci_artifacts = get_last_daily_ci_reports(
|
| 1270 |
+
artifact_names=artifact_names, output_dir=output_dir, token=os.environ["ACCESS_REPO_INFO_TOKEN"]
|
| 1271 |
+
)
|
| 1272 |
+
|
| 1273 |
+
message = Message(
|
| 1274 |
+
title,
|
| 1275 |
+
ci_title,
|
| 1276 |
+
model_results,
|
| 1277 |
+
additional_results,
|
| 1278 |
+
selected_warnings=selected_warnings,
|
| 1279 |
+
prev_ci_artifacts=prev_ci_artifacts,
|
| 1280 |
+
)
|
| 1281 |
+
|
| 1282 |
+
# send report only if there is any failure (for push CI)
|
| 1283 |
+
if message.n_failures or (ci_event != "push" and not ci_event.startswith("Push CI (AMD)")):
|
| 1284 |
+
message.post()
|
| 1285 |
+
message.post_reply()
|
tasks/tasksmith-441eeab80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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import re
|
| 18 |
+
import time
|
| 19 |
+
from typing import Dict, List
|
| 20 |
+
|
| 21 |
+
from get_ci_error_statistics import get_jobs
|
| 22 |
+
from slack_sdk import WebClient
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
client = WebClient(token=os.environ["CI_SLACK_BOT_TOKEN"])
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def handle_test_results(test_results):
|
| 29 |
+
expressions = test_results.split(" ")
|
| 30 |
+
|
| 31 |
+
failed = 0
|
| 32 |
+
success = 0
|
| 33 |
+
|
| 34 |
+
# When the output is short enough, the output is surrounded by = signs: "== OUTPUT =="
|
| 35 |
+
# When it is too long, those signs are not present.
|
| 36 |
+
time_spent = expressions[-2] if "=" in expressions[-1] else expressions[-1]
|
| 37 |
+
|
| 38 |
+
for i, expression in enumerate(expressions):
|
| 39 |
+
if "failed" in expression:
|
| 40 |
+
failed += int(expressions[i - 1])
|
| 41 |
+
if "passed" in expression:
|
| 42 |
+
success += int(expressions[i - 1])
|
| 43 |
+
|
| 44 |
+
return failed, success, time_spent
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def extract_first_line_failure(failures_short_lines):
|
| 48 |
+
failures = {}
|
| 49 |
+
file = None
|
| 50 |
+
in_error = False
|
| 51 |
+
for line in failures_short_lines.split("\n"):
|
| 52 |
+
if re.search(r"_ \[doctest\]", line):
|
| 53 |
+
in_error = True
|
| 54 |
+
file = line.split(" ")[2]
|
| 55 |
+
elif in_error and not line.split(" ")[0].isdigit():
|
| 56 |
+
failures[file] = line
|
| 57 |
+
in_error = False
|
| 58 |
+
|
| 59 |
+
return failures
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class Message:
|
| 63 |
+
def __init__(self, title: str, doc_test_results: Dict):
|
| 64 |
+
self.title = title
|
| 65 |
+
|
| 66 |
+
self.n_success = sum(job_result["n_success"] for job_result in doc_test_results.values())
|
| 67 |
+
self.n_failures = sum(job_result["n_failures"] for job_result in doc_test_results.values())
|
| 68 |
+
self.n_tests = self.n_success + self.n_failures
|
| 69 |
+
|
| 70 |
+
# Failures and success of the modeling tests
|
| 71 |
+
self.doc_test_results = doc_test_results
|
| 72 |
+
|
| 73 |
+
@property
|
| 74 |
+
def time(self) -> str:
|
| 75 |
+
all_results = [*self.doc_test_results.values()]
|
| 76 |
+
time_spent = [r["time_spent"].split(", ")[0] for r in all_results if len(r["time_spent"])]
|
| 77 |
+
total_secs = 0
|
| 78 |
+
|
| 79 |
+
for time in time_spent:
|
| 80 |
+
time_parts = time.split(":")
|
| 81 |
+
|
| 82 |
+
# Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute.
|
| 83 |
+
if len(time_parts) == 1:
|
| 84 |
+
time_parts = [0, 0, time_parts[0]]
|
| 85 |
+
|
| 86 |
+
hours, minutes, seconds = int(time_parts[0]), int(time_parts[1]), float(time_parts[2])
|
| 87 |
+
total_secs += hours * 3600 + minutes * 60 + seconds
|
| 88 |
+
|
| 89 |
+
hours, minutes, seconds = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60
|
| 90 |
+
return f"{int(hours)}h{int(minutes)}m{int(seconds)}s"
|
| 91 |
+
|
| 92 |
+
@property
|
| 93 |
+
def header(self) -> Dict:
|
| 94 |
+
return {"type": "header", "text": {"type": "plain_text", "text": self.title}}
|
| 95 |
+
|
| 96 |
+
@property
|
| 97 |
+
def no_failures(self) -> Dict:
|
| 98 |
+
return {
|
| 99 |
+
"type": "section",
|
| 100 |
+
"text": {
|
| 101 |
+
"type": "plain_text",
|
| 102 |
+
"text": f"🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.",
|
| 103 |
+
"emoji": True,
|
| 104 |
+
},
|
| 105 |
+
"accessory": {
|
| 106 |
+
"type": "button",
|
| 107 |
+
"text": {"type": "plain_text", "text": "Check Action results", "emoji": True},
|
| 108 |
+
"url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}",
|
| 109 |
+
},
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
@property
|
| 113 |
+
def failures(self) -> Dict:
|
| 114 |
+
return {
|
| 115 |
+
"type": "section",
|
| 116 |
+
"text": {
|
| 117 |
+
"type": "plain_text",
|
| 118 |
+
"text": (
|
| 119 |
+
f"There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in"
|
| 120 |
+
f" {self.time}."
|
| 121 |
+
),
|
| 122 |
+
"emoji": True,
|
| 123 |
+
},
|
| 124 |
+
"accessory": {
|
| 125 |
+
"type": "button",
|
| 126 |
+
"text": {"type": "plain_text", "text": "Check Action results", "emoji": True},
|
| 127 |
+
"url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}",
|
| 128 |
+
},
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
@property
|
| 132 |
+
def category_failures(self) -> List[Dict]:
|
| 133 |
+
failure_blocks = []
|
| 134 |
+
|
| 135 |
+
MAX_ERROR_TEXT = 3000 - len("The following examples had failures:\n\n\n\n") - len("[Truncated]\n")
|
| 136 |
+
line_length = 40
|
| 137 |
+
category_failures = {k: v["failed"] for k, v in doc_test_results.items() if isinstance(v, dict)}
|
| 138 |
+
|
| 139 |
+
def single_category_failures(category, failures):
|
| 140 |
+
text = ""
|
| 141 |
+
if len(failures) == 0:
|
| 142 |
+
return ""
|
| 143 |
+
text += f"*{category} failures*:".ljust(line_length // 2).rjust(line_length // 2) + "\n"
|
| 144 |
+
|
| 145 |
+
for idx, failure in enumerate(failures):
|
| 146 |
+
new_text = text + f"`{failure}`\n"
|
| 147 |
+
if len(new_text) > MAX_ERROR_TEXT:
|
| 148 |
+
text = text + "[Truncated]\n"
|
| 149 |
+
break
|
| 150 |
+
text = new_text
|
| 151 |
+
|
| 152 |
+
return text
|
| 153 |
+
|
| 154 |
+
for category, failures in category_failures.items():
|
| 155 |
+
report = single_category_failures(category, failures)
|
| 156 |
+
if len(report) == 0:
|
| 157 |
+
continue
|
| 158 |
+
block = {
|
| 159 |
+
"type": "section",
|
| 160 |
+
"text": {
|
| 161 |
+
"type": "mrkdwn",
|
| 162 |
+
"text": f"The following examples had failures:\n\n\n{report}\n",
|
| 163 |
+
},
|
| 164 |
+
}
|
| 165 |
+
failure_blocks.append(block)
|
| 166 |
+
|
| 167 |
+
return failure_blocks
|
| 168 |
+
|
| 169 |
+
@property
|
| 170 |
+
def payload(self) -> str:
|
| 171 |
+
blocks = [self.header]
|
| 172 |
+
|
| 173 |
+
if self.n_failures > 0:
|
| 174 |
+
blocks.append(self.failures)
|
| 175 |
+
|
| 176 |
+
if self.n_failures > 0:
|
| 177 |
+
blocks.extend(self.category_failures)
|
| 178 |
+
|
| 179 |
+
if self.n_failures == 0:
|
| 180 |
+
blocks.append(self.no_failures)
|
| 181 |
+
|
| 182 |
+
return json.dumps(blocks)
|
| 183 |
+
|
| 184 |
+
@staticmethod
|
| 185 |
+
def error_out():
|
| 186 |
+
payload = [
|
| 187 |
+
{
|
| 188 |
+
"type": "section",
|
| 189 |
+
"text": {
|
| 190 |
+
"type": "plain_text",
|
| 191 |
+
"text": "There was an issue running the tests.",
|
| 192 |
+
},
|
| 193 |
+
"accessory": {
|
| 194 |
+
"type": "button",
|
| 195 |
+
"text": {"type": "plain_text", "text": "Check Action results", "emoji": True},
|
| 196 |
+
"url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}",
|
| 197 |
+
},
|
| 198 |
+
}
|
| 199 |
+
]
|
| 200 |
+
|
| 201 |
+
print("Sending the following payload")
|
| 202 |
+
print(json.dumps({"blocks": json.loads(payload)}))
|
| 203 |
+
|
| 204 |
+
client.chat_postMessage(
|
| 205 |
+
channel=SLACK_REPORT_CHANNEL_ID,
|
| 206 |
+
text="There was an issue running the tests.",
|
| 207 |
+
blocks=payload,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
def post(self):
|
| 211 |
+
print("Sending the following payload")
|
| 212 |
+
print(json.dumps({"blocks": json.loads(self.payload)}))
|
| 213 |
+
|
| 214 |
+
text = f"{self.n_failures} failures out of {self.n_tests} tests," if self.n_failures else "All tests passed."
|
| 215 |
+
|
| 216 |
+
self.thread_ts = client.chat_postMessage(
|
| 217 |
+
channel=SLACK_REPORT_CHANNEL_ID,
|
| 218 |
+
blocks=self.payload,
|
| 219 |
+
text=text,
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
def get_reply_blocks(self, job_name, job_link, failures, text):
|
| 223 |
+
# `text` must be less than 3001 characters in Slack SDK
|
| 224 |
+
# keep some room for adding "[Truncated]" when necessary
|
| 225 |
+
MAX_ERROR_TEXT = 3000 - len("[Truncated]")
|
| 226 |
+
|
| 227 |
+
failure_text = ""
|
| 228 |
+
for key, value in failures.items():
|
| 229 |
+
new_text = failure_text + f"*{key}*\n_{value}_\n\n"
|
| 230 |
+
if len(new_text) > MAX_ERROR_TEXT:
|
| 231 |
+
# `failure_text` here has length <= 3000
|
| 232 |
+
failure_text = failure_text + "[Truncated]"
|
| 233 |
+
break
|
| 234 |
+
# `failure_text` here has length <= MAX_ERROR_TEXT
|
| 235 |
+
failure_text = new_text
|
| 236 |
+
|
| 237 |
+
title = job_name
|
| 238 |
+
content = {"type": "section", "text": {"type": "mrkdwn", "text": text}}
|
| 239 |
+
|
| 240 |
+
if job_link is not None:
|
| 241 |
+
content["accessory"] = {
|
| 242 |
+
"type": "button",
|
| 243 |
+
"text": {"type": "plain_text", "text": "GitHub Action job", "emoji": True},
|
| 244 |
+
"url": job_link,
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
return [
|
| 248 |
+
{"type": "header", "text": {"type": "plain_text", "text": title, "emoji": True}},
|
| 249 |
+
content,
|
| 250 |
+
{"type": "section", "text": {"type": "mrkdwn", "text": failure_text}},
|
| 251 |
+
]
|
| 252 |
+
|
| 253 |
+
def post_reply(self):
|
| 254 |
+
if self.thread_ts is None:
|
| 255 |
+
raise ValueError("Can only post reply if a post has been made.")
|
| 256 |
+
|
| 257 |
+
sorted_dict = sorted(self.doc_test_results.items(), key=lambda t: t[0])
|
| 258 |
+
for job_name, job_result in sorted_dict:
|
| 259 |
+
if len(job_result["failures"]) > 0:
|
| 260 |
+
text = f"*Num failures* :{len(job_result['failed'])} \n"
|
| 261 |
+
failures = job_result["failures"]
|
| 262 |
+
blocks = self.get_reply_blocks(job_name, job_result["job_link"], failures, text=text)
|
| 263 |
+
|
| 264 |
+
print("Sending the following reply")
|
| 265 |
+
print(json.dumps({"blocks": blocks}))
|
| 266 |
+
|
| 267 |
+
client.chat_postMessage(
|
| 268 |
+
channel=SLACK_REPORT_CHANNEL_ID,
|
| 269 |
+
text=f"Results for {job_name}",
|
| 270 |
+
blocks=blocks,
|
| 271 |
+
thread_ts=self.thread_ts["ts"],
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
time.sleep(1)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def retrieve_artifact(name: str):
|
| 278 |
+
_artifact = {}
|
| 279 |
+
|
| 280 |
+
if os.path.exists(name):
|
| 281 |
+
files = os.listdir(name)
|
| 282 |
+
for file in files:
|
| 283 |
+
try:
|
| 284 |
+
with open(os.path.join(name, file), encoding="utf-8") as f:
|
| 285 |
+
_artifact[file.split(".")[0]] = f.read()
|
| 286 |
+
except UnicodeDecodeError as e:
|
| 287 |
+
raise ValueError(f"Could not open {os.path.join(name, file)}.") from e
|
| 288 |
+
|
| 289 |
+
return _artifact
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def retrieve_available_artifacts():
|
| 293 |
+
class Artifact:
|
| 294 |
+
def __init__(self, name: str):
|
| 295 |
+
self.name = name
|
| 296 |
+
self.paths = []
|
| 297 |
+
|
| 298 |
+
def __str__(self):
|
| 299 |
+
return self.name
|
| 300 |
+
|
| 301 |
+
def add_path(self, path: str):
|
| 302 |
+
self.paths.append({"name": self.name, "path": path})
|
| 303 |
+
|
| 304 |
+
_available_artifacts: Dict[str, Artifact] = {}
|
| 305 |
+
|
| 306 |
+
directories = filter(os.path.isdir, os.listdir())
|
| 307 |
+
for directory in directories:
|
| 308 |
+
artifact_name = directory
|
| 309 |
+
if artifact_name not in _available_artifacts:
|
| 310 |
+
_available_artifacts[artifact_name] = Artifact(artifact_name)
|
| 311 |
+
|
| 312 |
+
_available_artifacts[artifact_name].add_path(directory)
|
| 313 |
+
|
| 314 |
+
return _available_artifacts
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
if __name__ == "__main__":
|
| 318 |
+
SLACK_REPORT_CHANNEL_ID = os.environ["SLACK_REPORT_CHANNEL"]
|
| 319 |
+
|
| 320 |
+
github_actions_jobs = get_jobs(
|
| 321 |
+
workflow_run_id=os.environ["GITHUB_RUN_ID"], token=os.environ["ACCESS_REPO_INFO_TOKEN"]
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
artifact_name_to_job_map = {}
|
| 325 |
+
for job in github_actions_jobs:
|
| 326 |
+
for step in job["steps"]:
|
| 327 |
+
if step["name"].startswith("Test suite reports artifacts: "):
|
| 328 |
+
artifact_name = step["name"][len("Test suite reports artifacts: ") :]
|
| 329 |
+
artifact_name_to_job_map[artifact_name] = job
|
| 330 |
+
break
|
| 331 |
+
|
| 332 |
+
available_artifacts = retrieve_available_artifacts()
|
| 333 |
+
|
| 334 |
+
doc_test_results = {}
|
| 335 |
+
# `artifact_key` is the artifact path
|
| 336 |
+
for artifact_key, artifact_obj in available_artifacts.items():
|
| 337 |
+
artifact_path = artifact_obj.paths[0]
|
| 338 |
+
if not artifact_path["path"].startswith("doc_tests_gpu_test_reports_"):
|
| 339 |
+
continue
|
| 340 |
+
|
| 341 |
+
# change "_" back to "/" (to show the job name as path)
|
| 342 |
+
job_name = artifact_path["path"].replace("doc_tests_gpu_test_reports_", "").replace("_", "/")
|
| 343 |
+
|
| 344 |
+
# This dict (for each job) will contain all the information relative to each doc test job, in particular:
|
| 345 |
+
# - failed: list of failed tests
|
| 346 |
+
# - failures: dict in the format 'test': 'error_message'
|
| 347 |
+
job_result = {}
|
| 348 |
+
doc_test_results[job_name] = job_result
|
| 349 |
+
|
| 350 |
+
job = artifact_name_to_job_map[artifact_path["path"]]
|
| 351 |
+
job_result["job_link"] = job["html_url"]
|
| 352 |
+
job_result["category"] = "Python Examples" if job_name.startswith("src/") else "MD Examples"
|
| 353 |
+
|
| 354 |
+
artifact = retrieve_artifact(artifact_path["path"])
|
| 355 |
+
if "stats" in artifact:
|
| 356 |
+
failed, success, time_spent = handle_test_results(artifact["stats"])
|
| 357 |
+
job_result["n_failures"] = failed
|
| 358 |
+
job_result["n_success"] = success
|
| 359 |
+
job_result["time_spent"] = time_spent[1:-1] + ", "
|
| 360 |
+
job_result["failed"] = []
|
| 361 |
+
job_result["failures"] = {}
|
| 362 |
+
|
| 363 |
+
all_failures = extract_first_line_failure(artifact["failures_short"])
|
| 364 |
+
for line in artifact["summary_short"].split("\n"):
|
| 365 |
+
if re.search("FAILED", line):
|
| 366 |
+
line = line.replace("FAILED ", "")
|
| 367 |
+
line = line.split()[0].replace("\n", "")
|
| 368 |
+
|
| 369 |
+
if "::" in line:
|
| 370 |
+
file_path, test = line.split("::")
|
| 371 |
+
else:
|
| 372 |
+
file_path, test = line, line
|
| 373 |
+
|
| 374 |
+
job_result["failed"].append(test)
|
| 375 |
+
failure = all_failures[test] if test in all_failures else "N/A"
|
| 376 |
+
job_result["failures"][test] = failure
|
| 377 |
+
|
| 378 |
+
# Save and to be uploaded as artifact
|
| 379 |
+
os.makedirs("doc_test_results", exist_ok=True)
|
| 380 |
+
with open("doc_test_results/doc_test_results.json", "w", encoding="UTF-8") as fp:
|
| 381 |
+
json.dump(doc_test_results, fp, ensure_ascii=False, indent=4)
|
| 382 |
+
|
| 383 |
+
message = Message("🤗 Results of the doc tests.", doc_test_results)
|
| 384 |
+
message.post()
|
| 385 |
+
message.post_reply()
|
tasks/tasksmith-441eeab80047/environment/source/utils/notification_service_quantization.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import ast
|
| 16 |
+
import datetime
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import time
|
| 21 |
+
from typing import Dict
|
| 22 |
+
|
| 23 |
+
from get_ci_error_statistics import get_jobs
|
| 24 |
+
from huggingface_hub import HfApi
|
| 25 |
+
from notification_service import (
|
| 26 |
+
Message,
|
| 27 |
+
handle_stacktraces,
|
| 28 |
+
handle_test_results,
|
| 29 |
+
prepare_reports,
|
| 30 |
+
retrieve_artifact,
|
| 31 |
+
retrieve_available_artifacts,
|
| 32 |
+
)
|
| 33 |
+
from slack_sdk import WebClient
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
api = HfApi()
|
| 37 |
+
client = WebClient(token=os.environ["CI_SLACK_BOT_TOKEN"])
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class QuantizationMessage(Message):
|
| 41 |
+
def __init__(
|
| 42 |
+
self,
|
| 43 |
+
title: str,
|
| 44 |
+
results: Dict,
|
| 45 |
+
):
|
| 46 |
+
self.title = title
|
| 47 |
+
|
| 48 |
+
# Failures and success of the modeling tests
|
| 49 |
+
self.n_success = sum(r["success"] for r in results.values())
|
| 50 |
+
self.single_gpu_failures = sum(r["failed"]["single"] for r in results.values())
|
| 51 |
+
self.multi_gpu_failures = sum(r["failed"]["multi"] for r in results.values())
|
| 52 |
+
self.n_failures = self.single_gpu_failures + self.multi_gpu_failures
|
| 53 |
+
|
| 54 |
+
self.n_tests = self.n_failures + self.n_success
|
| 55 |
+
self.results = results
|
| 56 |
+
self.thread_ts = None
|
| 57 |
+
|
| 58 |
+
@property
|
| 59 |
+
def payload(self) -> str:
|
| 60 |
+
blocks = [self.header]
|
| 61 |
+
|
| 62 |
+
if self.n_failures > 0:
|
| 63 |
+
blocks.append(self.failures_overwiew)
|
| 64 |
+
blocks.append(self.failures_detailed)
|
| 65 |
+
|
| 66 |
+
if self.n_failures == 0:
|
| 67 |
+
blocks.append(self.no_failures)
|
| 68 |
+
|
| 69 |
+
return json.dumps(blocks)
|
| 70 |
+
|
| 71 |
+
@property
|
| 72 |
+
def time(self) -> str:
|
| 73 |
+
all_results = self.results.values()
|
| 74 |
+
time_spent = []
|
| 75 |
+
for r in all_results:
|
| 76 |
+
if len(r["time_spent"]):
|
| 77 |
+
time_spent.extend([x for x in r["time_spent"].split(", ") if len(x.strip())])
|
| 78 |
+
total_secs = 0
|
| 79 |
+
|
| 80 |
+
for time in time_spent:
|
| 81 |
+
time_parts = time.split(":")
|
| 82 |
+
|
| 83 |
+
# Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute.
|
| 84 |
+
if len(time_parts) == 1:
|
| 85 |
+
time_parts = [0, 0, time_parts[0]]
|
| 86 |
+
|
| 87 |
+
hours, minutes, seconds = int(time_parts[0]), int(time_parts[1]), float(time_parts[2])
|
| 88 |
+
total_secs += hours * 3600 + minutes * 60 + seconds
|
| 89 |
+
|
| 90 |
+
hours, minutes, seconds = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60
|
| 91 |
+
return f"{int(hours)}h{int(minutes)}m{int(seconds)}s"
|
| 92 |
+
|
| 93 |
+
@property
|
| 94 |
+
def failures_overwiew(self) -> Dict:
|
| 95 |
+
return {
|
| 96 |
+
"type": "section",
|
| 97 |
+
"text": {
|
| 98 |
+
"type": "plain_text",
|
| 99 |
+
"text": (
|
| 100 |
+
f"There were {self.n_failures} failures, out of {self.n_tests} tests.\n"
|
| 101 |
+
f"The suite ran in {self.time}."
|
| 102 |
+
),
|
| 103 |
+
"emoji": True,
|
| 104 |
+
},
|
| 105 |
+
"accessory": {
|
| 106 |
+
"type": "button",
|
| 107 |
+
"text": {"type": "plain_text", "text": "Check Action results", "emoji": True},
|
| 108 |
+
"url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}",
|
| 109 |
+
},
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
@property
|
| 113 |
+
def failures_detailed(self) -> Dict:
|
| 114 |
+
failures = {k: v["failed"] for k, v in self.results.items()}
|
| 115 |
+
|
| 116 |
+
individual_reports = []
|
| 117 |
+
for key, value in failures.items():
|
| 118 |
+
device_report = self.get_device_report(value)
|
| 119 |
+
if sum(value.values()):
|
| 120 |
+
report = f"{device_report}{key}"
|
| 121 |
+
individual_reports.append(report)
|
| 122 |
+
|
| 123 |
+
header = "Single | Multi | Category\n"
|
| 124 |
+
failures_report = prepare_reports(
|
| 125 |
+
title="The following quantization tests had failures", header=header, reports=individual_reports
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
return {"type": "section", "text": {"type": "mrkdwn", "text": failures_report}}
|
| 129 |
+
|
| 130 |
+
def post(self):
|
| 131 |
+
payload = self.payload
|
| 132 |
+
print("Sending the following payload")
|
| 133 |
+
print(json.dumps({"blocks": json.loads(payload)}))
|
| 134 |
+
|
| 135 |
+
text = f"{self.n_failures} failures out of {self.n_tests} tests," if self.n_failures else "All tests passed."
|
| 136 |
+
|
| 137 |
+
self.thread_ts = client.chat_postMessage(
|
| 138 |
+
channel=SLACK_REPORT_CHANNEL_ID,
|
| 139 |
+
blocks=payload,
|
| 140 |
+
text=text,
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
def post_reply(self):
|
| 144 |
+
if self.thread_ts is None:
|
| 145 |
+
raise ValueError("Can only post reply if a post has been made.")
|
| 146 |
+
|
| 147 |
+
for job, job_result in self.results.items():
|
| 148 |
+
if len(job_result["failures"]):
|
| 149 |
+
for device, failures in job_result["failures"].items():
|
| 150 |
+
blocks = self.get_reply_blocks(
|
| 151 |
+
job,
|
| 152 |
+
job_result,
|
| 153 |
+
failures,
|
| 154 |
+
device,
|
| 155 |
+
text=f'Number of failures: {job_result["failed"][device]}',
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
print("Sending the following reply")
|
| 159 |
+
print(json.dumps({"blocks": blocks}))
|
| 160 |
+
|
| 161 |
+
client.chat_postMessage(
|
| 162 |
+
channel="#transformers-ci-daily-quantization",
|
| 163 |
+
text=f"Results for {job}",
|
| 164 |
+
blocks=blocks,
|
| 165 |
+
thread_ts=self.thread_ts["ts"],
|
| 166 |
+
)
|
| 167 |
+
time.sleep(1)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
if __name__ == "__main__":
|
| 171 |
+
setup_status = os.environ.get("SETUP_STATUS")
|
| 172 |
+
SLACK_REPORT_CHANNEL_ID = os.environ["SLACK_REPORT_CHANNEL"]
|
| 173 |
+
setup_failed = True if setup_status is not None and setup_status != "success" else False
|
| 174 |
+
|
| 175 |
+
# This env. variable is set in workflow file (under the job `send_results`).
|
| 176 |
+
ci_event = os.environ["CI_EVENT"]
|
| 177 |
+
|
| 178 |
+
title = f"🤗 Results of the {ci_event} - {os.getenv('CI_TEST_JOB')}."
|
| 179 |
+
|
| 180 |
+
if setup_failed:
|
| 181 |
+
Message.error_out(
|
| 182 |
+
title, ci_title="", runner_not_available=False, runner_failed=False, setup_failed=setup_failed
|
| 183 |
+
)
|
| 184 |
+
exit(0)
|
| 185 |
+
|
| 186 |
+
arguments = sys.argv[1:][0]
|
| 187 |
+
try:
|
| 188 |
+
quantization_matrix = ast.literal_eval(arguments)
|
| 189 |
+
# Need to change from elements like `quantization/bnb` to `quantization_bnb` (the ones used as artifact names).
|
| 190 |
+
quantization_matrix = [x.replace("quantization/", "quantization_") for x in quantization_matrix]
|
| 191 |
+
except SyntaxError:
|
| 192 |
+
Message.error_out(title, ci_title="")
|
| 193 |
+
raise ValueError("Errored out.")
|
| 194 |
+
|
| 195 |
+
available_artifacts = retrieve_available_artifacts()
|
| 196 |
+
|
| 197 |
+
quantization_results = {
|
| 198 |
+
quant: {
|
| 199 |
+
"failed": {"single": 0, "multi": 0},
|
| 200 |
+
"success": 0,
|
| 201 |
+
"time_spent": "",
|
| 202 |
+
"failures": {},
|
| 203 |
+
"job_link": {},
|
| 204 |
+
}
|
| 205 |
+
for quant in quantization_matrix
|
| 206 |
+
if f"run_quantization_torch_gpu_{ quant }_test_reports" in available_artifacts
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
github_actions_jobs = get_jobs(
|
| 210 |
+
workflow_run_id=os.environ["GITHUB_RUN_ID"], token=os.environ["ACCESS_REPO_INFO_TOKEN"]
|
| 211 |
+
)
|
| 212 |
+
github_actions_job_links = {job["name"]: job["html_url"] for job in github_actions_jobs}
|
| 213 |
+
|
| 214 |
+
artifact_name_to_job_map = {}
|
| 215 |
+
for job in github_actions_jobs:
|
| 216 |
+
for step in job["steps"]:
|
| 217 |
+
if step["name"].startswith("Test suite reports artifacts: "):
|
| 218 |
+
artifact_name = step["name"][len("Test suite reports artifacts: ") :]
|
| 219 |
+
artifact_name_to_job_map[artifact_name] = job
|
| 220 |
+
break
|
| 221 |
+
|
| 222 |
+
for quant in quantization_results.keys():
|
| 223 |
+
for artifact_path in available_artifacts[f"run_quantization_torch_gpu_{ quant }_test_reports"].paths:
|
| 224 |
+
artifact = retrieve_artifact(artifact_path["path"], artifact_path["gpu"])
|
| 225 |
+
if "stats" in artifact:
|
| 226 |
+
# Link to the GitHub Action job
|
| 227 |
+
job = artifact_name_to_job_map[artifact_path["path"]]
|
| 228 |
+
quantization_results[quant]["job_link"][artifact_path["gpu"]] = job["html_url"]
|
| 229 |
+
failed, success, time_spent = handle_test_results(artifact["stats"])
|
| 230 |
+
quantization_results[quant]["failed"][artifact_path["gpu"]] += failed
|
| 231 |
+
quantization_results[quant]["success"] += success
|
| 232 |
+
quantization_results[quant]["time_spent"] += time_spent[1:-1] + ", "
|
| 233 |
+
|
| 234 |
+
stacktraces = handle_stacktraces(artifact["failures_line"])
|
| 235 |
+
|
| 236 |
+
for line in artifact["summary_short"].split("\n"):
|
| 237 |
+
if line.startswith("FAILED "):
|
| 238 |
+
line = line[len("FAILED ") :]
|
| 239 |
+
line = line.split()[0].replace("\n", "")
|
| 240 |
+
|
| 241 |
+
if artifact_path["gpu"] not in quantization_results[quant]["failures"]:
|
| 242 |
+
quantization_results[quant]["failures"][artifact_path["gpu"]] = []
|
| 243 |
+
|
| 244 |
+
quantization_results[quant]["failures"][artifact_path["gpu"]].append(
|
| 245 |
+
{"line": line, "trace": stacktraces.pop(0)}
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
job_name = os.getenv("CI_TEST_JOB")
|
| 249 |
+
if not os.path.isdir(os.path.join(os.getcwd(), f"ci_results_{job_name}")):
|
| 250 |
+
os.makedirs(os.path.join(os.getcwd(), f"ci_results_{job_name}"))
|
| 251 |
+
|
| 252 |
+
with open(f"ci_results_{job_name}/quantization_results.json", "w", encoding="UTF-8") as fp:
|
| 253 |
+
json.dump(quantization_results, fp, indent=4, ensure_ascii=False)
|
| 254 |
+
|
| 255 |
+
target_workflow = "huggingface/transformers/.github/workflows/self-scheduled-caller.yml@refs/heads/main"
|
| 256 |
+
is_scheduled_ci_run = os.environ.get("CI_WORKFLOW_REF") == target_workflow
|
| 257 |
+
|
| 258 |
+
# upload results to Hub dataset (only for the scheduled daily CI run on `main`)
|
| 259 |
+
if is_scheduled_ci_run:
|
| 260 |
+
api.upload_file(
|
| 261 |
+
path_or_fileobj=f"ci_results_{job_name}/quantization_results.json",
|
| 262 |
+
path_in_repo=f"{datetime.datetime.today().strftime('%Y-%m-%d')}/ci_results_{job_name}/quantization_results.json",
|
| 263 |
+
repo_id="hf-internal-testing/transformers_daily_ci",
|
| 264 |
+
repo_type="dataset",
|
| 265 |
+
token=os.environ.get("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN", None),
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
message = QuantizationMessage(
|
| 269 |
+
title,
|
| 270 |
+
results=quantization_results,
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
message.post()
|
| 274 |
+
message.post_reply()
|
tasks/tasksmith-441eeab80047/environment/source/utils/past_ci_versions.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
past_versions_testing = {
|
| 6 |
+
"pytorch": {
|
| 7 |
+
"1.13": {
|
| 8 |
+
"torch": "1.13.1",
|
| 9 |
+
"torchvision": "0.14.1",
|
| 10 |
+
"torchaudio": "0.13.1",
|
| 11 |
+
"python": 3.9,
|
| 12 |
+
"cuda": "cu116",
|
| 13 |
+
"install": (
|
| 14 |
+
"python3 -m pip install --no-cache-dir -U torch==1.13.1 torchvision==0.14.1 torchaudio==0.13.1"
|
| 15 |
+
" --extra-index-url https://download.pytorch.org/whl/cu116"
|
| 16 |
+
),
|
| 17 |
+
"base_image": "nvidia/cuda:11.6.2-cudnn8-devel-ubuntu20.04",
|
| 18 |
+
},
|
| 19 |
+
"1.12": {
|
| 20 |
+
"torch": "1.12.1",
|
| 21 |
+
"torchvision": "0.13.1",
|
| 22 |
+
"torchaudio": "0.12.1",
|
| 23 |
+
"python": 3.9,
|
| 24 |
+
"cuda": "cu113",
|
| 25 |
+
"install": (
|
| 26 |
+
"python3 -m pip install --no-cache-dir -U torch==1.12.1 torchvision==0.13.1 torchaudio==0.12.1"
|
| 27 |
+
" --extra-index-url https://download.pytorch.org/whl/cu113"
|
| 28 |
+
),
|
| 29 |
+
"base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04",
|
| 30 |
+
},
|
| 31 |
+
"1.11": {
|
| 32 |
+
"torch": "1.11.0",
|
| 33 |
+
"torchvision": "0.12.0",
|
| 34 |
+
"torchaudio": "0.11.0",
|
| 35 |
+
"python": 3.9,
|
| 36 |
+
"cuda": "cu113",
|
| 37 |
+
"install": (
|
| 38 |
+
"python3 -m pip install --no-cache-dir -U torch==1.11.0 torchvision==0.12.0 torchaudio==0.11.0"
|
| 39 |
+
" --extra-index-url https://download.pytorch.org/whl/cu113"
|
| 40 |
+
),
|
| 41 |
+
"base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04",
|
| 42 |
+
},
|
| 43 |
+
"1.10": {
|
| 44 |
+
"torch": "1.10.2",
|
| 45 |
+
"torchvision": "0.11.3",
|
| 46 |
+
"torchaudio": "0.10.2",
|
| 47 |
+
"python": 3.9,
|
| 48 |
+
"cuda": "cu113",
|
| 49 |
+
"install": (
|
| 50 |
+
"python3 -m pip install --no-cache-dir -U torch==1.10.2 torchvision==0.11.3 torchaudio==0.10.2"
|
| 51 |
+
" --extra-index-url https://download.pytorch.org/whl/cu113"
|
| 52 |
+
),
|
| 53 |
+
"base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04",
|
| 54 |
+
},
|
| 55 |
+
# torchaudio < 0.10 has no CUDA-enabled binary distributions
|
| 56 |
+
"1.9": {
|
| 57 |
+
"torch": "1.9.1",
|
| 58 |
+
"torchvision": "0.10.1",
|
| 59 |
+
"torchaudio": "0.9.1",
|
| 60 |
+
"python": 3.9,
|
| 61 |
+
"cuda": "cu111",
|
| 62 |
+
"install": (
|
| 63 |
+
"python3 -m pip install --no-cache-dir -U torch==1.9.1 torchvision==0.10.1 torchaudio==0.9.1"
|
| 64 |
+
" --extra-index-url https://download.pytorch.org/whl/cu111"
|
| 65 |
+
),
|
| 66 |
+
"base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04",
|
| 67 |
+
},
|
| 68 |
+
},
|
| 69 |
+
"tensorflow": {
|
| 70 |
+
"2.11": {
|
| 71 |
+
"tensorflow": "2.11.1",
|
| 72 |
+
"install": "python3 -m pip install --no-cache-dir -U tensorflow==2.11.1",
|
| 73 |
+
"base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04",
|
| 74 |
+
},
|
| 75 |
+
"2.10": {
|
| 76 |
+
"tensorflow": "2.10.1",
|
| 77 |
+
"install": "python3 -m pip install --no-cache-dir -U tensorflow==2.10.1",
|
| 78 |
+
"base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04",
|
| 79 |
+
},
|
| 80 |
+
"2.9": {
|
| 81 |
+
"tensorflow": "2.9.3",
|
| 82 |
+
"install": "python3 -m pip install --no-cache-dir -U tensorflow==2.9.3",
|
| 83 |
+
"base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04",
|
| 84 |
+
},
|
| 85 |
+
"2.8": {
|
| 86 |
+
"tensorflow": "2.8.2",
|
| 87 |
+
"install": "python3 -m pip install --no-cache-dir -U tensorflow==2.8.2",
|
| 88 |
+
"base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04",
|
| 89 |
+
},
|
| 90 |
+
"2.7": {
|
| 91 |
+
"tensorflow": "2.7.3",
|
| 92 |
+
"install": "python3 -m pip install --no-cache-dir -U tensorflow==2.7.3",
|
| 93 |
+
"base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04",
|
| 94 |
+
},
|
| 95 |
+
"2.6": {
|
| 96 |
+
"tensorflow": "2.6.5",
|
| 97 |
+
"install": "python3 -m pip install --no-cache-dir -U tensorflow==2.6.5",
|
| 98 |
+
"base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04",
|
| 99 |
+
},
|
| 100 |
+
"2.5": {
|
| 101 |
+
"tensorflow": "2.5.3",
|
| 102 |
+
"install": "python3 -m pip install --no-cache-dir -U tensorflow==2.5.3",
|
| 103 |
+
"base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04",
|
| 104 |
+
},
|
| 105 |
+
},
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
if __name__ == "__main__":
|
| 110 |
+
parser = argparse.ArgumentParser("Choose the framework and version to install")
|
| 111 |
+
parser.add_argument(
|
| 112 |
+
"--framework", help="The framework to install. Should be `torch` or `tensorflow`", type=str, required=True
|
| 113 |
+
)
|
| 114 |
+
parser.add_argument("--version", help="The version of the framework to install.", type=str, required=True)
|
| 115 |
+
args = parser.parse_args()
|
| 116 |
+
|
| 117 |
+
info = past_versions_testing[args.framework][args.version]
|
| 118 |
+
|
| 119 |
+
os.system(f'echo "export INSTALL_CMD=\'{info["install"]}\'" >> ~/.profile')
|
| 120 |
+
print(f'echo "export INSTALL_CMD=\'{info["install"]}\'" >> ~/.profile')
|
| 121 |
+
|
| 122 |
+
cuda = ""
|
| 123 |
+
if args.framework == "pytorch":
|
| 124 |
+
cuda = info["cuda"]
|
| 125 |
+
os.system(f"echo \"export CUDA='{cuda}'\" >> ~/.profile")
|
| 126 |
+
print(f"echo \"export CUDA='{cuda}'\" >> ~/.profile")
|
tasks/tasksmith-441eeab80047/environment/source/utils/patch_helper.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""
|
| 17 |
+
This should help you prepare a patch, automatically extracting the commits to cherry-pick
|
| 18 |
+
in chronological order to avoid merge conflicts. An equivalent way to do this is to use
|
| 19 |
+
`git log --pretty=oneline HEAD...v4.41.0` and grep.
|
| 20 |
+
|
| 21 |
+
Potential TODO: automatically cherry-picks them.
|
| 22 |
+
|
| 23 |
+
Pass in a list of PR:
|
| 24 |
+
`python utils/patch_helper.py --prs 31108 31054 31008 31010 31004`
|
| 25 |
+
will produce the following:
|
| 26 |
+
```bash
|
| 27 |
+
Skipping invalid version tag: list
|
| 28 |
+
Skipping invalid version tag: localattn1
|
| 29 |
+
Git cherry-pick commands to run:
|
| 30 |
+
git cherry-pick 03935d300d60110bb86edb49d2315089cfb19789 #2024-05-24 11:00:59+02:00
|
| 31 |
+
git cherry-pick bdb9106f247fca48a71eb384be25dbbd29b065a8 #2024-05-24 19:02:55+02:00
|
| 32 |
+
git cherry-pick 84c4b72ee99e8e65a8a5754a5f9d6265b45cf67e #2024-05-27 10:34:14+02:00
|
| 33 |
+
git cherry-pick 936ab7bae5e040ec58994cb722dd587b9ab26581 #2024-05-28 11:56:05+02:00
|
| 34 |
+
git cherry-pick 0bef4a273825d2cfc52ddfe62ba486ee61cc116f #2024-05-29 13:33:26+01:00
|
| 35 |
+
```
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
import argparse
|
| 39 |
+
|
| 40 |
+
from git import GitCommandError, Repo
|
| 41 |
+
from packaging import version
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def get_merge_commit(repo, pr_number, since_tag):
|
| 45 |
+
try:
|
| 46 |
+
# Use git log to find the merge commit for the PR within the given tag range
|
| 47 |
+
merge_commit = next(repo.iter_commits(f"v{since_tag}...origin/main", grep=f"#{pr_number}"))
|
| 48 |
+
return merge_commit
|
| 49 |
+
except StopIteration:
|
| 50 |
+
print(f"No merge commit found for PR #{pr_number} between tags {since_tag} and {main}")
|
| 51 |
+
return None
|
| 52 |
+
except GitCommandError as e:
|
| 53 |
+
print(f"Error finding merge commit for PR #{pr_number}: {str(e)}")
|
| 54 |
+
return None
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def main(pr_numbers):
|
| 58 |
+
repo = Repo(".") # Initialize the Repo object for the current directory
|
| 59 |
+
merge_commits = []
|
| 60 |
+
|
| 61 |
+
tags = {}
|
| 62 |
+
for tag in repo.tags:
|
| 63 |
+
try:
|
| 64 |
+
# Parse and sort tags, skip invalid ones
|
| 65 |
+
tag_ver = version.parse(tag.name)
|
| 66 |
+
tags[tag_ver] = tag
|
| 67 |
+
except Exception:
|
| 68 |
+
print(f"Skipping invalid version tag: {tag.name}")
|
| 69 |
+
|
| 70 |
+
last_tag = sorted(tags)[-1]
|
| 71 |
+
major_minor = f"{last_tag.major}.{last_tag.minor}.0"
|
| 72 |
+
# Iterate through tag ranges to find the merge commits
|
| 73 |
+
for pr in pr_numbers:
|
| 74 |
+
pr = pr.split("https://github.com/huggingface/transformers/pull/")[-1]
|
| 75 |
+
commit = get_merge_commit(repo, pr, major_minor)
|
| 76 |
+
if commit:
|
| 77 |
+
merge_commits.append(commit)
|
| 78 |
+
|
| 79 |
+
# Sort commits by date
|
| 80 |
+
merge_commits.sort(key=lambda commit: commit.committed_datetime)
|
| 81 |
+
|
| 82 |
+
# Output the git cherry-pick commands
|
| 83 |
+
print("Git cherry-pick commands to run:")
|
| 84 |
+
for commit in merge_commits:
|
| 85 |
+
print(f"git cherry-pick {commit.hexsha} #{commit.committed_datetime}")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
if __name__ == "__main__":
|
| 89 |
+
parser = argparse.ArgumentParser(description="Find and sort merge commits for specified PRs.")
|
| 90 |
+
parser.add_argument("--prs", nargs="+", required=False, type=str, help="PR numbers to find merge commits for")
|
| 91 |
+
|
| 92 |
+
args = parser.parse_args()
|
| 93 |
+
if args.prs is None:
|
| 94 |
+
args.prs = "https://github.com/huggingface/transformers/pull/33753 https://github.com/huggingface/transformers/pull/33861 https://github.com/huggingface/transformers/pull/33906 https://github.com/huggingface/transformers/pull/33761 https://github.com/huggingface/transformers/pull/33586 https://github.com/huggingface/transformers/pull/33766 https://github.com/huggingface/transformers/pull/33958 https://github.com/huggingface/transformers/pull/33965".split()
|
| 95 |
+
main(args.prs)
|
tasks/tasksmith-441eeab80047/environment/source/utils/pr_slow_ci_models.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 models for which to run slow CI.
|
| 17 |
+
|
| 18 |
+
A new model added in a pull request will be included, as well as models specified in a GitHub pull request's comment
|
| 19 |
+
with a prefix `run-slow`, `run_slow` or `run slow`. For example, the commit message `run_slow: bert, gpt2` will give
|
| 20 |
+
`bert` and `gpt2`.
|
| 21 |
+
|
| 22 |
+
Usage:
|
| 23 |
+
|
| 24 |
+
```bash
|
| 25 |
+
python utils/pr_slow_ci_models.py
|
| 26 |
+
```
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
import argparse
|
| 30 |
+
import os.path
|
| 31 |
+
import re
|
| 32 |
+
import string
|
| 33 |
+
from pathlib import Path
|
| 34 |
+
from typing import List
|
| 35 |
+
|
| 36 |
+
from git import Repo
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
PATH_TO_REPO = Path(__file__).parent.parent.resolve()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def get_new_python_files_between_commits(base_commit: str, commits: List[str]) -> List[str]:
|
| 43 |
+
"""
|
| 44 |
+
Get the list of added python files between a base commit and one or several commits.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
repo (`git.Repo`):
|
| 48 |
+
A git repository (for instance the Transformers repo).
|
| 49 |
+
base_commit (`str`):
|
| 50 |
+
The commit reference of where to compare for the diff. This is the current commit, not the branching point!
|
| 51 |
+
commits (`List[str]`):
|
| 52 |
+
The list of commits with which to compare the repo at `base_commit` (so the branching point).
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
`List[str]`: The list of python files added between a base commit and one or several commits.
|
| 56 |
+
"""
|
| 57 |
+
code_diff = []
|
| 58 |
+
for commit in commits:
|
| 59 |
+
for diff_obj in commit.diff(base_commit):
|
| 60 |
+
# We always add new python files
|
| 61 |
+
if diff_obj.change_type == "A" and diff_obj.b_path.endswith(".py"):
|
| 62 |
+
code_diff.append(diff_obj.b_path)
|
| 63 |
+
|
| 64 |
+
return code_diff
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def get_new_python_files(diff_with_last_commit=False) -> List[str]:
|
| 68 |
+
"""
|
| 69 |
+
Return a list of python files that have been added between the current head and the main branch.
|
| 70 |
+
|
| 71 |
+
Returns:
|
| 72 |
+
`List[str]`: The list of python files added.
|
| 73 |
+
"""
|
| 74 |
+
repo = Repo(PATH_TO_REPO)
|
| 75 |
+
|
| 76 |
+
try:
|
| 77 |
+
# For the cases where the main branch exists locally
|
| 78 |
+
main = repo.refs.main
|
| 79 |
+
except AttributeError:
|
| 80 |
+
# On GitHub Actions runners, it doesn't have local main branch
|
| 81 |
+
main = repo.remotes.origin.refs.main
|
| 82 |
+
|
| 83 |
+
if not diff_with_last_commit:
|
| 84 |
+
print(f"main is at {main.commit}")
|
| 85 |
+
print(f"Current head is at {repo.head.commit}")
|
| 86 |
+
|
| 87 |
+
commits = repo.merge_base(main, repo.head)
|
| 88 |
+
for commit in commits:
|
| 89 |
+
print(f"Branching commit: {commit}")
|
| 90 |
+
else:
|
| 91 |
+
print(f"main is at {main.commit}")
|
| 92 |
+
commits = main.commit.parents
|
| 93 |
+
for commit in commits:
|
| 94 |
+
print(f"Parent commit: {commit}")
|
| 95 |
+
|
| 96 |
+
return get_new_python_files_between_commits(repo.head.commit, commits)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def get_new_model(diff_with_last_commit=False):
|
| 100 |
+
new_files = get_new_python_files(diff_with_last_commit)
|
| 101 |
+
reg = re.compile(r"src/transformers/models/(.*)/modeling_.*\.py")
|
| 102 |
+
|
| 103 |
+
new_model = ""
|
| 104 |
+
for x in new_files:
|
| 105 |
+
find_new_model = reg.findall(x)
|
| 106 |
+
if len(find_new_model) > 0:
|
| 107 |
+
new_model = find_new_model[0]
|
| 108 |
+
# It's unlikely we have 2 new modeling files in a pull request.
|
| 109 |
+
break
|
| 110 |
+
return new_model
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def parse_message(message: str) -> str:
|
| 114 |
+
"""
|
| 115 |
+
Parses a GitHub pull request's comment to find the models specified in it to run slow CI.
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
message (`str`): The body of a GitHub pull request's comment.
|
| 119 |
+
|
| 120 |
+
Returns:
|
| 121 |
+
`str`: The substring in `message` after `run-slow`, run_slow` or run slow`. If no such prefix is found, the
|
| 122 |
+
empty string is returned.
|
| 123 |
+
"""
|
| 124 |
+
if message is None:
|
| 125 |
+
return ""
|
| 126 |
+
|
| 127 |
+
message = message.strip().lower()
|
| 128 |
+
|
| 129 |
+
# run-slow: model_1, model_2
|
| 130 |
+
if not message.startswith(("run-slow", "run_slow", "run slow")):
|
| 131 |
+
return ""
|
| 132 |
+
message = message[len("run slow") :]
|
| 133 |
+
# remove leading `:`
|
| 134 |
+
while message.strip().startswith(":"):
|
| 135 |
+
message = message.strip()[1:]
|
| 136 |
+
|
| 137 |
+
return message
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def get_models(message: str):
|
| 141 |
+
models = parse_message(message)
|
| 142 |
+
return models.replace(",", " ").split()
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def check_model_names(model_name: str):
|
| 146 |
+
allowed = string.ascii_letters + string.digits + "_"
|
| 147 |
+
return not (model_name.startswith("_") or model_name.endswith("_")) and all(c in allowed for c in model_name)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
if __name__ == "__main__":
|
| 151 |
+
parser = argparse.ArgumentParser()
|
| 152 |
+
parser.add_argument("--message", type=str, default="", help="The content of a comment.")
|
| 153 |
+
parser.add_argument("--quantization", action="store_true", help="If we collect quantization tests")
|
| 154 |
+
args = parser.parse_args()
|
| 155 |
+
|
| 156 |
+
new_model = get_new_model()
|
| 157 |
+
specified_models = get_models(args.message)
|
| 158 |
+
models = ([] if new_model == "" else [new_model]) + specified_models
|
| 159 |
+
# a guard for strange model names
|
| 160 |
+
models = [model for model in models if check_model_names(model)]
|
| 161 |
+
|
| 162 |
+
# Add prefix
|
| 163 |
+
final_list = []
|
| 164 |
+
for model in models:
|
| 165 |
+
if not args.quantization:
|
| 166 |
+
if os.path.isdir(f"tests/models/{model}"):
|
| 167 |
+
final_list.append(f"models/{model}")
|
| 168 |
+
elif os.path.isdir(f"tests/{model}") and model != "quantization":
|
| 169 |
+
final_list.append(model)
|
| 170 |
+
elif os.path.isdir(f"tests/quantization/{model}"):
|
| 171 |
+
final_list.append(f"quantization/{model}")
|
| 172 |
+
|
| 173 |
+
print(sorted(set(final_list)))
|
tasks/tasksmith-441eeab80047/environment/source/utils/print_env.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
# coding=utf-8
|
| 4 |
+
# Copyright 2020 The HuggingFace Inc. team.
|
| 5 |
+
#
|
| 6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 7 |
+
# you may not use this file except in compliance with the License.
|
| 8 |
+
# You may obtain a copy of the License at
|
| 9 |
+
#
|
| 10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 11 |
+
#
|
| 12 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 15 |
+
# See the License for the specific language governing permissions and
|
| 16 |
+
# limitations under the License.
|
| 17 |
+
|
| 18 |
+
# this script dumps information about the environment
|
| 19 |
+
|
| 20 |
+
import os
|
| 21 |
+
import sys
|
| 22 |
+
|
| 23 |
+
import transformers
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
|
| 27 |
+
|
| 28 |
+
print("Python version:", sys.version)
|
| 29 |
+
print("transformers version:", transformers.__version__)
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
import torch
|
| 33 |
+
|
| 34 |
+
print("Torch version:", torch.__version__)
|
| 35 |
+
print("Cuda available:", torch.cuda.is_available())
|
| 36 |
+
print("Cuda version:", torch.version.cuda)
|
| 37 |
+
print("CuDNN version:", torch.backends.cudnn.version())
|
| 38 |
+
print("Number of GPUs available:", torch.cuda.device_count())
|
| 39 |
+
print("NCCL version:", torch.cuda.nccl.version())
|
| 40 |
+
except ImportError:
|
| 41 |
+
print("Torch version:", None)
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
import deepspeed
|
| 45 |
+
|
| 46 |
+
print("DeepSpeed version:", deepspeed.__version__)
|
| 47 |
+
except ImportError:
|
| 48 |
+
print("DeepSpeed version:", None)
|
| 49 |
+
|
| 50 |
+
try:
|
| 51 |
+
import tensorflow as tf
|
| 52 |
+
|
| 53 |
+
print("TensorFlow version:", tf.__version__)
|
| 54 |
+
print("TF GPUs available:", bool(tf.config.list_physical_devices("GPU")))
|
| 55 |
+
print("Number of TF GPUs available:", len(tf.config.list_physical_devices("GPU")))
|
| 56 |
+
except ImportError:
|
| 57 |
+
print("TensorFlow version:", None)
|
tasks/tasksmith-441eeab80047/environment/source/utils/process_bad_commit_report.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""An internal script to process `new_model_failures_with_bad_commit.json` produced by `utils/check_bad_commit.py`.
|
| 2 |
+
|
| 3 |
+
This is used by `.github/workflows/check_failed_model_tests.yml` to produce a slack report of the following form
|
| 4 |
+
|
| 5 |
+
```
|
| 6 |
+
<{url}|New failed tests>
|
| 7 |
+
{
|
| 8 |
+
"GH_ydshieh": {
|
| 9 |
+
"vit": 1
|
| 10 |
+
}
|
| 11 |
+
}
|
| 12 |
+
```
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import datetime
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
from collections import Counter
|
| 19 |
+
from copy import deepcopy
|
| 20 |
+
|
| 21 |
+
from huggingface_hub import HfApi
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
if __name__ == "__main__":
|
| 25 |
+
api = HfApi()
|
| 26 |
+
|
| 27 |
+
with open("new_model_failures_with_bad_commit.json") as fp:
|
| 28 |
+
data = json.load(fp)
|
| 29 |
+
|
| 30 |
+
# TODO: extend
|
| 31 |
+
team_members = [
|
| 32 |
+
"ydshieh",
|
| 33 |
+
"zucchini-nlp",
|
| 34 |
+
"ArthurZucker",
|
| 35 |
+
"gante",
|
| 36 |
+
"LysandreJik",
|
| 37 |
+
"molbap",
|
| 38 |
+
"qubvel",
|
| 39 |
+
"Rocketknight1",
|
| 40 |
+
"muellerzr",
|
| 41 |
+
"SunMarc",
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
# Counting the number of failures grouped by authors
|
| 45 |
+
new_data = {}
|
| 46 |
+
for model, model_result in data.items():
|
| 47 |
+
for device, failed_tests in model_result.items():
|
| 48 |
+
for failed_test in failed_tests:
|
| 49 |
+
author = failed_test["author"]
|
| 50 |
+
|
| 51 |
+
if author not in team_members:
|
| 52 |
+
author = failed_test["merged_by"]
|
| 53 |
+
|
| 54 |
+
if author not in new_data:
|
| 55 |
+
new_data[author] = Counter()
|
| 56 |
+
new_data[author].update([model])
|
| 57 |
+
for author in new_data:
|
| 58 |
+
new_data[author] = dict(new_data[author])
|
| 59 |
+
|
| 60 |
+
# Group by author
|
| 61 |
+
new_data_full = {author: deepcopy(data) for author in new_data}
|
| 62 |
+
for author, _data in new_data_full.items():
|
| 63 |
+
for model, model_result in _data.items():
|
| 64 |
+
for device, failed_tests in model_result.items():
|
| 65 |
+
failed_tests = [x for x in failed_tests if x["author"] == author or x["merged_by"] == author]
|
| 66 |
+
model_result[device] = failed_tests
|
| 67 |
+
_data[model] = {k: v for k, v in model_result.items() if len(v) > 0}
|
| 68 |
+
new_data_full[author] = {k: v for k, v in _data.items() if len(v) > 0}
|
| 69 |
+
|
| 70 |
+
# Upload to Hub and get the url
|
| 71 |
+
with open("new_model_failures_with_bad_commit_grouped_by_authors.json", "w") as fp:
|
| 72 |
+
json.dump(new_data_full, fp, ensure_ascii=False, indent=4)
|
| 73 |
+
commit_info = api.upload_file(
|
| 74 |
+
path_or_fileobj="new_model_failures_with_bad_commit_grouped_by_authors.json",
|
| 75 |
+
path_in_repo=f"{datetime.datetime.today().strftime('%Y-%m-%d')}/ci_results_run_models_gpu/new_model_failures_with_bad_commit_grouped_by_authors.json",
|
| 76 |
+
repo_id="hf-internal-testing/transformers_daily_ci",
|
| 77 |
+
repo_type="dataset",
|
| 78 |
+
token=os.environ.get("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN", None),
|
| 79 |
+
)
|
| 80 |
+
url = f"https://huggingface.co/datasets/hf-internal-testing/transformers_daily_ci/raw/{commit_info.oid}/{datetime.datetime.today().strftime('%Y-%m-%d')}/ci_results_run_models_gpu/new_model_failures_with_bad_commit_grouped_by_authors.json"
|
| 81 |
+
|
| 82 |
+
# Add `GH_` prefix as keyword mention
|
| 83 |
+
output = {}
|
| 84 |
+
for author, item in new_data.items():
|
| 85 |
+
author = f"GH_{author}"
|
| 86 |
+
output[author] = item
|
| 87 |
+
|
| 88 |
+
report = f"<{url}|New failed tests>\\n\\n"
|
| 89 |
+
report += json.dumps(output, indent=4).replace('"', '\\"').replace("\n", "\\n")
|
| 90 |
+
print(report)
|
tasks/tasksmith-441eeab80047/environment/source/utils/process_circleci_workflow_test_reports.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import argparse
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
|
| 18 |
+
import requests
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if __name__ == "__main__":
|
| 22 |
+
parser = argparse.ArgumentParser()
|
| 23 |
+
parser.add_argument("--workflow_id", type=str, required=True)
|
| 24 |
+
args = parser.parse_args()
|
| 25 |
+
workflow_id = args.workflow_id
|
| 26 |
+
|
| 27 |
+
r = requests.get(
|
| 28 |
+
f"https://circleci.com/api/v2/workflow/{workflow_id}/job",
|
| 29 |
+
headers={"Circle-Token": os.environ.get("CIRCLE_TOKEN", "")},
|
| 30 |
+
)
|
| 31 |
+
jobs = r.json()["items"]
|
| 32 |
+
|
| 33 |
+
os.makedirs("outputs", exist_ok=True)
|
| 34 |
+
|
| 35 |
+
workflow_summary = {}
|
| 36 |
+
# for each job, download artifacts
|
| 37 |
+
for job in jobs:
|
| 38 |
+
project_slug = job["project_slug"]
|
| 39 |
+
if job["name"].startswith(("tests_", "examples_", "pipelines_")):
|
| 40 |
+
url = f'https://circleci.com/api/v2/project/{project_slug}/{job["job_number"]}/artifacts'
|
| 41 |
+
r = requests.get(url, headers={"Circle-Token": os.environ.get("CIRCLE_TOKEN", "")})
|
| 42 |
+
job_artifacts = r.json()["items"]
|
| 43 |
+
|
| 44 |
+
os.makedirs(job["name"], exist_ok=True)
|
| 45 |
+
os.makedirs(f'outputs/{job["name"]}', exist_ok=True)
|
| 46 |
+
|
| 47 |
+
job_test_summaries = {}
|
| 48 |
+
for artifact in job_artifacts:
|
| 49 |
+
if artifact["path"].startswith("reports/") and artifact["path"].endswith("/summary_short.txt"):
|
| 50 |
+
node_index = artifact["node_index"]
|
| 51 |
+
url = artifact["url"]
|
| 52 |
+
r = requests.get(url, headers={"Circle-Token": os.environ.get("CIRCLE_TOKEN", "")})
|
| 53 |
+
test_summary = r.text
|
| 54 |
+
job_test_summaries[node_index] = test_summary
|
| 55 |
+
|
| 56 |
+
summary = {}
|
| 57 |
+
for node_index, node_test_summary in job_test_summaries.items():
|
| 58 |
+
for line in node_test_summary.splitlines():
|
| 59 |
+
if line.startswith("PASSED "):
|
| 60 |
+
test = line[len("PASSED ") :]
|
| 61 |
+
summary[test] = "passed"
|
| 62 |
+
elif line.startswith("FAILED "):
|
| 63 |
+
test = line[len("FAILED ") :].split()[0]
|
| 64 |
+
summary[test] = "failed"
|
| 65 |
+
# failed before passed
|
| 66 |
+
summary = dict(sorted(summary.items(), key=lambda x: (x[1], x[0])))
|
| 67 |
+
workflow_summary[job["name"]] = summary
|
| 68 |
+
|
| 69 |
+
# collected version
|
| 70 |
+
with open(f'outputs/{job["name"]}/test_summary.json', "w") as fp:
|
| 71 |
+
json.dump(summary, fp, indent=4)
|
| 72 |
+
|
| 73 |
+
new_workflow_summary = {}
|
| 74 |
+
for job_name, job_summary in workflow_summary.items():
|
| 75 |
+
for test, status in job_summary.items():
|
| 76 |
+
if test not in new_workflow_summary:
|
| 77 |
+
new_workflow_summary[test] = {}
|
| 78 |
+
new_workflow_summary[test][job_name] = status
|
| 79 |
+
|
| 80 |
+
for test, result in new_workflow_summary.items():
|
| 81 |
+
new_workflow_summary[test] = dict(sorted(result.items()))
|
| 82 |
+
new_workflow_summary = dict(sorted(new_workflow_summary.items()))
|
| 83 |
+
|
| 84 |
+
with open("outputs/test_summary.json", "w") as fp:
|
| 85 |
+
json.dump(new_workflow_summary, fp, indent=4)
|
tasks/tasksmith-441eeab80047/environment/source/utils/process_test_artifacts.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 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 |
+
This helper computes the "ideal" number of nodes to use in circle CI.
|
| 18 |
+
For each job, we compute this parameter and pass it to the `generated_config.yaml`.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
import json
|
| 22 |
+
import math
|
| 23 |
+
import os
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
MAX_PARALLEL_NODES = 8 # TODO create a mapping!
|
| 27 |
+
AVERAGE_TESTS_PER_NODES = 5
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def count_lines(filepath):
|
| 31 |
+
"""Count the number of lines in a file."""
|
| 32 |
+
try:
|
| 33 |
+
with open(filepath, "r") as f:
|
| 34 |
+
return len(f.read().split("\n"))
|
| 35 |
+
except FileNotFoundError:
|
| 36 |
+
return 0
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def compute_parallel_nodes(line_count, max_tests_per_node=10):
|
| 40 |
+
"""Compute the number of parallel nodes required."""
|
| 41 |
+
num_nodes = math.ceil(line_count / AVERAGE_TESTS_PER_NODES)
|
| 42 |
+
if line_count < 4:
|
| 43 |
+
return 1
|
| 44 |
+
return min(MAX_PARALLEL_NODES, num_nodes)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def process_artifacts(input_file, output_file):
|
| 48 |
+
# Read the JSON data from the input file
|
| 49 |
+
with open(input_file, "r") as f:
|
| 50 |
+
data = json.load(f)
|
| 51 |
+
|
| 52 |
+
# Process items and build the new JSON structure
|
| 53 |
+
transformed_data = {}
|
| 54 |
+
for item in data.get("items", []):
|
| 55 |
+
if "test_list" in item["path"]:
|
| 56 |
+
key = os.path.splitext(os.path.basename(item["path"]))[0]
|
| 57 |
+
transformed_data[key] = item["url"]
|
| 58 |
+
parallel_key = key.split("_test")[0] + "_parallelism"
|
| 59 |
+
file_path = os.path.join("test_preparation", f"{key}.txt")
|
| 60 |
+
line_count = count_lines(file_path)
|
| 61 |
+
transformed_data[parallel_key] = compute_parallel_nodes(line_count)
|
| 62 |
+
|
| 63 |
+
# Remove the "generated_config" key if it exists
|
| 64 |
+
if "generated_config" in transformed_data:
|
| 65 |
+
del transformed_data["generated_config"]
|
| 66 |
+
|
| 67 |
+
# Write the transformed data to the output file
|
| 68 |
+
with open(output_file, "w") as f:
|
| 69 |
+
json.dump(transformed_data, f, indent=2)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
if __name__ == "__main__":
|
| 73 |
+
input_file = "test_preparation/artifacts.json"
|
| 74 |
+
output_file = "test_preparation/transformed_artifacts.json"
|
| 75 |
+
process_artifacts(input_file, output_file)
|
tasks/tasksmith-441eeab80047/environment/source/utils/release.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 "legacy" in directories:
|
| 99 |
+
directories.remove("legacy")
|
| 100 |
+
for fname in fnames:
|
| 101 |
+
if fname.endswith(".py"):
|
| 102 |
+
update_version_in_file(os.path.join(folder, fname), version, file_type="examples")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def global_version_update(version: str, patch: bool = False):
|
| 106 |
+
"""
|
| 107 |
+
Update the version in all needed files.
|
| 108 |
+
|
| 109 |
+
Args:
|
| 110 |
+
version (`str`): The new version to set everywhere.
|
| 111 |
+
patch (`bool`, *optional*, defaults to `False`): Whether or not this is a patch release.
|
| 112 |
+
"""
|
| 113 |
+
for pattern, fname in REPLACE_FILES.items():
|
| 114 |
+
update_version_in_file(fname, version, pattern)
|
| 115 |
+
if not patch:
|
| 116 |
+
# We don't update the version in the examples for patch releases.
|
| 117 |
+
update_version_in_examples(version)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def remove_conversion_scripts():
|
| 121 |
+
"""
|
| 122 |
+
Delete the scripts that convert models from older, unsupported formats. We don't want to include these
|
| 123 |
+
in release wheels because they often have to open insecure file types (pickle, Torch .bin models). This results in
|
| 124 |
+
vulnerability scanners flagging us and can cause compliance issues for users with strict security policies.
|
| 125 |
+
"""
|
| 126 |
+
model_dir = Path(PATH_TO_MODELS)
|
| 127 |
+
for conversion_script in list(model_dir.glob("**/convert*.py")):
|
| 128 |
+
conversion_script.unlink()
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def get_version() -> packaging.version.Version:
|
| 132 |
+
"""
|
| 133 |
+
Reads the current version in the main __init__.
|
| 134 |
+
"""
|
| 135 |
+
with open(REPLACE_FILES["init"], "r") as f:
|
| 136 |
+
code = f.read()
|
| 137 |
+
default_version = REPLACE_PATTERNS["init"][0].search(code).groups()[0]
|
| 138 |
+
return packaging.version.parse(default_version)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def pre_release_work(patch: bool = False):
|
| 142 |
+
"""
|
| 143 |
+
Do all the necessary pre-release steps:
|
| 144 |
+
- figure out the next minor release version and ask confirmation
|
| 145 |
+
- update the version everywhere
|
| 146 |
+
- clean-up the model list in the main README
|
| 147 |
+
|
| 148 |
+
Args:
|
| 149 |
+
patch (`bool`, *optional*, defaults to `False`): Whether or not this is a patch release.
|
| 150 |
+
"""
|
| 151 |
+
# First let's get the default version: base version if we are in dev, bump minor otherwise.
|
| 152 |
+
default_version = get_version()
|
| 153 |
+
if patch and default_version.is_devrelease:
|
| 154 |
+
raise ValueError("Can't create a patch version from the dev branch, checkout a released version!")
|
| 155 |
+
if default_version.is_devrelease:
|
| 156 |
+
default_version = default_version.base_version
|
| 157 |
+
elif patch:
|
| 158 |
+
default_version = f"{default_version.major}.{default_version.minor}.{default_version.micro + 1}"
|
| 159 |
+
else:
|
| 160 |
+
default_version = f"{default_version.major}.{default_version.minor + 1}.0"
|
| 161 |
+
|
| 162 |
+
# Now let's ask nicely if we have found the right version.
|
| 163 |
+
version = input(f"Which version are you releasing? [{default_version}]")
|
| 164 |
+
if len(version) == 0:
|
| 165 |
+
version = default_version
|
| 166 |
+
|
| 167 |
+
print(f"Updating version to {version}.")
|
| 168 |
+
global_version_update(version, patch=patch)
|
| 169 |
+
print("Deleting conversion scripts.")
|
| 170 |
+
remove_conversion_scripts()
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def post_release_work():
|
| 174 |
+
"""
|
| 175 |
+
Do all the necessary post-release steps:
|
| 176 |
+
- figure out the next dev version and ask confirmation
|
| 177 |
+
- update the version everywhere
|
| 178 |
+
- clean-up the model list in the main README
|
| 179 |
+
"""
|
| 180 |
+
# First let's get the current version
|
| 181 |
+
current_version = get_version()
|
| 182 |
+
dev_version = f"{current_version.major}.{current_version.minor + 1}.0.dev0"
|
| 183 |
+
current_version = current_version.base_version
|
| 184 |
+
|
| 185 |
+
# Check with the user we got that right.
|
| 186 |
+
version = input(f"Which version are we developing now? [{dev_version}]")
|
| 187 |
+
if len(version) == 0:
|
| 188 |
+
version = dev_version
|
| 189 |
+
|
| 190 |
+
print(f"Updating version to {version}.")
|
| 191 |
+
global_version_update(version)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
if __name__ == "__main__":
|
| 195 |
+
parser = argparse.ArgumentParser()
|
| 196 |
+
parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.")
|
| 197 |
+
parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.")
|
| 198 |
+
args = parser.parse_args()
|
| 199 |
+
if not args.post_release:
|
| 200 |
+
pre_release_work(patch=args.patch)
|
| 201 |
+
elif args.patch:
|
| 202 |
+
print("Nothing to do after a patch :-)")
|
| 203 |
+
else:
|
| 204 |
+
post_release_work()
|
tasks/tasksmith-441eeab80047/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-441eeab80047/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-441eeab80047/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-441eeab80047/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-441eeab80047/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-441eeab80047/environment/source/utils/test_module/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-441eeab80047/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-441eeab80047/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-441eeab80047/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-441eeab80047/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-441eeab80047/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-441eeab80047/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-441eeab80047/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-441eeab80047/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-441eeab80047/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-441eeab80047/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-441eeab80047/environment/source/utils/update_metadata.py
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
# 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 |
+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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""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 |
+
)
|